Skip to content

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

Followup fixes to Text Editor accessibility tagging of text elements (#8783)

James Bruntonb7305f51f184
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/innerTags.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/innerTags.test.ts
index 13641a8c0b..6b75365837 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/innerTags.test.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/innerTags.test.ts
@@ -11,8 +11,10 @@ import {
test,
vi,
} from "vitest";
+import { EditTextCommand } from "@editor/tools/pdfTextEditor/commands/EditTextCommand";
import { MergeRunsCommand } from "@editor/tools/pdfTextEditor/commands/MergeRunsCommand";
import { RetagInnerCommand } from "@editor/tools/pdfTextEditor/commands/RetagInnerCommand";
+import { SetFontFamilyCommand } from "@editor/tools/pdfTextEditor/commands/SetFontFamilyCommand";
import { TagTextCommand } from "@editor/tools/pdfTextEditor/commands/TagTextCommand";
import { TagTextRangeCommand } from "@editor/tools/pdfTextEditor/commands/TagTextRangeCommand";
import { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
@@ -66,6 +68,59 @@ function retag(
history.execute(new RetagInnerCommand({ pageIndex: PAGE, key, type }), doc);
}
+/** Replace `from` with `to` in the run holding `within`, as typing would. */
+function edit(
+ doc: EditorDocument,
+ history: HistoryStack,
+ within: string,
+ from: string,
+ to: string,
+) {
+ const run = runWith(doc, within);
+ history.execute(
+ new EditTextCommand({
+ pageIndex: PAGE,
+ runId: run.id,
+ nextText: run.text.replace(from, to),
+ }),
+ doc,
+ );
+}
+
+function tagRange(
+ doc: EditorDocument,
+ history: HistoryStack,
+ within: string,
+ fragment: string,
+ as: StructureType,
+) {
+ const run = runWith(doc, within);
+ const start = run.text.indexOf(fragment);
+ history.execute(
+ new TagTextRangeCommand({
+ pageIndex: PAGE,
+ runId: run.id,
+ start,
+ end: start + fragment.length,
+ as,
+ }),
+ doc,
+ );
+}
+
+/** How many elements of `type` the saved file has in the block holding `within`'s text. */
+async function savedIn(
+ doc: EditorDocument,
+ within: string,
+ type: StructureType,
+): Promise<number> {
+ const block = doc
+ .structure(PAGE)
+ .block(runWith(doc, within).snapshot().mcid!)!.key;
+ const { structure } = await saved(doc);
+ return elementsIn(structure.pages.get(PAGE)!.elements, block, type).length;
+}
+
async function saved(doc: EditorDocument) {
const { blob } = await exportToBlob(doc, "tags.pdf");
const bytes = new Uint8Array(await blob.arrayBuffer());
@@ -271,3 +326,97 @@ describe("tags inside a run grouped from several paragraphs", () => {
expect(groupAndListTags(doc, new HistoryStack())).toEqual([]);
});
});
+
+describe("tags inside a run's text through edits to it", () => {
+ test.each([
+ ["a line redrawn whole", "German subsidiaries", "German", "Austrian"],
+ ["a line of a paragraph", "All three regions", "end of", "close of"],
+ ])("keeps a file's inline element in %s", async (_case, within, from, to) => {
+ const doc = await open();
+ const [before] = tagsIn(doc, within);
+ edit(doc, new HistoryStack(), within, from, to);
+
+ const [after] = tagsIn(doc, to);
+ expect(after.text.trim()).toBe(before.text.trim());
+ expect(after.role).toEqual(before.role);
+ expect(await savedIn(doc, to, before.role.type!)).toBe(1);
+ });
+
+ test("keeps an element the session tagged", async () => {
+ const doc = await open();
+ const history = new HistoryStack();
+ tagRange(doc, history, "Growth slowed", "two large contracts", "Span");
+ edit(doc, history, "Growth slowed", "Growth", "Sales");
+
+ expect(tagsIn(doc, "Sales slowed")).toMatchObject([
+ { text: "two large contracts", role: { type: "Span" } },
+ { role: { type: "Quote" } },
+ ]);
+ expect(await savedIn(doc, "Sales slowed", "Span")).toBe(1);
+ });
+
+ test("keeps the element through one edit after another", async () => {
+ const doc = await open();
+ const history = new HistoryStack();
+ edit(doc, history, "German subsidiaries", "German", "Austrian");
+ edit(doc, history, "Austrian subsidiaries", "this line", "this row");
+
+ expect(tagsIn(doc, "this row")).toMatchObject([
+ { text: "Umsatzerlöse", role: { type: "Span" } },
+ ]);
+ expect(await savedIn(doc, "this row", "Span")).toBe(1);
+ });
+
+ test("gives text typed inside an element to it, and text typed after it to its block", async () => {
+ const doc = await open();
+ const history = new HistoryStack();
+ tagRange(doc, history, "Growth slowed", "two large contracts", "Span");
+ edit(doc, history, "Growth slowed", "large", "big");
+ edit(doc, history, "Growth slowed", "contracts moved", "contracts, moved");
+
+ expect(tagsIn(doc, "Growth slowed")[0]).toMatchObject({
+ text: "two big contracts",
+ role: { type: "Span" },
+ });
+ });
+
+ test("puts the element back on undo", async () => {
+ const doc = await open();
+ const history = new HistoryStack();
+ edit(doc, history, "German subsidiaries", "German", "Austrian");
+ history.undo(doc);
+
+ expect(tagsIn(doc, "German subsidiaries")).toMatchObject([
+ { text: "Umsatzerlöse", role: { type: "Span" } },
+ ]);
+ expect(await savedIn(doc, "German subsidiaries", "Span")).toBe(1);
+ });
+
+ test("keeps a list item's label and body apart", async () => {
+ const doc = await open();
+ edit(doc, new HistoryStack(), "Close the two delayed", "Close", "Sign");
+
+ expect(tagsIn(doc, "Sign the two delayed")).toMatchObject([
+ { text: "1. ", role: { type: "Lbl" } },
+ { role: { type: "LBody" } },
+ ]);
+ });
+
+ test("keeps the element when the text changes font", async () => {
+ const doc = await open();
+ const run = runWith(doc, "German subsidiaries");
+ new HistoryStack().execute(
+ new SetFontFamilyCommand({
+ pageIndex: PAGE,
+ runId: run.id,
+ nextFamily: "Times-Roman",
+ }),
+ doc,
+ );
+
+ expect(tagsIn(doc, "German subsidiaries")).toMatchObject([
+ { text: "Umsatzerlöse", role: { type: "Span" } },
+ ]);
+ expect(await savedIn(doc, "German subsidiaries", "Span")).toBe(1);
+ });
+});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/tagMarks.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/tagMarks.test.ts
index 4586274712..06ad540648 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/tagMarks.test.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/tagMarks.test.ts
@@ -17,7 +17,15 @@ import {
copyTagMarks,
readTagMarks,
} from "@editor/tools/pdfTextEditor/pdfium/PdfiumTagMarks";
-import { emitTextLine } from "@editor/tools/pdfTextEditor/commands/editTextHelpers";
+import {
+ emitTextLine,
+ measureObjBoxPt,
+ readObjTexts,
+} from "@editor/tools/pdfTextEditor/commands/editTextHelpers";
+import {
+ uniformTags,
+ type TextTags,
+} from "@editor/tools/pdfTextEditor/model/TextTags";
import { allowConsole } from "@editor/tests/failOnConsole";
import {
buildClassicPdf,
@@ -248,7 +256,7 @@ describe("PdfiumTagMarks", () => {
fill: { r: 0, g: 0, b: 0, a: 255 },
originalFontPtr: 0,
fallbackFamily: "Helvetica",
- tagMarks: [{ name: "P", mcid: 0 }],
+ tags: uniformTags([{ name: "P", mcid: 0 }]),
});
expect(ptrs.length).toBeGreaterThan(1);
@@ -274,9 +282,55 @@ describe("PdfiumTagMarks", () => {
fill: { r: 0, g: 0, b: 0, a: 255 },
originalFontPtr: 0,
fallbackFamily: "Helvetica",
- tagMarks: [],
+ tags: uniformTags([]),
});
for (const ptr of ptrs) expect(m.FPDFPageObj_CountMarks(ptr)).toBe(0);
});
+
+ test("emitTextLine draws each stretch of text with its own tags, in order", async () => {
+ allowConsole.error(NO_CANVAS);
+ const doc = await open(taggedPdf());
+ const m = doc.module;
+ const page = doc.page(0);
+ const paragraph = { name: "P", mcid: 0 };
+ const span = { name: "Span", mcid: 2 };
+ const emit = (tags: TextTags, y: number) =>
+ emitTextLine({
+ doc,
+ page,
+ text: "reported as Umsatz.",
+ x: 72,
+ y,
+ fontSize: 12,
+ fill: { r: 0, g: 0, b: 0, a: 255 },
+ originalFontPtr: 0,
+ fallbackFamily: "Helvetica",
+ tags,
+ });
+
+ const ptrs = emit(
+ [
+ { end: 12, tags: [paragraph] },
+ { end: 18, tags: [span] },
+ { end: Infinity, tags: [paragraph] },
+ ],
+ 400,
+ );
+
+ const texts = readObjTexts(m, page.pagePtr, ptrs).map((t) => t?.trim());
+ expect(texts).toEqual(["reported", "as", "Umsatz", "."]);
+ expect(ptrs.map((ptr) => readTagMarks(m, ptr))).toEqual([
+ [paragraph],
+ [paragraph],
+ [span],
+ [paragraph],
+ ]);
+ // Split by its tags, the line's words sit where they sit drawn whole.
+ const lefts = (of: number[]) => of.map((ptr) => measureObjBoxPt(m, ptr)!.x);
+ const whole = lefts(emit(uniformTags([paragraph]), 300));
+ lefts(ptrs)
+ .slice(0, 3)
+ .forEach((x, i) => expect(x).toBeCloseTo(whole[i], 1));
+ });
});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/textRangeTagging.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/textRangeTagging.test.ts
index 9b9c16b108..6f271f43b0 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/textRangeTagging.test.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/textRangeTagging.test.ts
@@ -15,6 +15,8 @@ import {
rangeTagTypes,
TagTextRangeCommand,
} from "@editor/tools/pdfTextEditor/commands/TagTextRangeCommand";
+import { EditTextCommand } from "@editor/tools/pdfTextEditor/commands/EditTextCommand";
+import { RetagInnerCommand } from "@editor/tools/pdfTextEditor/commands/RetagInnerCommand";
import { readObjTexts } from "@editor/tools/pdfTextEditor/commands/editTextHelpers";
import {
charOrigins,
@@ -45,7 +47,10 @@ import { HistoryStack } from "@editor/tools/pdfTextEditor/store/HistoryStack";
import type { PageSnapshot } from "@editor/tools/pdfTextEditor/types";
import { exportToBlob } from "@editor/tools/pdfTextEditor/util/exportPdf";
import { headingOutline } from "@editor/tools/pdfTextEditor/util/headingOutline";
-import { locateHeading } from "@editor/tools/pdfTextEditor/util/textAccessibility";
+import {
+ innerTags,
+ locateHeading,
+} from "@editor/tools/pdfTextEditor/util/textAccessibility";
import {
buildClassicPdf,
streamBody,
@@ -111,6 +116,49 @@ function cutPdf(): Uint8Array {
);
}
+/** A page whose one paragraph (MCID 0) draws `line`, a text-showing operation with its spacing set before it. */
+function linePdf(line: string): Uint8Array {
+ return paragraphPdf(`BT /F1 12 Tf 72 700 Td ${line} ET`);
+}
+
+/** A page whose one paragraph (MCID 0) is drawn by `content`, with font F1 Helvetica. */
+function paragraphPdf(content: string): Uint8Array {
+ return buildClassicPdf(
+ [
+ {
+ num: 1,
+ body: "<< /Type /Catalog /Pages 2 0 R /StructTreeRoot 6 0 R /MarkInfo << /Marked true >> >>",
+ },
+ { num: 2, body: "<< /Type /Pages /Kids [3 0 R] /Count 1 >>" },
+ {
+ num: 3,
+ body:
+ "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents 4 0 R /StructParents 0 " +
+ "/Resources << /Font << /F1 5 0 R >> >> >>",
+ },
+ {
+ num: 4,
+ body: streamBody("", `/P <</MCID 0>> BDC ${content} EMC\n`),
+ },
+ {
+ num: 5,
+ body: "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>",
+ },
+ {
+ num: 6,
+ body: "<< /Type /StructTreeRoot /K 7 0 R /ParentTree 9 0 R /ParentTreeNextKey 1 >>",
+ },
+ {
+ num: 7,
+ body: "<< /Type /StructElem /S /Document /P 6 0 R /K [8 0 R] >>",
+ },
+ { num: 8, body: "<< /Type /StructElem /S /P /P 7 0 R /Pg 3 0 R /K 0 >>" },
+ { num: 9, body: "<< /Nums [0 [8 0 R]] >>" },
+ ],
+ 1,
+ );
+}
+
const opened: EditorDocument[] = [];
async function open(bytes: Uint8Array): Promise<EditorDocument> {
@@ -120,8 +168,32 @@ async function open(bytes: Uint8Array): Promise<EditorDocument> {
return doc;
}
-function runWith(doc: EditorDocument, fragment: string) {
- const run = doc.page(0).runs.find((r) => r.text.includes(fragment));
+async function openSample(): Promise<EditorDocument> {
+ const sample = path.join(
+ import.meta.dirname,
+ "../../../tests/test-fixtures/tagged-sample.pdf",
+ );
+ const doc = await EditorDocument.open(new Uint8Array(await readFile(sample)));
+ opened.push(doc);
+ PdfiumTextReader.populate(doc, doc.page(1));
+ return doc;
+}
+
+/**
+ * Chrome's "Save as PDF" output: each glyph an object of its own and each
+ * word space another, in fonts subset to the glyphs each draws, with some
+ * text inside a form XObject.
+ */
+async function openChromePdf(): Promise<EditorDocument> {
+ const file = path.join(
+ import.meta.dirname,
+ "../../../tests/test-fixtures/stirling-marketing.pdf",
+ );
+ return open(new Uint8Array(await readFile(file)));
+}
+
+function runWith(doc: EditorDocument, fragment: string, pageIndex = 0) {
+ const run = doc.page(pageIndex).runs.find((r) => r.text.includes(fragment));
if (!run) throw new Error(`no run contains "${fragment}"`);
return run;
}
@@ -131,21 +203,44 @@ function tagRange(
history: HistoryStack,
fragment: string,
as: StructureType,
-) {
- const run = runWith(doc, fragment);
+ pageIndex = 0,
+): TagTextRangeCommand {
+ const run = runWith(doc, fragment, pageIndex);
const start = run.text.indexOf(fragment);
+ const command = new TagTextRangeCommand({
+ pageIndex,
+ runId: run.id,
+ start,
+ end: start + fragment.length,
+ as,
+ });
+ history.execute(command, doc);
+ return command;
+}
+
+/** Replace `from` with `to` in the run holding `from`, as typing would. */
+function editText(
+ doc: EditorDocument,
+ history: HistoryStack,
+ from: string,
+ to: string,
+ pageIndex = 0,
+) {
+ const run = runWith(doc, from, pageIndex);
history.execute(
- new TagTextRangeCommand({
- pageIndex: 0,
+ new EditTextCommand({
+ pageIndex,
runId: run.id,
- start,
- end: start + fragment.length,
- as,
+ nextText: run.text.replace(from, to),
}),
doc,
);
}
+function runTexts(doc: EditorDocument, pageIndex = 0): string[] {
+ return doc.page(pageIndex).runs.map((run) => run.text.trim());
+}
+
async function savedBytes(doc: EditorDocument): Promise<Uint8Array> {
const { blob } = await exportToBlob(doc, "cut.pdf");
return new Uint8Array(await blob.arrayBuffer());
@@ -175,6 +270,54 @@ function textByMcid(doc: EditorDocument): Map<number, string> {
return out;
}
+interface Glyph {
+ char: string;
+ x: number;
+ y: number;
+}
+
+/** Every glyph page 0 draws with ink, line by line from the top, left to right. */
+function inkGlyphs(doc: EditorDocument): Glyph[] {
+ const m = doc.module;
+ const textPage = m.FPDFText_LoadPage(doc.page(0).pagePtr);
+ const x = m.pdfium.wasmExports.malloc(8);
+ const y = m.pdfium.wasmExports.malloc(8);
+ const glyphs: Glyph[] = [];
+ try {
+ for (let i = 0; i < m.FPDFText_CountChars(textPage); i++) {
+ const char = String.fromCodePoint(m.FPDFText_GetUnicode(textPage, i));
+ if (m.FPDFText_IsGenerated(textPage, i) === 1 || !/\S/.test(char)) {
+ continue;
+ }
+ m.FPDFText_GetCharOrigin(textPage, i, x, y);
+ glyphs.push({
+ char,
+ x: m.pdfium.getValue(x, "double"),
+ y: m.pdfium.getValue(y, "double"),
+ });
+ }
+ } finally {
+ m.pdfium.wasmExports.free(x);
+ m.pdfium.wasmExports.free(y);
+ m.FPDFText_ClosePage(textPage);
+ }
+ const line = (glyph: Glyph) => Math.round(glyph.y * 10);
+ return glyphs.sort((a, b) => line(b) - line(a) || a.x - b.x);
+}
+
+function words(text: string): string[] {
+ return text.split(/\s+/).filter(Boolean);
+}
+
+/** Every glyph of `glyphs` within 0.01 pt of where `at` draws it. */
+function expectDrawnAt(glyphs: Glyph[], at: Glyph[]): void {
+ expect(glyphs.map((g) => g.char).join("")).toBe(
+ at.map((g) => g.char).join(""),
+ );
+ const moved = glyphs.map((g, i) => Math.hypot(g.x - at[i].x, g.y - at[i].y));
+ expect(Math.max(...moved)).toBeLessThanOrEqual(0.01);
+}
+
/** An element's kids: an MCID as its number, a child element as its /S. */
function kidsOf(pdf: RawPdf, num: number): string[] {
return elementKids(pdf, pdf.objectBody(num)!)!.map((kid) => {
@@ -244,8 +387,7 @@ describe("tagging part of an element's text", () => {
const origin = charOrigins(
m,
pagePtr,
- new Map([[line, new Set([14])]]),
- new Map([[line, 27]]),
+ new Map([[line, "Sales rose in every region."]]),
)
.get(line)!
.get(14)!;
@@ -340,15 +482,7 @@ describe("tagging part of an element's text", () => {
});
test("tags a word of a real file's paragraph as a Span inside it", async () => {
- const sample = path.join(
- import.meta.dirname,
- "../../../tests/test-fixtures/tagged-sample.pdf",
- );
- const doc = await EditorDocument.open(
- new Uint8Array(await readFile(sample)),
- );
- opened.push(doc);
- PdfiumTextReader.populate(doc, doc.page(1));
+ const doc = await openSample();
const run = doc.page(1).runs.find((r) => r.text.includes("All amounts"))!;
const paragraph = doc.structure(1).block(run.snapshot().mcid!)!.key;
const spansIn = (elements: readonly StructureElement[]) =>
@@ -382,6 +516,202 @@ describe("tagging part of an element's text", () => {
});
});
+describe("tagging part of a spaced or kerned line", () => {
+ test.each([
+ [
+ "character and word spacing",
+ "0.4 Tc 3 Tw (Costs fell in most markets last year.) Tj",
+ ],
+ [
+ "kerning",
+ "[(Co) -40 (sts) 60 ( fe) 25 (ll) -120 ( in) 80 ( most) -50 ( mar) 15 (kets) 30 ( last year.)] TJ",
+ ],
+ [
+ "word spaces drawn as gaps",
+ "[(Costs) -333 (fell) -333 (in) -333 (most) -333 (markets) -333 (last) -333 (year.)] TJ",
+ ],
+ ])(
+ "draws every glyph of a line with %s where it was drawn, and saves it there",
+ async (_, line) => {
+ const doc = await open(linePdf(line));
+ const text = runWith(doc, "Costs").text;
+ const before = inkGlyphs(doc);
+ tagRange(doc, new HistoryStack(), "fell in most", "Span");
+ expectDrawnAt(inkGlyphs(doc), before);
+
+ const saved = await open(await savedBytes(doc));
+ expectDrawnAt(inkGlyphs(saved), before);
+ const run = runWith(saved, "Costs");
+ expect(words(run.text)).toEqual(words(text));
+ expect(
+ innerTags(saved, run.snapshot()).map(({ text, role }) => [
+ text.trim(),
+ role.type,
+ ]),
+ ).toEqual([["fell in most", "Span"]]);
+ },
+ );
+
+ test("refuses a cut that would read spaces into widely letter-spaced words, and changes nothing", async () => {
+ const doc = await open(
+ linePdf("1.5 Tc 4 Tw (Costs fell in most markets last year.) Tj"),
+ );
+ const before = inkGlyphs(doc);
+ const objects = doc.module.FPDFPage_CountObjects(doc.page(0).pagePtr);
+ expect(() =>
+ tagRange(doc, new HistoryStack(), "fell in most", "Span"),
+ ).toThrow();
+ expectDrawnAt(inkGlyphs(doc), before);
+ expect(doc.module.FPDFPage_CountObjects(doc.page(0).pagePtr)).toBe(objects);
+ expect(doc.structureEdits()).toEqual([]);
+ });
+});
+
+describe("tagging part of a line of a Chrome-produced file", () => {
+ test("draws every glyph where it was, and saves the text it tagged", async () => {
+ const doc = await openChromePdf();
+ const text = runWith(doc, "Free Adobe").text;
+ const before = inkGlyphs(doc);
+ tagRange(doc, new HistoryStack(), "Free Adobe", "Span");
+ expectDrawnAt(inkGlyphs(doc), before);
+
+ const saved = await open(await savedBytes(doc));
+ expectDrawnAt(inkGlyphs(saved), before);
+ const run = runWith(saved, "Free Adobe");
+ expect(words(run.text)).toEqual(words(text));
+ // Chrome wraps the heading's text in a NonStruct, which keeps the text
+ // either side.
+ expect(
+ innerTags(saved, run.snapshot()).map(({ text, role }) => [
+ text.trim(),
+ role.type,
+ ]),
+ ).toEqual([
+ ["The", "NonStruct"],
+ ["Free Adobe", "Span"],
+ ["Acrobat Alternative", "NonStruct"],
+ ]);
+ });
+
+ test("offers no tag for part of text inside a form XObject, which apply refuses", async () => {
+ const doc = await openChromePdf();
+ const run = runWith(doc, "Open Source");
+ const start = run.text.indexOf("Source");
+ const end = start + "Source".length;
+ expect(rangeTagTypes(doc, 0, run.id, start, end)).toEqual([]);
+ const cut = new TagTextRangeCommand({
+ pageIndex: 0,
+ runId: run.id,
+ start,
+ end,
+ as: "Span",
+ });
+ expect(() => new HistoryStack().execute(cut, doc)).toThrow();
+ });
+});
+
+describe("a block cut from part of a run", () => {
+ test("gets a run of its own, as a read of the page groups it", async () => {
+ const doc = await open(cutPdf());
+ const run = runWith(doc, "We sampled");
+ const cut = tagRange(doc, new HistoryStack(), "sampled", "H3");
+
+ expect(doc.page(0).findRun(run.id)).toBeUndefined();
+ expect(doc.page(0).findRun(cut.movedToRunId!)!.text.trim()).toBe("sampled");
+ expect(runTexts(doc).slice(5, 9)).toEqual([
+ "Methods",
+ "We",
+ "sampled",
+ "every store.",
+ ]);
+ });
+
+ test("leaves a run cut whole as it was", async () => {
+ const doc = await open(cutPdf());
+ const run = runWith(doc, "Outlook");
+ const cut = tagRange(doc, new HistoryStack(), "Outlook", "H2");
+ expect(cut.movedToRunId).toBeNull();
+ expect(doc.page(0).findRun(run.id)!.snapshot().mcid).toBe(4);
+ });
+
+ test.each([
+ ["the text before it", "We", "They"],
+ ["the text after it", "store", "shop"],
+ ])("survives an edit of %s", async (_part, from, to) => {
+ const doc = await open(cutPdf());
+ const history = new HistoryStack();
+ tagRange(doc, history, "sampled", "H3");
+ editText(doc, history, from, to);
+
+ expect(doc.headings()!.map((h) => h.type)).toEqual(["H1", "H3"]);
+ const bytes = await savedBytes(doc);
+ expect(await savedHeadings(doc)).toEqual(["H1", "H3"]);
+ expect(
+ textByMcid(await open(bytes))
+ .get(4)
+ ?.trim(),
+ ).toBe("sampled");
+ });
+
+ test("survives an edit of the paragraph it was cut from", async () => {
+ const doc = await openSample();
+ const history = new HistoryStack();
+ const headings = () =>
+ doc.headings()!.filter((h) => h.type === "H4").length;
+ tagRange(doc, history, "Atlas product line", "H4", 1);
+ expect(headings()).toBe(1);
+ expect(runWith(doc, "Revenue rose", 1).text).toContain(
+ "and the launch of the",
+ );
+
+ editText(doc, history, "Canada", "Mexico", 1);
+ expect(headings()).toBe(1);
+ const saved = await savedHeadings(doc);
+ expect(saved.filter((type) => type === "H4")).toHaveLength(1);
+ });
+
+ test("puts the run back on undo, and splits it the same way on redo", async () => {
+ const doc = await open(cutPdf());
+ const history = new HistoryStack();
+ const before = doc.page(0).runs.map((r) => [r.id, r.text]);
+ tagRange(doc, history, "sampled", "H3");
+ const split = doc.page(0).runs.map((r) => r.id);
+ editText(doc, history, "store", "shop");
+
+ history.undo(doc);
+ history.undo(doc);
+ expect(doc.page(0).runs.map((r) => [r.id, r.text])).toEqual(before);
+
+ history.redo(doc);
+ history.redo(doc);
+ expect(doc.page(0).runs.map((r) => r.id)).toEqual(split);
+ expect(runWith(doc, "shop").text.trim()).toBe("every shop.");
+ });
+
+ test("is made when an inline cut is retagged as a block", async () => {
+ const doc = await open(cutPdf());
+ const history = new HistoryStack();
+ tagRange(doc, history, "every", "Span");
+ const [span] = innerTags(doc, runWith(doc, "Sales rose").snapshot());
+ const retag = new RetagInnerCommand({
+ pageIndex: 0,
+ key: span.key,
+ type: "H2",
+ });
+ history.execute(retag, doc);
+ expect(doc.page(0).findRun(retag.movedToRunId!)!.text.trim()).toBe("every");
+
+ editText(doc, history, "region", "area");
+ expect(await savedHeadings(doc)).toEqual(["H1", "H2"]);
+
+ history.undo(doc);
+ history.undo(doc);
+ expect(innerTags(doc, runWith(doc, "Sales rose").snapshot())).toMatchObject(
+ [{ text: "every", role: { type: "Span" } }],
+ );
+ });
+});
+
describe("which tags part of a run's text can take", () => {
const typesFor = (
doc: EditorDocument,
@@ -406,24 +736,29 @@ describe("which tags part of a run's text can take", () => {
});
test("offers only inline types for text in an inline element", async () => {
- const doc = await EditorDocument.open(
- new Uint8Array(
- await readFile(
- path.join(
- import.meta.dirname,
- "../../../tests/test-fixtures/tagged-sample.pdf",
- ),
- ),
- ),
- );
- opened.push(doc);
- PdfiumTextReader.populate(doc, doc.page(1));
+ const doc = await openSample();
expect(typesFor(doc, 1, "appendix")).toEqual(
TEXT_RANGE_TYPES.filter(isInlineType),
);
expect(typesFor(doc, 1, "in the appendix")).toEqual([]);
});
+ test("offers none for text its element draws out of reading order, which apply refuses", async () => {
+ const doc = await open(
+ paragraphPdf(
+ "BT /F1 12 Tf 72 700 Td (Sales ) Tj ET " +
+ "BT /F1 12 Tf 176.06 700 Td (region.) Tj ET " +
+ "BT /F1 12 Tf 105.35 700 Td (rose in every ) Tj ET",
+ ),
+ );
+ const run = runWith(doc, "Sales rose in every region.");
+ const end = "Sales rose".length;
+ expect(rangeTagTypes(doc, 0, run.id, 0, end)).toEqual([]);
+ expect(() =>
+ tagRange(doc, new HistoryStack(), "Sales rose", "Span"),
+ ).toThrow();
+ });
+
test("offers none for untagged text or only spaces", async () => {
const doc = await open(cutPdf());
expect(typesFor(doc, 0, "Printed")).toEqual([]);
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/commands/EditTextCommand.ts b/frontend/src/editor/core/tools/pdfTextEditor/commands/EditTextCommand.ts
index aae441b65d..5e1cea2f20 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/commands/EditTextCommand.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/commands/EditTextCommand.ts
@@ -51,9 +51,20 @@ import {
isScanRun,
renderScanEdit,
} from "@editor/tools/pdfTextEditor/commands/scanTextEdit";
+import {
+ editedTags,
+ readRunTags,
+} from "@editor/tools/pdfTextEditor/commands/runTags";
+import {
+ sliceTags,
+ splitLines,
+ uniformTags,
+ type TextTags,
+} from "@editor/tools/pdfTextEditor/model/TextTags";
interface RevertLine {
text: string;
+ tags: TextTags;
x: number;
y: number;
fill: { r: number; g: number; b: number; a: number };
@@ -66,7 +77,13 @@ interface RevertLine {
interface RebuildLine {
baselineY: number;
fontSize: number;
- subRuns: Array<{ ptr: number; text: string; x: number; removed: boolean }>;
+ subRuns: Array<{
+ ptr: number;
+ text: string;
+ tags: TextTags;
+ x: number;
+ removed: boolean;
+ }>;
}
/** Snapshot of a run's paragraph model for the line-edit revert. */
@@ -122,6 +139,8 @@ export class EditTextCommand implements Command {
private readonly runId: string;
private readonly nextText: string;
private prevText: string | null = null;
+ /** `prevText`'s tags, read from the run's objects on the first apply. */
+ private prevTags: TextTags | null = null;
private overlaid = false;
private prevObjPtr = 0;
@@ -163,7 +182,13 @@ export class EditTextCommand implements Command {
/** Fresh objects emitted for new/changed lines (removed on revert). */
createdPtrs: number[];
/** Deleted lines, re-emitted as fallback on revert. */
- removed: Array<{ text: string; x: number; y: number; fontSize: number }>;
+ removed: Array<{
+ text: string;
+ tags: TextTags;
+ x: number;
+ y: number;
+ fontSize: number;
+ }>;
prev: RunModelSnapshot;
} | null = null;
@@ -191,6 +216,16 @@ export class EditTextCommand implements Command {
}
}
+ this.prevTags ??= readRunTags(doc, page, run);
+ const nextTags = editedTags(
+ doc,
+ this.pageIndex,
+ this.prevTags,
+ this.prevText,
+ this.nextText,
+ run.tagMarks,
+ );
+
const alreadyBase14 = /^base14:/.test(run.fontId);
// Invisible OCR text over a scan: rewrite the whole run visibly so the
// scanned ink can be covered, never patch its hidden objects in place.
@@ -217,7 +252,13 @@ export class EditTextCommand implements Command {
this.paragraphPlan = paraPlan;
this.prevParagraphSlots = paraPlan.prevSlots;
this.editSnapshot = snapshotRunModel(run);
- const result = applyParagraphEditPlan(doc, page, run, paraPlan);
+ const result = applyParagraphEditPlan(
+ doc,
+ page,
+ run,
+ paraPlan,
+ nextTags,
+ );
this.paragraphInsertedPtrs = result.insertedPtrs;
run.paragraphLineSlots = result.newSlots;
run.bounds = {
@@ -265,7 +306,15 @@ export class EditTextCommand implements Command {
if (prevLines.length !== nextLines.length) {
if (run.paragraphLineSlots.length === prevLines.length) {
// Slots map 1:1 to lines (a grow-mode paragraph) - diff per line.
- this.applyParagraphLineEdit(doc, page, run, prevLines, nextLines);
+ this.applyParagraphLineEdit(
+ doc,
+ page,
+ run,
+ prevLines,
+ nextLines,
+ this.prevTags,
+ nextTags,
+ );
run.text = this.nextText;
run.dirty = true;
page.markDirty();
@@ -277,7 +326,7 @@ export class EditTextCommand implements Command {
/^\r?\n/.test(this.nextText.slice(this.prevText.length))
) {
// Soft-wrapped paragraph: can't diff per line.
- this.applyParagraphAppend(doc, page, run);
+ this.applyParagraphAppend(doc, page, run, nextTags);
run.text = this.nextText;
run.dirty = true;
page.markDirty();
@@ -305,7 +354,7 @@ export class EditTextCommand implements Command {
this.prevMergedFromTexts = [...run.mergedFromTexts];
this.prevMergedFromBounds = run.mergedFromBounds.map((b) => ({ ...b }));
this.editSnapshot = snapshotRunModel(run);
- const result = applyPartialEditPlan(doc, page, run, partial);
+ const result = applyPartialEditPlan(doc, page, run, partial, nextTags);
this.partialInsertedPtrs = result.insertedPtrs;
run.mergedFromPtrs = result.newMergedFromPtrs;
run.mergedFromTexts = result.newMergedFromTexts;
@@ -416,7 +465,11 @@ export class EditTextCommand implements Command {
(run.pdfiumObjPtr ? safeGetFont(m, run.pdfiumObjPtr) : 0)
: 0;
- this.revertLines = snapshotRevertLines(run, this.prevText ?? "");
+ this.revertLines = snapshotRevertLines(
+ run,
+ this.prevText ?? "",
+ this.prevTags,
+ );
this.revertRotation = rotationFromMatrix(run.matrix) ?? null;
// Detach any cover rect that a PRIOR overlay edit left on the page.
@@ -494,7 +547,7 @@ export class EditTextCommand implements Command {
doc,
page,
run,
- lines: outputLines,
+ lines: splitLines(this.nextText, nextTags),
origins: planLineOrigins(run, outputLines.length, lineHeight),
originalFontPtr,
originalFontSubset: run.fontSubset,
@@ -606,6 +659,12 @@ export class EditTextCommand implements Command {
page.markNeedsGenerate();
}
+ private prevTagsOf(run: TextRun, start: number, end: number): TextTags {
+ return this.prevTags
+ ? sliceTags(this.prevTags, start, end)
+ : uniformTags(run.tagMarks);
+ }
+
// Exactly one revert strategy member may be set per apply. Enforced only by
// guard ordering, so fail fast in dev if two paths ran or a member leaked.
private assertSingleRevertPath(): void {
@@ -664,7 +723,7 @@ export class EditTextCommand implements Command {
fontSize: rem.fontSize,
fill: run.fill,
...inkFromRun(run),
- tagMarks: run.tagMarks,
+ tags: rem.tags,
originalFontPtr: 0,
charSpacingPt: run.charSpacingPt,
fallbackFamily,
@@ -738,12 +797,18 @@ export class EditTextCommand implements Command {
lines.push({
baselineY: prevSlot.baselineY,
fontSize: prevSlot.fontSize,
- subRuns: prevSlot.mergedFromPtrs.map((ptr, i) => ({
- ptr,
- text: prevSlot.mergedFromTexts[i] ?? "",
- x: prevSlot.mergedFromBounds[i]?.x ?? prevSlot.matrixE,
- removed: removed.has(ptr),
- })),
+ subRuns: prevSlot.mergedFromPtrs.map((ptr, i) => {
+ const text = prevSlot.mergedFromTexts[i] ?? "";
+ const start =
+ prevSlot.startChar + (prevSlot.mergedFromCharStarts[i] ?? 0);
+ return {
+ ptr,
+ text,
+ tags: this.prevTagsOf(run, start, start + text.length),
+ x: prevSlot.mergedFromBounds[i]?.x ?? prevSlot.matrixE,
+ removed: removed.has(ptr),
+ };
+ }),
});
}
this.rebuildAsOverlayModel(doc, page, run, lines, revertFallback);
@@ -799,12 +864,17 @@ export class EditTextCommand implements Command {
{
baselineY: run.matrix.f,
fontSize: run.fontSize,
- subRuns: this.prevMergedFromPtrs.map((ptr, i) => ({
- ptr,
- text: this.prevMergedFromTexts[i] ?? "",
- x: this.prevMergedFromBounds[i]?.x ?? run.matrix.e,
- removed: removed.has(ptr),
- })),
+ subRuns: this.prevMergedFromPtrs.map((ptr, i) => {
+ const text = this.prevMergedFromTexts[i] ?? "";
+ const start = this.editSnapshot?.mergedFromCharStarts[i] ?? 0;
+ return {
+ ptr,
+ text,
+ tags: this.prevTagsOf(run, start, start + text.length),
+ x: this.prevMergedFromBounds[i]?.x ?? run.matrix.e,
+ removed: removed.has(ptr),
+ };
+ }),
},
],
revertFallback,
@@ -887,7 +957,7 @@ export class EditTextCommand implements Command {
// omitting this forced every restored object back to fill: undo on
// invisible OCR text stamped visible glyphs over the scan.
...inkFromRun(run),
- tagMarks: run.tagMarks,
+ tags: line.tags,
});
if (ptrs.length === 0) continue;
lineAnchorPtrs.push(ptrs[0]);
@@ -924,6 +994,8 @@ export class EditTextCommand implements Command {
run: TextRun,
prevLines: string[],
nextLines: string[],
+ prevTags: TextTags,
+ nextTags: TextTags,
): void {
const m = doc.module;
const slots = run.paragraphLineSlots;
@@ -1032,7 +1104,7 @@ export class EditTextCommand implements Command {
fontSize: run.fontSize,
fill: run.fill,
...inkFromRun(run),
- tagMarks: run.tagMarks,
+ tags: sliceTags(nextTags, cursor, cursor + text.length),
originalFontPtr: reuseFontPtr,
originalFontSubset: run.fontSubset,
charSpacingPt: run.charSpacingPt,
@@ -1069,6 +1141,7 @@ export class EditTextCommand implements Command {
if (prevLines[j]) {
this.lineEdit.removed.push({
text: prevLines[j],
+ tags: sliceTags(prevTags, src.startChar, src.endChar),
x: src.mergedFromBounds[0]?.x ?? src.matrixE,
y: src.baselineY,
fontSize: src.fontSize,
@@ -1120,6 +1193,7 @@ export class EditTextCommand implements Command {
doc: EditorDocument,
page: Page,
run: TextRun,
+ nextTags: TextTags,
): void {
const m = doc.module;
const slots = run.paragraphLineSlots;
@@ -1173,7 +1247,7 @@ export class EditTextCommand implements Command {
fontSize: run.fontSize,
fill: run.fill,
...inkFromRun(run),
- tagMarks: run.tagMarks,
+ tags: sliceTags(nextTags, cursor, cursor + text.length),
originalFontPtr: 0,
charSpacingPt: run.charSpacingPt,
fallbackFamily,
@@ -1271,7 +1345,7 @@ export class EditTextCommand implements Command {
fontSize: line.fontSize,
fill: run.fill,
...inkFromRun(run),
- tagMarks: run.tagMarks,
+ tags: sr.tags,
originalFontPtr: 0,
charSpacingPt: run.charSpacingPt,
fallbackFamily,
@@ -1378,12 +1452,14 @@ function safeGetFont(
function snapshotRevertLines(
run: import("@editor/tools/pdfTextEditor/model/TextRun").TextRun,
prevText: string,
+ prevTags: TextTags,
): RevertLine[] {
- const lines = prevText.split(/\r?\n/);
+ const lines = splitLines(prevText, prevTags);
const lineHeight =
run.paragraphLineHeight > 0 ? run.paragraphLineHeight : run.fontSize * 1.2;
- return lines.map((text, idx) => ({
+ return lines.map(({ text, tags }, idx) => ({
text,
+ tags,
x: run.matrix.e,
y: run.matrix.f - idx * lineHeight,
fill: { ...run.fill },
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/commands/RetagInnerCommand.ts b/frontend/src/editor/core/tools/pdfTextEditor/commands/RetagInnerCommand.ts
index 285bf42993..e62c3a064a 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/commands/RetagInnerCommand.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/commands/RetagInnerCommand.ts
@@ -3,23 +3,25 @@ import {
RolledBackError,
type Command,
} from "@editor/tools/pdfTextEditor/commands/Command";
+import { splitByBlock } from "@editor/tools/pdfTextEditor/commands/splitByBlock";
+import { elementStretches } from "@editor/tools/pdfTextEditor/commands/TagTextRangeCommand";
import type { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
-import type {
- StructureRole,
- StructureType,
-} from "@editor/tools/pdfTextEditor/model/structureTypes";
+import { isInlineType } from "@editor/tools/pdfTextEditor/model/PageStructure";
+import type { StructureType } from "@editor/tools/pdfTextEditor/model/structureTypes";
/**
* Retag element `key`, one marking part of a block's text, or remove it with
* null, its text read as its block's again. Held on the page's structure and
- * written by the save; the page content keeps its marks.
+ * written by the save; the page content keeps its marks. Retagged as a block,
+ * its text moves into a run of its own.
*/
export class RetagInnerCommand implements Command {
readonly type = "retag-inner";
private readonly pageIndex: number;
private readonly key: string;
private readonly to: StructureType | null;
- private previous: StructureRole | null | undefined;
+ private undo: Array<() => void> = [];
+ private movedTo: string | null = null;
constructor(opts: {
pageIndex: number;
@@ -31,13 +33,28 @@ export class RetagInnerCommand implements Command {
this.to = opts.type;
}
+ /**
+ * The run the element's text was moved into, once applied; null while it
+ * is in the run it was in.
+ */
+ get movedToRunId(): string | null {
+ return this.movedTo;
+ }
+
apply(doc: EditorDocument): void {
const structure = doc.structure(this.pageIndex);
+ const undo: Array<() => void> = [];
try {
const previous = structure.innerType(this.key);
structure.setInnerType(this.key, this.to);
- if (this.previous === undefined) this.previous = previous;
+ // Only an element of a standard type can be changed or removed.
+ undo.push(() => structure.setInnerType(this.key, previous?.type ?? null));
+ this.movedTo =
+ this.to !== null && !isInlineType(this.to)
+ ? this.moveToOwnRun(doc, undo)
+ : null;
} catch (err) {
+ rollBack(undo);
throw new RolledBackError(
new Error(
i18n.t(
@@ -48,15 +65,33 @@ export class RetagInnerCommand implements Command {
),
);
}
+ this.undo = undo;
doc.page(this.pageIndex).bumpRevision();
}
revert(doc: EditorDocument): void {
- if (this.previous === undefined) return;
- // Only an element of a standard type can be changed or removed.
- doc
- .structure(this.pageIndex)
- .setInnerType(this.key, this.previous?.type ?? null);
+ rollBack(this.undo);
+ this.undo = [];
doc.page(this.pageIndex).bumpRevision();
}
+
+ private moveToOwnRun(
+ doc: EditorDocument,
+ undo: Array<() => void>,
+ ): string | null {
+ const page = doc.page(this.pageIndex);
+ const holds = (runId: string) =>
+ elementStretches(doc, this.pageIndex, runId).some(
+ ({ element }) => element.key === this.key,
+ );
+ const holders = page.runs.filter((run) => holds(run.id));
+ const moved = holders
+ .flatMap((run) => splitByBlock(doc, page, run, undo))
+ .find((part) => !holders.includes(part) && holds(part.id));
+ return moved?.id ?? null;
+ }
+}
+
+function rollBack(undo: Array<() => void>): void {
+ while (undo.length > 0) undo.pop()!();
}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/commands/SetFontFamilyCommand.ts b/frontend/src/editor/core/tools/pdfTextEditor/commands/SetFontFamilyCommand.ts
index 1b568822dc..5f97175f86 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/commands/SetFontFamilyCommand.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/commands/SetFontFamilyCommand.ts
@@ -12,6 +12,12 @@ import {
planLineOrigins,
removeMemberPtrs,
} from "@editor/tools/pdfTextEditor/commands/editTextHelpers";
+import { readRunTags } from "@editor/tools/pdfTextEditor/commands/runTags";
+import {
+ sliceTags,
+ splitLines,
+ type TextTags,
+} from "@editor/tools/pdfTextEditor/model/TextTags";
import { deviceFontEmitCount } from "@editor/tools/pdfTextEditor/util/deviceFontEmbed";
import {
setScanOverride,
@@ -62,6 +68,7 @@ export class SetFontFamilyCommand implements Command {
this.prevMemberPtrs = collectMemberPtrs(run).slice();
}
+ const tags = readRunTags(doc, page, run);
// Detach every original object so the page stops painting them.
removeMemberPtrs(
m,
@@ -80,22 +87,37 @@ export class SetFontFamilyCommand implements Command {
// separators a \n split can't see. Baseline stepping for the fallback case
// comes from planLineOrigins so it cannot drift from EditTextCommand's.
const slots = run.paragraphLineSlots;
- const splitTexts = slots.length > 0 ? null : run.text.split(/\r?\n/);
- const emitLines: Array<{ text: string; x: number; y: number }> = splitTexts
+ const splitLinesOfText =
+ slots.length > 0 ? null : splitLines(run.text, tags);
+ const emitLines: Array<{
+ text: string;
+ tags: TextTags;
+ x: number;
+ y: number;
+ }> = splitLinesOfText
? (() => {
- const origins = planLineOrigins(run, splitTexts.length, lineHeight);
- return splitTexts.map((text, i) => ({ text, ...origins[i] }));
+ const origins = planLineOrigins(
+ run,
+ splitLinesOfText.length,
+ lineHeight,
+ );
+ return splitLinesOfText.map((line, i) => ({
+ ...line,
+ ...origins[i],
+ }));
})()
- : slots.map((s) => ({
- text: run.text
- .slice(
- Math.max(0, s.startChar),
- Math.min(run.text.length, s.endChar),
- )
- .replace(/[\r\n]+$/, ""),
- x: s.matrixE,
- y: s.baselineY,
- }));
+ : slots.map((s) => {
+ const start = Math.max(0, s.startChar);
+ const text = run.text
+ .slice(start, Math.min(run.text.length, s.endChar))
+ .replace(/[\r\n]+$/, "");
+ return {
+ text,
+ tags: sliceTags(tags, start, start + text.length),
+ x: s.matrixE,
+ y: s.baselineY,
+ };
+ });
const lineAnchors: number[] = [];
const memberFs: number[] = [];
const leaf: number[] = [];
@@ -107,7 +129,7 @@ export class SetFontFamilyCommand implements Command {
doc,
page,
run,
- lines: emitLines.map((l) => l.text),
+ lines: emitLines.map(({ text, tags }) => ({ text, tags })),
origins: emitLines.map((l) => ({ x: l.x, y: l.y })),
originalFontPtr: 0, // base-14: never reuse the source font
fallbackFamily: this.nextFamily,
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/commands/TagTextRangeCommand.ts b/frontend/src/editor/core/tools/pdfTextEditor/commands/TagTextRangeCommand.ts
index a1c5607cf7..c203bc8095 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/commands/TagTextRangeCommand.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/commands/TagTextRangeCommand.ts
@@ -5,6 +5,7 @@ import {
type Command,
} from "@editor/tools/pdfTextEditor/commands/Command";
import {
+ collectContainersByPtr,
collectMemberPtrs,
measureObjBoxPt,
readObjTexts,
@@ -13,13 +14,29 @@ import {
import {
addTextPiece,
charOrigins,
+ glyphText,
+ inkStarts,
+ pieceOrigin,
+ placeGlyphs,
readMatrix,
readTextSource,
restoreText,
setPieceText,
+ type Placed,
+ type Placing,
type Point,
type TextSource,
} from "@editor/tools/pdfTextEditor/commands/textPieces";
+import { splitByBlock } from "@editor/tools/pdfTextEditor/commands/splitByBlock";
+import { readRunTags } from "@editor/tools/pdfTextEditor/commands/runTags";
+import { readsWordGap } from "@editor/tools/pdfTextEditor/pdfium/LineGrouper";
+import { taggedSpans } from "@editor/tools/pdfTextEditor/model/TextTags";
+import {
+ leaves,
+ lineList,
+ type Leaf,
+ type LeafList,
+} from "@editor/tools/pdfTextEditor/commands/runLeaves";
import type { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
import type { Page } from "@editor/tools/pdfTextEditor/model/Page";
import {
@@ -44,7 +61,9 @@ import {
* Tag part of a run's tagged text, code units `start` to `end`, as its own
* element of `as`, read in language `lang` when given. The save pass gives
* the element its place: inside the element the text was cut from for an
- * inline type, else splitting that element around it.
+ * inline type, else splitting that element around it. Splitting also
+ * replaces the run with one for each block, so `runId` may name no run once
+ * applied.
*/
export class TagTextRangeCommand implements Command {
readonly type = "tag-text-range";
@@ -57,6 +76,7 @@ export class TagTextRangeCommand implements Command {
/** Chosen on first apply, so a redo reuses them. */
private mcids: { cut: number; part: number } | null = null;
private undo: Array<() => void> = [];
+ private movedTo: string | null = null;
constructor(opts: {
pageIndex: number;
@@ -74,6 +94,14 @@ export class TagTextRangeCommand implements Command {
this.lang = opts.lang ?? null;
}
+ /**
+ * The run a block cut moved the cut text into, once applied; null while
+ * the text is in the run it was cut from.
+ */
+ get movedToRunId(): string | null {
+ return this.movedTo;
+ }
+
apply(doc: EditorDocument): void {
const page = doc.page(this.pageIndex);
const undo: Array<() => void> = [];
@@ -131,7 +159,8 @@ export class TagTextRangeCommand implements Command {
? { name: this.as, mcid: cut }
: { name: piece.tag.name, mcid: part };
const drawn = redraw(doc, page, plan, tagFor, undo);
- for (const affected of new Set(plan.objects.map((o) => o.leaf.run))) {
+ const runs = plan.objects.flatMap(({ leaf }) => (leaf ? [leaf.run] : []));
+ for (const affected of new Set(runs)) {
undo.push(snapshotRun(affected));
relist(doc, affected, plan, drawn);
keepRunTag(doc, affected);
@@ -150,6 +179,11 @@ export class TagTextRangeCommand implements Command {
if (this.lang !== null) {
structure.setOwnLang(structure.element(cut)!.key, this.lang);
}
+ if (isInlineType(this.as)) return;
+ const holder = splitByBlock(doc, page, run, undo).find(
+ (part) => innermostMcid(part.tagMarks) === cut,
+ );
+ this.movedTo = holder && holder !== run ? holder.id : null;
}
}
@@ -169,9 +203,12 @@ interface Piece {
tag: TagMark;
}
-/** An object the cut redraws some or all of, as its run lists it. */
+/** An object the cut redraws some or all of. */
interface CutObject {
- leaf: Leaf;
+ ptr: number;
+ text: string;
+ /** Where a run lists it; null for text no run shows, as a lone space. */
+ leaf: Leaf | null;
source: TextSource;
pieces: Piece[];
}
@@ -190,8 +227,8 @@ interface CutPlan {
/**
* Lay the content of every MCID the range draws out in the order the file
* holds it, the range's ends cutting objects into pieces. The range must be
- * one stretch of that content, with only the first MCID keeping a part
- * before it and only the last a part after.
+ * one stretch of that content's ink, with only the first MCID keeping a part
+ * before it and only the last a part after. Changes nothing.
*/
function planCut(
doc: EditorDocument,
@@ -210,25 +247,40 @@ function planCut(
];
const objects = pageObjects(m, page);
const ranged = new Map(inRange.map((leaf) => [leaf.ptr, leaf]));
+ const marks = new Map(objects.map((ptr) => [ptr, ownMark(doc, ptr)]));
+ const textOf = objectTexts(
+ m,
+ page,
+ leafOf,
+ objects.filter((ptr) => from.includes(marks.get(ptr)?.mcid ?? -1)),
+ );
const pieces: Piece[] = [];
for (const [n, mcid] of from.entries()) {
const own = objects.flatMap((ptr) => {
- const tag = ownMark(doc, ptr);
- if (tag?.mcid !== mcid) return [];
+ const tag = marks.get(ptr);
+ if (!tag || tag.mcid !== mcid) return [];
+ const text = textOf.get(ptr)!;
const leaf = ranged.get(ptr);
- if (!leaf) {
- const to = leafOf.get(ptr)?.text.length ?? 0;
- return [{ ptr, tag, from: 0, to, cut: false }];
- }
- return cutLeaf(leaf, start, end).map((part) => ({ ptr, tag, ...part }));
+ const parts = leaf
+ ? cutLeaf(leaf, start, end)
+ : [{ from: 0, to: text.length, cut: false }];
+ return parts.map((part) => ({
+ ptr,
+ tag,
+ ...part,
+ ink: /\S/.test(text.slice(part.from, part.to)),
+ }));
});
const cut = own.map((part) => part.cut);
const first = cut.indexOf(true);
const last = cut.lastIndexOf(true);
- const stretch = first >= 0 && cut.slice(first, last + 1).every(Boolean);
- const before = first > 0 && n > 0;
- const after = last < own.length - 1 && n < from.length - 1;
+ const inked = (parts: typeof own) => parts.some((part) => part.ink);
+ const stretch =
+ first >= 0 &&
+ own.slice(first, last + 1).every((part) => part.cut || !part.ink);
+ const before = n > 0 && inked(own.slice(0, first));
+ const after = n < from.length - 1 && inked(own.slice(last + 1));
if (!stretch || before || after) {
throw new Error("The range is not one stretch of its element's text");
}
@@ -237,36 +289,75 @@ function planCut(
});
}
+ const sources = new Map(
+ [...new Set(pieces.map((piece) => piece.ptr))].map((ptr) => [
+ ptr,
+ readTextSource(m, ptr),
+ ]),
+ );
const redrawn = new Set<Group>(["cut"]);
+ const inGroup = (group: Group) =>
+ pieces.filter((piece) => piece.group === group);
const length = (group: Group) =>
- pieces
- .filter((piece) => piece.group === group)
- .reduce((sum, piece) => sum + piece.to - piece.from, 0);
+ inGroup(group).reduce((sum, piece) => sum + piece.to - piece.from, 0);
+ const drawable = (group: Group) =>
+ inGroup(group).every((piece) => sources.get(piece.ptr));
if (from.length === 1 && length("before") > 0 && length("after") > 0) {
- redrawn.add(length("before") <= length("after") ? "before" : "after");
+ // A part that is not all text, as an underline drawn with it, cannot be
+ // redrawn, so the other is.
+ const [shorter, longer]: Group[] =
+ length("before") <= length("after")
+ ? ["before", "after"]
+ : ["after", "before"];
+ redrawn.add(drawable(shorter) ? shorter : longer);
}
- const cutObjects: CutObject[] = [];
- for (const ptr of new Set(pieces.map((piece) => piece.ptr))) {
+ const cutObjects = [...sources].flatMap(([ptr, source]): CutObject[] => {
const own = pieces.filter((piece) => piece.ptr === ptr);
- if (!own.some((piece) => redrawn.has(piece.group))) continue;
- const leaf = leafOf.get(ptr);
- const source = readTextSource(m, ptr);
- if (!leaf || !source) {
- throw new Error("Only text the editor reads can be redrawn");
- }
- cutObjects.push({ leaf, source, pieces: own });
- }
+ if (!own.some((piece) => redrawn.has(piece.group))) return [];
+ if (!source) throw new Error("Only text can be redrawn");
+ const leaf = leafOf.get(ptr) ?? null;
+ return [{ ptr, text: textOf.get(ptr)!, leaf, source, pieces: own }];
+ });
verifyTexts(m, page, cutObjects);
+ const origins = originsFor(m, page, cutObjects);
+ // A piece of only spaces the text page inferred is drawn by no glyph, so
+ // once redrawn it is no content of any MCID.
+ const empty = new Set(
+ cutObjects.flatMap(({ ptr, text, pieces: own }) =>
+ own.filter(
+ (piece) => !glyphText(text, origins.get(ptr)!, piece.from, piece.to),
+ ),
+ ),
+ );
+ const drawn = (piece: Piece) => !empty.has(piece);
return {
from,
- pieces,
+ pieces: pieces.filter(drawn),
redrawn,
- objects: cutObjects,
- origins: originsFor(m, page, cutObjects),
+ objects: cutObjects.map((o) => ({ ...o, pieces: o.pieces.filter(drawn) })),
+ origins,
};
}
+/**
+ * Each object's text: as its run lists it, or as the text page reads it for
+ * one no run lists, as a lone space. Empty for an object drawing no text.
+ */
+function objectTexts(
+ m: WrappedPdfiumModule,
+ page: Page,
+ leafOf: ReadonlyMap<number, Leaf>,
+ objects: readonly number[],
+): Map<number, string> {
+ const unlisted = objects.filter((ptr) => !leafOf.has(ptr));
+ const read = readObjTexts(m, page.pagePtr, unlisted);
+ const readOf = new Map(unlisted.map((ptr, i) => [ptr, read[i]]));
+ return new Map(
+ objects.map((ptr) => [ptr, leafOf.get(ptr)?.text ?? readOf.get(ptr) ?? ""]),
+ );
+}
+
function groupAt(i: number, first: number, last: number): Group {
if (i < first) return "before";
return i > last ? "after" : "cut";
@@ -296,43 +387,42 @@ function verifyTexts(
const held = readObjTexts(
m,
page.pagePtr,
- objects.map((o) => o.leaf.ptr),
+ objects.map((o) => o.ptr),
);
- if (held.some((text, i) => text !== objects[i].leaf.text)) {
+ if (held.some((text, i) => text !== objects[i].text)) {
throw new Error("The text the editor shows is not the text drawn");
}
}
-/** Where each piece starts, for every piece that does not start its object. */
+/** Where each object draws each character of its text a glyph draws. */
function originsFor(
m: WrappedPdfiumModule,
page: Page,
objects: readonly CutObject[],
): Map<number, Map<number, Point>> {
- const wanted = new Map<number, Set<number>>();
- const lengths = new Map<number, number>();
- for (const { leaf, pieces } of objects) {
- const offsets = pieces.map((piece) => piece.from).filter((at) => at > 0);
- if (offsets.length === 0) continue;
- wanted.set(leaf.ptr, new Set(offsets));
- lengths.set(leaf.ptr, leaf.text.length);
- }
- const origins = charOrigins(m, page.pagePtr, wanted, lengths);
- for (const [ptr, offsets] of wanted) {
- if ([...offsets].some((at) => !origins.get(ptr)?.has(at))) {
+ const origins = charOrigins(
+ m,
+ page.pagePtr,
+ new Map(objects.map(({ ptr, text }) => [ptr, text])),
+ );
+ for (const { ptr, text } of objects) {
+ const drawn = origins.get(ptr);
+ const ink = inkStarts(text, 0, text.length);
+ if (!drawn || ink.some((at) => !drawn.has(at))) {
throw new Error("PDFium cannot place a piece of the text");
}
}
return origins;
}
-/** The objects drawing each cut object's pieces, in reading order, by the object it was. */
-type Drawn = Map<number, Array<{ ptr: number; piece: Piece }>>;
+/** The objects drawing each cut object's text, in reading order, by the object it was. */
+type Drawn = Map<number, Placed[]>;
/**
* Redraw the pieces in the redrawn groups as new objects, in reading order so
* PDFium writes each MCID's content in that order. An object keeping a piece
- * is cut down to it; one keeping none is taken off the page.
+ * is cut down to it; one keeping none is taken off the page. Every glyph is
+ * then drawn where it was.
*/
function redraw(
doc: EditorDocument,
@@ -342,25 +432,52 @@ function redraw(
undo: Array<() => void>,
): Drawn {
const m = doc.module;
- const drawn: Drawn = new Map();
- const expected = new Map<number, string>();
- const objectFor = new Map(plan.objects.map((o) => [o.leaf.ptr, o]));
+ const heads: Array<{ piece: Piece; placing: Placing }> = [];
+ const placing = (
+ object: CutObject,
+ piece: Piece,
+ ptr: number,
+ tags: readonly TagMark[],
+ fresh: boolean,
+ ): Placing => ({
+ ptr,
+ from: piece.from,
+ to: piece.to,
+ text: object.text,
+ source: object.source,
+ origins: plan.origins.get(object.ptr)!,
+ tags,
+ fresh,
+ });
+ const glyphsOf = (object: CutObject, piece: Piece) =>
+ glyphText(object.text, plan.origins.get(object.ptr)!, piece.from, piece.to);
+ const objectFor = new Map(plan.objects.map((o) => [o.ptr, o]));
for (const piece of plan.pieces) {
const object = objectFor.get(piece.ptr);
if (!object || !plan.redrawn.has(piece.group)) continue;
- const text = object.leaf.text.slice(piece.from, piece.to);
- const origin = startOf(object, piece, plan.origins);
- const ptr = addTextPiece(m, doc.docPtr, page, object.source, text, origin, [
- tagFor(piece),
- ]);
+ const tags = [tagFor(piece)];
+ const { matrix } = object.source;
+ const origin = pieceOrigin(
+ plan.origins.get(object.ptr)!,
+ object.text,
+ piece.from,
+ ) ?? { x: matrix[4], y: matrix[5] };
+ const ptr = addTextPiece(
+ m,
+ doc.docPtr,
+ page,
+ object.source,
+ glyphsOf(object, piece),
+ origin,
+ tags,
+ );
if (!ptr) throw new Error("PDFium could not draw the text");
undo.push(() => removeAndDestroyObject(m, page.pagePtr, ptr));
- expected.set(ptr, text);
- drawn.set(piece.ptr, [...(drawn.get(piece.ptr) ?? []), { ptr, piece }]);
+ heads.push({ piece, placing: placing(object, piece, ptr, tags, true) });
}
for (const object of plan.objects) {
- const { ptr, text } = object.leaf;
+ const { ptr, text } = object;
const kept = object.pieces.find((piece) => !plan.redrawn.has(piece.group));
if (!kept) {
const index = pageObjects(m, page).indexOf(ptr);
@@ -369,40 +486,84 @@ function redraw(
continue;
}
const matrix = readMatrix(m, ptr);
- const keptText = text.slice(kept.from, kept.to);
- const origin = kept.from > 0 ? startOf(object, kept, plan.origins) : null;
- if (!matrix || !setPieceText(m, ptr, keptText, origin)) {
+ const origin =
+ kept.from > 0
+ ? pieceOrigin(plan.origins.get(ptr)!, text, kept.from)
+ : null;
+ if (!matrix || !setPieceText(m, ptr, glyphsOf(object, kept), origin)) {
throw new Error("PDFium could not redraw the text");
}
undo.push(() => restoreText(m, ptr, text, matrix));
- expected.set(ptr, keptText);
- const pieces = [...(drawn.get(ptr) ?? []), { ptr, piece: kept }];
- drawn.set(
- ptr,
- pieces.sort((a, b) => a.piece.from - b.piece.from),
- );
+ const tags = readTagMarks(m, ptr);
+ heads.push({
+ piece: kept,
+ placing: placing(object, kept, ptr, tags, false),
+ });
}
- // The text page ends an object's text with a space it infers from the gap
- // to the next, which is no glyph of the object's.
- const read = readObjTexts(m, page.pagePtr, [...expected.keys()]);
- if (
- [...expected.values()].some(
- (text, i) => read[i]?.trimEnd() !== text.trimEnd(),
- )
- ) {
- throw new Error("PDFium redrew the text differently");
- }
+ const placed = placeGlyphs(
+ m,
+ doc.docPtr,
+ page,
+ heads.map((head) => head.placing),
+ undo,
+ );
+ const drawn: Drawn = new Map();
+ heads.forEach(({ piece }, i) => {
+ drawn.set(piece.ptr, [...(drawn.get(piece.ptr) ?? []), ...placed[i]]);
+ });
+ for (const parts of drawn.values()) parts.sort((a, b) => a.from - b.from);
+ verifyRedrawn(m, page, plan, drawn);
return drawn;
}
-function startOf(
- object: CutObject,
- piece: Piece,
- origins: ReadonlyMap<number, ReadonlyMap<number, Point>>,
-): Point {
- if (piece.from > 0) return origins.get(object.leaf.ptr)!.get(piece.from)!;
- return { x: object.source.matrix[4], y: object.source.matrix[5] };
+function verifyRedrawn(
+ m: WrappedPdfiumModule,
+ page: Page,
+ plan: CutPlan,
+ drawn: Drawn,
+): void {
+ const parts = plan.objects.flatMap((object) =>
+ (drawn.get(object.ptr) ?? []).map((part, i, all) => ({
+ object,
+ part,
+ next: all[i + 1],
+ })),
+ );
+ const read = readObjTexts(
+ m,
+ page.pagePtr,
+ parts.map(({ part }) => part.ptr),
+ );
+ const wrong = parts.some(({ object, part, next }, i) => {
+ const { text } = object;
+ // A part starting with a space the text page inferred draws no glyph for
+ // it, and the text page reads that space as the part before's.
+ const own = text.slice(part.from, part.to).trimStart();
+ const got = read[i]?.trimStart();
+ // The text page ends an object's text with a space it infers from the gap
+ // to the next, which is no glyph of the object's.
+ if (got?.trimEnd() !== own.trimEnd()) return true;
+ // Between two parts of one word, as letter-spaced text drawn glyph by
+ // glyph, that space would split the word, as would the one a line read
+ // puts in a wide gap.
+ const inWord = next && /\S$/.test(own) && /\S/.test(text[part.to] ?? "");
+ return inWord && (got !== own || readApart(m, object.source, part, next));
+ });
+ if (wrong) throw new Error("PDFium redrew the text differently");
+}
+
+function readApart(
+ m: WrappedPdfiumModule,
+ source: TextSource,
+ part: Placed,
+ next: Placed,
+): boolean {
+ const before = measureObjBoxPt(m, part.ptr);
+ const after = measureObjBoxPt(m, next.ptr);
+ if (!before || !after) return true;
+ const fontSize = source.size * Math.hypot(source.matrix[0], source.matrix[1]);
+ return readsWordGap(after.x - (before.x + before.width), fontSize);
}
/** List the objects now drawing a run's text in place of the ones they replace. */
@@ -414,8 +575,7 @@ function relist(
): void {
const m = doc.module;
const replaced = plan.objects
- .map((o) => o.leaf)
- .filter((leaf) => leaf.run === run)
+ .flatMap(({ leaf }) => (leaf?.run === run ? [leaf] : []))
.sort((a, b) => b.index - a.index);
for (const leaf of replaced) {
const now = drawn.get(leaf.ptr)!;
@@ -426,9 +586,9 @@ function relist(
};
const entries = {
ptrs: now.map((d) => d.ptr),
- texts: now.map((d) => leaf.text.slice(d.piece.from, d.piece.to)),
+ texts: now.map((d) => leaf.text.slice(d.from, d.to)),
bounds: now.map((d) => box(d.ptr)),
- starts: now.map((d) => d.piece.from),
+ starts: now.map((d) => d.from),
};
replaceEntries(leaf.list, leaf.index, entries);
// A paragraph keeps its first line's arrays on the run as well.
@@ -465,67 +625,6 @@ function replaceEntries(
list.charStarts.splice(index, 1, ...entries.starts.map((at) => start + at));
}
-/** One object's text in a run, where it starts in the run's text, and the arrays listing it. */
-interface Leaf {
- run: TextRun;
- ptr: number;
- text: string;
- start: number;
- list: LeafList;
- index: number;
-}
-
-/** A run's parallel arrays for one line's objects. */
-interface LeafList {
- ptrs: number[];
- texts: string[];
- bounds: Array<{ x: number; right: number }>;
- charStarts: number[];
- /** Where the line starts in the run's text. */
- base: number;
-}
-
-function lineList(run: TextRun): LeafList {
- return {
- ptrs: run.mergedFromPtrs,
- texts: run.mergedFromTexts,
- bounds: run.mergedFromBounds,
- charStarts: run.mergedFromCharStarts,
- base: 0,
- };
-}
-
-/** The run's objects in reading order; null when their texts do not tile the run's. */
-function leaves(run: TextRun): Leaf[] | null {
- const lists: LeafList[] =
- run.paragraphLineSlots.length > 0
- ? run.paragraphLineSlots.map((slot) => ({
- ptrs: slot.mergedFromPtrs,
- texts: slot.mergedFromTexts,
- bounds: slot.mergedFromBounds,
- charStarts: slot.mergedFromCharStarts,
- base: slot.startChar,
- }))
- : [lineList(run)];
- const out = lists.flatMap((list) =>
- list.ptrs.map((ptr, index) => ({
- run,
- ptr,
- text: list.texts[index] ?? "",
- start: list.base + (list.charStarts[index] ?? Number.NaN),
- list,
- index,
- })),
- );
- const tiles = out.every(
- (leaf, i) =>
- leaf.ptr !== 0 &&
- run.text.slice(leaf.start, leaf.start + leaf.text.length) === leaf.text &&
- (i === 0 || leaf.start >= out[i - 1].start + out[i - 1].text.length),
- );
- return out.length > 0 && tiles ? out : null;
-}
-
/** Every page-level object a run lists, and where. */
function pageLeaves(page: Page): Map<number, Leaf> {
const out = new Map<number, Leaf>();
@@ -544,8 +643,9 @@ function pageObjects(m: WrappedPdfiumModule, page: Page): number[] {
/**
* The element owning every object the range draws. Throws when the run's
- * objects cannot be mapped to its text, or the range holds untagged or
- * artifact text, or text of more than one element.
+ * text is inside a form XObject, or its objects cannot be mapped to its text,
+ * or the range holds untagged or artifact text, or text of more than one
+ * element.
*/
function rangeOwner(
doc: EditorDocument,
@@ -553,6 +653,12 @@ function rangeOwner(
start: number,
end: number,
): StructureElement {
+ // A form's marks resolve against the form's own /StructParents, and its
+ // content is no page content a cut can redraw.
+ const containers = [...collectContainersByPtr(run).values()];
+ if (run.containerPtr !== 0 || containers.some(Boolean)) {
+ throw new Error("Only text drawn on the page itself can be cut");
+ }
const all = leaves(run);
if (!all) throw new Error("The run's objects do not match its text");
const inRange = all.filter(
@@ -575,8 +681,9 @@ function rangeOwner(
/**
* The types code units `start` to `end` of run `runId` can be tagged as:
* every TEXT_RANGE_TYPES entry, only the inline ones when the text's element
- * is not a block it can split, or none. Checks what apply refuses, without
- * changing anything.
+ * is not a block it can split, or none. Runs apply's checks without changing
+ * anything, all but those on where the redrawn text lands, which only drawing
+ * it shows.
*/
export function rangeTagTypes(
doc: EditorDocument,
@@ -592,6 +699,7 @@ export function rangeTagTypes(
let owner: StructureElement;
try {
owner = rangeOwner(doc, run, start, end);
+ planCut(doc, doc.page(pageIndex), run, start, end);
} catch {
return [];
}
@@ -607,29 +715,32 @@ export interface ElementStretch {
}
/**
- * The stretches of run `runId`'s text each element marks, in reading order:
- * one for each series of the run's objects one element marks. Untagged and
- * artifact text is left out, and every stretch when the run's objects cannot
- * be mapped to its text.
+ * The stretches of run `runId`'s text each element marks, in reading order,
+ * as `readRunTags` places its objects' tags. Untagged and artifact text is
+ * left out.
*/
export function elementStretches(
doc: EditorDocument,
pageIndex: number,
runId: string,
): ElementStretch[] {
- const run = doc.page(pageIndex).findRun(runId);
- const all = run ? leaves(run) : null;
- if (!all) return [];
+ const page = doc.page(pageIndex);
+ const run = page.findRun(runId);
+ if (!run) return [];
const structure = doc.structure(pageIndex);
const out: ElementStretch[] = [];
- let previous: StructureElement | null = null;
- for (const leaf of all) {
- const mcid = ownMark(doc, leaf.ptr)?.mcid ?? null;
+ const spans = taggedSpans(readRunTags(doc, page, run), run.text.length);
+ for (const { start, end, tags } of spans) {
+ const mcid = tags.some((tag) => tag.name === ARTIFACT_TAG)
+ ? null
+ : innermostMcid(tags);
const element = mcid === null ? null : structure.element(mcid);
- const end = leaf.start + leaf.text.length;
- if (element && element === previous) out.at(-1)!.end = end;
- else if (element) out.push({ start: leaf.start, end, element });
- previous = element;
+ const last = out.at(-1);
+ if (element && last?.element === element && last.end === start) {
+ last.end = end;
+ } else if (element) {
+ out.push({ start, end, element });
+ }
}
return out;
}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/commands/editTextHelpers.ts b/frontend/src/editor/core/tools/pdfTextEditor/commands/editTextHelpers.ts
index c057ae71e6..aaf3cbf599 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/commands/editTextHelpers.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/commands/editTextHelpers.ts
@@ -15,10 +15,13 @@ import {
import { getActiveCharcodeStrategy } from "@editor/tools/pdfTextEditor/charcode/CharcodeStrategy";
import { emitFallbackTextObject } from "@editor/tools/pdfTextEditor/util/fallbackFont";
import { emitDeviceFontTextObject } from "@editor/tools/pdfTextEditor/util/deviceFontEmbed";
+import { applyTagMarks } from "@editor/tools/pdfTextEditor/pdfium/PdfiumTagMarks";
import {
- applyTagMarks,
- type TagMark,
-} from "@editor/tools/pdfTextEditor/pdfium/PdfiumTagMarks";
+ taggedSpans,
+ uniformTags,
+ type TaggedSpan,
+ type TextTags,
+} from "@editor/tools/pdfTextEditor/model/TextTags";
import { nearestStandardFont } from "@editor/tools/pdfTextEditor/util/fontFamily";
import {
SCRATCH,
@@ -265,9 +268,10 @@ interface CreatedTextOptions {
strokeWidth?: number;
/** The run's on-page rotation (normalised cos/sin of its text matrix). */
rotation?: { cos: number; sin: number };
- // Required so every emit decides: a re-emit of existing text passes the
- // run's tags, new content passes none.
- tagMarks: readonly TagMark[];
+ // Required so every emit decides: a re-emit of existing text passes that
+ // text's tags, new content passes none. Each stretch with tags of its own
+ // is drawn as objects of its own.
+ tags: TextTags;
// Extra advance per glyph in PDF points - the source run's rendered
// letter-spacing (Tc), inferred at read time.
charSpacingPt?: number;
@@ -664,6 +668,9 @@ export function rotateObjectAbout(
}
export function emitTextLine(opts: CreatedTextOptions): number[] {
+ const spans = taggedSpans(opts.tags, opts.text.length);
+ if (spans.length > 1) return emitTaggedSpans(opts, spans);
+ const tagMarks = spans[0]?.tags ?? [];
const m = opts.doc.module;
const size = Math.max(4, opts.fontSize);
const family = opts.fallbackFamily ?? "Helvetica";
@@ -681,7 +688,7 @@ export function emitTextLine(opts: CreatedTextOptions): number[] {
// Every successful emit funnels through here, so this is the one place to
// re-apply the source run's ink state - new objects default to a flat fill.
applyInkState(m, ptrs, opts);
- applyTagMarks(m, opts.doc.docPtr, ptrs, opts.tagMarks);
+ applyTagMarks(m, opts.doc.docPtr, ptrs, tagMarks);
return ptrs;
};
@@ -1005,6 +1012,7 @@ export function emitTextLine(opts: CreatedTextOptions): number[] {
text: chunk.text,
x: cursor,
rotation: undefined,
+ tags: uniformTags(tagMarks),
outTexts: opts.outTexts ? chunkTexts : undefined,
});
if (wordPtrs.length === 0) continue;
@@ -1029,6 +1037,56 @@ export function emitTextLine(opts: CreatedTextOptions): number[] {
return withRotation(ptrs);
}
+/**
+ * Draw each span of `opts.text` with its own tags, one after another along
+ * the line.
+ */
+function emitTaggedSpans(
+ opts: CreatedTextOptions,
+ spans: readonly TaggedSpan[],
+): number[] {
+ const m = opts.doc.module;
+ const size = Math.max(4, opts.fontSize);
+ const family = opts.fallbackFamily ?? "Helvetica";
+ const spacing = opts.charSpacingPt ?? 0;
+ const ptrs: number[] = [];
+ let cursor = opts.x;
+ for (const { start, end, tags } of spans) {
+ const text = opts.text.slice(start, end);
+ const texts: string[] = [];
+ const own = emitTextLine({
+ ...opts,
+ text,
+ x: cursor,
+ rotation: undefined,
+ tags: uniformTags(tags),
+ outTexts: opts.outTexts ? texts : undefined,
+ });
+ opts.outTexts?.push(...texts);
+ ptrs.push(...own);
+ // Advanced as the per-word loop in emitTextLine advances, so splitting a
+ // line by tags does not move its words.
+ const ink = text.trimEnd();
+ const gap = text.slice(ink.length);
+ const right = Math.max(
+ cursor,
+ ...own.map((ptr) => measureObjRightEdgePt(m, ptr)),
+ );
+ const metric = measureAdvancePt(ink, family, size);
+ cursor += right - cursor >= metric * 0.35 ? right - cursor : metric;
+ cursor += gap
+ ? measureAdvancePt(gap, family, size) + spacing * (gap.length + 1)
+ : spacing;
+ }
+ const rot = opts.rotation;
+ if (rot) {
+ for (const ptr of ptrs) {
+ rotateObjectAbout(m, ptr, opts.x, opts.y, rot.cos, rot.sin);
+ }
+ }
+ return ptrs;
+}
+
interface TextObjReadModule {
FPDFText_LoadPage?: (page: number) => number;
FPDFText_ClosePage?: (tp: number) => void;
@@ -1299,7 +1357,7 @@ export function emitRunLines(opts: {
doc: EditorDocument;
page: Page;
run: TextRun;
- lines: string[];
+ lines: ReadonlyArray<{ text: string; tags: TextTags }>;
origins: LineOrigin[];
originalFontPtr: number;
fallbackFamily: string;
@@ -1308,7 +1366,7 @@ export function emitRunLines(opts: {
const rot = rotationFromMatrix(opts.run.matrix);
const out: EmittedLine[] = [];
for (let i = 0; i < opts.lines.length; i++) {
- const text = opts.lines[i];
+ const { text, tags } = opts.lines[i];
const origin = opts.origins[i];
if (!origin) continue;
if (text.length === 0) {
@@ -1332,7 +1390,7 @@ export function emitRunLines(opts: {
fallbackFamily: opts.fallbackFamily,
// Keep the run's rotation on re-emit (no-op for upright text).
rotation: rot,
- tagMarks: opts.run.tagMarks,
+ tags,
});
out.push({ ptrs, text, texts, x: origin.x, y: origin.y });
}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/commands/partialEdit.ts b/frontend/src/editor/core/tools/pdfTextEditor/commands/partialEdit.ts
index 029946700d..68c15cd37b 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/commands/partialEdit.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/commands/partialEdit.ts
@@ -16,6 +16,12 @@ import {
fallbackFontIdFor,
} from "@editor/tools/pdfTextEditor/util/fontCapability";
import { writeUtf16 } from "@editor/services/pdfiumService";
+import {
+ sliceTags,
+ uniformTags,
+ type TextTags,
+} from "@editor/tools/pdfTextEditor/model/TextTags";
+import { readTagMarks } from "@editor/tools/pdfTextEditor/pdfium/PdfiumTagMarks";
import { transformObject } from "@editor/tools/pdfTextEditor/util/objectTransform";
import {
SCRATCH,
@@ -614,6 +620,8 @@ export function applyPartialEditPlan(
page: Page,
run: TextRun,
plan: PartialEditPlan,
+ /** The edited text's tags: what each insert is drawn with. */
+ tags: TextTags,
/** Override the baseline used for emitted inserts. */
baselineY?: number,
// Override the left edge used for the FIRST unanchored insert (before any
@@ -734,6 +742,7 @@ export function applyPartialEditPlan(
// Read the object's own font BEFORE we touch it, so a fallback re-emit
// can reuse the same embedded font via the charcode path.
const modFontPtr = objFontPtr(m, ptr);
+ const modTags = readTagMarks(m, ptr);
setObjText(m, ptr, modText);
if (Math.abs(offset) > 0.05) {
try {
@@ -762,7 +771,7 @@ export function applyPartialEditPlan(
fontSize: run.fontSize,
fill: run.fill,
...inkFromRun(run),
- tagMarks: run.tagMarks,
+ tags: uniformTags(modTags),
originalFontPtr: modFontPtr,
originalFontSubset: run.fontSubset,
charSpacingPt: run.charSpacingPt,
@@ -818,6 +827,11 @@ export function applyPartialEditPlan(
}
} else if (op.type === "insert" && op.text) {
const insertText = op.text;
+ const insertTags = sliceTags(
+ tags,
+ op.startBIdx,
+ op.startBIdx + insertText.length,
+ );
const anchorIdx = op.anchorSubRunIdx;
const beforeIdx = op.anchorBeforeSubRunIdx;
if (anchorIdx !== undefined) absorbDeletesBefore(anchorIdx);
@@ -854,7 +868,7 @@ export function applyPartialEditPlan(
fontSize: run.fontSize,
fill: run.fill,
...inkFromRun(run),
- tagMarks: run.tagMarks,
+ tags: insertTags,
originalFontPtr: borrowedFontPtr,
originalFontSubset: run.fontSubset,
charSpacingPt: run.charSpacingPt,
@@ -897,7 +911,7 @@ export function applyPartialEditPlan(
fontSize: run.fontSize,
fill: run.fill,
...inkFromRun(run),
- tagMarks: run.tagMarks,
+ tags: insertTags,
originalFontPtr: 0,
charSpacingPt: run.charSpacingPt,
fallbackFamily,
@@ -1118,9 +1132,12 @@ export function bestFontPtrForText(
return 0;
}
-// Locate the single contiguous edit between `prev` and `next` via a
-// prefix/suffix scan.
-function diffSpan(
+/**
+ * The one stretch that differs between `prev` and `next`, by their common
+ * prefix and suffix: `start` to `prevEnd` in `prev`, `start` to `nextEnd` in
+ * `next`.
+ */
+export function diffSpan(
prev: string,
next: string,
): { start: number; prevEnd: number; nextEnd: number } {
@@ -1245,6 +1262,8 @@ export function applyParagraphEditPlan(
page: Page,
run: TextRun,
paraPlan: ParagraphEditPlan,
+ /** The edited text's tags. */
+ tags: TextTags,
): ParagraphEditApplyResult {
const m = doc.module;
// Per-VISUAL-line next text from the plan (slot-range derived).
@@ -1267,9 +1286,12 @@ export function applyParagraphEditPlan(
let minX = Infinity;
let maxRight = -Infinity;
+ let lineStart = 0;
for (let i = 0; i < newSlots.length; i++) {
const slot = newSlots[i];
const lineText = lines[i] ?? "";
+ const lineTags = sliceTags(tags, lineStart, lineStart + lineText.length);
+ lineStart += lineText.length + 1;
const planEntry = planBySlot.get(i);
if (!planEntry) {
// Unchanged line - keep slot data, just update bounds tracking.
@@ -1319,7 +1341,7 @@ export function applyParagraphEditPlan(
fontSize: slot.fontSize,
fill: run.fill,
...inkFromRun(run),
- tagMarks: run.tagMarks,
+ tags: lineTags,
originalFontPtr: reuseFontPtr,
originalFontSubset: slot.fontSubset,
charSpacingPt: run.charSpacingPt,
@@ -1360,6 +1382,7 @@ export function applyParagraphEditPlan(
page,
slotView,
planEntry.plan,
+ lineTags,
slot.baselineY,
slot.mergedFromBounds[0]?.x ?? slot.matrixE,
);
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/commands/runLeaves.ts b/frontend/src/editor/core/tools/pdfTextEditor/commands/runLeaves.ts
new file mode 100644
index 0000000000..85cafbbe69
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/commands/runLeaves.ts
@@ -0,0 +1,62 @@
+import type { TextRun } from "@editor/tools/pdfTextEditor/model/TextRun";
+
+/** One object's text in a run, where it starts in the run's text, and the arrays listing it. */
+export interface Leaf {
+ run: TextRun;
+ ptr: number;
+ text: string;
+ start: number;
+ list: LeafList;
+ index: number;
+}
+
+/** A run's parallel arrays for one line's objects. */
+export interface LeafList {
+ ptrs: number[];
+ texts: string[];
+ bounds: Array<{ x: number; right: number }>;
+ charStarts: number[];
+ /** Where the line starts in the run's text. */
+ base: number;
+}
+
+export function lineList(run: TextRun): LeafList {
+ return {
+ ptrs: run.mergedFromPtrs,
+ texts: run.mergedFromTexts,
+ bounds: run.mergedFromBounds,
+ charStarts: run.mergedFromCharStarts,
+ base: 0,
+ };
+}
+
+/** The run's objects in reading order; null when their texts do not tile the run's. */
+export function leaves(run: TextRun): Leaf[] | null {
+ const lists: LeafList[] =
+ run.paragraphLineSlots.length > 0
+ ? run.paragraphLineSlots.map((slot) => ({
+ ptrs: slot.mergedFromPtrs,
+ texts: slot.mergedFromTexts,
+ bounds: slot.mergedFromBounds,
+ charStarts: slot.mergedFromCharStarts,
+ base: slot.startChar,
+ }))
+ : [lineList(run)];
+ const out = lists.flatMap((list) =>
+ list.ptrs.map((ptr, index) => ({
+ run,
+ ptr,
+ text: list.texts[index] ?? "",
+ start: list.base + (list.charStarts[index] ?? Number.NaN),
+ list,
+ index,
+ })),
+ );
+ const tiles = out.every(
+ (leaf, i) =>
+ leaf.ptr !== 0 &&
+ run.text.slice(leaf.start, leaf.start + leaf.text.length) === leaf.text &&
+ (i === 0 || leaf.start >= out[i - 1].start + out[i - 1].text.length),
+ );
+ return out.length > 0 && tiles ? out : null;
+}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/commands/runTags.ts b/frontend/src/editor/core/tools/pdfTextEditor/commands/runTags.ts
new file mode 100644
index 0000000000..bcbad65112
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/commands/runTags.ts
@@ -0,0 +1,175 @@
+import type { WrappedPdfiumModule } from "@embedpdf/pdfium";
+import {
+ collectContainersByPtr,
+ collectMemberPtrs,
+ readObjTexts,
+} from "@editor/tools/pdfTextEditor/commands/editTextHelpers";
+import { diffSpan } from "@editor/tools/pdfTextEditor/commands/partialEdit";
+import { leaves } from "@editor/tools/pdfTextEditor/commands/runLeaves";
+import type { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
+import type { Page } from "@editor/tools/pdfTextEditor/model/Page";
+import type { TextRun } from "@editor/tools/pdfTextEditor/model/TextRun";
+import {
+ joinTags,
+ sameTags,
+ sliceTags,
+ taggedSpans,
+ tagsAt,
+ uniformTags,
+ type TagStretch,
+ type TextTags,
+} from "@editor/tools/pdfTextEditor/model/TextTags";
+import {
+ innermostMcid,
+ readTagMarks,
+ type TagMark,
+} from "@editor/tools/pdfTextEditor/pdfium/PdfiumTagMarks";
+
+/** Where one of a run's objects draws in the run's text. */
+interface ObjectSpan {
+ ptr: number;
+ start: number;
+ text: string;
+}
+
+/**
+ * The tags each code unit of `run.text` is drawn with, read from the objects
+ * drawing it. A space between two objects of one element is that element's;
+ * between an element inside the block and the block's own text, the block's.
+ * The run's own tags for all of it when its objects agree, or cannot be
+ * placed in its text.
+ */
+export function readRunTags(
+ doc: EditorDocument,
+ page: Page,
+ run: TextRun,
+): TextTags {
+ const uniform = uniformTags(run.tagMarks);
+ // A form's marks resolve against the form's own /StructParents, so they
+ // would mis-tag the page-level objects an edit draws.
+ const containers = [...collectContainersByPtr(run).values()];
+ if (run.containerPtr !== 0 || containers.some(Boolean)) return uniform;
+ const m = doc.module;
+ const ptrs = collectMemberPtrs(run).filter(Boolean);
+ const marks = new Map(ptrs.map((ptr) => [ptr, readTagMarks(m, ptr)]));
+ const [first] = marks.values();
+ if (!first || [...marks.values()].every((tags) => sameTags(tags, first))) {
+ return uniform;
+ }
+ const spans: readonly ObjectSpan[] | null =
+ leaves(run) ?? drawnSpans(m, page, run, ptrs);
+ if (!spans) return uniform;
+ const tagsOf = (span: ObjectSpan) =>
+ marks.get(span.ptr) ?? readTagMarks(m, span.ptr);
+ return spans.flatMap((span, i): TagStretch[] => {
+ const tags = tagsOf(span);
+ const next = spans[i + 1];
+ if (!next) return [{ end: Infinity, tags }];
+ const own = { end: span.start + span.text.length, tags };
+ const nextTags = tagsOf(next);
+ const gap = sameTags(tags, nextTags)
+ ? tags
+ : blockSide(doc, page.index, tags, nextTags);
+ return [own, { end: next.start, tags: gap }];
+ });
+}
+
+/**
+ * Where each object draws, read back from the page, for a run whose own
+ * lists no longer say: an edit that redrew it whole keeps only its objects.
+ */
+function drawnSpans(
+ m: WrappedPdfiumModule,
+ page: Page,
+ run: TextRun,
+ ptrs: number[],
+): ObjectSpan[] | null {
+ const texts = readObjTexts(m, page.pagePtr, ptrs);
+ const spans: ObjectSpan[] = [];
+ let cursor = 0;
+ for (const [i, ptr] of ptrs.entries()) {
+ const text = texts[i]?.trim();
+ if (!text) continue;
+ const start = run.text.indexOf(text, cursor);
+ if (start < 0) return null;
+ spans.push({ ptr, start, text });
+ cursor = start + text.length;
+ }
+ return spans.length > 0 ? spans : null;
+}
+
+/**
+ * The tags `nextText` is drawn with when it replaces `prevText`, which is
+ * drawn with `prev`. Text the edit keeps will keep its tags. New text takes
+ * those of the text it replaced when that was one element's, else those of
+ * the text before it, but where an element inside the block meets the
+ * block's own text, the block's: typing after a link does not extend it.
+ * `fallback` tags new text with nothing either side.
+ */
+export function editedTags(
+ doc: EditorDocument,
+ pageIndex: number,
+ prev: TextTags,
+ prevText: string,
+ nextText: string,
+ fallback: readonly TagMark[],
+): TextTags {
+ const spans = taggedSpans(prev, prevText.length);
+ if (spans.length <= 1) return uniformTags(spans[0]?.tags ?? fallback);
+ const { start, prevEnd, nextEnd } = diffSpan(prevText, nextText);
+ const inserted =
+ nextEnd > start
+ ? [
+ {
+ end: nextEnd - start,
+ tags:
+ insertedTags(doc, pageIndex, prev, prevText, start, prevEnd) ??
+ fallback,
+ },
+ ]
+ : [];
+ return joinTags(
+ joinTags(sliceTags(prev, 0, start), start, inserted),
+ nextEnd,
+ sliceTags(prev, prevEnd, Infinity),
+ );
+}
+
+function insertedTags(
+ doc: EditorDocument,
+ pageIndex: number,
+ prev: TextTags,
+ prevText: string,
+ start: number,
+ prevEnd: number,
+): readonly TagMark[] | null {
+ const replaced = taggedSpans(
+ sliceTags(prev, start, prevEnd),
+ prevEnd - start,
+ );
+ if (replaced.length === 1) return replaced[0].tags;
+ const before = start > 0 ? tagsAt(prev, start - 1) : null;
+ const after = prevEnd < prevText.length ? tagsAt(prev, prevEnd) : null;
+ if (!before || !after) return before ?? after;
+ return blockSide(doc, pageIndex, before, after);
+}
+
+/**
+ * The tags of text between `before` and `after`: `after` when only `before`
+ * marks an element inside the block, as a link inside a paragraph, else
+ * `before`.
+ */
+function blockSide(
+ doc: EditorDocument,
+ pageIndex: number,
+ before: readonly TagMark[],
+ after: readonly TagMark[],
+): readonly TagMark[] {
+ const insideBlock = (tags: readonly TagMark[]) => {
+ const mcid = innermostMcid(tags);
+ const element =
+ mcid === null ? null : doc.structure(pageIndex).element(mcid);
+ return element !== null && element.key !== element.block.key;
+ };
+ return insideBlock(before) && !insideBlock(after) ? after : before;
+}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/commands/scanStyle.ts b/frontend/src/editor/core/tools/pdfTextEditor/commands/scanStyle.ts
index 5e6f6393aa..6d32c932e6 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/commands/scanStyle.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/commands/scanStyle.ts
@@ -1,6 +1,7 @@
import type { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
import type { Page } from "@editor/tools/pdfTextEditor/model/Page";
import type { PageRect, RGBA } from "@editor/tools/pdfTextEditor/types";
+import { uniformTags } from "@editor/tools/pdfTextEditor/model/TextTags";
import { renderLuma } from "@editor/tools/pdfTextEditor/pdfium/BackgroundSampler";
import {
emitFillRect,
@@ -58,7 +59,7 @@ export function spanOf(
fill: BLACK,
originalFontPtr: 0,
fallbackFamily: family,
- tagMarks: [],
+ tags: uniformTags([]),
});
const span = measureObjSpanPt(doc.module, ptrs);
for (const p of ptrs) removeAndDestroyObject(doc.module, page.pagePtr, p);
@@ -163,7 +164,7 @@ export function placeText(
fallbackFamily: p.family,
// The invisible OCR layer carries the run's tags; tagging this visible
// copy as well would have assistive technology read the words twice.
- tagMarks: [],
+ tags: uniformTags([]),
// Fill and stroke (Tr 2): blur makes scanned strokes heavier than any bold.
...(p.weight
? { renderMode: 2, stroke: p.fill, strokeWidth: p.weight }
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/commands/scanTextEdit.ts b/frontend/src/editor/core/tools/pdfTextEditor/commands/scanTextEdit.ts
index bc5a65c932..862c7d6b78 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/commands/scanTextEdit.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/commands/scanTextEdit.ts
@@ -17,6 +17,7 @@ import {
} from "@editor/tools/pdfTextEditor/commands/scanLayout";
import { createBitmapImageObject } from "@editor/utils/pdfiumBitmapUtils";
import type { TagMark } from "@editor/tools/pdfTextEditor/pdfium/PdfiumTagMarks";
+import { uniformTags } from "@editor/tools/pdfTextEditor/model/TextTags";
import {
emitFillRect,
emitTextLine,
@@ -610,7 +611,7 @@ function emitInvisible(
originalFontPtr: state.fontPtr,
fallbackFamily: "Helvetica",
renderMode: INVISIBLE,
- tagMarks,
+ tags: uniformTags(tagMarks),
});
opaqueStroke(doc.module, ptrs);
return ptrs;
@@ -799,7 +800,7 @@ export function renderScanEdit(
originalFontPtr: 0,
fallbackFamily: st.family,
renderMode: INVISIBLE,
- tagMarks: run.tagMarks,
+ tags: uniformTags(run.tagMarks),
});
opaqueStroke(m, hidden);
state.created.push(soft, ...hidden);
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/commands/splitByBlock.ts b/frontend/src/editor/core/tools/pdfTextEditor/commands/splitByBlock.ts
new file mode 100644
index 0000000000..00ab6b364b
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/commands/splitByBlock.ts
@@ -0,0 +1,42 @@
+import { collectMemberPtrs } from "@editor/tools/pdfTextEditor/commands/editTextHelpers";
+import type { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
+import type { Page } from "@editor/tools/pdfTextEditor/model/Page";
+import type { TextRun } from "@editor/tools/pdfTextEditor/model/TextRun";
+import { PdfiumTextReader } from "@editor/tools/pdfTextEditor/pdfium/PdfiumTextReader";
+
+/**
+ * Replace `run` with a run for each structure block its text belongs to,
+ * grouped as a page read groups it. A text edit redraws a run under one tag,
+ * so a block left inside another's run loses its text on the next edit.
+ */
+export function splitByBlock(
+ doc: EditorDocument,
+ page: Page,
+ run: TextRun,
+ undo: Array<() => void>,
+): TextRun[] {
+ const m = doc.module;
+ const ptrs = collectMemberPtrs(run);
+ const onPage = new Set(
+ Array.from({ length: m.FPDFPage_CountObjects(page.pagePtr) }, (_, i) =>
+ m.FPDFPage_GetObject(page.pagePtr, i),
+ ),
+ );
+ if (ptrs.some((ptr) => !onPage.has(ptr))) {
+ throw new Error("Only text drawn on the page itself can be split");
+ }
+ // Only auto mode groups lines into one run.
+ const mode = run.paragraphLineSlots.length > 1 ? "auto" : "line";
+ const parts = PdfiumTextReader.readRuns(
+ doc,
+ page,
+ ptrs.map((ptr, i) => ({ ptr, id: `${run.id}-part${i}` })),
+ mode,
+ );
+ if (parts.length <= 1) return [run];
+ const runs = page.runs;
+ const at = runs.indexOf(run);
+ page.setRuns([...runs.slice(0, at), ...parts, ...runs.slice(at + 1)]);
+ undo.push(() => page.setRuns(runs));
+ return parts;
+}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/commands/textPieces.ts b/frontend/src/editor/core/tools/pdfTextEditor/commands/textPieces.ts
index ef8524c4f4..81b4d5f1d5 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/commands/textPieces.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/commands/textPieces.ts
@@ -6,6 +6,7 @@
*/
import type { WrappedPdfiumModule } from "@embedpdf/pdfium";
import { writeUtf16 } from "@editor/services/pdfiumService";
+import { removeAndDestroyObject } from "@editor/tools/pdfTextEditor/commands/editTextHelpers";
import type { Page } from "@editor/tools/pdfTextEditor/model/Page";
import type { RGBA } from "@editor/tools/pdfTextEditor/types";
import {
@@ -23,6 +24,11 @@ import {
const FPDF_PAGEOBJ_TEXT = 1;
+/** A glyph further than this from where its source drew it starts an object of its own. */
+const SPLIT_AT_PT = 0.01;
+/** A piece that cannot be drawn with every glyph this close to its source's is refused. */
+const REFUSE_AT_PT = 0.1;
+
/** How a text object draws its text, read before it is changed. */
export interface TextSource {
font: number;
@@ -66,60 +72,124 @@ export function readTextSource(
}
/**
- * Where each character starting at the wanted code units of each object's
- * text is drawn, in page space. An object is left out when the text page's
- * characters for it do not tile `lengths` code units, so none of its
- * positions can be trusted.
+ * Where each object draws each character of its text, by the code unit it
+ * starts at, in page space. The text page's characters for an object are
+ * matched to its text in order, past any space the text page inferred from a
+ * gap rather than read from a glyph, which has no place. An object whose
+ * characters do not spell its text is left out, so none of its places are
+ * trusted.
*/
export function charOrigins(
m: WrappedPdfiumModule,
pagePtr: number,
- wanted: ReadonlyMap<number, ReadonlySet<number>>,
- lengths: ReadonlyMap<number, number>,
+ texts: ReadonlyMap<number, string>,
): Map<number, Map<number, Point>> {
- const found = new Map<number, Map<number, Point>>();
- const units = new Map<number, number>();
+ const found = new Map<number, Map<number, Point>>(
+ [...texts.keys()].map((ptr) => [ptr, new Map()]),
+ );
+ const read = new Map<number, number>();
const textPage = m.FPDFText_LoadPage(pagePtr);
- if (!textPage) return found;
+ if (!textPage) return new Map();
try {
const xPtr = scratchPtr(m, SCRATCH.splitOriginX, 8);
const yPtr = scratchPtr(m, SCRATCH.splitOriginY, 8);
const count = m.FPDFText_CountChars(textPage);
for (let i = 0; i < count; i++) {
const objPtr = m.FPDFText_GetTextObject(textPage, i);
- const offsets = wanted.get(objPtr);
- if (!offsets || m.FPDFText_IsGenerated(textPage, i) === 1) continue;
- const at = units.get(objPtr) ?? 0;
- if (
- offsets.has(at) &&
- m.FPDFText_GetCharOrigin(textPage, i, xPtr, yPtr)
- ) {
- const origins = found.get(objPtr) ?? new Map<number, Point>();
+ const text = texts.get(objPtr);
+ const origins = found.get(objPtr);
+ if (text === undefined || !origins) continue;
+ if (m.FPDFText_IsGenerated(textPage, i) === 1) continue;
+ const char = String.fromCodePoint(m.FPDFText_GetUnicode(textPage, i));
+ const at = nextMatch(text, read.get(objPtr) ?? 0, char);
+ if (at === null) {
+ found.delete(objPtr);
+ continue;
+ }
+ if (m.FPDFText_GetCharOrigin(textPage, i, xPtr, yPtr)) {
origins.set(at, {
x: m.pdfium.getValue(xPtr, "double"),
y: m.pdfium.getValue(yPtr, "double"),
});
- found.set(objPtr, origins);
}
- units.set(
- objPtr,
- at + (m.FPDFText_GetUnicode(textPage, i) > 0xffff ? 2 : 1),
- );
+ read.set(objPtr, at + char.length);
}
} finally {
m.FPDFText_ClosePage(textPage);
}
- for (const objPtr of [...found.keys()]) {
- if (units.get(objPtr) !== lengths.get(objPtr)) found.delete(objPtr);
+ for (const [ptr, text] of texts) {
+ if (/\S/.test(text.slice(read.get(ptr) ?? 0))) found.delete(ptr);
}
return found;
}
+/** Where `char` comes next in `text` from code unit `at`, past spaces; null when it does not. */
+function nextMatch(text: string, at: number, char: string): number | null {
+ let unit = at;
+ while (!text.startsWith(char, unit) && /\s/.test(text[unit] ?? "")) unit++;
+ return text.startsWith(char, unit) ? unit : null;
+}
+
+/** The code units at which each character of `text` starts. */
+export function charStarts(text: string): number[] {
+ const starts: number[] = [];
+ for (let at = 0; at < text.length;) {
+ starts.push(at);
+ at += text.codePointAt(at)! > 0xffff ? 2 : 1;
+ }
+ return starts;
+}
+
+/** Where each character from code unit `from` to `to` of `text` that draws ink starts. */
+export function inkStarts(text: string, from: number, to: number): number[] {
+ return charStarts(text).filter(
+ (at) =>
+ at >= from &&
+ at < to &&
+ /\S/u.test(String.fromCodePoint(text.codePointAt(at)!)),
+ );
+}
+
+/**
+ * The characters from code unit `from` to `to` of a source's `text` that its
+ * glyphs drew, given where it drew them: what redrawing them draws. A space
+ * the text page inferred from a gap is left to the gap, as the source left it,
+ * and a subset font may have no glyph to draw it with.
+ */
+export function glyphText(
+ text: string,
+ origins: ReadonlyMap<number, Point>,
+ from: number,
+ to: number,
+): string {
+ return charStarts(text)
+ .filter((at) => at >= from && at < to && origins.has(at))
+ .map((at) => String.fromCodePoint(text.codePointAt(at)!))
+ .join("");
+}
+
+/**
+ * Where to start drawing a piece of `text` from code unit `from`: the
+ * source's place for the first character from there that a glyph drew, or
+ * failing that the last before it. A piece needing the second is only spaces
+ * no glyph drew, so where it lands cannot show. Null when no glyph drew any of
+ * `text`.
+ */
+export function pieceOrigin(
+ origins: ReadonlyMap<number, Point>,
+ text: string,
+ from: number,
+): Point | null {
+ const starts = charStarts(text).filter((at) => origins.has(at));
+ const at = starts.find((start) => start >= from) ?? starts.at(-1);
+ return at === undefined ? null : origins.get(at)!;
+}
+
/**
* Draw `text` as `source` draws its own, starting at `origin`, as a new
- * object last on the page carrying `tags`. Re-encoded through the font, so
- * any kerning or character spacing the source applied is lost. Returns 0
- * when PDFium cannot create it.
+ * object carrying `tags`, at page object `index` or last on the page.
+ * Re-encoded through the font, so any kerning or character spacing the
+ * source applied is lost. Returns 0 when PDFium cannot create it.
*/
export function addTextPiece(
m: WrappedPdfiumModule,
@@ -129,6 +199,7 @@ export function addTextPiece(
text: string,
origin: Point,
tags: readonly TagMark[],
+ index?: number,
): number {
const ptr = m.FPDFPageObj_CreateTextObj(docPtr, source.font, source.size);
if (!ptr) return 0;
@@ -150,10 +221,168 @@ export function addTextPiece(
}
m.FPDFTextObj_SetTextRenderMode(ptr, source.renderMode);
for (const tag of tags) addTagMark(m, docPtr, ptr, tag);
- m.FPDFPage_InsertObject(page.pagePtr, ptr);
+ if (index === undefined) m.FPDFPage_InsertObject(page.pagePtr, ptr);
+ else m.FPDFPage_InsertObjectAtIndex(page.pagePtr, ptr, index);
return ptr;
}
+/** An object drawing code units `from` to `to` of a source object's text. */
+export interface Placed {
+ ptr: number;
+ from: number;
+ to: number;
+}
+
+/** A piece of a source object's text, drawn so far by object `ptr` alone. */
+export interface Placing extends Placed {
+ /** The source object's whole text. */
+ text: string;
+ source: TextSource;
+ /** Where the source drew each character of `text`, as `charOrigins` reads it. */
+ origins: ReadonlyMap<number, Point>;
+ tags: readonly TagMark[];
+ /** Drawn by a new object, which lays its text out with no spacing of its own. */
+ fresh: boolean;
+}
+
+/**
+ * Split each piece's object wherever PDFium lays a glyph out elsewhere than
+ * the source drew it, each new part a new object starting exactly there and
+ * drawn right after the part before it. Undoing pushes onto `undo`. Returns
+ * the objects drawing each piece, in order. Throws when a glyph still lands
+ * further than REFUSE_AT_PT from where the source drew it.
+ */
+export function placeGlyphs(
+ m: WrappedPdfiumModule,
+ docPtr: number,
+ page: Page,
+ pieces: readonly Placing[],
+ undo: Array<() => void>,
+): Placed[][] {
+ const placed = pieces.map(({ ptr, from, to }) => [{ ptr, from, to }]);
+ let pending = pieces.map((piece, i) => ({
+ piece,
+ parts: placed[i],
+ head: placed[i][0],
+ fresh: piece.fresh,
+ }));
+ while (pending.length > 0) {
+ const drawn = drawnOrigins(
+ m,
+ page.pagePtr,
+ pending.map(({ piece, head }) => ({ piece, part: head })),
+ );
+ const next: typeof pending = [];
+ for (const { piece, parts, head, fresh } of pending) {
+ const breaks = misplaced(piece, head, drawn.get(head.ptr)!);
+ // Past its first break, an object keeping the source's spacing goes on
+ // as a new object, which lays out without it, so is measured afresh.
+ const cuts = fresh ? breaks : breaks.slice(0, 1);
+ if (cuts.length === 0) continue;
+ const kept = glyphText(piece.text, piece.origins, head.from, cuts[0]);
+ if (!setPieceText(m, head.ptr, kept, null)) {
+ throw new Error("PDFium could not redraw the text");
+ }
+ let index = pageObjectIndex(m, page, head.ptr);
+ const ends = [...cuts.slice(1), head.to];
+ const added = cuts.map((from, i) => {
+ const ptr = addTextPiece(
+ m,
+ docPtr,
+ page,
+ piece.source,
+ glyphText(piece.text, piece.origins, from, ends[i]),
+ piece.origins.get(from)!,
+ piece.tags,
+ ++index,
+ );
+ if (!ptr) throw new Error("PDFium could not draw the text");
+ undo.push(() => removeAndDestroyObject(m, page.pagePtr, ptr));
+ return { ptr, from, to: ends[i] };
+ });
+ head.to = cuts[0];
+ parts.splice(parts.indexOf(head) + 1, 0, ...added);
+ if (!fresh) next.push({ piece, parts, head: added[0], fresh: true });
+ }
+ pending = next;
+ }
+ verifyPlaced(m, page, pieces, placed);
+ return placed;
+}
+
+/**
+ * The glyphs of `head` that need an object of their own: each landing
+ * further than SPLIT_AT_PT from where the source drew it, once every glyph
+ * before it is drawn where the source drew it.
+ */
+function misplaced(
+ piece: Placing,
+ head: Placed,
+ drawn: ReadonlyMap<number, Point>,
+): number[] {
+ const breaks: number[] = [];
+ let shift: Point = { x: 0, y: 0 };
+ for (const at of inkStarts(piece.text, head.from, head.to)) {
+ const got = drawn.get(at - head.from)!;
+ const want = piece.origins.get(at)!;
+ const off = Math.hypot(got.x + shift.x - want.x, got.y + shift.y - want.y);
+ if (at > head.from && off > SPLIT_AT_PT) {
+ breaks.push(at);
+ shift = { x: want.x - got.x, y: want.y - got.y };
+ }
+ }
+ return breaks;
+}
+
+function verifyPlaced(
+ m: WrappedPdfiumModule,
+ page: Page,
+ pieces: readonly Placing[],
+ placed: readonly Placed[][],
+): void {
+ const parts = pieces.flatMap((piece, i) =>
+ placed[i].map((part) => ({ piece, part })),
+ );
+ const drawn = drawnOrigins(m, page.pagePtr, parts);
+ for (const { piece, part } of parts) {
+ for (const at of inkStarts(piece.text, part.from, part.to)) {
+ const got = drawn.get(part.ptr)!.get(at - part.from)!;
+ const want = piece.origins.get(at)!;
+ if (Math.hypot(got.x - want.x, got.y - want.y) > REFUSE_AT_PT) {
+ throw new Error("PDFium cannot draw the text where it was drawn");
+ }
+ }
+ }
+}
+
+/**
+ * Where each part's object draws its glyphs, by code unit of the part's
+ * text. Throws when the text page cannot place every one.
+ */
+function drawnOrigins(
+ m: WrappedPdfiumModule,
+ pagePtr: number,
+ parts: ReadonlyArray<{ piece: Placing; part: Placed }>,
+): Map<number, Map<number, Point>> {
+ const texts = new Map(
+ parts.map(({ piece, part }) => [
+ part.ptr,
+ piece.text.slice(part.from, part.to),
+ ]),
+ );
+ const found = charOrigins(m, pagePtr, texts);
+ for (const [ptr, text] of texts) {
+ const drawn = found.get(ptr);
+ if (
+ !drawn ||
+ inkStarts(text, 0, text.length).some((at) => !drawn.has(at))
+ ) {
+ throw new Error("PDFium cannot place a piece of the text");
+ }
+ }
+ return found;
+}
+
/** Give an existing object `text`, starting at `origin`: its own when null. */
export function setPieceText(
m: WrappedPdfiumModule,
@@ -211,3 +440,15 @@ function setText(m: WrappedPdfiumModule, objPtr: number, text: string) {
m.pdfium.wasmExports.free(buf);
}
}
+
+function pageObjectIndex(
+ m: WrappedPdfiumModule,
+ page: Page,
+ ptr: number,
+): number {
+ const count = m.FPDFPage_CountObjects(page.pagePtr);
+ for (let i = 0; i < count; i++) {
+ if (m.FPDFPage_GetObject(page.pagePtr, i) === ptr) return i;
+ }
+ throw new Error("The text is not on the page");
+}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/hooks/useTextAccessibility.ts b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useTextAccessibility.ts
index e3b1fea382..04cfecc361 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/hooks/useTextAccessibility.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useTextAccessibility.ts
@@ -150,14 +150,14 @@ export function useTextAccessibility(
(index: number, type: StructureType | null) => {
const picked = inner[index];
if (!run || !picked) return;
- store.dispatch(
- new RetagInnerCommand({
- pageIndex: run.pageIndex,
- key: picked.key,
- type,
- }),
- );
- if (type === null) store.selection.setTextRange(run.id, null);
+ const retag = new RetagInnerCommand({
+ pageIndex: run.pageIndex,
+ key: picked.key,
+ type,
+ });
+ store.dispatch(retag);
+ if (retag.movedToRunId) store.selection.selectOne(retag.movedToRunId);
+ else if (type === null) store.selection.setTextRange(run.id, null);
},
[store, run, inner],
);
@@ -167,16 +167,19 @@ export function useTextAccessibility(
(type: StructureType) => {
const range = selection.textRange;
if (!run || !range) return;
- store.dispatch(
- new TagTextRangeCommand({
- pageIndex: run.pageIndex,
- runId: run.id,
- ...range,
- as: type,
- }),
- );
- // The cut redraws the text, so the range no longer names what it did.
- store.selection.setTextRange(run.id, null);
+ const cut = new TagTextRangeCommand({
+ pageIndex: run.pageIndex,
+ runId: run.id,
+ ...range,
+ as: type,
+ });
+ store.dispatch(cut);
+ if (cut.movedToRunId) {
+ store.selection.selectOne(cut.movedToRunId);
+ } else {
+ // The cut redraws the text, so the range no longer names what it did.
+ store.selection.setTextRange(run.id, null);
+ }
},
[store, run, selection.textRange],
);
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/model/TextTags.ts b/frontend/src/editor/core/tools/pdfTextEditor/model/TextTags.ts
new file mode 100644
index 0000000000..96e05ad125
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/model/TextTags.ts
@@ -0,0 +1,106 @@
+import type { TagMark } from "@editor/tools/pdfTextEditor/pdfium/PdfiumTagMarks";
+
+/**
+ * The tags each code unit of a text is drawn with, as stretches in order:
+ * each runs from the previous one's end to its own. The last may end at
+ * Infinity, giving its tags to every code unit after; a code unit past the
+ * last stretch has none.
+ */
+export type TextTags = readonly TagStretch[];
+
+export interface TagStretch {
+ end: number;
+ tags: readonly TagMark[];
+}
+
+/** A stretch of a text whose code units all have the same tags. */
+export interface TaggedSpan {
+ start: number;
+ end: number;
+ tags: readonly TagMark[];
+}
+
+export function uniformTags(tags: readonly TagMark[]): TextTags {
+ return [{ end: Infinity, tags }];
+}
+
+export function tagsAt(text: TextTags, at: number): readonly TagMark[] {
+ return text.find((stretch) => stretch.end > at)?.tags ?? [];
+}
+
+/** Code units `start` to `end` of `text`, numbered from `start`. */
+export function sliceTags(
+ text: TextTags,
+ start: number,
+ end: number,
+): TextTags {
+ const out: TagStretch[] = [];
+ for (const stretch of text) {
+ if (stretch.end <= start) continue;
+ out.push({ end: Math.min(stretch.end, end) - start, tags: stretch.tags });
+ if (stretch.end >= end) break;
+ }
+ return out;
+}
+
+/** `tail`'s stretches numbered from `offset`, after `head`'s. */
+export function joinTags(
+ head: TextTags,
+ offset: number,
+ tail: TextTags,
+): TextTags {
+ return [
+ ...sliceTags(head, 0, offset),
+ ...tail.map(({ end, tags }) => ({ end: end + offset, tags })),
+ ];
+}
+
+/** The first `length` code units of `text` as spans, neighbours with the same tags joined. */
+export function taggedSpans(text: TextTags, length: number): TaggedSpan[] {
+ const out: TaggedSpan[] = [];
+ let start = 0;
+ for (const { end: stretchEnd, tags } of [
+ ...text,
+ { end: Infinity, tags: [] },
+ ]) {
+ const end = Math.min(stretchEnd, length);
+ if (end <= start) continue;
+ const last = out.at(-1);
+ if (last && sameTags(last.tags, tags)) last.end = end;
+ else out.push({ start, end, tags });
+ start = end;
+ if (start >= length) break;
+ }
+ return out;
+}
+
+/** `text` split at its line breaks, each line with its tags. */
+export function splitLines(
+ text: string,
+ tags: TextTags,
+): Array<{ text: string; tags: TextTags }> {
+ const lines: Array<{ text: string; tags: TextTags }> = [];
+ let start = 0;
+ for (const lineBreak of text.matchAll(/\r?\n/g)) {
+ lines.push({
+ text: text.slice(start, lineBreak.index),
+ tags: sliceTags(tags, start, lineBreak.index),
+ });
+ start = lineBreak.index + lineBreak[0].length;
+ }
+ lines.push({
+ text: text.slice(start),
+ tags: sliceTags(tags, start, Infinity),
+ });
+ return lines;
+}
+
+export function sameTags(
+ a: readonly TagMark[],
+ b: readonly TagMark[],
+): boolean {
+ return (
+ a.length === b.length &&
+ a.every((mark, i) => mark.name === b[i].name && mark.mcid === b[i].mcid)
+ );
+}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/pdfium/LineGrouper.ts b/frontend/src/editor/core/tools/pdfTextEditor/pdfium/LineGrouper.ts
index 4ea1d415be..f03babfc09 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/pdfium/LineGrouper.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/pdfium/LineGrouper.ts
@@ -30,8 +30,22 @@ const MAX_SPACE_UNIT_RATIO = 1;
const MULTI_SPACE_UNITS = 1.7;
function junctionGapRatio(prev: TextRun, cur: TextRun): number {
- const fontSize = Math.max(prev.fontSize, 4);
- return (cur.bounds.x - (prev.bounds.x + prev.bounds.width)) / fontSize;
+ return gapRatio(
+ cur.bounds.x - (prev.bounds.x + prev.bounds.width),
+ prev.fontSize,
+ );
+}
+
+function gapRatio(gapPt: number, fontSize: number): number {
+ return gapPt / Math.max(fontSize, 4);
+}
+
+/**
+ * Whether a line read puts a space between two objects on a line `gapPt`
+ * apart, the gap between their bounds, the first drawn at `fontSize` points.
+ */
+export function readsWordGap(gapPt: number, fontSize: number): boolean {
+ return gapRatio(gapPt, fontSize) > WORD_GAP_MIN_RATIO;
}
function lineSpaceUnitRatio(members: TextRun[]): number {
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/pdfium/PdfiumTextReader.ts b/frontend/src/editor/core/tools/pdfTextEditor/pdfium/PdfiumTextReader.ts
index 372d16061b..e0f4bd4528 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/pdfium/PdfiumTextReader.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/pdfium/PdfiumTextReader.ts
@@ -2,7 +2,7 @@ import type { WrappedPdfiumModule } from "@embedpdf/pdfium";
import { TextRun } from "@editor/tools/pdfTextEditor/model/TextRun";
import { ImageObject } from "@editor/tools/pdfTextEditor/model/ImageObject";
import { ShapeObject } from "@editor/tools/pdfTextEditor/model/ShapeObject";
-import type { Page } from "@editor/tools/pdfTextEditor/model/Page";
+import { Page } from "@editor/tools/pdfTextEditor/model/Page";
import type { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
import type { PageStructure } from "@editor/tools/pdfTextEditor/model/PageStructure";
import {
@@ -100,25 +100,51 @@ export class PdfiumTextReader {
// Annotation text is drawn by FPDF_ANNOT but lives outside the object
// tree, so record the boxes to explain why it can't be edited.
PdfiumAnnotationReader.populate(m, page);
- // LineGrouper always runs (merges per-glyph/per-word source objects into
- // one line).
- const blockKey = structureBlockKey(doc, page.index);
- LineGrouper.apply(page, blockKey);
- if (mode === "auto") ParagraphGrouper.apply(page, blockKey);
- // Grouping is done.
- // One walk feeds both: each was reading the same characters with its
- // own WASM round-trips, doubling the cost of every page read.
- const geometry = collectCharGeometry(m, page, textPagePtr);
- if (geometry) {
- inferRunCharSpacing(page, geometry);
- captureCharPositions(geometry);
- }
+ groupAndMeasure(doc, page, mode, textPagePtr);
} finally {
m.FPDFText_ClosePage(textPagePtr);
}
page.loaded = true;
}
+ /**
+ * Read page-level text objects as `populate` reads a page's, grouping them
+ * only with each other. A run is named by the id given its first object
+ * in reading order. Each object's own marks become its tags, so none may
+ * be inside a form XObject.
+ */
+ static readRuns(
+ doc: EditorDocument,
+ page: Page,
+ objects: ReadonlyArray<{ ptr: number; id: string }>,
+ mode: GroupingMode,
+ ): TextRun[] {
+ const m = doc.module;
+ // Grouping replaces a page's runs, so it works on a scratch page.
+ const scratch = new Page({
+ index: page.index,
+ pagePtr: page.pagePtr,
+ width: page.width,
+ height: page.height,
+ display: page.display,
+ });
+ const textPagePtr = m.FPDFText_LoadPage(page.pagePtr);
+ try {
+ scratch.setRuns(
+ objects.flatMap(({ ptr, id }) => {
+ const run = readTextRun(m, doc, page, ptr, id, IDENTITY, textPagePtr);
+ if (!run) return [];
+ run.tagMarks = readTagMarks(m, ptr);
+ return [run];
+ }),
+ );
+ groupAndMeasure(doc, scratch, mode, textPagePtr);
+ } finally {
+ m.FPDFText_ClosePage(textPagePtr);
+ }
+ return scratch.runs;
+ }
+
// Returns the runs whose captured positions actually moved, so the caller
// can re-snapshot just those instead of re-rendering every overlay per tick.
static recapturePositions(doc: EditorDocument, page: Page): Set<TextRun> {
@@ -138,6 +164,30 @@ export class PdfiumTextReader {
}
}
+/**
+ * Group the page's one-object runs into lines, and in auto mode paragraphs,
+ * then place their glyphs.
+ */
+function groupAndMeasure(
+ doc: EditorDocument,
+ page: Page,
+ mode: GroupingMode,
+ textPagePtr: number,
+): void {
+ // LineGrouper always runs (merges per-glyph/per-word source objects into
+ // one line).
+ const blockKey = structureBlockKey(doc, page.index);
+ LineGrouper.apply(page, blockKey);
+ if (mode === "auto") ParagraphGrouper.apply(page, blockKey);
+ // One walk feeds both: each was reading the same characters with its
+ // own WASM round-trips, doubling the cost of every page read.
+ const geometry = collectCharGeometry(doc.module, page, textPagePtr);
+ if (geometry) {
+ inferRunCharSpacing(page, geometry);
+ captureCharPositions(geometry);
+ }
+}
+
/** Every backing PDFium object pointer mapped to its post-grouping run. */
function indexRunsByObjectPtr(runs: TextRun[]): Map<number, TextRun> {
const map = new Map<number, TextRun>();
@@ -425,7 +475,7 @@ function walkObjects(
doc,
page,
objPtr,
- indexId,
+ `p${page.index}-t${indexId}`,
transform,
textPagePtr,
);
@@ -876,7 +926,7 @@ function readTextRun(
_doc: EditorDocument,
page: Page,
objPtr: number,
- index: number | string,
+ id: string,
transform: Affine,
textPagePtr: number,
): TextRun | null {
@@ -916,7 +966,7 @@ function readTextRun(
// Make the same face available to the overlay as a CSS FontFace.
if (fontPtr) registerEmbeddedFace(m, fontPtr);
// Treat the PDFium font handle pointer as a unique id within the doc.
- const fontId = fontPtr ? `pdf:${fontPtr}` : `pdf:unknown-${index}`;
+ const fontId = fontPtr ? `pdf:${fontPtr}` : `pdf:unknown-${id}`;
// Text render mode (PDF Tr): 0 fill (default), 1/2 stroke variants, 3
// invisible (OCR text layers over scans), 4-7 clipping variants.
@@ -938,7 +988,7 @@ function readTextRun(
const { stroke, strokeWidth } = readStroke(m, objPtr, renderMode);
return new TextRun({
- id: `p${page.index}-t${index}`,
+ id,
pageIndex: page.index,
pdfiumObjPtr: objPtr,
bounds,