Skip to content

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

Improve PDF text editor fidelity: fonts, typing, undo, scans, images and tables (#8906)

Anthony Stirlingf5864deacd74
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/service/ua/PdfUaRealCorpusTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/service/ua/PdfUaRealCorpusTest.java
index eb4744785c..d74371bfc3 100644
--- a/app/proprietary/src/test/java/stirling/software/proprietary/service/ua/PdfUaRealCorpusTest.java
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/service/ua/PdfUaRealCorpusTest.java
@@ -2,13 +2,18 @@ package stirling.software.proprietary.service.ua;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.Mockito.mock;
+import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Comparator;
+import java.util.HashMap;
import java.util.List;
+import java.util.Map;
+import java.util.TreeMap;
import java.util.stream.Stream;
import org.apache.pdfbox.Loader;
@@ -41,6 +46,22 @@ class PdfUaRealCorpusTest {
// caught by FontEmbeddingService, which keeps the original instead.
private static final List<String> KNOWN_EMBED_TEXT_DIFFS = List.of("rotated-text-sample.pdf");
+ // Files whose tagged output PDFBox reads back differently from the original, pinned to the
+ // exact text it reads so that any other change still fails. Vowel marks and brackets drawn as
+ // objects of their own in visual order come back in reading order once marked content groups
+ // them; a Devanagari vowel sign drawn ahead of its consonant under an ActualText span comes
+ // back as U+0000.
+ private static final Map<String, String> KNOWN_TAGGED_TEXT =
+ Map.of(
+ "rtl-marks-sample.pdf",
+ "שָׁלוֹם עוֹלָם يوُلدَُ جَمِيعُ النَّاسِ",
+ "rtl-mixed-sample.pdf",
+ "ISO 50001 بلغ الاستهلاك (في الربع) 12,450.75 كيلوواط [بزيادة 3.5%] حسب تقرير استخدم برنامج LibreOffice Writer أو Word لفتح report-2026.docx الآن. הטלפון הוא 03-555-1234 (שלוחה 12), והמחיר 1,299.90 לפי Open Source סעיף 4. An English line quoting مرحبا بالعالم and שלום עולם then 1,234. ISO 50001 هو المعيار",
+ "shaped-line-sample.pdf",
+ "नमस्ते दु\u0000नया, 2024.",
+ "thai-line-sample.pdf",
+ "มนุษยท\u0000 ง้ั หลายเกดิมามีอสิระ");
+
@BeforeAll
static void setUp() {
PdfUaValidationService validation = new PdfUaValidationService();
@@ -49,8 +70,7 @@ class PdfUaRealCorpusTest {
new PdfUaConversionService(
validation,
new FontEmbeddingService(),
- new CustomPDFDocumentFactory(
- org.mockito.Mockito.mock(PdfMetadataService.class)));
+ new CustomPDFDocumentFactory(mock(PdfMetadataService.class)));
repoRoot = findRepoRoot();
}
@@ -81,9 +101,9 @@ class PdfUaRealCorpusTest {
List<Outcome> outcomes = new ArrayList<>();
List<String> crashes = new ArrayList<>();
- java.util.Map<String, Integer> clauseFiles = new java.util.TreeMap<>();
- java.util.Map<String, String> clauseText = new java.util.HashMap<>();
- java.util.Map<String, String> clauseExamples = new java.util.HashMap<>();
+ Map<String, Integer> clauseFiles = new TreeMap<>();
+ Map<String, String> clauseText = new HashMap<>();
+ Map<String, String> clauseExamples = new HashMap<>();
for (Path pdf : pdfs) {
String name = repoRoot.relativize(pdf).toString().replace('\\', '/');
@@ -137,7 +157,7 @@ class PdfUaRealCorpusTest {
StringBuilder clauses =
new StringBuilder("\nBlocking clauses, by number of files affected\n");
clauseFiles.entrySet().stream()
- .sorted(java.util.Map.Entry.<String, Integer>comparingByValue().reversed())
+ .sorted(Map.Entry.<String, Integer>comparingByValue().reversed())
.forEach(
e ->
clauses.append(
@@ -168,13 +188,20 @@ class PdfUaRealCorpusTest {
String textAfter = safeExtract(after);
assertTrue(
textAfter != null, "the converted file could not be read back at all for " + name);
+ String expected =
+ KNOWN_TAGGED_TEXT.entrySet().stream()
+ .filter(known -> name.contains(known.getKey()))
+ .map(Map.Entry::getValue)
+ .findFirst()
+ .orElse(textBefore);
+ boolean preserved = expected.equals(textAfter);
assertTrue(
- textBefore.equals(textAfter),
+ preserved,
"tagging changed extracted text for "
+ name
- + "\n before: "
- + preview(textBefore)
- + "\n after: "
+ + "\n expected: "
+ + preview(expected)
+ + "\n after: "
+ preview(textAfter));
}
@@ -225,11 +252,11 @@ class PdfUaRealCorpusTest {
}
}
- private static final String File_BUILD = "build" + java.io.File.separator;
+ private static final String File_BUILD = "build" + File.separator;
// Playwright output, gitignored: leaving it in makes the corpus depend on
// what a local test run happened to leave behind.
- private static final String File_TEST_RESULTS = "test-results" + java.io.File.separator;
+ private static final String File_TEST_RESULTS = "test-results" + File.separator;
private static String render(List<Outcome> outcomes) {
StringBuilder sb = new StringBuilder("\nPDF/UA conversion over the repository corpus\n");
diff --git a/frontend/public/locales/en-US/translation.toml b/frontend/public/locales/en-US/translation.toml
index 6c5dce0b65..32bd186896 100644
--- a/frontend/public/locales/en-US/translation.toml
+++ b/frontend/public/locales/en-US/translation.toml
@@ -7633,8 +7633,13 @@ title = "Discard unsaved changes?"
[pdfTextEditor.error]
decodeImage = "Could not decode the selected image."
+duplicateDropsLetters = "Can't duplicate this text: no available font draws all of its letters."
+formLiftChangesDrawing = "Can't edit this: it is drawn as part of a group whose clipping or graphics settings the editor can't keep when it is changed."
insertImage = "Could not insert the selected image."
+needsShaping = "The editor can't yet draw this script's joined letters and vowel signs correctly, so this change was not made."
+replaceClippedImage = "Can't replace this image: it is cropped, and the replacement would show the parts the crop hides."
scanOffInk = "Can't edit this text: its recognised words don't line up with the scan. Run OCR again."
+unsafeRtlEdit = "Can't make this edit: the editor can't redraw this line's right-to-left text without changing it."
[pdfTextEditor.externalEdit]
pngFileType = "PNG image"
@@ -7656,23 +7661,42 @@ wholeWord = "Whole word"
[pdfTextEditor.fontPicker]
builtInGroup = "Built-in fonts"
+closestMatch = "This font is missing some of the selected letters, so they are drawn in the closest matching font."
deviceFontsNone = "No extra device fonts were found."
deviceFontsUnavailable = "Device fonts are unavailable. The built-in fonts still work."
deviceGroup = "Device fonts"
+documentFontCannotDraw = "The editor can't draw this text in the document's own font, so it was left in its current font."
documentGroup = "Document font"
embeddingForbidden = "This font's licence does not allow embedding it in a PDF. The text was left unchanged."
embedFailed = "This font could not be embedded in the PDF. The text was left unchanged."
includedGroup = "Included fonts"
label = "Font family"
matchedGroup = "Matched font"
+missingGlyphs = "This font is missing some of the selected characters, and they could not be kept in their current font. The text was left unchanged."
mixed = "Mixed"
+needsShaping = "The editor can't yet redraw this script's joined letters and vowel signs correctly, so that text was left in its current font."
noGlyphs = "This font has no characters for the selected text. The text was left unchanged."
noMatch = "No matching font"
+partOfRunUnsupported = "This text can only be restyled as a whole. Select the box instead of some of its words."
placeholder = "Font family"
scannedText = "Scanned text"
serverFontFailed = "That server font could not be downloaded. The text was left unchanged."
serverGroup = "Server fonts"
+someLeftUnchanged = "This font does not have the characters for some of the selected text. That text was left unchanged."
+styleSkipped = "Some of the selected text has no version of its font in that style, so it was left unchanged."
+styleUnavailable = "The selected text has no version of its font in that style, so it was left unchanged."
useDeviceFonts = "Use device fonts"
+weight = "Font weight"
+weightBlack = "Black"
+weightBold = "Bold"
+weightExtraBold = "Extra bold"
+weightExtraLight = "Extra light"
+weightLight = "Light"
+weightMedium = "Medium"
+weightNumber = "Weight {{weight}}"
+weightRegular = "Regular"
+weightSemibold = "Semibold"
+weightThin = "Thin"
[pdfTextEditor.fonts]
allPresent = "All letters & numbers present"
@@ -7717,6 +7741,7 @@ helpDesc = "This help"
saveDesc = "Save to your workspace"
[pdfTextEditor.help.editing]
+boldItalicDesc = "Bold / Italic, for the selected words or the whole box"
deleteDesc = "Remove selected"
duplicateDesc = "Duplicate selected"
groupDesc = "Group selected runs into one paragraph"
@@ -7767,6 +7792,8 @@ ocrUnavailable = "OCR is unavailable on this server."
oneImage = "Image"
oneShape = "Shape"
oneText = "Text"
+outlinedTextHint_one = "This page's text is drawn as shapes, so there is no text to edit. Run OCR first to make it editable."
+outlinedTextHint_other = "{{count}} pages have their text drawn as shapes, so there is no text to edit. Run OCR first to make it editable."
pages = "Pages"
runOcr = "Run OCR"
scanHint_one = "This page is a scanned image with no text to edit. Run OCR first to make its text editable."
@@ -7778,6 +7805,7 @@ scannedTextOffInk = "Scanned text · its recognised words sit off the scanned wo
tabDocument = "Document"
tabSelected = "Selected"
textBoxes = "Text boxes"
+unreadPagesHint = "{{count}} pages have no text to edit: some are scanned images and some draw their text as shapes. Run OCR first to make them editable."
width = "Width"
widthHint = "Text re-wraps to fit the width."
x = "X"
@@ -7953,6 +7981,8 @@ vertical = "Vertical ruler"
[pdfTextEditor.run]
lockedTitle = "Locked - use the Unlock button to edit"
+readOnlyOrderTitle = "This line's text can't be edited: it mixes right-to-left and left-to-right text in an order the editor can't redraw safely"
+resizeHandle = "Drag to change the width; the text rewraps"
[pdfTextEditor.saveRisk]
cancel = "Cancel"
@@ -8025,7 +8055,7 @@ ungroup = "Ungroup"
ungroupTooltip = "Split this paragraph into one run per line"
ungroupTooltipDisabled = "Select a multi-line paragraph to ungroup"
widthGrow = "Grow"
-widthGrowHint = "Grow widens a box as you type; Wrap keeps its width and flows onto new lines."
+widthGrowHint = "Grow widens a box as you type until it reaches the page edge, then flows onto new lines; Wrap keeps its width and flows onto new lines."
widthWrap = "Wrap"
[pdfTextEditor.spellcheck]
@@ -8036,13 +8066,14 @@ language = "Dictionary language"
[pdfTextEditor.table]
addColumn = "Add column"
addRow = "Add row"
+cellNoGlyphs = "This text has characters the table's fonts can't draw. Change or remove them to fill the cell."
column = "Col"
deleteColumn = "Delete column"
deleteRow = "Delete row"
done = "Done"
doneHint = "Stop editing this as a table"
-edit = "Edit"
editHint = "Edit as a table - type in cells, add or remove rows and columns"
+editTable = "Edit table"
move = "Move"
moveTable = "Drag to move the whole table"
recognizedHint = "Recognized table - click to select all its text"
@@ -8063,6 +8094,9 @@ alignMiddle = "Align middle"
alignRight = "Align right"
alignTop = "Align top"
arrange = "Arrange"
+bold = "Bold"
+boldOnly = "This font has only a bold version"
+boldUnavailable = "No bold version of this font"
bringForward = "Bring forward"
bringToFront = "Bring to front"
caseLower = "lowercase"
@@ -8083,10 +8117,12 @@ fontColour = "Font colour"
fontSize = "Font size"
formatting = "Text formatting"
italic = "Italic"
+italicOnly = "This font has only an italic version"
italicUnavailable = "This font has no italic version. Load your device fonts or pick another font family."
lock = "Lock selection"
lockTooltip = "Lock selection - prevents accidental edits"
more = "More actions"
+noBoldItalic = "No bold italic version of this font"
order = "Order"
outlineColour = "Outline colour"
outlineWidth = "Outline width (0 = none)"
diff --git a/frontend/src/editor/core/components/shared/FileSidebar.test.tsx b/frontend/src/editor/core/components/shared/FileSidebar.test.tsx
new file mode 100644
index 0000000000..b98916a5d3
--- /dev/null
+++ b/frontend/src/editor/core/components/shared/FileSidebar.test.tsx
@@ -0,0 +1,193 @@
+import { MantineProvider } from "@mantine/core";
+import { act, render, waitFor } from "@testing-library/react";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import FileSidebar from "@editor/components/shared/FileSidebar";
+import type { FileItemProps } from "@editor/components/shared/FileSidebarFileItem";
+import type { FileId } from "@editor/types/file";
+import type { StirlingFileStub } from "@editor/types/fileContext";
+
+const sidebar = vi.hoisted(() => ({
+ library: [] as StirlingFileStub[],
+ revision: 0,
+ rows: [] as FileItemProps[],
+ uploadTarget: null as StirlingFileStub[] | null,
+}));
+
+vi.mock("react-router-dom", async (importOriginal) => ({
+ ...(await importOriginal<object>()),
+ useNavigate: () => () => {},
+}));
+vi.mock("react-i18next", () => ({
+ useTranslation: () => ({
+ t: (key: string, fallback?: string) => fallback ?? key,
+ }),
+}));
+vi.mock("@editor/components/shared/FileSidebarFileItem", () => ({
+ FileItem: (props: FileItemProps) => {
+ sidebar.rows.push(props);
+ return <div data-testid={`row-${props.fileId}`}>{props.name}</div>;
+ },
+}));
+vi.mock("@editor/contexts/IndexedDBContext", () => ({
+ useIndexedDB: () => ({ loadLeafMetadata: async () => sidebar.library }),
+ useIndexedDBRevision: () => sidebar.revision,
+}));
+vi.mock("@editor/contexts/file/fileHooks", () => ({
+ useFileState: () => ({ state: { files: { ids: [], byId: {} } } }),
+ useFileActions: () => ({ actions: {} }),
+}));
+vi.mock("@editor/contexts/AppConfigContext", () => ({
+ useAppConfig: () => ({ config: { storageEnabled: true } }),
+}));
+vi.mock("@editor/hooks/useGoogleDrivePicker", () => ({
+ useGoogleDrivePicker: () => ({ isEnabled: false, openPicker: vi.fn() }),
+}));
+vi.mock("@editor/contexts/NavigationContext", () => ({
+ useNavigationState: () => ({ workbench: "viewer" }),
+ useNavigationActions: () => ({ actions: { setWorkbench: vi.fn() } }),
+ useNavigationGuard: () => ({ requestNavigation: vi.fn() }),
+}));
+vi.mock("@editor/contexts/ViewerContext", () => ({
+ useViewer: () => ({ activeFileId: null, setActiveFileId: vi.fn() }),
+}));
+vi.mock("@editor/hooks/useFileHandler", () => ({
+ useFileHandler: () => ({ addFiles: vi.fn() }),
+}));
+vi.mock("@editor/hooks/useAccountIdentity", () => ({
+ useAccountIdentity: () => ({
+ displayName: "",
+ profilePictureUrl: null,
+ isAnonymous: false,
+ }),
+}));
+vi.mock("@editor/hooks/useFreeCreditsSummary", () => ({
+ useFreeCreditsSummary: () => null,
+}));
+vi.mock("@editor/hooks/useOpenPlan", () => ({ useOpenPlan: () => null }));
+vi.mock("@editor/components/shared/navFooter/NavFooter", () => ({
+ NavFooter: () => null,
+}));
+vi.mock("@editor/components/shared/SidebarHeader", () => ({
+ SidebarHeader: () => null,
+}));
+vi.mock("@editor/data/labelDisplay", () => ({
+ useLabelName: () => (label: string) => label,
+}));
+vi.mock("@editor/hooks/useClassificationEnabled", () => ({
+ useClassificationEnabled: () => false,
+}));
+vi.mock("@editor/components/shared/fileSidebarGrouping", () => ({
+ FileSidebarGroupControls: () => null,
+ useFileSidebarGroups: () => null,
+}));
+vi.mock("@editor/components/shared/BulkUploadToServerModal", () => ({
+ default: (props: { files: StirlingFileStub[] }) => {
+ if (props.files.length > 0) sidebar.uploadTarget = props.files;
+ return null;
+ },
+}));
+vi.mock("@editor/components/filesPage/VersionHistoryModal", () => ({
+ VersionHistoryModal: () => null,
+}));
+vi.mock("@editor/components/filesPage/DeleteFilesDialog", () => ({
+ DeleteFilesDialog: () => null,
+}));
+vi.mock("@editor/components/shared/RenameFileDialog", () => ({
+ RenameFileDialog: () => null,
+}));
+vi.mock("@editor/components/shared/SidebarChecklistSlot", () => ({
+ SidebarChecklistSlot: () => null,
+}));
+vi.mock("@editor/components/chat/SidebarChat", () => ({
+ SidebarChat: () => null,
+}));
+vi.mock("@editor/extensions/openInNewWindow", () => ({
+ useOpenInNewWindow: () => ({
+ canOpenInNewWindow: () => false,
+ openInNewWindow: vi.fn(),
+ }),
+}));
+vi.mock("@editor/hooks/usePolicyFileBadges", () => ({
+ usePolicyFileBadges: () => new Map(),
+}));
+vi.mock("@editor/contexts/ToolFileEligibilityContext", () => ({
+ useToolEligibleFileIds: () => null,
+}));
+vi.mock("@editor/components/layout/useWorkbenchFileDrop", () => ({
+ useWorkbenchFileDrop: () => ({}),
+}));
+vi.mock("@editor/contexts/DamagedFileRepairContext", () => ({
+ useDamagedFileRepair: () => null,
+}));
+vi.mock("@editor/contexts/FilesPageContext", () => ({
+ useFilesPage: () => ({}),
+}));
+vi.mock("@editor/services/bulkAddProgress", () => ({
+ useBulkAddProgress: () => ({ total: 0, done: 0 }),
+}));
+vi.mock("@editor/services/fileStorage", () => ({
+ fileStorage: {},
+ onRecordUnreadable: () => () => {},
+}));
+
+function stub(
+ id: string,
+ name: string,
+ thumbnailUrl: string,
+): StirlingFileStub {
+ return {
+ id: id as FileId,
+ name,
+ size: 1,
+ type: "application/pdf",
+ lastModified: 1,
+ isLeaf: true,
+ originalFileId: id,
+ versionNumber: 1,
+ thumbnailUrl,
+ };
+}
+
+const view = () => (
+ <MantineProvider env="test">
+ <FileSidebar />
+ </MantineProvider>
+);
+
+describe("FileSidebar", () => {
+ beforeEach(() => {
+ sidebar.rows = [];
+ sidebar.uploadTarget = null;
+ sidebar.revision = 0;
+ sidebar.library = [stub("a", "first.pdf", "data:image/png;base64,AAAA")];
+ });
+
+ it("hands file rows the same handlers after the library reloads, acting on the reloaded files", async () => {
+ const { rerender } = render(view());
+ await waitFor(() => expect(sidebar.rows.at(-1)?.name).toBe("first.pdf"));
+ const before = sidebar.rows.at(-1)!;
+
+ sidebar.library = [stub("a", "renamed.pdf", "data:image/png;base64,BBBB")];
+ sidebar.revision = 1;
+ rerender(view());
+ await waitFor(() => expect(sidebar.rows.at(-1)?.name).toBe("renamed.pdf"));
+ const after = sidebar.rows.at(-1)!;
+
+ for (const handler of [
+ "onClick",
+ "onEyeClick",
+ "onDelete",
+ "onDownload",
+ "onRename",
+ "onDuplicate",
+ "onSaveToCloud",
+ "onVersionHistory",
+ ] as const)
+ expect(after[handler], handler).toBe(before[handler]);
+
+ act(() => before.onSaveToCloud?.(before.fileId));
+ expect(sidebar.uploadTarget?.map((file) => file.name)).toEqual([
+ "renamed.pdf",
+ ]);
+ });
+});
diff --git a/frontend/src/editor/core/components/shared/FileSidebar.tsx b/frontend/src/editor/core/components/shared/FileSidebar.tsx
index 411b178c08..c96ce55ac4 100644
--- a/frontend/src/editor/core/components/shared/FileSidebar.tsx
+++ b/frontend/src/editor/core/components/shared/FileSidebar.tsx
@@ -9,6 +9,7 @@ import React, {
} from "react";
import { Loader, Menu, Tooltip } from "@mantine/core";
import { useNavigate } from "react-router-dom";
+import { useStableCallback } from "@editor/hooks/useStableCallback";
import { ActionIcon } from "@editor/ui/ActionIcon";
import { NavSurface } from "@editor/ui/NavSurface";
import { Button } from "@editor/ui/Button";
@@ -709,26 +710,23 @@ const FileSidebar = forwardRef<HTMLDivElement, FileSidebarProps>(
}, []);
// Server copies require a deletion-scope choice; local-only files delete immediately.
- const handleSidebarDelete = useCallback(
- async (fileId: FileId) => {
- const stub = allFileStubs.find((s) => s.id === fileId);
- const hasCloud =
- !!stub &&
- typeof stub.remoteStorageId === "number" &&
- stub.remoteOwnedByCurrentUser === true;
- if (hasCloud && stub) {
- setDeleteTarget(stub);
- return;
- }
- // Its superseded versions go too - see orphanedAncestorIds.
- const orphans = await fileStorage.orphanedAncestorIds([fileId]);
- await fileActions.removeFiles([fileId, ...orphans], true);
- await refreshStubs();
- },
- [allFileStubs, fileActions, refreshStubs],
- );
+ const handleSidebarDelete = useStableCallback(async (fileId: FileId) => {
+ const stub = allFileStubs.find((s) => s.id === fileId);
+ const hasCloud =
+ !!stub &&
+ typeof stub.remoteStorageId === "number" &&
+ stub.remoteOwnedByCurrentUser === true;
+ if (hasCloud && stub) {
+ setDeleteTarget(stub);
+ return;
+ }
+ // Its superseded versions go too - see orphanedAncestorIds.
+ const orphans = await fileStorage.orphanedAncestorIds([fileId]);
+ await fileActions.removeFiles([fileId, ...orphans], true);
+ await refreshStubs();
+ });
- const handleConfirmSidebarDelete = useCallback(
+ const handleConfirmSidebarDelete = useStableCallback(
async (scope: DeleteScope) => {
const stub = deleteTarget;
if (!stub) return;
@@ -758,26 +756,19 @@ const FileSidebar = forwardRef<HTMLDivElement, FileSidebarProps>(
setDeleteTarget(null);
await refreshStubs();
},
- [deleteTarget, fileActions, refreshStubs],
);
- const handleSaveToCloud = useCallback(
- (fileId: FileId) => {
- const stub = allFileStubs.find((s) => s.id === fileId);
- if (stub) setSaveToServerTarget([stub]);
- },
- [allFileStubs],
- );
+ const handleSaveToCloud = useStableCallback((fileId: FileId) => {
+ const stub = allFileStubs.find((s) => s.id === fileId);
+ if (stub) setSaveToServerTarget([stub]);
+ });
- const handleVersionHistory = useCallback(
- (fileId: FileId) => {
- const stub = allFileStubs.find((s) => s.id === fileId);
- if (stub) setVersionHistoryTarget(stub);
- },
- [allFileStubs],
- );
+ const handleVersionHistory = useStableCallback((fileId: FileId) => {
+ const stub = allFileStubs.find((s) => s.id === fileId);
+ if (stub) setVersionHistoryTarget(stub);
+ });
- const warnDataUnavailable = useCallback(() => {
+ const warnDataUnavailable = useStableCallback(() => {
alert({
alertType: "warning",
title: t("fileSidebar.dataLostTitle", "File data is unavailable"),
@@ -788,36 +779,33 @@ const FileSidebar = forwardRef<HTMLDivElement, FileSidebarProps>(
expandable: false,
durationMs: 6000,
});
- }, [t]);
+ });
// Kebab: download a copy (desktop saves via the native dialog). Routed
// through the policy wrapper so export policies enforce here too.
- const handleDownload = useCallback(
- async (fileId: FileId) => {
- const stub = allFileStubs.find((s) => s.id === fileId);
- const file = await fileStorage.getStirlingFile(fileId);
- if (!file) {
- warnDataUnavailable();
- return;
- }
- try {
- await downloadFileWithPolicy({
- data: file,
- filename: stub?.name ?? file.name,
- fileId: fileId,
- });
- } catch (error) {
- console.error("[FileSidebar] Download failed:", error);
- alert({
- alertType: "error",
- title: t("fileSidebar.downloadFailed", "Download failed"),
- body: error instanceof Error ? error.message : String(error),
- expandable: false,
- });
- }
- },
- [allFileStubs, warnDataUnavailable, t],
- );
+ const handleDownload = useStableCallback(async (fileId: FileId) => {
+ const stub = allFileStubs.find((s) => s.id === fileId);
+ const file = await fileStorage.getStirlingFile(fileId);
+ if (!file) {
+ warnDataUnavailable();
+ return;
+ }
+ try {
+ await downloadFileWithPolicy({
+ data: file,
+ filename: stub?.name ?? file.name,
+ fileId: fileId,
+ });
+ } catch (error) {
+ console.error("[FileSidebar] Download failed:", error);
+ alert({
+ alertType: "error",
+ title: t("fileSidebar.downloadFailed", "Download failed"),
+ body: error instanceof Error ? error.message : String(error),
+ expandable: false,
+ });
+ }
+ });
const oneDriveSave = useOneDriveSave();
const oneDriveHandlers = useMemo(() => {
@@ -834,71 +822,59 @@ const FileSidebar = forwardRef<HTMLDivElement, FileSidebarProps>(
};
}, [allFileStubs, oneDriveSave]);
- const handleDuplicate = useCallback(
- async (fileId: FileId) => {
- const stub = allFileStubs.find((s) => s.id === fileId);
- if (!stub) return;
- try {
- const copyId = await duplicateStoredFile(
- stub,
- allFileStubs.map((s) => s.name),
- addFiles,
- );
- if (!copyId) {
- warnDataUnavailable();
- return;
- }
- await refreshStubs();
- } catch (error) {
- console.error("[FileSidebar] Duplicate failed:", error);
- alert({
- alertType: "error",
- title: t("fileSidebar.duplicateFailed", "Could not duplicate file"),
- body: error instanceof Error ? error.message : String(error),
- expandable: false,
- });
- }
- },
- [allFileStubs, addFiles, refreshStubs, warnDataUnavailable, t],
- );
-
- const handleRename = useCallback(
- (fileId: FileId) => {
- const stub = allFileStubs.find((s) => s.id === fileId);
- if (stub) setRenameTarget(stub);
- },
- [allFileStubs],
- );
-
- const handleConfirmRename = useCallback(
- async (name: string) => {
- const stub = renameTarget;
- if (!stub) return;
- const saved = await renameStoredFile(
+ const handleDuplicate = useStableCallback(async (fileId: FileId) => {
+ const stub = allFileStubs.find((s) => s.id === fileId);
+ if (!stub) return;
+ try {
+ const copyId = await duplicateStoredFile(
stub,
- name,
- fileActions.updateStirlingFileStub,
+ allFileStubs.map((s) => s.name),
+ addFiles,
);
- if (!saved) {
- throw new Error(
- t("fileSidebar.rename.error", "Could not rename the file."),
- );
+ if (!copyId) {
+ warnDataUnavailable();
+ return;
}
- setRenameTarget(null);
await refreshStubs();
- },
- [renameTarget, fileActions, refreshStubs, t],
- );
+ } catch (error) {
+ console.error("[FileSidebar] Duplicate failed:", error);
+ alert({
+ alertType: "error",
+ title: t("fileSidebar.duplicateFailed", "Could not duplicate file"),
+ body: error instanceof Error ? error.message : String(error),
+ expandable: false,
+ });
+ }
+ });
+
+ const handleRename = useStableCallback((fileId: FileId) => {
+ const stub = allFileStubs.find((s) => s.id === fileId);
+ if (stub) setRenameTarget(stub);
+ });
+
+ const handleConfirmRename = useStableCallback(async (name: string) => {
+ const stub = renameTarget;
+ if (!stub) return;
+ const saved = await renameStoredFile(
+ stub,
+ name,
+ fileActions.updateStirlingFileStub,
+ );
+ if (!saved) {
+ throw new Error(
+ t("fileSidebar.rename.error", "Could not rename the file."),
+ );
+ }
+ setRenameTarget(null);
+ await refreshStubs();
+ });
// Desktop-only; a no-op stub on web, where this stays hidden.
const { canOpenInNewWindow, openInNewWindow } = useOpenInNewWindow();
- const handleOpenInNewWindow = useCallback(
- (fileId: FileId) => {
- const stub = allFileStubs.find((s) => s.id === fileId);
- if (stub) openInNewWindow(stub);
- },
- [allFileStubs, openInNewWindow],
- );
+ const handleOpenInNewWindow = useStableCallback((fileId: FileId) => {
+ const stub = allFileStubs.find((s) => s.id === fileId);
+ if (stub) openInNewWindow(stub);
+ });
useEffect(() => {
if (!pendingViewFileId) return;
@@ -1037,80 +1013,66 @@ const FileSidebar = forwardRef<HTMLDivElement, FileSidebarProps>(
failedPicker.clearError();
}, [failedPicker, navigate, t]);
- const handleFileClick = useCallback(
- async (fileId: FileId) => {
- const stub = allFileStubs.find((s) => s.id === fileId);
- if (!stub) return;
+ const handleFileClick = useStableCallback(async (fileId: FileId) => {
+ const stub = allFileStubs.find((s) => s.id === fileId);
+ if (!stub) return;
+
+ // Its bytes are gone; opening it can only fail. Say so instead of a
+ // click that goes nowhere.
+ if (stub.dataUnavailable || lostFileIds.has(fileId)) {
+ alert({
+ alertType: "warning",
+ title: t("fileSidebar.dataLostTitle", "File data is unavailable"),
+ body: t(
+ "fileSidebar.dataLostBody",
+ "Couldn't find this file's contents. Add it again to keep working with it.",
+ ),
+ expandable: false,
+ durationMs: 6000,
+ });
+ return;
+ }
+
+ const workbenchFileId = state.files.ids.find(
+ (id) => (id as string) === (stub.id as string),
+ );
- // Its bytes are gone; opening it can only fail. Say so instead of a
- // click that goes nowhere.
- if (stub.dataUnavailable || lostFileIds.has(fileId)) {
- alert({
- alertType: "warning",
- title: t("fileSidebar.dataLostTitle", "File data is unavailable"),
- body: t(
- "fileSidebar.dataLostBody",
- "Couldn't find this file's contents. Add it again to keep working with it.",
- ),
- expandable: false,
- durationMs: 6000,
+ if (workbenchFileId) {
+ // If this is the file currently open in the viewer, route through the
+ // navigation guard so the save modal fires when there are unsaved changes.
+ const isCurrentlyViewed = workbenchFileId === viewedWorkbenchId;
+ if (isCurrentlyViewed) {
+ requestNavigation(() => {
+ void fileActions.removeFiles([workbenchFileId], false);
});
return;
}
+ await fileActions.removeFiles([workbenchFileId], false);
+ } else {
+ // Re-add by stub to preserve its ID - addFiles() would create a new UUID + IDB entry.
+ const workbenchCount = state.files.ids.length;
- const workbenchFileId = state.files.ids.find(
- (id) => (id as string) === (stub.id as string),
- );
+ if (workbenchCount > 0 && currentWorkbench === "viewer") {
+ navActions.setWorkbench("fileEditor");
+ }
- if (workbenchFileId) {
- // If this is the file currently open in the viewer, route through the
- // navigation guard so the save modal fires when there are unsaved changes.
- const isCurrentlyViewed = workbenchFileId === viewedWorkbenchId;
- if (isCurrentlyViewed) {
- requestNavigation(() => {
- void fileActions.removeFiles([workbenchFileId], false);
- });
- return;
- }
- await fileActions.removeFiles([workbenchFileId], false);
- } else {
- // Re-add by stub to preserve its ID - addFiles() would create a new UUID + IDB entry.
- const workbenchCount = state.files.ids.length;
+ await fileActions.addStirlingFileStubs([stub], { selectFiles: true });
- if (workbenchCount > 0 && currentWorkbench === "viewer") {
+ if (!staysOnAdd) {
+ if (workbenchCount === 0) {
+ navActions.setWorkbench("viewer");
+ } else {
navActions.setWorkbench("fileEditor");
}
-
- await fileActions.addStirlingFileStubs([stub], { selectFiles: true });
-
- if (!staysOnAdd) {
- if (workbenchCount === 0) {
- navActions.setWorkbench("viewer");
- } else {
- navActions.setWorkbench("fileEditor");
- }
- }
}
- },
- [
- allFileStubs,
- lostFileIds,
- t,
- state.files.ids,
- fileActions,
- navActions,
- currentWorkbench,
- activeFileId,
- requestNavigation,
- staysOnAdd,
- ],
- );
+ }
+ });
// Which file is currently open in the viewer - stable ID, never index-derived.
const viewedWorkbenchId =
currentWorkbench === "viewer" ? activeFileId : null;
- const handleEyeClick = useCallback(
+ const handleEyeClick = useStableCallback(
async (fileId: FileId, _e: React.MouseEvent) => {
const stub = allFileStubs.find((s) => s.id === fileId);
if (!stub) return;
@@ -1153,49 +1115,27 @@ const FileSidebar = forwardRef<HTMLDivElement, FileSidebarProps>(
await performSwitch();
}
},
- [
- allFileStubs,
- viewedWorkbenchId,
- state.files.ids,
- fileActions,
- navActions,
- currentWorkbench,
- setPendingViewFileId,
- requestNavigation,
- ],
);
// Shared ingest path for both the native picker and drag-and-drop.
// Per-tool validation happens downstream.
- const ingestFiles = useCallback(
- async (files: File[]) => {
- if (files.length === 0) return;
- await trackIngest(async () => {
- if (onUploadFiles) {
- await onUploadFiles(files);
- return;
- }
- await addFiles(files);
- // A tool that pinned its own workbench surface owns it - switching to
- // the viewer here strands the upload outside the tool being used.
- if (!staysOnAdd && !currentWorkbench.startsWith("custom:")) {
- navActions.setWorkbench(
- files.length === 1 ? "viewer" : "fileEditor",
- );
- }
- });
- },
- [
- trackIngest,
- addFiles,
- navActions,
- staysOnAdd,
- onUploadFiles,
- currentWorkbench,
- ],
- );
+ const ingestFiles = useStableCallback(async (files: File[]) => {
+ if (files.length === 0) return;
+ await trackIngest(async () => {
+ if (onUploadFiles) {
+ await onUploadFiles(files);
+ return;
+ }
+ await addFiles(files);
+ // A tool that pinned its own workbench surface owns it - switching to
+ // the viewer here strands the upload outside the tool being used.
+ if (!staysOnAdd && !currentWorkbench.startsWith("custom:")) {
+ navActions.setWorkbench(files.length === 1 ? "viewer" : "fileEditor");
+ }
+ });
+ });
- const handleNativeFilePick = useCallback(
+ const handleNativeFilePick = useStableCallback(
async (e: React.ChangeEvent<HTMLInputElement>) => {
const input = e.target;
try {
@@ -1207,10 +1147,9 @@ const FileSidebar = forwardRef<HTMLDivElement, FileSidebarProps>(
input.value = "";
}
},
- [ingestFiles, reportUploadFailure],
);
- const openNativeFilePicker = useCallback(() => {
+ const openNativeFilePicker = useStableCallback(() => {
void openFilesFromDisk({
onFallbackOpen: () => nativeFileInputRef.current?.click(),
})
@@ -1219,7 +1158,7 @@ const FileSidebar = forwardRef<HTMLDivElement, FileSidebarProps>(
console.error("[FileSidebar] Native file pick failed", err);
reportUploadFailure(err);
});
- }, [ingestFiles, reportUploadFailure]);
+ });
useEffect(() => {
if (!onRegisterOpenFromComputer) return;
diff --git a/frontend/src/editor/core/hooks/useStableCallback.ts b/frontend/src/editor/core/hooks/useStableCallback.ts
new file mode 100644
index 0000000000..5432753175
--- /dev/null
+++ b/frontend/src/editor/core/hooks/useStableCallback.ts
@@ -0,0 +1,23 @@
+import { useCallback, useLayoutEffect, useRef } from "react";
+
+/**
+ * A function that keeps one identity for the component's lifetime and always
+ * calls the latest `callback`. Use it for event handlers that would otherwise
+ * be re-memoised whenever their data changes.
+ *
+ * A memoised handler holds the render it was made in, and through it every
+ * handler that render held, so a component whose handlers are re-memoised at
+ * different times keeps a chain of its old renders, and their data, alive.
+ *
+ * Not for calling during render: the latest `callback` is installed when the
+ * render commits.
+ */
+export function useStableCallback<Args extends unknown[], Result>(
+ callback: (...args: Args) => Result,
+): (...args: Args) => Result {
+ const latest = useRef(callback);
+ useLayoutEffect(() => {
+ latest.current = callback;
+ });
+ return useCallback((...args: Args) => latest.current(...args), []);
+}
diff --git a/frontend/src/editor/core/icons/icons.ts b/frontend/src/editor/core/icons/icons.ts
index 84e0f2f393..b977c4b8ad 100644
--- a/frontend/src/editor/core/icons/icons.ts
+++ b/frontend/src/editor/core/icons/icons.ts
@@ -24,6 +24,7 @@ import BadgeDollarSign from "lucide-static/icons/badge-dollar-sign.svg?react";
import Banknote from "lucide-static/icons/banknote.svg?react";
import Bell from "lucide-static/icons/bell.svg?react";
import Blocks from "lucide-static/icons/blocks.svg?react";
+import Bold from "lucide-static/icons/bold.svg?react";
import Bolt from "lucide-static/icons/bolt.svg?react";
import Book from "lucide-static/icons/book.svg?react";
import BookOpen from "lucide-static/icons/book-open.svg?react";
@@ -458,6 +459,7 @@ export const ICONS = {
banknote: { Component: Banknote, kind: "lucide" },
bell: { Component: Bell, kind: "lucide" },
blocks: { Component: Blocks, kind: "lucide" },
+ bold: { Component: Bold, kind: "lucide" },
bolt: { Component: Bolt, kind: "lucide" },
book: { Component: Book, kind: "lucide" },
"book-open": { Component: BookOpen, kind: "lucide" },
diff --git a/frontend/src/editor/core/tests/helpers/recognizedTable.ts b/frontend/src/editor/core/tests/helpers/recognizedTable.ts
new file mode 100644
index 0000000000..fe2d7a5351
--- /dev/null
+++ b/frontend/src/editor/core/tests/helpers/recognizedTable.ts
@@ -0,0 +1,18 @@
+import type { Page } from "@playwright/test";
+
+/** Hovers the first recognized table, which is what reveals its chip, and clicks "Edit table". */
+export async function editRecognizedTable(page: Page): Promise<void> {
+ const edit = page
+ .locator('[data-testid^="pdf-editor-recognized-table-edit-"]')
+ .first();
+ await edit.waitFor({ state: "attached" });
+ const id = (await edit.getAttribute("data-testid"))!.replace(
+ "pdf-editor-recognized-table-edit-",
+ "",
+ );
+ const table = page.getByTestId(`pdf-editor-recognized-table-${id}`);
+ await table.scrollIntoViewIfNeeded();
+ const box = (await table.boundingBox())!;
+ await page.mouse.move(box.x + box.width / 2, box.y + box.height / 2);
+ await edit.click();
+}
diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-bold-toggle.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-bold-toggle.spec.ts
new file mode 100644
index 0000000000..f07b13287c
--- /dev/null
+++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-bold-toggle.spec.ts
@@ -0,0 +1,387 @@
+import { test, expect } from "@editor/tests/helpers/stub-test-base";
+import type { Page } from "@playwright/test";
+import { readFileSync } from "fs";
+import path from "path";
+import { openInTextEditor } from "@editor/tests/helpers/pdf-text-editor";
+
+// The font list names each family once; the Bold and Italic toggles move text
+// between the faces that family really has, and never make one up.
+
+const TAGGED_PDF = path.join(
+ import.meta.dirname,
+ "../test-fixtures/tagged-sample.pdf",
+);
+const COLOURED_PDF = path.join(
+ import.meta.dirname,
+ "../test-fixtures/coloured-word-sample.pdf",
+);
+
+const FONTS = path.join(
+ import.meta.dirname,
+ "../../../../../../app/core/src/main/resources/static/fonts",
+);
+
+/** A server family with a light and a semibold face, so the weight menu shows. */
+const SERVER_FAMILY = {
+ family: "Demo Sans",
+ faces: [
+ ["Light", 300, false, "LiberationSans-Regular.ttf"],
+ ["Regular", 400, false, "LiberationSans-Regular.ttf"],
+ ["Semibold", 600, true, "LiberationSans-Bold.ttf"],
+ ["Bold", 700, true, "LiberationSans-Bold.ttf"],
+ ] as const,
+};
+
+async function serveFonts(page: Page) {
+ const id = (i: number) => String(i + 1).repeat(64);
+ await page.route("**/api/v1/ui-data/editor-fonts**", (route) => {
+ const face = /editor-fonts\/([0-9a-f]{64})/.exec(route.request().url());
+ if (!face)
+ return route.fulfill({
+ json: {
+ families: [
+ {
+ family: SERVER_FAMILY.family,
+ faces: SERVER_FAMILY.faces.map(([style, weight, bold], i) => ({
+ id: id(i),
+ style,
+ weight,
+ bold,
+ italic: false,
+ postscriptName: `DemoSans-${style}`,
+ })),
+ },
+ ],
+ },
+ });
+ const index = SERVER_FAMILY.faces.findIndex((_, i) => id(i) === face[1]);
+ return route.fulfill({
+ body: readFileSync(path.join(FONTS, SERVER_FAMILY.faces[index][3])),
+ contentType: "font/ttf",
+ });
+ });
+}
+
+const FORMAT_CONTROLS = [
+ "pdf-editor-font-family",
+ "pdf-editor-font-weight",
+ "pdf-editor-font-size",
+ "pdf-editor-colour",
+ "pdf-editor-bold",
+ "pdf-editor-italic",
+ "pdf-editor-change-case",
+];
+
+/** The formatting controls a user cannot see: past the toolbar's edge, or missing from the formatting menu. */
+async function unreachableControls(page: Page): Promise<string[]> {
+ const menu = page.getByTestId("pdf-editor-format-menu");
+ if ((await menu.count()) > 0) {
+ const family = page.getByTestId("pdf-editor-font-family");
+ if (!(await family.isVisible())) await menu.click();
+ await family.waitFor({ state: "visible" });
+ const missing: string[] = [];
+ for (const id of FORMAT_CONTROLS)
+ if (!(await page.getByTestId(id).isVisible())) missing.push(id);
+ return missing;
+ }
+ return page.evaluate((ids) => {
+ const band = document
+ .querySelector(".pdf-editor-topbar__band")!
+ .getBoundingClientRect();
+ return ids.filter((id) => {
+ const control = document.querySelector(`[data-testid="${id}"]`);
+ if (!control) return true;
+ const box = control.getBoundingClientRect();
+ return box.left < band.left - 0.5 || box.right > band.right + 0.5;
+ });
+ }, FORMAT_CONTROLS);
+}
+
+async function openEditor(page: Page, file: string) {
+ await page.goto("/pdf-text-editor", { waitUntil: "domcontentloaded" });
+ await expect(page.getByTestId("pdf-editor-root")).toBeVisible({
+ timeout: 30_000,
+ });
+ await openInTextEditor(page, file);
+ await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
+ timeout: 60_000,
+ });
+ await expect.poll(() => runs(page), { timeout: 30_000 }).not.toHaveLength(0);
+}
+
+function runs(
+ page: Page,
+): Promise<Array<{ id: string; text: string; fontId: string }>> {
+ return page.evaluate(() => {
+ const w = window as unknown as {
+ __editor_store?: {
+ state: {
+ pages: { runs: { id: string; text: string; fontId: string }[] }[];
+ };
+ };
+ };
+ return (w.__editor_store?.state.pages[0]?.runs ?? []).map((r) => ({
+ id: r.id,
+ text: r.text,
+ fontId: r.fontId,
+ }));
+ });
+}
+
+async function runId(page: Page, text: string): Promise<string> {
+ const run = (await runs(page)).find((r) => r.text.startsWith(text));
+ expect(run, `no run starting "${text}"`).toBeTruthy();
+ return run!.id;
+}
+
+async function fontIdOf(page: Page, id: string): Promise<string | undefined> {
+ return (await runs(page)).find((r) => r.id === id)?.fontId;
+}
+
+function runBox(page: Page, id: string) {
+ return page.getByTestId(`pdf-editor-run-${id}`);
+}
+
+/** Put the run in the served family, whose extra weights bring up the weight menu. */
+async function pickServerFamily(page: Page, id: string) {
+ await runBox(page, id).click();
+ await page.getByTestId("pdf-editor-font-family").click();
+ await page
+ .getByRole("option", { name: SERVER_FAMILY.family, exact: true })
+ .click();
+ await expect.poll(() => fontIdOf(page, id)).toMatch(/Demo Sans/);
+}
+
+test.describe("PDF text editor - Bold toggle", () => {
+ test("the font list names each family once and Bold picks the bold face", async ({
+ page,
+ }) => {
+ await openEditor(page, TAGGED_PDF);
+ const body = await runId(page, "Revenue grew");
+ await runBox(page, body).click();
+
+ const bold = page.getByTestId("pdf-editor-bold");
+ await expect(bold).toBeEnabled();
+ await expect(bold).toHaveAttribute("aria-pressed", "false");
+ await expect(
+ page
+ .getByTestId("pdf-editor-italic")
+ .locator("xpath=preceding-sibling::*[1]"),
+ ).toHaveAttribute("data-testid", "pdf-editor-bold");
+
+ await page.getByTestId("pdf-editor-font-family").click();
+ await expect(
+ page.getByRole("option", { name: "Helvetica", exact: true }),
+ ).toBeVisible();
+ await expect(
+ page.getByRole("option", { name: /bold|oblique|italic/i }),
+ ).toHaveCount(0);
+ await page.keyboard.press("Escape");
+ await expect(
+ page.getByRole("option", { name: "Helvetica", exact: true }),
+ ).toBeHidden();
+
+ await bold.click();
+ await expect.poll(() => fontIdOf(page, body)).toMatch(/Helvetica-Bold$/);
+ await expect(bold).toHaveAttribute("aria-pressed", "true");
+ expect((await runs(page)).find((r) => r.id === body)?.text).toMatch(
+ /^Revenue grew in every region/,
+ );
+
+ await bold.click();
+ await expect.poll(() => fontIdOf(page, body)).not.toMatch(/Bold/);
+ await expect(bold).toHaveAttribute("aria-pressed", "false");
+
+ await page.getByTestId("pdf-editor-undo").click();
+ await expect.poll(() => fontIdOf(page, body)).toMatch(/Helvetica-Bold$/);
+ await page.getByTestId("pdf-editor-redo").click();
+ await expect.poll(() => fontIdOf(page, body)).not.toMatch(/Bold/);
+ });
+
+ test("a half-bold selection shows mixed and goes all bold", async ({
+ page,
+ }) => {
+ await openEditor(page, TAGGED_PDF);
+ const heading = await runId(page, "Quarterly report");
+ const body = await runId(page, "Revenue grew");
+
+ const headingFont = await fontIdOf(page, heading);
+
+ await runBox(page, body).click();
+ await runBox(page, heading).click({ modifiers: ["Shift"] });
+
+ const bold = page.getByTestId("pdf-editor-bold");
+ await expect(bold).toHaveAttribute("aria-pressed", "mixed");
+ await bold.click();
+
+ await expect.poll(() => fontIdOf(page, body)).toMatch(/Helvetica-Bold$/);
+ await expect(bold).toHaveAttribute("aria-pressed", "true");
+ expect(await fontIdOf(page, heading), "already bold, left as it was").toBe(
+ headingFont,
+ );
+ });
+
+ test("Bold is off with a reason for a font that has no bold face", async ({
+ page,
+ }) => {
+ await openEditor(page, COLOURED_PDF);
+ await runBox(page, await runId(page, "הטלפון")).click();
+
+ const bold = page.getByTestId("pdf-editor-bold");
+ await expect(bold).toBeDisabled();
+ await bold.hover();
+ await expect(page.getByRole("tooltip")).toContainText(
+ "No bold version of this font",
+ );
+ });
+
+ test("Bold onto a subset that lacks some letters draws them in the closest match and says so", async ({
+ page,
+ }) => {
+ await openEditor(page, COLOURED_PDF);
+ const line = await runId(page, "Total due today");
+ const before = await fontIdOf(page, line);
+ await runBox(page, line).click();
+
+ await page.getByTestId("pdf-editor-bold").click();
+
+ await expect(
+ page.getByText(/drawn in the closest matching font/),
+ ).toBeVisible();
+ await expect.poll(() => fontIdOf(page, line)).not.toBe(before);
+ expect((await runs(page)).find((r) => r.id === line)?.text).toBe(
+ "Total due today by card",
+ );
+ await expect(page.getByTestId("pdf-editor-bold")).toHaveAttribute(
+ "aria-pressed",
+ "true",
+ );
+ });
+});
+
+test.describe("PDF text editor - formatting controls stay reachable", () => {
+ for (const width of [1280, 1440, 1600, 1920]) {
+ test(`every control, the weight menu included, is reachable at ${width}px`, async ({
+ page,
+ }) => {
+ await serveFonts(page);
+ await page.setViewportSize({ width: 1920, height: 1000 });
+ await openEditor(page, TAGGED_PDF);
+ await pickServerFamily(page, await runId(page, "Revenue grew"));
+
+ await page.setViewportSize({ width, height: 1000 });
+
+ await expect.poll(() => unreachableControls(page)).toEqual([]);
+ });
+ }
+});
+
+function fillOf(page: Page, id: string): Promise<string | undefined> {
+ return page.evaluate((rid) => {
+ const w = window as unknown as {
+ __editor_store: {
+ state: {
+ pages: {
+ runs: { id: string; fill: { r: number; g: number; b: number } }[];
+ }[];
+ };
+ };
+ };
+ const fill = w.__editor_store.state.pages[0].runs.find(
+ (r) => r.id === rid,
+ )?.fill;
+ return fill ? `${fill.r},${fill.g},${fill.b}` : undefined;
+ }, id);
+}
+
+/** Narrow the window until the formatting controls fit inline with `slack` pixels to spare. */
+async function fitInlineWithSlack(page: Page, slack: number) {
+ const spare = await page.evaluate(() => {
+ const band = document.querySelector(".pdf-editor-topbar__band")!;
+ const last = document.querySelector(
+ '[data-testid="pdf-editor-change-case"]',
+ )!;
+ return Math.floor(
+ band.getBoundingClientRect().right - last.getBoundingClientRect().right,
+ );
+ });
+ const size = page.viewportSize()!;
+ await page.setViewportSize({
+ width: size.width - spare + slack,
+ height: size.height,
+ });
+}
+
+test.describe("PDF text editor - formatting popovers stay open", () => {
+ test("the colour picker stays open when opening it widens the field past the toolbar's edge", async ({
+ page,
+ }) => {
+ await page.setViewportSize({ width: 2200, height: 1000 });
+ await openEditor(page, TAGGED_PDF);
+ const body = await runId(page, "Revenue grew");
+ await runBox(page, body).click();
+ await expect(page.getByTestId("pdf-editor-colour")).toBeVisible();
+ // Narrower than the open colour field needs, wider than the closed one.
+ await fitInlineWithSlack(page, 12);
+ await expect(page.getByTestId("pdf-editor-format-menu")).toHaveCount(0);
+ await expect(page.getByTestId("pdf-editor-change-case")).toBeInViewport({
+ ratio: 1,
+ });
+ const before = await fillOf(page, body);
+
+ await page.getByTestId("pdf-editor-colour").click();
+ const saturation = page.locator(".mantine-ColorInput-saturation").first();
+ await expect(saturation).toBeVisible();
+ const box = (await saturation.boundingBox())!;
+ await saturation.click({ position: { x: box.width - 4, y: 4 } });
+
+ await expect.poll(() => fillOf(page, body)).not.toBe(before);
+ });
+
+ for (const width of [1920, 1280]) {
+ test(`the change-case menu, outline colour and weight menu open at ${width}px`, async ({
+ page,
+ }) => {
+ await serveFonts(page);
+ await page.setViewportSize({ width: 2400, height: 1000 });
+ await openEditor(page, TAGGED_PDF);
+ const body = await runId(page, "Revenue grew");
+ await pickServerFamily(page, body);
+ await page.setViewportSize({ width, height: 1000 });
+ const menu = page.getByTestId("pdf-editor-format-menu");
+ await expect(
+ page.getByTestId("pdf-editor-font-weight").or(menu),
+ ).toBeVisible();
+ const bold = page.getByTestId("pdf-editor-bold");
+ // Folded, the controls show once the formatting menu has opened.
+ const openFormatting = () =>
+ expect(async () => {
+ if ((await menu.count()) > 0 && !(await bold.isVisible()))
+ await menu.click();
+ await expect(bold).toBeVisible({ timeout: 2_000 });
+ }).toPass();
+
+ await openFormatting();
+ await page.getByTestId("pdf-editor-font-weight").click();
+ await expect(
+ page.getByRole("option", { name: /Semibold/ }),
+ ).toBeVisible();
+ await page.getByRole("option", { name: /Semibold/ }).click();
+ await expect.poll(() => fontIdOf(page, body)).toMatch(/Semibold/);
+
+ await openFormatting();
+ await page.getByTestId("pdf-editor-change-case").click();
+ await expect(
+ page.getByTestId("pdf-editor-change-case-upper"),
+ ).toBeVisible();
+ await page.getByTestId("pdf-editor-change-case-upper").click();
+ await expect
+ .poll(async () => (await runs(page)).find((r) => r.id === body)?.text)
+ .toMatch(/^REVENUE GREW/);
+
+ await openFormatting();
+ await page.getByTestId("pdf-editor-colour-advanced").click();
+ await expect(page.getByTestId("pdf-editor-outline-width")).toBeVisible();
+ });
+ }
+});
diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-bold-words.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-bold-words.spec.ts
new file mode 100644
index 0000000000..139eb5eed9
--- /dev/null
+++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-bold-words.spec.ts
@@ -0,0 +1,234 @@
+import { test, expect } from "@editor/tests/helpers/stub-test-base";
+import type { Page } from "@playwright/test";
+import path from "path";
+import { openInTextEditor } from "@editor/tests/helpers/pdf-text-editor";
+import {
+ downloadBytes,
+ reopenSavedBytes,
+ saveAndDownload,
+} from "@editor/tests/stubbed/saveHelpers";
+
+// Bold on words selected inside a text box makes those words bold on the page,
+// and only them, the way a word processor does.
+
+const TAGGED_PDF = path.join(
+ import.meta.dirname,
+ "../test-fixtures/tagged-sample.pdf",
+);
+const BODY = "Revenue grew in every region this quarter,";
+
+interface Rect {
+ x: number;
+ y: number;
+ width: number;
+ height: number;
+}
+
+interface EditorWindow {
+ __editor_store?: {
+ state: { pages: { runs: { id: string; text: string }[] }[] };
+ selection: { value: { textRange: { start: number; end: number } | null } };
+ };
+}
+
+async function openEditor(page: Page, file: string) {
+ await page.goto("/pdf-text-editor", { waitUntil: "domcontentloaded" });
+ await expect(page.getByTestId("pdf-editor-root")).toBeVisible({
+ timeout: 30_000,
+ });
+ await openInTextEditor(page, file);
+ await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
+ timeout: 60_000,
+ });
+ await expect.poll(() => bodyRun(page), { timeout: 30_000 }).toBeTruthy();
+}
+
+function bodyRun(page: Page): Promise<{ id: string; text: string } | null> {
+ return page.evaluate((body) => {
+ const w = window as unknown as EditorWindow;
+ return (
+ w.__editor_store?.state.pages[0]?.runs.find((r) =>
+ r.text.startsWith(body),
+ ) ?? null
+ );
+ }, BODY);
+}
+
+/** Where `word` sits in the run's box, read from the box's own text. */
+function wordRect(page: Page, runId: string, word: string): Promise<Rect> {
+ return page.evaluate(
+ ({ runId, word }) => {
+ const el = document.querySelector(
+ `[data-testid="pdf-editor-run-${runId}"]`,
+ )!;
+ const walker = document.createTreeWalker(el, NodeFilter.SHOW_TEXT);
+ const nodes: Text[] = [];
+ let text = "";
+ while (walker.nextNode()) {
+ nodes.push(walker.currentNode as Text);
+ text += (walker.currentNode as Text).data;
+ }
+ const locate = (at: number): [Text, number] => {
+ for (const node of nodes) {
+ if (at <= node.data.length) return [node, at];
+ at -= node.data.length;
+ }
+ const last = nodes[nodes.length - 1];
+ return [last, last.data.length];
+ };
+ const start = text.indexOf(word);
+ const range = document.createRange();
+ range.setStart(...locate(start));
+ range.setEnd(...locate(start + word.length));
+ // A range starting at a line break also covers the end of the line before it.
+ const rects = range.getClientRects();
+ const r = rects[rects.length - 1] ?? range.getBoundingClientRect();
+ return { x: r.x, y: r.y, width: r.width, height: r.height };
+ },
+ { runId, word },
+ );
+}
+
+/** How much ink the page bitmap has under each rect. */
+function inkUnder(page: Page, rects: Rect[]): Promise<number[]> {
+ return page.evaluate((rects) => {
+ const canvas = Array.from(
+ document.querySelectorAll<HTMLCanvasElement>(
+ '[data-testid="pdf-editor-page-0"] canvas',
+ ),
+ ).find((c) => c.width > 0 && c.height > 0)!;
+ const box = canvas.getBoundingClientRect();
+ const sx = canvas.width / box.width;
+ const sy = canvas.height / box.height;
+ const ctx = canvas.getContext("2d", { willReadFrequently: true })!;
+ return rects.map((r) => {
+ const data = ctx.getImageData(
+ Math.round((r.x - box.x) * sx),
+ Math.round((r.y - box.y) * sy),
+ Math.max(1, Math.round(r.width * sx)),
+ Math.max(1, Math.round(r.height * sy)),
+ ).data;
+ let ink = 0;
+ for (let i = 0; i < data.length; i += 4)
+ ink += 255 - (data[i] + data[i + 1] + data[i + 2]) / 3;
+ return ink / 255;
+ });
+ }, rects);
+}
+
+/** The ink under each rect once the bitmap has stopped changing. */
+async function settledInk(page: Page, rects: Rect[]): Promise<number[]> {
+ let last = "";
+ let ink: number[] = [];
+ await expect
+ .poll(
+ async () => {
+ ink = await inkUnder(page, rects);
+ const key = ink.map((v) => v.toFixed(1)).join();
+ const same = key === last;
+ last = key;
+ return same;
+ },
+ { timeout: 20_000, intervals: [300] },
+ )
+ .toBe(true);
+ return ink;
+}
+
+function textRange(page: Page) {
+ return page.evaluate(
+ () =>
+ (window as unknown as EditorWindow).__editor_store?.selection.value
+ .textRange ?? null,
+ );
+}
+
+async function wordRects(page: Page, runId: string, words: string[]) {
+ const rects: Rect[] = [];
+ for (const word of words) rects.push(await wordRect(page, runId, word));
+ return rects;
+}
+
+const WORDS = ["Revenue grew in", "every", "region", "led by demand"];
+
+test.describe("PDF text editor - Bold on selected words", () => {
+ test("Bold on a double-clicked word and on a word picked out with Shift+arrows makes only those words heavier, and a save keeps them", async ({
+ page,
+ }) => {
+ test.setTimeout(120_000);
+ await openEditor(page, TAGGED_PDF);
+ const { id } = (await bodyRun(page))!;
+ const rects = await wordRects(page, id, WORDS);
+ const before = await settledInk(page, rects);
+ const box = page.getByTestId(`pdf-editor-run-${id}`);
+
+ await box.click({ position: { x: 4, y: 4 } });
+ const every = rects[1];
+ await page.mouse.dblclick(
+ every.x + every.width / 2,
+ every.y + every.height / 2,
+ );
+ const start = BODY.indexOf("every");
+ await expect
+ .poll(() => textRange(page))
+ .toMatchObject({ start, end: expect.any(Number) });
+ await expect(page.getByTestId("pdf-editor-bold")).toHaveAttribute(
+ "aria-pressed",
+ "false",
+ );
+ await page.keyboard.press("ControlOrMeta+b");
+
+ await expect
+ .poll(async () => (await inkUnder(page, [every]))[0], {
+ timeout: 20_000,
+ })
+ .toBeGreaterThan(before[1] * 1.2);
+ const bolded = await settledInk(page, rects);
+ expect(bolded[0] / before[0]).toBeCloseTo(1, 1);
+ expect(bolded[3] / before[3]).toBeCloseTo(1, 1);
+ expect((await bodyRun(page))!.text.startsWith(BODY)).toBe(true);
+
+ const region = await wordRect(page, id, "region");
+ await page.mouse.dblclick(
+ region.x + region.width / 2,
+ region.y + region.height / 2,
+ );
+ await page.keyboard.press("ArrowLeft");
+ for (let i = 0; i < "region".length; i++)
+ await page.keyboard.press("Shift+ArrowRight");
+ const regionAt = BODY.indexOf("region");
+ await expect
+ .poll(() => textRange(page))
+ .toEqual({ start: regionAt, end: regionAt + "region".length });
+ await page.keyboard.press("ControlOrMeta+b");
+
+ await expect
+ .poll(async () => (await inkUnder(page, [region]))[0], {
+ timeout: 20_000,
+ })
+ .toBeGreaterThan(before[2] * 1.2);
+ const bothBold = await settledInk(page, rects);
+ await expect(page.getByTestId("pdf-editor-bold")).toHaveAttribute(
+ "aria-pressed",
+ "true",
+ );
+ expect(bothBold[0] / before[0]).toBeCloseTo(1, 1);
+ expect(bothBold[3] / before[3]).toBeCloseTo(1, 1);
+
+ const saved = await downloadBytes(await saveAndDownload(page, false));
+ expect(saved.toString("latin1")).toContain("/Helvetica-Bold");
+ await reopenSavedBytes(page, saved, "saved.pdf", 0, 60_000);
+ const reopened = (await bodyRun(page))!;
+ expect(reopened.text.startsWith(BODY)).toBe(true);
+ const reopenedRects = await wordRects(page, reopened.id, WORDS);
+ await expect
+ .poll(async () => (await inkUnder(page, reopenedRects))[1], {
+ timeout: 20_000,
+ })
+ .toBeGreaterThan(before[1] * 1.2);
+ const after = await settledInk(page, reopenedRects);
+ expect(after[2]).toBeGreaterThan(before[2] * 1.2);
+ expect(after[0] / before[0]).toBeCloseTo(1, 1);
+ expect(after[3] / before[3]).toBeCloseTo(1, 1);
+ });
+});
diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-clipped-image.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-clipped-image.spec.ts
new file mode 100644
index 0000000000..6c9f3e15e0
--- /dev/null
+++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-clipped-image.spec.ts
@@ -0,0 +1,119 @@
+import { test, expect } from "@editor/tests/helpers/stub-test-base";
+import type { Page } from "@playwright/test";
+import {
+ buildClassicPdf,
+ streamBody,
+} from "@editor/tools/pdfTextEditor/__tests__/pdfFixtures";
+import { openInTextEditor } from "@editor/tests/helpers/pdf-text-editor";
+
+// A picture cropped the way Word and PowerPoint crop one: a 200pt image drawn
+// through a 100pt window. What the user can grab is the window, never the
+// hidden rest of the image.
+
+const PAGE_PT = 300;
+const WINDOW_PT = { x: 100, y: 100, width: 100, height: 100 };
+
+function croppedImagePdf(): Buffer {
+ return Buffer.from(
+ buildClassicPdf(
+ [
+ { num: 1, body: "<< /Type /Catalog /Pages 2 0 R >>" },
+ { num: 2, body: "<< /Type /Pages /Kids [3 0 R] /Count 1 >>" },
+ {
+ num: 3,
+ body: `<< /Type /Page /Parent 2 0 R /MediaBox [0 0 ${PAGE_PT} ${PAGE_PT}] /Contents 4 0 R /Resources << /XObject << /Im 5 0 R >> >> >>`,
+ },
+ {
+ num: 4,
+ body: streamBody(
+ "",
+ "q 100 100 100 100 re W n 200 0 0 200 50 50 cm /Im Do Q",
+ ),
+ },
+ {
+ num: 5,
+ body: streamBody(
+ "/Type /XObject /Subtype /Image /Width 2 /Height 2 /ColorSpace /DeviceRGB /BitsPerComponent 8",
+ "\x00\x00\xff".repeat(4),
+ ),
+ },
+ ],
+ 1,
+ ),
+ );
+}
+
+interface EditorWin {
+ __editor_store: {
+ state: {
+ pages: Array<{
+ images: Array<{ bounds: { x: number; y: number } }>;
+ }>;
+ };
+ };
+}
+
+async function openCroppedImage(page: Page): Promise<void> {
+ await page.goto("/pdf-text-editor", { waitUntil: "domcontentloaded" });
+ await expect(page.getByTestId("pdf-editor-root")).toBeVisible({
+ timeout: 30_000,
+ });
+ await openInTextEditor(page, {
+ name: "cropped-image.pdf",
+ mimeType: "application/pdf",
+ buffer: croppedImagePdf(),
+ });
+ await expect(page.getByTestId("pdf-editor-image-p0-i0")).toBeVisible({
+ timeout: 60_000,
+ });
+}
+
+function imageX(page: Page): Promise<number> {
+ return page.evaluate(
+ () =>
+ (window as unknown as EditorWin).__editor_store.state.pages[0].images[0]
+ .bounds.x,
+ );
+}
+
+test.describe("PDF text editor: cropped image", () => {
+ test("selects and drags the window the image shows", async ({ page }) => {
+ await openCroppedImage(page);
+ const canvas = (await page
+ .getByTestId("pdf-editor-page-0")
+ .locator("canvas")
+ .first()
+ .boundingBox())!;
+ const handle = page.getByTestId("pdf-editor-image-p0-i0");
+ const box = (await handle.boundingBox())!;
+ const scale = canvas.width / PAGE_PT;
+ expect(box.width).toBeCloseTo(WINDOW_PT.width * scale, 0);
+ expect(box.height).toBeCloseTo(WINDOW_PT.height * scale, 0);
+ expect(box.x - canvas.x).toBeCloseTo(WINDOW_PT.x * scale, 0);
+ expect(canvas.y + canvas.height - (box.y + box.height)).toBeCloseTo(
+ WINDOW_PT.y * scale,
+ 0,
+ );
+
+ const from = { x: box.x + box.width / 2, y: box.y + box.height / 2 };
+ await handle.click();
+ await page.mouse.move(from.x, from.y);
+ await page.mouse.down();
+ await page.mouse.move(from.x + 60, from.y, { steps: 12 });
+ const ghost = page.getByTestId("pdf-editor-image-ghost");
+ await expect(ghost).toBeAttached();
+ const ghostBox = (await ghost.boundingBox())!;
+ expect(ghostBox.width).toBeCloseTo(2 * box.width, 0);
+ await page.mouse.up();
+ await expect(ghost).toHaveCount(0);
+
+ const startX = 50;
+ await expect
+ .poll(() => imageX(page), { timeout: 30_000 })
+ .toBeCloseTo(startX + 60 / scale, 0);
+ await expect
+ .poll(async () => (await handle.boundingBox())!.x, { timeout: 30_000 })
+ .toBeCloseTo(box.x + 60, 0);
+ expect((await handle.boundingBox())!.width).toBeCloseTo(box.width, 0);
+ });
+});
diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-edge-gestures.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-edge-gestures.spec.ts
index e23ed67f07..ab8a79b9da 100644
--- a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-edge-gestures.spec.ts
+++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-edge-gestures.spec.ts
@@ -79,10 +79,13 @@ test.describe("PDF text editor - edge gestures", () => {
const before = await shapeOf(page, "Downloads");
const box = await boxOf(page, "Downloads");
- // Grab the top edge - the frame, not the text interior.
- await page.mouse.move(box.x + box.width / 2, box.y + 2);
+ // Grab the frame just below the box, not the text interior: the run
+ // above overlaps this one's top edge, and its text wins there.
+ const below = box.y + box.height + 3;
+ await page.mouse.move(box.x + box.width / 2, box.y + box.height / 2);
+ await page.mouse.move(box.x + box.width / 2, below, { steps: 4 });
await page.mouse.down();
- await page.mouse.move(box.x + box.width / 2 + 40, box.y + 2, { steps: 8 });
+ await page.mouse.move(box.x + box.width / 2 + 40, below, { steps: 8 });
await page.mouse.up();
await page.waitForTimeout(400);
@@ -134,7 +137,8 @@ test.describe("PDF text editor - edge gestures", () => {
const before = await textOf(page, "Open Source");
const box = await boxOf(page, "Open Source");
- await page.mouse.move(box.x + 2, box.y + box.height / 2);
+ await page.mouse.move(box.x + 10, box.y + box.height / 2);
+ await page.mouse.move(box.x - 3, box.y + box.height / 2, { steps: 4 });
await page.mouse.down();
await page.mouse.move(box.x + 40, box.y + box.height / 2, { steps: 10 });
await page.mouse.up();
@@ -153,7 +157,16 @@ test.describe("PDF text editor - edge gestures", () => {
const before = await textOf(page, "Open Source");
const box = await boxOf(page, "Open Source");
- await page.mouse.move(box.x + box.width - 2, box.y + box.height / 2);
+ await page.mouse.move(box.x + box.width / 2, box.y + box.height / 2);
+ const handle = await page
+ .locator('[data-testid^="pdf-editor-width-handle-"]')
+ .boundingBox();
+ if (!handle) throw new Error("no width handle on the hovered run");
+ await page.mouse.move(
+ handle.x + handle.width / 2,
+ handle.y + handle.height / 2,
+ { steps: 4 },
+ );
await page.mouse.down();
await page.mouse.move(box.x + box.width * 0.5, box.y + box.height / 2, {
steps: 10,
diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-failed-open.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-failed-open.spec.ts
new file mode 100644
index 0000000000..738dfce718
--- /dev/null
+++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-failed-open.spec.ts
@@ -0,0 +1,41 @@
+import path from "path";
+import type { Page } from "@playwright/test";
+import { test, expect } from "@editor/tests/helpers/stub-test-base";
+import type { EditorStore } from "@editor/tools/pdfTextEditor/store/EditorStore";
+
+const FIXTURES = path.join(import.meta.dirname, "../test-fixtures");
+const RESTRICTED = path.join(FIXTURES, "owner-only-restricted.pdf");
+
+type EditorWindow = Window & { __editor_store: EditorStore };
+
+const openedName = (page: Page) =>
+ page.evaluate(
+ () => (window as unknown as EditorWindow).__editor_store.source.fileName,
+ );
+
+test.describe("PDF text editor - a file that does not open", () => {
+ test("offers the permissions password for a restricted workbench file and takes its name once it opens", async ({
+ page,
+ }) => {
+ await page.goto("/editor");
+ await page.getByTestId("file-input").setInputFiles(RESTRICTED);
+ // The upload opens the workbench's permission check, whose overlay takes
+ // the click until it closes; on a slow WebKit that outlasts the default.
+ await page
+ .getByRole("link", { name: "PDF Text Editor", exact: true })
+ .first()
+ .click({ timeout: 60_000 });
+ const banner = page.getByTestId("pdf-editor-error");
+ await banner
+ .getByRole("button", { name: "Enter permissions password" })
+ .click();
+ await page
+ .getByLabel("Permissions password", { exact: true })
+ .fill("owner-test-password");
+ await page.getByRole("button", { name: "Continue", exact: true }).click();
+ await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
+ timeout: 60_000,
+ });
+ await expect.poll(() => openedName(page)).toBe("owner-only-restricted.pdf");
+ });
+});
diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-find-bar.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-find-bar.spec.ts
index 9c3fa99f37..7a0e705e1d 100644
--- a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-find-bar.spec.ts
+++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-find-bar.spec.ts
@@ -2,6 +2,7 @@ import { test, expect } from "@editor/tests/helpers/stub-test-base";
import { openInTextEditor } from "@editor/tests/helpers/pdf-text-editor";
import type { Page } from "@playwright/test";
import path from "path";
+import { waitForEditorReady } from "@editor/tests/stubbed/editorReady";
const SAMPLE_PDF = path.join(
import.meta.dirname,
@@ -13,6 +14,9 @@ async function openFind(page: Page): Promise<void> {
await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
timeout: 60_000,
});
+ // The first page's render holds the main thread, and a cold worker's
+ // can outlast the click's wait for the button to stop moving.
+ await waitForEditorReady(page, 60_000);
await page.getByTestId("pdf-editor-open-find").click();
await expect(page.getByTestId("pdf-editor-find-bar")).toBeVisible();
}
diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-grow-columns.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-grow-columns.spec.ts
new file mode 100644
index 0000000000..f9e554982b
--- /dev/null
+++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-grow-columns.spec.ts
@@ -0,0 +1,138 @@
+import { test, expect } from "@editor/tests/helpers/stub-test-base";
+import type { Page } from "@playwright/test";
+import path from "path";
+import {
+ saveAndDownload,
+ stashCurrentDocument,
+ waitForReopenedPage,
+} from "@editor/tests/stubbed/saveHelpers";
+import { openInTextEditor } from "@editor/tests/helpers/pdf-text-editor";
+
+// Grow widens a box up to the page edge. On a page of two columns the text
+// beside a left-column line is an edge too: typing past the end of that line
+// wraps it inside its column instead of drawing over the column on its right.
+
+const TWO_COLUMN_PDF = path.join(
+ import.meta.dirname,
+ "../test-fixtures/two-column-sample.pdf",
+);
+const GUTTER_LEFT = 296.5;
+const TYPED = " with extra cargo";
+
+interface RunState {
+ id: string;
+ text: string;
+ bounds: { x: number; y: number; width: number; height: number };
+}
+
+interface EditorWindow {
+ __editor_store: {
+ state: { pages: { runs: RunState[] }[] };
+ };
+}
+
+const pageRuns = (page: Page): Promise<RunState[]> =>
+ page.evaluate(() =>
+ (window as unknown as EditorWindow).__editor_store.state.pages[0].runs.map(
+ ({ id, text, bounds }) => ({ id, text, bounds: { ...bounds } }),
+ ),
+ );
+
+const rightColumn = (runs: RunState[]) =>
+ runs
+ .filter((run) => run.bounds.x > GUTTER_LEFT)
+ .map(({ text, bounds }) => ({
+ text,
+ x: Math.round(bounds.x * 10) / 10,
+ y: Math.round(bounds.y * 10) / 10,
+ }))
+ .sort((a, b) => b.y - a.y || a.x - b.x);
+
+const acrossGutter = (runs: RunState[]) =>
+ runs
+ .filter(
+ (run) =>
+ !run.text.includes("regional council") &&
+ run.bounds.x < GUTTER_LEFT &&
+ run.bounds.x + run.bounds.width > GUTTER_LEFT,
+ )
+ .map((run) => run.text);
+
+async function open(page: Page, file: string): Promise<void> {
+ await stashCurrentDocument(page);
+ await openInTextEditor(page, file);
+ await waitForReopenedPage(page, 0, 60_000);
+}
+
+test("typing past a left-column line in Grow wraps it inside its column", async ({
+ page,
+}, testInfo) => {
+ await page.goto("/pdf-text-editor", { waitUntil: "domcontentloaded" });
+ await expect(page.getByTestId("pdf-editor-root")).toBeVisible({
+ timeout: 30_000,
+ });
+ await open(page, TWO_COLUMN_PDF);
+
+ const before = await pageRuns(page);
+ const target = before.find((run) => run.text.startsWith("Northern ferries"));
+ expect(target, "left column paragraph").toBeTruthy();
+ const neighbour = before.find((run) => run.text.startsWith("Village"));
+ expect(neighbour, "right column paragraph").toBeTruthy();
+ const linesBefore = target!.text.split("\n").length;
+
+ const box = page.getByTestId(`pdf-editor-run-${target!.id}`);
+ const beside = page.getByTestId(`pdf-editor-run-${neighbour!.id}`);
+ await box.click();
+ await expect(box).toBeFocused();
+ // Home and End scroll the page in the viewer, so the caret is placed directly.
+ await box.evaluate((el, at) => {
+ const walker = document.createTreeWalker(el, NodeFilter.SHOW_TEXT);
+ let left = at;
+ for (let node = walker.nextNode(); node; node = walker.nextNode()) {
+ const length = node.textContent?.length ?? 0;
+ if (left <= length) {
+ window.getSelection()!.collapse(node, left);
+ return;
+ }
+ left -= length;
+ }
+ }, target!.text.split("\n")[0].length);
+ await page.keyboard.type(TYPED, { delay: 40 });
+
+ const textNow = () =>
+ page.evaluate(
+ (id) =>
+ (
+ window as unknown as EditorWindow
+ ).__editor_store.state.pages[0].runs.find((run) => run.id === id)
+ ?.text ?? "",
+ target!.id,
+ );
+ await expect
+ .poll(async () => (await textNow()).replace(/\s+/g, " "), {
+ timeout: 30_000,
+ })
+ .toContain("the islands with extra cargo");
+ expect((await textNow()).split("\n").length).toBeGreaterThan(linesBefore);
+
+ const boxRight = (await box.boundingBox())!;
+ const besideLeft = (await beside.boundingBox())!;
+ expect(boxRight.x + boxRight.width).toBeLessThanOrEqual(besideLeft.x);
+
+ const during = await pageRuns(page);
+ expect(acrossGutter(during)).toEqual([]);
+ expect(rightColumn(during)).toEqual(rightColumn(before));
+
+ await box.evaluate((el) => el.blur());
+ const downloaded = await saveAndDownload(page, false);
+ const saved = testInfo.outputPath("grow-columns.pdf");
+ await downloaded.saveAs(saved);
+
+ await open(page, saved);
+ const reopened = await pageRuns(page);
+ expect(rightColumn(reopened)).toEqual(rightColumn(before));
+ expect(
+ reopened.find((run) => run.text.startsWith("Northern ferries"))?.text,
+ ).toMatch(/with\s+extra\s+cargo/);
+ expect(acrossGutter(reopened)).toEqual([]);
+});
diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-image-drag-lift.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-image-drag-lift.spec.ts
new file mode 100644
index 0000000000..4cb1646760
--- /dev/null
+++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-image-drag-lift.spec.ts
@@ -0,0 +1,264 @@
+import { test, expect } from "@editor/tests/helpers/stub-test-base";
+import type { Page } from "@playwright/test";
+import { openInTextEditor } from "@editor/tests/helpers/pdf-text-editor";
+
+// While an image is dragged, the page under its old spot shows what will be
+// there after the drop, never the image itself and never a blank patch.
+
+interface Fixture {
+ size: [number, number];
+ content: string;
+ /** Page-space box of the image's red ink. */
+ ink: { x: number; y: number; width: number; height: number };
+}
+
+const SMASK_W = 16;
+const SMASK_H = 6;
+
+// A red block in the middle of an image whose margins are transparent, as a
+// logo exported with its background removed.
+function smaskImage(): { rgb: string; alpha: string } {
+ let rgb = "";
+ let alpha = "";
+ for (let y = 0; y < SMASK_H; y++)
+ for (let x = 0; x < SMASK_W; x++) {
+ const ink = x >= 3 && x < 13 && y >= 1 && y < 5;
+ rgb += ink ? "\xcc\x10\x10" : "\xff\xff\xff";
+ alpha += ink ? "\xff" : "\x00";
+ }
+ return { rgb, alpha };
+}
+
+function inkOf(x: number, y: number, width: number, height: number) {
+ return {
+ x: x + (width * 3) / SMASK_W,
+ y: y + height / SMASK_H,
+ width: (width * 10) / SMASK_W,
+ height: (height * 4) / SMASK_H,
+ };
+}
+
+function buildPdf({ size, content }: Fixture): Buffer {
+ const { rgb, alpha } = smaskImage();
+ const icon = "\x10\x80\x10".repeat(16);
+ const stream = (dict: string, data: string) =>
+ `<< ${dict} /Length ${data.length} >>\nstream\n${data}\nendstream`;
+ const objects = [
+ "<< /Type /Catalog /Pages 2 0 R >>",
+ "<< /Type /Pages /Kids [3 0 R] /Count 1 >>",
+ `<< /Type /Page /Parent 2 0 R /MediaBox [0 0 ${size[0]} ${size[1]}] /Contents 4 0 R /Resources << /XObject << /Im 5 0 R /Ic 7 0 R >> /Font << /F1 8 0 R >> >> >>`,
+ stream("", content),
+ stream(
+ `/Type /XObject /Subtype /Image /Width ${SMASK_W} /Height ${SMASK_H} /ColorSpace /DeviceRGB /BitsPerComponent 8 /SMask 6 0 R`,
+ rgb,
+ ),
+ stream(
+ `/Type /XObject /Subtype /Image /Width ${SMASK_W} /Height ${SMASK_H} /ColorSpace /DeviceGray /BitsPerComponent 8`,
+ alpha,
+ ),
+ stream(
+ "/Type /XObject /Subtype /Image /Width 4 /Height 4 /ColorSpace /DeviceRGB /BitsPerComponent 8",
+ icon,
+ ),
+ "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica-Bold >>",
+ ];
+ let out = "%PDF-1.7\n";
+ const offsets = objects.map((body, i) => {
+ const at = out.length;
+ out += `${i + 1} 0 obj\n${body}\nendobj\n`;
+ return at;
+ });
+ const xref = out.length;
+ out += `xref\n0 ${objects.length + 1}\n0000000000 65535 f \n`;
+ for (const at of offsets) out += `${String(at).padStart(10, "0")} 00000 n \n`;
+ out += `trailer\n<< /Size ${objects.length + 1} /Root 1 0 R >>\nstartxref\n${xref}\n%%EOF`;
+ return Buffer.from(out, "latin1");
+}
+
+// The structure Microsoft Print To PDF writes: filled and stroked boxes as
+// paths, a large image with transparent margins, small icons each in a clip.
+const PRINT_TO_PDF: Fixture = {
+ size: [612, 792],
+ content: [
+ "0.93 0.95 0.98 rg 0 680 612 112 re f",
+ "0.2 0.3 0.5 RG 1 w 20 690 572 90 re S",
+ "1 1 1 rg 25 695 300 80 re f",
+ "q 184.6 0 0 55.2 31.8 707.9 cm /Im Do Q",
+ ...[
+ [520, 760],
+ [545, 760],
+ [60, 400],
+ ].map(
+ ([x, y]) =>
+ `q ${x} ${y} 14 14 re W n 18 0 0 18 ${x - 2} ${y - 2} cm /Ic Do Q`,
+ ),
+ ].join("\n"),
+ ink: inkOf(31.8, 707.9, 184.6, 55.2),
+};
+
+// Text under the ink, text over the image, on a tinted page, so a blank or
+// stale patch at the old spot cannot pass for the page beneath.
+const TEXT_UNDER: Fixture = {
+ size: [300, 300],
+ content: [
+ "0.85 0.9 1 rg 0 0 300 300 re f",
+ "BT /F1 28 Tf 0 0 0 rg 95 125 Td (UNDER) Tj ET",
+ "q 200 0 0 75 50 100 cm /Im Do Q",
+ "BT /F1 10 Tf 0 0 0 rg 216 150 Td (over) Tj ET",
+ ].join("\n"),
+ ink: inkOf(50, 100, 200, 75),
+};
+
+interface InkCounts {
+ red: number;
+ dark: number;
+ white: number;
+}
+
+// Pixel counts in the page canvas over page-space `box`, inset so edge
+// antialiasing does not count.
+function inkCounts(
+ page: Page,
+ pageSize: [number, number],
+ box: Fixture["ink"],
+): Promise<InkCounts> {
+ return page.evaluate(
+ ({ pageSize, box }) => {
+ const counts = { red: 0, dark: 0, white: 0 };
+ const canvas = document.querySelector<HTMLCanvasElement>(
+ '[data-testid="pdf-editor-page-0"] canvas',
+ );
+ if (!canvas?.width) return counts;
+ const k = canvas.width / pageSize[0];
+ const inset = 2;
+ const x = Math.round(box.x * k) + inset;
+ const y = Math.round((pageSize[1] - box.y - box.height) * k) + inset;
+ const w = Math.round(box.width * k) - 2 * inset;
+ const h = Math.round(box.height * k) - 2 * inset;
+ const data = canvas.getContext("2d")!.getImageData(x, y, w, h).data;
+ for (let i = 0; i < data.length; i += 4) {
+ const [r, g, b] = [data[i], data[i + 1], data[i + 2]];
+ if (r > 150 && g < 80 && b < 80) counts.red++;
+ if (r < 90 && g < 90 && b < 90) counts.dark++;
+ if (r > 250 && g > 250 && b > 250) counts.white++;
+ }
+ return counts;
+ },
+ { pageSize, box },
+ );
+}
+
+async function openFixture(page: Page, fixture: Fixture): Promise<void> {
+ await page.goto("/pdf-text-editor", { waitUntil: "domcontentloaded" });
+ await expect(page.getByTestId("pdf-editor-root")).toBeVisible({
+ timeout: 30_000,
+ });
+ await openInTextEditor(page, {
+ name: "image-drag.pdf",
+ mimeType: "application/pdf",
+ buffer: buildPdf(fixture),
+ });
+ await expect
+ .poll(async () => (await inkCounts(page, fixture.size, fixture.ink)).red, {
+ timeout: 60_000,
+ })
+ .toBeGreaterThan(0);
+}
+
+async function largestImageHandle(page: Page) {
+ const id = await page.evaluate(() => {
+ const images = (
+ window as unknown as {
+ __editor_store: {
+ state: {
+ pages: Array<{
+ images: Array<{ id: string; bounds: { width: number } }>;
+ }>;
+ };
+ };
+ }
+ ).__editor_store.state.pages[0].images;
+ return [...images].sort((a, b) => b.bounds.width - a.bounds.width)[0].id;
+ });
+ return page.getByTestId(`pdf-editor-image-${id}`);
+}
+
+function cssPerPoint(page: Page, fixture: Fixture): Promise<number> {
+ return page.evaluate(
+ (width) =>
+ document
+ .querySelector('[data-testid="pdf-editor-page-0"] canvas')!
+ .getBoundingClientRect().width / width,
+ fixture.size[0],
+ );
+}
+
+// Presses on the image and drags it `dyPt` points up the page, holding on.
+async function startDrag(page: Page, fixture: Fixture, dyPt: number) {
+ const handle = await largestImageHandle(page);
+ const box = (await handle.boundingBox())!;
+ // Near the left edge: text drawn over the middle takes presses there.
+ const from = { x: box.x + box.width * 0.05, y: box.y + box.height / 2 };
+ const dyCss = -dyPt * (await cssPerPoint(page, fixture));
+ await page.mouse.move(from.x, from.y);
+ await page.mouse.down();
+ await page.mouse.move(from.x, from.y + dyCss, { steps: 12 });
+ await expect(page.getByTestId("pdf-editor-image-ghost")).toBeAttached();
+}
+
+for (const [name, fixture, dy] of [
+ ["a Print To PDF page", PRINT_TO_PDF, -100],
+ ["text under the image", TEXT_UNDER, 80],
+] as const) {
+ test.describe(`PDF text editor: dragging an image over ${name}`, () => {
+ test("shows the page beneath the old spot, then the image where it is dropped", async ({
+ page,
+ }) => {
+ await openFixture(page, fixture);
+ const before = await inkCounts(page, fixture.size, fixture.ink);
+ await startDrag(page, fixture, dy);
+
+ await expect
+ .poll(
+ async () => (await inkCounts(page, fixture.size, fixture.ink)).red,
+ )
+ .toBe(0);
+ const during = await inkCounts(page, fixture.size, fixture.ink);
+ if (fixture === TEXT_UNDER) {
+ expect(before.dark).toBe(0);
+ expect(during.dark).toBeGreaterThan(0);
+ expect(during.white).toBe(0);
+ } else {
+ expect(during.white).toBeGreaterThan(0);
+ }
+
+ await page.mouse.up();
+ await expect(page.getByTestId("pdf-editor-image-ghost")).toHaveCount(0, {
+ timeout: 30_000,
+ });
+ expect((await inkCounts(page, fixture.size, fixture.ink)).red).toBe(0);
+ const moved = { ...fixture.ink, y: fixture.ink.y + dy };
+ expect((await inkCounts(page, fixture.size, moved)).red).toBeGreaterThan(
+ 0,
+ );
+ });
+
+ test("puts the image back when Escape cancels the drag", async ({
+ page,
+ }) => {
+ await openFixture(page, fixture);
+ const before = await inkCounts(page, fixture.size, fixture.ink);
+ await startDrag(page, fixture, dy);
+ await expect
+ .poll(
+ async () => (await inkCounts(page, fixture.size, fixture.ink)).red,
+ )
+ .toBe(0);
+ await page.keyboard.press("Escape");
+ await expect(page.getByTestId("pdf-editor-image-ghost")).toHaveCount(0);
+ expect(await inkCounts(page, fixture.size, fixture.ink)).toEqual(before);
+ await page.mouse.up();
+ expect(await inkCounts(page, fixture.size, fixture.ink)).toEqual(before);
+ });
+ });
+}
diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-known-issues.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-known-issues.spec.ts
index 6de68a48a5..07a0ff2f5d 100644
--- a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-known-issues.spec.ts
+++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-known-issues.spec.ts
@@ -9,6 +9,7 @@ import type { EditorTestWindow } from "@editor/tests/stubbed/editorTestTypes";
import { waitForEditorReady } from "@editor/tests/stubbed/editorReady";
import {
downloadBytes,
+ reopenSavedBytes,
saveAndDownload,
} from "@editor/tests/stubbed/saveHelpers";
@@ -275,15 +276,7 @@ test.describe("PDF text editor - fixed-issue regressions", () => {
// it is dropped and the save-risk modal always gates the save.
const saved = await downloadBytes(await saveAndDownload(page, true));
- await openInTextEditor(page, {
- name: "emoji-round-trip.pdf",
- mimeType: "application/pdf",
- buffer: saved,
- });
- await expect(
- page.locator('[data-testid^="pdf-editor-run-p1-"]').first(),
- ).toBeVisible({ timeout: 30_000 });
- await page.waitForTimeout(500);
+ await reopenSavedBytes(page, saved, "emoji-round-trip.pdf", 1);
const reopened = await page.evaluate(() => {
const s = (window as unknown as EditorTestWindow).__editor_store;
diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-live-wrap.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-live-wrap.spec.ts
new file mode 100644
index 0000000000..973a4fa2ba
--- /dev/null
+++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-live-wrap.spec.ts
@@ -0,0 +1,276 @@
+import { test, expect } from "@editor/tests/helpers/stub-test-base";
+import type { Page } from "@playwright/test";
+import path from "path";
+import { selectWrapWidthMode } from "@editor/tests/stubbed/widthModeHelpers";
+import { openInTextEditor } from "@editor/tests/helpers/pdf-text-editor";
+
+// Typing on past the right edge of a box has to break the line on the
+// keystroke that crosses it, while the user keeps typing: text never slides
+// sideways inside the box, never hides past its edge, and the caret follows
+// the letters onto the new line without jumping back.
+
+const PARAGRAPH_PDF = path.join(
+ import.meta.dirname,
+ "../test-fixtures/paragraph-sample.pdf",
+);
+
+const TYPED =
+ " and this sentence keeps going far beyond the right edge of the page so " +
+ "that it has to wrap onto new lines and keep going";
+
+interface Frame {
+ inputs: number;
+ domLetters: string;
+ model: string;
+ domLines: number;
+ caretAtEnd: boolean;
+ caret: { x: number; y: number } | null;
+ glyphRight: number | null;
+ glyphChar: string | null;
+ boxRight: number;
+ boxBottom: number;
+ pageRight: number;
+ scrolled: number;
+}
+
+interface EditorWindow {
+ __editor_store: {
+ state: { pages: { runs: { id: string; text: string }[] }[] };
+ };
+ __liveWrapFrames: Frame[];
+}
+
+async function open(page: Page, mode: "grow" | "wrap"): Promise<void> {
+ await page.goto("/pdf-text-editor", { waitUntil: "domcontentloaded" });
+ await expect(page.getByTestId("pdf-editor-root")).toBeVisible({
+ timeout: 30_000,
+ });
+ await openInTextEditor(page, PARAGRAPH_PDF);
+ await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
+ timeout: 60_000,
+ });
+ if (mode === "wrap") await selectWrapWidthMode(page);
+}
+
+async function focusEndOfHeading(page: Page): Promise<string> {
+ const heading = page
+ .locator('[data-testid^="pdf-editor-run-"]')
+ .filter({ hasText: /^Heading/ })
+ .first();
+ await expect(heading).toBeVisible({ timeout: 30_000 });
+ await heading.click();
+ await expect(heading).toBeFocused();
+ const testId = (await heading.getAttribute("data-testid")) ?? "";
+ await page.evaluate((id) => {
+ const el = document.querySelector<HTMLElement>(`[data-testid="${id}"]`)!;
+ const selection = window.getSelection()!;
+ selection.selectAllChildren(el);
+ selection.collapseToEnd();
+ }, testId);
+ return testId;
+}
+
+/** Records, on the frame after every input, what the user sees in the box. */
+function recordFrames(page: Page, testId: string): Promise<void> {
+ return page.evaluate((id) => {
+ const w = window as unknown as EditorWindow;
+ const el = document.querySelector<HTMLElement>(`[data-testid="${id}"]`)!;
+ const runId = el.dataset.runId;
+ const frames: Frame[] = [];
+ w.__liveWrapFrames = frames;
+ let inputs = 0;
+ const lineCount = () => el.innerText.replace(/\n$/, "").split("\n").length;
+ el.addEventListener("input", () => {
+ inputs += 1;
+ const n = inputs;
+ requestAnimationFrame(() => {
+ // A key handled before this frame was drawn makes it that key's frame:
+ // the user never saw this one. Engines differ in how often that is.
+ if (n !== inputs) return;
+ const selection = window.getSelection()!;
+ const box = el.getBoundingClientRect();
+ let caret: Frame["caret"] = null;
+ let glyphRight: number | null = null;
+ let glyphChar: string | null = null;
+ let caretAtEnd = false;
+ if (selection.rangeCount && el.contains(selection.focusNode)) {
+ const at = selection.getRangeAt(0).cloneRange();
+ at.collapse(false);
+ const rects = at.getClientRects();
+ const r = rects.length ? rects[0] : at.getBoundingClientRect();
+ caret = { x: r.x, y: r.y };
+ const rest = document.createRange();
+ rest.setStart(at.endContainer, at.endOffset);
+ rest.setEnd(el, el.childNodes.length);
+ caretAtEnd = rest.toString() === "";
+ const node = selection.focusNode!;
+ const offset = selection.focusOffset;
+ if (node.nodeType === Node.TEXT_NODE && offset > 0) {
+ const glyph = document.createRange();
+ glyph.setStart(node, offset - 1);
+ glyph.setEnd(node, offset);
+ glyphRight = glyph.getBoundingClientRect().right;
+ glyphChar = (node.textContent ?? "")[offset - 1];
+ }
+ }
+ const run = w.__editor_store.state.pages
+ .flatMap((p) => p.runs)
+ .find((r) => r.id === runId);
+ frames.push({
+ inputs: n,
+ domLetters: (el.textContent ?? "").replace(/\s/g, ""),
+ model: run?.text ?? "",
+ domLines: lineCount(),
+ caretAtEnd,
+ caret,
+ glyphRight,
+ glyphChar,
+ boxRight: box.right,
+ boxBottom: box.bottom,
+ pageRight: el
+ .closest("[data-testid^='pdf-editor-page-']")!
+ .getBoundingClientRect().right,
+ scrolled: el.scrollLeft + el.scrollTop,
+ });
+ });
+ });
+ }, testId);
+}
+
+// Holds the main thread for `frameMs` of every frame, as a slow machine does,
+// so the engine's re-measure lands several keystrokes after the letters it
+// measures.
+function slowFrames(page: Page, frameMs: number): Promise<void> {
+ return page.evaluate((ms) => {
+ const busy = () => {
+ const until = performance.now() + ms;
+ while (performance.now() < until);
+ requestAnimationFrame(busy);
+ };
+ requestAnimationFrame(busy);
+ }, frameMs);
+}
+
+async function typeAndRecord(
+ page: Page,
+ mode: "grow" | "wrap",
+ delay: number,
+ frameMs: number,
+): Promise<{ frames: Frame[]; startText: string; fontPx: number }> {
+ await open(page, mode);
+ const testId = await focusEndOfHeading(page);
+ const box = page.getByTestId(testId);
+ const startText = (await box.innerText()).replace(/\n$/, "");
+ const fontPx = parseFloat(
+ await box.evaluate((el) => getComputedStyle(el).fontSize),
+ );
+ await recordFrames(page, testId);
+ if (frameMs > 0) await slowFrames(page, frameMs);
+ await page.keyboard.type(TYPED, { delay });
+ await expect
+ .poll(
+ () =>
+ page.evaluate(
+ () =>
+ (window as unknown as EditorWindow).__liveWrapFrames.at(-1)
+ ?.inputs ?? 0,
+ ),
+ { timeout: 30_000 },
+ )
+ .toBe(TYPED.length);
+ const frames = await page.evaluate(
+ () => (window as unknown as EditorWindow).__liveWrapFrames,
+ );
+ return { frames, startText, fontPx };
+}
+
+function check(
+ frames: Frame[],
+ startText: string,
+ fontPx: number,
+ mode: "grow" | "wrap",
+): void {
+ const flat = (s: string) => s.replace(/\s+/g, " ");
+ const startLines = startText.split("\n").length;
+ // The box draws the PDF's advances only once the engine has re-measured the
+ // typed letters; until then they sit on the browser's, which can run a few
+ // pixels wider than the PDF's, so for the key before the PDF wraps the box
+ // can widen that far past its edge to show them.
+ const slack = fontPx * 0.5;
+ let crossedAt: Frame | null = null;
+ let brokeAt: Frame | null = null;
+ let previousCaret: Frame["caret"] = null;
+ for (const f of frames) {
+ const typed = startText + TYPED.slice(0, f.inputs);
+ const where = `after key ${f.inputs} (${JSON.stringify(TYPED[f.inputs - 1])})`;
+ expect(f.domLetters, `box text ${where}`).toBe(typed.replace(/\s/g, ""));
+ expect(flat(f.model), `model text ${where}`).toBe(flat(typed));
+ expect(f.caretAtEnd, `caret at the end of the text ${where}`).toBe(true);
+ expect(f.scrolled, `box scrolled sideways ${where}`).toBe(0);
+ const edge = mode === "grow" ? f.pageRight : frames[0].boxRight;
+ expect(f.boxRight, `box widened past its edge ${where}`).toBeLessThan(
+ edge + slack,
+ );
+ const letter = f.glyphChar !== null && f.glyphChar.trim() !== "";
+ if (letter && f.glyphRight !== null) {
+ if (!crossedAt && f.glyphRight > f.boxRight + 0.5) crossedAt = f;
+ expect(f.glyphRight, `last letter past the box ${where}`).toBeLessThan(
+ f.boxRight + slack,
+ );
+ expect(f.caret!.x, `caret past the box ${where}`).toBeLessThan(
+ f.boxRight + slack,
+ );
+ }
+ if (f.caret) {
+ expect(f.caret.y, `caret below the box ${where}`).toBeLessThan(
+ f.boxBottom,
+ );
+ if (previousCaret) {
+ const sameLine = Math.abs(f.caret.y - previousCaret.y) <= 2;
+ const forward = sameLine
+ ? f.caret.x >= previousCaret.x - 1
+ : f.caret.y > previousCaret.y;
+ expect(
+ forward,
+ `caret moved backwards ${where}: ${JSON.stringify(previousCaret)} -> ${JSON.stringify(f.caret)}`,
+ ).toBe(true);
+ }
+ previousCaret = f.caret;
+ }
+ if (!brokeAt && f.domLines > startLines) brokeAt = f;
+ }
+ expect(brokeAt, "the line never broke while typing").not.toBeNull();
+ const crossing =
+ crossedAt && crossedAt.inputs < brokeAt!.inputs ? crossedAt : brokeAt!;
+ // Counted in drawn frames, not keys: a key that lands before its frame is
+ // drawn leaves no frame for the user to see the line unbroken in.
+ expect(
+ frames.filter(
+ (f) => f.inputs > crossing.inputs && f.inputs < brokeAt!.inputs,
+ ).length,
+ "frames drawn between crossing the edge and the line break",
+ ).toBe(0);
+}
+
+test.describe("Typing past the box edge wraps on the crossing keystroke", () => {
+ test.setTimeout(120_000);
+ const paces = [
+ { delay: 25, frameMs: 0 },
+ { delay: 90, frameMs: 0 },
+ { delay: 25, frameMs: 28 },
+ ];
+ for (const mode of ["grow", "wrap"] as const) {
+ for (const { delay, frameMs } of paces) {
+ const pace = frameMs ? `, ${frameMs}ms frames` : "";
+ test(`${mode}, ${delay}ms per key${pace}`, async ({ page }) => {
+ const { frames, startText, fontPx } = await typeAndRecord(
+ page,
+ mode,
+ delay,
+ frameMs,
+ );
+ check(frames, startText, fontPx, mode);
+ });
+ }
+ }
+});
diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-multi-run-undo.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-multi-run-undo.spec.ts
index 08e164fd23..da73446ed3 100644
--- a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-multi-run-undo.spec.ts
+++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-multi-run-undo.spec.ts
@@ -112,13 +112,13 @@ test.describe("PDF text editor - a restyle of many runs is one undo step", () =>
const picker = page.getByTestId("pdf-editor-font-family");
await picker.click();
- await page.getByRole("option", { name: "Helvetica", exact: true }).click();
+ await page.getByRole("option", { name: "Times", exact: true }).click();
await page.waitForTimeout(2500);
// Sanity: the change has to have landed, or the undo assertion is vacuous.
const changed = await runsInModel(page);
expect(
- changed.filter((r) => /helvetica/i.test(r.fontId)).length,
+ changed.filter((r) => /times/i.test(r.fontId)).length,
"the font change did not apply",
).toBeGreaterThan(1);
diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-reopen.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-reopen.spec.ts
new file mode 100644
index 0000000000..e8028abac1
--- /dev/null
+++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-reopen.spec.ts
@@ -0,0 +1,55 @@
+import fs from "fs";
+import path from "path";
+import type { Page } from "@playwright/test";
+import { test, expect } from "@editor/tests/helpers/stub-test-base";
+import type { EditorStore } from "@editor/tools/pdfTextEditor/store/EditorStore";
+import { waitForEditorReady } from "@editor/tests/stubbed/editorReady";
+import { reopenSavedBytes } from "@editor/tests/stubbed/saveHelpers";
+
+const SAMPLE = path.join(import.meta.dirname, "../test-fixtures/sample.pdf");
+const REOPENS = 25;
+const HEAP_GROWTH_LIMIT = 32 * 1024 * 1024; // 32 MB
+
+type EditorWindow = Window & { __editor_store: EditorStore };
+
+const wasmHeapBytes = (page: Page) =>
+ page.evaluate(() => {
+ const doc = (window as unknown as EditorWindow).__editor_store.document;
+ const exports = doc?.module.pdfium.wasmExports as unknown as
+ | { memory: WebAssembly.Memory }
+ | undefined;
+ return exports?.memory.buffer.byteLength ?? 0;
+ });
+
+test.describe("PDF text editor - reopening files in one tab", () => {
+ test.setTimeout(240_000);
+
+ test("survives reopening the same file many times with the heap bounded", async ({
+ page,
+ }) => {
+ const bytes = fs.readFileSync(SAMPLE);
+ const crash = new Promise<never>((_, reject) =>
+ page.once("crash", () => reject(new Error("the tab crashed"))),
+ );
+ const open = (name: string) =>
+ Promise.race([
+ reopenSavedBytes(page, bytes, name).then(() =>
+ waitForEditorReady(page),
+ ),
+ crash,
+ ]);
+ await page.goto("/pdf-text-editor", { waitUntil: "domcontentloaded" });
+
+ await open("sample.pdf");
+ const firstHeap = await wasmHeapBytes(page);
+
+ for (let reopen = 1; reopen <= REOPENS; reopen++) {
+ await open(`sample-${reopen}.pdf`);
+ }
+
+ await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible();
+ expect(await wasmHeapBytes(page)).toBeLessThan(
+ firstHeap + HEAP_GROWTH_LIMIT,
+ );
+ });
+});
diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-run-grips.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-run-grips.spec.ts
new file mode 100644
index 0000000000..e62660b04c
--- /dev/null
+++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-run-grips.spec.ts
@@ -0,0 +1,283 @@
+import { test, expect } from "@editor/tests/helpers/stub-test-base";
+import type { Page } from "@playwright/test";
+import path from "path";
+import type { EditorTestWindow } from "@editor/tests/stubbed/editorTestTypes";
+import { waitForEditorReady } from "@editor/tests/stubbed/editorReady";
+import { openInTextEditor } from "@editor/tests/helpers/pdf-text-editor";
+
+// Every click on a run's text places the caret; the move frame and the width
+// handle sit just outside the box, so they never compete with the text.
+
+const SAMPLE = path.join(
+ import.meta.dirname,
+ "../test-fixtures/paragraph-sample.pdf",
+);
+const RUN = "p0-t0";
+// paragraph-sample's runs keep their lines under an explicit width, so the
+// rewrap is checked on a run the reflow does re-break.
+const REWRAP_SAMPLE = path.join(
+ import.meta.dirname,
+ "../../../../../public/samples/Sample.pdf",
+);
+
+async function open(page: Page, file = SAMPLE): Promise<void> {
+ await page.goto("/pdf-text-editor", { waitUntil: "domcontentloaded" });
+ await expect(page.getByTestId("pdf-editor-root")).toBeVisible({
+ timeout: 30_000,
+ });
+ await openInTextEditor(page, file);
+ await waitForEditorReady(page, 60_000);
+ await expect(
+ page.locator('[data-testid^="pdf-editor-run-p0-"]').first(),
+ ).toBeVisible({
+ timeout: 30_000,
+ });
+}
+
+interface Bounds {
+ x: number;
+ y: number;
+ width: number;
+ text: string;
+}
+
+function boundsOf(page: Page, runId = RUN): Promise<Bounds> {
+ return page.evaluate((id: string) => {
+ const run = (window as unknown as EditorTestWindow).__editor_store.doc
+ .page(0)
+ .runs.find((r) => r.id === id);
+ if (!run) throw new Error(`run ${id} not found`);
+ return {
+ x: run.bounds.x,
+ y: run.bounds.y,
+ width: run.bounds.width,
+ text: run.text,
+ };
+ }, runId);
+}
+
+async function boxOf(page: Page, runId = RUN) {
+ const box = await page.getByTestId(`pdf-editor-run-${runId}`).boundingBox();
+ if (!box) throw new Error("run has no box");
+ return box;
+}
+
+function charRect(page: Page, index: number) {
+ return page.evaluate(
+ ({ id, index }) => {
+ const el = document.querySelector(
+ `[data-testid="pdf-editor-run-${id}"]`,
+ )!;
+ const walker = document.createTreeWalker(el, NodeFilter.SHOW_TEXT);
+ let seen = 0;
+ for (let node = walker.nextNode(); node; node = walker.nextNode()) {
+ const length = node.textContent?.length ?? 0;
+ if (index < seen + length) {
+ const range = document.createRange();
+ range.setStart(node, index - seen);
+ range.setEnd(node, index - seen + 1);
+ const r = range.getBoundingClientRect();
+ return { left: r.left, right: r.right, width: r.width };
+ }
+ seen += length;
+ }
+ throw new Error(`no character ${index}`);
+ },
+ { id: RUN, index },
+ );
+}
+
+function caretOffset(page: Page): Promise<number | null> {
+ return page.evaluate((id: string) => {
+ const el = document.querySelector(`[data-testid="pdf-editor-run-${id}"]`);
+ const sel = window.getSelection();
+ if (!el || document.activeElement !== el) return null;
+ if (!sel?.focusNode || !el.contains(sel.focusNode)) return null;
+ const range = document.createRange();
+ range.setStart(el, 0);
+ range.setEnd(sel.focusNode, sel.focusOffset);
+ return range.toString().length;
+ }, RUN);
+}
+
+function gripAt(page: Page, at: { x: number; y: number }) {
+ return page.evaluate(
+ ({ x, y }) =>
+ document.elementFromPoint(x, y)?.getAttribute("data-grip") ?? null,
+ at,
+ );
+}
+
+function moveBandCentre(page: Page, edge: "bottom" | "left", runId = RUN) {
+ return page.evaluate(
+ ({ edge, runId }) => {
+ const bands = [
+ ...document.querySelectorAll(
+ `[data-testid="pdf-editor-grips-${runId}"] [data-grip="move"]`,
+ ),
+ ].map((band) => band.getBoundingClientRect());
+ if (bands.length === 0) return null;
+ const band = bands.reduce((best, rect) =>
+ edge === "bottom"
+ ? rect.top > best.top
+ ? rect
+ : best
+ : rect.right < best.right
+ ? rect
+ : best,
+ );
+ const centre = {
+ x: band.left + band.width / 2,
+ y: band.top + band.height / 2,
+ };
+ return document
+ .elementFromPoint(centre.x, centre.y)
+ ?.getAttribute("data-grip") === "move"
+ ? centre
+ : null;
+ },
+ { edge, runId },
+ );
+}
+
+async function clickAndExpectCaret(
+ page: Page,
+ x: number,
+ y: number,
+ offset: number,
+): Promise<void> {
+ const before = await boundsOf(page);
+ await page.mouse.click(x, y);
+ await expect.poll(() => caretOffset(page), { timeout: 10_000 }).toBe(offset);
+ const after = await boundsOf(page);
+ expect(after.x).toBeCloseTo(before.x, 1);
+ expect(after.y).toBeCloseTo(before.y, 1);
+ await page.keyboard.press("Escape");
+}
+
+test.describe("PDF text editor - run grips", () => {
+ test("clicks on the text place the caret instead of starting a drag", async ({
+ page,
+ }) => {
+ await open(page);
+ const { text } = await boundsOf(page);
+ const last = text.trimEnd().length - 1;
+ const box = await boxOf(page);
+
+ const fifth = await charRect(page, 5);
+ await clickAndExpectCaret(
+ page,
+ fifth.left + fifth.width * 0.75,
+ box.y + box.height - 2,
+ 6,
+ );
+
+ const lastChar = await charRect(page, last);
+ await clickAndExpectCaret(
+ page,
+ lastChar.left + lastChar.width * 0.75,
+ box.y + box.height / 2,
+ last + 1,
+ );
+ await clickAndExpectCaret(
+ page,
+ lastChar.right + 2,
+ box.y + box.height / 2,
+ last + 1,
+ );
+ });
+
+ test("dragging just outside the bottom or left edge moves the box", async ({
+ page,
+ }) => {
+ await open(page);
+ for (const edge of ["bottom", "left"] as const) {
+ const before = await boundsOf(page);
+ const box = await boxOf(page);
+ await page.mouse.move(box.x + box.width / 2, box.y + box.height / 2);
+ // The frame appears on hover. Leaving the box before it is drawn leaves
+ // nothing to grab, and the press then starts a marquee instead.
+ await expect(page.getByTestId(`pdf-editor-grips-${RUN}`)).toBeVisible();
+ // Aim at the middle of the band as drawn: a point fixed from the box
+ // rect sits under 2 px inside the band and misses it when the box and
+ // frame lay out a pixel apart.
+ let start = { x: 0, y: 0 };
+ await expect
+ .poll(async () => {
+ const centre = await moveBandCentre(page, edge);
+ if (centre) start = centre;
+ return centre !== null;
+ })
+ .toBe(true);
+ await page.mouse.move(start.x, start.y, { steps: 4 });
+ await expect
+ .poll(() => gripAt(page, start), { timeout: 10_000 })
+ .toBe("move");
+ await page.mouse.down();
+ await page.mouse.move(start.x + 40, start.y + 30, { steps: 8 });
+ await page.mouse.up();
+ await expect
+ .poll(async () => (await boundsOf(page)).x - before.x, {
+ timeout: 10_000,
+ })
+ .toBeGreaterThan(20);
+ const after = await boundsOf(page);
+ expect(after.text).toBe(before.text);
+ }
+ });
+
+ test("the width handle shows only while the box is selected or hovered", async ({
+ page,
+ }) => {
+ await open(page);
+ const handle = page.getByTestId(`pdf-editor-width-handle-${RUN}`);
+ await page.mouse.move(5, 5);
+ await expect(handle).toHaveCount(0);
+
+ const box = await boxOf(page);
+ await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2);
+ await page.mouse.move(5, 5);
+ await expect(handle).toBeVisible();
+ const h = await handle.boundingBox();
+ const b = await boxOf(page);
+ expect(h!.x).toBeGreaterThanOrEqual(b.x + b.width - 1);
+ expect(h!.y + h!.height / 2).toBeCloseTo(b.y + b.height / 2, 0);
+ await expect(handle).toHaveAttribute(
+ "aria-label",
+ "Drag to change the width; the text rewraps",
+ );
+ });
+
+ test("dragging the width handle narrows the box and rewraps the text", async ({
+ page,
+ }) => {
+ await open(page, REWRAP_SAMPLE);
+ const id = await page.evaluate(
+ () =>
+ (window as unknown as EditorTestWindow).__editor_store.doc
+ .page(0)
+ .runs.find((r) => /Open Source/.test(r.text))?.id ?? "",
+ );
+ const before = await boundsOf(page, id);
+ const box = await boxOf(page, id);
+ await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2);
+ const handle = page.getByTestId(`pdf-editor-width-handle-${id}`);
+ await expect(handle).toBeVisible();
+ const h = (await handle.boundingBox())!;
+ await page.mouse.move(h.x + h.width / 2, h.y + h.height / 2);
+ await page.mouse.down();
+ await page.mouse.move(box.x + box.width * 0.5, h.y + h.height / 2, {
+ steps: 10,
+ });
+ await page.mouse.up();
+
+ await expect
+ .poll(async () => (await boundsOf(page, id)).text, { timeout: 10_000 })
+ .toContain("\n");
+ const after = await boundsOf(page, id);
+ expect(after.width).toBeLessThan(before.width);
+ expect(after.text.split(/\s+/).filter(Boolean)).toEqual(
+ before.text.split(/\s+/).filter(Boolean),
+ );
+ });
+});
diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-scanned-ocr.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-scanned-ocr.spec.ts
index 92ca3bb94e..93d74a3eef 100644
--- a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-scanned-ocr.spec.ts
+++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-scanned-ocr.spec.ts
@@ -193,18 +193,23 @@ async function open(page: Page, file: string | Buffer): Promise<void> {
await settle(page);
}
-// The target line's band on the canvas, from its DOM overlay box.
-async function lineBox(page: Page, runId: string): Promise<Box> {
+// The target run's band on the canvas, from its DOM overlay box; with `line`,
+// only that line of the run.
+async function lineBox(page: Page, runId: string, line?: number): Promise<Box> {
return page.evaluate(
- ({ tid, id }) => {
+ ({ tid, id, line }) => {
const c = Array.from(
document.querySelectorAll<HTMLCanvasElement>(
`[data-testid="${tid}"] canvas`,
),
).find((x) => x.width > 0 && x.height > 0)!;
- const el = document.querySelector<HTMLElement>(
+ const run = document.querySelector<HTMLElement>(
`[data-testid="pdf-editor-run-${id}"]`,
)!;
+ const el =
+ line === undefined
+ ? run
+ : run.querySelector<HTMLElement>(`[data-pdf-editor-line="${line}"]`)!;
const cr = c.getBoundingClientRect();
const er = el.getBoundingClientRect();
const k = c.width / cr.width;
@@ -215,7 +220,7 @@ async function lineBox(page: Page, runId: string): Promise<Box> {
y1: Math.round((er.bottom - cr.bottom + cr.height) * k),
};
},
- { tid: PAGE_TESTID, id: runId },
+ { tid: PAGE_TESTID, id: runId, line },
);
}
@@ -350,9 +355,9 @@ for (const fixture of ["scanned-ocr-hocr.pdf", "scanned-ocr-sandwich.pdf"]) {
});
}
-// Tight 11/13pt leading: the cover must span both OCR lines of the block yet
-// stop short of the next block's ascenders.
-test("a word edit in a scanned OCR paragraph covers the block and spares the next line", async ({
+// Tight leading: the cover must span the edited line of the paragraph yet
+// stop short of the ascenders of the line below it.
+test("a word edit in a scanned OCR paragraph covers its line and spares the next line", async ({
page,
}) => {
test.setTimeout(120_000);
@@ -361,13 +366,15 @@ test("a word edit in a scanned OCR paragraph covers the block and spares the nex
timeout: 30_000,
});
await open(page, "scanned-ocr-paragraph.pdf");
- const all = await runs(page);
- const block = all.find((r) => r.text.includes("fourteen"));
- const next = all.find((r) => r.text.startsWith("date. Payment"));
- expect(block && next, "OCR grouping changed").toBeTruthy();
- const band = await lineBox(page, block!.id);
- // The DOM boxes overlap by a few rows that hold this block's descenders.
- const nextBand = { ...(await lineBox(page, next!.id)), y0: band.y1 + 1 };
+ const block = (await runs(page)).find((r) => r.text.includes("fourteen"));
+ expect(
+ block?.text.split("\n").map((l) => l.split(" ")[0]),
+ "OCR grouping changed",
+ ).toEqual(["This", "will", "date.", "interest"]);
+ const firstLine = await lineBox(page, block!.id, 0);
+ const band = await lineBox(page, block!.id, 1);
+ // The DOM line boxes overlap by a few rows that hold the edited line's descenders.
+ const nextBand = { ...(await lineBox(page, block!.id, 2)), y0: band.y1 + 1 };
await snap(page, "loaded");
await replaceRunText(
@@ -379,20 +386,15 @@ test("a word edit in a scanned OCR paragraph covers the block and spares the nex
const edited = (await runs(page)).find((r) => r.id === block!.id)!;
expect(edited.text).toContain("twenty-one");
- // The block's first line is untouched and keeps its scanned pixels.
- const firstLine = {
- ...band,
- y1: band.y0 + Math.round((band.y1 - band.y0) * 0.35),
- };
expect(
await diff(page, "loaded", "edited", firstLine),
"the unchanged first line was redrawn",
).toBe(0);
expect(
await diff(page, "loaded", "edited", band),
- "the block did not change on screen",
+ "the edited line did not change on screen",
).toBeGreaterThan(500);
- // New descenders may dip into the next box; erased scan ink may not.
+ // New descenders may dip into the next line; erased scan ink may not.
expect(
await diff(page, "loaded", "edited", nextBand, true),
"the cover erased part of the next OCR line",
@@ -557,7 +559,7 @@ test("Enter in a scanned block moves later text down a line, Backspace rejoins i
}) => {
test.setTimeout(120_000);
await openForm(page);
- const addr = (await runs(page)).find((r) => r.text.startsWith("12-4"))!;
+ const addr = (await runs(page)).find((r) => r.text.includes("\n12-4"))!;
await snap(page, "loaded");
const loadedSig = await bitmapSig(page);
@@ -566,7 +568,7 @@ test("Enter in a scanned block moves later text down a line, Backspace rejoins i
await settle(page, loadedSig);
await snap(page, "split");
const split = (await runs(page)).find((r) => r.id === addr.id)!;
- expect(split.text.split("\n")).toHaveLength(3);
+ expect(split.text.split("\n")).toHaveLength(addr.text.split("\n").length + 1);
// "EASTPORT" left the first line, and the TEL line now sits a row lower.
expect(
await diff(
@@ -647,8 +649,8 @@ test("deleting a scanned line hides it, and undo brings the scan back", async ({
expect(await diff(page, "loaded", "undone")).toBeLessThan(20);
});
-// Dragging a scanned block's frame: the scan is covered where it was and the
-// text is drawn where it was dropped.
+// Dragging a scanned block by the move grip just above its frame: the scan is
+// covered where it was and the text is drawn where it was dropped.
test("dragging a scanned block moves its text off the scan", async ({
page,
}) => {
@@ -660,9 +662,10 @@ test("dragging a scanned block moves its text off the scan", async ({
.getByTestId(`pdf-editor-run-${north.id}`)
.boundingBox())!;
const loadedSig = await bitmapSig(page);
- await page.mouse.move(box.x + box.width / 2, box.y + 2);
+ await page.mouse.move(box.x + box.width / 2, box.y + box.height / 2);
+ await page.mouse.move(box.x + box.width / 2, box.y - 3, { steps: 4 });
await page.mouse.down();
- await page.mouse.move(box.x + box.width / 2 + 120, box.y + 2, { steps: 8 });
+ await page.mouse.move(box.x + box.width / 2 + 120, box.y - 3, { steps: 8 });
await page.mouse.up();
await settle(page, loadedSig);
await snap(page, "moved");
diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-shapes.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-shapes.spec.ts
index 1576602fe4..ab2c1f275d 100644
--- a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-shapes.spec.ts
+++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-shapes.spec.ts
@@ -2,18 +2,59 @@ import { test, expect } from "@editor/tests/helpers/stub-test-base";
import { openInTextEditor } from "@editor/tests/helpers/pdf-text-editor";
import type { Page } from "@playwright/test";
import path from "path";
+import {
+ buildClassicPdf,
+ streamBody,
+} from "@editor/tools/pdfTextEditor/__tests__/pdfFixtures";
/**
* Vector shapes: what a delete or move leaves in the SAVED file, not just on
- * screen. PDFium writes back a form XObject child's removal but not its new
- * paint or position, so shapes inside a form are deleted at save time and are
- * not movable; the sample keeps most of its shapes in one such form.
+ * screen. PDFium does not write back a form XObject child's new position, so
+ * a shape inside a form is not movable, and deleting one first puts its form's
+ * contents onto the page. The sample's forms are transparency groups drawn at
+ * a page opacity that their own graphics states would replace once lifted, so
+ * deleting a shape in one is refused; the deletes that go through use a form
+ * drawn twice with nothing of its own but paths.
*/
const SAMPLE = path.join(
import.meta.dirname,
"../../../../../public/samples/Sample.pdf",
);
+const INSTANCE_OFFSET = 200;
+
+const TWICE_DRAWN_FORM = {
+ name: "twice-drawn-form.pdf",
+ mimeType: "application/pdf",
+ buffer: Buffer.from(
+ buildClassicPdf(
+ [
+ { num: 1, body: "<< /Type /Catalog /Pages 2 0 R >>" },
+ { num: 2, body: "<< /Type /Pages /Kids [3 0 R] /Count 1 >>" },
+ {
+ num: 3,
+ body: "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 400 300] /Contents 4 0 R /Resources << /XObject << /Fm 5 0 R >> >> >>",
+ },
+ {
+ num: 4,
+ body: streamBody(
+ "",
+ `q 1 0 0 1 20 40 cm /Fm Do Q q 1 0 0 1 ${20 + INSTANCE_OFFSET} 40 cm /Fm Do Q`,
+ ),
+ },
+ {
+ num: 5,
+ body: streamBody(
+ "/Type /XObject /Subtype /Form /BBox [0 0 160 200]",
+ "0 0 1 rg 0 0 160 120 re f 1 0 0 rg 20 140 80 40 re f",
+ ),
+ },
+ ],
+ 1,
+ ),
+ ),
+};
+
interface Rect {
x: number;
y: number;
@@ -48,12 +89,12 @@ async function openPdf(page: Page, file: PdfFile): Promise<void> {
await page.waitForTimeout(1500);
}
-async function openSample(page: Page): Promise<void> {
+async function openInEditor(page: Page, file: PdfFile = SAMPLE): Promise<void> {
await page.goto("/pdf-text-editor", { waitUntil: "domcontentloaded" });
await expect(page.getByTestId("pdf-editor-root")).toBeVisible({
timeout: 30_000,
});
- await openPdf(page, SAMPLE);
+ await openPdf(page, file);
}
async function saveAndReopen(page: Page): Promise<void> {
@@ -143,6 +184,11 @@ async function dragBy(
await page.waitForTimeout(500);
}
+/** The shift from a shape in the fixture's first form instance to the same shape in its second. */
+function otherInstanceDx(shape: ShapeInfo): number {
+ return shape.bounds.x < INSTANCE_OFFSET ? INSTANCE_OFFSET : -INSTANCE_OFFSET;
+}
+
async function largestGrouped(page: Page): Promise<ShapeInfo> {
const all = await shapes(page);
const grouped = all.filter((s) => s.grouped && isUnique(all, s));
@@ -170,26 +216,33 @@ async function grabbable(
}
test.describe("PDF text editor - vector shapes survive save", () => {
- test("a deleted shape inside a form is gone from the saved file", async ({
+ test("a deleted shape inside a form is gone from the saved file, and the form's other use keeps it", async ({
page,
}) => {
- await openSample(page);
+ await openInEditor(page, TWICE_DRAWN_FORM);
const target = await largestGrouped(page);
await deleteShape(page, target.id);
expect(drawnAt(await shapes(page), target.bounds)).toBe(false);
await saveAndReopen(page);
- expect(drawnAt(await shapes(page), target.bounds)).toBe(false);
+ const reopened = await shapes(page);
+ expect(drawnAt(reopened, target.bounds)).toBe(false);
+ expect(drawnAt(reopened, target.bounds, otherInstanceDx(target))).toBe(
+ true,
+ );
});
test("an undone delete inside a form keeps the shape in the saved file", async ({
page,
}) => {
- await openSample(page);
+ await openInEditor(page, TWICE_DRAWN_FORM);
const target = await largestGrouped(page);
await deleteShape(page, target.id);
+ expect(drawnAt(await shapes(page), target.bounds)).toBe(false);
await page.keyboard.press("ControlOrMeta+z");
- await page.waitForTimeout(500);
+ await expect
+ .poll(async () => drawnAt(await shapes(page), target.bounds))
+ .toBe(true);
await saveAndReopen(page);
expect(drawnAt(await shapes(page), target.bounds)).toBe(true);
@@ -198,22 +251,40 @@ test.describe("PDF text editor - vector shapes survive save", () => {
test("undoing a delete after the save that removed it brings the shape back", async ({
page,
}) => {
- await openSample(page);
+ await openInEditor(page, TWICE_DRAWN_FORM);
const target = await largestGrouped(page);
await deleteShape(page, target.id);
+ expect(drawnAt(await shapes(page), target.bounds)).toBe(false);
const download = page.waitForEvent("download");
await page.getByTestId("pdf-editor-download").click();
await download;
await page.keyboard.press("ControlOrMeta+z");
- await page.waitForTimeout(500);
+ await expect
+ .poll(async () => drawnAt(await shapes(page), target.bounds))
+ .toBe(true);
+
+ await saveAndReopen(page);
+ expect(drawnAt(await shapes(page), target.bounds)).toBe(true);
+ });
+
+ test("a shape in a form whose lift would change the drawing is not deleted", async ({
+ page,
+ }) => {
+ await openInEditor(page);
+ const target = await largestGrouped(page);
+ await deleteShape(page, target.id);
+ await expect(page.getByRole("alert")).toContainText(
+ "it is drawn as part of a group",
+ );
expect(drawnAt(await shapes(page), target.bounds)).toBe(true);
+ await expect(page.getByTestId("pdf-editor-undo")).toBeDisabled();
await saveAndReopen(page);
expect(drawnAt(await shapes(page), target.bounds)).toBe(true);
});
test("a shape inside a form does not move", async ({ page }) => {
- await openSample(page);
+ await openInEditor(page);
const { shape, at } = await grabbable(page, true);
await dragBy(page, at, 45);
expect(drawnAt(await shapes(page), shape.bounds)).toBe(true);
@@ -222,7 +293,7 @@ test.describe("PDF text editor - vector shapes survive save", () => {
test("a page-level shape's move and delete are in the saved file", async ({
page,
}) => {
- await openSample(page);
+ await openInEditor(page);
const { shape: moved, at } = await grabbable(page, false);
await dragBy(page, at, 45);
const after = (await shapes(page)).find((s) => s.id === moved.id);
diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-table-roundtrip.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-table-roundtrip.spec.ts
index 6322eaa33e..940950515d 100644
--- a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-table-roundtrip.spec.ts
+++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-table-roundtrip.spec.ts
@@ -1,4 +1,5 @@
import { test, expect } from "@editor/tests/helpers/stub-test-base";
+import { editRecognizedTable } from "@editor/tests/helpers/recognizedTable";
import { openInTextEditor } from "@editor/tests/helpers/pdf-text-editor";
import type { Page } from "@playwright/test";
import { mockAppApis } from "@editor/tests/helpers/api-stubs";
@@ -99,10 +100,7 @@ test("merged cells retain their borders after a structural edit and export", asy
path.join(import.meta.dirname, "../test-fixtures/merged-table-sample.pdf"),
);
await waitForFirstPage(page);
- await page
- .locator('[data-testid^="pdf-editor-recognized-table-edit-"]')
- .first()
- .click();
+ await editRecognizedTable(page);
const before = await page.evaluate(readMergedTable);
expect({
rows: before.rows,
@@ -145,10 +143,7 @@ test("merged cells retain their borders after a structural edit and export", asy
contentType: "application/pdf",
});
const reopenedPage = await reopenExport(page, saved);
- await reopenedPage
- .locator('[data-testid^="pdf-editor-recognized-table-edit-"]')
- .first()
- .click();
+ await editRecognizedTable(reopenedPage);
const reopened = await reopenedPage.evaluate(readMergedTable);
expect({ rows: reopened.rows, cols: reopened.cols }).toEqual({
rows: 8,
@@ -211,7 +206,7 @@ for (const file of [fixture, ...corpus]) {
expect(errors).toEqual([]);
return;
}
- await chips.first().click();
+ await editRecognizedTable(page);
const before = await page.evaluate(() => {
const store = (window as unknown as { __editor_store: EditorStore })
.__editor_store;
diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-tables.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-tables.spec.ts
index 8e2eddfc8b..6c3a287234 100644
--- a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-tables.spec.ts
+++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-tables.spec.ts
@@ -1,4 +1,5 @@
import { test, expect } from "@editor/tests/helpers/stub-test-base";
+import { editRecognizedTable } from "@editor/tests/helpers/recognizedTable";
import { openInTextEditor } from "@editor/tests/helpers/pdf-text-editor";
import type { EditorStore } from "@editor/tools/pdfTextEditor/store/EditorStore";
import path from "path";
@@ -274,10 +275,7 @@ test.describe("PDF text editor - tables", () => {
await expect(recognized).toHaveCount(1, { timeout: 15_000 });
await expect(recognized).toHaveText(/4×3/);
- await page
- .locator('[data-testid^="pdf-editor-recognized-table-edit-"]')
- .first()
- .click();
+ await editRecognizedTable(page);
await page.waitForFunction(
`(${STORE}.state.pages[0].tables ? ${STORE}.state.pages[0].tables.length : 0) > 0`,
undefined,
diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-toolbar-controls.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-toolbar-controls.spec.ts
index 12fa95dcd5..61f954c486 100644
--- a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-toolbar-controls.spec.ts
+++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-toolbar-controls.spec.ts
@@ -2,15 +2,10 @@ import { test, expect } from "@editor/tests/helpers/stub-test-base";
import { openInTextEditor } from "@editor/tests/helpers/pdf-text-editor";
import path from "path";
-// Two toolbar changes:
-//
-// * The bold button was a second, weaker way to say what the font family
-// picker already says, and it applied to whole runs rather than to the
-// text the user had selected. The weight control is gone; Helvetica Bold
-// and friends are still one dropdown pick away.
-// * Fill colour and outline colour sat side by side, so the common case
-// (change the text colour) had two pickers to choose between. Outline
-// colour and width now live behind an advanced control.
+// Fill colour and outline colour sat side by side, so the common case (change
+// the text colour) had two pickers to choose between. Outline colour and width
+// live behind an advanced control. The font list names a family once, so bold
+// is the Bold toggle's, beside Italic.
const PARAGRAPH_PDF = path.join(
import.meta.dirname,
@@ -55,33 +50,26 @@ function readRun(page: import("@playwright/test").Page, runId: string) {
}, runId);
}
-test.describe("PDF text editor - the weight control is gone", () => {
- test("the toolbar has no bold button", async ({ page }) => {
+test.describe("PDF text editor - bold is a toggle, not a list entry", () => {
+ test("the toolbar has Bold beside Italic", async ({ page }) => {
await openEditor(page, PARAGRAPH_PDF);
await selectFirstRun(page);
await expect(page.getByTestId("pdf-editor-toolbar")).toBeVisible();
- await expect(
- page.getByTestId("pdf-editor-bold"),
- "the bold weight control should have been dropped",
- ).toHaveCount(0);
- // Italic is a style, not a weight, and stays.
+ await expect(page.getByTestId("pdf-editor-bold")).toBeVisible();
await expect(page.getByTestId("pdf-editor-italic")).toBeVisible();
});
- test("bold is still reachable through the font family picker", async ({
- page,
- }) => {
+ test("Bold makes the selected run bold", async ({ page }) => {
await openEditor(page, PARAGRAPH_PDF);
const runId = await selectFirstRun(page);
const before = await readRun(page, runId);
expect(before, "run should be in the model").not.toBeNull();
- await page.getByTestId("pdf-editor-font-family").click();
- await page.getByRole("option", { name: "Helvetica Bold" }).click();
- await page.waitForTimeout(600);
+ await page.getByTestId("pdf-editor-bold").click();
- const after = await readRun(page, runId);
- expect(after!.fontId).toMatch(/Helvetica-Bold/);
+ await expect
+ .poll(async () => (await readRun(page, runId))?.fontId)
+ .toMatch(/Helvetica-Bold/);
});
});
diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-vis-fontsize.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-vis-fontsize.spec.ts
index b175caf3a7..0a29a29c2e 100644
--- a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-vis-fontsize.spec.ts
+++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-vis-fontsize.spec.ts
@@ -637,7 +637,7 @@ test.describe("PDF text editor - font family, measured on the rendered page", ()
// Would catch: a weight change that only relabels the font in the store. The
// glyph box barely moves between Helvetica and Helvetica Bold, so the only
// honest evidence is how much darker the stems are - the ink area.
- test("Helvetica Bold thickens the glyph ink without moving its box", async ({
+ test("the Bold toggle thickens Helvetica's glyph ink without moving its box", async ({
page,
}) => {
test.setTimeout(120_000);
@@ -648,7 +648,7 @@ test.describe("PDF text editor - font family, measured on the rendered page", ()
const regular = await settledInk(page);
expect(regular.n, "regular render must be inked").toBeGreaterThan(100);
- await setFamily(page, "Helvetica Bold");
+ await page.getByTestId("pdf-editor-bold").click();
const bold = await settledInk(page, { differentFrom: regular });
expect(
diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-width-modes.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-width-modes.spec.ts
index db063c2d87..1a931697ca 100644
--- a/frontend/src/editor/core/tests/stubbed/pdf-text-editor-width-modes.spec.ts
+++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor-width-modes.spec.ts
@@ -6,38 +6,20 @@ import { selectWrapWidthMode } from "@editor/tests/stubbed/widthModeHelpers";
// The sidebar promises two distinct behaviours:
//
-// Grow - "Boxes widen to the right as you type (no wrapping)."
-// Wrap - "Boxes keep their width; extra text wraps onto new lines."
-//
-// Neither held. Measured on paragraph-sample.pdf before this spec existed:
-//
-// grow / single-line box 303 -> 551 then STOPS at the page edge; 2944px of
-// typed text clipped and invisible; never wraps.
-// grow / paragraph box 500 -> 551 then stops; 1851px clipped; on blur the
-// box SHRINKS to 490 and the model never gains a line.
-// wrap / single-line box GREW 303 -> 551 (it is supposed to keep its width);
-// 3209px clipped; on blur box drops to 286 with the text
-// still long, and the model still has one line.
-// wrap / paragraph identical to grow - the two modes were indistinguishable.
-//
-// The user reported it as "grow mode doesn't grow, it just forces word wrap but
-// doesn't visually show it or change the cursor onto the new line until you
-// click off, and clicking back on resets the box to the old small size even
-// though there is now text overlapped on a new line".
+// Grow - boxes widen as you type until they reach the page edge, then the
+// overflow flows onto new lines.
+// Wrap - boxes keep their width and flow onto new lines.
//
// The rules this spec holds both modes to:
// * the box does not change size between blurring and re-focusing,
-// * Grow widens to fit, clips nothing, and never adds a line,
+// * Grow widens to fit, clips nothing, and stays on the page, wrapping only
+// what is typed past the page edge,
// * Wrap keeps its width and moves the overflow onto new lines WHILE typing.
//
-// Wrap's overflow used to stay hidden even after the model had wrapped, because
-// ReflowWrapCommand joined a wrap-created line with " " while the loader emits
-// one "\n" per visual line. run.text then held fewer lines than the page had ink
-// for, buildExactLines failed at the seam, and the box kept its pre-edit height
-// with the stale blocks still painted. Every visual line now joins with "\n" and
-// the wrap-owned ones are recorded in run.paragraphSoftStarts, so they stay
-// re-flowable. Measured after: wrap/paragraph clipped 2073px -> 4px, box height
-// 100 -> 148 (4 -> 6 lines) WHILE still focused, blocks 6 at one row each.
+// Wrap's overflow shows while typing only because run.text joins every visual
+// line with "\n" and records the wrap-owned ones in run.paragraphSoftStarts. A
+// line joined with " " leaves run.text with fewer lines than the page has ink
+// for, buildExactLines fails at the seam, and the box keeps its pre-edit height.
const PARAGRAPH_PDF = path.join(
import.meta.dirname,
@@ -205,10 +187,17 @@ for (const which of ["single", "paragraph"] as const) {
`${typed!.clipped}px of typed text is clipped out of sight`,
).toBeLessThanOrEqual(1);
expect(typed!.caretInBox, "the caret left the box").not.toBe(false);
+ const pageRight = await page
+ .getByTestId("pdf-editor-page-0")
+ .evaluate((el) => el.getBoundingClientRect().right);
+ const boxRight = await page
+ .getByTestId(testId)
+ .evaluate((el) => el.getBoundingClientRect().right);
expect(
- typed!.modelLines,
- "Grow must not wrap - the hint says 'no wrapping'",
- ).toBe(before!.modelLines);
+ boxRight,
+ "Grow ran the box off the page instead of wrapping",
+ ).toBeLessThanOrEqual(pageRight + 1);
+ expect(typed!.modelLines).toBeGreaterThan(before!.modelLines);
});
test("Grow keeps the same size across blur and re-focus", async ({
diff --git a/frontend/src/editor/core/tests/stubbed/pdf-text-editor.spec.ts b/frontend/src/editor/core/tests/stubbed/pdf-text-editor.spec.ts
index 3fd1d361b7..8d0b75dc7b 100644
--- a/frontend/src/editor/core/tests/stubbed/pdf-text-editor.spec.ts
+++ b/frontend/src/editor/core/tests/stubbed/pdf-text-editor.spec.ts
@@ -1,4 +1,5 @@
import { test, expect } from "@editor/tests/helpers/stub-test-base";
+import type { Page } from "@playwright/test";
import {
openInTextEditor,
scrollToEditorPage,
@@ -8,8 +9,8 @@ import path from "path";
// the fixture generators use.
import { PDFDocument } from "@cantoo/pdf-lib";
import {
- stashCurrentDocument,
- waitForReopenedPage,
+ downloadBytes,
+ reopenSavedBytes,
} from "@editor/tests/stubbed/saveHelpers";
const SAMPLE_PDF = path.join(
@@ -49,7 +50,7 @@ const BIG_SAMPLE_PDF = path.join(
// PDF text editor regression suite. It runs entirely in the browser via
// PDFium WASM, so these tests do not need a real backend.
-async function gotoEditor(page: import("@playwright/test").Page) {
+async function gotoEditor(page: Page) {
await page.goto("/pdf-text-editor", {
waitUntil: "domcontentloaded",
});
@@ -59,15 +60,30 @@ async function gotoEditor(page: import("@playwright/test").Page) {
}
/** Change the selected run's font family through the real toolbar dropdown. */
-async function selectFontFamily(
- page: import("@playwright/test").Page,
- optionLabel: string,
-) {
+async function selectFontFamily(page: Page, optionLabel: string) {
await page.getByTestId("pdf-editor-font-family").click();
await page.getByRole("option", { name: optionLabel, exact: true }).click();
}
-async function loadSamplePdf(page: import("@playwright/test").Page) {
+/** Turn the selected text's bold face on or off through the Bold toggle, and wait until it is. */
+async function setBold(page: Page, on: boolean) {
+ const bold = page.getByTestId("pdf-editor-bold");
+ await expect(bold).toBeEnabled();
+ if ((await bold.getAttribute("aria-pressed")) !== String(on))
+ await bold.click();
+ await expect(bold).toHaveAttribute("aria-pressed", String(on));
+}
+
+/** Put the selected text in Helvetica Bold: the family from the list, then the Bold toggle. */
+async function selectHelveticaBold(page: Page) {
+ await selectFontFamily(page, "Helvetica");
+ await expect(page.getByTestId("pdf-editor-font-family")).toHaveValue(
+ "Helvetica",
+ );
+ await setBold(page, true);
+}
+
+async function loadSamplePdf(page: Page) {
// The visible "Open" flow goes through the left-sidebar Files panel.
await openInTextEditor(page, SAMPLE_PDF);
await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
@@ -75,7 +91,7 @@ async function loadSamplePdf(page: import("@playwright/test").Page) {
});
}
-async function loadMultiPageSample(page: import("@playwright/test").Page) {
+async function loadMultiPageSample(page: Page) {
await openInTextEditor(page, MULTI_PAGE_PDF);
await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
timeout: 30_000,
@@ -84,7 +100,7 @@ async function loadMultiPageSample(page: import("@playwright/test").Page) {
/** Type a string into a contenteditable using `execCommand('insertText')`. */
async function typeIntoRun(
- page: import("@playwright/test").Page,
+ page: Page,
runTestId: string,
text: string,
position: "end" | "start" = "end",
@@ -322,18 +338,9 @@ test.describe("PDF text editor - save", () => {
const downloadPromise = page.waitForEvent("download");
await page.getByTestId("pdf-editor-download").click();
const download = await downloadPromise;
- const stream = await download.createReadStream();
- const chunks: Buffer[] = [];
- for await (const chunk of stream) chunks.push(chunk as Buffer);
- const savedBytes = Buffer.concat(chunks);
+ const savedBytes = await downloadBytes(download);
- // Push the saved bytes back into the dropzone as a new file. setInputFiles
- // accepts an in-memory payload.
- await openInTextEditor(page, {
- name: "round-trip.pdf",
- mimeType: "application/pdf",
- buffer: savedBytes,
- });
+ await reopenSavedBytes(page, savedBytes, "round-trip.pdf");
// The edited text must be present somewhere in page 0's runs.
const allText = await page
@@ -394,9 +401,7 @@ test.describe("PDF text editor - whitespace preservation", () => {
// These guard against a recurring class of regression where typed spaces
// vanish from the saved PDF.
- async function readFirstRunText(
- page: import("@playwright/test").Page,
- ): Promise<string> {
+ async function readFirstRunText(page: Page): Promise<string> {
return await page.evaluate(() => {
const store = (
window as unknown as {
@@ -409,24 +414,12 @@ test.describe("PDF text editor - whitespace preservation", () => {
});
}
- async function saveAndReopen(
- page: import("@playwright/test").Page,
- ): Promise<void> {
+ async function saveAndReopen(page: Page): Promise<void> {
const downloadPromise = page.waitForEvent("download");
await page.getByTestId("pdf-editor-download").click();
const download = await downloadPromise;
- const stream = await download.createReadStream();
- const chunks: Buffer[] = [];
- for await (const chunk of stream) chunks.push(chunk as Buffer);
- const savedBytes = Buffer.concat(chunks);
- await openInTextEditor(page, {
- name: "round-trip.pdf",
- mimeType: "application/pdf",
- buffer: savedBytes,
- });
- await expect(
- page.locator('[data-testid^="pdf-editor-run-p0-"]').first(),
- ).toBeVisible({ timeout: 30_000 });
+ const savedBytes = await downloadBytes(download);
+ await reopenSavedBytes(page, savedBytes, "round-trip.pdf");
}
test("NBSP typed into a single-line run is normalized to a regular space in the model", async ({
@@ -1035,7 +1028,7 @@ test.describe("PDF text editor - whitespace preservation", () => {
// Sequential-edit visual-integrity tests.
- async function findTaglineRun(page: import("@playwright/test").Page) {
+ async function findTaglineRun(page: Page) {
return await page.evaluate(() => {
const store = (
window as unknown as {
@@ -1073,7 +1066,7 @@ test.describe("PDF text editor - whitespace preservation", () => {
});
}
- async function readRun(page: import("@playwright/test").Page, id: string) {
+ async function readRun(page: Page, id: string) {
return await page.evaluate((tid) => {
const store = (
window as unknown as {
@@ -1105,11 +1098,7 @@ test.describe("PDF text editor - whitespace preservation", () => {
}, id);
}
- async function caretAt(
- page: import("@playwright/test").Page,
- tid: string,
- pos: number,
- ) {
+ async function caretAt(page: Page, tid: string, pos: number) {
await page.evaluate(
({ tid, pos }) => {
const el = document.querySelector<HTMLDivElement>(
@@ -1147,7 +1136,7 @@ test.describe("PDF text editor - whitespace preservation", () => {
}
async function execAt(
- page: import("@playwright/test").Page,
+ page: Page,
tid: string,
pos: number,
cmd: "insertText" | "delete",
@@ -1769,7 +1758,7 @@ test.describe("PDF text editor - whitespace preservation", () => {
}
async function snapshotIntegrity(
- page: import("@playwright/test").Page,
+ page: Page,
runId: string,
baselineY: number,
expectedText: string,
@@ -2114,19 +2103,8 @@ test.describe("PDF text editor - whitespace preservation", () => {
const downloadPromise = page.waitForEvent("download");
await page.getByTestId("pdf-editor-download").click();
const download = await downloadPromise;
- const stream = await download.createReadStream();
- const chunks: Buffer[] = [];
- for await (const chunk of stream) chunks.push(chunk as Buffer);
- const buf = Buffer.concat(chunks);
- await openInTextEditor(page, {
- name: "round-trip.pdf",
- mimeType: "application/pdf",
- buffer: buf,
- });
- await expect(
- page.locator('[data-testid^="pdf-editor-run-p0-"]').first(),
- ).toBeVisible({ timeout: 30_000 });
- await page.waitForTimeout(1500);
+ const buf = await downloadBytes(download);
+ await reopenSavedBytes(page, buf, "round-trip.pdf");
// Scan EVERY run on EVERY page.
const allText = await page.evaluate(() => {
@@ -2784,23 +2762,9 @@ test.describe("PDF text editor - multi-page", () => {
const downloadPromise = page.waitForEvent("download");
await page.getByTestId("pdf-editor-download").click();
const download = await downloadPromise;
- const stream = await download.createReadStream();
- const chunks: Buffer[] = [];
- for await (const chunk of stream) chunks.push(chunk as Buffer);
- const savedBytes = Buffer.concat(chunks);
+ const savedBytes = await downloadBytes(download);
- // Remember the document we are replacing: after the re-upload the OLD
- // document's page-2 runs are still mounted.
- await stashCurrentDocument(page);
- await openInTextEditor(page, {
- name: "round-trip.pdf",
- mimeType: "application/pdf",
- buffer: savedBytes,
- });
- await expect(page.getByTestId("pdf-editor-page-2")).toBeVisible({
- timeout: 30_000,
- });
- await waitForReopenedPage(page, 2);
+ await reopenSavedBytes(page, savedBytes, "round-trip.pdf", 2);
// Re-read the page-2 run text through PdfiumTextReader + LineGrouper.
const page2Text = await page.evaluate(() => {
@@ -2865,9 +2829,8 @@ test.describe("PDF text editor - bold/italic", () => {
const before = await readState(runId);
expect(before.undoDepth).toBeGreaterThan(0);
- // Now pick the bold variant. It should dispatch another edit (undo stack
- // grows). The dedicated weight button is gone; the picker is the way in.
- await selectFontFamily(page, "Helvetica Bold");
+ // Now the bold face. It should dispatch another edit (undo stack grows).
+ await setBold(page, true);
// The toolbar's active state flips on local component state, which can beat
// the command onto the screen - so wait for the history itself to grow.
@@ -2959,10 +2922,8 @@ test.describe("PDF text editor - bold/italic", () => {
// Bold then un-bold (the user's exact sequence). Each pick dispatches a
// SetFontFamily command.
- await selectFontFamily(page, "Helvetica Bold");
- await page.waitForTimeout(300);
- await selectFontFamily(page, "Helvetica");
- await page.waitForTimeout(300);
+ await selectHelveticaBold(page);
+ await setBold(page, false);
const after = await page.evaluate((id) => {
const store = (
@@ -3004,41 +2965,29 @@ test.describe("PDF text editor - bold/italic", () => {
const downloadPromise = page.waitForEvent("download");
await downloadBtn.click();
const dl = await downloadPromise;
- const stream = await dl.createReadStream();
- const chunks: Buffer[] = [];
- for await (const chunk of stream) chunks.push(chunk as Buffer);
- const savedBytes = Buffer.concat(chunks);
- await openInTextEditor(page, {
- name: "round-trip.pdf",
- mimeType: "application/pdf",
- buffer: savedBytes,
- });
- await expect(
- page.locator('[data-testid^="pdf-editor-run-p0-"]').first(),
- ).toBeVisible({ timeout: 30_000 });
- await page.waitForTimeout(500);
+ const savedBytes = await downloadBytes(dl);
+ await reopenSavedBytes(page, savedBytes, "round-trip.pdf");
- const reopenedRuns = await page.evaluate(() => {
- const store = (
- window as unknown as {
- __editor_store: {
- doc: { page: (i: number) => { runs: Array<{ text: string }> } };
- };
- }
- ).__editor_store;
- return store.doc.page(0).runs.map((r) => r.text);
- });
+ const reopenedRuns = () =>
+ page.evaluate(() => {
+ const store = (
+ window as unknown as {
+ __editor_store: {
+ doc: { page: (i: number) => { runs: Array<{ text: string }> } };
+ };
+ }
+ ).__editor_store;
+ return store.doc.page(0).runs.map((r) => r.text);
+ });
// The CORE assertion: each distinctive tagline word appears in EXACTLY ONE
- // run.
- const countCarrying = (word: string) =>
- reopenedRuns.filter((t) => t.includes(word)).length;
+ // run. Polled, because the run list fills in as the reopened file loads.
for (const word of ["Adobe", "Acrobat", "Alternative"]) {
- expect(
- countCarrying(word),
- `Runs carrying "${word}": ${JSON.stringify(
- reopenedRuns.filter((t) => t.includes(word)),
- )}`,
- ).toBe(1);
+ await expect
+ .poll(
+ async () => (await reopenedRuns()).filter((t) => t.includes(word)),
+ { message: `runs carrying "${word}"`, timeout: 15_000 },
+ )
+ .toHaveLength(1);
}
});
});
@@ -3311,22 +3260,10 @@ test.describe("PDF text editor - lazy page loading", () => {
const downloadPromise = page.waitForEvent("download");
await page.getByTestId("pdf-editor-download").click();
const download = await downloadPromise;
- const stream = await download.createReadStream();
- const chunks: Buffer[] = [];
- for await (const chunk of stream) chunks.push(chunk as Buffer);
- const savedBytes = Buffer.concat(chunks);
+ const savedBytes = await downloadBytes(download);
- await openInTextEditor(
- page,
- {
- name: "big-round-trip.pdf",
- mimeType: "application/pdf",
- buffer: savedBytes,
- },
- { zoomPercent: null },
- );
- await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
- timeout: 30_000,
+ await reopenSavedBytes(page, savedBytes, "big-round-trip.pdf", 0, 30_000, {
+ zoomPercent: null,
});
const reopenedText = await page
.waitForFunction(
@@ -3982,11 +3919,7 @@ test.describe("PDF text editor - Ctrl+A select all", () => {
test.describe("PDF text editor - stress: whitespace insertion variations", () => {
/** Caret at char index `pos` inside `runTestId`. */
- async function placeCaret(
- page: import("@playwright/test").Page,
- runTestId: string,
- pos: number,
- ) {
+ async function placeCaret(page: Page, runTestId: string, pos: number) {
await page.evaluate(
({ tid, pos }) => {
const el = document.querySelector<HTMLDivElement>(
@@ -4024,7 +3957,7 @@ test.describe("PDF text editor - stress: whitespace insertion variations", () =>
}
async function insertAt(
- page: import("@playwright/test").Page,
+ page: Page,
runTestId: string,
pos: number,
text: string,
@@ -4036,7 +3969,7 @@ test.describe("PDF text editor - stress: whitespace insertion variations", () =>
await page.waitForTimeout(250);
}
- async function readTagline(page: import("@playwright/test").Page) {
+ async function readTagline(page: Page) {
return await page.evaluate(() => {
const store = (
window as unknown as {
@@ -4068,7 +4001,7 @@ test.describe("PDF text editor - stress: whitespace insertion variations", () =>
});
}
- async function loadFixture(page: import("@playwright/test").Page) {
+ async function loadFixture(page: Page) {
await gotoEditor(page);
await openInTextEditor(page, USER_SAMPLE_PDF);
await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
@@ -4193,7 +4126,7 @@ test.describe("PDF text editor - stress: whitespace insertion variations", () =>
});
test.describe("PDF text editor - stress: bold / font swap variations", () => {
- async function loadFixture(page: import("@playwright/test").Page) {
+ async function loadFixture(page: Page) {
await gotoEditor(page);
await openInTextEditor(page, USER_SAMPLE_PDF);
await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
@@ -4202,7 +4135,7 @@ test.describe("PDF text editor - stress: bold / font swap variations", () => {
await page.waitForTimeout(500);
}
- async function selectTagline(page: import("@playwright/test").Page) {
+ async function selectTagline(page: Page) {
// The page-0 runs are read lazily on first intersection; wait for them
// to populate so the test actually runs instead of skipping on a race.
await page
@@ -4243,7 +4176,7 @@ test.describe("PDF text editor - stress: bold / font swap variations", () => {
return id;
}
- async function readRun(page: import("@playwright/test").Page, id: string) {
+ async function readRun(page: Page, id: string) {
return await page.evaluate((rid) => {
const store = (
window as unknown as {
@@ -4277,10 +4210,10 @@ test.describe("PDF text editor - stress: bold / font swap variations", () => {
test.skip(true, "fixture missing tagline");
return;
}
- for (const family of ["Helvetica Bold", "Helvetica", "Helvetica Bold"]) {
+ await selectHelveticaBold(page);
+ for (const on of [false, true]) {
await selectTagline(page);
- await selectFontFamily(page, family);
- await page.waitForTimeout(250);
+ await setBold(page, on);
}
const after = await readRun(page, id);
if (!after) throw new Error("run vanished after 3 bold toggles");
@@ -4301,8 +4234,7 @@ test.describe("PDF text editor - stress: bold / font swap variations", () => {
if (!before) throw new Error("baseline read failed");
// Re-select before each toolbar click.
await selectTagline(page);
- await selectFontFamily(page, "Helvetica Bold");
- await page.waitForTimeout(250);
+ await selectHelveticaBold(page);
await selectTagline(page);
await page.getByTestId("pdf-editor-italic").click();
await page.waitForTimeout(250);
@@ -4331,13 +4263,16 @@ test.describe("PDF text editor - stress: bold / font swap variations", () => {
const before = await readRun(page, id);
if (!before) throw new Error("baseline read failed");
expect(before.merged).toBeGreaterThan(10);
- await selectFontFamily(page, "Helvetica Bold");
- await page.waitForTimeout(250);
+ await selectHelveticaBold(page);
const mid = await readRun(page, id);
if (!mid) throw new Error("mid read failed");
expect(mid.merged).toBe(0);
- await page.getByTestId("pdf-editor-undo").click();
- await page.waitForTimeout(400);
+ // The family pick and the Bold toggle are one undo step each.
+ for (let step = 0; step < 2; step++)
+ await page.getByTestId("pdf-editor-undo").click();
+ await expect
+ .poll(async () => (await readRun(page, id))?.fontId)
+ .toBe(before.fontId);
const after = await readRun(page, id);
if (!after) throw new Error("post-undo read failed");
expect(after.fontId).toBe(before.fontId);
@@ -4355,8 +4290,7 @@ test.describe("PDF text editor - stress: bold / font swap variations", () => {
test.skip(true, "fixture missing tagline");
return;
}
- await selectFontFamily(page, "Helvetica Bold");
- await page.waitForTimeout(250);
+ await selectHelveticaBold(page);
// Now insert text into the bolded run.
await page.evaluate((tid) => {
const el = document.querySelector<HTMLDivElement>(
@@ -4378,19 +4312,8 @@ test.describe("PDF text editor - stress: bold / font swap variations", () => {
const downloadPromise = page.waitForEvent("download");
await page.getByTestId("pdf-editor-download").click();
const dl = await downloadPromise;
- const stream = await dl.createReadStream();
- const chunks: Buffer[] = [];
- for await (const chunk of stream) chunks.push(chunk as Buffer);
- const savedBytes = Buffer.concat(chunks);
- await openInTextEditor(page, {
- name: "round.pdf",
- mimeType: "application/pdf",
- buffer: savedBytes,
- });
- await expect(
- page.locator('[data-testid^="pdf-editor-run-p0-"]').first(),
- ).toBeVisible({ timeout: 30_000 });
- await page.waitForTimeout(500);
+ const savedBytes = await downloadBytes(dl);
+ await reopenSavedBytes(page, savedBytes, "round.pdf");
const reopenedRuns = await page.evaluate(() => {
const store = (
window as unknown as {
@@ -4427,7 +4350,7 @@ test.describe("PDF text editor - stress: bold / font swap variations", () => {
}
// Change font family through the real toolbar dropdown (the tagline run
// is already selected). The Select's onChange dispatches SetFontFamily.
- await selectFontFamily(page, "Times Roman");
+ await selectFontFamily(page, "Times");
await page.waitForTimeout(300);
const mid = await readRun(page, id);
if (!mid) throw new Error("mid read failed");
@@ -4444,7 +4367,7 @@ test.describe("PDF text editor - stress: bold / font swap variations", () => {
});
test.describe("PDF text editor - stress: add / remove cycles (no leaks)", () => {
- async function loadFixture(page: import("@playwright/test").Page) {
+ async function loadFixture(page: Page) {
await gotoEditor(page);
await openInTextEditor(page, USER_SAMPLE_PDF);
await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
@@ -4683,7 +4606,7 @@ test.describe("PDF text editor - stress: add / remove cycles (no leaks)", () =>
});
test.describe("PDF text editor - stress: save+reopen multi-cycle", () => {
- async function loadFixture(page: import("@playwright/test").Page) {
+ async function loadFixture(page: Page) {
await gotoEditor(page);
await openInTextEditor(page, USER_SAMPLE_PDF);
await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
@@ -4692,23 +4615,12 @@ test.describe("PDF text editor - stress: save+reopen multi-cycle", () => {
await page.waitForTimeout(500);
}
- async function saveAndReopenLocal(page: import("@playwright/test").Page) {
+ async function saveAndReopenLocal(page: Page) {
const downloadPromise = page.waitForEvent("download");
await page.getByTestId("pdf-editor-download").click();
const dl = await downloadPromise;
- const stream = await dl.createReadStream();
- const chunks: Buffer[] = [];
- for await (const chunk of stream) chunks.push(chunk as Buffer);
- const savedBytes = Buffer.concat(chunks);
- await openInTextEditor(page, {
- name: "round.pdf",
- mimeType: "application/pdf",
- buffer: savedBytes,
- });
- await expect(
- page.locator('[data-testid^="pdf-editor-run-p0-"]').first(),
- ).toBeVisible({ timeout: 30_000 });
- await page.waitForTimeout(500);
+ const savedBytes = await downloadBytes(dl);
+ await reopenSavedBytes(page, savedBytes, "round.pdf");
}
test("save+reopen three times in a row (with one edit each) doesn't compound ghost objects", async ({
@@ -4853,19 +4765,8 @@ test.describe("PDF text editor - stress: save+reopen multi-cycle", () => {
const downloadPromise = page.waitForEvent("download");
await page.getByTestId("pdf-editor-download").click();
const dl = await downloadPromise;
- const stream = await dl.createReadStream();
- const chunks: Buffer[] = [];
- for await (const chunk of stream) chunks.push(chunk as Buffer);
- const savedBytes = Buffer.concat(chunks);
- await openInTextEditor(page, {
- name: "round.pdf",
- mimeType: "application/pdf",
- buffer: savedBytes,
- });
- await expect(
- page.locator('[data-testid^="pdf-editor-run-p0-"]').first(),
- ).toBeVisible({ timeout: 30_000 });
- await page.waitForTimeout(500);
+ const savedBytes = await downloadBytes(dl);
+ await reopenSavedBytes(page, savedBytes, "round.pdf");
const allText = await page.evaluate(() => {
const store = (
window as unknown as {
@@ -4889,7 +4790,7 @@ test.describe("PDF text editor - stress: AddText box content fidelity", () => {
// The AddText flow has its own input path (singleton run, base-14 Helvetica
// from the start, no LineGrouper).
- async function loadFixture(page: import("@playwright/test").Page) {
+ async function loadFixture(page: Page) {
await gotoEditor(page);
await openInTextEditor(page, USER_SAMPLE_PDF);
await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
@@ -4899,7 +4800,7 @@ test.describe("PDF text editor - stress: AddText box content fidelity", () => {
}
async function addNewTextBox(
- page: import("@playwright/test").Page,
+ page: Page,
position: { x: number; y: number } = { x: 200, y: 600 },
): Promise<string> {
await page.getByTestId("pdf-editor-add-text").click();
@@ -4919,11 +4820,7 @@ test.describe("PDF text editor - stress: AddText box content fidelity", () => {
return newId;
}
- async function clearAndType(
- page: import("@playwright/test").Page,
- runId: string,
- text: string,
- ) {
+ async function clearAndType(page: Page, runId: string, text: string) {
await page.evaluate(
({ rid, t }) => {
const el = document.querySelector<HTMLDivElement>(
@@ -4945,11 +4842,7 @@ test.describe("PDF text editor - stress: AddText box content fidelity", () => {
await page.waitForTimeout(300);
}
- async function typeCharByChar(
- page: import("@playwright/test").Page,
- runId: string,
- sequence: string,
- ) {
+ async function typeCharByChar(page: Page, runId: string, sequence: string) {
// First clear the placeholder.
await page.evaluate((rid) => {
const el = document.querySelector<HTMLDivElement>(
@@ -4990,7 +4883,7 @@ test.describe("PDF text editor - stress: AddText box content fidelity", () => {
}
}
- async function readRun(page: import("@playwright/test").Page, id: string) {
+ async function readRun(page: Page, id: string) {
return await page.evaluate((rid) => {
const store = (
window as unknown as {
@@ -5026,23 +4919,12 @@ test.describe("PDF text editor - stress: AddText box content fidelity", () => {
}, id);
}
- async function saveAndReopenLocal(page: import("@playwright/test").Page) {
+ async function saveAndReopenLocal(page: Page) {
const downloadPromise = page.waitForEvent("download");
await page.getByTestId("pdf-editor-download").click();
const dl = await downloadPromise;
- const stream = await dl.createReadStream();
- const chunks: Buffer[] = [];
- for await (const chunk of stream) chunks.push(chunk as Buffer);
- const savedBytes = Buffer.concat(chunks);
- await openInTextEditor(page, {
- name: "round.pdf",
- mimeType: "application/pdf",
- buffer: savedBytes,
- });
- await expect(
- page.locator('[data-testid^="pdf-editor-run-p0-"]').first(),
- ).toBeVisible({ timeout: 30_000 });
- await page.waitForTimeout(500);
+ const savedBytes = await downloadBytes(dl);
+ await reopenSavedBytes(page, savedBytes, "round.pdf");
}
// Bulk insertText paths
@@ -5278,7 +5160,7 @@ test.describe("PDF text editor - stress: deletion shrinks bounds (no stuck-wide
// User-reported: "I can add spaces but after adding them I can't remove
// them".
- async function loadFixture(page: import("@playwright/test").Page) {
+ async function loadFixture(page: Page) {
await gotoEditor(page);
await openInTextEditor(page, USER_SAMPLE_PDF);
await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
@@ -5288,7 +5170,7 @@ test.describe("PDF text editor - stress: deletion shrinks bounds (no stuck-wide
}
async function addNewTextBox(
- page: import("@playwright/test").Page,
+ page: Page,
position: { x: number; y: number } = { x: 200, y: 600 },
): Promise<string> {
await page.getByTestId("pdf-editor-add-text").click();
@@ -5307,11 +5189,7 @@ test.describe("PDF text editor - stress: deletion shrinks bounds (no stuck-wide
});
}
- async function clearAndType(
- page: import("@playwright/test").Page,
- id: string,
- text: string,
- ) {
+ async function clearAndType(page: Page, id: string, text: string) {
await page.evaluate(
({ rid, t }) => {
const el = document.querySelector<HTMLDivElement>(
@@ -5333,11 +5211,7 @@ test.describe("PDF text editor - stress: deletion shrinks bounds (no stuck-wide
await page.waitForTimeout(300);
}
- async function backspace(
- page: import("@playwright/test").Page,
- id: string,
- n: number,
- ) {
+ async function backspace(page: Page, id: string, n: number) {
for (let i = 0; i < n; i++) {
await page.evaluate((rid) => {
const el = document.querySelector<HTMLDivElement>(
@@ -5358,7 +5232,7 @@ test.describe("PDF text editor - stress: deletion shrinks bounds (no stuck-wide
}
}
- async function readRun(page: import("@playwright/test").Page, id: string) {
+ async function readRun(page: Page, id: string) {
return await page.evaluate((rid) => {
const store = (
window as unknown as {
@@ -5455,19 +5329,8 @@ test.describe("PDF text editor - stress: deletion shrinks bounds (no stuck-wide
const downloadPromise = page.waitForEvent("download");
await page.getByTestId("pdf-editor-download").click();
const dl = await downloadPromise;
- const stream = await dl.createReadStream();
- const chunks: Buffer[] = [];
- for await (const chunk of stream) chunks.push(chunk as Buffer);
- const savedBytes = Buffer.concat(chunks);
- await openInTextEditor(page, {
- name: "round.pdf",
- mimeType: "application/pdf",
- buffer: savedBytes,
- });
- await expect(
- page.locator('[data-testid^="pdf-editor-run-p0-"]').first(),
- ).toBeVisible({ timeout: 30_000 });
- await page.waitForTimeout(500);
+ const savedBytes = await downloadBytes(dl);
+ await reopenSavedBytes(page, savedBytes, "round.pdf");
const xRuns = await page.evaluate(() => {
const store = (
window as unknown as {
@@ -5571,7 +5434,7 @@ test.describe("PDF text editor - stress: overlay box width hugs the text", () =>
// User reported the textbox visually "doesn't have the same width as the
// text".
- async function loadFixture(page: import("@playwright/test").Page) {
+ async function loadFixture(page: Page) {
await gotoEditor(page);
await openInTextEditor(page, USER_SAMPLE_PDF);
await expect(page.getByTestId("pdf-editor-page-0")).toBeVisible({
@@ -5581,7 +5444,7 @@ test.describe("PDF text editor - stress: overlay box width hugs the text", () =>
}
async function overlayCssWidth(
- page: import("@playwright/test").Page,
+ page: Page,
runTestId: string,
): Promise<number> {
return await page.evaluate((tid) => {
@@ -5591,10 +5454,7 @@ test.describe("PDF text editor - stress: overlay box width hugs the text", () =>
}, runTestId);
}
- async function cssTextWidth(
- page: import("@playwright/test").Page,
- runTestId: string,
- ): Promise<number> {
+ async function cssTextWidth(page: Page, runTestId: string): Promise<number> {
// Measure the text content's intrinsic CSS width via the same canvas
// measureText the overlay component uses.
return await page.evaluate((tid) => {
diff --git a/frontend/src/editor/core/tests/stubbed/saveHelpers.ts b/frontend/src/editor/core/tests/stubbed/saveHelpers.ts
index caa738d8a5..51bd64f794 100644
--- a/frontend/src/editor/core/tests/stubbed/saveHelpers.ts
+++ b/frontend/src/editor/core/tests/stubbed/saveHelpers.ts
@@ -1,5 +1,9 @@
import { expect } from "@editor/tests/helpers/stub-test-base";
import type { Download, Page } from "@playwright/test";
+import {
+ openInTextEditor,
+ scrollToEditorPage,
+} from "@editor/tests/helpers/pdf-text-editor";
/** Save helpers for the PDF text editor specs. */
@@ -25,6 +29,18 @@ export async function saveAndDownload(
await page.getByTestId("pdf-editor-download").click();
// Wait for the modal itself before arming the download listener.
await expect(confirm).toBeVisible({ timeout: 10_000 });
+ // The modal slides in; a click while it moves presses the button and
+ // releases past it, so no click fires and the download never starts.
+ await expect
+ .poll(() =>
+ confirm.evaluate(
+ (button) =>
+ (button.closest('[role="dialog"]') ?? button)
+ .getAnimations({ subtree: true })
+ .filter((animation) => animation.playState === "running").length,
+ ),
+ )
+ .toBe(0);
const downloadPromise = page.waitForEvent("download");
await confirm.click();
return downloadPromise;
@@ -74,3 +90,27 @@ export async function waitForReopenedPage(
{ timeout },
);
}
+
+/**
+ * Open `bytes` the way a user reopens a saved copy and wait until they, not the
+ * document they replace, have populated `pageIndex`. The replaced document's
+ * runs stay mounted while the new file is read, and for a moment afterwards the
+ * new document has no pages, so a wait on a visible run resolves too early.
+ */
+export async function reopenSavedBytes(
+ page: Page,
+ bytes: Buffer,
+ name: string,
+ pageIndex = 0,
+ timeout = 30_000,
+ { zoomPercent }: { zoomPercent?: number | null } = {},
+): Promise<void> {
+ await stashCurrentDocument(page);
+ await openInTextEditor(
+ page,
+ { name, mimeType: "application/pdf", buffer: bytes },
+ zoomPercent === undefined ? undefined : { zoomPercent },
+ );
+ if (pageIndex > 0) await scrollToEditorPage(page, pageIndex);
+ await waitForReopenedPage(page, pageIndex, timeout);
+}
diff --git a/frontend/src/editor/core/tests/test-fixtures/cairo-styles.pdf b/frontend/src/editor/core/tests/test-fixtures/cairo-styles.pdf
new file mode 100644
index 0000000000..a83cd894dc
Binary files /dev/null and b/frontend/src/editor/core/tests/test-fixtures/cairo-styles.pdf differ
diff --git a/frontend/src/editor/core/tests/test-fixtures/chrome-per-glyph-heading.pdf b/frontend/src/editor/core/tests/test-fixtures/chrome-per-glyph-heading.pdf
new file mode 100644
index 0000000000..608aea7928
Binary files /dev/null and b/frontend/src/editor/core/tests/test-fixtures/chrome-per-glyph-heading.pdf differ
diff --git a/frontend/src/editor/core/tests/test-fixtures/coloured-word-sample.pdf b/frontend/src/editor/core/tests/test-fixtures/coloured-word-sample.pdf
new file mode 100644
index 0000000000..41cc320819
Binary files /dev/null and b/frontend/src/editor/core/tests/test-fixtures/coloured-word-sample.pdf differ
diff --git a/frontend/src/editor/core/tests/test-fixtures/generate-coloured-word-sample.mjs b/frontend/src/editor/core/tests/test-fixtures/generate-coloured-word-sample.mjs
new file mode 100644
index 0000000000..ee3c87ca30
--- /dev/null
+++ b/frontend/src/editor/core/tests/test-fixtures/generate-coloured-word-sample.mjs
@@ -0,0 +1,45 @@
+// One-off script: generate `coloured-word-sample.pdf`, one paragraph of black
+// Liberation Sans with blue bold words, one ending a line and one mid-line,
+// a single line below it with a blue bold word, and a Hebrew line with a blue
+// word, printed by Chromium so each styled word is its own object.
+// Liberation Sans and Noto Sans Hebrew (SIL OFL) keep the embedded fonts
+// redistributable.
+//
+// Run with: node generate-coloured-word-sample.mjs
+import { readFileSync, writeFileSync } from "node:fs";
+import { fileURLToPath } from "node:url";
+import { dirname, join } from "node:path";
+import { chromium } from "@playwright/test";
+
+const __dirname = dirname(fileURLToPath(import.meta.url));
+const FONTS = join(
+ __dirname,
+ "../../../../../../app/core/src/main/resources/static/fonts",
+);
+const face = (weight, file, family = "Liberation Sans") =>
+ `@font-face { font-family: "${family}"; font-weight: ${weight}; src: url(data:font/ttf;base64,${readFileSync(join(FONTS, file)).toString("base64")}); }`;
+
+const html = `<!doctype html><html><head><style>
+${face(400, "LiberationSans-Regular.ttf")}
+${face(700, "LiberationSans-Bold.ttf")}
+${face(400, "NotoSansHebrew-Regular.ttf", "Hebrew")}
+body { margin: 48px; font: 14px/20px "Liberation Sans"; color: #000; }
+b, .blue { color: #1040d8; }
+</style></head><body>
+<p>Our office in the city centre is open daily<br>
+Glasgow and the west of <b>Scotland</b><br>
+call the <b>Helpdesk</b> team before noon<br>
+or write to us at the Harbour Street office</p>
+<p style="margin-top: 40px">Total due <b>today</b> by card</p>
+<p dir="rtl" style="margin-top: 40px; font-family: Hebrew">הטלפון <span class="blue">שלום</span> והמחיר</p>
+</body></html>`;
+
+const browser = await chromium.launch();
+const page = await browser.newPage();
+await page.setContent(html, { waitUntil: "load" });
+await page.evaluate(() => document.fonts.ready);
+const bytes = await page.pdf({ width: "420px", height: "330px" });
+await browser.close();
+const out = join(__dirname, "coloured-word-sample.pdf");
+writeFileSync(out, bytes);
+console.log(`wrote ${out} (${bytes.length} bytes)`);
diff --git a/frontend/src/editor/core/tests/test-fixtures/generate-mixed-style-sample.mjs b/frontend/src/editor/core/tests/test-fixtures/generate-mixed-style-sample.mjs
new file mode 100644
index 0000000000..afe6a6c9fa
--- /dev/null
+++ b/frontend/src/editor/core/tests/test-fixtures/generate-mixed-style-sample.mjs
@@ -0,0 +1,44 @@
+// One-off script: generate `mixed-style-sample.pdf`, lines that switch between
+// regular, bold, italic and bold italic mid-line, a symbols line and a line
+// with subscripts and superscripts, printed by Chromium so each styled word is
+// its own object in an embedded subset font.
+// Liberation Sans (SIL OFL) keeps the embedded fonts redistributable.
+//
+// Run with: node generate-mixed-style-sample.mjs
+import { readFileSync, writeFileSync } from "node:fs";
+import { fileURLToPath } from "node:url";
+import { dirname, join } from "node:path";
+import { chromium } from "@playwright/test";
+
+const __dirname = dirname(fileURLToPath(import.meta.url));
+const FONTS = join(
+ __dirname,
+ "../../../../../../app/core/src/main/resources/static/fonts",
+);
+const face = (weight, style, file) =>
+ `@font-face { font-family: "Liberation Sans"; font-weight: ${weight}; font-style: ${style}; src: url(data:font/ttf;base64,${readFileSync(join(FONTS, file)).toString("base64")}); }`;
+
+const html = `<!doctype html><html><head><style>
+${face(400, "normal", "LiberationSans-Regular.ttf")}
+${face(700, "normal", "LiberationSans-Bold.ttf")}
+${face(400, "italic", "LiberationSans-Italic.ttf")}
+${face(700, "italic", "LiberationSans-BoldItalic.ttf")}
+body { margin: 48px; font: 16px "Liberation Sans"; }
+p { margin: 0 0 14px; }
+</style></head><body>
+<p>Plain <b>bold</b> and <i>italic</i> and <b><i>both</i></b> in one line.</p>
+<p>Total due: <b>1,250.00 EUR</b> by Friday.</p>
+<p>Ratio a ≥ b → c, done ✓ today.</p>
+<p style="margin: 160px 0 0 140px">Note: <b>urgent</b> reply <i>needed</i> soon.</p>
+<p style="margin: 120px 0 0">Water is H<sub>2</sub>O and area is x<sup>2</sup> plus y<sup>3</sup>.</p>
+</body></html>`;
+
+const browser = await chromium.launch();
+const page = await browser.newPage();
+await page.setContent(html, { waitUntil: "load" });
+await page.evaluate(() => document.fonts.ready);
+const bytes = await page.pdf({ format: "A4" });
+await browser.close();
+const out = join(__dirname, "mixed-style-sample.pdf");
+writeFileSync(out, bytes);
+console.log(`wrote ${out} (${bytes.length} bytes)`);
diff --git a/frontend/src/editor/core/tests/test-fixtures/generate-rtl-marks-sample.mjs b/frontend/src/editor/core/tests/test-fixtures/generate-rtl-marks-sample.mjs
new file mode 100644
index 0000000000..1d4e0de925
--- /dev/null
+++ b/frontend/src/editor/core/tests/test-fixtures/generate-rtl-marks-sample.mjs
@@ -0,0 +1,37 @@
+// One-off script: generate `rtl-marks-sample.pdf`, a Hebrew line with niqqud and
+// an Arabic line with tashkeel, printed by Chromium with embedded subsets of
+// Noto Sans Hebrew and Noto Sans Arabic (both SIL OFL).
+//
+// Run with: node generate-rtl-marks-sample.mjs
+import { readFileSync, writeFileSync } from "node:fs";
+import { fileURLToPath } from "node:url";
+import { dirname, join } from "node:path";
+import { chromium } from "@playwright/test";
+
+const __dirname = dirname(fileURLToPath(import.meta.url));
+const FONTS = join(
+ __dirname,
+ "../../../../../../app/core/src/main/resources/static/fonts",
+);
+const face = (family, file) =>
+ `@font-face { font-family: "${family}"; src: url(data:font/ttf;base64,${readFileSync(join(FONTS, file)).toString("base64")}); }`;
+
+const html = `<!doctype html><html><head><style>
+${face("Hebrew", "NotoSansHebrew-Regular.ttf")}
+${face("Arabic", "NotoSansArabic-Regular.ttf")}
+body { margin: 48px; font: 20px "Hebrew", "Arabic"; }
+p { margin: 0 0 28px; }
+</style></head><body>
+<p dir="rtl">שָׁלוֹם עוֹלָם</p>
+<p dir="rtl">يُولَدُ جَمِيعُ النَّاسِ</p>
+</body></html>`;
+
+const browser = await chromium.launch();
+const page = await browser.newPage();
+await page.setContent(html, { waitUntil: "load" });
+await page.evaluate(() => document.fonts.ready);
+const bytes = await page.pdf({ format: "A6" });
+await browser.close();
+const out = join(__dirname, "rtl-marks-sample.pdf");
+writeFileSync(out, bytes);
+console.log(`wrote ${out} (${bytes.length} bytes)`);
diff --git a/frontend/src/editor/core/tests/test-fixtures/generate-rtl-mixed-sample.mjs b/frontend/src/editor/core/tests/test-fixtures/generate-rtl-mixed-sample.mjs
new file mode 100644
index 0000000000..371948d320
--- /dev/null
+++ b/frontend/src/editor/core/tests/test-fixtures/generate-rtl-mixed-sample.mjs
@@ -0,0 +1,45 @@
+// One-off script: generate `rtl-mixed-sample.pdf`, lines that mix directions:
+// Arabic and Hebrew holding numbers, Latin words and brackets, an English line
+// quoting both, and a right-to-left paragraph that opens with a Latin word.
+// Printed by Chromium with embedded subsets of Liberation Sans, Noto Sans
+// Hebrew and Noto Sans Arabic (all SIL OFL). Chromium draws the Arabic one
+// glyph per text object and the Latin, Hebrew and numbers a word or more per
+// object, so the file holds both shapes.
+//
+// Run with: node generate-rtl-mixed-sample.mjs
+import { readFileSync, writeFileSync } from "node:fs";
+import { fileURLToPath } from "node:url";
+import { dirname, join } from "node:path";
+import { chromium } from "@playwright/test";
+
+const __dirname = dirname(fileURLToPath(import.meta.url));
+const FONTS = join(
+ __dirname,
+ "../../../../../../app/core/src/main/resources/static/fonts",
+);
+const face = (family, file) =>
+ `@font-face { font-family: "${family}"; src: url(data:font/ttf;base64,${readFileSync(join(FONTS, file)).toString("base64")}); }`;
+
+const html = `<!doctype html><html><head><style>
+${face("Latin", "LiberationSans-Regular.ttf")}
+${face("Hebrew", "NotoSansHebrew-Regular.ttf")}
+${face("Arabic", "NotoSansArabic-Regular.ttf")}
+body { margin: 48px; font: 14px "Latin", "Hebrew", "Arabic"; }
+p { margin: 0 0 22px; }
+</style></head><body>
+<p dir="rtl">بلغ الاستهلاك (في الربع) 12,450.75 كيلوواط [بزيادة 3.5%] حسب تقرير ISO 50001</p>
+<p dir="rtl">استخدم برنامج LibreOffice Writer أو Word لفتح report-2026.docx الآن.</p>
+<p dir="rtl">הטלפון הוא 03-555-1234 (שלוחה 12), והמחיר 1,299.90 לפי Open Source סעיף 4.</p>
+<p>An English line quoting مرحبا بالعالم and שלום עולם then 1,234.</p>
+<p dir="rtl">ISO 50001 هو المعيار</p>
+</body></html>`;
+
+const browser = await chromium.launch();
+const page = await browser.newPage();
+await page.setContent(html, { waitUntil: "load" });
+await page.evaluate(() => document.fonts.ready);
+const bytes = await page.pdf({ format: "A4" });
+await browser.close();
+const out = join(__dirname, "rtl-mixed-sample.pdf");
+writeFileSync(out, bytes);
+console.log(`wrote ${out} (${bytes.length} bytes)`);
diff --git a/frontend/src/editor/core/tests/test-fixtures/generate-rtl-sample.mjs b/frontend/src/editor/core/tests/test-fixtures/generate-rtl-sample.mjs
new file mode 100644
index 0000000000..39bcd0ddfa
--- /dev/null
+++ b/frontend/src/editor/core/tests/test-fixtures/generate-rtl-sample.mjs
@@ -0,0 +1,37 @@
+// One-off script: generate `rtl-sample.pdf`, a right-to-left Hebrew line and a
+// left-to-right line with a Hebrew word in it, printed by Chromium with
+// embedded subsets of Noto Sans Hebrew and Liberation Sans (both SIL OFL).
+//
+// Run with: node generate-rtl-sample.mjs
+import { readFileSync, writeFileSync } from "node:fs";
+import { fileURLToPath } from "node:url";
+import { dirname, join } from "node:path";
+import { chromium } from "@playwright/test";
+
+const __dirname = dirname(fileURLToPath(import.meta.url));
+const FONTS = join(
+ __dirname,
+ "../../../../../../app/core/src/main/resources/static/fonts",
+);
+const face = (family, file) =>
+ `@font-face { font-family: "${family}"; src: url(data:font/ttf;base64,${readFileSync(join(FONTS, file)).toString("base64")}); }`;
+
+const html = `<!doctype html><html><head><style>
+${face("Latin", "LiberationSans-Regular.ttf")}
+${face("Hebrew", "NotoSansHebrew-Regular.ttf")}
+body { margin: 48px; font: 16px "Latin", "Hebrew"; }
+p { margin: 0 0 24px; }
+</style></head><body>
+<p dir="rtl">שלום עולם וברוכים הבאים</p>
+<p>Mixed: hello שלום world 123.</p>
+</body></html>`;
+
+const browser = await chromium.launch();
+const page = await browser.newPage();
+await page.setContent(html, { waitUntil: "load" });
+await page.evaluate(() => document.fonts.ready);
+const bytes = await page.pdf({ format: "A4" });
+await browser.close();
+const out = join(__dirname, "rtl-sample.pdf");
+writeFileSync(out, bytes);
+console.log(`wrote ${out} (${bytes.length} bytes)`);
diff --git a/frontend/src/editor/core/tests/test-fixtures/generate-scanned-ocr-outlined-address.sh b/frontend/src/editor/core/tests/test-fixtures/generate-scanned-ocr-outlined-address.sh
new file mode 100755
index 0000000000..8e325b7219
--- /dev/null
+++ b/frontend/src/editor/core/tests/test-fixtures/generate-scanned-ocr-outlined-address.sh
@@ -0,0 +1,27 @@
+#!/usr/bin/env bash
+# Writes scanned-ocr-outlined-address.pdf: an address block whose letters are
+# vector outlines, not text (as Microsoft Print to PDF emits), with ocrmypdf's
+# invisible text over it. Four black regular lines sit above a longer blue bold
+# link line, and OCR groups all five into one paragraph.
+set -euo pipefail
+here=$(cd "$(dirname "$0")" && pwd)
+work=$(mktemp -d)
+trap 'rm -rf "$work"' EXIT
+cat > "$work/address.ps" <<'PS'
+%!PS
+<< /PageSize [260 120] >> setpagedevice
+/Helvetica findfont 10 scalefont setfont
+0 0 0 setrgbcolor
+20 98 moveto (Stirling Tools Ltd) show
+20 84 moveto (12 Harbour Street) show
+20 70 moveto (Glasgow) show
+20 56 moveto (G1 4EE) show
+/Helvetica-Bold findfont 10 scalefont setfont
+0.05 0.25 0.85 setrgbcolor
+20 42 moveto (www.stirlingtools.example.com/contact) show
+showpage
+PS
+gs -q -dBATCH -dNOPAUSE -dNoOutputFonts -sDEVICE=pdfwrite \
+ -sOutputFile="$work/outlined.pdf" "$work/address.ps"
+ocrmypdf -q --output-type pdf "$work/outlined.pdf" \
+ "$here/scanned-ocr-outlined-address.pdf"
diff --git a/frontend/src/editor/core/tests/test-fixtures/generate-scanned-ocr-receipt.mjs b/frontend/src/editor/core/tests/test-fixtures/generate-scanned-ocr-receipt.mjs
new file mode 100644
index 0000000000..d827e6f601
--- /dev/null
+++ b/frontend/src/editor/core/tests/test-fixtures/generate-scanned-ocr-receipt.mjs
@@ -0,0 +1,71 @@
+// Generates `scanned-ocr-receipt.pdf`: a web receipt printed with its text
+// turned into outlines, the way Microsoft Print To PDF prints a web page, then
+// OCR'd by ocrmypdf 17. Small text with a web page's loose leading, a bordered
+// table of labels and values, and a footer address whose first line starts with
+// narrow letters, so OCR reports that line far smaller than the rest.
+//
+// Needs Ghostscript and ocrmypdf on PATH. Run with:
+// node generate-scanned-ocr-receipt.mjs
+import { execFileSync } from "node:child_process";
+import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { dirname, join } from "node:path";
+import { fileURLToPath } from "node:url";
+import { chromium } from "@playwright/test";
+
+const here = dirname(fileURLToPath(import.meta.url));
+
+const html = `<!doctype html><html><head><meta charset="utf-8"><style>
+@page { size: 300pt 400pt; margin: 0 }
+body { margin: 18pt 20pt; font-family: Arial, Helvetica, sans-serif; color: #000; }
+h1 { font-size: 13pt; margin: 0 0 8pt }
+p { font-size: 5.5pt; line-height: 10pt; margin: 0 0 9pt; width: 250pt }
+table { border-collapse: collapse; font-size: 7.5pt; margin: 4pt 0 12pt; width: 260pt }
+td { border: 0.75pt solid #000; padding: 3pt 4pt; }
+.footer { font-size: 4.5pt; line-height: 7pt; margin-top: 14pt }
+</style></head><body>
+<h1>Payment receipt</h1>
+<p>Thank you for your order. This receipt confirms the payment we received for the items listed below and can be kept for your records.</p>
+<table>
+<tr><td>Order number</td><td>Northwind 88213</td></tr>
+<tr><td>Payment date</td><td>Monday 3 March</td></tr>
+<tr><td>Payment method</td><td>Visa ending 4417</td></tr>
+<tr><td>Amount paid</td><td>Forty two pounds</td></tr>
+</table>
+<p>Questions about this payment can be sent to our support team, who will reply within two working days of receiving your message.</p>
+<div class="footer">Il Forno Trading Limited<br>Iliffe House, Unit 4<br>Kingsway Road, Bristol<br>United Kingdom BS1 6QA<br>Registered in England 0458812</div>
+</body></html>`;
+
+const work = mkdtempSync(join(tmpdir(), "ocr-receipt-"));
+try {
+ const source = join(work, "receipt.html");
+ const printed = join(work, "printed.pdf");
+ const outlined = join(work, "outlined.pdf");
+ writeFileSync(source, html);
+ const browser = await chromium.launch();
+ const page = await browser.newPage();
+ await page.goto(`file://${source}`);
+ await page.pdf({ path: printed, preferCSSPageSize: true });
+ await browser.close();
+ execFileSync("gs", [
+ "-q",
+ "-dNOPAUSE",
+ "-dBATCH",
+ "-sDEVICE=pdfwrite",
+ "-dNoOutputFonts",
+ "-o",
+ outlined,
+ printed,
+ ]);
+ execFileSync("ocrmypdf", [
+ "-q",
+ "-l",
+ "eng",
+ "--output-type",
+ "pdf",
+ outlined,
+ join(here, "scanned-ocr-receipt.pdf"),
+ ]);
+} finally {
+ rmSync(work, { recursive: true, force: true });
+}
diff --git a/frontend/src/editor/core/tests/test-fixtures/generate-scanned-ocr-tesseract.sh b/frontend/src/editor/core/tests/test-fixtures/generate-scanned-ocr-tesseract.sh
new file mode 100755
index 0000000000..eae063e3e5
--- /dev/null
+++ b/frontend/src/editor/core/tests/test-fixtures/generate-scanned-ocr-tesseract.sh
@@ -0,0 +1,24 @@
+#!/usr/bin/env bash
+# Writes scanned-ocr-tesseract.pdf: a 300 dpi scan of five lines of serif text
+# with Tesseract's own invisible text over it. Tesseract boxes each word with
+# its trailing space and stretches it to that box, so a word's space overhangs
+# the next word.
+set -euo pipefail
+here=$(cd "$(dirname "$0")" && pwd)
+work=$(mktemp -d)
+trap 'rm -rf "$work"' EXIT
+cat > "$work/page.ps" <<'PS'
+%!PS
+<< /PageSize [612 260] >> setpagedevice
+/Times-Roman findfont 13 scalefont setfont
+60 220 moveto (The quick brown fox jumps over the lazy dog while) show
+60 200 moveto (the farmer counts his sheep in the field. Pack my box with five dozen) show
+60 180 moveto (liquor jugs before the market closes for the evening.) show
+60 160 moveto (Sphinx of black quartz, judge my vow. How vexingly quick) show
+60 140 moveto (daft zebras jump when the wizard calls them home.) show
+showpage
+PS
+gs -q -dBATCH -dNOPAUSE -sDEVICE=pnggray -r300 \
+ -sOutputFile="$work/page.png" "$work/page.ps"
+tesseract "$work/page.png" "$work/page" -l eng --dpi 300 pdf >/dev/null 2>&1
+mv "$work/page.pdf" "$here/scanned-ocr-tesseract.pdf"
diff --git a/frontend/src/editor/core/tests/test-fixtures/generate-shaped-line-sample.mjs b/frontend/src/editor/core/tests/test-fixtures/generate-shaped-line-sample.mjs
new file mode 100644
index 0000000000..444905ca3a
--- /dev/null
+++ b/frontend/src/editor/core/tests/test-fixtures/generate-shaped-line-sample.mjs
@@ -0,0 +1,37 @@
+// One-off script: generate `shaped-line-sample.pdf`, a Devanagari line ending
+// in Latin punctuation and digits, printed by Chromium with embedded subsets of
+// Noto Sans Devanagari and Liberation Sans (both SIL OFL). Its conjuncts and
+// vowel signs are single shaped glyphs, which no other font can stand in for.
+//
+// Run with: node generate-shaped-line-sample.mjs
+import { readFileSync, writeFileSync } from "node:fs";
+import { fileURLToPath } from "node:url";
+import { dirname, join } from "node:path";
+import { chromium } from "@playwright/test";
+
+const __dirname = dirname(fileURLToPath(import.meta.url));
+const FONTS = join(
+ __dirname,
+ "../../../../../../app/core/src/main/resources/static/fonts",
+);
+const face = (family, file) =>
+ `@font-face { font-family: "${family}"; src: url(data:font/ttf;base64,${readFileSync(join(FONTS, file)).toString("base64")}); }`;
+
+const html = `<!doctype html><html><head><style>
+${face("Latin", "LiberationSans-Regular.ttf")}
+${face("Devanagari", "NotoSansDevanagari-Regular.ttf")}
+body { margin: 48px; font: 20px "Latin", "Devanagari"; }
+p { margin: 0; }
+</style></head><body>
+<p>नमस्ते दुनिया, 2024.</p>
+</body></html>`;
+
+const browser = await chromium.launch();
+const page = await browser.newPage();
+await page.setContent(html, { waitUntil: "load" });
+await page.evaluate(() => document.fonts.ready);
+const bytes = await page.pdf({ format: "A6" });
+await browser.close();
+const out = join(__dirname, "shaped-line-sample.pdf");
+writeFileSync(out, bytes);
+console.log(`wrote ${out} (${bytes.length} bytes)`);
diff --git a/frontend/src/editor/core/tests/test-fixtures/generate-subset-truetype-heading.sh b/frontend/src/editor/core/tests/test-fixtures/generate-subset-truetype-heading.sh
new file mode 100755
index 0000000000..834fcffd8e
--- /dev/null
+++ b/frontend/src/editor/core/tests/test-fixtures/generate-subset-truetype-heading.sh
@@ -0,0 +1,17 @@
+#!/usr/bin/env bash
+# Writes subset-truetype-heading.pdf: one bold heading set by cairo in a subset
+# of the bundled DejaVu Sans Bold, as a simple WinAnsi TrueType font with a
+# ToUnicode map. Such a subset keeps a code for letters it has no outline for,
+# which is the case the text editor's fallback has to catch.
+set -euo pipefail
+here=$(cd "$(dirname "$0")" && pwd)
+fonts=$(mktemp -d)
+trap 'rm -rf "$fonts"' EXIT
+cp "$here/../../../../../../app/core/src/main/resources/static/fonts/DejaVuSans-Bold.ttf" "$fonts/"
+cat > "$fonts/fonts.conf" <<CONF
+<?xml version="1.0"?><!DOCTYPE fontconfig SYSTEM "fonts.dtd">
+<fontconfig><dir>$fonts</dir><cachedir>$fonts/cache</cachedir></fontconfig>
+CONF
+PANGOCAIRO_BACKEND=fc FONTCONFIG_FILE="$fonts/fonts.conf" pango-view --no-display \
+ --font="DejaVu Sans Bold 24" --text="Quarterly report heading" --margin=20 \
+ -o "$here/subset-truetype-heading.pdf"
diff --git a/frontend/src/editor/core/tests/test-fixtures/generate-thai-line-sample.mjs b/frontend/src/editor/core/tests/test-fixtures/generate-thai-line-sample.mjs
new file mode 100644
index 0000000000..99fc258002
--- /dev/null
+++ b/frontend/src/editor/core/tests/test-fixtures/generate-thai-line-sample.mjs
@@ -0,0 +1,36 @@
+// One-off script: generate `thai-line-sample.pdf`, a Thai line with no spaces
+// between its words, printed by Chromium with an embedded subset of Noto Sans
+// Thai (SIL OFL). Its vowel and tone marks are drawn as glyphs of their own,
+// stacked over the letters they belong to.
+//
+// Run with: node generate-thai-line-sample.mjs
+import { readFileSync, writeFileSync } from "node:fs";
+import { fileURLToPath } from "node:url";
+import { dirname, join } from "node:path";
+import { chromium } from "@playwright/test";
+
+const __dirname = dirname(fileURLToPath(import.meta.url));
+const FONTS = join(
+ __dirname,
+ "../../../../../../app/core/src/main/resources/static/fonts",
+);
+const face = (family, file) =>
+ `@font-face { font-family: "${family}"; src: url(data:font/ttf;base64,${readFileSync(join(FONTS, file)).toString("base64")}); }`;
+
+const html = `<!doctype html><html><head><style>
+${face("Thai", "NotoSansThai-Regular.ttf")}
+body { margin: 48px; font: 20px "Thai"; }
+p { margin: 0; }
+</style></head><body>
+<p>มนุษย์ทั้งหลายเกิดมามีอิสระ</p>
+</body></html>`;
+
+const browser = await chromium.launch();
+const page = await browser.newPage();
+await page.setContent(html, { waitUntil: "load" });
+await page.evaluate(() => document.fonts.ready);
+const bytes = await page.pdf({ format: "A6" });
+await browser.close();
+const out = join(__dirname, "thai-line-sample.pdf");
+writeFileSync(out, bytes);
+console.log(`wrote ${out} (${bytes.length} bytes)`);
diff --git a/frontend/src/editor/core/tests/test-fixtures/generate-two-column-sample.mjs b/frontend/src/editor/core/tests/test-fixtures/generate-two-column-sample.mjs
new file mode 100644
index 0000000000..2c8b7f95fb
--- /dev/null
+++ b/frontend/src/editor/core/tests/test-fixtures/generate-two-column-sample.mjs
@@ -0,0 +1,162 @@
+import process from "node:process";
+// One-off script: generate `two-column-sample.pdf`.
+//
+// Page 1 - justified text in two columns 10pt apart, one Tj per line the way
+// TeX sets it, under a running header with its page number set
+// right beside it. The gutter is narrower than the widest gap a line
+// may hold, so only its alignment down the page tells it apart.
+// Page 2 - one column, each word its own object the way word processors save
+// justified text, with word gaps as wide as that gutter; and a list
+// of short labels with their values a tab stop away.
+//
+// Run with: node generate-two-column-sample.mjs
+import { writeFileSync } from "node:fs";
+import { fileURLToPath } from "node:url";
+import { dirname, join } from "node:path";
+import {
+ PDFDocument,
+ PDFName,
+ PDFRawStream,
+ StandardFonts,
+} from "@cantoo/pdf-lib";
+
+const __dirname = dirname(fileURLToPath(import.meta.url));
+const SIZE = 10;
+const LEADING = 12;
+const COLUMN_WIDTH = 240;
+const LEFT_X = 56;
+const RIGHT_X = LEFT_X + COLUMN_WIDTH + 10;
+const TOP = 720;
+
+const LEFT_TEXT = [
+ "Northern ferries carry freight between the islands every morning and return with the mail before the harbour closes for the night.",
+ "Weather reports arrive by radio at dawn, and the captains decide together whether the crossing is safe enough for the smaller boats.",
+];
+const RIGHT_TEXT = [
+ "Village councils meet each month to plan repairs to the piers, the lighthouse and the narrow roads that link the farms to the quay.",
+ "Visitors in summer double the population, so the councils publish timetables early and ask the bakeries to open their doors sooner.",
+];
+
+const LABELS = [
+ ["Name:", "Jana Novak, harbour office of the northern islands"],
+ ["Room:", "Freight bookings and passenger timetables for summer"],
+ ["Email:", "Crossing schedules and the second revision of fares"],
+ ["Code:", "Extension two hundred and eleven during office hours"],
+ ["Name:", "Tomas Berg, weather desk and the morning radio report"],
+];
+const LABEL_TAB = 37.5;
+
+const JUSTIFIED = [
+ ["Every", "word", "of", "this", "paragraph", "is", "its", "own"],
+ ["object,", "spread", "across", "the", "measure", "with", "gaps"],
+ ["as", "wide", "as", "a", "narrow", "column", "gutter", "so"],
+ ["only", "the", "page", "layout", "can", "say", "which", "gap"],
+ ["is", "a", "gutter", "and", "which", "is", "a", "word", "space."],
+];
+const JUSTIFIED_WIDTH = 220;
+
+function escape(text) {
+ return text.replace(/[\\()]/g, (c) => `\\${c}`);
+}
+
+function wrap(font, text, width) {
+ const lines = [];
+ let line = [];
+ for (const word of text.split(" ")) {
+ const next = [...line, word].join(" ");
+ if (line.length > 0 && font.widthOfTextAtSize(next, SIZE) > width) {
+ lines.push(line);
+ line = [word];
+ } else line.push(word);
+ }
+ lines.push(line);
+ return lines;
+}
+
+function column(font, paragraphs, x) {
+ const ops = [];
+ let y = TOP;
+ for (const paragraph of paragraphs) {
+ const lines = wrap(font, paragraph, COLUMN_WIDTH);
+ lines.forEach((words, i) => {
+ const text = words.join(" ");
+ const last = i === lines.length - 1;
+ const spare = COLUMN_WIDTH - font.widthOfTextAtSize(text, SIZE);
+ const tw = last ? 0 : spare / (words.length - 1);
+ ops.push(
+ `BT /F1 ${SIZE} Tf ${tw.toFixed(3)} Tw ${x} ${y} Td (${escape(text)}) Tj ET`,
+ );
+ y -= LEADING;
+ });
+ y -= LEADING;
+ }
+ return ops;
+}
+
+function rawStream(doc, body) {
+ const bytes = new TextEncoder().encode(body);
+ return doc.context.register(
+ PDFRawStream.of(doc.context.obj({ Length: bytes.length }), bytes),
+ );
+}
+
+function addPage(doc, font, ops) {
+ const page = doc.addPage([612, 792]);
+ page.node.setFontDictionary(PDFName.of("F1"), font.ref);
+ page.node.set(PDFName.of("Contents"), rawStream(doc, ops.join("\n")));
+}
+
+async function main() {
+ const doc = await PDFDocument.create();
+ const font = await doc.embedFont(StandardFonts.Helvetica);
+
+ const header =
+ "Island transport survey, second interim report to the regional council";
+ const headerRight = RIGHT_X + COLUMN_WIDTH;
+ const number = "1";
+ const numberX = headerRight - font.widthOfTextAtSize(number, SIZE);
+ const headerX = numberX - 8 - font.widthOfTextAtSize(header, SIZE);
+ addPage(doc, font, [
+ `BT /F1 ${SIZE} Tf ${headerX.toFixed(2)} 750 Td (${escape(header)}) Tj ET`,
+ `BT /F1 ${SIZE} Tf ${numberX.toFixed(2)} 750 Td (${number}) Tj ET`,
+ ...column(font, LEFT_TEXT, LEFT_X),
+ ...column(font, RIGHT_TEXT, RIGHT_X),
+ ]);
+
+ const second = [];
+ let y = TOP;
+ for (const words of JUSTIFIED) {
+ const inked = words.reduce(
+ (sum, word) => sum + font.widthOfTextAtSize(word, SIZE),
+ 0,
+ );
+ const gap = (JUSTIFIED_WIDTH - inked) / (words.length - 1);
+ let x = LEFT_X;
+ for (const word of words) {
+ second.push(
+ `BT /F1 ${SIZE} Tf ${x.toFixed(2)} ${y} Td (${escape(word)}) Tj ET`,
+ );
+ x += font.widthOfTextAtSize(word, SIZE) + gap;
+ }
+ y -= LEADING;
+ }
+ y -= 2 * LEADING;
+ for (const [label, value] of LABELS) {
+ second.push(`BT /F1 ${SIZE} Tf ${LEFT_X} ${y} Td (${escape(label)}) Tj ET`);
+ second.push(
+ `BT /F1 ${SIZE} Tf ${LEFT_X + LABEL_TAB} ${y} Td (${escape(value)}) Tj ET`,
+ );
+ y -= LEADING;
+ }
+ addPage(doc, font, second);
+
+ const bytes = await doc.save({ useObjectStreams: false });
+ const out = join(__dirname, "two-column-sample.pdf");
+ writeFileSync(out, bytes);
+ console.log(`wrote ${out} (${bytes.length} bytes)`);
+}
+
+main().catch((err) => {
+ console.error(err);
+ process.exit(1);
+});
diff --git a/frontend/src/editor/core/tests/test-fixtures/ligature-heading.pdf b/frontend/src/editor/core/tests/test-fixtures/ligature-heading.pdf
new file mode 100644
index 0000000000..8c76e84b52
Binary files /dev/null and b/frontend/src/editor/core/tests/test-fixtures/ligature-heading.pdf differ
diff --git a/frontend/src/editor/core/tests/test-fixtures/mixed-style-sample.pdf b/frontend/src/editor/core/tests/test-fixtures/mixed-style-sample.pdf
new file mode 100644
index 0000000000..34ef88e285
Binary files /dev/null and b/frontend/src/editor/core/tests/test-fixtures/mixed-style-sample.pdf differ
diff --git a/frontend/src/editor/core/tests/test-fixtures/rtl-marks-sample.pdf b/frontend/src/editor/core/tests/test-fixtures/rtl-marks-sample.pdf
new file mode 100644
index 0000000000..b646067245
Binary files /dev/null and b/frontend/src/editor/core/tests/test-fixtures/rtl-marks-sample.pdf differ
diff --git a/frontend/src/editor/core/tests/test-fixtures/rtl-mixed-sample.pdf b/frontend/src/editor/core/tests/test-fixtures/rtl-mixed-sample.pdf
new file mode 100644
index 0000000000..e361c1ad96
Binary files /dev/null and b/frontend/src/editor/core/tests/test-fixtures/rtl-mixed-sample.pdf differ
diff --git a/frontend/src/editor/core/tests/test-fixtures/rtl-sample.pdf b/frontend/src/editor/core/tests/test-fixtures/rtl-sample.pdf
new file mode 100644
index 0000000000..8b044fb82e
Binary files /dev/null and b/frontend/src/editor/core/tests/test-fixtures/rtl-sample.pdf differ
diff --git a/frontend/src/editor/core/tests/test-fixtures/scanned-ocr-outlined-address.pdf b/frontend/src/editor/core/tests/test-fixtures/scanned-ocr-outlined-address.pdf
new file mode 100644
index 0000000000..0e0ac79b38
Binary files /dev/null and b/frontend/src/editor/core/tests/test-fixtures/scanned-ocr-outlined-address.pdf differ
diff --git a/frontend/src/editor/core/tests/test-fixtures/scanned-ocr-receipt.pdf b/frontend/src/editor/core/tests/test-fixtures/scanned-ocr-receipt.pdf
new file mode 100644
index 0000000000..050b011652
Binary files /dev/null and b/frontend/src/editor/core/tests/test-fixtures/scanned-ocr-receipt.pdf differ
diff --git a/frontend/src/editor/core/tests/test-fixtures/scanned-ocr-tesseract.pdf b/frontend/src/editor/core/tests/test-fixtures/scanned-ocr-tesseract.pdf
new file mode 100644
index 0000000000..0e86e81937
Binary files /dev/null and b/frontend/src/editor/core/tests/test-fixtures/scanned-ocr-tesseract.pdf differ
diff --git a/frontend/src/editor/core/tests/test-fixtures/shaped-line-sample.pdf b/frontend/src/editor/core/tests/test-fixtures/shaped-line-sample.pdf
new file mode 100644
index 0000000000..fb0972457f
Binary files /dev/null and b/frontend/src/editor/core/tests/test-fixtures/shaped-line-sample.pdf differ
diff --git a/frontend/src/editor/core/tests/test-fixtures/subset-truetype-heading.pdf b/frontend/src/editor/core/tests/test-fixtures/subset-truetype-heading.pdf
new file mode 100644
index 0000000000..4c1aa0bfac
Binary files /dev/null and b/frontend/src/editor/core/tests/test-fixtures/subset-truetype-heading.pdf differ
diff --git a/frontend/src/editor/core/tests/test-fixtures/thai-line-sample.pdf b/frontend/src/editor/core/tests/test-fixtures/thai-line-sample.pdf
new file mode 100644
index 0000000000..413cd75501
Binary files /dev/null and b/frontend/src/editor/core/tests/test-fixtures/thai-line-sample.pdf differ
diff --git a/frontend/src/editor/core/tests/test-fixtures/two-column-sample.pdf b/frontend/src/editor/core/tests/test-fixtures/two-column-sample.pdf
new file mode 100644
index 0000000000..b205120f03
--- /dev/null
+++ b/frontend/src/editor/core/tests/test-fixtures/two-column-sample.pdf
@@ -0,0 +1,176 @@
+%PDF-1.7
+%����
+
+1 0 obj
+<<
+/Type /Pages
+/Kids [ 5 0 R 7 0 R ]
+/Count 2
+>>
+endobj
+
+2 0 obj
+<<
+/Type /Catalog
+/Pages 1 0 R
+>>
+endobj
+
+3 0 obj
+<<
+/Producer <FEFF007000640066002D006C006900620020002800680074007400700073003A002F002F006700690074006800750062002E0063006F006D002F0048006F007000640069006E0067002F007000640066002D006C006900620029>
+/ModDate (D:20261117121504Z)
+/Creator <FEFF007000640066002D006C006900620020002800680074007400700073003A002F002F006700690074006800750062002E0063006F006D002F0048006F007000640069006E0067002F007000640066002D006C006900620029>
+/CreationDate (D:20261117121504Z)
+>>
+endobj
+
+4 0 obj
+<<
+/Type /Font
+/Subtype /Type1
+/BaseFont /Helvetica
+/Encoding /WinAnsiEncoding
+>>
+endobj
+
+5 0 obj
+<<
+/Type /Page
+/Parent 1 0 R
+/Resources <<
+/Font <<
+/F1 4 0 R
+>>
+/XObject <<
+>>
+/ExtGState <<
+>>
+>>
+/MediaBox [ 0 0 612 792 ]
+/Annots [ ]
+/Contents 6 0 R
+>>
+endobj
+
+6 0 obj
+<<
+/Length 1156
+>>
+stream
+BT /F1 10 Tf 232.06 750 Td (Island transport survey, second interim report to the regional council) Tj ET
+BT /F1 10 Tf 540.44 750 Td (1) Tj ET
+BT /F1 10 Tf 3.852 Tw 56 720 Td (Northern ferries carry freight between the islands) Tj ET
+BT /F1 10 Tf 2.773 Tw 56 708 Td (every morning and return with the mail before the) Tj ET
+BT /F1 10 Tf 0.000 Tw 56 696 Td (harbour closes for the night.) Tj ET
+BT /F1 10 Tf 3.245 Tw 56 672 Td (Weather reports arrive by radio at dawn, and the) Tj ET
+BT /F1 10 Tf 0.661 Tw 56 660 Td (captains decide together whether the crossing is safe) Tj ET
+BT /F1 10 Tf 0.000 Tw 56 648 Td (enough for the smaller boats.) Tj ET
+BT /F1 10 Tf 1.724 Tw 306 720 Td (Village councils meet each month to plan repairs to) Tj ET
+BT /F1 10 Tf 2.175 Tw 306 708 Td (the piers, the lighthouse and the narrow roads that) Tj ET
+BT /F1 10 Tf 0.000 Tw 306 696 Td (link the farms to the quay.) Tj ET
+BT /F1 10 Tf 3.824 Tw 306 672 Td (Visitors in summer double the population, so the) Tj ET
+BT /F1 10 Tf 0.267 Tw 306 660 Td (councils publish timetables early and ask the bakeries) Tj ET
+BT /F1 10 Tf 0.000 Tw 306 648 Td (to open their doors sooner.) Tj ET
+endstream
+endobj
+
+7 0 obj
+<<
+/Type /Page
+/Parent 1 0 R
+/Resources <<
+/Font <<
+/F1 4 0 R
+>>
+/XObject <<
+>>
+/ExtGState <<
+>>
+>>
+/MediaBox [ 0 0 612 792 ]
+/Annots [ ]
+/Contents 8 0 R
+>>
+endobj
+
+8 0 obj
+<<
+/Length 2201
+>>
+stream
+BT /F1 10 Tf 56.00 720 Td (Every) Tj ET
+BT /F1 10 Tf 91.36 720 Td (word) Tj ET
+BT /F1 10 Tf 122.67 720 Td (of) Tj ET
+BT /F1 10 Tf 140.76 720 Td (this) Tj ET
+BT /F1 10 Tf 166.07 720 Td (paragraph) Tj ET
+BT /F1 10 Tf 221.10 720 Td (is) Tj ET
+BT /F1 10 Tf 238.06 720 Td (its) Tj ET
+BT /F1 10 Tf 257.81 720 Td (own) Tj ET
+BT /F1 10 Tf 56.00 708 Td (object,) Tj ET
+BT /F1 10 Tf 91.84 708 Td (spread) Tj ET
+BT /F1 10 Tf 128.78 708 Td (across) Tj ET
+BT /F1 10 Tf 164.61 708 Td (the) Tj ET
+BT /F1 10 Tf 184.89 708 Td (measure) Tj ET
+BT /F1 10 Tf 230.16 708 Td (with) Tj ET
+BT /F1 10 Tf 254.32 708 Td (gaps) Tj ET
+BT /F1 10 Tf 56.00 696 Td (as) Tj ET
+BT /F1 10 Tf 77.13 696 Td (wide) Tj ET
+BT /F1 10 Tf 108.26 696 Td (as) Tj ET
+BT /F1 10 Tf 129.39 696 Td (a) Tj ET
+BT /F1 10 Tf 145.52 696 Td (narrow) Tj ET
+BT /F1 10 Tf 186.50 696 Td (column) Tj ET
+BT /F1 10 Tf 229.30 696 Td (gutter) Tj ET
+BT /F1 10 Tf 265.44 696 Td (so) Tj ET
+BT /F1 10 Tf 56.00 684 Td (only) Tj ET
+BT /F1 10 Tf 83.73 684 Td (the) Tj ET
+BT /F1 10 Tf 107.02 684 Td (page) Tj ET
+BT /F1 10 Tf 138.65 684 Td (layout) Tj ET
+BT /F1 10 Tf 174.21 684 Td (can) Tj ET
+BT /F1 10 Tf 199.72 684 Td (say) Tj ET
+BT /F1 10 Tf 224.37 684 Td (which) Tj ET
+BT /F1 10 Tf 259.32 684 Td (gap) Tj ET
+BT /F1 10 Tf 56.00 672 Td (is) Tj ET
+BT /F1 10 Tf 72.69 672 Td (a) Tj ET
+BT /F1 10 Tf 87.72 672 Td (gutter) Tj ET
+BT /F1 10 Tf 122.76 672 Td (and) Tj ET
+BT /F1 10 Tf 148.91 672 Td (which) Tj ET
+BT /F1 10 Tf 183.93 672 Td (is) Tj ET
+BT /F1 10 Tf 200.62 672 Td (a) Tj ET
+BT /F1 10 Tf 215.65 672 Td (word) Tj ET
+BT /F1 10 Tf 246.69 672 Td (space.) Tj ET
+BT /F1 10 Tf 56 636 Td (Name:) Tj ET
+BT /F1 10 Tf 93.5 636 Td (Jana Novak, harbour office of the northern islands) Tj ET
+BT /F1 10 Tf 56 624 Td (Room:) Tj ET
+BT /F1 10 Tf 93.5 624 Td (Freight bookings and passenger timetables for summer) Tj ET
+BT /F1 10 Tf 56 612 Td (Email:) Tj ET
+BT /F1 10 Tf 93.5 612 Td (Crossing schedules and the second revision of fares) Tj ET
+BT /F1 10 Tf 56 600 Td (Code:) Tj ET
+BT /F1 10 Tf 93.5 600 Td (Extension two hundred and eleven during office hours) Tj ET
+BT /F1 10 Tf 56 588 Td (Name:) Tj ET
+BT /F1 10 Tf 93.5 588 Td (Tomas Berg, weather desk and the morning radio report) Tj ET
+endstream
+endobj
+
+xref
+0 9
+0000000000 65535 f
+0000000016 00000 n
+0000000082 00000 n
+0000000132 00000 n
+0000000602 00000 n
+0000000700 00000 n
+0000000873 00000 n
+0000002082 00000 n
+0000002255 00000 n
+
+trailer
+<<
+/Size 9
+/Root 2 0 R
+/Info 3 0 R
+>>
+
+startxref
+4509
+%%EOF
\ No newline at end of file
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/PdfTextEditor.tsx b/frontend/src/editor/core/tools/pdfTextEditor/PdfTextEditor.tsx
index da1adb7230..aeb9df1095 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/PdfTextEditor.tsx
+++ b/frontend/src/editor/core/tools/pdfTextEditor/PdfTextEditor.tsx
@@ -30,8 +30,10 @@ import {
import { useAutoLoadFile } from "@editor/tools/pdfTextEditor/hooks/useAutoLoadFile";
import { useWorkbenchPin } from "@editor/tools/pdfTextEditor/hooks/useWorkbenchPin";
import { useUnsavedChangesGuard } from "@editor/tools/pdfTextEditor/hooks/useUnsavedChangesGuard";
+import { useDeferredPanelView } from "@editor/tools/pdfTextEditor/hooks/useDeferredPanelView";
import { useEditorTestGlobal } from "@editor/tools/pdfTextEditor/hooks/useEditorTestGlobal";
import { useSelectionActions } from "@editor/tools/pdfTextEditor/hooks/useSelectionActions";
+import { useFontChangeWarning } from "@editor/tools/pdfTextEditor/components/fontPickFailure";
import { useEditorKeyboardShortcuts } from "@editor/tools/pdfTextEditor/hooks/useEditorKeyboardShortcuts";
import { useEditorClipboard } from "@editor/tools/pdfTextEditor/hooks/useEditorClipboard";
import { useOpenAtViewerText } from "@editor/tools/pdfTextEditor/hooks/useOpenAtViewerText";
@@ -51,9 +53,11 @@ import {
ViewerEditToolbar,
} from "@editor/tools/pdfTextEditor/components/ViewerEditToolbar";
import { useRegisterViewerPageTool } from "@editor/contexts/viewer/ViewerPageTool";
-import { InsertImageCommand } from "@editor/tools/pdfTextEditor/commands/InsertImageCommand";
+import {
+ centredImageRect,
+ InsertImageCommand,
+} from "@editor/tools/pdfTextEditor/commands/InsertImageCommand";
import { InsertTextCommand } from "@editor/tools/pdfTextEditor/commands/InsertTextCommand";
-import { DisplayTransform } from "@editor/tools/pdfTextEditor/model/DisplayTransform";
import { jpegExifOrientation } from "@editor/utils/jpegOrientation";
import { MergeRunsCommand } from "@editor/tools/pdfTextEditor/commands/MergeRunsCommand";
import { UngroupParagraphCommand } from "@editor/tools/pdfTextEditor/commands/UngroupParagraphCommand";
@@ -130,7 +134,8 @@ export default function PdfTextEditor(_props: BaseToolProps) {
useEditorTestGlobal(store);
// Dropping the document discards its edits; the file is then reopened fresh.
const discardEdits = useCallback(() => store.clearDocument(), [store]);
- useUnsavedChangesGuard(state.dirty);
+ const isDirty = useCallback(() => store.getState().dirty, [store]);
+ useUnsavedChangesGuard(state.dirty, isDirty);
const pinWorkbench = useWorkbenchPin();
// Opening a file can leave the workbench on Active Files, so landing a
// document pins the viewer back.
@@ -169,6 +174,7 @@ export default function PdfTextEditor(_props: BaseToolProps) {
useScanPrefit(store, state);
const sel = useSelectionActions(store);
+ const warnAboutFontChange = useFontChangeWarning();
// Guards against re-entrant saves while a (synchronous) serialize runs.
const savingRef = useRef(false);
@@ -303,7 +309,8 @@ export default function PdfTextEditor(_props: BaseToolProps) {
"pdfTextEditor",
isCurrent,
);
- if (!saved) return;
+ // The write-back swaps the source file id, so only the document is compared.
+ if (!saved || store.document !== doc) return;
store.markSaved(exported);
if (download) {
assertFilesNotBlocked([sourceId ?? undefined]);
@@ -460,23 +467,18 @@ export default function PdfTextEditor(_props: BaseToolProps) {
const visibleIndex = visiblePageNumber();
const page = pages.find((p) => p.pageIndex === visibleIndex) ?? pages[0];
if (!page) return;
- const w = page.width * INSERTED_IMAGE_RATIO;
- const h = w * (decoded.height / decoded.width);
- // Centre in the VISIBLE (display) page, then invert the CropBox/rotation
- // transform to raw PDF space (commands store raw coords).
- const ll = DisplayTransform.fromData(page.display).invert(
- (page.width - w) / 2,
- (page.height - h) / 2,
+ const rect = centredImageRect(
+ page.display,
+ decoded.width,
+ decoded.height,
+ INSERTED_IMAGE_RATIO,
);
const cmd = new InsertImageCommand({
pageIndex: page.pageIndex,
rgba: decoded.data.data,
pixelWidth: decoded.width,
pixelHeight: decoded.height,
- x: ll.x,
- y: ll.y,
- width: w,
- height: h,
+ ...rect,
jpegBytes,
});
store.dispatch(cmd);
@@ -641,6 +643,14 @@ export default function PdfTextEditor(_props: BaseToolProps) {
onFindNext: handleFindNext,
onEscape: handleEscape,
onMergeSelection: handleMergeSelection,
+ onToggleBold: useCallback(
+ () => void warnAboutFontChange(sel.toggleBold),
+ [warnAboutFontChange, sel.toggleBold],
+ ),
+ onToggleItalic: useCallback(
+ () => void warnAboutFontChange(sel.toggleItalic),
+ [warnAboutFontChange, sel.toggleItalic],
+ ),
});
useEditorClipboard({
@@ -650,14 +660,6 @@ export default function PdfTextEditor(_props: BaseToolProps) {
insertPastedText,
});
- const canGroup = selection.runIds.length >= 2;
- const canUngroup = (() => {
- if (selection.runIds.length !== 1) return false;
- const run = state.pages
- .flatMap((p) => p.runs)
- .find((r) => r.id === selection.runIds[0]);
- return !!run && (run.paragraphLineCount ?? 0) > 1;
- })();
const openImagePicker = useCallback(() => {
document
.querySelector<HTMLInputElement>('[data-testid="pdf-editor-image-input"]')
@@ -696,29 +698,58 @@ export default function PdfTextEditor(_props: BaseToolProps) {
store.clearPasswordPrompt();
}, [store, cancelAutoLoad]);
+ const onSetGroupingMode = useCallback(
+ (mode: GroupingMode) => store.setGroupingMode(mode),
+ [store],
+ );
+ const onSetWidthMode = useCallback(
+ (m: WidthMode) => store.setWidthMode(m),
+ [store],
+ );
+ const onSetShowRulers = useCallback(
+ (show: boolean) => store.setShowRulers(show),
+ [store],
+ );
+ const runOcr = ocr.runOcr;
+ const onRunOcr = useCallback(() => {
+ if (!savingRef.current && !applying) void runOcr();
+ }, [applying, runOcr]);
+ const removePassword = useCallback(() => {
+ if (!sourceFileId) return;
+ setSelectedFiles([sourceFileId]);
+ handleToolSelect("removePassword");
+ }, [sourceFileId, setSelectedFiles, handleToolSelect]);
+ const onOpenFind = useCallback(() => {
+ if (store.toggleFindOpen()) pinWorkbench();
+ }, [store, pinWorkbench]);
+ const onShowHelp = useCallback(() => store.setHelpOpen(true), [store]);
+
+ // Deferred so the typed letter is drawn before the panel, which a burst of typing outdates.
+ const panel = useDeferredPanelView(state, selection);
+ const canUngroup = useMemo(() => {
+ const ids = panel.selection.runIds;
+ if (ids.length !== 1) return false;
+ const run = panel.state.pages
+ .flatMap((p) => p.runs)
+ .find((r) => r.id === ids[0]);
+ return !!run && (run.paragraphLineCount ?? 0) > 1;
+ }, [panel]);
const sidebarProps = {
store,
- state,
- selection,
- canGroup,
+ state: panel.state,
+ selection: panel.selection,
+ canGroup: panel.selection.runIds.length >= 2,
canUngroup,
onGroup: handleMergeSelection,
onUngroup: handleUngroupSelection,
- onSetGroupingMode: (mode: GroupingMode) => store.setGroupingMode(mode),
- onSetWidthMode: (m: WidthMode) => store.setWidthMode(m),
- onSetShowRulers: (show: boolean) => store.setShowRulers(show),
- onRunOcr: () => {
- if (!savingRef.current && !applying) void ocr.runOcr();
- },
+ onSetGroupingMode,
+ onSetWidthMode,
+ onSetShowRulers,
+ onRunOcr,
ocrRunning: ocr.running,
- ocrAvailable: state.loading && !ocr.running ? null : ocr.available,
+ ocrAvailable: panel.state.loading && !ocr.running ? null : ocr.available,
ocrBlockedReason: ocr.blockedReason,
- onRemovePassword: sourceFileId
- ? () => {
- setSelectedFiles([sourceFileId]);
- handleToolSelect("removePassword");
- }
- : undefined,
+ onRemovePassword: sourceFileId ? removePassword : undefined,
};
return (
@@ -783,15 +814,8 @@ export default function PdfTextEditor(_props: BaseToolProps) {
compact={isMobile}
onSave={handleSave}
onDownload={handleDownload}
- onOpenFind={() => {
- if (store.getState().findOpen) {
- store.setFindOpen(false);
- return;
- }
- pinWorkbench();
- store.setFindOpen(true);
- }}
- onShowHelp={() => store.setHelpOpen(true)}
+ onOpenFind={onOpenFind}
+ onShowHelp={onShowHelp}
/>
)}
</Stack>
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/LineGrouperSpacing.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/LineGrouperSpacing.test.ts
index ee2d6e7243..57be464fb8 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/LineGrouperSpacing.test.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/LineGrouperSpacing.test.ts
@@ -2,7 +2,10 @@
import { describe, it, expect } from "vitest";
import { Page } from "@editor/tools/pdfTextEditor/model/Page";
import { TextRun } from "@editor/tools/pdfTextEditor/model/TextRun";
-import { LineGrouper } from "@editor/tools/pdfTextEditor/pdfium/LineGrouper";
+import {
+ LineGrouper,
+ type SpaceAdvance,
+} from "@editor/tools/pdfTextEditor/pdfium/LineGrouper";
import { RENDER_MODE_INVISIBLE } from "@editor/tools/pdfTextEditor/types";
let ptr = 5000;
@@ -41,11 +44,11 @@ function lineOf(
return runs;
}
-function joinLine(runs: TextRun[]): string {
+function joinLine(runs: TextRun[], spaceAdvance?: SpaceAdvance): string {
const page = new Page({ index: 0, pagePtr: 1, width: 600, height: 800 });
page.setRuns(runs);
page.loaded = true;
- const groups = LineGrouper.apply(page);
+ const groups = LineGrouper.apply(page, undefined, spaceAdvance);
expect(groups.length, "runs formed a single line group").toBe(1);
return groups[0].representative.text;
}
@@ -56,6 +59,94 @@ function runsBetween(text: string, before: string, after: string): number {
}
describe("LineGrouper inter-run space synthesis", () => {
+ it("keeps an 18pt monospace heading saved one word per object on one line", () => {
+ const menloSpace = () => 0.602;
+ const text = joinLine(
+ lineOf(
+ [
+ { text: "Heading ", width: 73, gapAfter: 12.9 },
+ { text: "in ", width: 18, gapAfter: 12 },
+ { text: "a ", width: 8.1, gapAfter: 13 },
+ { text: "bigger ", width: 62, gapAfter: 12.9 },
+ { text: "size", width: 41 },
+ ],
+ 18,
+ ),
+ menloSpace,
+ );
+ expect(text).toBe("Heading in a bigger size");
+ });
+
+ it("keeps the heading on one line when its subset font reports the 1em missing space width", () => {
+ const missingSpace = () => 1;
+ const page = new Page({ index: 0, pagePtr: 1, width: 600, height: 800 });
+ page.setRuns(
+ lineOf(
+ [
+ { text: "Heading", width: 73, gapAfter: 12.2 },
+ { text: "in", width: 19, gapAfter: 11.7 },
+ { text: "a", width: 9, gapAfter: 12 },
+ { text: "bigger", width: 62, gapAfter: 12.3 },
+ { text: "size", width: 41 },
+ ],
+ 18,
+ ),
+ );
+ page.loaded = true;
+ const groups = LineGrouper.apply(page, undefined, missingSpace);
+ expect(groups.map((g) => g.representative.text)).toEqual([
+ "Heading in a bigger size",
+ ]);
+ });
+
+ it("reads a condensed font's narrow word gaps as spaces", () => {
+ const impactSpace = () => 0.176;
+ const text = joinLine(
+ lineOf(
+ [
+ { text: "that", width: 18, gapAfter: 1.91 },
+ { text: "we", width: 12.7, gapAfter: 1.92 },
+ { text: "want", width: 22 },
+ ],
+ 11,
+ ),
+ impactSpace,
+ );
+ expect(text).toBe("that we want");
+ });
+
+ it("keeps a condensed font's letter spacing out of the words", () => {
+ const impactSpace = () => 0.176;
+ const text = joinLine(
+ lineOf(
+ [
+ { text: "w", width: 6, gapAfter: 0.6 },
+ { text: "a", width: 5, gapAfter: 0.6 },
+ { text: "n", width: 5, gapAfter: 0.6 },
+ { text: "t", width: 3 },
+ ],
+ 11,
+ ),
+ impactSpace,
+ );
+ expect(text).toBe("want");
+ });
+
+ it("still splits two 18pt columns a wide gutter apart", () => {
+ const page = new Page({ index: 0, pagePtr: 1, width: 600, height: 800 });
+ page.setRuns(
+ lineOf(
+ [
+ { text: "Left", width: 40, gapAfter: 40 },
+ { text: "Right", width: 50 },
+ ],
+ 18,
+ ),
+ );
+ page.loaded = true;
+ expect(LineGrouper.apply(page, undefined, () => 1)).toHaveLength(2);
+ });
+
it("emits one space for normal 10pt word gaps", () => {
const text = joinLine(
lineOf(
@@ -169,6 +260,120 @@ describe("LineGrouper inter-run space synthesis", () => {
);
expect(text).toBe("Water");
});
+
+ it("counts spaces by the font's space width when two gaps are all the line has", () => {
+ const helveticaSpace = () => 0.278;
+ const text = joinLine(
+ lineOf(
+ [
+ { text: "documents ", width: 50, gapAfter: 5.9 },
+ { text: "A ", width: 6.6, gapAfter: 9.4 },
+ { text: "B", width: 5.7 },
+ ],
+ 10,
+ ),
+ helveticaSpace,
+ );
+ expect(text).toBe("documents A B");
+ });
+
+ it("keeps two equal justified gaps as ONE space each when the font space is narrower", () => {
+ const helveticaSpace = () => 0.278;
+ const text = joinLine(
+ lineOf(
+ [
+ { text: "The", width: 16, gapAfter: 7.4 },
+ { text: "quick", width: 25, gapAfter: 7.4 },
+ { text: "brown", width: 29 },
+ ],
+ 10,
+ ),
+ helveticaSpace,
+ );
+ expect(text).toBe("The quick brown");
+ });
+
+ it("counts two and three spaces at exact multiples of a narrow font space", () => {
+ const helveticaSpace = () => 0.278;
+ const text = joinLine(
+ lineOf(
+ [
+ { text: "One", width: 18, gapAfter: 5.56 },
+ { text: "two", width: 17, gapAfter: 8.34 },
+ { text: "three", width: 24 },
+ ],
+ 10,
+ ),
+ helveticaSpace,
+ );
+ expect(text).toBe("One two three");
+ });
+
+ it("keeps the gap-based count when the runs' fonts disagree on the space width", () => {
+ const text = joinLine(
+ lineOf(
+ [
+ { text: "Alpha", width: 26, gapAfter: 6 },
+ { text: "beta", width: 20, gapAfter: 12 },
+ { text: "Gamma", width: 30 },
+ ],
+ 10,
+ ),
+ (run) => (run.text === "Gamma" ? 0.278 : 0.6),
+ );
+ expect(text).toBe("Alpha beta Gamma");
+ });
+
+ it("keeps a justified line in two fonts at one space a gap", () => {
+ const fs = 10;
+ const runs = lineOf(
+ [
+ { text: "Alpha", width: 28, gapAfter: 6 },
+ { text: "beta", width: 22, gapAfter: 6.2 },
+ { text: "gamma", width: 30, gapAfter: 5.9 },
+ { text: "delta", width: 26, gapAfter: 6.1 },
+ { text: "omega", width: 30 },
+ ],
+ fs,
+ );
+ runs[0].fontId = "pdf:2:Times";
+ const advance: SpaceAdvance = (run) =>
+ run.fontId === "pdf:2:Times" ? 0.25 : 0.35;
+
+ expect(joinLine(runs, advance)).toBe("Alpha beta gamma delta omega");
+ });
+
+ it("counts spaces typed in a second font by that font's space", () => {
+ const fs = 10;
+ const runs = lineOf(
+ [
+ { text: "Document", width: 44, gapAfter: 5.6 },
+ { text: "A", width: 6, gapAfter: 9.2 },
+ { text: "B", width: 6 },
+ ],
+ fs,
+ );
+ runs[0].fontId = "pdf:2:Aptos";
+ const advance: SpaceAdvance = (run) =>
+ run.fontId === "pdf:2:Aptos" ? 0.2 : 0.278;
+
+ expect(joinLine(runs, advance)).toBe("Document A B");
+ });
+
+ it("keeps the gap-based count when the font reports no usable space width", () => {
+ const text = joinLine(
+ lineOf(
+ [
+ { text: "Item", width: 20, gapAfter: 3.4 },
+ { text: "one", width: 17, gapAfter: 6.6 },
+ { text: "two", width: 18 },
+ ],
+ 10,
+ ),
+ () => 0,
+ );
+ expect(text).toBe("Item one two");
+ });
});
describe("LineGrouper text layers", () => {
@@ -225,3 +430,37 @@ describe("LineGrouper text layers", () => {
]);
});
});
+
+describe("OCR words boxed with their trailing space", () => {
+ it("keeps a word on its line when its stretched space overhangs the next word", () => {
+ const words = lineOf(
+ [
+ { text: "Pack ", width: 31.2, gapAfter: -2.64 },
+ { text: "my ", width: 24.48, gapAfter: -5.04 },
+ { text: "box", width: 18 },
+ ],
+ 12,
+ );
+ for (const word of words) word.renderMode = RENDER_MODE_INVISIBLE;
+ expect(joinLine(words).replace(/\s+/g, " ")).toBe("Pack my box");
+ });
+});
+
+describe("text that draws no ink", () => {
+ it("never joins a clip-only line to drawn text beside it", () => {
+ const [drawn, clip] = lineOf(
+ [
+ { text: "Drawn ", width: 40, gapAfter: 4 },
+ { text: "clip", width: 30 },
+ ],
+ 12,
+ );
+ clip.renderMode = 7;
+ const page = new Page({ index: 0, pagePtr: 1, width: 600, height: 800 });
+ page.setRuns([drawn, clip]);
+ page.loaded = true;
+ expect(
+ LineGrouper.apply(page).map((g) => g.representative.text.trim()),
+ ).toEqual(["Drawn", "clip"]);
+ });
+});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/ParagraphEdit.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/ParagraphEdit.test.ts
index 8043413449..ccc7b650b4 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/ParagraphEdit.test.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/ParagraphEdit.test.ts
@@ -122,16 +122,29 @@ describe("planPartialEdit surrogate-pair guard (astral chars)", () => {
});
describe("planPartialEdit interior-insert guard (single word object)", () => {
- it("bails when an inserted char splits a multi-char object's kept chars", () => {
+ // The word's object is removed and its new text drawn as ONE insert in its
+ // place, so no SetText can scramble the letters around the typed one.
+ const redrawsWhole = (prev: string, next: string) => {
+ const run = makeSingleSubRun(prev);
+ const plan = planPartialEdit(run, prev, next);
+ expect(plan?.removePtrs.map((r) => r.ptr)).toEqual([run.mergedFromPtrs[0]]);
+ expect(plan?.ops).toEqual([
+ expect.objectContaining({
+ type: "insert",
+ text: next,
+ anchorSubRunIdx: 0,
+ }),
+ ]);
+ };
+
+ it("redraws a word whole when an inserted char splits its kept chars", () => {
// "world" is ONE object; inserting "a" mid-word ("world"->"worald") leaves
// the survivors at non-contiguous new-text positions (0,1,2,4,5).
- const run = makeSingleSubRun("world");
- expect(planPartialEdit(run, "world", "worald")).toBeNull();
+ redrawsWhole("world", "worald");
});
- it("bails on a mid-word char replace (delete+insert interior)", () => {
- const run = makeSingleSubRun("world");
- expect(planPartialEdit(run, "world", "worXd")).toBeNull();
+ it("redraws a word whole on a mid-word char replace (delete+insert interior)", () => {
+ redrawsWhole("world", "worXd");
});
it("keeps the surgical path for a boundary delete (survivors contiguous)", () => {
@@ -199,18 +212,19 @@ describe("planParagraphEdit slot-range line mapping", () => {
expect(planParagraphEdit(run, run.text, "Zaaa bbb EXTRA")).toBeNull();
});
- it("forces a fresh word-split re-emit when a mid-line edit would SetText whitespace (the „ bug)", () => {
+ it("redraws a line whose one sub-run would SetText whitespace mid-line, never SetTexting it (the „ bug)", () => {
// A whole line as ONE sub-run carrying spaces (LaTeX one-object-per-line).
const run = makeParagraph(["aaa bbb ccc", "ddd eee"], ["\n"]);
const prev = run.text; // "aaa bbb ccc\nddd eee"
const next = "aaa Xbb ccc\nddd eee"; // replace one char mid-line-0
const plan = planParagraphEdit(run, prev, next);
- expect(plan).not.toBeNull();
const entry = plan?.perSlot.find((p) => p.slotIdx === 0);
- expect(entry).toBeDefined();
- // null plan => the apply step fresh-emits this line (word-split), avoiding „.
- expect(entry?.plan).toBeNull();
expect(entry?.nextLine).toBe("aaa Xbb ccc");
+ // A fresh emit word-splits the line, so whitespace never goes through SetText.
+ expect(entry?.plan?.ops.some((op) => op.type === "modify")).toBe(false);
+ expect(entry?.plan?.ops).toEqual([
+ expect.objectContaining({ type: "insert", text: "aaa Xbb ccc" }),
+ ]);
});
it("keeps the in-place modify fast path for a boundary edit on a single-word sub-run", () => {
@@ -226,19 +240,22 @@ describe("planParagraphEdit slot-range line mapping", () => {
expect(entry?.plan).not.toBeNull();
});
- it("re-emits a mid-word char replace instead of scrambling it (interior-insert guard)", () => {
+ it("redraws a mid-word char replace whole instead of scrambling it (interior-insert guard)", () => {
// Replacing a char in the MIDDLE of a single word object ("world"->"worXd")
// deletes 'l' and inserts 'X' between the surviving 'r' and 'd'.
const run = makeParagraph(["hello", "world"], ["\n"]);
const prev = run.text; // "hello\nworld"
const next = "hello\nworXd";
const plan = planParagraphEdit(run, prev, next);
- expect(plan).not.toBeNull();
const entry = plan?.perSlot.find((p) => p.slotIdx === 1);
- expect(entry).toBeDefined();
- // null slot plan => the apply step fresh-emits this line (correct order).
- expect(entry?.plan).toBeNull();
expect(entry?.nextLine).toBe("worXd");
+ expect(entry?.plan?.ops).toEqual([
+ expect.objectContaining({
+ type: "insert",
+ text: "worXd",
+ anchorSubRunIdx: 0,
+ }),
+ ]);
});
it("handles an all-hard-break paragraph (initial-load shape) too", () => {
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/PdfiumPageRenderer.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/PdfiumPageRenderer.test.ts
index 8977647684..b78b005f71 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/PdfiumPageRenderer.test.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/PdfiumPageRenderer.test.ts
@@ -1,4 +1,5 @@
import { describe, expect, it } from "vitest";
+import { Page } from "@editor/tools/pdfTextEditor/model/Page";
import { PdfiumPageRenderer } from "@editor/tools/pdfTextEditor/pdfium/PdfiumPageRenderer";
// A4 in PDF points.
@@ -40,3 +41,18 @@ describe("PdfiumPageRenderer.deviceScale", () => {
expect(PdfiumPageRenderer.deviceScale(A4_W, A4_H, 4, 2)).toBeCloseTo(8, 1);
});
});
+
+describe("PdfiumPageRenderer.pixelsCovering", () => {
+ it("scales each axis by the bitmap's own rounding on a long, narrow page", () => {
+ const page = new Page({ index: 0, pagePtr: 1, width: 100, height: 10_000 });
+ const scale = 1.004;
+ const raster = PdfiumPageRenderer.rasterSize(100, 10_000, scale);
+ const k = raster.height / 10_000;
+ const line = { x: 10, y: 20, width: 50, height: 12 };
+
+ const area = PdfiumPageRenderer.pixelsCovering(page, scale, line)!;
+
+ expect(area.y).toBeLessThanOrEqual((10_000 - line.y - line.height) * k);
+ expect(area.y + area.height).toBeGreaterThanOrEqual((10_000 - line.y) * k);
+ });
+});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/boldToggle.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/boldToggle.test.ts
new file mode 100644
index 0000000000..e7057587e2
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/boldToggle.test.ts
@@ -0,0 +1,139 @@
+import { act, renderHook } from "@testing-library/react";
+import { beforeAll, expect, test, vi } from "vitest";
+
+const { get } = vi.hoisted(() => ({ get: vi.fn() }));
+vi.mock("@editor/services/apiClient", () => ({ default: { get } }));
+
+import { useSelectionActions } from "@editor/tools/pdfTextEditor/hooks/useSelectionActions";
+import type { EditorStore } from "@editor/tools/pdfTextEditor/store/EditorStore";
+import { collectMemberPtrs } from "@editor/tools/pdfTextEditor/commands/editTextHelpers";
+import type { TextRun } from "@editor/tools/pdfTextEditor/model/TextRun";
+import {
+ editorStores,
+ savedBytes,
+ servePdfiumWasm,
+} from "@editor/tools/pdfTextEditor/__tests__/editorStores";
+
+const FPDF_PAGEOBJ_TEXT = 1;
+
+servePdfiumWasm();
+const { storeWith, fixture } = editorStores();
+
+beforeAll(() => {
+ get.mockRejectedValue(new Error("no server fonts"));
+ // jsdom has no canvas; text measurement falls back without one.
+ vi.spyOn(HTMLCanvasElement.prototype, "getContext").mockReturnValue(null);
+});
+
+function runOf(store: EditorStore, text: string): TextRun {
+ return store.document!.page(0).runs.find((r) => r.text === text)!;
+}
+
+/** The /BaseFont each piece of a run is drawn in, with the text it draws, as "text@Font". */
+function pieces(store: EditorStore, text: string): string[] {
+ const doc = store.document!;
+ const m = doc.module;
+ const page = doc.page(0);
+ const buf = m.pdfium.wasmExports.malloc(2048);
+ const name = m.pdfium.wasmExports.malloc(256);
+ const textPage = m.FPDFText_LoadPage(page.pagePtr);
+ try {
+ return collectMemberPtrs(runOf(store, text))
+ .filter((ptr) => ptr && m.FPDFPageObj_GetType(ptr) === FPDF_PAGEOBJ_TEXT)
+ .map((ptr) => {
+ m.FPDFTextObj_GetText(ptr, textPage, buf, 2048);
+ m.FPDFFont_GetBaseFontName(m.FPDFTextObj_GetFont(ptr), name, 256);
+ const font = m.pdfium.UTF8ToString(name).replace(/^[A-Z]{6}\+/, "");
+ return `${m.pdfium.UTF16ToString(buf)}@${font}`;
+ });
+ } finally {
+ m.FPDFText_ClosePage(textPage);
+ m.pdfium.wasmExports.free(buf);
+ m.pdfium.wasmExports.free(name);
+ }
+}
+
+function fonts(store: EditorStore, text: string): string[] {
+ return [...new Set(pieces(store, text).map((p) => p.split("@")[1]))].sort();
+}
+
+/** The run's text as its objects draw it, spaces aside. */
+function drawnText(store: EditorStore, text: string): string {
+ return pieces(store, text)
+ .map((p) => p.split("@")[0])
+ .join("")
+ .replace(/\s+/g, "");
+}
+
+function select(store: EditorStore, text: string): void {
+ store.selection.selectOne(runOf(store, text).id);
+}
+
+async function toggleBold(store: EditorStore) {
+ const { result } = renderHook(() => useSelectionActions(store));
+ let failure: unknown;
+ await act(async () => {
+ failure = await result.current.toggleBold();
+ });
+ return failure;
+}
+
+test("Bold off moves a heading to the document's regular face, keeps its text, and undoes and redoes", async () => {
+ const store = await fixture("mushroom-life.pdf");
+ const heading = "Spore Stage";
+ expect(fonts(store, heading)).toEqual(["LMRoman12-Bold"]);
+ select(store, heading);
+
+ expect(await toggleBold(store)).toBeNull();
+
+ expect(fonts(store, heading)).toEqual(["LMRoman12-Regular"]);
+ expect(drawnText(store, heading)).toBe("SporeStage");
+
+ store.undo();
+ expect(fonts(store, heading)).toEqual(["LMRoman12-Bold"]);
+ store.redo();
+ expect(fonts(store, heading)).toEqual(["LMRoman12-Regular"]);
+ expect(drawnText(store, heading)).toBe("SporeStage");
+
+ const saved = await storeWith(await savedBytes(store));
+ expect(fonts(saved, heading)).toEqual(["LMRoman12-Regular"]);
+});
+
+test("a letter the regular subset lacks stays in the bold face it was drawn in, and the user is told", async () => {
+ const store = await fixture("mushroom-life.pdf");
+ select(store, "Introduction");
+
+ expect(await toggleBold(store)).toBe("closestMatch");
+
+ expect(pieces(store, "Introduction")).toEqual([
+ "I@LMRoman12-Bold",
+ "ntroduction@LMRoman12-Regular",
+ ]);
+});
+
+test("Bold on draws the letters the bold subset lacks in the closest match and says so", async () => {
+ const store = await fixture("coloured-word-sample.pdf");
+ const line = "Total due today by card";
+ expect(fonts(store, line)).toEqual(["LiberationSans", "LiberationSans-Bold"]);
+ select(store, line);
+
+ expect(await toggleBold(store)).toBe("closestMatch");
+
+ const bold = () =>
+ pieces(store, line)
+ .filter((p) => p.endsWith("@LiberationSans-Bold"))
+ .map((p) => p.split("@")[0])
+ .join("");
+ expect(bold()).toMatch(/otal.*d.*e.*today.*y.*ca.*d/);
+ expect(bold()).not.toMatch(/[Tubr]/);
+ expect(drawnText(store, line)).toBe("Totalduetodaybycard");
+ expect(
+ store.document!.page(0).runs.find((r) => r.text === line)?.fontId,
+ ).toMatch(/^pdf:\d+:/);
+
+ store.undo();
+ expect(bold()).toBe("today ");
+ store.redo();
+ expect(bold()).not.toMatch(/[Tubr]/);
+ expect(drawnText(store, line)).toBe("Totalduetodaybycard");
+});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/chromeSpaceGap.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/chromeSpaceGap.test.ts
new file mode 100644
index 0000000000..96aacad296
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/chromeSpaceGap.test.ts
@@ -0,0 +1,95 @@
+// @vitest-environment node
+import { readFile } from "node:fs/promises";
+import { createRequire } from "node:module";
+import path from "node:path";
+import { afterAll, afterEach, beforeAll, expect, test, vi } from "vitest";
+import { EditTextCommand } from "@editor/tools/pdfTextEditor/commands/EditTextCommand";
+import { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
+import { PdfiumTextReader } from "@editor/tools/pdfTextEditor/pdfium/PdfiumTextReader";
+import { HistoryStack } from "@editor/tools/pdfTextEditor/store/HistoryStack";
+
+const HEADING_PDF = path.join(
+ import.meta.dirname,
+ "../../../tests/test-fixtures/chrome-per-glyph-heading.pdf",
+);
+const HEADING = "Audit Desk Notes";
+const FPDF_PAGEOBJ_TEXT = 1;
+
+const opened: EditorDocument[] = [];
+
+beforeAll(async () => {
+ const wasm = await readFile(
+ createRequire(import.meta.url).resolve("@embedpdf/pdfium/pdfium.wasm"),
+ );
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async (url: string) =>
+ String(url).endsWith(".wasm")
+ ? new Response(wasm, {
+ headers: { "Content-Type": "application/wasm" },
+ })
+ : new Response(null, { status: 404 }),
+ ),
+ );
+});
+
+afterEach(() => {
+ for (const doc of opened.splice(0)) doc.dispose();
+});
+
+afterAll(() => vi.unstubAllGlobals());
+
+async function openHeading() {
+ const doc = await EditorDocument.open(
+ new Uint8Array(await readFile(HEADING_PDF)),
+ );
+ opened.push(doc);
+ PdfiumTextReader.populate(doc, doc.page(0));
+ const run = doc.page(0).runs.find((r) => r.text === HEADING);
+ if (!run) throw new Error("heading run not found");
+ return { doc, run };
+}
+
+function headingObjectLefts(doc: EditorDocument, topY: number): number[] {
+ const m = doc.module;
+ const pagePtr = doc.page(0).pagePtr;
+ const box = m.pdfium.wasmExports.malloc(16);
+ const lefts: number[] = [];
+ try {
+ for (let i = 0; i < m.FPDFPage_CountObjects(pagePtr); i++) {
+ const obj = m.FPDFPage_GetObject(pagePtr, i);
+ if (m.FPDFPageObj_GetType(obj) !== FPDF_PAGEOBJ_TEXT) continue;
+ m.FPDFPageObj_GetBounds(obj, box, box + 4, box + 8, box + 12);
+ const top = m.pdfium.getValue(box + 12, "float");
+ if (Math.abs(top - topY) > 6) continue;
+ lefts.push(m.pdfium.getValue(box, "float"));
+ }
+ } finally {
+ m.pdfium.wasmExports.free(box);
+ }
+ return lefts.sort((a, b) => a - b);
+}
+
+test("typing a space between words and deleting it leaves no gap", async () => {
+ const { doc, run } = await openHeading();
+ const topY = run.bounds.y + run.bounds.height;
+ const before = headingObjectLefts(doc, topY);
+ const history = new HistoryStack();
+
+ for (const nextText of ["Audit Desk Notes", HEADING]) {
+ history.execute(
+ new EditTextCommand({ pageIndex: 0, runId: run.id, nextText }),
+ doc,
+ );
+ history.breakCoalescing();
+ }
+
+ const after = headingObjectLefts(doc, topY);
+ expect(after.length).toBe(before.length);
+ after.forEach((x, i) => expect(Math.abs(x - before[i])).toBeLessThan(0.5));
+
+ history.undo(doc);
+ history.undo(doc);
+ const undone = headingObjectLefts(doc, topY);
+ undone.forEach((x, i) => expect(Math.abs(x - before[i])).toBeLessThan(0.05));
+});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/clippedImage.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/clippedImage.test.ts
new file mode 100644
index 0000000000..50e9527f4b
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/clippedImage.test.ts
@@ -0,0 +1,287 @@
+// @vitest-environment node
+import { readFile } from "node:fs/promises";
+import { createRequire } from "node:module";
+import { afterEach, beforeAll, describe, expect, test, vi } from "vitest";
+import type { Command } from "@editor/tools/pdfTextEditor/commands/Command";
+import { DeleteImageCommand } from "@editor/tools/pdfTextEditor/commands/DeleteImageCommand";
+import { ReplaceImageCommand } from "@editor/tools/pdfTextEditor/commands/ReplaceImageCommand";
+import { SetImageTransformCommand } from "@editor/tools/pdfTextEditor/commands/SetImageTransformCommand";
+import { TransformImageObjectCommand } from "@editor/tools/pdfTextEditor/commands/TransformImageObjectCommand";
+import { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
+import { PdfiumTextReader } from "@editor/tools/pdfTextEditor/pdfium/PdfiumTextReader";
+import {
+ HistoryStack,
+ HistoryStepError,
+} from "@editor/tools/pdfTextEditor/store/HistoryStack";
+import type { PageRect } from "@editor/tools/pdfTextEditor/types";
+import { exportToBlob } from "@editor/tools/pdfTextEditor/util/exportPdf";
+import {
+ imageBoundsForVisible,
+ visibleImageBounds,
+} from "@editor/tools/pdfTextEditor/util/imageClip";
+import {
+ buildClassicPdf,
+ streamBody,
+} from "@editor/tools/pdfTextEditor/__tests__/pdfFixtures";
+import {
+ changedPixels,
+ rasterFirstPage,
+} from "@editor/tools/pdfTextEditor/__tests__/pageRaster";
+
+const SIZE = 300;
+const BLUE_2X2 = streamBody(
+ "/Type /XObject /Subtype /Image /Width 2 /Height 2 /ColorSpace /DeviceRGB /BitsPerComponent 8",
+ "\x00\x00\xff".repeat(4),
+);
+const IMAGE = "200 0 0 200 50 50 cm /Im Do";
+const WINDOW: PageRect = { x: 100, y: 100, width: 100, height: 100 };
+
+function fixture(page: string, form = ""): Uint8Array {
+ return buildClassicPdf(
+ [
+ { num: 1, body: "<< /Type /Catalog /Pages 2 0 R >>" },
+ { num: 2, body: "<< /Type /Pages /Kids [3 0 R] /Count 1 >>" },
+ {
+ num: 3,
+ body: `<< /Type /Page /Parent 2 0 R /MediaBox [0 0 ${SIZE} ${SIZE}] /Contents 4 0 R /Resources << /XObject << /Im 5 0 R /Fm 6 0 R >> /Font << /F1 7 0 R >> >> >>`,
+ },
+ { num: 4, body: streamBody("", page) },
+ { num: 5, body: BLUE_2X2 },
+ {
+ num: 6,
+ body: streamBody(
+ `/Type /XObject /Subtype /Form /BBox [0 0 ${SIZE} ${SIZE}] /Resources << /XObject << /Im 5 0 R >> >>`,
+ form,
+ ),
+ },
+ {
+ num: 7,
+ body: "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>",
+ },
+ ],
+ 1,
+ );
+}
+
+const SQUARE_CLIP = "100 100 100 100 re W n";
+const CASES: Array<[string, Uint8Array]> = [
+ ["a page-level rectangular clip", fixture(`q ${SQUARE_CLIP} ${IMAGE} Q`)],
+ [
+ "a page-level triangular clip",
+ fixture(`q 100 100 m 200 100 l 150 200 l h W n ${IMAGE} Q`),
+ ],
+ ["a clip inside the form", fixture("/Fm Do", `q ${SQUARE_CLIP} ${IMAGE} Q`)],
+ [
+ "nested clips beside text, as Word prints a cropped picture",
+ fixture(
+ `q 0 0 300 300 re W n BT /F1 12 Tf 20 250 Td (Caption) Tj ET q ${SQUARE_CLIP} q ${IMAGE} Q Q Q`,
+ ),
+ ],
+];
+
+const opened: EditorDocument[] = [];
+
+beforeAll(async () => {
+ const wasm = await readFile(
+ createRequire(import.meta.url).resolve("@embedpdf/pdfium/pdfium.wasm"),
+ );
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(
+ async () =>
+ new Response(wasm, { headers: { "Content-Type": "application/wasm" } }),
+ ),
+ );
+});
+
+afterEach(() => {
+ for (const doc of opened.splice(0)) doc.dispose();
+});
+
+async function open(bytes: Uint8Array): Promise<EditorDocument> {
+ const doc = await EditorDocument.open(bytes);
+ opened.push(doc);
+ PdfiumTextReader.populate(doc, doc.page(0));
+ return doc;
+}
+
+async function reopened(doc: EditorDocument): Promise<EditorDocument> {
+ return open(new Uint8Array(await (await exportToBlob(doc)).arrayBuffer()));
+}
+
+const raster = (doc: EditorDocument) => rasterFirstPage(doc, SIZE, SIZE);
+
+// Page-space box around the blue the page shows, or null when none shows.
+function blueBox(pixels: Uint8Array): PageRect | null {
+ let [x0, y0, x1, y1] = [Infinity, Infinity, -Infinity, -Infinity];
+ for (let row = 0; row < SIZE; row++) {
+ for (let col = 0; col < SIZE; col++) {
+ const i = (row * SIZE + col) * 4;
+ if (pixels[i] > 80 || pixels[i + 1] > 80 || pixels[i + 2] < 200) continue;
+ const y = SIZE - 1 - row;
+ [x0, y0, x1, y1] = [
+ Math.min(x0, col),
+ Math.min(y0, y),
+ Math.max(x1, col + 1),
+ Math.max(y1, y + 1),
+ ];
+ }
+ }
+ return x1 < 0 ? null : { x: x0, y: y0, width: x1 - x0, height: y1 - y0 };
+}
+
+function image(doc: EditorDocument) {
+ return doc.page(0).images[0];
+}
+
+function expectRect(actual: PageRect | null, expected: PageRect): void {
+ expect(actual).not.toBeNull();
+ for (const key of ["x", "y", "width", "height"] as const)
+ expect(Math.abs(actual![key] - expected[key])).toBeLessThanOrEqual(1);
+}
+
+function moveWindowTo(doc: EditorDocument, next: PageRect): Command {
+ const img = image(doc);
+ return new SetImageTransformCommand({
+ pageIndex: 0,
+ imageId: img.id,
+ nextBounds: imageBoundsForVisible(img, next),
+ });
+}
+
+async function expectEditKeepsWindow(
+ bytes: Uint8Array,
+ edit: (doc: EditorDocument) => Command,
+ window: PageRect,
+): Promise<void> {
+ const doc = await open(bytes);
+ const before = raster(doc);
+ const shownBefore = blueBox(before);
+ const history = new HistoryStack();
+ history.execute(edit(doc), doc);
+ const after = raster(doc);
+ expectRect(blueBox(after), window);
+ expectRect(visibleImageBounds(image(doc)), window);
+ const saved = await reopened(doc);
+ expect(changedPixels(after, raster(saved))).toBe(0);
+ expectRect(visibleImageBounds(image(saved)), window);
+ history.undo(doc);
+ expect(changedPixels(before, raster(doc))).toBe(0);
+ expectRect(blueBox(raster(doc)), shownBefore!);
+ history.redo(doc);
+ expect(changedPixels(after, raster(doc))).toBe(0);
+ history.undo(doc);
+ expect(changedPixels(before, raster(await reopened(doc)))).toBe(0);
+}
+
+describe.each(CASES)("an image cropped by %s", (_name, bytes) => {
+ test("is selected by the window it shows, not the hidden image", async () => {
+ const doc = await open(bytes);
+ expectRect(image(doc).bounds, { x: 50, y: 50, width: 200, height: 200 });
+ expectRect(visibleImageBounds(image(doc)), WINDOW);
+ });
+
+ test("moving the window moves the crop with it", async () => {
+ await expectEditKeepsWindow(
+ bytes,
+ (doc) => moveWindowTo(doc, { ...WINDOW, x: 140, y: 80 }),
+ { ...WINDOW, x: 140, y: 80 },
+ );
+ });
+
+ test("resizing the window scales the crop with it", async () => {
+ const half = { x: 100, y: 100, width: 50, height: 50 };
+ await expectEditKeepsWindow(bytes, (doc) => moveWindowTo(doc, half), half);
+ });
+
+ test("replacing it is refused rather than showing the hidden part", async () => {
+ const doc = await open(bytes);
+ const before = raster(doc);
+ const history = new HistoryStack();
+ const replace = new ReplaceImageCommand({
+ pageIndex: 0,
+ imageId: image(doc).id,
+ image: {
+ width: 2,
+ height: 2,
+ rgba: new Uint8Array(16).map((_, i) => [0, 200, 0, 255][i % 4]),
+ },
+ });
+ let refusal: unknown = null;
+ try {
+ history.execute(replace, doc);
+ } catch (err) {
+ refusal = err;
+ }
+ expect(refusal).toBeInstanceOf(HistoryStepError);
+ expect((refusal as HistoryStepError).documentIntact).toBe(true);
+ expect(history.canUndo).toBe(false);
+ expect(changedPixels(before, raster(doc))).toBe(0);
+ expect(changedPixels(before, raster(await reopened(doc)))).toBe(0);
+ });
+
+ test("deleting it and undoing restores the window exactly", async () => {
+ const doc = await open(bytes);
+ const before = raster(doc);
+ const history = new HistoryStack();
+ history.execute(
+ new DeleteImageCommand({ pageIndex: 0, imageId: image(doc).id }),
+ doc,
+ );
+ expect(blueBox(raster(doc))).toBeNull();
+ history.undo(doc);
+ expect(changedPixels(before, raster(doc))).toBe(0);
+ expectRect(visibleImageBounds(image(doc)), WINDOW);
+ });
+});
+
+describe("an image cropped off-centre", () => {
+ const offCentre = fixture(`q 60 60 80 80 re W n ${IMAGE} Q`);
+ const window = { x: 60, y: 60, width: 80, height: 80 };
+
+ test("turns in place about the window it shows", async () => {
+ await expectEditKeepsWindow(
+ offCentre,
+ (doc) =>
+ new TransformImageObjectCommand({
+ pageIndex: 0,
+ imageId: image(doc).id,
+ mode: "rotate-cw",
+ }),
+ window,
+ );
+ });
+
+ test("flips in place about the window it shows", async () => {
+ await expectEditKeepsWindow(
+ offCentre,
+ (doc) =>
+ new TransformImageObjectCommand({
+ pageIndex: 0,
+ imageId: image(doc).id,
+ mode: "flip-h",
+ }),
+ window,
+ );
+ });
+});
+
+describe("an image drawn by a form through the form's own clip", () => {
+ const formClipped = fixture(`q ${SQUARE_CLIP} /Fm Do Q`, IMAGE);
+
+ test("is selected by the window it shows", async () => {
+ const doc = await open(formClipped);
+ expectRect(visibleImageBounds(image(doc)), WINDOW);
+ });
+
+ test("moving it is refused, leaving the page as it was", async () => {
+ const doc = await open(formClipped);
+ const before = raster(doc);
+ const history = new HistoryStack();
+ expect(() =>
+ history.execute(moveWindowTo(doc, { ...WINDOW, x: 140 }), doc),
+ ).toThrow(HistoryStepError);
+ expect(changedPixels(before, raster(doc))).toBe(0);
+ expect(changedPixels(before, raster(await reopened(doc)))).toBe(0);
+ });
+});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/colouredWordEdit.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/colouredWordEdit.test.ts
new file mode 100644
index 0000000000..f62c774ca3
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/colouredWordEdit.test.ts
@@ -0,0 +1,365 @@
+// @vitest-environment node
+import { readFile } from "node:fs/promises";
+import { createRequire } from "node:module";
+import path from "node:path";
+import { afterAll, afterEach, beforeAll, expect, test, vi } from "vitest";
+import { EditTextCommand } from "@editor/tools/pdfTextEditor/commands/EditTextCommand";
+import {
+ applyPartialEditPlan,
+ planPartialEdit,
+ revertPartialEditPlan,
+} from "@editor/tools/pdfTextEditor/commands/partialEdit";
+import { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
+import { uniformTags } from "@editor/tools/pdfTextEditor/model/TextTags";
+import { readObjFill } from "@editor/tools/pdfTextEditor/pdfium/PdfiumObjectColour";
+import { PdfiumTextReader } from "@editor/tools/pdfTextEditor/pdfium/PdfiumTextReader";
+import { HistoryStack } from "@editor/tools/pdfTextEditor/store/HistoryStack";
+import { exportToBlob } from "@editor/tools/pdfTextEditor/util/exportPdf";
+
+const SAMPLE = path.join(
+ import.meta.dirname,
+ "../../../tests/test-fixtures/coloured-word-sample.pdf",
+);
+// The sample sets its lines 15pt apart.
+const LINE_PT = 15;
+
+async function openSample(bytes?: Uint8Array): Promise<EditorDocument> {
+ const doc = await EditorDocument.open(
+ bytes ?? new Uint8Array(await readFile(SAMPLE)),
+ );
+ PdfiumTextReader.populate(doc, doc.page(0));
+ return doc;
+}
+
+type Colour = "blue" | "black" | "other";
+type Face = "bold" | "regular";
+
+function colourOf(doc: EditorDocument, obj: number): Colour {
+ const fill = readObjFill(doc.module, obj);
+ if (!fill) return "other";
+ if (fill.b > 150 && fill.r < 80) return "blue";
+ if (Math.max(fill.r, fill.g, fill.b) < 60) return "black";
+ return "other";
+}
+
+function faceOf(doc: EditorDocument, obj: number): Face {
+ const m = doc.module;
+ const font = m.FPDFTextObj_GetFont(obj);
+ const len = m.FPDFFont_GetBaseFontName(font, 0, 0);
+ const buf = m.pdfium.wasmExports.malloc(len);
+ try {
+ m.FPDFFont_GetBaseFontName(font, buf, len);
+ return /bold/i.test(m.pdfium.UTF8ToString(buf)) ? "bold" : "regular";
+ } finally {
+ m.pdfium.wasmExports.free(buf);
+ }
+}
+
+interface DrawnChar {
+ ch: string;
+ x: number;
+ line: number;
+ c: Colour;
+ face: Face;
+}
+
+// Each drawn letter of the page in reading order, by where it sits.
+function drawnChars(doc: EditorDocument): DrawnChar[] {
+ const m = doc.module;
+ const textPage = m.FPDFText_LoadPage(doc.page(0).pagePtr);
+ const xy = m.pdfium.wasmExports.malloc(16);
+ const chars: DrawnChar[] = [];
+ try {
+ for (let i = 0; i < m.FPDFText_CountChars(textPage); i++) {
+ const ch = String.fromCodePoint(m.FPDFText_GetUnicode(textPage, i));
+ if (!/\S/.test(ch)) continue;
+ m.FPDFText_GetCharOrigin(textPage, i, xy, xy + 8);
+ const obj = m.FPDFText_GetTextObject(textPage, i);
+ chars.push({
+ ch,
+ x: m.pdfium.getValue(xy, "double"),
+ line: Math.round(m.pdfium.getValue(xy + 8, "double") / LINE_PT),
+ c: colourOf(doc, obj),
+ face: faceOf(doc, obj),
+ });
+ }
+ } finally {
+ m.FPDFText_ClosePage(textPage);
+ m.pdfium.wasmExports.free(xy);
+ }
+ return chars.sort((a, b) => b.line - a.line || a.x - b.x);
+}
+
+function drawnWord(doc: EditorDocument, word: string): DrawnChar[] {
+ const chars = drawnChars(doc);
+ const at = chars
+ .map(({ ch }) => ch)
+ .join("")
+ .indexOf(word);
+ expect(at, `"${word}" is drawn`).toBeGreaterThanOrEqual(0);
+ return chars.slice(at, at + word.length);
+}
+
+const wordColours = (doc: EditorDocument, word: string): Colour[] =>
+ drawnWord(doc, word).map(({ c }) => c);
+
+const wordFaces = (doc: EditorDocument, word: string): Face[] =>
+ drawnWord(doc, word).map(({ face }) => face);
+
+const sameColour = (c: Colour, n: number) => Array<Colour>(n).fill(c);
+
+const opened: EditorDocument[] = [];
+
+beforeAll(async () => {
+ const wasm = await readFile(
+ createRequire(import.meta.url).resolve("@embedpdf/pdfium/pdfium.wasm"),
+ );
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(
+ async () =>
+ new Response(wasm, {
+ headers: { "Content-Type": "application/wasm" },
+ }),
+ ),
+ );
+});
+
+afterEach(() => {
+ for (const doc of opened.splice(0)) doc.dispose();
+});
+
+afterAll(() => vi.unstubAllGlobals());
+
+async function open(bytes?: Uint8Array): Promise<EditorDocument> {
+ const doc = await openSample(bytes);
+ opened.push(doc);
+ return doc;
+}
+
+function typeAt(
+ history: HistoryStack,
+ doc: EditorDocument,
+ needle: string,
+ at: number,
+) {
+ const run = doc.page(0).runs.find((r) => r.text.includes(needle))!;
+ const i = run.text.indexOf(needle) + at;
+ history.execute(
+ new EditTextCommand({
+ pageIndex: 0,
+ runId: run.id,
+ nextText: run.text.slice(0, i) + "Q" + run.text.slice(i),
+ }),
+ doc,
+ );
+}
+
+test("the fixture has a paragraph, a single line and a Hebrew line, each with blue words", async () => {
+ const doc = await open();
+ const runs = doc.page(0).runs.filter((r) => r.text.trim());
+ expect(runs).toHaveLength(3);
+ expect(runs.find((r) => r.text.includes("Scotland"))!.text).toContain("\n");
+ expect(wordColours(doc, "Scotland")).toEqual(sameColour("blue", 8));
+ expect(wordColours(doc, "Totaldue")).toEqual(sameColour("black", 8));
+ expect(wordColours(doc, "today")).toEqual(sameColour("blue", 5));
+});
+
+test.each([
+ ["at the end of a line", "Scotland", 8, "Scotland", "ScotlandQ", "blue"],
+ ["mid-word", "Helpdesk", 4, "Helpdesk", "HelpQdesk", "blue"],
+ ["at the start of a word", "Helpdesk", 0, "Helpdesk", "QHelpdesk", "blue"],
+ ["mid-word on a single line", "today", 2, "today", "toQday", "blue"],
+ [
+ "after a black word beside a blue one",
+ "call the",
+ 8,
+ "callthe",
+ "theQ",
+ "black",
+ ],
+ [
+ "after a black word on a single line",
+ "due",
+ 3,
+ "Totaldue",
+ "dueQ",
+ "black",
+ ],
+] as const)(
+ "a letter typed %s takes the colour of the word it joins, through undo, redo and save",
+ async (_name, needle, at, original, word, colour) => {
+ const doc = await open();
+ const history = new HistoryStack();
+
+ typeAt(history, doc, needle, at);
+ expect(wordColours(doc, word)).toEqual(sameColour(colour, word.length));
+
+ history.undo(doc);
+ expect(wordColours(doc, original)).toEqual(
+ sameColour(colour, original.length),
+ );
+ history.redo(doc);
+ expect(wordColours(doc, word)).toEqual(sameColour(colour, word.length));
+
+ const saved = await open(
+ new Uint8Array(await (await exportToBlob(doc)).arrayBuffer()),
+ );
+ expect(wordColours(saved, word)).toEqual(sameColour(colour, word.length));
+ expect(wordFaces(saved, word)).toEqual(
+ Array(word.length).fill(colour === "blue" ? "bold" : "regular"),
+ );
+ expect(wordColours(saved, "team")).toEqual(sameColour("black", 4));
+ expect(wordColours(saved, "Scotland")).toEqual(sameColour("blue", 8));
+ },
+);
+
+test("an undo that redraws the pieces an edit removed draws each in its own colour", async () => {
+ const doc = await open();
+ const m = doc.module;
+ const page = doc.page(0);
+ const run = page.runs.find((r) => r.text.includes("today"))!;
+ const tags = uniformTags(run.tagMarks);
+ const prev = {
+ fonts: run.mergedFromPtrs.map((ptr) => m.FPDFTextObj_GetFont(ptr)),
+ fills: run.mergedFromPtrs.map((ptr) => readObjFill(m, ptr)),
+ charStarts: [...run.mergedFromCharStarts],
+ baselineY: run.matrix.f,
+ fontSubset: run.fontSubset,
+ };
+ const i = run.text.indexOf("today") + 2;
+ const plan = planPartialEdit(
+ run,
+ run.text,
+ run.text.slice(0, i) + "Q" + run.text.slice(i),
+ )!;
+ expect(plan.removePtrs.length).toBeGreaterThan(0);
+ const applied = applyPartialEditPlan(doc, page, run, plan, tags);
+ for (const ptr of applied.insertedPtrs)
+ m.FPDFPage_RemoveObject(page.pagePtr, ptr);
+
+ const redrawn = revertPartialEditPlan(
+ doc,
+ page,
+ run,
+ plan,
+ prev,
+ () => tags,
+ "Helvetica",
+ );
+
+ expect(redrawn?.size).toBeGreaterThan(0);
+ expect(wordColours(doc, "today")).toEqual(sameColour("blue", 5));
+ expect(wordColours(doc, "Totaldue")).toEqual(sameColour("black", 8));
+});
+
+test.each([
+ ["an Enter before a blue word", "call the ", "call the\n"],
+ ["an Enter after a blue word", "Helpdesk ", "Helpdesk\n"],
+ ["an edit spanning two lines", "Scotland\ncall", "ScotlandQ\nQcall"],
+])(
+ "after %s, every redrawn word keeps its own colour and face, through undo and save",
+ async (_name, from, to) => {
+ const doc = await open();
+ const history = new HistoryStack();
+ const run = doc.page(0).runs.find((r) => r.text.includes("Scotland"))!;
+ history.execute(
+ new EditTextCommand({
+ pageIndex: 0,
+ runId: run.id,
+ nextText: run.text.replace(from, to),
+ }),
+ doc,
+ );
+ const check = (d: EditorDocument) => {
+ expect(wordColours(d, "Helpdesk")).toEqual(sameColour("blue", 8));
+ expect(wordFaces(d, "Helpdesk")).toEqual(Array(8).fill("bold"));
+ expect(wordColours(d, "Scotland")).toEqual(sameColour("blue", 8));
+ expect(wordColours(d, "team")).toEqual(sameColour("black", 4));
+ expect(wordFaces(d, "team")).toEqual(Array(4).fill("regular"));
+ expect(wordColours(d, "callthe").slice(-3)).toEqual(
+ sameColour("black", 3),
+ );
+ };
+ check(doc);
+ check(
+ await open(new Uint8Array(await (await exportToBlob(doc)).arrayBuffer())),
+ );
+ history.undo(doc);
+ check(doc);
+ },
+);
+
+// Hebrew is drawn right to left, so its letters read backwards along the page.
+const drawnLeftToRight = (word: string) => [...word].reverse().join("");
+
+test.each([
+ ["inside the blue word", "שלום", 2, "שללום", "blue"],
+ ["after a black word", "הטלפון", 6, "הטלפוןל", "black"],
+] as const)(
+ "a letter typed into a right-to-left line %s takes that word's colour, through undo and save",
+ async (_name, needle, at, word, colour) => {
+ const doc = await open();
+ const history = new HistoryStack();
+ const run = doc.page(0).runs.find((r) => r.text.includes(needle))!;
+ const i = run.text.indexOf(needle) + at;
+ history.execute(
+ new EditTextCommand({
+ pageIndex: 0,
+ runId: run.id,
+ nextText: run.text.slice(0, i) + "ל" + run.text.slice(i),
+ }),
+ doc,
+ );
+ const drawn = drawnLeftToRight(word);
+ expect(wordColours(doc, drawn)).toEqual(sameColour(colour, word.length));
+ const saved = await open(
+ new Uint8Array(await (await exportToBlob(doc)).arrayBuffer()),
+ );
+ expect(wordColours(saved, drawn)).toEqual(sameColour(colour, word.length));
+ history.undo(doc);
+ expect(wordColours(doc, drawnLeftToRight("שלום"))).toEqual(
+ sameColour("blue", 4),
+ );
+ },
+);
+
+test("a right-to-left edit still draws after other documents were edited and closed", async () => {
+ for (const [from, to] of [
+ ["call the ", "call the\n"],
+ ["Scotland\ncall", "ScotlandQ\nQcall"],
+ ]) {
+ const doc = await openSample();
+ const history = new HistoryStack();
+ const run = doc.page(0).runs.find((r) => r.text.includes("Scotland"))!;
+ history.execute(
+ new EditTextCommand({
+ pageIndex: 0,
+ runId: run.id,
+ nextText: run.text.replace(from, to),
+ }),
+ doc,
+ );
+ const saved = await openSample(
+ new Uint8Array(await (await exportToBlob(doc)).arrayBuffer()),
+ );
+ history.undo(doc);
+ doc.dispose();
+ saved.dispose();
+ }
+
+ const doc = await open();
+ const run = doc.page(0).runs.find((r) => r.text.includes("שלום"))!;
+ const i = run.text.indexOf("שלום") + 2;
+ new HistoryStack().execute(
+ new EditTextCommand({
+ pageIndex: 0,
+ runId: run.id,
+ nextText: run.text.slice(0, i) + "ל" + run.text.slice(i),
+ }),
+ doc,
+ );
+ expect(wordColours(doc, drawnLeftToRight("שללום"))).toEqual(
+ sameColour("blue", 5),
+ );
+});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/complexScriptEdits.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/complexScriptEdits.test.ts
new file mode 100644
index 0000000000..61d5354e7a
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/complexScriptEdits.test.ts
@@ -0,0 +1,330 @@
+// @vitest-environment node
+import { readFile } from "node:fs/promises";
+import { createRequire } from "node:module";
+import path from "node:path";
+import { afterAll, afterEach, beforeAll, expect, test, vi } from "vitest";
+
+import { resetCmapCache } from "@editor/tools/pdfTextEditor/charcode/CmapResolver";
+import { resetContentStreamCache } from "@editor/tools/pdfTextEditor/charcode/ContentStreamResolver";
+import { resetFontHelperCaches } from "@editor/tools/pdfTextEditor/charcode/FontHelpers";
+import { lettersWithoutGlyph } from "@editor/tools/pdfTextEditor/charcode/fontGlyphs";
+import { RolledBackError } from "@editor/tools/pdfTextEditor/commands/Command";
+import { DuplicateRunCommand } from "@editor/tools/pdfTextEditor/commands/DuplicateRunCommand";
+import { EditTextCommand } from "@editor/tools/pdfTextEditor/commands/EditTextCommand";
+import { SetFontFamilyCommand } from "@editor/tools/pdfTextEditor/commands/SetFontFamilyCommand";
+import {
+ _clearDroppedBase14CharsForTests,
+ getDroppedBase14Chars,
+ resetCharCoverageCache,
+ resetOnPageAdvCache,
+} from "@editor/tools/pdfTextEditor/commands/editTextHelpers";
+import {
+ HistoryStack,
+ HistoryStepError,
+} from "@editor/tools/pdfTextEditor/store/HistoryStack";
+import { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
+import { PdfiumTextReader } from "@editor/tools/pdfTextEditor/pdfium/PdfiumTextReader";
+import { needsShaping } from "@editor/tools/pdfTextEditor/util/complexShaping";
+import {
+ emitDeviceFontTextObject,
+ loadDeviceFontInto,
+ resetDeviceFontEmbedCache,
+} from "@editor/tools/pdfTextEditor/util/deviceFontEmbed";
+import {
+ resetFontCompletions,
+ setClosestFont,
+} from "@editor/tools/pdfTextEditor/util/documentFontCompletion";
+import { exportToBlob } from "@editor/tools/pdfTextEditor/util/exportPdf";
+import { registerFontBytes } from "@editor/tools/pdfTextEditor/util/localFonts";
+import { FONT_DIR } from "@editor/tools/pdfTextEditor/__tests__/scanFixtures";
+
+const FIXTURES = path.join(import.meta.dirname, "../../../tests/test-fixtures");
+const BLACK = { r: 0, g: 0, b: 0, a: 255 };
+const DEVANAGARI = "Noto Sans Devanagari";
+const OTHER_DEVANAGARI = "Second Devanagari";
+const opened: EditorDocument[] = [];
+
+beforeAll(async () => {
+ const wasm = await readFile(
+ createRequire(import.meta.url).resolve("@embedpdf/pdfium/pdfium.wasm"),
+ );
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async (url: string) =>
+ String(url).endsWith(".wasm")
+ ? new Response(wasm, {
+ headers: { "Content-Type": "application/wasm" },
+ })
+ : new Response(null, { status: 404 }),
+ ),
+ );
+ for (const [family, file] of [
+ [DEVANAGARI, "NotoSansDevanagari-Regular.ttf"],
+ [OTHER_DEVANAGARI, "NotoSansDevanagari-Regular.ttf"],
+ ["Noto Sans", "NotoSans-Regular.ttf"],
+ ["Noto Sans Hebrew", "NotoSansHebrew-Regular.ttf"],
+ ["Liberation Sans", "LiberationSans-Regular.ttf"],
+ ])
+ registerFontBytes(
+ family,
+ new Uint8Array(await readFile(path.join(FONT_DIR, file))),
+ );
+});
+
+afterEach(() => {
+ for (const doc of opened.splice(0)) doc.dispose();
+ // Keyed by font and page pointers, which the next document reuses.
+ resetCharCoverageCache();
+ resetContentStreamCache();
+ resetCmapCache();
+ resetFontHelperCaches();
+ resetOnPageAdvCache();
+ resetDeviceFontEmbedCache();
+ resetFontCompletions();
+ _clearDroppedBase14CharsForTests();
+});
+
+afterAll(() => vi.unstubAllGlobals());
+
+async function open(bytes: Uint8Array): Promise<EditorDocument> {
+ const doc = await EditorDocument.open(bytes);
+ opened.push(doc);
+ PdfiumTextReader.populate(doc, doc.page(0));
+ return doc;
+}
+
+const sample = async () =>
+ open(new Uint8Array(await readFile(path.join(FIXTURES, "sample.pdf"))));
+
+const saved = async (doc: EditorDocument) =>
+ open(new Uint8Array(await (await exportToBlob(doc)).arrayBuffer()));
+
+const pageText = (doc: EditorDocument) =>
+ doc
+ .page(0)
+ .runs.map((run) => run.text)
+ .join("\n");
+
+/** A document holding `text` drawn straight from its code points, as another producer could have written it. */
+async function withLine(text: string): Promise<EditorDocument> {
+ const doc = await sample();
+ const page = doc.page(0);
+ expect(
+ emitDeviceFontTextObject(doc, page, DEVANAGARI, text, 24, BLACK, 60, 120),
+ ).not.toBe(0);
+ page.markDirty();
+ page.markNeedsGenerate();
+ return saved(doc);
+}
+
+test.each([
+ ["Noto Sans", "́"],
+ ["Noto Sans Hebrew", "ְ"],
+ [DEVANAGARI, "े"],
+])("draws a combining mark %s has, on its own", async (family, mark) => {
+ const doc = await sample();
+
+ expect(
+ emitDeviceFontTextObject(doc, doc.page(0), family, mark, 24, BLACK, 60, 60),
+ ).not.toBe(0);
+ expect(
+ lettersWithoutGlyph(doc.module, loadDeviceFontInto(doc, family), mark),
+ ).toEqual([]);
+});
+
+test("still refuses a combining mark the face does not have", async () => {
+ const doc = await sample();
+
+ expect(
+ emitDeviceFontTextObject(
+ doc,
+ doc.page(0),
+ "Liberation Sans",
+ "ְ",
+ 24,
+ BLACK,
+ 60,
+ 60,
+ ),
+ ).toBe(0);
+});
+
+test.each([
+ ["Latin with a combining accent", "café", false],
+ ["Greek", "Καλημέρα", false],
+ ["Cyrillic", "Привет", false],
+ ["Hebrew with niqqud", "שָׁלוֹם", false],
+ ["Arabic with harakat", "مَرْحَبًا", false],
+ ["Thai with single marks", "สวัสดี น้ำ", false],
+ ["Thai with a tone mark stacked on a vowel", "ที่", true],
+ ["Thai with a mark on a tall consonant", "ปั๊ม", true],
+ ["Devanagari with signs drawn in place", "नमस भारत कौन", false],
+ ["a Devanagari conjunct", "नमस्ते", true],
+ ["a Devanagari pre-base vowel sign", "किताब", true],
+ ["a Devanagari sign above", "नमे", true],
+ ["a Malayalam pre-base vowel sign", "കേരളം", true],
+ ["a Tibetan stack", "བཀྲ", true],
+ ["Syriac", "ܫܠܡܐ", true],
+])("%s: needs shaping is %j", (_, text, expected) => {
+ expect(needsShaping(text)).toBe(expected);
+});
+
+test("refuses typing a Devanagari conjunct and leaves the line as it was", async () => {
+ const doc = await sample();
+ const page = doc.page(0);
+ const run = page.runs[0];
+ setClosestFont(run.fontId, DEVANAGARI);
+ const before = run.text;
+
+ const edit = new EditTextCommand({
+ pageIndex: 0,
+ runId: run.id,
+ nextText: "नमस्ते",
+ });
+
+ expect(() => edit.apply(doc)).toThrow(RolledBackError);
+ expect(run.text).toBe(before);
+ expect(getDroppedBase14Chars()).toEqual([]);
+ expect(pageText(await saved(doc))).toContain(before.trim());
+});
+
+test("refuses typing a Devanagari conjunct when no face for it is loaded", async () => {
+ const doc = await sample();
+ const run = doc.page(0).runs[0];
+ const before = run.text;
+
+ const edit = new EditTextCommand({
+ pageIndex: 0,
+ runId: run.id,
+ nextText: `${before}नमस्ते`,
+ });
+
+ expect(() => edit.apply(doc)).toThrow(RolledBackError);
+ expect(run.text).toBe(before);
+ expect(getDroppedBase14Chars()).toEqual([]);
+});
+
+test("refuses a deletion that would redraw the rest of a conjunct", async () => {
+ const doc = await withLine("नमस्ते");
+ const page = doc.page(0);
+ const run = page.runs.find((r) => r.text.includes("नमस्ते"))!;
+ const before = run.text;
+ const objects = doc.module.FPDFPage_CountObjects(page.pagePtr);
+
+ const edit = new EditTextCommand({
+ pageIndex: 0,
+ runId: run.id,
+ nextText: before.replace("नमस्ते", "नमस्त"),
+ });
+
+ expect(() => edit.apply(doc)).toThrow(RolledBackError);
+ expect(run.text).toBe(before);
+ expect(doc.module.FPDFPage_CountObjects(page.pagePtr)).toBe(objects);
+ expect(pageText(await saved(doc))).toContain("नमस्ते");
+});
+
+test("an edit beside a conjunct the page already draws keeps it, through undo and redo", async () => {
+ const doc = await withLine("नमस्ते");
+ const page = doc.page(0);
+ const run = page.runs.find((r) => r.text.includes("नमस्ते"))!;
+ const before = run.text;
+ const history = new HistoryStack();
+
+ try {
+ history.execute(
+ new EditTextCommand({
+ pageIndex: 0,
+ runId: run.id,
+ nextText: `${before} ok`,
+ }),
+ doc,
+ );
+ } catch (err) {
+ expect(err).toBeInstanceOf(HistoryStepError);
+ expect((err as HistoryStepError).documentIntact).toBe(true);
+ expect(run.text).toBe(before);
+ return;
+ }
+ expect(run.text).toBe(`${before} ok`);
+ history.undo(doc);
+ expect(run.text).toBe(before);
+ history.redo(doc);
+ expect(run.text).toBe(`${before} ok`);
+ const text = pageText(await saved(doc));
+ expect(text).toContain("नमस्ते");
+ expect(text).toContain("ok");
+});
+
+test("refuses a Thai tone mark typed onto a vowel sign", async () => {
+ const doc = await sample();
+ const run = doc.page(0).runs[0];
+ const before = run.text;
+
+ const edit = new EditTextCommand({
+ pageIndex: 0,
+ runId: run.id,
+ nextText: `${before}ที่`,
+ });
+ const typed = new EditTextCommand({
+ pageIndex: 0,
+ runId: run.id,
+ nextText: `${before}ที`,
+ });
+
+ expect(() => edit.apply(doc)).toThrow(RolledBackError);
+ typed.apply(doc);
+ expect(() =>
+ new EditTextCommand({
+ pageIndex: 0,
+ runId: run.id,
+ nextText: `${before}ที่`,
+ }).apply(doc),
+ ).toThrow(RolledBackError);
+ expect(run.text).toBe(`${before}ที`);
+});
+
+test("still draws Devanagari whose signs need no shaping", async () => {
+ const doc = await sample();
+ const run = doc.page(0).runs[0];
+ setClosestFont(run.fontId, DEVANAGARI);
+
+ new EditTextCommand({
+ pageIndex: 0,
+ runId: run.id,
+ nextText: "नमस भारत",
+ }).apply(doc);
+
+ expect(run.text).toBe("नमस भारत");
+ expect(getDroppedBase14Chars()).toEqual([]);
+ expect(pageText(await saved(doc))).toContain("नमस भारत");
+});
+
+test("refuses a font change that would redraw a conjunct", async () => {
+ const doc = await withLine("नमस्ते");
+ const page = doc.page(0);
+ const run = page.runs.find((r) => r.text.includes("नमस्ते"))!;
+ const fontId = run.fontId;
+ const objects = doc.module.FPDFPage_CountObjects(page.pagePtr);
+
+ new SetFontFamilyCommand({
+ pageIndex: 0,
+ runId: run.id,
+ nextFamily: OTHER_DEVANAGARI,
+ }).apply(doc);
+
+ expect(run.fontId).toBe(fontId);
+ expect(doc.module.FPDFPage_CountObjects(page.pagePtr)).toBe(objects);
+});
+
+test("refuses a copy that would redraw a conjunct", async () => {
+ const doc = await withLine("नमस्ते");
+ const page = doc.page(0);
+ const run = page.runs.find((r) => r.text.includes("नमस्ते"))!;
+ const runs = page.runs.length;
+
+ const copy = new DuplicateRunCommand({ pageIndex: 0, runId: run.id });
+
+ expect(() => copy.apply(doc)).toThrow(RolledBackError);
+ expect(copy.insertedRunId).toBeNull();
+ expect(page.runs).toHaveLength(runs);
+});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/deviceFontEmbed.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/deviceFontEmbed.test.ts
index a9e24d029e..0ff7e3b5e3 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/deviceFontEmbed.test.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/deviceFontEmbed.test.ts
@@ -170,6 +170,8 @@ function fakeHarness(options: FakeModuleOptions = {}): FakeHarness {
ownedFonts.set(font.id, font);
},
ownedFont: (id: string) => ownedFonts.get(id),
+ findOwnedFont: (matches: (font: FontRef) => boolean) =>
+ [...ownedFonts.values()].find(matches),
recordEmbeddedFontFile: (bytes: Uint8Array) =>
embeddedFontFiles.push(bytes),
embeddedFontFiles: () => embeddedFontFiles,
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/documentFontCompletion.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/documentFontCompletion.test.ts
index 030d73be7c..462afa10ee 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/documentFontCompletion.test.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/documentFontCompletion.test.ts
@@ -86,6 +86,31 @@ beforeEach(() => {
});
describe("resolveOriginalFonts", () => {
+ it("reads no further font once the document has closed", async () => {
+ await install([
+ face(
+ "Liberation Sans",
+ "Regular",
+ "LiberationSans",
+ "LiberationSans-Regular.ttf",
+ ),
+ ]);
+ const m = documentNaming("ABCDEF+LiberationSans");
+ const readName = vi.spyOn(m, "FPDFFont_GetBaseFontName");
+ let checks = 0;
+ const openForOneCheck = () => checks++ < 1;
+
+ await resolveOriginalFonts(
+ m,
+ ["pdf:21:Liberation Sans", "pdf:22:Liberation Sans"],
+ openForOneCheck,
+ );
+
+ expect(readName.mock.calls.some(([handle]) => Number(handle) === 22)).toBe(
+ false,
+ );
+ });
+
it("completes a subset from the installed font its glyphs agree with", async () => {
await install([
face(
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/editBurstUndo.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/editBurstUndo.test.ts
new file mode 100644
index 0000000000..e41a69c20f
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/editBurstUndo.test.ts
@@ -0,0 +1,280 @@
+// @vitest-environment node
+import { readFile } from "node:fs/promises";
+import { createRequire } from "node:module";
+import path from "node:path";
+import {
+ afterAll,
+ afterEach,
+ beforeAll,
+ describe,
+ expect,
+ test,
+ vi,
+} from "vitest";
+import { EditTextCommand } from "@editor/tools/pdfTextEditor/commands/EditTextCommand";
+import { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
+import { PdfiumTextReader } from "@editor/tools/pdfTextEditor/pdfium/PdfiumTextReader";
+import { HistoryStack } from "@editor/tools/pdfTextEditor/store/HistoryStack";
+
+const SAMPLE = path.join(
+ import.meta.dirname,
+ "../../../tests/test-fixtures/paragraph-sample.pdf",
+);
+const HEADING = "Heading in a bigger size";
+const FPDF_PAGEOBJ_TEXT = 1;
+
+const opened: EditorDocument[] = [];
+
+beforeAll(async () => {
+ const wasmPath = createRequire(import.meta.url).resolve(
+ "@embedpdf/pdfium/pdfium.wasm",
+ );
+ const wasmBytes = await readFile(wasmPath);
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async () =>
+ Promise.resolve(
+ new Response(wasmBytes, {
+ headers: { "Content-Type": "application/wasm" },
+ }),
+ ),
+ ),
+ );
+});
+
+afterAll(() => {
+ vi.unstubAllGlobals();
+});
+
+afterEach(() => {
+ for (const doc of opened.splice(0)) doc.dispose();
+});
+
+async function open(): Promise<EditorDocument> {
+ const doc = await EditorDocument.open(new Uint8Array(await readFile(SAMPLE)));
+ opened.push(doc);
+ PdfiumTextReader.populate(doc, doc.page(0));
+ return doc;
+}
+
+// The heading line as drawn: the model can be right while undone objects still paint.
+function piecesOnHeadingLine(
+ doc: EditorDocument,
+ headingId: string,
+): Array<{ left: number; text: string }> {
+ const m = doc.module;
+ const pagePtr = doc.page(0).pagePtr;
+ const heading = doc.page(0).runs.find((r) => r.id === headingId)!;
+ const box = m.pdfium.wasmExports.malloc(16);
+ const text = m.pdfium.wasmExports.malloc(1024);
+ const textPage = m.FPDFText_LoadPage(pagePtr);
+ const pieces: Array<{ left: number; text: string }> = [];
+ try {
+ for (let i = 0; i < m.FPDFPage_CountObjects(pagePtr); i++) {
+ const obj = m.FPDFPage_GetObject(pagePtr, i);
+ if (m.FPDFPageObj_GetType(obj) !== FPDF_PAGEOBJ_TEXT) continue;
+ if (!m.FPDFPageObj_GetBounds(obj, box, box + 4, box + 8, box + 12))
+ continue;
+ const bottom = m.pdfium.getValue(box + 4, "float");
+ if (Math.abs(bottom - heading.bounds.y) > heading.bounds.height) continue;
+ m.FPDFTextObj_GetText(obj, textPage, text, 1024);
+ pieces.push({
+ left: m.pdfium.getValue(box, "float"),
+ text: m.pdfium.UTF16ToString(text),
+ });
+ }
+ } finally {
+ m.FPDFText_ClosePage(textPage);
+ m.pdfium.wasmExports.free(box);
+ m.pdfium.wasmExports.free(text);
+ }
+ return pieces.sort((a, b) => a.left - b.left);
+}
+
+function drawnOnHeadingLine(doc: EditorDocument, headingId: string): string {
+ return piecesOnHeadingLine(doc, headingId)
+ .map((p) => p.text)
+ .join("")
+ .replace(/\s+/g, "");
+}
+
+// Edits back to back, inside the history's merge window.
+function burst(
+ doc: EditorDocument,
+ history: HistoryStack,
+ headingId: string,
+ texts: string[],
+) {
+ for (const nextText of texts)
+ history.execute(
+ new EditTextCommand({ pageIndex: 0, runId: headingId, nextText }),
+ doc,
+ );
+}
+
+const squashed = (text: string) => text.replace(/\s+/g, "");
+
+describe("undoing a burst of edits to one line", () => {
+ const steps = [
+ `${HEADING} Zq7`,
+ `Xk ${HEADING} Zq7`,
+ `Xk Heading Wj9 in a bigger size Zq7`,
+ `Xk Heading Wj9 ina bigger size Zq7`,
+ `Xk Heading Wj9 ina Quixotic size Zq7`,
+ `Xk Heading Wj9 ina Quixotic size Zq`,
+ ];
+ const final = steps[steps.length - 1];
+
+ test("leaves nothing typed on the page, and redo draws it once", async () => {
+ const doc = await open();
+ const run = doc.page(0).runs.find((r) => r.text === HEADING)!;
+ const headingId = run.id;
+ const history = new HistoryStack();
+
+ burst(doc, history, headingId, steps);
+ expect(history.size().undo).toBe(1);
+ expect(drawnOnHeadingLine(doc, headingId)).toBe(squashed(final));
+
+ history.undo(doc);
+ expect(run.text).toBe(HEADING);
+ expect(drawnOnHeadingLine(doc, headingId)).toBe(squashed(HEADING));
+
+ history.redo(doc);
+ expect(run.text).toBe(final);
+ expect(drawnOnHeadingLine(doc, headingId)).toBe(squashed(final));
+
+ history.undo(doc);
+ expect(drawnOnHeadingLine(doc, headingId)).toBe(squashed(HEADING));
+ });
+
+ test.each([
+ ["a burst", 1],
+ ["separate edits", 2],
+ ])("leaves the edit before %s undoable", async (_case, undoSteps) => {
+ const doc = await open();
+ const run = doc.page(0).runs.find((r) => r.text === HEADING)!;
+ const headingId = run.id;
+ const history = new HistoryStack();
+
+ burst(doc, history, headingId, [`${HEADING} Zq7`]);
+ history.breakCoalescing();
+ burst(doc, history, headingId, [`${HEADING} Wj9`]);
+ if (undoSteps > 1) history.breakCoalescing();
+ burst(doc, history, headingId, [`${HEADING} Wj90`]);
+ expect(history.size().undo).toBe(1 + undoSteps);
+ for (let i = 0; i < undoSteps; i++) history.undo(doc);
+ expect(drawnOnHeadingLine(doc, headingId)).toBe(squashed(`${HEADING} Zq7`));
+ history.undo(doc);
+
+ expect(run.text).toBe(HEADING);
+ expect(drawnOnHeadingLine(doc, headingId)).toBe(squashed(HEADING));
+ });
+
+ test.each([
+ [`Xk ${HEADING}`, [HEADING, `${HEADING} Q`]],
+ [`Xk Yz ${HEADING}`, [`Yz ${HEADING}`, `Yz ${HEADING}!`]],
+ ])(
+ "puts back the spacing a burst deleting the first piece of %s shifted",
+ async (start, steps) => {
+ const doc = await open();
+ const run = doc.page(0).runs.find((r) => r.text === HEADING)!;
+ const history = new HistoryStack();
+ burst(doc, history, run.id, [start]);
+ history.breakCoalescing();
+ const pieces = piecesOnHeadingLine(doc, run.id);
+
+ burst(doc, history, run.id, steps);
+ history.undo(doc);
+
+ const restored = piecesOnHeadingLine(doc, run.id);
+ expect(restored.map((p) => p.text)).toEqual(pieces.map((p) => p.text));
+ restored.forEach((piece, i) =>
+ expect(piece.left).toBeCloseTo(pieces[i].left, 0),
+ );
+ },
+ );
+
+ test.each([
+ [["Heading in a bigger siz", "Heading in a bigger si"]],
+ [["Heading in a Qbigger size", "Heading in a QQbigger size"]],
+ ])("puts the line back in its own font after %j", async (steps) => {
+ const doc = await open();
+ const run = doc.page(0).runs.find((r) => r.text === HEADING)!;
+ const font = run.fontId;
+ const history = new HistoryStack();
+
+ burst(doc, history, run.id, steps);
+ history.undo(doc);
+ expect(run.fontId).toBe(font);
+ history.redo(doc);
+ history.undo(doc);
+
+ expect(run.fontId).toBe(font);
+ });
+
+ test("puts the line back where it started", async () => {
+ const doc = await open();
+ const run = doc.page(0).runs.find((r) => r.text === HEADING)!;
+ const headingId = run.id;
+ const left = piecesOnHeadingLine(doc, headingId)[0].left;
+ const history = new HistoryStack();
+
+ burst(doc, history, headingId, steps);
+ history.undo(doc);
+
+ expect(piecesOnHeadingLine(doc, headingId)[0].left).toBeCloseTo(left, 0);
+ });
+});
+
+describe("undoing a burst on a subset-embedded line", () => {
+ const SUBSET_SAMPLE = path.join(
+ import.meta.dirname,
+ "../../../tests/test-fixtures/subset-font-sample.pdf",
+ );
+ const LINE = "Body text with embedded subset glyphs";
+
+ test.each([
+ [[`${LINE}Z`, `${LINE}Z\nmore`]],
+ [[`${LINE.slice(0, -1)}`, `${LINE.slice(0, -1)}\nZ`]],
+ [[`${LINE}!`, `${LINE}!\nnew line`]],
+ ])("puts the line back in its embedded font after %j", async (steps) => {
+ const doc = await EditorDocument.open(
+ new Uint8Array(await readFile(SUBSET_SAMPLE)),
+ );
+ opened.push(doc);
+ PdfiumTextReader.populate(doc, doc.page(0));
+ const run = doc.page(0).runs.find((r) => r.text === LINE)!;
+ const font = run.fontId;
+ const history = new HistoryStack();
+
+ burst(doc, history, run.id, steps);
+ history.undo(doc);
+
+ expect(run.text).toBe(LINE);
+ expect(run.fontId).toBe(font);
+ });
+});
+
+describe("undoing one edit that removed a piece of the line", () => {
+ test.each([
+ ["deleting", HEADING],
+ ["replacing", `${HEADING} Wj9`],
+ ])("puts back the piece after %s it", async (_change, nextText) => {
+ const doc = await open();
+ const run = doc.page(0).runs.find((r) => r.text === HEADING)!;
+ const headingId = run.id;
+ const left = piecesOnHeadingLine(doc, headingId)[0].left;
+ const edit = (text: string) =>
+ new EditTextCommand({ pageIndex: 0, runId: headingId, nextText: text });
+ edit(`${HEADING} Zq7`).apply(doc);
+ const pieces = [...run.mergedFromTexts];
+ const change = edit(nextText);
+
+ change.apply(doc);
+ change.revert(doc);
+
+ expect(run.mergedFromTexts).toEqual(pieces);
+ expect(drawnOnHeadingLine(doc, headingId)).toBe(squashed(`${HEADING} Zq7`));
+ expect(piecesOnHeadingLine(doc, headingId)[0].left).toBeCloseTo(left, 0);
+ });
+});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/editorStores.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/editorStores.ts
new file mode 100644
index 0000000000..82064257bc
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/editorStores.ts
@@ -0,0 +1,65 @@
+import { readFile } from "node:fs/promises";
+import { createRequire } from "node:module";
+import path from "node:path";
+import { afterAll, afterEach, beforeAll, vi } from "vitest";
+import { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
+import { PdfiumTextReader } from "@editor/tools/pdfTextEditor/pdfium/PdfiumTextReader";
+import { EditorStore } from "@editor/tools/pdfTextEditor/store/EditorStore";
+import { exportToBlob } from "@editor/tools/pdfTextEditor/util/exportPdf";
+
+export const FIXTURES = path.join(
+ import.meta.dirname,
+ "../../../tests/test-fixtures",
+);
+
+/** Serves the bundled PDFium wasm to the editor's loader in place of `fetch` for the calling file's tests; call at its top level. */
+export function servePdfiumWasm(): void {
+ beforeAll(async () => {
+ const wasm = await readFile(
+ createRequire(import.meta.url).resolve("@embedpdf/pdfium/pdfium.wasm"),
+ );
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async (url: string) =>
+ String(url).endsWith(".wasm")
+ ? new Response(wasm, {
+ headers: { "Content-Type": "application/wasm" },
+ })
+ : new Response(null, { status: 404 }),
+ ),
+ );
+ });
+ afterAll(() => vi.unstubAllGlobals());
+}
+
+/** Opens PDFs into editor stores with page 0 read, each disposed after the test that opened it; call at a test file's top level. */
+export function editorStores() {
+ const stores: EditorStore[] = [];
+ afterEach(() => {
+ for (const store of stores.splice(0)) store.dispose();
+ });
+ async function storeWith(bytes: Uint8Array): Promise<EditorStore> {
+ const doc = await EditorDocument.open(bytes);
+ const store = new EditorStore();
+ stores.push(store);
+ await store.setDocument(doc);
+ PdfiumTextReader.populate(doc, doc.page(0));
+ return store;
+ }
+ async function fixture(name: string): Promise<EditorStore> {
+ return storeWith(new Uint8Array(await readFile(path.join(FIXTURES, name))));
+ }
+ return { storeWith, fixture };
+}
+
+// jsdom's Blob reads back through FileReader only.
+export async function savedBytes(store: EditorStore): Promise<Uint8Array> {
+ const blob = await exportToBlob(store.document!);
+ const buffer = await new Promise<ArrayBuffer>((resolve, reject) => {
+ const reader = new FileReader();
+ reader.onload = () => resolve(reader.result as ArrayBuffer);
+ reader.onerror = () => reject(reader.error);
+ reader.readAsArrayBuffer(blob);
+ });
+ return new Uint8Array(buffer);
+}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/exactLayout.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/exactLayout.test.ts
index 3faf0f0779..fa43611686 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/exactLayout.test.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/exactLayout.test.ts
@@ -72,6 +72,30 @@ describe("buildExactLines", () => {
expect(lines?.[1].left).toBe(40);
});
+ it.each([
+ ["after the last line", "ab\n", [40, 50, Number.NaN], 40],
+ [
+ "between two lines",
+ "ab\n\ncd",
+ [40, 50, Number.NaN, Number.NaN, 60, 70],
+ 40,
+ ],
+ ["before the first line", "\nab", [Number.NaN, 40, 50], 40],
+ ])(
+ "starts an empty line %s where its neighbour starts, not at the page edge",
+ (_case, text, starts, left) => {
+ const positions: CharPositions = {
+ starts,
+ ends: starts.map((x) => x + 10),
+ };
+ const lines = buildExactLines(text, positions);
+ expect(
+ lines?.every((line) => line.left === left || line.tokens.length > 0),
+ ).toBe(true);
+ expect(lines?.find((line) => line.tokens.length === 0)?.left).toBe(left);
+ },
+ );
+
it("drops the engine-trimmed trailing spaces into a zero-width token", () => {
const positions: CharPositions = {
starts: [0, 10, Number.NaN],
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/failedOpen.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/failedOpen.test.ts
new file mode 100644
index 0000000000..f2dd78591d
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/failedOpen.test.ts
@@ -0,0 +1,99 @@
+// @vitest-environment node
+import { readFile } from "node:fs/promises";
+import { createRequire } from "node:module";
+import path from "node:path";
+import { afterAll, afterEach, beforeAll, expect, test, vi } from "vitest";
+import { loadDocument } from "@editor/tools/pdfTextEditor/hooks/useDocumentLoader";
+import { EditorStore } from "@editor/tools/pdfTextEditor/store/EditorStore";
+
+const FIXTURES = path.join(import.meta.dirname, "../../../tests/test-fixtures");
+const PASSWORD = "testpass123";
+const stores: EditorStore[] = [];
+
+beforeAll(async () => {
+ const wasm = await readFile(
+ createRequire(import.meta.url).resolve("@embedpdf/pdfium/pdfium.wasm"),
+ );
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async (url: string) =>
+ String(url).endsWith(".wasm")
+ ? new Response(wasm, {
+ headers: { "Content-Type": "application/wasm" },
+ })
+ : new Response(null, { status: 404 }),
+ ),
+ );
+});
+
+afterEach(() => {
+ for (const store of stores.splice(0)) store.dispose();
+});
+
+afterAll(() => vi.unstubAllGlobals());
+
+async function fixture(name: string): Promise<File> {
+ return new File([await readFile(path.join(FIXTURES, name))], name, {
+ type: "application/pdf",
+ });
+}
+
+async function storeWithSample() {
+ const store = new EditorStore();
+ stores.push(store);
+ expect(await loadDocument(store, await fixture("sample.pdf"))).toBe(true);
+ return { store, sample: store.document };
+}
+
+test("a file that is not a PDF reports no open and leaves the document on screen", async () => {
+ const { store, sample } = await storeWithSample();
+ const broken = new File(["this is not a PDF"], "cannot-open.pdf", {
+ type: "application/pdf",
+ });
+ expect(await loadDocument(store, broken)).toBe(false);
+ expect(store.document).toBe(sample);
+ expect(store.getState().error).toBeTruthy();
+});
+
+test("a password prompt reports no open until the password is given", async () => {
+ const { store, sample } = await storeWithSample();
+ const locked = await fixture("encrypted.pdf");
+ expect(await loadDocument(store, locked)).toBe(false);
+ expect(store.document).toBe(sample);
+ expect(store.getState().passwordPrompt).toBeTruthy();
+
+ expect(await loadDocument(store, locked, PASSWORD)).toBe(true);
+ expect(store.document).not.toBe(sample);
+ expect(store.getState().passwordPrompt).toBeFalsy();
+});
+
+test("a load overtaken by a newer one reports no open", async () => {
+ const { store } = await storeWithSample();
+ const [older, newer] = await Promise.all([
+ fixture("sample.pdf"),
+ fixture("paragraph-sample.pdf"),
+ ]);
+ const first = loadDocument(store, older);
+ const second = loadDocument(store, newer);
+ expect(await first).toBe(false);
+ expect(await second).toBe(true);
+});
+
+test("an open whose document is still on screen when a newer open fails still reports the open", async () => {
+ const { store, sample } = await storeWithSample();
+ let failing: Promise<boolean> | null = null;
+ const stop = store.subscribe(() => {
+ if (failing || store.document === sample) return;
+ failing = loadDocument(
+ store,
+ new File(["this is not a PDF"], "cannot-open.pdf"),
+ );
+ });
+ const opening = loadDocument(store, await fixture("many-pages-sample.pdf"));
+ const opened = await opening;
+ stop();
+ expect(failing).not.toBeNull();
+ expect(await failing).toBe(false);
+ expect(opened).toBe(true);
+ expect(store.document).not.toBe(sample);
+});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/fontCapability.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/fontCapability.test.ts
index 6958fe7512..daac07029a 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/fontCapability.test.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/fontCapability.test.ts
@@ -1,10 +1,12 @@
import { describe, expect, it, beforeEach, vi } from "vitest";
import {
- canToggleItalic,
fallbackFamilyFor,
fallbackFontIdFor,
- italicCapability,
} from "@editor/tools/pdfTextEditor/util/fontCapability";
+import {
+ canRestyle,
+ restyledFace,
+} from "@editor/tools/pdfTextEditor/util/fontFaces";
import {
resetFontCompletions,
resolveOriginalFonts,
@@ -78,54 +80,106 @@ beforeEach(() => {
stubQueryLocalFonts(null);
});
-describe("italicCapability", () => {
+const NO_DOCUMENT = { documentFamilies: [] };
+
+describe("restyledFace for italic", () => {
it("flips a base-14 family in place", () => {
- expect(italicCapability("base14:Helvetica", true, null)).toEqual({
- family: "Helvetica-Oblique",
- source: "base14",
- });
- expect(italicCapability("base14:Times-BoldItalic", false, null)).toEqual({
- family: "Times-Bold",
- source: "base14",
- });
+ expect(
+ restyledFace(
+ "base14:Helvetica",
+ { italic: true },
+ { ...NO_DOCUMENT, externalFonts: null },
+ ),
+ ).toBe("Helvetica-Oblique");
+ expect(
+ restyledFace(
+ "base14:Times-BoldItalic",
+ { italic: false },
+ { ...NO_DOCUMENT, externalFonts: null },
+ ),
+ ).toBe("Times-Bold");
});
it("refuses an embedded family with no device fonts loaded", () => {
- expect(italicCapability("pdf:4242:Calibri", true, null).family).toBeNull();
+ expect(
+ restyledFace(
+ "pdf:4242:Calibri",
+ { italic: true },
+ { ...NO_DOCUMENT, externalFonts: null },
+ ),
+ ).toBeNull();
});
it("refuses a subset family whose installed face has no italic cut", () => {
expect(
- italicCapability("pdf:4242:Stencil", true, STENCIL).family,
+ restyledFace(
+ "pdf:4242:Stencil",
+ { italic: true },
+ { ...NO_DOCUMENT, externalFonts: STENCIL },
+ ),
).toBeNull();
});
it("uses the installed italic cut of the run's own family", () => {
- expect(italicCapability("pdf:4242:Calibri", true, CALIBRI)).toEqual({
- family: "Calibri Italic",
- source: "device",
- });
+ expect(
+ restyledFace(
+ "pdf:4242:Calibri",
+ { italic: true },
+ { ...NO_DOCUMENT, externalFonts: CALIBRI },
+ ),
+ ).toBe("Calibri Italic");
});
it("never substitutes a different typeface", () => {
// The whole point: Calibri does not become Helvetica just to look slanted.
- const cap = italicCapability("pdf:4242:Calibri", true, STENCIL);
- expect(cap.family).toBeNull();
- expect(cap.source).toBeNull();
+ expect(
+ restyledFace(
+ "pdf:4242:Calibri",
+ { italic: true },
+ { ...NO_DOCUMENT, externalFonts: STENCIL },
+ ),
+ ).toBeNull();
+ });
+
+ it("is read from the font list asked with, so a new list is asked afresh", () => {
+ const ask = (fonts: LocalFont[]) =>
+ restyledFace(
+ "pdf:4242:Calibri",
+ { italic: true },
+ { ...NO_DOCUMENT, externalFonts: fonts },
+ );
+ expect(ask(STENCIL)).toBeNull();
+ expect(ask(STENCIL)).toBeNull();
+ expect(ask(CALIBRI)).toBe("Calibri Italic");
+ expect(ask(CALIBRI)).toBe("Calibri Italic");
});
});
-describe("canToggleItalic", () => {
+describe("canRestyle to italic", () => {
it("is false for an empty selection", () => {
- expect(canToggleItalic([], CALIBRI)).toBe(false);
+ expect(
+ canRestyle(
+ [],
+ { italic: true },
+ { documentFamilies: [], externalFonts: CALIBRI },
+ ),
+ ).toBe(false);
});
it("needs EVERY run to be capable", () => {
expect(
- canToggleItalic(["base14:Helvetica", "base14:Times-Roman"], null),
+ canRestyle(
+ ["base14:Helvetica", "base14:Times-Roman"],
+ { italic: true },
+ { documentFamilies: [], externalFonts: null },
+ ),
).toBe(true);
expect(
- canToggleItalic(["base14:Helvetica", "pdf:1:Stencil"], STENCIL),
+ canRestyle(
+ ["base14:Helvetica", "pdf:1:Stencil"],
+ { italic: true },
+ { documentFamilies: [], externalFonts: STENCIL },
+ ),
).toBe(false);
});
});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/fontFaces.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/fontFaces.test.ts
new file mode 100644
index 0000000000..f845a3e9a1
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/fontFaces.test.ts
@@ -0,0 +1,345 @@
+// @vitest-environment node
+import { describe, expect, it } from "vitest";
+import {
+ familyKey,
+ parseFaceName,
+} from "@editor/tools/pdfTextEditor/util/faceNames";
+import {
+ BUILT_IN_FAMILIES,
+ canRestyle,
+ documentFamilies,
+ externalFamilies,
+ faceKeepingStyle,
+ restyledFace,
+ type FaceSources,
+} from "@editor/tools/pdfTextEditor/util/fontFaces";
+import { deriveToolbarState } from "@editor/tools/pdfTextEditor/util/toolbarState";
+import type { LocalFont } from "@editor/tools/pdfTextEditor/util/localFonts";
+import type {
+ PageSnapshot,
+ SelectionState,
+} from "@editor/tools/pdfTextEditor/types";
+
+// Names as pdffonts lists them in the test fixtures and the regression corpus.
+const REAL_NAMES: Array<[string, string, number, boolean]> = [
+ ["AAAAAA+LiberationSans", "LiberationSans", 400, false],
+ ["BAAAAA+LiberationSans-Bold", "LiberationSans", 700, false],
+ ["CAAAAA+LiberationSans-Italic", "LiberationSans", 400, true],
+ ["DAAAAA+LiberationSans-BoldItalic", "LiberationSans", 700, true],
+ ["Arial,Bold", "Arial", 700, false],
+ ["Arial,BoldItalic", "Arial", 700, true],
+ ["EAAAAA+Arial-BoldMT", "Arial", 700, false],
+ ["XOAUWI+ArialMT", "Arial", 400, false],
+ ["Helvetica-Oblique", "Helvetica", 400, true],
+ ["Helvetica-BoldOblique", "Helvetica", 700, true],
+ ["Times-BoldItalic", "Times", 700, true],
+ ["Times-Roman", "Times", 400, false],
+ ["YNEWNN+TimesNewRomanPSMT", "TimesNewRoman", 400, false],
+ ["ESSOFH+Times-New-Roman,", "Times New Roman", 400, false],
+ ["CLJQKD+Trebuchet-MS-Bold", "Trebuchet MS", 700, false],
+ ["JUEZMN+TrebuchetMS-Bold", "TrebuchetMS", 700, false],
+ ["DWPUQU+Georgia-Bold-Italic", "Georgia", 700, true],
+ ["XRKQNH+Palatino-Roman", "Palatino", 400, false],
+ ["QMJUWP+NimbusRomNo9L-Medi", "NimbusRomNo9L", 700, false],
+ ["NimbusRomNo9L-MediItal", "NimbusRomNo9L", 700, true],
+ ["NimbusSanL-Bold", "NimbusSanL", 700, false],
+ ["NimbusSanL-ReguItal", "NimbusSanL", 400, true],
+ ["URWBookmanL-Ligh", "URWBookmanL", 300, false],
+ ["URWBookmanL-DemiBoldItal", "URWBookmanL", 600, true],
+ ["Roboto-Medium", "Roboto", 500, false],
+ ["Franklin Gothic Medium", "Franklin Gothic", 500, false],
+ ["XICEAB+NimbusRomNo9L-ReguItal", "NimbusRomNo9L", 400, true],
+ ["ONWLAQ+LMRoman12-Bold", "LMRoman12", 700, false],
+ ["AAAAAA+HiraginoSans-W4", "HiraginoSans", 400, false],
+ ["KVGQPY+StandardSymL-Slant_167", "StandardSymL", 400, true],
+ [
+ "AAAAAA+.SFNS-Regular_wdth_opsz200000_GRAD_wght2580000",
+ ".SFNS",
+ 600,
+ false,
+ ],
+ ["JAAAAA+.SFNS-Bold", ".SFNS", 700, false],
+ ["Calibri Bold", "Calibri", 700, false],
+ ["Segoe UI Semibold", "Segoe UI", 600, false],
+ ["Segoe UI Semi Bold Italic", "Segoe UI", 600, true],
+ ["MinionPro-BoldIt", "MinionPro", 700, true],
+ ["HelveticaNeueBold", "HelveticaNeue", 700, false],
+ ["Calibri Light", "Calibri", 300, false],
+ ["Arial Black", "Arial", 900, false],
+];
+
+describe("parseFaceName", () => {
+ it.each(REAL_NAMES)(
+ "reads %s as %s at %i",
+ (name, family, weight, italic) => {
+ const parsed = parseFaceName(name);
+ expect(parsed.family).toBe(family);
+ expect(parsed.weight).toBe(weight);
+ expect(parsed.italic).toBe(italic);
+ },
+ );
+
+ it("keys one family the same whatever its separators", () => {
+ expect(familyKey(parseFaceName("Trebuchet-MS-Bold").family)).toBe(
+ familyKey(parseFaceName("TrebuchetMS").family),
+ );
+ expect(familyKey(parseFaceName("Times-New-Roman,").family)).toBe(
+ familyKey(parseFaceName("TimesNewRomanPSMT").family),
+ );
+ expect(familyKey(parseFaceName("Courier-New").family)).toBe(
+ familyKey(parseFaceName("CourierNewPSMT").family),
+ );
+ });
+
+ it("leaves a name with no style words whole", () => {
+ expect(parseFaceName("Helvetica Neue").family).toBe("Helvetica Neue");
+ expect(parseFaceName("Book Antiqua").family).toBe("Book Antiqua");
+ expect(parseFaceName("CairoFont-8-0").family).toBe("CairoFont 8 0");
+ });
+});
+
+describe("family grouping", () => {
+ it("lists each built-in family once with all four faces", () => {
+ expect(BUILT_IN_FAMILIES.map((entry) => entry.label)).toEqual([
+ "Helvetica",
+ "Times",
+ "Courier",
+ ]);
+ expect(BUILT_IN_FAMILIES.map((entry) => entry.value)).toEqual([
+ "Helvetica",
+ "Times-Roman",
+ "Courier",
+ ]);
+ for (const entry of BUILT_IN_FAMILIES) expect(entry.faces).toHaveLength(4);
+ });
+
+ it("groups document faces of one family whatever their name spelling", () => {
+ const families = documentFamilies([
+ "pdf:1:Arial",
+ "pdf:2:Arial,Bold",
+ "pdf:3:Arial-BoldMT",
+ "pdf:4:Arial,Italic",
+ "pdf:5:Georgia-Bold",
+ ]);
+ expect(families.map((entry) => entry.label)).toEqual(["Arial", "Georgia"]);
+ expect(families[0].faces.map((f) => [f.value, f.weight, f.italic])).toEqual(
+ [
+ ["pdf:1:Arial", 400, false],
+ ["pdf:2:Arial,Bold", 700, false],
+ ["pdf:4:Arial,Italic", 400, true],
+ ],
+ );
+ });
+
+ it("lists a bold-only family under its family name, standing for it by the bold face", () => {
+ const [georgia] = documentFamilies(["pdf:5:Georgia-Bold"]);
+ expect(georgia.label).toBe("Georgia");
+ expect(georgia.value).toBe("pdf:5:Georgia-Bold");
+ });
+
+ it("names an external face so the face lookup finds it again", () => {
+ const fonts: LocalFont[] = [
+ face("Segoe UI", "Regular"),
+ face("Segoe UI", "Semibold"),
+ face("Segoe UI", "Bold"),
+ face("Segoe UI", "Bold Italic"),
+ face("Acme Display Bold", "Regular"),
+ ];
+ const families = externalFamilies(fonts);
+ expect(families.map((entry) => entry.label)).toEqual([
+ "Acme Display",
+ "Segoe UI",
+ ]);
+ expect(families[0].faces).toEqual([
+ { value: "Acme Display Bold", weight: 700, italic: false },
+ ]);
+ expect(families[1].faces.map((f) => f.value)).toEqual([
+ "Segoe UI",
+ "Segoe UI Semibold",
+ "Segoe UI Bold",
+ "Segoe UI Bold Italic",
+ ]);
+ });
+});
+
+function face(family: string, style: string): LocalFont {
+ return {
+ family,
+ style,
+ fullName: style === "Regular" ? family : `${family} ${style}`,
+ postscriptName: `${family.replace(/ /g, "")}-${style.replace(/ /g, "")}`,
+ };
+}
+
+const NO_SOURCES: FaceSources = { documentFamilies: [], externalFonts: null };
+
+describe("restyledFace", () => {
+ const liberation = documentFamilies([
+ "pdf:1:LiberationSans",
+ "pdf:2:LiberationSans-Bold",
+ "pdf:3:LiberationSans-Italic",
+ ]);
+ const sources: FaceSources = {
+ documentFamilies: liberation,
+ externalFonts: null,
+ };
+
+ it("moves a document run to the document's own bold face", () => {
+ expect(restyledFace("pdf:1:LiberationSans", { bold: true }, sources)).toBe(
+ "pdf:2:LiberationSans-Bold",
+ );
+ expect(
+ restyledFace("pdf:2:LiberationSans-Bold", { bold: false }, sources),
+ ).toBe("pdf:1:LiberationSans");
+ });
+
+ it("has nothing for a style the family lacks, and nothing to do for one it is in", () => {
+ expect(
+ restyledFace("pdf:3:LiberationSans-Italic", { bold: true }, sources),
+ ).toBeNull();
+ expect(
+ restyledFace("pdf:2:LiberationSans-Bold", { bold: true }, sources),
+ ).toBeUndefined();
+ });
+
+ it("flips a built-in face in place", () => {
+ expect(
+ restyledFace("base14:Times-Italic", { bold: true }, NO_SOURCES),
+ ).toBe("Times-BoldItalic");
+ });
+
+ it("never synthesises bold for a family with no bold face", () => {
+ expect(
+ restyledFace("pdf:9:Garamond", { bold: true }, NO_SOURCES),
+ ).toBeNull();
+ expect(canRestyle(["pdf:9:Garamond"], { bold: true }, NO_SOURCES)).toBe(
+ false,
+ );
+ });
+
+ it("reaches a weight beyond regular and bold", () => {
+ const sfns = documentFamilies([
+ "pdf:1:.SFNS-Regular",
+ "pdf:2:.SFNS-Regular_wdth_opsz200000_GRAD_wght2580000",
+ "pdf:3:.SFNS-Bold",
+ ]);
+ expect(
+ restyledFace(
+ "pdf:1:.SFNS-Regular",
+ { weight: 600 },
+ { documentFamilies: sfns, externalFonts: null },
+ ),
+ ).toBe("pdf:2:.SFNS-Regular_wdth_opsz200000_GRAD_wght2580000");
+ });
+
+ it("keeps a run's weight and slant when its family is picked", () => {
+ const [helvetica] = BUILT_IN_FAMILIES;
+ expect(faceKeepingStyle(helvetica, { weight: 700, italic: true })).toBe(
+ "Helvetica-BoldOblique",
+ );
+ const [georgia] = documentFamilies(["pdf:5:Georgia-Bold"]);
+ expect(faceKeepingStyle(georgia, { weight: 400, italic: false })).toBe(
+ "pdf:5:Georgia-Bold",
+ );
+ });
+});
+
+function run(id: string, fontId: string) {
+ return {
+ id,
+ pageIndex: 0,
+ bounds: { x: 0, y: 0, width: 10, height: 10 },
+ matrix: { a: 1, b: 0, c: 0, d: 1, e: 0, f: 0 },
+ text: "x",
+ fontId,
+ fontSize: 12,
+ fill: { r: 0, g: 0, b: 0, a: 255 },
+ fontSubset: false,
+ };
+}
+
+function toolbarFor(runs: ReturnType<typeof run>[], selected: string[]) {
+ const pages = [{ pageIndex: 0, runs, images: [] } as unknown as PageSnapshot];
+ return deriveToolbarState(pages, {
+ runIds: selected,
+ imageIds: [],
+ } as unknown as SelectionState);
+}
+
+describe("toolbar bold state", () => {
+ it("offers bold for a document font whose bold face is elsewhere in the document", () => {
+ const state = toolbarFor(
+ [run("a", "pdf:1:LiberationSans"), run("b", "pdf:2:LiberationSans-Bold")],
+ ["a"],
+ );
+ expect(state.bold).toBe(false);
+ expect(state.canBold).toBe(true);
+ });
+
+ it("disables bold for a family with no bold face", () => {
+ const state = toolbarFor([run("a", "pdf:1:Garamond")], ["a"]);
+ expect(state.canBold).toBe(false);
+ });
+
+ it("shows a bold-only family as bold and locked", () => {
+ const state = toolbarFor([run("a", "pdf:1:Georgia-Bold")], ["a"]);
+ expect(state.bold).toBe(true);
+ expect(state.canBold).toBe(false);
+ });
+
+ it("marks a half-bold selection mixed and lets the toggle make it all bold", () => {
+ const state = toolbarFor(
+ [run("a", "base14:Helvetica"), run("b", "base14:Helvetica-Bold")],
+ ["a", "b"],
+ );
+ expect(state.mixed.bold).toBe(true);
+ expect(state.bold).toBe(false);
+ expect(state.canBold).toBe(true);
+ });
+
+ it("says Bold is off for want of a bold italic face, not of a bold one", () => {
+ const state = toolbarFor(
+ [
+ run("a", "pdf:1:Georgia-Italic"),
+ run("b", "pdf:2:Georgia-Bold"),
+ run("c", "pdf:3:Georgia"),
+ ],
+ ["a"],
+ );
+ expect(state.canBold).toBe(false);
+ expect(state.boldNeedsBoldItalic).toBe(true);
+ expect(
+ toolbarFor([run("a", "pdf:1:Garamond-Italic")], ["a"])
+ .boldNeedsBoldItalic,
+ ).toBe(false);
+ });
+
+ it("says Italic is off for want of a bold italic face, not of an italic one", () => {
+ const state = toolbarFor(
+ [run("a", "pdf:1:Georgia-Bold"), run("b", "pdf:2:Georgia-Italic")],
+ ["a"],
+ );
+ expect(state.canItalic).toBe(false);
+ expect(state.italicNeedsBoldItalic).toBe(true);
+ expect(
+ toolbarFor([run("a", "pdf:1:Garamond-Bold")], ["a"])
+ .italicNeedsBoldItalic,
+ ).toBe(false);
+ });
+
+ it("lists the weights of a family with more than regular and bold", () => {
+ const sfns = toolbarFor(
+ [
+ run("a", "pdf:1:.SFNS-Regular"),
+ run("b", "pdf:2:.SFNS-Regular_wdth_opsz200000_GRAD_wght2580000"),
+ run("c", "pdf:3:.SFNS-Bold"),
+ ],
+ ["a"],
+ );
+ expect(sfns.weights).toEqual([400, 600, 700]);
+ expect(sfns.weight).toBe(400);
+ expect(toolbarFor([run("a", "base14:Helvetica")], ["a"]).weights).toEqual(
+ [],
+ );
+ });
+});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/fontFacesFixtures.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/fontFacesFixtures.test.ts
new file mode 100644
index 0000000000..193ae7042b
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/fontFacesFixtures.test.ts
@@ -0,0 +1,81 @@
+// @vitest-environment node
+import { readdir, readFile } from "node:fs/promises";
+import path from "node:path";
+import { expect, test } from "vitest";
+import { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
+import { PdfiumTextReader } from "@editor/tools/pdfTextEditor/pdfium/PdfiumTextReader";
+import { parseFaceName } from "@editor/tools/pdfTextEditor/util/faceNames";
+import { documentFontIds } from "@editor/tools/pdfTextEditor/util/documentFontStyle";
+import {
+ documentFamilies,
+ type FontFamilyEntry,
+} from "@editor/tools/pdfTextEditor/util/fontFaces";
+import {
+ FIXTURES,
+ servePdfiumWasm,
+} from "@editor/tools/pdfTextEditor/__tests__/editorStores";
+
+servePdfiumWasm();
+
+/** The document fonts on a fixture's first page as families, or null when it does not open. */
+async function familiesOf(file: string): Promise<FontFamilyEntry[] | null> {
+ let doc: EditorDocument;
+ try {
+ doc = await EditorDocument.open(
+ new Uint8Array(await readFile(path.join(FIXTURES, file))),
+ );
+ } catch {
+ return null;
+ }
+ try {
+ PdfiumTextReader.populate(doc, doc.page(0));
+ return documentFamilies([
+ ...doc.page(0).runs.map((run) => run.fontId),
+ ...documentFontIds(),
+ ]);
+ } finally {
+ doc.dispose();
+ }
+}
+
+function faces(entry: FontFamilyEntry | undefined) {
+ return entry?.faces.map((f) => `${f.weight}${f.italic ? "i" : ""}`);
+}
+
+test("every fixture lists each family once, with no style left in its name", async () => {
+ const files = (await readdir(FIXTURES)).filter((f) => f.endsWith(".pdf"));
+ let opened = 0;
+ for (const file of files) {
+ const families = await familiesOf(file);
+ if (!families) continue;
+ opened++;
+ const keys = families.map((entry) => entry.key);
+ expect(new Set(keys).size, file).toBe(keys.length);
+ for (const entry of families)
+ expect(parseFaceName(entry.label).family, file).toBe(entry.label);
+ }
+ expect(opened).toBeGreaterThan(50);
+}, 300_000);
+
+test("the four Liberation Sans subsets of one paragraph are one family", async () => {
+ const families = (await familiesOf("mixed-style-sample.pdf"))!;
+ const liberation = families.find((e) => e.key === "liberationsans");
+ expect(faces(liberation)).toEqual(["400", "700", "400i", "700i"]);
+});
+
+test("base-14 fonts the PDF does not embed are known by the name it gives them", async () => {
+ const families = (await familiesOf("table-sample.pdf"))!;
+ expect(families.map((e) => e.label)).toEqual(["Helvetica"]);
+ expect(faces(families[0])).toEqual(["400", "700"]);
+});
+
+test("cairo's Georgia faces group and its bold-only Trebuchet stands for itself", async () => {
+ const families = (await familiesOf("cairo-styles.pdf"))!;
+ expect(faces(families.find((e) => e.key === "georgia"))).toEqual([
+ "400",
+ "700",
+ "400i",
+ "700i",
+ ]);
+ expect(faces(families.find((e) => e.key === "trebuchetms"))).toEqual(["700"]);
+});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/formLiftFidelity.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/formLiftFidelity.test.ts
new file mode 100644
index 0000000000..75b25884d3
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/formLiftFidelity.test.ts
@@ -0,0 +1,485 @@
+// @vitest-environment node
+import { readFile } from "node:fs/promises";
+import { createRequire } from "node:module";
+import { afterEach, beforeAll, describe, expect, test, vi } from "vitest";
+import { DeleteShapeCommand } from "@editor/tools/pdfTextEditor/commands/DeleteShapeCommand";
+import { MergeRunsCommand } from "@editor/tools/pdfTextEditor/commands/MergeRunsCommand";
+import { SetColourCommand } from "@editor/tools/pdfTextEditor/commands/SetColourCommand";
+import { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
+import { PdfiumTextReader } from "@editor/tools/pdfTextEditor/pdfium/PdfiumTextReader";
+import {
+ HistoryStack,
+ HistoryStepError,
+} from "@editor/tools/pdfTextEditor/store/HistoryStack";
+import { exportToBlob } from "@editor/tools/pdfTextEditor/util/exportPdf";
+import { toLatin1 } from "@editor/tools/pdfTextEditor/pdfdoc/bytes";
+import {
+ buildClassicPdf,
+ streamBody,
+} from "@editor/tools/pdfTextEditor/__tests__/pdfFixtures";
+import {
+ changedPixels,
+ rasterFirstPage,
+} from "@editor/tools/pdfTextEditor/__tests__/pageRaster";
+
+const SIZE = 300;
+const RED = { r: 255, g: 0, b: 0, a: 255 };
+const FONT = "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>";
+const TEXT = "0 0 0 rg BT /F1 14 Tf 20 50 Td (Trustworthy document) Tj ET";
+
+const opened: EditorDocument[] = [];
+
+beforeAll(async () => {
+ const wasm = await readFile(
+ createRequire(import.meta.url).resolve("@embedpdf/pdfium/pdfium.wasm"),
+ );
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(
+ async () =>
+ new Response(wasm, { headers: { "Content-Type": "application/wasm" } }),
+ ),
+ );
+});
+
+afterEach(() => {
+ for (const doc of opened.splice(0)) doc.dispose();
+});
+
+interface FixtureParts {
+ /** Page content; the form is `/Fm`. */
+ page: string;
+ /** Extra entries for the page's /Resources. */
+ pageResources?: string;
+ /** The form's content, drawn after a grey panel. */
+ form?: string;
+ /** Extra entries for the form's /Resources. */
+ formResources?: string;
+ /** Objects 8 and up, referenced by the parts above. */
+ extra?: string[];
+}
+
+function fixture(parts: FixtureParts): Uint8Array {
+ return buildClassicPdf(
+ [
+ { num: 1, body: "<< /Type /Catalog /Pages 2 0 R >>" },
+ { num: 2, body: "<< /Type /Pages /Kids [3 0 R] /Count 1 >>" },
+ {
+ num: 3,
+ body: `<< /Type /Page /Parent 2 0 R /MediaBox [0 0 ${SIZE} ${SIZE}] /Contents 4 0 R /Resources << /XObject << /Fm 5 0 R >> ${parts.pageResources ?? ""} >> >>`,
+ },
+ {
+ num: 4,
+ body: streamBody("", `1 0 0 rg 0 0 300 300 re f ${parts.page}`),
+ },
+ {
+ num: 5,
+ body: streamBody(
+ `/Type /XObject /Subtype /Form /BBox [0 0 200 100] /Resources << /Font << /F1 6 0 R >> ${parts.formResources ?? ""} >>`,
+ `0.8 0.8 0.8 rg 0 0 200 100 re f ${parts.form ?? ""} ${TEXT}`,
+ ),
+ },
+ { num: 6, body: FONT },
+ ...(parts.extra ?? []).map((body, i) => ({ num: 8 + i, body })),
+ ],
+ 1,
+ );
+}
+
+async function open(bytes: Uint8Array): Promise<EditorDocument> {
+ const doc = await EditorDocument.open(bytes);
+ opened.push(doc);
+ PdfiumTextReader.populate(doc, doc.page(0));
+ return doc;
+}
+
+const raster = (doc: EditorDocument) => rasterFirstPage(doc, SIZE, SIZE);
+
+async function saved(doc: EditorDocument): Promise<Uint8Array> {
+ return new Uint8Array(await (await exportToBlob(doc)).arrayBuffer());
+}
+
+function recolour(doc: EditorDocument): SetColourCommand {
+ const run = doc
+ .page(0)
+ .runs.find((r) => r.text.startsWith("Trustworthy document"))!;
+ return new SetColourCommand({ pageIndex: 0, runId: run.id, nextFill: RED });
+}
+
+async function expectLiftedFaithfully(bytes: Uint8Array): Promise<void> {
+ const doc = await open(bytes);
+ const before = raster(doc);
+ const history = new HistoryStack();
+ history.execute(recolour(doc), doc);
+ history.undo(doc);
+ expect(changedPixels(before, raster(doc))).toBe(0);
+ const reopened = await open(await saved(doc));
+ expect(changedPixels(before, raster(reopened))).toBe(0);
+}
+
+async function expectRefused(bytes: Uint8Array): Promise<void> {
+ const doc = await open(bytes);
+ const before = raster(doc);
+ const runsBefore = doc.page(0).runs.map((r) => r.snapshot());
+ const history = new HistoryStack();
+ let refusal: unknown = null;
+ try {
+ history.execute(recolour(doc), doc);
+ } catch (err) {
+ refusal = err;
+ }
+ expect(refusal).toBeInstanceOf(HistoryStepError);
+ expect((refusal as HistoryStepError).documentIntact).toBe(true);
+ expect(history.canUndo).toBe(false);
+ expect(doc.page(0).runs.map((r) => r.snapshot())).toEqual(runsBefore);
+ expect(changedPixels(before, raster(doc))).toBe(0);
+ const reopened = await open(await saved(doc));
+ expect(changedPixels(before, raster(reopened))).toBe(0);
+}
+
+const MULTIPLY = "<< /Type /ExtGState /BM /Multiply >>";
+const HALF = "<< /Type /ExtGState /ca 0.5 /CA 0.5 >>";
+
+describe("lifting form contents onto the page", () => {
+ test("is refused when the form is drawn through a clip that hides part of it", async () => {
+ await expectRefused(
+ fixture({ page: "q 100 100 75 100 re W n 1 0 0 1 100 100 cm /Fm Do Q" }),
+ );
+ });
+
+ test("keeps the drawing when the clip hides nothing on the page", async () => {
+ await expectLiftedFaithfully(
+ fixture({ page: "q 0 0 300 300 re W n 1 0 0 1 100 100 cm /Fm Do Q" }),
+ );
+ });
+
+ test("keeps the drawing when the clip only cuts what is off the page", async () => {
+ await expectLiftedFaithfully(
+ fixture({ page: "q 0 0 300 300 re W n 1 0 0 1 200 150 cm /Fm Do Q" }),
+ );
+ });
+
+ test("is refused when the form blends with a graphics state of its own", async () => {
+ await expectRefused(
+ fixture({
+ page: "q 1 0 0 1 100 100 cm /Fm Do Q",
+ formResources: "/ExtGState << /Blend 8 0 R >>",
+ form: "/Blend gs 0 0 1 rg 0 0 200 40 re f",
+ extra: [MULTIPLY],
+ }),
+ );
+ });
+
+ test("is refused when the form sets its own opacity", async () => {
+ await expectRefused(
+ fixture({
+ page: "q 1 0 0 1 100 100 cm /Fm Do Q",
+ formResources: "/ExtGState << /Half 8 0 R >>",
+ form: "/Half gs 0 0 1 rg 0 0 200 40 re f",
+ extra: [HALF],
+ }),
+ );
+ });
+
+ test("is refused when the form's graphics state name means something else on the page", async () => {
+ await expectRefused(
+ fixture({
+ page: "q /G0 gs 0 1 0 rg 0 200 300 50 re f Q q 1 0 0 1 100 100 cm /Fm Do Q",
+ pageResources: "/ExtGState << /G0 8 0 R >>",
+ formResources: "/ExtGState << /G0 9 0 R >>",
+ form: "/G0 gs 0 0 1 rg 0 0 200 40 re f",
+ extra: [HALF, MULTIPLY],
+ }),
+ );
+ });
+
+ test("keeps the drawing when the page binds the form's graphics state names to the same objects", async () => {
+ await expectLiftedFaithfully(
+ fixture({
+ page: "q /G0 gs 0 1 0 rg 0 200 300 50 re f Q q 1 0 0 1 100 100 cm /Fm Do Q",
+ pageResources: "/ExtGState << /G0 8 0 R >>",
+ formResources: "/ExtGState << /G0 8 0 R >>",
+ form: "/G0 gs 0 0 1 rg 0 0 200 40 re f",
+ extra: [HALF],
+ }),
+ );
+ });
+
+ test("is refused when the form fills with a pattern of its own", async () => {
+ await expectRefused(
+ fixture({
+ page: "q 1 0 0 1 100 100 cm /Fm Do Q",
+ formResources: "/Pattern << /P1 8 0 R >>",
+ form: "/Pattern cs /P1 scn 0 0 200 40 re f",
+ extra: [
+ "<< /PatternType 2 /Shading << /ShadingType 2 /ColorSpace /DeviceRGB /Coords [0 0 200 0] /Function << /FunctionType 2 /Domain [0 1] /C0 [0 1 0] /C1 [1 0 1] /N 1 >> >> >>",
+ ],
+ }),
+ );
+ });
+
+ test("is refused when the form is optional content", async () => {
+ const bytes = buildClassicPdf(
+ [
+ {
+ num: 1,
+ body: "<< /Type /Catalog /Pages 2 0 R /OCProperties << /OCGs [8 0 R] /D << /OFF [8 0 R] >> >> >>",
+ },
+ { num: 2, body: "<< /Type /Pages /Kids [3 0 R] /Count 1 >>" },
+ {
+ num: 3,
+ body: "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 300] /Contents 4 0 R /Resources << /XObject << /Fm 5 0 R /Shown 7 0 R >> /Properties << /oc1 8 0 R >> >> >>",
+ },
+ {
+ num: 4,
+ body: streamBody(
+ "",
+ "q 1 0 0 1 50 50 cm /Shown Do Q /OC /oc1 BDC q 1 0 0 1 50 150 cm /Fm Do Q EMC",
+ ),
+ },
+ {
+ num: 5,
+ body: streamBody(
+ "/Type /XObject /Subtype /Form /BBox [0 0 200 100] /Resources << /Font << /F1 6 0 R >> >>",
+ "BT /F1 14 Tf 0 50 Td (Hidden words) Tj ET",
+ ),
+ },
+ { num: 6, body: FONT },
+ {
+ num: 7,
+ body: streamBody(
+ "/Type /XObject /Subtype /Form /BBox [0 0 200 100] /Resources << /Font << /F1 6 0 R >> >>",
+ TEXT,
+ ),
+ },
+ { num: 8, body: "<< /Type /OCG /Name (Hidden) >>" },
+ ],
+ 1,
+ );
+ const doc = await open(bytes);
+ const before = raster(doc);
+ const hidden = doc.page(0).runs.find((r) => r.text === "Hidden words");
+ const history = new HistoryStack();
+ expect(() =>
+ history.execute(
+ new SetColourCommand({
+ pageIndex: 0,
+ runId: hidden!.id,
+ nextFill: RED,
+ }),
+ doc,
+ ),
+ ).toThrow(HistoryStepError);
+ expect(history.canUndo).toBe(false);
+ const reopened = await open(await saved(doc));
+ expect(changedPixels(before, raster(reopened))).toBe(0);
+ });
+
+ test("refuses a shape delete in a group drawn at a page opacity its own graphics state would replace", async () => {
+ const doc = await open(
+ buildClassicPdf(
+ [
+ { num: 1, body: "<< /Type /Catalog /Pages 2 0 R >>" },
+ { num: 2, body: "<< /Type /Pages /Kids [3 0 R] /Count 1 >>" },
+ {
+ num: 3,
+ body: `<< /Type /Page /Parent 2 0 R /MediaBox [0 0 ${SIZE} ${SIZE}] /Contents 4 0 R /Resources << /XObject << /Fm 5 0 R >> /ExtGState << /Faint 7 0 R >> >> >>`,
+ },
+ {
+ num: 4,
+ body: streamBody(
+ "",
+ "1 0 0 rg 0 0 300 300 re f q /Faint gs 1 0 0 1 50 100 cm /Fm Do Q",
+ ),
+ },
+ {
+ num: 5,
+ body: streamBody(
+ "/Type /XObject /Subtype /Form /BBox [0 0 200 100] /Group << /S /Transparency /I true >> /Resources << /ExtGState << /Half 6 0 R >> >>",
+ "/Half gs 0 0 1 rg 0 0 200 40 re f 0 1 0 rg 100 20 100 80 re f",
+ ),
+ },
+ { num: 6, body: HALF },
+ { num: 7, body: "<< /Type /ExtGState /ca 0.1 /CA 0.1 >>" },
+ ],
+ 1,
+ ),
+ );
+ const page = doc.page(0);
+ const before = raster(doc);
+ const shapesBefore = page.shapes.map((s) => s.id);
+ const target = page.shapes.find(
+ (s) => s.containerPtr && Math.abs(s.bounds.height - 40) < 1,
+ );
+ expect(target).toBeDefined();
+ const history = new HistoryStack();
+ let refusal: unknown = null;
+ try {
+ history.execute(
+ new DeleteShapeCommand({ pageIndex: 0, shapeId: target!.id }),
+ doc,
+ );
+ } catch (err) {
+ refusal = err;
+ }
+ expect(refusal).toBeInstanceOf(HistoryStepError);
+ expect((refusal as HistoryStepError).documentIntact).toBe(true);
+ expect(String((refusal as HistoryStepError).cause)).toContain(
+ "drawn as part of a group",
+ );
+ expect(history.canUndo).toBe(false);
+ expect(page.shapes.map((s) => s.id)).toEqual(shapesBefore);
+ expect(changedPixels(before, raster(doc))).toBe(0);
+ const reopened = await open(await saved(doc));
+ expect(changedPixels(before, raster(reopened))).toBe(0);
+ });
+
+ test("lifts nested forms and keeps their drawing", async () => {
+ const bytes = buildClassicPdf(
+ [
+ { num: 1, body: "<< /Type /Catalog /Pages 2 0 R >>" },
+ { num: 2, body: "<< /Type /Pages /Kids [3 0 R] /Count 1 >>" },
+ {
+ num: 3,
+ body: "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 300] /Contents 4 0 R /Resources << /XObject << /Outer 5 0 R >> >> >>",
+ },
+ { num: 4, body: streamBody("", "q 1 0 0 1 40 60 cm /Outer Do Q") },
+ {
+ num: 5,
+ body: streamBody(
+ "/Type /XObject /Subtype /Form /BBox [0 0 260 200] /Resources << /XObject << /Inner 7 0 R >> >>",
+ "0 0 1 rg 0 0 30 30 re f q 0.5 0 0 0.5 20 20 cm /Inner Do Q",
+ ),
+ },
+ { num: 6, body: FONT },
+ {
+ num: 7,
+ body: streamBody(
+ "/Type /XObject /Subtype /Form /BBox [0 0 400 200] /Resources << /Font << /F1 6 0 R >> >>",
+ `0.8 0.8 0.8 rg 0 0 400 100 re f ${TEXT}`,
+ ),
+ },
+ ],
+ 1,
+ );
+ await expectLiftedFaithfully(bytes);
+ });
+
+ test("is refused when a nested form is clipped inside its parent", async () => {
+ const bytes = buildClassicPdf(
+ [
+ { num: 1, body: "<< /Type /Catalog /Pages 2 0 R >>" },
+ { num: 2, body: "<< /Type /Pages /Kids [3 0 R] /Count 1 >>" },
+ {
+ num: 3,
+ body: "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 300] /Contents 4 0 R /Resources << /XObject << /Outer 5 0 R >> >> >>",
+ },
+ { num: 4, body: streamBody("", "q 1 0 0 1 40 60 cm /Outer Do Q") },
+ {
+ num: 5,
+ body: streamBody(
+ "/Type /XObject /Subtype /Form /BBox [0 0 260 200] /Resources << /XObject << /Inner 7 0 R >> >>",
+ "q 0 0 80 200 re W n /Inner Do Q",
+ ),
+ },
+ { num: 6, body: FONT },
+ {
+ num: 7,
+ body: streamBody(
+ "/Type /XObject /Subtype /Form /BBox [0 0 400 200] /Resources << /Font << /F1 6 0 R >> >>",
+ `0.8 0.8 0.8 rg 0 0 200 100 re f ${TEXT}`,
+ ),
+ },
+ ],
+ 1,
+ );
+ await expectRefused(bytes);
+ });
+
+ test("leaves the form's other uses drawing it whole", async () => {
+ const bytes = fixture({
+ page: "q 1 0 0 1 50 20 cm /Fm Do Q q 1 0 0 1 50 160 cm /Fm Do Q",
+ });
+ const doc = await open(bytes);
+ const before = raster(doc);
+ const runs = doc
+ .page(0)
+ .runs.filter((r) => r.text.startsWith("Trustworthy document"));
+ expect(runs).toHaveLength(2);
+ const lower = runs.reduce((a, b) => (a.bounds.y < b.bounds.y ? a : b));
+ const history = new HistoryStack();
+ history.execute(
+ new SetColourCommand({ pageIndex: 0, runId: lower.id, nextFill: RED }),
+ doc,
+ );
+ const out = await saved(doc);
+ expect(toLatin1(out)).toMatch(/\/Subtype\s*\/Form/);
+ const after = raster(await open(out));
+ let upperChanged = 0;
+ let lowerChanged = 0;
+ for (let y = 0; y < SIZE; y++) {
+ for (let x = 0; x < SIZE; x++) {
+ const i = (y * SIZE + x) * 4;
+ if (![0, 1, 2].some((c) => Math.abs(before[i + c] - after[i + c]) > 2))
+ continue;
+ if (y < SIZE / 2) upperChanged++;
+ else lowerChanged++;
+ }
+ }
+ expect(upperChanged).toBe(0);
+ expect(lowerChanged).toBeGreaterThan(0);
+ });
+
+ test("a merge that would lift one form it cannot keep lifts none", async () => {
+ const bytes = buildClassicPdf(
+ [
+ { num: 1, body: "<< /Type /Catalog /Pages 2 0 R >>" },
+ { num: 2, body: "<< /Type /Pages /Kids [3 0 R] /Count 1 >>" },
+ {
+ num: 3,
+ body: "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 300] /Contents 4 0 R /Resources << /XObject << /Free 5 0 R /Clipped 7 0 R >> >> >>",
+ },
+ {
+ num: 4,
+ body: streamBody(
+ "",
+ "q 1 0 0 1 20 200 cm /Free Do Q q 20 100 60 40 re W n 1 0 0 1 20 100 cm /Clipped Do Q",
+ ),
+ },
+ {
+ num: 5,
+ body: streamBody(
+ "/Type /XObject /Subtype /Form /BBox [0 0 200 40] /Resources << /Font << /F1 6 0 R >> >>",
+ "BT /F1 14 Tf 0 10 Td (Free words) Tj ET",
+ ),
+ },
+ { num: 6, body: FONT },
+ {
+ num: 7,
+ body: streamBody(
+ "/Type /XObject /Subtype /Form /BBox [0 0 200 40] /Resources << /Font << /F1 6 0 R >> >>",
+ "BT /F1 14 Tf 0 10 Td (Clipped words) Tj ET",
+ ),
+ },
+ ],
+ 1,
+ );
+ const doc = await open(bytes);
+ const free = doc.page(0).runs.find((r) => r.text.startsWith("Free words"))!;
+ const clipped = doc.page(0).runs.find((r) => r.text === "Clipped words")!;
+ const container = free.containerPtr;
+ const history = new HistoryStack();
+ expect(() =>
+ history.execute(
+ new MergeRunsCommand({
+ pageIndex: 0,
+ runIds: [free.id, clipped.id],
+ }),
+ doc,
+ ),
+ ).toThrow(HistoryStepError);
+ expect(container).not.toBe(0);
+ expect(free.containerPtr).toBe(container);
+ expect(history.canUndo).toBe(false);
+ });
+});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/formXObjectTypedText.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/formXObjectTypedText.test.ts
new file mode 100644
index 0000000000..31576a249e
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/formXObjectTypedText.test.ts
@@ -0,0 +1,113 @@
+// @vitest-environment node
+import { readFile } from "node:fs/promises";
+import { createRequire } from "node:module";
+import path from "node:path";
+import {
+ afterAll,
+ afterEach,
+ beforeAll,
+ describe,
+ expect,
+ test,
+ vi,
+} from "vitest";
+import { EditTextCommand } from "@editor/tools/pdfTextEditor/commands/EditTextCommand";
+import { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
+import { PdfiumTextReader } from "@editor/tools/pdfTextEditor/pdfium/PdfiumTextReader";
+
+const SAMPLE = path.join(
+ import.meta.dirname,
+ "../../../tests/test-fixtures/form-xobject-sample.pdf",
+);
+const SUBHEADING = "Subheading line below";
+const FPDF_PAGEOBJ_TEXT = 1;
+
+const opened: EditorDocument[] = [];
+
+beforeAll(async () => {
+ const wasmPath = createRequire(import.meta.url).resolve(
+ "@embedpdf/pdfium/pdfium.wasm",
+ );
+ const wasmBytes = await readFile(wasmPath);
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async () =>
+ Promise.resolve(
+ new Response(wasmBytes, {
+ headers: { "Content-Type": "application/wasm" },
+ }),
+ ),
+ ),
+ );
+});
+
+afterAll(() => {
+ vi.unstubAllGlobals();
+});
+
+afterEach(() => {
+ for (const doc of opened.splice(0)) doc.dispose();
+});
+
+async function open(): Promise<EditorDocument> {
+ const doc = await EditorDocument.open(new Uint8Array(await readFile(SAMPLE)));
+ opened.push(doc);
+ PdfiumTextReader.populate(doc, doc.page(0));
+ return doc;
+}
+
+function pageLevelText(doc: EditorDocument): string {
+ const m = doc.module;
+ const pagePtr = doc.page(0).pagePtr;
+ const buf = m.pdfium.wasmExports.malloc(1024);
+ const textPage = m.FPDFText_LoadPage(pagePtr);
+ let out = "";
+ try {
+ for (let i = 0; i < m.FPDFPage_CountObjects(pagePtr); i++) {
+ const obj = m.FPDFPage_GetObject(pagePtr, i);
+ if (m.FPDFPageObj_GetType(obj) !== FPDF_PAGEOBJ_TEXT) continue;
+ m.FPDFTextObj_GetText(obj, textPage, buf, 1024);
+ out += m.pdfium.UTF16ToString(buf);
+ }
+ } finally {
+ m.FPDFText_ClosePage(textPage);
+ m.pdfium.wasmExports.free(buf);
+ }
+ return out;
+}
+
+describe("text typed into a form XObject run", () => {
+ test("is removed from the page when it is deleted again", async () => {
+ const doc = await open();
+ const run = doc.page(0).runs.find((r) => r.text === SUBHEADING)!;
+ expect(run.containerPtr).not.toBe(0);
+ const edit = (nextText: string) =>
+ new EditTextCommand({ pageIndex: 0, runId: run.id, nextText }).apply(doc);
+
+ edit(`${SUBHEADING} Zq7`);
+ expect(pageLevelText(doc)).toContain("Zq7");
+
+ edit(SUBHEADING);
+ expect(run.text).toBe(SUBHEADING);
+ expect(pageLevelText(doc)).not.toContain("Zq7");
+ });
+
+ test("gives back its original box when an added line is undone", async () => {
+ const doc = await open();
+ const run = doc.page(0).runs.find((r) => r.text === SUBHEADING)!;
+ const before = { ...run.bounds };
+ const cmd = new EditTextCommand({
+ pageIndex: 0,
+ runId: run.id,
+ nextText: `${SUBHEADING}\nAdded line`,
+ });
+
+ cmd.apply(doc);
+ const live = doc.page(0).findRun(run.id)!;
+ expect(live.bounds.height).toBeGreaterThan(before.height);
+ cmd.revert(doc);
+
+ expect(live.text).toBe(SUBHEADING);
+ expect(live.bounds).toEqual(before);
+ });
+});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/ghostWhitespace.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/ghostWhitespace.test.ts
new file mode 100644
index 0000000000..2b73853c3f
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/ghostWhitespace.test.ts
@@ -0,0 +1,116 @@
+// @vitest-environment node
+import { describe, expect, it } from "vitest";
+import {
+ applyPartialEditPlan,
+ planPartialEdit,
+} from "@editor/tools/pdfTextEditor/commands/partialEdit";
+import type { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
+import type { Page } from "@editor/tools/pdfTextEditor/model/Page";
+import { TextRun } from "@editor/tools/pdfTextEditor/model/TextRun";
+import { uniformTags } from "@editor/tools/pdfTextEditor/model/TextTags";
+
+const FONT_SIZE = 12;
+// measureWhitespaceAdvancePt's no-DOM estimate for one space at FONT_SIZE.
+const SPACE_PT = FONT_SIZE * 0.27;
+
+/**
+ * One text object per letter, the way Chrome writes PDFs. A space between two
+ * objects belongs to no object: it is a "ghost" in the run's text.
+ */
+function perLetterRun(text: string): TextRun {
+ const run = new TextRun({
+ id: "p0-t0",
+ pageIndex: 0,
+ bounds: { x: 0, y: 0, width: text.length * 10, height: 14 },
+ matrix: { a: 1, b: 0, c: 0, d: 1, e: 0, f: 800 },
+ text,
+ fontId: "pdf:1:Serif",
+ fontSize: FONT_SIZE,
+ fill: { r: 0, g: 0, b: 0, a: 255 },
+ fontSubset: true,
+ pdfiumObjPtr: 0,
+ });
+ for (let i = 0; i < text.length; i++) {
+ if (/\s/.test(text[i])) continue;
+ run.mergedFromPtrs.push(100 + i);
+ run.mergedFromTexts.push(text[i]);
+ run.mergedFromBounds.push({ x: i * 10, right: i * 10 + 8 });
+ run.mergedFromCharStarts.push(i);
+ }
+ return run;
+}
+
+function fakeDocAndPage(objects: number[]) {
+ const x = new Map<number, number>();
+ const module = {
+ pdfium: {
+ wasmExports: { malloc: () => 16, free: () => {} },
+ getValue: () => 0,
+ },
+ FPDFPage_CountObjects: () => objects.length,
+ FPDFPage_GetObject: (_page: number, i: number) => objects[i] ?? 0,
+ FPDFPage_RemoveObject: () => true,
+ FPDFPageObj_Transform: (
+ ptr: number,
+ _a: number,
+ _b: number,
+ _c: number,
+ _d: number,
+ e: number,
+ ) => {
+ x.set(ptr, (x.get(ptr) ?? 0) + e);
+ },
+ };
+ const doc = { module, docPtr: 1, loadedPages: () => [] };
+ const page = { pagePtr: 2, markNeedsGenerate: () => {} };
+ return {
+ doc: doc as unknown as EditorDocument,
+ page: page as unknown as Page,
+ x,
+ };
+}
+
+describe("deleting a space between two text objects", () => {
+ it("records the removed gap before the following object", () => {
+ const run = perLetterRun("Audit Desk");
+ const plan = planPartialEdit(run, "Audit Desk", "AuditDesk");
+ expect(plan?.ghostGaps).toEqual([{ beforeSubRunIdx: 5, removed: 1 }]);
+ });
+
+ it("shifts every following object left by the space", () => {
+ const run = perLetterRun("Audit Desk");
+ const plan = planPartialEdit(run, "Audit Desk", "AuditDesk")!;
+ const { doc, page, x } = fakeDocAndPage(run.mergedFromPtrs);
+ const result = applyPartialEditPlan(doc, page, run, plan, uniformTags([]));
+ for (const ptr of run.mergedFromPtrs.slice(0, 5))
+ expect(x.get(ptr) ?? 0).toBe(0);
+ for (const ptr of run.mergedFromPtrs.slice(5))
+ expect(x.get(ptr)).toBeCloseTo(-SPACE_PT);
+ expect(result.newMergedFromBounds[5].x).toBeCloseTo(60 - SPACE_PT);
+ });
+
+ it("never closes more than the visible gap", () => {
+ const run = perLetterRun("Audit Desk");
+ // Objects nearly touching: the gap is narrower than a space.
+ run.mergedFromBounds[5] = { x: 9, right: 17 };
+ run.mergedFromBounds[4] = { x: 0, right: 8 };
+ const plan = planPartialEdit(run, "Audit Desk", "AuditDesk")!;
+ const { doc, page, x } = fakeDocAndPage(run.mergedFromPtrs);
+ applyPartialEditPlan(doc, page, run, plan, uniformTags([]));
+ expect(x.get(run.mergedFromPtrs[5])).toBeCloseTo(-1);
+ });
+
+ it("ignores a space carried inside a text object", () => {
+ const run = perLetterRun("Audit Desk");
+ // "t " as one object: deleting its space is a modify of that object.
+ run.mergedFromTexts[4] = "t ";
+ const plan = planPartialEdit(run, "Audit Desk", "AuditDesk");
+ expect(plan?.ghostGaps).toEqual([]);
+ });
+
+ it("leaves the gap to the deleted object's advance when the word before it goes too", () => {
+ const run = perLetterRun("Audit Desk");
+ const plan = planPartialEdit(run, "Audit Desk", "AudiDesk");
+ expect(plan?.ghostGaps).toEqual([]);
+ });
+});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/growEdge.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/growEdge.test.ts
new file mode 100644
index 0000000000..257930ef96
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/growEdge.test.ts
@@ -0,0 +1,161 @@
+// @vitest-environment node
+import { readFile } from "node:fs/promises";
+import { createRequire } from "node:module";
+import path from "node:path";
+import { afterAll, afterEach, beforeAll, expect, test, vi } from "vitest";
+import { EditTextCommand } from "@editor/tools/pdfTextEditor/commands/EditTextCommand";
+import { ReflowWrapCommand } from "@editor/tools/pdfTextEditor/commands/ReflowWrapCommand";
+import { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
+import type { Page } from "@editor/tools/pdfTextEditor/model/Page";
+import { PdfiumTextReader } from "@editor/tools/pdfTextEditor/pdfium/PdfiumTextReader";
+import type { TextRunSnapshot } from "@editor/tools/pdfTextEditor/types";
+import { exportToBlob } from "@editor/tools/pdfTextEditor/util/exportPdf";
+import { growEdge, growEdges } from "@editor/tools/pdfTextEditor/util/growEdge";
+
+const SAMPLE = path.join(
+ import.meta.dirname,
+ "../../../tests/test-fixtures/two-column-sample.pdf",
+);
+const RIGHT_COLUMN_X = 306;
+const GUTTER_LEFT = 296.5;
+
+const opened: EditorDocument[] = [];
+
+beforeAll(async () => {
+ const wasm = await readFile(
+ createRequire(import.meta.url).resolve("@embedpdf/pdfium/pdfium.wasm"),
+ );
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async (url: string) =>
+ String(url).endsWith(".wasm")
+ ? new Response(wasm, {
+ headers: { "Content-Type": "application/wasm" },
+ })
+ : new Response(null, { status: 404 }),
+ ),
+ );
+});
+
+afterEach(() => {
+ for (const doc of opened.splice(0)) doc.dispose();
+});
+
+afterAll(() => vi.unstubAllGlobals());
+
+async function open(bytes: Uint8Array) {
+ const doc = await EditorDocument.open(bytes);
+ opened.push(doc);
+ const page = doc.page(0);
+ PdfiumTextReader.populate(doc, page);
+ return { doc, page };
+}
+
+const snapshots = (page: Page) => page.runs.map((run) => run.snapshot());
+
+function rightColumn(page: Page) {
+ return page.runs
+ .filter((run) => run.bounds.x > GUTTER_LEFT)
+ .map((run) => ({
+ text: run.text,
+ x: Math.round(run.bounds.x * 10) / 10,
+ y: Math.round(run.bounds.y * 10) / 10,
+ }));
+}
+
+function snapshot(
+ id: string,
+ x: number,
+ width: number,
+ text: string,
+): TextRunSnapshot {
+ return {
+ id,
+ pageIndex: 0,
+ bounds: { x, y: 700, width, height: 10 },
+ matrix: { a: 10, b: 0, c: 0, d: 10, e: x, f: 702 },
+ text,
+ fontId: "base14:Helvetica",
+ fontSize: 10,
+ fill: { r: 0, g: 0, b: 0, a: 255 },
+ fontSubset: false,
+ };
+}
+
+test("a left-column paragraph grows up to the column on its right, less a gap", async () => {
+ const { page } = await open(new Uint8Array(await readFile(SAMPLE)));
+ const runs = snapshots(page);
+ const left = runs.find((run) => run.text.startsWith("Northern ferries"))!;
+
+ const edge = growEdge(left, runs);
+
+ expect(edge?.side).toBe("right");
+ expect(edge!.x).toBeGreaterThan(left.bounds.x + left.bounds.width);
+ expect(edge!.x).toBeLessThan(RIGHT_COLUMN_X);
+});
+
+test("text with nothing set beside it keeps the page edge", async () => {
+ const { page } = await open(new Uint8Array(await readFile(SAMPLE)));
+ const edges = growEdges(snapshots(page));
+
+ for (const run of page.runs.filter(
+ (run) => run.bounds.x > GUTTER_LEFT || run.text.includes("council"),
+ ))
+ expect(edges.get(run.id), run.text).toBeUndefined();
+});
+
+test("right-to-left text grows towards the text on its left", () => {
+ const latin = snapshot("latin", 40, 100, "Total amount");
+ const hebrew = snapshot("hebrew", 200, 80, "שלום עולם");
+
+ expect(growEdge(hebrew, [latin, hebrew])).toEqual({ side: "left", x: 145 });
+ expect(growEdge(latin, [latin, hebrew])).toEqual({ side: "right", x: 195 });
+});
+
+test("text on the lines above and below is no edge", () => {
+ const run = snapshot("run", 40, 100, "A line of text");
+ const above = {
+ ...snapshot("above", 200, 80, "Above"),
+ bounds: { x: 200, y: 711, width: 80, height: 10 },
+ };
+
+ expect(growEdge(run, [run, above])).toBeNull();
+});
+
+test("text wrapped at that edge leaves the right column as it was in the saved file", async () => {
+ const { doc, page } = await open(new Uint8Array(await readFile(SAMPLE)));
+ const before = rightColumn(page);
+ const left = page.runs.find((run) =>
+ run.text.startsWith("Northern ferries"),
+ )!;
+ const edge = growEdge(left.snapshot(), snapshots(page))!;
+ const typed = left.text.replace(
+ "the islands",
+ "the islands with extra cargo",
+ );
+
+ new EditTextCommand({ pageIndex: 0, runId: left.id, nextText: typed }).apply(
+ doc,
+ );
+ const wrap = new ReflowWrapCommand({
+ pageIndex: 0,
+ runId: left.id,
+ maxWidthPt: edge.x - left.bounds.x,
+ keepClearBelow: true,
+ });
+ wrap.apply(doc);
+ expect(wrap.refusedForSpaceBelow).toBe(false);
+ expect(rightColumn(page)).toEqual(before);
+
+ const saved = await open(
+ new Uint8Array(await (await exportToBlob(doc)).arrayBuffer()),
+ );
+ expect(rightColumn(saved.page)).toEqual(before);
+ const reread = saved.page.runs.find((run) =>
+ run.text.startsWith("Northern ferries"),
+ )!;
+ expect(reread.text.replace(/\s+/g, " ")).toContain(
+ "the islands with extra cargo",
+ );
+ expect(reread.bounds.x + reread.bounds.width).toBeLessThan(GUTTER_LEFT);
+});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/hiddenText.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/hiddenText.test.ts
new file mode 100644
index 0000000000..fefea94513
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/hiddenText.test.ts
@@ -0,0 +1,96 @@
+// @vitest-environment node
+import { readFile } from "node:fs/promises";
+import { createRequire } from "node:module";
+import { afterAll, beforeAll, expect, test, vi } from "vitest";
+import { EditTextCommand } from "@editor/tools/pdfTextEditor/commands/EditTextCommand";
+import { isScanRun } from "@editor/tools/pdfTextEditor/commands/scanTextEdit";
+import { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
+import { PdfiumTextReader } from "@editor/tools/pdfTextEditor/pdfium/PdfiumTextReader";
+import { HistoryStack } from "@editor/tools/pdfTextEditor/store/HistoryStack";
+import { exportToBlob } from "@editor/tools/pdfTextEditor/util/exportPdf";
+import { singleContentPdf } from "@editor/tools/pdfTextEditor/__tests__/pdfFixtures";
+
+beforeAll(async () => {
+ const wasm = await readFile(
+ createRequire(import.meta.url).resolve("@embedpdf/pdfium/pdfium.wasm"),
+ );
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(
+ async () =>
+ new Response(wasm, { headers: { "Content-Type": "application/wasm" } }),
+ ),
+ );
+});
+
+afterAll(() => vi.unstubAllGlobals());
+
+const RENDER_MODES = singleContentPdf(
+ [
+ "BT /F1 26 Tf 0 Tr 1 0 0 1 72 700 Tm (Mode 0 fill) Tj ET",
+ "BT /F1 26 Tf 1 Tr 1 0 0 1 72 650 Tm (Mode 1 stroke) Tj ET",
+ "BT /F1 26 Tf 3 Tr 1 0 0 1 72 600 Tm (Mode 3 invisible) Tj ET",
+ "BT /F1 26 Tf 7 Tr 1 0 0 1 72 550 Tm (Mode 7 clip) Tj ET",
+ ].join("\n"),
+);
+
+async function opened(bytes: Uint8Array): Promise<EditorDocument> {
+ const doc = await EditorDocument.open(bytes);
+ PdfiumTextReader.populate(doc, doc.page(0));
+ return doc;
+}
+
+test("reads invisible text with no picture behind it as hidden text, not a scan", async () => {
+ const doc = await opened(RENDER_MODES);
+ try {
+ const run = doc.page(0).runs.find((r) => r.text === "Mode 3 invisible")!;
+ expect(run.hiddenText).toBe(true);
+ expect(isScanRun(run)).toBe(false);
+ } finally {
+ doc.dispose();
+ }
+});
+
+test("keeps invisible and clip-only lines out of the paragraph of drawn lines above them", async () => {
+ const doc = await opened(RENDER_MODES);
+ try {
+ expect(
+ doc.page(0).runs.map((r) => [r.renderMode, r.text.split("\n").length]),
+ ).toEqual(
+ expect.arrayContaining([
+ [3, 1],
+ [7, 1],
+ ]),
+ );
+ } finally {
+ doc.dispose();
+ }
+});
+
+test("saves text typed into hidden text, and keeps it invisible", async () => {
+ const doc = await opened(RENDER_MODES);
+ let saved: EditorDocument | null = null;
+ try {
+ const run = doc.page(0).runs.find((r) => r.text === "Mode 3 invisible")!;
+ new HistoryStack().execute(
+ new EditTextCommand({
+ pageIndex: 0,
+ runId: run.id,
+ nextText: "Mode 3 invisible EXTRA",
+ }),
+ doc,
+ );
+ expect(run.text).toBe("Mode 3 invisible EXTRA");
+ saved = await opened(
+ new Uint8Array(await (await exportToBlob(doc)).arrayBuffer()),
+ );
+ const back = saved
+ .page(0)
+ .runs.find((r) => r.text.startsWith("Mode 3 invisible"))!;
+ expect(back.text).toBe("Mode 3 invisible EXTRA");
+ expect(back.renderMode).toBe(3);
+ } finally {
+ saved?.dispose();
+ doc.dispose();
+ }
+});
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 24f53f26de..b7cb2edd40 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/innerTags.test.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/innerTags.test.ts
@@ -392,6 +392,22 @@ describe("tags inside a run's text through edits to it", () => {
expect(await savedIn(doc, "German subsidiaries", "Span")).toBe(1);
});
+ test("puts a deleted element back on undoing a burst of edits", async () => {
+ const doc = await open();
+ const history = new HistoryStack();
+ edit(doc, history, "German subsidiaries", "Umsatzerlöse", "");
+ edit(doc, history, "German subsidiaries", "German", "Austrian");
+ expect(history.size().undo).toBe(1);
+ history.undo(doc);
+ history.redo(doc);
+ 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");
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/insertImagePlacement.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/insertImagePlacement.test.ts
new file mode 100644
index 0000000000..76e1dd6ed9
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/insertImagePlacement.test.ts
@@ -0,0 +1,212 @@
+// @vitest-environment node
+import { readFile } from "node:fs/promises";
+import { createRequire } from "node:module";
+import path from "node:path";
+import { afterAll, afterEach, beforeAll, expect, test, vi } from "vitest";
+import {
+ centredImageRect,
+ InsertImageCommand,
+} from "@editor/tools/pdfTextEditor/commands/InsertImageCommand";
+import { SetImageTransformCommand } from "@editor/tools/pdfTextEditor/commands/SetImageTransformCommand";
+import { imageMatrixBounds } from "@editor/tools/pdfTextEditor/model/affine";
+import { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
+import type { Page } from "@editor/tools/pdfTextEditor/model/Page";
+import { PdfiumTextReader } from "@editor/tools/pdfTextEditor/pdfium/PdfiumTextReader";
+import { HistoryStack } from "@editor/tools/pdfTextEditor/store/HistoryStack";
+import type { PageRect } from "@editor/tools/pdfTextEditor/types";
+import { exportToBlob } from "@editor/tools/pdfTextEditor/util/exportPdf";
+
+const FIXTURES = path.join(import.meta.dirname, "../../../tests/test-fixtures");
+const RATIO = 0.4;
+const opened: EditorDocument[] = [];
+
+beforeAll(async () => {
+ const wasm = await readFile(
+ createRequire(import.meta.url).resolve("@embedpdf/pdfium/pdfium.wasm"),
+ );
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async (url: string) =>
+ String(url).endsWith(".wasm")
+ ? new Response(wasm, {
+ headers: { "Content-Type": "application/wasm" },
+ })
+ : new Response(null, { status: 404 }),
+ ),
+ );
+});
+
+afterEach(() => {
+ for (const doc of opened.splice(0)) doc.dispose();
+});
+
+afterAll(() => vi.unstubAllGlobals());
+
+async function open(bytes: Uint8Array): Promise<EditorDocument> {
+ const doc = await EditorDocument.open(bytes);
+ opened.push(doc);
+ return doc;
+}
+
+async function openFixture(name: string): Promise<EditorDocument> {
+ return open(new Uint8Array(await readFile(path.join(FIXTURES, name))));
+}
+
+function solid(width: number, height: number): Uint8ClampedArray {
+ const rgba = new Uint8ClampedArray(width * height * 4);
+ for (let i = 0; i < rgba.length; i += 4) {
+ rgba[i] = 255;
+ rgba[i + 3] = 255;
+ }
+ return rgba;
+}
+
+function insert(page: Page, pixelWidth: number, pixelHeight: number) {
+ return new InsertImageCommand({
+ pageIndex: page.index,
+ rgba: solid(pixelWidth, pixelHeight),
+ pixelWidth,
+ pixelHeight,
+ ...centredImageRect(page.display.toData(), pixelWidth, pixelHeight, RATIO),
+ });
+}
+
+function onScreen(page: Page, raw: PageRect): PageRect {
+ const corners = [
+ page.display.apply(raw.x, raw.y),
+ page.display.apply(raw.x + raw.width, raw.y + raw.height),
+ ];
+ const x = Math.min(...corners.map((c) => c.x));
+ const y = Math.min(...corners.map((c) => c.y));
+ return {
+ x,
+ y,
+ width: Math.max(...corners.map((c) => c.x)) - x,
+ height: Math.max(...corners.map((c) => c.y)) - y,
+ };
+}
+
+function expectCentredUpright(page: Page, raw: PageRect, aspect: number): void {
+ const shown = onScreen(page, raw);
+ const { displayWidth, displayHeight } = page.display;
+ expect(shown.x + shown.width / 2).toBeCloseTo(displayWidth / 2, 3);
+ expect(shown.y + shown.height / 2).toBeCloseTo(displayHeight / 2, 3);
+ expect(shown.x).toBeGreaterThanOrEqual(-1e-3);
+ expect(shown.y).toBeGreaterThanOrEqual(-1e-3);
+ expect(shown.x + shown.width).toBeLessThanOrEqual(displayWidth + 1e-3);
+ expect(shown.y + shown.height).toBeLessThanOrEqual(displayHeight + 1e-3);
+ expect(shown.height / shown.width).toBeCloseTo(aspect, 3);
+}
+
+const CASES = [
+ ["rotated-pages.pdf", 0, 0],
+ ["rotated-pages.pdf", 1, 90],
+ ["rotated-pages.pdf", 2, 270],
+ ["rotated-pages.pdf", 3, 180],
+ ["cropbox-rotate90.pdf", 0, 90],
+ ["cropbox-offset.pdf", 0, 0],
+] as const;
+
+test.each(CASES)(
+ "a new image on %s page %i (/Rotate %i) is centred upright on the visible page, on screen and saved",
+ async (fixture, pageIndex, _rotation) => {
+ const doc = await openFixture(fixture);
+ const page = doc.page(pageIndex);
+ const history = new HistoryStack();
+ const cmd = insert(page, 50, 100);
+ history.execute(cmd, doc);
+ const image = page.images.find((i) => i.id === cmd.insertedImageId)!;
+ expectCentredUpright(page, image.bounds, 2);
+
+ const saved = await open(
+ new Uint8Array(await (await exportToBlob(doc)).arrayBuffer()),
+ );
+ const savedPage = saved.page(pageIndex);
+ PdfiumTextReader.populate(saved, savedPage);
+ const savedImage = savedPage.images.at(-1)!;
+ expectCentredUpright(savedPage, imageMatrixBounds(savedImage.matrix), 2);
+ },
+);
+
+test.each(CASES)(
+ "an image too tall for %s page %i (/Rotate %i) is shrunk to fit the visible page",
+ async (fixture, pageIndex, _rotation) => {
+ const doc = await openFixture(fixture);
+ const page = doc.page(pageIndex);
+ const cmd = insert(page, 10, 400);
+ new HistoryStack().execute(cmd, doc);
+ const image = page.images.find((i) => i.id === cmd.insertedImageId)!;
+ expectCentredUpright(page, image.bounds, 40);
+ expect(onScreen(page, image.bounds).height).toBeCloseTo(
+ page.display.displayHeight,
+ 3,
+ );
+ },
+);
+
+test.each([
+ ["rotated-pages.pdf", 1, 90],
+ ["rotated-pages.pdf", 2, 270],
+ ["cropbox-rotate90.pdf", 0, 90],
+] as const)(
+ "redo on %s page %i (/Rotate %i) restores the bounds the first insert gave, and a resize after it keeps the picture",
+ async (fixture, pageIndex, _rotation) => {
+ const doc = await openFixture(fixture);
+ const page = doc.page(pageIndex);
+ const history = new HistoryStack();
+ const cmd = insert(page, 50, 100);
+ history.execute(cmd, doc);
+ const id = cmd.insertedImageId!;
+ const first = page.findImage(id)!;
+ const applied = {
+ bounds: { ...first.bounds },
+ matrix: { ...first.matrix },
+ };
+
+ history.undo(doc);
+ expect(page.findImage(id)).toBeFalsy();
+ history.redo(doc);
+ const redone = page.findImage(id)!;
+ expect(redone.bounds).toEqual(applied.bounds);
+ expect(redone.matrix).toEqual(applied.matrix);
+ expect(redone.bounds).toEqual(imageMatrixBounds(redone.matrix));
+
+ const grown: PageRect = {
+ x: applied.bounds.x - applied.bounds.width / 2,
+ y: applied.bounds.y - applied.bounds.height / 2,
+ width: applied.bounds.width * 2,
+ height: applied.bounds.height * 2,
+ };
+ history.execute(
+ new SetImageTransformCommand({
+ pageIndex,
+ imageId: id,
+ nextBounds: grown,
+ }),
+ doc,
+ );
+ const resized = page.findImage(id)!;
+ const matrix = resized.matrix;
+ expect(resized.bounds.x).toBeCloseTo(grown.x, 3);
+ expect(resized.bounds.y).toBeCloseTo(grown.y, 3);
+ expect(resized.bounds.width).toBeCloseTo(grown.width, 3);
+ expect(resized.bounds.height).toBeCloseTo(grown.height, 3);
+ expect(
+ Math.hypot(matrix.a, matrix.b) / Math.hypot(matrix.c, matrix.d),
+ ).toBeCloseTo(
+ Math.hypot(applied.matrix.a, applied.matrix.b) /
+ Math.hypot(applied.matrix.c, applied.matrix.d),
+ 3,
+ );
+ const shown = onScreen(page, resized.bounds);
+ expect(shown.x + shown.width / 2).toBeCloseTo(
+ page.display.displayWidth / 2,
+ 3,
+ );
+ expect(shown.y + shown.height / 2).toBeCloseTo(
+ page.display.displayHeight / 2,
+ 3,
+ );
+ expect(shown.height / shown.width).toBeCloseTo(2, 3);
+ },
+);
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/lineContentOrder.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/lineContentOrder.test.ts
new file mode 100644
index 0000000000..5e8991289a
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/lineContentOrder.test.ts
@@ -0,0 +1,134 @@
+// @vitest-environment node
+import { readFile } from "node:fs/promises";
+import { createRequire } from "node:module";
+import {
+ afterAll,
+ afterEach,
+ beforeAll,
+ describe,
+ expect,
+ test,
+ vi,
+} from "vitest";
+import { EditTextCommand } from "@editor/tools/pdfTextEditor/commands/EditTextCommand";
+import { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
+import { PdfiumTextReader } from "@editor/tools/pdfTextEditor/pdfium/PdfiumTextReader";
+import {
+ buildClassicPdf,
+ streamBody,
+} from "@editor/tools/pdfTextEditor/__tests__/pdfFixtures";
+
+const FPDF_PAGEOBJ_TEXT = 1;
+const FPDF_PAGEOBJ_PATH = 2;
+
+// A highlight drawn between two words of a line, as word processors export one.
+function highlightedLinePdf(): Uint8Array {
+ return buildClassicPdf(
+ [
+ { num: 1, body: "<< /Type /Catalog /Pages 2 0 R >>" },
+ { 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 " +
+ "/Resources << /Font << /F1 5 0 R >> >> >>",
+ },
+ {
+ num: 4,
+ body: streamBody(
+ "",
+ "BT /F1 12 Tf 72 700 Td (Alpha ) Tj ET\n" +
+ "1 1 0 rg 106 696 30 14 re f 0 g\n" +
+ "BT /F1 12 Tf 108 700 Td (Beta ) Tj ET\n" +
+ "BT /F1 12 Tf 138 700 Td (Gamma) Tj ET\n",
+ ),
+ },
+ {
+ num: 5,
+ body: "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>",
+ },
+ ],
+ 1,
+ );
+}
+
+const opened: EditorDocument[] = [];
+
+beforeAll(async () => {
+ const wasm = await readFile(
+ createRequire(import.meta.url).resolve("@embedpdf/pdfium/pdfium.wasm"),
+ );
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async (url: string) =>
+ String(url).endsWith(".wasm")
+ ? new Response(wasm, {
+ headers: { "Content-Type": "application/wasm" },
+ })
+ : new Response(null, { status: 404 }),
+ ),
+ );
+});
+
+afterEach(() => {
+ for (const doc of opened.splice(0)) doc.dispose();
+});
+
+afterAll(() => vi.unstubAllGlobals());
+
+// The page's objects in content order: "#" for a path, else the text it draws.
+function contentOrder(doc: EditorDocument): string[] {
+ const m = doc.module;
+ const page = doc.page(0);
+ const buf = m.pdfium.wasmExports.malloc(512);
+ const textPage = m.FPDFText_LoadPage(page.pagePtr);
+ const out: string[] = [];
+ try {
+ for (let i = 0; i < m.FPDFPage_CountObjects(page.pagePtr); i++) {
+ const obj = m.FPDFPage_GetObject(page.pagePtr, i);
+ const type = m.FPDFPageObj_GetType(obj);
+ if (type === FPDF_PAGEOBJ_PATH) out.push("#");
+ else if (type === FPDF_PAGEOBJ_TEXT) {
+ m.FPDFTextObj_GetText(obj, textPage, buf, 512);
+ const text = m.pdfium.UTF16ToString(buf).trim();
+ if (text) out.push(text);
+ }
+ }
+ } finally {
+ m.FPDFText_ClosePage(textPage);
+ m.pdfium.wasmExports.free(buf);
+ }
+ return out;
+}
+
+async function open(): Promise<EditorDocument> {
+ const doc = await EditorDocument.open(highlightedLinePdf());
+ opened.push(doc);
+ PdfiumTextReader.populate(doc, doc.page(0));
+ return doc;
+}
+
+describe("editing a line with a highlight drawn between its words", () => {
+ test("keeps the highlight under its word when another word is typed", async () => {
+ const doc = await open();
+ const run = doc.page(0).runs.find((r) => r.text.includes("Beta"))!;
+ expect(run.text).toBe("Alpha Beta Gamma");
+ expect(contentOrder(doc)).toEqual(["Alpha", "#", "Beta", "Gamma"]);
+
+ const cmd = new EditTextCommand({
+ pageIndex: 0,
+ runId: run.id,
+ nextText: "Alpha New Beta Gamma Delta",
+ });
+ cmd.apply(doc);
+
+ const order = contentOrder(doc);
+ expect(order.indexOf("#")).toBeLessThan(order.indexOf("Beta"));
+ expect(order.filter((piece) => piece !== "#").join(" ")).toBe(
+ "Alpha New Beta Gamma Delta",
+ );
+
+ cmd.revert(doc);
+ expect(contentOrder(doc)).toEqual(["Alpha", "#", "Beta", "Gamma"]);
+ });
+});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/lineJoinFallbackGlyphs.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/lineJoinFallbackGlyphs.test.ts
new file mode 100644
index 0000000000..d08386666d
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/lineJoinFallbackGlyphs.test.ts
@@ -0,0 +1,88 @@
+// @vitest-environment node
+import { readFile } from "node:fs/promises";
+import { createRequire } from "node:module";
+import path from "node:path";
+import { afterAll, afterEach, beforeAll, expect, test, vi } from "vitest";
+import { EditTextCommand } from "@editor/tools/pdfTextEditor/commands/EditTextCommand";
+import { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
+import { PdfiumTextReader } from "@editor/tools/pdfTextEditor/pdfium/PdfiumTextReader";
+
+const SAMPLE = path.join(
+ import.meta.dirname,
+ "../../../tests/test-fixtures/subset-truetype-heading.pdf",
+);
+const HEADING = "Quarterly report heading";
+const FPDF_PAGEOBJ_TEXT = 1;
+
+const opened: EditorDocument[] = [];
+
+beforeAll(async () => {
+ const wasmPath = createRequire(import.meta.url).resolve(
+ "@embedpdf/pdfium/pdfium.wasm",
+ );
+ const wasmBytes = await readFile(wasmPath);
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async () =>
+ Promise.resolve(
+ new Response(wasmBytes, {
+ headers: { "Content-Type": "application/wasm" },
+ }),
+ ),
+ ),
+ );
+});
+
+afterAll(() => {
+ vi.unstubAllGlobals();
+});
+
+afterEach(() => {
+ for (const doc of opened.splice(0)) doc.dispose();
+});
+
+function edit(doc: EditorDocument, runId: string, nextText: string): void {
+ new EditTextCommand({ pageIndex: 0, runId, nextText }).apply(doc);
+}
+
+// The subset holds only the letters the heading used, so any other letter drawn in it has no outline.
+function lettersDrawnInFont(doc: EditorDocument, font: number): string {
+ const m = doc.module;
+ const pagePtr = doc.page(0).pagePtr;
+ const textPage = m.FPDFText_LoadPage(pagePtr);
+ const buffer = m.pdfium.wasmExports.malloc(1024);
+ let drawn = "";
+ try {
+ for (let i = 0; i < m.FPDFPage_CountObjects(pagePtr); i++) {
+ const obj = m.FPDFPage_GetObject(pagePtr, i);
+ if (m.FPDFPageObj_GetType(obj) !== FPDF_PAGEOBJ_TEXT) continue;
+ if (m.FPDFTextObj_GetFont(obj) !== font) continue;
+ m.FPDFTextObj_GetText(obj, textPage, buffer, 1024);
+ drawn += m.pdfium.UTF16ToString(buffer);
+ }
+ } finally {
+ m.pdfium.wasmExports.free(buffer);
+ m.FPDFText_ClosePage(textPage);
+ }
+ return drawn;
+}
+
+test("joining two lines keeps letters the subset font lacks in their fallback face", async () => {
+ const doc = await EditorDocument.open(new Uint8Array(await readFile(SAMPLE)));
+ opened.push(doc);
+ PdfiumTextReader.populate(doc, doc.page(0));
+ const run = doc.page(0).runs.find((r) => r.text === HEADING)!;
+ expect(run).toBeDefined();
+ const subset = doc.module.FPDFTextObj_GetFont(run.pdfiumObjPtr);
+ const typed = " quick jump";
+
+ edit(doc, run.id, "Quarterly report \nheading");
+ edit(doc, run.id, `Quarterly report \nheading${typed}`);
+ edit(doc, run.id, `Quarterly report heading${typed}`);
+
+ expect(doc.page(0).findRun(run.id)?.text).toBe(`${HEADING}${typed}`);
+ const outsideSubset = [
+ ...lettersDrawnInFont(doc, subset).replace(/\s/g, ""),
+ ].filter((ch) => !HEADING.includes(ch));
+ expect(outsideSubset).toEqual([]);
+});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/lineJoinSpaces.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/lineJoinSpaces.test.ts
new file mode 100644
index 0000000000..14cbc410e3
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/lineJoinSpaces.test.ts
@@ -0,0 +1,51 @@
+// @vitest-environment node
+import { describe, expect, it } from "vitest";
+import { Page } from "@editor/tools/pdfTextEditor/model/Page";
+import { TextRun } from "@editor/tools/pdfTextEditor/model/TextRun";
+import { LineGrouper } from "@editor/tools/pdfTextEditor/pdfium/LineGrouper";
+
+const FONT_SIZE = 18;
+const LETTER = FONT_SIZE * 0.5;
+let ptr = 2000;
+
+function piece(x: number, text: string): TextRun {
+ const ink = text.trimEnd().length * LETTER;
+ return new TextRun({
+ id: `r${ptr}`,
+ pageIndex: 0,
+ bounds: { x, y: 700, width: ink, height: FONT_SIZE },
+ matrix: { a: FONT_SIZE, b: 0, c: 0, d: FONT_SIZE, e: x, f: 700 },
+ text,
+ fontId: "pdf:1:Helvetica",
+ fontSize: FONT_SIZE,
+ fill: { r: 0, g: 0, b: 0, a: 255 },
+ fontSubset: false,
+ pdfiumObjPtr: ptr++,
+ containerPtr: 0,
+ });
+}
+
+function lines(runs: TextRun[]): string[] {
+ const page = new Page({ index: 0, pagePtr: 1, width: 600, height: 800 });
+ page.setRuns(runs);
+ page.loaded = true;
+ LineGrouper.apply(page);
+ return page.runs.map((run) => run.text);
+}
+
+describe("joining pieces of a line", () => {
+ it("joins across a gap its own typed spaces account for", () => {
+ const first = piece(40, "Heading a ");
+ const gap = 3.2 * LETTER;
+ const second = piece(40 + "Heading a".length * LETTER + gap, "next");
+
+ expect(lines([first, second])).toEqual(["Heading a next"]);
+ });
+
+ it("still keeps apart pieces a wide empty gap separates", () => {
+ const first = piece(40, "Heading");
+ const second = piece(40 + "Heading".length * LETTER + 6 * LETTER, "next");
+
+ expect(lines([first, second]).sort()).toEqual(["Heading", "next"]);
+ });
+});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/localFonts.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/localFonts.test.ts
index 17575b5860..203d54f81d 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/localFonts.test.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/localFonts.test.ts
@@ -1,12 +1,10 @@
import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
import {
- groupByFamily,
isLocalFontAccessSupported,
listLocalFonts,
listLocalFontsIfGranted,
resetLocalFontsCache,
} from "@editor/tools/pdfTextEditor/util/localFonts";
-import type { LocalFont } from "@editor/tools/pdfTextEditor/util/localFonts";
type QueryStub = () => Promise<unknown[]>;
@@ -24,15 +22,6 @@ function face(
return { family, style, postscriptName, fullName: `${family} ${style}` };
}
-function mkFont(family: string, style: string): LocalFont {
- return {
- family,
- style,
- fullName: `${family} ${style}`,
- postscriptName: `${family}-${style}`,
- };
-}
-
beforeEach(() => {
resetLocalFontsCache();
setQuery(null);
@@ -206,44 +195,3 @@ describe("listLocalFontsIfGranted", () => {
await expect(listLocalFontsIfGranted()).resolves.toBeNull();
});
});
-
-describe("groupByFamily", () => {
- it("collapses faces into families sorted case-insensitively", () => {
- const grouped = groupByFamily([
- mkFont("inter", "Regular"),
- mkFont("Arial", "Bold"),
- mkFont("Zapfino", "Regular"),
- mkFont("bahnschrift", "Light"),
- ]);
- expect(grouped.map((f) => f.family)).toEqual([
- "Arial",
- "bahnschrift",
- "inter",
- "Zapfino",
- ]);
- });
-
- it("merges faces of one family and sorts its styles", () => {
- const grouped = groupByFamily([
- mkFont("Inter", "Regular"),
- mkFont("Inter", "Bold"),
- mkFont("inter", "Italic"),
- ]);
- expect(grouped).toHaveLength(1);
- expect(grouped[0]?.family).toBe("Inter");
- expect(grouped[0]?.styles).toEqual(["Bold", "Italic", "Regular"]);
- });
-
- it("de-duplicates styles case-insensitively and skips empty ones", () => {
- const grouped = groupByFamily([
- mkFont("Inter", "Bold"),
- mkFont("Inter", "bold"),
- mkFont("Inter", ""),
- ]);
- expect(grouped[0]?.styles).toEqual(["Bold"]);
- });
-
- it("returns an empty list for no faces", () => {
- expect(groupByFamily([])).toEqual([]);
- });
-});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/mixedStyleEdit.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/mixedStyleEdit.test.ts
new file mode 100644
index 0000000000..9d97df710a
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/mixedStyleEdit.test.ts
@@ -0,0 +1,327 @@
+// @vitest-environment node
+import { readFile } from "node:fs/promises";
+import { createRequire } from "node:module";
+import path from "node:path";
+import {
+ afterAll,
+ afterEach,
+ beforeAll,
+ describe,
+ expect,
+ test,
+ vi,
+} from "vitest";
+import { EditTextCommand } from "@editor/tools/pdfTextEditor/commands/EditTextCommand";
+import { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
+import { HistoryStack } from "@editor/tools/pdfTextEditor/store/HistoryStack";
+import { PdfiumTextReader } from "@editor/tools/pdfTextEditor/pdfium/PdfiumTextReader";
+
+const SAMPLE = path.join(
+ import.meta.dirname,
+ "../../../tests/test-fixtures/mixed-style-sample.pdf",
+);
+const FPDF_PAGEOBJ_TEXT = 1;
+// Lines here are 14pt apart; a glyph sticking above its line stays well inside this.
+const LINE_SLACK_PT = 4;
+
+const opened: EditorDocument[] = [];
+
+beforeAll(async () => {
+ const wasm = await readFile(
+ createRequire(import.meta.url).resolve("@embedpdf/pdfium/pdfium.wasm"),
+ );
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(
+ async () =>
+ new Response(wasm, {
+ headers: { "Content-Type": "application/wasm" },
+ }),
+ ),
+ );
+});
+
+afterEach(() => {
+ for (const doc of opened.splice(0)) doc.dispose();
+});
+
+afterAll(() => vi.unstubAllGlobals());
+
+async function open(): Promise<EditorDocument> {
+ const doc = await EditorDocument.open(new Uint8Array(await readFile(SAMPLE)));
+ opened.push(doc);
+ PdfiumTextReader.populate(doc, doc.page(0));
+ return doc;
+}
+
+interface Piece {
+ left: number;
+ label: string;
+}
+
+// Each drawn piece on the line of the object holding `needle`, left to right, as "text@font".
+function placedPieces(doc: EditorDocument, needle: string): Piece[] {
+ const m = doc.module;
+ const page = doc.page(0);
+ const box = m.pdfium.wasmExports.malloc(16);
+ const text = m.pdfium.wasmExports.malloc(512);
+ const name = m.pdfium.wasmExports.malloc(256);
+ const textPage = m.FPDFText_LoadPage(page.pagePtr);
+ const pieces: Array<Piece & { top: number; text: string }> = [];
+ try {
+ for (let i = 0; i < m.FPDFPage_CountObjects(page.pagePtr); i++) {
+ const obj = m.FPDFPage_GetObject(page.pagePtr, i);
+ if (m.FPDFPageObj_GetType(obj) !== FPDF_PAGEOBJ_TEXT) continue;
+ m.FPDFPageObj_GetBounds(obj, box, box + 4, box + 8, box + 12);
+ m.FPDFTextObj_GetText(obj, textPage, text, 512);
+ m.FPDFFont_GetBaseFontName(m.FPDFTextObj_GetFont(obj), name, 256);
+ const font = m.pdfium.UTF8ToString(name).replace(/^[A-Z]{6}\+/, "");
+ const content = m.pdfium.UTF16ToString(text);
+ pieces.push({
+ left: m.pdfium.getValue(box, "float"),
+ top: m.pdfium.getValue(box + 12, "float"),
+ text: content,
+ label: `${content.trim()}@${font}`,
+ });
+ }
+ } finally {
+ m.FPDFText_ClosePage(textPage);
+ m.pdfium.wasmExports.free(box);
+ m.pdfium.wasmExports.free(text);
+ m.pdfium.wasmExports.free(name);
+ }
+ const anchor = pieces.find((p) => p.text.includes(needle))!;
+ return pieces
+ .filter((p) => Math.abs(p.top - anchor.top) <= LINE_SLACK_PT)
+ .sort((a, b) => a.left - b.left);
+}
+
+function pageText(doc: EditorDocument): string {
+ const m = doc.module;
+ const textPage = m.FPDFText_LoadPage(doc.page(0).pagePtr);
+ try {
+ let text = "";
+ for (let i = 0; i < m.FPDFText_CountChars(textPage); i++)
+ text += String.fromCodePoint(m.FPDFText_GetUnicode(textPage, i));
+ return text.replace(/\s+/g, " ");
+ } finally {
+ m.FPDFText_ClosePage(textPage);
+ }
+}
+
+function piecesOnLine(doc: EditorDocument, needle: string): string[] {
+ return placedPieces(doc, needle).map((p) => p.label);
+}
+
+function typeInto(
+ doc: EditorDocument,
+ needle: string,
+ at: number,
+ add: string,
+) {
+ const run = doc.page(0).runs.find((r) => r.text.includes(needle))!;
+ const i = run.text.indexOf(needle) + at;
+ new EditTextCommand({
+ pageIndex: 0,
+ runId: run.id,
+ nextText: run.text.slice(0, i) + add + run.text.slice(i),
+ }).apply(doc);
+}
+
+describe("typing inside a word of a line that mixes styles", () => {
+ test.each([
+ ["bold", "boXkld", /-Bold$/],
+ ["italic", "itXkalic", /-(Italic|Oblique)$/],
+ ["both", "boXkth", /-Bold(Italic|Oblique)$/],
+ ])(
+ "keeps every word in its own face after typing in %s",
+ async (word, edited, face) => {
+ const doc = await open();
+ const before = piecesOnLine(doc, "Plain");
+
+ typeInto(doc, word, 2, "Xk");
+
+ const after = piecesOnLine(doc, "Plain");
+ // The subset holds only the glyphs the word used, so typed letters it lacks come from a font of the same style.
+ const typed = after.find((p) => p.startsWith(`${edited}@`));
+ expect(typed?.split("@")[1]).toMatch(face);
+ const wordFonts = (pieces: string[]) =>
+ pieces.flatMap((p) => {
+ const [text, font] = p.split("@");
+ return text.split(/\s+/).map((w) => `${w}@${font}`);
+ });
+ const untouched = wordFonts(before).filter(
+ (w) => !w.startsWith(`${word}@`),
+ );
+ expect(wordFonts(after)).toEqual(expect.arrayContaining(untouched));
+ },
+ );
+});
+
+describe("typing inside a word of a single line that mixes styles", () => {
+ test.each([
+ ["urgent", "urXkgent", /-Bold$/],
+ ["needed", "neXkeded", /-(Italic|Oblique)$/],
+ ])(
+ "keeps every word in its own face after typing in %s",
+ async (word, edited, face) => {
+ const doc = await open();
+ const run = doc.page(0).runs.find((r) => r.text.includes("Note:"))!;
+ expect(run.paragraphLineSlots.length).toBeLessThan(2);
+ const before = piecesOnLine(doc, "Note:");
+
+ typeInto(doc, word, 2, "Xk");
+
+ const after = piecesOnLine(doc, "Note:");
+ const typed = after.find((p) => p.startsWith(`${edited}@`));
+ expect(typed?.split("@")[1]).toMatch(face);
+ const others = before
+ .filter((p) => !p.startsWith(`${word}@`))
+ .map((p) => p.split("@")[1]);
+ for (const font of others)
+ expect(after.some((p) => p.endsWith(`@${font}`))).toBe(true);
+ },
+ );
+});
+
+describe("typing a word into a mixed line one letter at a time", () => {
+ test.each([["Note:"], ["Plain"]])(
+ "keeps the other words' faces on the line starting %s",
+ async (needle) => {
+ const doc = await open();
+ const word = needle === "Note:" ? "urgent" : "bold";
+ const fontsBefore = new Set(
+ piecesOnLine(doc, needle).map((p) => p.split("@")[1]),
+ );
+
+ typeInto(doc, word, 2, "X");
+ typeInto(doc, `${word.slice(0, 2)}X`, 3, "k");
+
+ const fontsAfter = new Set(
+ piecesOnLine(doc, needle).map((p) => p.split("@")[1]),
+ );
+ for (const font of fontsBefore)
+ if (!/-Bold$/.test(font)) expect(fontsAfter).toContain(font);
+ expect([...fontsAfter].some((f) => /-Bold$/.test(f))).toBe(true);
+ },
+ );
+});
+
+describe("redrawing one piece of a mixed line", () => {
+ test("keeps the symbols it holds and moves the next piece only by the typed letter", async () => {
+ const doc = await open();
+ const checkBefore = placedPieces(doc, "Ratio").find((p) =>
+ p.label.startsWith("✓"),
+ )!;
+
+ typeInto(doc, "b →", 1, "X");
+
+ const after = placedPieces(doc, "Ratio");
+ const labels = after.map((p) => p.label);
+ for (const kept of ["Ratio", "a", "≥", "→", "c,", "done"])
+ expect(labels).toContain(`${kept}@LiberationSans`);
+ const shift =
+ after.find((p) => p.label.startsWith("✓"))!.left - checkBefore.left;
+ // Helvetica's X at the line's 12pt is 8pt wide; anything near twice that is a doubled space.
+ expect(shift).toBeGreaterThan(6);
+ expect(shift).toBeLessThan(10);
+ });
+
+ test("keeps the word where it started while letters are typed into it", async () => {
+ const doc = await open();
+ const leftOf = () =>
+ placedPieces(doc, "Plain").find((p) => /^bo/.test(p.label))!.left;
+ const start = leftOf();
+
+ typeInto(doc, "bold", 2, "X");
+ typeInto(doc, "boX", 3, "k");
+
+ expect(leftOf()).toBeCloseTo(start, 1);
+ });
+});
+
+describe("undoing an edit that redrew pieces of a mixed line", () => {
+ test.each([
+ ["Ratio", "b →", 1],
+ ["Note:", "urgent", 2],
+ ["Plain", "bold", 2],
+ ])(
+ "puts the line starting %s back exactly and redoes it the same way",
+ async (needle, word, at) => {
+ const doc = await open();
+ const history = new HistoryStack();
+ const drawn = () =>
+ placedPieces(doc, needle).map(({ label, left }) => ({
+ label,
+ left: Math.round(left * 10) / 10,
+ }));
+ const original = drawn();
+ const run = doc.page(0).runs.find((r) => r.text.includes(word))!;
+ const i = run.text.indexOf(word) + at;
+
+ history.execute(
+ new EditTextCommand({
+ pageIndex: 0,
+ runId: run.id,
+ nextText: run.text.slice(0, i) + "Xk" + run.text.slice(i),
+ }),
+ doc,
+ );
+ const edited = drawn();
+ history.undo(doc);
+
+ expect(drawn()).toEqual(original);
+ history.redo(doc);
+ expect(drawn()).toEqual(edited);
+ },
+ );
+});
+
+describe("a line with superscripts and subscripts", () => {
+ test("reads them as part of the line, in place", async () => {
+ const doc = await open();
+
+ expect(doc.page(0).runs.map((r) => r.text)).toContain(
+ "Water is H2O and area is x2 plus y3.",
+ );
+ });
+
+ test("moves them with their words when text is typed before them", async () => {
+ const doc = await open();
+ const scripts = () =>
+ placedPieces(doc, "plus").filter((p) => /^[23]@/.test(p.label));
+ const before = scripts();
+
+ typeInto(doc, "is H", 0, "XYZ ");
+
+ const after = scripts();
+ expect(after).toHaveLength(before.length);
+ const shifts = after.map((p, i) => p.left - before[i].left);
+ for (const shift of shifts) expect(shift).toBeCloseTo(shifts[0], 0);
+ expect(shifts[0]).toBeGreaterThan(20);
+ });
+});
+
+describe("the page's reading order after an edit", () => {
+ test("reads an edited line in place, and exactly as before once undone", async () => {
+ const doc = await open();
+ const history = new HistoryStack();
+ const original = pageText(doc);
+ const run = doc.page(0).runs.find((r) => r.text.includes("Water"))!;
+ const i = run.text.indexOf("is H");
+
+ history.execute(
+ new EditTextCommand({
+ pageIndex: 0,
+ runId: run.id,
+ nextText: run.text.slice(0, i) + "XYZ " + run.text.slice(i),
+ }),
+ doc,
+ );
+
+ expect(pageText(doc)).toContain("Water XYZ is H");
+ expect(pageText(doc).indexOf("Water")).toBe(original.indexOf("Water"));
+ history.undo(doc);
+ expect(pageText(doc)).toBe(original);
+ });
+});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/objectTexts.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/objectTexts.test.ts
new file mode 100644
index 0000000000..4528ce9f1a
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/objectTexts.test.ts
@@ -0,0 +1,152 @@
+// @vitest-environment node
+import { readdirSync } from "node:fs";
+import { readFile } from "node:fs/promises";
+import { createRequire } from "node:module";
+import path from "node:path";
+import { afterAll, beforeAll, expect, test, vi } from "vitest";
+import { readUtf16 } from "@editor/services/pdfiumService";
+import { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
+import { readObjectTexts } from "@editor/tools/pdfTextEditor/pdfium/objectTexts";
+import { PdfiumTextReader } from "@editor/tools/pdfTextEditor/pdfium/PdfiumTextReader";
+import {
+ buildClassicPdf,
+ streamBody,
+} from "@editor/tools/pdfTextEditor/__tests__/pdfFixtures";
+
+const FIXTURES = path.join(import.meta.dirname, "../../../tests/test-fixtures");
+const FPDF_PAGEOBJ_TEXT = 1;
+const FPDF_PAGEOBJ_FORM = 5;
+const MAX_PAGES = 3;
+
+beforeAll(async () => {
+ const wasm = await readFile(
+ createRequire(import.meta.url).resolve("@embedpdf/pdfium/pdfium.wasm"),
+ );
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async (url: string) =>
+ String(url).endsWith(".wasm")
+ ? new Response(wasm, {
+ headers: { "Content-Type": "application/wasm" },
+ })
+ : new Response(null, { status: 404 }),
+ ),
+ );
+});
+
+afterAll(() => vi.unstubAllGlobals());
+
+function textObjects(doc: EditorDocument, pagePtr: number): number[] {
+ const m = doc.module;
+ const out: number[] = [];
+ const visit = (ptr: number, depth: number) => {
+ const type = m.FPDFPageObj_GetType(ptr);
+ if (type === FPDF_PAGEOBJ_TEXT) out.push(ptr);
+ if (type !== FPDF_PAGEOBJ_FORM || depth > 4) return;
+ for (let i = 0; i < m.FPDFFormObj_CountObjects(ptr); i++)
+ visit(m.FPDFFormObj_GetObject(ptr, i), depth + 1);
+ };
+ for (let i = 0; i < m.FPDFPage_CountObjects(pagePtr); i++)
+ visit(m.FPDFPage_GetObject(pagePtr, i), 0);
+ return out;
+}
+
+function pdfiumText(doc: EditorDocument, textPage: number, ptr: number) {
+ const m = doc.module;
+ const len = m.FPDFTextObj_GetText(ptr, textPage, 0, 0);
+ if (len <= 2) return "";
+ const buf = m.pdfium.wasmExports.malloc(len);
+ try {
+ m.FPDFTextObj_GetText(ptr, textPage, buf, len);
+ return readUtf16(m, buf, len);
+ } finally {
+ m.pdfium.wasmExports.free(buf);
+ }
+}
+
+const pdfs = readdirSync(FIXTURES).filter((name) => name.endsWith(".pdf"));
+
+test.each(pdfs)(
+ "reads each object's text as PDFium does, in %s",
+ async (name) => {
+ let doc: EditorDocument;
+ try {
+ doc = await EditorDocument.open(
+ new Uint8Array(await readFile(path.join(FIXTURES, name))),
+ );
+ } catch {
+ return;
+ }
+ try {
+ for (let p = 0; p < Math.min(doc.pageCount, MAX_PAGES); p++) {
+ const pagePtr = doc.page(p).pagePtr;
+ const textPage = doc.module.FPDFText_LoadPage(pagePtr);
+ try {
+ const texts = readObjectTexts(doc.module, textPage);
+ expect(texts).not.toBeNull();
+ for (const ptr of textObjects(doc, pagePtr))
+ expect(texts?.get(ptr) ?? "").toBe(pdfiumText(doc, textPage, ptr));
+ } finally {
+ doc.module.FPDFText_ClosePage(textPage);
+ }
+ }
+ } finally {
+ doc.dispose();
+ }
+ },
+);
+
+test("a page of ten thousand labels loads in about the time its size suggests", async () => {
+ const cols = 50;
+ let content = "";
+ for (let i = 0; i < 10000; i++) {
+ const x = 10 + (i % cols) * 11.8;
+ const y = 780 - Math.floor(i / cols) * 3.8;
+ content += `BT /F1 3 Tf ${x.toFixed(1)} ${y.toFixed(1)} Td (L${i}) Tj ET\n`;
+ }
+ const doc = await EditorDocument.open(
+ buildClassicPdf(
+ [
+ { num: 1, body: "<< /Type /Catalog /Pages 2 0 R >>" },
+ { 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 " +
+ "/Resources << /Font << /F1 5 0 R >> >> >>",
+ },
+ { num: 4, body: streamBody("", content) },
+ {
+ num: 5,
+ body: "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>",
+ },
+ ],
+ 1,
+ ),
+ );
+ try {
+ const m = doc.module;
+ const pagePtr = doc.page(0).pagePtr;
+ const textPage = m.FPDFText_LoadPage(pagePtr);
+ let onePass = 0;
+ let perObject = 0;
+ try {
+ let started = performance.now();
+ readObjectTexts(m, textPage);
+ onePass = performance.now() - started;
+ started = performance.now();
+ for (const ptr of textObjects(doc, pagePtr).slice(0, 1000))
+ pdfiumText(doc, textPage, ptr);
+ perObject = (performance.now() - started) * 10;
+ } finally {
+ m.FPDFText_ClosePage(textPage);
+ }
+ // Relative, so a slow machine cannot fail it: the object-by-object read is far more than five times slower here.
+ expect(onePass * 5).toBeLessThan(perObject);
+
+ PdfiumTextReader.populate(doc, doc.page(0));
+ expect(doc.page(0).runs.length).toBeGreaterThan(0);
+ } finally {
+ doc.dispose();
+ }
+}, 60000);
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/ocrParagraphGrouping.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/ocrParagraphGrouping.test.ts
new file mode 100644
index 0000000000..0e680c03ec
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/ocrParagraphGrouping.test.ts
@@ -0,0 +1,362 @@
+// @vitest-environment node
+import { readFile } from "node:fs/promises";
+import { createRequire } from "node:module";
+import path from "node:path";
+import { afterAll, beforeAll, describe, expect, test, vi } from "vitest";
+import { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
+import { Page } from "@editor/tools/pdfTextEditor/model/Page";
+import { TextRun } from "@editor/tools/pdfTextEditor/model/TextRun";
+import { ParagraphGrouper } from "@editor/tools/pdfTextEditor/pdfium/ParagraphGrouper";
+import { PdfiumTextReader } from "@editor/tools/pdfTextEditor/pdfium/PdfiumTextReader";
+import {
+ RENDER_MODE_INVISIBLE,
+ type PageRuleSnapshot,
+} from "@editor/tools/pdfTextEditor/types";
+
+beforeAll(async () => {
+ const wasm = await readFile(
+ createRequire(import.meta.url).resolve("@embedpdf/pdfium/pdfium.wasm"),
+ );
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(
+ async () =>
+ new Response(wasm, { headers: { "Content-Type": "application/wasm" } }),
+ ),
+ );
+});
+
+afterAll(() => vi.unstubAllGlobals());
+
+async function readFixture(name: string): Promise<EditorDocument> {
+ return EditorDocument.open(
+ new Uint8Array(
+ await readFile(
+ path.join(import.meta.dirname, "../../../tests/test-fixtures", name),
+ ),
+ ),
+ );
+}
+
+async function fixtureRuns(name: string): Promise<string[]> {
+ const doc = await readFixture(name);
+ try {
+ const page = doc.page(0);
+ PdfiumTextReader.populate(doc, page);
+ return page.runs.map((run) => run.text.trim());
+ } finally {
+ doc.dispose();
+ }
+}
+
+test("reads a scanned paragraph whose lines OCR sized a point or two apart as one paragraph", async () => {
+ const doc = await readFixture("scanned-ocr-paragraph.pdf");
+ try {
+ const page = doc.page(0);
+ PdfiumTextReader.populate(doc, page);
+ expect(page.runs.map((run) => run.text.split("\n").length)).toEqual([4, 1]);
+ expect(page.runs[0].text).toMatch(/^This agreement.*\nwill deliver/);
+ expect(page.runs[0].text).toMatch(/\ninterest at two percent per month\.$/);
+ expect(page.runs[1].text).toBe("Signed: Maria Silva");
+ } finally {
+ doc.dispose();
+ }
+});
+
+describe("a web receipt printed as outlines and OCR'd", () => {
+ test("reads its footer address as one block, though OCR sizes its first line far smaller", async () => {
+ expect(await fixtureRuns("scanned-ocr-receipt.pdf")).toContain(
+ [
+ "Il Forno Trading Limited",
+ "lliffe House, Unit 4",
+ "Kingsway Road, Bristol",
+ "United Kingdom BS1 6QA",
+ "Registered in England 0458812",
+ ].join("\n"),
+ );
+ });
+
+ test("reads a paragraph of small loosely led text as one paragraph", async () => {
+ const runs = await fixtureRuns("scanned-ocr-receipt.pdf");
+ expect(runs).toContain(
+ "Questions about this payment can be sent to our support team, who will reply within two working days\nof receiving your message.",
+ );
+ expect(runs).toContain(
+ "Thank you for your order. This receipt confirms the payment we received for the items listed below and\ncan be kept for your records.",
+ );
+ });
+
+ test("keeps the heading and every cell of the bordered table their own boxes", async () => {
+ expect(await fixtureRuns("scanned-ocr-receipt.pdf")).toEqual(
+ expect.arrayContaining([
+ "Payment receipt",
+ "Order number",
+ "Payment date",
+ "Payment method",
+ "Amount paid",
+ "Northwind 88213",
+ "Monday 3 March",
+ "Visa ending 4417",
+ "Forty two pounds",
+ ]),
+ );
+ });
+});
+
+test("keeps the double-spaced lines of a scanned invoice apart", async () => {
+ for (const fixture of ["scanned-ocr-hocr.pdf", "scanned-ocr-sandwich.pdf"])
+ expect(await fixtureRuns(fixture)).toEqual(
+ expect.arrayContaining([
+ "Customer: Jane Example",
+ "Date: 12 September 2026",
+ "Please pay within thirty days of receipt.",
+ "Thank you for your business.",
+ ]),
+ );
+});
+
+test("reads a typed address whose lines OCR stretched differently as one block", async () => {
+ expect(await fixtureRuns("scanned-ocr-typewriter-form.pdf")).toContain(
+ "NORTH HARBOUR TRADING CO\n12-4, 88 RIVERSIDE ROAD, EASTPORT\nTEL : 44-20-555-0147/9",
+ );
+});
+
+const OCR_HEIGHT = 3.1;
+let ptr = 5000;
+
+// An OCR line as ocrmypdf writes it: the upright scale is the line's height, and the sideways one fits its first word to the scan.
+function ocrLine(
+ text: string,
+ x: number,
+ baseline: number,
+ stretch: number,
+ slope = 0,
+): TextRun {
+ return new TextRun({
+ id: `o${ptr}`,
+ pageIndex: 0,
+ bounds: {
+ x,
+ y: baseline - 0.6,
+ width: text.length * 2.2,
+ height: 2.45,
+ },
+ matrix: { a: stretch, b: slope * stretch, c: 0, d: 1, e: x, f: baseline },
+ text,
+ fontId: "pdf:1:GlyphLessFont",
+ fontSize: OCR_HEIGHT * Math.hypot(stretch, slope * stretch),
+ fill: { r: 0, g: 0, b: 0, a: 255 },
+ fontSubset: false,
+ pdfiumObjPtr: ptr++,
+ containerPtr: 0,
+ renderMode: RENDER_MODE_INVISIBLE,
+ });
+}
+
+function rule(x: number, y: number, width: number): PageRuleSnapshot {
+ return {
+ x,
+ y,
+ width,
+ height: 0.75,
+ ptr: 1,
+ thickness: 0.75,
+ color: { r: 0, g: 0, b: 0, a: 255 },
+ };
+}
+
+function group(runs: TextRun[], rules: PageRuleSnapshot[] = []): string[] {
+ const page = new Page({ index: 0, pagePtr: 1, width: 600, height: 800 });
+ page.setRuns(runs);
+ page.setRules(rules);
+ page.loaded = true;
+ ParagraphGrouper.apply(page);
+ return page.runs.map((run) => run.text);
+}
+
+const ADDRESS = [
+ "Northwind Trading Limited",
+ "Unit 4 Harbour Business Park",
+ "Kingsway Road, Bristol",
+ "United Kingdom BS1 6QA",
+ "Registered in England 0458812",
+];
+
+describe("grouping OCR lines whose reported sizes are noise", () => {
+ test("reads an address OCR sized 1.6, 2.2 and 3.1 as one block", () => {
+ const stretches = [0.52, 0.71, 1, 1, 1];
+ const runs = ADDRESS.map((text, i) =>
+ ocrLine(text, 20, 200 - i * 7, stretches[i]),
+ );
+ expect(runs.map((run) => run.fontSize.toFixed(1))).toEqual([
+ "1.6",
+ "2.2",
+ "3.1",
+ "3.1",
+ "3.1",
+ ]);
+ expect(group(runs)).toEqual([ADDRESS.join("\n")]);
+ });
+
+ test("keeps the words of a sideways scan apart", () => {
+ const runs = ADDRESS.map((text, i) =>
+ ocrLine(text, 20, 200 - i * 7, 1, 0.2),
+ );
+ expect(group(runs)).toHaveLength(ADDRESS.length);
+ });
+
+ test("keeps two addresses a paragraph's gap apart as two blocks", () => {
+ const runs = [
+ ...ADDRESS.slice(0, 2).map((text, i) =>
+ ocrLine(text, 20, 300 - i * 7, 1),
+ ),
+ ...ADDRESS.slice(2).map((text, i) => ocrLine(text, 20, 270 - i * 7, 1)),
+ ];
+ expect(group(runs)).toEqual([
+ ADDRESS.slice(0, 2).join("\n"),
+ ADDRESS.slice(2).join("\n"),
+ ]);
+ });
+
+ test("keeps labels and values on one row apart, and each row its own box", () => {
+ const rows = [
+ ["Order number", "Northwind 88213"],
+ ["Payment date", "Monday 3 March"],
+ ["Payment method", "Visa ending 4417"],
+ ];
+ const runs = rows.flatMap(([label, value], r) => [
+ ocrLine(label, 20, 300 - r * 7, 1),
+ ocrLine(value, 230, 300 - r * 7, 1),
+ ]);
+ expect(group(runs).sort()).toEqual(rows.flat().sort());
+ });
+
+ test("keeps the rows of a bordered table apart", () => {
+ const rows = ["Collected from the Kingsway", "store on Monday morning"];
+ const runs = rows.map((text, r) => ocrLine(text, 20, 300 - r * 7, 1));
+ expect(group(runs, [rule(16, 296.5, 120)])).toEqual(rows);
+ expect(
+ group(runs.map((run) => ocrLine(run.text, 20, run.matrix.f, 1))),
+ ).toEqual([rows.join("\n")]);
+ });
+});
+
+interface ScanLine {
+ text: string;
+ x: number;
+ f: number;
+ width: number;
+ fontSize: number;
+ a: number;
+ b?: number;
+ c?: number;
+}
+
+// A receipt's OCR lines with the geometry PDFium reported for them.
+function scanLine({
+ text,
+ x,
+ f,
+ width,
+ fontSize,
+ a,
+ b = 0,
+ c = 0,
+}: ScanLine): TextRun {
+ return new TextRun({
+ id: `s${ptr}`,
+ pageIndex: 0,
+ bounds: { x, y: f, width, height: 2.5 },
+ matrix: { a, b, c, d: 1, e: x, f },
+ text,
+ fontId: "pdf:1:GlyphLessFont",
+ fontSize,
+ fill: { r: 0, g: 0, b: 0, a: 255 },
+ fontSubset: false,
+ pdfiumObjPtr: ptr++,
+ containerPtr: 0,
+ renderMode: RENDER_MODE_INVISIBLE,
+ });
+}
+
+const RECEIPT_ADDRESS = [
+ "Flat Seven Harbour Mews",
+ "Kings Road",
+ "North Quay",
+ "BRISTOL, Avon",
+ "BS1 6QA",
+];
+const RECEIPT_FOOTER = [
+ "*¢ Help",
+ "© Contact",
+ "¢ Returns a Refunds",
+ "¢ Terms Privacy",
+ "¢ Cookies’ Legal",
+];
+
+function receiptFooterRow(): TextRun[] {
+ const baselines = [245.3, 238.3, 231.4, 224.4, 217.8];
+ const address = RECEIPT_ADDRESS.map((text, i) =>
+ scanLine({
+ text,
+ x: i === 4 ? 181.3 : 180.9,
+ f: baselines[i],
+ width: i === 0 ? 82.8 : i === 4 ? 16.5 : 40,
+ fontSize: i === 4 ? 4.27 : 4.6,
+ a: i === 4 ? 1.249 : 1.278,
+ }),
+ );
+ const footer = RECEIPT_FOOTER.map((text, i) =>
+ scanLine({
+ text,
+ x: i === 4 ? 322.5 : 322.3,
+ f: [245.5, 238.6, 231.7, 224.8, 218.0][i],
+ width: i === 0 ? 61.9 : 41.7,
+ fontSize: i === 0 ? 1.6 : 3.15,
+ a: i === 0 ? 0.495 : 0.971,
+ }),
+ );
+ const below = [
+ scanLine({
+ text: "Order placed online",
+ x: 181.4,
+ f: 207.0,
+ width: 50,
+ fontSize: 4.74,
+ a: 1.317,
+ }),
+ scanLine({
+ text: "via the web shop",
+ x: 181.4,
+ f: 200.0,
+ width: 45,
+ fontSize: 4.74,
+ a: 1.317,
+ }),
+ scanLine({
+ text: "Thank you",
+ x: 181.7,
+ f: 193.3,
+ width: 40,
+ fontSize: 6.71,
+ a: 0.887,
+ b: 0.004,
+ c: -0.005,
+ }),
+ ];
+ return [...address, ...footer, ...below];
+}
+
+describe("an address and a footer side by side on a scanned receipt", () => {
+ test("reads each as one block down to its last short line", () => {
+ const runs = group(receiptFooterRow());
+ expect(runs).toContain(RECEIPT_ADDRESS.join("\n"));
+ expect(runs).toContain(RECEIPT_FOOTER.join("\n"));
+ });
+
+ test("keeps the lines below the address their own block", () => {
+ expect(group(receiptFooterRow())).toContain(
+ "Order placed online\nvia the web shop",
+ );
+ });
+});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/overlayPainter.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/overlayPainter.test.ts
index 2fe42cc483..2763a9f5be 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/overlayPainter.test.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/overlayPainter.test.ts
@@ -1,4 +1,4 @@
-import { beforeAll, beforeEach, describe, expect, it } from "vitest";
+import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
import {
isLinePainted,
type PaintLine,
@@ -9,6 +9,7 @@ import {
plainSelectionRange,
readOverlayText,
refitEditedTokens,
+ repaintKeepingSelection,
restoreCaretOffset,
} from "@editor/tools/pdfTextEditor/util/overlayPainter";
@@ -202,6 +203,34 @@ describe("caret offsets", () => {
}
});
+ it("round-trips every offset after a break typed inside a painted line", () => {
+ const el = host();
+ paintLines(el, [line("First item"), line("Second item")], OPTS);
+ // Chrome puts the break inside the token span the caret was in.
+ el.children[0].childNodes[1].appendChild(document.createElement("br"));
+ const model = "First \nitem\nSecond item";
+ expect(readOverlayText(el)).toBe(model);
+ for (let offset = 0; offset <= model.length; offset += 1) {
+ restoreCaretOffset(el, offset);
+ expect(plainCaretOffset(el)).toBe(offset);
+ }
+ });
+
+ it("reads a line Backspace merged up as part of the line above", () => {
+ const el = host();
+ const merged = document.createElement("span");
+ merged.textContent = "bullet item";
+ const next = document.createElement("div");
+ next.textContent = "• Second item";
+ el.replaceChildren("• First ", merged, next);
+ const model = "• First bullet item\n• Second item";
+ expect(readOverlayText(el)).toBe(model);
+ for (let offset = 0; offset <= model.length; offset += 1) {
+ restoreCaretOffset(el, offset);
+ expect(plainCaretOffset(el)).toBe(offset);
+ }
+ });
+
it("clamps past the end instead of throwing", () => {
const el = host();
paintLines(el, [line("abc")], OPTS);
@@ -294,6 +323,49 @@ describe("readOverlayText - browser-emptied blocks", () => {
expect(readOverlayText(el)).toBe("\nleft margin");
});
+ // WebKit merges a line up into a blank one by moving its text in front of that block's filler <br> and leaving the filler there.
+ it("reads a block whose text is followed by the filler break as one line", () => {
+ const el = host();
+ paintLines(el, [line("first"), line("merged up"), line("last")], OPTS);
+ el.children[1].appendChild(document.createElement("br"));
+ expect(readOverlayText(el)).toBe("first\nmerged up\nlast");
+ });
+
+ it("keeps a real break at the end of a block, which the browser follows with a filler", () => {
+ const el = host();
+ paintLines(el, [line("first"), line("broken"), line("last")], OPTS);
+ el.children[1].append(
+ document.createElement("br"),
+ document.createElement("br"),
+ );
+ expect(readOverlayText(el)).toBe("first\nbroken\n\nlast");
+ });
+
+ it("counts a break just before the caret, inside a block, as a line", () => {
+ const el = host();
+ paintLines(el, [line("one two")], OPTS);
+ const block = el.children[0] as HTMLElement;
+ const after = document.createTextNode("two");
+ block.replaceChildren(
+ document.createTextNode("one"),
+ document.createElement("br"),
+ after,
+ );
+ window.getSelection()!.collapse(after, 0);
+ expect(plainCaretOffset(el)).toBe(4);
+ });
+
+ it("puts a caret at the start of a line WebKit merged up at the start of that line", () => {
+ const el = host();
+ paintLines(el, [line("first"), line("merged up"), line("last")], OPTS);
+ const block = el.children[1] as HTMLElement;
+ block.appendChild(document.createElement("br"));
+ let start: Node = block;
+ while (start.firstChild) start = start.firstChild;
+ window.getSelection()!.collapse(start, 0);
+ expect(plainCaretOffset(el)).toBe("first\n".length);
+ });
+
it("still splits a block that really does hold two lines", () => {
const el = host();
paintLines(el, [line("one two")], OPTS);
@@ -451,6 +523,56 @@ describe("selection ranges", () => {
expect(plainSelectionRange(el)).toBeNull();
});
+ it("keeps a selected word selected across a repaint of the same text", () => {
+ const el = host();
+ paintLines(el, [line("Hello brave world")], OPTS);
+ const selection = window.getSelection()!;
+ selection.removeAllRanges();
+ selection.addRange(plainDomRange(el, { start: 6, end: 11 })!);
+
+ repaintKeepingSelection(el, true, () =>
+ paintLines(el, [line("Hello brave world")], OPTS),
+ );
+
+ expect(plainSelectionRange(el)).toEqual({ start: 6, end: 11 });
+ });
+
+ it("puts a caret back where it was across a repaint", () => {
+ const el = host();
+ paintLines(el, [line("Hello world")], OPTS);
+ restoreCaretOffset(el, 4);
+
+ repaintKeepingSelection(el, true, () => paintPlainText(el, "Hello world"));
+
+ expect(plainCaretOffset(el)).toBe(4);
+ expect(plainSelectionRange(el)).toBeNull();
+ });
+
+ it("leaves the selection alone when the run does not own it", () => {
+ const el = host();
+ paintLines(el, [line("Hello world")], OPTS);
+ const selection = window.getSelection()!;
+ selection.removeAllRanges();
+
+ repaintKeepingSelection(el, false, () => paintPlainText(el, "Hello world"));
+
+ expect(selection.rangeCount).toBe(0);
+ });
+
+ it("does not read the selection for a run that is not taking it back", () => {
+ const el = host();
+ paintLines(el, [line("Hello world")], OPTS);
+ const read = vi.spyOn(window, "getSelection");
+ const paint = vi.fn();
+ try {
+ repaintKeepingSelection(el, false, paint);
+ expect(paint).toHaveBeenCalledTimes(1);
+ expect(read).not.toHaveBeenCalled();
+ } finally {
+ read.mockRestore();
+ }
+ });
+
it("maps a range back onto the painted text it was read from", () => {
const el = host();
paintLines(el, [line("Hello world"), line("second line")], OPTS);
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/pageRaster.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/pageRaster.ts
new file mode 100644
index 0000000000..4d44ec5a93
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/pageRaster.ts
@@ -0,0 +1,59 @@
+import type { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
+
+const FPDF_REVERSE_BYTE_ORDER = 0x10;
+
+/** The first page drawn by PDFium onto white at `width` x `height` pixels, as RGBA rows. */
+export function rasterFirstPage(
+ doc: EditorDocument,
+ width: number,
+ height: number,
+ alpha = true,
+): Uint8Array {
+ const m = doc.module;
+ const bitmap = m.FPDFBitmap_Create(width, height, alpha ? 1 : 0);
+ try {
+ m.FPDFBitmap_FillRect(bitmap, 0, 0, width, height, 0xffffffff);
+ m.FPDF_RenderPageBitmap(
+ bitmap,
+ doc.page(0).pagePtr,
+ 0,
+ 0,
+ width,
+ height,
+ 0,
+ FPDF_REVERSE_BYTE_ORDER,
+ );
+ const memory = (
+ m.pdfium.wasmExports as unknown as { memory: WebAssembly.Memory }
+ ).memory;
+ return new Uint8Array(
+ memory.buffer,
+ m.FPDFBitmap_GetBuffer(bitmap),
+ m.FPDFBitmap_GetStride(bitmap) * height,
+ ).slice();
+ } finally {
+ m.FPDFBitmap_Destroy(bitmap);
+ }
+}
+
+/** Pixels whose colour differs by more than antialiasing noise between two equal-sized rasters. */
+export function changedPixels(a: Uint8Array, b: Uint8Array): number {
+ let changed = 0;
+ for (let i = 0; i < a.length; i += 4)
+ if ([0, 1, 2].some((c) => Math.abs(a[i + c] - b[i + c]) > 2)) changed++;
+ return changed;
+}
+
+/** Pixels whose colour differs at all between two equal-sized canvas images. */
+export function differingPixels(a: ImageData, b: ImageData): number {
+ let count = 0;
+ for (let i = 0; i < a.data.length; i += 4) {
+ if (
+ a.data[i] !== b.data[i] ||
+ a.data[i + 1] !== b.data[i + 1] ||
+ a.data[i + 2] !== b.data[i + 2]
+ )
+ count++;
+ }
+ return count;
+}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/pageRepaintArea.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/pageRepaintArea.test.ts
new file mode 100644
index 0000000000..116580d718
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/pageRepaintArea.test.ts
@@ -0,0 +1,86 @@
+import { describe, expect, it } from "vitest";
+import { Page } from "@editor/tools/pdfTextEditor/model/Page";
+
+function page(): Page {
+ return new Page({ index: 0, pagePtr: 1, width: 600, height: 800 });
+}
+
+const box = (x: number, y: number, width: number, height: number) => ({
+ x,
+ y,
+ width,
+ height,
+});
+
+describe("Page repaint area", () => {
+ it("is the noted area for a bitmap painted just before the edit", () => {
+ const p = page();
+ p.markDirty();
+ const from = p.revision;
+ p.markDirty();
+ p.markDirty();
+ p.noteRepaintArea(from, p.revision, box(10, 20, 30, 40));
+
+ expect(p.repaintAreaSince(from)).toEqual(box(10, 20, 30, 40));
+ expect(p.repaintAreaSince(from + 1)).toEqual(box(10, 20, 30, 40));
+ });
+
+ it("grows to cover consecutive edits", () => {
+ const p = page();
+ const start = p.revision;
+ p.markDirty();
+ p.noteRepaintArea(start, p.revision, box(10, 10, 10, 10));
+ const middle = p.revision;
+ p.markDirty();
+ p.noteRepaintArea(middle, p.revision, box(50, 5, 10, 10));
+
+ expect(p.repaintAreaSince(start)).toEqual(box(10, 5, 50, 15));
+ });
+
+ it("leaves out edits the bitmap already shows", () => {
+ const p = page();
+ const start = p.revision;
+ p.markDirty();
+ p.noteRepaintArea(start, p.revision, box(0, 0, 10, 10));
+ const painted = p.revision;
+ p.markDirty();
+ p.noteRepaintArea(painted, p.revision, box(500, 700, 10, 10));
+
+ expect(p.repaintAreaSince(painted)).toEqual(box(500, 700, 10, 10));
+ });
+
+ it("asks for the whole page after a change nobody bounded", () => {
+ const p = page();
+ const from = p.revision;
+ p.markDirty();
+ p.noteRepaintArea(from, p.revision, box(10, 10, 10, 10));
+ p.bumpRevision();
+
+ expect(p.repaintAreaSince(from)).toBeNull();
+ });
+
+ it("asks for the whole page for a bitmap older than the noted span", () => {
+ const p = page();
+ p.markDirty();
+ const from = p.revision;
+ p.markDirty();
+ p.noteRepaintArea(from, p.revision, box(10, 10, 10, 10));
+
+ expect(p.repaintAreaSince(from - 1)).toBeNull();
+ expect(p.repaintAreaSince(p.revision)).toBeNull();
+ });
+
+ it("starts a fresh area when an edit does not follow the last one", () => {
+ const p = page();
+ const first = p.revision;
+ p.markDirty();
+ p.noteRepaintArea(first, p.revision, box(10, 10, 10, 10));
+ p.bumpRevision();
+ const second = p.revision;
+ p.markDirty();
+ p.noteRepaintArea(second, p.revision, box(200, 200, 5, 5));
+
+ expect(p.repaintAreaSince(first)).toBeNull();
+ expect(p.repaintAreaSince(second)).toEqual(box(200, 200, 5, 5));
+ });
+});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/paragraphFaces.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/paragraphFaces.test.ts
new file mode 100644
index 0000000000..2e51efde3f
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/paragraphFaces.test.ts
@@ -0,0 +1,92 @@
+// @vitest-environment node
+import { describe, expect, it } from "vitest";
+import { Page } from "@editor/tools/pdfTextEditor/model/Page";
+import { TextRun } from "@editor/tools/pdfTextEditor/model/TextRun";
+import {
+ LineGrouper,
+ lineFontIds,
+} from "@editor/tools/pdfTextEditor/pdfium/LineGrouper";
+import { ParagraphGrouper } from "@editor/tools/pdfTextEditor/pdfium/ParagraphGrouper";
+
+const SIZE = 11;
+const PITCH = 14;
+const LETTER = SIZE * 0.5;
+let ptr = 3000;
+
+// Fonts by id: the family a name table reports, and the face /BaseFont names.
+const FACES: Record<string, string> = {
+ "pdf:1:Georgia": "Georgia",
+ "pdf:2:Georgia-Bold": "Georgia-Bold",
+ "pdf:3:Georgia": "Georgia-Bold",
+ "pdf:4:Helvetica": "Helvetica",
+};
+
+function piece(x: number, row: number, text: string, fontId: string): TextRun {
+ const f = 700 - row * PITCH;
+ return new TextRun({
+ id: `r${ptr}`,
+ pageIndex: 0,
+ bounds: { x, y: f, width: text.trimEnd().length * LETTER, height: SIZE },
+ matrix: { a: SIZE, b: 0, c: 0, d: SIZE, e: x, f },
+ text,
+ fontId,
+ fontSize: SIZE,
+ fill: { r: 0, g: 0, b: 0, a: 255 },
+ fontSubset: false,
+ pdfiumObjPtr: ptr++,
+ containerPtr: 0,
+ });
+}
+
+// One line of pieces laid end to end.
+function line(row: number, parts: Array<[string, string]>): TextRun[] {
+ let x = 40;
+ return parts.map(([text, fontId]) => {
+ const run = piece(x, row, text, fontId);
+ x += text.length * LETTER;
+ return run;
+ });
+}
+
+function paragraphs(runs: TextRun[]): string[] {
+ const page = new Page({ index: 0, pagePtr: 1, width: 600, height: 800 });
+ page.setRuns(runs);
+ page.loaded = true;
+ const lines = LineGrouper.apply(page);
+ ParagraphGrouper.apply(
+ page,
+ undefined,
+ lineFontIds(lines),
+ (fontId) => FACES[fontId] ?? null,
+ );
+ return page.runs.map((run) => run.text);
+}
+
+describe("grouping lines into paragraphs by face", () => {
+ it("keeps a bold line apart from a regular one of the same family", () => {
+ const runs = [
+ ...line(0, [["Plain Georgia sentence here.", "pdf:1:Georgia"]]),
+ ...line(1, [
+ ["Xk ", "pdf:3:Georgia"],
+ ["Bold Georgia ", "pdf:2:Georgia-Bold"],
+ ["Quixotic ", "pdf:3:Georgia"],
+ ["sentence.", "pdf:2:Georgia-Bold"],
+ ]),
+ ];
+
+ expect(paragraphs(runs)).toHaveLength(2);
+ });
+
+ it("joins a line whose typed words outnumber its own letters", () => {
+ const runs = [
+ ...line(0, [
+ ["First ", "pdf:1:Georgia"],
+ ["Xk Wj9 Quixotic Pasted words ", "pdf:4:Helvetica"],
+ ["item", "pdf:1:Georgia"],
+ ]),
+ ...line(1, [["Second bullet item", "pdf:1:Georgia"]]),
+ ];
+
+ expect(paragraphs(runs)).toHaveLength(1);
+ });
+});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/partialEditKeepsLook.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/partialEditKeepsLook.test.ts
new file mode 100644
index 0000000000..fb3f4b7cd6
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/partialEditKeepsLook.test.ts
@@ -0,0 +1,215 @@
+// @vitest-environment node
+import { readFile } from "node:fs/promises";
+import { createRequire } from "node:module";
+import { afterAll, afterEach, beforeAll, expect, test, vi } from "vitest";
+import { EditTextCommand } from "@editor/tools/pdfTextEditor/commands/EditTextCommand";
+import {
+ buildClassicPdf,
+ streamBody,
+} from "@editor/tools/pdfTextEditor/__tests__/pdfFixtures";
+import { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
+import { PdfiumTextReader } from "@editor/tools/pdfTextEditor/pdfium/PdfiumTextReader";
+import { HistoryStack } from "@editor/tools/pdfTextEditor/store/HistoryStack";
+import { rasterFirstPage } from "@editor/tools/pdfTextEditor/__tests__/pageRaster";
+
+const HEADING = "Quarterly report heading";
+const PAGE_W = 612;
+const PAGE_H = 792;
+const BASELINE = 700;
+
+const opened: EditorDocument[] = [];
+
+beforeAll(async () => {
+ const wasm = await readFile(
+ createRequire(import.meta.url).resolve("@embedpdf/pdfium/pdfium.wasm"),
+ );
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(
+ async () =>
+ new Response(wasm, {
+ headers: { "Content-Type": "application/wasm" },
+ }),
+ ),
+ );
+});
+
+afterEach(() => {
+ for (const doc of opened.splice(0)) doc.dispose();
+});
+
+afterAll(() => vi.unstubAllGlobals());
+
+function pdf(content: string, font: string): Uint8Array {
+ return buildClassicPdf(
+ [
+ { num: 1, body: "<< /Type /Catalog /Pages 2 0 R >>" },
+ { num: 2, body: "<< /Type /Pages /Kids [3 0 R] /Count 1 >>" },
+ {
+ num: 3,
+ body: `<< /Type /Page /Parent 2 0 R /MediaBox [0 0 ${PAGE_W} ${PAGE_H}] /Resources << /Font << /F1 5 0 R >> >> /Contents 4 0 R >>`,
+ },
+ { num: 4, body: streamBody("", content) },
+ { num: 5, body: font },
+ ],
+ 1,
+ );
+}
+
+const HELVETICA = "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>";
+const KERNED = `[(Qua) 60 (rterly) -40 ( report heading)] TJ`;
+
+// Every letter 0.05 em wide, under the width an in-place edit is trusted to draw.
+const NARROW_HELVETICA = `<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /FirstChar 32 /LastChar 126 /Widths [${Array(95).fill(50).join(" ")}] >>`;
+
+async function open(bytes: Uint8Array): Promise<EditorDocument> {
+ const doc = await EditorDocument.open(bytes);
+ opened.push(doc);
+ PdfiumTextReader.populate(doc, doc.page(0));
+ return doc;
+}
+
+function inkedRows(doc: EditorDocument, fromY: number, toY: number): number {
+ const pixels = rasterFirstPage(doc, PAGE_W, PAGE_H, false);
+ let rows = 0;
+ for (let y = fromY; y < toY; y++) {
+ const row = PAGE_H - 1 - y;
+ for (let x = 0; x < PAGE_W; x++) {
+ if (pixels[(row * PAGE_W + x) * 4] < 128) {
+ rows++;
+ break;
+ }
+ }
+ }
+ return rows;
+}
+
+function originsOf(doc: EditorDocument): Array<{ char: string; x: number }> {
+ const m = doc.module;
+ const textPage = m.FPDFText_LoadPage(doc.page(0).pagePtr);
+ const at = m.pdfium.wasmExports.malloc(16);
+ try {
+ return Array.from({ length: m.FPDFText_CountChars(textPage) }, (_, i) => {
+ m.FPDFText_GetCharOrigin(textPage, i, at, at + 8);
+ return {
+ char: String.fromCodePoint(m.FPDFText_GetUnicode(textPage, i)),
+ x: m.pdfium.getValue(at, "double"),
+ };
+ });
+ } finally {
+ m.pdfium.wasmExports.free(at);
+ m.FPDFText_ClosePage(textPage);
+ }
+}
+
+function originOf(doc: EditorDocument, char: string): number {
+ return originsOf(doc).find((g) => g.char === char)!.x;
+}
+
+function drawnText(doc: EditorDocument): string {
+ return originsOf(doc)
+ .map((g) => g.char)
+ .join("")
+ .replace(/\s+/g, " ")
+ .trim();
+}
+
+// Letters this narrow overlap, and PDFium reads a space into every overlap.
+function drawnLetters(doc: EditorDocument): string {
+ return originsOf(doc)
+ .map((g) => g.char)
+ .join("")
+ .replace(/\s+/g, "");
+}
+
+function edit(doc: EditorDocument, nextText: string): HistoryStack {
+ const run = doc.page(0).runs.find((r) => r.text === HEADING)!;
+ const history = new HistoryStack();
+ history.execute(
+ new EditTextCommand({ pageIndex: 0, runId: run.id, nextText }),
+ doc,
+ );
+ return history;
+}
+
+test("deleting a letter from a kerned line that a clip cuts keeps the cut", async () => {
+ const clipTop = BASELINE + 8;
+ const doc = await open(
+ pdf(
+ `q 0 ${clipTop} ${PAGE_W} ${PAGE_H - clipTop} re W n BT /F1 24 Tf 72 ${BASELINE} Td ${KERNED} ET Q`,
+ HELVETICA,
+ ),
+ );
+ expect(inkedRows(doc, BASELINE - 6, clipTop)).toBe(0);
+
+ edit(doc, "Quarterly reprt heading");
+
+ expect(drawnText(doc)).toBe("Quarterly reprt heading");
+ expect(inkedRows(doc, BASELINE - 6, clipTop)).toBe(0);
+ expect(inkedRows(doc, clipTop, BASELINE + 18)).toBeGreaterThan(0);
+});
+
+test("deleting a letter from a kerned line keeps its word spacing", async () => {
+ const doc = await open(
+ pdf(`BT /F1 24 Tf 12 Tw 72 ${BASELINE} Td ${KERNED} ET`, HELVETICA),
+ );
+ const wordGap = originOf(doc, "h") - originOf(doc, "p");
+
+ edit(doc, "Quarterly rport heading");
+
+ expect(drawnText(doc)).toBe("Quarterly rport heading");
+ expect(originOf(doc, "h") - originOf(doc, "p")).toBeCloseTo(wordGap, 2);
+});
+
+test("undo puts back a piece an in-place edit drew too narrow to keep", async () => {
+ const doc = await open(
+ pdf(`BT /F1 24 Tf 72 ${BASELINE} Td (${HEADING}) Tj ET`, NARROW_HELVETICA),
+ );
+ const run = doc.page(0).runs.find((r) => r.text === HEADING)!;
+ const original = run.mergedFromPtrs[0];
+ const before = originsOf(doc);
+
+ const history = edit(doc, "Quarterly reprt heading");
+ expect(run.mergedFromPtrs).not.toContain(original);
+
+ history.undo(doc);
+
+ expect(run.text).toBe(HEADING);
+ expect(drawnLetters(doc)).toBe(HEADING.replace(/ /g, ""));
+ expect(originsOf(doc)).toEqual(before);
+
+ history.redo(doc);
+ expect(drawnLetters(doc)).toBe("Quarterlyreprtheading");
+});
+
+test("undo puts back a paragraph line an in-place edit drew too narrow to keep, every time", async () => {
+ const doc = await open(
+ pdf(
+ `BT /F1 24 Tf 72 ${BASELINE} Td (${HEADING}) Tj 0 -28 Td (Second line of the block) Tj ET`,
+ NARROW_HELVETICA,
+ ),
+ );
+ const run = doc.page(0).runs.find((r) => r.paragraphLineSlots.length > 1)!;
+ const original = run.text;
+ const firstLine = run.paragraphLineSlots[0].mergedFromPtrs[0];
+ const before = originsOf(doc);
+ const history = new HistoryStack();
+ history.execute(
+ new EditTextCommand({
+ pageIndex: 0,
+ runId: run.id,
+ nextText: original.replace("report", "reprt"),
+ }),
+ doc,
+ );
+ expect(run.paragraphLineSlots[0].mergedFromPtrs).not.toContain(firstLine);
+ const edited = drawnLetters(doc);
+
+ for (let i = 0; i < 3; i++) {
+ history.undo(doc);
+ expect(run.text).toBe(original);
+ expect(originsOf(doc)).toEqual(before);
+ history.redo(doc);
+ expect(drawnLetters(doc)).toBe(edited);
+ }
+});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/partialEditRedoObjects.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/partialEditRedoObjects.test.ts
new file mode 100644
index 0000000000..c434ac2782
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/partialEditRedoObjects.test.ts
@@ -0,0 +1,208 @@
+// @vitest-environment node
+import { readFile } from "node:fs/promises";
+import { createRequire } from "node:module";
+import {
+ afterAll,
+ afterEach,
+ beforeAll,
+ describe,
+ expect,
+ it,
+ vi,
+} from "vitest";
+import { EditTextCommand } from "@editor/tools/pdfTextEditor/commands/EditTextCommand";
+import {
+ buildClassicPdf,
+ streamBody,
+} from "@editor/tools/pdfTextEditor/__tests__/pdfFixtures";
+import { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
+import { PdfiumTextReader } from "@editor/tools/pdfTextEditor/pdfium/PdfiumTextReader";
+import { HistoryStack } from "@editor/tools/pdfTextEditor/store/HistoryStack";
+import { exportToBlob } from "@editor/tools/pdfTextEditor/util/exportPdf";
+
+const START = "Open Source editor";
+
+const opened: EditorDocument[] = [];
+
+beforeAll(async () => {
+ const wasm = await readFile(
+ createRequire(import.meta.url).resolve("@embedpdf/pdfium/pdfium.wasm"),
+ );
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(
+ async () =>
+ new Response(wasm, {
+ headers: { "Content-Type": "application/wasm" },
+ }),
+ ),
+ );
+});
+
+afterEach(() => {
+ for (const doc of opened.splice(0)) doc.dispose();
+ vi.restoreAllMocks();
+});
+
+afterAll(() => vi.unstubAllGlobals());
+
+function samplePdf(inForm: boolean): Uint8Array {
+ const line = `BT /F1 12 Tf 72 700 Td (${START}) Tj ET`;
+ return buildClassicPdf(
+ [
+ { num: 1, body: "<< /Type /Catalog /Pages 2 0 R >>" },
+ { 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 /Resources << /Font << /F1 6 0 R >> /XObject << /Fm1 5 0 R >> >> >>",
+ },
+ {
+ num: 4,
+ body: streamBody("", inForm ? "q 1 0 0 1 0 0 cm /Fm1 Do Q" : line),
+ },
+ {
+ num: 5,
+ body: streamBody(
+ "/Type /XObject /Subtype /Form /BBox [0 0 612 792] /Resources << /Font << /F1 6 0 R >> >>",
+ line,
+ ),
+ },
+ {
+ num: 6,
+ body: "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>",
+ },
+ ],
+ 1,
+ );
+}
+
+async function open(bytes: Uint8Array): Promise<EditorDocument> {
+ const doc = await EditorDocument.open(bytes);
+ opened.push(doc);
+ PdfiumTextReader.populate(doc, doc.page(0));
+ return doc;
+}
+
+function drawnText(doc: EditorDocument): string {
+ const m = doc.module;
+ const textPage = m.FPDFText_LoadPage(doc.page(0).pagePtr);
+ const count = m.FPDFText_CountChars(textPage);
+ const buf = m.pdfium.wasmExports.malloc(2 * (count + 1));
+ try {
+ m.FPDFText_GetText(textPage, 0, count, buf);
+ return m.pdfium.UTF16ToString(buf);
+ } finally {
+ m.pdfium.wasmExports.free(buf);
+ m.FPDFText_ClosePage(textPage);
+ }
+}
+
+// The page as drawn, independent of which native objects draw it: each object's kind and box in content order, and the text they read as.
+function pageLayout(doc: EditorDocument): string {
+ const m = doc.module;
+ const pagePtr = doc.page(0).pagePtr;
+ const box = m.pdfium.wasmExports.malloc(16);
+ try {
+ const objects = Array.from(
+ { length: m.FPDFPage_CountObjects(pagePtr) },
+ (_, i) => {
+ const ptr = m.FPDFPage_GetObject(pagePtr, i);
+ m.FPDFPageObj_GetBounds(ptr, box, box + 4, box + 8, box + 12);
+ const edges = [0, 4, 8, 12].map((at) =>
+ m.pdfium.getValue(box + at, "float").toFixed(3),
+ );
+ return `${m.FPDFPageObj_GetType(ptr)}@${edges.join(",")}`;
+ },
+ );
+ return JSON.stringify({ text: drawnText(doc), objects });
+ } finally {
+ m.pdfium.wasmExports.free(box);
+ }
+}
+
+async function exportedText(doc: EditorDocument): Promise<string> {
+ const saved = await open(
+ new Uint8Array(await (await exportToBlob(doc)).arrayBuffer()),
+ );
+ return pageLayout(saved);
+}
+
+// Objects ever taken off or put on the page, less those freed and those on it now: what nothing will ever free.
+function trackStranded(doc: EditorDocument): () => number {
+ const m = doc.module;
+ const seen = new Set<number>();
+ const freed = new Set<number>();
+ const remove = m.FPDFPage_RemoveObject.bind(m);
+ const insert = m.FPDFPage_InsertObject.bind(m);
+ const destroy = m.FPDFPageObj_Destroy.bind(m);
+ vi.spyOn(m, "FPDFPage_RemoveObject").mockImplementation((page, ptr) => {
+ seen.add(ptr);
+ return remove(page, ptr);
+ });
+ vi.spyOn(m, "FPDFPage_InsertObject").mockImplementation((page, ptr) => {
+ seen.add(ptr);
+ return insert(page, ptr);
+ });
+ vi.spyOn(m, "FPDFPageObj_Destroy").mockImplementation((ptr) => {
+ freed.add(ptr);
+ return destroy(ptr);
+ });
+ return () => {
+ const pagePtr = doc.page(0).pagePtr;
+ const onPage = new Set(
+ Array.from({ length: m.FPDFPage_CountObjects(pagePtr) }, (_, i) =>
+ m.FPDFPage_GetObject(pagePtr, i),
+ ),
+ );
+ return [...seen].filter((ptr) => !freed.has(ptr) && !onPage.has(ptr))
+ .length;
+ };
+}
+
+describe.each([
+ { where: "on the page", inForm: false },
+ { where: "inside a form", inForm: true },
+])("undoing and redoing a typed burst on text drawn $where", ({ inForm }) => {
+ it.each([
+ { edit: "typing before the text", steps: [`X ${START}`, `XY ${START}`] },
+ {
+ edit: "retyping inside a word",
+ steps: ["Open Sorce editor", "Open Sorrce editors"],
+ },
+ ])(
+ "keeps the same objects and the same page when $edit",
+ async ({ steps }) => {
+ const doc = await open(samplePdf(inForm));
+ const run = doc.page(0).runs.find((r) => r.text === START)!;
+ const history = new HistoryStack();
+ for (const nextText of steps)
+ history.execute(
+ new EditTextCommand({ pageIndex: 0, runId: run.id, nextText }),
+ doc,
+ );
+ const stranded = trackStranded(doc);
+
+ history.undo(doc);
+ const undone = pageLayout(doc);
+ history.redo(doc);
+ const redone = pageLayout(doc);
+ const redoneExport = await exportedText(doc);
+ const afterOneCycle = stranded();
+
+ for (let i = 0; i < 20; i++) {
+ history.undo(doc);
+ expect(pageLayout(doc)).toBe(undone);
+ history.redo(doc);
+ expect(pageLayout(doc)).toBe(redone);
+ }
+
+ expect(stranded()).toBeLessThanOrEqual(afterOneCycle);
+ expect(drawnText(doc).replace(/\s/g, "")).toBe(
+ steps.at(-1)!.replace(/\s/g, ""),
+ );
+ expect(await exportedText(doc)).toBe(redoneExport);
+ history.undo(doc);
+ expect(drawnText(doc).replace(/\s/g, "")).toBe(START.replace(/\s/g, ""));
+ },
+ );
+});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/partialRepaint.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/partialRepaint.test.ts
new file mode 100644
index 0000000000..79ff0a3e7a
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/partialRepaint.test.ts
@@ -0,0 +1,132 @@
+// @vitest-environment node
+import { readFile } from "node:fs/promises";
+import { createRequire } from "node:module";
+import path from "node:path";
+import {
+ afterAll,
+ afterEach,
+ beforeAll,
+ describe,
+ expect,
+ test,
+ vi,
+} from "vitest";
+import { EditTextCommand } from "@editor/tools/pdfTextEditor/commands/EditTextCommand";
+import { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
+import { PdfiumPageRenderer } from "@editor/tools/pdfTextEditor/pdfium/PdfiumPageRenderer";
+import { PdfiumTextReader } from "@editor/tools/pdfTextEditor/pdfium/PdfiumTextReader";
+import { EditorStore } from "@editor/tools/pdfTextEditor/store/EditorStore";
+import { differingPixels } from "@editor/tools/pdfTextEditor/__tests__/pageRaster";
+
+const FIXTURES = path.join(import.meta.dirname, "../../../tests/test-fixtures");
+const SCALE = 1.37;
+
+class TestImageData {
+ constructor(
+ readonly data: Uint8ClampedArray,
+ readonly width: number,
+ readonly height: number,
+ ) {}
+}
+
+const stores: EditorStore[] = [];
+
+beforeAll(async () => {
+ const wasmPath = createRequire(import.meta.url).resolve(
+ "@embedpdf/pdfium/pdfium.wasm",
+ );
+ const wasmBytes = await readFile(wasmPath);
+ vi.stubGlobal("ImageData", TestImageData);
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async () =>
+ Promise.resolve(
+ new Response(wasmBytes, {
+ headers: { "Content-Type": "application/wasm" },
+ }),
+ ),
+ ),
+ );
+});
+
+afterEach(() => {
+ for (const store of stores.splice(0)) store.dispose();
+});
+
+afterAll(() => {
+ vi.unstubAllGlobals();
+});
+
+async function open(fixture: string) {
+ const doc = await EditorDocument.open(
+ new Uint8Array(await readFile(path.join(FIXTURES, fixture))),
+ );
+ const store = new EditorStore();
+ stores.push(store);
+ await store.setDocument(doc);
+ const page = doc.page(0);
+ PdfiumTextReader.populate(doc, page);
+ return { doc, page, store };
+}
+
+function paste(onto: ImageData, area: ImageData, x: number, y: number) {
+ for (let row = 0; row < area.height; row++) {
+ const from = row * area.width * 4;
+ onto.data.set(
+ area.data.subarray(from, from + area.width * 4),
+ ((y + row) * onto.width + x) * 4,
+ );
+ }
+}
+
+describe("redrawing only the edited area", () => {
+ test.each([
+ ["a cropped page", "cropbox-offset.pdf", ["Hi there, Wj"]],
+ [
+ "a cropped page turned a quarter",
+ "cropbox-rotate90.pdf",
+ ["Hi there, Wj"],
+ ],
+ ["a line broken in three", "cropbox-offset.pdf", ["Hi\nthere\nWj"]],
+ [
+ "the last of three lines",
+ "cropbox-offset.pdf",
+ ["Hi\nthere\nWj", "Hi\nthere\nWj Qy"],
+ ],
+ ])("draws %s as a full render would", async (_case, fixture, texts) => {
+ const { doc, page, store } = await open(fixture);
+ const run = page.runs.find((r) => r.text === "Hi")!;
+ const edit = (nextText: string) =>
+ store.dispatch(
+ new EditTextCommand({ pageIndex: 0, runId: run.id, nextText }),
+ );
+ texts.slice(0, -1).forEach(edit);
+ const painted = page.revision;
+ const canvas = await PdfiumPageRenderer.render(doc, page, SCALE);
+
+ edit(texts[texts.length - 1]);
+ const area = PdfiumPageRenderer.pixelsCovering(
+ page,
+ SCALE,
+ page.repaintAreaSince(painted)!,
+ )!;
+ paste(
+ canvas,
+ await PdfiumPageRenderer.renderArea(doc, page, SCALE, area),
+ area.x,
+ area.y,
+ );
+
+ const full = await PdfiumPageRenderer.render(doc, page, SCALE);
+ expect(differingPixels(full, canvas)).toBe(0);
+ expect(differingPixels(full, await rendered(fixture))).toBeGreaterThan(0);
+ expect(area.width * area.height).toBeLessThan(
+ (full.width * full.height) / 2,
+ );
+ });
+});
+
+async function rendered(fixture: string): Promise<ImageData> {
+ const { doc, page } = await open(fixture);
+ return PdfiumPageRenderer.render(doc, page, SCALE);
+}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/partialRepaintScan.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/partialRepaintScan.test.ts
new file mode 100644
index 0000000000..b2458c80b6
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/partialRepaintScan.test.ts
@@ -0,0 +1,141 @@
+// @vitest-environment node
+import { readFile } from "node:fs/promises";
+import { createRequire } from "node:module";
+import {
+ afterAll,
+ afterEach,
+ beforeAll,
+ beforeEach,
+ describe,
+ expect,
+ test,
+ vi,
+} from "vitest";
+import { EditTextCommand } from "@editor/tools/pdfTextEditor/commands/EditTextCommand";
+import {
+ isScanRun,
+ prefitScanRun,
+} from "@editor/tools/pdfTextEditor/commands/scanTextEdit";
+import { PdfiumPageRenderer } from "@editor/tools/pdfTextEditor/pdfium/PdfiumPageRenderer";
+import { EditorStore } from "@editor/tools/pdfTextEditor/store/EditorStore";
+import {
+ _resetScanFacesForTests,
+ _setBundledScanFacesForTests,
+ type Face,
+} from "@editor/tools/pdfTextEditor/util/scanFontLibrary";
+import {
+ buildScan,
+ readBundledFaces,
+} from "@editor/tools/pdfTextEditor/__tests__/scanFixtures";
+import { differingPixels } from "@editor/tools/pdfTextEditor/__tests__/pageRaster";
+
+const { get } = vi.hoisted(() => ({ get: vi.fn() }));
+vi.mock("@editor/services/apiClient", () => ({ default: { get } }));
+
+const SCALE = 1.37;
+
+class TestImageData {
+ constructor(
+ readonly data: Uint8ClampedArray,
+ readonly width: number,
+ readonly height: number,
+ ) {}
+}
+
+let bundled: Face[] = [];
+const stores: EditorStore[] = [];
+
+beforeAll(async () => {
+ const wasmBytes = await readFile(
+ createRequire(import.meta.url).resolve("@embedpdf/pdfium/pdfium.wasm"),
+ );
+ vi.stubGlobal("ImageData", TestImageData);
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(
+ async () =>
+ new Response(wasmBytes, {
+ headers: { "Content-Type": "application/wasm" },
+ }),
+ ),
+ );
+ bundled = await readBundledFaces();
+});
+
+beforeEach(() => _setBundledScanFacesForTests(bundled));
+
+afterEach(() => {
+ for (const store of stores.splice(0)) store.dispose();
+});
+
+afterAll(() => {
+ _resetScanFacesForTests();
+ vi.unstubAllGlobals();
+});
+
+function paste(onto: ImageData, area: ImageData, x: number, y: number) {
+ for (let row = 0; row < area.height; row++) {
+ const from = row * area.width * 4;
+ onto.data.set(
+ area.data.subarray(from, from + area.width * 4),
+ ((y + row) * onto.width + x) * 4,
+ );
+ }
+}
+
+describe("redrawing only the edited area of scanned text", () => {
+ test.each([
+ ["the third line", ["\nmore", "\nmore\nthi", "\nmore\nthir"]],
+ ["the fourth line", ["\nmore\nthird\nfo", "\nmore\nthird\nfou"]],
+ ["several pasted lines", ["\nmore\nthird\nfourth"]],
+ ["a line taken away", ["\nmore\nthird", "\nmore"]],
+ ])(
+ "draws %s as a full render would",
+ { timeout: 120_000 },
+ async (_case, steps) => {
+ const { doc, page } = await buildScan(
+ [
+ {
+ family: "Carlito",
+ text: "Invoice 4471 for Jane Example",
+ size: 12,
+ },
+ ],
+ { dpi: 200, blur: 0.5, noise: 6 },
+ 260,
+ );
+ const store = new EditorStore();
+ stores.push(store);
+ await store.setDocument(doc);
+ const run = page.runs.find(isScanRun)!;
+ while (!prefitScanRun(doc, page, run, performance.now() + 50))
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ const base = run.text;
+ const edit = (suffix: string) =>
+ store.dispatch(
+ new EditTextCommand({
+ pageIndex: 0,
+ runId: run.id,
+ nextText: base + suffix,
+ }),
+ );
+ steps.slice(0, -1).forEach(edit);
+ const painted = page.revision;
+ const canvas = await PdfiumPageRenderer.render(doc, page, SCALE);
+
+ edit(steps[steps.length - 1]);
+ const raw = page.repaintAreaSince(painted);
+ const area = raw && PdfiumPageRenderer.pixelsCovering(page, SCALE, raw);
+ if (area)
+ paste(
+ canvas,
+ await PdfiumPageRenderer.renderArea(doc, page, SCALE, area),
+ area.x,
+ area.y,
+ );
+
+ const full = await PdfiumPageRenderer.render(doc, page, SCALE);
+ expect(differingPixels(full, canvas)).toBe(0);
+ },
+ );
+});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/readOnlyTextCommands.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/readOnlyTextCommands.test.ts
new file mode 100644
index 0000000000..623648b5b3
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/readOnlyTextCommands.test.ts
@@ -0,0 +1,291 @@
+// @vitest-environment node
+import { readFile } from "node:fs/promises";
+import { createRequire } from "node:module";
+import path from "node:path";
+import {
+ afterAll,
+ afterEach,
+ beforeAll,
+ describe,
+ expect,
+ test,
+ vi,
+} from "vitest";
+import { AlignParagraphLinesCommand } from "@editor/tools/pdfTextEditor/commands/AlignParagraphLinesCommand";
+import type { Command } from "@editor/tools/pdfTextEditor/commands/Command";
+import { CompositeCommand } from "@editor/tools/pdfTextEditor/commands/CompositeCommand";
+import { DeleteObjectCommand } from "@editor/tools/pdfTextEditor/commands/DeleteObjectCommand";
+import { DuplicateRunCommand } from "@editor/tools/pdfTextEditor/commands/DuplicateRunCommand";
+import { MergeRunsCommand } from "@editor/tools/pdfTextEditor/commands/MergeRunsCommand";
+import { MoveTextRunCommand } from "@editor/tools/pdfTextEditor/commands/MoveTextRunCommand";
+import { ReflowWrapCommand } from "@editor/tools/pdfTextEditor/commands/ReflowWrapCommand";
+import { SetColourCommand } from "@editor/tools/pdfTextEditor/commands/SetColourCommand";
+import { SetFontFamilyCommand } from "@editor/tools/pdfTextEditor/commands/SetFontFamilyCommand";
+import { SetFontSizeCommand } from "@editor/tools/pdfTextEditor/commands/SetFontSizeCommand";
+import { SetTextOutlineCommand } from "@editor/tools/pdfTextEditor/commands/SetTextOutlineCommand";
+import { UngroupParagraphCommand } from "@editor/tools/pdfTextEditor/commands/UngroupParagraphCommand";
+import { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
+import type { TextRun } from "@editor/tools/pdfTextEditor/model/TextRun";
+import { PdfiumTextReader } from "@editor/tools/pdfTextEditor/pdfium/PdfiumTextReader";
+import { HistoryStack } from "@editor/tools/pdfTextEditor/store/HistoryStack";
+
+const SAMPLE = path.join(
+ import.meta.dirname,
+ "../../../tests/test-fixtures/rtl-mixed-sample.pdf",
+);
+const READ_ONLY = "ISO 50001 هو المعيار";
+const ENGLISH =
+ "An English line quoting مرحبا بالعالم and שלום עולם then 1,234.";
+const HEBREW =
+ "הטלפון הוא 03-555-1234 (שלוחה 12), והמחיר 1,299.90 לפי Open Source סעיף 4.";
+const RED = { r: 255, g: 0, b: 0, a: 255 };
+
+const opened: EditorDocument[] = [];
+
+beforeAll(async () => {
+ const wasm = await readFile(
+ createRequire(import.meta.url).resolve("@embedpdf/pdfium/pdfium.wasm"),
+ );
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async (url: string) =>
+ String(url).endsWith(".wasm")
+ ? new Response(wasm, {
+ headers: { "Content-Type": "application/wasm" },
+ })
+ : new Response(null, { status: 404 }),
+ ),
+ );
+});
+
+afterEach(() => {
+ for (const doc of opened.splice(0)) doc.dispose();
+});
+
+afterAll(() => vi.unstubAllGlobals());
+
+async function open(): Promise<EditorDocument> {
+ const doc = await EditorDocument.open(new Uint8Array(await readFile(SAMPLE)));
+ opened.push(doc);
+ PdfiumTextReader.populate(doc, doc.page(0));
+ return doc;
+}
+
+const lineOf = (doc: EditorDocument, text: string): TextRun =>
+ doc.page(0).runs.find((run) => run.text === text)!;
+
+// Every object the page draws, in content order, with where and how it is drawn.
+function pageObjects(doc: EditorDocument): string[] {
+ const m = doc.module;
+ const pagePtr = doc.page(0).pagePtr;
+ const buf = m.pdfium.wasmExports.malloc(24);
+ const drawn: string[] = [];
+ try {
+ for (let i = 0; i < m.FPDFPage_CountObjects(pagePtr); i++) {
+ const obj = m.FPDFPage_GetObject(pagePtr, i);
+ m.FPDFPageObj_GetMatrix(obj, buf);
+ const matrix = [0, 4, 8, 12, 16, 20].map((at) =>
+ m.pdfium.getValue(buf + at, "float").toFixed(3),
+ );
+ m.FPDFPageObj_GetFillColor(obj, buf, buf + 4, buf + 8, buf + 12);
+ const fill = [0, 4, 8, 12].map((at) =>
+ m.pdfium.getValue(buf + at, "i32"),
+ );
+ m.FPDFPageObj_GetStrokeColor(obj, buf, buf + 4, buf + 8, buf + 12);
+ const stroke = [0, 4, 8, 12].map((at) =>
+ m.pdfium.getValue(buf + at, "i32"),
+ );
+ drawn.push(`${obj} ${matrix} fill ${fill} stroke ${stroke}`);
+ }
+ } finally {
+ m.pdfium.wasmExports.free(buf);
+ }
+ return drawn;
+}
+
+const model = (doc: EditorDocument) =>
+ doc.page(0).runs.map((run) => run.snapshot());
+
+type Build = (run: TextRun, doc: EditorDocument) => Command;
+
+const REDRAWS: Array<[string, Build]> = [
+ [
+ "a font family",
+ (run) =>
+ new SetFontFamilyCommand({
+ pageIndex: 0,
+ runId: run.id,
+ nextFamily: "Times-Roman",
+ }),
+ ],
+ [
+ "a font size",
+ (run) =>
+ new SetFontSizeCommand({ pageIndex: 0, runId: run.id, nextSize: 14 }),
+ ],
+ [
+ "a duplicate",
+ (run) => new DuplicateRunCommand({ pageIndex: 0, runId: run.id }),
+ ],
+ [
+ "an outline",
+ (run) =>
+ new SetTextOutlineCommand({
+ pageIndex: 0,
+ runId: run.id,
+ stroke: RED,
+ width: 1,
+ }),
+ ],
+ [
+ "a wrap width",
+ (run) =>
+ new ReflowWrapCommand({
+ pageIndex: 0,
+ runId: run.id,
+ maxWidthPt: 60,
+ explicit: true,
+ }),
+ ],
+ [
+ "a merge with another line",
+ (run, doc) =>
+ new MergeRunsCommand({
+ pageIndex: 0,
+ runIds: [lineOf(doc, ENGLISH).id, run.id],
+ }),
+ ],
+ [
+ "a batch holding a font size",
+ (run, doc) =>
+ new CompositeCommand([
+ new SetFontSizeCommand({
+ pageIndex: 0,
+ runId: lineOf(doc, ENGLISH).id,
+ nextSize: 14,
+ }),
+ new SetFontSizeCommand({ pageIndex: 0, runId: run.id, nextSize: 14 }),
+ ]),
+ ],
+];
+
+describe("a line the editor cannot redraw as it is drawn", () => {
+ test.each(REDRAWS)("is left as it is by %s", async (_name, build) => {
+ const doc = await open();
+ const history = new HistoryStack();
+ const run = lineOf(doc, READ_ONLY);
+ expect(run.textReadOnly).toBe(true);
+ const objects = pageObjects(doc);
+ const runs = model(doc);
+
+ expect(() => history.execute(build(run, doc), doc)).toThrow(
+ expect.objectContaining({ documentIntact: true }),
+ );
+
+ expect(pageObjects(doc)).toEqual(objects);
+ expect(model(doc)).toEqual(runs);
+ expect(history.canUndo).toBe(false);
+ });
+
+ test("is refused a duplicate before any copy is drawn", async () => {
+ const doc = await open();
+ const run = lineOf(doc, READ_ONLY);
+ const inserted = vi.spyOn(doc.module, "FPDFPage_InsertObject");
+
+ expect(() =>
+ new HistoryStack().execute(
+ new DuplicateRunCommand({ pageIndex: 0, runId: run.id }),
+ doc,
+ ),
+ ).toThrow(expect.objectContaining({ documentIntact: true }));
+
+ expect(inserted).not.toHaveBeenCalled();
+ });
+
+ test("is left as it is by line alignment of the paragraph holding it", async () => {
+ const doc = await open();
+ const history = new HistoryStack();
+ const merge = new MergeRunsCommand({
+ pageIndex: 0,
+ runIds: [lineOf(doc, HEBREW).id, lineOf(doc, ENGLISH).id],
+ });
+ history.execute(merge, doc);
+ const paragraph = doc.page(0).findRun(merge.representativeRunId!)!;
+ paragraph.readingOrderUnsure = true;
+ const objects = pageObjects(doc);
+ const runs = model(doc);
+
+ expect(() =>
+ history.execute(
+ new AlignParagraphLinesCommand({
+ pageIndex: 0,
+ runId: paragraph.id,
+ mode: "right",
+ }),
+ doc,
+ ),
+ ).toThrow(expect.objectContaining({ documentIntact: true }));
+
+ expect(pageObjects(doc)).toEqual(objects);
+ expect(model(doc)).toEqual(runs);
+ expect(history.size().undo).toBe(1);
+ });
+
+ test("stays read-only on every line its paragraph is split into", async () => {
+ const doc = await open();
+ const history = new HistoryStack();
+ const merge = new MergeRunsCommand({
+ pageIndex: 0,
+ runIds: [lineOf(doc, HEBREW).id, lineOf(doc, ENGLISH).id],
+ });
+ history.execute(merge, doc);
+ const paragraph = doc.page(0).findRun(merge.representativeRunId!)!;
+ paragraph.readingOrderUnsure = true;
+
+ const split = new UngroupParagraphCommand({
+ pageIndex: 0,
+ runId: paragraph.id,
+ });
+ history.execute(split, doc);
+
+ // The first line stays on the paragraph's own run.
+ const lines = [
+ paragraph,
+ ...split.resultRunIds.slice(1).map((id) => doc.page(0).findRun(id)!),
+ ];
+ expect(lines.map((line) => line.text)).toEqual([HEBREW, ENGLISH]);
+ expect(lines.map((line) => line.textReadOnly)).toEqual([true, true]);
+ });
+
+ test("can still be moved, recoloured and deleted, and each is undone", async () => {
+ const doc = await open();
+ const history = new HistoryStack();
+ const run = lineOf(doc, READ_ONLY);
+ const objects = pageObjects(doc);
+ const runs = model(doc);
+ const x = run.bounds.x;
+
+ history.execute(
+ new MoveTextRunCommand({ pageIndex: 0, runId: run.id, dx: 20, dy: -5 }),
+ doc,
+ );
+ expect(run.bounds.x).toBeCloseTo(x + 20);
+ history.execute(
+ new SetColourCommand({ pageIndex: 0, runId: run.id, nextFill: RED }),
+ doc,
+ );
+ expect(run.fill).toEqual(RED);
+ history.execute(
+ new DeleteObjectCommand({ pageIndex: 0, runId: run.id }),
+ doc,
+ );
+ expect(doc.page(0).findRun(run.id)).toBeUndefined();
+ expect(pageObjects(doc).length).toBeLessThan(objects.length);
+
+ while (history.canUndo) history.undo(doc);
+
+ // An undone delete draws the line's objects last on the page, so only what is drawn is compared.
+ expect(pageObjects(doc).sort()).toEqual([...objects].sort());
+ expect(model(doc)).toEqual(runs);
+ });
+});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/reflowBelow.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/reflowBelow.test.ts
new file mode 100644
index 0000000000..cbdbff66e0
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/reflowBelow.test.ts
@@ -0,0 +1,311 @@
+// @vitest-environment node
+import { readFile } from "node:fs/promises";
+import { createRequire } from "node:module";
+import path from "node:path";
+import { afterAll, afterEach, beforeAll, expect, test, vi } from "vitest";
+import { EditTextCommand } from "@editor/tools/pdfTextEditor/commands/EditTextCommand";
+import {
+ collectMemberPtrs,
+ measureObjBoundsPt,
+} from "@editor/tools/pdfTextEditor/commands/editTextHelpers";
+import { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
+import { PdfiumTextReader } from "@editor/tools/pdfTextEditor/pdfium/PdfiumTextReader";
+import { HistoryStack } from "@editor/tools/pdfTextEditor/store/HistoryStack";
+
+const SAMPLE = path.join(
+ import.meta.dirname,
+ "../../../tests/test-fixtures/paragraph-sample.pdf",
+);
+const HEADING = "Heading in a bigger size";
+const TWO_BREAKS = "Heading in\n\na bigger size";
+const LINE_ONE = "Subset font sample line one";
+
+const opened: EditorDocument[] = [];
+
+beforeAll(async () => {
+ const wasm = await readFile(
+ createRequire(import.meta.url).resolve("@embedpdf/pdfium/pdfium.wasm"),
+ );
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(
+ async () =>
+ new Response(wasm, { headers: { "Content-Type": "application/wasm" } }),
+ ),
+ );
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ for (const doc of opened.splice(0)) doc.dispose();
+});
+
+afterAll(() => vi.unstubAllGlobals());
+
+async function open() {
+ const doc = await EditorDocument.open(new Uint8Array(await readFile(SAMPLE)));
+ opened.push(doc);
+ const page = doc.page(0);
+ PdfiumTextReader.populate(doc, page);
+ const heading = page.runs.find((r) => r.text === HEADING)!;
+ const body = page.runs.find((r) => r !== heading)!;
+ const bodyInk = () =>
+ measureObjBoundsPt(doc.module, collectMemberPtrs(body))!.top;
+ return { doc, heading, body, bodyInk, startTop: bodyInk() };
+}
+
+function type(
+ doc: EditorDocument,
+ history: HistoryStack,
+ runId: string,
+ texts: string[],
+) {
+ for (const nextText of texts)
+ history.execute(
+ new EditTextCommand({ pageIndex: 0, runId, nextText }),
+ doc,
+ );
+}
+
+test("a line break the space below can take leaves the next paragraph where it is", async () => {
+ const { doc, heading, bodyInk, startTop } = await open();
+
+ type(doc, new HistoryStack(), heading.id, ["Heading in\na bigger size"]);
+
+ expect(bodyInk()).toBeCloseTo(startTop, 3);
+});
+
+test("moves the next paragraph down by the lines added over it", async () => {
+ const { doc, heading, body, bodyInk, startTop } = await open();
+ const bodyY = body.bounds.y;
+ const headingBottom = heading.bounds.y;
+
+ type(doc, new HistoryStack(), heading.id, [TWO_BREAKS]);
+
+ const drop = headingBottom - heading.bounds.y;
+ expect(drop).toBeGreaterThan(30);
+ expect(bodyInk()).toBeCloseTo(startTop - drop, 3);
+ expect(body.bounds.y).toBeCloseTo(bodyY - drop, 3);
+ expect(bodyInk()).toBeLessThan(heading.bounds.y);
+});
+
+test.each([
+ ["the line break alone", [TWO_BREAKS]],
+ ["a line break then typing", [TWO_BREAKS, "Heading in\n\nXa bigger size"]],
+ [
+ "typing then a line break",
+ ["Xk Heading in a bigger size", "Xk Heading in\n\na bigger size"],
+ ],
+ ["a line break then deleting", [TWO_BREAKS, "Heading in\n\na bigger"]],
+ [
+ "words typed around a line break",
+ [
+ `${HEADING} Zq7`,
+ `Xk ${HEADING} Zq7`,
+ "Xk Heading Wj9 in a bigger size Zq7",
+ "Xk Heading Wj9 ina bigger size Zq7",
+ "Xk Heading Wj9 ina\n\nbigger size Zq7",
+ ],
+ ],
+])(
+ "undo puts the paragraph back and redo moves it once, after %s",
+ async (_case, texts) => {
+ const { doc, heading, body, bodyInk, startTop } = await open();
+ const bodyY = body.bounds.y;
+ const history = new HistoryStack();
+
+ type(doc, history, heading.id, texts);
+ expect(history.size().undo).toBe(1);
+ const pushedTop = bodyInk();
+
+ history.undo(doc);
+ expect(heading.text).toBe(HEADING);
+ expect(bodyInk()).toBeCloseTo(startTop, 3);
+ expect(body.bounds.y).toBeCloseTo(bodyY, 3);
+
+ history.redo(doc);
+ expect(bodyInk()).toBeCloseTo(pushedTop, 3);
+
+ history.undo(doc);
+ history.redo(doc);
+ expect(bodyInk()).toBeCloseTo(pushedTop, 3);
+ },
+);
+
+test.each([
+ ["in one burst", false],
+ ["as separate steps", true],
+])(
+ "deleting the added lines brings the paragraph back up, %s",
+ async (_case, separate) => {
+ const { doc, heading, bodyInk, startTop } = await open();
+ const history = new HistoryStack();
+
+ type(doc, history, heading.id, [TWO_BREAKS]);
+ const pushedTop = bodyInk();
+ if (separate) history.breakCoalescing();
+ type(doc, history, heading.id, ["Heading in\na bigger size", HEADING]);
+ expect(bodyInk()).toBeCloseTo(startTop, 3);
+
+ history.undo(doc);
+ if (separate) expect(bodyInk()).toBeCloseTo(pushedTop, 3);
+ else expect(bodyInk()).toBeCloseTo(startTop, 3);
+ history.redo(doc);
+ expect(bodyInk()).toBeCloseTo(startTop, 3);
+ },
+);
+
+test("deleting blank lines added after the text brings the paragraph back up", async () => {
+ const { doc, heading, bodyInk, startTop } = await open();
+ const history = new HistoryStack();
+
+ type(doc, history, heading.id, [`${HEADING}\n\n`]);
+ expect(bodyInk()).toBeLessThan(startTop - 30);
+ type(doc, history, heading.id, [HEADING]);
+
+ expect(bodyInk()).toBeCloseTo(startTop, 3);
+});
+
+test("line breaks in the document's own paragraph move the text below by their height, and joining them brings it back", async () => {
+ const doc = await EditorDocument.open(
+ new Uint8Array(
+ await readFile(
+ path.join(
+ import.meta.dirname,
+ "../../../tests/test-fixtures/mixed-style-sample.pdf",
+ ),
+ ),
+ ),
+ );
+ opened.push(doc);
+ PdfiumTextReader.populate(doc, doc.page(0));
+ const [paragraph, below] = doc.page(0).runs;
+ const startY = below.bounds.y;
+ const original = paragraph.text;
+ const history = new HistoryStack();
+ const breaks = 7;
+
+ type(doc, history, paragraph.id, [
+ original.replace(" ", " " + "\n".repeat(breaks)),
+ ]);
+ // The box an edit gives the paragraph is not the one the document's text measured to; the lines are what moved.
+ expect(startY - below.bounds.y).toBeCloseTo(
+ breaks * paragraph.paragraphLineHeight,
+ 3,
+ );
+
+ history.breakCoalescing();
+ type(doc, history, paragraph.id, [original]);
+ expect(below.bounds.y).toBeCloseTo(startY, 3);
+});
+
+test.each([
+ ["both at once", [HEADING]],
+ ["one at a time", ["Heading in\na bigger size", HEADING]],
+])(
+ "a paragraph comes all the way back when the added lines go, %s, whatever the line height is by then",
+ async (_case, back) => {
+ const { doc, heading, bodyInk, startTop } = await open();
+ const history = new HistoryStack();
+
+ type(doc, history, heading.id, [TWO_BREAKS]);
+ expect(bodyInk()).toBeLessThan(startTop - 30);
+ history.breakCoalescing();
+ heading.paragraphLineHeight *= 0.8;
+ type(doc, history, heading.id, back);
+
+ expect(bodyInk()).toBeCloseTo(startTop, 3);
+ },
+);
+
+test("leaves a pushed paragraph where it is once it has been locked", async () => {
+ const { doc, heading, body, bodyInk } = await open();
+ const history = new HistoryStack();
+ type(doc, history, heading.id, [TWO_BREAKS]);
+ const pushedTop = bodyInk();
+ body.locked = true;
+
+ type(doc, history, heading.id, [HEADING]);
+
+ expect(bodyInk()).toBeCloseTo(pushedTop, 3);
+});
+
+test("joining the document's own lines leaves the text below where it is", async () => {
+ const doc = await EditorDocument.open(
+ new Uint8Array(
+ await readFile(
+ path.join(
+ import.meta.dirname,
+ "../../../tests/test-fixtures/mixed-style-sample.pdf",
+ ),
+ ),
+ ),
+ );
+ opened.push(doc);
+ PdfiumTextReader.populate(doc, doc.page(0));
+ const [paragraph, ...rest] = doc.page(0).runs;
+ const below = rest.map((run) => run.bounds.y);
+
+ type(doc, new HistoryStack(), paragraph.id, [
+ paragraph.text.replaceAll("\n", " "),
+ ]);
+
+ expect(rest.map((run) => run.bounds.y)).toEqual(below);
+});
+
+test("moves nothing when the paragraph below is locked", async () => {
+ const { doc, heading, body, bodyInk, startTop } = await open();
+ body.locked = true;
+
+ type(doc, new HistoryStack(), heading.id, [TWO_BREAKS]);
+
+ expect(bodyInk()).toBeCloseTo(startTop, 3);
+});
+
+test.each([
+ ["step by step", false],
+ ["as one redraw of the whole burst", true],
+])(
+ "undo of a burst in a fallback font puts the lines below back, %s",
+ async (_route, wholeBurst) => {
+ if (wholeBurst)
+ vi.spyOn(
+ EditTextCommand.prototype as unknown as { revertsExactly(): boolean },
+ "revertsExactly",
+ ).mockReturnValue(false);
+ const doc = await EditorDocument.open(
+ new Uint8Array(
+ await readFile(
+ path.join(
+ import.meta.dirname,
+ "../../../tests/test-fixtures/subset-font-sample.pdf",
+ ),
+ ),
+ ),
+ );
+ opened.push(doc);
+ PdfiumTextReader.populate(doc, doc.page(0));
+ const [first, second, third] = doc.page(0).runs;
+ const ink = (run: typeof first) =>
+ measureObjBoundsPt(doc.module, collectMemberPtrs(run))!.top;
+ const [secondTop, thirdTop] = [ink(second), ink(third)];
+ const history = new HistoryStack();
+
+ type(doc, history, first.id, [`${LINE_ONE}Z`, `${LINE_ONE}Z\nmore`]);
+ const pushedTop = ink(second);
+ expect(pushedTop).toBeLessThan(secondTop - 10);
+ expect(ink(third)).toBeCloseTo(thirdTop - (secondTop - pushedTop), 3);
+
+ history.undo(doc);
+ expect(ink(second)).toBeCloseTo(secondTop, 3);
+ expect(ink(third)).toBeCloseTo(thirdTop, 3);
+
+ history.redo(doc);
+ expect(ink(second)).toBeCloseTo(pushedTop, 3);
+
+ history.undo(doc);
+ history.redo(doc);
+ expect(ink(second)).toBeCloseTo(pushedTop, 3);
+ expect(first.text).toBe(`${LINE_ONE}Z\nmore`);
+ },
+);
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/reflowKeepsReadingOrder.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/reflowKeepsReadingOrder.test.ts
new file mode 100644
index 0000000000..925273a740
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/reflowKeepsReadingOrder.test.ts
@@ -0,0 +1,95 @@
+// @vitest-environment node
+import { readFile } from "node:fs/promises";
+import { createRequire } from "node:module";
+import path from "node:path";
+import { afterAll, afterEach, beforeAll, expect, test, vi } from "vitest";
+import { EditTextCommand } from "@editor/tools/pdfTextEditor/commands/EditTextCommand";
+import { ReflowWrapCommand } from "@editor/tools/pdfTextEditor/commands/ReflowWrapCommand";
+import { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
+import { PdfiumTextReader } from "@editor/tools/pdfTextEditor/pdfium/PdfiumTextReader";
+import { HistoryStack } from "@editor/tools/pdfTextEditor/store/HistoryStack";
+
+const FIXTURES = path.join(import.meta.dirname, "../../../tests/test-fixtures");
+const TYPED = " Pasted words here quick brown foxes jump";
+
+const opened: EditorDocument[] = [];
+
+beforeAll(async () => {
+ const wasm = await readFile(
+ createRequire(import.meta.url).resolve("@embedpdf/pdfium/pdfium.wasm"),
+ );
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async (url: string) =>
+ String(url).endsWith(".wasm")
+ ? new Response(wasm, {
+ headers: { "Content-Type": "application/wasm" },
+ })
+ : new Response(null, { status: 404 }),
+ ),
+ );
+});
+
+afterEach(() => {
+ for (const doc of opened.splice(0)) doc.dispose();
+});
+
+afterAll(() => vi.unstubAllGlobals());
+
+const squash = (s: string) => s.replace(/\s+/g, "");
+
+async function lineIn(file: string, index: number) {
+ const doc = await EditorDocument.open(
+ new Uint8Array(await readFile(path.join(FIXTURES, file))),
+ );
+ opened.push(doc);
+ PdfiumTextReader.populate(doc, doc.page(0));
+ return { doc, run: doc.page(0).runs[index] };
+}
+
+// The reflow lays a line's objects out left to right, which is the reverse of
+// how a right-to-left line reads, and splits a shaped cluster wherever its
+// marks sit apart from their base. The run's text must still read as typed.
+test.each([
+ ["rtl-sample.pdf", 0],
+ ["rtl-mixed-sample.pdf", 0],
+ ["rtl-mixed-sample.pdf", 2],
+ ["rtl-marks-sample.pdf", 0],
+ ["rtl-marks-sample.pdf", 1],
+ ["shaped-line-sample.pdf", 0],
+ ["thai-line-sample.pdf", 0],
+])(
+ "wrapping typed line %s #%i keeps its letters in reading order",
+ async (file, index) => {
+ const { doc, run } = await lineIn(file, index);
+ const original = run.text;
+ const history = new HistoryStack();
+ const typed = original + TYPED;
+ history.execute(
+ new EditTextCommand({ pageIndex: 0, runId: run.id, nextText: typed }),
+ doc,
+ );
+ history.execute(
+ new ReflowWrapCommand({ pageIndex: 0, runId: run.id, maxWidthPt: 90 }),
+ doc,
+ );
+ expect(squash(run.text)).toBe(squash(typed));
+ history.undo(doc);
+ expect(run.text).toBe(original);
+ },
+);
+
+// Once wrapped, an edit to a line of a shaping script redraws the letters left
+// on that line from code points, which the edit refuses, so wrapping it would
+// leave every later deletion on its first line refused.
+test("typing past the box edge leaves a line that needs shaping unwrapped", async () => {
+ const { doc, run } = await lineIn("shaped-line-sample.pdf", 0);
+ const typed = run.text + TYPED;
+ new EditTextCommand({ pageIndex: 0, runId: run.id, nextText: typed }).apply(
+ doc,
+ );
+ new ReflowWrapCommand({ pageIndex: 0, runId: run.id, maxWidthPt: 90 }).apply(
+ doc,
+ );
+ expect(run.text).toBe(typed);
+});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/reflowKeepsTypedText.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/reflowKeepsTypedText.test.ts
new file mode 100644
index 0000000000..ccf13e0905
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/reflowKeepsTypedText.test.ts
@@ -0,0 +1,76 @@
+// @vitest-environment node
+import { readFile } from "node:fs/promises";
+import { createRequire } from "node:module";
+import path from "node:path";
+import { afterAll, afterEach, beforeAll, expect, test, vi } from "vitest";
+import { EditTextCommand } from "@editor/tools/pdfTextEditor/commands/EditTextCommand";
+import { ReflowWrapCommand } from "@editor/tools/pdfTextEditor/commands/ReflowWrapCommand";
+import { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
+import { PdfiumTextReader } from "@editor/tools/pdfTextEditor/pdfium/PdfiumTextReader";
+import { HistoryStack } from "@editor/tools/pdfTextEditor/store/HistoryStack";
+
+const SAMPLE = path.join(
+ import.meta.dirname,
+ "../../../tests/test-fixtures/paragraph-sample.pdf",
+);
+const HEADING = "Heading in a bigger size";
+
+const opened: EditorDocument[] = [];
+
+beforeAll(async () => {
+ const wasm = await readFile(
+ createRequire(import.meta.url).resolve("@embedpdf/pdfium/pdfium.wasm"),
+ );
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(
+ async () =>
+ new Response(wasm, { headers: { "Content-Type": "application/wasm" } }),
+ ),
+ );
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ for (const doc of opened.splice(0)) doc.dispose();
+});
+
+afterAll(() => vi.unstubAllGlobals());
+
+async function open() {
+ const doc = await EditorDocument.open(new Uint8Array(await readFile(SAMPLE)));
+ opened.push(doc);
+ const page = doc.page(0);
+ PdfiumTextReader.populate(doc, page);
+ const heading = page.runs.find((r) => r.text === HEADING)!;
+ return { doc, heading };
+}
+
+// The overlay asks for a wrap on every keystroke that leaves a line past the
+// box edge, so a reflow runs between keystrokes on a run it has already
+// reflowed. Each one rebuilds the run's text from its objects.
+test("a reflow between keystrokes keeps every letter typed since the last one", async () => {
+ const { doc, heading } = await open();
+ const history = new HistoryStack();
+ let typed = HEADING;
+ for (const ch of "gggggg") {
+ typed += ch;
+ history.execute(
+ new EditTextCommand({ pageIndex: 0, runId: heading.id, nextText: typed }),
+ doc,
+ );
+ history.execute(
+ new ReflowWrapCommand({
+ pageIndex: 0,
+ runId: heading.id,
+ maxWidthPt: 150,
+ }),
+ doc,
+ );
+ expect(heading.text.replace(/\s+/g, " ")).toBe(typed);
+ }
+ history.undo(doc);
+ expect(heading.text).toBe(HEADING);
+ history.redo(doc);
+ expect(heading.text.replace(/\s+/g, " ")).toBe(typed);
+});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/reflowRoundTrip.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/reflowRoundTrip.test.ts
new file mode 100644
index 0000000000..635476d76f
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/reflowRoundTrip.test.ts
@@ -0,0 +1,208 @@
+// @vitest-environment node
+import { readFile } from "node:fs/promises";
+import { createRequire } from "node:module";
+import path from "node:path";
+import { afterAll, afterEach, beforeAll, expect, test, vi } from "vitest";
+import { EditTextCommand } from "@editor/tools/pdfTextEditor/commands/EditTextCommand";
+import { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
+import type { TextRun } from "@editor/tools/pdfTextEditor/model/TextRun";
+import { PdfiumTextReader } from "@editor/tools/pdfTextEditor/pdfium/PdfiumTextReader";
+import { HistoryStack } from "@editor/tools/pdfTextEditor/store/HistoryStack";
+
+const FIXTURES = path.join(import.meta.dirname, "../../../tests/test-fixtures");
+const FILES = [
+ "paragraph-sample.pdf",
+ "mixed-style-sample.pdf",
+ "justified-sample.pdf",
+ "letter-spacing-sample.pdf",
+ "multi-page-sample.pdf",
+ "mushroom-life.pdf",
+ "form-xobject-sample.pdf",
+ "link-annotations-sample.pdf",
+];
+
+const opened: EditorDocument[] = [];
+
+beforeAll(async () => {
+ const wasm = await readFile(
+ createRequire(import.meta.url).resolve("@embedpdf/pdfium/pdfium.wasm"),
+ );
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(
+ async () =>
+ new Response(wasm, { headers: { "Content-Type": "application/wasm" } }),
+ ),
+ );
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ for (const doc of opened.splice(0)) doc.dispose();
+});
+
+afterAll(() => vi.unstubAllGlobals());
+
+async function open(file: string) {
+ const doc = await EditorDocument.open(
+ new Uint8Array(await readFile(path.join(FIXTURES, file))),
+ );
+ opened.push(doc);
+ PdfiumTextReader.populate(doc, doc.page(0));
+ return doc;
+}
+
+// Break after the middle word of the first line, as Enter there would.
+function withBreaks(text: string, breaks: number): string {
+ const line = text.split("\n")[0];
+ const at = line.indexOf(" ", Math.floor(line.length / 2)) + 1 || line.length;
+ return text.slice(0, at) + "\n".repeat(breaks) + text.slice(at);
+}
+
+const editable = (run: TextRun) =>
+ !run.locked && run.renderMode !== 3 && run.text.trim().length >= 4;
+
+function others(doc: EditorDocument, edited: TextRun): string {
+ return doc
+ .page(0)
+ .runs.filter((r) => r !== edited)
+ .map((r) => `${r.id} ${r.bounds.x.toFixed(2)} ${r.bounds.y.toFixed(2)}`)
+ .join("\n");
+}
+
+function type(
+ doc: EditorDocument,
+ history: HistoryStack,
+ run: TextRun,
+ text: string,
+) {
+ history.execute(
+ new EditTextCommand({ pageIndex: 0, runId: run.id, nextText: text }),
+ doc,
+ );
+ history.breakCoalescing();
+}
+
+test.each(FILES)(
+ "in %s, taking added lines away leaves every other line where that many fewer Enters would have put it",
+ async (file) => {
+ const count = (await open(file)).page(0).runs.filter(editable).length;
+ for (let index = 0; index < Math.min(count, 8); index++) {
+ const once = await open(file);
+ const onceRun = once.page(0).runs.filter(editable)[index];
+ const original = onceRun.text;
+ const start = others(once, onceRun);
+ type(once, new HistoryStack(), onceRun, withBreaks(original, 1));
+ const afterOne = others(once, onceRun);
+
+ const doc = await open(file);
+ const run = doc.page(0).runs.filter(editable)[index];
+ const history = new HistoryStack();
+ type(doc, history, run, withBreaks(original, 1));
+ type(doc, history, run, withBreaks(original, 2));
+ type(doc, history, run, withBreaks(original, 3));
+ type(doc, history, run, withBreaks(original, 1));
+ expect(others(doc, run), `${file} run ${index} back to one`).toBe(
+ afterOne,
+ );
+ type(doc, history, run, original);
+ expect(others(doc, run), `${file} run ${index} back to none`).toBe(start);
+
+ while (history.size().undo > 0) history.undo(doc);
+ expect(others(doc, run), `${file} run ${index} undone`).toBe(start);
+ while (history.size().redo > 0) history.redo(doc);
+ expect(others(doc, run), `${file} run ${index} redone`).toBe(start);
+ }
+ },
+);
+
+test.each(FILES)(
+ "in %s, a burst of added and removed lines undoes and redoes as one step that is replayed whole",
+ async (file) => {
+ vi.spyOn(
+ EditTextCommand.prototype as unknown as { revertsExactly(): boolean },
+ "revertsExactly",
+ ).mockReturnValue(false);
+ const count = (await open(file)).page(0).runs.filter(editable).length;
+ for (let index = 0; index < Math.min(count, 4); index++) {
+ const doc = await open(file);
+ const run = doc.page(0).runs.filter(editable)[index];
+ const original = run.text;
+ const start = others(doc, run);
+ const history = new HistoryStack();
+ for (const breaks of [1, 2, 3, 1])
+ history.execute(
+ new EditTextCommand({
+ pageIndex: 0,
+ runId: run.id,
+ nextText: withBreaks(original, breaks),
+ }),
+ doc,
+ );
+ expect(history.size().undo).toBe(1);
+ const typed = others(doc, run);
+
+ history.undo(doc);
+ expect(others(doc, run), `${file} run ${index} undone`).toBe(start);
+ history.redo(doc);
+ expect(others(doc, run), `${file} run ${index} redone`).toBe(typed);
+
+ history.breakCoalescing();
+ type(doc, history, run, original);
+ expect(others(doc, run), `${file} run ${index} cleared`).toBe(start);
+ }
+ },
+);
+
+// How much of their height two runs share, where they share any width.
+function shared(a: TextRun, ay: number, b: TextRun): number {
+ if (
+ a.bounds.x >= b.bounds.x + b.bounds.width - 0.5 ||
+ a.bounds.x + a.bounds.width <= b.bounds.x + 0.5
+ )
+ return 0;
+ return Math.max(
+ 0,
+ Math.min(ay + a.bounds.height, b.bounds.y + b.bounds.height) -
+ Math.max(ay, b.bounds.y),
+ );
+}
+
+test.each(FILES)(
+ "in %s, a line moved by Enter never comes down on a line that stayed, and nothing above the edited text moves",
+ async (file) => {
+ const count = (await open(file)).page(0).runs.filter(editable).length;
+ for (let index = 0; index < Math.min(count, 8); index++) {
+ const doc = await open(file);
+ const run = doc.page(0).runs.filter(editable)[index];
+ const original = run.text;
+ const history = new HistoryStack();
+ for (const breaks of [1, 2, 3]) {
+ const others = doc.page(0).runs.filter((r) => r !== run);
+ const was = new Map(others.map((r) => [r.id, r.bounds.y]));
+ const bottom = run.bounds.y;
+ type(doc, history, run, withBreaks(original, breaks));
+ const moved = others.filter(
+ (r) => Math.abs(r.bounds.y - was.get(r.id)!) > 0.3,
+ );
+ const stayed = others.filter((r) => !moved.includes(r));
+ const label = `${file} run ${index}, ${breaks} breaks`;
+ expect(
+ moved.filter((m) => was.get(m.id)! > bottom + 0.5).map((m) => m.text),
+ `${label}: moved from above the edited text`,
+ ).toEqual([]);
+ expect(
+ moved
+ .filter((m) =>
+ stayed.some(
+ (s) =>
+ shared(m, m.bounds.y, s) > shared(m, was.get(m.id)!, s) + 0.5,
+ ),
+ )
+ .map((m) => m.text),
+ `${label}: came down on a line that stayed`,
+ ).toEqual([]);
+ }
+ }
+ },
+);
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/renderWithoutImage.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/renderWithoutImage.test.ts
new file mode 100644
index 0000000000..bb2972449b
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/renderWithoutImage.test.ts
@@ -0,0 +1,185 @@
+// @vitest-environment node
+import { readFile } from "node:fs/promises";
+import { createRequire } from "node:module";
+import { afterEach, beforeAll, describe, expect, test, vi } from "vitest";
+import { MoveTextRunCommand } from "@editor/tools/pdfTextEditor/commands/MoveTextRunCommand";
+import { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
+import { PdfiumPageRenderer } from "@editor/tools/pdfTextEditor/pdfium/PdfiumPageRenderer";
+import { PdfiumTextReader } from "@editor/tools/pdfTextEditor/pdfium/PdfiumTextReader";
+import { HistoryStack } from "@editor/tools/pdfTextEditor/store/HistoryStack";
+import { exportToBlob } from "@editor/tools/pdfTextEditor/util/exportPdf";
+import { visibleImageBounds } from "@editor/tools/pdfTextEditor/util/imageClip";
+import {
+ buildClassicPdf,
+ streamBody,
+} from "@editor/tools/pdfTextEditor/__tests__/pdfFixtures";
+
+const SIZE = 300;
+const SCALE = 1;
+const IMAGE = streamBody(
+ "/Type /XObject /Subtype /Image /Width 2 /Height 2 /ColorSpace /DeviceRGB /BitsPerComponent 8",
+ "\x00\x00\xff".repeat(4),
+);
+const UNDER =
+ "0.9 0.6 0.1 rg 60 60 180 40 re f BT /F1 14 Tf 0 0 0 rg 70 120 Td (Under the picture) Tj ET";
+const OVER = "BT /F1 14 Tf 1 0 0 rg 70 170 Td (Over it) Tj ET";
+const ELSEWHERE = "BT /F1 12 Tf 0 0 0 rg 20 270 Td (Elsewhere) Tj ET";
+
+function fixture(page: string, form = ""): Uint8Array {
+ return buildClassicPdf(
+ [
+ { num: 1, body: "<< /Type /Catalog /Pages 2 0 R >>" },
+ { num: 2, body: "<< /Type /Pages /Kids [3 0 R] /Count 1 >>" },
+ {
+ num: 3,
+ body: `<< /Type /Page /Parent 2 0 R /MediaBox [0 0 ${SIZE} ${SIZE}] /Contents 4 0 R /Resources << /XObject << /Im 5 0 R /Fm 6 0 R >> /Font << /F1 7 0 R >> >> >>`,
+ },
+ { num: 4, body: streamBody("", page) },
+ { num: 5, body: IMAGE },
+ {
+ num: 6,
+ body: streamBody(
+ `/Type /XObject /Subtype /Form /BBox [0 0 ${SIZE} ${SIZE}] /Resources << /XObject << /Im 5 0 R >> >>`,
+ form,
+ ),
+ },
+ {
+ num: 7,
+ body: "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>",
+ },
+ ],
+ 1,
+ );
+}
+
+const DRAW = "q 50 50 200 150 re W n 200 0 0 200 50 50 cm /Im Do Q";
+const CASES: Array<[string, Uint8Array, Uint8Array]> = [
+ [
+ "on the page, between text under and over it",
+ fixture(`${ELSEWHERE} ${UNDER} ${DRAW} ${OVER}`),
+ fixture(`${ELSEWHERE} ${UNDER} ${OVER}`),
+ ],
+ [
+ "inside a form",
+ fixture(`${ELSEWHERE} ${UNDER} /Fm Do ${OVER}`, DRAW),
+ fixture(`${ELSEWHERE} ${UNDER} /Fm Do ${OVER}`),
+ ],
+];
+
+const opened: EditorDocument[] = [];
+
+class TestImageData {
+ constructor(
+ readonly data: Uint8ClampedArray,
+ readonly width: number,
+ readonly height: number,
+ ) {}
+}
+
+beforeAll(async () => {
+ const wasm = await readFile(
+ createRequire(import.meta.url).resolve("@embedpdf/pdfium/pdfium.wasm"),
+ );
+ vi.stubGlobal("ImageData", TestImageData);
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(
+ async () =>
+ new Response(wasm, { headers: { "Content-Type": "application/wasm" } }),
+ ),
+ );
+});
+
+afterEach(() => {
+ for (const doc of opened.splice(0)) doc.dispose();
+});
+
+async function open(bytes: Uint8Array): Promise<EditorDocument> {
+ const doc = await EditorDocument.open(bytes);
+ opened.push(doc);
+ PdfiumTextReader.populate(doc, doc.page(0));
+ return doc;
+}
+
+async function render(doc: EditorDocument): Promise<Uint8ClampedArray> {
+ return (await PdfiumPageRenderer.render(doc, doc.page(0), SCALE)).data;
+}
+
+function differing(a: Uint8ClampedArray, b: Uint8ClampedArray): number {
+ let n = 0;
+ for (let i = 0; i < a.length; i += 4)
+ if ([0, 1, 2].some((c) => Math.abs(a[i + c] - b[i + c]) > 2)) n++;
+ return n;
+}
+
+async function saved(doc: EditorDocument): Promise<Uint8Array> {
+ return new Uint8Array(await (await exportToBlob(doc)).arrayBuffer());
+}
+
+function hideImage(doc: EditorDocument): ImageData {
+ const page = doc.page(0);
+ const image = page.images[0];
+ const area = PdfiumPageRenderer.pixelsCovering(
+ page,
+ SCALE,
+ visibleImageBounds(image),
+ )!;
+ return PdfiumPageRenderer.renderAreaWithout(
+ doc,
+ page,
+ SCALE,
+ area,
+ image.pdfiumObjPtr,
+ )!;
+}
+
+function moveElsewhere(doc: EditorDocument): MoveTextRunCommand {
+ const run = doc.page(0).runs.find((r) => r.text.startsWith("Elsewhere"))!;
+ return new MoveTextRunCommand({ pageIndex: 0, runId: run.id, dx: 30, dy: 0 });
+}
+
+describe.each(CASES)("an image %s", (_name, bytes, withoutImage) => {
+ test("renders the page under it as it would be without the image", async () => {
+ const doc = await open(bytes);
+ const page = doc.page(0);
+ const area = PdfiumPageRenderer.pixelsCovering(
+ page,
+ SCALE,
+ visibleImageBounds(page.images[0]),
+ )!;
+ const hidden = hideImage(doc);
+ const expected = await PdfiumPageRenderer.renderArea(
+ await open(withoutImage),
+ opened.at(-1)!.page(0),
+ SCALE,
+ area,
+ );
+ expect(differing(hidden.data, expected.data)).toBe(0);
+ });
+
+ test("leaves the document, its history and its saved file untouched", async () => {
+ const doc = await open(bytes);
+ const page = doc.page(0);
+ const revision = page.revision;
+ const before = await render(doc);
+ hideImage(doc);
+ expect(page.dirty).toBe(false);
+ expect(page.revision).toBe(revision);
+ expect(differing(before, await render(doc))).toBe(0);
+ expect(differing(before, await render(await open(await saved(doc))))).toBe(
+ 0,
+ );
+ const history = new HistoryStack();
+ history.execute(moveElsewhere(doc), doc);
+ const moved = await render(doc);
+ expect(differing(before, moved)).toBeGreaterThan(0);
+ expect(differing(moved, await render(await open(await saved(doc))))).toBe(
+ 0,
+ );
+ history.undo(doc);
+ expect(differing(before, await render(doc))).toBe(0);
+ expect(differing(before, await render(await open(await saved(doc))))).toBe(
+ 0,
+ );
+ });
+});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/replayAfterUndo.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/replayAfterUndo.test.ts
new file mode 100644
index 0000000000..0d941ac3a5
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/replayAfterUndo.test.ts
@@ -0,0 +1,300 @@
+// @vitest-environment node
+import { readFile } from "node:fs/promises";
+import { createRequire } from "node:module";
+import path from "node:path";
+import { afterAll, afterEach, beforeAll, expect, test, vi } from "vitest";
+import { DeleteObjectCommand } from "@editor/tools/pdfTextEditor/commands/DeleteObjectCommand";
+import { InsertTextCommand } from "@editor/tools/pdfTextEditor/commands/InsertTextCommand";
+import { DuplicateRunCommand } from "@editor/tools/pdfTextEditor/commands/DuplicateRunCommand";
+import { EditTextCommand } from "@editor/tools/pdfTextEditor/commands/EditTextCommand";
+import { SetColourCommand } from "@editor/tools/pdfTextEditor/commands/SetColourCommand";
+import { SetFontFamilyCommand } from "@editor/tools/pdfTextEditor/commands/SetFontFamilyCommand";
+import { SetTextOutlineCommand } from "@editor/tools/pdfTextEditor/commands/SetTextOutlineCommand";
+import { UngroupParagraphCommand } from "@editor/tools/pdfTextEditor/commands/UngroupParagraphCommand";
+import { emitCellText } from "@editor/tools/pdfTextEditor/commands/tableHelpers";
+import { collectMemberPtrs } from "@editor/tools/pdfTextEditor/commands/editTextHelpers";
+import type { Command } from "@editor/tools/pdfTextEditor/commands/Command";
+import { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
+import { readObjFill } from "@editor/tools/pdfTextEditor/pdfium/PdfiumObjectColour";
+import { PdfiumTextReader } from "@editor/tools/pdfTextEditor/pdfium/PdfiumTextReader";
+import { HistoryStack } from "@editor/tools/pdfTextEditor/store/HistoryStack";
+import { exportToBlob } from "@editor/tools/pdfTextEditor/util/exportPdf";
+
+const SAMPLE = path.join(
+ import.meta.dirname,
+ "../../../tests/test-fixtures/paragraph-sample.pdf",
+);
+const HEADING = "Heading in a bigger size";
+const FPDF_PAGEOBJ_TEXT = 1;
+const RED = { r: 220, g: 0, b: 0, a: 255 };
+
+const opened: EditorDocument[] = [];
+
+beforeAll(async () => {
+ const wasm = await readFile(
+ createRequire(import.meta.url).resolve("@embedpdf/pdfium/pdfium.wasm"),
+ );
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async (url: string) =>
+ String(url).endsWith(".wasm")
+ ? new Response(wasm, {
+ headers: { "Content-Type": "application/wasm" },
+ })
+ : new Response(null, { status: 404 }),
+ ),
+ );
+});
+
+afterEach(() => {
+ for (const doc of opened.splice(0)) doc.dispose();
+});
+
+afterAll(() => vi.unstubAllGlobals());
+
+async function open(bytes?: Uint8Array) {
+ const doc = await EditorDocument.open(
+ bytes ?? new Uint8Array(await readFile(SAMPLE)),
+ );
+ opened.push(doc);
+ PdfiumTextReader.populate(doc, doc.page(0));
+ return doc;
+}
+
+function drawnText(doc: EditorDocument): string {
+ const m = doc.module;
+ const pagePtr = doc.page(0).pagePtr;
+ const buf = m.pdfium.wasmExports.malloc(1024);
+ const textPage = m.FPDFText_LoadPage(pagePtr);
+ let out = "";
+ try {
+ for (let i = 0; i < m.FPDFPage_CountObjects(pagePtr); i++) {
+ const obj = m.FPDFPage_GetObject(pagePtr, i);
+ if (m.FPDFPageObj_GetType(obj) !== FPDF_PAGEOBJ_TEXT) continue;
+ m.FPDFTextObj_GetText(obj, textPage, buf, 1024);
+ out += m.pdfium.UTF16ToString(buf);
+ }
+ } finally {
+ m.FPDFText_ClosePage(textPage);
+ m.pdfium.wasmExports.free(buf);
+ }
+ // Objects a command draws go to the end of the page, so compare letters, not order.
+ return [...out.replace(/\s+/g, "")].sort().join("");
+}
+
+function step(doc: EditorDocument, history: HistoryStack, cmd: Command) {
+ history.execute(cmd, doc);
+ history.breakCoalescing();
+}
+
+const family = (runId: string, nextFamily: string) =>
+ new SetFontFamilyCommand({ pageIndex: 0, runId, nextFamily });
+
+test("redoing two font changes draws the line once, on the page and in the saved file", async () => {
+ const doc = await open();
+ const heading = doc.page(0).runs.find((r) => r.text === HEADING)!;
+ const once = drawnText(doc);
+ const history = new HistoryStack();
+
+ step(doc, history, family(heading.id, "Courier"));
+ step(doc, history, family(heading.id, "Times-Roman"));
+ history.undo(doc);
+ history.undo(doc);
+ history.redo(doc);
+ history.redo(doc);
+
+ expect(drawnText(doc)).toBe(once);
+ const saved = await open(
+ new Uint8Array(await (await exportToBlob(doc)).arrayBuffer()),
+ );
+ expect(drawnText(saved)).toBe(once);
+});
+
+test.each([
+ ["a font change", (id: string) => family(id, "Courier")],
+ [
+ "an outline",
+ (id: string) =>
+ new SetTextOutlineCommand({
+ pageIndex: 0,
+ runId: id,
+ stroke: RED,
+ width: 1,
+ }),
+ ],
+])(
+ "undoing a colour after redoing it over %s puts the drawn colour back",
+ async (_case, before) => {
+ const doc = await open();
+ const heading = doc.page(0).runs.find((r) => r.text === HEADING)!;
+ const history = new HistoryStack();
+
+ step(doc, history, before(heading.id));
+ step(
+ doc,
+ history,
+ new SetColourCommand({ pageIndex: 0, runId: heading.id, nextFill: RED }),
+ );
+ history.undo(doc);
+ history.undo(doc);
+ history.redo(doc);
+ history.redo(doc);
+ history.undo(doc);
+
+ for (const ptr of collectMemberPtrs(heading))
+ expect(readObjFill(doc.module, ptr)?.r).toBe(0);
+ },
+);
+
+test("redo keeps an edit made to a duplicated line", async () => {
+ const doc = await open();
+ const heading = doc.page(0).runs.find((r) => r.text === HEADING)!;
+ const history = new HistoryStack();
+ const duplicate = new DuplicateRunCommand({
+ pageIndex: 0,
+ runId: heading.id,
+ });
+ step(doc, history, duplicate);
+ step(
+ doc,
+ history,
+ new EditTextCommand({
+ pageIndex: 0,
+ runId: duplicate.insertedRunId!,
+ nextText: "Changed copy",
+ }),
+ );
+
+ history.undo(doc);
+ history.undo(doc);
+ history.redo(doc);
+ history.redo(doc);
+
+ expect(doc.page(0).findRun(duplicate.insertedRunId!)?.text).toBe(
+ "Changed copy",
+ );
+});
+
+test("redoing a delete after a redone font change takes the line out of the saved file", async () => {
+ const doc = await open();
+ const heading = doc.page(0).runs.find((r) => r.text === HEADING)!;
+ const history = new HistoryStack();
+ step(doc, history, family(heading.id, "Courier"));
+ step(
+ doc,
+ history,
+ new DeleteObjectCommand({ pageIndex: 0, runId: heading.id }),
+ );
+ const deleted = drawnText(doc);
+
+ history.undo(doc);
+ history.undo(doc);
+ history.redo(doc);
+ history.redo(doc);
+
+ expect(drawnText(doc)).toBe(deleted);
+ const saved = await open(
+ new Uint8Array(await (await exportToBlob(doc)).arrayBuffer()),
+ );
+ expect(saved.page(0).runs.map((r) => r.text)).not.toContain(HEADING);
+});
+
+test("undoing an outline after redoing it over a font change takes the stroke off", async () => {
+ const doc = await open();
+ const heading = doc.page(0).runs.find((r) => r.text === HEADING)!;
+ const history = new HistoryStack();
+ step(doc, history, family(heading.id, "Courier"));
+ step(
+ doc,
+ history,
+ new SetTextOutlineCommand({
+ pageIndex: 0,
+ runId: heading.id,
+ stroke: RED,
+ width: 1,
+ }),
+ );
+
+ history.undo(doc);
+ history.undo(doc);
+ history.redo(doc);
+ history.redo(doc);
+ history.undo(doc);
+
+ const FILL_ONLY = 0;
+ for (const ptr of collectMemberPtrs(heading))
+ expect(doc.module.FPDFTextObj_GetTextRenderMode(ptr)).toBe(FILL_ONLY);
+});
+
+test("redo keeps an edit made to added text", async () => {
+ const doc = await open();
+ const history = new HistoryStack();
+ const insert = new InsertTextCommand({
+ pageIndex: 0,
+ x: 60,
+ y: 60,
+ text: "New text",
+ });
+ step(doc, history, insert);
+ step(
+ doc,
+ history,
+ new EditTextCommand({
+ pageIndex: 0,
+ runId: insert.insertedRunId!,
+ nextText: "Changed text",
+ }),
+ );
+
+ history.undo(doc);
+ history.undo(doc);
+ history.redo(doc);
+ history.redo(doc);
+
+ expect(doc.page(0).findRun(insert.insertedRunId!)?.text).toBe("Changed text");
+});
+
+test("deleting a line of an ungrouped paragraph takes every word of it off the page", async () => {
+ const doc = await open();
+ const page = doc.page(0);
+ const body = page.runs.find((r) => r.text !== HEADING)!;
+ const secondLine = body.text.split("\n")[1];
+ const lines = body.text.split("\n");
+ const history = new HistoryStack();
+ step(doc, history, family(body.id, "Courier"));
+ const ungroup = new UngroupParagraphCommand({ pageIndex: 0, runId: body.id });
+ step(doc, history, ungroup);
+ const line = page.runs.find((r) => r.text.trim() === secondLine.trim())!;
+
+ step(doc, history, new DeleteObjectCommand({ pageIndex: 0, runId: line.id }));
+
+ const saved = await open(
+ new Uint8Array(await (await exportToBlob(doc)).arrayBuffer()),
+ );
+ const left = saved
+ .page(0)
+ .runs.map((r) => r.text)
+ .join("\n");
+ const others = lines.filter((l) => l !== secondLine);
+ const ownWords = secondLine
+ .trim()
+ .split(/\s+/)
+ .filter((word) => !others.some((l) => l.includes(word)));
+ expect(ownWords.length).toBeGreaterThan(2);
+ for (const word of ownWords) expect(left).not.toContain(word);
+
+ history.undo(doc);
+ history.undo(doc);
+ expect(body.text.split("\n")).toHaveLength(4);
+});
+
+test("new table cell text is drawn whole or not at all", async () => {
+ const doc = await open();
+ const page = doc.page(0);
+ const runs = page.runs.length;
+
+ expect(emitCellText(doc, page, 50, 50, "A漢字", 12)).toBeNull();
+ expect(emitCellText(doc, page, 50, 30, "漢字", 12)).toBeNull();
+ expect(page.runs).toHaveLength(runs);
+ expect(emitCellText(doc, page, 50, 10, "Plain", 12)?.run.text).toBe("Plain");
+});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/replayObjects.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/replayObjects.test.ts
new file mode 100644
index 0000000000..1751782b78
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/replayObjects.test.ts
@@ -0,0 +1,94 @@
+// @vitest-environment node
+import { readFile } from "node:fs/promises";
+import { createRequire } from "node:module";
+import path from "node:path";
+import { afterAll, afterEach, beforeAll, expect, test, vi } from "vitest";
+import { EditTextCommand } from "@editor/tools/pdfTextEditor/commands/EditTextCommand";
+import { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
+import { PdfiumTextReader } from "@editor/tools/pdfTextEditor/pdfium/PdfiumTextReader";
+import { HistoryStack } from "@editor/tools/pdfTextEditor/store/HistoryStack";
+
+const SAMPLE = path.join(
+ import.meta.dirname,
+ "../../../tests/test-fixtures/paragraph-sample.pdf",
+);
+const HEADING = "Heading in a bigger size";
+
+const opened: EditorDocument[] = [];
+
+beforeAll(async () => {
+ const wasm = await readFile(
+ createRequire(import.meta.url).resolve("@embedpdf/pdfium/pdfium.wasm"),
+ );
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async (url: string) =>
+ String(url).endsWith(".wasm")
+ ? new Response(wasm, {
+ headers: { "Content-Type": "application/wasm" },
+ })
+ : new Response(null, { status: 404 }),
+ ),
+ );
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ for (const doc of opened.splice(0)) doc.dispose();
+});
+
+afterAll(() => vi.unstubAllGlobals());
+
+// Objects taken off the page and neither put back nor freed.
+function trackDetached(doc: EditorDocument): Set<number> {
+ const m = doc.module;
+ const detached = new Set<number>();
+ const remove = m.FPDFPage_RemoveObject.bind(m);
+ const insert = m.FPDFPage_InsertObject.bind(m);
+ const destroy = m.FPDFPageObj_Destroy.bind(m);
+ vi.spyOn(m, "FPDFPage_RemoveObject").mockImplementation((page, ptr) => {
+ const removed = remove(page, ptr);
+ if (removed) detached.add(ptr);
+ return removed;
+ });
+ vi.spyOn(m, "FPDFPage_InsertObject").mockImplementation((page, ptr) => {
+ detached.delete(ptr);
+ return insert(page, ptr);
+ });
+ vi.spyOn(m, "FPDFPageObj_Destroy").mockImplementation((ptr) => {
+ detached.delete(ptr);
+ return destroy(ptr);
+ });
+ return detached;
+}
+
+test("undoing and redoing a burst that is replayed whole does not pile up objects", async () => {
+ vi.spyOn(
+ EditTextCommand.prototype as unknown as { revertsExactly(): boolean },
+ "revertsExactly",
+ ).mockReturnValue(false);
+ const doc = await EditorDocument.open(new Uint8Array(await readFile(SAMPLE)));
+ opened.push(doc);
+ PdfiumTextReader.populate(doc, doc.page(0));
+ const heading = doc.page(0).runs.find((r) => r.text === HEADING)!;
+ const history = new HistoryStack();
+ for (const nextText of [`Xk ${HEADING}`, `Xk ${HEADING} Zq7`])
+ history.execute(
+ new EditTextCommand({ pageIndex: 0, runId: heading.id, nextText }),
+ doc,
+ );
+ const detached = trackDetached(doc);
+ history.undo(doc);
+ history.redo(doc);
+ const afterOneCycle = detached.size;
+
+ for (let i = 0; i < 20; i++) {
+ history.undo(doc);
+ history.redo(doc);
+ }
+
+ expect(detached.size).toBeLessThanOrEqual(afterOneCycle + 2);
+ expect(heading.text).toBe(`Xk ${HEADING} Zq7`);
+ history.undo(doc);
+ expect(heading.text).toBe(HEADING);
+});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/restoreDocumentFont.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/restoreDocumentFont.test.ts
new file mode 100644
index 0000000000..41887a92ee
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/restoreDocumentFont.test.ts
@@ -0,0 +1,94 @@
+import { describe, expect, it, vi } from "vitest";
+
+vi.mock(
+ "@editor/tools/pdfTextEditor/commands/editTextHelpers",
+ async (orig) => ({
+ ...(await orig<object>()),
+ removeMemberPtrs: vi.fn(),
+ emitRunLines: vi.fn(() => [
+ { ptrs: [501], text: "Hello", texts: ["Hello"], x: 10, y: 140 },
+ ]),
+ }),
+);
+vi.mock("@editor/tools/pdfTextEditor/commands/runTags", () => ({
+ readRunTags: () => [],
+}));
+vi.mock("@editor/tools/pdfTextEditor/commands/scanTextEdit", () => ({
+ setScanOverride: () => null,
+}));
+vi.mock("@editor/tools/pdfTextEditor/util/deviceFontEmbed", () => ({
+ deviceFontEmitCount: () => 0,
+}));
+
+import { SetFontFamilyCommand } from "@editor/tools/pdfTextEditor/commands/SetFontFamilyCommand";
+import { Page } from "@editor/tools/pdfTextEditor/model/Page";
+import { TextRun } from "@editor/tools/pdfTextEditor/model/TextRun";
+import type { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
+
+function runInChangedFont(): { page: Page; run: TextRun } {
+ const page = new Page({ index: 0, pagePtr: 1, width: 200, height: 200 });
+ const run = new TextRun({
+ id: "r",
+ pageIndex: 0,
+ pdfiumObjPtr: 11,
+ bounds: { x: 10, y: 130, width: 60, height: 12 },
+ matrix: { a: 1, b: 0, c: 0, d: 1, e: 10, f: 140 },
+ text: "Hello",
+ fontId: "device:Acme Sans",
+ fontSize: 10,
+ fill: { r: 0, g: 0, b: 0, a: 255 },
+ fontSubset: false,
+ });
+ run.documentFont = { fontId: "pdf:7:Garamond", subset: true };
+ page.setRuns([run]);
+ return { page, run };
+}
+
+function fakeDoc(page: Page, emittedFont: number) {
+ const module = {
+ FPDFTextObj_GetFont: vi.fn(() => emittedFont),
+ FPDFPage_RemoveObject: vi.fn(() => true),
+ FPDFPageObj_Destroy: vi.fn(),
+ FPDFPage_InsertObject: vi.fn(),
+ FPDFPage_CountObjects: vi.fn(() => 0),
+ };
+ const doc = {
+ module,
+ page: () => page,
+ ownedFontAt: () => undefined,
+ } as unknown as EditorDocument;
+ return { doc, module };
+}
+
+function restore(doc: EditorDocument) {
+ new SetFontFamilyCommand({
+ pageIndex: 0,
+ runId: "r",
+ nextFamily: "pdf:7:Garamond",
+ }).apply(doc);
+}
+
+describe("SetFontFamilyCommand restoring the document font", () => {
+ it("marks the run restored when the new text uses the saved font", () => {
+ const { page, run } = runInChangedFont();
+ restore(fakeDoc(page, 7).doc);
+
+ expect(run.fontId).toBe("pdf:7:Garamond");
+ expect(run.documentFont).toBeNull();
+ });
+
+ it("keeps the run as it was when only a fallback font could draw it", () => {
+ const { page, run } = runInChangedFont();
+ const { doc, module } = fakeDoc(page, 99);
+ restore(doc);
+
+ expect(run.fontId).toBe("device:Acme Sans");
+ expect(run.documentFont).toEqual({
+ fontId: "pdf:7:Garamond",
+ subset: true,
+ });
+ expect(run.pdfiumObjPtr).toBe(11);
+ expect(module.FPDFPage_RemoveObject).toHaveBeenCalledWith(1, 501);
+ expect(module.FPDFPage_InsertObject).toHaveBeenCalledWith(1, 11);
+ });
+});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/rotatedTextEdit.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/rotatedTextEdit.test.ts
new file mode 100644
index 0000000000..bf5b18c709
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/rotatedTextEdit.test.ts
@@ -0,0 +1,71 @@
+// @vitest-environment node
+import { readFile } from "node:fs/promises";
+import { createRequire } from "node:module";
+import path from "node:path";
+import {
+ afterAll,
+ afterEach,
+ beforeAll,
+ describe,
+ expect,
+ test,
+ vi,
+} from "vitest";
+import { EditTextCommand } from "@editor/tools/pdfTextEditor/commands/EditTextCommand";
+import { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
+import { PdfiumTextReader } from "@editor/tools/pdfTextEditor/pdfium/PdfiumTextReader";
+import { exportToBlob } from "@editor/tools/pdfTextEditor/util/exportPdf";
+
+const SAMPLE = path.join(
+ import.meta.dirname,
+ "../../../tests/test-fixtures/rotated-text-sample.pdf",
+);
+
+const opened: EditorDocument[] = [];
+
+beforeAll(async () => {
+ const wasm = await readFile(
+ createRequire(import.meta.url).resolve("@embedpdf/pdfium/pdfium.wasm"),
+ );
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async (url: string) =>
+ String(url).endsWith(".wasm")
+ ? new Response(wasm, {
+ headers: { "Content-Type": "application/wasm" },
+ })
+ : new Response(null, { status: 404 }),
+ ),
+ );
+});
+
+afterEach(() => {
+ for (const doc of opened.splice(0)) doc.dispose();
+});
+
+afterAll(() => vi.unstubAllGlobals());
+
+async function open(bytes: Uint8Array): Promise<EditorDocument> {
+ const doc = await EditorDocument.open(bytes);
+ opened.push(doc);
+ PdfiumTextReader.populate(doc, doc.page(0));
+ return doc;
+}
+
+describe("editing turned text", () => {
+ test("keeps several typed words one line when the file is opened again", async () => {
+ const doc = await open(new Uint8Array(await readFile(SAMPLE)));
+ const run = doc.page(0).runs.find((r) => r.text.includes("Rotated"))!;
+ const edited = `Xk ${run.text} Wj9 Zq7`;
+ for (let end = run.text.length + 3; end <= edited.length; end++)
+ new EditTextCommand({
+ pageIndex: 0,
+ runId: run.id,
+ nextText: edited.slice(0, end),
+ }).apply(doc);
+
+ const saved = new Uint8Array(await (await exportToBlob(doc)).arrayBuffer());
+ const again = await open(saved);
+ expect(again.page(0).runs.map((r) => r.text)).toEqual([edited]);
+ });
+});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/rtlEdit.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/rtlEdit.test.ts
new file mode 100644
index 0000000000..d3ea207f77
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/rtlEdit.test.ts
@@ -0,0 +1,195 @@
+// @vitest-environment node
+import { readFile } from "node:fs/promises";
+import { createRequire } from "node:module";
+import path from "node:path";
+import {
+ afterAll,
+ afterEach,
+ beforeAll,
+ describe,
+ expect,
+ test,
+ vi,
+} from "vitest";
+import { DuplicateRunCommand } from "@editor/tools/pdfTextEditor/commands/DuplicateRunCommand";
+import { EditTextCommand } from "@editor/tools/pdfTextEditor/commands/EditTextCommand";
+import { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
+import { PdfiumTextReader } from "@editor/tools/pdfTextEditor/pdfium/PdfiumTextReader";
+import { HistoryStack } from "@editor/tools/pdfTextEditor/store/HistoryStack";
+
+const SAMPLE = path.join(
+ import.meta.dirname,
+ "../../../tests/test-fixtures/rtl-sample.pdf",
+);
+const HEBREW_LINE = "שלום עולם וברוכים הבאים";
+const FPDF_PAGEOBJ_TEXT = 1;
+
+const opened: EditorDocument[] = [];
+
+beforeAll(async () => {
+ const wasm = await readFile(
+ createRequire(import.meta.url).resolve("@embedpdf/pdfium/pdfium.wasm"),
+ );
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async (url: string) =>
+ String(url).endsWith(".wasm")
+ ? new Response(wasm, {
+ headers: { "Content-Type": "application/wasm" },
+ })
+ : new Response(null, { status: 404 }),
+ ),
+ );
+});
+
+afterEach(() => {
+ for (const doc of opened.splice(0)) doc.dispose();
+});
+
+afterAll(() => vi.unstubAllGlobals());
+
+async function open(): Promise<EditorDocument> {
+ const doc = await EditorDocument.open(new Uint8Array(await readFile(SAMPLE)));
+ opened.push(doc);
+ PdfiumTextReader.populate(doc, doc.page(0));
+ return doc;
+}
+
+// The page's text as a reader extracts it, one entry per line.
+function readLines(doc: EditorDocument): string[] {
+ const m = doc.module;
+ const textPage = m.FPDFText_LoadPage(doc.page(0).pagePtr);
+ try {
+ let text = "";
+ for (let i = 0; i < m.FPDFText_CountChars(textPage); i++)
+ text += String.fromCodePoint(m.FPDFText_GetUnicode(textPage, i));
+ return text
+ .split(/\r?\n/)
+ .map((line) => line.replace(/\s+/g, " ").trim())
+ .filter(Boolean);
+ } finally {
+ m.FPDFText_ClosePage(textPage);
+ }
+}
+
+// Left and right ink edge of every text object drawn on the line around `y`.
+function lineExtent(
+ doc: EditorDocument,
+ y: number,
+): { left: number; right: number } {
+ const m = doc.module;
+ const pagePtr = doc.page(0).pagePtr;
+ const box = m.pdfium.wasmExports.malloc(16);
+ let left = Infinity;
+ let right = -Infinity;
+ try {
+ for (let i = 0; i < m.FPDFPage_CountObjects(pagePtr); i++) {
+ const obj = m.FPDFPage_GetObject(pagePtr, i);
+ if (m.FPDFPageObj_GetType(obj) !== FPDF_PAGEOBJ_TEXT) continue;
+ m.FPDFPageObj_GetBounds(obj, box, box + 4, box + 8, box + 12);
+ const bottom = m.pdfium.getValue(box + 4, "float");
+ const top = m.pdfium.getValue(box + 12, "float");
+ if (y < bottom - 2 || y > top + 2) continue;
+ left = Math.min(left, m.pdfium.getValue(box, "float"));
+ right = Math.max(right, m.pdfium.getValue(box + 8, "float"));
+ }
+ } finally {
+ m.pdfium.wasmExports.free(box);
+ }
+ return { left, right };
+}
+
+function edit(
+ doc: EditorDocument,
+ history: HistoryStack,
+ needle: string,
+ next: (text: string) => string,
+) {
+ const run = doc.page(0).runs.find((r) => r.text.includes(needle))!;
+ history.execute(
+ new EditTextCommand({
+ pageIndex: 0,
+ runId: run.id,
+ nextText: next(run.text),
+ }),
+ doc,
+ );
+ return run;
+}
+
+describe("a right-to-left line", () => {
+ test("reads in its own order", async () => {
+ const doc = await open();
+
+ expect(doc.page(0).runs.map((r) => r.text.trim())).toContain(HEBREW_LINE);
+ });
+
+ test("still reads correctly and keeps its right edge after a word is changed", async () => {
+ const doc = await open();
+ const history = new HistoryStack();
+ const run = doc.page(0).runs.find((r) => r.text.includes("שלום ע"))!;
+ const y = run.bounds.y + run.bounds.height / 2;
+ const before = lineExtent(doc, y);
+
+ edit(doc, history, "שלום ע", (text) => text.replace("עולם", "עולם רב"));
+
+ expect(readLines(doc)).toContain("שלום עולם רב וברוכים הבאים");
+ expect(lineExtent(doc, y).right).toBeCloseTo(before.right, 0);
+ expect(lineExtent(doc, y).left).toBeLessThan(before.left);
+ });
+
+ test("keeps its words while left-to-right text is typed after them", async () => {
+ const doc = await open();
+ const history = new HistoryStack();
+
+ for (const typed of [" ", " Z", " Zq"])
+ edit(doc, history, "שלום ע", (text) => text.replace(/ ?Z?q?$/, typed));
+
+ const page = readLines(doc).join(" ");
+ expect(page).toContain("שלום עולם וברוכים הבאים");
+ expect(page).toContain("Zq");
+ });
+
+ test("comes back exactly on undo", async () => {
+ const doc = await open();
+ const history = new HistoryStack();
+ const original = readLines(doc);
+
+ edit(doc, history, "שלום ע", (text) => text.replace("עולם", "עולם רב"));
+ history.undo(doc);
+
+ expect(readLines(doc)).toEqual(original);
+ });
+});
+
+describe("a copy of right-to-left text", () => {
+ test("is refused when no font draws its letters, instead of made without them", async () => {
+ const doc = await open();
+ const history = new HistoryStack();
+ const run = doc.page(0).runs.find((r) => r.text.includes("שלום ע"))!;
+ const runs = doc.page(0).runs.length;
+ const objects = doc.module.FPDFPage_CountObjects(doc.page(0).pagePtr);
+
+ expect(() =>
+ history.execute(
+ new DuplicateRunCommand({ pageIndex: 0, runId: run.id }),
+ doc,
+ ),
+ ).toThrow(expect.objectContaining({ documentIntact: true }));
+
+ expect(doc.page(0).runs.length).toBe(runs);
+ expect(doc.module.FPDFPage_CountObjects(doc.page(0).pagePtr)).toBe(objects);
+ expect(history.canUndo).toBe(false);
+ });
+});
+
+describe("a right-to-left word in a left-to-right line", () => {
+ test("reads in place after one is typed among the left-to-right words", async () => {
+ const doc = await open();
+ const history = new HistoryStack();
+
+ edit(doc, history, "Mixed", (text) => text.replace("hello", "עולם hello"));
+
+ expect(readLines(doc)).toContain("Mixed: עולם hello שלום world 123.");
+ });
+});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/rtlMarks.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/rtlMarks.test.ts
new file mode 100644
index 0000000000..64dbd5eb62
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/rtlMarks.test.ts
@@ -0,0 +1,199 @@
+// @vitest-environment node
+import { readFile } from "node:fs/promises";
+import { createRequire } from "node:module";
+import path from "node:path";
+import { afterAll, afterEach, beforeAll, expect, test, vi } from "vitest";
+import { DeleteObjectCommand } from "@editor/tools/pdfTextEditor/commands/DeleteObjectCommand";
+import { EditTextCommand } from "@editor/tools/pdfTextEditor/commands/EditTextCommand";
+import { MoveTextRunCommand } from "@editor/tools/pdfTextEditor/commands/MoveTextRunCommand";
+import { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
+import { HistoryStack } from "@editor/tools/pdfTextEditor/store/HistoryStack";
+import { exportToBlob } from "@editor/tools/pdfTextEditor/util/exportPdf";
+import { PdfiumTextReader } from "@editor/tools/pdfTextEditor/pdfium/PdfiumTextReader";
+
+const SAMPLE = path.join(
+ import.meta.dirname,
+ "../../../tests/test-fixtures/rtl-marks-sample.pdf",
+);
+const HEBREW = "שָׁלוֹם עוֹלָם";
+const ARABIC = "يُولَدُ جَمِيعُ النَّاسِ";
+const FPDF_PAGEOBJ_TEXT = 1;
+
+const opened: EditorDocument[] = [];
+
+beforeAll(async () => {
+ const wasm = await readFile(
+ createRequire(import.meta.url).resolve("@embedpdf/pdfium/pdfium.wasm"),
+ );
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async (url: string) =>
+ String(url).endsWith(".wasm")
+ ? new Response(wasm, {
+ headers: { "Content-Type": "application/wasm" },
+ })
+ : new Response(null, { status: 404 }),
+ ),
+ );
+});
+
+afterEach(() => {
+ for (const doc of opened.splice(0)) doc.dispose();
+});
+
+afterAll(() => vi.unstubAllGlobals());
+
+async function open(bytes?: Uint8Array): Promise<EditorDocument> {
+ const doc = await EditorDocument.open(
+ bytes ?? new Uint8Array(await readFile(SAMPLE)),
+ );
+ opened.push(doc);
+ PdfiumTextReader.populate(doc, doc.page(0));
+ return doc;
+}
+
+const texts = (doc: EditorDocument) =>
+ doc.page(0).runs.map((run) => run.text.normalize("NFC"));
+
+test("reads each vowel mark after the letter it sits on", async () => {
+ const doc = await open();
+
+ expect(texts(doc)).toEqual([HEBREW, ARABIC].map((t) => t.normalize("NFC")));
+});
+
+// Every text object on the page that draws ink, a space glyph left out.
+function inked(doc: EditorDocument): number[] {
+ const m = doc.module;
+ const pagePtr = doc.page(0).pagePtr;
+ const box = m.pdfium.wasmExports.malloc(16);
+ const found: number[] = [];
+ try {
+ for (let i = 0; i < m.FPDFPage_CountObjects(pagePtr); i++) {
+ const obj = m.FPDFPage_GetObject(pagePtr, i);
+ if (m.FPDFPageObj_GetType(obj) !== FPDF_PAGEOBJ_TEXT) continue;
+ if (!m.FPDFPageObj_GetBounds(obj, box, box + 4, box + 8, box + 12))
+ continue;
+ const width =
+ m.pdfium.getValue(box + 8, "float") - m.pdfium.getValue(box, "float");
+ if (width > 0.01) found.push(obj);
+ }
+ } finally {
+ m.pdfium.wasmExports.free(box);
+ }
+ return found;
+}
+
+// The bottom edge of each inked text object whose ink lies between `bottom` and `top`.
+function inkedBetween(
+ doc: EditorDocument,
+ bottom: number,
+ top: number,
+): Map<number, number> {
+ const m = doc.module;
+ const box = m.pdfium.wasmExports.malloc(16);
+ const found = new Map<number, number>();
+ try {
+ for (const ptr of inked(doc)) {
+ m.FPDFPageObj_GetBounds(ptr, box, box + 4, box + 8, box + 12);
+ const low = m.pdfium.getValue(box + 4, "float");
+ if (low >= bottom && m.pdfium.getValue(box + 12, "float") <= top)
+ found.set(ptr, low);
+ }
+ } finally {
+ m.pdfium.wasmExports.free(box);
+ }
+ return found;
+}
+
+const owned = (doc: EditorDocument) =>
+ new Set(doc.page(0).runs.flatMap((run) => run.mergedFromPtrs));
+
+test("a line owns the letter and the mark of a pair drawn as two objects", async () => {
+ const doc = await open();
+
+ const stray = inked(doc).filter((ptr) => !owned(doc).has(ptr));
+
+ expect(stray).toEqual([]);
+});
+
+test("leaves no letter or mark behind when a word with vowel marks is deleted", async () => {
+ const doc = await open();
+ const run = doc.page(0).runs[0];
+ const before = inked(doc).length;
+ const [kept] = run.text.split(" ");
+
+ new HistoryStack().execute(
+ new EditTextCommand({ pageIndex: 0, runId: run.id, nextText: kept }),
+ doc,
+ );
+
+ const left = inked(doc);
+ expect(left.filter((ptr) => !owned(doc).has(ptr))).toEqual([]);
+ expect(left.length).toBeLessThan(before);
+ expect(texts(doc)[0]).toBe(kept.normalize("NFC"));
+});
+
+test("draws each mark once after a letter is typed on its line", async () => {
+ const doc = await open();
+ const history = new HistoryStack();
+ const run = doc.page(0).runs[0];
+ const before = inked(doc);
+
+ history.execute(
+ new EditTextCommand({
+ pageIndex: 0,
+ runId: run.id,
+ nextText: `${run.text} ם`,
+ }),
+ doc,
+ );
+
+ const after = inked(doc);
+ expect(after.filter((ptr) => !owned(doc).has(ptr))).toEqual([]);
+ expect(after.length).toBe(before.length + 1);
+ for (const ptr of before) expect(after).toContain(ptr);
+ history.undo(doc);
+ expect(inked(doc)).toEqual(before);
+});
+
+test("reads a letter and its mark once after a letter is typed straight after them", async () => {
+ const doc = await open();
+ const run = doc.page(0).runs[0];
+ const at = run.text.indexOf("ל");
+ const next = `${run.text.slice(0, at)}ם${run.text.slice(at)}`;
+
+ new HistoryStack().execute(
+ new EditTextCommand({ pageIndex: 0, runId: run.id, nextText: next }),
+ doc,
+ );
+
+ const saved = await exportToBlob(doc);
+ const again = await open(new Uint8Array(await saved.arrayBuffer()));
+ expect(texts(again)).toEqual([next, ARABIC].map((t) => t.normalize("NFC")));
+});
+
+test("moves and deletes every letter and mark of a line together", async () => {
+ const doc = await open();
+ const history = new HistoryStack();
+ const run = doc.page(0).runs[0];
+ const band = [run.bounds.y - 6, run.bounds.y + run.bounds.height + 6];
+ const before = inkedBetween(doc, band[0], band[1]);
+
+ history.execute(
+ new MoveTextRunCommand({ pageIndex: 0, runId: run.id, dx: 0, dy: 30 }),
+ doc,
+ );
+
+ const moved = inkedBetween(doc, band[0] + 30, band[1] + 30);
+ expect(moved.size).toBe(before.size);
+ for (const [ptr, low] of before)
+ expect(moved.get(ptr)).toBeCloseTo(low + 30, 1);
+
+ history.execute(
+ new DeleteObjectCommand({ pageIndex: 0, runId: run.id }),
+ doc,
+ );
+
+ expect(inkedBetween(doc, band[0] + 30, band[1] + 30).size).toBe(0);
+ expect(inkedBetween(doc, band[0], band[1]).size).toBe(0);
+});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/rtlMixedLine.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/rtlMixedLine.test.ts
new file mode 100644
index 0000000000..6d23fc3894
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/rtlMixedLine.test.ts
@@ -0,0 +1,446 @@
+// @vitest-environment node
+import { readFile } from "node:fs/promises";
+import { createRequire } from "node:module";
+import path from "node:path";
+import {
+ afterAll,
+ afterEach,
+ beforeAll,
+ describe,
+ expect,
+ test,
+ vi,
+} from "vitest";
+import { CompositeCommand } from "@editor/tools/pdfTextEditor/commands/CompositeCommand";
+import { EditTextCommand } from "@editor/tools/pdfTextEditor/commands/EditTextCommand";
+import { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
+import type { TextRun } from "@editor/tools/pdfTextEditor/model/TextRun";
+import { PdfiumTextReader } from "@editor/tools/pdfTextEditor/pdfium/PdfiumTextReader";
+import { EditorStore } from "@editor/tools/pdfTextEditor/store/EditorStore";
+import { HistoryStack } from "@editor/tools/pdfTextEditor/store/HistoryStack";
+import { detectSaveRisks } from "@editor/tools/pdfTextEditor/util/documentRisks";
+import { exportToBlob } from "@editor/tools/pdfTextEditor/util/exportPdf";
+
+const SAMPLE = path.join(
+ import.meta.dirname,
+ "../../../tests/test-fixtures/rtl-mixed-sample.pdf",
+);
+const ARABIC =
+ "بلغ الاستهلاك (في الربع) 12,450.75 كيلوواط [بزيادة 3.5%] حسب تقرير ISO 50001";
+const ARABIC_WITH_NAMES =
+ "استخدم برنامج LibreOffice Writer أو Word لفتح report-2026.docx الآن.";
+const HEBREW =
+ "הטלפון הוא 03-555-1234 (שלוחה 12), והמחיר 1,299.90 לפי Open Source סעיף 4.";
+const ENGLISH =
+ "An English line quoting مرحبا بالعالم and שלום עולם then 1,234.";
+const LATIN_FIRST = "ISO 50001 هو المعيار";
+const FPDF_PAGEOBJ_TEXT = 1;
+
+const opened: EditorDocument[] = [];
+
+beforeAll(async () => {
+ const wasm = await readFile(
+ createRequire(import.meta.url).resolve("@embedpdf/pdfium/pdfium.wasm"),
+ );
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async (url: string) =>
+ String(url).endsWith(".wasm")
+ ? new Response(wasm, {
+ headers: { "Content-Type": "application/wasm" },
+ })
+ : new Response(null, { status: 404 }),
+ ),
+ );
+});
+
+afterEach(() => {
+ for (const doc of opened.splice(0)) doc.dispose();
+});
+
+afterAll(() => vi.unstubAllGlobals());
+
+async function open(bytes?: Uint8Array): Promise<EditorDocument> {
+ const doc = await EditorDocument.open(
+ bytes ?? new Uint8Array(await readFile(SAMPLE)),
+ );
+ opened.push(doc);
+ PdfiumTextReader.populate(doc, doc.page(0));
+ return doc;
+}
+
+const texts = (doc: EditorDocument) => doc.page(0).runs.map((run) => run.text);
+
+const lineOf = (doc: EditorDocument, text: string): TextRun =>
+ doc.page(0).runs.find((run) => run.text === text)!;
+
+// Where every text object on the page sits, by pointer.
+function placements(doc: EditorDocument): Map<number, string> {
+ const m = doc.module;
+ const pagePtr = doc.page(0).pagePtr;
+ const matrix = m.pdfium.wasmExports.malloc(24);
+ const placed = new Map<number, string>();
+ try {
+ for (let i = 0; i < m.FPDFPage_CountObjects(pagePtr); i++) {
+ const obj = m.FPDFPage_GetObject(pagePtr, i);
+ if (m.FPDFPageObj_GetType(obj) !== FPDF_PAGEOBJ_TEXT) continue;
+ m.FPDFPageObj_GetMatrix(obj, matrix);
+ placed.set(
+ obj,
+ [16, 20]
+ .map((at) => m.pdfium.getValue(matrix + at, "float").toFixed(2))
+ .join(","),
+ );
+ }
+ } finally {
+ m.pdfium.wasmExports.free(matrix);
+ }
+ return placed;
+}
+
+function inkOf(
+ doc: EditorDocument,
+ ptr: number,
+): { left: number; right: number } {
+ const m = doc.module;
+ const box = m.pdfium.wasmExports.malloc(16);
+ try {
+ m.FPDFPageObj_GetBounds(ptr, box, box + 4, box + 8, box + 12);
+ return {
+ left: m.pdfium.getValue(box, "float"),
+ right: m.pdfium.getValue(box + 8, "float"),
+ };
+ } finally {
+ m.pdfium.wasmExports.free(box);
+ }
+}
+
+const leftOf = (placed: Map<number, string>, ptr: number) =>
+ Number(placed.get(ptr)!.split(",")[0]);
+
+// The letters drawn on the baseline `y`, left to right, spaces left out.
+function drawnOn(doc: EditorDocument, y: number): string {
+ const m = doc.module;
+ const textPage = m.FPDFText_LoadPage(doc.page(0).pagePtr);
+ const at = m.pdfium.wasmExports.malloc(16);
+ const letters: Array<{ x: number; char: string }> = [];
+ try {
+ for (let i = 0; i < m.FPDFText_CountChars(textPage); i++) {
+ if (m.FPDFText_IsGenerated(textPage, i) === 1) continue;
+ if (!m.FPDFText_GetCharOrigin(textPage, i, at, at + 8)) continue;
+ if (Math.abs(m.pdfium.getValue(at + 8, "double") - y) > 1) continue;
+ const char = String.fromCodePoint(m.FPDFText_GetUnicode(textPage, i));
+ if (char.trim())
+ letters.push({ x: m.pdfium.getValue(at, "double"), char });
+ }
+ } finally {
+ m.pdfium.wasmExports.free(at);
+ m.FPDFText_ClosePage(textPage);
+ }
+ return letters
+ .sort((a, b) => a.x - b.x)
+ .map(({ char }) => char)
+ .join("");
+}
+
+function edit(
+ doc: EditorDocument,
+ history: HistoryStack,
+ run: TextRun,
+ nextText: string,
+): void {
+ history.execute(
+ new EditTextCommand({ pageIndex: 0, runId: run.id, nextText }),
+ doc,
+ );
+}
+
+async function reopened(doc: EditorDocument): Promise<EditorDocument> {
+ const saved = await exportToBlob(doc);
+ return open(new Uint8Array(await saved.arrayBuffer()));
+}
+
+describe("a line mixing directions", () => {
+ test("reads numbers, Latin words and brackets in their own order", async () => {
+ const doc = await open();
+
+ expect(texts(doc)).toEqual([
+ ARABIC,
+ ARABIC_WITH_NAMES,
+ HEBREW,
+ ENGLISH,
+ LATIN_FIRST,
+ ]);
+ });
+
+ test("keeps every object where it was when letters are typed at its end", async () => {
+ const doc = await open();
+ const run = lineOf(doc, HEBREW);
+ const before = placements(doc);
+
+ edit(doc, new HistoryStack(), run, `${HEBREW} של`);
+
+ const after = placements(doc);
+ for (const [ptr, place] of before) expect(after.get(ptr)).toBe(place);
+ expect(after.size).toBe(before.size + 1);
+ const drawn = drawnOn(doc, run.matrix.f);
+ expect(drawn.startsWith("לש.4")).toBe(true);
+ expect(drawn).toContain("1,299.90");
+ expect(drawn).toContain("03-555-1234");
+ expect(texts(await reopened(doc))).toContain(`${HEBREW} של`);
+ });
+
+ test("grows a number typed after a Latin word leftwards with that word", async () => {
+ const doc = await open();
+ const run = lineOf(doc, ARABIC);
+ const latin = run.mergedFromPtrs[run.mergedFromTexts.indexOf("ISO 50001")];
+ const before = placements(doc);
+
+ edit(doc, new HistoryStack(), run, `${ARABIC} 507`);
+
+ const after = placements(doc);
+ for (const [ptr, place] of before)
+ if (ptr !== latin) expect(after.get(ptr)).toBe(place);
+ expect(leftOf(after, latin)).toBeLessThan(leftOf(before, latin) - 5);
+ const drawn = drawnOn(doc, run.matrix.f);
+ expect(drawn.startsWith("ISO50001507")).toBe(true);
+ expect(drawn).toContain("12,450.75");
+ expect(drawn).toContain("[%3.5");
+ expect(texts(await reopened(doc))).toContain(`${ARABIC} 507`);
+ });
+
+ test("moves the text after an insertion as one, and nothing before it", async () => {
+ const doc = await open();
+ const run = lineOf(doc, ARABIC);
+ const at = ARABIC.indexOf("كيلوواط");
+ const pieces = run.mergedFromPtrs.map((ptr, i) => ({
+ ptr,
+ start: run.mergedFromCharStarts[i],
+ }));
+ const before = placements(doc);
+ const next = `${ARABIC.slice(0, at)}75 ${ARABIC.slice(at)}`;
+
+ edit(doc, new HistoryStack(), run, next);
+
+ const after = placements(doc);
+ const shifts = pieces
+ .filter(({ start }) => start >= at)
+ .map(({ ptr }) => leftOf(after, ptr) - leftOf(before, ptr));
+ for (const { ptr, start } of pieces)
+ if (start < at - 1) expect(after.get(ptr)).toBe(before.get(ptr));
+ expect(shifts[0]).toBeLessThan(-5);
+ for (const shift of shifts) expect(shift).toBeCloseTo(shifts[0], 1);
+ expect(drawnOn(doc, run.matrix.f)).toContain("7512,450.75");
+ expect(texts(await reopened(doc))).toContain(next);
+ });
+
+ test("closes the gap a deleted word leaves and keeps the numbers beside it", async () => {
+ const doc = await open();
+ const run = lineOf(doc, ARABIC);
+ const next = ARABIC.replace("كيلوواط ", "");
+
+ edit(doc, new HistoryStack(), run, next);
+
+ const drawn = drawnOn(doc, run.matrix.f);
+ expect(drawn).toContain("]12,450.75(");
+ expect(drawn.startsWith("ISO50001")).toBe(true);
+ expect(texts(await reopened(doc))).toContain(next);
+ });
+
+ test("moves the rest of a line down at a line break, and back when the lines are joined", async () => {
+ const doc = await open();
+ const history = new HistoryStack();
+ const run = lineOf(doc, ARABIC);
+ const at = ARABIC.indexOf("كيلوواط");
+ const pieces = run.mergedFromPtrs.map((ptr, i) => ({
+ ptr,
+ start: run.mergedFromCharStarts[i],
+ }));
+ const before = placements(doc);
+ const baselineOf = (placed: Map<number, string>, ptr: number) =>
+ Number(placed.get(ptr)!.split(",")[1]);
+
+ edit(doc, history, run, `${ARABIC.slice(0, at)}\n${ARABIC.slice(at)}`);
+
+ const broken = placements(doc);
+ expect(broken.size).toBe(before.size);
+ for (const { ptr, start } of pieces) {
+ if (start < at - 1) expect(broken.get(ptr)).toBe(before.get(ptr));
+ if (start >= at)
+ expect(baselineOf(broken, ptr)).toBeLessThan(
+ baselineOf(before, ptr) - 10,
+ );
+ }
+ const read = texts(await reopened(doc)).map((text) => text.trim());
+ expect(read).toContain(ARABIC.slice(0, at).trim());
+ expect(read).toContain(ARABIC.slice(at));
+
+ edit(doc, history, run, ARABIC);
+
+ // A glyph that ended a line is set back by its box, not its exact advance.
+ const joined = placements(doc);
+ expect(joined.size).toBe(before.size);
+ for (const [ptr] of before) {
+ expect(leftOf(joined, ptr)).toBeCloseTo(leftOf(before, ptr), 0);
+ expect(baselineOf(joined, ptr)).toBeCloseTo(baselineOf(before, ptr), 1);
+ }
+ while (history.canUndo) history.undo(doc);
+ expect([...placements(doc)]).toEqual([...before]);
+ });
+
+ test("redraws only the Latin word that is changed", async () => {
+ const doc = await open();
+ const run = lineOf(doc, ARABIC_WITH_NAMES);
+ const next = ARABIC_WITH_NAMES.replace("Word", "Wordx");
+
+ edit(doc, new HistoryStack(), run, next);
+
+ const drawn = drawnOn(doc, run.matrix.f);
+ expect(drawn).toContain("report-2026.docx");
+ expect(drawn).toContain("Wordx");
+ expect(drawn).toContain("LibreOfficeWriter");
+ expect(texts(await reopened(doc))).toContain(next);
+ });
+
+ test("keeps an Arabic and a Hebrew quote in an English line", async () => {
+ const doc = await open();
+ const run = lineOf(doc, ENGLISH);
+ const before = placements(doc);
+
+ edit(doc, new HistoryStack(), run, `${ENGLISH} 42`);
+
+ const after = placements(doc);
+ for (const [ptr, place] of before) expect(after.get(ptr)).toBe(place);
+ expect(texts(await reopened(doc))).toContain(`${ENGLISH} 42`);
+ });
+
+ test("survives a burst of edits, and undo puts every object back", async () => {
+ const doc = await open();
+ const history = new HistoryStack();
+ const run = lineOf(doc, HEBREW);
+ const before = placements(doc);
+ const steps = [
+ HEBREW.replace("03-555-1234", "03-555-12345"),
+ HEBREW.replace("03-555-1234", "03-555-12345").replace("Open ", ""),
+ `${HEBREW.replace("03-555-1234", "03-555-12345").replace("Open ", "")} 9`,
+ ];
+
+ for (const step of steps) edit(doc, history, run, step);
+
+ expect(run.text).toBe(steps[2]);
+ expect(texts(await reopened(doc))).toContain(steps[2]);
+ while (history.canUndo) history.undo(doc);
+ expect(run.text).toBe(HEBREW);
+ expect([...placements(doc)]).toEqual([...before]);
+ while (history.canRedo) history.redo(doc);
+ expect(run.text).toBe(steps[2]);
+ expect(texts(await reopened(doc))).toContain(steps[2]);
+ });
+
+ test("sets one space between words typed one after another beside a drawn space", async () => {
+ const doc = await open();
+ const history = new HistoryStack();
+ const run = lineOf(doc, HEBREW);
+ const at = HEBREW.indexOf("03-");
+ const [first, rest] = [HEBREW.slice(0, at), HEBREW.slice(at)];
+ edit(doc, history, run, `${first}\n${rest}`);
+ const before = placements(doc);
+
+ edit(doc, history, run, `${first} Pk\n${rest}`);
+ edit(doc, history, run, `${first} Pk zap\n${rest}`);
+
+ const typed = [...placements(doc).keys()]
+ .filter((ptr) => !before.has(ptr))
+ .map((ptr) => inkOf(doc, ptr))
+ .sort((a, b) => a.left - b.left);
+ expect(typed).toHaveLength(2);
+ const gap = typed[1].left - typed[0].right;
+ expect(gap).toBeGreaterThan(2);
+ expect(gap).toBeLessThan(4.5);
+ });
+
+ test("refuses a whole redraw that no font can draw the line's own letters for", async () => {
+ const doc = await open();
+ const history = new HistoryStack();
+ const run = lineOf(doc, ARABIC);
+ const before = placements(doc);
+ // A box resized to wrap is redrawn whole.
+ run.wrapWidthPt = run.bounds.width;
+
+ expect(() => edit(doc, history, run, `${ARABIC} 5`)).toThrow(
+ expect.objectContaining({ documentIntact: true }),
+ );
+
+ expect(run.text).toBe(ARABIC);
+ expect(history.canUndo).toBe(false);
+ expect([...placements(doc)]).toEqual([...before]);
+ });
+
+ test("leaves a save nothing to warn about when its whole redraw is refused", async () => {
+ const doc = await EditorDocument.open(
+ new Uint8Array(await readFile(SAMPLE)),
+ );
+ const store = new EditorStore();
+ await store.setDocument(doc);
+ try {
+ PdfiumTextReader.populate(doc, doc.page(0));
+ const run = lineOf(doc, ARABIC);
+ // A box resized to wrap is redrawn whole.
+ run.wrapWidthPt = run.bounds.width;
+
+ store.dispatch(
+ new EditTextCommand({
+ pageIndex: 0,
+ runId: run.id,
+ nextText: `${ARABIC} 5`,
+ }),
+ );
+
+ expect(store.getState().error).not.toBeNull();
+ expect(run.text).toBe(ARABIC);
+ expect(store.history.canUndo).toBe(false);
+ expect(detectSaveRisks(doc).droppedChars).toEqual([]);
+ } finally {
+ store.dispose();
+ }
+ });
+
+ test("leaves every line of a batch alone when one of its edits is refused", async () => {
+ const doc = await open();
+ const history = new HistoryStack();
+ const before = placements(doc);
+ const batch = [ARABIC, LATIN_FIRST].map(
+ (text) =>
+ new EditTextCommand({
+ pageIndex: 0,
+ runId: lineOf(doc, text).id,
+ nextText: text.replace("ISO 50001", "ISO 5000"),
+ }),
+ );
+
+ expect(() => history.execute(new CompositeCommand(batch), doc)).toThrow(
+ expect.objectContaining({ documentIntact: true }),
+ );
+
+ expect(texts(doc)).toContain(ARABIC);
+ expect(texts(doc)).toContain(LATIN_FIRST);
+ expect(history.canUndo).toBe(false);
+ expect([...placements(doc)]).toEqual([...before]);
+ });
+
+ test("refuses an edit of a line it could not lay out the same way", async () => {
+ const doc = await open();
+ const history = new HistoryStack();
+ const run = lineOf(doc, LATIN_FIRST);
+ const before = placements(doc);
+
+ expect(run.readingOrderUnsure).toBe(true);
+ expect(() => edit(doc, history, run, `${LATIN_FIRST} 5`)).toThrow(
+ expect.objectContaining({ documentIntact: true }),
+ );
+
+ expect(run.text).toBe(LATIN_FIRST);
+ expect(history.canUndo).toBe(false);
+ expect([...placements(doc)]).toEqual([...before]);
+ });
+});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/savedGraphicsStates.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/savedGraphicsStates.test.ts
new file mode 100644
index 0000000000..94ff3e9cb9
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/savedGraphicsStates.test.ts
@@ -0,0 +1,151 @@
+// @vitest-environment node
+import { readFile } from "node:fs/promises";
+import { createRequire } from "node:module";
+import { afterEach, beforeAll, expect, test, vi } from "vitest";
+import { EditTextCommand } from "@editor/tools/pdfTextEditor/commands/EditTextCommand";
+import { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
+import { toLatin1 } from "@editor/tools/pdfTextEditor/pdfdoc/bytes";
+import { parseOps } from "@editor/tools/pdfTextEditor/pdfdoc/contentOps";
+import { dictKeys, RawPdf } from "@editor/tools/pdfTextEditor/pdfdoc/raw";
+import { PdfiumTextReader } from "@editor/tools/pdfTextEditor/pdfium/PdfiumTextReader";
+import { HistoryStack } from "@editor/tools/pdfTextEditor/store/HistoryStack";
+import { exportToBlob } from "@editor/tools/pdfTextEditor/util/exportPdf";
+import {
+ buildClassicPdf,
+ streamBody,
+} from "@editor/tools/pdfTextEditor/__tests__/pdfFixtures";
+import {
+ changedPixels,
+ rasterFirstPage,
+} from "@editor/tools/pdfTextEditor/__tests__/pageRaster";
+
+const WIDTH = 612;
+const HEIGHT = 792;
+
+const opened: EditorDocument[] = [];
+
+beforeAll(async () => {
+ const wasm = await readFile(
+ createRequire(import.meta.url).resolve("@embedpdf/pdfium/pdfium.wasm"),
+ );
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(
+ async () =>
+ new Response(wasm, { headers: { "Content-Type": "application/wasm" } }),
+ ),
+ );
+});
+
+afterEach(() => {
+ for (const doc of opened.splice(0)) doc.dispose();
+});
+
+// Three lines, the top one drawn at 35% opacity when `translucent`.
+function threeLines(translucent: boolean): Uint8Array {
+ const top = translucent ? "q /GS gs " : "q ";
+ return buildClassicPdf(
+ [
+ { num: 1, body: "<< /Type /Catalog /Pages 2 0 R >>" },
+ { num: 2, body: "<< /Type /Pages /Kids [3 0 R] /Count 1 >>" },
+ {
+ num: 3,
+ body: `<< /Type /Page /Parent 2 0 R /MediaBox [0 0 ${WIDTH} ${HEIGHT}] /Contents 4 0 R /Resources << /ExtGState << /GS 8 0 R >> /Font << /F1 5 0 R /F2 6 0 R /F3 7 0 R >> >> >>`,
+ },
+ {
+ num: 4,
+ body: streamBody(
+ "",
+ `${top}BT /F1 12 Tf 72 700 Td (Top line) Tj ET Q\nBT /F2 12 Tf 72 680 Td (Lower paragraph) Tj ET\nBT /F3 12 Tf 72 660 Td (Third paragraph) Tj ET`,
+ ),
+ },
+ {
+ num: 5,
+ body: "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>",
+ },
+ { num: 6, body: "<< /Type /Font /Subtype /Type1 /BaseFont /Courier >>" },
+ {
+ num: 7,
+ body: "<< /Type /Font /Subtype /Type1 /BaseFont /Times-Roman >>",
+ },
+ { num: 8, body: "<< /Type /ExtGState /ca 0.35 /CA 1 >>" },
+ ],
+ 1,
+ );
+}
+
+async function open(bytes: Uint8Array): Promise<EditorDocument> {
+ const doc = await EditorDocument.open(bytes);
+ opened.push(doc);
+ PdfiumTextReader.populate(doc, doc.page(0));
+ return doc;
+}
+
+async function save(doc: EditorDocument): Promise<Uint8Array> {
+ return new Uint8Array(await (await exportToBlob(doc)).arrayBuffer());
+}
+
+// Every graphics state the page names with `gs` that its resources lack.
+async function undeclaredStates(bytes: Uint8Array): Promise<string[]> {
+ const pdf = (await RawPdf.parse(bytes))!;
+ const pageNum = pdf.pageNumberAt(0)!;
+ const resources = pdf.pageInherited(pageNum, "Resources") ?? "<< >>";
+ const states = pdf.resolve(resources, "ExtGState");
+ const declared = new Set(states ? (dictKeys(states) ?? []) : []);
+ const content = toLatin1((await pdf.pageContent(pageNum))!);
+ return parseOps(content)
+ .filter((op) => op.op === "gs")
+ .map((op) => op.operands[0].slice(1))
+ .filter((name) => !declared.has(name));
+}
+
+async function render(bytes: Uint8Array): Promise<Uint8Array> {
+ return rasterFirstPage(await open(bytes), WIDTH, HEIGHT);
+}
+
+// Darkest pixel among the rows the top line is drawn on.
+function darkestOnTopLine(pixels: Uint8Array): number {
+ let darkest = 255;
+ for (let y = HEIGHT - 712; y < HEIGHT - 696; y++)
+ for (let x = 60; x < 260; x++)
+ darkest = Math.min(darkest, pixels[(y * WIDTH + x) * 4]);
+ return darkest;
+}
+
+test.each([
+ ["translucent", true],
+ ["opaque", false],
+])(
+ "%s text keeps its look and every graphics state it names across saves, undos and redos",
+ async (_case, translucent) => {
+ const doc = await open(threeLines(translucent));
+ const top = doc.page(0).runs.find((r) => r.text === "Top line")!;
+ const history = new HistoryStack();
+ const edit = () =>
+ new EditTextCommand({
+ pageIndex: 0,
+ runId: top.id,
+ nextText: "Top line\nNew line",
+ });
+ history.execute(edit(), doc);
+ history.breakCoalescing();
+
+ const saves = [await save(doc)];
+ for (let cycle = 0; cycle < 2; cycle++) {
+ history.undo(doc);
+ history.redo(doc);
+ saves.push(await save(doc));
+ }
+ history.undo(doc);
+ await save(doc);
+ history.execute(edit(), doc);
+ saves.push(await save(doc));
+
+ const first = await render(saves[0]);
+ if (translucent) expect(darkestOnTopLine(first)).toBeGreaterThan(120);
+ for (const bytes of saves) {
+ expect(await undeclaredStates(bytes)).toEqual([]);
+ expect(changedPixels(first, await render(bytes))).toBe(0);
+ }
+ },
+);
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/scaledFormEdit.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/scaledFormEdit.test.ts
new file mode 100644
index 0000000000..148f8a1409
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/scaledFormEdit.test.ts
@@ -0,0 +1,570 @@
+// @vitest-environment node
+import { readFile } from "node:fs/promises";
+import { createRequire } from "node:module";
+import {
+ afterAll,
+ afterEach,
+ beforeAll,
+ describe,
+ expect,
+ test,
+ vi,
+} from "vitest";
+import { DeleteImageCommand } from "@editor/tools/pdfTextEditor/commands/DeleteImageCommand";
+import { DeleteShapeCommand } from "@editor/tools/pdfTextEditor/commands/DeleteShapeCommand";
+import { SetImageTransformCommand } from "@editor/tools/pdfTextEditor/commands/SetImageTransformCommand";
+import { DeleteObjectCommand } from "@editor/tools/pdfTextEditor/commands/DeleteObjectCommand";
+import { MoveTextRunCommand } from "@editor/tools/pdfTextEditor/commands/MoveTextRunCommand";
+import { SetColourCommand } from "@editor/tools/pdfTextEditor/commands/SetColourCommand";
+import { SetFontSizeCommand } from "@editor/tools/pdfTextEditor/commands/SetFontSizeCommand";
+import type { Command } from "@editor/tools/pdfTextEditor/commands/Command";
+import { exportToBlob } from "@editor/tools/pdfTextEditor/util/exportPdf";
+import { EditTextCommand } from "@editor/tools/pdfTextEditor/commands/EditTextCommand";
+import { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
+import { PdfiumTextReader } from "@editor/tools/pdfTextEditor/pdfium/PdfiumTextReader";
+import { HistoryStack } from "@editor/tools/pdfTextEditor/store/HistoryStack";
+import {
+ buildClassicPdf,
+ streamBody,
+} from "@editor/tools/pdfTextEditor/__tests__/pdfFixtures";
+
+// The form draws at a quarter of its own scale, as design tools export labels.
+const FORM_SCALE = 0.25;
+const FORM_X = 72;
+const SAVED_X = 72.468;
+
+function scaledFormPdf(): Uint8Array {
+ return buildClassicPdf(
+ [
+ { num: 1, body: "<< /Type /Catalog /Pages 2 0 R >>" },
+ { 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 " +
+ "/Resources << /XObject << /Fm1 5 0 R >> >> >>",
+ },
+ {
+ num: 4,
+ body: streamBody(
+ "",
+ `q ${FORM_SCALE} 0 0 ${FORM_SCALE} ${FORM_X} 700 cm /Fm1 Do Q\n`,
+ ),
+ },
+ {
+ num: 5,
+ body: streamBody(
+ "/Type /XObject /Subtype /Form /BBox [0 0 2000 400] " +
+ "/Resources << /Font << /F1 6 0 R >> >>",
+ "BT /F1 48 Tf 0 100 Td (Open Source) Tj ET\n",
+ ),
+ },
+ {
+ num: 6,
+ body: "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>",
+ },
+ ],
+ 1,
+ );
+}
+
+const opened: EditorDocument[] = [];
+
+beforeAll(async () => {
+ const wasm = await readFile(
+ createRequire(import.meta.url).resolve("@embedpdf/pdfium/pdfium.wasm"),
+ );
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async (url: string) =>
+ String(url).endsWith(".wasm")
+ ? new Response(wasm, {
+ headers: { "Content-Type": "application/wasm" },
+ })
+ : new Response(null, { status: 404 }),
+ ),
+ );
+});
+
+afterEach(() => {
+ for (const doc of opened.splice(0)) doc.dispose();
+});
+
+afterAll(() => vi.unstubAllGlobals());
+
+function leftEdge(doc: EditorDocument, ptr: number): number {
+ const m = doc.module;
+ const box = m.pdfium.wasmExports.malloc(16);
+ try {
+ m.FPDFPageObj_GetBounds(ptr, box, box + 4, box + 8, box + 12);
+ return m.pdfium.getValue(box, "float");
+ } finally {
+ m.pdfium.wasmExports.free(box);
+ }
+}
+
+// The same label one form deeper: the page draws a half-scale form that draws the label's form at half scale again.
+function nestedFormPdf(): Uint8Array {
+ return buildClassicPdf(
+ [
+ { num: 1, body: "<< /Type /Catalog /Pages 2 0 R >>" },
+ { 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 " +
+ "/Resources << /XObject << /Fm0 7 0 R >> >> >>",
+ },
+ {
+ num: 4,
+ body: streamBody("", `q 0.5 0 0 0.5 ${FORM_X} 700 cm /Fm0 Do Q\n`),
+ },
+ {
+ num: 5,
+ body: streamBody(
+ "/Type /XObject /Subtype /Form /BBox [0 0 2000 400] " +
+ "/Resources << /Font << /F1 6 0 R >> >>",
+ "BT /F1 48 Tf 0 100 Td (Open Source) Tj ET\n",
+ ),
+ },
+ {
+ num: 6,
+ body: "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>",
+ },
+ {
+ num: 7,
+ body: streamBody(
+ "/Type /XObject /Subtype /Form /BBox [0 0 4000 800] " +
+ "/Resources << /XObject << /Fm1 5 0 R >> >>",
+ "q 0.5 0 0 0.5 0 0 cm /Fm1 Do Q\n",
+ ),
+ },
+ ],
+ 1,
+ );
+}
+
+async function openForm(bytes: Uint8Array = scaledFormPdf()) {
+ const doc = await EditorDocument.open(bytes);
+ opened.push(doc);
+ PdfiumTextReader.populate(doc, doc.page(0));
+ const run = doc.page(0).runs.find((r) => r.text.includes("Open"))!;
+ return { doc, run };
+}
+
+async function saved(doc: EditorDocument) {
+ const { doc: reopened } = await openForm(
+ new Uint8Array(await (await exportToBlob(doc)).arrayBuffer()),
+ );
+ return reopened.page(0).runs;
+}
+
+const RED = { r: 220, g: 0, b: 0, a: 255 };
+
+describe("text drawn inside a form", () => {
+ test.each<
+ [
+ string,
+ (id: string) => Command,
+ (run: {
+ bounds: { x: number };
+ fill: { r: number };
+ fontSize: number;
+ }) => void,
+ ]
+ >([
+ [
+ "a move",
+ (runId) => new MoveTextRunCommand({ pageIndex: 0, runId, dx: 50, dy: 0 }),
+ (run) => expect(run.bounds.x).toBeCloseTo(SAVED_X + 50, 1),
+ ],
+ [
+ "a colour",
+ (runId) => new SetColourCommand({ pageIndex: 0, runId, nextFill: RED }),
+ (run) => {
+ expect(run.fill.r).toBe(220);
+ expect(run.bounds.x).toBeCloseTo(SAVED_X, 1);
+ },
+ ],
+ [
+ "a size",
+ (runId) => new SetFontSizeCommand({ pageIndex: 0, runId, nextSize: 24 }),
+ (run) => expect(run.fontSize).toBeCloseTo(24, 1),
+ ],
+ ])("keeps %s in the saved file", async (_edit, command, check) => {
+ const { doc, run } = await openForm();
+
+ command(run.id).apply(doc);
+
+ const [reopened, ...rest] = await saved(doc);
+ expect(rest).toHaveLength(0);
+ expect(reopened.text).toBe("Open Source");
+ check(reopened);
+ });
+
+ test.each([
+ ["a form", scaledFormPdf],
+ ["a form inside a form", nestedFormPdf],
+ ])("typed before it saves as one line, in %s", async (_case, pdf) => {
+ const { doc, run } = await openForm(pdf());
+ const left = run.bounds.x;
+
+ new EditTextCommand({
+ pageIndex: 0,
+ runId: run.id,
+ nextText: "Xk " + run.text,
+ }).apply(doc);
+
+ const [reopened, ...rest] = await saved(doc);
+ expect(rest).toHaveLength(0);
+ expect(reopened.text).toBe("Xk Open Source");
+ expect(reopened.bounds.x).toBeCloseTo(left, 0);
+ });
+
+ test.each([
+ [
+ "typing",
+ (id: string) =>
+ new EditTextCommand({
+ pageIndex: 0,
+ runId: id,
+ nextText: "Xk Open Source",
+ }),
+ ],
+ [
+ "a delete",
+ (id: string) => new DeleteObjectCommand({ pageIndex: 0, runId: id }),
+ ],
+ [
+ "a move",
+ (id: string) =>
+ new MoveTextRunCommand({ pageIndex: 0, runId: id, dx: 50, dy: 0 }),
+ ],
+ ])(
+ "undo of %s puts it back where it was, on the page and in the saved file",
+ async (_edit, command) => {
+ const { doc, run } = await openForm();
+ const label = run.mergedFromPtrs[0] || run.pdfiumObjPtr;
+ const edit = command(run.id);
+
+ edit.apply(doc);
+ edit.revert(doc);
+
+ expect(leftEdge(doc, label)).toBeCloseTo(SAVED_X, 1);
+ const [reopened, ...rest] = await saved(doc);
+ expect(rest).toHaveLength(0);
+ expect(reopened.text).toBe("Open Source");
+ expect(reopened.bounds.x).toBeCloseTo(SAVED_X, 1);
+ },
+ );
+
+ test("undo of a typing burst puts it back where it was, however often it is redone", async () => {
+ const { doc, run } = await openForm();
+ const label = run.mergedFromPtrs[0] || run.pdfiumObjPtr;
+ const history = new HistoryStack();
+ for (const prefix of ["X ", "XY "])
+ history.execute(
+ new EditTextCommand({
+ pageIndex: 0,
+ runId: run.id,
+ nextText: prefix + "Open Source",
+ }),
+ doc,
+ );
+ expect(history.size().undo).toBe(1);
+ history.undo(doc);
+ history.redo(doc);
+ const redone = leftEdge(doc, label);
+
+ for (let i = 0; i < 20; i++) {
+ history.undo(doc);
+ history.redo(doc);
+ }
+ expect(leftEdge(doc, label)).toBeCloseTo(redone, 3);
+ history.undo(doc);
+
+ expect(leftEdge(doc, label)).toBeCloseTo(SAVED_X, 1);
+ expect(run.text).toBe("Open Source");
+ });
+});
+
+// A red 100pt square drawn by a quarter-scale form.
+function formImagePdf(): Uint8Array {
+ return buildClassicPdf(
+ [
+ { num: 1, body: "<< /Type /Catalog /Pages 2 0 R >>" },
+ { 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 " +
+ "/Resources << /XObject << /Fm1 5 0 R >> >> >>",
+ },
+ {
+ num: 4,
+ body: streamBody(
+ "",
+ `q ${FORM_SCALE} 0 0 ${FORM_SCALE} ${FORM_X} 500 cm /Fm1 Do Q\n`,
+ ),
+ },
+ {
+ num: 5,
+ body: streamBody(
+ "/Type /XObject /Subtype /Form /BBox [0 0 2000 2000] " +
+ "/Resources << /XObject << /Im1 6 0 R >> >>",
+ "q 400 0 0 400 0 0 cm /Im1 Do Q\n",
+ ),
+ },
+ {
+ num: 6,
+ body: streamBody(
+ "/Type /XObject /Subtype /Image /Width 1 /Height 1 " +
+ "/ColorSpace /DeviceRGB /BitsPerComponent 8 /Filter /ASCIIHexDecode",
+ "FF0000>",
+ ),
+ },
+ ],
+ 1,
+ );
+}
+
+describe("an image drawn inside a form", () => {
+ async function openImage(bytes: Uint8Array = formImagePdf()) {
+ const doc = await EditorDocument.open(bytes);
+ opened.push(doc);
+ PdfiumTextReader.populate(doc, doc.page(0));
+ return { doc, images: doc.page(0).images };
+ }
+ async function savedImages(doc: EditorDocument) {
+ const { images } = await openImage(
+ new Uint8Array(await (await exportToBlob(doc)).arrayBuffer()),
+ );
+ return images;
+ }
+
+ test("is gone from the saved file once deleted, and back in place after undo", async () => {
+ const { doc, images } = await openImage();
+ const [image] = images;
+ const box = { ...image.bounds };
+ const remove = new DeleteImageCommand({ pageIndex: 0, imageId: image.id });
+
+ remove.apply(doc);
+ expect(await savedImages(doc)).toHaveLength(0);
+
+ remove.revert(doc);
+ const [back, ...rest] = await savedImages(doc);
+ expect(rest).toHaveLength(0);
+ expect(back.bounds.x).toBeCloseTo(box.x, 1);
+ expect(back.bounds.width).toBeCloseTo(box.width, 1);
+ });
+
+ test("keeps a move in the saved file", async () => {
+ const { doc, images } = await openImage();
+ const [image] = images;
+ const nextBounds = { ...image.bounds, x: image.bounds.x + 60 };
+
+ new SetImageTransformCommand({
+ pageIndex: 0,
+ imageId: image.id,
+ nextBounds,
+ }).apply(doc);
+
+ const [moved, ...rest] = await savedImages(doc);
+ expect(rest).toHaveLength(0);
+ expect(moved.bounds.x).toBeCloseTo(nextBounds.x, 1);
+ expect(moved.bounds.width).toBeCloseTo(nextBounds.width, 1);
+ });
+});
+
+// One form drawn twice on the first page and once on the second, holding two lines.
+function sharedFormPdf(): Uint8Array {
+ const draw = (y: number) =>
+ `q ${FORM_SCALE} 0 0 ${FORM_SCALE} ${FORM_X} ${y} cm /Fm1 Do Q\n`;
+ const page = (contents: number) =>
+ `<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents ${contents} 0 R ` +
+ "/Resources << /XObject << /Fm1 5 0 R >> >> >>";
+ return buildClassicPdf(
+ [
+ { num: 1, body: "<< /Type /Catalog /Pages 2 0 R >>" },
+ { num: 2, body: "<< /Type /Pages /Kids [3 0 R 7 0 R] /Count 2 >>" },
+ { num: 3, body: page(4) },
+ { num: 4, body: streamBody("", draw(700) + draw(400)) },
+ {
+ num: 5,
+ body: streamBody(
+ "/Type /XObject /Subtype /Form /BBox [0 0 2000 400] " +
+ "/Resources << /Font << /F1 6 0 R >> >>",
+ "BT /F1 48 Tf 0 100 Td (Open Source) Tj ET\n" +
+ "BT /F1 48 Tf 0 -100 Td (Second label) Tj ET\n",
+ ),
+ },
+ {
+ num: 6,
+ body: "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>",
+ },
+ { num: 7, body: page(8) },
+ { num: 8, body: streamBody("", draw(700)) },
+ ],
+ 1,
+ );
+}
+
+describe("a form drawn more than once", () => {
+ async function texts(doc: EditorDocument, pageIndex: number) {
+ const page = doc.page(pageIndex);
+ PdfiumTextReader.populate(doc, page);
+ return page.runs
+ .map((r) => `${r.text.trim()}@${Math.round(r.bounds.y)}`)
+ .sort();
+ }
+
+ test("keeps its text everywhere else when one copy is edited", async () => {
+ const doc = await EditorDocument.open(sharedFormPdf());
+ opened.push(doc);
+ const firstPage = await texts(doc, 0);
+ const secondPage = await texts(doc, 1);
+ const edited = doc
+ .page(0)
+ .runs.find((r) => r.text.includes("Open") && r.bounds.y > 600)!;
+
+ new SetColourCommand({
+ pageIndex: 0,
+ runId: edited.id,
+ nextFill: RED,
+ }).apply(doc);
+
+ const saved = await EditorDocument.open(
+ new Uint8Array(await (await exportToBlob(doc)).arrayBuffer()),
+ );
+ opened.push(saved);
+ expect(await texts(saved, 0)).toEqual(firstPage);
+ expect(await texts(saved, 1)).toEqual(secondPage);
+ const reds = saved.page(0).runs.filter((r) => r.fill.r === 220);
+ expect(reds.map((r) => r.text.trim())).toEqual(["Open Source"]);
+ });
+
+ test("leaves the other line of the edited copy in place and editable", async () => {
+ const doc = await EditorDocument.open(sharedFormPdf());
+ opened.push(doc);
+ const before = await texts(doc, 0);
+ const page = doc.page(0);
+ const first = page.runs.find(
+ (r) => r.text.includes("Open") && r.bounds.y > 600,
+ )!;
+ const second = page.runs.find(
+ (r) => r.text.includes("Second") && r.bounds.y > 600,
+ )!;
+
+ const was = `Second label@${Math.round(second.bounds.y)}`;
+
+ new SetColourCommand({
+ pageIndex: 0,
+ runId: first.id,
+ nextFill: RED,
+ }).apply(doc);
+ expect(second.containerPtr).toBe(0);
+ new MoveTextRunCommand({
+ pageIndex: 0,
+ runId: second.id,
+ dx: 0,
+ dy: -20,
+ }).apply(doc);
+
+ const saved = await EditorDocument.open(
+ new Uint8Array(await (await exportToBlob(doc)).arrayBuffer()),
+ );
+ opened.push(saved);
+ const moved = `Second label@${Math.round(second.bounds.y)}`;
+ expect(await texts(saved, 0)).toEqual(
+ before.map((line) => (line === was ? moved : line)).sort(),
+ );
+ });
+});
+
+// One form holding a filled panel, drawn twice on the first page and once on the second.
+function sharedPanelFormPdf(): Uint8Array {
+ const draw = (y: number) => `q 1 0 0 1 ${FORM_X} ${y} cm /Fm1 Do Q\n`;
+ const page = (contents: number) =>
+ `<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents ${contents} 0 R ` +
+ "/Resources << /XObject << /Fm1 5 0 R >> >> >>";
+ return buildClassicPdf(
+ [
+ { num: 1, body: "<< /Type /Catalog /Pages 2 0 R >>" },
+ { num: 2, body: "<< /Type /Pages /Kids [3 0 R 7 0 R] /Count 2 >>" },
+ { num: 3, body: page(4) },
+ { num: 4, body: streamBody("", draw(600) + draw(300)) },
+ {
+ num: 5,
+ body: streamBody(
+ "/Type /XObject /Subtype /Form /BBox [0 0 400 120] " +
+ "/Resources << /Font << /F1 6 0 R >> >>",
+ "1 0.9 0.2 rg 0 0 300 100 re f\n" +
+ "0 g BT /F1 12 Tf 10 40 Td (Panel label) Tj ET\n",
+ ),
+ },
+ {
+ num: 6,
+ body: "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>",
+ },
+ { num: 7, body: page(8) },
+ { num: 8, body: streamBody("", draw(600)) },
+ ],
+ 1,
+ );
+}
+
+describe("a shape in a form drawn more than once", () => {
+ function panels(doc: EditorDocument, pageIndex: number): number[] {
+ const page = doc.page(pageIndex);
+ if (!page.loaded) PdfiumTextReader.populate(doc, page);
+ return page.shapes.map((s) => Math.round(s.bounds.y)).sort();
+ }
+
+ async function savedPanels(doc: EditorDocument) {
+ const reopened = await EditorDocument.open(
+ new Uint8Array(await (await exportToBlob(doc)).arrayBuffer()),
+ );
+ opened.push(reopened);
+ return [panels(reopened, 0), panels(reopened, 1)];
+ }
+
+ async function deleteUpperPanel() {
+ const doc = await EditorDocument.open(sharedPanelFormPdf());
+ opened.push(doc);
+ panels(doc, 0);
+ panels(doc, 1);
+ const upper = doc.page(0).shapes.find((s) => s.bounds.y > 500)!;
+ const history = new HistoryStack();
+ history.execute(
+ new DeleteShapeCommand({ pageIndex: 0, shapeId: upper.id }),
+ doc,
+ );
+ return { doc, history };
+ }
+
+ test("is deleted from the copy it was picked in and nowhere else", async () => {
+ const { doc, history } = await deleteUpperPanel();
+
+ expect(panels(doc, 0)).toEqual([300]);
+ expect(await savedPanels(doc)).toEqual([[300], [600]]);
+
+ history.undo(doc);
+ expect(panels(doc, 0)).toEqual([300, 600]);
+ expect(await savedPanels(doc)).toEqual([[300, 600], [600]]);
+
+ history.redo(doc);
+ expect(await savedPanels(doc)).toEqual([[300], [600]]);
+ expect(await savedPanels(doc)).toEqual([[300], [600]]);
+ });
+
+ test("keeps the text of the copy it was deleted from", async () => {
+ const { doc } = await deleteUpperPanel();
+
+ const reopened = await saved(doc);
+ expect(
+ reopened
+ .filter((r) => r.text.includes("Panel"))
+ .map((r) => Math.round(r.bounds.y / 100)),
+ ).toEqual(expect.arrayContaining([6, 3]));
+ });
+});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/scanEditHistory.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/scanEditHistory.test.ts
index 280096d5e4..c209aa4eec 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/scanEditHistory.test.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/scanEditHistory.test.ts
@@ -25,6 +25,7 @@ vi.mock("@editor/tools/pdfTextEditor/commands/scanTextEdit", () => ({
isScanRun: (run: { renderMode?: number }) => run.renderMode === 3,
captureScanEdit: () => ({}) as ScanEditState,
renderScanEdit,
+ scanBlockBounds: () => null,
}));
function fixture() {
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/scanFontLibrary.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/scanFontLibrary.test.ts
index 87910ef6dc..7b73d607f8 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/scanFontLibrary.test.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/scanFontLibrary.test.ts
@@ -106,7 +106,7 @@ function labels(): string[] {
beforeEach(() => {
get.mockReset();
- jarFetch.mockClear();
+ jarFetch.mockReset();
vi.stubGlobal("fetch", jarFetch);
forgetServerFontList();
resetLocalFontsCache();
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/scanFontMatch.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/scanFontMatch.test.ts
index bc8c32e645..683093b523 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/scanFontMatch.test.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/scanFontMatch.test.ts
@@ -1457,6 +1457,9 @@ describe("edits that need no font, and text no font can draw", () => {
);
});
+// A blank scan: drawn behind the OCR text, so it is read as a scan, with no ink on it.
+const PAPER = "q 1 g 0 0 612 792 re f Q";
+
describe("reading scanned words inside a form", () => {
test("puts each word on its baseline on the page, not in the form", async () => {
const form =
@@ -1469,7 +1472,10 @@ describe("reading scanned words inside a form", () => {
num: 3,
body: "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources << /XObject << /Fx 6 0 R >> >> /Contents 4 0 R >>",
},
- { num: 4, body: streamBody("", "q 1 0 0 1 0 300 cm /Fx Do Q") },
+ {
+ num: 4,
+ body: streamBody("", `${PAPER} q 1 0 0 1 0 300 cm /Fx Do Q`),
+ },
{
num: 5,
body: "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>",
@@ -1514,7 +1520,7 @@ describe("scanned text whose OCR words do not line up with the scan", () => {
num: 4,
body: streamBody(
"",
- `BT /F1 12 Tf 3 Tr ${scale} Tz 1 0 0 1 50 700 Tm (Invoice for Jane Example) Tj ET`,
+ `${PAPER} BT /F1 12 Tf 3 Tr ${scale} Tz 1 0 0 1 50 700 Tm (Invoice for Jane Example) Tj ET`,
),
},
{
@@ -1624,7 +1630,7 @@ describe("scanned text whose OCR layer sits off the scanned words", () => {
num: 4,
body: streamBody(
"",
- "BT /F1 12 Tf 3 Tr 1 0 0 1 50 700 Tm (Invoice for Jane Example) Tj ET",
+ `${PAPER} BT /F1 12 Tf 3 Tr 1 0 0 1 50 700 Tm (Invoice for Jane Example) Tj ET`,
),
},
{
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/scanLayout.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/scanLayout.test.ts
index d39a0b6a69..1e124d69ca 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/scanLayout.test.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/scanLayout.test.ts
@@ -156,6 +156,16 @@ describe("layoutScanEdit", () => {
expect(l.kept.every((k) => !k.moved)).toBe(true);
});
+ it("typing at the end of a line draws past text already drawn there", () => {
+ const lines = block("TRADING CO");
+ const coEnd = lines[0].words[1].x + 10;
+ const earlier = { line: 0, x: coEnd + 4, right: coEnd + 4 + 15 };
+ const l = run(lines, "TRADING CO LTD", { obstacles: [earlier] });
+ expect(l.typed).toEqual([
+ expect.objectContaining({ text: "LTD", x: earlier.right + 4 }),
+ ]);
+ });
+
it("a restyle redraws every word as text", () => {
const l = run(block("NORTH CO", "TEL 1"), "NORTH CO\nTEL 1", {
redraw: true,
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/scanLineLook.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/scanLineLook.test.ts
new file mode 100644
index 0000000000..eb82f26902
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/scanLineLook.test.ts
@@ -0,0 +1,179 @@
+// @vitest-environment node
+import { readFile } from "node:fs/promises";
+import { createRequire } from "node:module";
+import path from "node:path";
+import {
+ afterAll,
+ afterEach,
+ beforeAll,
+ beforeEach,
+ expect,
+ test,
+ vi,
+} from "vitest";
+import { EditTextCommand } from "@editor/tools/pdfTextEditor/commands/EditTextCommand";
+import {
+ isScanRun,
+ prefitScanRun,
+} from "@editor/tools/pdfTextEditor/commands/scanTextEdit";
+import { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
+import { PdfiumTextReader } from "@editor/tools/pdfTextEditor/pdfium/PdfiumTextReader";
+import type { TextRun } from "@editor/tools/pdfTextEditor/model/TextRun";
+import { EditorStore } from "@editor/tools/pdfTextEditor/store/EditorStore";
+import { exportToBlob } from "@editor/tools/pdfTextEditor/util/exportPdf";
+import {
+ _resetScanFacesForTests,
+ _setBundledScanFacesForTests,
+ type Face,
+} from "@editor/tools/pdfTextEditor/util/scanFontLibrary";
+import { readBundledFaces } from "@editor/tools/pdfTextEditor/__tests__/scanFixtures";
+
+const { get } = vi.hoisted(() => ({ get: vi.fn() }));
+vi.mock("@editor/services/apiClient", () => ({ default: { get } }));
+
+const FIXTURE = path.join(
+ import.meta.dirname,
+ "../../../tests/test-fixtures/scanned-ocr-outlined-address.pdf",
+);
+
+class TestImageData {
+ constructor(
+ readonly data: Uint8ClampedArray,
+ readonly width: number,
+ readonly height: number,
+ ) {}
+}
+
+let bundled: Face[] = [];
+const stores: EditorStore[] = [];
+const docs: EditorDocument[] = [];
+
+beforeAll(async () => {
+ const wasmBytes = await readFile(
+ createRequire(import.meta.url).resolve("@embedpdf/pdfium/pdfium.wasm"),
+ );
+ vi.stubGlobal("ImageData", TestImageData);
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(
+ async () =>
+ new Response(wasmBytes, {
+ headers: { "Content-Type": "application/wasm" },
+ }),
+ ),
+ );
+ bundled = await readBundledFaces();
+});
+
+beforeEach(() => _setBundledScanFacesForTests(bundled));
+
+afterEach(() => {
+ for (const store of stores.splice(0)) store.dispose();
+ for (const doc of docs.splice(0)) doc.dispose();
+});
+
+afterAll(() => {
+ _resetScanFacesForTests();
+ vi.unstubAllGlobals();
+});
+
+async function openAddress() {
+ const doc = await EditorDocument.open(
+ new Uint8Array(await readFile(FIXTURE)),
+ );
+ const store = new EditorStore();
+ stores.push(store);
+ await store.setDocument(doc);
+ const page = doc.page(0);
+ PdfiumTextReader.populate(doc, page);
+ const run = page.runs.find((r) => isScanRun(r) && r.text.includes("4EE"))!;
+ while (!prefitScanRun(doc, page, run, performance.now() + 50))
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ return { doc, store, run };
+}
+
+const FILL_AND_STROKE = 2;
+
+function drawnHeavy(doc: EditorDocument, run: TextRun): boolean[] {
+ const m = doc.module;
+ return (run.scanEdit?.textPtrs ?? []).map((p) => {
+ const font = m.FPDFTextObj_GetFont(p);
+ const len = m.FPDFFont_GetBaseFontName(font, 0, 0);
+ const buf = m.pdfium.wasmExports.malloc(len);
+ try {
+ m.FPDFFont_GetBaseFontName(font, buf, len);
+ return (
+ /bold/i.test(m.pdfium.UTF8ToString(buf)) ||
+ m.FPDFTextObj_GetTextRenderMode(p) === FILL_AND_STROKE
+ );
+ } finally {
+ m.pdfium.wasmExports.free(buf);
+ }
+ });
+}
+
+async function visibleRunsAfterSave(doc: EditorDocument) {
+ const saved = await EditorDocument.open(
+ new Uint8Array(await (await exportToBlob(doc)).arrayBuffer()),
+ );
+ docs.push(saved);
+ const page = saved.page(0);
+ PdfiumTextReader.populate(saved, page);
+ return page.runs.filter((r) => !isScanRun(r) && r.text.trim() !== "");
+}
+
+test(
+ "a word typed into a black line of a scanned paragraph keeps that line's colour and weight, not a blue bold line's below it",
+ { timeout: 180_000 },
+ async () => {
+ const { doc, store, run } = await openAddress();
+ expect(run.text.split("\n")).toHaveLength(5);
+
+ store.dispatch(
+ new EditTextCommand({
+ pageIndex: 0,
+ runId: run.id,
+ nextText: run.text.replace("4EE", "4EEX"),
+ }),
+ );
+ const heavy = drawnHeavy(doc, run);
+ expect(heavy.length).toBeGreaterThan(0);
+ expect(heavy.every((h) => !h)).toBe(true);
+
+ const typed = (await visibleRunsAfterSave(doc)).filter((r) =>
+ r.text.includes("4EEX"),
+ );
+ expect(typed.length).toBeGreaterThan(0);
+ for (const r of typed) {
+ expect(Math.max(r.fill.r, r.fill.g, r.fill.b)).toBeLessThan(80);
+ }
+ },
+);
+
+test(
+ "a word typed into the blue bold line of the same paragraph stays blue and bold",
+ { timeout: 180_000 },
+ async () => {
+ const { doc, store, run } = await openAddress();
+
+ store.dispatch(
+ new EditTextCommand({
+ pageIndex: 0,
+ runId: run.id,
+ nextText: run.text.replace("contact", "contactX"),
+ }),
+ );
+ const heavy = drawnHeavy(doc, run);
+ expect(heavy.length).toBeGreaterThan(0);
+ expect(heavy.every((h) => h)).toBe(true);
+
+ const typed = (await visibleRunsAfterSave(doc)).filter((r) =>
+ r.text.includes("contactX"),
+ );
+ expect(typed.length).toBeGreaterThan(0);
+ for (const r of typed) {
+ expect(r.fill.b).toBeGreaterThan(150);
+ expect(r.fill.r).toBeLessThan(80);
+ }
+ },
+);
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/scanResize.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/scanResize.test.ts
new file mode 100644
index 0000000000..ee367530fd
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/scanResize.test.ts
@@ -0,0 +1,261 @@
+// @vitest-environment node
+import { readFile } from "node:fs/promises";
+import { createRequire } from "node:module";
+import path from "node:path";
+import {
+ afterAll,
+ afterEach,
+ beforeAll,
+ beforeEach,
+ expect,
+ test,
+ vi,
+} from "vitest";
+import { EditTextCommand } from "@editor/tools/pdfTextEditor/commands/EditTextCommand";
+import { resizeRunCommand } from "@editor/tools/pdfTextEditor/commands/resizeRun";
+import {
+ isScanRun,
+ prefitScanRun,
+} from "@editor/tools/pdfTextEditor/commands/scanTextEdit";
+import { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
+import type { Page } from "@editor/tools/pdfTextEditor/model/Page";
+import { PdfiumPageRenderer } from "@editor/tools/pdfTextEditor/pdfium/PdfiumPageRenderer";
+import { PdfiumTextReader } from "@editor/tools/pdfTextEditor/pdfium/PdfiumTextReader";
+import { EditorStore } from "@editor/tools/pdfTextEditor/store/EditorStore";
+import { exportToBlob } from "@editor/tools/pdfTextEditor/util/exportPdf";
+import {
+ _resetScanFacesForTests,
+ _setBundledScanFacesForTests,
+ type Face,
+} from "@editor/tools/pdfTextEditor/util/scanFontLibrary";
+import { readBundledFaces } from "@editor/tools/pdfTextEditor/__tests__/scanFixtures";
+import { differingPixels } from "@editor/tools/pdfTextEditor/__tests__/pageRaster";
+
+const { get } = vi.hoisted(() => ({ get: vi.fn() }));
+vi.mock("@editor/services/apiClient", () => ({ default: { get } }));
+
+const SCALE = 2;
+const FIXTURE = path.join(
+ import.meta.dirname,
+ "../../../tests/test-fixtures/scanned-ocr-paragraph.pdf",
+);
+
+class TestImageData {
+ constructor(
+ readonly data: Uint8ClampedArray,
+ readonly width: number,
+ readonly height: number,
+ ) {}
+}
+
+let bundled: Face[] = [];
+const stores: EditorStore[] = [];
+
+beforeAll(async () => {
+ const wasmBytes = await readFile(
+ createRequire(import.meta.url).resolve("@embedpdf/pdfium/pdfium.wasm"),
+ );
+ vi.stubGlobal("ImageData", TestImageData);
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(
+ async () =>
+ new Response(wasmBytes, {
+ headers: { "Content-Type": "application/wasm" },
+ }),
+ ),
+ );
+ bundled = await readBundledFaces();
+});
+
+beforeEach(() => _setBundledScanFacesForTests(bundled));
+
+afterEach(() => {
+ for (const store of stores.splice(0)) store.dispose();
+});
+
+afterAll(() => {
+ _resetScanFacesForTests();
+ vi.unstubAllGlobals();
+});
+
+function inkPixels(
+ image: ImageData,
+ page: Page,
+ area: { x: number; y: number; width: number; height: number },
+): number {
+ let count = 0;
+ const top = Math.floor((page.height - area.y - area.height) * SCALE);
+ const bottom = Math.ceil((page.height - area.y) * SCALE);
+ for (let y = Math.max(0, top); y < Math.min(image.height, bottom); y++)
+ for (
+ let x = Math.max(0, Math.floor(area.x * SCALE));
+ x < Math.min(image.width, Math.ceil((area.x + area.width) * SCALE));
+ x++
+ ) {
+ const i = (y * image.width + x) * 4;
+ if (image.data[i] + image.data[i + 1] + image.data[i + 2] < 3 * 160)
+ count++;
+ }
+ return count;
+}
+
+async function openParagraph(bytes: Uint8Array) {
+ const doc = await EditorDocument.open(bytes);
+ const store = new EditorStore();
+ stores.push(store);
+ await store.setDocument(doc);
+ const page = doc.page(0);
+ PdfiumTextReader.populate(doc, page);
+ const run = page.runs.find(
+ (r) => isScanRun(r) && r.text.startsWith("This agreement"),
+ )!;
+ return { doc, store, page, run };
+}
+
+test(
+ "narrowing a scanned paragraph rewraps its words into the new width, as one undo step",
+ { timeout: 180_000 },
+ async () => {
+ const { doc, store, page, run } = await openParagraph(
+ new Uint8Array(await readFile(FIXTURE)),
+ );
+ while (!prefitScanRun(doc, page, run, performance.now() + 50))
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ const original = run.text;
+ const oldBounds = { ...run.bounds };
+ const width = oldBounds.width * 0.6;
+ const before = await PdfiumPageRenderer.render(doc, page, SCALE);
+
+ const cmd = resizeRunCommand(doc, 0, run.id, width);
+ expect(cmd).toBeInstanceOf(EditTextCommand);
+ store.dispatch(cmd!);
+
+ const wrapped = run.text;
+ const resized = { ...run.bounds };
+ const lineHeight = oldBounds.height / original.split("\n").length;
+ expect(resized.x).toBeGreaterThan(oldBounds.x - 2);
+ expect(resized.x + resized.width).toBeLessThanOrEqual(
+ oldBounds.x + width + 2,
+ );
+ expect(resized.height).toBeGreaterThan(
+ lineHeight * (wrapped.split("\n").length - 0.5),
+ );
+ expect(wrapped.split("\n").length).toBeGreaterThan(
+ original.split("\n").length,
+ );
+ expect(wrapped.replace(/\s+/g, " ")).toBe(original.replace(/\s+/g, " "));
+ const after = await PdfiumPageRenderer.render(doc, page, SCALE);
+ const right = oldBounds.x + width + 2;
+ expect(
+ inkPixels(after, page, {
+ x: right,
+ y: oldBounds.y - lineHeight * 3,
+ width: oldBounds.x + oldBounds.width + 4 - right,
+ height: oldBounds.height + lineHeight * 3,
+ }),
+ ).toBe(0);
+ expect(
+ inkPixels(before, page, {
+ x: right,
+ y: oldBounds.y,
+ width: oldBounds.x + oldBounds.width + 4 - right,
+ height: oldBounds.height,
+ }),
+ ).toBeGreaterThan(0);
+
+ const lines = run.scanEdit!.lines;
+ const inkTops = [...run.scanEdit!.inks]
+ .filter(([key, ink]) => ink && key.split(":")[1] === key.split(":")[2])
+ .map(([key, ink]) => {
+ const [li, wi] = key.split(":").map(Number);
+ const word = lines[li].words[wi];
+ return {
+ text: word.text.trim(),
+ top: ink!.ink.rect.y + ink!.ink.rect.height - word.baseline,
+ };
+ });
+ const tallest = Math.max(...inkTops.map((w) => w.top));
+ expect(
+ inkTops
+ .filter((w) => /[ij]/.test(w.text) && w.top < tallest * 0.9)
+ .map((w) => w.text),
+ ).toEqual([]);
+
+ store.undo();
+ expect(run.text).toBe(original);
+ expect(run.bounds).toEqual(oldBounds);
+ expect(
+ differingPixels(
+ before,
+ await PdfiumPageRenderer.render(doc, page, SCALE),
+ ),
+ ).toBe(0);
+
+ store.redo();
+ expect(run.text).toBe(wrapped);
+ expect(run.bounds).toEqual(resized);
+ expect(
+ differingPixels(after, await PdfiumPageRenderer.render(doc, page, SCALE)),
+ ).toBe(0);
+
+ const saved = new Uint8Array(await (await exportToBlob(doc)).arrayBuffer());
+ const reopened = await openParagraph(saved);
+ expect(reopened.run.text).toBe(wrapped);
+ },
+);
+
+test(
+ "a resize straight after typing in a scanned paragraph undoes on its own",
+ { timeout: 180_000 },
+ async () => {
+ const { doc, store, page, run } = await openParagraph(
+ new Uint8Array(await readFile(FIXTURE)),
+ );
+ while (!prefitScanRun(doc, page, run, performance.now() + 50))
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ const typed = run.text.replace("supplier\n", "supplier,\n");
+ store.dispatch(
+ new EditTextCommand({ pageIndex: 0, runId: run.id, nextText: typed }),
+ );
+ store.dispatch(resizeRunCommand(doc, 0, run.id, run.bounds.width * 0.6)!);
+ expect(run.text).not.toBe(typed);
+
+ store.undo();
+ expect(run.text).toBe(typed);
+ },
+);
+
+test(
+ "typing a line into a scanned paragraph grows its box, and undo puts the box back",
+ { timeout: 180_000 },
+ async () => {
+ const { doc, store, page, run } = await openParagraph(
+ new Uint8Array(await readFile(FIXTURE)),
+ );
+ while (!prefitScanRun(doc, page, run, performance.now() + 50))
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ const original = run.text;
+ const oldBounds = { ...run.bounds };
+ const lineHeight = oldBounds.height / original.split("\n").length;
+
+ store.dispatch(
+ new EditTextCommand({
+ pageIndex: 0,
+ runId: run.id,
+ nextText: `${original}\nThank you.`,
+ }),
+ );
+ const grown = { ...run.bounds };
+ expect(grown.y).toBeLessThan(oldBounds.y - lineHeight * 0.5);
+ expect(grown.y + grown.height).toBeCloseTo(
+ oldBounds.y + oldBounds.height,
+ -1,
+ );
+
+ store.undo();
+ expect(run.bounds).toEqual(oldBounds);
+ store.redo();
+ expect(run.bounds).toEqual(grown);
+ },
+);
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/scanTesseractSave.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/scanTesseractSave.test.ts
new file mode 100644
index 0000000000..375a6c9245
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/scanTesseractSave.test.ts
@@ -0,0 +1,146 @@
+// @vitest-environment node
+import { readFile } from "node:fs/promises";
+import { createRequire } from "node:module";
+import path from "node:path";
+import {
+ afterAll,
+ afterEach,
+ beforeAll,
+ beforeEach,
+ expect,
+ test,
+ vi,
+} from "vitest";
+import { EditTextCommand } from "@editor/tools/pdfTextEditor/commands/EditTextCommand";
+import { exportToBlob } from "@editor/tools/pdfTextEditor/util/exportPdf";
+import {
+ isScanRun,
+ prefitScanRun,
+} from "@editor/tools/pdfTextEditor/commands/scanTextEdit";
+import { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
+import { PdfiumTextReader } from "@editor/tools/pdfTextEditor/pdfium/PdfiumTextReader";
+import { EditorStore } from "@editor/tools/pdfTextEditor/store/EditorStore";
+import {
+ _resetScanFacesForTests,
+ _setBundledScanFacesForTests,
+ type Face,
+} from "@editor/tools/pdfTextEditor/util/scanFontLibrary";
+import { readBundledFaces } from "@editor/tools/pdfTextEditor/__tests__/scanFixtures";
+
+const { get } = vi.hoisted(() => ({ get: vi.fn() }));
+vi.mock("@editor/services/apiClient", () => ({ default: { get } }));
+
+const FIXTURE = path.join(
+ import.meta.dirname,
+ "../../../tests/test-fixtures/scanned-ocr-tesseract.pdf",
+);
+
+class TestImageData {
+ constructor(
+ readonly data: Uint8ClampedArray,
+ readonly width: number,
+ readonly height: number,
+ ) {}
+}
+
+let bundled: Face[] = [];
+const stores: EditorStore[] = [];
+
+beforeAll(async () => {
+ const wasmBytes = await readFile(
+ createRequire(import.meta.url).resolve("@embedpdf/pdfium/pdfium.wasm"),
+ );
+ vi.stubGlobal("ImageData", TestImageData);
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(
+ async () =>
+ new Response(wasmBytes, {
+ headers: { "Content-Type": "application/wasm" },
+ }),
+ ),
+ );
+ bundled = await readBundledFaces();
+});
+
+beforeEach(() => _setBundledScanFacesForTests(bundled));
+
+afterEach(() => {
+ for (const store of stores.splice(0)) store.dispose();
+});
+
+afterAll(() => {
+ _resetScanFacesForTests();
+ vi.unstubAllGlobals();
+});
+
+async function openParagraph(bytes: Uint8Array) {
+ const doc = await EditorDocument.open(bytes);
+ const store = new EditorStore();
+ stores.push(store);
+ await store.setDocument(doc);
+ const page = doc.page(0);
+ PdfiumTextReader.populate(doc, page);
+ const run = page.runs.find(
+ (r) => isScanRun(r) && r.text.startsWith("The quick"),
+ )!;
+ return { doc, store, page, run };
+}
+
+async function fitted() {
+ const opened = await openParagraph(new Uint8Array(await readFile(FIXTURE)));
+ while (
+ !prefitScanRun(opened.doc, opened.page, opened.run, performance.now() + 50)
+ )
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ return opened;
+}
+
+const LINES = [
+ "The quick brown fox jumps over the lazy dog while",
+ "the farmer counts his sheep in the field. Pack my box with five dozen",
+ "liquor jugs before the market closes for the evening.",
+ "Sphinx of black quartz, judge my vow. How vexingly quick",
+ "daft zebras jump when the wizard calls them home.",
+];
+
+const flat = (text: string) => text.replace(/\s+/g, " ").trim();
+
+test(
+ "reads each Tesseract line whole, though every word's space overhangs the next",
+ { timeout: 180_000 },
+ async () => {
+ const { run } = await openParagraph(
+ new Uint8Array(await readFile(FIXTURE)),
+ );
+ expect(run.text.split("\n").map(flat)).toEqual(LINES);
+ },
+);
+
+test(
+ "keeps the space between every word of the lines a typed line pushes down",
+ { timeout: 180_000 },
+ async () => {
+ const { doc, store, run } = await fitted();
+ store.dispatch(
+ new EditTextCommand({
+ pageIndex: 0,
+ runId: run.id,
+ nextText: run.text.replace(/while\s*\n/, "while\nadded line\n"),
+ }),
+ );
+ const saved = await EditorDocument.open(
+ new Uint8Array(await (await exportToBlob(doc)).arrayBuffer()),
+ );
+ try {
+ const page = saved.page(0);
+ PdfiumTextReader.populate(saved, page);
+ const text = page.runs.map((r) => flat(r.text)).join(" ");
+ expect(text).toBe(
+ flat([LINES[0], "added line", ...LINES.slice(1)].join(" ")),
+ );
+ } finally {
+ saved.dispose();
+ }
+ },
+);
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/scanWidenRejoins.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/scanWidenRejoins.test.ts
new file mode 100644
index 0000000000..fba955be29
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/scanWidenRejoins.test.ts
@@ -0,0 +1,212 @@
+// @vitest-environment node
+import { readFile } from "node:fs/promises";
+import { createRequire } from "node:module";
+import path from "node:path";
+import {
+ afterAll,
+ afterEach,
+ beforeAll,
+ beforeEach,
+ expect,
+ test,
+ vi,
+} from "vitest";
+import { EditTextCommand } from "@editor/tools/pdfTextEditor/commands/EditTextCommand";
+import { resizeRunCommand } from "@editor/tools/pdfTextEditor/commands/resizeRun";
+import { exportToBlob } from "@editor/tools/pdfTextEditor/util/exportPdf";
+import {
+ isScanRun,
+ prefitScanRun,
+} from "@editor/tools/pdfTextEditor/commands/scanTextEdit";
+import { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
+import { PdfiumTextReader } from "@editor/tools/pdfTextEditor/pdfium/PdfiumTextReader";
+import { EditorStore } from "@editor/tools/pdfTextEditor/store/EditorStore";
+import {
+ _resetScanFacesForTests,
+ _setBundledScanFacesForTests,
+ type Face,
+} from "@editor/tools/pdfTextEditor/util/scanFontLibrary";
+import { readBundledFaces } from "@editor/tools/pdfTextEditor/__tests__/scanFixtures";
+
+const { get } = vi.hoisted(() => ({ get: vi.fn() }));
+vi.mock("@editor/services/apiClient", () => ({ default: { get } }));
+
+const FIXTURE = path.join(
+ import.meta.dirname,
+ "../../../tests/test-fixtures/scanned-ocr-paragraph.pdf",
+);
+
+class TestImageData {
+ constructor(
+ readonly data: Uint8ClampedArray,
+ readonly width: number,
+ readonly height: number,
+ ) {}
+}
+
+let bundled: Face[] = [];
+const stores: EditorStore[] = [];
+
+beforeAll(async () => {
+ const wasmBytes = await readFile(
+ createRequire(import.meta.url).resolve("@embedpdf/pdfium/pdfium.wasm"),
+ );
+ vi.stubGlobal("ImageData", TestImageData);
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(
+ async () =>
+ new Response(wasmBytes, {
+ headers: { "Content-Type": "application/wasm" },
+ }),
+ ),
+ );
+ bundled = await readBundledFaces();
+});
+
+beforeEach(() => _setBundledScanFacesForTests(bundled));
+
+afterEach(() => {
+ for (const store of stores.splice(0)) store.dispose();
+});
+
+afterAll(() => {
+ _resetScanFacesForTests();
+ vi.unstubAllGlobals();
+});
+
+async function openParagraph(bytes: Uint8Array) {
+ const doc = await EditorDocument.open(bytes);
+ const store = new EditorStore();
+ stores.push(store);
+ await store.setDocument(doc);
+ const page = doc.page(0);
+ PdfiumTextReader.populate(doc, page);
+ const run = page.runs.find(
+ (r) => isScanRun(r) && r.text.startsWith("This agreement"),
+ )!;
+ return { doc, store, page, run };
+}
+
+async function fitted() {
+ const opened = await openParagraph(new Uint8Array(await readFile(FIXTURE)));
+ while (
+ !prefitScanRun(opened.doc, opened.page, opened.run, performance.now() + 50)
+ )
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ return opened;
+}
+
+test(
+ "widening a narrowed scanned paragraph back rejoins the lines the narrowing broke",
+ { timeout: 180_000 },
+ async () => {
+ const { doc, store, run } = await fitted();
+ const original = run.text;
+ const width = run.bounds.width;
+
+ store.dispatch(resizeRunCommand(doc, 0, run.id, width * 0.6)!);
+ expect(run.text.split("\n").length).toBeGreaterThan(
+ original.split("\n").length,
+ );
+ store.dispatch(resizeRunCommand(doc, 0, run.id, width + 1)!);
+
+ expect(run.text).toBe(original);
+ },
+);
+
+test(
+ "widening a scanned paragraph past its margin joins the lines the scan wrapped, as one undo step",
+ { timeout: 180_000 },
+ async () => {
+ const { doc, store, run } = await fitted();
+ const original = run.text;
+
+ store.dispatch(resizeRunCommand(doc, 0, run.id, run.bounds.width * 1.5)!);
+ const widened = run.text;
+ expect(widened.split("\n").length).toBeLessThan(
+ original.split("\n").length,
+ );
+ expect(widened.replace(/\s+/g, " ")).toBe(original.replace(/\s+/g, " "));
+
+ store.undo();
+ expect(run.text).toBe(original);
+ store.redo();
+ expect(run.text).toBe(widened);
+ },
+);
+
+const EDITS: Array<[string, (text: string) => string]> = [
+ [
+ "an Enter typed after a sentence",
+ (text) => text.replace("customer. ", "customer. \n"),
+ ],
+ ["a typed word", (text) => text.replace("goods", "boxed goods")],
+ ["a deleted word", (text) => text.replace("goods ", "")],
+];
+
+test.each(EDITS)(
+ "after %s in a narrowed scanned paragraph, widening rejoins the wraps and keeps a typed break",
+ { timeout: 180_000 },
+ async (name, edit) => {
+ const { doc, store, run } = await fitted();
+ const width = run.bounds.width;
+
+ store.dispatch(resizeRunCommand(doc, 0, run.id, width * 0.6)!);
+ const narrowed = run.text;
+ const edited = edit(narrowed);
+ expect(edited).not.toBe(narrowed);
+ store.dispatch(
+ new EditTextCommand({ pageIndex: 0, runId: run.id, nextText: edited }),
+ );
+ const linesBefore = run.text.split("\n").length;
+
+ const widen = resizeRunCommand(doc, 0, run.id, width * 1.5);
+ expect(widen).not.toBeNull();
+ store.dispatch(widen!);
+ const widened = run.text;
+
+ expect(widened.split("\n").length).toBeLessThan(linesBefore);
+ expect(widened.replace(/\s+/g, " ")).toBe(edited.replace(/\s+/g, " "));
+ if (name.startsWith("an Enter"))
+ expect(widened).toMatch(/customer\.\s*\n\s*The supplier/);
+
+ store.undo();
+ expect(run.text).toBe(edited);
+ store.redo();
+ expect(run.text).toBe(widened);
+ },
+);
+
+test.each([
+ ["narrowing and widening", (text: string) => text],
+ [
+ "an Enter typed after a sentence",
+ (text: string) => text.replace("customer. ", "customer. \n"),
+ ],
+])(
+ "after %s, a saved scanned paragraph reopens as one run with the same lines",
+ { timeout: 180_000 },
+ async (_name, edit) => {
+ const { doc, store, run } = await fitted();
+ const width = run.bounds.width;
+ store.dispatch(resizeRunCommand(doc, 0, run.id, width * 0.6)!);
+ const edited = edit(run.text);
+ if (edited !== run.text)
+ store.dispatch(
+ new EditTextCommand({ pageIndex: 0, runId: run.id, nextText: edited }),
+ );
+ store.dispatch(resizeRunCommand(doc, 0, run.id, width * 1.5)!);
+ const lines = run.text.split("\n").map((line) => line.trim());
+
+ const saved = new Uint8Array(await (await exportToBlob(doc)).arrayBuffer());
+ const reopened = await openParagraph(saved);
+
+ expect(
+ reopened.page.runs.filter((r) => r.text.includes("agreement")),
+ ).toHaveLength(1);
+ expect(reopened.run.text.split("\n").map((line) => line.trim())).toEqual(
+ lines,
+ );
+ },
+);
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/selectionToolbarState.test.tsx b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/selectionToolbarState.test.tsx
new file mode 100644
index 0000000000..713d7321c3
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/selectionToolbarState.test.tsx
@@ -0,0 +1,166 @@
+import { MantineProvider } from "@mantine/core";
+import { act, render, renderHook, screen } from "@testing-library/react";
+import { beforeAll, expect, test, vi } from "vitest";
+
+const { get } = vi.hoisted(() => ({ get: vi.fn() }));
+vi.mock("@editor/services/apiClient", () => ({ default: { get } }));
+
+import { FormatGroup } from "@editor/tools/pdfTextEditor/components/toolbar/FormatGroup";
+import { StyleTextRangeCommand } from "@editor/tools/pdfTextEditor/commands/StyleTextRangeCommand";
+import { useToolbarController } from "@editor/tools/pdfTextEditor/hooks/useToolbarController";
+import type { TextRun } from "@editor/tools/pdfTextEditor/model/TextRun";
+import type { EditorStore } from "@editor/tools/pdfTextEditor/store/EditorStore";
+import type { PageSnapshot } from "@editor/tools/pdfTextEditor/types";
+import {
+ editorStores,
+ servePdfiumWasm,
+} from "@editor/tools/pdfTextEditor/__tests__/editorStores";
+
+servePdfiumWasm();
+const { fixture } = editorStores();
+
+beforeAll(() => {
+ get.mockRejectedValue(new Error("no server fonts"));
+ vi.spyOn(HTMLCanvasElement.prototype, "getContext").mockReturnValue(null);
+});
+
+/** tagged-sample.pdf with "every" redrawn in Helvetica-Bold and "region" in Times-Roman. */
+async function styledLine(): Promise<{ store: EditorStore; run: TextRun }> {
+ const store = await fixture("tagged-sample.pdf");
+ // A revision no page has, so the first dispatch publishes the page as read.
+ store.publishPages([
+ {
+ pageIndex: 0,
+ revision: -1,
+ runs: [],
+ images: [],
+ shapes: [],
+ annotations: [],
+ rules: [],
+ } as unknown as PageSnapshot,
+ ]);
+ const run = store
+ .document!.page(0)
+ .runs.find((r) => r.text.startsWith("Revenue"))!;
+ const at = (word: string) => run.text.indexOf(word);
+ store.dispatch(
+ new StyleTextRangeCommand({
+ pageIndex: 0,
+ runId: run.id,
+ faces: [
+ { start: at("every"), end: at("every") + 5, face: "Helvetica-Bold" },
+ { start: at("region"), end: at("region") + 6, face: "Times-Roman" },
+ ],
+ }),
+ );
+ return { store, run };
+}
+
+function select(store: EditorStore, run: TextRun, part: string | null): void {
+ store.selection.selectOne(run.id);
+ if (part === null) return;
+ const start = run.text.indexOf(part);
+ store.selection.setTextRange(run.id, { start, end: start + part.length });
+}
+
+function toolbar(store: EditorStore) {
+ return renderHook(() =>
+ useToolbarController(store, store.getState(), store.selection.value),
+ ).result.current.state;
+}
+
+test("Bold reads on for a selected bold word inside a regular box", async () => {
+ const { store, run } = await styledLine();
+ select(store, run, "every");
+
+ const state = toolbar(store);
+
+ expect(state.bold).toBe(true);
+ expect(state.mixed.bold).toBe(false);
+ expect(state.weight).toBe(700);
+ expect(state.fontFamily).toMatch(/Helvetica-Bold$/);
+});
+
+test("Bold reads mixed for a selection of bold and regular words of one family, which is not a mixed family", async () => {
+ const { store, run } = await styledLine();
+ select(store, run, "in every");
+
+ const state = toolbar(store);
+
+ expect(state.bold).toBe(false);
+ expect(state.mixed.bold).toBe(true);
+ expect(state.weight).toBeNull();
+ expect(state.mixed.fontFamily).toBe(false);
+});
+
+test("the family reads as the selected words' own, and as mixed when they differ", async () => {
+ const { store, run } = await styledLine();
+ select(store, run, "region");
+ expect(toolbar(store).fontFamily).toMatch(/Times-Roman$/);
+ expect(toolbar(store).mixed.fontFamily).toBe(false);
+
+ select(store, run, "every region");
+ expect(toolbar(store).mixed.fontFamily).toBe(true);
+});
+
+test("with no characters selected the controls describe the box", async () => {
+ const { store, run } = await styledLine();
+ select(store, run, null);
+
+ const state = toolbar(store);
+
+ expect(state.bold).toBe(false);
+ expect(state.mixed.bold).toBe(false);
+ expect(state.fontFamily).toBe(run.fontId);
+});
+
+function Toolbar({ store }: { store: EditorStore }) {
+ const controller = useToolbarController(
+ store,
+ store.getState(),
+ store.selection.value,
+ );
+ return <FormatGroup controller={controller} />;
+}
+
+function renderToolbar(store: EditorStore) {
+ return render(
+ <MantineProvider env="test">
+ <Toolbar store={store} />
+ </MantineProvider>,
+ );
+}
+
+test("the Bold toggle and family field show a selection of mixed words as mixed", async () => {
+ const { store, run } = await styledLine();
+ select(store, run, "every region");
+
+ renderToolbar(store);
+
+ expect(screen.getByTestId("pdf-editor-bold")).toHaveAttribute(
+ "aria-pressed",
+ "mixed",
+ );
+ expect(screen.getByTestId("pdf-editor-font-family")).toHaveAttribute(
+ "placeholder",
+ "pdfTextEditor.fontPicker.mixed",
+ );
+});
+
+test("the Bold toggle shows on for a bold word and off for a regular one beside it", async () => {
+ const { store, run } = await styledLine();
+ select(store, run, "every");
+ const { unmount } = renderToolbar(store);
+ expect(screen.getByTestId("pdf-editor-bold")).toHaveAttribute(
+ "aria-pressed",
+ "true",
+ );
+ unmount();
+
+ act(() => select(store, run, "grew"));
+ renderToolbar(store);
+ expect(screen.getByTestId("pdf-editor-bold")).toHaveAttribute(
+ "aria-pressed",
+ "false",
+ );
+});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/servedFontCommands.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/servedFontCommands.test.ts
new file mode 100644
index 0000000000..0cd7ab8b4a
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/servedFontCommands.test.ts
@@ -0,0 +1,523 @@
+// @vitest-environment node
+import { readFileSync } from "node:fs";
+import { readFile } from "node:fs/promises";
+import { createRequire } from "node:module";
+import path from "node:path";
+import {
+ afterAll,
+ afterEach,
+ beforeAll,
+ beforeEach,
+ expect,
+ test,
+ vi,
+} from "vitest";
+
+const { get } = vi.hoisted(() => ({ get: vi.fn() }));
+vi.mock("@editor/services/apiClient", () => ({ default: { get } }));
+
+import { resetCmapCache } from "@editor/tools/pdfTextEditor/charcode/CmapResolver";
+import { resetContentStreamCache } from "@editor/tools/pdfTextEditor/charcode/ContentStreamResolver";
+import { resetFontHelperCaches } from "@editor/tools/pdfTextEditor/charcode/FontHelpers";
+import { DuplicateRunCommand } from "@editor/tools/pdfTextEditor/commands/DuplicateRunCommand";
+import { EditTextCommand } from "@editor/tools/pdfTextEditor/commands/EditTextCommand";
+import {
+ _clearDroppedBase14CharsForTests,
+ getDroppedBase14Chars,
+ readObjTexts,
+ resetCharCoverageCache,
+ resetOnPageAdvCache,
+ resetPerCharBranchPtrs,
+} from "@editor/tools/pdfTextEditor/commands/editTextHelpers";
+import { SetFontFamilyCommand } from "@editor/tools/pdfTextEditor/commands/SetFontFamilyCommand";
+import { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
+import type { TextRun } from "@editor/tools/pdfTextEditor/model/TextRun";
+import { PdfiumTextReader } from "@editor/tools/pdfTextEditor/pdfium/PdfiumTextReader";
+import {
+ emitDeviceFontTextObject,
+ familyCoverage,
+} from "@editor/tools/pdfTextEditor/util/deviceFontEmbed";
+import { exportToBlob } from "@editor/tools/pdfTextEditor/util/exportPdf";
+import { setClosestFont } from "@editor/tools/pdfTextEditor/util/documentFontCompletion";
+import {
+ isItalicFont,
+ resetDocumentFontStyles,
+} from "@editor/tools/pdfTextEditor/util/documentFontStyle";
+import { loadExternalFontBytes } from "@editor/tools/pdfTextEditor/util/externalFonts";
+import {
+ SERVER_FONTS_URL,
+ forgetServerFontList,
+ loadServerFonts,
+} from "@editor/tools/pdfTextEditor/util/serverFonts";
+import { FONT_DIR } from "@editor/tools/pdfTextEditor/__tests__/scanFixtures";
+
+const FIXTURES = path.join(import.meta.dirname, "../../../tests/test-fixtures");
+const SERVED = [
+ ["Liberation Sans", "LiberationSans-Regular.ttf"],
+ ["Liberation Serif", "LiberationSerif-Regular.ttf"],
+] as const;
+const faceId = (i: number) => (i + 1).toString(16).padStart(64, "0");
+const opened: EditorDocument[] = [];
+let wasm: Buffer<ArrayBuffer>;
+
+let served: ReadonlyArray<readonly [string, string]> = SERVED;
+
+function serveFonts(): void {
+ get.mockImplementation(async (url: string) => {
+ if (url === SERVER_FONTS_URL)
+ return {
+ data: {
+ families: served.map(([family, file], i) => ({
+ family,
+ faces: [
+ {
+ id: faceId(i),
+ style: "Regular",
+ bold: false,
+ italic: false,
+ weight: 400,
+ postscriptName: file.replace(".ttf", ""),
+ },
+ ],
+ })),
+ },
+ };
+ const index = served.findIndex((_, i) => url.endsWith(faceId(i)));
+ if (index >= 0)
+ return {
+ data: new Uint8Array(
+ readFileSync(path.join(FONT_DIR, served[index][1])),
+ ).buffer,
+ };
+ throw new Error("unavailable");
+ });
+}
+
+beforeAll(async () => {
+ wasm = await readFile(
+ createRequire(import.meta.url).resolve("@embedpdf/pdfium/pdfium.wasm"),
+ );
+});
+
+beforeEach(async () => {
+ served = SERVED;
+ get.mockReset();
+ forgetServerFontList();
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async (url: string) =>
+ String(url).endsWith(".wasm")
+ ? new Response(wasm, {
+ headers: { "Content-Type": "application/wasm" },
+ })
+ : new Response(null, { status: 404 }),
+ ),
+ );
+ serveFonts();
+ await loadServerFonts();
+ for (const [family] of SERVED) await loadExternalFontBytes(family);
+ _clearDroppedBase14CharsForTests();
+ resetDocumentFontStyles();
+});
+
+afterEach(() => {
+ // Font and page handles are reused by the next document opened; the editor resets these when it loads one.
+ resetCharCoverageCache();
+ resetContentStreamCache();
+ resetCmapCache();
+ resetFontHelperCaches();
+ resetOnPageAdvCache();
+ resetPerCharBranchPtrs();
+ for (const doc of opened.splice(0)) doc.dispose();
+ forgetServerFontList();
+});
+
+afterAll(() => vi.unstubAllGlobals());
+
+async function open(name: string): Promise<EditorDocument> {
+ const doc = await EditorDocument.open(
+ new Uint8Array(await readFile(path.join(FIXTURES, name))),
+ );
+ opened.push(doc);
+ PdfiumTextReader.populate(doc, doc.page(0));
+ return doc;
+}
+
+function fontNameOf(doc: EditorDocument, ptr: number): string {
+ const m = doc.module;
+ const name = m.pdfium.wasmExports.malloc(256);
+ try {
+ m.FPDFFont_GetBaseFontName(m.FPDFTextObj_GetFont(ptr), name, 256);
+ return m.pdfium.UTF8ToString(name).replace(/^[A-Z]{6}\+/, "");
+ } finally {
+ m.pdfium.wasmExports.free(name);
+ }
+}
+
+test("duplicates a line whose missing letters come from a served lookalike", async () => {
+ const doc = await open("subset-font-sample.pdf");
+ const page = doc.page(0);
+ const run = page.runs[0];
+ setClosestFont(run.fontId, "Liberation Sans");
+ const before = page.runs.length;
+
+ const cmd = new DuplicateRunCommand({ pageIndex: 0, runId: run.id });
+ cmd.apply(doc);
+
+ expect(page.runs).toHaveLength(before + 1);
+ const copy = page.findRun(cmd.insertedRunId!)!;
+ expect(copy.text).toBe(run.text);
+ expect(fontNameOf(doc, copy.pdfiumObjPtr)).toBe("LiberationSans");
+
+ cmd.revert(doc);
+ expect(page.runs).toHaveLength(before);
+});
+
+test("goes on drawing a typed word in its served lookalike as more of it is typed", async () => {
+ const doc = await open("mushroom-life.pdf");
+ const run = doc.page(0).runs.find((r) => r.text === "Spore Stage")!;
+ setClosestFont(run.fontId, "Liberation Serif");
+
+ for (const nextText of ["Z Stage", "Zq Stage"])
+ new EditTextCommand({ pageIndex: 0, runId: run.id, nextText }).apply(doc);
+
+ expect(fontNameOf(doc, run.pdfiumObjPtr)).toBe("LiberationSerif");
+});
+
+test("redo keeps a served font after the server's font list is reloaded", async () => {
+ const doc = await open("subset-font-sample.pdf");
+ const run = doc.page(0).runs[0];
+ const cmd = new SetFontFamilyCommand({
+ pageIndex: 0,
+ runId: run.id,
+ nextFamily: "Liberation Serif",
+ });
+ cmd.apply(doc);
+ expect(fontNameOf(doc, run.pdfiumObjPtr)).toBe("LiberationSerif");
+
+ cmd.revert(doc);
+ forgetServerFontList();
+ cmd.apply(doc);
+
+ expect(fontNameOf(doc, run.pdfiumObjPtr)).toBe("LiberationSerif");
+});
+
+test("redo keeps the face a font change drew in after another server offers a different one", async () => {
+ const doc = await open("subset-font-sample.pdf");
+ const run = doc.page(0).runs[0];
+ const cmd = new SetFontFamilyCommand({
+ pageIndex: 0,
+ runId: run.id,
+ nextFamily: "Liberation Serif",
+ });
+ cmd.apply(doc);
+ cmd.revert(doc);
+
+ served = [["Liberation Serif", "LiberationSerif-Bold.ttf"]];
+ forgetServerFontList();
+ await loadServerFonts();
+ await loadExternalFontBytes("Liberation Serif");
+ cmd.apply(doc);
+
+ expect(fontNameOf(doc, run.pdfiumObjPtr)).toBe("LiberationSerif");
+});
+
+test("checks typed letters against the face the document holds, not a newer one of the same name", async () => {
+ const doc = await open("subset-font-sample.pdf");
+ const page = doc.page(0);
+ const black = { r: 0, g: 0, b: 0, a: 255 };
+ const draw = (text: string) =>
+ emitDeviceFontTextObject(
+ doc,
+ page,
+ "Liberation Serif",
+ text,
+ 12,
+ black,
+ 40,
+ 40,
+ );
+ expect(draw("Latin")).not.toBe(0);
+
+ served = [["Liberation Serif", "NotoSansJP-Regular.ttf"]];
+ forgetServerFontList();
+ await loadServerFonts();
+ await loadExternalFontBytes("Liberation Serif");
+ expect(familyCoverage(null, "Liberation Serif")?.(0x6f22)).toBe(true);
+
+ expect(draw("漢字")).toBe(0);
+});
+
+test("a duplicated right-to-left line is drawn in the same direction as the original", async () => {
+ served = [["Noto Sans Hebrew", "NotoSansHebrew-Regular.ttf"]];
+ forgetServerFontList();
+ await loadServerFonts();
+ await loadExternalFontBytes("Noto Sans Hebrew");
+ const doc = await open("rtl-sample.pdf");
+ const page = doc.page(0);
+ const run = page.runs.find((r) => /^[\u0590-\u05ff ]+$/.test(r.text))!;
+ setClosestFont(run.fontId, "Noto Sans Hebrew");
+
+ const cmd = new DuplicateRunCommand({ pageIndex: 0, runId: run.id });
+ cmd.apply(doc);
+
+ const saved = await EditorDocument.open(
+ new Uint8Array(await (await exportToBlob(doc)).arrayBuffer()),
+ );
+ opened.push(saved);
+ PdfiumTextReader.populate(saved, saved.page(0));
+ const squash = (text: string) => text.replace(/\s+/g, "");
+ const lines = saved
+ .page(0)
+ .runs.flatMap((r) => r.text.split("\n"))
+ .filter((line) => /^[\u0590-\u05ff ]+$/.test(line));
+ expect(lines.map(squash)).toEqual([squash(run.text), squash(run.text)]);
+});
+
+/** What the run's objects draw, each as "font|text", in the order the run holds them. */
+function drawn(doc: EditorDocument, run: TextRun): string[] {
+ const ptrs = [
+ ...new Set(
+ [
+ ...run.paragraphLeafPtrs,
+ ...run.mergedFromPtrs,
+ run.pdfiumObjPtr,
+ ].filter(Boolean),
+ ),
+ ];
+ const texts = readObjTexts(doc.module, doc.page(0).pagePtr, ptrs);
+ return ptrs.map((ptr, i) => `${fontNameOf(doc, ptr)}|${texts[i]?.trim()}`);
+}
+
+/** The page's objects in content order, which PDFium's reading of each object's text depends on. */
+function contentOrder(doc: EditorDocument): number[] {
+ const m = doc.module;
+ const pagePtr = doc.page(0).pagePtr;
+ return Array.from({ length: m.FPDFPage_CountObjects(pagePtr) }, (_, i) =>
+ m.FPDFPage_GetObject(pagePtr, i),
+ );
+}
+
+const letters = (text: string) => [...text.replace(/\s+/g, "")].sort().join("");
+const lettersDrawn = (pieces: string[]) =>
+ letters(pieces.map((piece) => piece.slice(piece.indexOf("|") + 1)).join(""));
+
+async function savedText(doc: EditorDocument): Promise<string> {
+ const saved = await EditorDocument.open(
+ new Uint8Array(await (await exportToBlob(doc)).arrayBuffer()),
+ );
+ opened.push(saved);
+ PdfiumTextReader.populate(saved, saved.page(0));
+ return saved
+ .page(0)
+ .runs.map((r) => r.text)
+ .join("\n");
+}
+
+test.each(["Liberation Serif", "Times-Roman"])(
+ "a letter %s lacks stays in the font that drew it",
+ async (family) => {
+ const doc = await open("mixed-style-sample.pdf");
+ const run = doc.page(0).runs.find((r) => r.text.includes("✓"))!;
+ const before = { fontId: run.fontId, drawn: drawn(doc, run) };
+ const tick = before.drawn.find((piece) => piece.endsWith("|✓"))!;
+ const cmd = new SetFontFamilyCommand({
+ pageIndex: 0,
+ runId: run.id,
+ nextFamily: family,
+ });
+
+ expect(cmd.wouldLoseText(doc)).toBe(false);
+ expect(drawn(doc, run)).toEqual(before.drawn);
+
+ cmd.apply(doc);
+ const after = { fontId: run.fontId, drawn: drawn(doc, run) };
+ expect(lettersDrawn(after.drawn)).toBe(letters(run.text));
+ expect(after.drawn).toContain(tick);
+ expect(fontNameOf(doc, run.pdfiumObjPtr)).toBe(family.replace(/\s/g, ""));
+ expect(after.fontId).not.toBe(before.fontId);
+ expect(getDroppedBase14Chars()).toEqual([]);
+ expect(await savedText(doc)).toContain("✓");
+
+ cmd.revert(doc);
+ expect({ fontId: run.fontId, drawn: drawn(doc, run) }).toEqual(before);
+
+ cmd.apply(doc);
+ expect({ fontId: run.fontId, drawn: drawn(doc, run) }).toEqual(after);
+ },
+);
+
+test("a letter kept in its own font survives typing elsewhere in the paragraph", async () => {
+ const doc = await open("mixed-style-sample.pdf");
+ const run = doc.page(0).runs.find((r) => r.text.includes("✓"))!;
+ new SetFontFamilyCommand({
+ pageIndex: 0,
+ runId: run.id,
+ nextFamily: "Liberation Serif",
+ }).apply(doc);
+ const tick = drawn(doc, run).find((piece) => piece.endsWith("|✓"))!;
+
+ const edit = new EditTextCommand({
+ pageIndex: 0,
+ runId: run.id,
+ nextText: `${run.text.slice(0, 3)}Zq${run.text.slice(3)}`,
+ });
+ edit.apply(doc);
+
+ const pieces = drawn(doc, run);
+ expect(pieces).toContain(tick);
+ expect(pieces.filter((piece) => piece !== tick)).toEqual(
+ pieces
+ .filter((piece) => piece !== tick)
+ .map((piece) => piece.replace(/^[^|]*/, "LiberationSerif")),
+ );
+ expect(lettersDrawn(pieces)).toBe(letters(run.text));
+ expect(getDroppedBase14Chars()).toEqual([]);
+ expect(await savedText(doc)).toContain("✓");
+});
+
+test("putting a run back in its document font leaves a kept letter where it is", async () => {
+ const doc = await open("mixed-style-sample.pdf");
+ const run = doc.page(0).runs.find((r) => r.text.includes("✓"))!;
+ const original = run.fontId;
+ const tick = drawn(doc, run).find((piece) => piece.endsWith("|✓"))!;
+ new SetFontFamilyCommand({
+ pageIndex: 0,
+ runId: run.id,
+ nextFamily: "Liberation Serif",
+ }).apply(doc);
+
+ const restore = new SetFontFamilyCommand({
+ pageIndex: 0,
+ runId: run.id,
+ nextFamily: original,
+ });
+ expect(restore.wouldLoseText(doc)).toBe(false);
+ restore.apply(doc);
+
+ const pieces = drawn(doc, run);
+ expect(run.fontId).toBe(original);
+ expect(pieces).toContain(tick);
+ expect(
+ pieces.filter(
+ (piece) => piece !== tick && !/^LiberationSans\|/.test(piece),
+ ),
+ ).toEqual([]);
+ expect(lettersDrawn(pieces)).toBe(letters(run.text));
+ expect(getDroppedBase14Chars()).toEqual([]);
+});
+
+test.each(["Liberation Serif", "Times-Roman"])(
+ "putting a run back after %s leaves no letter in that font",
+ async (family) => {
+ const doc = await open("mixed-style-sample.pdf");
+ const run = doc.page(0).runs.find((r) => r.text.includes("✓"))!;
+ const original = run.fontId;
+ new SetFontFamilyCommand({
+ pageIndex: 0,
+ runId: run.id,
+ nextFamily: family,
+ }).apply(doc);
+
+ new SetFontFamilyCommand({
+ pageIndex: 0,
+ runId: run.id,
+ nextFamily: original,
+ }).apply(doc);
+
+ const pieces = drawn(doc, run);
+ expect(run.fontId).toBe(original);
+ expect(
+ pieces.filter((piece) => piece.startsWith(family.replace(/\s/g, ""))),
+ ).toEqual([]);
+ expect(lettersDrawn(pieces)).toBe(letters(run.text));
+ },
+);
+
+test("a right-to-left word kept in its own font reads in the same order once saved", async () => {
+ const doc = await open("rtl-sample.pdf");
+ const run = doc.page(0).runs.find((r) => r.text.startsWith("Mixed"))!;
+ const words = run.text.split(/\s+/);
+
+ new SetFontFamilyCommand({
+ pageIndex: 0,
+ runId: run.id,
+ nextFamily: "Times-Roman",
+ }).apply(doc);
+
+ expect(drawn(doc, run)).toContain("NotoSansHebrew|שלום");
+ const saved = (await savedText(doc))
+ .split("\n")
+ .find((line) => line.startsWith("Mixed"))!;
+ expect(saved.split(/\s+/)).toEqual(words);
+});
+
+test("a line the new font has no letter of is still drawn whole", async () => {
+ const doc = await open("rtl-sample.pdf");
+ const run = doc.page(0).runs.find((r) => /^[\u0590-\u05ff ]+$/.test(r.text))!;
+ const before = drawn(doc, run);
+ const order = contentOrder(doc);
+ const cmd = new SetFontFamilyCommand({
+ pageIndex: 0,
+ runId: run.id,
+ nextFamily: "Times-Roman",
+ });
+
+ expect(cmd.wouldLoseText(doc)).toBe(false);
+ cmd.apply(doc);
+
+ expect(lettersDrawn(drawn(doc, run))).toBe(letters(run.text));
+ expect(getDroppedBase14Chars()).toEqual([]);
+
+ cmd.revert(doc);
+ expect(drawn(doc, run)).toEqual(before);
+ expect(contentOrder(doc)).toEqual(order);
+});
+
+test.each(["Liberation Serif", "Times-Roman"])(
+ "a change to %s that would leave shaped letters undrawn changes nothing",
+ async (family) => {
+ const doc = await open("shaped-line-sample.pdf");
+ const run = doc.page(0).runs.find((r) => r.text.includes("2024"))!;
+ const page = () => ({
+ fontId: run.fontId,
+ drawn: drawn(doc, run),
+ order: contentOrder(doc),
+ });
+ const before = page();
+ expect(lettersDrawn(before.drawn)).toBe(letters(run.text));
+ const cmd = new SetFontFamilyCommand({
+ pageIndex: 0,
+ runId: run.id,
+ nextFamily: family,
+ });
+
+ expect(cmd.wouldLoseText(doc)).toBe(true);
+ expect(page()).toEqual(before);
+
+ cmd.apply(doc);
+ expect(page()).toEqual(before);
+ expect(getDroppedBase14Chars()).toEqual([]);
+ expect(await savedText(doc)).toContain("2024");
+
+ cmd.revert(doc);
+ expect(page()).toEqual(before);
+ },
+);
+
+test("a font is known italic by the PDF's own name for it when its family name leaves the style out", async () => {
+ const doc = await open("mixed-style-sample.pdf");
+ const m = doc.module;
+ const run = doc.page(0).runs.find((r) => r.text.includes("italic"))!;
+ const fontOf = (word: string) => {
+ const ptrs = run.paragraphLeafPtrs;
+ const texts = readObjTexts(m, doc.page(0).pagePtr, ptrs);
+ const ptr = ptrs[texts.findIndex((text) => text?.trim() === word)];
+ return `pdf:${m.FPDFTextObj_GetFont(ptr)}:Liberation Sans`;
+ };
+
+ expect(isItalicFont(fontOf("italic"))).toBe(true);
+ expect(isItalicFont(fontOf("both"))).toBe(true);
+ expect(isItalicFont(fontOf("bold"))).toBe(false);
+ expect(isItalicFont(fontOf("Plain"))).toBe(false);
+});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/serverFonts.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/serverFonts.test.ts
index 426c0716c7..fe1418fbc6 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/serverFonts.test.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/serverFonts.test.ts
@@ -20,15 +20,26 @@ import {
loadedExternalFonts,
} from "@editor/tools/pdfTextEditor/util/externalFonts";
import {
- familyOptions,
listLocalFonts,
pickLocalFontFace,
resetLocalFontsCache,
} from "@editor/tools/pdfTextEditor/util/localFonts";
import { deviceFontIdFor } from "@editor/tools/pdfTextEditor/util/deviceFontEmbed";
-import { italicCapability } from "@editor/tools/pdfTextEditor/util/fontCapability";
+import {
+ externalFamilies,
+ restyledFace,
+ type StyleRequest,
+} from "@editor/tools/pdfTextEditor/util/fontFaces";
import { resetFontCompletions } from "@editor/tools/pdfTextEditor/util/documentFontCompletion";
+/** The face a run's font moves to for `request` among the external fonts loaded so far. */
+function faceWithLoadedFonts(fontId: string, request: StyleRequest) {
+ return restyledFace(fontId, request, {
+ documentFamilies: [],
+ externalFonts: loadedExternalFonts(),
+ });
+}
+
const requestsAtImport = get.mock.calls.length;
const REGULAR = "1".repeat(64);
@@ -464,14 +475,12 @@ describe("server fonts", () => {
serveManifestAndFaces();
await loadServerFonts();
- expect(italicCapability("device:Acme Sans", true)).toEqual({
- family: "Acme Sans Italic",
- source: "device",
- });
- expect(italicCapability("device:Acme Sans Bold", true)).toEqual({
- family: null,
- source: null,
- });
+ expect(faceWithLoadedFonts("device:Acme Sans", { italic: true })).toBe(
+ "Acme Sans Italic",
+ );
+ expect(
+ faceWithLoadedFonts("device:Acme Sans Bold", { italic: true }),
+ ).toBeNull();
});
it("loads the new face after a refresh replaces the one already loaded", async () => {
@@ -559,17 +568,17 @@ describe("server fonts", () => {
});
const fonts = (await loadServerFonts()) ?? [];
- expect(familyOptions(fonts, []).map((option) => option.value)).toEqual([
+ expect(externalFamilies(fonts)[0].faces.map((face) => face.value)).toEqual([
"Acme Sans",
"Acme Sans Bold",
+ "Acme Sans Italic",
]);
expect(serverFaceFor("Acme Sans")?.id).toBe(REGULAR);
expect(serverFaceFor("Acme Sans Bold")?.id).toBe(BOLD);
expect(serverFaceFor("Acme Sans Italic")?.id).toBe(ITALIC);
- expect(italicCapability("device:Acme Sans", true)).toEqual({
- family: "Acme Sans Italic",
- source: "device",
- });
+ expect(faceWithLoadedFonts("device:Acme Sans", { italic: true })).toBe(
+ "Acme Sans Italic",
+ );
});
it("italicises a server Times New Roman with its own italic face", async () => {
@@ -586,27 +595,23 @@ describe("server fonts", () => {
],
},
});
- expect(italicCapability("pdf:1:Times New Roman", true)).toEqual({
- family: "Times-Italic",
- source: "base14",
- });
+ expect(faceWithLoadedFonts("pdf:1:Times New Roman", { italic: true })).toBe(
+ "Times-Italic",
+ );
const fonts = await loadServerFonts();
- expect(italicCapability("device:Times New Roman", true)).toEqual({
- family: "Times New Roman Italic",
- source: "device",
- });
- expect(italicCapability("device:Times New Roman Italic", false)).toEqual({
- family: "Times New Roman",
- source: "device",
- });
+ expect(
+ faceWithLoadedFonts("device:Times New Roman", { italic: true }),
+ ).toBe("Times New Roman Italic");
+ expect(
+ faceWithLoadedFonts("device:Times New Roman Italic", { italic: false }),
+ ).toBe("Times New Roman");
expect(
pickLocalFontFace(fonts ?? [], "Times New Roman Italic")?.style,
).toBe("Italic");
- expect(italicCapability("base14:Times-Roman", true)).toEqual({
- family: "Times-Italic",
- source: "base14",
- });
+ expect(faceWithLoadedFonts("base14:Times-Roman", { italic: true })).toBe(
+ "Times-Italic",
+ );
});
});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/shapedLineEdit.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/shapedLineEdit.test.ts
new file mode 100644
index 0000000000..c24ebb1b4f
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/shapedLineEdit.test.ts
@@ -0,0 +1,289 @@
+// @vitest-environment node
+import { readFile } from "node:fs/promises";
+import { createRequire } from "node:module";
+import path from "node:path";
+import { afterAll, afterEach, beforeAll, expect, test, vi } from "vitest";
+import { EditTextCommand } from "@editor/tools/pdfTextEditor/commands/EditTextCommand";
+import {
+ applyPartialEditPlan,
+ planPartialEdit,
+ revertPartialEditPlan,
+} from "@editor/tools/pdfTextEditor/commands/partialEdit";
+import { readObjFill } from "@editor/tools/pdfTextEditor/pdfium/PdfiumObjectColour";
+import { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
+import type { TextRun } from "@editor/tools/pdfTextEditor/model/TextRun";
+import { uniformTags } from "@editor/tools/pdfTextEditor/model/TextTags";
+import { PdfiumTextReader } from "@editor/tools/pdfTextEditor/pdfium/PdfiumTextReader";
+import { HistoryStack } from "@editor/tools/pdfTextEditor/store/HistoryStack";
+import { exportToBlob } from "@editor/tools/pdfTextEditor/util/exportPdf";
+
+// A left-to-right line whose producer drew three letters apart from their vowel signs: each pair is two text objects inside one ActualText span.
+const SAMPLE = path.join(
+ import.meta.dirname,
+ "../../../tests/test-fixtures/shaped-line-sample.pdf",
+);
+const FPDF_PAGEOBJ_TEXT = 1;
+
+const opened: EditorDocument[] = [];
+
+beforeAll(async () => {
+ const wasm = await readFile(
+ createRequire(import.meta.url).resolve("@embedpdf/pdfium/pdfium.wasm"),
+ );
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async (url: string) =>
+ String(url).endsWith(".wasm")
+ ? new Response(wasm, {
+ headers: { "Content-Type": "application/wasm" },
+ })
+ : new Response(null, { status: 404 }),
+ ),
+ );
+});
+
+afterEach(() => {
+ for (const doc of opened.splice(0)) doc.dispose();
+});
+
+afterAll(() => vi.unstubAllGlobals());
+
+async function open(bytes?: Uint8Array): Promise<EditorDocument> {
+ const doc = await EditorDocument.open(
+ bytes ?? new Uint8Array(await readFile(SAMPLE)),
+ );
+ opened.push(doc);
+ PdfiumTextReader.populate(doc, doc.page(0));
+ return doc;
+}
+
+const lineOf = (doc: EditorDocument) => doc.page(0).runs[0];
+
+/** The text of every run once the document is saved and opened again. */
+async function reopenedTexts(doc: EditorDocument): Promise<string[]> {
+ const saved = await exportToBlob(doc);
+ const again = await open(new Uint8Array(await saved.arrayBuffer()));
+ return again.page(0).runs.map((run) => run.text);
+}
+
+/** Every text object on the page in content order, with the left edge of its ink; a space glyph has none and is left out. */
+function inked(doc: EditorDocument): Map<number, number> {
+ const m = doc.module;
+ const pagePtr = doc.page(0).pagePtr;
+ const box = m.pdfium.wasmExports.malloc(16);
+ const found = new Map<number, number>();
+ try {
+ for (let i = 0; i < m.FPDFPage_CountObjects(pagePtr); i++) {
+ const obj = m.FPDFPage_GetObject(pagePtr, i);
+ if (m.FPDFPageObj_GetType(obj) !== FPDF_PAGEOBJ_TEXT) continue;
+ if (!m.FPDFPageObj_GetBounds(obj, box, box + 4, box + 8, box + 12))
+ continue;
+ const left = m.pdfium.getValue(box, "float");
+ if (m.pdfium.getValue(box + 8, "float") - left > 0.01)
+ found.set(obj, left);
+ }
+ } finally {
+ m.pdfium.wasmExports.free(box);
+ }
+ return found;
+}
+
+/** Each piece of the line that holds text with the pieces after it that hold none: a letter and the objects drawing the rest of its glyphs. */
+function clusters(run: TextRun): number[][] {
+ const found: number[][] = [];
+ run.mergedFromPtrs.forEach((ptr, i) => {
+ if (run.mergedFromTexts[i] === "" && found.length > 0)
+ found[found.length - 1].push(ptr);
+ else found.push([ptr]);
+ });
+ return found;
+}
+
+const shaped = (run: TextRun) =>
+ clusters(run).filter((cluster) => cluster.length > 1);
+
+/** Whether the objects of each cluster follow one another in content order with nothing between them. */
+function drawnTogether(doc: EditorDocument, run: TextRun): boolean {
+ const order = [...inked(doc).keys()];
+ return shaped(run).every((cluster) => {
+ const at = cluster.map((ptr) => order.indexOf(ptr)).sort((a, b) => a - b);
+ return at[0] >= 0 && at[at.length - 1] - at[0] === cluster.length - 1;
+ });
+}
+
+function edit(
+ doc: EditorDocument,
+ history: HistoryStack,
+ next: (text: string) => string,
+): TextRun {
+ const run = lineOf(doc);
+ history.execute(
+ new EditTextCommand({
+ pageIndex: 0,
+ runId: run.id,
+ nextText: next(run.text),
+ }),
+ doc,
+ );
+ return run;
+}
+
+test("a line owns the letter and the vowel sign of a pair drawn as two objects", async () => {
+ const doc = await open();
+ const run = lineOf(doc);
+
+ expect(shaped(run)).toHaveLength(3);
+ expect([...inked(doc).keys()]).toEqual(run.mergedFromPtrs);
+ expect(await reopenedTexts(doc)).toEqual([run.text]);
+});
+
+test("a letter typed at the start moves every vowel sign with its letter", async () => {
+ const doc = await open();
+ const history = new HistoryStack();
+ const before = inked(doc);
+ const pairs = shaped(lineOf(doc));
+
+ const run = edit(doc, history, (text) => `x${text}`);
+
+ const after = inked(doc);
+ const moved = (ptr: number) => after.get(ptr)! - before.get(ptr)!;
+ expect(shaped(run)).toEqual(pairs);
+ for (const [letter, sign] of pairs) {
+ expect(moved(letter)).toBeGreaterThan(1);
+ expect(moved(sign)).toBeCloseTo(moved(letter), 2);
+ }
+ expect(drawnTogether(doc, run)).toBe(true);
+ expect(await reopenedTexts(doc)).toEqual([run.text]);
+
+ history.undo(doc);
+ expect(inked(doc)).toEqual(before);
+ expect(await reopenedTexts(doc)).toEqual([run.text]);
+
+ history.redo(doc);
+ expect(shaped(run)).toEqual(pairs);
+ for (const [ptr, left] of after)
+ if (before.has(ptr)) expect(inked(doc).get(ptr)).toBeCloseTo(left, 2);
+ expect(await reopenedTexts(doc)).toEqual([run.text]);
+});
+
+test("letters typed after a pair are drawn after both of its objects", async () => {
+ const doc = await open();
+ const history = new HistoryStack();
+ const before = inked(doc);
+
+ const run = edit(doc, history, (text) => text.replace("2024", "20x24"));
+
+ expect(run.text).toContain("20x24");
+ expect(shaped(run)).toHaveLength(3);
+ expect(drawnTogether(doc, run)).toBe(true);
+ expect(await reopenedTexts(doc)).toEqual([run.text]);
+
+ history.undo(doc);
+ expect(inked(doc)).toEqual(before);
+ history.redo(doc);
+ expect(drawnTogether(doc, run)).toBe(true);
+ expect(await reopenedTexts(doc)).toEqual([run.text]);
+});
+
+test("a deleted word takes its vowel sign off the page with its letter", async () => {
+ const doc = await open();
+ const history = new HistoryStack();
+ const before = inked(doc);
+ const [gone, ...kept] = shaped(lineOf(doc));
+
+ const run = edit(doc, history, (text) => text.slice(text.indexOf(" ") + 1));
+
+ const after = inked(doc);
+ for (const ptr of gone) expect(after.has(ptr)).toBe(false);
+ expect(shaped(run)).toEqual(kept);
+ expect([...after.keys()]).toEqual(run.mergedFromPtrs);
+ const moved = (ptr: number) => after.get(ptr)! - before.get(ptr)!;
+ for (const [letter, sign] of kept) {
+ expect(moved(letter)).toBeLessThan(-1);
+ expect(moved(sign)).toBeCloseTo(moved(letter), 2);
+ }
+ expect(await reopenedTexts(doc)).toEqual([run.text]);
+
+ history.undo(doc);
+ expect(inked(doc)).toEqual(before);
+ expect(await reopenedTexts(doc)).toEqual([run.text]);
+});
+
+test("a vowel sign deleted from its letter is no longer drawn", async () => {
+ const doc = await open();
+ const history = new HistoryStack();
+ const before = inked(doc);
+ const [changed, ...kept] = shaped(lineOf(doc));
+
+ const run = edit(doc, history, (text) => text.replace("े", ""));
+
+ const after = inked(doc);
+ for (const ptr of changed) expect(after.has(ptr)).toBe(false);
+ expect(shaped(run)).toEqual(kept);
+ expect([...after.keys()]).toEqual(run.mergedFromPtrs);
+ expect(await reopenedTexts(doc)).toEqual([run.text]);
+
+ history.undo(doc);
+ expect(inked(doc)).toEqual(before);
+ expect(await reopenedTexts(doc)).toEqual([run.text]);
+});
+
+test("a run of edits keeps every pair whole, and undo puts every object back", async () => {
+ const doc = await open();
+ const history = new HistoryStack();
+ const before = inked(doc);
+ const steps: Array<(text: string) => string> = [
+ (text) => `x${text}`,
+ (text) => `${text}y`,
+ (text) => text.replace("2024", "20z24"),
+ (text) => text.slice(text.indexOf(" ") + 1),
+ ];
+
+ for (const step of steps) {
+ history.breakCoalescing();
+ const run = edit(doc, history, step);
+ expect(new Set(inked(doc).keys())).toEqual(new Set(run.mergedFromPtrs));
+ expect(drawnTogether(doc, run)).toBe(true);
+ expect(await reopenedTexts(doc)).toEqual([run.text]);
+ }
+ expect(shaped(lineOf(doc))).toHaveLength(2);
+
+ for (const _ of steps) history.undo(doc);
+ expect(inked(doc)).toEqual(before);
+ expect(await reopenedTexts(doc)).toEqual([lineOf(doc).text]);
+});
+
+test("an undo that cannot put the original objects back still returns each vowel sign with its letter", async () => {
+ const doc = await open();
+ const m = doc.module;
+ const page = doc.page(0);
+ const run = lineOf(doc);
+ const before = inked(doc);
+ const tags = uniformTags(run.tagMarks);
+ const prev = {
+ fonts: run.mergedFromPtrs.map((ptr) => m.FPDFTextObj_GetFont(ptr)),
+ fills: run.mergedFromPtrs.map((ptr) => readObjFill(m, ptr)),
+ charStarts: [...run.mergedFromCharStarts],
+ baselineY: run.matrix.f,
+ fontSubset: run.fontSubset,
+ };
+ const plan = planPartialEdit(run, run.text, `x${run.text}`)!;
+ const applied = applyPartialEditPlan(doc, page, run, plan, tags);
+ for (const ptr of applied.insertedPtrs)
+ m.FPDFPage_RemoveObject(page.pagePtr, ptr);
+
+ const redrawn = revertPartialEditPlan(
+ doc,
+ page,
+ run,
+ plan,
+ prev,
+ () => tags,
+ "Helvetica",
+ );
+
+ expect(redrawn?.size).toBe(0);
+ const after = inked(doc);
+ expect([...after.keys()]).toEqual([...before.keys()]);
+ for (const [ptr, left] of before) expect(after.get(ptr)).toBeCloseTo(left, 1);
+});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/spacesReopen.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/spacesReopen.test.ts
new file mode 100644
index 0000000000..aaf653eb2e
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/spacesReopen.test.ts
@@ -0,0 +1,66 @@
+// @vitest-environment node
+import { readFile } from "node:fs/promises";
+import { createRequire } from "node:module";
+import path from "node:path";
+import { afterAll, afterEach, beforeAll, expect, test, vi } from "vitest";
+import { EditTextCommand } from "@editor/tools/pdfTextEditor/commands/EditTextCommand";
+import { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
+import { PdfiumTextReader } from "@editor/tools/pdfTextEditor/pdfium/PdfiumTextReader";
+import { exportToBlob } from "@editor/tools/pdfTextEditor/util/exportPdf";
+
+const FIXTURES = path.join(import.meta.dirname, "../../../tests/test-fixtures");
+const opened: EditorDocument[] = [];
+
+beforeAll(async () => {
+ const wasm = await readFile(
+ createRequire(import.meta.url).resolve("@embedpdf/pdfium/pdfium.wasm"),
+ );
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async (url: string) =>
+ String(url).endsWith(".wasm")
+ ? new Response(wasm, {
+ headers: { "Content-Type": "application/wasm" },
+ })
+ : new Response(null, { status: 404 }),
+ ),
+ );
+});
+
+afterEach(() => {
+ for (const doc of opened.splice(0)) doc.dispose();
+});
+
+afterAll(() => vi.unstubAllGlobals());
+
+async function open(bytes: Uint8Array) {
+ const doc = await EditorDocument.open(bytes);
+ opened.push(doc);
+ PdfiumTextReader.populate(doc, doc.page(0));
+ return doc;
+}
+
+test.each([
+ ["sample.pdf", " A B"],
+ ["paragraph-sample.pdf", " A B"],
+ ["sample.pdf", " A B C"],
+ ["subset-font-sample.pdf", " A B"],
+])(
+ "spaces typed onto a line of %s read back as typed: %j",
+ async (name, typed) => {
+ const doc = await open(
+ new Uint8Array(await readFile(path.join(FIXTURES, name))),
+ );
+ const run = doc
+ .page(0)
+ .runs.find((r) => !r.text.includes("\n") && r.text.trim().length > 3)!;
+ const nextText = run.text.trimEnd() + typed;
+ new EditTextCommand({ pageIndex: 0, runId: run.id, nextText }).apply(doc);
+
+ const saved = await open(
+ new Uint8Array(await (await exportToBlob(doc)).arrayBuffer()),
+ );
+
+ expect(saved.page(0).runs.map((r) => r.text.trimEnd())).toContain(nextText);
+ },
+);
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/spanOfDroppedChars.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/spanOfDroppedChars.test.ts
new file mode 100644
index 0000000000..b02b05abae
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/spanOfDroppedChars.test.ts
@@ -0,0 +1,82 @@
+// @vitest-environment node
+import { readFile } from "node:fs/promises";
+import { createRequire } from "node:module";
+import path from "node:path";
+import {
+ afterAll,
+ afterEach,
+ beforeAll,
+ beforeEach,
+ describe,
+ expect,
+ test,
+ vi,
+} from "vitest";
+import { spanOf } from "@editor/tools/pdfTextEditor/commands/scanStyle";
+import {
+ emitTextLine,
+ getDroppedBase14Chars,
+ resetDroppedBase14Chars,
+} from "@editor/tools/pdfTextEditor/commands/editTextHelpers";
+import { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
+import { BLACK } from "@editor/tools/pdfTextEditor/model/Color";
+import { uniformTags } from "@editor/tools/pdfTextEditor/model/TextTags";
+
+const SAMPLE = path.join(
+ import.meta.dirname,
+ "../../../tests/test-fixtures/paragraph-sample.pdf",
+);
+
+let doc: EditorDocument;
+
+beforeAll(async () => {
+ const wasm = await readFile(
+ createRequire(import.meta.url).resolve("@embedpdf/pdfium/pdfium.wasm"),
+ );
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async (url: string) =>
+ String(url).endsWith(".wasm")
+ ? new Response(wasm, {
+ headers: { "Content-Type": "application/wasm" },
+ })
+ : new Response(null, { status: 404 }),
+ ),
+ );
+});
+
+beforeEach(async () => {
+ resetDroppedBase14Chars();
+ doc = await EditorDocument.open(new Uint8Array(await readFile(SAMPLE)));
+});
+
+afterEach(() => doc.dispose());
+
+afterAll(() => vi.unstubAllGlobals());
+
+describe("measuring text a standard font cannot draw", () => {
+ test("leaves the save warning's dropped characters alone", () => {
+ expect(
+ spanOf(doc, doc.page(0), "Hのテキ", "Helvetica", 12),
+ ).toBeGreaterThan(0);
+
+ expect(getDroppedBase14Chars()).toEqual([]);
+ });
+
+ test("still records the characters a real edit drops", () => {
+ emitTextLine({
+ doc,
+ page: doc.page(0),
+ text: "Hのテ",
+ x: 0,
+ y: 0,
+ fontSize: 12,
+ fill: BLACK,
+ originalFontPtr: 0,
+ fallbackFamily: "Helvetica",
+ tags: uniformTags([]),
+ });
+
+ expect(getDroppedBase14Chars()).toEqual(["の", "テ"]);
+ });
+});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/strandedGlyphs.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/strandedGlyphs.test.ts
new file mode 100644
index 0000000000..3ae47f3bd1
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/strandedGlyphs.test.ts
@@ -0,0 +1,61 @@
+// @vitest-environment node
+import { describe, it, expect } from "vitest";
+import { planPartialEdit } from "@editor/tools/pdfTextEditor/commands/partialEdit";
+import { TextRun } from "@editor/tools/pdfTextEditor/model/TextRun";
+
+function glyphPerObjectRun(text: string): TextRun {
+ const run = new TextRun({
+ id: "p0-t0",
+ pageIndex: 0,
+ bounds: { x: 0, y: 0, width: text.length * 6, height: 14 },
+ matrix: { a: 1, b: 0, c: 0, d: 1, e: 0, f: 800 },
+ text,
+ fontId: "pdf:1:Unknown",
+ fontSize: 12,
+ fill: { r: 0, g: 0, b: 0, a: 255 },
+ fontSubset: false,
+ pdfiumObjPtr: 0,
+ });
+ run.mergedFromPtrs = [...text].map((_, i) => 300 + i);
+ run.mergedFromTexts = [...text];
+ run.mergedFromBounds = [...text].map((_, i) => ({
+ x: i * 6,
+ right: i * 6 + 5,
+ }));
+ run.mergedFromCharStarts = [...text].map((_, i) => i);
+ return run;
+}
+
+function keptText(run: TextRun, prev: string, next: string): string {
+ const plan = planPartialEdit(run, prev, next);
+ if (!plan) throw new Error("no plan");
+ return plan.subRunStatus
+ .map((status, i) => (status === "all-kept" ? run.mergedFromTexts[i] : "_"))
+ .join("");
+}
+
+describe("planPartialEdit leaves no old glyph inside a new word", () => {
+ it("retypes a letter of a deleted word that the diff matched into the new one", () => {
+ const run = glyphPerObjectRun("Downloads");
+ expect(keptText(run, "Downloads", "Xk Quixotic")).not.toMatch(/[a-z]/i);
+ });
+
+ it("retypes a letter left stranded once its neighbours are retyped", () => {
+ const run = glyphPerObjectRun("Quarterly report");
+ expect(
+ keptText(run, "Quarterly report", "Annual summary").replace(/_/g, ""),
+ ).not.toMatch(/l/);
+ });
+
+ it("keeps the letters around a one-letter typo fix", () => {
+ const run = glyphPerObjectRun("cat");
+ expect(keptText(run, "cat", "cut")).toBe("c_t");
+ });
+
+ it("keeps whole words the edit does not touch", () => {
+ const run = glyphPerObjectRun("Free Adobe Alternative");
+ expect(
+ keptText(run, "Free Adobe Alternative", "Free Quixotic Alternative"),
+ ).toBe("Free _____ Alternative");
+ });
+});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/styleTextRange.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/styleTextRange.test.ts
new file mode 100644
index 0000000000..81c6b3e191
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/styleTextRange.test.ts
@@ -0,0 +1,442 @@
+import { act, renderHook } from "@testing-library/react";
+import { beforeAll, expect, test, vi } from "vitest";
+
+const { get } = vi.hoisted(() => ({ get: vi.fn() }));
+vi.mock("@editor/services/apiClient", () => ({ default: { get } }));
+
+import {
+ useSelectionActions,
+ type FontPickFailure,
+} from "@editor/tools/pdfTextEditor/hooks/useSelectionActions";
+import type { EditorStore } from "@editor/tools/pdfTextEditor/store/EditorStore";
+import {
+ collectMemberPtrs,
+ drawnEndPt,
+} from "@editor/tools/pdfTextEditor/commands/editTextHelpers";
+import { readTextSource } from "@editor/tools/pdfTextEditor/commands/textPieces";
+import { EditTextCommand } from "@editor/tools/pdfTextEditor/commands/EditTextCommand";
+import type { TextRun } from "@editor/tools/pdfTextEditor/model/TextRun";
+import {
+ editorStores,
+ savedBytes,
+ servePdfiumWasm,
+} from "@editor/tools/pdfTextEditor/__tests__/editorStores";
+
+const FPDF_PAGEOBJ_TEXT = 1;
+const REVENUE = "Revenue grew in every region this quarter,";
+
+servePdfiumWasm();
+const { storeWith, fixture } = editorStores();
+
+beforeAll(() => {
+ get.mockRejectedValue(new Error("no server fonts"));
+ // jsdom has no canvas; text measurement falls back without one.
+ vi.spyOn(HTMLCanvasElement.prototype, "getContext").mockReturnValue(null);
+});
+
+function runStarting(store: EditorStore, text: string): TextRun {
+ const run = store.document!.page(0).runs.find((r) => r.text.startsWith(text));
+ expect(run, `no run starting "${text}"`).toBeTruthy();
+ return run!;
+}
+
+interface Drawn {
+ text: string;
+ font: string;
+ x: number;
+ right: number;
+}
+
+/** Each object of the run with the text it draws, its /BaseFont and where its ink starts and ends. */
+function drawn(store: EditorStore, run: TextRun): Drawn[] {
+ const doc = store.document!;
+ const m = doc.module;
+ const page = doc.page(0);
+ const buf = m.pdfium.wasmExports.malloc(2048);
+ const name = m.pdfium.wasmExports.malloc(256);
+ const box = m.pdfium.wasmExports.malloc(16);
+ const textPage = m.FPDFText_LoadPage(page.pagePtr);
+ try {
+ return collectMemberPtrs(run)
+ .filter((ptr) => ptr && m.FPDFPageObj_GetType(ptr) === FPDF_PAGEOBJ_TEXT)
+ .map((ptr) => {
+ m.FPDFTextObj_GetText(ptr, textPage, buf, 2048);
+ m.FPDFFont_GetBaseFontName(m.FPDFTextObj_GetFont(ptr), name, 256);
+ m.FPDFPageObj_GetBounds(ptr, box, box + 4, box + 8, box + 12);
+ return {
+ text: m.pdfium.UTF16ToString(buf).trim(),
+ font: m.pdfium.UTF8ToString(name).replace(/^[A-Z]{6}\+/, ""),
+ x: m.pdfium.getValue(box, "float"),
+ right: m.pdfium.getValue(box + 8, "float"),
+ };
+ });
+ } finally {
+ m.FPDFText_ClosePage(textPage);
+ m.pdfium.wasmExports.free(buf);
+ m.pdfium.wasmExports.free(name);
+ m.pdfium.wasmExports.free(box);
+ }
+}
+
+/** The run's words as "text@Font", objects split at spaces. */
+function faces(store: EditorStore, run: TextRun): string[] {
+ return drawn(store, run).flatMap((piece) =>
+ piece.text.split(/\s+/).map((word) => `${word}@${piece.font}`),
+ );
+}
+
+function wordsIn(store: EditorStore, run: TextRun, font: string): string[] {
+ return faces(store, run)
+ .filter((face) => face.endsWith(`@${font}`))
+ .map((face) => face.split("@")[0]);
+}
+
+function pageText(store: EditorStore): string {
+ const doc = store.document!;
+ const m = doc.module;
+ const textPage = m.FPDFText_LoadPage(doc.page(0).pagePtr);
+ const count = m.FPDFText_CountChars(textPage);
+ const buf = m.pdfium.wasmExports.malloc((count + 1) * 2);
+ try {
+ m.FPDFText_GetText(textPage, 0, count, buf);
+ return m.pdfium.UTF16ToString(buf);
+ } finally {
+ m.pdfium.wasmExports.free(buf);
+ m.FPDFText_ClosePage(textPage);
+ }
+}
+
+/** Where the engine puts the first letter of `needle` on the page, from the page's own text. */
+function originOf(store: EditorStore, needle: string): number {
+ const at = pageText(store).indexOf(needle);
+ expect(at, `"${needle}" is not on the page`).toBeGreaterThanOrEqual(0);
+ const doc = store.document!;
+ const m = doc.module;
+ const textPage = m.FPDFText_LoadPage(doc.page(0).pagePtr);
+ const xy = m.pdfium.wasmExports.malloc(16);
+ try {
+ m.FPDFText_GetCharOrigin(textPage, at, xy, xy + 8);
+ return m.pdfium.getValue(xy, "double");
+ } finally {
+ m.pdfium.wasmExports.free(xy);
+ m.FPDFText_ClosePage(textPage);
+ }
+}
+
+/**
+ * The objects of `run` that together draw `word`, in order, and for each after
+ * the first how far it starts from where the one before it left the pen.
+ */
+function seamsIn(store: EditorStore, run: TextRun, word: string): number[] {
+ const m = store.document!.module;
+ const objects = drawn(store, run).flatMap((piece, i) => {
+ const ptr = collectMemberPtrs(run).filter(
+ (p) => p && m.FPDFPageObj_GetType(p) === FPDF_PAGEOBJ_TEXT,
+ )[i];
+ const source = readTextSource(m, ptr);
+ return source && piece.text ? [{ ...piece, ptr, source }] : [];
+ });
+ objects.sort((a, b) => a.source.matrix[4] - b.source.matrix[4]);
+ for (let first = 0; first < objects.length; first++) {
+ let spelled = "";
+ for (let last = first; last < objects.length; last++) {
+ spelled += objects[last].text;
+ if (!word.startsWith(spelled)) break;
+ if (spelled !== word) continue;
+ return objects.slice(first + 1, last + 1).map((piece, k) => {
+ const before = objects[first + k];
+ const penEnd = drawnEndPt(
+ m,
+ [before.ptr],
+ [before.text],
+ before.source.size,
+ );
+ return piece.source.matrix[4] - penEnd - run.charSpacingPt;
+ });
+ }
+ }
+ throw new Error(`no objects of the run spell "${word}"`);
+}
+
+function selectText(store: EditorStore, run: TextRun, part: string): void {
+ const start = run.text.indexOf(part);
+ expect(start, `"${part}" is not in the run`).toBeGreaterThanOrEqual(0);
+ store.selection.selectOne(run.id);
+ store.selection.setTextRange(run.id, { start, end: start + part.length });
+}
+
+async function perform(
+ store: EditorStore,
+ action: (
+ actions: ReturnType<typeof useSelectionActions>,
+ ) => Promise<FontPickFailure | null>,
+): Promise<FontPickFailure | null> {
+ const { result } = renderHook(() => useSelectionActions(store));
+ let failure: FontPickFailure | null = null;
+ await act(async () => {
+ failure = await action(result.current);
+ });
+ return failure;
+}
+
+test("Bold on one word mid-line bolds that word only and moves the rest of the line by the width it gains", async () => {
+ const store = await fixture("tagged-sample.pdf");
+ const run = runStarting(store, "Revenue grew");
+ const before = {
+ grew: originOf(store, "grew"),
+ every: originOf(store, "every"),
+ region: originOf(store, "region"),
+ led: originOf(store, "led by"),
+ };
+ selectText(store, run, "every");
+
+ expect(await perform(store, (a) => a.toggleBold())).toBeNull();
+
+ expect(wordsIn(store, run, "Helvetica-Bold")).toEqual(["every"]);
+ expect(originOf(store, "grew")).toBeCloseTo(before.grew, 1);
+ expect(originOf(store, "every")).toBeCloseTo(before.every, 1);
+ // Helvetica-Bold "every" is about 1.6pt wider than the regular cut at this size.
+ const moved = originOf(store, "region") - before.region;
+ expect(moved).toBeGreaterThan(0.5);
+ expect(moved).toBeLessThan(4);
+ expect(originOf(store, "led by")).toBeCloseTo(before.led, 1);
+ expect(run.text).toBe(`${REVENUE}\nled by demand for the new product line.`);
+});
+
+test("Italic on a range across a word boundary slants exactly those letters", async () => {
+ const store = await fixture("tagged-sample.pdf");
+ const run = runStarting(store, "Revenue grew");
+ const ew = originOf(store, "ew in");
+ selectText(store, run, "ew in ev");
+
+ expect(await perform(store, (a) => a.toggleItalic())).toBeNull();
+
+ const pieces = drawn(store, run).filter((p) => p.text);
+ expect(
+ pieces.filter((p) => p.font === "Helvetica-Oblique").map((p) => p.text),
+ ).toEqual(["ew", "in", "ev"]);
+ expect(pieces.find((p) => p.text === "gr")?.font).toBe("Helvetica");
+ expect(pieces.find((p) => p.text === "ery")?.font).toBe("Helvetica");
+ // One word, so the slanted half starts where the upright half ends.
+ expect(Math.abs(originOf(store, "ew in") - ew)).toBeLessThan(0.3);
+});
+
+test("Bold on the first word of a line toggles off again", async () => {
+ const store = await fixture("tagged-sample.pdf");
+ const run = runStarting(store, "Revenue grew");
+ selectText(store, run, "Revenue");
+
+ await perform(store, (a) => a.toggleBold());
+ expect(wordsIn(store, run, "Helvetica-Bold")).toEqual(["Revenue"]);
+ await perform(store, (a) => a.toggleBold());
+
+ expect(wordsIn(store, run, "Helvetica-Bold")).toEqual([]);
+ expect(pageText(store)).toContain(REVENUE);
+});
+
+test("a weight picked for part of a line applies to that part only", async () => {
+ const store = await fixture("tagged-sample.pdf");
+ const run = runStarting(store, "Revenue grew");
+ selectText(store, run, "region");
+
+ expect(await perform(store, (a) => a.changeFontWeight(700))).toBeNull();
+
+ expect(wordsIn(store, run, "Helvetica-Bold")).toEqual(["region"]);
+});
+
+test("a family picked for part of a line redraws that part in the family, keeping its style", async () => {
+ const store = await fixture("tagged-sample.pdf");
+ const run = runStarting(store, "Revenue grew");
+ selectText(store, run, "every region");
+
+ expect(await perform(store, (a) => a.changeFontFamily("Times-Roman"))).toBe(
+ null,
+ );
+
+ expect(wordsIn(store, run, "Times-Roman")).toEqual(["every", "region"]);
+ expect(wordsIn(store, run, "Helvetica")).toContain("quarter,");
+});
+
+test("undo puts the line back exactly and redo restyles it again", async () => {
+ const store = await fixture("tagged-sample.pdf");
+ const run = runStarting(store, "Revenue grew");
+ const before = drawn(store, run);
+ selectText(store, run, "every");
+ await perform(store, (a) => a.toggleBold());
+ const after = drawn(store, run);
+ expect(wordsIn(store, run, "Helvetica-Bold")).toEqual(["every"]);
+
+ store.undo();
+ expect(drawn(store, run)).toEqual(before);
+ expect(pageText(store)).toContain(REVENUE);
+
+ store.redo();
+ expect(drawn(store, run)).toEqual(after);
+ store.undo();
+ store.redo();
+ expect(drawn(store, run)).toEqual(after);
+});
+
+test("a save keeps the styled word in its own face and the line in reading order", async () => {
+ const store = await fixture("tagged-sample.pdf");
+ const run = runStarting(store, "Revenue grew");
+ selectText(store, run, "every");
+ await perform(store, (a) => a.toggleBold());
+
+ const reopened = await storeWith(await savedBytes(store));
+ const saved = runStarting(reopened, "Revenue grew");
+ expect(wordsIn(reopened, saved, "Helvetica-Bold")).toEqual(["every"]);
+ expect(pageText(reopened)).toContain(REVENUE);
+ expect(saved.text.split("\n")[0]).toBe(REVENUE);
+});
+
+test("a range spanning two lines of a paragraph restyles both parts and leaves the other lines alone", async () => {
+ const store = await fixture("paragraph-sample.pdf");
+ const run = runStarting(store, "First line of the body");
+ const lines = run.text.split("\n");
+ const third = drawn(store, run).find((p) =>
+ p.text.startsWith("left margin"),
+ )!;
+ selectText(store, run, "together.\nSecond line");
+
+ expect(await perform(store, (a) => a.toggleBold())).toBeNull();
+
+ expect(wordsIn(store, run, "Helvetica-Bold")).toEqual([
+ "together.",
+ "Second",
+ "line",
+ ]);
+ expect(run.text.split("\n")).toEqual(lines);
+ expect(
+ drawn(store, run).find((p) => p.text.startsWith("left margin")),
+ ).toEqual(third);
+ expect(pageText(store)).toContain("grouped together.");
+});
+
+test("letters the bold subset lacks stay in the regular face and the user is told", async () => {
+ const store = await fixture("mushroom-life.pdf");
+ const run = runStarting(store, "Mushrooms represent");
+ selectText(store, run, "unique");
+
+ expect(await perform(store, (a) => a.toggleBold())).toBe("closestMatch");
+
+ const bold = wordsIn(store, run, "LMRoman12-Bold").join("");
+ expect(bold.length).toBeGreaterThan(0);
+ expect(bold).toBe("uniue");
+ expect(
+ faces(store, run)
+ .map((face) => face.split("@")[0])
+ .join(""),
+ ).toContain("unique");
+ expect(run.text).toContain("a unique posi-");
+});
+
+test.each([
+ [
+ "before its last letter",
+ "represent one of nature’s",
+ "nature’s",
+ "of nature’s most",
+ ],
+ ["mid-word", "unique", "unique", "a unique posi"],
+ [
+ "at the start of a word",
+ "biological",
+ "biological",
+ "the biological world",
+ ],
+])(
+ "a letter the bold subset lacks %s abuts the letters around it and reads as one word, on the page and after a save",
+ async (_where, part, word, reads) => {
+ const store = await fixture("mushroom-life.pdf");
+ const run = runStarting(store, "Mushrooms represent");
+ selectText(store, run, part);
+
+ expect(await perform(store, (a) => a.toggleBold())).toBe("closestMatch");
+
+ const seams = seamsIn(store, run, word);
+ expect(seams.length).toBeGreaterThan(0);
+ for (const seam of seams) expect(Math.abs(seam)).toBeLessThan(0.01);
+ expect(pageText(store)).toContain(reads);
+ const reopened = await storeWith(await savedBytes(store));
+ expect(pageText(reopened)).toContain(reads);
+ },
+);
+
+test("typing straight after a bolded word goes on in bold", async () => {
+ const store = await fixture("tagged-sample.pdf");
+ const run = runStarting(store, "Revenue grew");
+ selectText(store, run, "every");
+ await perform(store, (a) => a.toggleBold());
+
+ const at = run.text.indexOf("every") + "every".length;
+ store.dispatch(
+ new EditTextCommand({
+ pageIndex: 0,
+ runId: run.id,
+ nextText: `${run.text.slice(0, at)}one${run.text.slice(at)}`,
+ }),
+ );
+
+ expect(wordsIn(store, run, "Helvetica-Bold")).toEqual(["every", "one"]);
+ expect(pageText(store)).toContain("in everyone region");
+ expect(wordsIn(store, run, "Helvetica")).toContain("region");
+});
+
+test("right-to-left text refuses a change to part of its line and stays as drawn", async () => {
+ const store = await fixture("coloured-word-sample.pdf");
+ const run = runStarting(store, "הטלפון");
+ const before = drawn(store, run);
+ selectText(store, run, "שלום");
+
+ expect(await perform(store, (a) => a.toggleBold())).toBeNull();
+
+ expect(store.getState().error).toMatch(/right-to-left/);
+ expect(drawn(store, run)).toEqual(before);
+ expect(store.history.canUndo).toBe(false);
+});
+
+test("text that needs shaping refuses a change to part of it", async () => {
+ const store = await fixture("shaped-line-sample.pdf");
+ const run = store.document!.page(0).runs[0];
+ const before = drawn(store, run);
+ store.selection.selectOne(run.id);
+ store.selection.setTextRange(run.id, { start: 0, end: 3 });
+
+ expect(await perform(store, (a) => a.changeFontFamily("Times-Roman"))).toBe(
+ "needsShaping",
+ );
+ expect(drawn(store, run)).toEqual(before);
+});
+
+test("in a wrapped box a change rewraps the paragraph only when a line would overflow", async () => {
+ const store = await fixture("paragraph-sample.pdf");
+ store.setWidthMode("wrap");
+ const run = runStarting(store, "First line of the body");
+ const text = run.text;
+ selectText(store, run, "bottom");
+ await perform(store, (a) => a.toggleBold());
+ expect(run.text).toBe(text);
+
+ selectText(store, run, "Second line continues the paragraph and shares");
+ await perform(store, (a) => a.toggleBold());
+ expect(run.text).not.toBe(text);
+ expect(run.text.replace(/\s+/g, " ")).toBe(text.replace(/\s+/g, " "));
+
+ store.undo();
+ expect(run.text).toBe(text);
+});
+
+test("with the whole box's text selected Bold applies to the box as before", async () => {
+ const store = await fixture("tagged-sample.pdf");
+ const run = runStarting(store, "Revenue grew");
+ store.selection.selectOne(run.id);
+ store.selection.setTextRange(run.id, { start: 0, end: run.text.length });
+
+ await perform(store, (a) => a.toggleBold());
+
+ const live = runStarting(store, "Revenue grew");
+ expect(new Set(drawn(store, live).map((p) => p.font))).toEqual(
+ new Set(["Helvetica-Bold"]),
+ );
+});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/tableCellText.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/tableCellText.test.ts
new file mode 100644
index 0000000000..edfb76c381
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/tableCellText.test.ts
@@ -0,0 +1,145 @@
+// @vitest-environment node
+import { readFile } from "node:fs/promises";
+import { createRequire } from "node:module";
+import path from "node:path";
+import { afterAll, afterEach, beforeAll, expect, test, vi } from "vitest";
+import { EditTextCommand } from "@editor/tools/pdfTextEditor/commands/EditTextCommand";
+import { FillTableCellCommand } from "@editor/tools/pdfTextEditor/commands/FillTableCellCommand";
+import { InsertTableCommand } from "@editor/tools/pdfTextEditor/commands/InsertTableCommand";
+import { cellTextDrawable } from "@editor/tools/pdfTextEditor/commands/tableHelpers";
+import { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
+import { PdfiumTextReader } from "@editor/tools/pdfTextEditor/pdfium/PdfiumTextReader";
+import { HistoryStack } from "@editor/tools/pdfTextEditor/store/HistoryStack";
+import { exportToBlob } from "@editor/tools/pdfTextEditor/util/exportPdf";
+import { preloadFallbackFontBytes } from "@editor/tools/pdfTextEditor/util/fallbackFont";
+
+const SAMPLE = path.join(
+ import.meta.dirname,
+ "../../../tests/test-fixtures/paragraph-sample.pdf",
+);
+const FALLBACK_FONT = path.join(
+ import.meta.dirname,
+ "../../../../../../public/fonts/NotoSans-Regular.ttf",
+);
+const CYRILLIC = "Привет мир";
+
+const opened: EditorDocument[] = [];
+let serveFallbackFont = false;
+
+beforeAll(async () => {
+ const wasm = await readFile(
+ createRequire(import.meta.url).resolve("@embedpdf/pdfium/pdfium.wasm"),
+ );
+ const font = await readFile(FALLBACK_FONT);
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async (url: string) => {
+ if (String(url).endsWith(".wasm"))
+ return new Response(wasm, {
+ headers: { "Content-Type": "application/wasm" },
+ });
+ if (serveFallbackFont && String(url).endsWith("NotoSans-Regular.ttf"))
+ return new Response(font);
+ return new Response(null, { status: 404 });
+ }),
+ );
+});
+
+afterEach(() => {
+ for (const doc of opened.splice(0)) doc.dispose();
+});
+
+afterAll(() => vi.unstubAllGlobals());
+
+async function open(bytes?: Uint8Array): Promise<EditorDocument> {
+ const doc = await EditorDocument.open(
+ bytes ?? new Uint8Array(await readFile(SAMPLE)),
+ );
+ opened.push(doc);
+ PdfiumTextReader.populate(doc, doc.page(0));
+ return doc;
+}
+
+async function withTable() {
+ const doc = await open();
+ const history = new HistoryStack();
+ const insert = new InsertTableCommand({
+ pageIndex: 0,
+ x: 72,
+ y: 200,
+ width: 300,
+ height: 60,
+ rows: 2,
+ cols: 2,
+ });
+ history.execute(insert, doc);
+ history.breakCoalescing();
+ const tableId = insert.insertedTableId!;
+ const fill = (text: string, col = 0) => {
+ const cmd = new FillTableCellCommand({ tableId, row: 0, col, text });
+ history.execute(cmd, doc);
+ history.breakCoalescing();
+ return cmd;
+ };
+ return { doc, history, fill };
+}
+
+async function savedTexts(doc: EditorDocument): Promise<string[]> {
+ const reopened = await open(
+ new Uint8Array(await (await exportToBlob(doc)).arrayBuffer()),
+ );
+ return reopened.page(0).runs.map((run) => run.text.trim());
+}
+
+// Runs first: once the fallback face has loaded it stays loaded for the file.
+test.each([CYRILLIC, "Total я", "日本語"])(
+ "a new cell refuses %s whole while no loaded font draws it",
+ async (text) => {
+ const { doc, fill } = await withTable();
+ const runs = doc.page(0).runs.length;
+
+ expect(cellTextDrawable(text)).toBe(false);
+ expect(fill(text).insertedRunId).toBeNull();
+
+ expect(doc.page(0).runs).toHaveLength(runs);
+ expect(doc.page(0).tables[0].cellRuns[0][0]).toBeNull();
+ },
+);
+
+test("a new cell draws letters outside the standard fonts in the fallback face, and they are saved", async () => {
+ serveFallbackFont = true;
+ await preloadFallbackFontBytes();
+ const { doc, history, fill } = await withTable();
+ const before = await savedTexts(doc);
+
+ expect(cellTextDrawable(CYRILLIC)).toBe(true);
+ expect(cellTextDrawable("日本語")).toBe(false);
+ const runId = fill(CYRILLIC).insertedRunId!;
+ expect(fill("Total я", 1).insertedRunId).not.toBeNull();
+ expect(doc.page(0).findRun(runId)?.text).toBe(CYRILLIC);
+ expect(await savedTexts(doc)).toEqual(
+ expect.arrayContaining([CYRILLIC, "Total я"]),
+ );
+
+ history.execute(
+ new EditTextCommand({
+ pageIndex: 0,
+ runId,
+ nextText: `${CYRILLIC}!`,
+ }),
+ doc,
+ );
+ expect(await savedTexts(doc)).toContain(`${CYRILLIC}!`);
+
+ history.undo(doc);
+ history.undo(doc);
+ history.undo(doc);
+ expect(await savedTexts(doc)).toEqual(before);
+
+ history.redo(doc);
+ history.redo(doc);
+ history.redo(doc);
+ const redone = await savedTexts(doc);
+ expect(redone).toEqual(expect.arrayContaining([`${CYRILLIC}!`, "Total я"]));
+ expect(await savedTexts(doc)).toEqual(redone);
+});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/tableCommands.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/tableCommands.test.ts
index 934a33302d..7ad93749ab 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/tableCommands.test.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/tableCommands.test.ts
@@ -201,8 +201,6 @@ function ruleShape(rule: PageRuleSnapshot): ShapeObject {
bounds: { x: rule.x, y: rule.y, width: rule.width, height: rule.height },
pdfiumObjPtr: rule.ptr,
containerPtr: 0,
- topLevelContainerPtr: 0,
- containerTransform: { a: 1, b: 0, c: 0, d: 1, e: 0, f: 0 },
});
}
@@ -377,6 +375,32 @@ describe("table commands (fake PDFium)", () => {
expect(extra.bounds).toEqual(before[1].bounds);
});
+ it("refuses to scale a table holding a line it cannot redraw, before any cell changes", () => {
+ const { model, primary, extra } = filledTable();
+ extra.readingOrderUnsure = true;
+ const before = {
+ runs: [primary.snapshot(), extra.snapshot()],
+ colEdges: [...model.colEdges],
+ rowEdges: [...model.rowEdges],
+ };
+ const history = new HistoryStack();
+
+ expect(() =>
+ history.execute(
+ new ResizeTableCommand({
+ tableId: model.id,
+ edit: { kind: "scale", width: 600, height: 180 },
+ }),
+ doc,
+ ),
+ ).toThrow(expect.objectContaining({ documentIntact: true }));
+
+ expect([primary.snapshot(), extra.snapshot()]).toEqual(before.runs);
+ expect(model.colEdges).toEqual(before.colEdges);
+ expect(model.rowEdges).toEqual(before.rowEdges);
+ expect(history.canUndo).toBe(false);
+ });
+
it("does not draw separators through a cell merged across both axes", () => {
const { model } = filledTable();
model.cellSpans[0][0] = { rowSpan: 2, colSpan: 2 };
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/tableDetection.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/tableDetection.test.ts
index bf4be94203..f63de70270 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/tableDetection.test.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/tableDetection.test.ts
@@ -626,19 +626,25 @@ describe("detectTables", () => {
const cands = [
{
run: run(60, 700, 30, "A"),
+ inset: [],
+ text: "A",
left: 60,
right: 90,
cx: 75,
cy: 706,
height: 8,
+ baseline: 700,
},
{
run: run(60, 680, 30, "B"),
+ inset: [],
+ text: "B",
left: 60,
right: 90,
cx: 75,
cy: 686,
height: 8,
+ baseline: 680,
},
];
const banded = bandByRules(cands, pins);
@@ -648,3 +654,260 @@ describe("detectTables", () => {
expect(banded![1].cands).toHaveLength(1);
});
});
+
+describe("detectTables - letters a line draws as objects of their own", () => {
+ // Three lines of an Arabic paragraph as the reader returns them: [x, y, width, height, baseline, text]. The one-letter runs are letters the producer drew apart from their words, inside the line's extent.
+ const PARAGRAPH: Array<[number, number, number, number, number, string]> = [
+ [276.56, 693.87, 62.06, 1.42, 694.59, "ر الصفحة 12)."],
+ [328.13, 693.15, 177.86, 9.79, 694.59, "معدل ال مو 75% في عام 2026 وفقاً ("],
+ [519.52, 694.59, 3.29, 4.11, 694.59, "ي"],
+ [510.4, 699.42, 9.4, 1.52, 691.19, "بلغ"],
+ [475, 698.12, 1.5, 1.52, 689.89, "ن"],
+ [
+ 217.86,
+ 665.27,
+ 300.69,
+ 1.42,
+ 665.99,
+ "وروا الموقع https://www.example.org",
+ ],
+ [520.55, 670.37, 1.5, 1.52, 662.14, "ز"],
+ [222, 669.47, 3.05, 1.57, 661.24, "ت"],
+ [262.45, 668.57, 1.5, 1.52, 660.34, "ن"],
+ [
+ 115.31,
+ 636.67,
+ 363.6,
+ 1.42,
+ 637.39,
+ "امج LibreOffice Writer أو Word ل ح",
+ ],
+ [479.45, 642.22, 43.22, 1.52, 633.99, "اس خدم برن"],
+ [256.95, 640.72, 6.3, 1.57, 632.49, "فت"],
+ [510.1, 640.72, 3.05, 1.57, 632.49, "ت"],
+ [119.3, 639.97, 1.5, 1.52, 631.74, "ن"],
+ ];
+ const drawn = ([
+ x,
+ y,
+ width,
+ height,
+ baseline,
+ text,
+ ]: (typeof PARAGRAPH)[0]) =>
+ run(x, y, width, text, {
+ bounds: { x, y, width, height },
+ matrix: { a: 1, b: 0, c: 0, d: 1, e: x, f: baseline },
+ fontSize: 11,
+ });
+
+ it("does not build a table out of a paragraph whose lines hold separately drawn letters", () => {
+ expect(detectTables(PARAGRAPH.map(drawn), 0)).toEqual([]);
+ });
+
+ it("puts a letter drawn inside a cell's text in that cell", () => {
+ const table = grid([50, 200, 350], 700, 20, [
+ ["Item", "Qty", "Price"],
+ ["القطاع", "2", "$10.00"],
+ ["Gadget", "5", "$25.00"],
+ ]);
+ const sector = table[3];
+ // Low enough on the line to band as a row of its own were it a candidate.
+ const letter = run(70, 677, 3, "ن", {
+ bounds: { x: 70, y: 677, width: 3, height: 1 },
+ });
+
+ const plain = detectTables(table, 0);
+ const tables = detectTables([...table, letter], 0);
+
+ expect(tables).toHaveLength(1);
+ expect(tables[0].colEdges).toEqual(plain[0].colEdges);
+ expect(tables[0].rowEdges).toEqual(plain[0].rowEdges);
+ const cell = tables[0].cells.find((c) => c.row === 1 && c.col === 0);
+ expect(cell?.runIds).toEqual([sector.id, letter.id]);
+ });
+
+ it("leaves a run inside a left-to-right line a candidate of its own", () => {
+ const table = grid([50, 200, 350], 700, 20, [
+ ["Item", "Qty", "Price"],
+ ["Widget", "2", "$10.00"],
+ ["Gadget", "5", "$25.00"],
+ ]);
+ const mark = run(70, 677, 3, ".", {
+ bounds: { x: 70, y: 677, width: 3, height: 1 },
+ matrix: { a: 1, b: 0, c: 0, d: 1, e: 70, f: 680 },
+ });
+
+ const cells = detectTables([...table, mark], 0)[0].cells;
+
+ expect(cells.find((c) => c.runIds.includes(table[3].id))?.runIds).toEqual([
+ table[3].id,
+ ]);
+ expect(cells.find((c) => c.runIds.includes(mark.id))?.runIds).toEqual([
+ mark.id,
+ ]);
+ });
+
+ it("keeps both of two runs drawn over each other", () => {
+ const table = grid([50, 200, 350], 700, 20, [
+ ["Item", "Qty", "Price"],
+ ["Widget", "2", "$10.00"],
+ ["Gadget", "5", "$25.00"],
+ ]);
+ const doubled = run(50, 680, 60, "Widget");
+
+ const cell = detectTables([...table, doubled], 0)[0].cells.find(
+ (c) => c.row === 1 && c.col === 0,
+ );
+
+ expect(cell?.runIds).toEqual([table[3].id, doubled.id]);
+ });
+});
+
+describe("detectTables - layouts that only look like a grid", () => {
+ const SENTENCES = [
+ "The committee reviewed every submission before",
+ "the deadline and returned its findings to the",
+ "board, which approved the budget for the year",
+ "after a short discussion of the revised targets",
+ "and the schedule proposed by the finance team.",
+ "Members asked for a summary of the main risks.",
+ ];
+ const ruleAt = (y: number) => ({
+ x: 40,
+ y: y - 0.25,
+ width: 560,
+ height: 0.5,
+ });
+
+ it("does not build a table out of a running watermark", () => {
+ const turned = { a: 0.7, b: 0.7, c: -0.7, d: 0.7 };
+ const runs = grid([50, 200, 350], 700, 40, [
+ ["DRAFT", "DRAFT", "DRAFT"],
+ ["DRAFT", "DRAFT", "DRAFT"],
+ ["DRAFT", "DRAFT", "DRAFT"],
+ ]).map((r) => ({ ...r, matrix: { ...r.matrix, ...turned } }));
+
+ expect(detectTables(runs, 0)).toEqual([]);
+ });
+
+ it("does not build a table out of an upright watermark tiled over body text", () => {
+ const grey = { fill: { r: 200, g: 200, b: 200, a: 255 } };
+ const tiles = grid([60, 250, 440], 720, 110, [
+ ["CONFIDENTIAL", "CONFIDENTIAL", "CONFIDENTIAL"],
+ ["CONFIDENTIAL", "CONFIDENTIAL", "CONFIDENTIAL"],
+ ["CONFIDENTIAL", "CONFIDENTIAL", "CONFIDENTIAL"],
+ ["CONFIDENTIAL", "CONFIDENTIAL", "CONFIDENTIAL"],
+ ]).map((r) => ({ ...r, ...grey, bounds: { ...r.bounds, width: 110 } }));
+ const body = Array.from({ length: 24 }, (_, i) =>
+ run(50, 726 - i * 14, 500, SENTENCES[i % SENTENCES.length]),
+ );
+
+ expect(detectTables([...body, ...tiles], 0)).toEqual([]);
+ });
+
+ it("keeps a table a watermark runs across", () => {
+ const table = grid([50, 200, 350], 700, 20, [
+ ["Item", "Qty", "Price"],
+ ["Widget", "2", "$10.00"],
+ ["Gadget", "5", "$25.00"],
+ ]);
+ const watermark = run(40, 640, 400, "CONFIDENTIAL", {
+ bounds: { x: 40, y: 640, width: 400, height: 90 },
+ matrix: { a: 30, b: 20, c: -20, d: 30, e: 40, f: 640 },
+ });
+
+ expect(detectTables([...table, watermark], 0)).toHaveLength(1);
+ });
+
+ it("does not take a grid that other page text runs through", () => {
+ const table = grid([50, 200, 350], 700, 20, [
+ ["Item", "Qty", "Price"],
+ ["Widget", "2", "$10.00"],
+ ["Gadget", "5", "$25.00"],
+ ]);
+ const paragraph = run(
+ 40,
+ 655,
+ 380,
+ "Body text set across the same area as the grid\nand reading straight through it\nline after line",
+ {
+ bounds: { x: 40, y: 655, width: 380, height: 60 },
+ paragraphLineCount: 3,
+ },
+ );
+
+ expect(detectTables([...table, paragraph], 0)).toEqual([]);
+ });
+
+ it("does not treat two columns of running text as a table", () => {
+ const runs = grid(
+ [50, 320],
+ 700,
+ 16,
+ SENTENCES.map((line, i) => [line, SENTENCES[(i + 3) % 6]]),
+ ).map((r) => ({ ...r, bounds: { ...r.bounds, width: 240 } }));
+
+ expect(detectTables(runs, 0)).toEqual([]);
+ });
+
+ const line = (x: number, y: number, text: string) =>
+ run(x, y, 120, text, { bounds: { x, y, width: 120, height: 6 } });
+
+ it("does not pair two blocks of lines that sit side by side on their own pitches", () => {
+ const left = Array.from({ length: 14 }, (_, i) =>
+ line(50, 700 - i * 11, `Left block line ${i}`),
+ );
+ const right = Array.from({ length: 11 }, (_, i) =>
+ line(320, 702 - i * 14, `Right block line ${i}`),
+ );
+
+ expect(detectTables([...left, ...right], 0)).toEqual([]);
+ });
+
+ it("keeps a table whose cells wrap onto extra lines in either column", () => {
+ const rows: [string, string][] = [
+ ["Item", "Notes"],
+ ["Widget", "Fits the small frame"],
+ ["", "and the large one"],
+ ["Gadget with a", "Ships flat"],
+ ["long name", ""],
+ ["Sprocket", "Spare part"],
+ ["", "for the gadget"],
+ ["Bracket for", "Wall mount"],
+ ["the wall", ""],
+ ];
+ const runs = rows.flatMap(([a, b], i) =>
+ [a && line(50, 700 - i * 11, a), b && line(320, 701 - i * 11, b)].filter(
+ (r): r is TextRunSnapshot => !!r,
+ ),
+ );
+
+ expect(detectTables(runs, 0)).toHaveLength(1);
+ });
+
+ it("keeps a table's edge near its text when its columns sit far apart", () => {
+ const runs = [
+ line(50, 700, "Declared interest"),
+ line(480, 700, "Declared value"),
+ line(50, 690, "in timely delivery"),
+ line(480, 690, "per the consignor"),
+ ];
+ const [table] = detectTables(runs, 0);
+
+ expect(table.colEdges[0]).toBeGreaterThan(30);
+ expect(table.colEdges[table.cols]).toBeLessThan(620);
+ });
+
+ it("keeps a table of long descriptions whose rows the page rules apart", () => {
+ const runs = grid(
+ [50, 320],
+ 700,
+ 20,
+ SENTENCES.map((line, i) => [line, SENTENCES[(i + 3) % 6]]),
+ ).map((r) => ({ ...r, bounds: { ...r.bounds, width: 240 } }));
+ const rules = [716, ...SENTENCES.map((_, i) => 696 - i * 20)].map(ruleAt);
+
+ expect(detectTables(runs, 0, {}, rules)).toHaveLength(1);
+ });
+});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/tableGrouping.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/tableGrouping.test.ts
new file mode 100644
index 0000000000..068e3e074b
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/tableGrouping.test.ts
@@ -0,0 +1,100 @@
+// @vitest-environment node
+import { describe, expect, it } from "vitest";
+import { Page } from "@editor/tools/pdfTextEditor/model/Page";
+import { TextRun } from "@editor/tools/pdfTextEditor/model/TextRun";
+import { LineGrouper } from "@editor/tools/pdfTextEditor/pdfium/LineGrouper";
+import { ParagraphGrouper } from "@editor/tools/pdfTextEditor/pdfium/ParagraphGrouper";
+import { RENDER_MODE_INVISIBLE } from "@editor/tools/pdfTextEditor/types";
+
+const FONT_SIZE = 9;
+// Tight enough for the rows to pass as lines of one paragraph.
+const ROW_PITCH = 16;
+let ptr = 1000;
+
+function cell(x: number, row: number, text: string, renderMode = 0): TextRun {
+ const f = 700 - row * ROW_PITCH;
+ return new TextRun({
+ id: `r${ptr}`,
+ pageIndex: 0,
+ bounds: {
+ x,
+ y: f,
+ width: text.length * FONT_SIZE * 0.5,
+ height: FONT_SIZE,
+ },
+ matrix: { a: FONT_SIZE, b: 0, c: 0, d: FONT_SIZE, e: x, f },
+ text,
+ fontId: "pdf:1:Test",
+ fontSize: FONT_SIZE,
+ fill: { r: 0, g: 0, b: 0, a: 255 },
+ fontSubset: false,
+ pdfiumObjPtr: ptr++,
+ containerPtr: 0,
+ renderMode,
+ });
+}
+
+function group(runs: TextRun[]): string[] {
+ const page = new Page({ index: 0, pagePtr: 1, width: 600, height: 800 });
+ page.setRuns(runs);
+ page.loaded = true;
+ LineGrouper.apply(page);
+ ParagraphGrouper.apply(page);
+ return page.runs.map((run) => run.text);
+}
+
+describe("grouping a table", () => {
+ it("keeps every cell of a tightly set table its own box", () => {
+ const rows = [
+ ["Item", "Qty", "Price", "Total"],
+ ["Widget 1", "10", "13.20", "16.30"],
+ ["Widget 2", "17", "20.20", "23.30"],
+ ["Widget 3", "24", "27.20", "30.30"],
+ ];
+ const runs = rows.flatMap((row, r) =>
+ row.map((text, c) => cell(40 + c * 60, r, text)),
+ );
+
+ expect(group(runs).sort()).toEqual(rows.flat().sort());
+ });
+
+ it("keeps a two-column table of labels and amounts apart", () => {
+ const rows = [
+ ["Subtotal", "1,204.00"],
+ ["Tax", "240.80"],
+ ["Total", "1,444.80"],
+ ];
+ const runs = rows.flatMap((row, r) =>
+ row.map((text, c) => cell(40 + c * 120, r, text)),
+ );
+
+ expect(group(runs).sort()).toEqual(rows.flat().sort());
+ });
+
+ it("still joins narrow columns of running text into paragraphs", () => {
+ const left = ["The quick brown", "fox jumps over", "the lazy dog"];
+ const right = ["Pack my box", "with five dozen", "liquor jugs"];
+ const runs = [
+ ...left.map((text, r) => cell(40, r, text)),
+ ...right.map((text, r) => cell(200, r, text)),
+ ];
+
+ expect(group(runs).sort()).toEqual(
+ [left.join("\n"), right.join("\n")].sort(),
+ );
+ });
+
+ it("keeps a scanned paragraph whole when a typed word sits on one of its lines", () => {
+ const ocr = [
+ "This agreement is made between",
+ "the supplier and the customer",
+ "within fourteen days",
+ ];
+ const runs = [
+ ...ocr.map((text, r) => cell(40, r, text, RENDER_MODE_INVISIBLE)),
+ cell(200, 0, "Yp3"),
+ ];
+
+ expect(group(runs).sort()).toEqual(["Yp3", ocr.join("\n")].sort());
+ });
+});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/toolbarState.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/toolbarState.test.ts
index 39b4070a58..e8a444f065 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/toolbarState.test.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/toolbarState.test.ts
@@ -53,3 +53,71 @@ describe("deriveToolbarState mixed.fontFamily", () => {
expect(s.mixed.fontFamily).toBe(false);
});
});
+
+describe("deriveToolbarState documentFontId", () => {
+ const changed = (id: string, from: string) => ({
+ ...mkRun(id, "device:Arial"),
+ documentFontId: from,
+ });
+
+ it("is null while the runs are still in the PDF's own font", () => {
+ const s = deriveToolbarState(
+ mkPages([mkRun("a", "pdf:1:Garamond")]),
+ mkSel(["a"]),
+ );
+ expect(s.documentFontId).toBeNull();
+ });
+
+ it("names the font every selected run was changed away from", () => {
+ const s = deriveToolbarState(
+ mkPages([changed("a", "pdf:1:Garamond"), changed("b", "pdf:1:Garamond")]),
+ mkSel(["a", "b"]),
+ );
+ expect(s.documentFontId).toBe("pdf:1:Garamond");
+ });
+
+ it("is null when the runs came from different fonts", () => {
+ const s = deriveToolbarState(
+ mkPages([changed("a", "pdf:1:Garamond"), changed("b", "pdf:2:Bodoni")]),
+ mkSel(["a", "b"]),
+ );
+ expect(s.documentFontId).toBeNull();
+ });
+
+ it("is null when only some runs were changed", () => {
+ const s = deriveToolbarState(
+ mkPages([changed("a", "pdf:1:Garamond"), mkRun("b", "device:Arial")]),
+ mkSel(["a", "b"]),
+ );
+ expect(s.documentFontId).toBeNull();
+ });
+});
+
+describe("deriveToolbarState for characters selected inside a run", () => {
+ const pages = mkPages([mkRun("a", "base14:Helvetica")]);
+
+ it("describes the selected characters' fonts, not the run's", () => {
+ const s = deriveToolbarState(pages, mkSel(["a"]), null, [
+ "base14:Helvetica-Bold",
+ ]);
+ expect(s.bold).toBe(true);
+ expect(s.fontFamily).toBe("base14:Helvetica-Bold");
+ });
+
+ it("reads bold and regular cuts of one family as one family with Bold mixed", () => {
+ const s = deriveToolbarState(pages, mkSel(["a"]), null, [
+ "base14:Helvetica",
+ "base14:Helvetica-Bold",
+ ]);
+ expect(s.mixed.bold).toBe(true);
+ expect(s.mixed.fontFamily).toBe(false);
+ });
+
+ it("reads two families as mixed", () => {
+ const s = deriveToolbarState(pages, mkSel(["a"]), null, [
+ "base14:Helvetica",
+ "base14:Times-Roman",
+ ]);
+ expect(s.mixed.fontFamily).toBe(true);
+ });
+});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/twoColumnLines.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/twoColumnLines.test.ts
new file mode 100644
index 0000000000..a63b9345b8
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/twoColumnLines.test.ts
@@ -0,0 +1,126 @@
+// @vitest-environment node
+import { readFile } from "node:fs/promises";
+import { createRequire } from "node:module";
+import path from "node:path";
+import { afterAll, afterEach, beforeAll, expect, test, vi } from "vitest";
+import { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
+import type { GroupingMode } from "@editor/tools/pdfTextEditor/types";
+import { PdfiumTextReader } from "@editor/tools/pdfTextEditor/pdfium/PdfiumTextReader";
+import { detectTables } from "@editor/tools/pdfTextEditor/util/tableDetection";
+
+const SAMPLE = path.join(
+ import.meta.dirname,
+ "../../../tests/test-fixtures/two-column-sample.pdf",
+);
+const GUTTER = { left: 296.5, right: 305.5 };
+
+const opened: EditorDocument[] = [];
+
+beforeAll(async () => {
+ const wasm = await readFile(
+ createRequire(import.meta.url).resolve("@embedpdf/pdfium/pdfium.wasm"),
+ );
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async (url: string) =>
+ String(url).endsWith(".wasm")
+ ? new Response(wasm, {
+ headers: { "Content-Type": "application/wasm" },
+ })
+ : new Response(null, { status: 404 }),
+ ),
+ );
+});
+
+afterEach(() => {
+ for (const doc of opened.splice(0)) doc.dispose();
+});
+
+afterAll(() => vi.unstubAllGlobals());
+
+async function read(pageIndex: number, mode: GroupingMode) {
+ const doc = await EditorDocument.open(new Uint8Array(await readFile(SAMPLE)));
+ opened.push(doc);
+ const page = doc.page(pageIndex);
+ PdfiumTextReader.populate(doc, page, mode);
+ return page;
+}
+
+function crossesGutter(run: { bounds: { x: number; width: number } }) {
+ return (
+ run.bounds.x < GUTTER.right && run.bounds.x + run.bounds.width > GUTTER.left
+ );
+}
+
+test("reads each column's lines apart at a gutter narrower than the widest word gap", async () => {
+ const page = await read(0, "line");
+ const body = page.runs.filter((run) => !/regional council/.test(run.text));
+
+ expect(body.filter(crossesGutter).map((run) => run.text)).toEqual([]);
+ expect(body.map((run) => run.text)).toContain(
+ "Northern ferries carry freight between the islands",
+ );
+ expect(body.map((run) => run.text)).toContain(
+ "Village councils meet each month to plan repairs to",
+ );
+});
+
+test("groups each column into paragraphs of its own", async () => {
+ const page = await read(0, "auto");
+ const body = page.runs.filter((run) => !/regional council/.test(run.text));
+
+ expect(body.filter(crossesGutter).map((run) => run.text)).toEqual([]);
+ expect(body.map((run) => run.text.replace(/\s+/g, " "))).toEqual(
+ expect.arrayContaining([
+ "Northern ferries carry freight between the islands every morning and return with the mail before the harbour closes for the night.",
+ "Village councils meet each month to plan repairs to the piers, the lighthouse and the narrow roads that link the farms to the quay.",
+ ]),
+ );
+});
+
+test("finds no table in a page of two columns", async () => {
+ const page = await read(0, "line");
+
+ expect(
+ detectTables(
+ page.runs.map((run) => run.snapshot()),
+ 0,
+ {},
+ page.rules,
+ ),
+ ).toEqual([]);
+});
+
+test("keeps a running header on one line with the page number set beside it", async () => {
+ const page = await read(0, "line");
+
+ expect(page.runs.map((run) => run.text)).toContain(
+ "Island transport survey, second interim report to the regional council 1",
+ );
+});
+
+test("keeps justified words saved one object each on their lines, however wide their gaps", async () => {
+ const page = await read(1, "line");
+
+ expect(page.runs.slice(0, 5).map((run) => run.text)).toEqual([
+ "Every word of this paragraph is its own",
+ "object, spread across the measure with gaps",
+ "as wide as a narrow column gutter so",
+ "only the page layout can say which gap",
+ "is a gutter and which is a word space.",
+ ]);
+});
+
+test("keeps short labels on one line with their values a tab stop away", async () => {
+ const page = await read(1, "line");
+
+ expect(
+ page.runs.slice(5).map((run) => run.text.replace(/\s+/g, " ")),
+ ).toEqual([
+ "Name: Jana Novak, harbour office of the northern islands",
+ "Room: Freight bookings and passenger timetables for summer",
+ "Email: Crossing schedules and the second revision of fares",
+ "Code: Extension two hundred and eleven during office hours",
+ "Name: Tomas Berg, weather desk and the morning radio report",
+ ]);
+});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/type3Restore.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/type3Restore.test.ts
new file mode 100644
index 0000000000..ce3058b8ac
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/type3Restore.test.ts
@@ -0,0 +1,85 @@
+// @vitest-environment node
+import { readFile } from "node:fs/promises";
+import { createRequire } from "node:module";
+import { afterAll, beforeAll, expect, test, vi } from "vitest";
+import { SetFontFamilyCommand } from "@editor/tools/pdfTextEditor/commands/SetFontFamilyCommand";
+import { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
+import { PdfiumTextReader } from "@editor/tools/pdfTextEditor/pdfium/PdfiumTextReader";
+import {
+ buildClassicPdf,
+ streamBody,
+} from "@editor/tools/pdfTextEditor/__tests__/pdfFixtures";
+
+beforeAll(async () => {
+ const wasm = await readFile(
+ createRequire(import.meta.url).resolve("@embedpdf/pdfium/pdfium.wasm"),
+ );
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(
+ async () =>
+ new Response(wasm, { headers: { "Content-Type": "application/wasm" } }),
+ ),
+ );
+});
+
+afterAll(() => vi.unstubAllGlobals());
+
+const BOX = "0 0 500 700 d1 0 0 500 700 re f";
+
+// A Type 3 font as older Matplotlib writes it: glyphs named by a Differences
+// encoding and no ToUnicode map.
+function type3Pdf(): Uint8Array {
+ return buildClassicPdf(
+ [
+ { num: 1, body: "<< /Type /Catalog /Pages 2 0 R >>" },
+ { 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] " +
+ "/Resources << /Font << /T3 5 0 R >> >> /Contents 4 0 R >>",
+ },
+ {
+ num: 4,
+ body: streamBody("", "BT /T3 20 Tf 72 700 Td (abba) Tj ET"),
+ },
+ {
+ num: 5,
+ body:
+ "<< /Type /Font /Subtype /Type3 /FontBBox [0 0 500 700] " +
+ "/FontMatrix [0.001 0 0 0.001 0 0] /CharProcs << /a 6 0 R /b 7 0 R >> " +
+ "/Encoding << /Type /Encoding /Differences [97 /a /b] >> " +
+ "/FirstChar 97 /LastChar 98 /Widths [500 500] /Resources << >> >>",
+ },
+ { num: 6, body: streamBody("", BOX) },
+ { num: 7, body: streamBody("", BOX) },
+ ],
+ 1,
+ );
+}
+
+test("refuses, with a reason, to put text back in a Type 3 document font it cannot write", async () => {
+ const doc = await EditorDocument.open(type3Pdf());
+ try {
+ const page = doc.page(0);
+ PdfiumTextReader.populate(doc, page);
+ const run = page.runs.find((r) => r.text.trim() === "abba")!;
+ const original = run.fontId;
+ new SetFontFamilyCommand({
+ pageIndex: 0,
+ runId: run.id,
+ nextFamily: "Helvetica",
+ }).apply(doc);
+ expect(run.fontId).not.toBe(original);
+
+ const restore = new SetFontFamilyCommand({
+ pageIndex: 0,
+ runId: run.id,
+ nextFamily: original,
+ });
+ expect(restore.refusal(doc)).toBe("notRestored");
+ } finally {
+ doc.dispose();
+ }
+});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/typedAdvances.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/typedAdvances.test.ts
new file mode 100644
index 0000000000..0e24dde831
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/typedAdvances.test.ts
@@ -0,0 +1,71 @@
+import { describe, expect, test } from "vitest";
+import {
+ lineWidthPx,
+ mergeAdvances,
+ unpricedChars,
+} from "@editor/tools/pdfTextEditor/util/typedAdvances";
+
+const BROWSER_PX = 20;
+const browser = () => BROWSER_PX;
+
+describe("typed letter prices", () => {
+ test("names the letters the table cannot price, line breaks aside", () => {
+ const table = new Map([["a", 0.5]]);
+ expect([...unpricedChars("ab\nca", table)].sort()).toEqual(["b", "c"]);
+ expect(unpricedChars("aa", table).size).toBe(0);
+ });
+
+ test("a learned price replaces the one the run started with", () => {
+ const merged = mergeAdvances(
+ new Map([
+ ["a", 0.5],
+ ["b", 0.6],
+ ]),
+ new Map([["a", 0.4]]),
+ );
+ expect(merged?.get("a")).toBe(0.4);
+ expect(merged?.get("b")).toBe(0.6);
+ });
+
+ test("prices typed letters from the table and unknown ones from the browser", () => {
+ const table = new Map([["a", 0.5]]);
+ // 10px font: "a" is 5px, "z" falls back to the browser's 20px.
+ expect(lineWidthPx("aaz", 0, null, table, 10, 1, browser)).toBe(30);
+ });
+
+ test("keeps the engine's width for the measured part and prices only what was typed after it", () => {
+ const measured = {
+ text: "ab cd",
+ starts: [0, 4, NaN, 12, 16],
+ ends: [5, 9, NaN, 17, 21],
+ };
+ const table = new Map([["e", 0.5]]);
+ // The measured line reaches 21pt; at 2px/pt that is 42px, plus "e" at 5px.
+ expect(lineWidthPx("ab cde", 0, measured, table, 10, 2, browser)).toBe(47);
+ });
+
+ test("an edit inside the measured text prices from the first changed letter", () => {
+ const measured = {
+ text: "abcd",
+ starts: [0, 4, 8, 12],
+ ends: [5, 9, 13, 17],
+ };
+ const table = new Map([
+ ["x", 0.4],
+ ["c", 0.4],
+ ["d", 0.4],
+ ]);
+ // "ab" is known: the pen stands at 8pt (16px) before the changed letter.
+ expect(lineWidthPx("abxcd", 0, measured, table, 10, 2, browser)).toBe(28);
+ });
+
+ test("measures the line the caret is on, ignoring its trailing spaces", () => {
+ const measured = {
+ text: "ab\ncd",
+ starts: [0, 4, NaN, 0, 4],
+ ends: [5, 9, NaN, 5, 9],
+ };
+ const table = new Map([[" ", 0.3]]);
+ expect(lineWidthPx("ab\ncd ", 1, measured, table, 10, 1, browser)).toBe(9);
+ });
+});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/typedOverWord.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/typedOverWord.test.ts
new file mode 100644
index 0000000000..6ecd3e0569
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/typedOverWord.test.ts
@@ -0,0 +1,300 @@
+// @vitest-environment node
+import { readFile } from "node:fs/promises";
+import { createRequire } from "node:module";
+import path from "node:path";
+import { afterAll, afterEach, beforeAll, expect, test, vi } from "vitest";
+import { resetContentStreamCache } from "@editor/tools/pdfTextEditor/charcode/ContentStreamResolver";
+import { EditTextCommand } from "@editor/tools/pdfTextEditor/commands/EditTextCommand";
+import {
+ resetCharCoverageCache,
+ resetOnPageAdvCache,
+} from "@editor/tools/pdfTextEditor/commands/editTextHelpers";
+import { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
+import { PdfiumTextReader } from "@editor/tools/pdfTextEditor/pdfium/PdfiumTextReader";
+import { HistoryStack } from "@editor/tools/pdfTextEditor/store/HistoryStack";
+import { exportToBlob } from "@editor/tools/pdfTextEditor/util/exportPdf";
+
+const FIXTURES = path.join(import.meta.dirname, "../../../tests/test-fixtures");
+const FPDF_PAGEOBJ_TEXT = 1;
+
+const opened: EditorDocument[] = [];
+
+beforeAll(async () => {
+ const wasm = await readFile(
+ createRequire(import.meta.url).resolve("@embedpdf/pdfium/pdfium.wasm"),
+ );
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async (url: string) =>
+ String(url).endsWith(".wasm")
+ ? new Response(wasm, {
+ headers: { "Content-Type": "application/wasm" },
+ })
+ : new Response(null, { status: 404 }),
+ ),
+ );
+});
+
+afterEach(() => {
+ for (const doc of opened.splice(0)) doc.dispose();
+ // Keyed by font and page pointers, which the next document reuses.
+ resetCharCoverageCache();
+ resetContentStreamCache();
+ resetOnPageAdvCache();
+});
+
+afterAll(() => vi.unstubAllGlobals());
+
+async function open(bytes: Uint8Array): Promise<EditorDocument> {
+ const doc = await EditorDocument.open(bytes);
+ opened.push(doc);
+ PdfiumTextReader.populate(doc, doc.page(0));
+ return doc;
+}
+
+const fixture = async (name: string) =>
+ open(new Uint8Array(await readFile(path.join(FIXTURES, name))));
+
+const saved = async (doc: EditorDocument) =>
+ open(new Uint8Array(await (await exportToBlob(doc)).arrayBuffer()));
+
+interface Glyph {
+ char: string;
+ x: number;
+}
+
+interface Drawn {
+ text: string;
+ font: string;
+ left: number;
+ glyphs: Glyph[];
+}
+
+/** Every text object on the baseline at `y`, with the characters its glyphs drew and where. */
+function drawnOn(doc: EditorDocument, y: number): Drawn[] {
+ const m = doc.module;
+ const pagePtr = doc.page(0).pagePtr;
+ const buf = m.pdfium.wasmExports.malloc(1024);
+ const textPage = m.FPDFText_LoadPage(pagePtr);
+ const glyphs = new Map<number, Glyph[]>();
+ const out: Drawn[] = [];
+ try {
+ for (let i = 0; i < m.FPDFText_CountChars(textPage); i++) {
+ if (m.FPDFText_IsGenerated(textPage, i) === 1) continue;
+ const obj = m.FPDFText_GetTextObject(textPage, i);
+ m.FPDFText_GetCharOrigin(textPage, i, buf, buf + 8);
+ const drawn = glyphs.get(obj) ?? [];
+ drawn.push({
+ char: String.fromCodePoint(m.FPDFText_GetUnicode(textPage, i)),
+ x: m.pdfium.getValue(buf, "double"),
+ });
+ glyphs.set(obj, drawn);
+ }
+ for (let i = 0; i < m.FPDFPage_CountObjects(pagePtr); i++) {
+ const obj = m.FPDFPage_GetObject(pagePtr, i);
+ if (m.FPDFPageObj_GetType(obj) !== FPDF_PAGEOBJ_TEXT) continue;
+ m.FPDFPageObj_GetBounds(obj, buf, buf + 4, buf + 8, buf + 12);
+ const left = m.pdfium.getValue(buf, "float");
+ const bottom = m.pdfium.getValue(buf + 4, "float");
+ const top = m.pdfium.getValue(buf + 12, "float");
+ if (bottom > y + 1 || top < y) continue;
+ m.FPDFTextObj_GetText(obj, textPage, buf, 512);
+ const text = m.pdfium.UTF16ToString(buf);
+ m.FPDFFont_GetBaseFontName(m.FPDFTextObj_GetFont(obj), buf, 256);
+ out.push({
+ text,
+ font: m.pdfium.UTF8ToString(buf),
+ left: Math.round(left * 10) / 10,
+ glyphs: glyphs.get(obj) ?? [],
+ });
+ }
+ } finally {
+ m.FPDFText_ClosePage(textPage);
+ m.pdfium.wasmExports.free(buf);
+ }
+ return out;
+}
+
+/** Give the line holding `word` each of `texts` in turn, as a key at a time does. */
+function typeTexts(
+ doc: EditorDocument,
+ history: HistoryStack,
+ word: string,
+ texts: (original: string) => string[],
+) {
+ const run = doc.page(0).runs.find((r) => r.text.includes(word))!;
+ const original = run.text;
+ for (const nextText of texts(original))
+ history.execute(
+ new EditTextCommand({ pageIndex: 0, runId: run.id, nextText }),
+ doc,
+ );
+ return { run, original, baseline: run.matrix.f };
+}
+
+/** Select `word` in the line holding it and type `typed` over it. */
+function typeOver(
+ doc: EditorDocument,
+ history: HistoryStack,
+ word: string,
+ typed: string,
+) {
+ return typeTexts(doc, history, word, (original) =>
+ [...typed].map((_, keys) =>
+ original.replace(word, typed.slice(0, keys + 1)),
+ ),
+ );
+}
+
+const lettersIn = (drawn: Drawn[], font: RegExp) =>
+ drawn
+ .filter((object) => font.test(object.font))
+ .flatMap((object) => [...object.text.replace(/\s/g, "")]);
+
+const lineAt = (doc: EditorDocument, y: number) =>
+ doc
+ .page(0)
+ .runs.filter((r) => Math.abs(r.matrix.f - y) < 2)
+ .map((r) => r.text);
+
+/** How far the glyph drawing "ti" moves the pen, from where the "c" after it starts: a ligature's advance, which neither a missing-glyph box nor an "i" alone has. */
+function ligatureAdvance(drawn: Drawn[]): number | null {
+ for (const { glyphs } of drawn)
+ for (let i = 0; i + 2 < glyphs.length; i++)
+ if (
+ glyphs
+ .slice(i, i + 3)
+ .map(({ char }) => char)
+ .join("") === "tic"
+ )
+ return glyphs[i + 2].x - glyphs[i].x;
+ return null;
+}
+
+test.each([
+ [
+ "a word typed over a selected one",
+ ["Quarterly Z heading", "Quarterly Ze heading", "Quarterly Zebra heading"],
+ (drawn: Drawn) => drawn,
+ ],
+ // Deleting a letter rewrites the heading's object in place, and undoing that lays its letters out afresh.
+ [
+ "letters typed into the middle of a word",
+ [
+ "Quaterly report heading",
+ "QuaZterly report heading",
+ "QuaZbterly report heading",
+ ],
+ ({ text, font, left }: Drawn) => ({ text, font, left }),
+ ],
+])(
+ "draws %s in a face that has the letters when the document's subset keeps a box for those it lacks",
+ async (_case, texts, restored) => {
+ const doc = await fixture("subset-truetype-heading.pdf");
+ const history = new HistoryStack();
+ const subset = /DejaVuSans-Bold/;
+ const held = new Set("Quarterlyreportheading");
+ const next = texts.at(-1)!;
+ const before = drawnOn(
+ doc,
+ doc.page(0).runs.find((r) => r.text.includes("Quarterly"))!.matrix.f,
+ );
+
+ const { run, original, baseline } = typeTexts(
+ doc,
+ history,
+ "Quarterly",
+ () => texts,
+ );
+
+ expect(run.text).toBe(next);
+ for (const letter of lettersIn(drawnOn(doc, baseline), subset))
+ expect(held).toContain(letter);
+ const again = await saved(doc);
+ expect(lineAt(again, baseline)).toEqual([next]);
+ for (const letter of lettersIn(drawnOn(again, baseline), subset))
+ expect(held).toContain(letter);
+
+ history.undo(doc);
+ expect(run.text).toBe(original);
+ expect(drawnOn(doc, baseline).map(restored)).toEqual(before.map(restored));
+ history.redo(doc);
+ expect(run.text).toBe(next);
+ for (const letter of lettersIn(drawnOn(doc, baseline), subset))
+ expect(held).toContain(letter);
+ },
+);
+
+test("keeps a ligature whose letters the subset holds no glyphs of their own for, through an edit of its line, a save and an undo", async () => {
+ const doc = await fixture("ligature-heading.pdf");
+ const history = new HistoryStack();
+ const heading = doc.page(0).runs.find((r) => r.text === "Article premier")!;
+ const advance = ligatureAdvance(drawnOn(doc, heading.matrix.f))!;
+ const ligature = (from: EditorDocument) =>
+ expect(ligatureAdvance(drawnOn(from, heading.matrix.f))).toBeCloseTo(
+ advance,
+ 1,
+ );
+
+ const { run, baseline } = typeOver(doc, history, "premier", "prime");
+
+ expect(run.text).toBe("Article prime");
+ ligature(doc);
+ const again = await saved(doc);
+ expect(lineAt(again, baseline)).toEqual(["Article prime"]);
+ ligature(again);
+
+ history.undo(doc);
+ expect(run.text).toBe("Article premier");
+ ligature(doc);
+ expect(lineAt(await saved(doc), baseline)).toEqual(["Article premier"]);
+ history.redo(doc);
+ expect(run.text).toBe("Article prime");
+ ligature(doc);
+});
+
+test.each([
+ ["mushroom-life.pdf", "Spore", "Zqx 7", "Zqx 7 Stage"],
+ ["mixed-style-sample.pdf", "reply", "Zqx", "Note: urgent Zqx needed soon."],
+])(
+ "keeps the spaces beside a word typed over one in %s",
+ async (file, word, typed, expected) => {
+ const doc = await fixture(file);
+ const history = new HistoryStack();
+ const singleSpaced = (texts: string[]) =>
+ texts.map((text) => text.replace(/ +/g, " "));
+
+ const { run, original, baseline } = typeOver(doc, history, word, typed);
+ const before = lineAt(await fixture(file), baseline);
+
+ expect(singleSpaced(lineAt(await saved(doc), baseline))).toEqual([
+ expected,
+ ]);
+
+ history.undo(doc);
+ expect(run.text).toBe(original);
+ expect(lineAt(await saved(doc), baseline)).toEqual(before);
+ history.redo(doc);
+ expect(singleSpaced(lineAt(await saved(doc), baseline))).toEqual([
+ expected,
+ ]);
+ },
+);
+
+test("redraws a paragraph line whose font draws no space when its first word is typed over, and puts the line back on undo", async () => {
+ const doc = await fixture("mushroom-life.pdf");
+ const history = new HistoryStack();
+ const texts = (from: EditorDocument) => from.page(0).runs.map((r) => r.text);
+ const before = texts(doc);
+ const typedLine = async () =>
+ texts(await saved(doc)).find((text) => text.includes("Zqx"));
+
+ typeOver(doc, history, "Mushrooms", "Zqx");
+
+ expect(await typedLine()).toMatch(/^Zqx represent one of nature/);
+
+ history.undo(doc);
+ expect(texts(await saved(doc))).toEqual(before);
+ history.redo(doc);
+ expect(await typedLine()).toMatch(/^Zqx represent one of nature/);
+});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/typedScriptText.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/typedScriptText.test.ts
new file mode 100644
index 0000000000..c046df81fd
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/typedScriptText.test.ts
@@ -0,0 +1,245 @@
+// @vitest-environment node
+import { readFileSync } from "node:fs";
+import { readFile } from "node:fs/promises";
+import { createRequire } from "node:module";
+import path from "node:path";
+import {
+ afterAll,
+ afterEach,
+ beforeAll,
+ beforeEach,
+ describe,
+ expect,
+ test,
+ vi,
+} from "vitest";
+
+const { get } = vi.hoisted(() => ({ get: vi.fn() }));
+vi.mock("@editor/services/apiClient", () => ({ default: { get } }));
+
+import { EditTextCommand } from "@editor/tools/pdfTextEditor/commands/EditTextCommand";
+import { getDroppedBase14Chars } from "@editor/tools/pdfTextEditor/commands/editTextHelpers";
+import { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
+import { PdfiumTextReader } from "@editor/tools/pdfTextEditor/pdfium/PdfiumTextReader";
+import { EditorStore } from "@editor/tools/pdfTextEditor/store/EditorStore";
+import {
+ SERVER_FONTS_URL,
+ forgetServerFontList,
+} from "@editor/tools/pdfTextEditor/util/serverFonts";
+import { _resetScanFacesForTests } from "@editor/tools/pdfTextEditor/util/scanFontLibrary";
+import { FONT_DIR } from "@editor/tools/pdfTextEditor/__tests__/scanFixtures";
+
+const SAMPLE = path.join(
+ import.meta.dirname,
+ "../../../tests/test-fixtures/mixed-style-sample.pdf",
+);
+const FPDF_PAGEOBJ_TEXT = 1;
+
+let wasm: Buffer<ArrayBuffer>;
+const stores: EditorStore[] = [];
+
+const SERVED = [
+ ["Noto Sans JP", "NotoSansJP-Regular.ttf"],
+ ["Noto Sans Arabic", "NotoSansArabic-Regular.ttf"],
+] as const;
+const faceId = (i: number) => (i + 1).toString(16).padStart(64, "0");
+
+function serveScriptFonts(): void {
+ get.mockImplementation(async (url: string) => {
+ if (url === SERVER_FONTS_URL)
+ return {
+ data: {
+ families: SERVED.map(([family, file], i) => ({
+ family,
+ faces: [
+ {
+ id: faceId(i),
+ style: "Regular",
+ bold: false,
+ italic: false,
+ weight: 400,
+ postscriptName: file.replace(".ttf", ""),
+ },
+ ],
+ })),
+ },
+ };
+ const served = SERVED.findIndex((_, i) => url.endsWith(faceId(i)));
+ if (served >= 0)
+ return {
+ data: new Uint8Array(
+ readFileSync(path.join(FONT_DIR, SERVED[served][1])),
+ ).buffer,
+ };
+ throw new Error("unavailable");
+ });
+}
+
+beforeAll(async () => {
+ wasm = await readFile(
+ createRequire(import.meta.url).resolve("@embedpdf/pdfium/pdfium.wasm"),
+ );
+});
+
+beforeEach(() => {
+ get.mockReset();
+ forgetServerFontList();
+ _resetScanFacesForTests();
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async (url: string) =>
+ String(url).endsWith(".wasm")
+ ? new Response(wasm, {
+ headers: { "Content-Type": "application/wasm" },
+ })
+ : new Response(null, { status: 404 }),
+ ),
+ );
+});
+
+afterEach(() => {
+ for (const store of stores.splice(0)) store.dispose();
+});
+
+afterAll(() => vi.unstubAllGlobals());
+
+async function storeWithSample(): Promise<EditorStore> {
+ const doc = await EditorDocument.open(new Uint8Array(await readFile(SAMPLE)));
+ const store = new EditorStore();
+ stores.push(store);
+ await store.setDocument(doc);
+ PdfiumTextReader.populate(doc, doc.page(0));
+ return store;
+}
+
+// Every text object on the first page as "text@BaseFont", subset tag stripped.
+function drawnTexts(doc: EditorDocument): string[] {
+ const m = doc.module;
+ const page = doc.page(0);
+ const text = m.pdfium.wasmExports.malloc(512);
+ const name = m.pdfium.wasmExports.malloc(256);
+ const textPage = m.FPDFText_LoadPage(page.pagePtr);
+ const out: string[] = [];
+ try {
+ for (let i = 0; i < m.FPDFPage_CountObjects(page.pagePtr); i++) {
+ const obj = m.FPDFPage_GetObject(page.pagePtr, i);
+ if (m.FPDFPageObj_GetType(obj) !== FPDF_PAGEOBJ_TEXT) continue;
+ m.FPDFTextObj_GetText(obj, textPage, text, 512);
+ m.FPDFFont_GetBaseFontName(m.FPDFTextObj_GetFont(obj), name, 256);
+ out.push(
+ `${m.pdfium.UTF16ToString(text).trim()}@${m.pdfium.UTF8ToString(name).replace(/^[A-Z]{6}\+/, "")}`,
+ );
+ }
+ } finally {
+ m.FPDFText_ClosePage(textPage);
+ m.pdfium.wasmExports.free(text);
+ m.pdfium.wasmExports.free(name);
+ }
+ return out;
+}
+
+function typeAtEnd(store: EditorStore, needle: string, add: string): string {
+ const run = store
+ .document!.page(0)
+ .runs.find((r) => r.text.includes(needle))!;
+ const before = run.text;
+ store.dispatch(
+ new EditTextCommand({
+ pageIndex: 0,
+ runId: run.id,
+ nextText: run.text + add,
+ }),
+ );
+ return before;
+}
+
+describe("typing text of a script no loaded font draws", () => {
+ test("draws it in a served font of that script once the font arrives", async () => {
+ serveScriptFonts();
+ const store = await storeWithSample();
+ const doc = store.document!;
+
+ typeAtEnd(store, "Note:", " 日本語");
+
+ await vi.waitFor(() =>
+ expect(drawnTexts(doc)).toContain("日本語@NotoSansJP-Regular"),
+ );
+ expect(getDroppedBase14Chars()).not.toContain("日");
+ });
+
+ test("leaves the rest of the paragraph in its own faces and symbols when it redraws", async () => {
+ serveScriptFonts();
+ const store = await storeWithSample();
+ const doc = store.document!;
+ const run = doc.page(0).runs.find((r) => r.text.includes("Ratio"))!;
+ const at = run.text.indexOf("Ratio") + "Ratio ".length;
+ const untouched = drawnTexts(doc).filter((t) => !t.startsWith("Ratio"));
+
+ store.dispatch(
+ new EditTextCommand({
+ pageIndex: 0,
+ runId: run.id,
+ nextText: run.text.slice(0, at) + "日本語 " + run.text.slice(at),
+ }),
+ );
+ await vi.waitFor(() =>
+ expect(drawnTexts(doc)).toContain("日本語@NotoSansJP-Regular"),
+ );
+
+ const after = drawnTexts(doc);
+ expect(after).toEqual(expect.arrayContaining(untouched));
+ for (const kept of ["Ratio", "a", "≥", "b", "→", "c,", "done"])
+ expect(after).toContain(`${kept}@LiberationSans`);
+ });
+
+ test("draws typed Arabic in a served Arabic font, reading back as typed", async () => {
+ serveScriptFonts();
+ const store = await storeWithSample();
+ const doc = store.document!;
+
+ typeAtEnd(store, "Note:", " سلام");
+
+ await vi.waitFor(() =>
+ expect(
+ drawnTexts(doc).some((t) => t.endsWith("@NotoSansArabic-Regular")),
+ ).toBe(true),
+ );
+ const arabic = drawnTexts(doc).find((t) =>
+ t.endsWith("@NotoSansArabic-Regular"),
+ )!;
+ expect(arabic.split("@")[0].normalize("NFKC")).toBe("سلام");
+ });
+
+ test("keeps the edit one undo step after redrawing it", async () => {
+ serveScriptFonts();
+ const store = await storeWithSample();
+ const doc = store.document!;
+
+ const before = typeAtEnd(store, "Note:", " 日本語");
+ await vi.waitFor(() =>
+ expect(drawnTexts(doc)).toContain("日本語@NotoSansJP-Regular"),
+ );
+
+ store.undo();
+
+ expect(drawnTexts(doc).some((t) => t.includes("日本語"))).toBe(false);
+ expect(doc.page(0).runs.find((r) => r.text.includes("Note:"))!.text).toBe(
+ before,
+ );
+ });
+
+ test("still drops the text and warns about it when no server font covers it", async () => {
+ get.mockRejectedValue(new Error("unavailable"));
+ const store = await storeWithSample();
+
+ typeAtEnd(store, "Note:", " 日本語");
+
+ expect(getDroppedBase14Chars()).toContain("日");
+ await vi.waitFor(() =>
+ expect(get).toHaveBeenCalledWith(SERVER_FONTS_URL, expect.anything()),
+ );
+ expect(drawnTexts(store.document!).some((t) => t.includes("日本語"))).toBe(
+ false,
+ );
+ });
+});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/typedSpaces.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/typedSpaces.test.ts
new file mode 100644
index 0000000000..b94d5e58a0
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/typedSpaces.test.ts
@@ -0,0 +1,129 @@
+// @vitest-environment node
+import { readFile } from "node:fs/promises";
+import { createRequire } from "node:module";
+import path from "node:path";
+import {
+ afterAll,
+ afterEach,
+ beforeAll,
+ describe,
+ expect,
+ it,
+ vi,
+} from "vitest";
+import {
+ applyPartialEditPlan,
+ planPartialEdit,
+} from "@editor/tools/pdfTextEditor/commands/partialEdit";
+import { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
+import { uniformTags } from "@editor/tools/pdfTextEditor/model/TextTags";
+import { PdfiumTextReader } from "@editor/tools/pdfTextEditor/pdfium/PdfiumTextReader";
+import {
+ buildClassicPdf,
+ streamBody,
+} from "@editor/tools/pdfTextEditor/__tests__/pdfFixtures";
+
+const opened: EditorDocument[] = [];
+
+async function open(bytes: Uint8Array): Promise<EditorDocument> {
+ const doc = await EditorDocument.open(bytes);
+ opened.push(doc);
+ PdfiumTextReader.populate(doc, doc.page(0));
+ return doc;
+}
+
+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)));
+}
+
+/** One Helvetica line drawn a word per text object, so each word is a sub-run of its own. */
+function wordPerObjectPdf(...words: Array<[string, number]>): Uint8Array {
+ const content = words
+ .map(([word, x]) => `BT /F1 12 Tf ${x} 700 Td (${word}) Tj ET\n`)
+ .join("");
+ return buildClassicPdf(
+ [
+ { num: 1, body: "<< /Type /Catalog /Pages 2 0 R >>" },
+ { 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 " +
+ "/Resources << /Font << /F1 5 0 R >> >> >>",
+ },
+ { num: 4, body: streamBody("", content) },
+ {
+ num: 5,
+ body: "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>",
+ },
+ ],
+ 1,
+ );
+}
+
+function edit(doc: EditorDocument, prev: string, next: string) {
+ const page = doc.page(0);
+ const run = page.runs.find((r) => r.text === prev);
+ if (!run) throw new Error(`no run reads "${prev}"`);
+ const prevTexts = [...run.mergedFromTexts];
+ const prevBounds = run.mergedFromBounds.map((b) => ({ ...b }));
+ const before = (text: string) => prevBounds[prevTexts.indexOf(text)];
+ const plan = planPartialEdit(run, prev, next);
+ if (!plan) throw new Error("no plan");
+ const result = applyPartialEditPlan(doc, page, run, plan, uniformTags([]));
+ const after = (text: string) => {
+ const i = result.newMergedFromTexts.indexOf(text);
+ if (i < 0) throw new Error(`no object reads "${text}"`);
+ return result.newMergedFromBounds[i];
+ };
+ return { fontSize: run.fontSize, before, after };
+}
+
+beforeAll(async () => {
+ const wasmBytes = await readFile(
+ createRequire(import.meta.url).resolve("@embedpdf/pdfium/pdfium.wasm"),
+ );
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async () =>
+ Promise.resolve(
+ new Response(wasmBytes, {
+ headers: { "Content-Type": "application/wasm" },
+ }),
+ ),
+ ),
+ );
+});
+
+afterEach(() => {
+ while (opened.length) opened.pop()!.dispose();
+});
+
+afterAll(() => {
+ vi.unstubAllGlobals();
+});
+
+describe("applyPartialEditPlan keeps the space after typed text", () => {
+ it("puts text typed after a trailing space one space past the last letter", async () => {
+ const doc = await openChromePdf();
+ const { fontSize, after } = edit(doc, "Open Source ", "Open Source X");
+ expect(after("X").x - after("e ").right).toBeGreaterThan(fontSize * 0.2);
+ });
+
+ it("moves the following word one space past a typed word that ends in a space", async () => {
+ const doc = await open(wordPerObjectPdf(["Privacy", 72], ["First", 111.4]));
+ const { fontSize, before, after } = edit(
+ doc,
+ "PrivacyFirst",
+ "Privacy Big First",
+ );
+ const oldGap = before("First").x - before("Privacy").right;
+ const space = after("First").x - after("Big").right - oldGap;
+ expect(space).toBeGreaterThan(fontSize * 0.2);
+ expect(space).toBeLessThan(fontSize * 0.35);
+ });
+});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/typedWordFace.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/typedWordFace.test.ts
new file mode 100644
index 0000000000..97d95bc1d6
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/typedWordFace.test.ts
@@ -0,0 +1,153 @@
+// @vitest-environment node
+import { readFile } from "node:fs/promises";
+import { createRequire } from "node:module";
+import path from "node:path";
+import {
+ afterAll,
+ afterEach,
+ beforeAll,
+ describe,
+ expect,
+ test,
+ vi,
+} from "vitest";
+import { EditTextCommand } from "@editor/tools/pdfTextEditor/commands/EditTextCommand";
+import { lacksGlyphsFor } from "@editor/tools/pdfTextEditor/commands/editTextHelpers";
+import { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
+import { PdfiumTextReader } from "@editor/tools/pdfTextEditor/pdfium/PdfiumTextReader";
+import { exportToBlob } from "@editor/tools/pdfTextEditor/util/exportPdf";
+
+// A LaTeX document: its Latin Modern subset holds only the letters the text uses, and no "9" or "Q".
+const SAMPLE = path.join(
+ import.meta.dirname,
+ "../../../tests/test-fixtures/mushroom-life.pdf",
+);
+const FPDF_PAGEOBJ_TEXT = 1;
+
+const opened: EditorDocument[] = [];
+
+beforeAll(async () => {
+ const wasm = await readFile(
+ createRequire(import.meta.url).resolve("@embedpdf/pdfium/pdfium.wasm"),
+ );
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async (url: string) =>
+ String(url).endsWith(".wasm")
+ ? new Response(wasm, {
+ headers: { "Content-Type": "application/wasm" },
+ })
+ : new Response(null, { status: 404 }),
+ ),
+ );
+});
+
+afterEach(() => {
+ for (const doc of opened.splice(0)) doc.dispose();
+});
+
+afterAll(() => vi.unstubAllGlobals());
+
+async function open(bytes: Uint8Array): Promise<EditorDocument> {
+ const doc = await EditorDocument.open(bytes);
+ opened.push(doc);
+ PdfiumTextReader.populate(doc, doc.page(0));
+ return doc;
+}
+
+interface Drawn {
+ text: string;
+ font: number;
+ name: string;
+}
+
+function drawnObjects(doc: EditorDocument): Drawn[] {
+ const m = doc.module;
+ const pagePtr = doc.page(0).pagePtr;
+ const text = m.pdfium.wasmExports.malloc(1024);
+ const name = m.pdfium.wasmExports.malloc(256);
+ const textPage = m.FPDFText_LoadPage(pagePtr);
+ const out: Drawn[] = [];
+ try {
+ for (let i = 0; i < m.FPDFPage_CountObjects(pagePtr); i++) {
+ const obj = m.FPDFPage_GetObject(pagePtr, i);
+ if (m.FPDFPageObj_GetType(obj) !== FPDF_PAGEOBJ_TEXT) continue;
+ m.FPDFTextObj_GetText(obj, textPage, text, 512);
+ const font = m.FPDFTextObj_GetFont(obj);
+ m.FPDFFont_GetBaseFontName(font, name, 256);
+ out.push({
+ text: m.pdfium.UTF16ToString(text),
+ font,
+ name: m.pdfium.UTF8ToString(name),
+ });
+ }
+ } finally {
+ m.FPDFText_ClosePage(textPage);
+ m.pdfium.wasmExports.free(text);
+ m.pdfium.wasmExports.free(name);
+ }
+ return out;
+}
+
+async function typeBefore(
+ doc: EditorDocument,
+ word: string,
+ typed: string,
+): Promise<string> {
+ const page = doc.page(0);
+ const run = page.runs.find(
+ (r) =>
+ r.text.includes(`${word} represent`) ||
+ r.text.includes(`Mushrooms ${word}`),
+ )!;
+ for (const ch of typed) {
+ const current = page.runs.find((r) => r.id === run.id)!.text;
+ const at = current.indexOf(word);
+ new EditTextCommand({
+ pageIndex: 0,
+ runId: run.id,
+ nextText: current.slice(0, at) + ch + current.slice(at),
+ }).apply(doc);
+ }
+ return run.id;
+}
+
+describe("typing a word against one the document's font draws", () => {
+ test("draws every typed letter, even one the font has no glyph for", async () => {
+ const doc = await open(new Uint8Array(await readFile(SAMPLE)));
+ const blank = () =>
+ drawnObjects(doc)
+ .filter(({ text, font }) => lacksGlyphsFor(doc.module, font, text))
+ .map(({ text }) => text);
+ const before = blank();
+ await typeBefore(doc, "represent", "Wj9 ");
+
+ expect(blank()).toEqual(before);
+ });
+
+ test("leaves the word it was typed against in the document's font", async () => {
+ const doc = await open(new Uint8Array(await readFile(SAMPLE)));
+ const fontBefore = drawnObjects(doc).find(({ text }) =>
+ text.includes("Mushrooms"),
+ )!.name;
+ await typeBefore(doc, "represent", "Wj9 ");
+
+ const word = drawnObjects(doc).find(({ text }) =>
+ /^represent\s*$/.test(text),
+ );
+ expect(word?.name).toBe(fontBefore);
+ });
+
+ test("keeps the edited paragraph one box when the file is opened again", async () => {
+ const doc = await open(new Uint8Array(await readFile(SAMPLE)));
+ const paragraphs = doc.page(0).runs.length;
+ await typeBefore(doc, "Mushrooms", "Xk ");
+
+ const saved = new Uint8Array(await (await exportToBlob(doc)).arrayBuffer());
+ const again = await open(saved);
+ expect(again.page(0).runs).toHaveLength(paragraphs);
+ expect(
+ again.page(0).runs.find((r) => r.text.includes("Xk Mushrooms"))?.text,
+ ).toContain("tion in the biological world");
+ });
+});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/undoAfterTableRow.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/undoAfterTableRow.test.ts
new file mode 100644
index 0000000000..744ad8ce5a
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/undoAfterTableRow.test.ts
@@ -0,0 +1,224 @@
+// @vitest-environment node
+import { readFile } from "node:fs/promises";
+import { createRequire } from "node:module";
+import { afterAll, afterEach, beforeAll, expect, test, vi } from "vitest";
+import { DeleteShapeCommand } from "@editor/tools/pdfTextEditor/commands/DeleteShapeCommand";
+import { EditTextCommand } from "@editor/tools/pdfTextEditor/commands/EditTextCommand";
+import { FillTableCellCommand } from "@editor/tools/pdfTextEditor/commands/FillTableCellCommand";
+import { ModifyTableCommand } from "@editor/tools/pdfTextEditor/commands/ModifyTableCommand";
+import type { Command } from "@editor/tools/pdfTextEditor/commands/Command";
+import { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
+import type { TableModel } from "@editor/tools/pdfTextEditor/model/TableModel";
+import { PdfiumTextReader } from "@editor/tools/pdfTextEditor/pdfium/PdfiumTextReader";
+import { HistoryStack } from "@editor/tools/pdfTextEditor/store/HistoryStack";
+import { exportToBlob } from "@editor/tools/pdfTextEditor/util/exportPdf";
+import { adoptedTableModel } from "@editor/tools/pdfTextEditor/util/tableAdoption";
+import { detectTables } from "@editor/tools/pdfTextEditor/util/tableDetection";
+import {
+ buildClassicPdf,
+ streamBody,
+} from "@editor/tools/pdfTextEditor/__tests__/pdfFixtures";
+
+const CELLS = [
+ ["Item", "Qty", "Price"],
+ ["Widget 1", "10.10", "13.20"],
+ ["Widget 2", "17.10", "20.20"],
+ ["Widget 3", "24.10", "27.20"],
+];
+const LEFT = 72;
+const TOP = 700;
+const COL_WIDTH = 100;
+const ROW_HEIGHT = 20;
+const BADGE = { x: 420, y: 650, width: 60, height: 30 };
+
+// Every cell draws its own borders, as an exported table does, so the page holds far more rule objects than the grid the editor redraws.
+function borderedTablePdf(): Uint8Array {
+ const rules: string[] = [];
+ const texts: string[] = [];
+ CELLS.forEach((row, r) => {
+ const y = TOP - (r + 1) * ROW_HEIGHT;
+ row.forEach((text, c) => {
+ const x = LEFT + c * COL_WIDTH;
+ rules.push(
+ `${x} ${y} 1 ${ROW_HEIGHT} re f`,
+ `${x} ${y} ${COL_WIDTH} 1 re f`,
+ `${x} ${y + ROW_HEIGHT} ${COL_WIDTH} 1 re f`,
+ `${x + COL_WIDTH} ${y} 1 ${ROW_HEIGHT} re f`,
+ );
+ texts.push(`BT /F1 9 Tf ${x + 4} ${y + 6} Td (${text}) Tj ET`);
+ });
+ });
+ const badge = `0.9 0.2 0.2 rg ${BADGE.x} ${BADGE.y} ${BADGE.width} ${BADGE.height} re f`;
+ return buildClassicPdf(
+ [
+ { num: 1, body: "<< /Type /Catalog /Pages 2 0 R >>" },
+ { 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 " +
+ "/Resources << /Font << /F1 5 0 R >> >> >>",
+ },
+ {
+ num: 4,
+ body: streamBody("", `${[...rules, ...texts, badge].join("\n")}\n`),
+ },
+ {
+ num: 5,
+ body: "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>",
+ },
+ ],
+ 1,
+ );
+}
+
+const opened: EditorDocument[] = [];
+
+beforeAll(async () => {
+ const wasm = await readFile(
+ createRequire(import.meta.url).resolve("@embedpdf/pdfium/pdfium.wasm"),
+ );
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async (url: string) =>
+ String(url).endsWith(".wasm")
+ ? new Response(wasm, {
+ headers: { "Content-Type": "application/wasm" },
+ })
+ : new Response(null, { status: 404 }),
+ ),
+ );
+});
+
+afterEach(() => {
+ for (const doc of opened.splice(0)) doc.dispose();
+});
+
+afterAll(() => vi.unstubAllGlobals());
+
+async function open(bytes: Uint8Array): Promise<EditorDocument> {
+ const doc = await EditorDocument.open(bytes);
+ opened.push(doc);
+ PdfiumTextReader.populate(doc, doc.page(0));
+ return doc;
+}
+
+async function saved(doc: EditorDocument): Promise<EditorDocument> {
+ return open(new Uint8Array(await (await exportToBlob(doc)).arrayBuffer()));
+}
+
+const texts = (doc: EditorDocument): string[] =>
+ doc
+ .page(0)
+ .runs.flatMap((run) => run.text.split("\n"))
+ .map((text) => text.trim())
+ .filter(Boolean)
+ .sort();
+
+function adoptTable(doc: EditorDocument): TableModel {
+ const page = doc.page(0);
+ const [table] = detectTables(
+ page.runs.map((run) => run.snapshot()),
+ 0,
+ {},
+ page.rules,
+ );
+ const model = adoptedTableModel(doc.module, page, table);
+ page.tables = [...page.tables, model];
+ return model;
+}
+
+function step(doc: EditorDocument, history: HistoryStack, cmd: Command): void {
+ history.execute(cmd, doc);
+ history.breakCoalescing();
+}
+
+function addFilledRow(
+ doc: EditorDocument,
+ history: HistoryStack,
+ model: TableModel,
+): void {
+ const row = model.rows;
+ step(
+ doc,
+ history,
+ new ModifyTableCommand({ tableId: model.id, op: "add-row", index: row }),
+ );
+ step(
+ doc,
+ history,
+ new FillTableCellCommand({
+ tableId: model.id,
+ row,
+ col: 0,
+ text: "NewCell",
+ }),
+ );
+}
+
+test("a text edit made before a table row was added can be undone, redone and saved", async () => {
+ const doc = await open(borderedTablePdf());
+ const original = texts(doc);
+ const item = doc.page(0).runs.find((run) => run.text.startsWith("Item"))!;
+ const typed = `${item.text}Zq`;
+ const history = new HistoryStack();
+
+ step(
+ doc,
+ history,
+ new EditTextCommand({ pageIndex: 0, runId: item.id, nextText: typed }),
+ );
+ const model = adoptTable(doc);
+ expect(model.ruled).toBe(true);
+ const objectsBeforeRow = doc.module.FPDFPage_CountObjects(
+ doc.page(0).pagePtr,
+ );
+ addFilledRow(doc, history, model);
+ expect(doc.module.FPDFPage_CountObjects(doc.page(0).pagePtr)).toBeLessThan(
+ objectsBeforeRow - CELLS.length,
+ );
+
+ history.undo(doc);
+ history.undo(doc);
+ history.undo(doc);
+
+ expect(history.size()).toEqual({ undo: 0, redo: 3 });
+ expect(texts(doc)).toEqual(original);
+ expect(texts(await saved(doc))).toEqual(original);
+
+ history.redo(doc);
+ history.redo(doc);
+ history.redo(doc);
+
+ const edited = texts(await saved(doc));
+ expect(edited).toContain(typed);
+ expect(edited).toContain("NewCell");
+ expect(texts(await saved(doc))).toEqual(edited);
+});
+
+test("a shape deleted before a table row was added comes back on undo", async () => {
+ const doc = await open(borderedTablePdf());
+ const page = doc.page(0);
+ const badge = page.shapes.find(
+ (shape) => Math.abs(shape.bounds.x - BADGE.x) < 1,
+ )!;
+ const history = new HistoryStack();
+
+ step(
+ doc,
+ history,
+ new DeleteShapeCommand({ pageIndex: 0, shapeId: badge.id }),
+ );
+ addFilledRow(doc, history, adoptTable(doc));
+ history.undo(doc);
+ history.undo(doc);
+ history.undo(doc);
+
+ expect(page.findShape(badge.id)).toBe(badge);
+ const reopened = await saved(doc);
+ expect(
+ reopened
+ .page(0)
+ .shapes.some((shape) => Math.abs(shape.bounds.x - BADGE.x) < 1),
+ ).toBe(true);
+});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/undoKernedEdit.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/undoKernedEdit.test.ts
new file mode 100644
index 0000000000..fb9ce66607
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/undoKernedEdit.test.ts
@@ -0,0 +1,221 @@
+// @vitest-environment node
+import { readFile } from "node:fs/promises";
+import { createRequire } from "node:module";
+import path from "node:path";
+import { afterAll, afterEach, beforeAll, expect, test, vi } from "vitest";
+import { EditTextCommand } from "@editor/tools/pdfTextEditor/commands/EditTextCommand";
+import { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
+import { PdfiumTextReader } from "@editor/tools/pdfTextEditor/pdfium/PdfiumTextReader";
+import { HistoryStack } from "@editor/tools/pdfTextEditor/store/HistoryStack";
+import { exportToBlob } from "@editor/tools/pdfTextEditor/util/exportPdf";
+import { rasterFirstPage } from "@editor/tools/pdfTextEditor/__tests__/pageRaster";
+
+const FIXTURES = path.join(import.meta.dirname, "../../../tests/test-fixtures");
+// Set by cairo with a TJ kern between most letter pairs.
+const KERNED_HEADING = "subset-truetype-heading.pdf";
+const HEADING = "Quarterly report heading";
+const SIZE = 600;
+
+const opened: EditorDocument[] = [];
+
+beforeAll(async () => {
+ const wasm = await readFile(
+ createRequire(import.meta.url).resolve("@embedpdf/pdfium/pdfium.wasm"),
+ );
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(
+ async () =>
+ new Response(wasm, {
+ headers: { "Content-Type": "application/wasm" },
+ }),
+ ),
+ );
+});
+
+afterEach(() => {
+ for (const doc of opened.splice(0)) doc.dispose();
+});
+
+afterAll(() => vi.unstubAllGlobals());
+
+async function open(source: string | Uint8Array): Promise<EditorDocument> {
+ const bytes =
+ typeof source === "string"
+ ? new Uint8Array(await readFile(path.join(FIXTURES, source)))
+ : source;
+ const doc = await EditorDocument.open(bytes);
+ opened.push(doc);
+ PdfiumTextReader.populate(doc, doc.page(0));
+ return doc;
+}
+
+interface Glyph {
+ char: string;
+ x: number;
+ y: number;
+}
+
+function glyphs(doc: EditorDocument): Glyph[] {
+ const m = doc.module;
+ const textPage = m.FPDFText_LoadPage(doc.page(0).pagePtr);
+ const at = m.pdfium.wasmExports.malloc(16);
+ try {
+ return Array.from({ length: m.FPDFText_CountChars(textPage) }, (_, i) => {
+ m.FPDFText_GetCharOrigin(textPage, i, at, at + 8);
+ return {
+ char: String.fromCodePoint(m.FPDFText_GetUnicode(textPage, i)),
+ x: m.pdfium.getValue(at, "double"),
+ y: m.pdfium.getValue(at + 8, "double"),
+ };
+ });
+ } finally {
+ m.pdfium.wasmExports.free(at);
+ m.FPDFText_ClosePage(textPage);
+ }
+}
+
+function differingBytes(a: Uint8Array, b: Uint8Array): number {
+ let count = 0;
+ for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) count++;
+ return count;
+}
+
+function furthestShiftPt(before: Glyph[], after: Glyph[]): number {
+ expect(after.map((g) => g.char).join("")).toBe(
+ before.map((g) => g.char).join(""),
+ );
+ return Math.max(
+ ...before.map((g, i) =>
+ Math.max(Math.abs(g.x - after[i].x), Math.abs(g.y - after[i].y)),
+ ),
+ );
+}
+
+async function expectAsUntouched(doc: EditorDocument, file: string) {
+ const untouched = await open(file);
+ expect(furthestShiftPt(glyphs(untouched), glyphs(doc))).toBeLessThan(0.01);
+ expect(
+ differingBytes(
+ rasterFirstPage(untouched, SIZE, SIZE),
+ rasterFirstPage(doc, SIZE, SIZE),
+ ),
+ ).toBe(0);
+}
+
+function edit(
+ doc: EditorDocument,
+ history: HistoryStack,
+ text: string,
+ steps: string[],
+) {
+ const run = doc.page(0).runs.find((r) => r.text === text)!;
+ for (const nextText of steps)
+ history.execute(
+ new EditTextCommand({ pageIndex: 0, runId: run.id, nextText }),
+ doc,
+ );
+ return run;
+}
+
+test.each([
+ { edit: "deleting a letter", steps: ["Quarterly reprt heading"] },
+ { edit: "typing into a word", steps: ["QuarZterly report heading"] },
+ {
+ edit: "typing two letters into a word",
+ steps: ["QuarZterly report heading", "QuarZbterly report heading"],
+ },
+ { edit: "replacing a letter", steps: ["Quarterly reXort heading"] },
+ {
+ edit: "several deletions and a typed letter",
+ steps: [
+ "Quarterly reprt heading",
+ "Quarterly rept heading",
+ "Quartrly rept heading",
+ "Quartrly rept headXing",
+ ],
+ },
+])(
+ "undoing $edit on a kerned heading puts every letter back where it was drawn",
+ async ({ steps }) => {
+ const doc = await open(KERNED_HEADING);
+ const history = new HistoryStack();
+ const run = edit(doc, history, HEADING, steps);
+
+ while (history.canUndo) history.undo(doc);
+
+ expect(run.text).toBe(HEADING);
+ await expectAsUntouched(doc, KERNED_HEADING);
+ },
+);
+
+test("redo after an exact undo draws the edit again, and undo puts it back again", async () => {
+ const doc = await open(KERNED_HEADING);
+ const history = new HistoryStack();
+ const run = edit(doc, history, HEADING, ["Quarterly reprt heading"]);
+ const edited = glyphs(doc);
+ const editedRaster = rasterFirstPage(doc, SIZE, SIZE);
+
+ history.undo(doc);
+ history.redo(doc);
+
+ expect(run.text).toBe("Quarterly reprt heading");
+ expect(furthestShiftPt(edited, glyphs(doc))).toBeLessThan(0.01);
+ expect(differingBytes(editedRaster, rasterFirstPage(doc, SIZE, SIZE))).toBe(
+ 0,
+ );
+
+ history.undo(doc);
+ await expectAsUntouched(doc, KERNED_HEADING);
+});
+
+test("saving after undoing a deleted letter writes the heading as the untouched file draws it", async () => {
+ const doc = await open(KERNED_HEADING);
+ const history = new HistoryStack();
+ edit(doc, history, HEADING, ["Quarterly reprt heading"]);
+ history.undo(doc);
+
+ const saved = await open(
+ new Uint8Array(await (await exportToBlob(doc)).arrayBuffer()),
+ );
+
+ expect(saved.page(0).runs.map((r) => r.text)).toEqual([HEADING]);
+ await expectAsUntouched(saved, KERNED_HEADING);
+});
+
+test.each([
+ "Large Palatino display line.",
+ "Small Times New Roman footnote text line.",
+])(
+ "undoing a deleted letter in the kerned cairo line %s is exact",
+ async (line) => {
+ const doc = await open("cairo-styles.pdf");
+ const history = new HistoryStack();
+ const run = edit(doc, history, line, [line.replace("e", "")]);
+
+ history.undo(doc);
+
+ expect(run.text).toBe(line);
+ await expectAsUntouched(doc, "cairo-styles.pdf");
+ },
+);
+
+test("undoing a deleted letter on a line of a kerned paragraph is exact", async () => {
+ const doc = await open("cairo-styles.pdf");
+ const run = doc.page(0).runs.find((r) => r.text.startsWith("Accents:"))!;
+ const original = run.text;
+ const history = new HistoryStack();
+ history.execute(
+ new EditTextCommand({
+ pageIndex: 0,
+ runId: run.id,
+ nextText: original.replace("naïve", "naïe"),
+ }),
+ doc,
+ );
+
+ history.undo(doc);
+
+ expect(run.text).toBe(original);
+ await expectAsUntouched(doc, "cairo-styles.pdf");
+});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/undoLineBreakBurst.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/undoLineBreakBurst.test.ts
new file mode 100644
index 0000000000..f7e422daca
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/undoLineBreakBurst.test.ts
@@ -0,0 +1,102 @@
+// @vitest-environment node
+import { readFile } from "node:fs/promises";
+import { createRequire } from "node:module";
+import path from "node:path";
+import {
+ afterAll,
+ afterEach,
+ beforeAll,
+ describe,
+ expect,
+ test,
+ vi,
+} from "vitest";
+import { EditTextCommand } from "@editor/tools/pdfTextEditor/commands/EditTextCommand";
+import { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
+import { HistoryStack } from "@editor/tools/pdfTextEditor/store/HistoryStack";
+import { PdfiumTextReader } from "@editor/tools/pdfTextEditor/pdfium/PdfiumTextReader";
+
+const SAMPLE = path.join(
+ import.meta.dirname,
+ "../../../tests/test-fixtures/mixed-style-sample.pdf",
+);
+const FPDF_PAGEOBJ_TEXT = 1;
+
+const opened: EditorDocument[] = [];
+
+beforeAll(async () => {
+ const wasm = await readFile(
+ createRequire(import.meta.url).resolve("@embedpdf/pdfium/pdfium.wasm"),
+ );
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async (url: string) =>
+ String(url).endsWith(".wasm")
+ ? new Response(wasm, {
+ headers: { "Content-Type": "application/wasm" },
+ })
+ : new Response(null, { status: 404 }),
+ ),
+ );
+});
+
+afterEach(() => {
+ for (const doc of opened.splice(0)) doc.dispose();
+});
+
+afterAll(() => vi.unstubAllGlobals());
+
+// Every text object on the page as "text@font", sorted.
+function drawn(doc: EditorDocument): string[] {
+ const m = doc.module;
+ const pagePtr = doc.page(0).pagePtr;
+ const textPage = m.FPDFText_LoadPage(pagePtr);
+ const text = m.pdfium.wasmExports.malloc(1024);
+ const name = m.pdfium.wasmExports.malloc(256);
+ const out: string[] = [];
+ try {
+ for (let i = 0; i < m.FPDFPage_CountObjects(pagePtr); i++) {
+ const obj = m.FPDFPage_GetObject(pagePtr, i);
+ if (m.FPDFPageObj_GetType(obj) !== FPDF_PAGEOBJ_TEXT) continue;
+ m.FPDFTextObj_GetText(obj, textPage, text, 512);
+ m.FPDFFont_GetBaseFontName(m.FPDFTextObj_GetFont(obj), name, 256);
+ out.push(
+ `${m.pdfium.UTF16ToString(text).trim()}@${m.pdfium.UTF8ToString(name)}`,
+ );
+ }
+ } finally {
+ m.FPDFText_ClosePage(textPage);
+ m.pdfium.wasmExports.free(text);
+ m.pdfium.wasmExports.free(name);
+ }
+ return out.sort();
+}
+
+describe("a line broken with Enter and then typed on", () => {
+ test("undoes to the very objects it started from, symbols and faces included", async () => {
+ const doc = await EditorDocument.open(
+ new Uint8Array(await readFile(SAMPLE)),
+ );
+ opened.push(doc);
+ PdfiumTextReader.populate(doc, doc.page(0));
+ const before = drawn(doc);
+ const runId = doc.page(0).runs.find((r) => r.text.includes("Plain"))!.id;
+ const history = new HistoryStack();
+ const type = (change: (text: string) => string) =>
+ history.execute(
+ new EditTextCommand({
+ pageIndex: 0,
+ runId,
+ nextText: change(doc.page(0).findRun(runId)!.text),
+ }),
+ doc,
+ );
+
+ type((text) => text.replace("italic ", "italic \n"));
+ type((text) => text.replace("\n and both", " Pk\n and both"));
+ type((text) => `${text} Pasted`);
+ history.undo(doc);
+
+ expect(drawn(doc)).toEqual(before);
+ });
+});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/ungroupDocumentFont.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/ungroupDocumentFont.test.ts
new file mode 100644
index 0000000000..40f26368e2
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/ungroupDocumentFont.test.ts
@@ -0,0 +1,59 @@
+import { describe, expect, it } from "vitest";
+import { UngroupParagraphCommand } from "@editor/tools/pdfTextEditor/commands/UngroupParagraphCommand";
+import { Page } from "@editor/tools/pdfTextEditor/model/Page";
+import { TextRun } from "@editor/tools/pdfTextEditor/model/TextRun";
+import type { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
+
+function paragraphInChangedFont(): Page {
+ const page = new Page({ index: 0, pagePtr: 1, width: 200, height: 200 });
+ const rep = new TextRun({
+ id: "p",
+ pageIndex: 0,
+ pdfiumObjPtr: 11,
+ bounds: { x: 10, y: 120, width: 100, height: 30 },
+ matrix: { a: 1, b: 0, c: 0, d: 1, e: 10, f: 140 },
+ text: "first\nsecond\nthird",
+ fontId: "device:Acme Sans",
+ fontSize: 10,
+ fill: { r: 0, g: 0, b: 0, a: 255 },
+ fontSubset: false,
+ });
+ rep.paragraphMemberPtrs = [11, 12, 13];
+ rep.paragraphMemberContainers = [1, 1, 1];
+ rep.paragraphMemberFs = [140, 128, 116];
+ rep.documentFont = { fontId: "pdf:7:Garamond", subset: true };
+ page.setRuns([rep]);
+ return page;
+}
+
+function fakeDoc(page: Page): EditorDocument {
+ return { module: {}, page: () => page } as unknown as EditorDocument;
+}
+
+describe("UngroupParagraphCommand document font", () => {
+ it("keeps the restore option on every line of a paragraph whose font was changed", () => {
+ const page = paragraphInChangedFont();
+ new UngroupParagraphCommand({ pageIndex: 0, runId: "p" }).apply(
+ fakeDoc(page),
+ );
+
+ expect(page.runs.map((r) => r.snapshot().documentFontId)).toEqual([
+ "pdf:7:Garamond",
+ "pdf:7:Garamond",
+ "pdf:7:Garamond",
+ ]);
+ expect(page.runs[2].documentFont?.subset).toBe(true);
+ });
+
+ it("leaves the paragraph restorable after the ungroup is undone", () => {
+ const page = paragraphInChangedFont();
+ const doc = fakeDoc(page);
+ const cmd = new UngroupParagraphCommand({ pageIndex: 0, runId: "p" });
+ cmd.apply(doc);
+ cmd.revert(doc);
+
+ expect(page.runs.map((r) => r.snapshot().documentFontId)).toEqual([
+ "pdf:7:Garamond",
+ ]);
+ });
+});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/widenRejoinsLines.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/widenRejoinsLines.test.ts
new file mode 100644
index 0000000000..25e34f41e5
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/widenRejoinsLines.test.ts
@@ -0,0 +1,209 @@
+// @vitest-environment node
+import { readFile } from "node:fs/promises";
+import { createRequire } from "node:module";
+import path from "node:path";
+import { afterAll, afterEach, beforeAll, expect, test, vi } from "vitest";
+import { EditTextCommand } from "@editor/tools/pdfTextEditor/commands/EditTextCommand";
+import { resizeRunCommand } from "@editor/tools/pdfTextEditor/commands/resizeRun";
+import { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
+import type { TextRun } from "@editor/tools/pdfTextEditor/model/TextRun";
+import { PdfiumTextReader } from "@editor/tools/pdfTextEditor/pdfium/PdfiumTextReader";
+import { HistoryStack } from "@editor/tools/pdfTextEditor/store/HistoryStack";
+import { exportToBlob } from "@editor/tools/pdfTextEditor/util/exportPdf";
+
+const FIXTURES = path.join(import.meta.dirname, "../../../tests/test-fixtures");
+const opened: EditorDocument[] = [];
+
+beforeAll(async () => {
+ const wasm = await readFile(
+ createRequire(import.meta.url).resolve("@embedpdf/pdfium/pdfium.wasm"),
+ );
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(
+ async () =>
+ new Response(wasm, { headers: { "Content-Type": "application/wasm" } }),
+ ),
+ );
+});
+
+afterEach(() => {
+ for (const doc of opened.splice(0)) doc.dispose();
+});
+
+afterAll(() => vi.unstubAllGlobals());
+
+async function open(source: string | Uint8Array, pageIndex = 0) {
+ const bytes =
+ typeof source === "string"
+ ? new Uint8Array(await readFile(path.join(FIXTURES, source)))
+ : source;
+ const doc = await EditorDocument.open(bytes);
+ opened.push(doc);
+ PdfiumTextReader.populate(doc, doc.page(pageIndex));
+ return doc;
+}
+
+function runStarting(doc: EditorDocument, start: string, pageIndex = 0) {
+ const run = doc
+ .page(pageIndex)
+ .runs.find((r) => r.text.trimStart().startsWith(start));
+ if (!run) throw new Error(`no run starting "${start}"`);
+ return run;
+}
+
+function resize(
+ doc: EditorDocument,
+ history: HistoryStack,
+ run: TextRun,
+ width: number,
+ pageIndex = 0,
+) {
+ const cmd = resizeRunCommand(doc, pageIndex, run.id, width);
+ if (cmd) history.execute(cmd, doc);
+}
+
+const lines = (run: TextRun) => run.text.split("\n").map((l) => l.trim());
+const words = (text: string) => text.replace(/\s+/g, " ").trim();
+const pageWidth = (doc: EditorDocument) => doc.page(0).display.cropWidth;
+
+function positions(doc: EditorDocument, run: TextRun): string {
+ const m = doc.module;
+ const buf = m.pdfium.wasmExports.malloc(16);
+ try {
+ return run.paragraphLeafPtrs
+ .map((ptr) => {
+ m.FPDFPageObj_GetBounds(ptr, buf, buf + 4, buf + 8, buf + 12);
+ return [0, 4, 8, 12]
+ .map((o) => m.pdfium.getValue(buf + o, "float").toFixed(2))
+ .join(",");
+ })
+ .join(" ");
+ } finally {
+ m.pdfium.wasmExports.free(buf);
+ }
+}
+
+test("narrowing a paragraph and widening it back restores its document lines", async () => {
+ const doc = await open("paragraph-sample.pdf");
+ const history = new HistoryStack();
+ const run = runStarting(doc, "First line of the body");
+ const original = run.text;
+ const width = run.bounds.width;
+
+ resize(doc, history, run, width * 0.6);
+ expect(lines(run).length).toBeGreaterThan(4);
+ resize(doc, history, run, width);
+
+ expect(run.text).toBe(original);
+});
+
+test("widening to the page edge pulls words up across the margin's breaks but not across a line the author ended, and undo restores it", async () => {
+ const doc = await open("paragraph-sample.pdf");
+ const history = new HistoryStack();
+ const run = runStarting(doc, "First line of the body");
+ const original = run.text;
+ const bounds = { ...run.bounds };
+ const placed = positions(doc, run);
+
+ resize(doc, history, run, pageWidth(doc) - run.bounds.x - 10);
+ const widened = run.text;
+
+ expect(lines(run)[0]).toBe(
+ "First line of the body paragraph that we want grouped together. Second",
+ );
+ expect(words(widened)).toBe(words(original));
+ expect(lines(run).at(-1)).toBe(
+ "Fourth line wraps the paragraph at the bottom of the column.",
+ );
+
+ history.undo(doc);
+ expect(run.text).toBe(original);
+ expect(run.bounds).toEqual(bounds);
+ expect(positions(doc, run)).toBe(placed);
+
+ history.redo(doc);
+ expect(run.text).toBe(widened);
+
+ const saved = new Uint8Array(await (await exportToBlob(doc)).arrayBuffer());
+ const reopened = await open(saved);
+ expect(lines(runStarting(reopened, "First line of the body"))).toEqual(
+ lines(run),
+ );
+});
+
+test("a line the user ended with Enter stays ended when the box widens", async () => {
+ const doc = await open("paragraph-sample.pdf");
+ const history = new HistoryStack();
+ const run = runStarting(doc, "First line of the body");
+ const typed = run.text.replace("Second line", "Second\nline");
+ expect(typed).not.toBe(run.text);
+ history.execute(
+ new EditTextCommand({ pageIndex: 0, runId: run.id, nextText: typed }),
+ doc,
+ );
+
+ resize(doc, history, run, pageWidth(doc) - run.bounds.x - 10);
+
+ expect(lines(run).length).toBeLessThan(typed.split("\n").length);
+ expect(lines(run).some((l) => l.endsWith("Second"))).toBe(true);
+ expect(lines(run).some((l) => l.startsWith("line continues"))).toBe(true);
+});
+
+test("widening justified copy joins the lines it was set to", async () => {
+ const doc = await open("justified-sample.pdf");
+ const history = new HistoryStack();
+ const run = runStarting(doc, "Justified copy");
+ const original = run.text;
+
+ resize(doc, history, run, run.bounds.width * 2);
+
+ expect(lines(run).length).toBeLessThan(original.split("\n").length);
+ expect(words(run.text)).toBe(words(original));
+});
+
+test("widening one paragraph never pulls in the next, and keeps its hyphenated breaks", async () => {
+ const doc = await open("mushroom-life.pdf");
+ const history = new HistoryStack();
+ const run = runStarting(doc, "Mushrooms represent");
+ const next = runStarting(doc, "Spore Stage");
+ const nextText = next.text;
+ const nextTop = next.bounds.y + next.bounds.height;
+ const lineCount = lines(run).length;
+
+ resize(doc, history, run, run.bounds.width * 1.4);
+
+ expect(lines(run).length).toBeLessThan(lineCount);
+ expect(next.text).toBe(nextText);
+ expect(run.text).not.toContain("Spore Stage");
+ expect(run.text).toContain("posi-\ntion");
+ expect(next.bounds.y + next.bounds.height).toBeCloseTo(nextTop, 3);
+});
+
+test("short lines of a list stay apart however wide the box gets", async () => {
+ const doc = await open("cairo-styles.pdf");
+ const history = new HistoryStack();
+ const run = runStarting(doc, "First bullet item");
+ const original = run.text;
+
+ resize(doc, history, run, pageWidth(doc) - run.bounds.x - 10);
+
+ expect(run.text).toBe(original);
+});
+
+test("narrowing the heading wraps it and pushes the body down, and widening it back makes it one line and lets the body back up", async () => {
+ const doc = await open("paragraph-sample.pdf");
+ const history = new HistoryStack();
+ const run = runStarting(doc, "Heading in a bigger size");
+ const body = runStarting(doc, "First line of the body");
+ const bodyY = body.bounds.y;
+ const width = run.bounds.width;
+
+ resize(doc, history, run, width * 0.5);
+ expect(lines(run).length).toBeGreaterThan(1);
+ expect(body.bounds.y).toBeLessThan(bodyY - 1);
+ resize(doc, history, run, width + 2);
+
+ expect(run.text).toBe("Heading in a bigger size");
+ expect(body.bounds.y).toBeCloseTo(bodyY, 3);
+});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/wrapCaret.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/wrapCaret.test.ts
new file mode 100644
index 0000000000..76f9b0fdb7
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/wrapCaret.test.ts
@@ -0,0 +1,25 @@
+import { describe, expect, it } from "vitest";
+import { offsetAcrossRewrap } from "@editor/tools/pdfTextEditor/util/wrapCaret";
+
+describe("offsetAcrossRewrap", () => {
+ it("keeps the caret after the same letter when a space becomes a line break", () => {
+ expect(offsetAcrossRewrap("one two three", 13, "one two\nthree")).toBe(13);
+ expect(offsetAcrossRewrap("one two three", 5, "one\ntwo three")).toBe(5);
+ });
+
+ it("keeps the caret after a space it had just passed", () => {
+ expect(offsetAcrossRewrap("one two ", 8, "one\ntwo ")).toBe(8);
+ });
+
+ it("follows the letters when the rewrap drops a doubled space", () => {
+ expect(offsetAcrossRewrap("one two", 8, "one\ntwo")).toBe(7);
+ });
+
+ it("puts a caret before the first letter at the start", () => {
+ expect(offsetAcrossRewrap("one two", 0, "one\ntwo")).toBe(0);
+ });
+
+ it("stops at the end of shorter text", () => {
+ expect(offsetAcrossRewrap("one two", 7, "one")).toBe(3);
+ });
+});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/__tests__/wrapPushesBelow.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/wrapPushesBelow.test.ts
new file mode 100644
index 0000000000..99f57b2ea4
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/__tests__/wrapPushesBelow.test.ts
@@ -0,0 +1,257 @@
+// @vitest-environment node
+import { readFile } from "node:fs/promises";
+import { createRequire } from "node:module";
+import path from "node:path";
+import { afterAll, afterEach, beforeAll, expect, test, vi } from "vitest";
+import { EditTextCommand } from "@editor/tools/pdfTextEditor/commands/EditTextCommand";
+import { ReflowWrapCommand } from "@editor/tools/pdfTextEditor/commands/ReflowWrapCommand";
+import {
+ collectMemberPtrs,
+ measureObjBoundsPt,
+} from "@editor/tools/pdfTextEditor/commands/editTextHelpers";
+import { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
+import { PdfiumTextReader } from "@editor/tools/pdfTextEditor/pdfium/PdfiumTextReader";
+import { HistoryStack } from "@editor/tools/pdfTextEditor/store/HistoryStack";
+
+const TABLE_BELOW = path.join(
+ import.meta.dirname,
+ "../../../tests/test-fixtures/sample.pdf",
+);
+const SAMPLE = path.join(
+ import.meta.dirname,
+ "../../../tests/test-fixtures/paragraph-sample.pdf",
+);
+const HEADING = "Heading in a bigger size";
+const LONG = `${HEADING} that the user keeps typing well past the right edge of the page, on and on, until it needs three more lines`;
+
+const opened: EditorDocument[] = [];
+
+beforeAll(async () => {
+ const wasm = await readFile(
+ createRequire(import.meta.url).resolve("@embedpdf/pdfium/pdfium.wasm"),
+ );
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(
+ async () =>
+ new Response(wasm, { headers: { "Content-Type": "application/wasm" } }),
+ ),
+ );
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ for (const doc of opened.splice(0)) doc.dispose();
+});
+
+afterAll(() => vi.unstubAllGlobals());
+
+async function open() {
+ const doc = await EditorDocument.open(new Uint8Array(await readFile(SAMPLE)));
+ opened.push(doc);
+ const page = doc.page(0);
+ PdfiumTextReader.populate(doc, page);
+ const heading = page.runs.find((r) => r.text === HEADING)!;
+ const body = page.runs.find((r) => r !== heading)!;
+ const bodyInk = () =>
+ measureObjBoundsPt(doc.module, collectMemberPtrs(body))!.top;
+ const pageRight = page.display.cropLeft + page.display.cropWidth;
+ return { doc, heading, body, bodyInk, pageRight };
+}
+
+function typeAndWrap(
+ doc: EditorDocument,
+ history: HistoryStack,
+ runId: string,
+ maxWidthPt: number,
+) {
+ history.execute(
+ new EditTextCommand({ pageIndex: 0, runId, nextText: LONG }),
+ doc,
+ );
+ history.execute(
+ new ReflowWrapCommand({ pageIndex: 0, runId, maxWidthPt }),
+ doc,
+ );
+}
+
+test("lines a wrap adds move the text below down by their height", async () => {
+ const { doc, heading, body, bodyInk, pageRight } = await open();
+ const startTop = bodyInk();
+ const bodyY = body.bounds.y;
+
+ typeAndWrap(
+ doc,
+ new HistoryStack(),
+ heading.id,
+ pageRight - heading.bounds.x,
+ );
+
+ const added = heading.text.split("\n").length - 1;
+ expect(added).toBeGreaterThan(0);
+ const drop = added * heading.paragraphLineHeight;
+ expect(body.bounds.y).toBeCloseTo(bodyY - drop, 3);
+ expect(bodyInk()).toBeCloseTo(startTop - drop, 3);
+ expect(bodyInk()).toBeLessThan(heading.bounds.y);
+ expect(heading.bounds.x + heading.bounds.width).toBeLessThanOrEqual(
+ pageRight,
+ );
+});
+
+test("undo puts the text below back exactly and redo moves it once", async () => {
+ const { doc, heading, body, bodyInk, pageRight } = await open();
+ const startTop = bodyInk();
+ const bodyY = body.bounds.y;
+ const history = new HistoryStack();
+
+ typeAndWrap(doc, history, heading.id, pageRight - heading.bounds.x);
+ expect(history.size().undo).toBe(1);
+ const pushedTop = bodyInk();
+ expect(pushedTop).toBeLessThan(startTop - 10);
+
+ history.undo(doc);
+ expect(heading.text).toBe(HEADING);
+ expect(bodyInk()).toBeCloseTo(startTop, 3);
+ expect(body.bounds.y).toBeCloseTo(bodyY, 3);
+
+ history.redo(doc);
+ expect(bodyInk()).toBeCloseTo(pushedTop, 3);
+ history.undo(doc);
+ history.redo(doc);
+ expect(bodyInk()).toBeCloseTo(pushedTop, 3);
+});
+
+test("deleting the wrapped words brings the text below back up", async () => {
+ const { doc, heading, bodyInk, pageRight } = await open();
+ const startTop = bodyInk();
+ const history = new HistoryStack();
+
+ typeAndWrap(doc, history, heading.id, pageRight - heading.bounds.x);
+ expect(bodyInk()).toBeLessThan(startTop - 10);
+ history.breakCoalescing();
+ history.execute(
+ new EditTextCommand({ pageIndex: 0, runId: heading.id, nextText: HEADING }),
+ doc,
+ );
+
+ expect(bodyInk()).toBeCloseTo(startTop, 3);
+});
+
+test("typing on after a wrap and wrapping again stays one undo step that puts everything back", async () => {
+ const { doc, heading, body, bodyInk, pageRight } = await open();
+ const startTop = bodyInk();
+ const bodyY = body.bounds.y;
+ const history = new HistoryStack();
+ const width = pageRight - heading.bounds.x;
+
+ typeAndWrap(doc, history, heading.id, width);
+ const firstLines = heading.text.split("\n").length;
+ const firstTop = bodyInk();
+ history.execute(
+ new EditTextCommand({
+ pageIndex: 0,
+ runId: heading.id,
+ nextText: `${heading.text} and then a pause before typing a good deal more`,
+ }),
+ doc,
+ );
+ history.execute(
+ new ReflowWrapCommand({
+ pageIndex: 0,
+ runId: heading.id,
+ maxWidthPt: width,
+ }),
+ doc,
+ );
+ const added = heading.text.split("\n").length - firstLines;
+ expect(added).toBeGreaterThan(0);
+ expect(bodyInk()).toBeLessThanOrEqual(firstTop);
+ expect(bodyInk()).toBeLessThan(heading.bounds.y);
+ expect(history.size().undo).toBe(1);
+ const pushedTop = bodyInk();
+ const wrappedText = heading.text;
+
+ history.undo(doc);
+ expect(heading.text).toBe(HEADING);
+ expect(bodyInk()).toBeCloseTo(startTop, 3);
+ expect(body.bounds.y).toBeCloseTo(bodyY, 3);
+
+ history.redo(doc);
+ expect(heading.text).toBe(wrappedText);
+ expect(bodyInk()).toBeCloseTo(pushedTop, 3);
+});
+
+async function openTableBelow() {
+ const doc = await EditorDocument.open(
+ new Uint8Array(await readFile(TABLE_BELOW)),
+ );
+ opened.push(doc);
+ const page = doc.page(0);
+ PdfiumTextReader.populate(doc, page);
+ const line = page.runs.find((r) => r.text.startsWith("Test document"))!;
+ const width = page.display.cropLeft + page.display.cropWidth - line.bounds.x;
+ return { doc, page, line, width };
+}
+
+const PAST_EDGE =
+ "Test document for word documents and this sentence keeps going far beyond the right edge of the page so that it has to wrap onto new lines";
+
+test.each([
+ ["refuses", true],
+ ["still wraps when not asked to keep clear", false],
+])(
+ "a wrap whose new line would land on a table drawn below %s",
+ async (_case, keepClearBelow) => {
+ const { doc, page, line, width } = await openTableBelow();
+ const history = new HistoryStack();
+ const others = page.runs
+ .filter((r) => r !== line)
+ .map((r) => ({ ...r.bounds }));
+ history.execute(
+ new EditTextCommand({
+ pageIndex: 0,
+ runId: line.id,
+ nextText: PAST_EDGE,
+ }),
+ doc,
+ );
+ const reflow = new ReflowWrapCommand({
+ pageIndex: 0,
+ runId: line.id,
+ maxWidthPt: width,
+ keepClearBelow,
+ });
+ history.execute(reflow, doc);
+
+ expect(reflow.refusedForSpaceBelow).toBe(keepClearBelow);
+ expect(line.text.includes("\n")).toBe(!keepClearBelow);
+ expect(page.runs.filter((r) => r !== line).map((r) => r.bounds)).toEqual(
+ others,
+ );
+ history.undo(doc);
+ expect(line.text).not.toBe(PAST_EDGE);
+ history.redo(doc);
+ expect(reflow.refusedForSpaceBelow).toBe(keepClearBelow);
+ expect(line.text.includes("\n")).toBe(!keepClearBelow);
+ },
+);
+
+test("a wrap with clear space below is not refused", async () => {
+ const { doc, heading, bodyInk, pageRight } = await open();
+ const startTop = bodyInk();
+ const history = new HistoryStack();
+ history.execute(
+ new EditTextCommand({ pageIndex: 0, runId: heading.id, nextText: LONG }),
+ doc,
+ );
+ const reflow = new ReflowWrapCommand({
+ pageIndex: 0,
+ runId: heading.id,
+ maxWidthPt: pageRight - heading.bounds.x,
+ keepClearBelow: true,
+ });
+ history.execute(reflow, doc);
+ expect(reflow.refusedForSpaceBelow).toBe(false);
+ expect(heading.text.includes("\n")).toBe(true);
+ expect(bodyInk()).toBeLessThan(startTop - 10);
+});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/charcode/CmapResolver.ts b/frontend/src/editor/core/tools/pdfTextEditor/charcode/CmapResolver.ts
index 65694f70bd..57cd62d575 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/charcode/CmapResolver.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/charcode/CmapResolver.ts
@@ -1,3 +1,4 @@
+import type { WrappedPdfiumModule } from "@embedpdf/pdfium";
import type {
CharcodeResolver,
CharcodeResolveResult,
@@ -12,6 +13,7 @@ import {
SCRATCH,
scratchPtr,
} from "@editor/tools/pdfTextEditor/util/wasmScratch";
+import { clearOnDocumentClose } from "@editor/tools/pdfTextEditor/pdfium/pointerCaches";
/** Strategy 1: parse the embedded font's cmap table. */
@@ -86,7 +88,7 @@ function getOrBuildCmap(
/** Build + cache a font's cmap. */
export function primeFontGlyphMap(
font: number,
- module: import("@embedpdf/pdfium").WrappedPdfiumModule,
+ module: WrappedPdfiumModule,
): void {
if (!font) return;
getOrBuildCmap(font, { module, pagePtr: 0, docPtr: 0 });
@@ -127,10 +129,7 @@ function buildCmap(
}
/** Copy a font's embedded program bytes out of the WASM heap (null = none). */
-function readFontData(
- font: number,
- m: import("@embedpdf/pdfium").WrappedPdfiumModule,
-): Uint8Array | null {
+function readFontData(font: number, m: WrappedPdfiumModule): Uint8Array | null {
const fontMod = m as unknown as FontDataModule;
if (!fontMod.FPDFFont_GetFontData) return null;
@@ -327,6 +326,7 @@ export function resetCmapCache(): void {
cmapCache.clear();
fontShaCache.clear();
}
+clearOnDocumentClose(resetCmapCache);
/** Test-only alias for {@link resetCmapCache}. */
export function _clearCmapCacheForTests(): void {
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/charcode/ContentStreamResolver.ts b/frontend/src/editor/core/tools/pdfTextEditor/charcode/ContentStreamResolver.ts
index 0bbc8e8b0d..959e4ea096 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/charcode/ContentStreamResolver.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/charcode/ContentStreamResolver.ts
@@ -4,6 +4,7 @@ import type {
CharcodeResolveResult,
ResolverContext,
} from "@editor/tools/pdfTextEditor/charcode/CharcodeStrategy";
+import { clearOnDocumentClose } from "@editor/tools/pdfTextEditor/pdfium/pointerCaches";
// Strategy 2: scrape Unicode→charcode mappings by walking the page's existing
// text via PDFium's text page API.
@@ -14,6 +15,7 @@ interface TextPageModule {
FPDFText_CountChars?: (textPage: number) => number;
FPDFText_GetUnicode?: (textPage: number, idx: number) => number;
FPDFText_GetTextObject?: (textPage: number, idx: number) => number;
+ FPDFText_IsGenerated?: (textPage: number, idx: number) => number;
}
interface FontReadModule {
@@ -95,6 +97,8 @@ function buildPageMap(ctx: ResolverContext): Map<number, Map<number, number>> {
// in a given font gets the next sequential CID starting at 1.
const perFontNext = new Map<number, number>();
for (let i = 0; i < count; i++) {
+ // A space the text page inferred from a gap is given the object before it, whose font drew no glyph for it.
+ if (tpMod.FPDFText_IsGenerated?.(textPage, i) === 1) continue;
const unicode = drawnCodePoint(tpMod.FPDFText_GetUnicode(textPage, i));
if (!unicode) continue;
const obj = tpMod.FPDFText_GetTextObject(textPage, i);
@@ -133,6 +137,7 @@ function buildPageMap(ctx: ResolverContext): Map<number, Map<number, number>> {
export function resetContentStreamCache(): void {
perPageCache.clear();
}
+clearOnDocumentClose(resetContentStreamCache);
/** Test-only alias for {@link resetContentStreamCache}. */
export function _clearContentStreamCacheForTests(): void {
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/charcode/FontHelpers.ts b/frontend/src/editor/core/tools/pdfTextEditor/charcode/FontHelpers.ts
index 41d9b9de36..9287e8b7e8 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/charcode/FontHelpers.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/charcode/FontHelpers.ts
@@ -4,6 +4,7 @@ import {
SCRATCH,
scratchPtr,
} from "@editor/tools/pdfTextEditor/util/wasmScratch";
+import { clearOnDocumentClose } from "@editor/tools/pdfTextEditor/pdfium/pointerCaches";
/**
* Client-side font helpers for the charcode emit path.
@@ -269,3 +270,4 @@ export function resetFontHelperCaches(): void {
reusableFontCache.clear();
fontNameCache.clear();
}
+clearOnDocumentClose(resetFontHelperCaches);
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/charcode/fontGlyphs.ts b/frontend/src/editor/core/tools/pdfTextEditor/charcode/fontGlyphs.ts
new file mode 100644
index 0000000000..8d938523a9
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/charcode/fontGlyphs.ts
@@ -0,0 +1,226 @@
+/**
+ * What a font's own program draws for a character, which its encoding cannot
+ * say: a subset keeps the code for a letter it dropped the glyph of, and can
+ * hold two letters only as one ligature glyph.
+ */
+import type { WrappedPdfiumModule } from "@embedpdf/pdfium";
+import { setCharcodesOn } from "@editor/tools/pdfTextEditor/charcode/charcodeRegistry";
+import { drawnCodePoint } from "@editor/tools/pdfTextEditor/pdfium/lineEndHyphen";
+import {
+ SCRATCH,
+ scratchPtr,
+} from "@editor/tools/pdfTextEditor/util/wasmScratch";
+
+/**
+ * "outline": the font draws the character with a glyph of its own.
+ * "box": it draws the glyph it shows for every character it lacks.
+ * "none": PDFium reads no outline, as for every character of a Type 3 font.
+ */
+type Glyph = "outline" | "box" | "none";
+
+// Characters a subset rarely holds. Two of them drawn with one outline are both the font's missing-glyph box: no font draws two of these alike.
+const RARE_CHARACTERS =
+ "^`|~{}\u00a4\u00ac\u00b1\u00f7\u00de\u00f0\u00fe\u0192";
+const PROBE_FONT_SIZE = 12;
+const SINGLE_BYTE_CODES = 255;
+const SCRATCH_GRID = 16;
+const SCRATCH_STEP_PT = 30;
+
+const outlines = new Map<number, Map<string, string | null>>();
+const missingOutlines = new Map<number, string | null>();
+const codeTexts = new Map<number, Map<string, number>>();
+
+/** Font pointers are reused across documents, so every document starts empty. */
+export function resetFontGlyphs(): void {
+ outlines.clear();
+ missingOutlines.clear();
+ codeTexts.clear();
+}
+
+function outlineOf(
+ m: WrappedPdfiumModule,
+ font: number,
+ ch: string,
+): string | null {
+ let perFont = outlines.get(font);
+ if (!perFont) {
+ perFont = new Map();
+ outlines.set(font, perFont);
+ }
+ const known = perFont.get(ch);
+ if (known !== undefined) return known;
+ let outline: string | null = null;
+ try {
+ outline = readOutline(m, font, ch);
+ } catch {
+ outline = null;
+ }
+ perFont.set(ch, outline);
+ return outline;
+}
+
+function readOutline(
+ m: WrappedPdfiumModule,
+ font: number,
+ ch: string,
+): string | null {
+ const path = m.FPDFFont_GetGlyphPath(
+ font,
+ ch.codePointAt(0)!,
+ PROBE_FONT_SIZE,
+ );
+ if (!path) return null;
+ const count = m.FPDFGlyphPath_CountGlyphSegments(path);
+ const point = scratchPtr(m, SCRATCH.glyphPoint, 8);
+ const parts: string[] = [];
+ for (let i = 0; i < count; i++) {
+ const segment = m.FPDFGlyphPath_GetGlyphPathSegment(path, i);
+ if (!m.FPDFPathSegment_GetPoint(segment, point, point + 4)) return null;
+ parts.push(
+ `${m.FPDFPathSegment_GetType(segment)} ${m.pdfium.getValue(point, "float").toFixed(4)} ${m.pdfium.getValue(point + 4, "float").toFixed(4)}`,
+ );
+ }
+ return parts.join(";");
+}
+
+function missingOutlineOf(m: WrappedPdfiumModule, font: number): string | null {
+ const known = missingOutlines.get(font);
+ if (known !== undefined) return known;
+ const seen = new Set<string>();
+ let missing: string | null = null;
+ for (const ch of RARE_CHARACTERS) {
+ const outline = outlineOf(m, font, ch);
+ if (!outline) continue;
+ if (seen.has(outline)) {
+ missing = outline;
+ break;
+ }
+ seen.add(outline);
+ }
+ missingOutlines.set(font, missing);
+ return missing;
+}
+
+function glyphOf(m: WrappedPdfiumModule, font: number, ch: string): Glyph {
+ const outline = outlineOf(m, font, ch);
+ if (outline === null) return "none";
+ return outline === missingOutlineOf(m, font) ? "box" : "outline";
+}
+
+/**
+ * The letters of `text` that `font` has no glyph of their own for: each is drawn as
+ * the font's missing-glyph box, or has no outline where another letter of `text` has
+ * one, which a subset font draws blank. A font PDFium reads no outline from at all is
+ * not judged, so none of its letters are returned.
+ */
+export function lettersWithoutGlyph(
+ m: WrappedPdfiumModule,
+ font: number,
+ text: string,
+): string[] {
+ if (!font) return [];
+ // Control and private-use codes reach a glyph by the font's own code, never by Unicode.
+ const letters = [...new Set(text.replace(/[\s\p{C}]+/gu, ""))];
+ const glyphs = letters.map((ch) => glyphOf(m, font, ch));
+ const readable = glyphs.includes("outline");
+ return letters.filter(
+ (_, i) => glyphs[i] === "box" || (readable && glyphs[i] === "none"),
+ );
+}
+
+/**
+ * The text each single-byte code of `font` reads as, lowest code first. Each
+ * code is drawn on the page as an object of its own, read back through one
+ * text page, and taken off again.
+ */
+function codeTextsOf(
+ m: WrappedPdfiumModule,
+ docPtr: number,
+ pagePtr: number,
+ font: number,
+): Map<string, number> {
+ const known = codeTexts.get(font);
+ if (known) return known;
+ const drawn = new Map<number, { code: number; text: string }>();
+ for (let c = 1; c <= SINGLE_BYTE_CODES; c++) {
+ const ptr = m.FPDFPageObj_CreateTextObj(docPtr, font, PROBE_FONT_SIZE);
+ if (!ptr) continue;
+ if (!setCharcodesOn(m, ptr, [c])) {
+ m.FPDFPageObj_Destroy(ptr);
+ continue;
+ }
+ // Apart, so the text page reads each as a line of its own and not as one drawn twice.
+ m.FPDFPageObj_Transform(
+ ptr,
+ 1,
+ 0,
+ 0,
+ 1,
+ (c % SCRATCH_GRID) * SCRATCH_STEP_PT,
+ Math.floor(c / SCRATCH_GRID) * SCRATCH_STEP_PT,
+ );
+ m.FPDFPage_InsertObject(pagePtr, ptr);
+ drawn.set(ptr, { code: c, text: "" });
+ }
+ const textPage = m.FPDFText_LoadPage(pagePtr);
+ try {
+ const count = textPage ? m.FPDFText_CountChars(textPage) : 0;
+ for (let i = 0; i < count; i++) {
+ const entry = drawn.get(m.FPDFText_GetTextObject(textPage, i));
+ if (!entry || m.FPDFText_IsGenerated(textPage, i) === 1) continue;
+ const unicode = drawnCodePoint(m.FPDFText_GetUnicode(textPage, i));
+ if (unicode) entry.text += String.fromCodePoint(unicode);
+ }
+ } finally {
+ if (textPage) m.FPDFText_ClosePage(textPage);
+ for (const ptr of drawn.keys()) {
+ m.FPDFPage_RemoveObject(pagePtr, ptr);
+ m.FPDFPageObj_Destroy(ptr);
+ }
+ }
+ const codes = new Map<string, number>();
+ for (const { code: c, text } of drawn.values())
+ if (text && !codes.has(text)) codes.set(text, c);
+ codeTexts.set(font, codes);
+ return codes;
+}
+
+/**
+ * The codes that draw `text` in `font` where FPDFText_SetText would draw a
+ * missing-glyph box or nothing: it encodes one character at a time, and the
+ * font holds some of them only inside a ligature. Null when every letter of
+ * `text` has a glyph of its own, or when the font's single-byte codes cannot
+ * draw all of it.
+ */
+export function ligatureCodes(
+ m: WrappedPdfiumModule,
+ docPtr: number,
+ pagePtr: number,
+ font: number,
+ text: string,
+): number[] | null {
+ if (!font || !docPtr || !pagePtr || [...text].length < 2) return null;
+ try {
+ const lacking = new Set(lettersWithoutGlyph(m, font, text));
+ if (lacking.size === 0) return null;
+ const lacks = (drawn: string) => [...drawn].some((ch) => lacking.has(ch));
+ const codes = codeTextsOf(m, docPtr, pagePtr, font);
+ const ligatures = [...codes.keys()]
+ .filter((drawn) => [...drawn].length > 1)
+ .sort((a, b) => b.length - a.length);
+ const out: number[] = [];
+ for (let at = 0; at < text.length;) {
+ const ligature = ligatures.find(
+ (drawn) => text.startsWith(drawn, at) && lacks(drawn),
+ );
+ const piece = ligature ?? String.fromCodePoint(text.codePointAt(at)!);
+ const code = codes.get(piece);
+ if (code === undefined || (!ligature && lacks(piece))) return null;
+ out.push(code);
+ at += piece.length;
+ }
+ return out;
+ } catch {
+ return null;
+ }
+}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/commands/AlignParagraphLinesCommand.ts b/frontend/src/editor/core/tools/pdfTextEditor/commands/AlignParagraphLinesCommand.ts
index 83e8cda342..93c2ac7862 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/commands/AlignParagraphLinesCommand.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/commands/AlignParagraphLinesCommand.ts
@@ -1,3 +1,6 @@
+import type { WrappedPdfiumModule } from "@embedpdf/pdfium";
+import { liftRunToPage } from "@editor/tools/pdfTextEditor/commands/liftFromForm";
+import { refuseRedrawOfReadOnlyText } from "@editor/tools/pdfTextEditor/commands/readOnlyText";
import type { Command } from "@editor/tools/pdfTextEditor/commands/Command";
import type { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
import type { TextRun } from "@editor/tools/pdfTextEditor/model/TextRun";
@@ -47,6 +50,8 @@ export class AlignParagraphLinesCommand implements Command {
const page = doc.page(this.pageIndex);
const run = page.findRun(this.runId);
if (!run || !AlignParagraphLinesCommand.canAlign(run)) return;
+ refuseRedrawOfReadOnlyText(run);
+ liftRunToPage(doc, page, run);
// Paragraph-wide left/right edge across every line.
const extents = run.paragraphLineSlots.map((_, i) =>
@@ -112,7 +117,7 @@ export class AlignParagraphLinesCommand implements Command {
/** Translate one line's glyph objects + its model bounds by dx. */
private shiftLine(
- m: import("@embedpdf/pdfium").WrappedPdfiumModule,
+ m: WrappedPdfiumModule,
run: TextRun,
i: number,
dx: number,
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/commands/ChangeZOrderCommand.ts b/frontend/src/editor/core/tools/pdfTextEditor/commands/ChangeZOrderCommand.ts
index edc59fe310..cc810ef10c 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/commands/ChangeZOrderCommand.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/commands/ChangeZOrderCommand.ts
@@ -1,5 +1,10 @@
+import type { Page } from "@editor/tools/pdfTextEditor/model/Page";
import type { Command } from "@editor/tools/pdfTextEditor/commands/Command";
import type { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
+import {
+ indexedInsertOf,
+ insertPageObjectAt,
+} from "@editor/tools/pdfTextEditor/util/insertPageObject";
import { collectMemberPtrs } from "@editor/tools/pdfTextEditor/commands/editTextHelpers";
export type ZOrderMode =
@@ -8,14 +13,6 @@ export type ZOrderMode =
| "forward" // swap with the object directly above it
| "backward"; // swap with the object directly below it
-interface InsertAtModule {
- FPDFPage_InsertObjectAtIndex?: (
- page: number,
- obj: number,
- idx: number,
- ) => boolean;
-}
-
/** One warning per session, not one per apply() - a drag can fire dozens. */
let warnedMissingInsertAt = false;
@@ -45,8 +42,7 @@ export class ChangeZOrderCommand implements Command {
apply(doc: EditorDocument): void {
const page = doc.page(this.pageIndex);
const m = doc.module;
- const ext = m as unknown as InsertAtModule;
- if (!ext.FPDFPage_InsertObjectAtIndex) {
+ if (!indexedInsertOf(m)) {
if (typeof console !== "undefined" && !warnedMissingInsertAt) {
warnedMissingInsertAt = true;
console.warn(
@@ -98,7 +94,7 @@ export class ChangeZOrderCommand implements Command {
m.FPDFPage_RemoveObject(page.pagePtr, ptr);
}
located.forEach(({ ptr }, j) => {
- ext.FPDFPage_InsertObjectAtIndex!(page.pagePtr, ptr, insertAt + j);
+ insertPageObjectAt(m, page.pagePtr, ptr, insertAt + j);
});
// markDirty bumps the revision so PageView re-renders the bitmap.
page.markDirty();
@@ -109,23 +105,20 @@ export class ChangeZOrderCommand implements Command {
if (this.memberPrev.length === 0) return;
const page = doc.page(this.pageIndex);
const m = doc.module;
- const ext = m as unknown as InsertAtModule;
- if (!ext.FPDFPage_InsertObjectAtIndex) return;
+ if (!indexedInsertOf(m)) return;
for (const { ptr } of this.memberPrev) {
m.FPDFPage_RemoveObject(page.pagePtr, ptr);
}
// Re-inserting in ascending original index order reconstructs the
// exact pre-apply list.
for (const { ptr, idx } of this.memberPrev) {
- ext.FPDFPage_InsertObjectAtIndex(page.pagePtr, ptr, idx);
+ insertPageObjectAt(m, page.pagePtr, ptr, idx);
}
page.markDirty();
page.markNeedsGenerate();
}
- private resolveMemberPtrs(
- page: import("@editor/tools/pdfTextEditor/model/Page").Page,
- ): Set<number> {
+ private resolveMemberPtrs(page: Page): Set<number> {
if (this.runId) {
const run = page.runs.find((r) => r.id === this.runId);
if (!run) return new Set();
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/commands/Command.ts b/frontend/src/editor/core/tools/pdfTextEditor/commands/Command.ts
index 070a46702b..2907c1bfcd 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/commands/Command.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/commands/Command.ts
@@ -1,4 +1,11 @@
import type { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
+import type { PageRect } from "@editor/tools/pdfTextEditor/types";
+
+export interface PageRepaintArea {
+ pageIndex: number;
+ /** Raw page space. */
+ area: PageRect;
+}
// Every user-initiated mutation goes through a Command so it can be recorded,
// replayed, and reverted by the HistoryStack.
@@ -16,6 +23,14 @@ export interface Command {
// previous undo step however long ago that step ran.
coalesceIgnoresTimeWindow?(previous: Command | null): boolean;
supersedes?(adjacent: Command): boolean;
+ /** Undo or redo a merged group in one move, on its last command; false steps through it instead. */
+ moveGroup?(
+ doc: EditorDocument,
+ group: readonly Command[],
+ phase: "apply" | "revert",
+ ): boolean;
+ /** The one page area this command draws in, asked before and after apply; null or absent redraws whole pages. */
+ repaintArea?(doc: EditorDocument): PageRepaintArea | null;
}
export class RolledBackError extends Error {
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/commands/CompositeCommand.ts b/frontend/src/editor/core/tools/pdfTextEditor/commands/CompositeCommand.ts
index 2e8516a660..56210f7d3a 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/commands/CompositeCommand.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/commands/CompositeCommand.ts
@@ -19,6 +19,10 @@ export class CompositeCommand implements Command {
this.commands.push(cmd);
}
+ includes(cmd: Command): boolean {
+ return this.commands.includes(cmd);
+ }
+
/** The most recent child - used to derive the group's coalesce key. */
get last(): Command {
return this.commands[this.commands.length - 1];
@@ -38,6 +42,7 @@ export class CompositeCommand implements Command {
order: Command[],
phase: "apply" | "revert",
): void {
+ if (this.last.moveGroup?.(doc, this.commands, phase)) return;
const done: Command[] = [];
for (const [i, cmd] of order.entries()) {
if (!order[i + 1]?.supersedes?.(cmd)) {
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/commands/DeleteImageCommand.ts b/frontend/src/editor/core/tools/pdfTextEditor/commands/DeleteImageCommand.ts
index 8a73751da3..1608a39fa8 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/commands/DeleteImageCommand.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/commands/DeleteImageCommand.ts
@@ -1,7 +1,9 @@
+import { liftImageToPage } from "@editor/tools/pdfTextEditor/commands/liftFromForm";
import type { Command } from "@editor/tools/pdfTextEditor/commands/Command";
import type { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
import { ImageObject } from "@editor/tools/pdfTextEditor/model/ImageObject";
import type { ImageObjectSnapshot } from "@editor/tools/pdfTextEditor/types";
+import { insertPageObjectAt } from "@editor/tools/pdfTextEditor/util/insertPageObject";
/** Remove an image object from a page. */
export class DeleteImageCommand implements Command {
@@ -25,6 +27,8 @@ export class DeleteImageCommand implements Command {
const page = doc.page(this.pageIndex);
const img = page.findImage(this.imageId);
if (!img) return;
+ // An image the form keeps drawing must not vanish from the model alone: the saved file would still show it.
+ if (!liftImageToPage(doc, page, img)) return;
if (this.snapshot === null) {
this.snapshot = img.snapshot();
this.cachedObjPtr = img.pdfiumObjPtr;
@@ -53,28 +57,19 @@ export class DeleteImageCommand implements Command {
if (!this.snapshot || !this.cachedObjPtr) return;
const page = doc.page(this.pageIndex);
const m = doc.module as unknown as {
- FPDFPage_InsertObjectAtIndex?: (
- page: number,
- obj: number,
- index: number,
- ) => boolean;
- FPDFPage_InsertObject: (page: number, obj: number) => void;
+ FPDFPage_InsertObjectAtIndex?: unknown;
};
- const insertAt = m.FPDFPage_InsertObjectAtIndex;
- let inserted = false;
- if (typeof insertAt === "function" && this.originalIndex >= 0) {
- try {
- inserted = insertAt.call(
- m,
- page.pagePtr,
- this.cachedObjPtr,
- this.originalIndex,
- );
- } catch {
- inserted = false;
- }
- }
- if (!inserted) {
+ if (
+ typeof m.FPDFPage_InsertObjectAtIndex === "function" &&
+ this.originalIndex >= 0
+ ) {
+ insertPageObjectAt(
+ doc.module,
+ page.pagePtr,
+ this.cachedObjPtr,
+ this.originalIndex,
+ );
+ } else {
// Fallback: re-insert at end.
doc.module.FPDFPage_InsertObject(page.pagePtr, this.cachedObjPtr);
if (this.originalIndex >= 0) {
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/commands/DeleteObjectCommand.ts b/frontend/src/editor/core/tools/pdfTextEditor/commands/DeleteObjectCommand.ts
index 6b5641625e..c9791ae3ef 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/commands/DeleteObjectCommand.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/commands/DeleteObjectCommand.ts
@@ -1,3 +1,4 @@
+import { liftRunToPage } from "@editor/tools/pdfTextEditor/commands/liftFromForm";
import type { Command } from "@editor/tools/pdfTextEditor/commands/Command";
import type { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
import type { TextRunSnapshot } from "@editor/tools/pdfTextEditor/types";
@@ -51,21 +52,22 @@ export class DeleteObjectCommand implements Command {
page.setRuns(page.runs.filter((r) => r.id !== run.id));
return;
}
- if (this.snapshot === null) {
- this.snapshot = run.snapshot();
- this.removedRun = run;
- const memberPtrs = collectMemberPtrs(run);
- const containerByPtr = collectContainersByPtr(run);
- const seen = new Set<number>();
- this.cachedPtrs = [];
- for (const ptr of memberPtrs) {
- if (!ptr || seen.has(ptr)) continue;
- seen.add(ptr);
- this.cachedPtrs.push({
- ptr,
- containerPtr: containerByPtr.get(ptr) ?? run.containerPtr,
- });
- }
+ // Lifted first, so undo can put the objects back: nothing reinserts into a form.
+ liftRunToPage(doc, page, run);
+ // Read on every apply: redoing an earlier step draws the run in new objects.
+ this.snapshot = run.snapshot();
+ this.removedRun = run;
+ const memberPtrs = collectMemberPtrs(run);
+ const containerByPtr = collectContainersByPtr(run);
+ const seen = new Set<number>();
+ this.cachedPtrs = [];
+ for (const ptr of memberPtrs) {
+ if (!ptr || seen.has(ptr)) continue;
+ seen.add(ptr);
+ this.cachedPtrs.push({
+ ptr,
+ containerPtr: containerByPtr.get(ptr) ?? run.containerPtr,
+ });
}
removeMemberPtrs(
doc.module,
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/commands/DeleteShapeCommand.ts b/frontend/src/editor/core/tools/pdfTextEditor/commands/DeleteShapeCommand.ts
index 4d096abcf0..3772079b95 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/commands/DeleteShapeCommand.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/commands/DeleteShapeCommand.ts
@@ -1,36 +1,17 @@
-import type { WrappedPdfiumModule } from "@embedpdf/pdfium";
+import { liftFormToPage } from "@editor/tools/pdfTextEditor/commands/liftFromForm";
+import { pageObjectIndex } from "@editor/tools/pdfTextEditor/commands/editTextHelpers";
import type { Command } from "@editor/tools/pdfTextEditor/commands/Command";
import type { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
-import type { Page } from "@editor/tools/pdfTextEditor/model/Page";
import type { ShapeObject } from "@editor/tools/pdfTextEditor/model/ShapeObject";
import type { PageRuleSnapshot } from "@editor/tools/pdfTextEditor/types";
-import { transformObject } from "@editor/tools/pdfTextEditor/util/objectTransform";
-import {
- SCRATCH,
- scratchPtr,
-} from "@editor/tools/pdfTextEditor/util/wasmScratch";
-
-interface PageInsertModule {
- FPDFPage_InsertObjectAtIndex?: (
- page: number,
- obj: number,
- index: number,
- ) => boolean;
-}
-
-interface DrawMode {
- fillMode: number;
- stroke: boolean;
-}
-
-const IDENTITY = { a: 1, b: 0, c: 0, d: 1, e: 0, f: 0 };
+import { insertPageObjectAt } from "@editor/tools/pdfTextEditor/util/insertPageObject";
/**
- * Remove a vector shape. A shape on the page leaves the object list at once.
- * One inside a form XObject is hidden and queued in `pendingFormRemovals` for
- * the save to remove: PDFium writes back a form child's removal but not its
- * paint, and has no call to put a removed child back, so removing it here
- * would make the delete impossible to undo.
+ * Remove a vector shape. One inside a form XObject has that form's instance
+ * lifted onto the page first, so the shape goes from the instance it was
+ * picked in and every other use of the form still draws it. Does nothing when
+ * the form cannot be lifted: a shape the form keeps drawing would only vanish
+ * from the editor and still be in the saved file.
*/
export class DeleteShapeCommand implements Command {
readonly type = "delete-shape";
@@ -42,8 +23,6 @@ export class DeleteShapeCommand implements Command {
/** Position among the shapes and in the page's object list, for revert. */
private shapeIndex = -1;
private objectIndex = -1;
- /** Paint a hidden form child had, for revert. */
- private hiddenDrawMode: DrawMode | null = null;
constructor(opts: { pageIndex: number; shapeId: string }) {
this.pageIndex = opts.pageIndex;
@@ -54,18 +33,17 @@ export class DeleteShapeCommand implements Command {
const page = doc.page(this.pageIndex);
const shape = page.findShape(this.shapeId);
if (!shape || !shape.pdfiumObjPtr) return;
+ if (shape.containerPtr && !liftFormToPage(doc, page, shape.containerPtr))
+ return;
const m = doc.module;
+ const objectIndex = pageObjectIndex(
+ doc.module,
+ page.pagePtr,
+ shape.pdfiumObjPtr,
+ );
+ if (!m.FPDFPage_RemoveObject(page.pagePtr, shape.pdfiumObjPtr)) return;
+ this.objectIndex = objectIndex;
this.shapeIndex = page.shapes.indexOf(shape);
- if (shape.containerPtr) {
- const drawMode = readDrawMode(m, shape.pdfiumObjPtr);
- if (!drawMode) return;
- if (!m.FPDFPath_SetDrawMode(shape.pdfiumObjPtr, 0, false)) return;
- this.hiddenDrawMode = drawMode;
- page.pendingFormRemovals.set(shape.pdfiumObjPtr, shape.containerPtr);
- } else {
- this.objectIndex = indexOnPage(doc, page.pagePtr, shape.pdfiumObjPtr);
- if (!m.FPDFPage_RemoveObject(page.pagePtr, shape.pdfiumObjPtr)) return;
- }
this.removed = shape;
this.removedRules = page.rules.filter(
(rule) => rule.ptr === shape.pdfiumObjPtr,
@@ -84,20 +62,12 @@ export class DeleteShapeCommand implements Command {
const shape = this.removed;
if (!shape) return;
const page = doc.page(this.pageIndex);
- const m = doc.module;
- if (this.hiddenDrawMode) {
- m.FPDFPath_SetDrawMode(
- shape.pdfiumObjPtr,
- this.hiddenDrawMode.fillMode,
- this.hiddenDrawMode.stroke,
- );
- this.hiddenDrawMode = null;
- if (!page.pendingFormRemovals.delete(shape.pdfiumObjPtr)) {
- restoreOntoPage(doc, page, shape);
- }
- } else {
- insertOnPage(doc, page, shape.pdfiumObjPtr, this.objectIndex);
- }
+ insertPageObjectAt(
+ doc.module,
+ page.pagePtr,
+ shape.pdfiumObjPtr,
+ this.objectIndex,
+ );
const shapes = [...page.shapes];
shapes.splice(
this.shapeIndex >= 0 ? this.shapeIndex : shapes.length,
@@ -114,60 +84,3 @@ export class DeleteShapeCommand implements Command {
page.markNeedsGenerate();
}
}
-
-/**
- * A save has already removed this shape from its form, and a form child cannot
- * be re-added, so it returns as a page object just below that form, mapped to
- * the same place on the page.
- */
-function restoreOntoPage(
- doc: EditorDocument,
- page: Page,
- shape: ShapeObject,
-): void {
- const t = shape.containerTransform;
- transformObject(doc.module, shape.pdfiumObjPtr, t.a, t.b, t.c, t.d, t.e, t.f);
- const formIndex = indexOnPage(doc, page.pagePtr, shape.topLevelContainerPtr);
- insertOnPage(doc, page, shape.pdfiumObjPtr, formIndex);
- shape.containerPtr = 0;
- shape.topLevelContainerPtr = 0;
- shape.containerTransform = { ...IDENTITY };
-}
-
-function insertOnPage(
- doc: EditorDocument,
- page: Page,
- objPtr: number,
- index: number,
-): void {
- const m = doc.module;
- const inserted =
- index >= 0 &&
- (m as unknown as PageInsertModule).FPDFPage_InsertObjectAtIndex?.(
- page.pagePtr,
- objPtr,
- index,
- );
- if (!inserted) m.FPDFPage_InsertObject(page.pagePtr, objPtr);
-}
-
-function readDrawMode(m: WrappedPdfiumModule, objPtr: number): DrawMode | null {
- const buf = scratchPtr(m, SCRATCH.shapeDrawMode, 8);
- if (!m.FPDFPath_GetDrawMode(objPtr, buf, buf + 4)) return null;
- return {
- fillMode: m.pdfium.getValue(buf, "i32"),
- stroke: m.pdfium.getValue(buf + 4, "i32") !== 0,
- };
-}
-
-function indexOnPage(
- doc: EditorDocument,
- pagePtr: number,
- objPtr: number,
-): number {
- const total = doc.module.FPDFPage_CountObjects(pagePtr);
- for (let i = 0; i < total; i++) {
- if (doc.module.FPDFPage_GetObject(pagePtr, i) === objPtr) return i;
- }
- return -1;
-}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/commands/DuplicateRunCommand.ts b/frontend/src/editor/core/tools/pdfTextEditor/commands/DuplicateRunCommand.ts
index 037b985b08..119a0cf81f 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/commands/DuplicateRunCommand.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/commands/DuplicateRunCommand.ts
@@ -1,4 +1,14 @@
-import type { Command } from "@editor/tools/pdfTextEditor/commands/Command";
+import i18n from "i18next";
+import {
+ needsShaping,
+ needsShapingMessage,
+} from "@editor/tools/pdfTextEditor/util/complexShaping";
+import {
+ RolledBackError,
+ type Command,
+} from "@editor/tools/pdfTextEditor/commands/Command";
+import { drawsWhole } from "@editor/tools/pdfTextEditor/commands/bidiLineEdit";
+import { refuseRedrawOfReadOnlyText } from "@editor/tools/pdfTextEditor/commands/readOnlyText";
import type { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
import { TextRun } from "@editor/tools/pdfTextEditor/model/TextRun";
import { writeUtf16 } from "@editor/services/pdfiumService";
@@ -6,11 +16,28 @@ import {
fallbackFamilyFor,
fallbackFontIdFor,
} from "@editor/tools/pdfTextEditor/util/fontCapability";
-import { sanitizeForBase14 } from "@editor/tools/pdfTextEditor/commands/editTextHelpers";
+import {
+ removeAndDestroyObject,
+ sanitizeForBase14,
+} from "@editor/tools/pdfTextEditor/commands/editTextHelpers";
+import { emitDeviceFontTextObject } from "@editor/tools/pdfTextEditor/util/deviceFontEmbed";
+import { nearestStandardFont } from "@editor/tools/pdfTextEditor/util/fontFamily";
+import { helveticaVariantFor } from "@editor/tools/pdfTextEditor/util/helveticaVariant";
+import type { Page } from "@editor/tools/pdfTextEditor/model/Page";
+import {
+ needsArabicShaping,
+ shapeArabic,
+} from "@editor/tools/pdfTextEditor/util/arabicShaping";
+import {
+ hasRtl,
+ isRtlBase,
+ visualOrder,
+} from "@editor/tools/pdfTextEditor/util/bidi";
// Clone a text run at a fixed offset (default 12pt right + 12pt down) so the
// user can quickly stamp the same text elsewhere on the page.
const OFFSET = 12;
+const CLEAR_OF_PAGE_PT = 20000;
export class DuplicateRunCommand implements Command {
readonly type = "duplicate-run";
@@ -34,36 +61,29 @@ export class DuplicateRunCommand implements Command {
const page = doc.page(this.pageIndex);
const src = page.findRun(this.runId);
if (!src) return;
- const m = doc.module;
- const fallback = fallbackFamilyFor(src.fontId);
- const newPtr = m.FPDFPageObj_NewTextObj(
- doc.docPtr,
- fallback,
- Math.max(4, src.fontSize),
- );
- if (!newPtr) return;
- // Base-14 can only render WinAnsi; drop other code points, not U+00FF tofu.
- const textPtr = writeUtf16(
- m,
- sanitizeForBase14(src.text.replace(/\r?\n/g, " ")),
- );
- try {
- m.FPDFText_SetText(newPtr, textPtr);
- } finally {
- m.pdfium.wasmExports.free(textPtr);
- }
- m.FPDFPageObj_SetFillColor(
- newPtr,
- src.fill.r,
- src.fill.g,
- src.fill.b,
- src.fill.a,
- );
+ refuseRedrawOfReadOnlyText(src);
+ if (needsShaping(src.text))
+ throw new RolledBackError(new Error(needsShapingMessage()));
const newX = src.matrix.e + OFFSET;
const newY = src.matrix.f - OFFSET;
- m.FPDFPageObj_Transform(newPtr, 1, 0, 0, 1, newX, newY);
- m.FPDFPage_InsertObject(page.pagePtr, newPtr);
- const id = `p${page.index}-dup-${page.runs.length}-${newPtr}`;
+ const drawn = drawCopy(doc, page, src, newX, newY);
+ if (!drawn) return;
+ const { ptr: newPtr, family } = drawn;
+ // The copy is one object in one fallback face, which seldom holds right-to-left letters: a copy of only the line's digits and brackets is refused.
+ if (hasRtl(src.text) && !copyDrawsWhole(doc, page, newPtr, src.text)) {
+ removeAndDestroyObject(doc.module, page.pagePtr, newPtr);
+ throw new RolledBackError(
+ new Error(
+ i18n.t(
+ "pdfTextEditor.error.duplicateDropsLetters",
+ "Can't duplicate this text: no available font draws all of its letters.",
+ ),
+ ),
+ );
+ }
+ // Kept across redo: later steps that edit the copy find it by this id.
+ const id =
+ this.createdRunId ?? `p${page.index}-dup-${page.runs.length}-${newPtr}`;
const clone = new TextRun({
id,
pageIndex: page.index,
@@ -76,7 +96,7 @@ export class DuplicateRunCommand implements Command {
},
matrix: { a: 1, b: 0, c: 0, d: 1, e: newX, f: newY },
text: src.text,
- fontId: fallbackFontIdFor(fallback),
+ fontId: fallbackFontIdFor(family),
fontSize: src.fontSize,
fill: { ...src.fill },
fontSubset: false,
@@ -97,3 +117,74 @@ export class DuplicateRunCommand implements Command {
page.markNeedsGenerate();
}
}
+
+// Read back clear of the page: where the copy lies on the letters it copies, PDFium takes a doubled letter for one.
+function copyDrawsWhole(
+ doc: EditorDocument,
+ page: Page,
+ ptr: number,
+ text: string,
+): boolean {
+ const m = doc.module;
+ m.FPDFPageObj_Transform(ptr, 1, 0, 0, 1, 0, -CLEAR_OF_PAGE_PT);
+ const whole = drawsWhole(m, page, [ptr], text);
+ m.FPDFPageObj_Transform(ptr, 1, 0, 0, 1, 0, CLEAR_OF_PAGE_PT);
+ return whole;
+}
+
+// A standard font is created by name; any other family has to be loaded into the document first.
+function drawCopy(
+ doc: EditorDocument,
+ page: Page,
+ src: TextRun,
+ x: number,
+ y: number,
+): { ptr: number; family: string } | null {
+ const m = doc.module;
+ const size = Math.max(4, src.fontSize);
+ const text = src.text.replace(/\r?\n/g, " ");
+ const wanted = fallbackFamilyFor(src.fontId);
+ if (nearestStandardFont(wanted) !== wanted) {
+ const ptr = emitDeviceFontTextObject(
+ doc,
+ page,
+ wanted,
+ drawnLeftToRight(text),
+ size,
+ src.fill,
+ x,
+ y,
+ );
+ if (ptr) return { ptr, family: wanted };
+ }
+ const family =
+ nearestStandardFont(wanted) === wanted
+ ? wanted
+ : helveticaVariantFor(src.fontId);
+ const ptr = m.FPDFPageObj_NewTextObj(doc.docPtr, family, size);
+ if (!ptr) return null;
+ // Base-14 renders only WinAnsi: drop other code points rather than persist them as U+00FF tofu.
+ const textPtr = writeUtf16(m, sanitizeForBase14(text));
+ try {
+ m.FPDFText_SetText(ptr, textPtr);
+ } finally {
+ m.pdfium.wasmExports.free(textPtr);
+ }
+ m.FPDFPageObj_SetFillColor(
+ ptr,
+ src.fill.r,
+ src.fill.g,
+ src.fill.b,
+ src.fill.a,
+ );
+ m.FPDFPageObj_Transform(ptr, 1, 0, 0, 1, x, y);
+ m.FPDFPage_InsertObject(page.pagePtr, ptr);
+ return { ptr, family };
+}
+
+// Glyphs are drawn left to right in content order, so right-to-left text goes in reordered and shaped.
+function drawnLeftToRight(text: string): string {
+ if (!hasRtl(text)) return text;
+ const shaped = needsArabicShaping(text) ? shapeArabic(text).text : text;
+ return visualOrder(shaped, isRtlBase(text)).visual;
+}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/commands/EditTextCommand.ts b/frontend/src/editor/core/tools/pdfTextEditor/commands/EditTextCommand.ts
index 1b44f4de91..95b9fa8b3a 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/commands/EditTextCommand.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/commands/EditTextCommand.ts
@@ -1,7 +1,27 @@
+import { liftRunToPage } from "@editor/tools/pdfTextEditor/commands/liftFromForm";
+import {
+ softStartsFor,
+ softStartsOf,
+} from "@editor/tools/pdfTextEditor/pdfium/lineBreaks";
+import {
+ needsShaping,
+ needsShapingMessage,
+} from "@editor/tools/pdfTextEditor/util/complexShaping";
+import { unsafeRtlEditMessage } from "@editor/tools/pdfTextEditor/commands/readOnlyText";
import i18n from "i18next";
-import type { Command } from "@editor/tools/pdfTextEditor/commands/Command";
-import { RENDER_MODE_INVISIBLE } from "@editor/tools/pdfTextEditor/types";
+import type { WrappedPdfiumModule } from "@embedpdf/pdfium";
+import {
+ RolledBackError,
+ type Command,
+ type PageRepaintArea,
+} from "@editor/tools/pdfTextEditor/commands/Command";
+import {
+ RENDER_MODE_INVISIBLE,
+ type PageRect,
+ type RGBA,
+} from "@editor/tools/pdfTextEditor/types";
import type { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
+import { readObjFill } from "@editor/tools/pdfTextEditor/pdfium/PdfiumObjectColour";
import { PdfiumTextWriter } from "@editor/tools/pdfTextEditor/pdfium/PdfiumTextWriter";
import {
sampleBackground,
@@ -9,26 +29,40 @@ import {
} from "@editor/tools/pdfTextEditor/pdfium/BackgroundSampler";
import {
charcodesResolveFully,
+ objectTexts,
collectContainersByPtr,
+ contentIndices,
+ restoreContentOrder,
collectMemberPtrs,
+ droppedCharsSeen,
emitFillRect,
emitTextLine,
everyCharIn,
inkFromRun,
+ measureObjBoundsPt,
measureObjSpanPt,
+ moveObjectLeftEdgeTo,
removeMemberPtrs,
rotationFromMatrix,
warmOnPageAdvances,
planLineOrigins,
emitRunLines,
+ sliceFontSpans,
+ type FontSpan,
} from "@editor/tools/pdfTextEditor/commands/editTextHelpers";
+import { deviceFamilyOf } from "@editor/tools/pdfTextEditor/util/deviceFontEmbed";
import {
bestFontPtrForText,
applyParagraphEditPlan,
applyPartialEditPlan,
- planModifiesWhitespace,
- planParagraphEdit,
- planPartialEdit,
+ diffSpan,
+ planModifiesUndrawableWhitespace,
+ piecesFromObjects,
+ sourceFontSpans,
+ planUndoableParagraphEdit,
+ planUndoablePartialEdit,
+ redrawingUndrawableWhitespace,
+ revertPartialEditPlan,
setObjText,
type ParagraphEditPlan,
type PartialEditPlan,
@@ -43,6 +77,16 @@ import type {
TextRun,
} from "@editor/tools/pdfTextEditor/model/TextRun";
import { transformObject } from "@editor/tools/pdfTextEditor/util/objectTransform";
+import {
+ readMatrix,
+ writeMatrix,
+} from "@editor/tools/pdfTextEditor/commands/textPieces";
+import { hasRtl } from "@editor/tools/pdfTextEditor/util/bidi";
+import {
+ applyBidiLineEdit,
+ drawsLetters,
+ planBidiLineEdit,
+} from "@editor/tools/pdfTextEditor/commands/bidiLineEdit";
import {
SCRATCH,
scratchPtr,
@@ -51,6 +95,7 @@ import {
captureScanEdit,
isScanRun,
renderScanEdit,
+ scanBlockBounds,
} from "@editor/tools/pdfTextEditor/commands/scanTextEdit";
import {
editedTags,
@@ -62,6 +107,14 @@ import {
uniformTags,
type TextTags,
} from "@editor/tools/pdfTextEditor/model/TextTags";
+import { MoveTextRunCommand } from "@editor/tools/pdfTextEditor/commands/MoveTextRunCommand";
+import {
+ type PushRecord,
+ pushRecords,
+ runsPulledBack,
+ setPushRecords,
+ runsPushedBelow,
+} from "@editor/tools/pdfTextEditor/commands/pushRunsBelow";
interface RevertLine {
text: string;
@@ -109,6 +162,63 @@ interface RunModelSnapshot {
pdfiumObjPtr: number;
}
+// A later step's undo redraws what this edit inserted as new objects, which `inserted` cannot name.
+function withGained(
+ m: WrappedPdfiumModule,
+ page: Page,
+ run: TextRun,
+ inserted: readonly number[],
+ before: RunModelSnapshot | null,
+ removed: ReadonlySet<number>,
+): number[] {
+ if (!before) return [...inserted];
+ const kept = new Set(
+ collectMemberPtrs(before).filter((ptr) => ptr && !removed.has(ptr)),
+ );
+ const onPage = new Set(
+ Array.from({ length: m.FPDFPage_CountObjects(page.pagePtr) }, (_, i) =>
+ m.FPDFPage_GetObject(page.pagePtr, i),
+ ),
+ );
+ if (![...kept].every((ptr) => onPage.has(ptr))) return [...inserted];
+ const containers = collectContainersByPtr(run);
+ const gained = collectMemberPtrs(run).filter(
+ (ptr) => ptr && !kept.has(ptr) && !containers.get(ptr),
+ );
+ return [...new Set([...inserted, ...gained])];
+}
+
+// Typed text has no font's shaping applied whichever face draws it, and with no face loaded for it the letters would be dropped instead. Read from the letter before, which a typed mark is set on.
+function typesUnshaped(prev: string, next: string): boolean {
+ const { start, nextEnd } = diffSpan(prev, next);
+ return needsShaping(next.slice(Math.max(0, start - 1), nextEnd));
+}
+
+/** What each object of the run reads as, by object. */
+function memberTexts(
+ doc: EditorDocument,
+ page: Page,
+ run: TextRun,
+): Map<number, string> {
+ const ptrs = collectMemberPtrs(run).filter((ptr) => ptr);
+ const texts = objectTexts(doc.module, page.pagePtr, ptrs) ?? [];
+ return new Map(ptrs.map((ptr, i) => [ptr, texts[i] ?? ""]));
+}
+
+// An object the edit drew or rewrote is drawn from code points, so any shaped cluster in it comes out wrong. An object that read as nothing is a glyph piece whose text an ActualText span gives to a neighbour, and moving the pair can hand the text to it instead.
+function drewUnshaped(
+ doc: EditorDocument,
+ page: Page,
+ run: TextRun,
+ before: ReadonlyMap<number, string>,
+): boolean {
+ for (const [ptr, text] of memberTexts(doc, page, run)) {
+ const was = before.get(ptr);
+ if (was !== "" && was !== text && needsShaping(text)) return true;
+ }
+ return false;
+}
+
// True when a partial-edit plan only ADDED objects (no original object was
// freed via removePtrs, none mutated in place via a "modify" op).
function planIsPureInsert(plan: PartialEditPlan): boolean {
@@ -132,6 +242,11 @@ function scanFontSize(
return size > 2 && size < ink.height * 3 ? size : fallback;
}
+const UPRIGHT_TOLERANCE = 1e-6;
+const MIN_REPAINT_MARGIN_PT = 4;
+const REPAINT_MARGIN_PER_FONT_SIZE = 1.5;
+const PAGE_SPAN_PT = 100_000; // past any page edge; the bitmap clips the rest
+
/** Edit a text run. */
export class EditTextCommand implements Command {
readonly type = "edit-text";
@@ -141,6 +256,8 @@ export class EditTextCommand implements Command {
private prevText: string | null = null;
/** `prevText`'s tags, read from the run's objects on the first apply. */
private prevTags: TextTags | null = null;
+ private readonly nextTagsOverride: TextTags | null;
+ private readonly nextFont: { ptr: number; id: string } | null;
private overlaid = false;
private prevObjPtr = 0;
@@ -152,6 +269,8 @@ export class EditTextCommand implements Command {
* lookalike.
*/
private prevFontPtr = 0;
+ // The run's face before this edit's first apply, whichever path the edit then takes.
+ private startFont: { ptr: number; id: string } | null = null;
private coverRectPtr = 0;
// Ink of an invisible OCR run this edit made visible, restored on revert.
private scanSource: { fill: TextRun["fill"]; fontSize: number } | null = null;
@@ -159,6 +278,9 @@ export class EditTextCommand implements Command {
/** Set when apply went through the word-level scanned-OCR path. */
private scanEdited = false;
private scanRefused = false;
+ // The box of a scanned block before this edit and around what it drew, so undo and redo put back exactly the size the overlay and inspector read.
+ private scanBounds: { before: PageRect; after: PageRect | null } | null =
+ null;
private newTextPtr = 0;
private revertLines: RevertLine[] = [];
/** Rotation of the run when apply() snapshotted it; re-applied on revert. */
@@ -166,9 +288,18 @@ export class EditTextCommand implements Command {
/** Set when the apply path took the partial-edit (LCS) shortcut. */
private partialPlan: PartialEditPlan | null = null;
private partialInsertedPtrs: number[] = [];
+ private partialRedo: PartialRedo | null = null;
+ // A draw that left characters out is redrawn by a redo once their fonts arrive, so its objects are not kept for reuse.
+ private partialDrewAll = false;
private prevMergedFromPtrs: number[] = [];
private prevMergedFromTexts: string[] = [];
private prevMergedFromBounds: Array<{ x: number; right: number }> = [];
+ /** The font each pre-edit sub-run was drawn in (parallel to its ptrs). */
+ private prevMergedFromFonts: number[] = [];
+ /** The fill each pre-edit sub-run was drawn in (parallel to its ptrs). */
+ private prevMergedFromFills: Array<RGBA | null> = [];
+ /** The objects drawn by an apply that kept right-to-left text's own objects; null when it took another path. */
+ private bidiInsertedPtrs: number[] | null = null;
/** Set when the apply path took the paragraph-aware partial shortcut. */
private paragraphPlan: ParagraphEditPlan | null = null;
private paragraphInsertedPtrs: number[] = [];
@@ -176,42 +307,173 @@ export class EditTextCommand implements Command {
// Full pre-edit model snapshot, captured by the partial / paragraph-partial
// apply paths.
private editSnapshot: RunModelSnapshot | null = null;
+ // The run's own objects before a partial apply, with where each sat; null when one lives in a form and cannot be put back.
+ private originalObjects: OriginalObjects | null = null;
+ private revertedExactly = false;
/** Set when the apply path took the paragraph line add/remove shortcut. */
private lineEdit: {
/** Matched lines translated to a new baseline (reversed on revert). */
moves: Array<{ ptr: number; dy: number }>;
/** Fresh objects emitted for new/changed lines (removed on revert). */
createdPtrs: number[];
- /** Deleted lines, re-emitted as fallback on revert. */
+ /** Deleted lines: put back as they were when they lived on the page itself, else re-emitted as fallback on revert. */
removed: Array<{
text: string;
tags: TextTags;
x: number;
y: number;
fontSize: number;
+ detached: Array<{ ptr: number; index: number }> | null;
}>;
prev: RunModelSnapshot;
} | null = null;
- constructor(opts: { pageIndex: number; runId: string; nextText: string }) {
+ // Objects the last whole-burst replay drew for this run, kept on the burst's last edit: the next replay replaces and frees them.
+ private replayDrawn: number[] = [];
+ private readonly pushesBelow: boolean;
+ private readonly explicit: boolean;
+ // The runs below that this edit's added lines moved down, chosen on the first apply so a redo moves the same ones.
+ private pushes: MoveTextRunCommand[] | null = null;
+ // What the run was recorded as holding down before and after this edit, when the edit changed it.
+ private pushRecords: {
+ before: readonly PushRecord[];
+ after: readonly PushRecord[];
+ } | null = null;
+ // Which lines start at a wrap before and after this edit, so a later widening rejoins wraps and keeps typed breaks.
+ private softBefore: SoftStarts | null = null;
+ private softAfter: SoftStarts | null = null;
+
+ constructor(opts: {
+ pageIndex: number;
+ runId: string;
+ nextText: string;
+ nextTags?: TextTags | null;
+ nextFont?: { ptr: number; id: string } | null;
+ pushesBelow?: boolean;
+ explicit?: boolean;
+ }) {
this.pageIndex = opts.pageIndex;
this.runId = opts.runId;
this.nextText = opts.nextText;
+ this.nextTagsOverride = opts.nextTags ?? null;
+ this.nextFont = opts.nextFont ?? null;
+ this.pushesBelow = opts.pushesBelow ?? true;
+ this.explicit = opts.explicit ?? false;
}
apply(doc: EditorDocument): void {
+ const page = doc.page(this.pageIndex);
+ const run = page.findRun(this.runId);
+ const deciding =
+ this.pushes === null &&
+ this.pushesBelow &&
+ run !== undefined &&
+ !isScanRun(run);
+ const lines = run ? lineCount(this.nextText) - lineCount(run.text) : 0;
+ const oldBottom = run?.bounds.y ?? 0;
+ const shaped = run !== undefined && needsShaping(this.nextText);
+ if (shaped && typesUnshaped(run.text, this.nextText))
+ throw new RolledBackError(new Error(needsShapingMessage()));
+ const membersBefore = shaped ? memberTexts(doc, page, run) : null;
+ const softBefore = run ? softStartsNow(run) : null;
+ this.applyEdit(doc);
+ if (run && membersBefore && drewUnshaped(doc, page, run, membersBefore)) {
+ this.revertEdit(doc);
+ throw new RolledBackError(new Error(needsShapingMessage()));
+ }
+ if (this.pushes === null) {
+ if (!deciding || this.scanEdited || lines === 0) this.pushes = [];
+ else if (lines > 0) {
+ const lineHeight =
+ run.paragraphLineHeight > 0
+ ? run.paragraphLineHeight
+ : run.fontSize * 1.2;
+ const { runIds, dy } = runsPushedBelow(
+ page,
+ run,
+ oldBottom,
+ lines * lineHeight,
+ );
+ this.pushes = runIds.map((runId) => this.moveBelow(runId, dy));
+ if (runIds.length > 0)
+ this.pushRecords = {
+ before: pushRecords(run),
+ after: [
+ ...pushRecords(run),
+ {
+ lineCount: lineCount(this.nextText),
+ linesAdded: lines,
+ runIds,
+ dy,
+ },
+ ],
+ };
+ } else {
+ // By lines, not ink: a blank line holds the text below down without drawing anything.
+ const { moves, records } = runsPulledBack(
+ page,
+ run,
+ lineCount(this.nextText),
+ );
+ this.pushes = moves.map(({ runId, dy }) => this.moveBelow(runId, dy));
+ this.pushRecords = { before: pushRecords(run), after: records };
+ }
+ }
+ if (run && softBefore) {
+ this.softBefore ??= softBefore;
+ this.softAfter ??= {
+ flags: softStartsFor(run.text, softBefore.text, softBefore.flags),
+ text: run.text,
+ };
+ setSoftStarts(run, this.softAfter);
+ }
+ this.redoPushes(doc);
+ }
+
+ private moveBelow(runId: string, dy: number): MoveTextRunCommand {
+ return new MoveTextRunCommand({
+ pageIndex: this.pageIndex,
+ runId,
+ dx: 0,
+ dy,
+ });
+ }
+
+ private redoPushes(doc: EditorDocument): void {
+ const run = doc.page(this.pageIndex).findRun(this.runId);
+ for (const push of this.pushes ?? []) push.apply(doc);
+ if (run && this.pushRecords) setPushRecords(run, this.pushRecords.after);
+ }
+
+ private undoPushes(doc: EditorDocument): void {
+ const run = doc.page(this.pageIndex).findRun(this.runId);
+ for (const push of [...(this.pushes ?? [])].reverse()) push.revert(doc);
+ if (run && this.pushRecords) setPushRecords(run, this.pushRecords.before);
+ }
+
+ private applyEdit(doc: EditorDocument): void {
const page = doc.page(this.pageIndex);
const run = page.findRun(this.runId);
if (!run) return;
+ this.originalObjects = null;
+ this.revertedExactly = false;
if (this.prevText === null) this.prevText = run.text;
+ if (!this.startFont && run.containerPtr === 0 && run.pdfiumObjPtr) {
+ const ptr = safeGetFont(doc.module, run.pdfiumObjPtr);
+ if (ptr) this.startFont = { ptr, id: run.fontId };
+ }
// No-op edit: a contentEditable insert can fire several `input` events for
// one keystroke burst, re-dispatching the SAME final text.
if (this.prevText === this.nextText) return;
+ if (run.textReadOnly && !this.scanEdited && !isScanRun(run))
+ throw new RolledBackError(new Error(unsafeRtlEditMessage()));
+ liftRunToPage(doc, page, run);
if (this.scanEdited || isScanRun(run)) {
run.scanEdit ??= captureScanEdit(doc.module, run, page);
if (run.scanEdit) {
this.scanEdited = true;
+ this.scanBounds ??= { before: { ...run.bounds }, after: null };
this.scanRefused = !renderScanEdit(
doc,
page,
@@ -219,27 +481,50 @@ export class EditTextCommand implements Command {
run.scanEdit,
this.nextText,
);
+ if (!this.scanRefused) {
+ this.scanBounds.after ??= scanBlockBounds(doc, run);
+ if (this.scanBounds.after) run.bounds = { ...this.scanBounds.after };
+ }
return;
}
}
this.prevTags ??= readRunTags(doc, page, run);
- const nextTags = editedTags(
- doc,
- this.pageIndex,
- this.prevTags,
- this.prevText,
- this.nextText,
- run.tagMarks,
- );
+ const nextTags =
+ this.nextTagsOverride ??
+ editedTags(
+ doc,
+ this.pageIndex,
+ this.prevTags,
+ this.prevText,
+ this.nextText,
+ run.tagMarks,
+ );
+
+ if (this.redoPartialEdit(doc, page, run)) return;
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.
- const scanText = run.renderMode === RENDER_MODE_INVISIBLE;
+ const scanText = isScanRun(run);
// A run rotated within the page can't use the surgical partial/paragraph
// paths - those assume horizontal layout.
const isRotated = !!rotationFromMatrix(run.matrix);
+ // Only the full re-emit below can switch the run to a given face.
+ const keepsFont = this.nextFont === null;
+ // The partial paths shift pieces rightward from where they were; only the full re-emit lays out right-to-left text.
+ const leftToRight = !hasRtl(this.prevText ?? "") && !hasRtl(this.nextText);
+
+ if (
+ !leftToRight &&
+ this.nextText.length > 0 &&
+ run.wrapWidthPt === null &&
+ !isRotated &&
+ !scanText &&
+ keepsFont &&
+ this.applyKeepingLineObjects(doc, page, run, nextTags)
+ )
+ return;
// PARAGRAPH-AWARE PARTIAL PATH: paragraphs (multi-line runs) keep per-line
// sub-run data in `paragraphLineSlots`.
@@ -248,17 +533,43 @@ export class EditTextCommand implements Command {
this.paragraphPlan === null &&
run.paragraphLineSlots.length > 1 &&
!isRotated &&
- !scanText
+ !scanText &&
+ keepsFont &&
+ leftToRight
) {
- const paraPlan = planParagraphEdit(
+ const planned = planUndoableParagraphEdit(
+ doc.module,
+ page.pagePtr,
run,
this.prevText ?? "",
this.nextText,
);
+ const paraPlan =
+ planned &&
+ redrawingUndrawableWhitespace(
+ doc.module,
+ planned,
+ page.pagePtr,
+ doc.docPtr,
+ );
if (paraPlan) {
this.paragraphPlan = paraPlan;
this.prevParagraphSlots = paraPlan.prevSlots;
this.editSnapshot = snapshotRunModel(run);
+ this.originalObjects = captureOriginalObjects(
+ doc.module,
+ run,
+ paraPlan.prevSlots.flatMap((slot) => slot.mergedFromPtrs),
+ paraPlan.perSlot.flatMap((entry) =>
+ entry.plan
+ ? entry.plan.removePtrs
+ : paraPlan.prevSlots[entry.slotIdx].mergedFromPtrs.map((ptr) => ({
+ ptr,
+ containerPtr: -1,
+ })),
+ ),
+ page.pagePtr,
+ );
const result = applyParagraphEditPlan(
doc,
page,
@@ -306,7 +617,9 @@ export class EditTextCommand implements Command {
this.prevText.length > 0 &&
run.paragraphLineSlots.length >= 1 &&
!isRotated &&
- !scanText
+ !scanText &&
+ keepsFont &&
+ leftToRight
) {
const prevLines = this.prevText.split(/\r?\n/);
const nextLines = this.nextText.split(/\r?\n/);
@@ -350,19 +663,63 @@ export class EditTextCommand implements Command {
run.paragraphLineSlots.length < 2 &&
!/\r?\n/.test(this.nextText) &&
!isRotated &&
- !scanText
+ !scanText &&
+ keepsFont &&
+ leftToRight
) {
- const partial = planPartialEdit(run, this.prevText ?? "", this.nextText);
- // An in-place "modify" op that re-SetTexts whitespace paints „ on an
- // embedded subset font with no space glyph.
- if (partial && !planModifiesWhitespace(partial)) {
+ const partial = planUndoablePartialEdit(
+ doc.module,
+ page.pagePtr,
+ run,
+ this.prevText ?? "",
+ this.nextText,
+ );
+ if (
+ partial &&
+ !planModifiesUndrawableWhitespace(
+ doc.module,
+ partial,
+ page.pagePtr,
+ doc.docPtr,
+ )
+ ) {
this.partialPlan = partial;
this.prevMergedFromPtrs = [...run.mergedFromPtrs];
this.prevMergedFromTexts = [...run.mergedFromTexts];
this.prevMergedFromBounds = run.mergedFromBounds.map((b) => ({ ...b }));
+ this.prevMergedFromFonts = run.mergedFromPtrs.map((ptr) =>
+ safeGetFont(doc.module, ptr),
+ );
+ this.prevMergedFromFills = run.mergedFromPtrs.map((ptr) =>
+ readObjFill(doc.module, ptr),
+ );
this.editSnapshot = snapshotRunModel(run);
+ this.originalObjects = captureOriginalObjects(
+ doc.module,
+ run,
+ run.mergedFromPtrs,
+ partial.removePtrs,
+ page.pagePtr,
+ );
+ const drops = droppedCharsSeen();
const result = applyPartialEditPlan(doc, page, run, partial, nextTags);
+ this.partialDrewAll = droppedCharsSeen() === drops;
this.partialInsertedPtrs = result.insertedPtrs;
+ // A reflow leaves a one-line run's objects in paragraphLeafPtrs too,
+ // and that list wins over mergedFromPtrs wherever the run's objects
+ // are collected: a letter left out of it is dropped by the next reflow.
+ if (run.paragraphLeafPtrs.length > 0) {
+ const containerOf = new Map(
+ run.paragraphLeafPtrs.map((ptr, i) => [
+ ptr,
+ run.paragraphLeafContainers[i] ?? run.containerPtr,
+ ]),
+ );
+ run.paragraphLeafPtrs = [...result.newMergedFromPtrs];
+ run.paragraphLeafContainers = result.newMergedFromPtrs.map(
+ (ptr) => containerOf.get(ptr) ?? run.containerPtr,
+ );
+ }
run.mergedFromPtrs = result.newMergedFromPtrs;
run.mergedFromTexts = result.newMergedFromTexts;
run.mergedFromBounds = result.newMergedFromBounds;
@@ -462,15 +819,46 @@ export class EditTextCommand implements Command {
));
// Borrow the font of the member sharing the most chars with the new text.
const borrowPtrs = collectMemberPtrs(run);
+ // A full re-emit leaves the run's piece texts out of step with its objects, so each is read off the page.
const borrowTexts =
run.mergedFromTexts.length === borrowPtrs.length
? run.mergedFromTexts
- : borrowPtrs.map(() => run.text);
+ : (objectTexts(m, page.pagePtr, borrowPtrs) ??
+ borrowPtrs.map(() => run.text));
+ // A font that cannot draw every new character still draws the words it can.
+ const coveredWordsOnly =
+ !this.nextFont &&
+ !canReuseFont &&
+ !scanText &&
+ run.containerPtr === 0 &&
+ candidateFontPtr !== 0;
const originalFontPtr =
- canReuseFont && !scanText
+ this.nextFont?.ptr ||
+ (canReuseFont && !scanText
? bestFontPtrForText(m, borrowPtrs, borrowTexts, this.nextText) ||
(run.pdfiumObjPtr ? safeGetFont(m, run.pdfiumObjPtr) : 0)
- : 0;
+ : coveredWordsOnly
+ ? bestFontPtrForText(m, borrowPtrs, borrowTexts, this.nextText) ||
+ candidateFontPtr
+ : 0);
+ // Read before the source objects go: a run mixing bold and regular keeps each word's face, and a letter
+ // drawn in another font because the run's own lacks it stays in that font.
+ const oneLine =
+ !/\n/.test(this.prevText ?? "") && !/\n/.test(this.nextText);
+ // A paragraph's own pieces are those of its first line only, so its lines are read off the page.
+ const pieces =
+ oneLine && run.mergedFromPtrs.length > 0
+ ? run
+ : (piecesFromObjects(
+ m,
+ page.pagePtr,
+ oneLine ? run.paragraphLeafPtrs : borrowPtrs,
+ this.prevText ?? "",
+ ) ?? (oneLine ? run : null));
+ const fontSpans =
+ !this.nextFont && !scanText && pieces
+ ? editedFontSpans(doc, page, pieces, this.prevText ?? "", this.nextText)
+ : undefined;
this.revertLines = snapshotRevertLines(
run,
@@ -495,6 +883,17 @@ export class EditTextCommand implements Command {
const memberPtrs = collectMemberPtrs(run);
const containers = collectContainersByPtr(run);
+ this.editSnapshot = snapshotRunModel(run);
+ this.originalObjects = captureOriginalObjects(
+ m,
+ run,
+ memberPtrs,
+ memberPtrs.map((ptr) => ({
+ ptr,
+ containerPtr: containers.get(ptr) ?? run.containerPtr,
+ })),
+ page.pagePtr,
+ );
const allRemoved = removeMemberPtrs(
m,
page,
@@ -558,7 +957,9 @@ export class EditTextCommand implements Command {
origins: planLineOrigins(run, outputLines.length, lineHeight),
originalFontPtr,
originalFontSubset: run.fontSubset,
+ originalFontForCoveredWords: coveredWordsOnly,
fallbackFamily,
+ fontSpansByLine: fontSpans && spansByLine(fontSpans, this.nextText),
});
for (const line of emitted) {
// Empty lines keep a placeholder slot; a FAILED emit is dropped entirely.
@@ -600,11 +1001,13 @@ export class EditTextCommand implements Command {
if (lineAnchorPtrs.length > 0) {
this.newTextPtr = lineAnchorPtrs[0];
run.pdfiumObjPtr = lineAnchorPtrs[0];
- if (originalFontPtr === 0) {
+ // A line kept in its own pieces' faces is still the document's font, not a base-14 one to SetText over.
+ if (originalFontPtr === 0 && !fontSpans) {
run.fontId = fallbackFontIdFor(fallbackFamily);
run.fontSubset = false;
- } else {
+ } else if (originalFontPtr !== 0) {
// Borrow path: the new objects use the borrowed font handle.
+ if (this.nextFont) run.fontId = this.nextFont.id;
run.fontSubset = false;
}
run.paragraphMemberPtrs = lineAnchorPtrs;
@@ -660,10 +1063,95 @@ export class EditTextCommand implements Command {
const right = Math.max(run.bounds.x + run.bounds.width, span.right);
run.bounds = { ...run.bounds, x: left, width: Math.max(0, right - left) };
}
+ const addedLines = outputLines.length - this.prevText.split(/\r?\n/).length;
+ if (addedLines > 0 && !rotationFromMatrix(run.matrix)) {
+ const drop = addedLines * lineHeight;
+ run.bounds = {
+ ...run.bounds,
+ y: run.bounds.y - drop,
+ height: run.bounds.height + drop,
+ };
+ }
run.text = this.nextText;
run.dirty = true;
page.markDirty();
page.markNeedsGenerate();
+ // A whole redraw finds no font for some right-to-left letters and leaves them out. Letters the run already drew are put back and the edit refused; a typed letter still waits for its script's font.
+ if (
+ !leftToRight &&
+ !scanText &&
+ allRemoved &&
+ this.originalObjects !== null &&
+ !drawsLetters(
+ m,
+ page,
+ allEmittedPtrs,
+ keptText(this.prevText, this.nextText),
+ )
+ ) {
+ this.revertEdit(doc);
+ throw new RolledBackError(new Error(unsafeRtlEditMessage()));
+ }
+ }
+
+ // Edit a run holding right-to-left text by moving the objects the edit leaves alone and drawing only what it changes. False, with nothing changed, when the run's objects do not draw its text the way the editor lays it out; throws when what it must redraw no font can draw.
+ private applyKeepingLineObjects(
+ doc: EditorDocument,
+ page: Page,
+ run: TextRun,
+ nextTags: TextTags,
+ ): boolean {
+ const prev = this.prevText ?? "";
+ const plan = planBidiLineEdit(doc, page, run, prev, this.nextText);
+ if (!plan) return false;
+ const snapshot = snapshotRunModel(run);
+ const originals = captureOriginalObjects(
+ doc.module,
+ run,
+ plan.ptrs,
+ plan.removePtrs.map((ptr) => ({ ptr, containerPtr: 0 })),
+ page.pagePtr,
+ );
+ if (!originals) return false;
+ const result = applyBidiLineEdit(doc, page, run, prev, plan, nextTags);
+ if (!result) throw new RolledBackError(new Error(unsafeRtlEditMessage()));
+ this.editSnapshot = snapshot;
+ this.originalObjects = originals;
+ this.bidiInsertedPtrs = result.insertedPtrs;
+ const drawn = result.lines.filter((line) => line.ptrs.length > 0);
+ const all = result.lines.flatMap((line) => line.ptrs);
+ const [only] = result.lines;
+ const oneLine = result.lines.length === 1;
+ run.mergedFromPtrs = oneLine ? only.ptrs : [];
+ run.mergedFromTexts = oneLine ? only.texts : [];
+ run.mergedFromBounds = oneLine ? only.bounds : [];
+ run.mergedFromCharStarts = oneLine ? only.charStarts : [];
+ run.paragraphMemberPtrs = oneLine ? [] : drawn.map((line) => line.ptrs[0]);
+ run.paragraphMemberContainers = run.paragraphMemberPtrs.map(() => 0);
+ run.paragraphMemberFs = oneLine ? [] : drawn.map((line) => line.y);
+ run.paragraphLeafPtrs = oneLine ? [] : all;
+ run.paragraphLeafContainers = run.paragraphLeafPtrs.map(() => 0);
+ run.paragraphLineSlots = oneLine
+ ? []
+ : buildSlotsFromOverlayEmit(doc.module, run, result.lines, run.fontId);
+ const lineHeight =
+ run.paragraphLineHeight > 0
+ ? run.paragraphLineHeight
+ : run.fontSize * 1.2;
+ if (!oneLine) run.paragraphLineHeight = lineHeight;
+ run.pdfiumObjPtr = all[0] ?? run.pdfiumObjPtr;
+ const drop = (result.lines.length - prev.split("\n").length) * lineHeight;
+ run.bounds = {
+ x: result.left,
+ y: run.bounds.y - drop,
+ width: clampWidthToPage(result.left, result.right - result.left, page),
+ height: run.bounds.height + drop,
+ };
+ run.text = this.nextText;
+ run.dirty = true;
+ page.markDirty();
+ page.markNeedsGenerate();
+ return true;
}
private prevTagsOf(run: TextRun, start: number, end: number): TextTags {
@@ -672,10 +1160,114 @@ export class EditTextCommand implements Command {
: uniformTags(run.tagMarks);
}
+ // Taken before the revert detaches what the apply drew, while those objects still sit where it put them.
+ private capturePartialRedo(
+ m: WrappedPdfiumModule,
+ page: Page,
+ run: TextRun,
+ inserted: readonly number[],
+ ): PartialRedo | null {
+ const plan = this.partialPlan;
+ const originals = this.originalObjects;
+ const before = this.editSnapshot;
+ if (!plan || !originals || !before || !this.partialDrewAll) return null;
+ const after = collectMemberPtrs(run).filter(Boolean);
+ const matrices = new Map<number, Float32Array>();
+ for (const ptr of after) {
+ const matrix = readMatrix(m, ptr);
+ if (!matrix) return null;
+ matrices.set(ptr, matrix);
+ }
+ const order = contentIndices(m, page.pagePtr, after);
+ if (order.size !== new Set(after).size) return null;
+ const kept = new Set(after);
+ return {
+ plan,
+ originals,
+ inserted: [...inserted],
+ detach: collectMemberPtrs(before).filter((ptr) => ptr && !kept.has(ptr)),
+ modified: plan.ops.flatMap((op) =>
+ op.type === "modify" &&
+ op.subRunIdx !== undefined &&
+ op.text !== undefined
+ ? [{ ptr: plan.prevMergedFromPtrs[op.subRunIdx], text: op.text }]
+ : [],
+ ),
+ matrices,
+ order,
+ model: snapshotRunModel(run),
+ };
+ }
+
+ // A redo puts back the very objects the apply drew, rather than drawing new ones: a later step of the burst holds them, and the replaced ones would be left detached with nothing to free them.
+ private redoPartialEdit(
+ doc: EditorDocument,
+ page: Page,
+ run: TextRun,
+ ): boolean {
+ const redo = this.partialRedo;
+ this.partialRedo = null;
+ const before = this.editSnapshot;
+ if (!redo || !before || run.text !== this.prevText) return false;
+ const members = collectMemberPtrs(run);
+ const expected = collectMemberPtrs(before);
+ if (
+ members.length !== expected.length ||
+ members.some((ptr, i) => ptr !== expected[i])
+ )
+ return false;
+ const m = doc.module;
+ for (const ptr of redo.detach) m.FPDFPage_RemoveObject(page.pagePtr, ptr);
+ for (const { ptr, text } of redo.modified) setObjText(doc, page, ptr, text);
+ for (const ptr of redo.inserted) m.FPDFPage_InsertObject(page.pagePtr, ptr);
+ for (const [ptr, matrix] of redo.matrices) writeMatrix(m, ptr, matrix);
+ restoreContentOrder(
+ m,
+ page.pagePtr,
+ [...redo.order].map(([ptr, index]) => ({ ptr, index })),
+ );
+ restoreRunModel(run, redo.model);
+ this.partialPlan = redo.plan;
+ this.partialInsertedPtrs = redo.inserted;
+ this.originalObjects = redo.originals;
+ run.text = this.nextText;
+ run.dirty = true;
+ page.markDirty();
+ page.markNeedsGenerate();
+ return true;
+ }
+
+ // Removed objects are only detached, never destroyed, so the originals return with their own fonts and glyphs, which a re-emit cannot rebuild for a Type 3 or subset face.
+ private putOriginalObjectsBack(m: WrappedPdfiumModule, page: Page): boolean {
+ const originals = this.originalObjects;
+ this.originalObjects = null;
+ if (!originals) return false;
+ this.revertedExactly = true;
+ for (const ptr of originals.detached)
+ m.FPDFPage_InsertObject(page.pagePtr, ptr);
+ for (const [ptr, matrix] of originals.matrices) writeMatrix(m, ptr, matrix);
+ restoreContentOrder(
+ m,
+ page.pagePtr,
+ [...originals.order].map(([ptr, index]) => ({ ptr, index })),
+ );
+ return true;
+ }
+
+ /** True when revert puts back the very objects apply took off the page. */
+ private revertsExactly(): boolean {
+ return (
+ this.originalObjects !== null ||
+ (this.lineEdit !== null &&
+ this.lineEdit.removed.every((rem) => rem.detached !== null))
+ );
+ }
+
// 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 {
const set =
+ (this.bidiInsertedPtrs !== null ? 1 : 0) +
(this.lineEdit !== null ? 1 : 0) +
(this.paragraphPlan !== null ? 1 : 0) +
(this.partialPlan !== null ? 1 : 0) +
@@ -688,16 +1280,37 @@ export class EditTextCommand implements Command {
}
revert(doc: EditorDocument): void {
+ this.undoPushes(doc);
+ this.revertEdit(doc);
+ const run = doc.page(this.pageIndex).findRun(this.runId);
+ if (run && this.softBefore) setSoftStarts(run, this.softBefore);
+ }
+
+ private revertEdit(doc: EditorDocument): void {
const page = doc.page(this.pageIndex);
const run = page.findRun(this.runId);
if (!run || this.prevText === null) return;
if (this.scanEdited && run.scanEdit) {
renderScanEdit(doc, page, run, run.scanEdit, this.prevText);
+ if (this.scanBounds) run.bounds = { ...this.scanBounds.before };
return;
}
this.assertSingleRevertPath();
const m = doc.module;
+ if (this.bidiInsertedPtrs) {
+ for (const ptr of this.bidiInsertedPtrs)
+ m.FPDFPage_RemoveObject(page.pagePtr, ptr);
+ this.bidiInsertedPtrs = null;
+ if (this.editSnapshot && this.putOriginalObjectsBack(m, page))
+ restoreRunModel(run, this.editSnapshot);
+ run.text = this.prevText;
+ run.dirty = true;
+ page.markDirty();
+ page.markNeedsGenerate();
+ return;
+ }
+
// Paragraph line add/remove revert: move matched lines back to their
// original baselines, drop the freshly-emitted new/changed lines.
if (this.lineEdit) {
@@ -718,9 +1331,16 @@ export class EditTextCommand implements Command {
}
}
restoreRunModel(run, this.lineEdit.prev);
- if (this.lineEdit.removed.length > 0) {
+ const putBack = this.lineEdit.removed.flatMap(
+ (rem) => rem.detached ?? [],
+ );
+ for (const { ptr } of putBack) m.FPDFPage_InsertObject(page.pagePtr, ptr);
+ if (putBack.length > 0) restoreContentOrder(m, page.pagePtr, putBack);
+ const lost = this.lineEdit.removed.filter((rem) => !rem.detached);
+ this.revertedExactly = lost.length === 0;
+ if (lost.length > 0) {
const fallbackFamily = fallbackFamilyFor(this.prevFontId ?? run.fontId);
- for (const rem of this.lineEdit.removed) {
+ for (const rem of lost) {
const ptrs = emitTextLine({
doc,
page,
@@ -760,6 +1380,26 @@ export class EditTextCommand implements Command {
}
}
this.paragraphInsertedPtrs = [];
+ if (this.editSnapshot && this.putOriginalObjectsBack(m, page)) {
+ for (const entry of this.paragraphPlan.perSlot) {
+ const prevSlot = this.prevParagraphSlots[entry.slotIdx];
+ for (const op of entry.plan?.ops ?? [])
+ if (op.type === "modify" && op.subRunIdx !== undefined)
+ setObjText(
+ doc,
+ page,
+ prevSlot.mergedFromPtrs[op.subRunIdx],
+ prevSlot.mergedFromTexts[op.subRunIdx] ?? "",
+ );
+ }
+ restoreRunModel(run, this.editSnapshot);
+ run.text = this.prevText;
+ run.dirty = true;
+ this.paragraphPlan = null;
+ page.markDirty();
+ page.markNeedsGenerate();
+ return;
+ }
// Pure-insert edit (no original object freed/mutated): every original
// object is still alive, so restore the exact pre-edit model.
const pureInsert = this.paragraphPlan.perSlot.every(
@@ -785,7 +1425,8 @@ export class EditTextCommand implements Command {
for (const op of entry.plan.ops) {
if (op.type === "modify" && op.subRunIdx !== undefined) {
setObjText(
- m,
+ doc,
+ page,
prevSlot.mergedFromPtrs[op.subRunIdx],
prevSlot.mergedFromTexts[op.subRunIdx] ?? "",
);
@@ -830,7 +1471,16 @@ export class EditTextCommand implements Command {
// Partial-edit fast path revert: the removed sub-objects are gone from
// PDFium permanently.
if (this.partialPlan) {
- for (const ptr of this.partialInsertedPtrs) {
+ const inserted = withGained(
+ m,
+ page,
+ run,
+ this.partialInsertedPtrs,
+ this.editSnapshot,
+ new Set(this.partialPlan.removePtrs.map((r) => r.ptr)),
+ );
+ const redo = this.capturePartialRedo(m, page, run, inserted);
+ for (const ptr of inserted) {
if (!ptr) continue;
try {
m.FPDFPage_RemoveObject(page.pagePtr, ptr);
@@ -844,7 +1494,8 @@ export class EditTextCommand implements Command {
for (const op of this.partialPlan.ops) {
if (op.type === "modify" && op.subRunIdx !== undefined) {
setObjText(
- m,
+ doc,
+ page,
this.prevMergedFromPtrs[op.subRunIdx],
this.prevMergedFromTexts[op.subRunIdx] ?? "",
);
@@ -852,17 +1503,46 @@ export class EditTextCommand implements Command {
}
// No original objects were destroyed: restore the EXACT pre-edit model so
// undo keeps the original embedded fonts AND redo re-engages the.
- if (this.partialPlan.removePtrs.length === 0 && this.editSnapshot) {
+ if (this.editSnapshot && this.putOriginalObjectsBack(m, page)) {
restoreRunModel(run, this.editSnapshot);
run.text = this.prevText;
run.dirty = true;
this.partialPlan = null;
+ this.partialRedo = redo;
page.markDirty();
page.markNeedsGenerate();
return;
}
const revertFallback = fallbackFamilyFor(this.prevFontId ?? run.fontId);
const removed = new Set(this.partialPlan.removePtrs.map((r) => r.ptr));
+ const snap = this.editSnapshot;
+ const replacements =
+ snap && run.containerPtr === 0
+ ? revertPartialEditPlan(
+ doc,
+ page,
+ run,
+ this.partialPlan,
+ {
+ fonts: this.prevMergedFromFonts,
+ fills: this.prevMergedFromFills,
+ charStarts: snap.mergedFromCharStarts,
+ baselineY: snap.matrixF,
+ fontSubset: snap.fontSubset,
+ },
+ (start, end) => this.prevTagsOf(run, start, end),
+ revertFallback,
+ )
+ : null;
+ if (snap && replacements) {
+ restoreRunModelReplacing(run, snap, replacements);
+ run.text = this.prevText;
+ run.dirty = true;
+ this.partialPlan = null;
+ page.markDirty();
+ page.markNeedsGenerate();
+ return;
+ }
this.rebuildAsOverlayModel(
doc,
page,
@@ -938,6 +1618,16 @@ export class EditTextCommand implements Command {
}
}
+ if (this.editSnapshot && this.putOriginalObjectsBack(m, page)) {
+ restoreRunModel(run, this.editSnapshot);
+ run.text = this.prevText;
+ run.dirty = true;
+ this.overlaid = false;
+ page.markDirty();
+ page.markNeedsGenerate();
+ return;
+ }
+
// PDFium has no insert-into-form-xobject API, so the truly-original
// pointers (if they lived in a form) are gone forever.
const revertFallback = fallbackFamilyFor(this.prevFontId ?? "");
@@ -987,6 +1677,7 @@ export class EditTextCommand implements Command {
run.paragraphLeafPtrs = allRestoredPtrs;
run.paragraphLeafContainers = allRestoredPtrs.map(() => 0);
run.containerPtr = 0;
+ if (this.editSnapshot) run.bounds = { ...this.editSnapshot.bounds };
run.dirty = true;
this.overlaid = false;
page.markDirty();
@@ -1013,10 +1704,11 @@ export class EditTextCommand implements Command {
const topBaseline = slots[0]?.baselineY ?? run.matrix.f;
const leftX = slots[0]?.matrixE ?? run.matrix.e;
const fallbackFamily = fallbackFamilyFor(this.prevFontId ?? run.fontId);
- // Re-emitted lines keep the run's embedded face. Joining two lines with
- // Delete/Backspace only REMOVES characters, so every glyph the joined line
- // needs already rendered in this font; emitting at base-14 turned the whole
- // line a different typeface. Read before the loop starts mutating.
+ // Re-emitted lines keep the run's embedded face for the words it draws:
+ // emitting at base-14 turned the whole line a different typeface. Letters
+ // typed earlier may have fallen back because the subset lacks them, and
+ // the subset still maps their codes with no outline, so those words keep
+ // the fallback. Read before the loop starts mutating.
const memberPtrs = collectMemberPtrs(run);
const memberTexts =
run.mergedFromTexts.length === memberPtrs.length
@@ -1028,6 +1720,13 @@ export class EditTextCommand implements Command {
(run.pdfiumObjPtr ? safeGetFont(m, run.pdfiumObjPtr) : 0)
: 0;
const match = lineLCS(prevLines, nextLines);
+ const prevText = prevLines.join("\n");
+ const nextText = nextLines.join("\n");
+ const pieces = piecesFromObjects(m, page.pagePtr, memberPtrs, prevText);
+ const spans = pieces
+ ? editedFontSpans(doc, page, pieces, prevText, nextText)
+ : undefined;
+ const spansOfLine = spans && spansByLine(spans, nextText);
this.lineEdit = {
moves: [],
@@ -1100,6 +1799,7 @@ export class EditTextCommand implements Command {
// has a different x per line, and slot 0's x drops it into the
// neighbouring column.
const lineX = slots[i]?.matrixE ?? leftX;
+ const lineSpans = spansOfLine?.[i];
const emittedTexts: string[] = [];
const ptrs = emitTextLine({
outTexts: emittedTexts,
@@ -1109,11 +1809,13 @@ export class EditTextCommand implements Command {
x: lineX,
y,
fontSize: run.fontSize,
- fill: run.fill,
+ fill: lineSpans?.[0]?.fill ?? run.fill,
...inkFromRun(run),
tags: sliceTags(nextTags, cursor, cursor + text.length),
- originalFontPtr: reuseFontPtr,
+ fontSpans: lineSpans,
+ originalFontPtr: lineSpans?.[0]?.fontPtr || reuseFontPtr,
originalFontSubset: run.fontSubset,
+ originalFontForCoveredWords: reuseFontPtr !== 0,
charSpacingPt: run.charSpacingPt,
fallbackFamily,
});
@@ -1142,9 +1844,22 @@ export class EditTextCommand implements Command {
}
// Remove objects of any prev line no next line reused.
+ const dropped = slots.filter((_, j) => !usedPrev.has(j));
+ // Read before any is removed, so every index is a position in the same content.
+ const order = contentIndices(
+ m,
+ page.pagePtr,
+ dropped.flatMap((src) => src.mergedFromPtrs.filter(Boolean)),
+ );
for (let j = 0; j < slots.length; j++) {
if (usedPrev.has(j)) continue;
const src = slots[j];
+ const ptrs = src.mergedFromPtrs.filter(Boolean);
+ const onPage =
+ !src.containerPtr &&
+ !run.containerPtr &&
+ ptrs.length > 0 &&
+ ptrs.every((ptr) => order.has(ptr));
if (prevLines[j]) {
this.lineEdit.removed.push({
text: prevLines[j],
@@ -1152,6 +1867,9 @@ export class EditTextCommand implements Command {
x: src.mergedFromBounds[0]?.x ?? src.matrixE,
y: src.baselineY,
fontSize: src.fontSize,
+ detached: onPage
+ ? ptrs.map((ptr) => ({ ptr, index: order.get(ptr)! }))
+ : null,
});
}
for (const ptr of src.mergedFromPtrs) {
@@ -1359,6 +2077,8 @@ export class EditTextCommand implements Command {
});
slotLive.push(...ptrs);
} else if (sr.ptr) {
+ // Move what the edit shifted back beside the redrawn pieces.
+ if (run.containerPtr === 0) moveObjectLeftEdgeTo(m, sr.ptr, sr.x);
slotLive.push(sr.ptr);
}
}
@@ -1386,8 +2106,137 @@ export class EditTextCommand implements Command {
});
}
- /** Consecutive typing on the SAME run coalesces into one undo step. */
- coalesceKey(): string {
+ /** Undo or redo a burst as one edit: each step's undo names objects a later step replaced. */
+ moveGroup(
+ doc: EditorDocument,
+ group: readonly Command[],
+ phase: "apply" | "revert",
+ ): boolean {
+ if (group.length < 2) return false;
+ const edits: EditTextCommand[] = [];
+ for (const cmd of group) {
+ if (
+ !(cmd instanceof EditTextCommand) ||
+ cmd.pageIndex !== this.pageIndex ||
+ cmd.runId !== this.runId ||
+ cmd.scanEdited
+ )
+ return false;
+ edits.push(cmd);
+ }
+ // Every step puts back exactly the objects the step before it drew, so stepping through keeps each piece's own font and glyphs.
+ if (
+ phase === "revert"
+ ? edits.every((edit) => edit.revertsExactly())
+ : edits.every((edit) => edit.revertedExactly)
+ )
+ return false;
+ const first = edits[0].prevText;
+ const run = doc.page(this.pageIndex).findRun(this.runId);
+ if (first === null || !run || isScanRun(run)) return false;
+ // A later step may have redrawn the run in a fallback; undo goes back to the face the burst started from.
+ const { startFont } = edits[0];
+ const firstFont =
+ startFont && (edits[0].overlaid || run.fontId !== startFont.id)
+ ? startFont
+ : null;
+ const move = new EditTextCommand({
+ pageIndex: this.pageIndex,
+ runId: this.runId,
+ nextText: phase === "revert" ? first : this.nextText,
+ nextTags: phase === "revert" ? edits[0].prevTags : null,
+ nextFont: phase === "revert" ? firstFont : null,
+ pushesBelow: false,
+ });
+ const reversed = [...edits].reverse();
+ if (phase === "revert") for (const edit of reversed) edit.undoPushes(doc);
+ const before = new Set(collectMemberPtrs(run));
+ // Only while the run is still made of exactly what the last replay drew: after any other step, that step may hold these objects.
+ const replaced = this.replayDrawn.every((ptr) => before.has(ptr))
+ ? this.replayDrawn
+ : [];
+ try {
+ move.apply(doc);
+ if (phase === "revert") edits[0].restoreLayout(doc, run);
+ } catch (err) {
+ try {
+ move.revert(doc);
+ if (phase === "revert") for (const edit of edits) edit.redoPushes(doc);
+ } catch {
+ throw err;
+ }
+ throw new RolledBackError(err);
+ }
+ if (phase === "apply") for (const edit of edits) edit.redoPushes(doc);
+ const soft = phase === "revert" ? edits[0].softBefore : this.softAfter;
+ if (soft) setSoftStarts(run, soft);
+ const after = new Set(collectMemberPtrs(run));
+ // The replay command is thrown away, and with it the only record of the objects it took off the page.
+ for (const ptr of replaced)
+ if (ptr && !after.has(ptr)) doc.module.FPDFPageObj_Destroy(ptr);
+ this.replayDrawn = [...after].filter((ptr) => ptr && !before.has(ptr));
+ return true;
+ }
+
+ // The move plans from the burst's shifted pieces; a piece starting where one of this edit's did goes back there, and the pieces after it with it.
+ private restoreLayout(doc: EditorDocument, run: TextRun): void {
+ const snap = this.editSnapshot;
+ if (!snap || run.containerPtr !== 0 || run.text !== snap.text) return;
+ let shift = 0;
+ run.mergedFromBounds = run.mergedFromBounds.map((bounds, i) => {
+ const was = snap.mergedFromCharStarts.indexOf(
+ run.mergedFromCharStarts[i],
+ );
+ const x = snap.mergedFromBounds[was]?.x;
+ if (x !== undefined) shift = x - bounds.x;
+ const ptr = run.mergedFromPtrs[i];
+ if (ptr && shift) moveObjectLeftEdgeTo(doc.module, ptr, bounds.x + shift);
+ return { x: bounds.x + shift, right: bounds.right + shift };
+ });
+ run.bounds = { ...snap.bounds };
+ run.matrix = { ...run.matrix, e: snap.matrixE };
+ }
+
+ repaintArea(doc: EditorDocument): PageRepaintArea | null {
+ if (this.pushes?.length) return null;
+ const run = doc.page(this.pageIndex).findRun(this.runId);
+ // Turned text is typed along its own slant, out of its upright box.
+ if (
+ !run ||
+ Math.abs(run.matrix.b) > UPRIGHT_TOLERANCE ||
+ Math.abs(run.matrix.c) > UPRIGHT_TOLERANCE
+ )
+ return null;
+ // Covers what a scanned edit paints around its words: covers, softened edges, i-dots.
+ const margin = Math.max(
+ MIN_REPAINT_MARGIN_PT,
+ run.fontSize * REPAINT_MARGIN_PER_FONT_SIZE,
+ );
+ const { x, y, width, height } = run.bounds;
+ const scan = isScanRun(run);
+ // A scanned edit moves the scan's own words, which can land past the run's box.
+ const [left, right] = scan
+ ? [-PAGE_SPAN_PT, PAGE_SPAN_PT]
+ : [x - margin, x + width + margin];
+ // Lines a scanned edit adds or drops sit below the run's one-line box.
+ const drawn =
+ scan && run.scanEdit
+ ? measureObjBoundsPt(doc.module, [
+ ...run.scanEdit.created,
+ ...run.scanEdit.textPtrs,
+ ])
+ : null;
+ const bottom = Math.min(y, drawn?.bottom ?? y) - margin;
+ const top = Math.max(y + height, drawn?.top ?? y + height) + margin;
+ return {
+ pageIndex: this.pageIndex,
+ area: { x: left, y: bottom, width: right - left, height: top - bottom },
+ };
+ }
+
+ /** Consecutive typing on the SAME run coalesces into one undo step; an `explicit` edit (a resize) is always its own. */
+ coalesceKey(): string | null {
+ if (this.explicit) return null;
return `edit-text:${this.pageIndex}:${this.runId}`;
}
@@ -1426,6 +2275,10 @@ export class EditTextCommand implements Command {
}
}
+function lineCount(text: string): number {
+ return text.split(/\r?\n/).length;
+}
+
// The text `next` adds to `prev` when the change is a pure insertion at a
// single point, or null when it is anything else.
function insertedChunk(prev: string, next: string): string | null {
@@ -1445,6 +2298,12 @@ function insertedChunk(prev: string, next: string): string | null {
}
/** Keep a run's model width from claiming space past the page's right edge. */
+// What `prev` and `next` share before and after the one stretch that differs.
+function keptText(prev: string, next: string): string {
+ const { start, prevEnd } = diffSpan(prev, next);
+ return prev.slice(0, start) + prev.slice(prevEnd);
+}
+
function clampWidthToPage(x: number, width: number, page: Page): number {
// x/width are RAW PDF space, so the right edge is the CropBox right edge in
// raw space.
@@ -1453,10 +2312,7 @@ function clampWidthToPage(x: number, width: number, page: Page): number {
return Math.min(width, maxWidth);
}
-function safeGetFont(
- m: import("@embedpdf/pdfium").WrappedPdfiumModule,
- objPtr: number,
-): number {
+function safeGetFont(m: WrappedPdfiumModule, objPtr: number): number {
const fn = (m as unknown as { FPDFTextObj_GetFont?: (p: number) => number })
.FPDFTextObj_GetFont;
if (!fn) return 0;
@@ -1468,7 +2324,7 @@ function safeGetFont(
}
function snapshotRevertLines(
- run: import("@editor/tools/pdfTextEditor/model/TextRun").TextRun,
+ run: TextRun,
prevText: string,
prevTags: TextTags,
): RevertLine[] {
@@ -1486,10 +2342,39 @@ function snapshotRevertLines(
}));
}
+// The face and fill each stretch of an edited run's text came from; undefined for a run drawn in one of each.
+function editedFontSpans(
+ doc: EditorDocument,
+ page: Page,
+ pieces: Parameters<typeof sourceFontSpans>[1],
+ prevText: string,
+ nextText: string,
+): FontSpan[] | undefined {
+ const m = doc.module;
+ return sourceFontSpans(m, pieces, prevText, nextText, (font, text) =>
+ charcodesResolveFully(m, font, text, page.pagePtr, doc.docPtr),
+ )?.map((span) => ({
+ ...span,
+ fallbackFamily: deviceFamilyOf(doc, span.fontPtr) ?? span.fallbackFamily,
+ }));
+}
+
+/** `spans`, which run the length of `text`, cut into the spans of each of its lines. */
+function spansByLine(spans: readonly FontSpan[], text: string): FontSpan[][] {
+ const lines: FontSpan[][] = [];
+ let start = 0;
+ for (const line of text.split(/\r?\n/)) {
+ const at = text.indexOf(line, start);
+ lines.push(sliceFontSpans(spans, at, at + line.length));
+ start = at + line.length;
+ }
+ return lines;
+}
+
// Reconstruct `paragraphLineSlots` from the data the overlay loop just emitted.
function buildSlotsFromOverlayEmit(
- m: import("@embedpdf/pdfium").WrappedPdfiumModule,
- run: import("@editor/tools/pdfTextEditor/model/TextRun").TextRun,
+ m: WrappedPdfiumModule,
+ run: TextRun,
perLineEmits: Array<{
ptrs: number[];
texts: string[];
@@ -1498,7 +2383,7 @@ function buildSlotsFromOverlayEmit(
y: number;
}>,
fontId: string,
-): import("@editor/tools/pdfTextEditor/model/TextRun").ParagraphLineSlot[] {
+): ParagraphLineSlot[] {
const slots = [];
let cursor = 0;
for (const emit of perLineEmits) {
@@ -1595,7 +2480,7 @@ function buildSlotsFromOverlayEmit(
}
function boundsFromPtr(
- m: import("@embedpdf/pdfium").WrappedPdfiumModule,
+ m: WrappedPdfiumModule,
ptr: number,
fallbackX: number,
): { x: number; right: number } {
@@ -1731,7 +2616,7 @@ function sliceLineAcrossPtrs(
}
function buildSlotForLine(
- m: import("@embedpdf/pdfium").WrappedPdfiumModule,
+ m: WrappedPdfiumModule,
ptrs: number[],
text: string,
baselineY: number,
@@ -1792,6 +2677,56 @@ function snapshotRunModel(run: TextRun): RunModelSnapshot {
};
}
+interface OriginalObjects {
+ detached: number[];
+ matrices: Map<number, Float32Array>;
+ order: Map<number, number>;
+}
+
+/** What a partial apply left on the page, so its redo can put the same objects back. */
+interface PartialRedo {
+ plan: PartialEditPlan;
+ originals: OriginalObjects;
+ /** Drawn by the apply; detached while undone. */
+ inserted: number[];
+ /** The run's objects before the apply that it took off the page. */
+ detach: number[];
+ /** Objects the apply kept but gave new text. */
+ modified: Array<{ ptr: number; text: string }>;
+ matrices: Map<number, Float32Array>;
+ order: Map<number, number>;
+ model: RunModelSnapshot;
+}
+
+function captureOriginalObjects(
+ m: WrappedPdfiumModule,
+ run: TextRun,
+ ptrs: readonly number[],
+ removed: ReadonlyArray<{ ptr: number; containerPtr: number }>,
+ pagePtr: number,
+): OriginalObjects | null {
+ if (run.containerPtr !== 0) return null;
+ const inForm = new Set(
+ run.paragraphLeafPtrs.filter((_, i) => run.paragraphLeafContainers[i]),
+ );
+ if (
+ removed.some(({ ptr, containerPtr }) => containerPtr > 0 || inForm.has(ptr))
+ )
+ return null;
+ const matrices = new Map<number, Float32Array>();
+ for (const ptr of ptrs) {
+ if (!ptr) continue;
+ const matrix = readMatrix(m, ptr);
+ if (!matrix) return null;
+ matrices.set(ptr, matrix);
+ }
+ return {
+ detached: [...new Set(removed.map(({ ptr }) => ptr).filter(Boolean))],
+ matrices,
+ order: contentIndices(m, pagePtr, matrices.keys()),
+ };
+}
+
function restoreRunModel(run: TextRun, snap: RunModelSnapshot): void {
run.matrix = { ...run.matrix, e: snap.matrixE, f: snap.matrixF };
run.bounds = { ...snap.bounds };
@@ -1811,6 +2746,22 @@ function restoreRunModel(run: TextRun, snap: RunModelSnapshot): void {
run.pdfiumObjPtr = snap.pdfiumObjPtr;
}
+function restoreRunModelReplacing(
+ run: TextRun,
+ snap: RunModelSnapshot,
+ replacements: Map<number, number>,
+): void {
+ const swapped = (list: number[]) =>
+ list.map((ptr) => replacements.get(ptr) ?? ptr);
+ restoreRunModel(run, snap);
+ run.mergedFromPtrs = swapped(run.mergedFromPtrs);
+ run.paragraphLeafPtrs = swapped(run.paragraphLeafPtrs);
+ run.paragraphMemberPtrs = swapped(run.paragraphMemberPtrs);
+ for (const slot of run.paragraphLineSlots)
+ slot.mergedFromPtrs = swapped(slot.mergedFromPtrs);
+ run.pdfiumObjPtr = replacements.get(run.pdfiumObjPtr) ?? run.pdfiumObjPtr;
+}
+
/** LCS over lines: maps next-line index -> matched prev-line index. */
function lineLCS(a: string[], b: string[]): Map<number, number> {
const m = a.length;
@@ -1858,7 +2809,7 @@ function reflattenLeafArrays(run: TextRun): void {
/** Replace a restored slot (matched by baseline) with re-emitted objects. */
function patchSlotPtrsByBaseline(
- m: import("@embedpdf/pdfium").WrappedPdfiumModule,
+ m: WrappedPdfiumModule,
run: TextRun,
baselineY: number,
ptrs: number[],
@@ -1882,3 +2833,17 @@ function patchSlotPtrsByBaseline(
rebuilt.endChar = old.endChar;
run.paragraphLineSlots[idx] = rebuilt;
}
+
+interface SoftStarts {
+ flags: boolean[];
+ text: string;
+}
+
+function softStartsNow(run: TextRun): SoftStarts {
+ return { flags: softStartsOf(run), text: run.text };
+}
+
+function setSoftStarts(run: TextRun, soft: SoftStarts): void {
+ run.paragraphSoftStarts = [...soft.flags];
+ run.paragraphSoftStartsText = soft.text;
+}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/commands/InsertImageCommand.ts b/frontend/src/editor/core/tools/pdfTextEditor/commands/InsertImageCommand.ts
index 4d1cba8add..a186ad0a49 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/commands/InsertImageCommand.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/commands/InsertImageCommand.ts
@@ -1,7 +1,9 @@
import type { Command } from "@editor/tools/pdfTextEditor/commands/Command";
import type { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
import { ImageObject } from "@editor/tools/pdfTextEditor/model/ImageObject";
-import type { Affine } from "@editor/tools/pdfTextEditor/types";
+import type { Affine, PageRect } from "@editor/tools/pdfTextEditor/types";
+import type { DisplayTransformData } from "@editor/tools/pdfTextEditor/model/DisplayTransform";
+import { DisplayTransform } from "@editor/tools/pdfTextEditor/model/DisplayTransform";
import type { WrappedPdfiumModule } from "@embedpdf/pdfium";
import {
counterPageRotation,
@@ -17,6 +19,31 @@ import {
scratchPtr,
} from "@editor/tools/pdfTextEditor/util/wasmScratch";
+/**
+ * Raw-space rectangle for a new image that shows upright, centred on the
+ * visible page and no wider than `widthRatio` of it nor taller than it.
+ * InsertImageCommand counter-rotates this rectangle about its centre, so the
+ * centre is what has to map to the middle of the visible page.
+ */
+export function centredImageRect(
+ display: DisplayTransformData,
+ pixelWidth: number,
+ pixelHeight: number,
+ widthRatio: number,
+): PageRect {
+ const scale = Math.min(
+ (display.displayWidth * widthRatio) / pixelWidth,
+ display.displayHeight / pixelHeight,
+ );
+ const width = pixelWidth * scale;
+ const height = pixelHeight * scale;
+ const centre = DisplayTransform.fromData(display).invert(
+ display.displayWidth / 2,
+ display.displayHeight / 2,
+ );
+ return { x: centre.x - width / 2, y: centre.y - height / 2, width, height };
+}
+
// Insert a decoded raster image onto a page at the given lower-left coordinate,
// scaled to `(width, height)` PDF points.
export class InsertImageCommand implements Command {
@@ -33,8 +60,8 @@ export class InsertImageCommand implements Command {
private readonly jpegBytes?: Uint8Array;
private createdImageId: string | null;
private createdObjPtr: number;
- /** Matrix written on first embed; reused so redo re-inserts the same object. */
- private appliedMatrix: Affine | null;
+ /** Matrix and bounds from the first embed; redo restores both unchanged. */
+ private applied: { matrix: Affine; bounds: PageRect } | null;
constructor(opts: {
pageIndex: number;
@@ -58,7 +85,7 @@ export class InsertImageCommand implements Command {
this.jpegBytes = opts.jpegBytes;
this.createdImageId = null;
this.createdObjPtr = 0;
- this.appliedMatrix = null;
+ this.applied = null;
}
get insertedImageId(): string | null {
@@ -72,25 +99,13 @@ export class InsertImageCommand implements Command {
// The object was only detached (not destroyed), so this is safe and leak-free.
if (this.createdObjPtr) {
m.FPDFPage_InsertObject(page.pagePtr, this.createdObjPtr);
- if (this.createdImageId) {
+ if (this.createdImageId && this.applied) {
const restored = new ImageObject({
id: this.createdImageId,
pageIndex: page.index,
pdfiumObjPtr: this.createdObjPtr,
- bounds: {
- x: this.x,
- y: this.y,
- width: this.width,
- height: this.height,
- },
- matrix: this.appliedMatrix ?? {
- a: this.width,
- b: 0,
- c: 0,
- d: this.height,
- e: this.x,
- f: this.y,
- },
+ bounds: { ...this.applied.bounds },
+ matrix: { ...this.applied.matrix },
});
page.setImages([...page.images, restored]);
}
@@ -149,23 +164,19 @@ export class InsertImageCommand implements Command {
e: this.x,
f: this.y,
};
- this.appliedMatrix = matrix;
+ // On a /Rotate page the counter-rotated object's real AABB has swapped
+ // width/height vs the pre-rotation rect.
+ const bounds: PageRect = rot
+ ? imageMatrixBounds(matrix)
+ : { x: this.x, y: this.y, width: this.width, height: this.height };
+ this.applied = { matrix, bounds };
const imageId = `p${page.index}-new-img-${page.images.length}-${newObjPtr}`;
const created = new ImageObject({
id: imageId,
pageIndex: page.index,
pdfiumObjPtr: newObjPtr,
- // On a /Rotate page the counter-rotated object's real AABB has swapped
- // width/height vs the pre-rotation rect.
- bounds: rot
- ? imageMatrixBounds(matrix)
- : {
- x: this.x,
- y: this.y,
- width: this.width,
- height: this.height,
- },
- matrix,
+ bounds: { ...bounds },
+ matrix: { ...matrix },
});
page.setImages([...page.images, created]);
page.markDirty();
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/commands/InsertTextCommand.ts b/frontend/src/editor/core/tools/pdfTextEditor/commands/InsertTextCommand.ts
index 1e5c93604d..a96aa1677c 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/commands/InsertTextCommand.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/commands/InsertTextCommand.ts
@@ -94,7 +94,9 @@ export class InsertTextCommand implements Command {
}
: { a: 1, b: 0, c: 0, d: 1, e: this.x, f: this.y };
- const runId = `p${page.index}-new-${page.runs.length}-${objPtr}`;
+ // Kept across redo: later steps that edit this text find it by this id.
+ const runId =
+ this.createdRunId ?? `p${page.index}-new-${page.runs.length}-${objPtr}`;
const run = new TextRun({
id: runId,
pageIndex: page.index,
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/commands/MaterialiseTableCommand.ts b/frontend/src/editor/core/tools/pdfTextEditor/commands/MaterialiseTableCommand.ts
index f4b44ff090..75ecf4ef11 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/commands/MaterialiseTableCommand.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/commands/MaterialiseTableCommand.ts
@@ -4,6 +4,7 @@ import {
type Command,
} from "@editor/tools/pdfTextEditor/commands/Command";
import type { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
+import { insertPageObjectAt } from "@editor/tools/pdfTextEditor/util/insertPageObject";
import type { Page } from "@editor/tools/pdfTextEditor/model/Page";
import type { TextRun } from "@editor/tools/pdfTextEditor/model/TextRun";
import type {
@@ -15,6 +16,7 @@ import type { ScanColors } from "@editor/tools/pdfTextEditor/util/scanSampling";
import {
measureObjBoxPt,
measureObjSpanPt,
+ sanitizeForBase14,
} from "@editor/tools/pdfTextEditor/commands/editTextHelpers";
import {
emitCellText,
@@ -136,14 +138,13 @@ export class MaterialiseTableCommand implements Command {
const found = locateTable(doc, this.tableId);
if (!found) return;
const { page, model } = found;
- const mod = doc.module as unknown as ZOrderModule;
if (this.emittedPtrs.length > 0) {
removeObjects(doc.module, page, this.emittedPtrs);
this.emittedPtrs = [];
}
// Lowest index last, so each form lands back where it was taken from.
for (const { ptr, index } of [...this.droppedForms].reverse()) {
- mod.FPDFPage_InsertObjectAtIndex?.(page.pagePtr, ptr, index);
+ insertPageObjectAt(doc.module, page.pagePtr, ptr, index);
}
this.droppedForms = [];
if (this.paintedPtrs.length > 0) {
@@ -230,7 +231,16 @@ export class MaterialiseTableCommand implements Command {
const target = this.placeOf(doc, run);
if (!target || target.width <= 0 || target.height <= 0) return null;
const nominal = Math.min(72, Math.max(4, target.height / CAP_RATIO));
- const emitted = emitCellText(doc, page, 0, 0, run.text, nominal, ink);
+ // Only what the standard fonts encode: text with any other character would be refused whole, and the cell left blank.
+ const emitted = emitCellText(
+ doc,
+ page,
+ 0,
+ 0,
+ sanitizeForBase14(run.text),
+ nominal,
+ ink,
+ );
if (!emitted) return null;
this.emittedPtrs.push(emitted.ptr);
const box = measureObjBoxPt(doc.module, emitted.ptr);
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/commands/MergeRunsCommand.ts b/frontend/src/editor/core/tools/pdfTextEditor/commands/MergeRunsCommand.ts
index e2749e4149..346dcc3173 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/commands/MergeRunsCommand.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/commands/MergeRunsCommand.ts
@@ -1,3 +1,8 @@
+import {
+ assertLiftable,
+ liftRunToPage,
+} from "@editor/tools/pdfTextEditor/commands/liftFromForm";
+import { refuseRedrawOfReadOnlyText } from "@editor/tools/pdfTextEditor/commands/readOnlyText";
import i18n from "i18next";
import type { Command } from "@editor/tools/pdfTextEditor/commands/Command";
import type { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
@@ -58,6 +63,10 @@ export class MergeRunsCommand implements Command {
.map((id) => page.findRun(id))
.filter((r): r is TextRun => !!r);
if (runs.length < 2) return;
+ // The merged paragraph is edited as one run, which would redraw the line with it.
+ for (const run of runs) refuseRedrawOfReadOnlyText(run);
+ assertLiftable(doc, page, runs);
+ for (const run of runs) liftRunToPage(doc, page, run);
runs.sort((a, b) => b.matrix.f - a.matrix.f);
const rep = runs[0];
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/commands/ModifyTableCommand.ts b/frontend/src/editor/core/tools/pdfTextEditor/commands/ModifyTableCommand.ts
index 7cdf63274c..50f5ee37b0 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/commands/ModifyTableCommand.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/commands/ModifyTableCommand.ts
@@ -1,3 +1,4 @@
+import { liftRunToPage } from "@editor/tools/pdfTextEditor/commands/liftFromForm";
import { locateTable } from "@editor/tools/pdfTextEditor/util/locateTable";
import type { Command } from "@editor/tools/pdfTextEditor/commands/Command";
import type { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
@@ -14,6 +15,7 @@ import {
} from "@editor/tools/pdfTextEditor/util/tableGeometry";
import {
bandColorFor,
+ assertTableLiftable,
paintRowFill,
redrawGrid,
removeObjects,
@@ -58,6 +60,7 @@ export class ModifyTableCommand implements Command {
const found = locateTable(doc, this.tableId);
if (!found) return;
const { page, model } = found;
+ assertTableLiftable(doc, page, model);
const isRow = this.op.endsWith("row");
const count = isRow ? model.rows : model.cols;
const adding = this.op.startsWith("add");
@@ -371,7 +374,9 @@ export class ModifyTableCommand implements Command {
if (!pred(r, c)) continue;
for (const id of model.runsAt(r, c)) {
const run = page.findRun(id);
- if (run) shiftRunBy(doc.module, run, dx, dy);
+ if (!run) continue;
+ liftRunToPage(doc, page, run);
+ shiftRunBy(doc.module, run, dx, dy);
}
}
}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/commands/MoveTextRunCommand.ts b/frontend/src/editor/core/tools/pdfTextEditor/commands/MoveTextRunCommand.ts
index 6667ebaba6..955cf2be67 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/commands/MoveTextRunCommand.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/commands/MoveTextRunCommand.ts
@@ -1,3 +1,5 @@
+import type { TextRun } from "@editor/tools/pdfTextEditor/model/TextRun";
+import { liftRunToPage } from "@editor/tools/pdfTextEditor/commands/liftFromForm";
import type { Command } from "@editor/tools/pdfTextEditor/commands/Command";
import type { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
import { collectMemberPtrs } from "@editor/tools/pdfTextEditor/commands/editTextHelpers";
@@ -11,9 +13,9 @@ import {
export class MoveTextRunCommand implements Command {
readonly type = "move-text-run";
private readonly pageIndex: number;
- private readonly runId: string;
+ readonly runId: string;
private readonly dx: number;
- private readonly dy: number;
+ readonly dy: number;
private appliedPtrs: number[];
/** Set when the run was scanned text, moved by redrawing it. */
private scanPrev: ScanOverride | null = null;
@@ -35,6 +37,7 @@ export class MoveTextRunCommand implements Command {
const page = doc.page(this.pageIndex);
const run = page.findRun(this.runId);
if (!run) return;
+ liftRunToPage(doc, page, run);
// Scanned words are pixels: cover them where they were, draw them anew.
const scanPrev = setScanOverride(doc, page, run, (o) => ({
...o,
@@ -96,11 +99,7 @@ export class MoveTextRunCommand implements Command {
}
/** Shift the run's matrix/bounds + per-line + sub-run model by (dx, dy). */
- private shiftModel(
- run: import("@editor/tools/pdfTextEditor/model/TextRun").TextRun,
- dx: number,
- dy: number,
- ): void {
+ private shiftModel(run: TextRun, dx: number, dy: number): void {
run.matrix = { ...run.matrix, e: run.matrix.e + dx, f: run.matrix.f + dy };
run.bounds = { ...run.bounds, x: run.bounds.x + dx, y: run.bounds.y + dy };
if (run.paragraphMemberFs.length > 0) {
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/commands/ReflowWrapCommand.ts b/frontend/src/editor/core/tools/pdfTextEditor/commands/ReflowWrapCommand.ts
index 332f474fa0..344f48b523 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/commands/ReflowWrapCommand.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/commands/ReflowWrapCommand.ts
@@ -1,7 +1,13 @@
+import { liftRunToPage } from "@editor/tools/pdfTextEditor/commands/liftFromForm";
+import { refuseRedrawOfReadOnlyText } from "@editor/tools/pdfTextEditor/commands/readOnlyText";
import { drawnText } from "@editor/tools/pdfTextEditor/pdfium/lineEndHyphen";
+import { softStartsOf } from "@editor/tools/pdfTextEditor/pdfium/lineBreaks";
import i18n from "i18next";
import type { Command } from "@editor/tools/pdfTextEditor/commands/Command";
import type { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
+import type { Page } from "@editor/tools/pdfTextEditor/model/Page";
+import type { PageRect } from "@editor/tools/pdfTextEditor/types";
+import { overlaps } from "@editor/tools/pdfTextEditor/util/tableAdoption";
import type {
ParagraphLineSlot,
TextRun,
@@ -11,10 +17,19 @@ import { readUtf16 } from "@editor/services/pdfiumService";
import { rotationFromMatrix } from "@editor/tools/pdfTextEditor/commands/editTextHelpers";
import { transformObject } from "@editor/tools/pdfTextEditor/util/objectTransform";
import { isScanRun } from "@editor/tools/pdfTextEditor/commands/scanTextEdit";
+import { needsShaping } from "@editor/tools/pdfTextEditor/util/complexShaping";
import {
SCRATCH,
scratchPtr,
} from "@editor/tools/pdfTextEditor/util/wasmScratch";
+import { MoveTextRunCommand } from "@editor/tools/pdfTextEditor/commands/MoveTextRunCommand";
+import {
+ type PushRecord,
+ pushRecords,
+ runsPulledBack,
+ runsPushedBelow,
+ setPushRecords,
+} from "@editor/tools/pdfTextEditor/commands/pushRunsBelow";
import {
endsWithSpace,
groupWords,
@@ -54,6 +69,7 @@ interface RunSnapshot {
paragraphLeafContainers: number[];
paragraphLineSlots: ParagraphLineSlot[];
paragraphSoftStarts: boolean[];
+ paragraphSoftStartsText: string;
mergedFromPtrs: number[];
mergedFromTexts: string[];
mergedFromBounds: Array<{ x: number; right: number }>;
@@ -68,30 +84,50 @@ export class ReflowWrapCommand implements Command {
private readonly runId: string;
private readonly maxWidthPt: number;
private readonly explicit: boolean;
+ private readonly keepClearBelow: boolean;
private applied = false;
+ private refused = false;
/** Per-object translation applied, so revert can undo it exactly. */
private moves: Array<{ ptr: number; dx: number; dy: number }> = [];
private prev: RunSnapshot | null = null;
+ // The runs below the lines this reflow added or removed moved, chosen on the first apply so a redo moves the same ones.
+ private pushes: MoveTextRunCommand[] | null = null;
+ private pushRecords: {
+ before: readonly PushRecord[];
+ after: readonly PushRecord[];
+ } | null = null;
/**
* `explicit` marks a width the user set directly (resize handle, width
* field): the paragraph re-lines even when nothing overflows, so widening
* rejoins lines an earlier wrap broke, and it is its own undo step rather
* than part of the typing burst.
+ *
+ * `keepClearBelow` leaves the run as it was when the lines the wrap adds
+ * would land on something the push cannot move out of the way: a line,
+ * fill, shape or image, or text that is locked, rotated, scanned, in a
+ * table or would leave the page. `refusedForSpaceBelow` then reads true.
*/
constructor(opts: {
pageIndex: number;
runId: string;
maxWidthPt: number;
explicit?: boolean;
+ keepClearBelow?: boolean;
}) {
this.pageIndex = opts.pageIndex;
this.runId = opts.runId;
this.maxWidthPt = opts.maxWidthPt;
this.explicit = opts.explicit ?? false;
+ this.keepClearBelow = opts.keepClearBelow ?? false;
+ }
+
+ get refusedForSpaceBelow(): boolean {
+ return this.refused;
}
apply(doc: EditorDocument): void {
+ if (this.refused) return;
const page = doc.page(this.pageIndex);
const run = page.findRun(this.runId);
if (!run || isScanRun(run)) return;
@@ -99,6 +135,12 @@ export class ReflowWrapCommand implements Command {
// Reflow math is axis-aligned (advance +x, step -y); a rotated run reads
// along a rotated axis, so skip rather than scatter glyphs.
if (rotationFromMatrix(run.matrix)) return;
+ // An edit to one line of a wrapped run redraws the letters left on that
+ // line, which text that needs shaping refuses, so a wrap the user did not
+ // ask for would block every later edit to the line.
+ if (!this.explicit && needsShaping(run.text)) return;
+ refuseRedrawOfReadOnlyText(run);
+ liftRunToPage(doc, page, run);
const m = doc.module;
// Geometry + text must reflect the latest edits, and FPDFTextObj_GetText
@@ -112,6 +154,10 @@ export class ReflowWrapCommand implements Command {
m.FPDFText_ClosePage(textPage);
}
if (leaves.length === 0) return;
+ // The reflow lines objects up left to right and rebuilds the text in that
+ // order. A line that does not read in that order, such as right-to-left
+ // text or marks drawn apart from their letters, would come back scrambled.
+ if (!readsInObjectOrder(leaves, run.text)) return;
const fontSize = run.fontSize > 0 ? run.fontSize : 12;
const lineHeight =
@@ -173,8 +219,7 @@ export class ReflowWrapCommand implements Command {
if (carried) return Math.max(0, gap);
return gap > 0 ? gap : spaceWidth;
};
- // Manual line breaks the user typed (Enter) live in run.text as "\n".
- const hardBreaks = hardBreakNonWsCounts(run.text, run.paragraphSoftStarts);
+ const hardBreaks = hardBreakNonWsCounts(run.text, softStartsOf(run));
this.prev = snapshotRun(run);
@@ -268,6 +313,82 @@ export class ReflowWrapCommand implements Command {
page.markDirty();
page.markNeedsGenerate();
this.applied = true;
+ const deciding = this.pushes === null;
+ if (deciding) this.decidePushes(page, run, this.prev);
+ for (const push of this.pushes ?? []) push.apply(doc);
+ if (this.pushRecords) setPushRecords(run, this.pushRecords.after);
+ if (deciding && this.keepClearBelow && this.landsOnUnmoved(page, run)) {
+ this.revert(doc);
+ this.pushes = [];
+ this.pushRecords = null;
+ this.refused = true;
+ }
+ }
+
+ // What the added lines now cover that was clear of the run before and did not move out of their way.
+ private landsOnUnmoved(page: Page, run: TextRun): boolean {
+ const prev = this.prev;
+ if (!prev) return false;
+ const added = {
+ x: run.bounds.x,
+ y: run.bounds.y,
+ width: run.bounds.width,
+ height: prev.bounds.y - run.bounds.y,
+ };
+ if (added.height <= 0) return false;
+ const covers = (r: PageRect) =>
+ overlaps(r, added) && !overlaps(r, prev.bounds);
+ // Text is allowed the slack runsPushedBelow gives it: lines set tighter than their boxes already overlap a little.
+ const slack = run.fontSize * TEXT_OVERLAP_EM;
+ const textBand = {
+ ...added,
+ y: added.y + slack,
+ height: added.height - slack,
+ };
+ const moved = new Set(this.pushes?.map((p) => p.runId) ?? []);
+ const textHit = page.runs.some(
+ (r) =>
+ r !== run &&
+ !moved.has(r.id) &&
+ textBand.height > 0 &&
+ overlaps(r.bounds, textBand) &&
+ !overlaps(r.bounds, prev.bounds),
+ );
+ return (
+ textHit ||
+ page.rules.some(covers) ||
+ page.fills.some(covers) ||
+ page.shapes.some((s) => covers(s.bounds)) ||
+ page.images.some((i) => covers(i.bounds))
+ );
+ }
+
+ // The same room-making EditTextCommand gives lines typed with Enter: lines a wrap adds cover the text below just the same.
+ private decidePushes(page: Page, run: TextRun, prev: RunSnapshot): void {
+ const lines = lineCount(run.text) - lineCount(prev.text);
+ const move = (runId: string, dy: number) =>
+ new MoveTextRunCommand({ pageIndex: this.pageIndex, runId, dx: 0, dy });
+ if (lines > 0) {
+ const { runIds, dy } = runsPushedBelow(
+ page,
+ run,
+ prev.bounds.y,
+ lines * run.paragraphLineHeight,
+ );
+ this.pushes = runIds.map((runId) => move(runId, dy));
+ if (runIds.length > 0)
+ this.pushRecords = {
+ before: pushRecords(run),
+ after: [
+ ...pushRecords(run),
+ { lineCount: lineCount(run.text), linesAdded: lines, runIds, dy },
+ ],
+ };
+ } else if (lines < 0) {
+ const { moves, records } = runsPulledBack(page, run, lineCount(run.text));
+ this.pushes = moves.map(({ runId, dy }) => move(runId, dy));
+ this.pushRecords = { before: pushRecords(run), after: records };
+ } else this.pushes = [];
}
revert(doc: EditorDocument): void {
@@ -275,6 +396,8 @@ export class ReflowWrapCommand implements Command {
const page = doc.page(this.pageIndex);
const run = page.findRun(this.runId);
if (!run) return;
+ for (const push of [...(this.pushes ?? [])].reverse()) push.revert(doc);
+ if (this.pushRecords) setPushRecords(run, this.pushRecords.before);
const m = doc.module;
for (let i = this.moves.length - 1; i >= 0; i--) {
const mv = this.moves[i];
@@ -312,6 +435,12 @@ export class ReflowWrapCommand implements Command {
}
}
+const TEXT_OVERLAP_EM = 0.25;
+
+function lineCount(text: string): number {
+ return text.split(/\r?\n/).length;
+}
+
/** Read every leaf object's ACTUAL geometry + text straight from PDFium. */
function extractLeaves(
m: WrappedPdfiumModule,
@@ -352,6 +481,11 @@ function extractLeaves(
return leaves;
}
+function readsInObjectOrder(leaves: Leaf[], text: string): boolean {
+ const letters = (s: string): string => s.replace(/\s+/g, "");
+ return letters(leaves.map((leaf) => leaf.text).join("")) === letters(text);
+}
+
/** The non-whitespace char counts at which `text` has a hard "\n" break. */
function hardBreakNonWsCounts(
text: string,
@@ -363,9 +497,9 @@ function hardBreakNonWsCounts(
for (const ch of text) {
if (ch === "\n") {
lineIndex += 1;
- // A break this command inserted to make the text fit is not the user's,
- // so it must stay re-flowable. Reading it back as forced would freeze the
- // paragraph at whatever width it happened to be wrapped to.
+ // A soft break is not the author's, so it must stay re-flowable. Reading
+ // it back as forced would freeze the paragraph at whatever width it
+ // happened to be wrapped to.
if (!softStarts?.[lineIndex]) out.set(nonWs, (out.get(nonWs) ?? 0) + 1);
} else if (!/\s/.test(ch)) nonWs += 1;
}
@@ -498,6 +632,7 @@ function rebuildRunFromLines(
} else {
run.text = glyphDerived;
}
+ run.paragraphSoftStartsText = run.text;
const s0 = slots[0];
if (s0) {
@@ -576,6 +711,7 @@ function snapshotRun(run: TextRun): RunSnapshot {
paragraphLeafContainers: [...run.paragraphLeafContainers],
paragraphLineSlots: run.paragraphLineSlots.map(cloneSlot),
paragraphSoftStarts: [...run.paragraphSoftStarts],
+ paragraphSoftStartsText: run.paragraphSoftStartsText,
mergedFromPtrs: [...run.mergedFromPtrs],
mergedFromTexts: [...run.mergedFromTexts],
mergedFromBounds: run.mergedFromBounds.map((b) => ({ ...b })),
@@ -597,6 +733,7 @@ function restoreRun(run: TextRun, prev: RunSnapshot): void {
run.paragraphLeafContainers = [...prev.paragraphLeafContainers];
run.paragraphLineSlots = prev.paragraphLineSlots.map(cloneSlot);
run.paragraphSoftStarts = [...prev.paragraphSoftStarts];
+ run.paragraphSoftStartsText = prev.paragraphSoftStartsText;
run.mergedFromPtrs = [...prev.mergedFromPtrs];
run.mergedFromTexts = [...prev.mergedFromTexts];
run.mergedFromBounds = prev.mergedFromBounds.map((b) => ({ ...b }));
@@ -656,7 +793,8 @@ function resegmentByLines(
}
const start = posAtNonWsIndex(preReflowText, cumNw);
const lastPos = posAtNonWsIndex(preReflowText, cumNw + nw - 1);
- out.push(preReflowText.slice(start, lastPos + 1));
+ // A line that joined soft-broken lines spans their breaks.
+ out.push(preReflowText.slice(start, lastPos + 1).replace(/\n/g, " "));
cumNw += nw;
}
return out;
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/commands/ReplaceImageCommand.ts b/frontend/src/editor/core/tools/pdfTextEditor/commands/ReplaceImageCommand.ts
index 5796455df6..83521ec839 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/commands/ReplaceImageCommand.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/commands/ReplaceImageCommand.ts
@@ -1,4 +1,8 @@
-import type { Command } from "@editor/tools/pdfTextEditor/commands/Command";
+import i18n from "i18next";
+import {
+ RolledBackError,
+ type Command,
+} from "@editor/tools/pdfTextEditor/commands/Command";
import type { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
import type { ImageObject } from "@editor/tools/pdfTextEditor/model/ImageObject";
import type { Page } from "@editor/tools/pdfTextEditor/model/Page";
@@ -14,14 +18,12 @@ import {
scratchPtr,
} from "@editor/tools/pdfTextEditor/util/wasmScratch";
import { copyTagMarks } from "@editor/tools/pdfTextEditor/pdfium/PdfiumTagMarks";
-
-interface ZOrderModule {
- FPDFPage_InsertObjectAtIndex?: (
- page: number,
- obj: number,
- index: number,
- ) => boolean;
-}
+import {
+ indexedInsertOf,
+ insertPageObjectAt,
+} from "@editor/tools/pdfTextEditor/util/insertPageObject";
+import { pageObjectIndex } from "@editor/tools/pdfTextEditor/commands/editTextHelpers";
+import { clipHidesImage } from "@editor/tools/pdfTextEditor/util/imageClip";
interface MatrixModule {
FPDFImageObj_SetMatrix?: (
@@ -89,6 +91,18 @@ export class ReplaceImageCommand implements Command {
const page = doc.page(this.pageIndex);
const img = page.findImage(this.imageId);
if (!img || !img.pdfiumObjPtr) return;
+ // The replacement is a new object, and PDFium cannot give an object a
+ // clip, so it would show what the original's clip hides.
+ if (clipHidesImage(img)) {
+ throw new RolledBackError(
+ new Error(
+ i18n.t(
+ "pdfTextEditor.error.replaceClippedImage",
+ "Can't replace this image: it is cropped, and the replacement would show the parts the crop hides.",
+ ),
+ ),
+ );
+ }
const m = doc.module;
// A form-nested original cannot be detached and put back (this build has
// no FPDFFormObj_InsertObject), so hide it in place instead and draw the
@@ -98,7 +112,7 @@ export class ReplaceImageCommand implements Command {
this.prevObjPtr = img.pdfiumObjPtr;
this.prevMatrix = { ...img.matrix };
this.prevBounds = { ...img.bounds };
- this.prevIndex = objectIndex(m, page.pagePtr, this.prevObjPtr);
+ this.prevIndex = pageObjectIndex(m, page.pagePtr, this.prevObjPtr);
}
const matrix = this.prevMatrix;
const box = this.prevBounds;
@@ -107,7 +121,7 @@ export class ReplaceImageCommand implements Command {
if (this.nextObjPtr) {
if (nested) setActive(m, this.prevObjPtr, false);
else m.FPDFPage_RemoveObject(page.pagePtr, this.prevObjPtr);
- insertObjectAt(m, page.pagePtr, this.nextObjPtr, this.prevIndex);
+ insertPageObjectAt(m, page.pagePtr, this.nextObjPtr, this.prevIndex);
this.adopt(page, img, this.nextObjPtr);
return;
}
@@ -149,9 +163,9 @@ export class ReplaceImageCommand implements Command {
if (nested) setActive(m, this.prevObjPtr, false);
else m.FPDFPage_RemoveObject(page.pagePtr, this.prevObjPtr);
// The embed appended, so without this the replacement jumps to the top.
- if (this.prevIndex >= 0 && supportsInsertAtIndex(m)) {
+ if (this.prevIndex >= 0 && indexedInsertOf(m)) {
m.FPDFPage_RemoveObject(page.pagePtr, objPtr);
- insertObjectAt(m, page.pagePtr, objPtr, this.prevIndex);
+ insertPageObjectAt(m, page.pagePtr, objPtr, this.prevIndex);
}
this.nextObjPtr = objPtr;
this.adopt(page, img, objPtr);
@@ -166,7 +180,7 @@ export class ReplaceImageCommand implements Command {
// Detach only again: the replacement is what redo re-attaches.
m.FPDFPage_RemoveObject(page.pagePtr, this.nextObjPtr);
if (img.containerPtr) setActive(m, this.prevObjPtr, true);
- else insertObjectAt(m, page.pagePtr, this.prevObjPtr, this.prevIndex);
+ else insertPageObjectAt(m, page.pagePtr, this.prevObjPtr, this.prevIndex);
this.adopt(page, img, this.prevObjPtr);
}
@@ -180,43 +194,6 @@ export class ReplaceImageCommand implements Command {
}
}
-function objectIndex(
- m: WrappedPdfiumModule,
- pagePtr: number,
- objPtr: number,
-): number {
- const total = m.FPDFPage_CountObjects(pagePtr);
- for (let i = 0; i < total; i++) {
- if (m.FPDFPage_GetObject(pagePtr, i) === objPtr) return i;
- }
- return -1;
-}
-
-function supportsInsertAtIndex(m: WrappedPdfiumModule): boolean {
- return (
- typeof (m as unknown as ZOrderModule).FPDFPage_InsertObjectAtIndex ===
- "function"
- );
-}
-
-/** Re-attach a detached object at `index`, appending when that is unavailable. */
-function insertObjectAt(
- m: WrappedPdfiumModule,
- pagePtr: number,
- objPtr: number,
- index: number,
-): void {
- const insertAt = (m as unknown as ZOrderModule).FPDFPage_InsertObjectAtIndex;
- if (typeof insertAt === "function" && index >= 0) {
- try {
- if (insertAt.call(m, pagePtr, objPtr, index)) return;
- } catch {
- /* fall through to append */
- }
- }
- m.FPDFPage_InsertObject(pagePtr, objPtr);
-}
-
function setImageMatrix(
m: WrappedPdfiumModule,
objPtr: number,
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/commands/ResizeTableCommand.ts b/frontend/src/editor/core/tools/pdfTextEditor/commands/ResizeTableCommand.ts
index 575fb34937..d5cf5edbfc 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/commands/ResizeTableCommand.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/commands/ResizeTableCommand.ts
@@ -1,4 +1,5 @@
import { locateTable } from "@editor/tools/pdfTextEditor/util/locateTable";
+import { refuseRedrawOfReadOnlyText } from "@editor/tools/pdfTextEditor/commands/readOnlyText";
import type { Command } from "@editor/tools/pdfTextEditor/commands/Command";
import type { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
import type { Page } from "@editor/tools/pdfTextEditor/model/Page";
@@ -13,6 +14,7 @@ import {
} from "@editor/tools/pdfTextEditor/util/tableGeometry";
import {
absoluteFontScale,
+ assertTableLiftable,
applyCellPlacement,
captureCellPlacement,
type CellPlacement,
@@ -69,6 +71,9 @@ export class ResizeTableCommand implements Command {
const found = locateTable(doc, this.tableId);
if (!found) return;
const { page, model } = found;
+ assertTableLiftable(doc, page, model);
+ // Scaling resizes every cell's text, so it is refused whole before any cell is touched.
+ if (this.edit.kind === "scale") refuseScalingReadOnlyText(page, model);
this.before = {
colEdges: [...model.colEdges],
rowEdges: [...model.rowEdges],
@@ -216,6 +221,17 @@ export class ResizeTableCommand implements Command {
}
}
+function refuseScalingReadOnlyText(page: Page, model: TableModel): void {
+ for (let r = 0; r < model.rows; r++) {
+ for (let c = 0; c < model.cols; c++) {
+ for (const id of model.runsAt(r, c)) {
+ const run = page.findRun(id);
+ if (run) refuseRedrawOfReadOnlyText(run);
+ }
+ }
+ }
+}
+
// Resize every cell's text through the toolbar's own font-size command, so the
// glyph scaling, matrix and letter-spacing bookkeeping stay in one place.
function scaleCellFonts(
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/commands/SetColourCommand.ts b/frontend/src/editor/core/tools/pdfTextEditor/commands/SetColourCommand.ts
index 3477333865..88ffc0443d 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/commands/SetColourCommand.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/commands/SetColourCommand.ts
@@ -1,3 +1,4 @@
+import { liftRunToPage } from "@editor/tools/pdfTextEditor/commands/liftFromForm";
import i18n from "i18next";
import type { Command } from "@editor/tools/pdfTextEditor/commands/Command";
import type { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
@@ -33,6 +34,7 @@ export class SetColourCommand implements Command {
const page = doc.page(this.pageIndex);
const run = page.findRun(this.runId);
if (!run) return;
+ liftRunToPage(doc, page, run);
const scanPrev = setScanOverride(doc, page, run, (o) => ({
...o,
fill: { ...this.nextFill },
@@ -41,19 +43,18 @@ export class SetColourCommand implements Command {
this.scanPrev = scanPrev;
return;
}
- if (this.prevFill === null) {
- this.prevFill = { ...run.fill };
- const m = doc.module;
- const seen = new Set<number>();
- this.prevMemberFills = [];
- for (const ptr of collectMemberPtrs(run)) {
- if (!ptr || seen.has(ptr)) continue;
- seen.add(ptr);
- this.prevMemberFills.push({
- ptr,
- fill: readObjFill(m, ptr) ?? { ...run.fill },
- });
- }
+ // Read on every apply: redoing an earlier step draws the run in new objects.
+ this.prevFill = { ...run.fill };
+ const m = doc.module;
+ const seen = new Set<number>();
+ this.prevMemberFills = [];
+ for (const ptr of collectMemberPtrs(run)) {
+ if (!ptr || seen.has(ptr)) continue;
+ seen.add(ptr);
+ this.prevMemberFills.push({
+ ptr,
+ fill: readObjFill(m, ptr) ?? { ...run.fill },
+ });
}
run.fill = { ...this.nextFill };
run.dirty = true;
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/commands/SetFontFamilyCommand.ts b/frontend/src/editor/core/tools/pdfTextEditor/commands/SetFontFamilyCommand.ts
index e4191495f8..df2cda5c49 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/commands/SetFontFamilyCommand.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/commands/SetFontFamilyCommand.ts
@@ -1,5 +1,10 @@
+import { liftRunToPage } from "@editor/tools/pdfTextEditor/commands/liftFromForm";
+import { needsShaping } from "@editor/tools/pdfTextEditor/util/complexShaping";
+import { refuseRedrawOfReadOnlyText } from "@editor/tools/pdfTextEditor/commands/readOnlyText";
+import type { WrappedPdfiumModule } from "@embedpdf/pdfium";
import type { Command } from "@editor/tools/pdfTextEditor/commands/Command";
import type { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
+import type { Page } from "@editor/tools/pdfTextEditor/model/Page";
import {
cloneParagraphLineSlot,
type ParagraphLineSlot,
@@ -7,29 +12,63 @@ import {
} from "@editor/tools/pdfTextEditor/model/TextRun";
import {
collectContainersByPtr,
+ charcodesResolveFully,
collectMemberPtrs,
+ contentIndices,
+ droppedCharsOf,
emitRunLines,
planLineOrigins,
+ recordUndrawableChars,
+ removeAndDestroyObject,
removeMemberPtrs,
+ restoreContentOrder,
+ warmOnPageAdvances,
+ type EmittedLine,
+ type FontSpan,
} from "@editor/tools/pdfTextEditor/commands/editTextHelpers";
+import { piecesFromObjects } from "@editor/tools/pdfTextEditor/commands/partialEdit";
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 {
+ deviceFontEmitCount,
+ familyCoverage,
+} from "@editor/tools/pdfTextEditor/util/deviceFontEmbed";
import {
base14FontId,
deviceFontId,
+ documentFontHandle,
+ familyOf,
+ isDocumentFontId,
+ nearestStandardFont,
+ stripSubsetTag,
} from "@editor/tools/pdfTextEditor/util/fontFamily";
+import { readFontName } from "@editor/tools/pdfTextEditor/charcode/FontHelpers";
+import { fallbackFamilyFor } from "@editor/tools/pdfTextEditor/util/fontCapability";
+import { fontCompletionFor } from "@editor/tools/pdfTextEditor/util/documentFontCompletion";
import {
+ isScanRun,
setScanOverride,
type ScanOverride,
} from "@editor/tools/pdfTextEditor/commands/scanTextEdit";
+interface LineToEmit {
+ text: string;
+ tags: TextTags;
+ /** Where the line starts in the run's text. */
+ start: number;
+ x: number;
+ y: number;
+}
+
// Re-emit a run's text in another family: PDFium has no SetFont accessor.
-// Device fonts embed when pre-warmed, else the nearest standard face.
+// Device fonts embed when pre-warmed, else the nearest standard face. A
+// document fontId reuses that font of the PDF, the run's own one to restore it.
+// Letters the family has no glyph for stay in the font that drew them, and a
+// change that would still leave a letter undrawn is not made.
export class SetFontFamilyCommand implements Command {
readonly type = "set-font-family";
private readonly pageIndex: number;
@@ -37,10 +76,12 @@ export class SetFontFamilyCommand implements Command {
private readonly nextFamily: string;
/** Set when the run was scanned text, re-set by redrawing it. */
private scanPrev: ScanOverride | null = null;
- /** Full pre-edit model snapshot for revert. */
+ /** The run as this apply found it, for revert. */
private prev: RunModelSnapshot | null;
/** Original on-page member ptrs (re-inserted on revert). */
private prevMemberPtrs: number[];
+ /** Where each original sat in the page's content order, which decides how the text of an object reads beside its neighbours. */
+ private prevContentOrder: Array<{ ptr: number; index: number }>;
/** Every object this command created (removed on revert). */
private createdPtrs: number[];
@@ -50,6 +91,7 @@ export class SetFontFamilyCommand implements Command {
this.nextFamily = opts.nextFamily;
this.prev = null;
this.prevMemberPtrs = [];
+ this.prevContentOrder = [];
this.createdPtrs = [];
}
@@ -57,6 +99,13 @@ export class SetFontFamilyCommand implements Command {
const page = doc.page(this.pageIndex);
const run = page.findRun(this.runId);
if (!run) return;
+ refuseRedrawOfReadOnlyText(run);
+ if (needsShaping(run.text)) return;
+ const toDocumentFont = isDocumentFontId(this.nextFamily);
+ const documentFont = run.documentFont;
+ const restoring =
+ toDocumentFont && documentFont?.fontId === this.nextFamily;
+ if (toDocumentFont && !documentFontHandle(this.nextFamily)) return;
const scanPrev = setScanOverride(doc, page, run, (o) => ({
...o,
family: this.nextFamily,
@@ -66,13 +115,24 @@ export class SetFontFamilyCommand implements Command {
return;
}
const m = doc.module;
+ liftRunToPage(doc, page, run);
- if (this.prev === null) {
- this.prev = snapshotRun(run);
- this.prevMemberPtrs = collectMemberPtrs(run).slice();
+ // Read on every apply: redoing an earlier step draws the run in new objects.
+ this.prev = snapshotRun(run);
+ this.prevMemberPtrs = collectMemberPtrs(run).slice();
+ this.prevContentOrder = [
+ ...contentIndices(m, page.pagePtr, this.prevMemberPtrs),
+ ].map(([ptr, index]) => ({ ptr, index }));
+
+ if (!restoring && !documentFont && isDocumentFontId(run.fontId)) {
+ run.documentFont = { fontId: run.fontId, subset: run.fontSubset };
}
- const tags = readRunTags(doc, page, run);
+ const emitLines = linesToEmit(run, readRunTags(doc, page, run));
+ const lineHeight = lineHeightOf(run);
+ // Read while the source objects are still on the page: the kept fonts and their glyph advances come off them.
+ const keptFonts = this.keptFontSpans(doc, page, run, emitLines);
+ warmOnPageAdvances(m, page.pagePtr);
// Detach every original object so the page stops painting them.
removeMemberPtrs(
m,
@@ -82,46 +142,6 @@ export class SetFontFamilyCommand implements Command {
run.containerPtr,
);
- // Re-emit one base-14 object per visual line at descending baselines.
- const lineHeight =
- run.paragraphLineHeight > 0
- ? run.paragraphLineHeight
- : run.fontSize * 1.2;
- // Prefer per-line SLOT ranges: run.text joins SOFT-wrapped lines with
- // 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 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,
- splitLinesOfText.length,
- lineHeight,
- );
- return splitLinesOfText.map((line, i) => ({
- ...line,
- ...origins[i],
- }));
- })()
- : 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[] = [];
@@ -129,14 +149,9 @@ export class SetFontFamilyCommand implements Command {
// Emits with the embedded device face are counted, so the font id below
// can say what actually rendered rather than what was requested.
const deviceEmitsBefore = deviceFontEmitCount(doc, this.nextFamily);
- const emitted = emitRunLines({
- doc,
- page,
- run,
- 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,
+ let emitted: EmittedLine[] = [];
+ const dropped = droppedCharsOf(() => {
+ emitted = this.emit(doc, page, run, emitLines, keptFonts);
});
for (const line of emitted) {
memberFs.push(line.y);
@@ -149,8 +164,14 @@ export class SetFontFamilyCommand implements Command {
created.push(...line.ptrs);
}
- if (created.length === 0) {
- // Nothing emitted (e.g. all-whitespace dropped) - restore and bail.
+ // A move to a document font drawn only in fallback faces did not put the run in that font.
+ const targetFont = documentFontHandle(this.nextFamily);
+ const notInTarget =
+ toDocumentFont &&
+ !created.some((ptr) => m.FPDFTextObj_GetFont(ptr) === targetFont);
+ if (created.length === 0 || notInTarget || losesLetters(dropped)) {
+ // Nothing usable emitted (e.g. all-whitespace dropped), or a letter went undrawn - restore and bail.
+ for (const ptr of created) removeAndDestroyObject(m, page.pagePtr, ptr);
this.reinsertOriginals(m, page);
restoreRun(run, this.prev);
// Neutralise the command: it still lands in history, and a revert with
@@ -159,16 +180,27 @@ export class SetFontFamilyCommand implements Command {
return;
}
+ // Only characters that draw nothing get this far, and a save still lists them as dropped.
+ recordUndrawableChars(dropped.join(""));
this.createdPtrs = created;
run.pdfiumObjPtr = lineAnchors.find((p) => p) ?? leaf[0];
// `device:` marks glyphs from an embedded device font; a substituted run
// keeps `base14:`, so nothing keying off that prefix changes meaning.
const embedded =
deviceFontEmitCount(doc, this.nextFamily) > deviceEmitsBefore;
- run.fontId = embedded
- ? deviceFontId(this.nextFamily)
- : base14FontId(this.nextFamily);
- run.fontSubset = false;
+ if (restoring) {
+ run.fontId = this.nextFamily;
+ run.fontSubset = documentFont?.subset ?? false;
+ run.documentFont = null;
+ } else if (toDocumentFont) {
+ run.fontId = this.nextFamily;
+ run.fontSubset = isSubsetFont(m, targetFont);
+ } else {
+ run.fontId = embedded
+ ? deviceFontId(this.nextFamily)
+ : base14FontId(this.nextFamily);
+ run.fontSubset = false;
+ }
// Reset ALL model bookkeeping to the freshly-emitted objects so later
// commands act on the live objects, not the removed originals.
run.mergedFromPtrs = [];
@@ -192,6 +224,152 @@ export class SetFontFamilyCommand implements Command {
page.markNeedsGenerate();
}
+ wouldLoseText(doc: EditorDocument): boolean {
+ return this.refusal(doc) === "losesText";
+ }
+
+ /**
+ * Why applying this would be refused, or null when it would apply: a letter
+ * of the run left undrawn, or a restore the document font cannot draw (a
+ * Type 3 font with no way to encode new text, say). Found by drawing the run
+ * beside itself and taking that back, so the answer is the emit's own and
+ * the page is left as it was.
+ */
+ refusal(doc: EditorDocument): "losesText" | "notRestored" | null {
+ const page = doc.page(this.pageIndex);
+ const run = page.findRun(this.runId);
+ if (!run || isScanRun(run) || run.scanEdit) return null;
+ const restoring = isDocumentFontId(this.nextFamily);
+ if (restoring && !documentFontHandle(this.nextFamily)) return null;
+ const emitLines = linesToEmit(run, readRunTags(doc, page, run));
+ const keptFonts = this.keptFontSpans(doc, page, run, emitLines);
+ warmOnPageAdvances(doc.module, page.pagePtr);
+ let emitted: EmittedLine[] = [];
+ const dropped = droppedCharsOf(() => {
+ emitted = this.emit(doc, page, run, emitLines, keptFonts);
+ });
+ const restoreFont = documentFontHandle(this.nextFamily);
+ let drawsRestoreFont = false;
+ for (const line of emitted)
+ for (const ptr of line.ptrs) {
+ if (doc.module.FPDFTextObj_GetFont(ptr) === restoreFont)
+ drawsRestoreFont = true;
+ removeAndDestroyObject(doc.module, page.pagePtr, ptr);
+ }
+ if (losesLetters(dropped)) return "losesText";
+ return restoring && !drawsRestoreFont ? "notRestored" : null;
+ }
+
+ /**
+ * How much of the run's visible text the next font has glyphs for: the rest
+ * is drawn in the closest font that has them, and none means the change
+ * would not put the run in that font at all.
+ */
+ coverage(doc: EditorDocument): "all" | "some" | "none" {
+ const page = doc.page(this.pageIndex);
+ const run = page.findRun(this.runId);
+ if (!run || isScanRun(run) || run.scanEdit) return "all";
+ const draws = this.nextFontDraws(doc, page);
+ if (!draws) return "all";
+ const visible = [...run.text].filter(
+ (ch) => !/\s/.test(ch) && !DRAWS_NOTHING.test(ch),
+ );
+ const drawn = visible.filter(draws).length;
+ if (drawn === visible.length) return "all";
+ return drawn === 0 ? "none" : "some";
+ }
+
+ /** Whether the next font has a glyph for a character; null when that cannot be known. */
+ private nextFontDraws(
+ doc: EditorDocument,
+ page: Page,
+ ): ((ch: string) => boolean) | null {
+ const target = documentFontHandle(this.nextFamily);
+ if (!target) return familyDraws(doc, this.nextFamily);
+ return (ch) =>
+ charcodesResolveFully(doc.module, target, ch, page.pagePtr, doc.docPtr);
+ }
+
+ private emit(
+ doc: EditorDocument,
+ page: Page,
+ run: TextRun,
+ lines: readonly LineToEmit[],
+ keptFonts: ReadonlyArray<readonly FontSpan[] | undefined> | undefined,
+ ): EmittedLine[] {
+ // Only a document font is reused for the run; either way `keptFonts` holds the letters that stay where they are.
+ const targetFont = documentFontHandle(this.nextFamily);
+ return emitRunLines({
+ doc,
+ page,
+ run,
+ lines: lines.map(({ text, tags }) => ({ text, tags })),
+ origins: lines.map((line) => ({ x: line.x, y: line.y })),
+ originalFontPtr: targetFont,
+ originalFontSubset: !targetFont
+ ? run.fontSubset
+ : run.documentFont?.fontId === this.nextFamily
+ ? run.documentFont.subset
+ : isSubsetFont(doc.module, targetFont),
+ fallbackFamily: targetFont
+ ? fallbackFamilyFor(this.nextFamily)
+ : this.nextFamily,
+ fontSpansByLine: keptFonts,
+ });
+ }
+
+ /**
+ * Per line, the stretches the next font has no glyph for, each with the font
+ * its letters are drawn in. Undefined when the next font draws every letter.
+ * A move to a document font keeps only letters still in a font of the
+ * document: one the editor drew, in the family being left or a stand-in for
+ * it, goes with the rest of the run.
+ */
+ private keptFontSpans(
+ doc: EditorDocument,
+ page: Page,
+ run: TextRun,
+ lines: readonly LineToEmit[],
+ ): Array<FontSpan[] | undefined> | undefined {
+ const m = doc.module;
+ const restoreFont = documentFontHandle(this.nextFamily);
+ const draws = this.nextFontDraws(doc, page);
+ if (!draws) return undefined;
+ const lacks = (ch: string) => !/\s/.test(ch) && !draws(ch);
+ if (![...run.text].some(lacks)) return undefined;
+ const fontAt = sourceFontAt(m, page.pagePtr, run);
+ const leaving = familyOf(run.fontId);
+ // A run still in a document font was drawn by the PDF, so a font named like it is that face, not a stand-in.
+ const drawnByEditor = (font: number) =>
+ !!doc.ownedFontAt(font) ||
+ (!isDocumentFontId(run.fontId) &&
+ [leaving, nearestStandardFont(leaving)].includes(
+ stripSubsetTag(readFontName(m, font) ?? ""),
+ ));
+ // A face completed from its real font draws a missing letter closer than the face the run is leaving.
+ const completed =
+ run.documentFont?.fontId !== this.nextFamily &&
+ !!fontCompletionFor(this.nextFamily);
+ const keeps = (font: number) =>
+ !restoreFont ||
+ (!completed && font !== restoreFont && !drawnByEditor(font));
+ const fallbackFamily = restoreFont
+ ? fallbackFamilyFor(this.nextFamily)
+ : this.nextFamily;
+ return lines.map((line) => {
+ const kept = new Array<number>(line.text.length).fill(0);
+ for (const stretch of stretchesLacking(line.text, lacks)) {
+ if (NEEDS_SHAPING.test(line.text.slice(stretch.start, stretch.end)))
+ continue;
+ for (let c = stretch.start; c < stretch.end; c++) {
+ const font = fontAt[line.start + c] ?? 0;
+ if (keeps(font)) kept[c] = font;
+ }
+ }
+ return spansOf(line.text, kept, fallbackFamily);
+ });
+ }
+
revert(doc: EditorDocument): void {
if (this.scanPrev) {
const page = doc.page(this.pageIndex);
@@ -223,10 +401,7 @@ export class SetFontFamilyCommand implements Command {
page.markNeedsGenerate();
}
- private reinsertOriginals(
- m: import("@embedpdf/pdfium").WrappedPdfiumModule,
- page: import("@editor/tools/pdfTextEditor/model/Page").Page,
- ): void {
+ private reinsertOriginals(m: WrappedPdfiumModule, page: Page): void {
for (const ptr of this.prevMemberPtrs) {
if (!ptr) continue;
try {
@@ -235,13 +410,152 @@ export class SetFontFamilyCommand implements Command {
/* best-effort */
}
}
+ restoreContentOrder(m, page.pagePtr, this.prevContentOrder);
+ }
+}
+
+/** Whether an emit in `family` draws a character in that family's own face; null when that cannot be known. */
+function familyDraws(
+ doc: EditorDocument,
+ family: string,
+): ((ch: string) => boolean) | null {
+ const covers = familyCoverage(doc, family);
+ return covers && ((ch) => covers(ch.codePointAt(0)!));
+}
+
+/**
+ * Text whose look depends on shaping: combining marks, joiners, the joining
+ * scripts and conjoining jamo. Redrawn letter by letter in its own font it
+ * would lose its ligatures and mark positions, so it is never split off.
+ */
+const NEEDS_SHAPING =
+ /\p{M}|\u200c|\u200d|[\u1100-\u11ff]|\p{Script=Arabic}|\p{Script=Syriac}|\p{Script=Nko}|\p{Script=Mandaic}|\p{Script=Mongolian}|\p{Script=Phags_Pa}|\p{Script=Adlam}/u;
+export const ATTACHES_TO_PREVIOUS = /\p{M}|\u200c|\u200d/u;
+/** Format and control characters draw nothing, so losing one loses no letter. */
+const DRAWS_NOTHING = /[\p{Cf}\p{Cc}]/u;
+
+export function isSubsetFont(m: WrappedPdfiumModule, font: number): boolean {
+ return /^[A-Z]{6}\+/.test(readFontName(m, font) ?? "");
+}
+
+export function losesLetters(dropped: readonly string[]): boolean {
+ return dropped.some((ch) => !DRAWS_NOTHING.test(ch));
+}
+
+function lineHeightOf(run: TextRun): number {
+ return run.paragraphLineHeight > 0
+ ? run.paragraphLineHeight
+ : run.fontSize * 1.2;
+}
+
+// Prefer per-line SLOT ranges: run.text joins SOFT-wrapped lines with
+// separators a \n split can't see. Baseline stepping for the fallback case
+// comes from planLineOrigins so it cannot drift from EditTextCommand's.
+function linesToEmit(run: TextRun, tags: TextTags): LineToEmit[] {
+ const slots = run.paragraphLineSlots;
+ if (slots.length > 0)
+ return 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),
+ start,
+ x: s.matrixE,
+ y: s.baselineY,
+ };
+ });
+ const lines = splitLines(run.text, tags);
+ const origins = planLineOrigins(run, lines.length, lineHeightOf(run));
+ let cursor = 0;
+ return lines.map((line, i) => {
+ const start = run.text.indexOf(line.text, cursor);
+ cursor = start + line.text.length;
+ return { ...line, ...origins[i], start };
+ });
+}
+
+/** The font handle drawing each code unit of the run's text, 0 where none is known. */
+function sourceFontAt(
+ m: WrappedPdfiumModule,
+ pagePtr: number,
+ run: TextRun,
+): number[] {
+ const fontAt = new Array<number>(run.text.length).fill(0);
+ const mark = (
+ pieces: Pick<
+ ParagraphLineSlot,
+ "mergedFromPtrs" | "mergedFromTexts" | "mergedFromCharStarts"
+ >,
+ offset: number,
+ ) =>
+ pieces.mergedFromPtrs.forEach((ptr, i) => {
+ const start = offset + (pieces.mergedFromCharStarts[i] ?? 0);
+ const end = start + (pieces.mergedFromTexts[i]?.length ?? 0);
+ const font = ptr ? m.FPDFTextObj_GetFont(ptr) : 0;
+ for (let c = Math.max(0, start); c < Math.min(end, fontAt.length); c++)
+ fontAt[c] = font;
+ });
+ if (run.paragraphLineSlots.length > 0) {
+ for (const slot of run.paragraphLineSlots) mark(slot, slot.startChar);
+ } else {
+ const pieces =
+ run.mergedFromPtrs.length > 0
+ ? run
+ : piecesFromObjects(m, pagePtr, collectMemberPtrs(run), run.text);
+ if (pieces) mark(pieces, 0);
+ }
+ for (let c = 1; c < fontAt.length; c++) fontAt[c] ||= fontAt[c - 1];
+ for (let c = fontAt.length - 2; c >= 0; c--) fontAt[c] ||= fontAt[c + 1];
+ if (fontAt[0] === 0 && run.pdfiumObjPtr)
+ fontAt.fill(m.FPDFTextObj_GetFont(run.pdfiumObjPtr));
+ return fontAt;
+}
+
+/** Each unbroken stretch of `text` holding a character `lacks` is true of, with the marks attached to it. */
+function stretchesLacking(
+ text: string,
+ lacks: (ch: string) => boolean,
+): Array<{ start: number; end: number }> {
+ const stretches: Array<{ start: number; end: number }> = [];
+ let open: { start: number; end: number } | null = null;
+ let at = 0;
+ for (const ch of text) {
+ const end = at + ch.length;
+ if (lacks(ch) || (open && ATTACHES_TO_PREVIOUS.test(ch))) {
+ if (open) open.end = end;
+ else stretches.push((open = { start: at, end }));
+ } else {
+ open = null;
+ }
+ at = end;
+ }
+ return stretches;
+}
+
+/** `kept` as font spans: 0 is the next font, and a space stays with the letter before it. */
+function spansOf(
+ text: string,
+ kept: readonly number[],
+ family: string,
+): FontSpan[] | undefined {
+ const spans: FontSpan[] = [];
+ for (let c = 0; c < text.length; c++) {
+ const last = spans[spans.length - 1];
+ if (last && (/\s/.test(text[c]) || kept[c] === last.fontPtr))
+ last.end = c + 1;
+ else spans.push({ end: c + 1, fontPtr: kept[c], fallbackFamily: family });
}
+ return spans.some((span) => span.fontPtr !== 0) ? spans : undefined;
}
interface RunModelSnapshot {
text: string;
fontId: string;
fontSubset: boolean;
+ documentFont: TextRun["documentFont"];
fill: { r: number; g: number; b: number; a: number };
pdfiumObjPtr: number;
containerPtr: number;
@@ -263,6 +577,7 @@ function snapshotRun(run: TextRun): RunModelSnapshot {
text: run.text,
fontId: run.fontId,
fontSubset: run.fontSubset,
+ documentFont: run.documentFont,
fill: { ...run.fill },
pdfiumObjPtr: run.pdfiumObjPtr,
containerPtr: run.containerPtr,
@@ -284,6 +599,7 @@ function restoreRun(run: TextRun, snap: RunModelSnapshot): void {
run.text = snap.text;
run.fontId = snap.fontId;
run.fontSubset = snap.fontSubset;
+ run.documentFont = snap.documentFont;
run.fill = { ...snap.fill };
run.pdfiumObjPtr = snap.pdfiumObjPtr;
run.containerPtr = snap.containerPtr;
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/commands/SetFontSizeCommand.ts b/frontend/src/editor/core/tools/pdfTextEditor/commands/SetFontSizeCommand.ts
index 74d418d46b..903ac4d86e 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/commands/SetFontSizeCommand.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/commands/SetFontSizeCommand.ts
@@ -1,3 +1,6 @@
+import type { TextRun } from "@editor/tools/pdfTextEditor/model/TextRun";
+import { liftRunToPage } from "@editor/tools/pdfTextEditor/commands/liftFromForm";
+import { refuseRedrawOfReadOnlyText } from "@editor/tools/pdfTextEditor/commands/readOnlyText";
import type { Command } from "@editor/tools/pdfTextEditor/commands/Command";
import type { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
import { collectMemberPtrs } from "@editor/tools/pdfTextEditor/commands/editTextHelpers";
@@ -30,6 +33,8 @@ export class SetFontSizeCommand implements Command {
const page = doc.page(this.pageIndex);
const run = page.findRun(this.runId);
if (!run) return;
+ refuseRedrawOfReadOnlyText(run);
+ liftRunToPage(doc, page, run);
// Scaled from the size actually drawn: before the first edit the run may
// still report OCR's guess, which is far off. Fixed once, so redo matches.
const drawn = scanDrawnSize(doc, page, run);
@@ -146,7 +151,7 @@ export class SetFontSizeCommand implements Command {
/** Mirror the PDFium object scaling in the run's model bookkeeping. */
function rescaleRunModel(
- run: import("@editor/tools/pdfTextEditor/model/TextRun").TextRun,
+ run: TextRun,
s: number,
ax: number,
ay: number,
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/commands/SetImageTransformCommand.ts b/frontend/src/editor/core/tools/pdfTextEditor/commands/SetImageTransformCommand.ts
index e83e36dba7..2e40e7c8d4 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/commands/SetImageTransformCommand.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/commands/SetImageTransformCommand.ts
@@ -1,3 +1,4 @@
+import { liftImageToPage } from "@editor/tools/pdfTextEditor/commands/liftFromForm";
import type { Command } from "@editor/tools/pdfTextEditor/commands/Command";
import type { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
import type { Affine, PageRect } from "@editor/tools/pdfTextEditor/types";
@@ -6,6 +7,7 @@ import {
remapImageMatrix,
} from "@editor/tools/pdfTextEditor/model/affine";
import { retargetClipPath } from "@editor/tools/pdfTextEditor/util/objectTransform";
+import { readImageClip } from "@editor/tools/pdfTextEditor/util/imageClip";
/** Set an image object's transform to an absolute target. */
export class SetImageTransformCommand implements Command {
@@ -32,6 +34,7 @@ export class SetImageTransformCommand implements Command {
const page = doc.page(this.pageIndex);
const img = page.findImage(this.imageId);
if (!img || !img.pdfiumObjPtr) return;
+ if (!liftImageToPage(doc, page, img)) return;
let prevBounds = this.prevBounds;
let prevMatrix = this.prevMatrix;
if (prevBounds === null || prevMatrix === null) {
@@ -52,6 +55,12 @@ export class SetImageTransformCommand implements Command {
retargetClipPath(doc.module, img.pdfiumObjPtr, prevMatrix, next);
img.matrix = next;
img.bounds = imageMatrixBounds(next);
+ img.clip = readImageClip(
+ doc.module,
+ page.pagePtr,
+ img.pdfiumObjPtr,
+ img.containerPtr,
+ );
img.dirty = true;
page.markDirty();
page.markNeedsGenerate();
@@ -95,6 +104,12 @@ export class SetImageTransformCommand implements Command {
retargetClipPath(m, img.pdfiumObjPtr, img.matrix, this.prevMatrix);
img.bounds = { ...this.prevBounds };
img.matrix = { ...this.prevMatrix };
+ img.clip = readImageClip(
+ m,
+ page.pagePtr,
+ img.pdfiumObjPtr,
+ img.containerPtr,
+ );
img.dirty = true;
page.markDirty();
page.markNeedsGenerate();
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/commands/SetTextOutlineCommand.ts b/frontend/src/editor/core/tools/pdfTextEditor/commands/SetTextOutlineCommand.ts
index 95d8628220..86500e2351 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/commands/SetTextOutlineCommand.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/commands/SetTextOutlineCommand.ts
@@ -1,3 +1,5 @@
+import { liftRunToPage } from "@editor/tools/pdfTextEditor/commands/liftFromForm";
+import { refuseRedrawOfReadOnlyText } from "@editor/tools/pdfTextEditor/commands/readOnlyText";
import i18n from "i18next";
import type { Command } from "@editor/tools/pdfTextEditor/commands/Command";
import type { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
@@ -57,22 +59,23 @@ export class SetTextOutlineCommand implements Command {
const page = doc.page(this.pageIndex);
const run = page.findRun(this.runId);
if (!run) return;
+ refuseRedrawOfReadOnlyText(run);
+ liftRunToPage(doc, page, run);
- if (this.prev === null) {
- const seen = new Set<number>();
- const members: MemberInk[] = [];
- for (const ptr of collectMemberPtrs(run)) {
- if (!ptr || seen.has(ptr)) continue;
- seen.add(ptr);
- members.push(readMemberInk(doc, ptr, run));
- }
- this.prev = {
- renderMode: run.renderMode,
- stroke: run.stroke ? { ...run.stroke } : null,
- strokeWidth: run.strokeWidth,
- members,
- };
+ // Read on every apply: redoing an earlier step draws the run in new objects.
+ const seen = new Set<number>();
+ const members: MemberInk[] = [];
+ for (const ptr of collectMemberPtrs(run)) {
+ if (!ptr || seen.has(ptr)) continue;
+ seen.add(ptr);
+ members.push(readMemberInk(doc, ptr, run));
}
+ this.prev = {
+ renderMode: run.renderMode,
+ stroke: run.stroke ? { ...run.stroke } : null,
+ strokeWidth: run.strokeWidth,
+ members,
+ };
const outlined = this.nextStroke !== null && this.nextWidth > 0;
// An invisible OCR layer stays invisible, and a clipping mode (4-7) keeps
@@ -113,7 +116,6 @@ export class SetTextOutlineCommand implements Command {
stroke: member.stroke,
strokeWidth: member.strokeWidth,
});
- if (!member.stroke) clearStroke(doc, member.ptr);
}
page.markNeedsGenerate();
}
@@ -132,7 +134,6 @@ export class SetTextOutlineCommand implements Command {
stroke: run.stroke,
strokeWidth: run.strokeWidth,
});
- if (!run.stroke) clearStroke(doc, ptr);
}
doc.page(this.pageIndex).markNeedsGenerate();
}
@@ -191,14 +192,3 @@ function readMemberInk(
return { ptr, renderMode, stroke: null, strokeWidth: 0 };
}
}
-
-/** A zero-width transparent stroke is how PDFium expresses "no outline". */
-function clearStroke(doc: EditorDocument, ptr: number): void {
- const mod = doc.module as unknown as OutlineModule;
- try {
- mod.FPDFPageObj_SetStrokeWidth?.(ptr, 0);
- mod.FPDFPageObj_SetStrokeColor?.(ptr, 0, 0, 0, 0);
- } catch {
- /* best-effort */
- }
-}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/commands/StyleTextRangeCommand.ts b/frontend/src/editor/core/tools/pdfTextEditor/commands/StyleTextRangeCommand.ts
new file mode 100644
index 0000000000..c69068b9c6
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/commands/StyleTextRangeCommand.ts
@@ -0,0 +1,961 @@
+import i18n from "i18next";
+import type { WrappedPdfiumModule } from "@embedpdf/pdfium";
+import {
+ RolledBackError,
+ type Command,
+} from "@editor/tools/pdfTextEditor/commands/Command";
+import { liftRunToPage } from "@editor/tools/pdfTextEditor/commands/liftFromForm";
+import { ReflowWrapCommand } from "@editor/tools/pdfTextEditor/commands/ReflowWrapCommand";
+import {
+ refuseRedrawOfReadOnlyText,
+ unsafeRtlEditMessage,
+} from "@editor/tools/pdfTextEditor/commands/readOnlyText";
+import { isScanRun } from "@editor/tools/pdfTextEditor/commands/scanTextEdit";
+import {
+ charcodesResolveFully,
+ collectMemberPtrs,
+ contentIndices,
+ drawnEndPt,
+ droppedCharsOf,
+ emitTextLine,
+ measureObjSpanPt,
+ removeAndDestroyObject,
+ restoreContentOrder,
+ rotationFromMatrix,
+ warmOnPageAdvances,
+ type FontSpan,
+} from "@editor/tools/pdfTextEditor/commands/editTextHelpers";
+import { piecesFromObjects } from "@editor/tools/pdfTextEditor/commands/partialEdit";
+import {
+ ATTACHES_TO_PREVIOUS,
+ isSubsetFont,
+ losesLetters,
+} from "@editor/tools/pdfTextEditor/commands/SetFontFamilyCommand";
+import {
+ charOrigins,
+ readMatrix,
+ readTextSource,
+ writeMatrix,
+ type Point,
+ type TextSource,
+} from "@editor/tools/pdfTextEditor/commands/textPieces";
+import { readFontName } from "@editor/tools/pdfTextEditor/charcode/FontHelpers";
+import type { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
+import type { Page } from "@editor/tools/pdfTextEditor/model/Page";
+import {
+ cloneParagraphLineSlot,
+ type ParagraphLineSlot,
+ type TextRun,
+} from "@editor/tools/pdfTextEditor/model/TextRun";
+import { uniformTags } from "@editor/tools/pdfTextEditor/model/TextTags";
+import { readTagMarks } from "@editor/tools/pdfTextEditor/pdfium/PdfiumTagMarks";
+import { hasRtl } from "@editor/tools/pdfTextEditor/util/bidi";
+import { needsShaping } from "@editor/tools/pdfTextEditor/util/complexShaping";
+import {
+ deviceFamilyOf,
+ familyCoverage,
+} from "@editor/tools/pdfTextEditor/util/deviceFontEmbed";
+import {
+ documentFontIdAt,
+ noteDocumentFontStyle,
+} from "@editor/tools/pdfTextEditor/util/documentFontStyle";
+import { fallbackFamilyFor } from "@editor/tools/pdfTextEditor/util/fontCapability";
+import {
+ base14FontId,
+ deviceFontId,
+ documentFontHandle,
+ nearestStandardFont,
+ stripSubsetTag,
+} from "@editor/tools/pdfTextEditor/util/fontFamily";
+import { transformObject } from "@editor/tools/pdfTextEditor/util/objectTransform";
+import type { RGBA, TextRange } from "@editor/tools/pdfTextEditor/types";
+
+/**
+ * Characters `start` to `end` of a run's text, as code units, to draw in
+ * `face`: a value the font list gives, which is a document fontId, a standard
+ * font name or a device family.
+ */
+export interface FaceStretch {
+ start: number;
+ end: number;
+ face: string;
+}
+
+/** Characters `start` to `end` of a run's text, drawn in one font. */
+export interface FontStretch {
+ start: number;
+ end: number;
+ fontId: string;
+}
+
+/** Some of one run's characters, selected apart from the rest of it. */
+export interface SelectedPart {
+ page: Page;
+ run: TextRun;
+ range: TextRange;
+}
+
+/** Why a run's selected characters cannot be restyled on their own. */
+export type RangeRefusal = "rightToLeft" | "needsShaping" | "unsupported";
+
+interface Piece {
+ ptr: number;
+ text: string;
+ /** Where the piece's text starts in the run's text. */
+ start: number;
+ bounds: { x: number; right: number };
+}
+
+interface Line {
+ /** Index into the run's paragraph line slots; -1 when the run has none. */
+ slot: number;
+ pieces: Piece[];
+}
+
+interface Target {
+ fontPtr: number;
+ fallbackFamily: string;
+}
+
+interface Unit {
+ /** Code units of the piece's text. */
+ start: number;
+ end: number;
+ /** The face of each code unit of the unit, null where it keeps its own. */
+ targets: Array<Target | null>;
+}
+
+interface RunSnapshot {
+ bounds: TextRun["bounds"];
+ pdfiumObjPtr: number;
+ mergedFromPtrs: number[];
+ mergedFromTexts: string[];
+ mergedFromBounds: Array<{ x: number; right: number }>;
+ mergedFromCharStarts: number[];
+ paragraphMemberPtrs: number[];
+ paragraphLeafPtrs: number[];
+ paragraphLeafContainers: number[];
+ paragraphLineSlots: ParagraphLineSlot[];
+}
+
+/**
+ * Restyle some characters of a run, leaving the rest of it as it is drawn. The
+ * objects holding those characters are redrawn word by word where their words
+ * already stood, each stretch in its own font as typing beside a styled word
+ * draws it, and the text after them on the line moves by the width the change
+ * adds or takes away. A character the new face has no glyph for stays in the
+ * font that drew it. Lines drawn right to left or needing shaping are refused,
+ * as their letters cannot be redrawn one stretch at a time.
+ */
+export class StyleTextRangeCommand implements Command {
+ readonly type = "style-text-range";
+ private readonly pageIndex: number;
+ private readonly runId: string;
+ private readonly faces: readonly FaceStretch[];
+ private readonly wrapWidthPt: number | null;
+ private prev: RunSnapshot | null = null;
+ private removed: Array<{ ptr: number; index: number }> = [];
+ private created: number[] = [];
+ private shifted: Array<{ ptr: number; dx: number; matrix: Float32Array }> =
+ [];
+ private reflow: ReflowWrapCommand | null = null;
+
+ /** `wrapWidthPt` is the width the run's lines rewrap to when a change makes one overflow it; null never rewraps. */
+ constructor(opts: {
+ pageIndex: number;
+ runId: string;
+ faces: readonly FaceStretch[];
+ wrapWidthPt?: number | null;
+ }) {
+ this.pageIndex = opts.pageIndex;
+ this.runId = opts.runId;
+ this.faces = opts.faces;
+ this.wrapWidthPt = opts.wrapWidthPt ?? null;
+ }
+
+ /** Why this change cannot be made, or null when it can. */
+ refusal(doc: EditorDocument): RangeRefusal | null {
+ const page = doc.page(this.pageIndex);
+ const run = page.findRun(this.runId);
+ if (!run) return "unsupported";
+ const lines = runLines(doc, page, run);
+ if (typeof lines === "string") return lines;
+ const changes = this.changes(doc, page, run, lines).targets;
+ return piecesRefusal(doc, lines, (piece) => touches(piece, changes));
+ }
+
+ /**
+ * How much of the selection that is not already in its new face that face
+ * has glyphs for. The rest stays in the font that drew it.
+ */
+ coverage(doc: EditorDocument): "all" | "some" | "none" | "unchanged" {
+ const page = doc.page(this.pageIndex);
+ const run = page.findRun(this.runId);
+ const lines = run && linesOf(doc, page, run);
+ if (!run || !lines) return "unchanged";
+ const { targets, kept } = this.changes(doc, page, run, lines);
+ if (kept === 0) return targets.size === 0 ? "unchanged" : "all";
+ return targets.size === 0 ? "none" : "some";
+ }
+
+ apply(doc: EditorDocument): void {
+ const page = doc.page(this.pageIndex);
+ const run = page.findRun(this.runId);
+ this.prev = null;
+ if (!run) return;
+ refuseRedrawOfReadOnlyText(run);
+ const refusal = this.refusal(doc);
+ if (refusal === "rightToLeft")
+ throw new RolledBackError(new Error(unsafeRtlEditMessage()));
+ if (refusal === "needsShaping")
+ throw new RolledBackError(new Error(cannotRestyleMessage()));
+ if (refusal) return;
+ liftRunToPage(doc, page, run);
+ const lines = linesOf(doc, page, run);
+ if (!lines) return;
+ const { targets } = this.changes(doc, page, run, lines);
+ if (targets.size === 0) return;
+
+ const m = doc.module;
+ this.prev = snapshotRun(run);
+ this.removed = [];
+ this.created = [];
+ this.shifted = [];
+ this.reflow = null;
+ const touched = lines.flatMap((line) =>
+ line.pieces.filter((piece) => touches(piece, targets)),
+ );
+ const order = contentIndices(
+ m,
+ page.pagePtr,
+ touched.map((piece) => piece.ptr),
+ );
+ const origins = charOrigins(
+ m,
+ page.pagePtr,
+ new Map(touched.map((piece) => [piece.ptr, piece.text])),
+ );
+ const spanBefore = measureObjSpanPt(m, collectMemberPtrs(run));
+ warmOnPageAdvances(m, page.pagePtr);
+
+ const redrawn = new Map<number, Piece[]>();
+ const dropped = droppedCharsOf(() => {
+ for (const line of lines) {
+ if (!line.pieces.some((piece) => touches(piece, targets))) continue;
+ line.pieces = this.redrawLine(doc, page, run, line, targets, {
+ origins,
+ order,
+ redrawn,
+ });
+ }
+ });
+ if (losesLetters(dropped)) {
+ this.takeBackObjects(doc, page);
+ restoreRun(run, this.prev);
+ this.prev = null;
+ throw new RolledBackError(new Error(missingGlyphsMessage()));
+ }
+ updateRunModel(run, lines, redrawn);
+ const spanAfter = measureObjSpanPt(m, collectMemberPtrs(run));
+ if (spanBefore && spanAfter)
+ run.bounds = {
+ ...run.bounds,
+ width: Math.max(
+ 0,
+ run.bounds.width + spanAfter.right - spanBefore.right,
+ ),
+ };
+ run.charPositionsKey = null;
+ run.dirty = true;
+ page.markDirty();
+ page.markNeedsGenerate();
+ if (this.wrapWidthPt !== null && this.wrapWidthPt > 0) {
+ this.reflow = new ReflowWrapCommand({
+ pageIndex: this.pageIndex,
+ runId: this.runId,
+ maxWidthPt: this.wrapWidthPt,
+ keepClearBelow: true,
+ });
+ this.reflow.apply(doc);
+ }
+ }
+
+ revert(doc: EditorDocument): void {
+ if (!this.prev) return;
+ const page = doc.page(this.pageIndex);
+ const run = page.findRun(this.runId);
+ if (!run) return;
+ this.reflow?.revert(doc);
+ this.reflow = null;
+ this.takeBackObjects(doc, page);
+ restoreRun(run, this.prev);
+ this.prev = null;
+ run.charPositionsKey = null;
+ run.dirty = true;
+ page.markDirty();
+ page.markNeedsGenerate();
+ }
+
+ private takeBackObjects(doc: EditorDocument, page: Page): void {
+ const m = doc.module;
+ for (const ptr of this.created)
+ removeAndDestroyObject(m, page.pagePtr, ptr);
+ for (const { ptr } of this.removed)
+ m.FPDFPage_InsertObject(page.pagePtr, ptr);
+ restoreContentOrder(m, page.pagePtr, this.removed);
+ for (const { ptr, dx, matrix } of [...this.shifted].reverse()) {
+ transformObject(m, ptr, 1, 0, 0, 1, -dx, 0);
+ writeMatrix(m, ptr, matrix);
+ }
+ this.created = [];
+ this.removed = [];
+ this.shifted = [];
+ }
+
+ /** The face each character of the selection changes to, and how many the face it was given has no glyph for. */
+ private changes(
+ doc: EditorDocument,
+ page: Page,
+ run: TextRun,
+ lines: readonly Line[],
+ ): { targets: Map<number, Target>; kept: number } {
+ const m = doc.module;
+ const fontAt = new Map<number, number>();
+ for (const line of lines)
+ for (const piece of line.pieces) {
+ const font = piece.ptr ? m.FPDFTextObj_GetFont(piece.ptr) : 0;
+ for (let c = 0; c < piece.text.length; c++)
+ fontAt.set(piece.start + c, font);
+ }
+ const targets = new Map<number, Target>();
+ const idOf = fontIdNamer(doc);
+ let kept = 0;
+ for (const { start, end, face } of this.faces) {
+ const target = targetOf(face);
+ const draws = facesDraw(doc, page, face, target);
+ const faceId = fontIdOfFace(face);
+ for (let c = Math.max(0, start); c < Math.min(end, run.text.length);) {
+ const ch = String.fromCodePoint(run.text.codePointAt(c)!);
+ const at = c;
+ c += ch.length;
+ const font = fontAt.get(at);
+ if (/\s/.test(ch) || font === undefined) continue;
+ const already = target.fontPtr
+ ? font === target.fontPtr
+ : idOf(font) === faceId;
+ if (already) continue;
+ if (!draws(ch)) {
+ kept++;
+ continue;
+ }
+ for (let u = at; u < c; u++) targets.set(u, target);
+ }
+ }
+ return { targets, kept };
+ }
+
+ private redrawLine(
+ doc: EditorDocument,
+ page: Page,
+ run: TextRun,
+ line: Line,
+ targets: ReadonlyMap<number, Target>,
+ read: {
+ origins: ReadonlyMap<number, ReadonlyMap<number, Point>>;
+ order: ReadonlyMap<number, number>;
+ redrawn: Map<number, Piece[]>;
+ },
+ ): Piece[] {
+ const m = doc.module;
+ let offset = 0;
+ const out: Piece[] = [];
+ for (const piece of line.pieces) {
+ if (!touches(piece, targets)) {
+ if (Math.abs(offset) > 0.001 && piece.ptr) {
+ const matrix = readMatrix(m, piece.ptr);
+ if (matrix) {
+ transformObject(m, piece.ptr, 1, 0, 0, 1, offset, 0);
+ this.shifted.push({ ptr: piece.ptr, dx: offset, matrix });
+ }
+ }
+ out.push({
+ ...piece,
+ bounds: {
+ x: piece.bounds.x + offset,
+ right: piece.bounds.right + offset,
+ },
+ });
+ continue;
+ }
+ const source = readTextSource(m, piece.ptr)!;
+ const units = unitsOf(piece, targets);
+ const origins = read.origins.get(piece.ptr);
+ const placed =
+ origins && units.every((unit) => origins.has(unit.start))
+ ? origins
+ : null;
+ const index = contentIndices(m, page.pagePtr, [piece.ptr]).get(piece.ptr);
+ m.FPDFPage_RemoveObject(page.pagePtr, piece.ptr);
+ this.removed.push({
+ ptr: piece.ptr,
+ index: read.order.get(piece.ptr) ?? index ?? 0,
+ });
+ const drawn: Piece[] = [];
+ const draw = (unit: Unit, x: number): DrawnUnit => {
+ const result = drawUnit(doc, page, run, piece, source, unit, x);
+ drawn.push(...result.pieces);
+ return result;
+ };
+ if (placed) {
+ let before: { end: number; penEnd: number } | null = null;
+ for (const unit of units) {
+ const origin = placed.get(unit.start)!.x;
+ // A word split only where its font changes reads as one word only when its parts abut.
+ if (before?.end === unit.start) offset = before.penEnd - origin;
+ const result = draw(unit, origin + offset);
+ offset += result.widthChange;
+ before = { end: unit.end, penEnd: result.penEnd };
+ }
+ } else {
+ offset += draw(
+ {
+ start: 0,
+ end: piece.text.length,
+ targets: pieceTargets(piece, targets),
+ },
+ source.matrix[4] + offset,
+ ).widthChange;
+ }
+ const ptrs = drawn.map((p) => p.ptr);
+ this.created.push(...ptrs);
+ if (index !== undefined)
+ restoreContentOrder(
+ m,
+ page.pagePtr,
+ ptrs.map((ptr, k) => ({ ptr, index: index + k })),
+ );
+ read.redrawn.set(piece.ptr, drawn);
+ out.push(...drawn);
+ }
+ return out;
+ }
+}
+
+/** The face of each code unit of a piece, a space taking the one before it. */
+function pieceTargets(
+ piece: Piece,
+ targets: ReadonlyMap<number, Target>,
+): Array<Target | null> {
+ const out: Array<Target | null> = [];
+ for (let c = 0; c < piece.text.length; c++) {
+ const own = targets.get(piece.start + c) ?? null;
+ out.push(/\s/.test(piece.text[c]) && c > 0 ? out[c - 1] : own);
+ }
+ return out;
+}
+
+/** The run's lines, or why none of its pieces can be restyled on their own. */
+function runLines(
+ doc: EditorDocument,
+ page: Page,
+ run: TextRun,
+): Line[] | RangeRefusal {
+ if (run.textReadOnly) return "rightToLeft";
+ if (isScanRun(run) || run.scanEdit || rotationFromMatrix(run.matrix))
+ return "unsupported";
+ return linesOf(doc, page, run) ?? "unsupported";
+}
+
+/** Why the pieces `restyles` picks cannot be redrawn on their own, or null when they can. */
+function piecesRefusal(
+ doc: EditorDocument,
+ lines: readonly Line[],
+ restyles: (piece: Piece) => boolean,
+): RangeRefusal | null {
+ for (const line of lines) {
+ const picked = line.pieces.filter(restyles);
+ if (picked.length === 0) continue;
+ // A line's later pieces are moved along it, which is only the way it reads when it runs left to right.
+ if (hasRtl(line.pieces.map((piece) => piece.text).join("")))
+ return "rightToLeft";
+ if (
+ picked.some(
+ (p) => needsShaping(p.text) || ATTACHES_TO_PREVIOUS.test(p.text),
+ )
+ )
+ return "needsShaping";
+ for (const piece of picked) {
+ const at = line.pieces.indexOf(piece);
+ if (line.pieces[at + 1]?.text === "") return "unsupported";
+ const source = readTextSource(doc.module, piece.ptr);
+ if (!source || !upright(source.matrix)) return "unsupported";
+ }
+ }
+ return null;
+}
+
+/** Why the characters `range` covers cannot be restyled apart from the rest of `run`, or null when they can. */
+export function rangeRefusal(
+ doc: EditorDocument,
+ page: Page,
+ run: TextRun,
+ range: TextRange,
+): RangeRefusal | null {
+ const lines = runLines(doc, page, run);
+ if (typeof lines === "string") return lines;
+ return piecesRefusal(
+ doc,
+ lines,
+ (piece) =>
+ piece.start < range.end && piece.start + piece.text.length > range.start,
+ );
+}
+
+/**
+ * The stretches of a piece drawn apart: each run of letters in one face, split
+ * at spaces. Each goes where its first letter stood, so the words a change
+ * leaves alone keep their places on a justified or kerned line.
+ */
+function unitsOf(piece: Piece, targets: ReadonlyMap<number, Target>): Unit[] {
+ const units: Unit[] = [];
+ let open: Unit | null = null;
+ for (let c = 0; c < piece.text.length; c++) {
+ const ch = piece.text[c];
+ if (/\s/.test(ch)) {
+ open = null;
+ continue;
+ }
+ const target = targets.get(piece.start + c) ?? null;
+ const low = c > 0 && /[\udc00-\udfff]/.test(ch);
+ if (open && (low || open.targets[open.targets.length - 1] === target)) {
+ open.end = c + 1;
+ open.targets.push(target);
+ } else {
+ open = { start: c, end: c + 1, targets: [target] };
+ units.push(open);
+ }
+ }
+ return units;
+}
+
+interface DrawnUnit {
+ pieces: Piece[];
+ widthChange: number;
+ /**
+ * Where a letter drawn straight after the unit starts: its pen position plus
+ * the run's letter spacing, as within one object, not its ink edge.
+ */
+ penEnd: number;
+}
+
+function drawUnit(
+ doc: EditorDocument,
+ page: Page,
+ run: TextRun,
+ piece: Piece,
+ source: TextSource,
+ unit: Unit,
+ x: number,
+): DrawnUnit {
+ const m = doc.module;
+ const text = piece.text.slice(unit.start, unit.end);
+ const size = source.size * Math.hypot(source.matrix[0], source.matrix[1]);
+ const ownFallback =
+ deviceFamilyOf(doc, source.font) ??
+ fallbackFamilyFor(
+ `pdf:${source.font}:${stripSubsetTag(readFontName(m, source.font) ?? "")}`,
+ );
+ const fill: RGBA = source.fill ?? run.fill;
+ const common = {
+ doc,
+ page,
+ y: source.matrix[5],
+ fontSize: size,
+ fill,
+ renderMode: source.renderMode,
+ stroke: source.stroke,
+ strokeWidth: source.strokeWidth ?? undefined,
+ tags: uniformTags(readTagMarks(m, piece.ptr)),
+ charSpacingPt: run.charSpacingPt,
+ };
+ const spans: FontSpan[] = [];
+ unit.targets.forEach((target, i) => {
+ const font = target ? target.fontPtr : source.font;
+ const family = target ? target.fallbackFamily : ownFallback;
+ const last = spans[spans.length - 1];
+ if (last && last.fontPtr === font && last.fallbackFamily === family)
+ last.end = i + 1;
+ else spans.push({ end: i + 1, fontPtr: font, fallbackFamily: family });
+ });
+ const restyled = unit.targets.some(Boolean);
+ const outTexts: string[] = [];
+ const ptrs = emitTextLine({
+ ...common,
+ text,
+ x,
+ originalFontPtr: spans.length === 1 ? spans[0].fontPtr : 0,
+ originalFontSubset: isSubsetFont(m, spans[0].fontPtr),
+ fallbackFamily: spans[0].fallbackFamily,
+ fontSpans: spans.length > 1 ? spans : undefined,
+ outTexts,
+ });
+ let widthChange = 0;
+ if (restyled) {
+ // Against the letters drawn as they were from the same place, ink to ink:
+ // a subset font's advances cannot be looked up by character. What that
+ // draw drops is no loss.
+ let before = 0;
+ droppedCharsOf(() => {
+ const probe = emitTextLine({
+ ...common,
+ text,
+ x,
+ originalFontPtr: source.font,
+ originalFontSubset: isSubsetFont(m, source.font),
+ fallbackFamily: ownFallback,
+ });
+ before = measureObjSpanPt(m, probe)?.right ?? x;
+ for (const ptr of probe) removeAndDestroyObject(m, page.pagePtr, ptr);
+ });
+ widthChange = (measureObjSpanPt(m, ptrs)?.right ?? x) - before;
+ }
+ return {
+ pieces: placedPieces(m, ptrs, outTexts, text, piece.start + unit.start, x),
+ widthChange,
+ penEnd: drawnEndPt(m, ptrs, outTexts, size) + run.charSpacingPt,
+ };
+}
+
+function placedPieces(
+ m: WrappedPdfiumModule,
+ ptrs: readonly number[],
+ texts: readonly string[],
+ text: string,
+ start: number,
+ x: number,
+): Piece[] {
+ let cursor = 0;
+ return ptrs.map((ptr, i) => {
+ const carried = (texts[i] ?? "").trim();
+ const at = carried ? text.indexOf(carried, cursor) : -1;
+ const from = at >= 0 ? at : cursor;
+ const piece = carried && at >= 0 ? carried : text.slice(cursor);
+ cursor = from + piece.length;
+ const span = measureObjSpanPt(m, [ptr]);
+ return {
+ ptr,
+ text: piece,
+ start: start + from,
+ bounds: span ? { x: span.left, right: span.right } : { x, right: x },
+ };
+ });
+}
+
+/** The run's pieces line by line, each with where its text sits in the run's; null when they cannot be matched to it. */
+function linesOf(doc: EditorDocument, page: Page, run: TextRun): Line[] | null {
+ const m = doc.module;
+ const boundsOf = (ptr: number) => {
+ const span = ptr ? measureObjSpanPt(m, [ptr]) : null;
+ return span ? { x: span.left, right: span.right } : { x: 0, right: 0 };
+ };
+ let lines: Line[];
+ if (run.paragraphLineSlots.length > 0) {
+ lines = run.paragraphLineSlots.map((slot, i) => ({
+ slot: i,
+ pieces: slot.mergedFromPtrs.map((ptr, k) => ({
+ ptr,
+ text: slot.mergedFromTexts[k] ?? "",
+ start: slot.startChar + (slot.mergedFromCharStarts[k] ?? 0),
+ bounds: slot.mergedFromBounds[k] ?? boundsOf(ptr),
+ })),
+ }));
+ } else {
+ const parallel =
+ run.mergedFromPtrs.length > 0 &&
+ run.mergedFromTexts.length === run.mergedFromPtrs.length &&
+ run.mergedFromCharStarts.length === run.mergedFromPtrs.length;
+ const own = parallel
+ ? run
+ : piecesFromObjects(
+ m,
+ page.pagePtr,
+ collectMemberPtrs(run).filter(Boolean),
+ run.text,
+ );
+ if (!own) return null;
+ const byLine = new Map<number, Piece[]>();
+ own.mergedFromPtrs.forEach((ptr, k) => {
+ const start = own.mergedFromCharStarts[k] ?? 0;
+ const lineIndex = run.text.slice(0, start).split("\n").length - 1;
+ const pieces = byLine.get(lineIndex) ?? [];
+ pieces.push({
+ ptr,
+ text: own.mergedFromTexts[k] ?? "",
+ start,
+ bounds: (parallel && run.mergedFromBounds[k]) || boundsOf(ptr),
+ });
+ byLine.set(lineIndex, pieces);
+ });
+ lines = [...byLine.keys()]
+ .sort((a, b) => a - b)
+ .map((key) => ({ slot: -1, pieces: byLine.get(key)! }));
+ }
+ const spelled = lines.every((line) =>
+ line.pieces.every(
+ (piece) =>
+ run.text.slice(piece.start, piece.start + piece.text.length) ===
+ piece.text,
+ ),
+ );
+ return spelled ? lines : null;
+}
+
+/** Each stretch of the run's text drawn in one font, by the font of the piece drawing it; a space takes the font before it. */
+function fontStretchesOf(
+ doc: EditorDocument,
+ page: Page,
+ run: TextRun,
+): FontStretch[] {
+ const m = doc.module;
+ const lines = isScanRun(run) || run.scanEdit ? null : linesOf(doc, page, run);
+ const fontAt = new Array<number>(run.text.length).fill(0);
+ for (const line of lines ?? [])
+ for (const piece of line.pieces) {
+ const font = piece.ptr ? m.FPDFTextObj_GetFont(piece.ptr) : 0;
+ for (let c = 0; c < piece.text.length; c++)
+ if (piece.start + c < fontAt.length) fontAt[piece.start + c] = font;
+ }
+ for (let c = 1; c < fontAt.length; c++) fontAt[c] ||= fontAt[c - 1];
+ for (let c = fontAt.length - 2; c >= 0; c--) fontAt[c] ||= fontAt[c + 1];
+ const runFont = documentFontHandle(run.fontId);
+ const idOf = fontIdNamer(doc);
+ const stretches: FontStretch[] = [];
+ for (let c = 0; c < fontAt.length;) {
+ const font = fontAt[c];
+ let end = c + 1;
+ while (end < fontAt.length && fontAt[end] === font) end++;
+ stretches.push({
+ start: c,
+ end,
+ fontId: !font || font === runFont ? run.fontId : idOf(font),
+ });
+ c = end;
+ }
+ return stretches;
+}
+
+/**
+ * The fonts drawing the selected characters of `run`, one entry per font,
+ * spaces left out unless nothing else is selected.
+ */
+export function rangeFontIds(
+ doc: EditorDocument,
+ page: Page,
+ run: TextRun,
+ range: TextRange,
+): string[] {
+ const stretches = fontStretchesOf(doc, page, run).filter(
+ (s) => s.end > range.start && s.start < range.end,
+ );
+ const inked = stretches.filter((s) =>
+ /\S/.test(
+ run.text.slice(
+ Math.max(s.start, range.start),
+ Math.min(s.end, range.end),
+ ),
+ ),
+ );
+ return [
+ ...new Set((inked.length > 0 ? inked : stretches).map((s) => s.fontId)),
+ ];
+}
+
+/** The selected stretches of `run`, each with the font that draws it, spaces left with their neighbours. */
+export function selectedFontStretches(
+ doc: EditorDocument,
+ page: Page,
+ run: TextRun,
+ range: TextRange,
+): FontStretch[] {
+ return fontStretchesOf(doc, page, run)
+ .map((s) => ({
+ ...s,
+ start: Math.max(s.start, range.start),
+ end: Math.min(s.end, range.end),
+ }))
+ .filter(
+ (s) => s.end > s.start && /\S/.test(run.text.slice(s.start, s.end)),
+ );
+}
+
+/** Names fonts as {@link fontIdOf} does, each font once. */
+function fontIdNamer(doc: EditorDocument): (font: number) => string {
+ const names = new Map<number, string>();
+ return (font) => {
+ let name = names.get(font);
+ if (name === undefined) names.set(font, (name = fontIdOf(doc, font)));
+ return name;
+ };
+}
+
+/** The fontId a font a run is drawn in goes by, as the reader or a font change would name it. */
+function fontIdOf(doc: EditorDocument, font: number): string {
+ const device = deviceFamilyOf(doc, font);
+ if (device) return deviceFontId(device);
+ const read = documentFontIdAt(font);
+ if (read) return read;
+ const name = stripSubsetTag(readFontName(doc.module, font) ?? "");
+ if (name && nearestStandardFont(name) === name) return base14FontId(name);
+ noteDocumentFontStyle(doc.module, font);
+ return documentFontIdAt(font) ?? `pdf:${font}:${name}`;
+}
+
+function fontIdOfFace(face: string): string {
+ if (documentFontHandle(face)) return face;
+ return nearestStandardFont(face) === face
+ ? base14FontId(face)
+ : deviceFontId(face);
+}
+
+function targetOf(face: string): Target {
+ const handle = documentFontHandle(face);
+ return handle
+ ? { fontPtr: handle, fallbackFamily: fallbackFamilyFor(face) }
+ : { fontPtr: 0, fallbackFamily: face };
+}
+
+function facesDraw(
+ doc: EditorDocument,
+ page: Page,
+ face: string,
+ target: Target,
+): (ch: string) => boolean {
+ if (target.fontPtr)
+ return (ch) =>
+ charcodesResolveFully(
+ doc.module,
+ target.fontPtr,
+ ch,
+ page.pagePtr,
+ doc.docPtr,
+ );
+ const covers = familyCoverage(doc, face);
+ return covers ? (ch) => covers(ch.codePointAt(0)!) : () => true;
+}
+
+function touches(piece: Piece, targets: ReadonlyMap<number, Target>): boolean {
+ for (let c = 0; c < piece.text.length; c++)
+ if (targets.has(piece.start + c)) return true;
+ return false;
+}
+
+/** Unrotated, unslanted and scaled alike both ways, as a redrawn word is: a word processor's 0.2% stretch is within that. */
+function upright(matrix: Float32Array): boolean {
+ const [a, b, c, d] = matrix;
+ return (
+ a > 0 &&
+ Math.abs(b) < 1e-3 * a &&
+ Math.abs(c) < 1e-3 * a &&
+ Math.abs(a - d) < 0.01 * a
+ );
+}
+
+function updateRunModel(
+ run: TextRun,
+ lines: readonly Line[],
+ redrawn: ReadonlyMap<number, Piece[]>,
+): void {
+ for (const line of lines) {
+ if (line.slot < 0) continue;
+ const slot = run.paragraphLineSlots[line.slot];
+ slot.mergedFromPtrs = line.pieces.map((p) => p.ptr);
+ slot.mergedFromTexts = line.pieces.map((p) => p.text);
+ slot.mergedFromBounds = line.pieces.map((p) => ({ ...p.bounds }));
+ slot.mergedFromCharStarts = line.pieces.map(
+ (p) => p.start - slot.startChar,
+ );
+ }
+ const all = lines.flatMap((line) => line.pieces);
+ const own = run.paragraphLineSlots.length > 0 ? lines[0].pieces : all;
+ run.mergedFromPtrs = own.map((p) => p.ptr);
+ run.mergedFromTexts = own.map((p) => p.text);
+ run.mergedFromBounds = own.map((p) => ({ ...p.bounds }));
+ const ownStart = run.paragraphLineSlots[0]?.startChar ?? 0;
+ run.mergedFromCharStarts = own.map((p) => p.start - ownStart);
+ if (
+ run.paragraphLineSlots.length > 0 ||
+ run.paragraphLeafPtrs.length > 0 ||
+ run.paragraphMemberPtrs.length > 0
+ ) {
+ run.paragraphLeafPtrs = all.map((p) => p.ptr);
+ run.paragraphLeafContainers = all.map(() => 0);
+ }
+ const replaced = (ptr: number) => redrawn.get(ptr)?.[0]?.ptr ?? ptr;
+ run.paragraphMemberPtrs = run.paragraphMemberPtrs.map(replaced);
+ run.pdfiumObjPtr = replaced(run.pdfiumObjPtr);
+}
+
+function snapshotRun(run: TextRun): RunSnapshot {
+ return {
+ bounds: { ...run.bounds },
+ pdfiumObjPtr: run.pdfiumObjPtr,
+ mergedFromPtrs: [...run.mergedFromPtrs],
+ mergedFromTexts: [...run.mergedFromTexts],
+ mergedFromBounds: run.mergedFromBounds.map((b) => ({ ...b })),
+ mergedFromCharStarts: [...run.mergedFromCharStarts],
+ paragraphMemberPtrs: [...run.paragraphMemberPtrs],
+ paragraphLeafPtrs: [...run.paragraphLeafPtrs],
+ paragraphLeafContainers: [...run.paragraphLeafContainers],
+ paragraphLineSlots: run.paragraphLineSlots.map(cloneParagraphLineSlot),
+ };
+}
+
+function restoreRun(run: TextRun, snap: RunSnapshot): void {
+ run.bounds = { ...snap.bounds };
+ run.pdfiumObjPtr = snap.pdfiumObjPtr;
+ run.mergedFromPtrs = [...snap.mergedFromPtrs];
+ run.mergedFromTexts = [...snap.mergedFromTexts];
+ run.mergedFromBounds = snap.mergedFromBounds.map((b) => ({ ...b }));
+ run.mergedFromCharStarts = [...snap.mergedFromCharStarts];
+ run.paragraphMemberPtrs = [...snap.paragraphMemberPtrs];
+ run.paragraphLeafPtrs = [...snap.paragraphLeafPtrs];
+ run.paragraphLeafContainers = [...snap.paragraphLeafContainers];
+ run.paragraphLineSlots = snap.paragraphLineSlots.map(cloneParagraphLineSlot);
+}
+
+function cannotRestyleMessage(): string {
+ return i18n.t(
+ "pdfTextEditor.fontPicker.needsShaping",
+ "The editor can't yet redraw this script's joined letters and vowel signs correctly, so that text was left in its current font.",
+ );
+}
+
+function missingGlyphsMessage(): string {
+ return i18n.t(
+ "pdfTextEditor.fontPicker.missingGlyphs",
+ "This font is missing some of the selected characters, and they could not be kept in their current font. The text was left unchanged.",
+ );
+}
+
+/**
+ * The run and the characters of it the selection holds, when they leave some
+ * of its letters out; null when nothing within a run is selected or the whole
+ * of one is, which a change applies to as a box.
+ */
+export function selectedPartOfRun(
+ doc: EditorDocument | null,
+ selection: { runIds: readonly string[]; textRange: TextRange | null },
+): SelectedPart | null {
+ const range = selection.textRange;
+ if (!doc || !range || selection.runIds.length !== 1) return null;
+ for (const page of doc.loadedPages()) {
+ const run = page.findRun(selection.runIds[0]);
+ if (!run) continue;
+ const start = Math.max(0, Math.min(range.start, run.text.length));
+ const end = Math.max(start, Math.min(range.end, run.text.length));
+ if (end === start) return null;
+ const outside = run.text.slice(0, start) + run.text.slice(end);
+ return /\S/.test(outside) ? { page, run, range: { start, end } } : null;
+ }
+ return null;
+}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/commands/TagTextRangeCommand.ts b/frontend/src/editor/core/tools/pdfTextEditor/commands/TagTextRangeCommand.ts
index 0b03943d20..5616277a41 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/commands/TagTextRangeCommand.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/commands/TagTextRangeCommand.ts
@@ -38,6 +38,7 @@ import {
type LeafList,
} from "@editor/tools/pdfTextEditor/commands/runLeaves";
import type { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
+import { insertPageObjectAt } from "@editor/tools/pdfTextEditor/util/insertPageObject";
import type { Page } from "@editor/tools/pdfTextEditor/model/Page";
import {
isInlineType,
@@ -487,7 +488,7 @@ function redraw(
if (!kept) {
const index = pageObjects(m, page).indexOf(ptr);
m.FPDFPage_RemoveObject(page.pagePtr, ptr);
- undo.push(() => m.FPDFPage_InsertObjectAtIndex(page.pagePtr, ptr, index));
+ undo.push(() => insertPageObjectAt(m, page.pagePtr, ptr, index));
continue;
}
const matrix = readMatrix(m, ptr);
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/commands/TransformImageObjectCommand.ts b/frontend/src/editor/core/tools/pdfTextEditor/commands/TransformImageObjectCommand.ts
index 4cb8bbaf38..0dc6868ac2 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/commands/TransformImageObjectCommand.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/commands/TransformImageObjectCommand.ts
@@ -1,7 +1,12 @@
+import { liftImageToPage } from "@editor/tools/pdfTextEditor/commands/liftFromForm";
import type { Command } from "@editor/tools/pdfTextEditor/commands/Command";
import type { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
import type { Affine } from "@editor/tools/pdfTextEditor/types";
import { retargetClipPath } from "@editor/tools/pdfTextEditor/util/objectTransform";
+import {
+ readImageClip,
+ visibleImageBounds,
+} from "@editor/tools/pdfTextEditor/util/imageClip";
// Apply an in-place transform to an image: rotate by 90° (CW or CCW), flip
// horizontally, or flip vertically.
@@ -45,12 +50,27 @@ export class TransformImageObjectCommand implements Command {
const page = doc.page(this.pageIndex);
const img = page.findImage(this.imageId);
if (!img || !img.pdfiumObjPtr) return;
+ if (!liftImageToPage(doc, page, img)) return;
if (this.prevMatrix === null) this.prevMatrix = { ...img.matrix };
- const next = composeAboutCentre(img.matrix, this.mode);
+ // About the centre of what shows, so a clipped image turns in place
+ // rather than swinging its window around the hidden part.
+ const shown = visibleImageBounds(img);
+ const next = composeAboutCentre(
+ img.matrix,
+ this.mode,
+ shown.x + shown.width / 2,
+ shown.y + shown.height / 2,
+ );
setMatrix(doc, img.pdfiumObjPtr, next);
retargetClipPath(doc.module, img.pdfiumObjPtr, img.matrix, next);
img.matrix = next;
img.bounds = matrixBoundsAxisAligned(next);
+ img.clip = readImageClip(
+ doc.module,
+ page.pagePtr,
+ img.pdfiumObjPtr,
+ img.containerPtr,
+ );
img.dirty = true;
page.markDirty();
page.markNeedsGenerate();
@@ -65,17 +85,26 @@ export class TransformImageObjectCommand implements Command {
retargetClipPath(doc.module, img.pdfiumObjPtr, img.matrix, this.prevMatrix);
img.matrix = { ...this.prevMatrix };
img.bounds = matrixBoundsAxisAligned(this.prevMatrix);
+ img.clip = readImageClip(
+ doc.module,
+ page.pagePtr,
+ img.pdfiumObjPtr,
+ img.containerPtr,
+ );
img.dirty = true;
page.markDirty();
page.markNeedsGenerate();
}
}
-// Compose `T(cx, cy) * Op * T(-cx, -cy) * M` where M is the input matrix, Op is
-// the rotation/flip, and (cx, cy) is M's image-centre in page space.
-function composeAboutCentre(m: Affine, mode: ImageTransformMode): Affine {
- const cx = m.e + (m.a + m.c) / 2;
- const cy = m.f + (m.b + m.d) / 2;
+// Compose `T(cx, cy) * Op * T(-cx, -cy) * M` where M is the input matrix and
+// Op is the rotation/flip about the page-space point (cx, cy).
+function composeAboutCentre(
+ m: Affine,
+ mode: ImageTransformMode,
+ cx: number,
+ cy: number,
+): Affine {
// Op transforms image-space (post-rotation/flip is applied to page-space
// output).
let oa: number, ob: number, oc: number, od: number;
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/commands/UngroupParagraphCommand.ts b/frontend/src/editor/core/tools/pdfTextEditor/commands/UngroupParagraphCommand.ts
index 87210f2dc0..2f0972c9f1 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/commands/UngroupParagraphCommand.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/commands/UngroupParagraphCommand.ts
@@ -7,6 +7,7 @@ import {
TextRun,
} from "@editor/tools/pdfTextEditor/model/TextRun";
import { readTagMarks } from "@editor/tools/pdfTextEditor/pdfium/PdfiumTagMarks";
+import { readMatrix } from "@editor/tools/pdfTextEditor/commands/textPieces";
/** Split a paragraph-grouped run back into one editable run per source line. */
interface RepSnapshot {
@@ -28,6 +29,13 @@ export class UngroupParagraphCommand implements Command {
private prev: RepSnapshot | null = null;
private createdRunIds: string[] = [];
+ private prevLineObjects: {
+ ptrs: number[];
+ texts: string[];
+ bounds: Array<{ x: number; right: number }>;
+ charStarts: number[];
+ } = { ptrs: [], texts: [], bounds: [], charStarts: [] };
+
constructor(opts: { pageIndex: number; runId: string }) {
this.pageIndex = opts.pageIndex;
this.runId = opts.runId;
@@ -56,6 +64,12 @@ export class UngroupParagraphCommand implements Command {
paragraphLineSlots: rep.paragraphLineSlots.map(cloneParagraphLineSlot),
};
+ this.prevLineObjects = {
+ ptrs: [...rep.mergedFromPtrs],
+ texts: [...rep.mergedFromTexts],
+ bounds: rep.mergedFromBounds.map((b) => ({ ...b })),
+ charStarts: [...rep.mergedFromCharStarts],
+ };
const ptrs = rep.paragraphMemberPtrs;
const fs = rep.paragraphMemberFs;
const containers = rep.paragraphMemberContainers;
@@ -67,6 +81,9 @@ export class UngroupParagraphCommand implements Command {
? slots.map((s) => rep.text.slice(s.startChar, s.endChar))
: rep.text.split(/\r?\n/);
const n = Math.min(lines.length, ptrs.length);
+ const leavesByLine = useSlots
+ ? null
+ : leavesPerLine(doc, rep, fs.slice(0, n));
const newRuns: TextRun[] = [];
const perLineHeight =
rep.paragraphLineHeight > 0
@@ -93,13 +110,19 @@ export class UngroupParagraphCommand implements Command {
fill: { ...rep.fill },
fontSubset: rep.fontSubset,
renderMode: rep.renderMode,
+ hiddenText: rep.hiddenText,
});
r.containerPtr = containers[i] ?? 0;
+ r.documentFont = rep.documentFont && { ...rep.documentFont };
+ // Which of the paragraph's lines could not be read back is not kept, so none of them becomes editable by being split off.
+ r.readingOrderUnsure = rep.readingOrderUnsure;
// Each line keeps its own object's tags: lines grouped into one paragraph
// can belong to different structure elements, such as list items.
if (!r.containerPtr) {
r.tagMarks = ptrs[i] ? readTagMarks(doc.module, ptrs[i]) : rep.tagMarks;
}
+ if (useSlots) takeLineObjects(r, slots[i]);
+ else if (leavesByLine) takeLineLeaves(r, baselineY, leavesByLine[i]);
newRuns.push(r);
}
this.createdRunIds = newRuns.map((r) => r.id);
@@ -119,6 +142,9 @@ export class UngroupParagraphCommand implements Command {
height: rep.fontSize,
};
rep.matrix = { ...rep.matrix, f: fs[0] ?? rep.matrix.f };
+ if (useSlots) takeLineObjects(rep, slots[0]);
+ else if (leavesByLine)
+ takeLineLeaves(rep, fs[0] ?? rep.matrix.f, leavesByLine[0]);
// Replace rep with rep + (n-1) new lines; the first line stays on rep.
const tail = newRuns.slice(1);
@@ -153,6 +179,10 @@ export class UngroupParagraphCommand implements Command {
rep.paragraphLineSlots = this.prev.paragraphLineSlots.map(
cloneParagraphLineSlot,
);
+ rep.mergedFromPtrs = this.prevLineObjects.ptrs;
+ rep.mergedFromTexts = this.prevLineObjects.texts;
+ rep.mergedFromBounds = this.prevLineObjects.bounds;
+ rep.mergedFromCharStarts = this.prevLineObjects.charStarts;
const tailIds = new Set(this.createdRunIds.slice(1));
page.setRuns(page.runs.filter((r) => !tailIds.has(r.id)));
page.markDirty();
@@ -167,3 +197,51 @@ export class UngroupParagraphCommand implements Command {
);
}
}
+
+// A line redrawn word by word is several objects; a run that keeps only the first leaves the rest on the page when it is deleted or restyled.
+function takeLineObjects(run: TextRun, slot: ParagraphLineSlot): void {
+ if (slot.mergedFromPtrs.length < 2) return;
+ run.mergedFromPtrs = [...slot.mergedFromPtrs];
+ run.mergedFromTexts = [...slot.mergedFromTexts];
+ run.mergedFromBounds = slot.mergedFromBounds.map((b) => ({ ...b }));
+ run.mergedFromCharStarts = [...slot.mergedFromCharStarts];
+}
+
+interface Leaf {
+ ptr: number;
+ container: number;
+}
+
+// The word objects of a paragraph redrawn word by word, split between its lines by baseline; null when it has none beyond the line anchors.
+function leavesPerLine(
+ doc: EditorDocument,
+ rep: TextRun,
+ baselines: number[],
+): Leaf[][] | null {
+ if (rep.paragraphLeafPtrs.length <= rep.paragraphMemberPtrs.length)
+ return null;
+ const lines: Leaf[][] = baselines.map(() => []);
+ rep.paragraphLeafPtrs.forEach((ptr, i) => {
+ const y = ptr ? readMatrix(doc.module, ptr)?.[5] : undefined;
+ if (y === undefined) return;
+ let nearest = 0;
+ baselines.forEach((baseline, line) => {
+ if (Math.abs(baseline - y) < Math.abs(baselines[nearest] - y))
+ nearest = line;
+ });
+ lines[nearest].push({
+ ptr,
+ container: rep.paragraphLeafContainers[i] ?? 0,
+ });
+ });
+ return lines;
+}
+
+function takeLineLeaves(run: TextRun, baselineY: number, leaves: Leaf[]): void {
+ if (leaves.length === 0) return;
+ run.paragraphMemberPtrs = [run.pdfiumObjPtr];
+ run.paragraphMemberContainers = [run.containerPtr];
+ run.paragraphMemberFs = [baselineY];
+ run.paragraphLeafPtrs = leaves.map((leaf) => leaf.ptr);
+ run.paragraphLeafContainers = leaves.map((leaf) => leaf.container);
+}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/commands/bidiLineEdit.ts b/frontend/src/editor/core/tools/pdfTextEditor/commands/bidiLineEdit.ts
new file mode 100644
index 0000000000..31053b4392
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/commands/bidiLineEdit.ts
@@ -0,0 +1,993 @@
+/**
+ * Editing text that holds right-to-left letters without redrawing it.
+ *
+ * Such text cannot be rebuilt from its characters: its letters are shaped
+ * glyphs of a subset font with no way back from a character to the glyph, and
+ * its numbers and Latin words sit where the document's own layout put them. So
+ * every object the edit does not touch stays the object the document drew,
+ * moved when the text beside it grows, shrinks or breaks onto another line;
+ * only the touched stretch is drawn again, in drawn order, and each line keeps
+ * the edge it reads from.
+ *
+ * The text is first matched, glyph by glyph, against its lines laid out with
+ * {@link visualOrder}. Text that does not match is not planned at all.
+ */
+import type { WrappedPdfiumModule } from "@embedpdf/pdfium";
+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 type { RGBA } from "@editor/tools/pdfTextEditor/types";
+import { readObjFill } from "@editor/tools/pdfTextEditor/pdfium/PdfiumObjectColour";
+import {
+ tagsAt,
+ uniformTags,
+ type TextTags,
+} from "@editor/tools/pdfTextEditor/model/TextTags";
+import {
+ collectMemberPtrs,
+ contentIndices,
+ drawnEndPt,
+ emitTextLine,
+ inkFromRun,
+ measureObjSpanPt,
+ objectTexts,
+ removeAndDestroyObject,
+ removeTextObject,
+} from "@editor/tools/pdfTextEditor/commands/editTextHelpers";
+import { indexedInsertOf } from "@editor/tools/pdfTextEditor/util/insertPageObject";
+import {
+ bestFontPtrForText,
+ diffSpan,
+} from "@editor/tools/pdfTextEditor/commands/partialEdit";
+import {
+ readPageGlyphs,
+ type DrawnGlyph,
+} from "@editor/tools/pdfTextEditor/pdfium/drawnGlyphs";
+import {
+ placeGlyphs,
+ type PlacedGlyph,
+} from "@editor/tools/pdfTextEditor/pdfium/drawnLine";
+import {
+ joinsAt,
+ shapeArabic,
+} from "@editor/tools/pdfTextEditor/util/arabicShaping";
+import { isRtlBase, visualOrder } from "@editor/tools/pdfTextEditor/util/bidi";
+import { fallbackFamilyFor } from "@editor/tools/pdfTextEditor/util/fontCapability";
+import { transformObject } from "@editor/tools/pdfTextEditor/util/objectTransform";
+
+interface LineObject {
+ ptr: number;
+ /** Objects with no glyph of their own that go wherever this one goes: the rest of its glyph cluster, marks sitting on its letters. */
+ followers: number[];
+ /** Its glyphs, by their place in the map. */
+ glyphs: number[];
+ /** The stretch of the text it draws. */
+ start: number;
+ end: number;
+}
+
+/** A glyph with the line of the text it is drawn on; `object` indexes the map's objects. */
+interface LineGlyph extends PlacedGlyph {
+ line: number;
+}
+
+interface Row {
+ baseline: number;
+ left: number;
+ right: number;
+}
+
+interface DrawnMap {
+ /** Every glyph, line after line and left to right within each. */
+ glyphs: LineGlyph[];
+ /** The glyph drawing each code unit of the text; -1 for a space, line break or control no glyph draws. */
+ glyphOf: number[];
+ objects: LineObject[];
+ /** Where each line of the text is drawn; null for a line that draws nothing. */
+ rows: Array<Row | null>;
+}
+
+type Token =
+ | { kind: "glyph"; glyph: number }
+ | { kind: "free"; unit: number }
+ | {
+ kind: "new";
+ char: string;
+ rightToLeft: boolean;
+ start: number;
+ end: number;
+ };
+
+type Item =
+ | { kind: "kept"; first: number; last: number }
+ | { kind: "space"; width: number }
+ | { kind: "word"; text: string; start: number; end: number };
+
+interface PlannedLine {
+ items: Item[];
+ baseline: number;
+ /** The edge the line is set from: its right when the text reads right to left, else its left. */
+ anchor: number;
+ start: number;
+ text: string;
+}
+
+export interface BidiLineEditPlan {
+ /** Every object of the run, for the caller to remember where each sat. */
+ ptrs: number[];
+ /** The objects the edit takes off the page. */
+ removePtrs: number[];
+ map: DrawnMap;
+ lines: PlannedLine[];
+ next: string;
+ start: number;
+ shift: number;
+ prevEnd: number;
+ rightToLeft: boolean;
+}
+
+/** One line of the run after the edit: its objects in reading order with the text each draws. */
+export interface EditedLine {
+ ptrs: number[];
+ texts: string[];
+ charStarts: number[];
+ bounds: Array<{ x: number; right: number }>;
+ text: string;
+ x: number;
+ y: number;
+}
+
+export interface BidiLineEditResult {
+ insertedPtrs: number[];
+ lines: EditedLine[];
+ left: number;
+ right: number;
+}
+
+const SAME_PEN_PT = 0.01;
+const BRACKETS = "()[]{}";
+// Letters that take a different form beside one another, the marks between them, and the tatweel that joins both ways.
+const JOINING = /[ؠ-ٟٮ-ۓۺ-ۼ]/;
+const UNDRAWN = /[\s\p{Cf}]/u;
+const FALLBACK_SPACE_EM = 0.27;
+const MIN_SPACE_SHARE = 0.3;
+const DEFAULT_LEADING = 1.2;
+const PARKED_BELOW_PAGE_EM = 20;
+// Glyphs of one line can sit a little off its baseline; the next line is a whole line away.
+const ONE_LINE_EM = 0.6;
+
+// The letters of a text whatever order and form they are drawn in: a shaped letter is its plain one, a bracket either of its pair.
+function lettersKey(text: string): string {
+ return [...text.normalize("NFKC").replace(/[\s\p{Cf}]/gu, "")]
+ .map((ch) =>
+ BRACKETS.includes(ch) ? BRACKETS[BRACKETS.indexOf(ch) & ~1] : ch,
+ )
+ .sort()
+ .join("");
+}
+
+function sameGlyphText(drawn: string, text: string): boolean {
+ return drawn === text || lettersKey(drawn) === lettersKey(text);
+}
+
+// How many drawn positions from `at` the glyph covers when it shows the text there; 0 when it does not.
+function glyphSpan(
+ glyph: PlacedGlyph,
+ text: string,
+ order: readonly number[],
+ at: number,
+): number {
+ for (const length of new Set([
+ glyph.text.length,
+ glyph.text.normalize("NFKC").length,
+ ])) {
+ const units = order.slice(at, at + length);
+ if (units.length < length) continue;
+ const low = Math.min(...units);
+ if (Math.max(...units) - low + 1 !== length) continue;
+ if (sameGlyphText(glyph.text, text.slice(low, low + length))) return length;
+ }
+ return 0;
+}
+
+// Of two spaces side by side where the page draws one space glyph, the first is the gap before the glyph when there is one, not the glyph.
+function spaceBeforeGlyph(
+ text: string,
+ order: readonly number[],
+ at: number,
+ glyphs: readonly PlacedGlyph[],
+ next: number,
+): boolean {
+ const glyph = glyphs[next];
+ const before = glyphs[next - 1];
+ if (!before || glyph.text !== " " || at + 1 >= order.length) return false;
+ if (!/\s/.test(text[order[at]]) || !/\s/.test(text[order[at + 1]]))
+ return false;
+ return glyph.left - before.right >= (glyph.right - glyph.left) / 2;
+}
+
+// The glyph drawing each code unit of the line `text`, or null when the glyphs from left to right are not `text` as visualOrder lays it out.
+function matchGlyphs(text: string, glyphs: PlacedGlyph[]): number[] | null {
+ const { order } = visualOrder(text, isRtlBase(text));
+ const glyphOf = new Array<number>(text.length).fill(-1);
+ let next = 0;
+ let at = 0;
+ while (at < order.length) {
+ const glyph = glyphs[next];
+ let span = glyph ? glyphSpan(glyph, text, order, at) : 0;
+ const tied = glyphs[next + 1];
+ // Two glyphs drawn from the same pen position sort either way.
+ if (
+ span === 0 &&
+ glyph &&
+ tied &&
+ Math.abs(tied.left - glyph.left) < SAME_PEN_PT &&
+ glyphSpan(tied, text, order, at) > 0
+ ) {
+ glyphs[next] = tied;
+ glyphs[next + 1] = glyph;
+ span = glyphSpan(tied, text, order, at);
+ }
+ if (span > 0 && !spaceBeforeGlyph(text, order, at, glyphs, next)) {
+ for (let k = 0; k < span; k++) glyphOf[order[at + k]] = next;
+ next++;
+ at += span;
+ } else if (UNDRAWN.test(text[order[at]])) at++;
+ else return null;
+ }
+ return next === glyphs.length ? glyphOf : null;
+}
+
+// Only the stretches drawn anew are shaped: a kept letter is a glyph already, and shaping it could merge it with its neighbour into one ligature.
+function shapeAnew(
+ text: string,
+ anew: (unit: number) => boolean,
+): { text: string; source: number[]; sourceEnd: number[] } {
+ const out = { text: "", source: [] as number[], sourceEnd: [] as number[] };
+ let unit = 0;
+ while (unit < text.length) {
+ let end = unit + 1;
+ if (!anew(unit)) {
+ out.text += text[unit];
+ out.source.push(unit);
+ out.sourceEnd.push(end);
+ } else {
+ while (end < text.length && anew(end)) end++;
+ const shaped = shapeArabic(text.slice(unit, end));
+ out.text += shaped.text;
+ for (const source of shaped.source) out.source.push(source + unit);
+ for (const source of shaped.sourceEnd) out.sourceEnd.push(source + unit);
+ }
+ unit = end;
+ }
+ return out;
+}
+
+function lineStarts(text: string): Array<{ start: number; text: string }> {
+ let start = 0;
+ return text.split("\n").map((line) => {
+ const at = start;
+ start += line.length + 1;
+ return { start: at, text: line };
+ });
+}
+
+function readDrawnMap(
+ doc: EditorDocument,
+ page: Page,
+ run: TextRun,
+ text: string,
+): DrawnMap | null {
+ const m = doc.module;
+ const textPage = m.FPDFText_LoadPage(page.pagePtr);
+ if (!textPage) return null;
+ let pageGlyphs;
+ try {
+ pageGlyphs = readPageGlyphs(m, textPage);
+ } finally {
+ m.FPDFText_ClosePage(textPage);
+ }
+ if (!pageGlyphs) return null;
+ const objects: LineObject[] = [];
+ const drawn: DrawnGlyph[][] = [];
+ for (const ptr of collectMemberPtrs(run)) {
+ const own = pageGlyphs.byObject.get(ptr);
+ if (own?.length) {
+ objects.push({ ptr, followers: [], glyphs: [], start: Infinity, end: 0 });
+ drawn.push(own);
+ } else if (objects.length > 0)
+ objects[objects.length - 1].followers.push(ptr);
+ else return null;
+ }
+ const oneLine = ONE_LINE_EM * Math.max(run.fontSize, 4);
+ const bands: Array<{ baseline: number; objects: number[] }> = [];
+ for (const [object, own] of drawn.entries()) {
+ const rest =
+ own.length === 1 ? measureObjSpanPt(m, objects[object].followers) : null;
+ if (rest) {
+ own[0].left = Math.min(own[0].left, rest.left);
+ own[0].right = Math.max(own[0].right, rest.right);
+ }
+ const { baseline } = own[0];
+ if (own.some((glyph) => Math.abs(glyph.baseline - baseline) > oneLine))
+ return null;
+ const band = bands.find((b) => Math.abs(b.baseline - baseline) <= oneLine);
+ if (band) band.objects.push(object);
+ else bands.push({ baseline, objects: [object] });
+ }
+ bands.sort((a, b) => b.baseline - a.baseline);
+
+ const lines = lineStarts(text);
+ const inked = lines.filter((line) =>
+ [...line.text].some((ch) => !UNDRAWN.test(ch)),
+ );
+ if (bands.length !== inked.length || inked.length === 0) return null;
+ const map: DrawnMap = {
+ glyphs: [],
+ glyphOf: new Array<number>(text.length).fill(-1),
+ objects,
+ rows: lines.map(() => null),
+ };
+ for (const [index, line] of lines.entries()) {
+ const band = bands[inked.indexOf(line)];
+ if (!band) continue;
+ const { glyphs, riders } = placeGlyphs(
+ band.objects.map((object) => drawn[object]),
+ );
+ const glyphOf = matchGlyphs(line.text, glyphs);
+ if (!glyphOf) return null;
+ const first = map.glyphs.length;
+ for (const glyph of glyphs)
+ map.glyphs.push({
+ ...glyph,
+ object: band.objects[glyph.object],
+ line: index,
+ });
+ glyphOf.forEach((glyph, unit) => {
+ if (glyph >= 0) map.glyphOf[line.start + unit] = first + glyph;
+ });
+ for (const [rider, host] of riders) {
+ const riding = objects[band.objects[rider]];
+ objects[band.objects[host.object]].followers.push(
+ riding.ptr,
+ ...riding.followers,
+ );
+ riding.followers = [];
+ }
+ map.rows[index] = {
+ baseline: band.baseline,
+ left: Math.min(...glyphs.map((glyph) => glyph.left)),
+ right: Math.max(...glyphs.map((glyph) => glyph.right)),
+ };
+ }
+ map.glyphs.forEach((glyph, i) => objects[glyph.object].glyphs.push(i));
+ map.glyphOf.forEach((glyph, unit) => {
+ if (glyph < 0) return;
+ const object = objects[map.glyphs[glyph].object];
+ object.start = Math.min(object.start, unit);
+ object.end = Math.max(object.end, unit + 1);
+ });
+ // An object is moved or redrawn whole, so the text it draws has to be one stretch no other object draws into.
+ for (let unit = 0; unit < text.length; unit++) {
+ if (map.glyphOf[unit] < 0) continue;
+ const owner = objects[map.glyphs[map.glyphOf[unit]].object];
+ if (
+ objects.some(
+ (o) =>
+ o !== owner && o.glyphs.length > 0 && unit >= o.start && unit < o.end,
+ )
+ )
+ return null;
+ }
+ return map;
+}
+
+function median(values: number[]): number | null {
+ if (values.length === 0) return null;
+ const sorted = [...values].sort((a, b) => a - b);
+ return sorted[Math.floor((sorted.length - 1) / 2)];
+}
+
+// The spaces and controls no glyph draws that sit between each glyph and the one drawn after it on its line, with the width each space takes of the gap. The text page's box for a glyph can run on over the gap after it; a space the text holds is then given a plain space's width back out of that box.
+function freeUnits(
+ text: string,
+ map: DrawnMap,
+ spaceWidth: number,
+): { between: number[][]; widths: Map<number, number> } {
+ const between: number[][] = map.glyphs.map(() => []);
+ const widths = new Map<number, number>();
+ for (const line of lineStarts(text)) {
+ let last = -1;
+ for (const at of visualOrder(line.text, isRtlBase(line.text)).order) {
+ const glyph = map.glyphOf[line.start + at];
+ if (glyph >= 0) last = glyph;
+ else if (last >= 0) between[last].push(line.start + at);
+ }
+ }
+ between.forEach((units, i) => {
+ const glyph = map.glyphs[i];
+ const after = map.glyphs[i + 1];
+ const spaces = units.filter((unit) => /\s/.test(text[unit]));
+ if (spaces.length === 0 || after?.line !== glyph.line) return;
+ let width = (after.left - glyph.right) / spaces.length;
+ if (width < MIN_SPACE_SHARE * spaceWidth) {
+ width = spaceWidth;
+ glyph.right = Math.max(glyph.left, after.left - spaces.length * width);
+ }
+ for (const unit of spaces) widths.set(unit, width);
+ });
+ return { between, widths };
+}
+
+// Removing or adding a stretch that repeats the text before it reads as any of several equal edits. The one starting at a word's start leaves the letters around it joined as they were.
+function wordAlignedDiff(
+ prev: string,
+ next: string,
+): { start: number; prevEnd: number; nextEnd: number } {
+ const span = diffSpan(prev, next);
+ if (span.nextEnd !== span.start && span.prevEnd !== span.start) return span;
+ const text = span.nextEnd === span.start ? prev : next;
+ const end = Math.max(span.prevEnd, span.nextEnd);
+ for (let back = 0; back <= span.start; back++) {
+ const start = span.start - back;
+ if (back > 0 && text[start] !== text[end - back]) break;
+ if (start === 0 || /\s/.test(text[start - 1]))
+ return {
+ start,
+ prevEnd: span.prevEnd - back,
+ nextEnd: span.nextEnd - back,
+ };
+ }
+ return span;
+}
+
+function sameUnits(a: readonly number[], b: readonly number[]): boolean {
+ return a.length === b.length && a.every((unit, i) => unit === b[i]);
+}
+
+/**
+ * Plan an edit of a run from `prev` to `next` that keeps every object it can.
+ * Null when the run's objects do not draw `prev` the way it lays out, or the
+ * edit leaves nothing to keep; nothing on the page is touched either way.
+ */
+export function planBidiLineEdit(
+ doc: EditorDocument,
+ page: Page,
+ run: TextRun,
+ prev: string,
+ next: string,
+): BidiLineEditPlan | null {
+ if (/\r/.test(prev) || /\r/.test(next)) return null;
+ const map = readDrawnMap(doc, page, run, prev);
+ if (!map) return null;
+ const fontSize = Math.max(run.fontSize, 4);
+ const free = freeUnits(prev, map, FALLBACK_SPACE_EM * fontSize);
+ // A glyph ends where the one drawn against it starts: the text page's own box for it is only near that, and two stretches set apart and back together would not meet where they did.
+ map.glyphs.forEach((glyph, i) => {
+ const after = map.glyphs[i + 1];
+ if (after?.line === glyph.line && free.between[i].length === 0)
+ glyph.right = after.left;
+ });
+ const { start, prevEnd, nextEnd } = wordAlignedDiff(prev, next);
+ const shift = nextEnd - prevEnd;
+ const toNext = (unit: number) =>
+ unit < start ? unit : unit >= prevEnd ? unit + shift : -1;
+ const toPrev = (unit: number) =>
+ unit < start ? unit : unit >= nextEnd ? unit - shift : -1;
+ const anew = Array.from(next, (_, unit) => unit >= start && unit < nextEnd);
+ const touched = new Set<LineObject>();
+ const touch = (object: LineObject): boolean => {
+ if (touched.has(object)) return false;
+ touched.add(object);
+ for (let unit = object.start; unit < object.end; unit++)
+ if (toNext(unit) >= 0) anew[toNext(unit)] = true;
+ return true;
+ };
+ const objectAt = (unit: number): LineObject | null =>
+ map.glyphOf[unit] >= 0
+ ? map.objects[map.glyphs[map.glyphOf[unit]].object]
+ : null;
+ for (const object of map.objects) {
+ if (object.glyphs.length === 0) continue;
+ const cut = object.start < prevEnd && object.end > start && prevEnd > start;
+ if (cut || (object.start < start && start < object.end)) touch(object);
+ }
+ // A letter that joined a removed neighbour, or now joins a new one, changes form, and its word with it.
+ const touchWord = (from: number, step: 1 | -1): boolean => {
+ let changed = false;
+ for (
+ let unit = from;
+ unit >= 0 && unit < prev.length && JOINING.test(prev[unit]);
+ unit += step
+ ) {
+ const object = objectAt(unit);
+ if (object) changed = touch(object) || changed;
+ else if (!anew[toNext(unit)]) {
+ anew[toNext(unit)] = true;
+ changed = true;
+ }
+ }
+ return changed;
+ };
+ if (joinsAt(prev, start)) touchWord(start - 1, -1);
+ if (joinsAt(prev, prevEnd)) touchWord(prevEnd, 1);
+
+ const prevMirrored = new Map<number, boolean>();
+ for (const line of lineStarts(prev)) {
+ const drawn = visualOrder(line.text, isRtlBase(line.text));
+ drawn.order.forEach((unit, at) =>
+ prevMirrored.set(line.start + unit, drawn.visual[at] !== line.text[unit]),
+ );
+ }
+ const nextLines = lineStarts(next);
+ // A kept object must still be drawn as it was: each glyph straight after the one it followed, a bracket facing the way it did.
+ const layOut = (): { lines: Token[][]; disturbed: LineObject[] } => {
+ const disturbed: LineObject[] = [];
+ const seen = new Map<LineObject, number>();
+ const lines = nextLines.map((line) => {
+ const shaped = shapeAnew(line.text, (unit) => anew[line.start + unit]);
+ const drawn = visualOrder(shaped.text, isRtlBase(line.text));
+ const tokens: Token[] = [];
+ let before: Token | null = null;
+ drawn.order.forEach((at, position) => {
+ const unit = line.start + shaped.source[at];
+ if (anew[unit]) {
+ before = {
+ kind: "new",
+ char: drawn.visual[position],
+ rightToLeft: drawn.rightToLeft[position],
+ start: unit,
+ end: line.start + shaped.sourceEnd[at],
+ };
+ tokens.push(before);
+ return;
+ }
+ const glyph = map.glyphOf[toPrev(unit)];
+ if (glyph < 0) {
+ tokens.push({ kind: "free", unit: toPrev(unit) });
+ return;
+ }
+ const object = map.objects[map.glyphs[glyph].object];
+ const mirrored = drawn.visual[position] !== shaped.text[at];
+ if (prevMirrored.get(toPrev(unit)) !== mirrored) disturbed.push(object);
+ if (before?.kind === "glyph" && before.glyph === glyph) return;
+ const count = seen.get(object) ?? 0;
+ const follows =
+ count === 0 ||
+ (before?.kind === "glyph" && before.glyph === glyph - 1);
+ if (!follows || object.glyphs[count] !== glyph) disturbed.push(object);
+ seen.set(object, count + 1);
+ before = { kind: "glyph", glyph };
+ tokens.push(before);
+ });
+ return tokens;
+ });
+ return { lines, disturbed };
+ };
+ let { lines, disturbed } = layOut();
+ for (let round = 0; round <= map.objects.length; round++) {
+ let changed = false;
+ for (let unit = 1; unit < next.length; unit++) {
+ if (anew[unit - 1] === anew[unit] || !joinsAt(next, unit)) continue;
+ const kept = anew[unit] ? unit - 1 : unit;
+ if (touchWord(toPrev(kept), anew[unit] ? -1 : 1)) changed = true;
+ }
+ for (const object of disturbed) if (touch(object)) changed = true;
+ if (!changed) break;
+ ({ lines, disturbed } = layOut());
+ }
+ if (touched.size === map.objects.filter((o) => o.glyphs.length > 0).length)
+ return null;
+
+ const spaceWidth =
+ median([...free.widths.values()]) ?? FALLBACK_SPACE_EM * fontSize;
+ const itemsOf = (tokens: Token[]): Item[] => {
+ const items: Item[] = [];
+ let pending: number[] = [];
+ let wordRightToLeft = false;
+ const flush = () => {
+ for (const unit of pending)
+ if (/\s/.test(prev[unit]))
+ items.push({
+ kind: "space",
+ width: free.widths.get(unit) ?? spaceWidth,
+ });
+ pending = [];
+ };
+ for (const token of tokens) {
+ const last = items[items.length - 1];
+ if (token.kind === "free") {
+ pending.push(token.unit);
+ } else if (token.kind === "glyph") {
+ if (
+ last?.kind === "kept" &&
+ last.last === token.glyph - 1 &&
+ map.glyphs[last.last].line === map.glyphs[token.glyph].line &&
+ sameUnits(pending, free.between[last.last])
+ ) {
+ last.last = token.glyph;
+ pending = [];
+ } else {
+ flush();
+ items.push({ kind: "kept", first: token.glyph, last: token.glyph });
+ }
+ } else if (/\s/.test(token.char)) {
+ flush();
+ items.push({ kind: "space", width: spaceWidth });
+ } else if (!UNDRAWN.test(token.char)) {
+ const joinsWord =
+ pending.length === 0 &&
+ last?.kind === "word" &&
+ wordRightToLeft === token.rightToLeft;
+ flush();
+ if (joinsWord && last?.kind === "word") {
+ last.text += token.char;
+ last.start = Math.min(last.start, token.start);
+ last.end = Math.max(last.end, token.end);
+ } else {
+ items.push({
+ kind: "word",
+ text: token.char,
+ start: token.start,
+ end: token.end,
+ });
+ wordRightToLeft = token.rightToLeft;
+ }
+ }
+ }
+ flush();
+ // A space at either end of a line draws nothing and was never part of its extent.
+ while (items[0]?.kind === "space") items.shift();
+ while (items[items.length - 1]?.kind === "space") items.pop();
+ return items;
+ };
+
+ const rightToLeft = isRtlBase(prev);
+ const leading =
+ run.paragraphLineHeight > 0
+ ? run.paragraphLineHeight
+ : run.fontSize * DEFAULT_LEADING;
+ const firstRow = map.rows.find((row) => row !== null)!;
+ let row = firstRow;
+ let baseline = run.matrix.f;
+ const planned: PlannedLine[] = nextLines.map((line, index) => {
+ // A line is set from the edge of the line its first kept letter came from, so a line the edit leaves alone stays put.
+ for (let unit = line.start; unit < line.start + line.text.length; unit++) {
+ const glyph = anew[unit] ? -1 : map.glyphOf[toPrev(unit)];
+ if (glyph < 0) continue;
+ row = map.rows[map.glyphs[glyph].line] ?? row;
+ break;
+ }
+ baseline =
+ map.rows[index]?.baseline ??
+ (index === 0 ? baseline : baseline - leading);
+ return {
+ items: itemsOf(lines[index]),
+ baseline,
+ anchor: rightToLeft ? row.right : row.left,
+ start: line.start,
+ text: line.text,
+ };
+ });
+ return {
+ ptrs: [
+ ...new Set(
+ map.objects.flatMap(({ ptr, followers }) => [ptr, ...followers]),
+ ),
+ ],
+ removePtrs: [...touched].flatMap(({ ptr, followers }) => [
+ ptr,
+ ...followers,
+ ]),
+ map,
+ lines: planned,
+ next,
+ start,
+ shift,
+ prevEnd,
+ rightToLeft,
+ };
+}
+
+/** Whether every letter of `text` is among those the objects draw, counted. */
+export function drawsLetters(
+ m: WrappedPdfiumModule,
+ page: Page,
+ ptrs: readonly number[],
+ text: string,
+): boolean {
+ const wanted = lettersKey(text);
+ if (wanted === "") return true;
+ const drawn = ptrs.length > 0 ? objectTexts(m, page.pagePtr, ptrs) : null;
+ if (drawn === null) return false;
+ const left = new Map<string, number>();
+ for (const ch of lettersKey(drawn.join("")))
+ left.set(ch, (left.get(ch) ?? 0) + 1);
+ for (const ch of wanted) {
+ const count = left.get(ch) ?? 0;
+ if (count === 0) return false;
+ left.set(ch, count - 1);
+ }
+ return true;
+}
+
+/** Whether the objects draw every letter of `text`, in any order. An emit that finds no font for a letter leaves it out without saying so. */
+export function drawsWhole(
+ m: WrappedPdfiumModule,
+ page: Page,
+ ptrs: readonly number[],
+ text: string,
+): boolean {
+ const drawn = ptrs.length > 0 ? objectTexts(m, page.pagePtr, ptrs) : null;
+ return drawn !== null && lettersKey(drawn.join("")) === lettersKey(text);
+}
+
+type Word = Extract<Item, { kind: "word" }>;
+
+// The code unit of the text before the edit that the one at `unit` after it came from, or the first one past the edit when it is new.
+function sourceUnit(plan: BidiLineEditPlan, unit: number): number {
+ if (unit < plan.start) return unit;
+ return Math.max(plan.prevEnd, unit - plan.shift);
+}
+
+// Text extraction and screen readers follow content order, so a new stretch goes straight after the object drawing the text before it, not at the end of the page.
+function placeInReadingOrder(
+ m: WrappedPdfiumModule,
+ pagePtr: number,
+ plan: BidiLineEditPlan,
+ words: ReadonlyMap<Word, { ptrs: number[] }>,
+): void {
+ const insertAt = indexedInsertOf(m);
+ if (!insertAt) return;
+ const { map } = plan;
+ const removed = new Set(plan.removePtrs);
+ const keptObject = (unit: number): LineObject | null => {
+ const glyph = map.glyphOf[unit] ?? -1;
+ const object = glyph >= 0 ? map.objects[map.glyphs[glyph].object] : null;
+ return object && !removed.has(object.ptr) ? object : null;
+ };
+ const drawn = [...words]
+ .filter(([, word]) => word.ptrs.length > 0)
+ .sort(([a], [b]) => a.start - b.start);
+ let last: { anchor: LineObject; ptr: number } | null = null;
+ for (const [item, word] of drawn) {
+ const from = sourceUnit(plan, item.start);
+ let anchor: LineObject | null = null;
+ for (let unit = from - 1; unit >= 0 && !anchor; unit--)
+ anchor = keptObject(unit);
+ const after = anchor !== null;
+ for (let unit = from; unit < map.glyphOf.length && !anchor; unit++)
+ anchor = keptObject(unit);
+ if (!anchor) continue;
+ for (const ptr of word.ptrs) m.FPDFPage_RemoveObject(pagePtr, ptr);
+ // An object and the ones drawing the rest of its glyph cluster sit together in content order; nothing goes between them.
+ const cluster =
+ after && last?.anchor === anchor
+ ? [last.ptr]
+ : [anchor.ptr, ...anchor.followers];
+ const indices = [...contentIndices(m, pagePtr, cluster).values()];
+ const index =
+ indices.length === 0
+ ? undefined
+ : after
+ ? Math.max(...indices) + 1
+ : Math.min(...indices);
+ word.ptrs.forEach((ptr, i) => {
+ if (index === undefined || !insertAt(pagePtr, ptr, index + i))
+ m.FPDFPage_InsertObject(pagePtr, ptr);
+ });
+ if (after) last = { anchor, ptr: word.ptrs[word.ptrs.length - 1] };
+ }
+}
+
+function objectFont(m: WrappedPdfiumModule, ptr: number): number {
+ try {
+ return m.FPDFTextObj_GetFont(ptr);
+ } catch {
+ return 0;
+ }
+}
+
+/**
+ * Carry out a plan: draw the new stretches, take the touched objects off the
+ * page and move the kept objects to where the edited text puts them.
+ *
+ * Null, with the page as it was, when a stretch holding letters the document
+ * drew cannot be drawn again whole: no loaded font has them in the form they
+ * now take.
+ */
+export function applyBidiLineEdit(
+ doc: EditorDocument,
+ page: Page,
+ run: TextRun,
+ prev: string,
+ plan: BidiLineEditPlan,
+ tags: TextTags,
+): BidiLineEditResult | null {
+ const m = doc.module;
+ const { map, next } = plan;
+ const drawing = map.objects.filter((object) => object.glyphs.length > 0);
+ const texts = drawing.map((object) => prev.slice(object.start, object.end));
+ const size = Math.max(4, run.fontSize);
+ const fallbackFamily = fallbackFamilyFor(run.fontId);
+ const toPrev = (unit: number) =>
+ unit < plan.start
+ ? unit
+ : unit - plan.shift >= plan.prevEnd
+ ? unit - plan.shift
+ : -1;
+ const sourceGlyph = (unit: number) =>
+ toPrev(unit) >= 0 ? map.glyphOf[toPrev(unit)] : -1;
+ const sourceObjectOf = (word: Word): number => {
+ for (let unit = word.start; unit < word.end; unit++)
+ if (sourceGlyph(unit) >= 0)
+ return map.objects[map.glyphs[sourceGlyph(unit)].object].ptr;
+ return 0;
+ };
+ // A redrawn letter keeps the font and fill of the object that drew it; a typed one takes the font of the piece sharing most of its letters.
+ const fillFor = (word: Word): RGBA => {
+ const source = sourceObjectOf(word);
+ return (source ? readObjFill(m, source) : null) ?? run.fill;
+ };
+ const fontFor = (word: Word): number => {
+ const source = sourceObjectOf(word);
+ if (source) return objectFont(m, source);
+ return bestFontPtrForText(
+ m,
+ drawing.map(({ ptr }) => ptr),
+ texts,
+ next.slice(word.start, word.end),
+ );
+ };
+ // A new stretch is drawn clear of the page and of every other one, then moved into place: read back where it lands on letters still drawn there, PDFium takes the doubled letters for one and the stretch for misdrawn.
+ const parkedX = Math.min(...map.glyphs.map((glyph) => glyph.left));
+ const parkedY = (index: number) => -PARKED_BELOW_PAGE_EM * size * (index + 1);
+ const words = new Map<
+ Word,
+ { ptrs: number[]; width: number; parkedY: number }
+ >();
+ const dropEmitted = () => {
+ for (const word of words.values())
+ for (const ptr of word.ptrs) removeAndDestroyObject(m, page.pagePtr, ptr);
+ };
+ for (const line of plan.lines) {
+ for (const item of line.items) {
+ if (item.kind !== "word") continue;
+ const drawn: string[] = [];
+ const ptrs = emitTextLine({
+ doc,
+ page,
+ text: item.text,
+ x: parkedX,
+ y: parkedY(words.size),
+ fontSize: run.fontSize,
+ fill: fillFor(item),
+ ...inkFromRun(run),
+ originalFontPtr: fontFor(item),
+ originalFontSubset: run.fontSubset,
+ originalFontForCoveredWords: true,
+ fallbackFamily,
+ charSpacingPt: run.charSpacingPt,
+ tags: uniformTags(tagsAt(tags, item.start)),
+ drawnInOrder: true,
+ outTexts: drawn,
+ });
+ words.set(item, {
+ ptrs,
+ width:
+ ptrs.length > 0
+ ? Math.max(0, drawnEndPt(m, ptrs, drawn, size) - parkedX)
+ : 0,
+ parkedY: parkedY(words.size),
+ });
+ const redrawn = Array.from({ length: item.end - item.start }, (_, i) =>
+ sourceGlyph(item.start + i),
+ ).some((glyph) => glyph >= 0);
+ if (redrawn && !drawsWhole(m, page, ptrs, item.text)) {
+ dropEmitted();
+ return null;
+ }
+ }
+ }
+ for (const ptr of plan.removePtrs) removeTextObject(m, page, ptr, 0);
+
+ const widthOf = (item: Item): number =>
+ item.kind === "space"
+ ? item.width
+ : item.kind === "word"
+ ? words.get(item)!.width
+ : map.glyphs[item.last].right - map.glyphs[item.first].left;
+ interface Piece {
+ ptrs: number[];
+ text: string;
+ start: number;
+ left: number;
+ right: number;
+ }
+ const result: BidiLineEditResult = {
+ insertedPtrs: [...words.values()].flatMap(({ ptrs }) => ptrs),
+ lines: [],
+ left: Infinity,
+ right: -Infinity,
+ };
+ for (const line of plan.lines) {
+ const total = line.items.reduce((sum, item) => sum + widthOf(item), 0);
+ let pen = plan.rightToLeft ? line.anchor - total : line.anchor;
+ const pieces: Piece[] = [];
+ const moved = new Set<LineObject>();
+ for (const item of line.items) {
+ if (item.kind === "word") {
+ const { ptrs, parkedY: from } = words.get(item)!;
+ for (const ptr of ptrs)
+ transformObject(
+ m,
+ ptr,
+ 1,
+ 0,
+ 0,
+ 1,
+ pen - parkedX,
+ line.baseline - from,
+ );
+ const span = measureObjSpanPt(m, ptrs);
+ if (ptrs.length > 0)
+ pieces.push({
+ ptrs,
+ text: next.slice(item.start, item.end),
+ start: item.start,
+ left: span?.left ?? pen,
+ right: span?.right ?? pen,
+ });
+ } else if (item.kind === "kept") {
+ const dx = pen - map.glyphs[item.first].left;
+ for (let rank = item.first; rank <= item.last; rank++) {
+ const glyph = map.glyphs[rank];
+ const object = map.objects[glyph.object];
+ if (moved.has(object)) continue;
+ moved.add(object);
+ const dy = line.baseline - map.rows[glyph.line]!.baseline;
+ if (Math.abs(dx) >= SAME_PEN_PT || Math.abs(dy) >= SAME_PEN_PT)
+ for (const ptr of [object.ptr, ...object.followers])
+ transformObject(m, ptr, 1, 0, 0, 1, dx, dy);
+ pieces.push({
+ ptrs: [object.ptr, ...object.followers],
+ text: prev.slice(object.start, object.end),
+ start:
+ object.start < plan.start
+ ? object.start
+ : object.start + plan.shift,
+ left: map.glyphs[object.glyphs[0]].left + dx,
+ right:
+ map.glyphs[object.glyphs[object.glyphs.length - 1]].right + dx,
+ });
+ }
+ }
+ pen += widthOf(item);
+ }
+ pieces.sort((a, b) => a.start - b.start);
+ const edited: EditedLine = {
+ ptrs: [],
+ texts: [],
+ charStarts: [],
+ bounds: [],
+ text: line.text,
+ x: pieces.length > 0 ? Math.min(...pieces.map((p) => p.left)) : pen,
+ y: line.baseline,
+ };
+ for (const piece of pieces) {
+ piece.ptrs.forEach((ptr, i) => {
+ edited.ptrs.push(ptr);
+ edited.texts.push(i === 0 ? piece.text : "");
+ edited.charStarts.push(
+ piece.start - line.start + (i === 0 ? 0 : piece.text.length),
+ );
+ edited.bounds.push({ x: piece.left, right: piece.right });
+ });
+ result.left = Math.min(result.left, piece.left);
+ result.right = Math.max(result.right, piece.right);
+ }
+ result.lines.push(edited);
+ }
+ placeInReadingOrder(m, page.pagePtr, plan, words);
+ return result;
+}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/commands/editTextHelpers.ts b/frontend/src/editor/core/tools/pdfTextEditor/commands/editTextHelpers.ts
index 35fc60d1d7..71c1c7b72d 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/commands/editTextHelpers.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/commands/editTextHelpers.ts
@@ -17,8 +17,29 @@ import {
tryResolveCharcodes,
} from "@editor/tools/pdfTextEditor/charcode/charcodeRegistry";
import { getActiveCharcodeStrategy } from "@editor/tools/pdfTextEditor/charcode/CharcodeStrategy";
+import {
+ lettersWithoutGlyph,
+ ligatureCodes,
+ resetFontGlyphs,
+} from "@editor/tools/pdfTextEditor/charcode/fontGlyphs";
import { emitFallbackTextObject } from "@editor/tools/pdfTextEditor/util/fallbackFont";
-import { emitDeviceFontTextObject } from "@editor/tools/pdfTextEditor/util/deviceFontEmbed";
+import {
+ deviceFamilyOf,
+ emitDeviceFontTextObject,
+} from "@editor/tools/pdfTextEditor/util/deviceFontEmbed";
+import {
+ hasRtl,
+ isRtlBase,
+ visualOrder,
+} from "@editor/tools/pdfTextEditor/util/bidi";
+import {
+ needsArabicShaping,
+ shapeArabic,
+} from "@editor/tools/pdfTextEditor/util/arabicShaping";
+import {
+ noteUndrawnScriptText,
+ scriptFaceFamilyFor,
+} from "@editor/tools/pdfTextEditor/util/scanFontLibrary";
import { getExternalFontBytes } from "@editor/tools/pdfTextEditor/util/externalFonts";
import {
advanceWidth,
@@ -27,6 +48,7 @@ import {
} from "@editor/tools/pdfTextEditor/util/fontMetrics";
import { applyTagMarks } from "@editor/tools/pdfTextEditor/pdfium/PdfiumTagMarks";
import {
+ sliceTags,
taggedSpans,
uniformTags,
type TaggedSpan,
@@ -40,6 +62,12 @@ import {
SCRATCH,
scratchPtr,
} from "@editor/tools/pdfTextEditor/util/wasmScratch";
+import { transformObject } from "@editor/tools/pdfTextEditor/util/objectTransform";
+import {
+ indexedInsertOf,
+ insertPageObjectAt,
+} from "@editor/tools/pdfTextEditor/util/insertPageObject";
+import { clearOnDocumentClose } from "@editor/tools/pdfTextEditor/pdfium/pointerCaches";
// Remove a PAGE-level object and FREE its PDFium allocation.
// `FPDFPage_RemoveObject` only detaches the object.
@@ -78,6 +106,7 @@ export function resetPerCharBranchPtrs(): void {
perCharBranchPtrs.clear();
readBackValidated.clear();
}
+clearOnDocumentClose(resetPerCharBranchPtrs);
/** Test-only: clear the verified-ptr set between cases. */
export function _clearVerifiedPerCharPtrsForTests(): void {
@@ -103,16 +132,67 @@ export function _clearDroppedBase14CharsForTests(): void {
resetDroppedBase14Chars();
}
+/** Stop warning about `chars` once something draws them. */
+export function forgetDroppedChars(chars: string): void {
+ for (const ch of chars) droppedBase14Chars.delete(ch);
+}
+
export function recordUndrawableChars(chars: string): void {
recordDroppedChars(chars, "");
}
+let measuring = false;
+
+/** Run `measure`, which emits text only to size it, without adding to the characters a save warns were dropped. */
+export function withoutDroppedChars<T>(measure: () => T): T {
+ const was = measuring;
+ measuring = true;
+ try {
+ return measure();
+ } finally {
+ measuring = was;
+ }
+}
+
+let droppedDuringEmit: Set<string> | null = null;
+
+/**
+ * Run `emit` and return the visible characters it could not draw. They stay
+ * out of what a save warns were dropped, and no script font is fetched for
+ * them: this is for a caller that takes back an emit that lost any.
+ */
+export function droppedCharsOf(emit: () => void): string[] {
+ const outer = droppedDuringEmit;
+ const was = measuring;
+ const dropped = new Set<string>();
+ droppedDuringEmit = dropped;
+ measuring = true;
+ try {
+ emit();
+ } finally {
+ droppedDuringEmit = outer;
+ measuring = was;
+ }
+ return [...dropped];
+}
+
+let dropsSeen = 0;
+
+/** Rises whenever an emit leaves out a visible character, measuring or not: equal readings around a draw mean it drew every character. */
+export function droppedCharsSeen(): number {
+ return dropsSeen;
+}
+
/** Record every VISIBLE char present in `original` but missing from `kept`. */
function recordDroppedChars(original: string, kept: string): void {
const keptSet = new Set(kept);
- for (const ch of original) {
- if (!keptSet.has(ch) && ch.trim().length > 0) droppedBase14Chars.add(ch);
- }
+ const lost = [...original].filter(
+ (ch) => !keptSet.has(ch) && ch.trim().length > 0,
+ );
+ if (lost.length === 0) return;
+ dropsSeen++;
+ const into = droppedDuringEmit ?? (measuring ? null : droppedBase14Chars);
+ for (const ch of lost) into?.add(ch);
}
/** True when every character in `text` is also present in `pool`. */
@@ -129,7 +209,9 @@ const charCoverage = new Map<number, Map<string, boolean>>();
/** Doc-scoped reset: PDFium reuses font pointers across documents. */
export function resetCharCoverageCache(): void {
charCoverage.clear();
+ resetFontGlyphs();
}
+clearOnDocumentClose(resetCharCoverageCache);
// True when the emit path will map EVERY char in this font. Same condition
// emitTextLine uses to take its setCharcodes branch, so a true here means the
@@ -174,6 +256,15 @@ export function charcodesResolveFully(
return true;
}
+/** True when `fontPtr` has no glyph of its own for one of `text`'s letters, as {@link lettersWithoutGlyph} judges it. */
+export function lacksGlyphsFor(
+ m: WrappedPdfiumModule,
+ fontPtr: number,
+ text: string,
+): boolean {
+ return lettersWithoutGlyph(m, fontPtr, text).length > 0;
+}
+
/** Strip characters a base-14 (WinAnsi) font cannot render. */
export function sanitizeForBase14(text: string): string {
let out = "";
@@ -192,7 +283,15 @@ export function sanitizeForBase14(text: string): string {
}
/** Every PDFium pointer that backs a run. */
-export function collectMemberPtrs(run: TextRun): number[] {
+export function collectMemberPtrs(
+ run: Pick<
+ TextRun,
+ | "paragraphLeafPtrs"
+ | "paragraphMemberPtrs"
+ | "mergedFromPtrs"
+ | "pdfiumObjPtr"
+ >,
+): number[] {
if (run.paragraphLeafPtrs.length > 0) return run.paragraphLeafPtrs;
if (run.paragraphMemberPtrs.length > 0) return run.paragraphMemberPtrs;
if (run.mergedFromPtrs.length > 0) return run.mergedFromPtrs;
@@ -224,6 +323,29 @@ interface FormRemovalModule {
FPDFFormObj_RemoveObject?: (form: number, obj: number) => boolean;
}
+/** Detach a text object from its form XObject or, as text typed into a form run is drawn there, the page; false if neither held it. */
+export function removeTextObject(
+ m: WrappedPdfiumModule,
+ page: Page,
+ ptr: number,
+ containerPtr: number,
+): boolean {
+ const formMod = m as unknown as FormRemovalModule;
+ if (containerPtr && formMod.FPDFFormObj_RemoveObject) {
+ try {
+ if (formMod.FPDFFormObj_RemoveObject(containerPtr, ptr)) return true;
+ } catch {
+ /* fall back to the page */
+ }
+ }
+ try {
+ const removed = m.FPDFPage_RemoveObject(page.pagePtr, ptr);
+ return !containerPtr || !!removed;
+ } catch {
+ return false;
+ }
+}
+
/** Best-effort removal of every pointer in `ptrs`. */
export function removeMemberPtrs(
m: WrappedPdfiumModule,
@@ -233,7 +355,6 @@ export function removeMemberPtrs(
fallbackContainerPtr: number,
): boolean {
if (ptrs.length === 0) return false;
- const formMod = m as unknown as FormRemovalModule;
let allOk = true;
for (const ptr of ptrs) {
if (!ptr) {
@@ -241,22 +362,7 @@ export function removeMemberPtrs(
continue;
}
const container = containerByPtr.get(ptr) ?? fallbackContainerPtr;
- let ok: boolean;
- if (container && formMod.FPDFFormObj_RemoveObject) {
- try {
- ok = !!formMod.FPDFFormObj_RemoveObject(container, ptr);
- } catch {
- ok = false;
- }
- } else {
- try {
- m.FPDFPage_RemoveObject(page.pagePtr, ptr);
- ok = true;
- } catch {
- ok = false;
- }
- }
- if (!ok) allOk = false;
+ if (!removeTextObject(m, page, ptr, container)) allOk = false;
}
return allOk;
}
@@ -294,6 +400,23 @@ interface CreatedTextOptions {
// so callers that must map pointers back onto the source string cannot guess
// it - and reading it back costs a full page text extraction per line.
outTexts?: string[];
+ /** Stretches of `text` to draw in fonts of their own, each ending at `end`; a re-emitted line keeps each word's bold or italic face. */
+ fontSpans?: readonly FontSpan[];
+ /** Set when `text` is already in the order its glyphs are drawn, left to right. */
+ drawnInOrder?: boolean;
+ /** Draw `text` as one object, spaces included, instead of one per word. */
+ oneObject?: boolean;
+ /** Draw in `originalFontPtr` only the words whose every character it provably maps; the others take the fallback. */
+ originalFontForCoveredWords?: boolean;
+}
+
+export interface FontSpan {
+ end: number;
+ fontPtr: number;
+ /** The base-14 or completion family for characters `fontPtr` cannot draw. */
+ fallbackFamily?: string;
+ /** The span's own fill; absent, it takes the line's. */
+ fill?: RGBA;
}
interface CreateTextObjModule {
@@ -397,7 +520,7 @@ const MAX_PLAUSIBLE_ADVANCE_EM = 2;
/** Baseline origin of char `idx` in page points, or null when unreadable. */
function charOriginPt(
- m: import("@embedpdf/pdfium").WrappedPdfiumModule,
+ m: WrappedPdfiumModule,
tp: number,
idx: number,
): { x: number; y: number } | null {
@@ -417,7 +540,7 @@ function charOriginPt(
}
function looseBoxAdvancePt(
- m: import("@embedpdf/pdfium").WrappedPdfiumModule,
+ m: WrappedPdfiumModule,
tp: number,
idx: number,
): number | null {
@@ -436,10 +559,7 @@ function looseBoxAdvancePt(
}
/** |scale| of a page object's matrix (1 when unreadable). */
-function objMatrixScale(
- m: import("@embedpdf/pdfium").WrappedPdfiumModule,
- objPtr: number,
-): number {
+function objMatrixScale(m: WrappedPdfiumModule, objPtr: number): number {
const buf = scratchPtr(m, SCRATCH.editMatrix, 6 * 4);
try {
if (!m.FPDFPageObj_GetMatrix(objPtr, buf)) return 1;
@@ -453,7 +573,7 @@ function objMatrixScale(
}
function buildOnPageAdvMap(
- m: import("@embedpdf/pdfium").WrappedPdfiumModule,
+ m: WrappedPdfiumModule,
pagePtr: number,
): Map<number, Map<number, number>> {
const mod = m as unknown as LooseBoxModule;
@@ -548,7 +668,7 @@ function buildOnPageAdvMap(
/** On-page rendered advance (per em) of `ch` in `font`, or null if absent. */
function onPageAdvanceEm(
- m: import("@embedpdf/pdfium").WrappedPdfiumModule,
+ m: WrappedPdfiumModule,
pagePtr: number,
font: number,
ch: string,
@@ -572,7 +692,7 @@ function onPageAdvanceEm(
* lets a re-emit keep the original face instead of collapsing.
*/
export function warmOnPageAdvances(
- m: import("@embedpdf/pdfium").WrappedPdfiumModule,
+ m: WrappedPdfiumModule,
pagePtr: number,
): void {
if (!pagePtr || onPageAdvCache.has(pagePtr)) return;
@@ -587,6 +707,7 @@ export function warmOnPageAdvances(
export function resetOnPageAdvCache(): void {
onPageAdvCache.clear();
}
+clearOnDocumentClose(resetOnPageAdvCache);
/** Test-only alias for {@link resetOnPageAdvCache}. */
export function _clearOnPageAdvCacheForTests(): void {
@@ -705,6 +826,9 @@ export function rotateObjectAbout(
}
export function emitTextLine(opts: CreatedTextOptions): number[] {
+ if (!opts.drawnInOrder && hasRtl(opts.text)) return emitInVisualOrder(opts);
+ if (opts.fontSpans && opts.fontSpans.length > 1)
+ return emitFontSpans(opts, opts.fontSpans);
const spans = taggedSpans(opts.tags, opts.text.length);
if (spans.length > 1) return emitTaggedSpans(opts, spans);
const tagMarks = spans[0]?.tags ?? [];
@@ -729,9 +853,16 @@ export function emitTextLine(opts: CreatedTextOptions): number[] {
return ptrs;
};
- // Emit ONE word at (x, y) and return its pointer (0 on failure).
- const emitWord = (text: string, x: number): number => {
- // base-14 can only render WinAnsi; drop the rest, not U+00FF tofu.
+ // Letters the page already draws in the font are proof it has them, where a charcode resolver can come up empty.
+ const fontDraws = (font: number, text: string): boolean =>
+ charcodesResolveFully(m, font, text, opts.page.pagePtr, opts.doc.docPtr) ||
+ [...text].every(
+ (ch) => onPageAdvanceEm(m, opts.page.pagePtr, font, ch) !== null,
+ );
+
+ const emitBase14 = (text: string, x: number): number => {
+ // base-14 can only render WinAnsi; drop the rest so PDFium never emits
+ // U+00FF tofu.
const base14Text = sanitizeForBase14(text);
const newBase14 = (): number => {
const ptr = m.FPDFPageObj_NewTextObj(opts.doc.docPtr, family, size);
@@ -743,45 +874,61 @@ export function emitTextLine(opts: CreatedTextOptions): number[] {
? 0
: m.FPDFPageObj_NewTextObj(opts.doc.docPtr, substitute, size);
};
- const emitBase14 = (): number => {
- // A pre-warmed device font emits with its REAL face. Standard names skip
- // this and a cold cache returns 0, so existing emits are unchanged.
- if (nearestStandardFont(family) !== family) {
- const dp = emitDeviceFontTextObject(
- opts.doc,
- opts.page,
- family,
- text,
- size,
- opts.fill,
- x,
- opts.y,
- );
- if (dp) return dp;
- }
- // Some chars are outside base-14's WinAnsi range.
- if ([...text].length > [...base14Text].length) {
- const fp = emitFallbackTextObject(
- opts.doc,
- opts.page,
- text,
- size,
- opts.fill,
- x,
- opts.y,
- );
- if (fp) return fp;
- // The bundled Noto fallback couldn't render the non-Latin chars either,
- // so the base-14 emit below drops them.
- recordDroppedChars(text, base14Text);
- }
- if (base14Text.length === 0) return 0; // nothing representable - drop
- const p = newBase14();
- if (!p) return 0;
- setTextOn(m, p, base14Text);
- applyFillAndPos(m, opts.page, p, opts.fill, x, opts.y);
- return p;
- };
+ // A pre-warmed device font emits with its REAL face. Standard names skip
+ // this and a cold cache returns 0, so existing emits are unchanged.
+ if (nearestStandardFont(family) !== family) {
+ const dp = emitDeviceFontTextObject(
+ opts.doc,
+ opts.page,
+ family,
+ text,
+ size,
+ opts.fill,
+ x,
+ opts.y,
+ );
+ if (dp) return dp;
+ }
+ // Some chars are outside base-14's WinAnsi range.
+ if ([...text].length > [...base14Text].length) {
+ const fp = emitFallbackTextObject(
+ opts.doc,
+ opts.page,
+ text,
+ size,
+ opts.fill,
+ x,
+ opts.y,
+ );
+ if (fp) return fp;
+ const scriptFamily = scriptFaceFamilyFor(text);
+ const sp = scriptFamily
+ ? emitDeviceFontTextObject(
+ opts.doc,
+ opts.page,
+ scriptFamily,
+ text,
+ size,
+ opts.fill,
+ x,
+ opts.y,
+ )
+ : 0;
+ if (sp) return sp;
+ // Nothing loaded draws these chars, so the base-14 emit below drops them until their script's fonts arrive.
+ if (!measuring) noteUndrawnScriptText(text);
+ recordDroppedChars(text, base14Text);
+ }
+ if (base14Text.length === 0) return 0; // nothing representable - drop
+ const p = newBase14();
+ if (!p) return 0;
+ setTextOn(m, p, base14Text);
+ applyFillAndPos(m, opts.page, p, opts.fill, x, opts.y);
+ return p;
+ };
+
+ // Emit ONE word at (x, y) and return its pointer (0 on failure).
+ const emitWord = (text: string, x: number): number => {
if (!canReuse) {
// Still record the attempt: this is the only signal that an edit fell
// back instead of reusing the source face.
@@ -798,15 +945,20 @@ export function emitTextLine(opts: CreatedTextOptions): number[] {
: "no source font available (Helvetica fresh emit)",
outcome: "no-font",
});
- return emitBase14();
+ return emitBase14(text, x);
}
+ if (
+ opts.originalFontForCoveredWords &&
+ !fontDraws(opts.originalFontPtr, text.replace(/\s+/g, ""))
+ )
+ return emitBase14(text, x);
const ptr = m2.FPDFPageObj_CreateTextObj!(
opts.doc.docPtr,
opts.originalFontPtr,
size,
);
- if (!ptr) return emitBase14();
+ if (!ptr) return emitBase14(text, x);
// Reuse path: resolve real font charcodes so the embedded subset font
// renders the chars; falls back to SetText internally.
const strategyUsed = writeViaCharcodesOrSetText(ptr, text);
@@ -817,9 +969,19 @@ export function emitTextLine(opts: CreatedTextOptions): number[] {
// per visible char means the reused font produced .notdef / 0-width.
const minExpected = visible * size * 0.15;
if (visible > 0 && right - x < minExpected) {
- // Discard the .notdef object and free it (we re-emit in base-14 next).
removeAndDestroyObject(m, opts.page.pagePtr, ptr);
- return emitBase14();
+ return (
+ (strategyUsed !== null && emitWithSetText(text, x)) ||
+ emitBase14(text, x)
+ );
+ }
+ if (
+ strategyUsed === null &&
+ lacksGlyphsFor(m, opts.originalFontPtr, text) &&
+ !setLigatureCodes(ptr, text)
+ ) {
+ removeAndDestroyObject(m, opts.page.pagePtr, ptr);
+ return emitBase14(text, x);
}
// Read-back validation for a source-font SetText.
if (strategyUsed === null) {
@@ -834,10 +996,14 @@ export function emitTextLine(opts: CreatedTextOptions): number[] {
if (!allProven) {
const got = readBackTextObj(m, opts.page.pagePtr, ptr);
if (got !== null) {
- const norm = (s: string) => s.replace(/\s+/g, "");
+ // Readers return right-to-left text in reading order, not the drawn order written here.
+ const norm = (s: string) =>
+ hasRtl(s)
+ ? [...s.replace(/\s+/g, "")].sort().join("")
+ : s.replace(/\s+/g, "");
if (norm(got) !== norm(text)) {
removeAndDestroyObject(m, opts.page.pagePtr, ptr);
- return emitBase14();
+ return emitBase14(text, x);
}
if (opts.originalFontPtr) {
for (const c of visibleChars) {
@@ -870,15 +1036,62 @@ export function emitTextLine(opts: CreatedTextOptions): number[] {
if (known > 0 && expected > 0) {
const ratio = (right - x) / expected;
if (ratio < 0.6 || ratio > 1.7) {
- // Wrong-glyph guess: discard + free, then re-emit in base-14.
removeAndDestroyObject(m, opts.page.pagePtr, ptr);
- return emitBase14();
+ return emitWithSetText(text, x) || emitBase14(text, x);
}
}
+ // With no advance to compare, the width says nothing; the font's own mapping still tells a wrong code from a right one.
+ if ([...text.trim()].length === 1 && !readsBackAs(ptr, text)) {
+ removeAndDestroyObject(m, opts.page.pagePtr, ptr);
+ return emitWithSetText(text, x) || emitBase14(text, x);
+ }
}
return ptr;
};
+ function setLigatureCodes(ptr: number, text: string): boolean {
+ const codes = ligatureCodes(
+ m,
+ opts.doc.docPtr,
+ opts.page.pagePtr,
+ opts.originalFontPtr,
+ text,
+ );
+ return codes !== null && setCharcodesOn(m, ptr, codes);
+ }
+
+ // A guessed code that reads back as another character drew that character. A font that reads back nothing has no mapping to judge by.
+ function readsBackAs(ptr: number, text: string): boolean {
+ const got = readBackTextObj(m, opts.page.pagePtr, ptr);
+ if (got === null || got.trim() === "") return true;
+ return got.trim() === text.trim();
+ }
+
+ // A wrong charcode guess says nothing about the font's own text mapping, which draws every longer word.
+ function emitWithSetText(text: string, x: number): number {
+ if (lacksGlyphsFor(m, opts.originalFontPtr, text)) return 0;
+ const ptr = m2.FPDFPageObj_CreateTextObj!(
+ opts.doc.docPtr,
+ opts.originalFontPtr,
+ size,
+ );
+ if (!ptr) return 0;
+ setTextOn(m, ptr, text);
+ applyFillAndPos(m, opts.page, ptr, opts.fill, x, opts.y);
+ const visible = text.replace(/\s+/g, "");
+ const got = readBackTextObj(m, opts.page.pagePtr, ptr);
+ const sameChars = (a: string, b: string) =>
+ [...a].sort().join("") === [...b].sort().join("");
+ if (
+ got !== null &&
+ sameChars(got.replace(/\s+/g, ""), visible) &&
+ measureObjRightEdgePt(m, ptr) - x >= visible.length * size * 0.15
+ )
+ return ptr;
+ removeAndDestroyObject(m, opts.page.pagePtr, ptr);
+ return 0;
+ }
+
// Try-charcodes wrapper: when we're reusing a source font AND the active
// charcode strategy can resolve EVERY char in the chunk.
function writeViaCharcodesOrSetText(
@@ -1003,8 +1216,15 @@ export function emitTextLine(opts: CreatedTextOptions): number[] {
) {
const ptrs: number[] = [];
let cursor = opts.x;
+ // One face for the whole word: letters the source font has would otherwise keep it while the rest fall back.
+ const wholeWordFallback =
+ !!opts.originalFontForCoveredWords &&
+ canReuse &&
+ !fontDraws(opts.originalFontPtr, opts.text);
for (const ch of opts.text) {
- const ptr = emitWord(ch, cursor);
+ const ptr = wholeWordFallback
+ ? emitBase14(ch, cursor)
+ : emitWord(ch, cursor);
if (ptr) {
ptrs.push(ptr);
opts.outTexts?.push(ch);
@@ -1022,7 +1242,8 @@ export function emitTextLine(opts: CreatedTextOptions): number[] {
}
// Fast path: no whitespace at all → one text object holds the whole word.
- if (!hasAnyWhitespace) {
+ // A turned line stays one object too: words drawn apart along a turned baseline read back as separate lines.
+ if (!hasAnyWhitespace || opts.oneObject || opts.rotation) {
const ptr = emitWord(opts.text, opts.x);
if (ptr) opts.outTexts?.push(opts.text);
return withRotation(ptr ? [ptr] : []);
@@ -1049,13 +1270,11 @@ export function emitTextLine(opts: CreatedTextOptions): number[] {
x: cursor,
rotation: undefined,
tags: uniformTags(tagMarks),
- outTexts: opts.outTexts ? chunkTexts : undefined,
+ outTexts: chunkTexts,
});
if (wordPtrs.length === 0) continue;
if (opts.outTexts) opts.outTexts.push(...chunkTexts);
- let rightEdge = 0;
- for (const p of wordPtrs)
- rightEdge = Math.max(rightEdge, measureObjRightEdgePt(m, p));
+ const rightEdge = drawnEndPt(m, wordPtrs, chunkTexts, size);
// Only trust the measured edge when it advanced by a believable amount:
// a face PDFium can't measure reports a near-zero ink box and would put
// the next word on top of this one.
@@ -1073,10 +1292,213 @@ export function emitTextLine(opts: CreatedTextOptions): number[] {
return withRotation(ptrs);
}
+// A reader reverses the letters of each right-to-left object but orders a left-to-right line's objects by position, so each right-to-left run inside one is drawn as a single object, spaces and all.
+function emitDirectionRuns(
+ opts: CreatedTextOptions,
+ rightToLeft: readonly boolean[],
+): 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 x = opts.x;
+ let start = 0;
+ while (start < opts.text.length) {
+ let end = start + 1;
+ while (end < opts.text.length && rightToLeft[end] === rightToLeft[start])
+ end++;
+ const text = opts.text.slice(start, end);
+ const ink = text.trimEnd();
+ const texts: string[] = [];
+ const spans = sliceFontSpans(opts.fontSpans, start, end);
+ const font = spans[0]?.fontPtr || opts.originalFontPtr;
+ // A font with no space glyph cannot hold the run whole; its words stay apart.
+ const whole =
+ rightToLeft[start] &&
+ (!font ||
+ charcodesResolveFully(
+ m,
+ font,
+ " ",
+ opts.page.pagePtr,
+ opts.doc.docPtr,
+ ));
+ const own = ink.trim()
+ ? emitTextLine({
+ ...opts,
+ text,
+ x,
+ rotation: undefined,
+ oneObject: whole,
+ fontSpans: spans.length > 1 ? spans : undefined,
+ originalFontPtr: font,
+ fill: spans[0]?.fill ?? opts.fill,
+ fallbackFamily: spans[0]?.fallbackFamily ?? opts.fallbackFamily,
+ outTexts: texts,
+ })
+ : [];
+ opts.outTexts?.push(...texts);
+ ptrs.push(...own);
+ const drawnEnd =
+ own.length > 0
+ ? drawnEndPt(m, own, texts, size)
+ : x + measureAdvancePt(ink, family, size);
+ const trailing = text.slice(ink.length);
+ x =
+ Math.max(x, drawnEnd) +
+ (trailing
+ ? measureAdvancePt(trailing, family, size) + spacing * trailing.length
+ : 0);
+ start = end;
+ }
+ const rot = opts.rotation;
+ if (rot)
+ for (const ptr of ptrs)
+ rotateObjectAbout(m, ptr, opts.x, opts.y, rot.cos, rot.sin);
+ return ptrs;
+}
+
+export function sliceFontSpans(
+ spans: readonly FontSpan[] | undefined,
+ start: number,
+ end: number,
+): FontSpan[] {
+ const out: FontSpan[] = [];
+ let from = 0;
+ for (const span of spans ?? []) {
+ if (span.end > start && from < end)
+ out.push({ ...span, end: Math.min(span.end, end) - start });
+ from = span.end;
+ }
+ return out;
+}
+
+// Each drawn position takes the font of the character it shows.
+function visualFontSpans(
+ spans: readonly FontSpan[] | undefined,
+ order: readonly number[],
+): FontSpan[] | undefined {
+ if (!spans || spans.length < 2) return undefined;
+ const spanAt = (index: number) =>
+ spans.find((span) => index < span.end) ?? spans[spans.length - 1];
+ const out: Array<FontSpan & { source: FontSpan }> = [];
+ order.forEach((index, drawn) => {
+ const source = spanAt(index);
+ const last = out[out.length - 1];
+ if (last && last.source === source) last.end = drawn + 1;
+ else out.push({ ...source, end: drawn + 1, source });
+ });
+ return out.map(({ source: _source, ...span }) => span);
+}
+
+// Glyphs are drawn left to right in content order, so right-to-left text goes in reordered; each object still reports the logical stretch it shows.
+function emitInVisualOrder(opts: CreatedTextOptions): number[] {
+ const shaped = needsArabicShaping(opts.text) ? shapeArabic(opts.text) : null;
+ const rtlBase = isRtlBase(opts.text);
+ const { visual, order, rightToLeft } = visualOrder(
+ shaped?.text ?? opts.text,
+ rtlBase,
+ );
+ const starts = order.map((i) => (shaped ? shaped.source[i] : i));
+ const ends = order.map((i) => (shaped ? shaped.sourceEnd[i] : i + 1));
+ const drawn: string[] = [];
+ const fontSpans = visualFontSpans(opts.fontSpans, starts);
+ const drawnOpts: CreatedTextOptions = {
+ ...opts,
+ text: visual,
+ drawnInOrder: true,
+ fontSpans,
+ tags: uniformTags(taggedSpans(opts.tags, opts.text.length)[0]?.tags ?? []),
+ outTexts: drawn,
+ };
+ const ptrs = rtlBase
+ ? emitTextLine(drawnOpts)
+ : emitDirectionRuns(drawnOpts, rightToLeft);
+ const shown: Array<{ ptr: number; text: string; start: number }> = [];
+ let cursor = 0;
+ ptrs.forEach((ptr, i) => {
+ const text = drawn[i] ?? "";
+ const at = visual.indexOf(text, cursor);
+ if (at < 0 || !text) {
+ shown.push({ ptr, text, start: Infinity });
+ return;
+ }
+ const start = Math.min(...starts.slice(at, at + text.length));
+ const end = Math.max(...ends.slice(at, at + text.length));
+ shown.push({ ptr, text: opts.text.slice(start, end), start });
+ cursor = at + text.length;
+ });
+ // A reader reverses each right-to-left object's letters but, in a left-to-right line, takes the objects in content order.
+ if (!rtlBase) {
+ shown.sort((a, b) => a.start - b.start);
+ const m = opts.doc.module;
+ for (const { ptr } of shown) {
+ m.FPDFPage_RemoveObject(opts.page.pagePtr, ptr);
+ m.FPDFPage_InsertObject(opts.page.pagePtr, ptr);
+ }
+ }
+ opts.outTexts?.push(...shown.map(({ text }) => text));
+ return shown.map(({ ptr }) => ptr);
+}
+
/**
* Draw each span of `opts.text` with its own tags, one after another along
* the line.
*/
+function emitFontSpans(
+ opts: CreatedTextOptions,
+ spans: readonly FontSpan[],
+): 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;
+ let start = 0;
+ for (const span of spans) {
+ const { end, fontPtr } = span;
+ const text = opts.text.slice(start, end);
+ const texts: string[] = [];
+ const own = emitTextLine({
+ ...opts,
+ text,
+ x: cursor,
+ rotation: undefined,
+ fontSpans: undefined,
+ originalFontPtr: fontPtr || opts.originalFontPtr,
+ fill: span.fill ?? opts.fill,
+ // A word already typed in a device face goes on in that family, which the name inside its embedded copy does not spell.
+ fallbackFamily:
+ deviceFamilyOf(opts.doc, fontPtr) ??
+ span.fallbackFamily ??
+ opts.fallbackFamily,
+ tags: sliceTags(opts.tags, start, end),
+ outTexts: texts,
+ });
+ opts.outTexts?.push(...texts);
+ ptrs.push(...own);
+ // Advanced as emitTaggedSpans advances, so splitting a line by font does not move its words.
+ const ink = text.trimEnd();
+ const gap = text.slice(ink.length);
+ const right = Math.max(cursor, drawnEndPt(m, own, texts, size));
+ 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;
+ start = end;
+ }
+ const rot = opts.rotation;
+ if (rot) {
+ for (const ptr of ptrs) {
+ rotateObjectAbout(m, ptr, opts.x, opts.y, rot.cos, rot.sin);
+ }
+ }
+ return ptrs;
+}
+
function emitTaggedSpans(
opts: CreatedTextOptions,
spans: readonly TaggedSpan[],
@@ -1096,7 +1518,7 @@ function emitTaggedSpans(
x: cursor,
rotation: undefined,
tags: uniformTags(tags),
- outTexts: opts.outTexts ? texts : undefined,
+ outTexts: texts,
});
opts.outTexts?.push(...texts);
ptrs.push(...own);
@@ -1104,10 +1526,7 @@ function emitTaggedSpans(
// 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 right = Math.max(cursor, drawnEndPt(m, own, texts, size));
const metric = measureAdvancePt(ink, family, size);
cursor += right - cursor >= metric * 0.35 ? right - cursor : metric;
cursor += gap
@@ -1188,22 +1607,30 @@ function readBackTextObj(
pagePtr: number,
objPtr: number,
): string | null {
+ return objectTexts(m, pagePtr, [objPtr])?.[0] ?? null;
+}
+
+/** What each object reads as, through one text page; null when the module cannot read text. */
+export function objectTexts(
+ m: WrappedPdfiumModule,
+ pagePtr: number,
+ ptrs: readonly number[],
+): string[] | null {
const mod = m as unknown as TextObjReadModule;
- if (
- !mod.FPDFText_LoadPage ||
- !mod.FPDFTextObj_GetText ||
- !mod.FPDFText_ClosePage
- ) {
+ const getText = mod.FPDFTextObj_GetText;
+ if (!mod.FPDFText_LoadPage || !getText || !mod.FPDFText_ClosePage) {
return null;
}
const tp = mod.FPDFText_LoadPage(pagePtr);
if (!tp) return null;
try {
- const len = mod.FPDFTextObj_GetText(objPtr, tp, 0, 0);
- if (len <= 2) return "";
- const buf = scratchPtr(m, SCRATCH.editObjText, len);
- mod.FPDFTextObj_GetText(objPtr, tp, buf, len);
- return drawnText(readUtf16(m, buf, len));
+ return ptrs.map((objPtr) => {
+ const len = getText(objPtr, tp, 0, 0);
+ if (len <= 2) return "";
+ const buf = scratchPtr(m, SCRATCH.editObjText, len);
+ getText(objPtr, tp, buf, len);
+ return drawnText(readUtf16(m, buf, len));
+ });
} catch {
return null;
} finally {
@@ -1215,6 +1642,103 @@ function readBackTextObj(
}
}
+/** Sum of the drawn font's advances for `text` at `size`, or null when the font cannot map one of its chars. */
+function glyphAdvancePt(
+ m: WrappedPdfiumModule,
+ objPtr: number,
+ text: string,
+ size: number,
+): number | null {
+ const fontPtr = m.FPDFTextObj_GetFont(objPtr);
+ if (!fontPtr) return null;
+ const widthPtr = scratchPtr(m, SCRATCH.emitGlyphWidth, 4);
+ let total = 0;
+ for (const ch of text) {
+ if (!m.FPDFFont_GetGlyphWidth(fontPtr, ch.codePointAt(0)!, size, widthPtr))
+ return null;
+ const width = m.pdfium.getValue(widthPtr, "float");
+ if (!(width > 0)) return null;
+ total += width;
+ }
+ return total;
+}
+
+/**
+ * Where the next text drawn after `ptrs` should start: each object's origin plus
+ * its font's advances, or its ink edge when the font cannot say. Ink alone stops
+ * short of the last glyph's advance and pulls every later word in by its side
+ * bearing.
+ */
+export function drawnEndPt(
+ m: WrappedPdfiumModule,
+ ptrs: readonly number[],
+ texts: readonly string[],
+ size: number,
+): number {
+ const matrix = scratchPtr(m, SCRATCH.emitMatrix, 24);
+ let end = 0;
+ for (const [i, ptr] of ptrs.entries()) {
+ const ink = measureObjRightEdgePt(m, ptr);
+ let right = ink;
+ const text = texts.length === ptrs.length ? texts[i].trimEnd() : "";
+ const glyphs = text ? glyphAdvancePt(m, ptr, text, size) : null;
+ if (glyphs !== null && m.FPDFPageObj_GetMatrix(ptr, matrix)) {
+ const scale = m.pdfium.getValue(matrix, "float");
+ const fromGlyphs =
+ m.pdfium.getValue(matrix + 16, "float") + glyphs * scale;
+ if (fromGlyphs >= ink - 0.5 && fromGlyphs <= ink + size * 0.5)
+ right = fromGlyphs;
+ }
+ end = Math.max(end, right);
+ }
+ return end;
+}
+
+/** Index of `ptr` among the page-level objects, or -1 when the page does not hold it directly. */
+export function pageObjectIndex(
+ m: WrappedPdfiumModule,
+ pagePtr: number,
+ ptr: number,
+): number {
+ const count = m.FPDFPage_CountObjects(pagePtr);
+ for (let i = 0; i < count; i++)
+ if (m.FPDFPage_GetObject(pagePtr, i) === ptr) return i;
+ return -1;
+}
+
+/** Each of `ptrs` found at page level with its index in the page's content order. */
+export function contentIndices(
+ m: WrappedPdfiumModule,
+ pagePtr: number,
+ ptrs: Iterable<number>,
+): Map<number, number> {
+ const wanted = new Set(ptrs);
+ const found = new Map<number, number>();
+ const count = m.FPDFPage_CountObjects(pagePtr);
+ for (let i = 0; i < count && found.size < wanted.size; i++) {
+ const ptr = m.FPDFPage_GetObject(pagePtr, i);
+ if (wanted.has(ptr)) found.set(ptr, i);
+ }
+ return found;
+}
+
+/**
+ * Put each page-level object back at its index in content order. Text
+ * extraction, search and screen readers follow that order, so an edited line
+ * whose objects were appended would otherwise read at the end of the page.
+ * `placed` must hold every object that moved; anything else keeps its place.
+ */
+export function restoreContentOrder(
+ m: WrappedPdfiumModule,
+ pagePtr: number,
+ placed: ReadonlyArray<{ ptr: number; index: number }>,
+): void {
+ if (!indexedInsertOf(m) || placed.length === 0) return;
+ for (const { ptr } of placed) m.FPDFPage_RemoveObject(pagePtr, ptr);
+ for (const { ptr, index } of [...placed].sort((a, b) => a.index - b.index))
+ insertPageObjectAt(m, pagePtr, ptr, index);
+}
+
export function measureObjRightEdgePt(
m: WrappedPdfiumModule,
objPtr: number,
@@ -1310,6 +1834,22 @@ export function measureObjBoundsPt(
return right > left ? { left, bottom, right, top } : null;
}
+const LEFT_EDGE_TOLERANCE_PT = 0.02;
+
+/** Shift an object sideways so its inked left edge sits at `x`; one with no ink (a space) is left be. */
+export function moveObjectLeftEdgeTo(
+ m: WrappedPdfiumModule,
+ ptr: number,
+ x: number,
+): void {
+ const span = measureObjSpanPt(m, [ptr]);
+ if (!span) return;
+ const dx = x - span.left;
+ if (Math.abs(dx) > LEFT_EDGE_TOLERANCE_PT) {
+ transformObject(m, ptr, 1, 0, 0, 1, dx, 0);
+ }
+}
+
function setTextOn(m: WrappedPdfiumModule, ptr: number, text: string): void {
// FPDFText_SetText copies, so a pooled buffer is safe to overwrite next call.
const byteLen = (text.length + 1) * 2;
@@ -1410,6 +1950,9 @@ export function emitRunLines(opts: {
originalFontPtr: number;
fallbackFamily: string;
originalFontSubset?: boolean;
+ originalFontForCoveredWords?: boolean;
+ /** Per output line, the source fonts to keep within it. */
+ fontSpansByLine?: ReadonlyArray<readonly FontSpan[] | undefined>;
}): EmittedLine[] {
const rot = rotationFromMatrix(opts.run.matrix);
const out: EmittedLine[] = [];
@@ -1422,6 +1965,9 @@ export function emitRunLines(opts: {
continue;
}
const texts: string[] = [];
+ const fontSpans = opts.fontSpansByLine?.[i];
+ // emitTextLine splits a line only on two or more spans, so one span is the font of the whole line.
+ const wholeLine = fontSpans?.length === 1 ? fontSpans[0] : undefined;
const ptrs = emitTextLine({
outTexts: texts,
doc: opts.doc,
@@ -1432,15 +1978,26 @@ export function emitRunLines(opts: {
fontSize: opts.run.fontSize,
fill: opts.run.fill,
...inkFromRun(opts.run),
- originalFontPtr: opts.originalFontPtr,
+ originalFontPtr: wholeLine?.fontPtr || opts.originalFontPtr,
originalFontSubset: opts.originalFontSubset,
+ originalFontForCoveredWords: opts.originalFontForCoveredWords,
charSpacingPt: opts.run.charSpacingPt,
- fallbackFamily: opts.fallbackFamily,
+ fallbackFamily: wholeLine?.fallbackFamily ?? opts.fallbackFamily,
// Keep the run's rotation on re-emit (no-op for upright text).
rotation: rot,
tags,
+ fontSpans,
});
- out.push({ ptrs, text, texts, x: origin.x, y: origin.y });
+ // A right-to-left line keeps its right edge, where it starts.
+ const ink =
+ !rot && isRtlBase(text) ? measureObjSpanPt(opts.doc.module, ptrs) : null;
+ const shift = ink
+ ? opts.run.bounds.x + opts.run.bounds.width - ink.right
+ : 0;
+ if (ptrs.length > 0 && Number.isFinite(shift) && Math.abs(shift) > 0.05)
+ for (const ptr of ptrs)
+ transformObject(opts.doc.module, ptr, 1, 0, 0, 1, shift, 0);
+ out.push({ ptrs, text, texts, x: origin.x + shift, y: origin.y });
}
return out;
}
@@ -1459,6 +2016,9 @@ export function inkFromRun(run: {
};
}
+// Text render modes that paint a stroke (ISO 32000-1 9.3.6).
+const STROKING_MODES = new Set([1, 2, 5, 6]);
+
/** Re-apply render mode and outline to freshly created text objects. */
export function applyInkState(
m: WrappedPdfiumModule,
@@ -1485,9 +2045,12 @@ export function applyInkState(
);
mod.FPDFPageObj_SetStrokeWidth?.(p, width);
} else {
- // A transparent zero-width stroke is how "no outline" is expressed.
+ // An opaque stroke on text that never strokes needs no graphics
+ // state; a transparent one does, and PDFium can save a page naming
+ // that state after dropping its definition.
+ const strokeAlpha = STROKING_MODES.has(mode) ? 0 : 255;
mod.FPDFPageObj_SetStrokeWidth?.(p, 0);
- mod.FPDFPageObj_SetStrokeColor?.(p, 0, 0, 0, 0);
+ mod.FPDFPageObj_SetStrokeColor?.(p, 0, 0, 0, strokeAlpha);
}
} catch {
/* best-effort */
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/commands/liftFromForm.ts b/frontend/src/editor/core/tools/pdfTextEditor/commands/liftFromForm.ts
new file mode 100644
index 0000000000..4591201aa6
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/commands/liftFromForm.ts
@@ -0,0 +1,497 @@
+import type { WrappedPdfiumModule } from "@embedpdf/pdfium";
+import i18n from "i18next";
+import type { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
+import type { Page } from "@editor/tools/pdfTextEditor/model/Page";
+import type { ImageObject } from "@editor/tools/pdfTextEditor/model/ImageObject";
+import type { TextRun } from "@editor/tools/pdfTextEditor/model/TextRun";
+import type { FormNode } from "@editor/tools/pdfTextEditor/pdfdoc/formLocalResources";
+import {
+ collectContainersByPtr,
+ pageObjectIndex,
+ restoreContentOrder,
+} from "@editor/tools/pdfTextEditor/commands/editTextHelpers";
+import { RolledBackError } from "@editor/tools/pdfTextEditor/commands/Command";
+import { isScanRun } from "@editor/tools/pdfTextEditor/commands/scanTextEdit";
+import { readMatrix } from "@editor/tools/pdfTextEditor/commands/textPieces";
+import { markNamesOf } from "@editor/tools/pdfTextEditor/pdfium/PdfiumTagMarks";
+import { transformObject } from "@editor/tools/pdfTextEditor/util/objectTransform";
+import {
+ SCRATCH,
+ scratchPtr,
+} from "@editor/tools/pdfTextEditor/util/wasmScratch";
+
+// PDFium never saves a change made inside a form XObject, and saves an object
+// taken out of one only by rewriting the form's shared stream, so every other
+// use of the form loses it too. Taking this page's instance off the page
+// leaves the shared stream alone, and its contents go onto the page as
+// ordinary objects, in the same place and order, where later changes save.
+//
+// PDFium cannot give an object a clip, so a clip that cuts what the form
+// draws, an optional-content mark, and resources only the form binds would be
+// lost with the instance; a lift that would lose any of them is refused.
+
+interface FormModule {
+ FPDFFormObj_CountObjects?: (form: number) => number;
+ FPDFFormObj_GetObject?: (form: number, index: number) => number;
+ FPDFFormObj_RemoveObject?: (form: number, obj: number) => boolean;
+}
+
+const FPDF_PAGEOBJ_FORM = 5;
+// As deep as the reader walks: a run is never found in a form nested further.
+const MAX_FORM_DEPTH = 4;
+
+function childrenOf(m: WrappedPdfiumModule, form: number): number[] {
+ const mod = m as unknown as FormModule;
+ const count = mod.FPDFFormObj_CountObjects?.(form) ?? 0;
+ const children: number[] = [];
+ for (let i = 0; i < count; i++) {
+ const child = mod.FPDFFormObj_GetObject?.(form, i) ?? 0;
+ if (child) children.push(child);
+ }
+ return children;
+}
+
+// The forms from `form` down to `wanted`, outermost first; null when `form` does not lead to it.
+function chainFrom(
+ m: WrappedPdfiumModule,
+ form: number,
+ wanted: number,
+ depth: number,
+): number[] | null {
+ if (form === wanted) return [form];
+ if (depth >= MAX_FORM_DEPTH) return null;
+ for (const child of childrenOf(m, form)) {
+ if (m.FPDFPageObj_GetType(child) !== FPDF_PAGEOBJ_FORM) continue;
+ const rest = chainFrom(m, child, wanted, depth + 1);
+ if (rest) return [form, ...rest];
+ }
+ return null;
+}
+
+/** The forms from a page-level one down to `form`, outermost first; null when the page does not draw it. */
+export function chainTo(
+ m: WrappedPdfiumModule,
+ pagePtr: number,
+ form: number,
+): number[] | null {
+ const count = m.FPDFPage_CountObjects(pagePtr);
+ for (let i = 0; i < count; i++) {
+ const top = m.FPDFPage_GetObject(pagePtr, i);
+ if (!top || m.FPDFPageObj_GetType(top) !== FPDF_PAGEOBJ_FORM) continue;
+ const chain = chainFrom(m, top, form, 1);
+ if (chain) return chain;
+ }
+ return null;
+}
+
+type Point = [number, number];
+type Affine6 = [number, number, number, number, number, number];
+
+const IDENTITY: Affine6 = [1, 0, 0, 1, 0, 0];
+const SEGMENT_BEZIER = 1;
+// Points of slack when testing that a clip encloses what the form draws.
+const CLIP_SLACK_PT = 0.5;
+
+function apply(t: Affine6, [x, y]: Point): Point {
+ return [t[0] * x + t[2] * y + t[4], t[1] * x + t[3] * y + t[5]];
+}
+
+function innerThenOuter(inner: Affine6, outer: Affine6): Affine6 {
+ return [
+ inner[0] * outer[0] + inner[1] * outer[2],
+ inner[0] * outer[1] + inner[1] * outer[3],
+ inner[2] * outer[0] + inner[3] * outer[2],
+ inner[2] * outer[1] + inner[3] * outer[3],
+ inner[4] * outer[0] + inner[5] * outer[2] + outer[4],
+ inner[4] * outer[1] + inner[5] * outer[3] + outer[5],
+ ];
+}
+
+function boundsIn(
+ m: WrappedPdfiumModule,
+ obj: number,
+ toPage: Affine6,
+): [number, number, number, number] | null {
+ const buf = scratchPtr(m, SCRATCH.liftBounds, 16);
+ if (!m.FPDFPageObj_GetBounds(obj, buf, buf + 4, buf + 8, buf + 12))
+ return null;
+ const [l, b, r, t] = [0, 1, 2, 3].map((i) =>
+ m.pdfium.getValue(buf + i * 4, "float"),
+ );
+ const corners = [
+ apply(toPage, [l, b]),
+ apply(toPage, [r, b]),
+ apply(toPage, [r, t]),
+ apply(toPage, [l, t]),
+ ];
+ const xs = corners.map((p) => p[0]);
+ const ys = corners.map((p) => p[1]);
+ return [Math.min(...xs), Math.min(...ys), Math.max(...xs), Math.max(...ys)];
+}
+
+// The polygon of one clip path in page space; null when it holds a curve.
+function clipPolygon(
+ m: WrappedPdfiumModule,
+ clip: number,
+ path: number,
+ toPage: Affine6,
+): Point[] | null {
+ const buf = scratchPtr(m, SCRATCH.liftClipPoint, 8);
+ const points: Point[] = [];
+ const count = m.FPDFClipPath_CountPathSegments(clip, path);
+ for (let i = 0; i < count; i++) {
+ const segment = m.FPDFClipPath_GetPathSegment(clip, path, i);
+ if (!segment || m.FPDFPathSegment_GetType(segment) === SEGMENT_BEZIER)
+ return null;
+ if (!m.FPDFPathSegment_GetPoint(segment, buf, buf + 4)) return null;
+ points.push(
+ apply(toPage, [
+ m.pdfium.getValue(buf, "float"),
+ m.pdfium.getValue(buf + 4, "float"),
+ ]),
+ );
+ }
+ const last = points[points.length - 1];
+ if (
+ points.length > 1 &&
+ Math.abs(last[0] - points[0][0]) < 1e-3 &&
+ Math.abs(last[1] - points[0][1]) < 1e-3
+ )
+ points.pop();
+ return points.length >= 3 ? points : null;
+}
+
+// True when `inside` lies within the convex polygon, whichever way it winds.
+function convexHolds(polygon: Point[], inside: Point[]): boolean {
+ let sign = 0;
+ for (let i = 0; i < polygon.length; i++) {
+ const [ax, ay] = polygon[i];
+ const [bx, by] = polygon[(i + 1) % polygon.length];
+ const length = Math.hypot(bx - ax, by - ay);
+ if (length < 1e-6) continue;
+ for (const [px, py] of inside) {
+ const side = ((bx - ax) * (py - ay) - (by - ay) * (px - ax)) / length;
+ if (Math.abs(side) <= CLIP_SLACK_PT) continue;
+ const s = Math.sign(side);
+ if (sign === 0) sign = s;
+ else if (s !== sign) return false;
+ }
+ }
+ return isConvex(polygon);
+}
+
+function isConvex(polygon: Point[]): boolean {
+ let sign = 0;
+ for (let i = 0; i < polygon.length; i++) {
+ const [ax, ay] = polygon[i];
+ const [bx, by] = polygon[(i + 1) % polygon.length];
+ const [cx, cy] = polygon[(i + 2) % polygon.length];
+ const turn = (bx - ax) * (cy - by) - (by - ay) * (cx - bx);
+ if (Math.abs(turn) < 1e-6) continue;
+ if (sign === 0) sign = Math.sign(turn);
+ else if (Math.sign(turn) !== sign) return false;
+ }
+ return true;
+}
+
+// Whether the clip the form object is drawn through hides any of what it
+// draws on the visible page. A clip by text, or by a shape this cannot test,
+// counts as hiding something.
+function clipHidesContent(
+ m: WrappedPdfiumModule,
+ page: Page,
+ form: number,
+ toPage: Affine6,
+): boolean {
+ const clip = m.FPDFPageObj_GetClipPath(form);
+ if (!clip) return false;
+ const paths = m.FPDFClipPath_CountPaths(clip);
+ if (paths < 0) return false;
+ if (paths === 0) return true;
+ const drawn = boundsIn(m, form, toPage);
+ if (!drawn) return true;
+ const d = page.display;
+ const left = Math.max(drawn[0], d.cropLeft);
+ const bottom = Math.max(drawn[1], d.cropBottom);
+ const right = Math.min(drawn[2], d.cropLeft + d.cropWidth);
+ const top = Math.min(drawn[3], d.cropBottom + d.cropHeight);
+ if (left >= right || bottom >= top) return false;
+ const visible: Point[] = [
+ [left, bottom],
+ [right, bottom],
+ [right, top],
+ [left, top],
+ ];
+ for (let path = 0; path < paths; path++) {
+ const polygon = clipPolygon(m, clip, path, toPage);
+ if (!polygon || !convexHolds(polygon, visible)) return true;
+ }
+ return false;
+}
+
+function formChildren(m: WrappedPdfiumModule, form: number): number[] {
+ return childrenOf(m, form).filter(
+ (child) => m.FPDFPageObj_GetType(child) === FPDF_PAGEOBJ_FORM,
+ );
+}
+
+// The file's form behind each form object in `forms`, matched in drawing
+// order; empty when the counts differ, so no object can be matched wrongly.
+function matchNodes(
+ forms: number[],
+ nodes: FormNode[],
+): Array<[number, FormNode]> {
+ return forms.length === nodes.length
+ ? forms.map((form, i) => [form, nodes[i]])
+ : [];
+}
+
+/**
+ * Match the page's form objects to the file's form XObjects they draw, so a
+ * lift can tell which forms bind resources of their own. Must run as the page
+ * is first read, while its form objects are still in the file's order:
+ * PdfiumTextReader.populate calls it.
+ */
+export function claimFormNodes(doc: EditorDocument, page: Page): void {
+ if (page.formNodes) return;
+ page.formNodes = new Map();
+ const hazards = doc.formHazardsOn(page.index);
+ if (!Array.isArray(hazards)) return;
+ const m = doc.module;
+ const forms: number[] = [];
+ const count = m.FPDFPage_CountObjects(page.pagePtr);
+ for (let i = 0; i < count; i++) {
+ const obj = m.FPDFPage_GetObject(page.pagePtr, i);
+ if (obj && m.FPDFPageObj_GetType(obj) === FPDF_PAGEOBJ_FORM)
+ forms.push(obj);
+ }
+ for (const [form, node] of matchNodes(forms, hazards))
+ page.formNodes.set(form, node);
+}
+
+// The file's forms behind `chain`, outermost first; null where one is unknown.
+function chainNodes(
+ m: WrappedPdfiumModule,
+ page: Page,
+ chain: number[],
+): Array<FormNode | null> {
+ const nodes: Array<FormNode | null> = [page.formNodes?.get(chain[0]) ?? null];
+ for (let i = 1; i < chain.length; i++) {
+ const parent = nodes[i - 1];
+ const match = parent
+ ? matchNodes(formChildren(m, chain[i - 1]), parent.forms).find(
+ ([form]) => form === chain[i],
+ )
+ : undefined;
+ nodes.push(match ? match[1] : null);
+ }
+ return nodes;
+}
+
+function resourcesChangeDrawing(
+ doc: EditorDocument,
+ page: Page,
+ chain: number[],
+): boolean {
+ const hazards = doc.formHazardsOn(page.index);
+ if (hazards === "none") return false;
+ if (hazards === "unknown") return true;
+ return chainNodes(doc.module, page, chain).some(
+ (node) => !node || node.changesDrawing,
+ );
+}
+
+// The forms nested in `chain` that end up drawn by the page, with the file's form behind each.
+function liftedNodes(
+ m: WrappedPdfiumModule,
+ page: Page,
+ chain: number[],
+): Array<[number, FormNode]> {
+ const nodes = chainNodes(m, page, chain);
+ return chain.flatMap((form, i) => {
+ const node = nodes[i];
+ if (!node) return [];
+ return matchNodes(formChildren(m, form), node.forms).filter(
+ ([child]) => child !== chain[i + 1],
+ );
+ });
+}
+
+// Whether dissolving `chain`, outermost form first, would change how the page draws.
+function liftChangesDrawing(
+ doc: EditorDocument,
+ page: Page,
+ chain: number[],
+): boolean {
+ if (resourcesChangeDrawing(doc, page, chain)) return true;
+ const m = doc.module;
+ let toPage = IDENTITY;
+ for (const form of chain) {
+ if (markNamesOf(m, form).includes("OC")) return true;
+ if (clipHidesContent(m, page, form, toPage)) return true;
+ const matrix = readMatrix(m, form);
+ if (!matrix) return true;
+ toPage = innerThenOuter(Array.from(matrix) as Affine6, toPage);
+ }
+ return false;
+}
+
+function refuseLift(): never {
+ throw new RolledBackError(
+ new Error(
+ i18n.t(
+ "pdfTextEditor.error.formLiftChangesDrawing",
+ "Can't edit this: it is drawn as part of a group whose clipping or graphics settings the editor can't keep when it is changed.",
+ ),
+ ),
+ );
+}
+
+// Replaces a form instance drawn by the page itself with the objects it drew.
+function dissolve(page: Page, m: WrappedPdfiumModule, form: number): boolean {
+ const remove = (m as unknown as FormModule).FPDFFormObj_RemoveObject;
+ const matrix = readMatrix(m, form);
+ const at = pageObjectIndex(m, page.pagePtr, form);
+ if (!remove || !matrix || at < 0) return false;
+ const children = childrenOf(m, form);
+ // Off the page before anything leaves it: an instance still on the page has its shared stream rewritten.
+ if (!m.FPDFPage_RemoveObject(page.pagePtr, form)) return false;
+ const [a, b, c, d, e, f] = matrix;
+ const placed: Array<{ ptr: number; index: number }> = [];
+ for (const child of children) {
+ if (!remove(form, child)) continue;
+ transformObject(m, child, a, b, c, d, e, f);
+ m.FPDFPage_InsertObject(page.pagePtr, child);
+ placed.push({ ptr: child, index: at + placed.length });
+ }
+ restoreContentOrder(m, page.pagePtr, placed);
+ forgetForm(page, form);
+ return true;
+}
+
+// Everything the model recorded as living in `form` now lives on the page.
+function forgetForm(page: Page, form: number): void {
+ const onPage = (container: number) => (container === form ? 0 : container);
+ for (const run of page.runs) {
+ run.containerPtr = onPage(run.containerPtr);
+ run.topLevelContainerPtr = onPage(run.topLevelContainerPtr);
+ if (run.paragraphMemberContainers.includes(form))
+ run.paragraphMemberContainers = run.paragraphMemberContainers.map(onPage);
+ if (run.paragraphLeafContainers.includes(form))
+ run.paragraphLeafContainers = run.paragraphLeafContainers.map(onPage);
+ if (run.paragraphLineSlots.some((slot) => slot.containerPtr === form))
+ run.paragraphLineSlots = run.paragraphLineSlots.map((slot) => ({
+ ...slot,
+ containerPtr: onPage(slot.containerPtr),
+ }));
+ }
+ for (const image of page.images)
+ image.containerPtr = onPage(image.containerPtr);
+ for (const shape of page.shapes)
+ shape.containerPtr = onPage(shape.containerPtr);
+}
+
+function drawsEditedScan(page: Page, forms: number[]): boolean {
+ return page.runs.some(
+ (run) =>
+ run.scanEdit !== null &&
+ [...collectContainersByPtr(run).values()].some((container) =>
+ forms.includes(container),
+ ),
+ );
+}
+
+/**
+ * Puts everything the form instance `container` draws onto the page itself,
+ * in the same place and order, and takes the instance off the page. A form
+ * nested in others is reached by dissolving each one around it first. Not
+ * undone: the page looks the same before and after, and PDFium has no call to
+ * put an object back into a form.
+ *
+ * Throws RolledBackError, changing nothing, when lifting would change how the
+ * page draws (see assertLiftable). Returns false, changing nothing, when the
+ * page does not draw `container`, this build cannot take objects out of a
+ * form, or the form holds scanned text that has been edited, whose redraw is
+ * tied to where the form drew it.
+ */
+export function liftFormToPage(
+ doc: EditorDocument,
+ page: Page,
+ container: number,
+): boolean {
+ const m = doc.module;
+ const chain = chainTo(m, page.pagePtr, container);
+ if (!chain || drawsEditedScan(page, chain)) return false;
+ if (liftChangesDrawing(doc, page, chain)) refuseLift();
+ const nested = liftedNodes(m, page, chain);
+ for (const form of chain) if (!dissolve(page, m, form)) return false;
+ for (const form of chain) page.formNodes?.delete(form);
+ for (const [form, node] of nested) page.formNodes?.set(form, node);
+ page.markDirty();
+ page.markNeedsGenerate();
+ return true;
+}
+
+function formsDrawing(run: TextRun): Set<number> {
+ const forms = new Set(
+ [...collectContainersByPtr(run)]
+ .filter(([ptr, container]) => ptr && container)
+ .map(([, container]) => container),
+ );
+ return forms.size === 0 || isScanRun(run) ? new Set() : forms;
+}
+
+/**
+ * Throws RolledBackError when lifting any form that draws part of `runs`
+ * would change how the page draws: the form is drawn through a clip that
+ * hides some of it, inside optional content, or binds graphics states,
+ * patterns, shadings, colour spaces or marked-content properties the page
+ * binds differently. A command that lifts after changing anything calls this
+ * first, so a refusal leaves the document as it was.
+ */
+export function assertLiftable(
+ doc: EditorDocument,
+ page: Page,
+ runs: Iterable<TextRun>,
+): void {
+ for (const run of runs) {
+ for (const form of formsDrawing(run)) {
+ const chain = chainTo(doc.module, page.pagePtr, form);
+ if (chain && liftChangesDrawing(doc, page, chain)) refuseLift();
+ }
+ }
+}
+
+/**
+ * Lifts the forms that draw any part of `run` onto the page, leaving the run
+ * page-level. Scanned text is left alone; it is edited by redrawing. Throws
+ * as assertLiftable does, before lifting any. Returns false when a form could
+ * not be lifted, in which case edits to the run will not survive a save.
+ */
+export function liftRunToPage(
+ doc: EditorDocument,
+ page: Page,
+ run: TextRun,
+): boolean {
+ const forms = formsDrawing(run);
+ if (forms.size === 0) return true;
+ assertLiftable(doc, page, [run]);
+ let lifted = true;
+ for (const form of forms) {
+ // An earlier form in this loop may have held this one, and lifted it with it.
+ if (![...collectContainersByPtr(run).values()].includes(form)) continue;
+ lifted = liftFormToPage(doc, page, form) && lifted;
+ }
+ if (lifted) run.dirty = true;
+ return lifted;
+}
+
+/** Lifts the form that draws `image` onto the page; false when it could not be, and the image is then still in the form. */
+export function liftImageToPage(
+ doc: EditorDocument,
+ page: Page,
+ image: ImageObject,
+): boolean {
+ if (!image.containerPtr) return true;
+ return liftFormToPage(doc, page, image.containerPtr);
+}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/commands/partialEdit.ts b/frontend/src/editor/core/tools/pdfTextEditor/commands/partialEdit.ts
index 68c15cd37b..a1a9b35dcb 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/commands/partialEdit.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/commands/partialEdit.ts
@@ -1,3 +1,4 @@
+import type { WrappedPdfiumModule } from "@embedpdf/pdfium";
import type { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
import type { Page } from "@editor/tools/pdfTextEditor/model/Page";
import type {
@@ -5,11 +6,21 @@ import type {
TextRun,
} from "@editor/tools/pdfTextEditor/model/TextRun";
import {
+ charcodesResolveFully,
+ collectContainersByPtr,
+ contentIndices,
cssFontSpecFor,
+ restoreContentOrder,
emitTextLine,
+ readObjTexts,
+ type FontSpan,
inkFromRun,
isVerifiedPerCharPtr,
measureObjRightEdgePt,
+ measureObjSpanPt,
+ moveObjectLeftEdgeTo,
+ removeAndDestroyObject,
+ removeTextObject,
} from "@editor/tools/pdfTextEditor/commands/editTextHelpers";
import {
fallbackFamilyFor,
@@ -22,19 +33,35 @@ import {
type TextTags,
} from "@editor/tools/pdfTextEditor/model/TextTags";
import { readTagMarks } from "@editor/tools/pdfTextEditor/pdfium/PdfiumTagMarks";
+import { readObjFill } from "@editor/tools/pdfTextEditor/pdfium/PdfiumObjectColour";
+import type { RGBA } from "@editor/tools/pdfTextEditor/types";
+import { readMatrix } from "@editor/tools/pdfTextEditor/commands/textPieces";
import { transformObject } from "@editor/tools/pdfTextEditor/util/objectTransform";
+import { deviceFamilyOf } from "@editor/tools/pdfTextEditor/util/deviceFontEmbed";
+import { setCharcodesOn } from "@editor/tools/pdfTextEditor/charcode/charcodeRegistry";
+import { ligatureCodes } from "@editor/tools/pdfTextEditor/charcode/fontGlyphs";
import {
SCRATCH,
scratchPtr,
} from "@editor/tools/pdfTextEditor/util/wasmScratch";
-/** Set the text of an EXISTING PDFium text object, preserving its font. */
+/** Set the text of an EXISTING PDFium text object, preserving its font and any ligature its letters can only be drawn with. */
export function setObjText(
- m: import("@embedpdf/pdfium").WrappedPdfiumModule,
+ doc: EditorDocument,
+ page: Page,
ptr: number,
text: string,
): void {
if (!ptr) return;
+ const m = doc.module;
+ const codes = ligatureCodes(
+ m,
+ doc.docPtr,
+ page.pagePtr,
+ objFontPtr(m, ptr),
+ text,
+ );
+ if (codes && setCharcodesOn(m, ptr, codes)) return;
const buf = writeUtf16(m, text);
try {
m.FPDFText_SetText(ptr, buf);
@@ -47,7 +74,7 @@ export function setObjText(
/** Read a text object's left/right edge in page points. */
function objBoundsLR(
- m: import("@embedpdf/pdfium").WrappedPdfiumModule,
+ m: WrappedPdfiumModule,
ptr: number,
fallbackX: number,
): { x: number; right: number } {
@@ -66,7 +93,7 @@ function objBoundsLR(
// each ptr holds - it emits per word OR per character, so deriving it from the
// text mislabels every ptr past the word count.
function buildSlotMerged(
- m: import("@embedpdf/pdfium").WrappedPdfiumModule,
+ m: WrappedPdfiumModule,
ptrs: number[],
text: string,
leftX: number,
@@ -168,7 +195,7 @@ function surrogatePairsSurviveTogether(
next: string,
keptA: Set<number>,
keptB: Set<number>,
- alignment: Array<{ aIdx: number; bIdx: number }>,
+ alignment: Alignment,
): boolean {
const aToB = new Map<number, number>();
const bToA = new Map<number, number>();
@@ -199,6 +226,28 @@ function surrogatePairsSurviveTogether(
return true;
}
+/**
+ * The pieces straight after the one at `idx` that hold no text of their own:
+ * objects drawing the rest of its glyph cluster, such as a vowel mark drawn
+ * apart from its letter. They are moved, removed and kept with it, and nothing
+ * goes between them in content order.
+ */
+function ridersOf(texts: readonly string[], idx: number): number[] {
+ const riders: number[] = [];
+ if (texts[idx] === "") return riders;
+ for (let i = idx + 1; i < texts.length && texts[i] === ""; i++)
+ riders.push(i);
+ return riders;
+}
+
+/** The piece the one at `idx` rides, or -1 when it holds text itself or nothing with text comes before it. */
+function riddenBy(texts: readonly string[], idx: number): number {
+ if (texts[idx] !== "") return -1;
+ let owner = idx - 1;
+ while (owner >= 0 && texts[owner] === "") owner--;
+ return owner;
+}
+
/** Diff-driven partial editing. */
export interface PartialEditOp {
type: "keep" | "insert" | "modify";
@@ -224,19 +273,29 @@ export interface PartialEditPlan {
ops: PartialEditOp[];
/** Per-sub-run status (parallel to prevMergedFromPtrs). */
subRunStatus: Array<"all-kept" | "all-deleted" | "mixed">;
+ /**
+ * Deleted whitespace that belonged to no object, by the sub-run right after
+ * it. Removing it frees no object, so the apply has to close the space it
+ * took by shifting what follows.
+ */
+ ghostGaps: Array<{ beforeSubRunIdx: number; removed: number }>;
/** Snapshot of current model arrays for revert. */
prevMergedFromPtrs: number[];
prevMergedFromTexts: string[];
prevMergedFromBounds: Array<{ x: number; right: number }>;
+ /** The edited text that every op's startBIdx indexes into. */
+ nextText: string;
}
+export type Alignment = Array<{ aIdx: number; bIdx: number }>;
+
function lcsIndices(
a: string,
b: string,
): {
keptA: Set<number>;
keptB: Set<number>;
- alignment: Array<{ aIdx: number; bIdx: number }>;
+ alignment: Alignment;
} {
const m = a.length;
const n = b.length;
@@ -251,7 +310,7 @@ function lcsIndices(
}
const keptA = new Set<number>();
const keptB = new Set<number>();
- const alignment: Array<{ aIdx: number; bIdx: number }> = [];
+ const alignment: Alignment = [];
let i = m;
let j = n;
while (i > 0 && j > 0) {
@@ -270,10 +329,81 @@ function lcsIndices(
return { keptA, keptB, alignment };
}
+const MAX_STRANDED_KEEP = 2;
+const MAX_KEPT_SHARE = 0.5;
+
+function isWordChar(ch: string): boolean {
+ return /\S/.test(ch);
+}
+
+function mostlyDeletedWord(
+ prevText: string,
+ keptA: Set<number>,
+ at: number,
+): boolean {
+ let from = at;
+ while (from > 0 && isWordChar(prevText[from - 1])) from--;
+ let to = at;
+ while (to + 1 < prevText.length && isWordChar(prevText[to + 1])) to++;
+ let kept = 0;
+ for (let a = from; a <= to; a++) if (keptA.has(a)) kept++;
+ return kept < (to - from + 1) * MAX_KEPT_SHARE;
+}
+
+// A kept letter of a deleted word inside a typed one stays put and opens gaps, so retype it.
+function withoutStrandedGlyphs(
+ prevText: string,
+ nextText: string,
+ keptA: Set<number>,
+ keptB: Set<number>,
+ alignment: Alignment,
+): {
+ keptA: Set<number>;
+ keptB: Set<number>;
+ alignment: Alignment;
+} {
+ const typedLetter = (b: number) =>
+ b >= 0 && b < nextText.length && !keptB.has(b) && isWordChar(nextText[b]);
+ const deletedLetter = (a: number) =>
+ a >= 0 && a < prevText.length && !keptA.has(a) && isWordChar(prevText[a]);
+ const stranded = new Set<number>();
+ for (let i = 0; i < alignment.length;) {
+ let j = i;
+ while (
+ j + 1 < alignment.length &&
+ alignment[j + 1].bIdx === alignment[j].bIdx + 1 &&
+ alignment[j + 1].aIdx === alignment[j].aIdx + 1
+ )
+ j++;
+ const { aIdx: fromA, bIdx: b } = alignment[i];
+ const { aIdx: toA, bIdx: end } = alignment[j];
+ if (
+ end - b + 1 <= MAX_STRANDED_KEEP &&
+ (deletedLetter(fromA - 1) || deletedLetter(toA + 1)) &&
+ mostlyDeletedWord(prevText, keptA, fromA) &&
+ (typedLetter(b - 1) || typedLetter(end + 1))
+ )
+ for (let k = b; k <= end; k++) stranded.add(k);
+ i = j + 1;
+ }
+ if (stranded.size === 0) return { keptA, keptB, alignment };
+ const kept = alignment.filter(({ bIdx }) => !stranded.has(bIdx));
+ // Retyping one letter can strand its neighbour ("ua" then "l" of "Annual"), so repeat.
+ return withoutStrandedGlyphs(
+ prevText,
+ nextText,
+ new Set(kept.map(({ aIdx }) => aIdx)),
+ new Set(kept.map(({ bIdx }) => bIdx)),
+ kept,
+ );
+}
+
export function planPartialEdit(
run: TextRun,
prevText: string,
nextText: string,
+ /** Objects to redraw whole rather than set new text on: see {@link objectsToRedrawWhole}. */
+ redrawWhole: ReadonlySet<number> = new Set(),
): PartialEditPlan | null {
if (run.mergedFromPtrs.length === 0) return null;
if (run.mergedFromTexts.length !== run.mergedFromPtrs.length) return null;
@@ -305,6 +435,14 @@ export function planPartialEdit(
}
}
+ ({ keptA, keptB, alignment } = withoutStrandedGlyphs(
+ prevText,
+ nextText,
+ keptA,
+ keptB,
+ alignment,
+ ));
+
// Only now, against the alignment the ops walk will actually use: a diff
// boundary landing inside an astral char would emit a lone surrogate.
if (
@@ -388,6 +526,30 @@ export function planPartialEdit(
}
}
+ // Sub-runs in text order; a gap's whitespace sits between consecutive ones.
+ // A gap after an all-deleted sub-run is already covered by that sub-run's
+ // advance, which the apply subtracts.
+ const ghostGaps: Array<{ beforeSubRunIdx: number; removed: number }> = [];
+ const textOrder = subRunRanges
+ .map((range, idx) => ({ range, idx }))
+ .filter(
+ (e): e is { range: { start: number; end: number }; idx: number } =>
+ e.range !== null && e.range.end > e.range.start,
+ )
+ .sort((a, b) => a.range.start - b.range.start);
+ for (let k = 1; k < textOrder.length; k++) {
+ const before = textOrder[k - 1];
+ const after = textOrder[k];
+ if (subRunStatus[before.idx] === "all-deleted") continue;
+ let removed = 0;
+ for (let c = before.range.end; c < after.range.start; c++) {
+ if (charToSubRun[c] === -1 && /\s/.test(prevText[c]) && !keptA.has(c)) {
+ removed += 1;
+ }
+ }
+ if (removed > 0) ghostGaps.push({ beforeSubRunIdx: after.idx, removed });
+ }
+
// Build ops by walking nextText.
const ops: PartialEditOp[] = [];
let lastSubRun = -1;
@@ -420,7 +582,10 @@ export function planPartialEdit(
const bToA = new Map<number, number>();
for (const { aIdx, bIdx } of alignment) bToA.set(bIdx, aIdx);
- // INTERIOR-INSERT GUARD. Single-char sub-runs have no interior.
+ // A piece typed into mid-word keeps no contiguous stretch of its letters, so
+ // SetText cannot patch it: redraw that piece whole, in its own place, and
+ // leave the rest of the line's objects untouched.
+ const replacedSubRuns = new Set<number>();
{
const keptMin = new Map<number, number>();
const keptMax = new Map<number, number>();
@@ -435,9 +600,29 @@ export function planPartialEdit(
keptCnt.set(sr, (keptCnt.get(sr) ?? 0) + 1);
}
for (const [sr, cnt] of keptCnt) {
- if (keptMax.get(sr)! - keptMin.get(sr)! + 1 !== cnt) return null;
+ if (keptMax.get(sr)! - keptMin.get(sr)! + 1 !== cnt)
+ replacedSubRuns.add(sr);
+ }
+ // SetText reaches one object: the rest of a piece's glyph cluster would go on drawing the letters taken out of it.
+ for (const sr of mixedSubRuns)
+ if (ridersOf(run.mergedFromTexts, sr).length > 0) replacedSubRuns.add(sr);
+ for (const sr of mixedSubRuns)
+ if (redrawWhole.has(run.mergedFromPtrs[sr])) replacedSubRuns.add(sr);
+ for (const { aIdx, bIdx } of alignment) {
+ if (!replacedSubRuns.has(charToSubRun[aIdx])) continue;
+ keptA.delete(aIdx);
+ keptB.delete(bIdx);
+ }
+ for (const sr of replacedSubRuns) {
+ subRunStatus[sr] = "all-deleted";
+ mixedSubRuns.delete(sr);
+ mixedSurviving.delete(sr);
}
}
+ for (let i = 0; i < subRunStatus.length; i++) {
+ const owner = riddenBy(run.mergedFromTexts, i);
+ if (owner >= 0) subRunStatus[i] = subRunStatus[owner];
+ }
for (let b = 0; b < nextText.length; b++) {
if (keptB.has(b)) {
@@ -483,6 +668,15 @@ export function planPartialEdit(
}
lastEmittedBIdx = b;
} else {
+ const replaced = charToSubRun[bToA.get(b) ?? -1];
+ if (
+ insertAnchorSubRun === undefined &&
+ replaced !== undefined &&
+ replacedSubRuns.has(replaced)
+ ) {
+ if (insertBuf.length > 0) flushInsert();
+ insertAnchorSubRun = replaced;
+ }
if (insertBuf.length === 0) {
insertStartBIdx = b;
// Whitespace chars skipped since the last real glyph are ghost
@@ -512,12 +706,151 @@ export function planPartialEdit(
removePtrs,
ops,
subRunStatus,
+ ghostGaps,
prevMergedFromPtrs: [...run.mergedFromPtrs],
prevMergedFromTexts: [...run.mergedFromTexts],
prevMergedFromBounds: run.mergedFromBounds.map((b) => ({ ...b })),
+ nextText,
};
}
+// A kern is tens of thousandths of an em; the float noise in PDFium's char origins stays far below this.
+const KERN_TOLERANCE_PT = 0.01;
+
+/** The objects a plan would set new text on in place. */
+function modifiedPtrs(plan: PartialEditPlan): number[] {
+ return plan.ops.flatMap((op) =>
+ op.type === "modify" && op.subRunIdx !== undefined
+ ? [plan.prevMergedFromPtrs[op.subRunIdx]]
+ : [],
+ );
+}
+
+/**
+ * The objects among `ptrs` an edit should redraw whole rather than set new
+ * text on: those whose letters are not all spaced by their font's advance plus
+ * one constant letter spacing, a TJ kern. SetText lays an object out from its
+ * advances alone, so text set on a kerned object can never be set back where
+ * it was drawn, and undo would shift its letters. A letter whose width the font
+ * cannot report is never evidence. Loads a text page.
+ *
+ * A redraw is a new object, which carries neither the original's clip nor its
+ * word spacing (Tw); an object with either stays edited in place, so the edit
+ * draws right and only its undo is inexact.
+ */
+function objectsToRedrawWhole(
+ m: WrappedPdfiumModule,
+ pagePtr: number,
+ ptrs: Iterable<number>,
+): Set<number> {
+ const wanted = new Set([...ptrs].filter(Boolean));
+ const redraw = new Set<number>();
+ if (wanted.size === 0) return redraw;
+ const glyphs = new Map<number, Array<{ cp: number; x: number }>>();
+ const textPage = m.FPDFText_LoadPage(pagePtr);
+ if (!textPage) return redraw;
+ try {
+ const xPtr = scratchPtr(m, SCRATCH.kernOriginX, 8);
+ const yPtr = scratchPtr(m, SCRATCH.kernOriginY, 8);
+ const count = m.FPDFText_CountChars(textPage);
+ for (let i = 0; i < count; i++) {
+ const ptr = m.FPDFText_GetTextObject(textPage, i);
+ if (!wanted.has(ptr) || m.FPDFText_IsGenerated(textPage, i) === 1)
+ continue;
+ if (!m.FPDFText_GetCharOrigin(textPage, i, xPtr, yPtr)) continue;
+ const list = glyphs.get(ptr) ?? [];
+ list.push({
+ cp: m.FPDFText_GetUnicode(textPage, i),
+ x: m.pdfium.getValue(xPtr, "double"),
+ });
+ glyphs.set(ptr, list);
+ }
+ } finally {
+ m.FPDFText_ClosePage(textPage);
+ }
+ const sizePtr = scratchPtr(m, SCRATCH.kernFontSize, 4);
+ const widthPtr = scratchPtr(m, SCRATCH.kernGlyphWidth, 4);
+ for (const [ptr, list] of glyphs) {
+ const matrix = readMatrix(m, ptr);
+ const font = objFontPtr(m, ptr);
+ if (!matrix || !font || matrix[0] <= 0 || Math.abs(matrix[1]) > 1e-3)
+ continue;
+ const clip = m.FPDFPageObj_GetClipPath(ptr);
+ if (clip && m.FPDFClipPath_CountPaths(clip) > 0) continue;
+ if (!m.FPDFTextObj_GetFontSize(ptr, sizePtr)) continue;
+ const size = m.pdfium.getValue(sizePtr, "float");
+ const letters: number[] = [];
+ const spaces: number[] = [];
+ for (let k = 0; k + 1 < list.length; k++) {
+ const { cp, x } = list[k];
+ if (cp < 0x20 || cp === 0xa0) continue;
+ if (!m.FPDFFont_GetGlyphWidth(font, cp, size, widthPtr)) continue;
+ const width = m.pdfium.getValue(widthPtr, "float");
+ if (!(width > 0)) continue;
+ const extra = (list[k + 1].x - x) / matrix[0] - width;
+ (cp === 0x20 ? spaces : letters).push(extra);
+ }
+ if (letters.length === 0) continue;
+ const low = Math.min(...letters);
+ const high = Math.max(...letters);
+ const tolerance = KERN_TOLERANCE_PT / matrix[0];
+ const kerned = high - low > tolerance;
+ // A kern after a space reads like word spacing, so a space only counts as Tw when it is set apart further than the kerns themselves vary.
+ const slack = Math.max(tolerance, high - low);
+ const wordSpaced = spaces.some(
+ (extra) => extra < low - slack || extra > high + slack,
+ );
+ if (kerned && !wordSpaced) redraw.add(ptr);
+ }
+ return redraw;
+}
+
+/** {@link planPartialEdit}, redrawing whole each piece whose in-place edit undo could not set back exactly. */
+export function planUndoablePartialEdit(
+ m: WrappedPdfiumModule,
+ pagePtr: number,
+ run: TextRun,
+ prevText: string,
+ nextText: string,
+): PartialEditPlan | null {
+ const plan = planPartialEdit(run, prevText, nextText);
+ if (!plan) return null;
+ const kerned = objectsToRedrawWhole(
+ m,
+ pagePtr,
+ onPage(run, modifiedPtrs(plan)),
+ );
+ return kerned.size > 0
+ ? planPartialEdit(run, prevText, nextText, kerned)
+ : plan;
+}
+
+/** {@link planParagraphEdit}, redrawing whole each piece whose in-place edit undo could not set back exactly. */
+export function planUndoableParagraphEdit(
+ m: WrappedPdfiumModule,
+ pagePtr: number,
+ run: TextRun,
+ prevText: string,
+ nextText: string,
+): ParagraphEditPlan | null {
+ const plan = planParagraphEdit(run, prevText, nextText);
+ if (!plan) return null;
+ const modified = plan.perSlot.flatMap((entry) =>
+ entry.plan ? modifiedPtrs(entry.plan) : [],
+ );
+ const kerned = objectsToRedrawWhole(m, pagePtr, onPage(run, modified));
+ return kerned.size > 0
+ ? planParagraphEdit(run, prevText, nextText, kerned)
+ : plan;
+}
+
+// Undo puts back only objects it took off the page itself; one taken out of a form is redrawn instead, and can lose its font.
+function onPage(run: TextRun, ptrs: number[]): number[] {
+ if (run.containerPtr !== 0) return [];
+ const containerOf = collectContainersByPtr(run);
+ return ptrs.filter((ptr) => !containerOf.get(ptr));
+}
+
let _wsMeasureCanvas: HTMLCanvasElement | null = null;
/** Canvas-measured advance width for whitespace chars. */
function measureWhitespaceAdvancePt(
@@ -542,7 +875,7 @@ interface FontReadingModule {
// Borrow the font handle from the FIRST surviving sub-object that wasn't slated
// for removal.
function borrowFontFromSurvivor(
- m: import("@embedpdf/pdfium").WrappedPdfiumModule,
+ m: WrappedPdfiumModule,
plan: PartialEditPlan,
): number {
const fontMod = m as unknown as FontReadingModule;
@@ -564,7 +897,7 @@ function borrowFontFromSurvivor(
// Borrow the font of a surviving sub-object that ACTUALLY CONTAINS the
// characters we're about to insert.
function borrowFontForChars(
- m: import("@embedpdf/pdfium").WrappedPdfiumModule,
+ m: WrappedPdfiumModule,
plan: PartialEditPlan,
chars: string,
): number {
@@ -600,8 +933,28 @@ function borrowFontForChars(
return borrowFontFromSurvivor(m, plan);
}
-interface FormRemovalModule {
- FPDFFormObj_RemoveObject?: (form: number, obj: number) => boolean;
+// The font a redrawn piece was first drawn in. A word typed against it can push the whole piece into a fallback face; once the typed letters move away, the words that font draws go back to it.
+// Keyed by object pointer, which PDFium reuses once an object is destroyed, so an entry holds only while the object still draws in the font it was recorded with.
+const sourceFonts = new WeakMap<
+ EditorDocument,
+ Map<number, { source: number; drawn: number }>
+>();
+
+function sourceFontsOf(
+ doc: EditorDocument,
+): Map<number, { source: number; drawn: number }> {
+ let fonts = sourceFonts.get(doc);
+ if (!fonts) {
+ fonts = new Map();
+ sourceFonts.set(doc, fonts);
+ }
+ return fonts;
+}
+
+function sourceFontOf(doc: EditorDocument, ptr: number): number {
+ const drawn = objFontPtr(doc.module, ptr);
+ const entry = sourceFontsOf(doc).get(ptr);
+ return entry && entry.drawn === drawn ? entry.source : drawn;
}
export interface PartialEditApplyResult {
@@ -629,26 +982,66 @@ export function applyPartialEditPlan(
defaultX?: number,
): PartialEditApplyResult {
const m = doc.module;
- const formMod = m as unknown as FormRemovalModule;
const emitY = baselineY ?? run.matrix.f;
const startX = defaultX ?? run.bounds.x;
+ const containerOf = collectContainersByPtr(run);
+ // An object inside a form XObject moves in the form's own space, which the form's matrix scales away from the page's.
+ const shiftAlongPage = (ptr: number, dx: number): void => {
+ const container = containerOf.get(ptr) ?? run.containerPtr;
+ const form = container ? readMatrix(m, container) : null;
+ const det = form ? form[0] * form[3] - form[1] * form[2] : 1;
+ if (!form || Math.abs(det) < 1e-9)
+ transformObject(m, ptr, 1, 0, 0, 1, dx, 0);
+ else
+ transformObject(
+ m,
+ ptr,
+ 1,
+ 0,
+ 0,
+ 1,
+ (form[3] * dx) / det,
+ (-form[1] * dx) / det,
+ );
+ };
+ // Letters typed onto a word take that word's face and colour, so it is not drawn half in one style and half in another.
+ const wordNeighbour = (text: string, beforeIdx?: number): number => {
+ let last = newMergedFromTexts.length - 1;
+ while (last >= 0 && newMergedFromTexts[last] === "") last--;
+ const touching =
+ last >= 0 && /\S$/.test(newMergedFromTexts[last]) && /^\S/.test(text)
+ ? newMergedFromPtrs[last]
+ : beforeIdx !== undefined &&
+ /\S$/.test(text) &&
+ /^\S/.test(plan.prevMergedFromTexts[beforeIdx] ?? "")
+ ? plan.prevMergedFromPtrs[beforeIdx]
+ : 0;
+ return touching;
+ };
+ const drawsAll = (font: number, text: string): boolean =>
+ charcodesResolveFully(
+ m,
+ font,
+ text.replace(/\s+/g, ""),
+ page.pagePtr,
+ doc.docPtr,
+ );
+ const lineStart =
+ run.containerPtr === 0
+ ? Math.min(
+ ...contentIndices(m, page.pagePtr, plan.prevMergedFromPtrs).values(),
+ )
+ : Infinity;
+ // Read before the removals below take any of these objects off the page.
+ const prevFills = plan.prevMergedFromPtrs.map((ptr) =>
+ ptr ? readObjFill(m, ptr) : null,
+ );
+ const fillOf = (prevIdx: number | undefined) =>
+ (prevIdx === undefined ? null : prevFills[prevIdx]) ?? run.fill;
// Removals run before the walk below: it re-emits from the surviving
// pointers, so a deleted object still on the page would be re-counted.
for (const { ptr, containerPtr } of plan.removePtrs) {
- if (!ptr) continue;
- if (containerPtr && formMod.FPDFFormObj_RemoveObject) {
- try {
- formMod.FPDFFormObj_RemoveObject(containerPtr, ptr);
- } catch {
- /* best-effort */
- }
- } else {
- try {
- m.FPDFPage_RemoveObject(page.pagePtr, ptr);
- } catch {
- /* best-effort */
- }
- }
+ if (ptr) removeTextObject(m, page, ptr, containerPtr);
}
const fallbackFamily = fallbackFamilyFor(run.fontId);
@@ -691,31 +1084,157 @@ export function applyPartialEditPlan(
// Strategy: walk ops in order.
let firstX = startX;
let lastEnd = startX;
+ // Bounds stop at the last glyph's ink, so the trailing space must be added back.
+ let spacesAtEnd = "";
+ const trailingSpaces = (text: string) => /\s*$/.exec(text)?.[0] ?? "";
+ function extendLastEnd(right: number, text: string): void {
+ if (right < lastEnd) return;
+ lastEnd = right;
+ spacesAtEnd = trailingSpaces(text);
+ }
+ // Tc stretches spaces too, matching the gaps emitTextLine draws.
+ const whitespaceAdvancePt = (text: string) =>
+ text
+ ? measureWhitespaceAdvancePt(text, fallbackFamily, run.fontSize) +
+ run.charSpacingPt * text.length
+ : 0;
let offset = 0;
+ // A rider has no place of its own on the line: it sits wherever its piece is put.
+ const rides = (idx: number) => riddenBy(plan.prevMergedFromTexts, idx) >= 0;
// Tracks the highest sub-run index we've already accounted for in `offset`.
let processedUpTo = -1;
+ // Closing a deleted ghost space mirrors inserting one (same width), but
+ // never past the visible gap, so objects can't be pulled onto each other.
+ const ghostGapBefore = new Map(
+ plan.ghostGaps.map((g) => [g.beforeSubRunIdx, g.removed]),
+ );
+ function absorbGhostGap(idx: number): void {
+ const removed = ghostGapBefore.get(idx);
+ if (!removed) return;
+ ghostGapBefore.delete(idx);
+ const width =
+ measureWhitespaceAdvancePt(
+ " ".repeat(removed),
+ fallbackFamily,
+ run.fontSize,
+ ) +
+ run.charSpacingPt * removed;
+ const here = plan.prevMergedFromBounds[idx];
+ const left = previousRightEdge(idx);
+ const gap = here && left !== null ? Math.max(0, here.x - left) : width;
+ offset -= Math.min(width, gap);
+ }
+ // Right edge of the sub-run drawn just before `idx` in the original layout.
+ function previousRightEdge(idx: number): number | null {
+ const here = plan.prevMergedFromBounds[idx];
+ if (!here) return null;
+ let best: number | null = null;
+ for (const b of plan.prevMergedFromBounds) {
+ if (b.right <= here.x + 0.01 && (best === null || b.right > best))
+ best = b.right;
+ }
+ return best;
+ }
function absorbDeletesBefore(idx: number): void {
for (let i = processedUpTo + 1; i < idx; i++) {
- if (plan.subRunStatus[i] === "all-deleted") {
+ if (plan.subRunStatus[i] === "all-deleted" && !rides(i)) {
const b = plan.prevMergedFromBounds[i];
if (!b) continue;
// Subtract the deleted sub-run's ADVANCE, not just its ink width.
- const next = plan.prevMergedFromBounds[i + 1];
+ const next =
+ plan.prevMergedFromBounds[
+ i + 1 + ridersOf(plan.prevMergedFromTexts, i).length
+ ];
offset -= next && next.x > b.x ? next.x - b.x : b.right - b.x;
}
}
processedUpTo = Math.max(processedUpTo, idx);
}
- for (const op of plan.ops) {
+ const nextSurvivorOp: Array<PartialEditOp | undefined> = [];
+ let upcoming: PartialEditOp | undefined;
+ for (let i = plan.ops.length - 1; i >= 0; i--) {
+ nextSurvivorOp[i] = upcoming;
+ const o = plan.ops[i];
+ if ((o.type === "keep" || o.type === "modify") && o.subRunIdx !== undefined)
+ upcoming = o;
+ }
+
+ // Null when nothing follows the insert or a deletion before it is still pending.
+ const followingX = (opIndex: number): number | null => {
+ const idx = nextSurvivorOp[opIndex]?.subRunIdx;
+ if (idx === undefined) return null;
+ for (let i = processedUpTo + 1; i < idx; i++)
+ if (plan.subRunStatus[i] === "all-deleted" && !rides(i)) return null;
+ const bounds = plan.prevMergedFromBounds[idx];
+ return bounds ? bounds.x + offset : null;
+ };
+
+ const insertAnchorX = (
+ origBounds: { x: number } | null,
+ beforeBounds: { x: number } | null,
+ leadingGap: number,
+ ): number => {
+ if (origBounds) return origBounds.x + offset;
+ if (beforeBounds) return beforeBounds.x + offset;
+ return lastEnd + leadingGap + whitespaceAdvancePt(spacesAtEnd);
+ };
+
+ const offsetAfterInsert = (
+ opIndex: number,
+ origBounds: { x: number; right: number } | null,
+ beforeBounds: { x: number } | null,
+ insert: {
+ text: string;
+ anchorX: number;
+ rightEdge: number;
+ width: number;
+ leadingGap: number;
+ hasInk: boolean;
+ },
+ ): number => {
+ const op = plan.ops[opIndex];
+ // Anchored (mixed-replacement): delta vs original sub-run width.
+ if (origBounds)
+ return (
+ insert.width -
+ (origBounds.right - origBounds.x) -
+ whitespaceAdvancePt(
+ trailingSpaces(plan.prevMergedFromTexts[op.anchorSubRunIdx!] ?? ""),
+ )
+ );
+ const following = nextSurvivorOp[opIndex];
+ if (beforeBounds) {
+ // Spaces typed before the next word belong to no object, so add their width.
+ const between =
+ following && following.subRunIdx === op.anchorBeforeSubRunIdx
+ ? plan.nextText.slice(
+ op.startBIdx + insert.text.length,
+ following.startBIdx,
+ )
+ : "";
+ return insert.width + whitespaceAdvancePt(between);
+ }
+ // Keep the old gap from the new text's end: ink width drifts a side bearing per key.
+ const followX = followingX(opIndex);
+ if (followX === null || !insert.hasInk)
+ // The ghost-space gap also pushes everything after this insert right.
+ return insert.leadingGap + insert.width;
+ const gap = Math.max(0, followX - insert.anchorX);
+ const trailingAdvance = whitespaceAdvancePt(trailingSpaces(insert.text));
+ return insert.rightEdge + trailingAdvance + gap - followX;
+ };
+
+ for (const [opIndex, op] of plan.ops.entries()) {
if (op.type === "keep" && op.subRunIdx !== undefined) {
absorbDeletesBefore(op.subRunIdx);
+ absorbGhostGap(op.subRunIdx);
const ptr = plan.prevMergedFromPtrs[op.subRunIdx];
const text = plan.prevMergedFromTexts[op.subRunIdx];
const origBounds = plan.prevMergedFromBounds[op.subRunIdx];
if (Math.abs(offset) > 0.05) {
try {
- transformObject(m, ptr, 1, 0, 0, 1, offset, 0);
+ shiftAlongPage(ptr, offset);
} catch {
/* best-effort */
}
@@ -726,7 +1245,25 @@ export function applyPartialEditPlan(
newMergedFromTexts.push(text);
newMergedFromBounds.push({ x: newX, right: newRight });
newMergedFromCharStarts.push(op.startBIdx);
- if (newRight > lastEnd) lastEnd = newRight;
+ extendLastEnd(newRight, text);
+ for (const rider of ridersOf(plan.prevMergedFromTexts, op.subRunIdx)) {
+ const riderPtr = plan.prevMergedFromPtrs[rider];
+ const riderBounds = plan.prevMergedFromBounds[rider];
+ if (Math.abs(offset) > 0.05) {
+ try {
+ shiftAlongPage(riderPtr, offset);
+ } catch {
+ /* best-effort */
+ }
+ }
+ newMergedFromPtrs.push(riderPtr);
+ newMergedFromTexts.push("");
+ newMergedFromBounds.push({
+ x: riderBounds.x + offset,
+ right: riderBounds.right + offset,
+ });
+ newMergedFromCharStarts.push(op.startBIdx + text.length);
+ }
} else if (
op.type === "modify" &&
op.subRunIdx !== undefined &&
@@ -735,6 +1272,7 @@ export function applyPartialEditPlan(
// Edit a mixed sub-run's EXISTING object in place: SetText the surviving
// chars so the embedded font is kept.
absorbDeletesBefore(op.subRunIdx);
+ absorbGhostGap(op.subRunIdx);
const ptr = plan.prevMergedFromPtrs[op.subRunIdx];
const origBounds = plan.prevMergedFromBounds[op.subRunIdx];
const origWidth = origBounds.right - origBounds.x;
@@ -743,10 +1281,10 @@ export function applyPartialEditPlan(
// can reuse the same embedded font via the charcode path.
const modFontPtr = objFontPtr(m, ptr);
const modTags = readTagMarks(m, ptr);
- setObjText(m, ptr, modText);
+ setObjText(doc, page, ptr, modText);
if (Math.abs(offset) > 0.05) {
try {
- transformObject(m, ptr, 1, 0, 0, 1, offset, 0);
+ shiftAlongPage(ptr, offset);
} catch {
/* best-effort */
}
@@ -769,7 +1307,7 @@ export function applyPartialEditPlan(
x: newX,
y: emitY,
fontSize: run.fontSize,
- fill: run.fill,
+ fill: fillOf(op.subRunIdx),
...inkFromRun(run),
tags: uniformTags(modTags),
originalFontPtr: modFontPtr,
@@ -810,7 +1348,7 @@ export function applyPartialEditPlan(
cur += w;
charCursor += slice.length;
}
- if (reRight > lastEnd) lastEnd = reRight;
+ extendLastEnd(reRight, modText);
offset += reRight - newX - origWidth;
}
} else {
@@ -820,7 +1358,7 @@ export function applyPartialEditPlan(
newMergedFromTexts.push(modText);
newMergedFromBounds.push({ x: newX, right: newRight });
newMergedFromCharStarts.push(op.startBIdx);
- if (newRight > lastEnd) lastEnd = newRight;
+ extendLastEnd(newRight, modText);
// Subsequent sub-runs shift by the width delta (surviving text is
// usually narrower than the original).
offset += newRight - newX - origWidth;
@@ -834,8 +1372,13 @@ export function applyPartialEditPlan(
);
const anchorIdx = op.anchorSubRunIdx;
const beforeIdx = op.anchorBeforeSubRunIdx;
- if (anchorIdx !== undefined) absorbDeletesBefore(anchorIdx);
- else if (beforeIdx !== undefined) absorbDeletesBefore(beforeIdx);
+ if (anchorIdx !== undefined) {
+ absorbDeletesBefore(anchorIdx);
+ absorbGhostGap(anchorIdx);
+ } else if (beforeIdx !== undefined) {
+ absorbDeletesBefore(beforeIdx);
+ absorbGhostGap(beforeIdx);
+ }
const origBounds =
anchorIdx !== undefined ? plan.prevMergedFromBounds[anchorIdx] : null;
// "prefix of the following word" anchor: emit at that kept sub-run's
@@ -845,17 +1388,36 @@ export function applyPartialEditPlan(
// Anchor priority: * anchorSubRunIdx: emit at the replaced sub-run's x.
const leadingGap =
(op.leadingGhostCount ?? 0) * Math.max(1, run.fontSize) * 0.25;
- const anchorX = origBounds
- ? origBounds.x + offset
- : beforeBounds
- ? beforeBounds.x + offset
- : lastEnd + leadingGap;
-
+ const anchorX = insertAnchorX(origBounds, beforeBounds, leadingGap);
+
+ // A redrawn piece keeps its own face (bold, italic, a symbol font) for every
+ // word it can draw, and a fallback of its style for the rest.
+ const ownFont =
+ anchorIdx !== undefined
+ ? sourceFontOf(doc, plan.prevMergedFromPtrs[anchorIdx])
+ : 0;
// Borrow the font from a survivor that actually contains the inserted
// chars, so the new glyph reuses that exact embedded font.
- const borrowedFontPtr = allInsertCharsAreSafe
- ? borrowFontForChars(m, plan, insertText)
- : 0;
+ const neighbour = ownFont ? 0 : wordNeighbour(insertText, beforeIdx);
+ const neighbourFont = neighbour ? objFontPtr(m, neighbour) : 0;
+ const insertFill =
+ anchorIdx !== undefined
+ ? fillOf(anchorIdx)
+ : ((neighbour ? readObjFill(m, neighbour) : null) ?? run.fill);
+ const neighbourDraws =
+ neighbourFont !== 0 && drawsAll(neighbourFont, insertText);
+ const borrowedFontPtr =
+ ownFont ||
+ (neighbourDraws ? neighbourFont : 0) ||
+ (!neighbourFont && allInsertCharsAreSafe
+ ? borrowFontForChars(m, plan, insertText)
+ : 0);
+ const faceFont = ownFont || neighbourFont;
+ const insertFallback = faceFont
+ ? (deviceFamilyOf(doc, faceFont) ??
+ fallbackFamilyFor(`pdf:${faceFont}:${baseFontName(m, faceFont)}`))
+ : fallbackFamily;
+ const emittedTexts: string[] = [];
// Try the borrowed source font first; measure the result and fall back to
// Helvetica if the rendered width is sub-threshold.
@@ -866,13 +1428,14 @@ export function applyPartialEditPlan(
x: anchorX,
y: emitY,
fontSize: run.fontSize,
- fill: run.fill,
+ fill: insertFill,
...inkFromRun(run),
tags: insertTags,
originalFontPtr: borrowedFontPtr,
originalFontSubset: run.fontSubset,
charSpacingPt: run.charSpacingPt,
- fallbackFamily,
+ fallbackFamily: insertFallback,
+ outTexts: emittedTexts,
});
let realRightEdge = anchorX;
for (const ptr of ptrs) {
@@ -902,6 +1465,7 @@ export function applyPartialEditPlan(
/* best-effort */
}
}
+ emittedTexts.length = 0;
ptrs = emitTextLine({
doc,
page,
@@ -909,12 +1473,13 @@ export function applyPartialEditPlan(
x: anchorX,
y: emitY,
fontSize: run.fontSize,
- fill: run.fill,
+ fill: insertFill,
...inkFromRun(run),
tags: insertTags,
originalFontPtr: 0,
charSpacingPt: run.charSpacingPt,
- fallbackFamily,
+ fallbackFamily: insertFallback,
+ outTexts: emittedTexts,
});
realRightEdge = anchorX;
for (const ptr of ptrs) {
@@ -923,46 +1488,44 @@ export function applyPartialEditPlan(
}
measuredWidth = realRightEdge - anchorX;
}
- // Add the advance width of whitespace chars so the offset that shifts
- // following kept sub-runs accounts for inserted spaces.
- const whitespaceLen = insertText.length - nonWhitespaceLen;
- if (whitespaceLen > 0) {
- const wsWidth = measureWhitespaceAdvancePt(
- " ".repeat(whitespaceLen),
- fallbackFamily,
- run.fontSize,
- );
- // Letter-spaced runs stretch inserted spaces too (Tc applies to
- // space glyphs), matching the widened gaps emitTextLine produced.
- measuredWidth += wsWidth + run.charSpacingPt * whitespaceLen;
- }
- // Map emitted ptrs back to text. emitTextLine emits one ptr per
- // whitespace-separated WORD on the normal path.
- const insertWords: Array<{ text: string; start: number }> = [];
- {
- const wordRe = /\S+/g;
- let wm: RegExpExecArray | null;
- while ((wm = wordRe.exec(insertText)) !== null) {
- insertWords.push({ text: wm[0], start: wm.index });
+ if (ownFont)
+ for (const ptr of ptrs)
+ if (ptr)
+ sourceFontsOf(doc).set(ptr, {
+ source: ownFont,
+ drawn: objFontPtr(m, ptr),
+ });
+ if (origBounds && ptrs.length > 0) {
+ const pieceText = plan.prevMergedFromTexts[anchorIdx!] ?? "";
+ const firstInk = objBoundsLR(m, ptrs[0], anchorX).x;
+ const drift = anchorX - firstInk;
+ // Same first glyph, so the redrawn piece starts where the old one did instead of creeping a side bearing per keystroke.
+ // A piece that opens with a space starts at the space, not at its first ink, so there is no bearing to take back.
+ if (
+ pieceText[0] === insertText[0] &&
+ /\S/.test(insertText[0]) &&
+ Math.abs(drift) > 0.05
+ ) {
+ for (const ptr of ptrs) transformObject(m, ptr, 1, 0, 0, 1, drift, 0);
+ realRightEdge += drift;
+ measuredWidth = realRightEdge - anchorX;
}
}
- if (ptrs.length === insertWords.length) {
- for (let i = 0; i < ptrs.length; i++) {
- const word = insertWords[i];
- if (!word) {
- try {
- m.FPDFPage_RemoveObject(page.pagePtr, ptrs[i]);
- } catch {
- /* best-effort */
- }
- continue;
- }
- const bnds = objBoundsLR(m, ptrs[i], anchorX);
- newMergedFromPtrs.push(ptrs[i]);
- newMergedFromTexts.push(word.text);
+ // The emitted ink already spans spaces between words; only whitespace past the last glyph is missing.
+ measuredWidth += whitespaceAdvancePt(
+ nonWhitespaceLen === 0 ? insertText : trailingSpaces(insertText),
+ );
+ // Map each emitted ptr to the text it actually carries: a word the font
+ // could not draw is dropped, so counting words would shift every later one.
+ const placed = placeEmittedTexts(insertText, ptrs, emittedTexts);
+ if (placed) {
+ for (const { ptr, text, start } of placed) {
+ const bnds = objBoundsLR(m, ptr, anchorX);
+ newMergedFromPtrs.push(ptr);
+ newMergedFromTexts.push(text);
newMergedFromBounds.push({ x: bnds.x, right: bnds.right });
- newMergedFromCharStarts.push(op.startBIdx + word.start);
- insertedPtrs.push(ptrs[i]);
+ newMergedFromCharStarts.push(op.startBIdx + start);
+ insertedPtrs.push(ptr);
}
} else {
// Per-char (or mismatched) emit: slice the insert text across ptrs.
@@ -993,21 +1556,26 @@ export function applyPartialEditPlan(
charCursor += sliceText.length;
}
}
- if (realRightEdge > lastEnd) lastEnd = realRightEdge;
- // Update offset: * anchored (mixed-replacement): delta vs original
- // sub-run width.
- if (origBounds) {
- const origWidth = origBounds.right - origBounds.x;
- offset += measuredWidth - origWidth;
- } else if (beforeBounds) {
- offset += measuredWidth;
- } else {
- // The ghost-space gap also pushes everything after this insert right.
- offset += leadingGap + measuredWidth;
- }
+ extendLastEnd(realRightEdge, insertText);
+ offset += offsetAfterInsert(opIndex, origBounds, beforeBounds, {
+ text: insertText,
+ anchorX,
+ rightEdge: realRightEdge,
+ width: measuredWidth,
+ leadingGap,
+ hasInk: nonWhitespaceLen > 0,
+ });
}
}
+ placeInsertedPieces(
+ m,
+ page.pagePtr,
+ newMergedFromPtrs,
+ newMergedFromTexts,
+ new Set(insertedPtrs),
+ lineStart,
+ );
page.markNeedsGenerate();
if (newMergedFromBounds.length > 0) {
@@ -1027,12 +1595,91 @@ export function applyPartialEditPlan(
};
}
+/** The pre-edit state of a partial edit's sub-runs that its plan does not hold. */
+export interface PartialEditRevertState {
+ /** Font each sub-run was drawn in, parallel to `plan.prevMergedFromPtrs`. */
+ fonts: number[];
+ /** Fill each sub-run was drawn in, parallel to `plan.prevMergedFromPtrs`; null where unreadable. */
+ fills: Array<RGBA | null>;
+ charStarts: number[];
+ baselineY: number;
+ fontSubset: boolean;
+}
+
+/** Inverse of applyPartialEditPlan once its inserts are gone: maps each removed sub-run to its redrawn object, or null with the page untouched. */
+export function revertPartialEditPlan(
+ doc: EditorDocument,
+ page: Page,
+ run: TextRun,
+ plan: PartialEditPlan,
+ prev: PartialEditRevertState,
+ tagsOf: (start: number, end: number) => TextTags,
+ fallbackFamily: string,
+): Map<number, number> | null {
+ const m = doc.module;
+ const ptrs = plan.prevMergedFromPtrs;
+ const removed = new Set(plan.removePtrs.map((r) => r.ptr));
+ // A font handle dies with its last object, so reuse it only while a kept object holds it.
+ const liveFonts = new Set(
+ ptrs.flatMap((ptr, i) => (ptr && !removed.has(ptr) ? [prev.fonts[i]] : [])),
+ );
+ const replacements = new Map<number, number>();
+ const discard = (extra: number[]): null => {
+ for (const ptr of [...replacements.values(), ...extra]) {
+ removeAndDestroyObject(m, page.pagePtr, ptr);
+ }
+ return null;
+ };
+ for (let i = 0; i < ptrs.length; i++) {
+ const ptr = ptrs[i];
+ if (!removed.has(ptr)) continue;
+ const text = plan.prevMergedFromTexts[i] ?? "";
+ const bounds = plan.prevMergedFromBounds[i];
+ if (!text || !bounds) return discard([]);
+ const start = prev.charStarts[i] ?? 0;
+ const font = prev.fonts[i] ?? 0;
+ const emitted = emitTextLine({
+ doc,
+ page,
+ text,
+ x: bounds.x,
+ y: prev.baselineY,
+ fontSize: run.fontSize,
+ fill: prev.fills[i] ?? run.fill,
+ ...inkFromRun(run),
+ tags: tagsOf(start, start + text.length),
+ originalFontPtr: liveFonts.has(font) ? font : 0,
+ originalFontSubset: prev.fontSubset,
+ charSpacingPt: run.charSpacingPt,
+ fallbackFamily,
+ });
+ if (emitted.length !== 1 || !emitted[0]) return discard(emitted);
+ replacements.set(ptr, emitted[0]);
+ }
+ for (let i = 0; i < ptrs.length; i++) {
+ const live = replacements.get(ptrs[i]) ?? ptrs[i];
+ const bounds = plan.prevMergedFromBounds[i];
+ if (!live || !bounds || riddenBy(plan.prevMergedFromTexts, i) >= 0)
+ continue;
+ const left = measureObjSpanPt(m, [live])?.left;
+ moveObjectLeftEdgeTo(m, live, bounds.x);
+ const moved = measureObjSpanPt(m, [live])?.left;
+ if (left === undefined || moved === undefined || moved === left) continue;
+ // A rider's stored bounds are its piece's, so it follows by the piece's shift, not to the piece's edge.
+ for (const rider of ridersOf(plan.prevMergedFromTexts, i))
+ if (ptrs[rider])
+ transformObject(m, ptrs[rider], 1, 0, 0, 1, moved - left, 0);
+ }
+ return replacements;
+}
+
/** Paragraph-aware partial edit. */
export interface ParagraphEditPlan {
/** Per-slot per-line plan, parallel to `run.paragraphLineSlots`. */
perSlot: Array<{
slotIdx: number;
plan: PartialEditPlan | null;
+ prevLine: string;
nextLine: string;
}>;
/** Per-VISUAL-line next text, parallel to `run.paragraphLineSlots`. */
@@ -1048,18 +1695,256 @@ function countChar(s: string, ch: string): number {
return n;
}
-/** True when a plan would SetText whitespace in place via a "modify" op. */
-export function planModifiesWhitespace(plan: PartialEditPlan): boolean {
- return plan.ops.some(
- (op) => op.type === "modify" && !!op.text && /\s/.test(op.text),
- );
+// Pieces that stayed keep their place, so a fill or underline drawn between them still paints under its word; only the new pieces move, to just after the line piece before them. Pieces inside a form are not page objects and are left alone.
+function placeInsertedPieces(
+ m: WrappedPdfiumModule,
+ pagePtr: number,
+ pieces: readonly number[],
+ texts: readonly string[],
+ inserted: ReadonlySet<number>,
+ lineStart: number,
+): void {
+ for (let i = 0; i < pieces.length; i++) {
+ const ptr = pieces[i];
+ if (!inserted.has(ptr)) continue;
+ const at = contentIndices(m, pagePtr, pieces);
+ const here = at.get(ptr);
+ if (here === undefined) continue;
+ // A piece and its riders are one stretch of content order whichever of them comes first in it, so a neighbour goes past the whole stretch.
+ const clusterAt = (piece: number): number[] => {
+ const owner = riddenBy(texts, piece);
+ const head = owner >= 0 ? owner : piece;
+ return [head, ...ridersOf(texts, head)].flatMap((j) =>
+ at.has(pieces[j]) ? [at.get(pieces[j])!] : [],
+ );
+ };
+ let before = i - 1;
+ while (before >= 0 && !at.has(pieces[before])) before--;
+ let after = i + 1;
+ while (
+ after < pieces.length &&
+ (!at.has(pieces[after]) || inserted.has(pieces[after]))
+ )
+ after++;
+ const last = before >= 0 ? Math.max(...clusterAt(before)) : -1;
+ const first = after < pieces.length ? Math.min(...clusterAt(after)) : -1;
+ const target =
+ last >= 0
+ ? last + (last < here ? 1 : 0)
+ : first >= 0
+ ? first - (first < here ? 0 : 1)
+ : Number.isFinite(lineStart)
+ ? Math.min(lineStart, here)
+ : here;
+ if (target !== here)
+ restoreContentOrder(m, pagePtr, [{ ptr, index: target }]);
+ }
+}
+
+/** Each ptr with the stretch of `text` it carries, found in order; null when the emit's texts cannot all be placed. */
+function placeEmittedTexts(
+ text: string,
+ ptrs: number[],
+ emittedTexts: string[],
+): Array<{ ptr: number; text: string; start: number }> | null {
+ if (emittedTexts.length !== ptrs.length) return null;
+ const out: Array<{ ptr: number; text: string; start: number }> = [];
+ let cursor = 0;
+ for (let i = 0; i < ptrs.length; i++) {
+ const carried = emittedTexts[i].trim();
+ if (!carried) continue;
+ const start = text.indexOf(carried, cursor);
+ if (start < 0) return null;
+ out.push({ ptr: ptrs[i], text: carried, start });
+ cursor = start + carried.length;
+ }
+ return out;
+}
+
+/** The pieces `ptrs` draw of `line`, found in order by their own text; null when one cannot be placed. */
+export function piecesFromObjects(
+ m: WrappedPdfiumModule,
+ pagePtr: number,
+ ptrs: number[],
+ line: string,
+): Pick<
+ ParagraphLineSlot,
+ "mergedFromPtrs" | "mergedFromTexts" | "mergedFromCharStarts"
+> | null {
+ const texts = readObjTexts(m, pagePtr, ptrs);
+ const starts: number[] = [];
+ const kept: string[] = [];
+ let cursor = 0;
+ for (const raw of texts) {
+ const text = raw?.trim() ?? "";
+ const at = text ? line.indexOf(text, cursor) : -1;
+ if (at < 0) return null;
+ starts.push(at);
+ kept.push(text);
+ cursor = at + text.length;
+ }
+ return {
+ mergedFromPtrs: ptrs,
+ mergedFromTexts: kept,
+ mergedFromCharStarts: starts,
+ };
+}
+
+interface PieceStyle {
+ font: number;
+ fill: RGBA | null;
+}
+
+/**
+ * The font and fill each stretch of `nextLine` came from, when the line held more than one:
+ * characters outside the edited middle keep their piece's, and typed ones take those of the
+ * word they were typed into. Undefined for a line drawn in a single font and fill.
+ */
+export function sourceFontSpans(
+ m: WrappedPdfiumModule,
+ pieces: Pick<
+ ParagraphLineSlot,
+ "mergedFromPtrs" | "mergedFromTexts" | "mergedFromCharStarts"
+ >,
+ prevLine: string,
+ nextLine: string,
+ covers?: (fontPtr: number, text: string) => boolean,
+): FontSpan[] | undefined {
+ const styles = new Map<string, PieceStyle>();
+ const styleOf = (ptr: number): PieceStyle | null => {
+ const font = objFontPtr(m, ptr);
+ if (!font) return null;
+ const fill = readObjFill(m, ptr);
+ const key = fill
+ ? `${font}:${fill.r},${fill.g},${fill.b},${fill.a}`
+ : `${font}`;
+ if (!styles.has(key)) styles.set(key, { font, fill });
+ return styles.get(key)!;
+ };
+ const styleAt = new Array<PieceStyle | null>(prevLine.length).fill(null);
+ pieces.mergedFromPtrs.forEach((ptr, i) => {
+ const start = pieces.mergedFromCharStarts[i];
+ const end = start + (pieces.mergedFromTexts[i]?.length ?? 0);
+ const style = styleOf(ptr);
+ for (let c = Math.max(0, start); c < Math.min(end, prevLine.length); c++)
+ styleAt[c] = style;
+ });
+ for (let c = 1; c < styleAt.length; c++) styleAt[c] ||= styleAt[c - 1];
+ for (let c = styleAt.length - 2; c >= 0; c--) styleAt[c] ||= styleAt[c + 1];
+ if (new Set(styleAt.filter(Boolean)).size < 2) return undefined;
+
+ let prefix = 0;
+ while (
+ prefix < prevLine.length &&
+ prefix < nextLine.length &&
+ prevLine[prefix] === nextLine[prefix]
+ )
+ prefix++;
+ let suffix = 0;
+ while (
+ suffix < prevLine.length - prefix &&
+ suffix < nextLine.length - prefix &&
+ prevLine[prevLine.length - 1 - suffix] ===
+ nextLine[nextLine.length - 1 - suffix]
+ )
+ suffix++;
+ const typedEnd = nextLine.length - suffix;
+ const after = styleAt[prevLine.length - suffix] ?? null;
+ const chosen: Array<PieceStyle | null> = [];
+ // A new word takes the style after it, else the nearest of the line's styles whose font can draw it.
+ const typedWordStyle = (j: number): PieceStyle | null => {
+ let before: PieceStyle | null = null;
+ for (let k = j - 1; k >= 0 && !before; k--)
+ if (!/\s/.test(nextLine[k])) before = chosen[k];
+ const word = /^\S*/.exec(nextLine.slice(j))?.[0] ?? "";
+ const candidates = [
+ ...new Set([after, before, chosen[j - 1] ?? null, ...styleAt]),
+ ].filter((style): style is PieceStyle => style !== null);
+ return (
+ (covers &&
+ word &&
+ candidates.find((style) => covers(style.font, word))) ||
+ candidates[0] ||
+ null
+ );
+ };
+ for (let j = 0; j < nextLine.length; j++) {
+ if (j < prefix) chosen.push(styleAt[j]);
+ else if (j >= typedEnd)
+ chosen.push(styleAt[j - nextLine.length + prevLine.length]);
+ else if (j > 0 && !/\s/.test(nextLine[j - 1])) chosen.push(chosen[j - 1]);
+ else chosen.push(typedWordStyle(j));
+ }
+ const spans: FontSpan[] = [];
+ let lastStyle: PieceStyle | null = null;
+ for (let j = 0; j < chosen.length; j++) {
+ const style = chosen[j];
+ const last = spans[spans.length - 1];
+ if (last && (!style || style === lastStyle)) {
+ last.end = j + 1;
+ continue;
+ }
+ const font = style?.font ?? 0;
+ spans.push({
+ end: j + 1,
+ fontPtr: font,
+ fallbackFamily: fallbackFamilyFor(`pdf:${font}:${baseFontName(m, font)}`),
+ ...(style?.fill ? { fill: style.fill } : {}),
+ });
+ lastStyle = style;
+ }
+ return spans.length > 1 ? spans : undefined;
+}
+
+// /BaseFont keeps the style suffix ("LiberationSans-Bold") that the name table's family drops.
+function baseFontName(m: WrappedPdfiumModule, fontPtr: number): string {
+ if (!fontPtr) return "";
+ const len = m.FPDFFont_GetBaseFontName(fontPtr, 0, 0);
+ if (len <= 1) return "";
+ const buf = scratchPtr(m, SCRATCH.partialFontName, len);
+ m.FPDFFont_GetBaseFontName(fontPtr, buf, len);
+ return m.pdfium.UTF8ToString(buf).replace(/^[A-Z]{6}\+/, "");
+}
+
+/** True when a plan's in-place "modify" op would SetText whitespace its own piece's font cannot encode, which paints „ on a subset with no space glyph. */
+export function planModifiesUndrawableWhitespace(
+ m: WrappedPdfiumModule,
+ plan: PartialEditPlan,
+ pagePtr: number,
+ docPtr: number,
+): boolean {
+ return plan.ops.some((op) => {
+ if (op.type !== "modify" || !op.text || !/\s/.test(op.text)) return false;
+ if (op.subRunIdx === undefined) return true;
+ const font = objFontPtr(m, plan.prevMergedFromPtrs[op.subRunIdx]);
+ const whitespace = [...new Set(op.text.match(/\s/g))].join("");
+ return !charcodesResolveFully(m, font, whitespace, pagePtr, docPtr);
+ });
+}
+
+/**
+ * `plan` with each line that {@link planModifiesUndrawableWhitespace} holds for left to be redrawn whole.
+ * Settled before the edit is applied, because its undo puts back the objects the plan says were taken off.
+ */
+export function redrawingUndrawableWhitespace(
+ m: WrappedPdfiumModule,
+ plan: ParagraphEditPlan,
+ pagePtr: number,
+ docPtr: number,
+): ParagraphEditPlan {
+ return {
+ ...plan,
+ perSlot: plan.perSlot.map((entry) =>
+ entry.plan &&
+ planModifiesUndrawableWhitespace(m, entry.plan, pagePtr, docPtr)
+ ? { ...entry, plan: null }
+ : entry,
+ ),
+ };
}
/** Read a text object's own font handle (0 when unavailable). */
-function objFontPtr(
- m: import("@embedpdf/pdfium").WrappedPdfiumModule,
- ptr: number,
-): number {
+function objFontPtr(m: WrappedPdfiumModule, ptr: number): number {
const fontMod = m as unknown as FontReadingModule;
if (!ptr || !fontMod.FPDFTextObj_GetFont) return 0;
try {
@@ -1080,7 +1965,7 @@ function objFontPtr(
* Returns 0 when nothing matches, leaving the caller on its normal fallback.
*/
export function siblingFontPtrForText(
- m: import("@embedpdf/pdfium").WrappedPdfiumModule,
+ m: WrappedPdfiumModule,
slots: ParagraphLineSlot[],
selfIndex: number,
fontId: string,
@@ -1103,7 +1988,7 @@ export function siblingFontPtrForText(
}
export function bestFontPtrForText(
- m: import("@embedpdf/pdfium").WrappedPdfiumModule,
+ m: WrappedPdfiumModule,
ptrs: number[],
texts: string[],
targetText: string,
@@ -1171,6 +2056,7 @@ export function planParagraphEdit(
run: TextRun,
prevText: string,
nextText: string,
+ redrawWhole: ReadonlySet<number> = new Set(),
): ParagraphEditPlan | null {
const slots = run.paragraphLineSlots;
if (slots.length < 2) return null;
@@ -1218,11 +2104,7 @@ export function planParagraphEdit(
const hit = slots[hitSlot];
nextLines[hitSlot] = nextText.slice(hit.startChar, hit.endChar + delta);
- const perSlot: Array<{
- slotIdx: number;
- plan: PartialEditPlan | null;
- nextLine: string;
- }> = [];
+ const perSlot: ParagraphEditPlan["perSlot"] = [];
const prevLine = prevLines[hitSlot];
const nextLine = nextLines[hitSlot];
@@ -1230,17 +2112,20 @@ export function planParagraphEdit(
// A slot with no sub-run objects can't be partially edited (e.g. an empty
// line the user just typed the first character into).
if (hit.mergedFromPtrs.length === 0) {
- perSlot.push({ slotIdx: hitSlot, plan: null, nextLine });
+ perSlot.push({ slotIdx: hitSlot, plan: null, prevLine, nextLine });
} else {
// Build a synthetic mini-TextRun view of the slot so the existing
// planPartialEdit / applyPartialEditPlan code can operate on it.
const slotView = makeSlotView(run, hit, prevLine);
- let plan = planPartialEdit(slotView, prevLine, nextLine);
- // An in-place "modify" op re-SetTexts a sub-run's surviving chars.
- if (plan && planModifiesWhitespace(plan)) plan = null;
+ const plan = planPartialEdit(slotView, prevLine, nextLine, redrawWhole);
// Per-line LCS couldn't model the change - re-emit just this line
// rather than failing the whole paragraph to the overlay re-emit.
- perSlot.push({ slotIdx: hitSlot, plan: plan ?? null, nextLine });
+ perSlot.push({
+ slotIdx: hitSlot,
+ plan: plan ?? null,
+ prevLine,
+ nextLine,
+ });
}
return {
@@ -1273,11 +2158,12 @@ export function applyParagraphEditPlan(
);
const planBySlot = new Map<
number,
- { plan: PartialEditPlan | null; nextLine: string }
+ { plan: PartialEditPlan | null; prevLine: string; nextLine: string }
>();
for (const entry of paraPlan.perSlot) {
planBySlot.set(entry.slotIdx, {
plan: entry.plan,
+ prevLine: entry.prevLine,
nextLine: entry.nextLine,
});
}
@@ -1320,6 +2206,14 @@ export function applyParagraphEditPlan(
// in Helvetica while the paragraph around it keeps the document's own
// face. Its SIBLING lines carry exactly the face it should inherit.
siblingFontPtrForText(m, newSlots, i, slot.fontId, lineText);
+ const fontSpans = sourceFontSpans(
+ m,
+ slot,
+ planEntry.prevLine,
+ lineText,
+ (font, text) =>
+ charcodesResolveFully(m, font, text, page.pagePtr, doc.docPtr),
+ );
for (const ptr of slot.mergedFromPtrs) {
if (!ptr) continue;
try {
@@ -1346,6 +2240,7 @@ export function applyParagraphEditPlan(
originalFontSubset: slot.fontSubset,
charSpacingPt: run.charSpacingPt,
fallbackFamily,
+ fontSpans,
});
const built = buildSlotMerged(m, ptrs, lineText, leftX, emittedTexts);
slot.mergedFromPtrs = built.ptrs;
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/commands/pushRunsBelow.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/commands/pushRunsBelow.test.ts
new file mode 100644
index 0000000000..15d0a84923
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/commands/pushRunsBelow.test.ts
@@ -0,0 +1,260 @@
+import { describe, expect, it } from "vitest";
+import {
+ runsPulledBack,
+ runsPushedBelow,
+ setPushRecords,
+} from "@editor/tools/pdfTextEditor/commands/pushRunsBelow";
+import type { Page } from "@editor/tools/pdfTextEditor/model/Page";
+import type { TextRun } from "@editor/tools/pdfTextEditor/model/TextRun";
+
+function run(id: string, x: number, y: number, width: number, height = 12) {
+ return {
+ id,
+ text: "x",
+ bounds: { x, y, width, height },
+ matrix: { a: 1, b: 0, c: 0, d: 1, e: x, f: y },
+ fontSize: 12,
+ locked: false,
+ containerPtr: 0,
+ renderMode: 0,
+ scanEdit: null,
+ } as unknown as TextRun;
+}
+
+function page(runs: TextRun[], cellRuns: (string | null)[][] = []): Page {
+ return {
+ runs,
+ findRun: (id: string) => runs.find((r) => r.id === id),
+ tables: cellRuns.length
+ ? [
+ {
+ cellRuns,
+ cellExtraRuns: cellRuns.map((row) => row.map(() => null)),
+ },
+ ]
+ : [],
+ display: { cropBottom: 0 },
+ } as unknown as Page;
+}
+
+// The edited run grew from bottom 500 down to 470: two 15pt lines.
+const edited = () => run("edited", 50, 470, 300, 45);
+
+describe("runsPushedBelow", () => {
+ it("moves the line the new lines land on, and the one that then lands on", () => {
+ const next = run("next", 50, 484, 300);
+ const after = run("after", 50, 468, 300);
+ expect(
+ runsPushedBelow(page([edited(), next, after]), edited(), 500),
+ ).toEqual({
+ runIds: ["next", "after"],
+ dy: -30,
+ });
+ });
+
+ it("stops at a gap wide enough to take the added lines", () => {
+ const next = run("next", 50, 484, 300);
+ const far = run("far", 50, 300, 300);
+ expect(
+ runsPushedBelow(page([edited(), next, far]), edited(), 500).runIds,
+ ).toEqual(["next"]);
+ });
+
+ it("moves a line the new lines stop only just short of", () => {
+ // The edited run's new bottom is 470; a line topping out at 469.5 clears it by less than a tenth of an em.
+ const justBelow = run("just below", 50, 457.5, 300);
+ expect(
+ runsPushedBelow(page([edited(), justBelow]), edited(), 500).runIds,
+ ).toEqual(["just below"]);
+ });
+
+ it("leaves a line the new lines clear by a tenth of an em or more", () => {
+ const clear = run("clear", 50, 456, 300);
+ expect(
+ runsPushedBelow(page([edited(), clear]), edited(), 500).runIds,
+ ).toEqual([]);
+ });
+
+ it("leaves text in another column alone", () => {
+ const beside = run("beside", 400, 484, 150);
+ expect(
+ runsPushedBelow(page([edited(), beside]), edited(), 500).runIds,
+ ).toEqual([]);
+ });
+
+ it("leaves the column beside the edited text alone, down to a full-width line under both", () => {
+ const leftLine = run("left line", 50, 484, 300);
+ const rightLines = [
+ run("right 1", 400, 500, 200),
+ run("right 2", 400, 484, 200),
+ run("right 3", 400, 440, 200),
+ ];
+ const footnote = run("footnote", 50, 468, 600);
+ expect(
+ runsPushedBelow(
+ page([edited(), leftLine, ...rightLines, footnote]),
+ edited(),
+ 500,
+ ).runIds,
+ ).toEqual(["left line", "footnote", "right 3"]);
+ });
+
+ it("takes a line outside the edited width that a moved line comes down on", () => {
+ const wide = run("wide", 50, 484, 400);
+ const rightAligned = run("right aligned", 380, 466, 200);
+ expect(
+ runsPushedBelow(page([edited(), wide, rightAligned]), edited(), 500)
+ .runIds,
+ ).toEqual(["wide", "right aligned"]);
+ });
+
+ it("takes a line a moved line would pass right over", () => {
+ const wide = run("wide", 50, 484, 600);
+ const passed = run("passed over", 400, 468, 200);
+ expect(
+ runsPushedBelow(page([edited(), wide, passed]), edited(), 500).runIds,
+ ).toEqual(["wide", "passed over"]);
+ });
+
+ it("takes a piece drawn separately among the lines of a moved paragraph", () => {
+ const paragraph = run("paragraph", 50, 400, 500, 96);
+ const piece = run("piece", 420, 430, 100);
+ expect(
+ runsPushedBelow(page([edited(), paragraph, piece]), edited(), 500).runIds,
+ ).toEqual(["paragraph", "piece"]);
+ });
+
+ // The overlay draws a line's box a line height tall and a descender deeper
+ // than its ink, so ink that clears by under a point still puts the moved
+ // line's box over the one below, and the box on top takes the clicks.
+ it("takes a line whose box a moved line's box would come down on", () => {
+ const next = run("next", 50, 484, 300);
+ const list = run("list", 70, 440.3, 200);
+ expect(
+ runsPushedBelow(page([edited(), next, list]), edited(), 500).runIds,
+ ).toEqual(["next", "list"]);
+ });
+
+ it("leaves a line beside a moved line where it is when nothing comes down on it", () => {
+ const narrow = run("narrow", 50, 484, 300);
+ const beside = run("beside", 400, 484, 200);
+ expect(
+ runsPushedBelow(page([edited(), narrow, beside]), edited(), 500).runIds,
+ ).toEqual(["narrow"]);
+ });
+
+ it("moves nothing when a line a moved line comes down on cannot move", () => {
+ const wide = run("wide", 50, 484, 400);
+ const rightAligned = run("right aligned", 380, 466, 200);
+ rightAligned.locked = true;
+ expect(
+ runsPushedBelow(page([edited(), wide, rightAligned]), edited(), 500)
+ .runIds,
+ ).toEqual([]);
+ });
+
+ it("moves nothing when a table cell is in the way", () => {
+ const next = run("next", 50, 484, 300);
+ expect(
+ runsPushedBelow(page([edited(), next], [["next"]]), edited(), 500).runIds,
+ ).toEqual([]);
+ });
+
+ it("moves nothing when a line would be pushed off the page", () => {
+ const next = run("next", 50, 20, 300, 470);
+ expect(
+ runsPushedBelow(page([edited(), next]), edited(), 500).runIds,
+ ).toEqual([]);
+ });
+
+ it("does nothing when the run did not grow downwards", () => {
+ const next = run("next", 50, 484, 300);
+ const shrunk = run("edited", 50, 500, 300);
+ expect(runsPushedBelow(page([shrunk, next]), shrunk, 500).runIds).toEqual(
+ [],
+ );
+ });
+});
+
+describe("runsPulledBack", () => {
+ // Two 15pt lines were added to a one-line run: the first moved `near`, the second moved `near` again and reached `far`.
+ function pushedTwice() {
+ const runs = [
+ edited(),
+ run("near", 50, 454, 300),
+ run("far", 50, 420, 300),
+ ];
+ setPushRecords(runs[0], [
+ { lineCount: 2, linesAdded: 1, runIds: ["near"], dy: -15 },
+ { lineCount: 3, linesAdded: 1, runIds: ["near", "far"], dy: -15 },
+ ]);
+ return { page: page(runs), edited: runs[0] };
+ }
+
+ it("takes back only what the line that went had pushed", () => {
+ const { page: p, edited: e } = pushedTwice();
+ expect(runsPulledBack(p, e, 2)).toEqual({
+ moves: [
+ { runId: "near", dy: 15 },
+ { runId: "far", dy: 15 },
+ ],
+ records: [{ lineCount: 2, linesAdded: 1, runIds: ["near"], dy: -15 }],
+ });
+ });
+
+ it("takes everything back when every added line goes", () => {
+ const { page: p, edited: e } = pushedTwice();
+ expect(runsPulledBack(p, e, 1)).toEqual({
+ moves: [
+ { runId: "near", dy: 30 },
+ { runId: "far", dy: 15 },
+ ],
+ records: [],
+ });
+ });
+
+ it("takes nothing back while the lines that pushed are all still there", () => {
+ const { page: p, edited: e } = pushedTwice();
+ expect(runsPulledBack(p, e, 3).moves).toEqual([]);
+ expect(runsPulledBack(p, e, 5).records).toHaveLength(2);
+ });
+
+ it("takes back a share of a push made for several lines at once", () => {
+ const runs = [edited(), run("near", 50, 454, 300)];
+ setPushRecords(runs[0], [
+ { lineCount: 4, linesAdded: 3, runIds: ["near"], dy: -45 },
+ ]);
+ const { moves, records } = runsPulledBack(page(runs), runs[0], 3);
+ expect(moves).toHaveLength(1);
+ expect(moves[0].dy).toBeCloseTo(15, 6);
+ expect(records).toHaveLength(1);
+ expect(records[0]).toMatchObject({ lineCount: 3, linesAdded: 2 });
+ expect(records[0].dy).toBeCloseTo(-30, 6);
+ });
+
+ it("leaves a run that can no longer move", () => {
+ const { page: p, edited: e } = pushedTwice();
+ p.findRun("near")!.locked = true;
+ expect(runsPulledBack(p, e, 1).moves).toEqual([{ runId: "far", dy: 15 }]);
+ });
+});
+
+describe("invisible text", () => {
+ const invisible = (hiddenText: boolean) => {
+ const r = run("invisible", 50, 484, 300);
+ Object.assign(r, { renderMode: 3, hiddenText });
+ return r;
+ };
+
+ it("moves invisible text with no picture behind it", () => {
+ expect(
+ runsPushedBelow(page([edited(), invisible(true)]), edited(), 500).runIds,
+ ).toEqual(["invisible"]);
+ });
+
+ it("leaves an OCR layer over a scan where it is", () => {
+ expect(
+ runsPushedBelow(page([edited(), invisible(false)]), edited(), 500).runIds,
+ ).toEqual([]);
+ });
+});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/commands/pushRunsBelow.ts b/frontend/src/editor/core/tools/pdfTextEditor/commands/pushRunsBelow.ts
new file mode 100644
index 0000000000..7d7c08af19
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/commands/pushRunsBelow.ts
@@ -0,0 +1,353 @@
+import type { Page } from "@editor/tools/pdfTextEditor/model/Page";
+import type { TextRun } from "@editor/tools/pdfTextEditor/model/TextRun";
+import type { PageRect } from "@editor/tools/pdfTextEditor/types";
+import { rotationFromMatrix } from "@editor/tools/pdfTextEditor/commands/editTextHelpers";
+import { isScanRun } from "@editor/tools/pdfTextEditor/commands/scanTextEdit";
+
+// Lines set tighter than their own boxes already overlap the line above a little; that much is the document's layout, not a collision.
+const TOUCH_TOLERANCE_EM = 0.25;
+const SLACK_PT = 0.5;
+const BOX_ESTIMATE_EM = 0.5;
+// The room a line keeps under it, where the document gave it at least that: lines that only just clear each other read as touching.
+const CLEARANCE_EM = 0.1;
+const AMONG_LINES_SHARE = 0.5;
+
+const top = (run: TextRun) => run.bounds.y + run.bounds.height;
+
+function overlapsSpan(run: TextRun, left: number, right: number): boolean {
+ return run.bounds.x < right && run.bounds.x + run.bounds.width > left;
+}
+
+function inTable(page: Page, runId: string): boolean {
+ return page.tables.some(
+ (table) =>
+ table.cellRuns.some((row) => row.includes(runId)) ||
+ table.cellExtraRuns.some((row) =>
+ row.some((extra) => extra?.includes(runId)),
+ ),
+ );
+}
+
+function canMove(page: Page, run: TextRun): boolean {
+ return (
+ !run.locked &&
+ !rotationFromMatrix(run.matrix) &&
+ !isScanRun(run) &&
+ !inTable(page, run.id)
+ );
+}
+
+/**
+ * The runs below `edited` that its growth from `oldBottom` down to its current
+ * bottom lands on, together with every run those then land on, all to move down
+ * by the same amount. A run counts as landed on once less than a tenth of an em
+ * is left above it, unless the document set it closer than that to begin
+ * with. Directly under the edited text only runs sharing its
+ * width are taken, so the column beside it stays put; a moved line wider than
+ * that takes whatever it would itself come down on, such as a right-aligned
+ * line or the text under a heading that spans two columns. Empty when nothing
+ * would be covered, and also when any run in that chain cannot move or would
+ * leave the page: moving only part of a chain swaps one overlap for another.
+ *
+ * `addedHeight` is the height of the lines the edit added. The runs move by
+ * that, so the distance from the last line to the text below stays what the
+ * document had, unless the box grew by something else altogether.
+ */
+export function runsPushedBelow(
+ page: Page,
+ edited: TextRun,
+ oldBottom: number,
+ addedHeight = 0,
+): { runIds: string[]; dy: number } {
+ const grown = oldBottom - edited.bounds.y;
+ const none = { runIds: [], dy: 0 };
+ if (grown <= 0.5 || !canMove(page, edited) || inTable(page, edited.id))
+ return none;
+ // The box of an edited run is an estimate where the document's was measured, so the first edit shifts its bottom by a little more or less than the lines it added.
+ const drop =
+ Math.abs(grown - addedHeight) <= edited.fontSize * BOX_ESTIMATE_EM
+ ? addedHeight
+ : grown;
+ const tolerance = edited.fontSize * TOUCH_TOLERANCE_EM;
+ const left = edited.bounds.x;
+ const right = edited.bounds.x + edited.bounds.width;
+ const clearance = edited.fontSize * CLEARANCE_EM;
+ // The lowest bottom of what has moved so far, and where that bottom was before it moved.
+ let limit = edited.bounds.y;
+ let limitBefore = oldBottom;
+ const below = page.runs
+ .filter((r) => r !== edited && top(r) <= oldBottom + tolerance)
+ .sort((a, b) => top(b) - top(a));
+ const pushed: string[] = [];
+ for (const run of below) {
+ if (!overlapsSpan(run, left, right)) continue;
+ // Negative where the two already overlapped: that much is the document's layout, and stays.
+ const gapBefore = limitBefore - top(run);
+ if (top(run) <= limit - Math.min(clearance, gapBefore) + SLACK_PT) break;
+ if (!canMove(page, run) || run.bounds.y - drop < page.display.cropBottom)
+ return none;
+ pushed.push(run.id);
+ if (run.bounds.y - drop < limit) {
+ limit = run.bounds.y - drop;
+ limitBefore = run.bounds.y;
+ }
+ }
+ const runIds = withRunsLandedOn(page, edited, pushed, drop);
+ return runIds ? { runIds, dy: -drop } : none;
+}
+
+// How much of their height two boxes share, where they share any width.
+function overlapDepth(a: PageRect, b: PageRect): number {
+ if (a.x >= b.x + b.width - SLACK_PT || a.x + a.width <= b.x + SLACK_PT)
+ return 0;
+ return Math.max(
+ 0,
+ Math.min(a.y + a.height, b.y + b.height) - Math.max(a.y, b.y),
+ );
+}
+
+function canMoveDown(page: Page, run: TextRun, drop: number): boolean {
+ return canMove(page, run) && !(run.bounds.y - drop < page.display.cropBottom);
+}
+
+// The overlay's line metrics, for fonts the page has not measured: CSS ascent and descent, and the line height it falls back to. Must stay in step with the flow box in TextRunOverlay.
+const BOX_ASCENT_EM = 0.95;
+const BOX_DESCENT_EM = 0.25;
+const BOX_LINE_HEIGHT_EM = 1.2;
+
+// Where the overlay draws `run`'s box: a line height per line from above the first baseline, a descender deeper than the last, and never less than its ink.
+function overlayBox(run: TextRun): PageRect {
+ const size = run.fontSize > 0 ? run.fontSize : 12;
+ const lineHeight =
+ run.paragraphLineHeight > 0
+ ? run.paragraphLineHeight
+ : size * BOX_LINE_HEIGHT_EM;
+ const metrics = (BOX_ASCENT_EM + BOX_DESCENT_EM) * size;
+ const boxTop =
+ run.matrix.f +
+ Math.max(0, (lineHeight - metrics) / 2) +
+ BOX_ASCENT_EM * size;
+ const boxBottom =
+ boxTop -
+ run.text.split(/\r?\n/).length * lineHeight -
+ BOX_DESCENT_EM * size;
+ const y = Math.min(run.bounds.y, boxBottom);
+ return {
+ x: run.bounds.x,
+ y,
+ width: run.bounds.width,
+ height: Math.max(top(run), boxTop) - y,
+ };
+}
+
+const lowered = (rect: PageRect, drop: number): PageRect => ({
+ ...rect,
+ y: rect.y - drop,
+ height: rect.height + drop,
+});
+
+// `pushed` plus every run outside the edited width that one of them comes down on, and so on down; null when one of those cannot move. A run only the moved run's overlay box comes down on, not its ink, is taken where it can move and left where it cannot.
+function withRunsLandedOn(
+ page: Page,
+ edited: TextRun,
+ pushed: string[],
+ drop: number,
+): string[] | null {
+ const moving = new Set(pushed);
+ const chain = page.runs.filter((r) => moving.has(r.id));
+ const unmoved = new UnmovedRuns(
+ page.runs.filter((r) => r.id !== edited.id && !moving.has(r.id)),
+ );
+ for (let i = 0; i < chain.length; i++) {
+ const run = chain[i];
+ // Everything the run passes over on its way down, not only where it stops: a drop of several lines can clear a line entirely.
+ const swept = lowered(run.bounds, drop);
+ const box = overlayBox(run);
+ const sweptBox = lowered(box, drop);
+ const landed: number[] = [];
+ unmoved.within(box, sweptBox, (other, order) => {
+ if (moving.has(other.id)) return true;
+ // Lines set tighter than their boxes already share a little height; only more than that is a collision.
+ const before = overlapDepth(run.bounds, other.bounds);
+ // A run mostly inside the moving one's box sits among its lines, such as a word the document drew separately, and goes with them.
+ const among = before > other.bounds.height * AMONG_LINES_SHARE;
+ // Written as "not clear" so a box with no measurable height counts as landed on.
+ const inkHit =
+ among || !(overlapDepth(swept, other.bounds) <= before + SLACK_PT);
+ if (!inkHit) {
+ const otherBox = unmoved.boxes[order];
+ const boxHit = !(
+ overlapDepth(sweptBox, otherBox) <=
+ overlapDepth(box, otherBox) + SLACK_PT
+ );
+ if (!boxHit || !canMoveDown(page, other, drop)) return false;
+ }
+ landed.push(order);
+ return true;
+ });
+ for (const order of landed.sort((a, b) => a - b)) {
+ const other = unmoved.runs[order];
+ if (moving.has(other.id)) continue;
+ if (!canMoveDown(page, other, drop)) return null;
+ moving.add(other.id);
+ chain.push(other);
+ }
+ }
+ const seeds = new Set(pushed);
+ return [...pushed, ...chain.map((r) => r.id).filter((id) => !seeds.has(id))];
+}
+
+// Slack on the band query: the exact test runs on every candidate, so a wider band only costs a few extra comparisons.
+const BAND_MARGIN_PT = 1;
+
+/**
+ * The runs not yet moving, in page order, indexed by height so a moving run
+ * only meets the runs level with what it sweeps. Every collision needs the
+ * two boxes to share some height, so nothing outside that band can be landed
+ * on. A run whose box cannot be ordered (a negative, infinite or missing
+ * height) is offered to every query instead.
+ */
+class UnmovedRuns {
+ readonly runs: readonly TextRun[];
+ /** Each run's overlay box, by its index in `runs`. */
+ readonly boxes: readonly PageRect[];
+ private readonly byBottom: number[];
+ private readonly next: Int32Array;
+ private readonly unordered: number[] = [];
+ private readonly tallest: number;
+
+ constructor(runs: readonly TextRun[]) {
+ this.runs = runs;
+ this.boxes = runs.map(overlayBox);
+ const ordered: number[] = [];
+ let tallest = 0;
+ const orderable = ({ y, height }: PageRect) =>
+ Number.isFinite(y) && Number.isFinite(height) && height >= 0;
+ runs.forEach((run, order) => {
+ const box = this.boxes[order];
+ if (orderable(run.bounds) && orderable(box)) {
+ ordered.push(order);
+ tallest = Math.max(tallest, box.height);
+ } else this.unordered.push(order);
+ });
+ this.byBottom = ordered.sort(
+ (a, b) => this.boxes[a].y - this.boxes[b].y || a - b,
+ );
+ this.tallest = tallest;
+ this.next = Int32Array.from(
+ { length: this.byBottom.length + 1 },
+ (_, i) => i,
+ );
+ }
+
+ /**
+ * Offers `visit` each run whose box can share height with `a` or `b`, by
+ * its index in `runs`. A run `visit` answers true for is not offered again.
+ */
+ within(
+ a: PageRect,
+ b: PageRect,
+ visit: (run: TextRun, order: number) => boolean,
+ ): void {
+ for (const order of this.unordered) visit(this.runs[order], order);
+ const edges = [a.y, a.y + a.height, b.y, b.y + b.height];
+ const low = Math.min(...edges) - this.tallest - BAND_MARGIN_PT;
+ const high = Math.max(...edges) + BAND_MARGIN_PT;
+ if (!(low <= high)) {
+ this.byBottom.forEach((order) => visit(this.runs[order], order));
+ return;
+ }
+ let lo = 0;
+ let hi = this.byBottom.length;
+ while (lo < hi) {
+ const mid = (lo + hi) >> 1;
+ if (this.boxes[this.byBottom[mid]].y < low) lo = mid + 1;
+ else hi = mid;
+ }
+ for (let i = this.live(lo); i < this.byBottom.length;) {
+ const order = this.byBottom[i];
+ if (this.boxes[order].y > high) break;
+ if (visit(this.runs[order], order)) this.next[i] = i + 1;
+ i = this.live(i + 1);
+ }
+ }
+
+ // The first slot at or after `i` still offered, skipping taken ones in amortised constant time.
+ private live(i: number): number {
+ let root = i;
+ while (this.next[root] !== root) root = this.next[root];
+ while (this.next[i] !== root) {
+ const after = this.next[i];
+ this.next[i] = root;
+ i = after;
+ }
+ return root;
+ }
+}
+
+/** One push: the runs an edit moved, how far, and the lines of the edited run it made room for. */
+export interface PushRecord {
+ /** How many lines the edited run had once this push was made. */
+ lineCount: number;
+ linesAdded: number;
+ runIds: readonly string[];
+ /** Negative: down the page. */
+ dy: number;
+}
+
+// The pushes each edited run still holds the runs below down with, oldest first, net of undo.
+const pushedBelow = new WeakMap<TextRun, readonly PushRecord[]>();
+
+export function pushRecords(edited: TextRun): readonly PushRecord[] {
+ return pushedBelow.get(edited) ?? [];
+}
+
+/** Replaces what `edited` is recorded as holding down; undo and redo put back the list they found. */
+export function setPushRecords(
+ edited: TextRun,
+ records: readonly PushRecord[],
+): void {
+ pushedBelow.set(edited, records);
+}
+
+/**
+ * What to let back up now `edited` is down to `lineCount` lines: every push
+ * made for a line it no longer has is taken back, the latest first, so the
+ * runs below end up exactly where that many lines put them the first time,
+ * whatever the line height has become since. A push made for several lines is
+ * taken back by the share of them that went. `records` is what is still held
+ * down afterwards.
+ *
+ * A run that can no longer move, such as one locked since, stays where it is
+ * and is no longer held to this run.
+ */
+export function runsPulledBack(
+ page: Page,
+ edited: TextRun,
+ lineCount: number,
+): { moves: Array<{ runId: string; dy: number }>; records: PushRecord[] } {
+ const records = [...pushRecords(edited)];
+ const rise = new Map<string, number>();
+ for (let last = records.at(-1); last; last = records.at(-1)) {
+ const gone = Math.min(last.linesAdded, last.lineCount - lineCount);
+ if (gone <= 0) break;
+ const share = gone / last.linesAdded;
+ for (const runId of last.runIds)
+ rise.set(runId, (rise.get(runId) ?? 0) - last.dy * share);
+ records.pop();
+ if (gone < last.linesAdded)
+ records.push({
+ ...last,
+ lineCount: last.lineCount - gone,
+ linesAdded: last.linesAdded - gone,
+ dy: last.dy * (1 - share),
+ });
+ }
+ const moves = [...rise]
+ .filter(([runId]) => {
+ const run = page.findRun(runId);
+ return run !== undefined && canMove(page, run);
+ })
+ .map(([runId, dy]) => ({ runId, dy }));
+ return { moves, records };
+}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/commands/pushRunsBelowScaling.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/commands/pushRunsBelowScaling.test.ts
new file mode 100644
index 0000000000..def2b0bdf3
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/commands/pushRunsBelowScaling.test.ts
@@ -0,0 +1,323 @@
+import { describe, expect, it } from "vitest";
+import { runsPushedBelow } from "@editor/tools/pdfTextEditor/commands/pushRunsBelow";
+import { rotationFromMatrix } from "@editor/tools/pdfTextEditor/commands/editTextHelpers";
+import type { Page } from "@editor/tools/pdfTextEditor/model/Page";
+import type { TextRun } from "@editor/tools/pdfTextEditor/model/TextRun";
+import type { PageRect } from "@editor/tools/pdfTextEditor/types";
+
+interface Bounds {
+ x: number;
+ y: number;
+ width: number;
+ height: number;
+}
+
+let fieldReads = 0;
+
+function run(
+ id: string,
+ bounds: Bounds,
+ extra: { locked?: boolean; b?: number; renderMode?: number } = {},
+): TextRun {
+ return {
+ get id() {
+ fieldReads++;
+ return id;
+ },
+ get bounds() {
+ fieldReads++;
+ return bounds;
+ },
+ text: "x",
+ matrix: { a: 1, b: extra.b ?? 0, c: 0, d: 1, e: bounds.x, f: bounds.y },
+ fontSize: 12,
+ locked: extra.locked ?? false,
+ containerPtr: 0,
+ renderMode: extra.renderMode ?? 0,
+ scanEdit: null,
+ } as unknown as TextRun;
+}
+
+function page(
+ runs: TextRun[],
+ cellRuns: string[][] = [],
+ cropBottom = 0,
+): Page {
+ return {
+ runs,
+ findRun: (id: string) => runs.find((r) => r.id === id),
+ tables: cellRuns.length
+ ? [
+ {
+ cellRuns,
+ cellExtraRuns: cellRuns.map((row) => row.map(() => null)),
+ },
+ ]
+ : [],
+ display: { cropBottom },
+ } as unknown as Page;
+}
+
+function referencePushedBelow(
+ page: Page,
+ edited: TextRun,
+ oldBottom: number,
+ addedHeight = 0,
+): { runIds: string[]; dy: number } {
+ const top = (r: TextRun) => r.bounds.y + r.bounds.height;
+ const inTable = (id: string) =>
+ page.tables.some(
+ (t) =>
+ t.cellRuns.some((row) => row.includes(id)) ||
+ t.cellExtraRuns.some((row) => row.some((e) => e?.includes(id))),
+ );
+ const canMove = (r: TextRun) =>
+ !r.locked &&
+ !rotationFromMatrix(r.matrix) &&
+ r.renderMode !== 3 &&
+ !inTable(r.id);
+ const depth = (a: PageRect, b: PageRect) =>
+ a.x >= b.x + b.width - 0.5 || a.x + a.width <= b.x + 0.5
+ ? 0
+ : Math.max(
+ 0,
+ Math.min(a.y + a.height, b.y + b.height) - Math.max(a.y, b.y),
+ );
+ const overlayBox = (r: TextRun): PageRect => {
+ const boxTop = r.matrix.f + 0.95 * r.fontSize;
+ const y = Math.min(r.bounds.y, boxTop - 1.45 * r.fontSize);
+ return {
+ x: r.bounds.x,
+ y,
+ width: r.bounds.width,
+ height: Math.max(top(r), boxTop) - y,
+ };
+ };
+ const grown = oldBottom - edited.bounds.y;
+ const none = { runIds: [], dy: 0 };
+ if (grown <= 0.5 || !canMove(edited) || inTable(edited.id)) return none;
+ const drop =
+ Math.abs(grown - addedHeight) <= edited.fontSize * 0.5
+ ? addedHeight
+ : grown;
+ const tolerance = edited.fontSize * 0.25;
+ const left = edited.bounds.x;
+ const right = edited.bounds.x + edited.bounds.width;
+ const clearance = edited.fontSize * 0.1;
+ let limit = edited.bounds.y;
+ let limitBefore = oldBottom;
+ const pushed: string[] = [];
+ for (const r of page.runs
+ .filter((r) => r !== edited && top(r) <= oldBottom + tolerance)
+ .sort((a, b) => top(b) - top(a))) {
+ if (!(r.bounds.x < right && r.bounds.x + r.bounds.width > left)) continue;
+ if (top(r) <= limit - Math.min(clearance, limitBefore - top(r)) + 0.5)
+ break;
+ if (!canMove(r) || r.bounds.y - drop < page.display.cropBottom) return none;
+ pushed.push(r.id);
+ if (r.bounds.y - drop < limit) {
+ limit = r.bounds.y - drop;
+ limitBefore = r.bounds.y;
+ }
+ }
+ const moving = new Set(pushed);
+ const chain = page.runs.filter((r) => moving.has(r.id));
+ for (let i = 0; i < chain.length; i++) {
+ const r = chain[i];
+ const swept = {
+ ...r.bounds,
+ y: r.bounds.y - drop,
+ height: r.bounds.height + drop,
+ };
+ for (const other of page.runs) {
+ if (other.id === edited.id || moving.has(other.id)) continue;
+ const before = depth(r.bounds, other.bounds);
+ const among = before > other.bounds.height * 0.5;
+ const inkHit = among || !(depth(swept, other.bounds) <= before + 0.5);
+ const movable =
+ canMove(other) && !(other.bounds.y - drop < page.display.cropBottom);
+ if (!inkHit) {
+ const box = overlayBox(r);
+ const otherBox = overlayBox(other);
+ const sweptBox = { ...box, y: box.y - drop, height: box.height + drop };
+ if (depth(sweptBox, otherBox) <= depth(box, otherBox) + 0.5 || !movable)
+ continue;
+ } else if (!movable) return none;
+ moving.add(other.id);
+ chain.push(other);
+ }
+ }
+ return {
+ runIds: [
+ ...pushed,
+ ...chain.map((r) => r.id).filter((id) => !pushed.includes(id)),
+ ],
+ dy: -drop,
+ };
+}
+
+function seeded(seed: number): () => number {
+ let state = seed;
+ return () => {
+ state = (state * 1664525 + 1013904223) >>> 0;
+ return state / 2 ** 32;
+ };
+}
+
+function randomLayout(seed: number) {
+ const random = seeded(seed);
+ const pick = <T>(items: T[]) => items[Math.floor(random() * items.length)];
+ const fontSize = pick([9, 12, 18]);
+ const edited = run(
+ "edited",
+ {
+ x: random() * 200,
+ y: 400 + random() * 100,
+ width: 40 + random() * 400,
+ height: fontSize * (1 + Math.floor(random() * 3)),
+ },
+ {},
+ );
+ (edited as { fontSize: number }).fontSize = fontSize;
+ const runs: TextRun[] = [edited];
+ const odd = () => {
+ const roll = random();
+ return roll < 0.02 ? -5 : roll < 0.03 ? 0 : roll < 0.035 ? NaN : null;
+ };
+ const extra = () => ({
+ locked: random() < 0.01,
+ b: random() < 0.01 ? 0.5 : 0,
+ renderMode: random() < 0.01 ? 3 : 0,
+ });
+ const id = (i: number) =>
+ random() < 0.03 ? `r${Math.floor(random() * i)}` : `r${i}`;
+ const pitch = fontSize * (0.8 + random() * 0.8);
+ const rows = 2 + Math.floor(random() * 25);
+ for (let row = 0; row < rows; row++) {
+ const y = edited.bounds.y - (row + 1) * pitch + (random() - 0.5) * 6;
+ for (let k = Math.floor(random() * 4); k >= 0; k--) {
+ const height = odd() ?? fontSize * (0.8 + random() * (row % 7 ? 0.5 : 3));
+ runs.push(
+ run(
+ id(runs.length),
+ { x: random() * 500, y, width: 5 + random() * 300, height },
+ extra(),
+ ),
+ );
+ }
+ }
+ for (let i = Math.floor(random() * 10); i > 0; i--)
+ runs.push(
+ run(
+ id(runs.length),
+ {
+ x: random() * 500,
+ y: random() * 520,
+ width: 5 + random() * 300,
+ height: odd() ?? 4 + random() * 30,
+ },
+ extra(),
+ ),
+ );
+ runs.sort(() => random() - 0.5);
+ const tabled = runs.filter(() => random() < 0.03).map((r) => r.id);
+ const oldBottom = edited.bounds.y + 5 + random() * 60;
+ const addedHeight = pick([0, oldBottom - edited.bounds.y, 15, 30]);
+ return {
+ page: page(runs, tabled.length ? [tabled] : [], pick([0, 0, 0, 0, 200])),
+ edited,
+ oldBottom,
+ addedHeight,
+ };
+}
+
+// Every column overlaps its neighbour by 10pt, so only the first column lies
+// under the edited line and the rest are found by landing on each other.
+function overlappingGrid(count: number): {
+ page: Page;
+ edited: TextRun;
+} {
+ const edited = run("edited", { x: 0, y: 99970, width: 40, height: 12 });
+ const runs = [edited];
+ for (let i = 0; i < count; i++)
+ runs.push(
+ run(`r${i}`, {
+ x: (i % 20) * 50,
+ y: 99984 - Math.floor(i / 20) * 14,
+ width: 60,
+ height: 12,
+ }),
+ );
+ return { page: page(runs), edited };
+}
+
+describe("runsPushedBelow planning", () => {
+ it("chooses exactly what checking every run against every moving run chooses", () => {
+ let moved = 0;
+ let landed = 0;
+ for (let seed = 1; seed <= 3000; seed++) {
+ const { page, edited, oldBottom, addedHeight } = randomLayout(seed);
+ const expected = referencePushedBelow(
+ page,
+ edited,
+ oldBottom,
+ addedHeight,
+ );
+ expect(
+ runsPushedBelow(page, edited, oldBottom, addedHeight),
+ `seed ${seed}`,
+ ).toEqual(expected);
+ if (expected.runIds.length > 1) moved++;
+ if (
+ expected.runIds.some(
+ (id) =>
+ !page.runs.some(
+ (r) =>
+ r.id === id &&
+ r.bounds.x < edited.bounds.x + edited.bounds.width &&
+ r.bounds.x + r.bounds.width > edited.bounds.x,
+ ),
+ )
+ )
+ landed++;
+ }
+ expect(moved).toBeGreaterThan(300);
+ expect(landed).toBeGreaterThan(200);
+ });
+
+ it("finds a grid by landing in the same order as checking every pair", () => {
+ const { page, edited } = overlappingGrid(2_000);
+ const expected = referencePushedBelow(page, edited, 100000, 30);
+ expect(expected.runIds).toHaveLength(2_000);
+ expect(runsPushedBelow(page, edited, 100000, 30)).toEqual(expected);
+ });
+
+ it("finds a grid of 10,000 runs by landing without comparing every pair", () => {
+ const count = 10_000;
+ const { page, edited } = overlappingGrid(count);
+ fieldReads = 0;
+ const planned = runsPushedBelow(page, edited, 100000, 30);
+ expect(new Set(planned.runIds).size).toBe(count);
+ expect(fieldReads).toBeLessThan(count * 400);
+ });
+
+ it("does not revisit a grid that is already moving as a whole", () => {
+ const count = 10_000;
+ const edited = run("edited", { x: 0, y: 7970, width: 1200, height: 12 });
+ const runs = [edited];
+ for (let i = 0; i < count; i++)
+ runs.push(
+ run(`r${i}`, {
+ x: (i % 20) * 50,
+ y: 7984 - Math.floor(i / 20) * 14,
+ width: 40,
+ height: 12,
+ }),
+ );
+ fieldReads = 0;
+ expect(runsPushedBelow(page(runs), edited, 8000, 30).runIds).toHaveLength(
+ count,
+ );
+ expect(fieldReads).toBeLessThan(count * 100);
+ });
+});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/commands/readOnlyText.ts b/frontend/src/editor/core/tools/pdfTextEditor/commands/readOnlyText.ts
new file mode 100644
index 0000000000..1549af5413
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/commands/readOnlyText.ts
@@ -0,0 +1,22 @@
+import i18n from "i18next";
+import { RolledBackError } from "@editor/tools/pdfTextEditor/commands/Command";
+
+export function unsafeRtlEditMessage(): string {
+ return i18n.t(
+ "pdfTextEditor.error.unsafeRtlEdit",
+ "Can't make this edit: the editor can't redraw this line's right-to-left text without changing it.",
+ );
+}
+
+/**
+ * Refuses a command that would redraw, rescale, restyle, regroup or copy the
+ * text of a line the reader could not read back faithfully. Call it before
+ * anything is changed: the refusal reports the document as intact. Moving,
+ * deleting and recolouring a run leave its drawn text alone and need no check.
+ */
+export function refuseRedrawOfReadOnlyText(run: {
+ textReadOnly: boolean;
+}): void {
+ if (run.textReadOnly)
+ throw new RolledBackError(new Error(unsafeRtlEditMessage()));
+}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/commands/resizeRun.ts b/frontend/src/editor/core/tools/pdfTextEditor/commands/resizeRun.ts
new file mode 100644
index 0000000000..216101cd54
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/commands/resizeRun.ts
@@ -0,0 +1,62 @@
+import type { Command } from "@editor/tools/pdfTextEditor/commands/Command";
+import { EditTextCommand } from "@editor/tools/pdfTextEditor/commands/EditTextCommand";
+import { ReflowWrapCommand } from "@editor/tools/pdfTextEditor/commands/ReflowWrapCommand";
+import {
+ RewrapTextCommand,
+ rewrapDrawnLines,
+} from "@editor/tools/pdfTextEditor/commands/rewrapDrawnLines";
+import { rotationFromMatrix } from "@editor/tools/pdfTextEditor/commands/editTextHelpers";
+import {
+ isScanRun,
+ wrapScanText,
+} from "@editor/tools/pdfTextEditor/commands/scanTextEdit";
+import type { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
+import type { TextRunSnapshot } from "@editor/tools/pdfTextEditor/types";
+
+/** Whether the user may set `run`'s width: never read-only text, and a scanned block only while upright, since its rewrap lays lines out along the page's axes. */
+export function canResizeRun(
+ run: Pick<TextRunSnapshot, "renderMode" | "textReadOnly" | "matrix">,
+): boolean {
+ if (run.textReadOnly) return false;
+ if (!isScanRun(run)) return true;
+ const turn = rotationFromMatrix(run.matrix);
+ return !turn || (Math.abs(turn.sin) < 1e-6 && turn.cos > 0);
+}
+
+/**
+ * The command that sets a run's width to `widthPt`, as its own undo step, or
+ * null when there is nothing to do. A scanned block is rewrapped by rewriting
+ * its text, since its words are pixels that only the scan redraw can move.
+ */
+export function resizeRunCommand(
+ doc: EditorDocument,
+ pageIndex: number,
+ runId: string,
+ widthPt: number,
+): Command | null {
+ const page = doc.page(pageIndex);
+ const run = page.findRun(runId);
+ if (!run || !canResizeRun(run)) return null;
+ const maxWidthPt = Math.max(1, widthPt);
+ if (isScanRun(run)) {
+ const wrapped = wrapScanText(doc, page, run, maxWidthPt);
+ if (wrapped === null || wrapped === run.text) return null;
+ return new EditTextCommand({
+ pageIndex,
+ runId,
+ nextText: wrapped,
+ explicit: true,
+ });
+ }
+ const rewrapped = rewrapDrawnLines(doc, page, run, maxWidthPt);
+ if (rewrapped !== null)
+ return rewrapped === run.text
+ ? null
+ : new RewrapTextCommand(pageIndex, runId, rewrapped, maxWidthPt);
+ return new ReflowWrapCommand({
+ pageIndex,
+ runId,
+ maxWidthPt,
+ explicit: true,
+ });
+}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/commands/rewrapDrawnLines.ts b/frontend/src/editor/core/tools/pdfTextEditor/commands/rewrapDrawnLines.ts
new file mode 100644
index 0000000000..ea0662cf73
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/commands/rewrapDrawnLines.ts
@@ -0,0 +1,224 @@
+import type { Command } from "@editor/tools/pdfTextEditor/commands/Command";
+import { EditTextCommand } from "@editor/tools/pdfTextEditor/commands/EditTextCommand";
+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 {
+ softStartsFor,
+ softStartsOf,
+} from "@editor/tools/pdfTextEditor/pdfium/lineBreaks";
+import { drawnText } from "@editor/tools/pdfTextEditor/pdfium/lineEndHyphen";
+
+interface Token {
+ start: number;
+ end: number;
+ left: number;
+ right: number;
+ line: number;
+}
+
+/**
+ * `run`'s text re-broken to `maxWidthPt` when its lines are drawn as whole
+ * line objects, which a reflow cannot split because it only moves objects;
+ * null when its objects are already per word or glyph, or its letters cannot
+ * be lined up with the page's. Only whitespace changes: soft breaks join, and
+ * a break replaces the space before a word that would pass the width.
+ */
+export function rewrapDrawnLines(
+ doc: EditorDocument,
+ page: Page,
+ run: TextRun,
+ maxWidthPt: number,
+): string | null {
+ const ptrs = new Set(
+ run.paragraphLeafPtrs.length > 0
+ ? run.paragraphLeafPtrs
+ : run.mergedFromPtrs.length > 0
+ ? run.mergedFromPtrs
+ : [run.pdfiumObjPtr],
+ );
+ page.flushGenerate(doc.module);
+ const boxes = letterBoxes(doc, page, ptrs);
+ if (!boxes) return null;
+ const tokens = tokensOf(run.text, boxes);
+ if (!tokens || !tokens.some((t, i) => tokens[i + 1]?.line === t.line))
+ return null;
+ if (boxes.objects >= tokens.length) return null;
+
+ const soft = softStartsOf(run);
+ const startX = Math.min(...tokens.map((t) => t.left));
+ const space = medianGap(tokens) ?? run.fontSize * 0.25;
+ const chars = [...run.text];
+ if (chars.length !== run.text.length) return null;
+ let cursor = startX;
+ for (let i = 0; i < tokens.length; i++) {
+ const token = tokens[i];
+ const prev = tokens[i - 1];
+ const width = token.right - token.left;
+ if (prev) {
+ const between = run.text.slice(prev.end, token.start);
+ const breaks = [...between].filter((ch) => ch === "\n").length;
+ const hard = breaks > 1 || (breaks === 1 && !soft[token.line]);
+ const gap =
+ prev.line === token.line ? Math.max(0, token.left - prev.right) : space;
+ if (hard) {
+ cursor = startX;
+ } else if (cursor + gap + width > startX + maxWidthPt + 0.5) {
+ setSeparator(chars, prev.end, token.start, "\n");
+ cursor = startX;
+ } else {
+ if (breaks === 1) setSeparator(chars, prev.end, token.start, " ");
+ cursor += gap;
+ }
+ }
+ cursor += width;
+ }
+ return chars.join("");
+}
+
+/** The resize of a run drawn as whole line objects: its text rewritten with new breaks, keeping the width the user chose. */
+export class RewrapTextCommand implements Command {
+ readonly type = "rewrap-text";
+ private readonly edit: EditTextCommand;
+ private prev: {
+ width: number | null;
+ softStarts: boolean[];
+ softStartsText: string;
+ } | null = null;
+
+ constructor(
+ private readonly pageIndex: number,
+ private readonly runId: string,
+ nextText: string,
+ private readonly widthPt: number,
+ ) {
+ this.edit = new EditTextCommand({
+ pageIndex,
+ runId,
+ nextText,
+ explicit: true,
+ });
+ }
+
+ apply(doc: EditorDocument): void {
+ const run = doc.page(this.pageIndex).findRun(this.runId);
+ if (!run) return;
+ const prevText = run.text;
+ const softStarts = softStartsOf(run);
+ this.prev = {
+ width: run.wrapWidthPt,
+ softStarts: run.paragraphSoftStarts,
+ softStartsText: run.paragraphSoftStartsText,
+ };
+ this.edit.apply(doc);
+ run.wrapWidthPt = this.widthPt;
+ run.paragraphSoftStarts = softStartsFor(run.text, prevText, softStarts);
+ run.paragraphSoftStartsText = run.text;
+ }
+
+ revert(doc: EditorDocument): void {
+ this.edit.revert(doc);
+ const run = doc.page(this.pageIndex).findRun(this.runId);
+ if (!run || !this.prev) return;
+ run.wrapWidthPt = this.prev.width;
+ run.paragraphSoftStarts = this.prev.softStarts;
+ run.paragraphSoftStartsText = this.prev.softStartsText;
+ }
+
+ describe(): string {
+ return this.edit.describe?.() ?? this.type;
+ }
+
+ coalesceKey(): string | null {
+ return null;
+ }
+}
+
+interface LetterBoxes {
+ letters: Array<{ char: string; left: number; right: number }>;
+ objects: number;
+}
+
+// The page's non-space letters drawn by `ptrs`, in the text page's order,
+// which is reading order for the lines of one paragraph.
+function letterBoxes(
+ doc: EditorDocument,
+ page: Page,
+ ptrs: ReadonlySet<number>,
+): LetterBoxes | null {
+ const m = doc.module;
+ const textPage = m.FPDFText_LoadPage(page.pagePtr);
+ const buf = m.pdfium.wasmExports.malloc(32);
+ const letters: LetterBoxes["letters"] = [];
+ const seen = new Set<number>();
+ try {
+ const count = m.FPDFText_CountChars(textPage);
+ for (let i = 0; i < count; i++) {
+ const object = m.FPDFText_GetTextObject(textPage, i);
+ if (!ptrs.has(object)) continue;
+ const code = m.FPDFText_GetUnicode(textPage, i);
+ if (code === 0 || /\s/.test(String.fromCodePoint(code))) continue;
+ if (!m.FPDFText_GetCharBox(textPage, i, buf, buf + 8, buf + 16, buf + 24))
+ return null;
+ seen.add(object);
+ letters.push({
+ char: drawnText(String.fromCodePoint(code)),
+ left: m.pdfium.getValue(buf, "double"),
+ right: m.pdfium.getValue(buf + 8, "double"),
+ });
+ }
+ } finally {
+ m.pdfium.wasmExports.free(buf);
+ m.FPDFText_ClosePage(textPage);
+ }
+ return letters.length > 0 ? { letters, objects: seen.size } : null;
+}
+
+function tokensOf(text: string, boxes: LetterBoxes): Token[] | null {
+ const tokens: Token[] = [];
+ let letter = 0;
+ let line = 0;
+ const re = /\S+|\n/g;
+ for (const match of text.matchAll(re)) {
+ if (match[0] === "\n") {
+ line++;
+ continue;
+ }
+ const first = boxes.letters[letter];
+ for (const ch of match[0])
+ if (boxes.letters[letter++]?.char !== ch) return null;
+ const last = boxes.letters[letter - 1];
+ if (!first || !last) return null;
+ tokens.push({
+ start: match.index,
+ end: match.index + match[0].length,
+ left: first.left,
+ right: last.right,
+ line,
+ });
+ }
+ return letter === boxes.letters.length ? tokens : null;
+}
+
+function medianGap(tokens: Token[]): number | null {
+ const gaps = tokens
+ .slice(1)
+ .map((t, i) => (t.line === tokens[i].line ? t.left - tokens[i].right : -1))
+ .filter((g) => g > 0)
+ .sort((a, b) => a - b);
+ return gaps.length > 0 ? gaps[Math.floor(gaps.length / 2)] : null;
+}
+
+function setSeparator(
+ chars: string[],
+ from: number,
+ to: number,
+ separator: " " | "\n",
+): void {
+ for (let i = from; i < to; i++)
+ if (chars[i] === "\n" || chars[i] === " ") {
+ chars[i] = separator;
+ for (let j = i + 1; j < to; j++) if (chars[j] === "\n") chars[j] = " ";
+ return;
+ }
+}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/commands/scanFit.ts b/frontend/src/editor/core/tools/pdfTextEditor/commands/scanFit.ts
index 7588c8ef8d..22f150fdf3 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/commands/scanFit.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/commands/scanFit.ts
@@ -166,6 +166,39 @@ function compare(
);
}
+/** Stroke width of `style` drawn over the span's text, over the scan's own: above 1 when the style is heavier than that span. */
+export function strokeRatioOn(
+ doc: EditorDocument,
+ page: Page,
+ span: SpanInk,
+ style: ScanStyle,
+): number {
+ const natural = spanOf(
+ doc,
+ page,
+ span.original,
+ style.family,
+ style.fontSize,
+ );
+ const stretch = natural
+ ? clampStretch(span.ink.body.width / natural)
+ : style.stretch;
+ return compare(
+ doc,
+ page,
+ span,
+ {
+ family: style.family,
+ size: style.fontSize,
+ stretch,
+ weight: style.weight,
+ hollow: style.hollow,
+ },
+ style.softness,
+ true,
+ ).weight;
+}
+
// Render pixels per scanned pixel: an upscaled low-res scan is soft however sharp its steps look, so this floors the softness.
function scanPixelSpan(
doc: EditorDocument,
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/commands/scanLayout.ts b/frontend/src/editor/core/tools/pdfTextEditor/commands/scanLayout.ts
index 294ba88a6f..79f12ea09d 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/commands/scanLayout.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/commands/scanLayout.ts
@@ -35,6 +35,8 @@ export interface LayoutInput {
) => number;
/** Redraw every word as text (a restyle), instead of keeping the scan. */
redraw: boolean;
+ /** Text already drawn on a line that is not part of this block, which typed text must not land on. */
+ obstacles?: Array<{ line: number; x: number; right: number }>;
}
export interface PlacedWord {
@@ -167,10 +169,14 @@ export function layoutScanEdit(input: LayoutInput): Layout {
// A line starts where it always did, so deleting its first word pulls
// the rest left rather than leaving a hole.
const scannedLead = anchor && anchor.line === line ? (anchor.lead ?? 0) : 0;
- const x =
- (pen === null ? lineStart(line) : pen() + gap(prev, anchor)) +
- Math.max(0, pending.lead - scannedLead) * input.space;
const text = pending.text;
+ const width = input.textWidth(text, anchor, dels);
+ const x = clearOfObstacles(
+ line,
+ (pen === null ? lineStart(line) : pen() + gap(prev, anchor)) +
+ Math.max(0, pending.lead - scannedLead) * input.space,
+ width,
+ );
layout.typed.push({
text,
x,
@@ -181,7 +187,7 @@ export function layoutScanEdit(input: LayoutInput): Layout {
!!anchor && anchor.line === line && Math.abs(x - anchor.x) < 0.5,
replaced: dels,
});
- const end = x + input.textWidth(text, anchor, dels);
+ const end = x + width;
pen = () => end;
prev = anchor;
lastKept = null;
@@ -189,6 +195,14 @@ export function layoutScanEdit(input: LayoutInput): Layout {
pending = null;
};
+ const clearOfObstacles = (line: number, x: number, width: number) => {
+ let at = x;
+ for (const o of [...(input.obstacles ?? [])].sort((a, b) => a.x - b.x))
+ if (o.line === line && o.right > at && o.x < at + width)
+ at = o.right + input.space;
+ return at;
+ };
+
const flowStart = (w: LayoutWord, line: number): number => {
if (pen === null) return lineStart(line);
if (lastKept && besideInScan(lastKept.word, w))
@@ -269,6 +283,45 @@ export function rewrapLines(
return chars.join("");
}
+/** `text` with the breaks `soft` flags (one flag per line) pulled up while the line above still `fits`, swapping only spaces and line breaks so offsets hold. */
+export function joinSoftLines(
+ text: string,
+ soft: readonly boolean[],
+ fits: (line: string) => boolean,
+): string {
+ const chars = [...text];
+ if (chars.length !== text.length) return text;
+ const softAt = new Set<number>();
+ let line = 0;
+ chars.forEach((ch, i) => {
+ if (ch === "\n" && soft[++line]) softAt.add(i);
+ });
+ let start = 0;
+ while (start < chars.length) {
+ let end = chars.indexOf("\n", start);
+ if (end < 0) end = chars.length;
+ while (softAt.has(end)) {
+ const nextEnd = chars.indexOf("\n", end + 1);
+ const lineEnd = nextEnd < 0 ? chars.length : nextEnd;
+ let wordEnd = end + 1;
+ while (wordEnd < lineEnd && chars[wordEnd] === " ") wordEnd++;
+ if (wordEnd === lineEnd) break;
+ while (wordEnd < lineEnd && chars[wordEnd] !== " ") wordEnd++;
+ const joined = chars.slice(start, wordEnd).join("").replaceAll("\n", " ");
+ if (!fits(joined.trim())) break;
+ chars[end] = " ";
+ softAt.delete(end);
+ if (chars.slice(wordEnd, lineEnd).some((ch) => ch !== " ")) {
+ chars[wordEnd] = "\n";
+ softAt.add(wordEnd);
+ end = wordEnd;
+ } else end = lineEnd;
+ }
+ start = end + 1;
+ }
+ return chars.join("");
+}
+
// The last space on [start, end) with a word on both sides of it.
function lastBreak(chars: string[], start: number, end: number): number {
let at = end - 1;
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/commands/scanPaint.ts b/frontend/src/editor/core/tools/pdfTextEditor/commands/scanPaint.ts
index e7e02c4ea9..2e3020691c 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/commands/scanPaint.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/commands/scanPaint.ts
@@ -79,6 +79,17 @@ export interface Span {
right: number;
}
+/** Where a word's letters end in its box: OCR may box a word with its trailing space, and the letters take their share of it. */
+export function lettersRight(word: {
+ text: string;
+ x: number;
+ right: number;
+}): number {
+ const letters = word.text.trimEnd().length;
+ if (letters === 0 || letters === word.text.length) return word.right;
+ return word.x + ((word.right - word.x) * letters) / word.text.length;
+}
+
export function invisibleText(
canvas: Canvas,
text: string,
@@ -88,6 +99,10 @@ export function invisibleText(
font: SearchableFont,
): number[] {
const m = canvas.doc.module;
+ const letterSpan = {
+ left: span.left,
+ right: lettersRight({ text, x: span.left, right: span.right }),
+ };
const ptrs = emitTextLine({
doc: canvas.doc,
page: canvas.page,
@@ -100,9 +115,11 @@ export function invisibleText(
fallbackFamily: font.family,
renderMode: RENDER_MODE_INVISIBLE,
tags: uniformTags(canvas.tagMarks),
+ // A word keeps its trailing space, as OCR wrote it: the gap alone is too narrow to read back as one.
+ oneObject: !/\s/.test(text.trimEnd()),
});
opaqueStroke(m, ptrs);
- scaleToSpan(m, ptrs, () => span);
+ scaleToSpan(m, ptrs, () => letterSpan);
return ptrs;
}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/commands/scanStyle.ts b/frontend/src/editor/core/tools/pdfTextEditor/commands/scanStyle.ts
index b42ab0100f..050284faeb 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/commands/scanStyle.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/commands/scanStyle.ts
@@ -15,6 +15,7 @@ import {
emitTextLine,
measureObjSpanPt,
removeAndDestroyObject,
+ withoutDroppedChars,
} from "@editor/tools/pdfTextEditor/commands/editTextHelpers";
import { transformObject } from "@editor/tools/pdfTextEditor/util/objectTransform";
import { advanceWidth } from "@editor/tools/pdfTextEditor/util/fontMetrics";
@@ -55,18 +56,20 @@ export function spanOf(
size: number,
): number {
const sheet = doc.scratchPageFor(page);
- const ptrs = emitTextLine({
- doc: sheet.doc,
- page: sheet.page,
- text,
- x: 0,
- y: 0,
- fontSize: size,
- fill: BLACK,
- originalFontPtr: 0,
- fallbackFamily: family,
- tags: uniformTags([]),
- });
+ const ptrs = withoutDroppedChars(() =>
+ emitTextLine({
+ doc: sheet.doc,
+ page: sheet.page,
+ text,
+ x: 0,
+ y: 0,
+ fontSize: size,
+ fill: BLACK,
+ originalFontPtr: 0,
+ fallbackFamily: family,
+ tags: uniformTags([]),
+ }),
+ );
const span = measureObjSpanPt(doc.module, ptrs);
for (const p of ptrs)
removeAndDestroyObject(doc.module, sheet.page.pagePtr, p);
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/commands/scanTextEdit.ts b/frontend/src/editor/core/tools/pdfTextEditor/commands/scanTextEdit.ts
index 4e7c295dd4..8124c1b15e 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/commands/scanTextEdit.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/commands/scanTextEdit.ts
@@ -13,6 +13,7 @@ import type { TextRun } from "@editor/tools/pdfTextEditor/model/TextRun";
import {
RENDER_MODE_INVISIBLE,
type Affine,
+ type PageRect,
type RGBA,
} from "@editor/tools/pdfTextEditor/types";
import {
@@ -32,13 +33,16 @@ import {
lineRegion,
type PlacedWord,
} from "@editor/tools/pdfTextEditor/commands/scanOffInk";
+import { softStartsOf } from "@editor/tools/pdfTextEditor/pdfium/lineBreaks";
import {
+ joinSoftLines,
layoutScanEdit,
rewrapLines,
type LayoutWord,
} from "@editor/tools/pdfTextEditor/commands/scanLayout";
import {
emitFillRect,
+ measureObjBoxPt,
removeAndDestroyObject,
removeMemberPtrs,
recordUndrawableChars,
@@ -58,6 +62,7 @@ import {
preferredScanFace,
preferredStyle,
rankStyles,
+ strokeRatioOn,
withPreferredFace,
type FitInput,
type FitWord,
@@ -70,6 +75,7 @@ import {
drawInFont,
emitSearchable,
invisibleText,
+ lettersRight,
pasteImage,
wordGap,
type Canvas,
@@ -155,6 +161,8 @@ export interface ScanEditState {
undrawableWithFaces?: number;
/** Styles for text in the block that the scan sets at another size. */
classes: Array<{ style: ScanStyle; top: number }>;
+ /** Per OCR line, the style of a group of lines whose ink or weight is not the block's; null for lines in the block's look. */
+ lineStyles?: Map<number, ScanStyle | null>;
face?: Face | null;
nearbyFace?: Face | null;
neighbours?: PlacedWord[];
@@ -168,8 +176,11 @@ export interface ScanEditState {
typedFromScan?: boolean;
}
-export function isScanRun(run: { renderMode?: number }): boolean {
- return run.renderMode === RENDER_MODE_INVISIBLE;
+export function isScanRun(run: {
+ renderMode?: number;
+ hiddenText?: boolean;
+}): boolean {
+ return run.renderMode === RENDER_MODE_INVISIBLE && !run.hiddenText;
}
function emptyState(lines: ScanLine[], fontPtr: number): ScanEditState {
@@ -634,15 +645,17 @@ const X_HEIGHT_ONLY = /^[acemnorsuvwxz\s\p{P}]+$/u;
// One style for the whole block, fitted to its longest line, so an edit never
// switches face or size part way through a sentence. Only text the scan itself
-// sets at another size (a label and its value on one OCR line) gets its own.
+// sets at another size (a label and its value on one OCR line), or lines it
+// sets in another colour or weight, get their own.
function styleFor(
doc: EditorDocument,
page: Page,
state: ScanEditState,
span: SpanInk | null,
+ line?: number,
): ScanStyle | null {
return onOriginalScan(doc, page, state, () =>
- styleOnScan(doc, page, state, span),
+ styleOnScan(doc, page, state, span, line),
);
}
@@ -651,27 +664,36 @@ function styleOnScan(
page: Page,
state: ScanEditState,
span: SpanInk | null,
+ line: number | undefined,
): ScanStyle | null {
if (undrawableWithFewerFaces(state)) state.block = undefined;
if (state.block === undefined) {
state.block = fitBlock(doc, page, state);
+ state.lineStyles = undefined;
if (state.block === null) state.undrawableWithFaces = scanFacesGeneration();
}
- if (state.block && fittedForOtherPreference(doc, state))
+ if (state.block && fittedForOtherPreference(doc, state)) {
state.block = withPreferredFit(doc, page, state, state.block);
+ state.lineStyles = undefined;
+ }
const block = state.block;
const blockStyle = drawnBlockStyle(doc, state);
if (!block || !blockStyle) return null;
if (!span) return blockStyle;
const top = inkTop(span);
const near = (t: number) => Math.abs(top / t - 1) < 0.25;
- if (near(block.top)) return blockStyle;
- if (
- block.xHeight !== null &&
- X_HEIGHT_ONLY.test(span.original) &&
- near(block.xHeight)
- )
- return blockStyle;
+ const atBlockSize =
+ near(block.top) ||
+ (block.xHeight !== null &&
+ X_HEIGHT_ONLY.test(span.original) &&
+ near(block.xHeight));
+ if (atBlockSize)
+ return (
+ (line === undefined
+ ? null
+ : lineLookStyle(doc, page, state, line, block.ref, blockStyle)) ??
+ blockStyle
+ );
const known = state.classes.find((c) => near(c.top));
if (known) return known.style;
const ranked = rank(doc, page, state, [span], span);
@@ -683,6 +705,87 @@ function styleOnScan(
return style;
}
+// Lines the OCR joined into one paragraph can differ in colour or weight while
+// sharing a size, such as an address over a bold coloured link; each such line
+// takes the look of its own group, fitted to that group's longest line.
+const LOOK_INK_DISTANCE = 96;
+const LOOK_STROKE = Math.log(1.25);
+
+interface LineLook {
+ ink: RGBA;
+ /** -1 lighter strokes than the block's reference line, 1 heavier, 0 alike. */
+ weight: number;
+}
+
+const inkDistance = (a: RGBA, b: RGBA) =>
+ Math.abs(a.r - b.r) + Math.abs(a.g - b.g) + Math.abs(a.b - b.b);
+
+const sameLook = (a: LineLook, b: LineLook) =>
+ a.weight === b.weight && inkDistance(a.ink, b.ink) < LOOK_INK_DISTANCE;
+
+// Relative to the reference line: the fitted style need not match even that
+// line's strokes, as on a low-resolution scan no face draws as thin as the scan.
+function lookOf(
+ doc: EditorDocument,
+ page: Page,
+ span: SpanInk,
+ blockStyle: ScanStyle,
+ refRatio: number,
+): LineLook {
+ const stroke = Math.log(
+ strokeRatioOn(doc, page, span, blockStyle) / refRatio,
+ );
+ return {
+ ink: span.ink.fill,
+ weight: Math.abs(stroke) < LOOK_STROKE ? 0 : stroke > 0 ? -1 : 1,
+ };
+}
+
+function lineLookStyle(
+ doc: EditorDocument,
+ page: Page,
+ state: ScanEditState,
+ line: number,
+ ref: SpanInk,
+ blockStyle: ScanStyle,
+): ScanStyle | null {
+ const known = (state.lineStyles ??= new Map());
+ if (known.has(line)) return known.get(line) ?? null;
+ const inked = inkedLines(doc, page, state);
+ const own = inked.find((l) => l.li === line);
+ if (inked.length < 2 || !own) {
+ known.set(line, null);
+ return null;
+ }
+ const refRatio = strokeRatioOn(doc, page, ref, blockStyle);
+ const ownLook = lookOf(doc, page, own.ink, blockStyle, refRatio);
+ if (sameLook(ownLook, { ink: ref.ink.fill, weight: 0 })) {
+ known.set(line, null);
+ return null;
+ }
+ const group = inked.filter(
+ (l) =>
+ l === own ||
+ sameLook(lookOf(doc, page, l.ink, blockStyle, refRatio), ownLook),
+ );
+ const longest = group.reduce((p, q) =>
+ q.ink.original.length > p.ink.original.length ? q : p,
+ );
+ const groupRef = referenceSpan(doc, page, state, longest);
+ const ranked = rank(
+ doc,
+ page,
+ state,
+ group.map((l) => l.ink),
+ groupRef,
+ );
+ const style = ranked.length
+ ? (preferredStyle(doc, ranked) ?? ranked[0].style)
+ : null;
+ for (const l of group) known.set(l.li, style);
+ return style;
+}
+
/** Baseline-to-baseline distance in the block, for lines added below it. */
function linePitch(state: ScanEditState, style: ScanStyle): number {
const gaps = state.lines
@@ -693,16 +796,29 @@ function linePitch(state: ScanEditState, style: ScanStyle): number {
}
/** Typical gap between neighbouring words in the block. */
+const BOX_TOUCH_EM = 0.1;
+
function wordSpace(state: ScanEditState, style: ScanStyle): number {
const gaps = state.lines.flatMap((l) =>
l.words
.slice(1)
- .map((w, i) => w.x - l.words[i].right)
+ .map(
+ (w, i) => w.x - lettersRight({ ...l.words[i], text: boxedText(l, i) }),
+ )
.filter((g) => g > 0),
);
return gaps.length ? median(gaps) : style.fontSize * 0.28;
}
+// A word's text with its trailing space only when its box holds that space,
+// as Tesseract's does: such a box reaches the next word's.
+function boxedText(line: ScanLine, w: number): string {
+ const word = line.words[w];
+ const next = line.words[w + 1];
+ const reaches = next && next.x < word.right + BOX_TOUCH_EM * word.fontSize;
+ return reaches ? word.text : word.text.trimEnd() || word.text;
+}
+
function fallbackStyle(
state: ScanEditState,
ink = BLACK,
@@ -920,7 +1036,8 @@ function editStyles(
if (known) return known;
const blockStyle = fitted();
const own =
- styleFor(doc, page, state, anchor ? inkOf(anchor) : null) ?? blockStyle;
+ styleFor(doc, page, state, anchor ? inkOf(anchor) : null, anchor?.line) ??
+ blockStyle;
const style = withOverride(o, anchorBase(o, own, blockStyle));
styles.set(anchor, style);
return style;
@@ -973,6 +1090,39 @@ function scanGlyphSource(
};
}
+// Visible text of other runs on the block's lines, such as words typed into an earlier save of this scan.
+function drawnTextOnLines(
+ page: Page,
+ run: TextRun,
+ lines: Array<{ baseline: number }>,
+ state: ScanEditState,
+): Array<{ line: number; x: number; right: number }> {
+ const out: Array<{ line: number; x: number; right: number }> = [];
+ for (const other of page.runs) {
+ if (other === run || isScanRun(other) || other.text.trim() === "") continue;
+ const slots = other.paragraphLineSlots.length
+ ? other.paragraphLineSlots
+ : [
+ {
+ baselineY: other.matrix.f,
+ mergedFromBounds: [
+ { x: other.bounds.x, right: other.bounds.x + other.bounds.width },
+ ],
+ },
+ ];
+ for (const slot of slots) {
+ const line = lines.findIndex(
+ (l, li) =>
+ Math.abs(l.baseline - slot.baselineY) <= state.lines[li].height * 0.5,
+ );
+ if (line < 0) continue;
+ for (const b of slot.mergedFromBounds)
+ out.push({ line, x: b.x, right: b.right });
+ }
+ }
+ return out;
+}
+
function renderUprightScanEdit(
doc: EditorDocument,
page: Page,
@@ -1059,6 +1209,7 @@ function renderUprightScanEdit(
text,
pitch,
space,
+ obstacles: state.frame ? [] : drawnTextOnLines(page, run, lines, state),
wordWidth: inkWidth,
textWidth: (t, anchor, replaced) => {
if (!shows(t, anchor)) return anchor ? keptWidth(anchor, replaced) : 0;
@@ -1231,7 +1382,7 @@ function renderUprightScanEdit(
});
emitSearchable(
canvas,
- sw.text.trimEnd() || sw.text,
+ boxedText(state.lines[k.word.line], k.word.index),
{ left: k.x, right: k.x + sw.right - sw.x },
sw.baseline + k.baseline - lineBase(k.word.line),
sw.fontSize,
@@ -1295,7 +1446,7 @@ function syncOriginalWords(
} else if (!gone.has(key) && state.lifted.has(key)) {
const back = invisibleText(
canvas,
- word.text.trimEnd() || word.text,
+ boxedText(line, wi),
{ left: word.x, right: word.right },
word.baseline,
word.fontSize,
@@ -1308,6 +1459,37 @@ function syncOriginalWords(
}
}),
);
+ if (state.lifted.size > 0) bringWordsToPage(canvas, state);
+}
+
+// The reader groups lines within one form at a time, so OCR words left in the
+// scan's form beside words this edit drew on the page would read back as two
+// lines, and the paragraph as two runs, once the file is reopened.
+function bringWordsToPage(canvas: Canvas, state: ScanEditState): void {
+ const { doc, page } = canvas;
+ state.lines.forEach((line, li) =>
+ line.words.forEach((word, wi) => {
+ if (word.container === 0 || state.lifted.has(`${li}:${wi}`)) return;
+ removeMemberPtrs(
+ doc.module,
+ page,
+ [word.ptr, ...(word.extraPtrs ?? [])],
+ new Map([[word.ptr, word.container]]),
+ 0,
+ );
+ const drawn = invisibleText(
+ canvas,
+ boxedText(line, wi),
+ { left: word.x, right: word.right },
+ word.baseline,
+ word.fontSize,
+ { originalFontPtr: state.fontPtr, family: "Helvetica" },
+ );
+ word.ptr = drawn[0] ?? 0;
+ word.extraPtrs = drawn.slice(1);
+ word.container = 0;
+ }),
+ );
}
// Deleting the run takes its drawn text and OCR words; the covers stay, as the scan under them is the old text.
@@ -1325,6 +1507,38 @@ function attachToRun(run: TextRun, state: ScanEditState): void {
];
}
+/** Page-space box around a scanned run's text as last drawn: the OCR words still on the page plus the text the edit emitted. Null for a turned block, whose words are not in page space, or when nothing can be measured. */
+export function scanBlockBounds(
+ doc: EditorDocument,
+ run: TextRun,
+): PageRect | null {
+ const state = run.scanEdit;
+ if (!state || state.frame) return null;
+ const boxes: PageRect[] = state.lines.flatMap((line, li) =>
+ line.words
+ .filter((_, wi) => !state.lifted.has(`${li}:${wi}`))
+ .map((w) => ({
+ x: w.x,
+ y: w.baseline,
+ width: w.right - w.x,
+ height: line.height,
+ })),
+ );
+ for (const ptr of state.textPtrs) {
+ const box = measureObjBoxPt(doc.module, ptr);
+ if (box && box.width > 0) boxes.push(box);
+ }
+ if (boxes.length === 0) return null;
+ const x = Math.min(...boxes.map((b) => b.x));
+ const y = Math.min(...boxes.map((b) => b.y));
+ return {
+ x,
+ y,
+ width: Math.max(...boxes.map((b) => b.x + b.width)) - x,
+ height: Math.max(...boxes.map((b) => b.y + b.height)) - y,
+ };
+}
+
/** The run's scan-edit state, captured on first use; null when it has none. */
export function scanEditOf(
doc: EditorDocument,
@@ -1351,7 +1565,8 @@ export function wrapScanText(
const width = (line: string) =>
spanOf(doc, page, line, style.family, style.fontSize) * style.stretch;
const fits = (line: string) => line === "" || width(line) <= maxWidthPt;
- const grown = rewrapLines(run.text, fits, true);
+ const joined = joinSoftLines(run.text, softStartsOf(run), fits);
+ const grown = rewrapLines(joined, fits, true);
const wrapped = roomBelow(
page,
run,
@@ -1360,7 +1575,7 @@ export function wrapScanText(
grown.split("\n").length,
)
? grown
- : rewrapLines(run.text, fits, false);
+ : rewrapLines(joined, fits, false);
// All or nothing: without room for the last line's overflow the text would just stick out on another line.
const settled = wrapped
.split("\n")
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/commands/tableHelpers.ts b/frontend/src/editor/core/tools/pdfTextEditor/commands/tableHelpers.ts
index 93b725e806..777a9d242e 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/commands/tableHelpers.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/commands/tableHelpers.ts
@@ -1,3 +1,7 @@
+import {
+ assertLiftable,
+ liftRunToPage,
+} from "@editor/tools/pdfTextEditor/commands/liftFromForm";
import type { WrappedPdfiumModule } from "@embedpdf/pdfium";
import type { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
import type { Page } from "@editor/tools/pdfTextEditor/model/Page";
@@ -12,6 +16,10 @@ import {
measureObjSpanPt,
sanitizeForBase14,
} from "@editor/tools/pdfTextEditor/commands/editTextHelpers";
+import {
+ emitFallbackTextObject,
+ fallbackFontDraws,
+} from "@editor/tools/pdfTextEditor/util/fallbackFont";
import { transformObject } from "@editor/tools/pdfTextEditor/util/objectTransform";
const LINE_RGB = { r: 0, g: 0, b: 0 } as const;
@@ -404,8 +412,21 @@ export interface EmittedText {
run: TextRun;
}
-// Insert a base-14 (Helvetica) text object at a page-space point and register a
-// matching run. Mirrors InsertTextCommand's core; used for cell content.
+const leavesBase14 = (text: string): boolean =>
+ [...sanitizeForBase14(text)].length < [...text].length;
+
+/** True when cell text can be drawn whole: the standard fonts encode every character, or the fallback face has loaded and covers them. */
+export function cellTextDrawable(text: string): boolean {
+ return !leavesBase14(text) || fallbackFontDraws(text);
+}
+
+/**
+ * Inserts `text` at a page-space point and registers a matching run: in the
+ * standard font `family` when that encodes every character, otherwise in the
+ * fallback face. Draws all of `text` or nothing: null when some character
+ * cannot be drawn, since a run holding letters the page never drew loses them
+ * on save.
+ */
export function emitCellText(
doc: EditorDocument,
page: Page,
@@ -417,22 +438,14 @@ export function emitCellText(
family: string = CELL_FAMILY,
): EmittedText | null {
const m = doc.module;
- const sanitized = sanitizeForBase14(text);
- // PDFium can only build a text object for a base-14 name; a family it cannot
- // resolve returns 0, so fall back rather than dropping the text.
- const ptr =
- m.FPDFPageObj_NewTextObj(doc.docPtr, family, fontSize) ||
- m.FPDFPageObj_NewTextObj(doc.docPtr, CELL_FAMILY, fontSize);
+ const standard = !leavesBase14(text);
+ const drawn = standard ? sanitizeForBase14(text) : text;
+ // Setting empty text traps in PDFium.
+ if (drawn.length === 0) return null;
+ const ptr = standard
+ ? emitStandardText(doc, page, x, y, drawn, fontSize, fill, family)
+ : emitFallbackTextObject(doc, page, drawn, fontSize, fill, x, y);
if (!ptr) return null;
- const textPtr = writeUtf16(m, sanitized);
- try {
- m.FPDFText_SetText(ptr, textPtr);
- } finally {
- m.pdfium.wasmExports.free(textPtr);
- }
- m.FPDFPageObj_SetFillColor(ptr, fill.r, fill.g, fill.b, fill.a);
- m.FPDFPageObj_Transform(ptr, 1, 0, 0, 1, x, y);
- m.FPDFPage_InsertObject(page.pagePtr, ptr);
const runId = `p${page.index}-cell-${page.runs.length}-${ptr}`;
// Measured, not estimated: a guessed box puts the editing overlay off the
@@ -446,11 +459,11 @@ export function emitCellText(
bounds: measured ?? {
x,
y,
- width: Math.max(1, text.length * fontSize * 0.55),
+ width: Math.max(1, drawn.length * fontSize * 0.55),
height: fontSize * 1.2,
},
matrix: { a: 1, b: 0, c: 0, d: 1, e: x, f: y },
- text,
+ text: drawn,
fontId: `base14:${family}`,
fontSize,
fill: { ...fill },
@@ -460,6 +473,35 @@ export function emitCellText(
return { ptr, run };
}
+function emitStandardText(
+ doc: EditorDocument,
+ page: Page,
+ x: number,
+ y: number,
+ text: string,
+ fontSize: number,
+ fill: RGBA,
+ family: string,
+): number {
+ const m = doc.module;
+ // PDFium can only build a text object for a base-14 name; a family it cannot
+ // resolve returns 0, so fall back rather than dropping the text.
+ const ptr =
+ m.FPDFPageObj_NewTextObj(doc.docPtr, family, fontSize) ||
+ m.FPDFPageObj_NewTextObj(doc.docPtr, CELL_FAMILY, fontSize);
+ if (!ptr) return 0;
+ const textPtr = writeUtf16(m, text);
+ try {
+ m.FPDFText_SetText(ptr, textPtr);
+ } finally {
+ m.pdfium.wasmExports.free(textPtr);
+ }
+ m.FPDFPageObj_SetFillColor(ptr, fill.r, fill.g, fill.b, fill.a);
+ m.FPDFPageObj_Transform(ptr, 1, 0, 0, 1, x, y);
+ m.FPDFPage_InsertObject(page.pagePtr, ptr);
+ return ptr;
+}
+
/** Translate a run and its PDFium object by (dx, dy) page points. */
export function shiftRunBy(
m: WrappedPdfiumModule,
@@ -488,6 +530,22 @@ export function shiftRunBy(
// its cell so content keeps its position within the cell rather than being
// re-anchored. Used by every resize; reversible by calling it with the old
// edges.
+/** Throws, before anything is changed, when a run in the table cannot be lifted out of its form (see assertLiftable). */
+export function assertTableLiftable(
+ doc: EditorDocument,
+ page: Page,
+ model: TableModel,
+): void {
+ const runs = model.cellRuns.flatMap((row, r) =>
+ row.flatMap((_id, c) => model.runsAt(r, c)),
+ );
+ assertLiftable(
+ doc,
+ page,
+ runs.map((id) => page.findRun(id)).filter((run) => run !== undefined),
+ );
+}
+
export function setTableEdges(
doc: EditorDocument,
page: Page,
@@ -537,7 +595,10 @@ export function setTableEdges(
model.colEdges = [...colEdges];
model.rowEdges = [...rowEdges];
renormaliseFontBase(model);
- for (const mv of moves) shiftRunBy(doc.module, mv.run, mv.dx, mv.dy);
+ for (const mv of moves) {
+ liftRunToPage(doc, page, mv.run);
+ shiftRunBy(doc.module, mv.run, mv.dx, mv.dy);
+ }
redrawGrid(doc, page, model);
}
@@ -655,6 +716,7 @@ export function applyCellPlacement(
const targetBaseline =
model.cellRect(spot.row, spot.col).y + spot.baseline * scale;
const dy = targetBaseline - run.matrix.f;
+ liftRunToPage(doc, page, run);
shiftRunBy(doc.module, run, dx, dy);
}
}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/commands/textPieces.ts b/frontend/src/editor/core/tools/pdfTextEditor/commands/textPieces.ts
index b0ed025905..d6b71083c6 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/commands/textPieces.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/commands/textPieces.ts
@@ -429,7 +429,7 @@ export function readMatrix(
);
}
-function writeMatrix(
+export function writeMatrix(
m: WrappedPdfiumModule,
objPtr: number,
matrix: Float32Array,
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/DiscardChangesModal.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/DiscardChangesModal.tsx
index 87b99b274a..d4ab0deccf 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/components/DiscardChangesModal.tsx
+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/DiscardChangesModal.tsx
@@ -1,3 +1,4 @@
+import { memo } from "react";
import { Group, Modal, Stack, Text } from "@mantine/core";
import { useTranslation } from "react-i18next";
import { Button } from "@editor/ui/Button";
@@ -9,7 +10,7 @@ interface Props {
onCancel: () => void;
}
-export function DiscardChangesModal({
+export const DiscardChangesModal = memo(function DiscardChangesModal({
incomingFileName,
onConfirm,
onCancel,
@@ -58,4 +59,4 @@ export function DiscardChangesModal({
</Stack>
</Modal>
);
-}
+});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/EditorPanelActions.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/EditorPanelActions.tsx
index 55f9b8537a..de3488e480 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/components/EditorPanelActions.tsx
+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/EditorPanelActions.tsx
@@ -1,3 +1,4 @@
+import { memo } from "react";
import { Box, Group, Tooltip } from "@mantine/core";
import { Icon } from "@editor/ui/Icon";
import { useTranslation } from "react-i18next";
@@ -12,7 +13,7 @@ interface Props {
onShowHelp: () => void;
}
-export function EditorPanelActions({
+export const EditorPanelActions = memo(function EditorPanelActions({
compact,
onSave,
onDownload,
@@ -105,4 +106,4 @@ export function EditorPanelActions({
</Group>
</Box>
);
-}
+});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/EditorSidebar.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/EditorSidebar.tsx
index 8738766c5a..df244d6432 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/components/EditorSidebar.tsx
+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/EditorSidebar.tsx
@@ -1,4 +1,4 @@
-import { useCallback, useEffect, useMemo, useState } from "react";
+import { memo, useCallback, useEffect, useMemo, useState } from "react";
import { Box, Center, Group, Stack, Tabs, Text } from "@mantine/core";
import { useTranslation } from "react-i18next";
import { Icon } from "@editor/ui/Icon";
@@ -29,6 +29,7 @@ import {
scanTypingDropped,
} from "@editor/tools/pdfTextEditor/commands/scanTextEdit";
import { ScanFontMatchModal } from "@editor/tools/pdfTextEditor/components/inspector/ScanFontMatchModal";
+import type { ImageReview } from "@editor/tools/pdfTextEditor/util/imageAccessibility";
import type {
EditorViewState,
LoadProgress,
@@ -55,7 +56,7 @@ interface SidebarProps extends Omit<ScanHintProps, "pages"> {
export type SidebarTab = "selected" | "document";
-export function EditorSidebar({
+export const EditorSidebar = memo(function EditorSidebar({
store,
state,
selection,
@@ -76,7 +77,6 @@ export function EditorSidebar({
const { t } = useTranslation();
const controller = useToolbarController(store, state, selection);
const geometry = useSelectionGeometry(store, state, selection);
- const documentLanguage = useDocumentLanguage(store, state);
const hasSelection =
selection.runIds.length > 0 ||
selection.imageIds.length > 0 ||
@@ -113,22 +113,6 @@ export function EditorSidebar({
if (!reviewing && !(ACCESSIBILITY_EDITING && artifactTextSelected)) return;
return readAllPagesInBackground(store);
}, [reviewingAccessibility, tab, imageSelected, artifactTextSelected, store]);
- const setMarkedTagged = useCallback(
- (marked: boolean) => store.dispatch(new SetMarkedTaggedCommand(marked)),
- [store],
- );
- const headings = useHeadingOutline(
- store,
- state,
- reviewingAccessibility && tab === "document",
- );
-
- const bulkTagging = useBulkTagging(
- store,
- state,
- reviewingAccessibility && tab === "document",
- );
-
// Following the selection only catches one appearing, so moving from one
// selected image to the next would leave the new one's description hidden.
const selectNextImageToReview = () => {
@@ -200,37 +184,78 @@ export function EditorSidebar({
)}
</Tabs.Panel>
<Tabs.Panel value="document">
- <DocumentInspector
- pages={state.pages}
- groupingMode={state.groupingMode}
- widthMode={state.widthMode}
- showRulers={state.showRulers}
- onSetGroupingMode={onSetGroupingMode}
- onSetWidthMode={onSetWidthMode}
- onSetShowRulers={onSetShowRulers}
- imageReview={
- reviewingAccessibility ? controller.imageReview : null
- }
- onSelectNextImageToReview={selectNextImageToReview}
- untaggedPages={bulkTagging.untaggedPages}
- onTagUntaggedContent={bulkTagging.tagAll}
- markedTagged={
- editorDocument?.canSetMarkedTagged()
- ? editorDocument.markedTagged()
- : null
- }
- onSetMarkedTagged={setMarkedTagged}
- hasTags={!!editorDocument?.hasStructureTree()}
- headingOutline={headings.outline}
- onSelectHeading={headings.selectHeading}
- documentLanguage={documentLanguage}
- />
+ {tab === "document" && (
+ <DocumentTab
+ store={store}
+ state={state}
+ reviewingAccessibility={reviewingAccessibility}
+ imageReview={
+ reviewingAccessibility ? controller.imageReview : null
+ }
+ onSelectNextImageToReview={selectNextImageToReview}
+ onSetGroupingMode={onSetGroupingMode}
+ onSetWidthMode={onSetWidthMode}
+ onSetShowRulers={onSetShowRulers}
+ />
+ )}
</Tabs.Panel>
</Box>
</LanguagesInUse.Provider>
{scanFontMatch && <ScanFontMatchModal match={scanFontMatch} />}
</Tabs>
);
+});
+
+function DocumentTab({
+ store,
+ state,
+ reviewingAccessibility,
+ imageReview,
+ onSelectNextImageToReview,
+ onSetGroupingMode,
+ onSetWidthMode,
+ onSetShowRulers,
+}: Pick<
+ SidebarProps,
+ "store" | "state" | "onSetGroupingMode" | "onSetWidthMode" | "onSetShowRulers"
+> & {
+ reviewingAccessibility: boolean;
+ imageReview: ImageReview | null;
+ onSelectNextImageToReview: () => void;
+}) {
+ const documentLanguage = useDocumentLanguage(store, state);
+ const headings = useHeadingOutline(store, state, reviewingAccessibility);
+ const bulkTagging = useBulkTagging(store, state, reviewingAccessibility);
+ const setMarkedTagged = useCallback(
+ (marked: boolean) => store.dispatch(new SetMarkedTaggedCommand(marked)),
+ [store],
+ );
+ const editorDocument = store.document;
+ return (
+ <DocumentInspector
+ pages={state.pages}
+ groupingMode={state.groupingMode}
+ widthMode={state.widthMode}
+ showRulers={state.showRulers}
+ onSetGroupingMode={onSetGroupingMode}
+ onSetWidthMode={onSetWidthMode}
+ onSetShowRulers={onSetShowRulers}
+ imageReview={imageReview}
+ onSelectNextImageToReview={onSelectNextImageToReview}
+ untaggedPages={bulkTagging.untaggedPages}
+ onTagUntaggedContent={bulkTagging.tagAll}
+ markedTagged={
+ editorDocument?.canSetMarkedTagged()
+ ? editorDocument.markedTagged()
+ : null
+ }
+ onSetMarkedTagged={setMarkedTagged}
+ hasTags={!!editorDocument?.hasStructureTree()}
+ headingOutline={headings.outline}
+ onSelectHeading={headings.selectHeading}
+ documentLanguage={documentLanguage}
+ />
+ );
}
/** What the Selected tab shows before the user has picked anything. */
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/EditorTopBar.css b/frontend/src/editor/core/tools/pdfTextEditor/components/EditorTopBar.css
index b05caf2472..02614f6b23 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/components/EditorTopBar.css
+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/EditorTopBar.css
@@ -36,6 +36,13 @@
padding-bottom: 0.125rem;
}
+.pdf-editor-topbar__format {
+ display: flex;
+ align-items: center;
+ gap: 0.25rem;
+ flex: 0 0 auto;
+}
+
.pdf-editor-topbar__file {
display: flex;
align-items: center;
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/EditorTopBar.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/EditorTopBar.tsx
index 7be58f462f..2578294f88 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/components/EditorTopBar.tsx
+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/EditorTopBar.tsx
@@ -1,4 +1,10 @@
-import { useRef } from "react";
+import {
+ useCallback,
+ useEffect,
+ useLayoutEffect,
+ useRef,
+ useState,
+} from "react";
import { Icon } from "@editor/ui/Icon";
import { Group, Menu, Popover, Tooltip } from "@mantine/core";
import { useTranslation } from "react-i18next";
@@ -13,9 +19,74 @@ import {
import { useEditorSession } from "@editor/tools/pdfTextEditor/store/EditorSession";
import { useElementWidth } from "@editor/tools/pdfTextEditor/hooks/useElementWidth";
import { modShortcut } from "@editor/utils/hotkeys";
+import { offsetClearing } from "@editor/tools/pdfTextEditor/util/clearingOffset";
import "@editor/tools/pdfTextEditor/components/EditorTopBar.css";
const COMPACT_BELOW_PX = 900;
+const FORMAT_MENU_GAP = 8;
+
+function FormatMenu({ controller }: { controller: Controller }) {
+ const { t } = useTranslation();
+ const [offset, setOffset] = useState(FORMAT_MENU_GAP);
+ const targetRef = useRef<HTMLButtonElement | null>(null);
+ const dropdownRef = useRef<HTMLDivElement | null>(null);
+ const { selectedRunIds } = controller;
+
+ // The dropdown hangs over the top of the page, where the line being formatted often sits.
+ const clearSelectedText = useCallback(() => {
+ requestAnimationFrame(() => {
+ const anchor = targetRef.current?.getBoundingClientRect();
+ const dropdown = dropdownRef.current?.getBoundingClientRect();
+ if (!anchor || !dropdown) return;
+ const selected = selectedRunIds.flatMap((id) => {
+ const el = document.querySelector(`[data-run-id="${CSS.escape(id)}"]`);
+ return el ? [el.getBoundingClientRect()] : [];
+ });
+ setOffset(
+ offsetClearing(
+ anchor.bottom,
+ {
+ left: anchor.left,
+ right: anchor.left + dropdown.width,
+ height: dropdown.height,
+ },
+ selected,
+ FORMAT_MENU_GAP,
+ window.innerHeight,
+ ),
+ );
+ });
+ }, [selectedRunIds]);
+
+ return (
+ <Popover
+ position="bottom-start"
+ withinPortal
+ shadow="md"
+ offset={offset}
+ onOpen={clearSelectedText}
+ onClose={() => setOffset(FORMAT_MENU_GAP)}
+ >
+ <Popover.Target>
+ <Button
+ ref={targetRef}
+ size="sm"
+ variant="tertiary"
+ accent="neutral"
+ aria-label={t("pdfTextEditor.toolbar.formatting", "Text formatting")}
+ data-testid="pdf-editor-format-menu"
+ style={NO_SHRINK}
+ leftSection={<Icon name="case-sensitive" size={20} />}
+ />
+ </Popover.Target>
+ <Popover.Dropdown ref={dropdownRef}>
+ <Group gap="xs" wrap="wrap" maw={320}>
+ <FormatGroup controller={controller} inPopover />
+ </Group>
+ </Popover.Dropdown>
+ </Popover>
+ );
+}
interface EditorTopBarProps {
controller: Controller;
@@ -48,6 +119,44 @@ export function EditorTopBar({
const barRef = useRef<HTMLDivElement | null>(null);
const barWidth = useElementWidth(barRef);
const compact = barWidth !== null && barWidth < COMPACT_BELOW_PX;
+ const bandRef = useRef<HTMLDivElement | null>(null);
+ // The bar width the formatting controls need inline; 0 until they are seen not to fit.
+ const [formatNeeds, setFormatNeeds] = useState(0);
+ const foldFormat = compact || (barWidth !== null && barWidth < formatNeeds);
+ const formatShape = [
+ controller.hasRunSelection,
+ controller.hasImageSelection,
+ controller.state.weights.length > 0,
+ ].join();
+ // Other controls may fit again; measuring them inline happens before paint.
+ useLayoutEffect(() => setFormatNeeds(0), [formatShape]);
+ // The controls can grow after they mount (the device-fonts button, a loader), which re-renders only them.
+ const [formatGroup, setFormatGroup] = useState<HTMLDivElement | null>(null);
+ const [formatWidth, setFormatWidth] = useState(0);
+ useEffect(() => {
+ if (!formatGroup || typeof ResizeObserver === "undefined") return;
+ const observer = new ResizeObserver(([entry]) =>
+ setFormatWidth(entry.contentRect.width),
+ );
+ observer.observe(formatGroup);
+ return () => observer.disconnect();
+ }, [formatGroup]);
+ useLayoutEffect(() => {
+ const band = bandRef.current;
+ if (!band || barWidth === null || foldFormat || !hasSelection) return;
+ // The colour field widens while its picker is open; folding then would
+ // remount the controls and close the picker under the pointer.
+ if (formatGroup?.querySelector('[aria-expanded="true"]')) return;
+ const overflow = band.scrollWidth - band.clientWidth;
+ if (overflow > 0) setFormatNeeds(Math.ceil(barWidth + overflow));
+ }, [
+ barWidth,
+ foldFormat,
+ hasSelection,
+ formatGroup,
+ formatWidth,
+ formatShape,
+ ]);
const addTextLabel = addTextArmed
? t("pdfTextEditor.sidebar.clickPageToAddText", "Click page to add text")
@@ -84,7 +193,7 @@ export function EditorTopBar({
{/* Shown from the first frame, idle until the document is read, so the
bar does not pop in after the load. */}
- <div className="pdf-editor-topbar__band">
+ <div className="pdf-editor-topbar__band" ref={bandRef}>
<Tooltip
label={t("pdfTextEditor.toolbar.undoTooltip", {
defaultValue: "Undo ({{shortcut}})",
@@ -267,30 +376,12 @@ export function EditorTopBar({
is invisible rather than visibly clipped. */}
<ObjectGroup controller={controller} />
<ToolbarSeparator />
- {compact ? (
- <Popover position="bottom-start" withinPortal shadow="md">
- <Popover.Target>
- <Button
- size="sm"
- variant="tertiary"
- accent="neutral"
- aria-label={t(
- "pdfTextEditor.toolbar.formatting",
- "Text formatting",
- )}
- data-testid="pdf-editor-format-menu"
- style={NO_SHRINK}
- leftSection={<Icon name="case-sensitive" size={20} />}
- />
- </Popover.Target>
- <Popover.Dropdown>
- <Group gap="xs" wrap="wrap" maw={320}>
- <FormatGroup controller={controller} />
- </Group>
- </Popover.Dropdown>
- </Popover>
+ {foldFormat ? (
+ <FormatMenu controller={controller} />
) : (
- <FormatGroup controller={controller} />
+ <div className="pdf-editor-topbar__format" ref={setFormatGroup}>
+ <FormatGroup controller={controller} />
+ </div>
)}
</>
)}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/FindBar.test.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/FindBar.test.tsx
index 71bd8b3c9a..96e56c387c 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/components/FindBar.test.tsx
+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/FindBar.test.tsx
@@ -23,32 +23,36 @@ import type { EditorStore } from "@editor/tools/pdfTextEditor/store/EditorStore"
import type { EditTextCommand } from "@editor/tools/pdfTextEditor/commands/EditTextCommand";
import type { PageSnapshot } from "@editor/tools/pdfTextEditor/types";
-function setup() {
- const runs = [
+function setup(
+ runs = [
{ id: "a", text: "Invoice for Jane", locked: false },
{ id: "b", text: "Jane Example", locked: false },
- ];
+ ],
+) {
const page = {
index: 0,
runs,
findRun: (id: string) => runs.find((r) => r.id === id),
};
const dispatch = vi.fn();
+ const highlight = { set: vi.fn() };
const store = {
dispatch,
document: { loadedPages: () => [page] },
selection: {
selectOne: vi.fn(),
- highlight: { set: vi.fn() },
+ highlight,
},
} as unknown as EditorStore;
const pages = [{ pageIndex: 0, runs }] as unknown as PageSnapshot[];
- render(
+ const view = (current: PageSnapshot[]) => (
<MantineProvider env="test">
- <FindBar store={store} pages={pages} onClose={vi.fn()} />
- </MantineProvider>,
+ <FindBar store={store} pages={current} onClose={vi.fn()} />
+ </MantineProvider>
);
- return { dispatch, runs };
+ const { rerender } = render(view(pages));
+ const showPages = (next: PageSnapshot[]) => rerender(view(next));
+ return { dispatch, runs, highlight, showPages };
}
describe("Replace all on unfitted scanned text", () => {
@@ -155,3 +159,69 @@ describe("Replace all on unfitted scanned text", () => {
]);
});
});
+
+describe("Find", () => {
+ it("steps through each occurrence and highlights only the matched letters", () => {
+ const { highlight } = setup([
+ { id: "a", text: "Jane met Jane", locked: false },
+ { id: "b", text: "Jane Example", locked: false },
+ ]);
+ fireEvent.change(screen.getByTestId("pdf-editor-find-input"), {
+ target: { value: "Jane" },
+ });
+
+ fireEvent.click(screen.getByTestId("pdf-editor-find-next"));
+ fireEvent.click(screen.getByTestId("pdf-editor-find-next"));
+ fireEvent.click(screen.getByTestId("pdf-editor-find-next"));
+
+ const shown = highlight.set.mock.calls
+ .map(([match]) => JSON.stringify(match))
+ .filter((match, i, all) => match !== "null" && match !== all[i - 1])
+ .map((match) => JSON.parse(match));
+ expect(shown).toEqual([
+ { runId: "a", range: { start: 0, end: 4 } },
+ { runId: "a", range: { start: 9, end: 13 } },
+ { runId: "b", range: { start: 0, end: 4 } },
+ { runId: "a", range: { start: 0, end: 4 } },
+ ]);
+ });
+
+ it("replaces only the current occurrence", () => {
+ const { dispatch } = setup([
+ { id: "a", text: "Jane met Jane", locked: false },
+ ]);
+ fireEvent.change(screen.getByTestId("pdf-editor-find-input"), {
+ target: { value: "Jane" },
+ });
+ fireEvent.change(screen.getByTestId("pdf-editor-replace-input"), {
+ target: { value: "Mary" },
+ });
+ fireEvent.click(screen.getByTestId("pdf-editor-find-next"));
+
+ fireEvent.click(screen.getByTestId("pdf-editor-replace-one"));
+
+ const command = dispatch.mock.calls[0][0] as EditTextCommand;
+ expect(command.resultText).toBe("Jane met Mary");
+ });
+
+ it("moves the highlight with the match when the text around it is edited", () => {
+ const { highlight, showPages } = setup([
+ { id: "a", text: "Jane met Jane", locked: false },
+ ]);
+ fireEvent.change(screen.getByTestId("pdf-editor-find-input"), {
+ target: { value: "Jane" },
+ });
+
+ showPages([
+ {
+ pageIndex: 0,
+ runs: [{ id: "a", text: "Dear Jane met Jane", locked: false }],
+ },
+ ] as unknown as PageSnapshot[]);
+
+ expect(highlight.set).toHaveBeenLastCalledWith({
+ runId: "a",
+ range: { start: 5, end: 9 },
+ });
+ });
+});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/FindBar.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/FindBar.tsx
index fc0a7eb28d..94f6d039b2 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/components/FindBar.tsx
+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/FindBar.tsx
@@ -35,7 +35,9 @@ interface Match {
runId: string;
/** Run snapshot (cached so navigation can scroll to it). */
run: TextRunSnapshot;
- /** Every occurrence inside this run, as offsets into `run.text`. */
+ /** This occurrence, as offsets into `run.text`. */
+ range: TextMatch;
+ /** Every occurrence inside this run, so Replace all edits each run once. */
ranges: TextMatch[];
}
@@ -84,8 +86,14 @@ export function FindBar({ store, pages, onClose }: FindBarProps) {
for (const page of pages) {
for (const run of page.runs) {
const ranges = findMatches(run.text, query, options);
- if (ranges.length > 0) {
- out.push({ pageIndex: page.pageIndex, runId: run.id, run, ranges });
+ for (const range of ranges) {
+ out.push({
+ pageIndex: page.pageIndex,
+ runId: run.id,
+ run,
+ range,
+ ranges,
+ });
}
}
}
@@ -97,7 +105,10 @@ export function FindBar({ store, pages, onClose }: FindBarProps) {
const m = matches[idx];
if (!m) return;
store.selection.selectOne(m.runId);
- store.selection.highlight.set(m.runId);
+ store.selection.highlight.set({
+ runId: m.runId,
+ range: { start: m.range.start, end: m.range.end },
+ });
const el = document.querySelector<HTMLElement>(
`[data-testid="pdf-editor-run-${m.runId}"]`,
);
@@ -144,21 +155,27 @@ export function FindBar({ store, pages, onClose }: FindBarProps) {
}
}, [searchKey, matches, focusMatch, activeIndex]);
+ // Edits move the letters under a match, so the highlight follows the match rather than its old offsets.
+ useEffect(() => {
+ const m = matches[activeIndex];
+ store.selection.highlight.set(
+ m
+ ? { runId: m.runId, range: { start: m.range.start, end: m.range.end } }
+ : null,
+ );
+ }, [matches, activeIndex, store]);
+
/**
- * Replace the CURRENT match with the replace text. Dispatches one
- * EditTextCommand. Every occurrence inside that run is swapped in a
- * single pass so a run like "Foo foo FOO" becomes "bar bar bar" -
- * matches the user's mental model of "replace happens to the
- * highlighted run" without surprising them with partial mutations.
- * The replacement is spliced literally, so "$&" stays "$&".
+ * Replace the CURRENT occurrence, the one highlighted. The replacement is
+ * spliced literally, so "$&" stays "$&".
*/
const doReplaceOne = useCallback(() => {
if (!query || replacing) return;
const m = matches[activeIndex];
if (!m) return;
// A locked run is still findable, but must not be rewritten.
- if (m.run.locked) return;
- const updated = replaceMatches(m.run.text, m.ranges, replace);
+ if (m.run.locked || m.run.textReadOnly) return;
+ const updated = replaceMatches(m.run.text, [m.range], replace);
if (updated === m.run.text) return;
store.dispatch(
new EditTextCommand({
@@ -179,9 +196,11 @@ export function FindBar({ store, pages, onClose }: FindBarProps) {
const doc = store.document;
if (!doc || replacing || !query || matches.length === 0) return;
const targets: ScanFitTarget[] = [];
+ const seen = new Set<string>();
for (const m of matches) {
// Skip locked runs: the lock is a user instruction, not a hint.
- if (m.run.locked) continue;
+ if (m.run.locked || m.run.textReadOnly || seen.has(m.runId)) continue;
+ seen.add(m.runId);
if (replaceMatches(m.run.text, m.ranges, replace) === m.run.text)
continue;
const page = doc.loadedPages().find((p) => p.index === m.pageIndex);
@@ -192,7 +211,7 @@ export function FindBar({ store, pages, onClose }: FindBarProps) {
const cmds: EditTextCommand[] = [];
for (const { page, run: target } of targets) {
const run = page.findRun(target.id);
- if (!run || run.locked) continue;
+ if (!run || run.locked || run.textReadOnly) continue;
const ranges = findMatches(run.text, query, options);
const updated = replaceMatches(run.text, ranges, replace);
if (updated === run.text) continue;
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/FontFamilySelect.test.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/FontFamilySelect.test.tsx
index ecdc54fda2..aa9e087186 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/components/FontFamilySelect.test.tsx
+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/FontFamilySelect.test.tsx
@@ -1,3 +1,4 @@
+import { useState } from "react";
import { MantineProvider } from "@mantine/core";
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
@@ -13,6 +14,7 @@ import {
forgetServerFontList,
} from "@editor/tools/pdfTextEditor/util/serverFonts";
import { resetLocalFontsCache } from "@editor/tools/pdfTextEditor/util/localFonts";
+import { documentFamilies } from "@editor/tools/pdfTextEditor/util/fontFaces";
const MANIFEST = {
families: [
@@ -78,15 +80,49 @@ describe("font picker server fonts", () => {
expect(get).toHaveBeenCalledWith(SERVER_FONTS_URL, expect.anything());
});
- it("offers the bold cut of a server family that has one", async () => {
+ it("lists a server family once, leaving its bold face to the Bold toggle", async () => {
const onChange = vi.fn(async () => null);
const input = renderPicker(onChange);
fireEvent.click(input);
- fireEvent.click(await screen.findByText("Acme Sans Bold"));
+ fireEvent.click(await screen.findByText("Acme Sans"));
+
+ await waitFor(() => expect(onChange).toHaveBeenCalledWith("Acme Sans"));
+ expect(screen.queryByText("Acme Sans Bold")).not.toBeInTheDocument();
+ });
+
+ it("lists each built-in family once", async () => {
+ const input = renderPicker(async () => null);
+
+ fireEvent.click(input);
+ await screen.findByText("Acme Sans");
+
+ const options = screen.getAllByRole("option").map((o) => o.textContent);
+ expect(options).toEqual(["Helvetica", "Times", "Courier", "Acme Sans"]);
+ });
+
+ it("lists a family that has only a bold face under its family name", async () => {
+ get.mockImplementation(async (url: string) => {
+ if (url !== SERVER_FONTS_URL) throw new Error(`unexpected ${url}`);
+ return {
+ data: {
+ families: [
+ {
+ family: "Acme Display Bold",
+ faces: [{ ...MANIFEST.families[0].faces[0], id: "3".repeat(64) }],
+ },
+ ],
+ },
+ };
+ });
+ const onChange = vi.fn(async () => null);
+ const input = renderPicker(onChange);
+
+ fireEvent.click(input);
+ fireEvent.click(await screen.findByText("Acme Display"));
await waitFor(() =>
- expect(onChange).toHaveBeenCalledWith("Acme Sans Bold"),
+ expect(onChange).toHaveBeenCalledWith("Acme Display Bold"),
);
});
@@ -117,7 +153,7 @@ describe("font picker server fonts", () => {
const input = renderPicker(onChange);
fireEvent.click(input);
- fireEvent.click(await screen.findByText("Acme Sans Bold"));
+ fireEvent.click(await screen.findByText("Acme Sans"));
await waitFor(() =>
expect(alert).toHaveBeenCalledWith({
@@ -147,7 +183,8 @@ describe("font picker server fonts", () => {
fireEvent.click(input);
- expect(await screen.findAllByText("Acme Sans Bold")).toHaveLength(1);
+ expect(await screen.findAllByText("Acme Sans")).toHaveLength(1);
+ expect(screen.queryByText("Acme Sans Bold")).not.toBeInTheDocument();
});
it("raises nothing when the font applies", async () => {
@@ -161,6 +198,50 @@ describe("font picker server fonts", () => {
expect(alert).not.toHaveBeenCalled();
});
+ it.each<FontPickFailure>([
+ "serverFontFailed",
+ "embedFailed",
+ "noGlyphs",
+ "missingGlyphs",
+ ])("names the text's own font again after a %s refusal", async (failure) => {
+ const onChange = vi.fn(async (): Promise<FontPickFailure> => failure);
+ const input = renderPicker(onChange);
+
+ fireEvent.click(input);
+ fireEvent.change(input, { target: { value: "Acme" } });
+ fireEvent.click(await screen.findByText("Acme Sans"));
+
+ await waitFor(() => expect(alert).toHaveBeenCalled());
+ await waitFor(() => expect(input).not.toBeDisabled());
+ expect(input).toHaveValue("Helvetica");
+ });
+
+ it("names the picked font once the text takes it", async () => {
+ function Controlled() {
+ const [value, setValue] = useState("Helvetica");
+ return (
+ <MantineProvider env="test">
+ <FontFamilySelect
+ value={value}
+ onChange={async (family) => {
+ setValue(family);
+ return null;
+ }}
+ />
+ </MantineProvider>
+ );
+ }
+ render(<Controlled />);
+ const input = screen.getByTestId("pdf-editor-font-family");
+
+ fireEvent.click(input);
+ fireEvent.change(input, { target: { value: "Acme" } });
+ fireEvent.click(await screen.findByText("Acme Sans"));
+
+ await waitFor(() => expect(input).not.toBeDisabled());
+ expect(input).toHaveValue("Acme Sans");
+ });
+
it("names the font a scan was matched to, not a document font", async () => {
render(
<MantineProvider env="test">
@@ -240,3 +321,54 @@ describe("font picker device fonts", () => {
).not.toBeInTheDocument();
});
});
+
+describe("font picker document font", () => {
+ beforeEach(() => {
+ Element.prototype.scrollIntoView = vi.fn();
+ });
+
+ it("offers the PDF's own font again once the text was changed away from it", async () => {
+ const onChange = vi.fn();
+ render(
+ <MantineProvider env="test">
+ <FontFamilySelect
+ value="Helvetica"
+ documentFontId="pdf:7:Garamond"
+ onChange={onChange}
+ />
+ </MantineProvider>,
+ );
+
+ fireEvent.click(screen.getByTestId("pdf-editor-font-family"));
+ fireEvent.click(await screen.findByText("Garamond"));
+
+ await waitFor(() =>
+ expect(onChange).toHaveBeenCalledWith("pdf:7:Garamond"),
+ );
+ });
+
+ it("lists the document's faces of the text's own family once", async () => {
+ render(
+ <MantineProvider env="test">
+ <FontFamilySelect
+ value="Calibri"
+ fontId="pdf:2:Calibri-Bold"
+ documentFamilies={documentFamilies([
+ "pdf:1:Calibri",
+ "pdf:2:Calibri-Bold",
+ "pdf:3:Calibri-Italic",
+ ])}
+ onChange={vi.fn()}
+ />
+ </MantineProvider>,
+ );
+ const input = screen.getByTestId("pdf-editor-font-family");
+ expect(input).toHaveValue("Calibri");
+
+ fireEvent.click(input);
+
+ expect(
+ await screen.findAllByRole("option", { name: "Calibri" }),
+ ).toHaveLength(1);
+ });
+});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/FontFamilySelect.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/FontFamilySelect.tsx
index 432a07542f..82e3a022fa 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/components/FontFamilySelect.tsx
+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/FontFamilySelect.tsx
@@ -2,25 +2,46 @@ import {
useCallback,
useEffect,
useMemo,
+ useRef,
useState,
useSyncExternalStore,
} from "react";
-import { Group, Loader, Select, Text, Tooltip } from "@mantine/core";
-import type { ComboboxData, ComboboxItemGroup } from "@mantine/core";
+import {
+ getParsedComboboxData,
+ Group,
+ Loader,
+ Select,
+ Text,
+ Tooltip,
+} from "@mantine/core";
+import type {
+ ComboboxData,
+ ComboboxItem,
+ ComboboxItemGroup,
+} from "@mantine/core";
import { useTranslation } from "react-i18next";
import { Button } from "@editor/ui/Button";
import { Icon } from "@editor/ui/Icon";
-import { alert } from "@editor/components/toast";
import { useServerFontsGroupLabel } from "@editor/tools/pdfTextEditor/hooks/useServerFontsGroupLabel";
import type { FontPickFailure } from "@editor/tools/pdfTextEditor/hooks/useSelectionActions";
+import { useFontChangeWarning } from "@editor/tools/pdfTextEditor/components/fontPickFailure";
+import {
+ familyOf,
+ isDocumentFontId,
+} from "@editor/tools/pdfTextEditor/util/fontFamily";
+import {
+ BUILT_IN_FAMILIES,
+ documentFamilies as groupDocumentFonts,
+ externalFamilies,
+ fontFamilyKey,
+ type FontFamilyEntry,
+} from "@editor/tools/pdfTextEditor/util/fontFaces";
import {
- familyOptions,
isLocalFontAccessSupported,
listLocalFontsIfGranted,
loadedLocalFonts,
retryLocalFonts,
subscribeLocalFonts,
- type FontFamilyOption,
} from "@editor/tools/pdfTextEditor/util/localFonts";
import {
loadedServerFonts,
@@ -28,60 +49,53 @@ import {
subscribeServerFonts,
} from "@editor/tools/pdfTextEditor/util/serverFonts";
-/** Base-14 families, renderable by every viewer without embedding. */
-export const BUILT_IN_FONT_FAMILIES: FontFamilyOption[] = [
- { value: "Helvetica", label: "Helvetica" },
- { value: "Helvetica-Bold", label: "Helvetica Bold" },
- { value: "Times-Roman", label: "Times Roman" },
- { value: "Times-Bold", label: "Times Bold" },
- { value: "Times-Italic", label: "Times Italic" },
- { value: "Courier", label: "Courier" },
- { value: "Courier-Bold", label: "Courier Bold" },
-];
-
-const BUILT_IN_NAMES = BUILT_IN_FONT_FAMILIES.map((option) => option.value);
+function itemOf(entry: FontFamilyEntry): ComboboxItem {
+ return { value: entry.value, label: entry.label };
+}
-const PICK_FAILURE_TEXT: Record<FontPickFailure, [string, string]> = {
- serverFontFailed: [
- "pdfTextEditor.fontPicker.serverFontFailed",
- "That server font could not be downloaded. The text was left unchanged.",
- ],
- embeddingForbidden: [
- "pdfTextEditor.fontPicker.embeddingForbidden",
- "This font's licence does not allow embedding it in a PDF. The text was left unchanged.",
- ],
- embedFailed: [
- "pdfTextEditor.fontPicker.embedFailed",
- "This font could not be embedded in the PDF. The text was left unchanged.",
- ],
- noGlyphs: [
- "pdfTextEditor.fontPicker.noGlyphs",
- "This font has no characters for the selected text. The text was left unchanged.",
- ],
-};
+function withoutKeys(
+ entries: FontFamilyEntry[],
+ taken: FontFamilyEntry[],
+): FontFamilyEntry[] {
+ const keys = new Set(taken.map((entry) => entry.key));
+ return entries.filter((entry) => !keys.has(entry.key));
+}
type DeviceFontNotice = "unavailable" | "none";
interface FontFamilySelectProps {
value: string | null;
+ /** The selection's fontId, which names the family its face belongs to; null for scanned text. */
+ fontId?: string | null;
+ /** The document's own fonts as families, offered for the selection's family and the one it can be restored to. */
+ documentFamilies?: FontFamilyEntry[];
/** Set for scanned text: `value` is the matched font (null while none is in force) and `label` the matcher's name for it. */
scanned?: { label?: string };
+ /** The document font the selection was changed from, offered so the text can go back to it. */
+ documentFontId?: string | null;
onChange: (family: string) => void | Promise<FontPickFailure | null>;
mixed?: boolean;
disabled?: boolean;
touch?: boolean;
+ /** False renders the list inside the toolbar's own popover rather than portalled out of it. */
+ withinPortal?: boolean;
}
/** Font picker. Device fonts are additive: no prompt until the user asks. */
export function FontFamilySelect({
value,
+ fontId = null,
+ documentFamilies = [],
scanned,
+ documentFontId = null,
onChange,
mixed = false,
disabled = false,
touch = false,
+ withinPortal = true,
}: FontFamilySelectProps) {
const { t } = useTranslation();
+ const warnAbout = useFontChangeWarning();
const [loading, setLoading] = useState(false);
const [applying, setApplying] = useState(false);
const [notice, setNotice] = useState<DeviceFontNotice | null>(null);
@@ -102,15 +116,15 @@ export function FontFamilySelect({
);
const serverOptions = useMemo(
- () => familyOptions(serverFonts, BUILT_IN_NAMES),
+ () => withoutKeys(externalFamilies(serverFonts), BUILT_IN_FAMILIES),
[serverFonts],
);
const deviceOptions = useMemo(
() =>
- familyOptions(localFonts, [
- ...BUILT_IN_NAMES,
- ...serverOptions.map((option) => option.value),
+ withoutKeys(externalFamilies(localFonts), [
+ ...BUILT_IN_FAMILIES,
+ ...serverOptions,
]),
[localFonts, serverOptions],
);
@@ -134,105 +148,166 @@ export function FontFamilySelect({
if (supported && !loadedLocalFonts()) void listLocalFontsIfGranted();
}, [supported]);
- const isKnown = useCallback(
- (family: string) =>
- [...BUILT_IN_FONT_FAMILIES, ...serverOptions, ...deviceOptions].some(
- (option) => option.value === family,
- ),
+ const listed = useMemo(
+ () => [...BUILT_IN_FAMILIES, ...serverOptions, ...deviceOptions],
[serverOptions, deviceOptions],
);
- // The run's own face when we hold no bytes for it. Shown so the user can see
- // what the text IS, listed disabled so picking it can't substitute Helvetica.
- const documentFamily = useMemo(
- () => (!mixed && value && !isKnown(value) ? value : null),
- [mixed, value, isKnown],
+ const familyHolding = useCallback(
+ (face: string | null) =>
+ face && isDocumentFontId(face)
+ ? (documentFamilies.find((entry) =>
+ entry.faces.some((f) => f.value === face),
+ ) ??
+ groupDocumentFonts([face])[0] ??
+ null)
+ : null,
+ [documentFamilies],
+ );
+
+ const restoreFamily = useMemo(
+ () => familyHolding(documentFontId),
+ [familyHolding, documentFontId],
+ );
+
+ const currentKey = useMemo(
+ () => (mixed || !value ? null : fontFamilyKey(fontId ?? value)),
+ [mixed, value, fontId],
+ );
+
+ // The run's own family when no other list names it, so the user can see what the text IS.
+ const currentDocumentFamily = useMemo(() => {
+ if (!currentKey || listed.some((entry) => entry.key === currentKey))
+ return null;
+ return (
+ familyHolding(fontId) ??
+ documentFamilies.find((entry) => entry.key === currentKey) ??
+ null
+ );
+ }, [currentKey, listed, familyHolding, fontId, documentFamilies]);
+
+ // Listed disabled so picking a face we hold no bytes for can't substitute Helvetica.
+ const unknownFamily = useMemo(
+ () =>
+ currentKey &&
+ value &&
+ !currentDocumentFamily &&
+ restoreFamily?.key !== currentKey &&
+ !listed.some((entry) => entry.key === currentKey)
+ ? value
+ : null,
+ [currentKey, value, currentDocumentFamily, restoreFamily, listed],
);
const data = useMemo<ComboboxData>(() => {
+ const documentItems: ComboboxItem[] = [];
+ if (restoreFamily) documentItems.push(itemOf(restoreFamily));
+ // The text is already in this family and the toggles move it between its faces, so the entry names it and does nothing.
+ if (currentDocumentFamily && currentDocumentFamily !== restoreFamily)
+ documentItems.push({ ...itemOf(currentDocumentFamily), disabled: true });
+ // Always list the current font: a Select whose value has no option filters by stale search text.
+ if (unknownFamily)
+ documentItems.push({
+ value: unknownFamily,
+ label: scanned?.label ?? unknownFamily,
+ disabled: true,
+ });
if (
serverOptions.length === 0 &&
deviceOptions.length === 0 &&
- !documentFamily
+ documentItems.length === 0
) {
- return BUILT_IN_FONT_FAMILIES;
+ return BUILT_IN_FAMILIES.map(itemOf);
}
const groups: ComboboxItemGroup[] = [];
- if (documentFamily) {
+ if (documentItems.length > 0) {
groups.push({
group: scanned
? t("pdfTextEditor.fontPicker.matchedGroup", "Matched font")
: t("pdfTextEditor.fontPicker.documentGroup", "Document font"),
- items: [
- {
- value: documentFamily,
- label: scanned?.label ?? documentFamily,
- disabled: true,
- },
- ],
+ items: documentItems,
});
}
groups.push({
group: t("pdfTextEditor.fontPicker.builtInGroup", "Built-in fonts"),
- items: BUILT_IN_FONT_FAMILIES,
+ items: BUILT_IN_FAMILIES.map(itemOf),
});
if (serverOptions.length > 0) {
groups.push({
group: serverGroupLabel,
- items: serverOptions,
+ items: serverOptions.map(itemOf),
});
}
if (deviceOptions.length > 0) {
groups.push({
group: t("pdfTextEditor.fontPicker.deviceGroup", "Device fonts"),
- items: deviceOptions,
+ items: deviceOptions.map(itemOf),
});
}
return groups;
}, [
serverOptions,
deviceOptions,
- documentFamily,
+ restoreFamily,
+ currentDocumentFamily,
+ unknownFamily,
scanned,
serverGroupLabel,
t,
]);
- const pickFailureText = useCallback(
- (failure: FontPickFailure): string => {
- const [key, fallback] = PICK_FAILURE_TEXT[failure];
- return t(key, fallback);
- },
- [t],
- );
+ // Mantine shows nothing for a value with no matching option; the document
+ // font is in `data` precisely so a recognised face still gets named.
+ const selected = useMemo(() => {
+ if (!currentKey) return null;
+ if (unknownFamily) return unknownFamily;
+ const candidates = [...listed, currentDocumentFamily, restoreFamily].filter(
+ (entry): entry is FontFamilyEntry => entry !== null,
+ );
+ const faceNames = fontId ? [fontId, familyOf(fontId)] : [value];
+ const entry =
+ candidates.find((candidate) =>
+ candidate.faces.some((face) => faceNames.includes(face.value)),
+ ) ?? candidates.find((candidate) => candidate.key === currentKey);
+ return entry?.value ?? null;
+ }, [
+ currentKey,
+ unknownFamily,
+ listed,
+ currentDocumentFamily,
+ restoreFamily,
+ fontId,
+ value,
+ ]);
+
+ const selectedLabel = useMemo(() => {
+ if (!selected) return "";
+ const option = getParsedComboboxData(data)
+ .flatMap((entry) => ("items" in entry ? entry.items : [entry]))
+ .find((item) => item.value === selected);
+ return option?.label ?? selected;
+ }, [data, selected]);
+
+ // Mantine only resyncs its search text when `value` changes, and blur never
+ // reaches an input disabled mid-apply, so a refused pick would stay named.
+ const [search, setSearch] = useState(selectedLabel);
+ const selectedLabelRef = useRef(selectedLabel);
+ selectedLabelRef.current = selectedLabel;
const applyFamily = useCallback(
async (family: string) => {
setNotice(null);
setApplying(true);
try {
- const failure = await onChange(family);
- if (failure) {
- alert({
- alertType: "warning",
- title: pickFailureText(failure),
- expandable: false,
- });
- }
+ await warnAbout(() => onChange(family));
} finally {
setApplying(false);
+ setSearch(selectedLabelRef.current);
}
},
- [onChange, pickFailureText],
+ [onChange, warnAbout],
);
- // Mantine shows nothing for a value with no matching option; the document
- // font is in `data` precisely so a recognised face still gets named.
- const selected = useMemo(() => {
- if (mixed || !value) return null;
- return isKnown(value) || documentFamily === value ? value : null;
- }, [mixed, value, isKnown, documentFamily]);
-
const placeholder = useMemo(() => {
if (mixed) return t("pdfTextEditor.fontPicker.mixed", "Mixed");
if (scanned)
@@ -252,8 +327,11 @@ export function FontFamilySelect({
w={touch ? undefined : 138}
style={touch ? { flex: 1, minWidth: 0 } : { flexShrink: 0 }}
searchable
+ comboboxProps={{ withinPortal }}
data={data}
value={selected}
+ searchValue={search}
+ onSearchChange={setSearch}
onChange={(next) => {
if (next) void applyFamily(next);
}}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/HelpOverlay.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/HelpOverlay.tsx
index 5efb004e9e..9e99ac8e7c 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/components/HelpOverlay.tsx
+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/HelpOverlay.tsx
@@ -1,6 +1,7 @@
-import { Fragment } from "react";
+import { Fragment, useMemo } from "react";
import { Modal, Stack, Text } from "@mantine/core";
import { useTranslation } from "react-i18next";
+import type { TFunction } from "i18next";
import HotkeyDisplay from "@editor/components/hotkeys/HotkeyDisplay";
import { isMacLike, type HotkeyBinding } from "@editor/utils/hotkeys";
import "@editor/tools/pdfTextEditor/components/HelpOverlay.css";
@@ -29,9 +30,8 @@ const mod = (
...extra,
});
-export function HelpOverlay({ opened, onClose }: HelpOverlayProps) {
- const { t } = useTranslation();
- const SHORTCUTS: Section[] = [
+function shortcutSections(t: TFunction): Section[] {
+ return [
{
heading: t("pdfTextEditor.help.editing.heading", "Editing"),
items: [
@@ -70,6 +70,13 @@ export function HelpOverlay({ opened, onClose }: HelpOverlayProps) {
"Group selected runs into one paragraph",
),
},
+ {
+ bindings: [mod("KeyB"), mod("KeyI")],
+ description: t(
+ "pdfTextEditor.help.editing.boldItalicDesc",
+ "Bold / Italic, for the selected words or the whole box",
+ ),
+ },
{
bindings: [mod("KeyD")],
description: t(
@@ -195,6 +202,12 @@ export function HelpOverlay({ opened, onClose }: HelpOverlayProps) {
],
},
];
+}
+
+export function HelpOverlay({ opened, onClose }: HelpOverlayProps) {
+ const { t } = useTranslation();
+ // The editor re-renders this on every keystroke, open or not.
+ const sections = useMemo(() => shortcutSections(t), [t]);
return (
<Modal
@@ -205,7 +218,7 @@ export function HelpOverlay({ opened, onClose }: HelpOverlayProps) {
data-testid="pdf-editor-help-overlay"
>
<Stack gap="lg">
- {SHORTCUTS.map((section) => (
+ {sections.map((section) => (
<section key={section.heading}>
<h3 className="pdf-editor-help__section-title">
{section.heading}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/ImageHandle.test.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/ImageHandle.test.tsx
new file mode 100644
index 0000000000..5b0675d332
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/ImageHandle.test.tsx
@@ -0,0 +1,90 @@
+import { render, screen } from "@testing-library/react";
+import { MantineProvider } from "@mantine/core";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { ImageHandle } from "@editor/tools/pdfTextEditor/components/ImageHandle";
+import { DisplayTransform } from "@editor/tools/pdfTextEditor/model/DisplayTransform";
+import type { ImageObjectSnapshot } from "@editor/tools/pdfTextEditor/types";
+
+const IMAGE: ImageObjectSnapshot = {
+ id: "p0-i0",
+ pageIndex: 0,
+ bounds: { x: 50, y: 50, width: 100, height: 100 },
+ matrix: { a: 100, b: 0, c: 0, d: 100, e: 50, f: 50 },
+};
+
+function mouse(type: string, clientX: number, clientY: number): MouseEvent {
+ return new MouseEvent(type, {
+ bubbles: true,
+ cancelable: true,
+ button: 0,
+ clientX,
+ clientY,
+ });
+}
+
+type ActFlag = { IS_REACT_ACT_ENVIRONMENT?: boolean };
+
+describe("ImageHandle drag", () => {
+ // Outside act React renders moves on its own schedule, as a browser does,
+ // instead of flushing each one before the next arrives.
+ let actEnvironment: boolean | undefined;
+ beforeEach(() => {
+ actEnvironment = (globalThis as ActFlag).IS_REACT_ACT_ENVIRONMENT;
+ (globalThis as ActFlag).IS_REACT_ACT_ENVIRONMENT = false;
+ // jsdom lays nothing out; react-rnd bounds the drag by these sizes.
+ vi.spyOn(HTMLElement.prototype, "offsetWidth", "get").mockImplementation(
+ function (this: HTMLElement) {
+ return parseFloat(this.style.width) || 0;
+ },
+ );
+ vi.spyOn(HTMLElement.prototype, "offsetHeight", "get").mockImplementation(
+ function (this: HTMLElement) {
+ return parseFloat(this.style.height) || 0;
+ },
+ );
+ });
+ afterEach(() => {
+ (globalThis as ActFlag).IS_REACT_ACT_ENVIRONMENT = actEnvironment;
+ vi.restoreAllMocks();
+ });
+
+ it("drops the image where the pointer let go when moves outpace rendering", async () => {
+ const onTransformCommit = vi.fn();
+ render(
+ <MantineProvider env="test">
+ <div style={{ position: "relative", width: 300, height: 300 }}>
+ <ImageHandle
+ image={IMAGE}
+ pageHeight={300}
+ transform={DisplayTransform.identity(300, 300)}
+ scale={1}
+ selected
+ onSelect={() => {}}
+ onTransformCommit={onTransformCommit}
+ />
+ </div>
+ </MantineProvider>,
+ );
+ const handle = screen.getByTestId("pdf-editor-image-p0-i0");
+ handle.dispatchEvent(mouse("mousedown", 100, 100));
+ await vi.waitFor(() =>
+ expect(handle.className).toContain("react-draggable-dragging"),
+ );
+ // Moves delivered back to back, with no render between them.
+ for (const x of [110, 120, 130, 140]) {
+ handle.ownerDocument.dispatchEvent(mouse("mousemove", x, 100));
+ }
+ handle.ownerDocument.dispatchEvent(mouse("mouseup", 140, 100));
+ await vi.waitFor(() =>
+ expect(handle.className).not.toContain("react-draggable-dragging"),
+ );
+
+ expect(onTransformCommit).toHaveBeenCalledTimes(1);
+ expect(onTransformCommit.mock.calls[0][0]).toMatchObject({
+ x: 90,
+ y: 50,
+ width: 100,
+ height: 100,
+ });
+ });
+});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/ImageHandle.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/ImageHandle.tsx
index dd2da85d6d..5725c1da0d 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/components/ImageHandle.tsx
+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/ImageHandle.tsx
@@ -1,6 +1,6 @@
-import { useState } from "react";
+import { useEffect, useRef, useState } from "react";
import React from "react";
-import { Rnd } from "react-rnd";
+import { Rnd, type RndDragEvent } from "react-rnd";
import { Tooltip } from "@mantine/core";
import { useTranslation } from "react-i18next";
import { Icon } from "@editor/ui/Icon";
@@ -10,6 +10,78 @@ import type {
PageRect,
} from "@editor/tools/pdfTextEditor/types";
import type { DisplayTransform } from "@editor/tools/pdfTextEditor/model/DisplayTransform";
+import {
+ imageBoundsForVisible,
+ visibleImageBounds,
+} from "@editor/tools/pdfTextEditor/util/imageClip";
+import type { ImagePixels } from "@editor/tools/pdfTextEditor/util/imagePixels";
+
+function ImageGhost({
+ pixels,
+ style,
+}: {
+ pixels: ImagePixels;
+ style: React.CSSProperties;
+}) {
+ const ref = useRef<HTMLCanvasElement | null>(null);
+ useEffect(() => {
+ const canvas = ref.current;
+ const context = canvas?.getContext("2d");
+ if (!canvas || !context) return;
+ canvas.width = pixels.width;
+ canvas.height = pixels.height;
+ context.putImageData(
+ new ImageData(
+ new Uint8ClampedArray(pixels.rgba),
+ pixels.width,
+ pixels.height,
+ ),
+ 0,
+ 0,
+ );
+ }, [pixels]);
+ return (
+ <canvas
+ ref={ref}
+ data-testid="pdf-editor-image-ghost"
+ style={{ position: "absolute", pointerEvents: "none", ...style }}
+ />
+ );
+}
+
+interface DragOrigin {
+ pointerX: number;
+ pointerY: number;
+ left: number;
+ top: number;
+ maxLeft: number;
+ maxTop: number;
+}
+
+function pointerOf(e: RndDragEvent): { x: number; y: number } | null {
+ if ("changedTouches" in e) {
+ const touch = e.changedTouches[0];
+ return touch ? { x: touch.clientX, y: touch.clientY } : null;
+ }
+ return { x: e.clientX, y: e.clientY };
+}
+
+// react-draggable adds each move to the position it last rendered, so moves
+// that arrive before React commits the one before them are lost and the box
+// trails the pointer. Firefox and WebKit deliver several per frame, so the
+// box is placed from the pointer's travel since the press instead.
+function draggedTo(
+ origin: DragOrigin | null,
+ e: RndDragEvent,
+): { x: number; y: number } | null {
+ const pointer = pointerOf(e);
+ if (!origin || !pointer) return null;
+ const clamp = (v: number, max: number) => Math.min(Math.max(v, 0), max);
+ return {
+ x: clamp(origin.left + pointer.x - origin.pointerX, origin.maxLeft),
+ y: clamp(origin.top + pointer.y - origin.pointerY, origin.maxTop),
+ };
+}
interface ImageHandleProps {
image: ImageObjectSnapshot;
@@ -22,6 +94,20 @@ interface ImageHandleProps {
onTransformCommit: (next: PageRect) => void;
/** Why the image needs the user's attention, if it does. */
attention?: ImageAttention | null;
+ /**
+ * The image's pixels as the page draws them, filling its bounds, so a drag
+ * carries the picture instead of an empty frame. Null when unreadable.
+ */
+ readPixels?: () => ImagePixels | null;
+ /** Paints the page as it is without the image, for the length of a gesture. */
+ onLift?: () => void;
+ /**
+ * Ends the gesture onLift began. Returns true when the page will repaint
+ * with the change; otherwise the image is already painted back.
+ */
+ onSettle?: (committed: boolean) => boolean;
+ /** The page revision the canvas shows. */
+ pageRevision?: number;
}
/** Draggable + resizable affordance for an image object. */
@@ -34,6 +120,10 @@ export function ImageHandle({
onSelect,
onTransformCommit,
attention = null,
+ readPixels,
+ onLift,
+ onSettle,
+ pageRevision = -1,
}: ImageHandleProps) {
const { t } = useTranslation();
const [dragging, setDragging] = useState(false);
@@ -41,24 +131,66 @@ export function ImageHandle({
// Shift during a corner drag keeps the proportions, as in Acrobat. Read
// from every resize event, so pressing or releasing it mid-drag applies.
const [keepRatio, setKeepRatio] = useState(false);
+ const [ghost, setGhost] = useState<ImagePixels | null>(null);
+ const dragOriginRef = useRef<DragOrigin | null>(null);
+ const [dragPosition, setDragPosition] = useState<{
+ x: number;
+ y: number;
+ } | null>(null);
+ const liftedRef = useRef(false);
+ const cancelledRef = useRef(false);
+ const escapeRef = useRef<((e: KeyboardEvent) => void) | null>(null);
+ // The painted revision a committed gesture waits to see replaced: the
+ // picture stays on the moving box until the page draws it in place.
+ const awaitingPaintRef = useRef<number | null>(null);
+ const settleRef = useRef(onSettle);
+ settleRef.current = onSettle;
+
+ useEffect(() => {
+ if (awaitingPaintRef.current === null) return;
+ if (pageRevision === awaitingPaintRef.current) return;
+ awaitingPaintRef.current = null;
+ setGhost(null);
+ }, [pageRevision]);
+
+ useEffect(
+ () => () => {
+ if (escapeRef.current)
+ window.removeEventListener("keydown", escapeRef.current);
+ if (liftedRef.current) settleRef.current?.(false);
+ },
+ [],
+ );
+
+ // A raw-PDF AABB as CSS px on the page: 4 corners through the display
+ // transform, then min/max.
+ function cssRect(r: PageRect) {
+ const corners = [
+ transform.apply(r.x, r.y),
+ transform.apply(r.x + r.width, r.y),
+ transform.apply(r.x, r.y + r.height),
+ transform.apply(r.x + r.width, r.y + r.height),
+ ];
+ const minX = Math.min(...corners.map((c) => c.x));
+ const maxX = Math.max(...corners.map((c) => c.x));
+ const minY = Math.min(...corners.map((c) => c.y));
+ const maxY = Math.max(...corners.map((c) => c.y));
+ return {
+ left: minX * scale,
+ top: (pageHeight - maxY) * scale,
+ width: (maxX - minX) * scale,
+ height: (maxY - minY) * scale,
+ };
+ }
- // Map the image's raw-PDF AABB into display-PDF space (4 corners through the
- // transform, then min/max), then to CSS px.
- const b = image.bounds;
- const dispCorners = [
- transform.apply(b.x, b.y),
- transform.apply(b.x + b.width, b.y),
- transform.apply(b.x, b.y + b.height),
- transform.apply(b.x + b.width, b.y + b.height),
- ];
- const dispMinX = Math.min(...dispCorners.map((c) => c.x));
- const dispMaxX = Math.max(...dispCorners.map((c) => c.x));
- const dispMinY = Math.min(...dispCorners.map((c) => c.y));
- const dispMaxY = Math.max(...dispCorners.map((c) => c.y));
- const left = dispMinX * scale;
- const top = (pageHeight - dispMaxY) * scale;
- const width = Math.max(8, (dispMaxX - dispMinX) * scale);
- const height = Math.max(8, (dispMaxY - dispMinY) * scale);
+ // The box is what shows: a clipped image's hidden part is not the user's to
+ // grab.
+ const b = visibleImageBounds(image);
+ const shown = cssRect(b);
+ const left = shown.left;
+ const top = shown.top;
+ const width = Math.max(8, shown.width);
+ const height = Math.max(8, shown.height);
function cssToPdfBounds(
leftCss: number,
@@ -89,13 +221,80 @@ export function ImageHandle({
return { x: maxX - w, y: maxY - h, width: w, height: h };
}
+ // The whole image placed in the box of what shows, in percent so it keeps
+ // its place while a resize stretches the box. The pixels are upright in raw
+ // page space, so on a quarter-turned page they are laid out unturned about
+ // the image's centre and then turned with the page.
+ const full = cssRect(image.bounds);
+ const turned = transform.rotate % 2 === 1;
+ const ghostWidth = turned ? full.height : full.width;
+ const ghostHeight = turned ? full.width : full.height;
+ const percent = (part: number, whole: number) =>
+ `${(part / Math.max(whole, 1e-6)) * 100}%`;
+ const ghostStyle: React.CSSProperties = {
+ left: percent(
+ full.left + full.width / 2 - ghostWidth / 2 - shown.left,
+ shown.width,
+ ),
+ top: percent(
+ full.top + full.height / 2 - ghostHeight / 2 - shown.top,
+ shown.height,
+ ),
+ width: percent(ghostWidth, shown.width),
+ height: percent(ghostHeight, shown.height),
+ transform: transform.rotate
+ ? `rotate(${transform.rotate * 90}deg)`
+ : undefined,
+ };
+
+ // Shows the picture on the moving box and the page without it beneath.
+ // Without readable pixels nothing is lifted: hiding the image behind an
+ // empty frame would lose it from view.
+ function startLift(): void {
+ awaitingPaintRef.current = null;
+ cancelledRef.current = false;
+ const pixels = readPixels?.() ?? null;
+ setGhost(pixels);
+ if (!pixels || liftedRef.current) return;
+ liftedRef.current = true;
+ onLift?.();
+ const cancelOnEscape = (e: KeyboardEvent) => {
+ if (e.key !== "Escape" || !liftedRef.current) return;
+ cancelledRef.current = true;
+ endLift(false);
+ };
+ escapeRef.current = cancelOnEscape;
+ window.addEventListener("keydown", cancelOnEscape);
+ }
+
+ function endLift(committed: boolean): void {
+ if (escapeRef.current)
+ window.removeEventListener("keydown", escapeRef.current);
+ escapeRef.current = null;
+ const lifted = liftedRef.current;
+ liftedRef.current = false;
+ const repaints = lifted && (onSettle?.(committed) ?? false);
+ if (repaints) awaitingPaintRef.current = pageRevision;
+ else setGhost(null);
+ }
+
+ // Commits a gesture's result unless Escape cancelled it.
+ function finishGesture(next: PageRect | null): void {
+ if (cancelledRef.current) {
+ cancelledRef.current = false;
+ return;
+ }
+ if (next) onTransformCommit(imageBoundsForVisible(image, next));
+ endLift(next !== null);
+ }
+
// Locked images are inert: no select, drag, or resize.
const locked = image.locked === true;
return (
<Rnd
size={{ width, height }}
- position={{ x: left, y: top }}
+ position={dragPosition ?? { x: left, y: top }}
disableDragging={locked}
enableResizing={
!locked && (selected || hovered)
@@ -108,34 +307,54 @@ export function ImageHandle({
: false
}
bounds="parent"
- onDragStart={() => {
+ onDragStart={(e, data) => {
+ const pointer = pointerOf(e);
+ const parent = data.node.parentElement;
+ dragOriginRef.current =
+ pointer && parent
+ ? {
+ pointerX: pointer.x,
+ pointerY: pointer.y,
+ left,
+ top,
+ maxLeft: Math.max(0, parent.offsetWidth - width),
+ maxTop: Math.max(0, parent.offsetHeight - height),
+ }
+ : null;
setDragging(true);
+ startLift();
onSelect();
}}
+ onDrag={(e) => {
+ const at = draggedTo(dragOriginRef.current, e);
+ if (at) setDragPosition(at);
+ }}
lockAspectRatio={keepRatio}
onResizeStart={(e) => {
setKeepRatio(e.shiftKey);
if (locked) return;
+ startLift();
onSelect();
}}
onResize={(e) => setKeepRatio(e.shiftKey)}
- onDragStop={(_, data) => {
+ onDragStop={(e, data) => {
+ const at = draggedTo(dragOriginRef.current, e) ?? data;
+ dragOriginRef.current = null;
+ setDragPosition(null);
setDragging(false);
// Rnd fixes its bounds when the drag starts, so a scroll mid-drag
// (Safari scrolls the viewer when the pointer leaves it) can drop the
// image off the page, where PDFium crops it.
// An image larger than the page cannot fit, so it is left where it is.
const page = data.node.parentElement;
- const clamp = (at: number, room: number) =>
- room >= 0 ? Math.min(Math.max(0, at), room) : at;
- const x = page ? clamp(data.x, page.clientWidth - width) : data.x;
- const y = page ? clamp(data.y, page.clientHeight - height) : data.y;
+ const clamp = (v: number, room: number) =>
+ room >= 0 ? Math.min(Math.max(0, v), room) : v;
+ const x = page ? clamp(at.x, page.clientWidth - width) : at.x;
+ const y = page ? clamp(at.y, page.clientHeight - height) : at.y;
const next = cssToPdfBounds(x, y, width, height);
const moved =
- Math.abs(next.x - image.bounds.x) > 0.01 ||
- Math.abs(next.y - image.bounds.y) > 0.01;
- if (!moved) return;
- onTransformCommit(next);
+ Math.abs(next.x - b.x) > 0.01 || Math.abs(next.y - b.y) > 0.01;
+ finishGesture(moved ? next : null);
}}
onResizeStop={(_e, _dir, ref, _delta, position) => {
setKeepRatio(false);
@@ -146,12 +365,11 @@ export function ImageHandle({
ref.offsetHeight,
);
const changed =
- Math.abs(next.x - image.bounds.x) > 0.01 ||
- Math.abs(next.y - image.bounds.y) > 0.01 ||
- Math.abs(next.width - image.bounds.width) > 0.01 ||
- Math.abs(next.height - image.bounds.height) > 0.01;
- if (!changed) return;
- onTransformCommit(next);
+ Math.abs(next.x - b.x) > 0.01 ||
+ Math.abs(next.y - b.y) > 0.01 ||
+ Math.abs(next.width - b.width) > 0.01 ||
+ Math.abs(next.height - b.height) > 0.01;
+ finishGesture(changed ? next : null);
}}
style={{
outline: selected
@@ -159,7 +377,7 @@ export function ImageHandle({
: hovered || dragging
? "1px dashed rgba(0,0,0,0.45)"
: "none",
- background:
+ backgroundColor:
selected || dragging ? "rgba(44,123,229,0.08)" : "transparent",
cursor: locked ? "default" : "move",
// No explicit zIndex - text overlays paint on top via DOM order.
@@ -186,6 +404,11 @@ export function ImageHandle({
data-testid={`pdf-editor-image-${image.id}`}
data-locked={locked ? "true" : undefined}
>
+ {ghost && (
+ <div style={{ position: "absolute", inset: 0, overflow: "hidden" }}>
+ <ImageGhost pixels={ghost} style={ghostStyle} />
+ </div>
+ )}
{attention && (
<Tooltip
label={
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/MobileActionBar.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/MobileActionBar.tsx
index ebeb4fc447..22eaee8a54 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/components/MobileActionBar.tsx
+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/MobileActionBar.tsx
@@ -129,16 +129,14 @@ export function MobileActionBar({
icon="type"
label={t("pdfTextEditor.mobile.addText", "Text")}
pressed={addTextArmed}
- onClick={() => store.setMode(addTextArmed ? "select" : "addText")}
+ onClick={() => store.toggleMode("addText")}
data-testid="pdf-editor-add-text"
/>
<BarButton
icon="table"
label={t("pdfTextEditor.sidebar.table", "Table")}
pressed={addTableArmed}
- onClick={() =>
- store.setMode(addTableArmed ? "select" : "addTable")
- }
+ onClick={() => store.toggleMode("addTable")}
data-testid="pdf-editor-add-table"
/>
<BarButton
@@ -152,7 +150,7 @@ export function MobileActionBar({
icon="search"
label={t("pdfTextEditor.mobile.find", "Find")}
pressed={findOpen}
- onClick={() => store.setFindOpen(!findOpen)}
+ onClick={() => store.toggleFindOpen()}
data-testid="pdf-editor-open-find"
/>
<ZoomMenu />
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/MobileEditorSheets.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/MobileEditorSheets.tsx
index 8aa3749194..1e8d880590 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/components/MobileEditorSheets.tsx
+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/MobileEditorSheets.tsx
@@ -1,4 +1,4 @@
-import { useEffect, type ComponentProps } from "react";
+import { memo, useEffect, type ComponentProps } from "react";
import { Drawer } from "@mantine/core";
import { useTranslation } from "react-i18next";
import { EditorSidebar } from "@editor/tools/pdfTextEditor/components/EditorSidebar";
@@ -19,7 +19,9 @@ const SHEET_STYLES = {
header: { paddingBottom: "0.5rem" },
} as const;
-export function MobileEditorSheets(props: Omit<SidebarProps, "initialTab">) {
+export const MobileEditorSheets = memo(function MobileEditorSheets(
+ props: Omit<SidebarProps, "initialTab">,
+) {
const { t } = useTranslation();
const { store, state, selection } = props;
const controller = useToolbarController(store, state, selection);
@@ -75,4 +77,4 @@ export function MobileEditorSheets(props: Omit<SidebarProps, "initialTab">) {
</Drawer>
</>
);
-}
+});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/PageView.test.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/PageView.test.tsx
new file mode 100644
index 0000000000..fb8374844e
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/PageView.test.tsx
@@ -0,0 +1,116 @@
+import { render, waitFor } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import {
+ pageSnapshot,
+ stubDocument,
+ stubbedPageView,
+ VisibleObserver,
+} from "@editor/tools/pdfTextEditor/components/pageViewTestSupport";
+import { Page } from "@editor/tools/pdfTextEditor/model/Page";
+import { PdfiumPageRenderer } from "@editor/tools/pdfTextEditor/pdfium/PdfiumPageRenderer";
+import type { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
+
+vi.mock("@editor/tools/pdfTextEditor/components/TableOverlay", () => ({
+ TableOverlay: () => null,
+}));
+
+function view(live: Page, document: EditorDocument) {
+ return stubbedPageView(document, pageSnapshot(live));
+}
+
+function editArea(live: Page): void {
+ const from = live.revision;
+ live.markDirty();
+ live.noteRepaintArea(from, live.revision, {
+ x: 10,
+ y: 10,
+ width: 20,
+ height: 20,
+ });
+}
+
+describe("PageView partial redraw", () => {
+ const originalObserver = globalThis.IntersectionObserver;
+
+ beforeEach(() => {
+ globalThis.IntersectionObserver =
+ VisibleObserver as unknown as typeof IntersectionObserver;
+ vi.spyOn(HTMLCanvasElement.prototype, "getContext").mockReturnValue(null);
+ });
+
+ afterEach(() => {
+ globalThis.IntersectionObserver = originalObserver;
+ // restoreAllMocks would also strip the setup's matchMedia mock the next render needs.
+ for (const spy of [
+ HTMLCanvasElement.prototype.getContext,
+ PdfiumPageRenderer.render,
+ PdfiumPageRenderer.renderArea,
+ ])
+ if (vi.isMockFunction(spy)) spy.mockRestore();
+ });
+
+ it("draws the whole page once when redrawing the edited area fails", async () => {
+ const live = new Page({ index: 0, pagePtr: 1, width: 600, height: 800 });
+ const document = stubDocument(live);
+ const renderPage = vi
+ .spyOn(PdfiumPageRenderer, "render")
+ .mockImplementation(
+ async (_doc, page, scale) =>
+ PdfiumPageRenderer.rasterSize(
+ page.width,
+ page.height,
+ scale,
+ ) as ImageData,
+ );
+ const renderArea = vi
+ .spyOn(PdfiumPageRenderer, "renderArea")
+ .mockRejectedValue(new Error("out of memory"));
+
+ const { rerender } = render(view(live, document));
+ await waitFor(() => expect(renderPage).toHaveBeenCalledTimes(1));
+
+ editArea(live);
+ rerender(view(live, document));
+
+ await waitFor(() => expect(renderPage).toHaveBeenCalledTimes(2));
+ expect(renderArea).toHaveBeenCalledTimes(1);
+ });
+
+ it("takes the error away once an edit's area redraws", async () => {
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
+ const live = new Page({ index: 0, pagePtr: 1, width: 600, height: 800 });
+ const document = stubDocument(live);
+ const size = (scale: number) =>
+ PdfiumPageRenderer.rasterSize(
+ live.width,
+ live.height,
+ scale,
+ ) as ImageData;
+ const renderPage = vi
+ .spyOn(PdfiumPageRenderer, "render")
+ .mockImplementationOnce(async (_doc, _page, scale) => size(scale))
+ .mockRejectedValue(new Error("out of memory"));
+ const renderArea = vi
+ .spyOn(PdfiumPageRenderer, "renderArea")
+ .mockImplementation(
+ async (_doc, _page, _scale, area) => area as unknown as ImageData,
+ );
+
+ const { rerender, queryByTestId } = render(view(live, document));
+ await waitFor(() => expect(renderPage).toHaveBeenCalledTimes(1));
+ editArea(live);
+ rerender(view(live, document));
+ await waitFor(() =>
+ expect(queryByTestId("pdf-editor-page-0-error")).not.toBeNull(),
+ );
+
+ editArea(live);
+ rerender(view(live, document));
+
+ await waitFor(() => expect(renderArea).toHaveBeenCalledTimes(2));
+ await waitFor(() =>
+ expect(queryByTestId("pdf-editor-page-0-error")).toBeNull(),
+ );
+ warn.mockRestore();
+ });
+});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/PageView.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/PageView.tsx
index f4b7432f4b..6b3fe76205 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/components/PageView.tsx
+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/PageView.tsx
@@ -1,15 +1,23 @@
import { memo, useEffect, useMemo, useRef, useState } from "react";
+import type { FindMatch } from "@editor/tools/pdfTextEditor/store/Selection";
import { Box } from "@mantine/core";
import { useTranslation } from "react-i18next";
import { Button } from "@editor/ui/Button";
import { PdfiumPageRenderer } from "@editor/tools/pdfTextEditor/pdfium/PdfiumPageRenderer";
+import type { Page } from "@editor/tools/pdfTextEditor/model/Page";
import type { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
import type {
+ PageRect,
PageSnapshot,
TextRange,
+ TextRunSnapshot,
} from "@editor/tools/pdfTextEditor/types";
import { TextRunOverlay } from "@editor/tools/pdfTextEditor/components/TextRunOverlay";
-import { isScanRun } from "@editor/tools/pdfTextEditor/commands/scanTextEdit";
+import { canResizeRun } from "@editor/tools/pdfTextEditor/commands/resizeRun";
+import {
+ growEdges,
+ type GrowEdge,
+} from "@editor/tools/pdfTextEditor/util/growEdge";
import { TableOverlay } from "@editor/tools/pdfTextEditor/components/TableOverlay";
import { ACCESSIBILITY_EDITING } from "@editor/constants/featureFlags";
import {
@@ -17,6 +25,8 @@ import {
type ImageAttention,
} from "@editor/tools/pdfTextEditor/util/imageAccessibility";
import { ImageHandle } from "@editor/tools/pdfTextEditor/components/ImageHandle";
+import { readShownImagePixels } from "@editor/tools/pdfTextEditor/util/imagePixels";
+import { visibleImageBounds } from "@editor/tools/pdfTextEditor/util/imageClip";
import type { EditorStore } from "@editor/tools/pdfTextEditor/store/EditorStore";
import { ShapeHandle } from "@editor/tools/pdfTextEditor/components/ShapeHandle";
import { AnnotationOutline } from "@editor/tools/pdfTextEditor/components/AnnotationOutline";
@@ -43,10 +53,10 @@ interface PageViewProps {
selectedRunIds: string[];
selectedImageIds: string[];
selectedShapeIds: string[];
+ /** The find-bar occurrence on show. */
+ findMatch?: FindMatch | null;
/** The AnnotationBox id of the selected form field widget. */
selectedFormFieldId?: string | null;
- /** Run id currently highlighted by the find-bar (yellow). */
- highlightedRunId?: string | null;
onSelectRun: (runId: string, shiftKey: boolean) => void;
onSelectImage: (imageId: string) => void;
onSelectShape: (shapeId: string, extend: boolean) => void;
@@ -71,8 +81,19 @@ interface PageViewProps {
dx: number,
dy: number,
) => void;
- /** Wrap-mode reflow request; maxWidthPt in PDF points. */
- onWrapRun?: (pageIndex: number, runId: string, maxWidthPt: number) => void;
+ /**
+ * Wrap-mode reflow request; maxWidthPt in PDF points. Returns the run's text
+ * after the wrap, or null when it was refused because its new lines had
+ * nowhere clear to go.
+ */
+ onWrapRun?: (
+ pageIndex: number,
+ runId: string,
+ maxWidthPt: number,
+ keepClearBelow?: boolean,
+ ) => string | null | void;
+ /** The run with the engine's pen positions for its current text, read now. */
+ onMeasureRun?: (pageIndex: number, runId: string) => TextRunSnapshot | null;
/** Right-edge drag to a new box width; widthPt in PDF points. */
onResizeRun?: (pageIndex: number, runId: string, widthPt: number) => void;
/** Fires when the user clicks on a non-text area of the page. */
@@ -115,8 +136,8 @@ export const PageView = memo(function PageView({
selectedRunIds,
selectedImageIds,
selectedShapeIds,
+ findMatch,
selectedFormFieldId = null,
- highlightedRunId,
onSelectRun,
onSelectImage,
onSelectShape,
@@ -127,6 +148,7 @@ export const PageView = memo(function PageView({
selectedTextRange,
onMoveRun,
onWrapRun,
+ onMeasureRun,
onResizeRun,
onPageClick,
onTransformImage,
@@ -144,6 +166,11 @@ export const PageView = memo(function PageView({
}
return out;
}, [document, page]);
+ const runGrowEdges = useMemo(
+ () =>
+ widthMode === "grow" ? growEdges(page.runs) : new Map<string, GrowEdge>(),
+ [page.runs, widthMode],
+ );
const canvasRef = useRef<HTMLCanvasElement | null>(null);
const containerRef = useRef<HTMLDivElement | null>(null);
// `raster` is the CSS layout size; the bitmap itself renders at deviceScale
@@ -165,8 +192,11 @@ export const PageView = memo(function PageView({
// Per document: a newly opened file reuses this view for its page of the same index.
const visibleDocRef = useRef<typeof document | null>(null);
const firstRenderedDocRef = useRef<typeof document | null>(null);
+ const [gripLayer, setGripLayer] = useState<HTMLDivElement | null>(null);
const firstPaintedDocRef = useRef<typeof document | null>(null);
const [paintedRevision, setPaintedRevision] = useState(-1);
+ // Read by the render effect, which must not re-run when it changes.
+ const paintedRevisionRef = useRef(-1);
const [renderError, setRenderError] = useState<string | null>(null);
const [retryToken, setRetryToken] = useState(0);
// True when this page is within ~one viewport of the visible area.
@@ -227,44 +257,81 @@ export const PageView = memo(function PageView({
return;
}
let cancelled = false;
+ let settleTimer = 0;
if (!canvas) return;
- setRenderError(null);
- PdfiumPageRenderer.render(
- document,
- document.page(page.pageIndex),
+ const live = document.page(page.pageIndex);
+ const revision = page.revision;
+ const markPainted = () => {
+ paintedRevisionRef.current = revision;
+ setPaintedRevision(revision);
+ };
+ const noteFirstRender = () => {
+ if (firstRenderedDocRef.current === document) return;
+ firstRenderedDocRef.current = document;
+ onFirstRendered?.(page.pageIndex);
+ };
+ const noteFirstPaint = () => {
+ if (firstPaintedDocRef.current === document) return;
+ firstPaintedDocRef.current = document;
+ onFirstPainted?.();
+ };
+ const paintFull = () => {
+ PdfiumPageRenderer.render(document, live, deviceScale)
+ .then((image) => {
+ if (cancelled || !canvasRef.current) return;
+ canvas.width = image.width;
+ canvas.height = image.height;
+ const ctx = canvas.getContext("2d");
+ if (ctx) ctx.putImageData(image, 0, 0);
+ setRenderError(null);
+ markPainted();
+ noteFirstRender();
+ noteFirstPaint();
+ })
+ .catch((err: unknown) => {
+ if (cancelled) return;
+ const msg =
+ err instanceof Error ? `${err.name}: ${err.message}` : String(err);
+ console.warn(
+ `[pdf-editor] page ${page.pageIndex} render failed`,
+ err,
+ );
+ setRenderError(msg);
+ // Flip the first-rendered flag on error too, or the loading overlay never dismisses.
+ noteFirstRender();
+ });
+ };
+ const area = changedPixels(
+ live,
deviceScale,
- )
- .then((image) => {
- if (cancelled || !canvasRef.current) return;
- canvas.width = image.width;
- canvas.height = image.height;
- const ctx = canvas.getContext("2d");
- if (ctx) ctx.putImageData(image, 0, 0);
- setPaintedRevision(page.revision);
- if (firstRenderedDocRef.current !== document) {
- firstRenderedDocRef.current = document;
- onFirstRendered?.(page.pageIndex);
- }
- if (firstPaintedDocRef.current !== document) {
- firstPaintedDocRef.current = document;
- onFirstPainted?.();
- }
- })
- .catch((err: unknown) => {
- if (cancelled) return;
- const msg =
- err instanceof Error ? `${err.name}: ${err.message}` : String(err);
- console.warn(`[pdf-editor] page ${page.pageIndex} render failed`, err);
- setRenderError(msg);
- // Flip the first-rendered flag on error too, so the loading
- // overlay dismisses instead of leaving the user on a spinner.
- if (firstRenderedDocRef.current !== document) {
- firstRenderedDocRef.current = document;
- onFirstRendered?.(page.pageIndex);
- }
- });
+ canvas,
+ paintedRevisionRef.current,
+ );
+ if (area) {
+ // Redrawing the whole page, scan image and all, is most of what a keystroke costs.
+ PdfiumPageRenderer.renderArea(document, live, deviceScale, area)
+ .then((image) => {
+ if (cancelled || !canvasRef.current) return;
+ canvas.getContext("2d")?.putImageData(image, area.x, area.y);
+ setRenderError(null);
+ markPainted();
+ settleTimer = window.setTimeout(
+ paintFull,
+ FULL_REDRAW_AFTER_TYPING_MS,
+ );
+ })
+ .catch(() => {
+ if (cancelled) return;
+ paintedRevisionRef.current = -1;
+ setRetryToken((n) => n + 1);
+ });
+ } else {
+ setRenderError(null);
+ paintFull();
+ }
return () => {
cancelled = true;
+ window.clearTimeout(settleTimer);
};
}, [
nearViewport,
@@ -277,6 +344,60 @@ export const PageView = memo(function PageView({
retryToken,
]);
+ // A lifted image: the canvas pixels it covered, put back if the gesture is
+ // cancelled, and the revision a committed gesture must move the page past.
+ const liftRef = useRef<{
+ area: PageRect;
+ covered: ImageData;
+ revision: number;
+ } | null>(null);
+
+ // Paints the page under image `imageId` as it would be without it, so a
+ // drag shows only the moving picture. One area render per gesture.
+ function liftImage(imageId: string): void {
+ const canvas = canvasRef.current;
+ const ctx = canvas?.getContext("2d");
+ const live = document.page(page.pageIndex);
+ const image = live.findImage(imageId);
+ if (!canvas || !ctx || !image || liftRef.current) return;
+ if (!showsWholePage(canvas, live, deviceScale)) return;
+ const area = PdfiumPageRenderer.pixelsCovering(
+ live,
+ deviceScale,
+ visibleImageBounds(image),
+ );
+ if (!area) return;
+ const without = PdfiumPageRenderer.renderAreaWithout(
+ document,
+ live,
+ deviceScale,
+ area,
+ image.pdfiumObjPtr,
+ );
+ if (!without) return;
+ liftRef.current = {
+ area,
+ covered: ctx.getImageData(area.x, area.y, area.width, area.height),
+ revision: live.revision,
+ };
+ ctx.putImageData(without, area.x, area.y);
+ }
+
+ // Ends a lift. Returns true when the page has changed and will repaint;
+ // otherwise the image is painted back where it was.
+ function settleImage(committed: boolean): boolean {
+ const lift = liftRef.current;
+ liftRef.current = null;
+ if (!lift) return false;
+ const repaints =
+ committed && document.page(page.pageIndex).revision !== lift.revision;
+ if (!repaints)
+ canvasRef.current
+ ?.getContext("2d")
+ ?.putImageData(lift.covered, lift.area.x, lift.area.y);
+ return repaints;
+ }
+
return (
<Box
// Fills the viewer's page box and stays transparent until painted, so
@@ -400,6 +521,12 @@ export const PageView = memo(function PageView({
onTransformImage?.(page.pageIndex, image.id, next)
}
attention={imageAttentions.get(image.id) ?? null}
+ readPixels={() =>
+ readShownImagePixels(store, page.pageIndex, image.id)
+ }
+ onLift={() => liftImage(image.id)}
+ onSettle={settleImage}
+ pageRevision={paintedRevision}
/>
))}
{/* Grid + empty-cell editors sit below the run overlays so filled
@@ -409,7 +536,11 @@ export const PageView = memo(function PageView({
transform={transform}
scale={cssScale}
store={store}
+ selectedRunIds={selectedRunIds}
/>
+ {/* Every run's move/width grips, after the objects beneath the text and
+ before all runs, so a grip never takes a click aimed at any run. */}
+ <div ref={setGripLayer} style={{ display: "contents" }} />
{page.runs.map((run) => (
<TextRunOverlay
key={run.id}
@@ -419,27 +550,30 @@ export const PageView = memo(function PageView({
transform={transform}
scale={cssScale}
widthMode={widthMode}
+ growEdge={runGrowEdges.get(run.id) ?? null}
pageRevision={paintedRevision}
+ gripLayer={gripLayer}
selected={selectedRunIds.includes(run.id)}
- highlighted={highlightedRunId === run.id}
+ findRange={findMatch?.runId === run.id ? findMatch.range : null}
onSelect={(shiftKey) => onSelectRun(run.id, shiftKey)}
onEdit={(nextText) => onEditRun(page.pageIndex, run.id, nextText)}
- onTextRangeChange={
- ACCESSIBILITY_EDITING
- ? (range) => onSelectRunText?.(run.id, range)
- : undefined
- }
+ onTextRangeChange={(range) => onSelectRunText?.(run.id, range)}
textRange={
selectedRunIds.length === 1 && selectedRunIds[0] === run.id
? selectedTextRange
: null
}
onMove={(dx, dy) => onMoveRun?.(page.pageIndex, run.id, dx, dy)}
- onWrap={(maxWidthPt) =>
- onWrapRun?.(page.pageIndex, run.id, maxWidthPt)
+ onWrap={(maxWidthPt, keepClearBelow) =>
+ onWrapRun?.(page.pageIndex, run.id, maxWidthPt, keepClearBelow)
+ }
+ onMeasure={
+ onMeasureRun
+ ? () => onMeasureRun(page.pageIndex, run.id)
+ : undefined
}
onResize={
- onResizeRun && !isScanRun(run)
+ onResizeRun && canResizeRun(run)
? (widthPt) => onResizeRun(page.pageIndex, run.id, widthPt)
: undefined
}
@@ -458,3 +592,27 @@ export const PageView = memo(function PageView({
</Box>
);
});
+
+// Long enough a typing pause to draw the page whole, repairing anything a partial redraw missed.
+const FULL_REDRAW_AFTER_TYPING_MS = 400;
+
+// The canvas pixels to redraw over a bitmap painted at revision `painted`, or null to draw the whole page.
+function changedPixels(
+ page: Page,
+ scale: number,
+ canvas: HTMLCanvasElement,
+ painted: number,
+): PageRect | null {
+ if (!showsWholePage(canvas, page, scale)) return null;
+ const raw = page.repaintAreaSince(painted);
+ return raw && PdfiumPageRenderer.pixelsCovering(page, scale, raw);
+}
+
+function showsWholePage(
+ canvas: HTMLCanvasElement,
+ page: Page,
+ scale: number,
+): boolean {
+ const full = PdfiumPageRenderer.rasterSize(page.width, page.height, scale);
+ return canvas.width === full.width && canvas.height === full.height;
+}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/PageViewResize.test.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/PageViewResize.test.tsx
new file mode 100644
index 0000000000..53d0658536
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/PageViewResize.test.tsx
@@ -0,0 +1,77 @@
+import { render } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import {
+ pageSnapshot,
+ stubDocument,
+ stubbedPageView,
+} from "@editor/tools/pdfTextEditor/components/pageViewTestSupport";
+import { Page } from "@editor/tools/pdfTextEditor/model/Page";
+import type { TextRunSnapshot } from "@editor/tools/pdfTextEditor/types";
+
+const { resizable } = vi.hoisted(() => ({
+ resizable: new Map<string, boolean>(),
+}));
+
+vi.mock("@editor/tools/pdfTextEditor/components/TableOverlay", () => ({
+ TableOverlay: () => null,
+}));
+vi.mock("@editor/tools/pdfTextEditor/components/TextRunOverlay", () => ({
+ TextRunOverlay: (props: {
+ run: { id: string };
+ onResize?: (widthPt: number) => void;
+ }) => {
+ resizable.set(props.run.id, props.onResize !== undefined);
+ return null;
+ },
+}));
+
+const UPRIGHT = { a: 1, b: 0, c: 0, d: 1, e: 72, f: 700 };
+const TURNED = { a: 0, b: 1, c: -1, d: 0, e: 72, f: 700 };
+
+function run(id: string, extra: Partial<TextRunSnapshot>): TextRunSnapshot {
+ return {
+ id,
+ bounds: { x: 72, y: 700, width: 200, height: 12 },
+ matrix: UPRIGHT,
+ text: id,
+ ...extra,
+ } as TextRunSnapshot;
+}
+
+describe("PageView resize handle", () => {
+ const originalObserver = globalThis.IntersectionObserver;
+
+ beforeEach(() => {
+ resizable.clear();
+ globalThis.IntersectionObserver = class {
+ observe() {}
+ disconnect() {}
+ unobserve() {}
+ } as unknown as typeof IntersectionObserver;
+ });
+
+ afterEach(() => {
+ globalThis.IntersectionObserver = originalObserver;
+ });
+
+ it("is offered on upright scanned text and plain text, not on read-only or turned scanned text", () => {
+ const live = new Page({ index: 0, pagePtr: 1, width: 600, height: 800 });
+ const page = pageSnapshot(live, [
+ run("plain", {}),
+ run("scanned", { renderMode: 3 }),
+ run("scannedReadOnly", { renderMode: 3, textReadOnly: true }),
+ run("scannedTurned", { renderMode: 3, matrix: TURNED }),
+ run("readOnly", { textReadOnly: true }),
+ ]);
+ render(
+ stubbedPageView(stubDocument(live), page, { onResizeRun: () => {} }),
+ );
+ expect(Object.fromEntries(resizable)).toEqual({
+ plain: true,
+ scanned: true,
+ scannedReadOnly: false,
+ scannedTurned: false,
+ readOnly: false,
+ });
+ });
+});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/PasswordPromptModal.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/PasswordPromptModal.tsx
index 67dfdb0f84..f00f82fb6a 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/components/PasswordPromptModal.tsx
+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/PasswordPromptModal.tsx
@@ -1,4 +1,4 @@
-import { useEffect, useState } from "react";
+import { memo, useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import EncryptedPdfUnlockModal from "@editor/components/shared/EncryptedPdfUnlockModal";
@@ -10,7 +10,7 @@ interface PasswordPromptModalProps {
onCancel: () => void;
}
-export function PasswordPromptModal({
+export const PasswordPromptModal = memo(function PasswordPromptModal({
prompt,
loading,
onSubmit,
@@ -45,4 +45,4 @@ export function PasswordPromptModal({
testIdPrefix="pdf-editor-password"
/>
);
-}
+});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/SaveRiskModal.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/SaveRiskModal.tsx
index 3d5425ba26..cd003afc92 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/components/SaveRiskModal.tsx
+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/SaveRiskModal.tsx
@@ -1,3 +1,4 @@
+import { memo } from "react";
import { Modal, Stack, Text, Group, List } from "@mantine/core";
import { Button } from "@editor/ui/Button";
import { useTranslation } from "react-i18next";
@@ -15,7 +16,7 @@ interface SaveRiskModalProps {
}
/** Warns before a save that would damage signatures / XFA. */
-export function SaveRiskModal({
+export const SaveRiskModal = memo(function SaveRiskModal({
risks,
onConfirm,
onCancel,
@@ -70,4 +71,4 @@ export function SaveRiskModal({
</Stack>
</Modal>
);
-}
+});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/ScanHint.test.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/ScanHint.test.tsx
index f2fcd81c51..f72ec8769f 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/components/ScanHint.test.tsx
+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/ScanHint.test.tsx
@@ -102,3 +102,62 @@ describe("scan hint action", () => {
).not.toBeInTheDocument();
});
});
+
+function outlinedPage(letters: number, height = 3): PageSnapshot {
+ return {
+ width: 612,
+ height: 792,
+ runs: [],
+ images: [{ bounds: { x: 40, y: 700, width: 80, height: 40 } }],
+ shapes: Array.from({ length: letters }, (_, i) => ({
+ bounds: {
+ x: 40 + (i % 90) * 6,
+ y: 600 - Math.floor(i / 90) * 12,
+ width: 4,
+ height,
+ },
+ })),
+ } as unknown as PageSnapshot;
+}
+
+describe("pages whose text is drawn as shapes", () => {
+ const renderHint = (pages: PageSnapshot[]) =>
+ render(
+ <MantineProvider env="test">
+ <ScanHint
+ pages={pages}
+ onRunOcr={vi.fn()}
+ ocrRunning={false}
+ ocrAvailable
+ />
+ </MantineProvider>,
+ );
+
+ it("offers OCR for a page of letter-sized outlines with no text", () => {
+ renderHint([outlinedPage(1600)]);
+ expect(screen.getByTestId("pdf-editor-scan-hint-ocr")).toBeEnabled();
+ });
+
+ it("does not call shape-drawn pages scanned images when both kinds are present", () => {
+ renderHint([scanPage(), outlinedPage(1600)]);
+ const hint = screen.getByTestId("pdf-editor-scan-hint");
+ expect(hint).toHaveTextContent("unreadPagesHint");
+ expect(hint).not.toHaveTextContent("scanHint");
+ });
+
+ it("does not offer OCR for a page with a few drawn shapes", () => {
+ renderHint([outlinedPage(20)]);
+ expect(
+ screen.queryByTestId("pdf-editor-scan-hint"),
+ ).not.toBeInTheDocument();
+ });
+
+ it("does not offer OCR when the page has text", () => {
+ renderHint([
+ { ...outlinedPage(1600), runs: [{ id: "r" }] } as PageSnapshot,
+ ]);
+ expect(
+ screen.queryByTestId("pdf-editor-scan-hint"),
+ ).not.toBeInTheDocument();
+ });
+});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/ScanHint.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/ScanHint.tsx
index d89e87fe14..5d51086819 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/components/ScanHint.tsx
+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/ScanHint.tsx
@@ -15,6 +15,21 @@ function isUnreadScan(page: PageSnapshot): boolean {
);
}
+// "Print to PDF" and some exporters draw every letter as an outline and write no text at all.
+const LETTER_SHAPES_MIN = 80;
+const LETTER_MAX_HEIGHT_PT = 30;
+
+function isOutlinedText(page: PageSnapshot): boolean {
+ if (page.runs.length > 0) return false;
+ const letters = (page.shapes ?? []).filter(
+ (shape) =>
+ shape.bounds.height > 0 &&
+ shape.bounds.height <= LETTER_MAX_HEIGHT_PT &&
+ shape.bounds.width <= LETTER_MAX_HEIGHT_PT * 2,
+ );
+ return letters.length >= LETTER_SHAPES_MIN;
+}
+
/** Offers OCR when the pages they opened are scans with no text. */
export interface ScanHintProps {
pages: PageSnapshot[];
@@ -36,17 +51,34 @@ export function ScanHint({
const { t } = useTranslation();
const reasonId = useId();
const scans = pages.filter(isUnreadScan).length;
- if (scans === 0) return null;
+ const outlined = pages.filter(
+ (page) => !isUnreadScan(page) && isOutlinedText(page),
+ ).length;
+ if (scans + outlined === 0) return null;
return (
<Stack gap={6} align="center" data-testid="pdf-editor-scan-hint">
<Text size="xs" c="dimmed" ta="center">
- {t("pdfTextEditor.inspector.scanHint", {
- count: scans,
- defaultValue_one:
- "This page is a scanned image with no text to edit. Run OCR first to make its text editable.",
- defaultValue_other:
- "{{count}} pages are scanned images with no text to edit. Run OCR first to make their text editable.",
- })}
+ {scans === 0
+ ? t("pdfTextEditor.inspector.outlinedTextHint", {
+ count: outlined,
+ defaultValue_one:
+ "This page's text is drawn as shapes, so there is no text to edit. Run OCR first to make it editable.",
+ defaultValue_other:
+ "{{count}} pages have their text drawn as shapes, so there is no text to edit. Run OCR first to make it editable.",
+ })
+ : outlined > 0
+ ? t("pdfTextEditor.inspector.unreadPagesHint", {
+ count: scans + outlined,
+ defaultValue:
+ "{{count}} pages have no text to edit: some are scanned images and some draw their text as shapes. Run OCR first to make them editable.",
+ })
+ : t("pdfTextEditor.inspector.scanHint", {
+ count: scans,
+ defaultValue_one:
+ "This page is a scanned image with no text to edit. Run OCR first to make its text editable.",
+ defaultValue_other:
+ "{{count}} pages are scanned images with no text to edit. Run OCR first to make their text editable.",
+ })}
</Text>
<Button
size="sm"
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/TableOverlay.css b/frontend/src/editor/core/tools/pdfTextEditor/components/TableOverlay.css
new file mode 100644
index 0000000000..521fbcdd0b
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/TableOverlay.css
@@ -0,0 +1,60 @@
+.pdf-editor-table-chip {
+ position: absolute;
+ bottom: calc(100% + 4px);
+ right: -1px;
+ display: flex;
+ align-items: center;
+ gap: 2px;
+ padding: 1px;
+ background: var(--c-surface);
+ border: 1px solid var(--c-border);
+ border-radius: 6px;
+ white-space: nowrap;
+ z-index: 30;
+ opacity: 0;
+ pointer-events: none;
+ transition: opacity 120ms ease-out;
+}
+
+.pdf-editor-table-chip[data-shown="true"],
+.pdf-editor-table-chip:focus-within {
+ opacity: 1;
+ pointer-events: auto;
+}
+
+.pdf-editor-table-chip button {
+ display: flex;
+ align-items: center;
+ gap: 4px;
+ padding: 1px 6px;
+ font-size: 11px;
+ line-height: 16px;
+ color: var(--c-text-muted);
+ background: transparent;
+ border: none;
+ border-radius: 4px;
+ cursor: pointer;
+}
+
+.pdf-editor-table-chip button:hover {
+ color: var(--c-text);
+ background: var(--c-hover);
+}
+
+.pdf-editor-table-chip button:focus-visible {
+ outline: 2px solid var(--c-accent-fg, var(--c-primary));
+ outline-offset: 1px;
+}
+
+.pdf-editor-table-chip-divider {
+ width: 1px;
+ align-self: stretch;
+ margin: 3px 0;
+ background: var(--c-border);
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .pdf-editor-table-chip {
+ transition: none;
+ }
+}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/TableOverlay.test.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/TableOverlay.test.tsx
new file mode 100644
index 0000000000..0ec70414a9
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/TableOverlay.test.tsx
@@ -0,0 +1,297 @@
+import { MantineProvider } from "@mantine/core";
+import { fireEvent, render, screen } from "@testing-library/react";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { TableOverlay } from "@editor/tools/pdfTextEditor/components/TableOverlay";
+import { DisplayTransform } from "@editor/tools/pdfTextEditor/model/DisplayTransform";
+import type { EditorStore } from "@editor/tools/pdfTextEditor/store/EditorStore";
+import type {
+ PageSnapshot,
+ TableSnapshot,
+ TextRunSnapshot,
+} from "@editor/tools/pdfTextEditor/types";
+
+const mocks = vi.hoisted(() => ({
+ drawable: true,
+ alert: vi.fn(),
+ detected: [] as unknown[],
+}));
+vi.mock("@editor/tools/pdfTextEditor/util/tableDetection", () => ({
+ detectTables: () => mocks.detected,
+}));
+vi.mock("@editor/components/toast", () => ({ alert: mocks.alert }));
+vi.mock("@editor/tools/pdfTextEditor/commands/tableHelpers", async (load) => ({
+ ...(await load<object>()),
+ cellTextDrawable: () => mocks.drawable,
+}));
+vi.mock("@editor/tools/pdfTextEditor/commands/FillTableCellCommand", () => ({
+ FillTableCellCommand: class {
+ readonly type = "fill-table-cell";
+ insertedRunId: string | null = null;
+ apply(): void {}
+ revert(): void {}
+ },
+}));
+
+const TABLE: TableSnapshot = {
+ id: "t1",
+ pageIndex: 0,
+ rows: 1,
+ cols: 1,
+ colEdges: [100, 300],
+ rowEdges: [500, 460],
+ bounds: { x: 100, y: 460, width: 200, height: 40 },
+ cells: [
+ {
+ row: 0,
+ col: 0,
+ rect: { x: 100, y: 460, width: 200, height: 40 },
+ runIds: [],
+ colSpan: 1,
+ rowSpan: 1,
+ },
+ ],
+ confidence: 1,
+ synthetic: true,
+ ruled: true,
+ pageRuled: false,
+ adopted: false,
+ scanned: false,
+ columnStyles: [],
+ headerStyle: null,
+};
+
+const PAGE: PageSnapshot = {
+ pageIndex: 0,
+ width: 612,
+ height: 792,
+ dirty: false,
+ revision: 0,
+ runs: [],
+ images: [],
+ shapes: [],
+ tables: [TABLE],
+ display: DisplayTransform.identity(612, 792).toData(),
+};
+
+function renderCell(fills: boolean) {
+ const store = {
+ dispatch: vi.fn((cmd: { insertedRunId: string | null }) => {
+ if (fills) cmd.insertedRunId = "cell-run";
+ }),
+ selection: { selectOne: vi.fn() },
+ };
+ render(
+ <MantineProvider env="test">
+ <TableOverlay
+ page={PAGE}
+ transform={DisplayTransform.identity(612, 792)}
+ scale={1}
+ store={store as unknown as EditorStore}
+ />
+ </MantineProvider>,
+ );
+ return { store, cell: screen.getByTestId("pdf-editor-table-cell-t1-0-0") };
+}
+
+function type(cell: HTMLElement, text: string): void {
+ cell.textContent = text;
+ fireEvent.blur(cell);
+}
+
+describe("typing into an empty table cell", () => {
+ beforeEach(() => {
+ mocks.drawable = true;
+ mocks.alert.mockClear();
+ });
+
+ it("keeps text the table's fonts cannot draw in the cell and says why", () => {
+ mocks.drawable = false;
+ const { store, cell } = renderCell(true);
+ type(cell, "A漢字");
+ expect(store.dispatch).not.toHaveBeenCalled();
+ expect(cell.textContent).toBe("A漢字");
+ expect(mocks.alert).toHaveBeenCalledOnce();
+ });
+
+ it("keeps the text and says why when the fill draws nothing", () => {
+ const { store, cell } = renderCell(false);
+ type(cell, "Total");
+ expect(store.dispatch).toHaveBeenCalledOnce();
+ expect(cell.textContent).toBe("Total");
+ expect(mocks.alert).toHaveBeenCalledOnce();
+ });
+
+ it("hands accepted text to the page and selects it", () => {
+ const { store, cell } = renderCell(true);
+ type(cell, "Total");
+ expect(cell.textContent).toBe("");
+ expect(store.selection.selectOne).toHaveBeenCalledWith("cell-run");
+ expect(mocks.alert).not.toHaveBeenCalled();
+ });
+});
+
+const RECOGNIZED: TableSnapshot = {
+ ...TABLE,
+ id: "r1",
+ rows: 2,
+ cols: 2,
+ colEdges: [100, 200, 300],
+ rowEdges: [500, 480, 460],
+ cells: [
+ {
+ row: 0,
+ col: 0,
+ rect: { x: 100, y: 480, width: 100, height: 20 },
+ runIds: ["cell-a"],
+ colSpan: 1,
+ rowSpan: 1,
+ },
+ ],
+ synthetic: false,
+ ruled: false,
+};
+
+function renderRecognized(selectedRunIds: string[] = []) {
+ mocks.detected = [RECOGNIZED];
+ const store = { adoptTable: vi.fn(), selection: { selectMany: vi.fn() } };
+ const view = render(
+ <MantineProvider env="test">
+ <div data-testid="layer">
+ <TableOverlay
+ page={{ ...PAGE, tables: [] }}
+ transform={DisplayTransform.identity(612, 792)}
+ scale={1}
+ store={store as unknown as EditorStore}
+ selectedRunIds={selectedRunIds}
+ />
+ </div>
+ </MantineProvider>,
+ );
+ const box = screen.getByTestId("pdf-editor-recognized-table-r1");
+ box.getBoundingClientRect = () => new DOMRect(100, 292, 200, 40);
+ return {
+ store,
+ view,
+ box,
+ chip: screen.getByTestId("pdf-editor-recognized-table-chip-r1"),
+ };
+}
+
+function pointerAt(x: number, y: number): void {
+ fireEvent(
+ screen.getByTestId("layer"),
+ new MouseEvent("pointermove", { clientX: x, clientY: y, bubbles: true }),
+ );
+}
+
+describe("a recognized table", () => {
+ beforeEach(() => {
+ mocks.detected = [];
+ });
+
+ it("draws nothing over the page until the pointer reaches it", () => {
+ const { box, chip } = renderRecognized();
+ expect(box.dataset.shown).toBe("false");
+ expect(box.style.border).toBe("1px solid transparent");
+ expect(chip.dataset.shown).toBe("false");
+ expect(box.querySelectorAll("[style*='border-left']")).toHaveLength(0);
+ });
+
+ it("shows a dotted outline and one chip on hover, without a grid", () => {
+ const { box, chip } = renderRecognized();
+ pointerAt(150, 300);
+ expect(box.dataset.shown).toBe("true");
+ expect(box.style.border).toContain("dotted");
+ expect(box.style.border).toContain("--c-accent-fg");
+ expect(chip.dataset.shown).toBe("true");
+ expect(box.querySelectorAll("[style*='border-left']")).toHaveLength(0);
+ expect(box.querySelectorAll("[style*='border-top']")).toHaveLength(0);
+ pointerAt(500, 700);
+ expect(chip.dataset.shown).toBe("false");
+ });
+
+ it("shows its chip while any of its text is selected", () => {
+ const { chip } = renderRecognized(["cell-a"]);
+ expect(chip.dataset.shown).toBe("true");
+ });
+
+ it("keeps the chip reachable from the keyboard while hidden", () => {
+ const { store } = renderRecognized();
+ const edit = screen.getByTestId("pdf-editor-recognized-table-edit-r1");
+ edit.focus();
+ expect(document.activeElement).toBe(edit);
+ fireEvent.click(edit);
+ expect(store.adoptTable).toHaveBeenCalledWith(RECOGNIZED);
+ fireEvent.click(
+ screen.getByTestId("pdf-editor-recognized-table-select-r1"),
+ );
+ expect(store.selection.selectMany).toHaveBeenCalledWith(["cell-a"]);
+ });
+});
+
+function textRun(id: string, y: number, x = 100, width = 150): TextRunSnapshot {
+ return {
+ id,
+ text: id,
+ bounds: { x, y, width, height: 14 },
+ } as unknown as TextRunSnapshot;
+}
+
+function renderEditing(runs: TextRunSnapshot[]) {
+ const table: TableSnapshot = {
+ ...TABLE,
+ rows: 2,
+ cols: 2,
+ colEdges: [100, 200, 300],
+ rowEdges: [500, 480, 460],
+ ruled: false,
+ };
+ render(
+ <MantineProvider env="test">
+ <TableOverlay
+ page={{ ...PAGE, runs, tables: [table] }}
+ transform={DisplayTransform.identity(612, 792)}
+ scale={1}
+ store={{} as unknown as EditorStore}
+ />
+ </MantineProvider>,
+ );
+ return {
+ frame: screen.getByTestId("pdf-editor-table-t1"),
+ toolbar: screen.getByTestId("pdf-editor-table-controls-t1"),
+ };
+}
+
+describe("a table being edited", () => {
+ it("draws a dotted edge around a cell grid of solid lines", () => {
+ const { frame } = renderEditing([]);
+ expect(frame.style.border).toContain("dotted");
+ const lines = frame.querySelectorAll<HTMLElement>(
+ "[style*='border-left'], [style*='border-top']",
+ );
+ expect(lines.length).toBe(2);
+ for (const line of lines)
+ expect(line.getAttribute("style")).toMatch(/solid/);
+ });
+
+ it("puts its toolbar above the table when nothing is there", () => {
+ const { toolbar } = renderEditing([textRun("far", 700)]);
+ expect(toolbar.dataset.placement).toBe("above");
+ expect(parseFloat(toolbar.style.top)).toBeLessThan(292);
+ });
+
+ it("moves its toolbar below the table rather than over the text above it", () => {
+ const { toolbar } = renderEditing([textRun("heading", 505)]);
+ expect(toolbar.dataset.placement).toBe("below");
+ expect(parseFloat(toolbar.style.top)).toBeGreaterThan(332);
+ });
+
+ it("tries the other end of the edge before covering text", () => {
+ const { toolbar } = renderEditing([
+ textRun("aside", 505, 330, 40),
+ textRun("note", 420, 100, 40),
+ ]);
+ expect(toolbar.dataset.placement).toBe("above");
+ expect(parseFloat(toolbar.style.left)).toBeLessThan(99);
+ });
+});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/TableOverlay.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/TableOverlay.tsx
index a83a372bcc..51890bdff9 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/components/TableOverlay.tsx
+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/TableOverlay.tsx
@@ -1,4 +1,4 @@
-import { useMemo, useRef, useState } from "react";
+import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
import { Tooltip } from "@mantine/core";
import { useTranslation } from "react-i18next";
import { Icon } from "@editor/ui/Icon";
@@ -15,6 +15,8 @@ import { overlaps } from "@editor/tools/pdfTextEditor/util/tableAdoption";
import { detectTables } from "@editor/tools/pdfTextEditor/util/tableDetection";
import { ModifyTableCommand } from "@editor/tools/pdfTextEditor/commands/ModifyTableCommand";
import { FillTableCellCommand } from "@editor/tools/pdfTextEditor/commands/FillTableCellCommand";
+import { cellTextDrawable } from "@editor/tools/pdfTextEditor/commands/tableHelpers";
+import { alert } from "@editor/components/toast";
import type { TableResize } from "@editor/tools/pdfTextEditor/commands/ResizeTableCommand";
import { ResizeTableCommand } from "@editor/tools/pdfTextEditor/commands/ResizeTableCommand";
import { MaterialiseTableCommand } from "@editor/tools/pdfTextEditor/commands/MaterialiseTableCommand";
@@ -24,6 +26,7 @@ import {
pageCanvas,
sampleTableColors,
} from "@editor/tools/pdfTextEditor/util/scanSampling";
+import "@editor/tools/pdfTextEditor/components/TableOverlay.css";
// Edge handles live wholly OUTSIDE the grid, in a margin strip below it
// (columns) or left of it (rows), the way a spreadsheet puts them in its
@@ -36,6 +39,14 @@ const GRAB = 13;
/** Selection accent, matching the image handle's outline. */
const ACCENT = "var(--c-accent-fg)";
+const OUTLINE =
+ "1px dotted color-mix(in srgb, var(--c-accent-fg) 45%, transparent)";
+const GRID_LINE =
+ "1px solid color-mix(in srgb, var(--c-accent-fg) 25%, transparent)";
+/** Reach around the table and its chip that still counts as over them, so crossing the gap between the two does not flicker the chip. */
+const HOVER_SLACK = 6;
+/** Gap between the table edge (or its handle strip) and the editing toolbar. */
+const TOOLBAR_GAP = 6;
// The controls sit over page content, so they need to read as a floating
// toolbar rather than as loose buttons tangled in the text behind them.
@@ -54,25 +65,13 @@ const toolbarStyle: React.CSSProperties = {
whiteSpace: "nowrap",
};
-const chipStyle: React.CSSProperties = {
- display: "flex",
- alignItems: "center",
- gap: 4,
- padding: "2px 6px",
- fontSize: 11,
- lineHeight: "16px",
- color: ACCENT,
- background: "transparent",
- border: "none",
- borderRadius: 4,
- cursor: "pointer",
-};
-
interface TableOverlayProps {
page: PageSnapshot;
transform: DisplayTransform;
scale: number;
store: EditorStore;
+ /** A recognized table shows its affordances while any of its text is selected. */
+ selectedRunIds?: readonly string[];
}
interface CssRect {
@@ -114,6 +113,7 @@ export function TableOverlay({
transform,
scale,
store,
+ selectedRunIds = [],
}: TableOverlayProps) {
const detected = useMemo(
() => detectTables(page.runs, page.pageIndex, {}, page.rules ?? []),
@@ -138,6 +138,9 @@ export function TableOverlay({
transform={transform}
scale={scale}
store={store}
+ selected={table.cells.some((c) =>
+ c.runIds.some((id) => selectedRunIds.includes(id)),
+ )}
/>
))}
{synthetic.map((table) => (
@@ -194,74 +197,84 @@ function justifyFor(align: TableCellStyle["align"]): string {
return "flex-start";
}
-// A grid recognized from ordinary text. Shows its structure and lets the user
-// select the whole thing, but structural edits need the tracked geometry that
-// only inserted tables carry.
+// A grid recognized from ordinary text. The page is the user's document, so
+// nothing is drawn over it until the pointer is over the table or its text is
+// selected; the chip stays focusable while hidden and shows on keyboard focus.
+// Structural edits need the tracked geometry that only inserted tables carry.
function RecognizedTable({
table,
page,
transform,
scale,
store,
+ selected,
}: {
table: TableSnapshot;
page: PageSnapshot;
transform: DisplayTransform;
scale: number;
store: EditorStore;
+ selected: boolean;
}) {
const { t } = useTranslation();
const box = rectToCss(table.bounds, transform, scale, page.height);
const runIds = table.cells.flatMap((c) => c.runIds);
+ const ref = useRef<HTMLDivElement | null>(null);
+ const chipRef = useRef<HTMLDivElement | null>(null);
+ const hovered = usePointerOver(ref, chipRef);
+ const shown = hovered || selected;
return (
<div
+ ref={ref}
data-testid={`pdf-editor-recognized-table-${table.id}`}
+ data-shown={shown}
style={{
position: "absolute",
left: box.left,
top: box.top,
width: box.width,
height: box.height,
- border: table.pageRuled
- ? "1px solid color-mix(in srgb, var(--c-accent-fg) 35%, transparent)"
- : "1px dashed color-mix(in srgb, var(--c-accent-fg) 55%, transparent)",
+ border: shown ? OUTLINE : "1px solid transparent",
+ borderRadius: 2,
pointerEvents: "none",
boxSizing: "border-box",
}}
>
- {!table.pageRuled && gridLines(table, box)}
- <div style={{ ...toolbarStyle, top: -26, left: -1 }}>
+ <div
+ ref={chipRef}
+ className="pdf-editor-table-chip"
+ data-shown={shown}
+ data-testid={`pdf-editor-recognized-table-chip-${table.id}`}
+ >
<Tooltip
label={t(
- "pdfTextEditor.table.recognizedHint",
- "Recognized table - click to select all its text",
+ "pdfTextEditor.table.editHint",
+ "Edit as a table - type in cells, add or remove rows and columns",
)}
>
<button
type="button"
- onClick={() => store.selection.selectMany(runIds)}
- data-testid={`pdf-editor-recognized-table-select-${table.id}`}
- style={chipStyle}
+ onClick={() => store.adoptTable(table)}
+ data-testid={`pdf-editor-recognized-table-edit-${table.id}`}
>
<Icon name="table" size={13} />
- {table.rows}×{table.cols}
+ {t("pdfTextEditor.table.editTable", "Edit table")}
</button>
</Tooltip>
+ <span className="pdf-editor-table-chip-divider" />
<Tooltip
label={t(
- "pdfTextEditor.table.editHint",
- "Edit as a table - type in cells, add or remove rows and columns",
+ "pdfTextEditor.table.recognizedHint",
+ "Recognized table - click to select all its text",
)}
>
<button
type="button"
- onClick={() => store.adoptTable(table)}
- data-testid={`pdf-editor-recognized-table-edit-${table.id}`}
- style={chipStyle}
+ onClick={() => store.selection.selectMany(runIds)}
+ data-testid={`pdf-editor-recognized-table-select-${table.id}`}
>
- <Icon name="pencil" size={13} />
- {t("pdfTextEditor.table.edit", "Edit")}
+ {table.rows}×{table.cols}
</button>
</Tooltip>
</div>
@@ -269,6 +282,43 @@ function RecognizedTable({
);
}
+// Whether the pointer is over `target` or `extra`, read from the document: the
+// run overlays above the table and the page canvas below it take the pointer,
+// so the table's own box (pointer-events: none) never sees it.
+function usePointerOver(
+ target: React.RefObject<HTMLElement | null>,
+ extra: React.RefObject<HTMLElement | null>,
+): boolean {
+ const [over, setOver] = useState(false);
+ useEffect(() => {
+ const doc = target.current?.ownerDocument;
+ if (!doc) return;
+ const inside = (el: HTMLElement | null, x: number, y: number) => {
+ if (!el) return false;
+ const r = el.getBoundingClientRect();
+ return (
+ x >= r.left - HOVER_SLACK &&
+ x <= r.right + HOVER_SLACK &&
+ y >= r.top - HOVER_SLACK &&
+ y <= r.bottom + HOVER_SLACK
+ );
+ };
+ const onMove = (e: MouseEvent) =>
+ setOver(
+ inside(target.current, e.clientX, e.clientY) ||
+ inside(extra.current, e.clientX, e.clientY),
+ );
+ const onLeave = () => setOver(false);
+ doc.addEventListener("pointermove", onMove, { passive: true });
+ doc.documentElement.addEventListener("pointerleave", onLeave);
+ return () => {
+ doc.removeEventListener("pointermove", onMove);
+ doc.documentElement.removeEventListener("pointerleave", onLeave);
+ };
+ }, [target, extra]);
+ return over;
+}
+
// Internal separators for a table, positioned relative to the outer box.
function gridLines(table: TableSnapshot, box: CssRect) {
const w = table.bounds.width;
@@ -285,8 +335,7 @@ function gridLines(table: TableSnapshot, box: CssRect) {
left: fx * box.width,
top: 0,
bottom: 0,
- borderLeft:
- "1px dashed color-mix(in srgb, var(--c-accent-fg) 35%, transparent)",
+ borderLeft: GRID_LINE,
}}
/>,
);
@@ -302,8 +351,7 @@ function gridLines(table: TableSnapshot, box: CssRect) {
top: fy * box.height,
left: 0,
right: 0,
- borderTop:
- "1px dashed color-mix(in srgb, var(--c-accent-fg) 35%, transparent)",
+ borderTop: GRID_LINE,
}}
/>,
);
@@ -311,6 +359,52 @@ function gridLines(table: TableSnapshot, box: CssRect) {
return lines;
}
+function centredIn(r: PageRect, bounds: PageRect): boolean {
+ const x = r.x + r.width / 2;
+ const y = r.y + r.height / 2;
+ return (
+ x >= bounds.x &&
+ x <= bounds.x + bounds.width &&
+ y >= bounds.y &&
+ y <= bounds.y + bounds.height
+ );
+}
+
+type ToolbarPlacement = "above" | "below";
+
+// Above the table unless that covers text or leaves the page, then below its
+// handle strip, each tried at the left edge and then the right; where every
+// spot covers something, above at the left if it stays on the page.
+function placeToolbar(
+ box: CssRect,
+ toolbar: { width: number; height: number },
+ blockers: readonly CssRect[],
+ pageHeightPx: number,
+): { placement: ToolbarPlacement; top: number; left: number } {
+ const above = box.top - toolbar.height - TOOLBAR_GAP;
+ const below = box.top + box.height + MARGIN + TOOLBAR_GAP;
+ const lefts = [box.left - 1, box.left + box.width + 1 - toolbar.width];
+ const clear = (top: number, left: number) =>
+ !blockers.some(
+ (r) =>
+ r.left < left + toolbar.width &&
+ r.left + r.width > left &&
+ r.top < top + toolbar.height &&
+ r.top + r.height > top,
+ );
+ const aboveFits = above >= 0;
+ const belowFits = below + toolbar.height <= pageHeightPx;
+ const spots: Array<{ placement: ToolbarPlacement; top: number }> = [];
+ if (aboveFits) spots.push({ placement: "above", top: above });
+ if (belowFits) spots.push({ placement: "below", top: below });
+ for (const spot of spots)
+ for (const left of lefts)
+ if (clear(spot.top, left)) return { ...spot, left };
+ return aboveFits || !belowFits
+ ? { placement: "above", top: above, left: lefts[0] }
+ : { placement: "below", top: below, left: lefts[0] };
+}
+
// An inserted table with tracked geometry: supports add/remove row & column and
// click-to-type empty cells.
function EditableTable({
@@ -424,6 +518,28 @@ function EditableTable({
const emptyCells = table.cells.filter((c) => c.runIds.length === 0);
+ const toolbarRef = useRef<HTMLDivElement | null>(null);
+ const [toolbarSize, setToolbarSize] = useState({ width: 260, height: 28 });
+ useLayoutEffect(() => {
+ const el = toolbarRef.current;
+ if (!el) return;
+ const next = { width: el.offsetWidth, height: el.offsetHeight };
+ if (next.width === 0 || next.height === 0) return;
+ setToolbarSize((prev) =>
+ prev.width === next.width && prev.height === next.height ? prev : next,
+ );
+ });
+ const ownRuns = new Set(table.cells.flatMap((c) => c.runIds));
+ const blockers = page.runs
+ .filter((r) => !ownRuns.has(r.id) && !centredIn(r.bounds, table.bounds))
+ .map((r) => rectToCss(r.bounds, transform, scale, page.height));
+ const toolbarAt = placeToolbar(
+ box,
+ toolbarSize,
+ blockers,
+ page.height * scale,
+ );
+
return (
<>
<div
@@ -439,10 +555,7 @@ function EditableTable({
// Outline what is being edited, but only draw cell separators the
// page does not already draw - dashes on top of printed rules are
// just fuzz over lines the reader can already see.
- border:
- table.ruled || table.pageRuled
- ? "1px solid color-mix(in srgb, var(--c-accent-fg) 35%, transparent)"
- : "1px dashed color-mix(in srgb, var(--c-accent-fg) 55%, transparent)",
+ border: OUTLINE,
}}
>
{!table.ruled && !table.pageRuled && gridLines(table, box)}
@@ -462,19 +575,31 @@ function EditableTable({
}
}}
onBlur={(e) => {
- const text = e.currentTarget.textContent?.trim() ?? "";
+ const input = e.currentTarget;
+ const text = input.textContent?.trim() ?? "";
if (!text) return;
- e.currentTarget.textContent = "";
- const cmd = new FillTableCellCommand({
- tableId: table.id,
- row: cell.row,
- col: cell.col,
- text,
- });
- mutate(cmd);
- if (cmd.insertedRunId) {
- store.selection.selectOne(cmd.insertedRunId);
+ const cmd = cellTextDrawable(text)
+ ? new FillTableCellCommand({
+ tableId: table.id,
+ row: cell.row,
+ col: cell.col,
+ text,
+ })
+ : null;
+ if (cmd) mutate(cmd);
+ if (!cmd?.insertedRunId) {
+ alert({
+ alertType: "warning",
+ title: t(
+ "pdfTextEditor.table.cellNoGlyphs",
+ "This text has characters the table's fonts can't draw. Change or remove them to fill the cell.",
+ ),
+ expandable: false,
+ });
+ return;
}
+ input.textContent = "";
+ store.selection.selectOne(cmd.insertedRunId);
}}
style={{
position: "absolute",
@@ -606,8 +731,10 @@ function EditableTable({
)}
</div>
<div
- style={{ ...toolbarStyle, left: box.left - 1, top: box.top - 30 }}
+ ref={toolbarRef}
+ style={{ ...toolbarStyle, left: toolbarAt.left, top: toolbarAt.top }}
data-testid={`pdf-editor-table-controls-${table.id}`}
+ data-placement={toolbarAt.placement}
>
<DragArea
testid={`pdf-editor-table-move-handle-${table.id}`}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/TextRunOverlay.css b/frontend/src/editor/core/tools/pdfTextEditor/components/TextRunOverlay.css
index d385a8d9b7..520d2fdab0 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/components/TextRunOverlay.css
+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/TextRunOverlay.css
@@ -8,6 +8,32 @@
translate: -2px -2px;
}
+.pdf-editor-run-grips {
+ position: absolute;
+ pointer-events: none;
+ translate: -2px -2px;
+}
+
+.pdf-editor-run-grip {
+ position: absolute;
+ pointer-events: auto;
+}
+
+.pdf-editor-run-width-handle {
+ position: absolute;
+ left: calc(100% + 1px);
+ top: 50%;
+ width: 6px;
+ height: 14px;
+ translate: 0 -50%;
+ box-sizing: border-box;
+ border: 1px solid var(--c-border-strong);
+ border-radius: 3px;
+ background: var(--c-surface);
+ cursor: ew-resize;
+ pointer-events: auto;
+}
+
.pdf-editor-run.is-pristine,
.pdf-editor-run.is-pristine * {
color: transparent !important;
@@ -27,3 +53,8 @@
::highlight(pdf-editor-text-range) {
background-color: color-mix(in srgb, var(--c-primary) 28%, transparent);
}
+
+/* Must stay in sync with FIND_MATCH_HIGHLIGHT in overlayPainter.ts. */
+::highlight(pdf-editor-find-match) {
+ background-color: color-mix(in srgb, var(--c-highlight) 60%, transparent);
+}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/TextRunOverlay.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/TextRunOverlay.tsx
index 13cd38761d..40ed0e340a 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/components/TextRunOverlay.tsx
+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/TextRunOverlay.tsx
@@ -1,5 +1,13 @@
import { scanFaceCssFamily } from "@editor/tools/pdfTextEditor/util/scanFontLibrary";
-import { useEffect, useMemo, useRef, useState } from "react";
+import {
+ type CSSProperties,
+ type PointerEvent as ReactPointerEvent,
+ useEffect,
+ useMemo,
+ useRef,
+ useState,
+} from "react";
+import { createPortal } from "react-dom";
import { useTranslation } from "react-i18next";
import {
RENDER_MODE_INVISIBLE,
@@ -13,10 +21,8 @@ import {
resolveLang,
useSpellcheckPreference,
} from "@editor/tools/pdfTextEditor/util/spellcheck";
-import {
- embeddedFaceFamily,
- onEmbeddedFaceLoaded,
-} from "@editor/tools/pdfTextEditor/util/embeddedFace";
+import { embeddedFaceFamily } from "@editor/tools/pdfTextEditor/util/embeddedFace";
+import { useFontEpoch } from "@editor/tools/pdfTextEditor/hooks/useFontEpoch";
import {
isDeviceFontId,
nearestStandardFont,
@@ -36,6 +42,8 @@ import {
normalizeContainerCaret,
type PaintLine,
paintLines,
+ FIND_MATCH_HIGHLIGHT,
+ canHighlightTextRanges,
highlightTextRange,
paintPlainText,
plainCaretOffset,
@@ -44,29 +52,34 @@ import {
readOverlayText,
refitEditedTokens,
refitTokens,
+ repaintKeepingSelection,
restoreCaretOffset,
} from "@editor/tools/pdfTextEditor/util/overlayPainter";
+import { offsetAcrossRewrap } from "@editor/tools/pdfTextEditor/util/wrapCaret";
import {
cssFontShorthand,
+ measureAdvancePx,
measureFontMetrics,
measureLongestTokenWidth,
measureMaxLineWidth,
- resetTextMetricsCache,
} from "@editor/tools/pdfTextEditor/util/textMetrics";
+import {
+ lineWidthPx,
+ type MeasuredText,
+ mergeAdvances,
+ unpricedChars,
+} from "@editor/tools/pdfTextEditor/util/typedAdvances";
import { MIN_WRAP_WIDTH_EM } from "@editor/tools/pdfTextEditor/commands/ReflowWrapCommand";
import { serverFontCssFamily } from "@editor/tools/pdfTextEditor/util/serverFonts";
+import type { GrowEdge } from "@editor/tools/pdfTextEditor/util/growEdge";
import "@editor/tools/pdfTextEditor/components/TextRunOverlay.css";
const SETTLE_MS = 400;
const STALL_MS = 250;
-// Idle time before a wrap-mode run re-wraps. This has to be longer than the gap
-// between keystrokes: a reflow physically moves the glyph objects, so one that
-// lands mid-burst drags the text - and the caret - out from under the user.
-// Measured at 180ms it fired 10 times across 70 typed characters and produced
-// 13 backward caret jumps. It only needs to beat the user clicking away.
-const LIVE_WRAP_MS = 700;
+/** Must stay in sync with `.pdf-editor-run` padding in TextRunOverlay.css. */
+const BOX_PADDING_PX = 2;
// Un-measured keystrokes a run absorbs before the overlay takes over the
// glyphs. One or two are re-rendered fast enough to leave the page's own ink
@@ -269,19 +282,50 @@ function computeExactLayout(args: {
return { lines, leftPx, topPx: stack.topPx, widthPx, heightPx, signature };
}
+function measuredTextOf(run: TextRunSnapshot): MeasuredText | null {
+ const { charStartsX: starts, charEndsX: ends } = run;
+ if (!starts || !ends || starts.length !== run.text.length) return null;
+ return { text: run.text, starts, ends };
+}
+
// PDF advance per em for every character the run already carries. Scale-free,
-// so it stays valid as the user zooms.
+// so it stays valid as the user zooms. Each character is priced from its last
+// occurrence: the engine can draw typed letters at other advances than the
+// document's own, and the letters typed last are the ones the next keystroke
+// repeats.
function charAdvancesEm(run: TextRunSnapshot): Map<string, number> | null {
const starts = run.charStartsX;
const ends = run.charEndsX;
if (!starts || !ends || starts.length !== run.text.length) return null;
if (!(run.fontSize > 0)) return null;
const map = new Map<string, number>();
+ const price = (ch: string, widthPt: number) => {
+ if (Number.isFinite(widthPt) && widthPt > 0)
+ map.set(ch, widthPt / run.fontSize);
+ };
+ const placed = (i: number) =>
+ Number.isFinite(starts[i]) && Number.isFinite(ends[i]);
+ // A glyph's box is its ink, not its advance: neighbours overlap it. The pen
+ // moves from one glyph's start to the next one's.
+ for (let i = 0; i + 1 < run.text.length; i += 1) {
+ if (run.text[i + 1] === "\n" || !placed(i) || !placed(i + 1)) continue;
+ price(run.text[i], starts[i + 1] - starts[i]);
+ }
+ // A space the PDF draws by advancing the pen has no box of its own, so it
+ // takes what is left of the step between the glyphs either side of it.
for (let i = 0; i < run.text.length; i += 1) {
- const width = ends[i] - starts[i];
- if (!Number.isFinite(width) || width <= 0) continue;
- const ch = run.text[i];
- if (!map.has(ch)) map.set(ch, width / run.fontSize);
+ if (!placed(i) || run.text[i] === "\n") continue;
+ let j = i + 1;
+ while (j < run.text.length && run.text[j] !== "\n" && !placed(j)) j += 1;
+ const gap = j - i - 1;
+ const own = map.get(run.text[i]);
+ if (gap === 0 || j >= run.text.length || run.text[j] === "\n") {
+ if (own === undefined) price(run.text[i], ends[i] - starts[i]);
+ continue;
+ }
+ if (own === undefined) continue;
+ const each = (starts[j] - starts[i] - own * run.fontSize) / gap;
+ for (let k = i + 1; k < j; k += 1) price(run.text[k], each);
}
return map.size > 0 ? map : null;
}
@@ -312,58 +356,169 @@ interface TextRunOverlayProps {
/** Raw-PDF -> display (CropBox/rotation) transform. */
transform: DisplayTransform;
scale: number;
- /** "grow": box widens to the right. "wrap": locked width, wraps down. */
+ /** "grow": box widens to the right up to the page edge, then wraps. "wrap": locked width, wraps down. */
widthMode: WidthMode;
+ /** Other text set beside the run on its rows, which Grow wraps short of as it does the page edge. */
+ growEdge?: GrowEdge | null;
selected: boolean;
- /** True when this run is the active find-match (yellow highlight). */
- highlighted?: boolean;
+ /** The find-bar occurrence inside this run, painted as a highlight. */
+ findRange?: TextRange | null;
pageRevision?: number;
onSelect: (shiftKey: boolean) => void;
onEdit: (nextText: string) => void;
/** Fires when the user Ctrl+drags the run to a new position. dx/dy are PDF points. */
onMove?: (dx: number, dy: number) => void;
- // Fires on blur in Wrap mode when the edited content overflows the locked box
- // width.
- onWrap?: (maxWidthPt: number) => void;
+ /**
+ * Fires when typed text overflows the box: past the locked width in Wrap,
+ * past the page edge in Grow, which asks to keep clear of what lies below.
+ * Runs synchronously and returns the run's text after the wrap, or null when
+ * the wrap was refused.
+ */
+ onWrap?: (
+ maxWidthPt: number,
+ keepClearBelow?: boolean,
+ ) => string | null | void;
+ /**
+ * The run with the engine's pen positions for its current text, read
+ * synchronously. Costs a re-read of the page, so the box calls it only for
+ * a letter it has no PDF advance for, for a line that looks to cross the
+ * edge, and once a wrap has moved the lines.
+ */
+ onMeasure?: () => TextRunSnapshot | null;
/** Fires when the user drags the right edge to a new width, in PDF points. */
onResize?: (widthPt: number) => void;
/** Fires while the box has focus, as the characters selected inside it change. */
onTextRangeChange?: (range: TextRange | null) => void;
/** The characters selected inside the box, highlighted while it has no focus. */
textRange?: TextRange | null;
+ /**
+ * Where the move/width grips render: a layer in the same positioned parent
+ * as the box, painted beneath every run. Without it the box has no grips.
+ */
+ gripLayer?: HTMLElement | null;
}
/**
- * Which gesture the pointer is over: the frame, the right edge, or the text
- * interior. The right edge re-wraps the run to a new width; the rest of the
- * frame moves it.
+ * Which grip the pointer is over: the right edge re-wraps the run to a new
+ * width; the rest of the frame moves it.
*/
-type EdgeZone = "move" | "resize" | null;
+type EdgeZone = "move" | "resize";
+
+/** How far the grip bands reach outside the box, and into it, in CSS px. */
+const GRIP_OUT_PX = 5;
+const GRIP_IN_PX = 1;
-/** Grab band around the box, in CSS px. Matches the visible ring's reach. */
-const EDGE_PX = 7;
+const GRIP_BANDS: ReadonlyArray<{
+ side: "top" | "bottom" | "left" | "right";
+ style: CSSProperties;
+}> = [
+ {
+ side: "top",
+ style: {
+ left: -GRIP_OUT_PX,
+ right: -GRIP_OUT_PX,
+ top: -GRIP_OUT_PX,
+ height: GRIP_OUT_PX + GRIP_IN_PX,
+ },
+ },
+ {
+ side: "bottom",
+ style: {
+ left: -GRIP_OUT_PX,
+ right: -GRIP_OUT_PX,
+ bottom: -GRIP_OUT_PX,
+ height: GRIP_OUT_PX + GRIP_IN_PX,
+ },
+ },
+ {
+ side: "left",
+ style: {
+ left: -GRIP_OUT_PX,
+ top: 0,
+ bottom: 0,
+ width: GRIP_OUT_PX + GRIP_IN_PX,
+ },
+ },
+ {
+ side: "right",
+ style: {
+ right: -GRIP_OUT_PX,
+ top: 0,
+ bottom: 0,
+ width: GRIP_OUT_PX + GRIP_IN_PX,
+ },
+ },
+];
/**
- * Classify a pointer position against the run's own box.
- *
- * The box is contentEditable, so handles cannot be child elements without
- * becoming editable content. Hit-testing the border band instead gives the
- * same affordance with no DOM inside the editable region.
+ * The caret for a click inside the box but above its first line or below its
+ * last, where the browser would otherwise put it at the end of the text.
*/
-function edgeZoneAt(
+function caretBesideLines(
el: HTMLElement,
clientX: number,
clientY: number,
- canResize: boolean,
-): EdgeZone {
- const r = el.getBoundingClientRect();
- const nearLeft = clientX - r.left <= EDGE_PX;
- const nearRight = r.right - clientX <= EDGE_PX;
- const nearTop = clientY - r.top <= EDGE_PX;
- const nearBottom = r.bottom - clientY <= EDGE_PX;
- if (canResize && nearRight && !nearTop && !nearBottom) return "resize";
- if (nearTop || nearBottom || nearLeft || nearRight) return "move";
- return null;
+): Range | null {
+ const text = document.createRange();
+ text.selectNodeContents(el);
+ const r = text.getBoundingClientRect();
+ if (r.height <= 2 || (clientY >= r.top && clientY <= r.bottom)) return null;
+ const boxes = Array.from(text.getClientRects()).filter((b) => b.height > 2);
+ const line =
+ boxes.length === 0
+ ? r
+ : clientY < r.top
+ ? boxes.reduce((a, b) => (b.top < a.top ? b : a))
+ : boxes.reduce((a, b) => (b.bottom > a.bottom ? b : a));
+ // The middle of the nearest line: near the edge of its line box WebKit's
+ // hit test misses the glyphs and returns the end of the text.
+ const y = (line.top + line.bottom) / 2;
+ const position = document.caretPositionFromPoint?.(clientX, y);
+ const caret = position
+ ? document.createRange()
+ : (document.caretRangeFromPoint?.(clientX, y) ?? null);
+ if (position && caret) caret.setStart(position.offsetNode, position.offset);
+ if (!caret || !el.contains(caret.startContainer)) return null;
+ caret.collapse(true);
+ return caret;
+}
+
+/** The line of `text` holding character offset `offset`, and its index. */
+function lineAt(text: string, offset: number): { index: number; text: string } {
+ const lines = text.split("\n");
+ let start = 0;
+ for (let index = 0; index < lines.length; index += 1) {
+ const end = start + lines[index].length;
+ if (offset <= end) return { index, text: lines[index] };
+ start = end + 1;
+ }
+ return { index: lines.length - 1, text: lines[lines.length - 1] };
+}
+
+/** Where the collapsed caret inside `el` is drawn, or null without one. */
+function caretClientX(el: HTMLElement): number | null {
+ const selection = window.getSelection();
+ if (!selection?.rangeCount || !el.contains(selection.focusNode)) return null;
+ const caret = selection.getRangeAt(0).cloneRange();
+ caret.collapse(false);
+ const rects = caret.getClientRects();
+ const rect = rects.length > 0 ? rects[0] : caret.getBoundingClientRect();
+ return rect.width === 0 && rect.height === 0 && rect.x === 0 ? null : rect.x;
+}
+
+// The room `edge` leaves a box whose left sits at `leftPx`, in CSS px. A turned page lays the page's x along the screen's y, where Grow does not reach.
+function growEdgeRoomPx(
+ edge: GrowEdge | null | undefined,
+ run: TextRunSnapshot,
+ transform: DisplayTransform,
+ scale: number,
+ leftPx: number,
+): number {
+ if (!edge || transform.rotate !== 0) return Number.POSITIVE_INFINITY;
+ const edgePx = transform.apply(edge.x, run.matrix.f).x * scale;
+ if (edge.side === "right") return edgePx - leftPx;
+ const end = run.bounds.x + run.bounds.width;
+ return transform.apply(end, run.matrix.f).x * scale - edgePx;
}
/** One editable HTML element per PDF text run. */
@@ -374,16 +529,19 @@ export function TextRunOverlay({
transform,
scale,
widthMode,
+ growEdge,
selected,
- highlighted,
+ findRange,
pageRevision,
onSelect,
onEdit,
onMove,
onWrap,
+ onMeasure,
onResize,
onTextRangeChange,
textRange,
+ gripLayer,
}: TextRunOverlayProps) {
const { t } = useTranslation();
// Subscribed, so toggling the preference re-renders every overlay.
@@ -428,7 +586,7 @@ export function TextRunOverlay({
// run on a coloured page got a grey band. Sampled from the rendered bitmap
// once per focus, so the read never lands in the typing path.
const [maskColor, setMaskColor] = useState<string | null>(null);
- const [faceEpoch, setFaceEpoch] = useState(0);
+ const faceEpoch = useFontEpoch();
// True between compositionstart and compositionend (IME). While composing
// onInput must not dispatch per-keystroke edits; we commit once on end.
const composingRef = useRef(false);
@@ -442,9 +600,20 @@ export function TextRunOverlay({
const [dragOffset, setDragOffset] = useState<{ x: number; y: number } | null>(
null,
);
- // Which edge the pointer is over, so the cursor can advertise the gesture
- // before the user commits to it. Null means the text interior.
- const [edgeZone, setEdgeZone] = useState<EdgeZone>(null);
+ const [gripZone, setGripZone] = useState<EdgeZone | null>(null);
+ const gripsRef = useRef<HTMLDivElement | null>(null);
+ // The grips frame is a sibling, so it is sized from the box's rendered
+ // border box: the box grows with its text past the height it is given.
+ const [boxSize, setBoxSize] = useState<{ w: number; h: number } | null>(null);
+ useEffect(() => {
+ const el = ref.current;
+ if (!el || typeof ResizeObserver === "undefined") return;
+ const observer = new ResizeObserver(() =>
+ setBoxSize({ w: el.offsetWidth, h: el.offsetHeight }),
+ );
+ observer.observe(el);
+ return () => observer.disconnect();
+ }, []);
// Live box width while the right edge is being dragged, in CSS px.
const [resizeWidthPx, setResizeWidthPx] = useState<number | null>(null);
// Detaches an in-flight resize's window listeners, so a cancelled or
@@ -452,6 +621,16 @@ export function TextRunOverlay({
const endResizeRef = useRef<(() => void) | null>(null);
useEffect(() => () => endResizeRef.current?.(), []);
const originalBoundsWidthRef = useRef<number>(run.bounds.width);
+ // The widest line when focus arrived: Grow wraps only what is typed past the page edge, never a line the document already set wider.
+ const focusWidestRef = useRef(0);
+ // Set when a Grow wrap was refused for want of room below: the box then grows past the page edge for the rest of this edit rather than draw over what is there.
+ const [growBlocked, setGrowBlocked] = useState(false);
+ // Content width the typed text needs beyond the laid-out box, in CSS px,
+ // until the next wrap or focus change.
+ const [fitWidthPx, setFitWidthPx] = useState<number | null>(null);
+ const unwrappedLineRef = useRef<{ index: number; width: number } | null>(
+ null,
+ );
// Whether this run was a real (multi-line) paragraph when it first mounted.
const faceName = run.scanFamily ?? run.fontId;
@@ -532,27 +711,28 @@ export function TextRunOverlay({
const advanceEm = useMemo(() => charAdvancesEm(run), [run]);
// Kept across the edit: the engine drops the pen positions the moment the
- // text changes, and a token typed into needs them most right then.
+ // text changes, and a token typed into needs them most right then. Letters
+ // learned from a measure mid-burst stay until the face changes.
const heldAdvanceEmRef = useRef<Map<string, number> | null>(null);
- if (advanceEm) heldAdvanceEmRef.current = advanceEm;
-
- useEffect(() => {
- const bump = () => {
- resetTextMetricsCache();
- setFaceEpoch((n) => n + 1);
- };
- const unsubscribe = onEmbeddedFaceLoaded(bump);
- let cancelled = false;
- if (typeof document !== "undefined" && document.fonts) {
- void document.fonts.ready.then(() => {
- if (!cancelled) bump();
- });
- }
- return () => {
- cancelled = true;
- unsubscribe();
- };
- }, []);
+ const heldAdvanceFaceRef = useRef("");
+ const advanceFace = `${run.fontId}\u0000${run.fontSize}`;
+ if (heldAdvanceFaceRef.current !== advanceFace) {
+ heldAdvanceFaceRef.current = advanceFace;
+ heldAdvanceEmRef.current = null;
+ }
+ if (advanceEm)
+ heldAdvanceEmRef.current = mergeAdvances(
+ heldAdvanceEmRef.current,
+ advanceEm,
+ );
+ // Letters a measure could not price, such as a mark with no advance of its
+ // own, so a burst does not re-read the page for them on every keystroke.
+ const unpriceableRef = useRef(new Set<string>());
+ // The latest text the engine gave pen positions for, from the run or from a
+ // measure taken mid-keystroke, whichever is newer.
+ const measuredRef = useRef<MeasuredText | null>(null);
+ const runMeasured = measuredTextOf(run);
+ if (runMeasured) measuredRef.current = runMeasured;
useEffect(() => {
const el = ref.current;
@@ -590,6 +770,20 @@ export function TextRunOverlay({
fontSizePx,
advanceEm: heldAdvanceEmRef.current,
};
+ const livePaintOpts = () => ({
+ ...paintOpts,
+ advanceEm: heldAdvanceEmRef.current,
+ });
+ const lineWidth = (text: string, lineIndex: number) =>
+ lineWidthPx(
+ text,
+ lineIndex,
+ measuredRef.current,
+ heldAdvanceEmRef.current,
+ fontSizePx,
+ scale,
+ (ch) => measureAdvancePx(ch, font),
+ );
useEffect(() => {
if (!layoutIsGuessed) {
@@ -661,18 +855,15 @@ export function TextRunOverlay({
// Keyed off the selection, not the focus: replaceChildren below detaches
// whatever node the caret sits in, and a caret this run holds without being
// document.activeElement is still a caret the next insert needs.
- const caret = plainCaretOffset(el);
- if (freshExact) {
- paintLines(el, freshExact.lines, paintOpts);
- } else {
- paintPlainText(el, run.text);
- }
- paintedSignatureRef.current = wantSignature;
// Only while the run still holds focus. A selection outlives the blur that
// ended the edit, so re-seating it into a blurred run takes focus BACK -
// and the user's next click elsewhere then fires this run's blur handler,
// dispatching a spurious wrap that also wipes the redo stack.
- if (caret !== null && ownsFocus) restoreCaretOffset(el, caret);
+ repaintKeepingSelection(el, ownsFocus, () => {
+ if (freshExact) paintLines(el, freshExact.lines, paintOpts);
+ else paintPlainText(el, run.text);
+ });
+ paintedSignatureRef.current = wantSignature;
}, [run.text, freshExact, font, fontSizePx, touched, faceEpoch]);
// After the paint above, which replaces the nodes a range would hold. The
@@ -685,6 +876,13 @@ export function TextRunOverlay({
return range ? highlightTextRange(range) : undefined;
}, [focused, textRange, run.text, freshExact, font, fontSizePx, faceEpoch]);
+ useEffect(() => {
+ const el = ref.current;
+ if (!findRange || !el) return;
+ const range = plainDomRange(el, findRange);
+ return range ? highlightTextRange(range, FIND_MATCH_HIGHLIGHT) : undefined;
+ }, [findRange, run.text, freshExact, font, fontSizePx, faceEpoch]);
+
const anchor = transform.apply(run.matrix.e, run.matrix.f);
const flowLeft = anchor.x * scale;
@@ -724,18 +922,21 @@ export function TextRunOverlay({
(run.wrapWidthPt ?? originalBoundsWidthRef.current) * scale,
fontSizePx * MIN_WRAP_WIDTH_EM,
);
- // The mode the user picked, and nothing else. Forcing a paragraph to wrap in
- // Grow made the two modes indistinguishable for body text and contradicted
- // the control's own hint ("Boxes widen to the right as you type (no
- // wrapping)").
+ // The mode the user picked, and nothing else: wrapping a paragraph in Grow
+ // before it reaches the page edge makes the two modes indistinguishable.
const wantWrap = wrapMode;
const left = exact ? exact.leftPx : flowLeft;
- // Wrap keeps the box on the page - that is the whole point of the mode, and
- // its overflow goes onto new lines instead. Grow has nowhere to put the
- // overflow, so capping it there just hides what the user is typing: it grew
- // to the page edge and then clipped everything beyond, measured at 2944px of
- // invisible text on a single-line run.
+ // Both modes keep typed text on the page: Wrap at its locked width, Grow once
+ // the box reaches the page edge or the text set beside it, never narrower
+ // than the run already is.
const pageCap = Math.max(fontSizePx * 4, pageWidth * scale - left - 4);
+ const growCap = Math.min(
+ pageCap,
+ Math.max(
+ growEdgeRoomPx(growEdge, run, transform, scale, left),
+ originalBoundsWidthRef.current * scale,
+ ),
+ );
// Wrapping cannot break inside a word, so a box narrower than the longest one
// hides its tail however the lines are broken - 707px of a held-down key
// measured invisible, with the caret out there past the box edge.
@@ -749,6 +950,10 @@ export function TextRunOverlay({
Math.min(wrapLockWidth, pageCap),
longestTokenWidth + fontSizePx,
);
+ // The reflow lays text out along the page axis, so a turned run keeps growing.
+ const growWraps = !wantWrap && !!onWrap && !runRotation && !growBlocked;
+ const growWrapWidth = Math.max(growCap, longestTokenWidth + fontSizePx);
+ const growOverflowWidth = Math.max(growWrapWidth, focusWidestRef.current);
const maxOnPageWidth = wantWrap ? pageCap : Number.POSITIVE_INFINITY;
const naturalWidth = wantWrap
? wrapLockWidth
@@ -757,55 +962,185 @@ export function TextRunOverlay({
const top = exact ? exact.topPx : flowTop;
// Width must not depend on anything that can flip between renders, or the box
- // visibly pumps between two sizes while the user types. Two things could:
- // room for the caret appeared only WHILE focused, and the measured fallback
- // dropped out the moment `freshExact` arrived. The engine now re-measures
- // every 100ms, so both flipped about ten times a second. Always keep the
- // slack, always take the wider of the two - the result is a pure function of
- // the layout, the text and the font, and a few pixels of margin costs
- // nothing next to a box that will not sit still.
+ // visibly pumps between two sizes while the user types: caret room kept only
+ // while focused, or the measured fallback dropped once `freshExact` arrives,
+ // would each flip with the engine's 100ms re-measure. So the slack is always
+ // kept and the wider of the two always taken.
const exactWidth = exact
? Math.max(exact.widthPx + fontSizePx * 0.5, measuredWidth + fontSizePx)
: 0;
- // Capped at the page edge: an editing box hanging off the page reads as
- // broken, and the glyphs under it would be off-page anyway.
- //
- // A line longer than that is therefore clipped while it is being typed, and
- // the reflow on blur brings it back onto the page. The alternative - letting
- // the box wrap the line - is what put the overlay a full line out of register
- // with the bitmap: the PDF draws each line as ONE text object at one pen
- // origin and cannot wrap, so an overlay that wraps stops describing the page
- // underneath it.
- // Wrap holds its width and pushes overflow onto new lines; widening to the
- // page edge instead is Grow's job, and doing both makes the modes identical.
+ // Grow stops at the page edge or the text beside it, or at the document's
+ // own width for a line it set wider than that, focused or not so the box
+ // keeps its size across a blur; the live reflow below moves the overflow
+ // onto new lines. The box itself never wraps: the PDF draws each line as ONE
+ // text object at one pen origin, so an overlay that wrapped by CSS would
+ // stop describing the page underneath it.
const userWidthPx = (run.wrapWidthPt ?? 0) * scale;
- const width = wantWrap
+ const grownWidth = exact ? exactWidth : flowWidth;
+ const laidOutWidth = wantWrap
? wrapWidth
- : Math.max(exact ? exactWidth : flowWidth, userWidthPx);
+ : Math.max(
+ growWraps
+ ? Math.min(
+ grownWidth,
+ Math.max(
+ growWrapWidth,
+ originalBoundsWidthRef.current * scale + fontSizePx,
+ ),
+ )
+ : grownWidth,
+ userWidthPx,
+ );
+ const width =
+ fitWidthPx === null ? laidOutWidth : Math.max(laidOutWidth, fitWidthPx);
const height = exact ? exact.heightPx : flowHeight;
// An exact layout is never wrapped - its lines are the PDF's own. Only the
// plain-text fallback, where CSS flow genuinely owns the layout, may wrap.
const whiteSpace: "pre" | "pre-wrap" =
!exact && wantWrap ? "pre-wrap" : "pre";
- // Wrap AS THE USER TYPES, not only on blur. Deferring it meant the overflow
- // sat invisible past the box edge until they clicked away - over a thousand
- // pixels of it - and the caret only dropped onto the new line at that point.
- // The reflow shares EditTextCommand's coalesce key and ignores the time
- // window, so running it mid-burst does not fragment undo.
- const wrapTarget = wrapWidth;
- useEffect(() => {
- if (!wantWrap || !onWrap || !focused) return;
- const el = ref.current;
- if (!el || composingRef.current) return;
- const widest = measureMaxLineWidth(readOverlayText(el), font);
- if (widest <= wrapTarget + 1) return;
- const timer = window.setTimeout(
- () => onWrap(wrapTarget / scale),
- LIVE_WRAP_MS,
+ // Wrap AS THE USER TYPES, on the keystroke that crosses the edge, and paint
+ // the wrapped text into the box before the next key can arrive. The reflow
+ // turns a space into a line break in the model; a DOM still holding the space
+ // hands it back on the next keystroke's edit, so a wrap the box did not
+ // mirror at once was undone by every key typed after it. It shares
+ // EditTextCommand's coalesce key and ignores the time window, so running it
+ // mid-burst does not fragment undo.
+ function wrapTypedText(el: HTMLDivElement, text: string): boolean {
+ if (!onWrap || !(wantWrap || growWraps)) return false;
+ const longest = measureLongestTokenWidth(text, font) + fontSizePx;
+ const target = wantWrap
+ ? Math.max(Math.min(wrapLockWidth, pageCap), longest)
+ : Math.max(growCap, longest);
+ const overflowAt = wantWrap
+ ? target
+ : Math.max(target, focusWidestRef.current);
+ // Only the line being typed on: the canvas can measure a line the document
+ // set a few points wider than the PDF draws it, and a reflow on every
+ // keystroke for a line the PDF says fits costs more the longer the burst.
+ const caret = plainCaretOffset(el);
+ const line = lineAt(text, caret ?? text.length);
+ // A space typed at the edge waits for the letter after it: wrapping on it
+ // would leave nothing on the new line for the caret to follow.
+ let width = lineWidth(text, line.index);
+ if (width <= overflowAt) return false;
+ // Priced letters can land a pixel either side of the PDF's, and the reflow
+ // judges by the PDF's: asking it on a price alone gets a refusal, and the
+ // half-em retry below then breaks the line two keys late.
+ if (onMeasure && measuredRef.current?.text !== text) {
+ const measured = onMeasure();
+ if (measured?.text === text) {
+ learnAdvances(measured);
+ width = lineWidth(text, line.index);
+ if (width <= overflowAt) return false;
+ }
+ }
+ // A line the reflow left as it was is retried once it is half an em wider.
+ const unwrapped = unwrappedLineRef.current;
+ if (
+ unwrapped?.index === line.index &&
+ width < unwrapped.width + fontSizePx * 0.5
+ ) {
+ return false;
+ }
+ const wrapped = wantWrap
+ ? onWrap(target / scale)
+ : onWrap(target / scale, true);
+ if (wrapped === null) {
+ setGrowBlocked(true);
+ return false;
+ }
+ if (typeof wrapped !== "string" || wrapped === text) {
+ unwrappedLineRef.current = { index: line.index, width };
+ return false;
+ }
+ unwrappedLineRef.current = null;
+ paintMeasured(el, wrapped);
+ if (caret !== null)
+ restoreCaretOffset(el, offsetAcrossRewrap(text, caret, wrapped));
+ setFitWidthPx(null);
+ return true;
+ }
+
+ // Lays `text` out where the PDF now draws it, read in this keystroke: a
+ // later repaint from the debounced re-measure then finds nothing to move.
+ // Plain text, laid out on the browser's advances, when it cannot be read.
+ function paintMeasured(el: HTMLDivElement, text: string): void {
+ const measured = onMeasure?.() ?? null;
+ const layout =
+ measured && measured.text === text && !runRotation
+ ? computeExactLayout({
+ run: measured,
+ transform,
+ pageHeight,
+ scale,
+ font,
+ fontSizePx,
+ lineHeightPx,
+ ascent,
+ descent,
+ })
+ : null;
+ if (measured) learnAdvances(measured);
+ if (layout) {
+ paintLines(el, layout.lines, livePaintOpts());
+ paintedSignatureRef.current = layout.signature;
+ } else {
+ paintPlainText(el, text);
+ paintedSignatureRef.current = "";
+ }
+ }
+
+ function learnAdvances(measured: TextRunSnapshot): void {
+ measuredRef.current = measuredTextOf(measured) ?? measuredRef.current;
+ heldAdvanceEmRef.current = mergeAdvances(
+ heldAdvanceEmRef.current,
+ charAdvancesEm(measured),
);
- return () => window.clearTimeout(timer);
- }, [wantWrap, onWrap, focused, editTick, wrapTarget, font, scale]);
+ }
+
+ // Prices every letter of `text` from the PDF before the keystroke is laid
+ // out, reading the run once for any letter not priced yet: a letter priced
+ // on the browser's advance is drawn wider or narrower than the page draws
+ // it, and correcting it later moves the caret back under the user.
+ function priceTypedLetters(text: string): void {
+ if (!onMeasure) return;
+ const unpriced = unpricedChars(text, heldAdvanceEmRef.current);
+ for (const ch of unpriceableRef.current) unpriced.delete(ch);
+ if (unpriced.size === 0) return;
+ const measured = onMeasure();
+ if (!measured || measured.text !== text) return;
+ learnAdvances(measured);
+ for (const ch of unpriced)
+ if (!heldAdvanceEmRef.current?.has(ch)) unpriceableRef.current.add(ch);
+ }
+
+ function commitTypedText(el: HTMLDivElement, raw: string): void {
+ const text = raw.replace(/\u00A0/g, " ");
+ onEdit(text);
+ priceTypedLetters(text);
+ // Re-fit the token the user just typed into. Its painted width is the
+ // PDF's advance for the ORIGINAL string, so leaving it alone lays the
+ // new text out at the browser's own advances and the caret drifts off
+ // the glyphs on the page, a pixel or so per keystroke.
+ if (isLinePainted(el)) refitEditedTokens(el, livePaintOpts());
+ if (!wrapTypedText(el, text)) fitTypedText(el);
+ }
+
+ // Widen the box to keep the caret in it when the line it is typing on did
+ // not wrap, such as one drawn as a single PDF object with no break to take.
+ // The box clips, so without this the text and the caret sit out of sight
+ // past its edge. Half an em is left clipped: the browser draws freshly
+ // typed letters up to that much wider than the PDF until the engine
+ // re-measures them, and the PDF wraps them on the next key.
+ function fitTypedText(el: HTMLDivElement): void {
+ const caretX = caretClientX(el);
+ if (caretX === null) return;
+ const box = el.getBoundingClientRect();
+ const contentLeft = box.left + BOX_PADDING_PX;
+ if (caretX <= box.right - BOX_PADDING_PX + fontSizePx * 0.5) return;
+ setFitWidthPx(Math.ceil(caretX - contentLeft) + 1);
+ }
// Which dictionary the browser should load. "auto" falls back to the
// page's own language, which is what the element would inherit anyway.
@@ -852,6 +1187,52 @@ export function TextRunOverlay({
window.addEventListener("pointercancel", onPointerCancel);
}
+ // Below the drag threshold nothing moved: from a grip that is a plain click
+ // (select); with Ctrl held it is the multi-select gesture it looks like.
+ function startMove(
+ originX: number,
+ originY: number,
+ viaGrip: boolean,
+ commit: (dx: number, dy: number) => void,
+ ) {
+ dragOriginRef.current = { x: originX, y: originY };
+ setDragging(true);
+ setDragOffset({ x: 0, y: 0 });
+ // Pointer events (mouse/pen/touch) with a global capture so the
+ // drag keeps tracking even if the cursor leaves the overlay.
+ const onPointerMove = (ev: PointerEvent) => {
+ const origin = dragOriginRef.current;
+ if (!origin) return;
+ setDragOffset({
+ x: ev.clientX - origin.x,
+ y: ev.clientY - origin.y,
+ });
+ };
+ const onPointerUp = (ev: PointerEvent) => {
+ window.removeEventListener("pointermove", onPointerMove);
+ window.removeEventListener("pointerup", onPointerUp);
+ setDragging(false);
+ setDragOffset(null);
+ const origin = dragOriginRef.current;
+ dragOriginRef.current = null;
+ if (!origin) return;
+ // Screen delta -> display-PDF delta, then invert the linear part of
+ // the CropBox/rotation transform to a raw-PDF delta.
+ const ddx = (ev.clientX - origin.x) / scale;
+ const ddy = -(ev.clientY - origin.y) / scale;
+ const v = transform.invertVector(ddx, ddy);
+ const dx = v.x;
+ const dy = v.y;
+ if (Math.abs(dx) < 0.5 && Math.abs(dy) < 0.5) {
+ onSelect(!viaGrip);
+ return;
+ }
+ commit(dx, dy);
+ };
+ window.addEventListener("pointermove", onPointerMove);
+ window.addEventListener("pointerup", onPointerUp);
+ }
+
const spellcheckLang = resolveLang(
spellcheck,
typeof document === "undefined" ? null : document.documentElement.lang,
@@ -859,13 +1240,123 @@ export function TextRunOverlay({
const pristine = !showsGlyphs;
- return (
+ const boxTransform =
+ [
+ dragOffset ? `translate(${dragOffset.x}px, ${dragOffset.y}px)` : "",
+ // Turn the box with the text. Placed before scaleX so the fit still
+ // stretches along the run's own axis rather than the page's.
+ runRotation ? `rotate(${runRotation.deg}deg)` : "",
+ fit.scaleX !== 1 ? `scaleX(${fit.scaleX})` : "",
+ ]
+ .filter(Boolean)
+ .join(" ") || undefined;
+ // Rotate about the text's own origin - the left end of its first
+ // baseline - which is the point the flow geometry positions. Otherwise
+ // scale from the run's own origin, never its centre.
+ const boxTransformOrigin = runRotation
+ ? `0 ${firstBaselineFromTop}px`
+ : fit.scaleX !== 1
+ ? "0 50%"
+ : undefined;
+
+ const isOwnElement = (target: EventTarget | null) =>
+ target instanceof Node &&
+ (!!ref.current?.contains(target) || !!gripsRef.current?.contains(target));
+ const leaveHover = (e: { relatedTarget: EventTarget | null }) => {
+ setGripZone(null);
+ if (!isOwnElement(e.relatedTarget)) setHovered(false);
+ };
+ const startGrip = (e: ReactPointerEvent<HTMLDivElement>, zone: EdgeZone) => {
+ if ((e.ctrlKey || e.metaKey) && e.shiftKey) return;
+ e.stopPropagation();
+ e.preventDefault();
+ ref.current?.blur();
+ if (zone === "resize" && onResize) {
+ startResize(e.clientX, e.pointerId, onResize);
+ } else if (onMove) {
+ startMove(e.clientX, e.clientY, true, onMove);
+ }
+ };
+ const showGrips =
+ !run.locked &&
+ (!!onMove || canResize) &&
+ (hovered || selected || dragging || resizeWidthPx !== null);
+ const gripProps = (zone: EdgeZone) => ({
+ onPointerDown: (e: ReactPointerEvent<HTMLDivElement>) => startGrip(e, zone),
+ onMouseEnter: () => {
+ setHovered(true);
+ setGripZone(zone);
+ },
+ onMouseLeave: leaveHover,
+ });
+ const resizeHandleLabel = t(
+ "pdfTextEditor.run.resizeHandle",
+ "Drag to change the width; the text rewraps",
+ );
+ // Never a child of the box: inside the contentEditable the grips would
+ // become editable content.
+ const grips =
+ showGrips && gripLayer
+ ? createPortal(
+ <div
+ ref={gripsRef}
+ className="pdf-editor-run-grips"
+ data-testid={`pdf-editor-grips-${run.id}`}
+ onClick={(e) => e.stopPropagation()}
+ style={{
+ left,
+ top,
+ width: boxSize?.w ?? resizeWidthPx ?? width,
+ height: boxSize?.h ?? height,
+ transform: boxTransform,
+ transformOrigin: boxTransformOrigin,
+ }}
+ >
+ {GRIP_BANDS.map(({ side, style }) => {
+ const zone: EdgeZone =
+ side === "right" && canResize ? "resize" : "move";
+ if (zone === "move" && !onMove) return null;
+ return (
+ <div
+ key={side}
+ className="pdf-editor-run-grip"
+ data-grip={zone}
+ style={{
+ ...style,
+ cursor:
+ zone === "resize"
+ ? "ew-resize"
+ : dragging
+ ? "grabbing"
+ : "grab",
+ }}
+ {...gripProps(zone)}
+ />
+ );
+ })}
+ {canResize && (
+ <div
+ className="pdf-editor-run-width-handle"
+ data-testid={`pdf-editor-width-handle-${run.id}`}
+ role="separator"
+ aria-orientation="vertical"
+ aria-label={resizeHandleLabel}
+ title={resizeHandleLabel}
+ {...gripProps("resize")}
+ />
+ )}
+ </div>,
+ gripLayer,
+ )
+ : null;
+
+ const box = (
<div
ref={ref}
data-testid={`pdf-editor-run-${run.id}`}
data-run-id={run.id}
className={`pdf-editor-run${pristine ? " is-pristine" : ""}`}
- contentEditable={!run.locked}
+ contentEditable={!run.locked && !run.textReadOnly}
suppressContentEditableWarning
spellCheck={spellcheck.enabled && focused}
lang={spellcheckLang ?? undefined}
@@ -876,7 +1367,12 @@ export function TextRunOverlay({
"pdfTextEditor.run.lockedTitle",
"Locked - use the Unlock button to edit",
)
- : undefined
+ : run.textReadOnly
+ ? t(
+ "pdfTextEditor.run.readOnlyOrderTitle",
+ "This line's text can't be edited: it mixes right-to-left and left-to-right text in an order the editor can't redraw safely",
+ )
+ : undefined
}
onKeyDown={(e) => {
// A caret parked on the container (a click past the text lands there)
@@ -900,64 +1396,9 @@ export function TextRunOverlay({
e.stopPropagation();
// Locked runs are inert: no select, no drag, no edit.
if (run.locked) return;
- const zone = edgeZoneAt(
- e.currentTarget,
- e.clientX,
- e.clientY,
- canResize,
- );
- if (zone === "resize" && onResize) {
- e.preventDefault();
+ if ((e.ctrlKey || e.metaKey) && onMove) {
e.currentTarget.blur();
- startResize(e.clientX, e.pointerId, onResize);
- return;
- }
-
- // Ctrl+drag still moves from anywhere inside, so existing muscle
- // memory keeps working; grabbing the frame is the discoverable path.
- if ((e.ctrlKey || e.metaKey || zone === "move") && onMove) {
- const viaFrame = zone === "move" && !(e.ctrlKey || e.metaKey);
- if (viaFrame) e.preventDefault();
- dragOriginRef.current = { x: e.clientX, y: e.clientY };
- setDragging(true);
- setDragOffset({ x: 0, y: 0 });
- e.currentTarget.blur();
- // Pointer events (mouse/pen/touch) with a global capture so the
- // drag keeps tracking even if the cursor leaves the overlay.
- const onPointerMove = (ev: PointerEvent) => {
- const origin = dragOriginRef.current;
- if (!origin) return;
- setDragOffset({
- x: ev.clientX - origin.x,
- y: ev.clientY - origin.y,
- });
- };
- const onPointerUp = (ev: PointerEvent) => {
- window.removeEventListener("pointermove", onPointerMove);
- window.removeEventListener("pointerup", onPointerUp);
- setDragging(false);
- setDragOffset(null);
- const origin = dragOriginRef.current;
- dragOriginRef.current = null;
- if (!origin) return;
- // Screen delta -> display-PDF delta, then invert the linear part of
- // the CropBox/rotation transform to a raw-PDF delta.
- const ddx = (ev.clientX - origin.x) / scale;
- const ddy = -(ev.clientY - origin.y) / scale;
- const v = transform.invertVector(ddx, ddy);
- const dx = v.x;
- const dy = v.y;
- // Below the drag threshold nothing moved. From the frame that is
- // a plain click (select); with Ctrl held it is the multi-select
- // gesture it looks like.
- if (Math.abs(dx) < 0.5 && Math.abs(dy) < 0.5) {
- onSelect(!viaFrame);
- return;
- }
- onMove(dx, dy);
- };
- window.addEventListener("pointermove", onPointerMove);
- window.addEventListener("pointerup", onPointerUp);
+ startMove(e.clientX, e.clientY, false, onMove);
return;
}
// Shift-click EXTENDS the multi-object selection.
@@ -966,8 +1407,15 @@ export function TextRunOverlay({
onSelect(true);
return;
}
+ const caret = caretBesideLines(e.currentTarget, e.clientX, e.clientY);
+ if (caret) e.preventDefault();
pointerFocusRef.current = true;
e.currentTarget.focus({ preventScroll: true });
+ if (caret) {
+ const sel = window.getSelection();
+ sel?.removeAllRanges();
+ sel?.addRange(caret);
+ }
onSelect(false);
}}
onFocus={(e) => {
@@ -977,6 +1425,15 @@ export function TextRunOverlay({
const el = e.currentTarget;
// Remember the text at focus so blur can tell if the user edited it.
focusTextRef.current = readOverlayText(el);
+ setGrowBlocked(false);
+ setFitWidthPx(null);
+ unwrappedLineRef.current = null;
+ focusWidestRef.current = Math.max(
+ 0,
+ ...focusTextRef.current
+ .split("\n")
+ .map((_, i) => lineWidth(focusTextRef.current, i)),
+ );
const fromPointer = pointerFocusRef.current;
pointerFocusRef.current = false;
const sel = window.getSelection();
@@ -990,6 +1447,7 @@ export function TextRunOverlay({
}}
onBlur={(e) => {
setTouched(false);
+ setFitWidthPx(null);
setMaskColor(null);
setFocused(false);
// WebKit routes keystrokes to the SELECTION even when the element has
@@ -1008,13 +1466,16 @@ export function TextRunOverlay({
sel.removeAllRanges();
}
}
- // Wrap mode: when the just-edited content overflows the locked box
- // width.
- if (!wantWrap || !onWrap) return;
+ if (!onWrap || !(wantWrap || growWraps)) return;
const el = e.currentTarget;
const domText = readOverlayText(el);
if (domText === focusTextRef.current) return; // not edited
const widest = measureMaxLineWidth(domText, font);
+ if (!wantWrap) {
+ if (widest > growOverflowWidth + 1)
+ onWrap(growWrapWidth / scale, true);
+ return;
+ }
// Reflow to the box the user locked, NOT to `width` - with an exact
// layout that is however wide the text grew, so nothing ever overflows.
//
@@ -1029,8 +1490,7 @@ export function TextRunOverlay({
// Only when something actually overflows. Reflowing a paragraph
// unconditionally re-breaks lines the user never touched: the reflow
// rebuilds every line, so a two-character edit that still fits could
- // still move words between lines the moment the box lost focus. The
- // base branch never reflowed here at all.
+ // still move words between lines the moment the box lost focus.
if (widest <= target + 1) return;
onWrap(target / scale);
}}
@@ -1041,7 +1501,7 @@ export function TextRunOverlay({
composingRef.current = false;
// Commit the composed string once, like onInput's non-IME path.
const el = e.currentTarget;
- onEdit(readOverlayText(el).replace(/\u00A0/g, " "));
+ commitTypedText(el, readOverlayText(el));
}}
onInput={(e) => {
setTouched(true);
@@ -1050,32 +1510,12 @@ export function TextRunOverlay({
// Skip intermediate IME steps; compositionend commits the result.
if (composingRef.current || e.nativeEvent.isComposing) return;
const el = e.currentTarget;
- // Re-fit the token the user just typed into. Its painted width is the
- // PDF's advance for the ORIGINAL string, so leaving it alone lays the
- // new text out at the browser's own advances and the caret drifts off
- // the glyphs on the page, a pixel or so per keystroke.
- if (isLinePainted(el)) refitEditedTokens(el, paintOpts);
// Always read hard breaks only - never synthesise newlines from browser
// soft-wraps.
- const raw = readOverlayText(el);
- const text = raw.replace(/\u00A0/g, " ");
- onEdit(text);
- // No per-keystroke reflow: while focused, the box is CAPPED to the page
- // and wraps via CSS, so the editing view is always on-page.
+ commitTypedText(el, readOverlayText(el));
}}
onMouseEnter={() => setHovered(true)}
- onMouseLeave={() => {
- setHovered(false);
- setEdgeZone(null);
- }}
- onPointerMove={(e) => {
- // Only while idle: mid-drag the cursor is owned by the gesture.
- if (run.locked || dragging) return;
- if (resizeWidthPx !== null) return;
- setEdgeZone(
- edgeZoneAt(e.currentTarget, e.clientX, e.clientY, canResize),
- );
- }}
+ onMouseLeave={leaveHover}
style={{
left,
top,
@@ -1084,24 +1524,8 @@ export function TextRunOverlay({
// Live Ctrl+drag preview: follow the cursor via transform, and
// float above siblings + dim slightly so the move reads clearly.
// Drag preview and the width fit both live here, so compose them.
- transform:
- [
- dragOffset ? `translate(${dragOffset.x}px, ${dragOffset.y}px)` : "",
- // Turn the box with the text. Placed before scaleX so the fit still
- // stretches along the run's own axis rather than the page's.
- runRotation ? `rotate(${runRotation.deg}deg)` : "",
- fit.scaleX !== 1 ? `scaleX(${fit.scaleX})` : "",
- ]
- .filter(Boolean)
- .join(" ") || undefined,
- // Rotate about the text's own origin - the left end of its first
- // baseline - which is the point the flow geometry positions. Otherwise
- // scale from the run's own origin, never its centre.
- transformOrigin: runRotation
- ? `0 ${firstBaselineFromTop}px`
- : fit.scaleX !== 1
- ? "0 50%"
- : undefined,
+ transform: boxTransform,
+ transformOrigin: boxTransformOrigin,
opacity: dragging ? 0.75 : 1,
zIndex: dragging ? 20 : undefined,
// Only the opacity settle is animated.
@@ -1131,8 +1555,8 @@ export function TextRunOverlay({
: undefined,
backgroundColor: showsGlyphs
? (maskColor ?? contrastingMaskFor(run.fill))
- : highlighted
- ? "rgba(255,217,0,0.45)"
+ : findRange && !canHighlightTextRanges()
+ ? "color-mix(in srgb, var(--c-highlight) 45%, transparent)"
: selected
? "rgba(44,123,229,0.10)"
: hovered
@@ -1149,25 +1573,31 @@ export function TextRunOverlay({
: dragging
? "2px solid #2c7be5"
: selected
- ? edgeZone || resizeWidthPx !== null
+ ? gripZone || resizeWidthPx !== null
? "2px solid #2c7be5"
: "1px solid #2c7be5"
: hovered
? "1px dashed rgba(44,123,229,0.5)"
: "1px dashed transparent",
- // The cursor is the affordance: the box advertises move/resize on the
- // frame and keeps the I-beam over the text.
cursor: run.locked
? "default"
: dragging
? "grabbing"
- : resizeWidthPx !== null || edgeZone === "resize"
+ : resizeWidthPx !== null
? "ew-resize"
- : edgeZone === "move"
- ? "grab"
- : undefined,
- overflow: "hidden",
+ : undefined,
+ // Clip, never scroll: a box scrolled to keep the caret in view slides
+ // every glyph in it off the page's own. Typed text the box cannot
+ // wrap widens it instead (`fitWidthPx`).
+ overflow: "clip",
}}
/>
);
+
+ return (
+ <>
+ {grips}
+ {box}
+ </>
+ );
}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/TextRunOverlayFonts.test.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/TextRunOverlayFonts.test.tsx
new file mode 100644
index 0000000000..06a3f6db4c
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/TextRunOverlayFonts.test.tsx
@@ -0,0 +1,132 @@
+import { act, render, renderHook } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import {
+ pageSnapshot,
+ stubDocument,
+ stubbedPageView,
+ VisibleObserver,
+} from "@editor/tools/pdfTextEditor/components/pageViewTestSupport";
+import { useFontEpoch } from "@editor/tools/pdfTextEditor/hooks/useFontEpoch";
+import { Page } from "@editor/tools/pdfTextEditor/model/Page";
+import { PdfiumPageRenderer } from "@editor/tools/pdfTextEditor/pdfium/PdfiumPageRenderer";
+import { resetTextMetricsCache } from "@editor/tools/pdfTextEditor/util/textMetrics";
+import type { TextRunSnapshot } from "@editor/tools/pdfTextEditor/types";
+
+vi.mock("@editor/tools/pdfTextEditor/components/TableOverlay", () => ({
+ TableOverlay: () => null,
+}));
+
+vi.mock(
+ "@editor/tools/pdfTextEditor/util/textMetrics",
+ async (importOriginal) => ({
+ ...(await importOriginal<object>()),
+ resetTextMetricsCache: vi.fn(),
+ }),
+);
+
+class FakeFontFaceSet extends EventTarget {
+ status: FontFaceSetLoadStatus = "loaded";
+ readyReads = 0;
+ get ready(): Promise<FontFaceSet> {
+ this.readyReads++;
+ return Promise.resolve(this as unknown as FontFaceSet);
+ }
+}
+
+function textRun(i: number): TextRunSnapshot {
+ const y = 760 - i * 14;
+ return {
+ id: `p0-r${i}`,
+ pageIndex: 0,
+ bounds: { x: 40, y, width: 120, height: 12 },
+ matrix: { a: 1, b: 0, c: 0, d: 1, e: 40, f: y },
+ text: `Line ${i}`,
+ fontId: "base14:Helvetica",
+ fontSize: 12,
+ fill: { r: 0, g: 0, b: 0, a: 255 },
+ fontSubset: false,
+ };
+}
+
+function view(live: Page, runs: TextRunSnapshot[]) {
+ return stubbedPageView(stubDocument(live), pageSnapshot(live, runs));
+}
+
+describe("waiting for fonts on a page of many runs", () => {
+ const originalObserver = globalThis.IntersectionObserver;
+ let fonts: FakeFontFaceSet;
+
+ beforeEach(() => {
+ fonts = new FakeFontFaceSet();
+ Object.defineProperty(document, "fonts", {
+ configurable: true,
+ value: fonts,
+ });
+ globalThis.IntersectionObserver =
+ VisibleObserver as unknown as typeof IntersectionObserver;
+ vi.spyOn(HTMLCanvasElement.prototype, "getContext").mockReturnValue(null);
+ vi.spyOn(PdfiumPageRenderer, "render").mockImplementation(
+ async (_doc, page, scale) =>
+ PdfiumPageRenderer.rasterSize(
+ page.width,
+ page.height,
+ scale,
+ ) as ImageData,
+ );
+ vi.mocked(resetTextMetricsCache).mockClear();
+ });
+
+ afterEach(() => {
+ globalThis.IntersectionObserver = originalObserver;
+ Reflect.deleteProperty(document, "fonts");
+ for (const spy of [
+ HTMLCanvasElement.prototype.getContext,
+ PdfiumPageRenderer.render,
+ ])
+ if (vi.isMockFunction(spy)) spy.mockRestore();
+ });
+
+ it("clears the measurements once for the page when fonts finish loading, not once per run", async () => {
+ const live = new Page({ index: 0, pagePtr: 1, width: 600, height: 800 });
+ const runs = Array.from({ length: 40 }, (_, i) => textRun(i));
+ const { unmount } = render(view(live, runs));
+ await act(async () => {});
+ expect(
+ document.querySelectorAll('[data-testid^="pdf-editor-run-"]'),
+ ).toHaveLength(40);
+ expect(fonts.readyReads).toBeLessThanOrEqual(1);
+ vi.mocked(resetTextMetricsCache).mockClear();
+
+ act(() => {
+ fonts.dispatchEvent(new Event("loadingdone"));
+ });
+
+ expect(resetTextMetricsCache).toHaveBeenCalledTimes(1);
+ unmount();
+ });
+
+ it("moves every overlay to the new fonts together, and a later one starts there", () => {
+ const first = renderHook(() => useFontEpoch());
+ const second = renderHook(() => useFontEpoch());
+ const before = first.result.current;
+ expect(second.result.current).toBe(before);
+
+ act(() => {
+ fonts.dispatchEvent(new Event("loadingdone"));
+ });
+
+ expect(first.result.current).toBe(before + 1);
+ expect(second.result.current).toBe(before + 1);
+ expect(resetTextMetricsCache).toHaveBeenCalledTimes(1);
+ expect(renderHook(() => useFontEpoch()).result.current).toBe(before + 1);
+ });
+
+ it("waits for fonts still loading when the page opens", async () => {
+ fonts.status = "loading";
+ const { result } = renderHook(() => useFontEpoch());
+ const before = result.current;
+ await act(async () => {});
+ expect(result.current).toBe(before + 1);
+ expect(fonts.readyReads).toBe(1);
+ });
+});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/TextRunOverlayGrowWrap.test.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/TextRunOverlayGrowWrap.test.tsx
new file mode 100644
index 0000000000..1982b9cd3b
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/TextRunOverlayGrowWrap.test.tsx
@@ -0,0 +1,398 @@
+import { MantineProvider } from "@mantine/core";
+import { act, fireEvent, render, screen } from "@testing-library/react";
+import { useState } from "react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { TextRunOverlay } from "@editor/tools/pdfTextEditor/components/TextRunOverlay";
+import {
+ plainCaretOffset,
+ readOverlayText,
+} from "@editor/tools/pdfTextEditor/util/overlayPainter";
+import { DisplayTransform } from "@editor/tools/pdfTextEditor/model/DisplayTransform";
+import type {
+ TextRunSnapshot,
+ WidthMode,
+} from "@editor/tools/pdfTextEditor/types";
+import type { GrowEdge } from "@editor/tools/pdfTextEditor/util/growEdge";
+
+const CHAR_PX = 6;
+const longest = (text: string) =>
+ Math.max(...text.split(/\r?\n/).map((l) => l.length)) * CHAR_PX;
+
+// jsdom has no innerText setter, so the plain-text paint is spelled out with
+// the <br>s a browser would make of it.
+vi.mock(
+ "@editor/tools/pdfTextEditor/util/overlayPainter",
+ async (importOriginal) => ({
+ ...(await importOriginal<object>()),
+ paintPlainText: (el: HTMLElement, text: string) =>
+ el.replaceChildren(
+ ...text
+ .split("\n")
+ .flatMap((line, i) => [
+ ...(i > 0 ? [document.createElement("br")] : []),
+ document.createTextNode(line),
+ ]),
+ ),
+ }),
+);
+
+vi.mock(
+ "@editor/tools/pdfTextEditor/util/textMetrics",
+ async (importOriginal) => ({
+ ...(await importOriginal<object>()),
+ measureFontMetrics: () => ({ ascent: 9, descent: 3 }),
+ measureMaxLineWidth: (text: string) => longest(text),
+ measureAdvancePx: (text: string) => text.length * CHAR_PX,
+ measureLongestTokenWidth: (text: string) =>
+ Math.max(0, ...text.split(/\s+/).map((w) => w.length)) * CHAR_PX,
+ }),
+);
+
+// jsdom lays nothing out, so a range has no rects to read.
+Range.prototype.getClientRects = () => [] as unknown as DOMRectList;
+Range.prototype.getBoundingClientRect = () => new DOMRect();
+
+const PAGE_WIDTH = 200;
+const LEFT = 40;
+const PAGE_CAP = PAGE_WIDTH - LEFT - 4;
+
+function run(text: string): TextRunSnapshot {
+ return {
+ id: "r1",
+ pageIndex: 0,
+ bounds: { x: LEFT, y: 700, width: longest(text), height: 12 },
+ matrix: { a: 1, b: 0, c: 0, d: 1, e: LEFT, f: 700 },
+ text,
+ fontId: "base14:Helvetica",
+ fontSize: 10,
+ fill: { r: 0, g: 0, b: 0, a: 255 },
+ fontSubset: false,
+ };
+}
+
+/** Greedy word wrap at `widthPx`, turning the breaking space into a newline as the reflow does. */
+function wrapText(text: string, widthPx: number): string {
+ const perLine = Math.floor(widthPx / CHAR_PX);
+ return text
+ .split("\n")
+ .map((line) => {
+ const out: string[] = [];
+ let rest = line;
+ while (rest.length > perLine) {
+ const cut = rest.lastIndexOf(" ", perLine);
+ if (cut <= 0) break;
+ out.push(rest.slice(0, cut));
+ rest = rest.slice(cut + 1);
+ }
+ return [...out, rest].join("\n");
+ })
+ .join("\n");
+}
+
+type OnWrap = (
+ maxWidthPt: number,
+ keepClearBelow?: boolean,
+) => string | null | void;
+
+let editedTexts: string[] = [];
+
+function Harness({
+ text,
+ widthMode,
+ onWrap,
+ growEdge,
+}: {
+ text: string;
+ widthMode: WidthMode;
+ onWrap: OnWrap;
+ growEdge?: GrowEdge | null;
+}) {
+ const [current, setCurrent] = useState(text);
+ const edit = (next: string) => {
+ editedTexts.push(next);
+ setCurrent(next);
+ };
+ return (
+ <TextRunOverlay
+ run={run(current)}
+ pageHeight={792}
+ pageWidth={PAGE_WIDTH}
+ transform={DisplayTransform.identity(PAGE_WIDTH, 792)}
+ scale={1}
+ widthMode={widthMode}
+ growEdge={growEdge}
+ selected={false}
+ onSelect={() => {}}
+ onEdit={edit}
+ onWrap={(width, keepClear) => {
+ const result = onWrap(width, keepClear);
+ if (typeof result === "string") setCurrent(result);
+ return result;
+ }}
+ />
+ );
+}
+
+function renderRun(
+ text: string,
+ widthMode: WidthMode = "grow",
+ wraps: "refuse" | "wrap" | "ignore" = "ignore",
+ growEdge: GrowEdge | null = null,
+) {
+ editedTexts = [];
+ const onWrap = vi.fn((width: number, _keepClear?: boolean) => {
+ if (wraps === "refuse") return null;
+ if (wraps === "ignore") return undefined;
+ return wrapText(lastEdit(), width);
+ });
+ render(
+ <MantineProvider env="test">
+ <Harness
+ text={text}
+ widthMode={widthMode}
+ onWrap={onWrap}
+ growEdge={growEdge}
+ />
+ </MantineProvider>,
+ );
+ const box = screen.getByTestId("pdf-editor-run-r1");
+ act(() => {
+ fireEvent.focus(box);
+ });
+ return { box, onWrap };
+}
+
+function lastEdit(): string {
+ return editedTexts[editedTexts.length - 1] ?? "";
+}
+
+function type(box: HTMLElement, text: string): void {
+ act(() => {
+ box.textContent = text;
+ window.getSelection()!.selectAllChildren(box);
+ window.getSelection()!.collapseToEnd();
+ fireEvent.input(box);
+ });
+}
+
+/** Insert `ch` at the caret, as a keystroke does, and fire its input. */
+function typeAtCaret(box: HTMLElement, ch: string): void {
+ act(() => {
+ const selection = window.getSelection()!;
+ const node = selection.focusNode as Text;
+ const offset = selection.focusOffset;
+ node.insertData(offset, ch);
+ selection.collapse(node, offset + ch.length);
+ fireEvent.input(box);
+ });
+}
+
+const SHORT = "Short line";
+const LONG = `${SHORT} that the user keeps typing past the page edge`;
+
+describe("Grow mode at the page edge", () => {
+ beforeEach(() => vi.useFakeTimers());
+ afterEach(() => vi.useRealTimers());
+
+ it("wraps text typed past the page edge at the width left on the page", () => {
+ const { box, onWrap } = renderRun(SHORT);
+ type(box, LONG);
+ act(() => {
+ vi.advanceTimersByTime(1000);
+ });
+ expect(onWrap).toHaveBeenCalledOnce();
+ expect(onWrap.mock.calls[0][0]).toBeCloseTo(PAGE_CAP, 3);
+ });
+
+ it("stops the box at the page edge while the user types", () => {
+ const { box } = renderRun(SHORT);
+ type(box, LONG);
+ expect(parseFloat(box.style.width)).toBeLessThanOrEqual(PAGE_CAP);
+ });
+
+ it("keeps widening without wrapping while the text still fits on the page", () => {
+ const { box, onWrap } = renderRun(SHORT);
+ type(box, `${SHORT} plus a few`);
+ act(() => {
+ vi.advanceTimersByTime(1000);
+ });
+ expect(onWrap).not.toHaveBeenCalled();
+ expect(parseFloat(box.style.width)).toBeGreaterThan(longest(SHORT));
+ });
+
+ it("leaves a line the document already set past the page edge alone until text is typed", () => {
+ const { box, onWrap } = renderRun(LONG);
+ expect(parseFloat(box.style.width)).toBeGreaterThanOrEqual(longest(LONG));
+ act(() => {
+ vi.advanceTimersByTime(1000);
+ });
+ fireEvent.blur(box);
+ expect(onWrap).not.toHaveBeenCalled();
+ });
+
+ it("does not split a word too long for the page", () => {
+ const word = "x".repeat(40);
+ const { box, onWrap } = renderRun(SHORT);
+ type(box, word);
+ act(() => {
+ vi.advanceTimersByTime(1000);
+ });
+ expect(onWrap).not.toHaveBeenCalled();
+ expect(parseFloat(box.style.width)).toBeGreaterThanOrEqual(longest(word));
+ });
+
+ it("wraps on blur whatever is still past the edge", () => {
+ const { box, onWrap } = renderRun(SHORT);
+ type(box, LONG);
+ onWrap.mockClear();
+ fireEvent.blur(box);
+ expect(onWrap).toHaveBeenCalledOnce();
+ expect(onWrap.mock.calls[0][0]).toBeCloseTo(PAGE_CAP, 3);
+ });
+
+ it("asks to keep clear of what lies below the new lines", () => {
+ const { box, onWrap } = renderRun(SHORT);
+ type(box, LONG);
+ act(() => {
+ vi.advanceTimersByTime(1000);
+ });
+ expect(onWrap.mock.calls[0][1]).toBe(true);
+ });
+
+ it("grows past the edge instead when the wrap has nowhere clear to go", () => {
+ const { box, onWrap } = renderRun(SHORT, "grow", "refuse");
+ type(box, LONG);
+ act(() => {
+ vi.advanceTimersByTime(1000);
+ });
+ expect(onWrap).toHaveBeenCalledOnce();
+ expect(parseFloat(box.style.width)).toBeGreaterThanOrEqual(longest(LONG));
+ type(box, `${LONG} and more`);
+ act(() => {
+ vi.advanceTimersByTime(1000);
+ });
+ fireEvent.blur(box);
+ expect(onWrap).toHaveBeenCalledOnce();
+ });
+});
+
+describe("Wrapping as the user types", () => {
+ beforeEach(() => vi.useFakeTimers());
+ afterEach(() => vi.useRealTimers());
+
+ it("wraps on the keystroke that crosses the page edge, without waiting", () => {
+ const { box, onWrap } = renderRun(SHORT);
+ type(box, LONG);
+ expect(onWrap).toHaveBeenCalledOnce();
+ });
+
+ it("draws the wrapped lines in the box at once, caret after the last letter typed", () => {
+ const { box } = renderRun(SHORT, "grow", "wrap");
+ type(box, LONG);
+ const wrapped = wrapText(LONG, PAGE_CAP);
+ expect(wrapped).toContain("\n");
+ expect(readOverlayText(box)).toBe(wrapped);
+ expect(plainCaretOffset(box)).toBe(wrapped.length);
+ });
+
+ it("keeps the break when typing goes on after it", () => {
+ const { box } = renderRun(SHORT, "grow", "wrap");
+ type(box, LONG);
+ const wrapped = wrapText(LONG, PAGE_CAP);
+ typeAtCaret(box, "s");
+ expect(lastEdit()).toBe(`${wrapped}s`);
+ });
+
+ it("wraps in Wrap mode on the crossing keystroke too", () => {
+ const { box, onWrap } = renderRun(SHORT, "wrap", "wrap");
+ type(box, `${SHORT} and some more`);
+ expect(onWrap).toHaveBeenCalledOnce();
+ expect(readOverlayText(box)).toContain("\n");
+ });
+
+ it("leaves a space typed at the edge for the letter after it", () => {
+ const fits = `${SHORT} ${"y".repeat(Math.floor(PAGE_CAP / CHAR_PX) - SHORT.length - 2)}`;
+ const { box, onWrap } = renderRun(SHORT);
+ type(box, `${fits} `);
+ expect(onWrap).not.toHaveBeenCalled();
+ type(box, `${fits} z`);
+ expect(onWrap).toHaveBeenCalledOnce();
+ });
+
+ it("asks only about the line being typed on", () => {
+ const { box, onWrap } = renderRun(SHORT, "wrap");
+ type(box, `${LONG}\nshort`);
+ expect(onWrap).not.toHaveBeenCalled();
+ });
+
+ it("does not ask again for a line the reflow left as it was until it grows", () => {
+ const { box, onWrap } = renderRun(SHORT);
+ type(box, LONG);
+ type(box, LONG);
+ expect(onWrap).toHaveBeenCalledOnce();
+ type(box, `${LONG}s`);
+ expect(onWrap).toHaveBeenCalledTimes(2);
+ });
+
+ it("waits for an IME composition to end before wrapping", () => {
+ const { box, onWrap } = renderRun(SHORT, "grow", "wrap");
+ act(() => {
+ box.focus();
+ fireEvent.compositionStart(box);
+ });
+ type(box, LONG);
+ expect(onWrap).not.toHaveBeenCalled();
+ act(() => {
+ fireEvent.compositionEnd(box);
+ });
+ expect(onWrap).toHaveBeenCalledOnce();
+ expect(readOverlayText(box)).toBe(wrapText(LONG, PAGE_CAP));
+ });
+});
+
+describe("Grow mode beside other text", () => {
+ const COLUMN_EDGE = LEFT + 100;
+ const NEXT_COLUMN: GrowEdge = { side: "right", x: COLUMN_EDGE };
+
+ it("wraps text typed up to the next column at that column, not the page edge", () => {
+ const { box, onWrap } = renderRun(SHORT, "grow", "wrap", NEXT_COLUMN);
+ type(box, LONG);
+ expect(onWrap).toHaveBeenCalledOnce();
+ expect(onWrap.mock.calls[0][0]).toBeCloseTo(COLUMN_EDGE - LEFT, 3);
+ expect(onWrap.mock.calls[0][1]).toBe(true);
+ expect(readOverlayText(box)).toBe(wrapText(LONG, COLUMN_EDGE - LEFT));
+ });
+
+ it("stops the box short of the next column while the user types", () => {
+ const { box } = renderRun(SHORT, "grow", "ignore", NEXT_COLUMN);
+ type(box, LONG);
+ expect(parseFloat(box.style.width)).toBeLessThanOrEqual(COLUMN_EDGE - LEFT);
+ });
+
+ it("wraps on blur at the next column too", () => {
+ const { box, onWrap } = renderRun(SHORT, "grow", "ignore", NEXT_COLUMN);
+ type(box, LONG);
+ onWrap.mockClear();
+ fireEvent.blur(box);
+ expect(onWrap).toHaveBeenCalledOnce();
+ expect(onWrap.mock.calls[0][0]).toBeCloseTo(COLUMN_EDGE - LEFT, 3);
+ });
+
+ it("measures right-to-left text from its right end to the text on its left", () => {
+ const rtl = "שלום עולם";
+ const edge: GrowEdge = { side: "left", x: LEFT - 40 };
+ const { box, onWrap } = renderRun(rtl, "grow", "ignore", edge);
+ type(box, `${rtl} ${"מילה ".repeat(30)}`);
+ expect(onWrap).toHaveBeenCalledOnce();
+ expect(onWrap.mock.calls[0][0]).toBeCloseTo(longest(rtl) + 40, 3);
+ });
+
+ it("keeps the page edge when the next column is past it", () => {
+ const { box, onWrap } = renderRun(SHORT, "grow", "ignore", {
+ side: "right",
+ x: PAGE_WIDTH + 50,
+ });
+ type(box, LONG);
+ expect(onWrap.mock.calls[0][0]).toBeCloseTo(PAGE_CAP, 3);
+ });
+});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/ViewerEditLayer.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/ViewerEditLayer.tsx
index 94c791b428..6839775b5e 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/components/ViewerEditLayer.tsx
+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/ViewerEditLayer.tsx
@@ -5,7 +5,7 @@ import {
} from "@editor/tools/pdfTextEditor/hooks/useEditorStore";
import {
useEditorSelection,
- useHighlightedRunId,
+ useFindMatch,
} from "@editor/tools/pdfTextEditor/hooks/useEditorSelection";
import { PageView } from "@editor/tools/pdfTextEditor/components/PageView";
import { pageViewHandlers } from "@editor/tools/pdfTextEditor/util/pageViewHandlers";
@@ -104,7 +104,7 @@ function EditablePage({
const widthMode = useEditorState(store, (s) => s.widthMode);
const showRulers = useEditorState(store, (s) => s.showRulers);
const selection = useEditorSelection(store);
- const highlightedRunId = useHighlightedRunId(store);
+ const findMatch = useFindMatch(store);
// PageView is memoised: hand it only this page's share of the selection, in
// arrays that keep their identity while that share is unchanged, so a click
@@ -112,7 +112,7 @@ function EditablePage({
const runIds = useOwnIds(selection.runIds, page.runs);
const imageIds = useOwnIds(selection.imageIds, page.images);
const shapeIds = useOwnIds(selection.shapeIds, page.shapes);
- const ownsHighlight = page.runs.some((r) => r.id === highlightedRunId);
+ const ownsMatch = page.runs.some((r) => r.id === findMatch?.runId);
const ownsFormField = (page.annotations ?? []).some(
(a) => a.id === selection.formFieldId,
);
@@ -129,8 +129,8 @@ function EditablePage({
selectedRunIds={runIds}
selectedImageIds={imageIds}
selectedShapeIds={shapeIds}
+ findMatch={ownsMatch ? findMatch : null}
selectedFormFieldId={ownsFormField ? selection.formFieldId : null}
- highlightedRunId={ownsHighlight ? highlightedRunId : null}
selectedTextRange={
runIds.length === 1 && selection.runIds.length === 1
? selection.textRange
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/ViewerEditToolbar.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/ViewerEditToolbar.tsx
index 5b369eb48b..798c20bf97 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/components/ViewerEditToolbar.tsx
+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/ViewerEditToolbar.tsx
@@ -1,7 +1,13 @@
-import { useEffect } from "react";
+import { memo, useEffect } from "react";
import { useEditorStoreView } from "@editor/tools/pdfTextEditor/hooks/useEditorStore";
import { useEditorSelection } from "@editor/tools/pdfTextEditor/hooks/useEditorSelection";
import { useToolbarController } from "@editor/tools/pdfTextEditor/hooks/useToolbarController";
+import { useDeferredPanelView } from "@editor/tools/pdfTextEditor/hooks/useDeferredPanelView";
+import type {
+ EditorStore,
+ EditorViewState,
+} from "@editor/tools/pdfTextEditor/store/EditorStore";
+import type { SelectionState } from "@editor/tools/pdfTextEditor/types";
import { EditorTopBar } from "@editor/tools/pdfTextEditor/components/EditorTopBar";
import { MobileEditorTopBar } from "@editor/tools/pdfTextEditor/components/MobileEditorTopBar";
import { MobileActionBar } from "@editor/tools/pdfTextEditor/components/MobileActionBar";
@@ -17,7 +23,8 @@ const CONTROLS =
export function ViewerEditToolbar() {
const { store, state } = useEditorStoreView();
const selection = useEditorSelection(store);
- const controller = useToolbarController(store, state, selection);
+ // Deferred so the typed letter is drawn before the bars, which a burst of typing outdates.
+ const bars = useDeferredPanelView(state, selection);
const isMobile = useIsMobile();
// A plain press on the bare viewer around the pages clears the selection,
@@ -37,34 +44,12 @@ export function ViewerEditToolbar() {
return (
<>
- {isMobile ? (
- <MobileEditorTopBar
- controller={controller}
- hasDocument={state.hasDocument}
- dirty={state.dirty}
- />
- ) : (
- <EditorTopBar
- controller={controller}
- hasDocument={state.hasDocument}
- dirty={state.dirty}
- addTextArmed={state.mode === "addText"}
- addTableArmed={state.mode === "addTable"}
- onToggleAddTable={() =>
- store.setMode(
- store.getState().mode === "addTable" ? "select" : "addTable",
- )
- }
- onToggleAddText={() =>
- store.setMode(
- store.getState().mode === "addText" ? "select" : "addText",
- )
- }
- findOpen={state.findOpen}
- onToggleFind={() => store.setFindOpen(!store.getState().findOpen)}
- onShowHelp={() => store.setHelpOpen(true)}
- />
- )}
+ <TopBar
+ store={store}
+ state={bars.state}
+ selection={bars.selection}
+ mobile={isMobile}
+ />
{state.findOpen && state.hasDocument && (
<FindBar
store={store}
@@ -77,12 +62,60 @@ export function ViewerEditToolbar() {
);
}
+interface BarProps {
+ store: EditorStore;
+ state: EditorViewState;
+ selection: SelectionState;
+}
+
+const TopBar = memo(function TopBar({
+ store,
+ state,
+ selection,
+ mobile,
+}: BarProps & { mobile: boolean }) {
+ const controller = useToolbarController(store, state, selection);
+ if (mobile)
+ return (
+ <MobileEditorTopBar
+ controller={controller}
+ hasDocument={state.hasDocument}
+ dirty={state.dirty}
+ />
+ );
+ return (
+ <EditorTopBar
+ controller={controller}
+ hasDocument={state.hasDocument}
+ dirty={state.dirty}
+ addTextArmed={state.mode === "addText"}
+ addTableArmed={state.mode === "addTable"}
+ onToggleAddTable={() => store.toggleMode("addTable")}
+ onToggleAddText={() => store.toggleMode("addText")}
+ findOpen={state.findOpen}
+ onToggleFind={() => store.toggleFindOpen()}
+ onShowHelp={() => store.setHelpOpen(true)}
+ />
+ );
+});
+
/** The editing actions a small screen shows below the pages. */
export function ViewerEditActionBar() {
const { store, state } = useEditorStoreView();
const selection = useEditorSelection(store);
- const controller = useToolbarController(store, state, selection);
+ const bars = useDeferredPanelView(state, selection);
if (!state.hasDocument) return null;
+ return (
+ <ActionBar store={store} state={bars.state} selection={bars.selection} />
+ );
+}
+
+const ActionBar = memo(function ActionBar({
+ store,
+ state,
+ selection,
+}: BarProps) {
+ const controller = useToolbarController(store, state, selection);
return (
<MobileActionBar
store={store}
@@ -92,4 +125,4 @@ export function ViewerEditActionBar() {
findOpen={state.findOpen}
/>
);
-}
+});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/fontPickFailure.ts b/frontend/src/editor/core/tools/pdfTextEditor/components/fontPickFailure.ts
new file mode 100644
index 0000000000..a3e3057175
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/fontPickFailure.ts
@@ -0,0 +1,75 @@
+import { useCallback } from "react";
+import { useTranslation } from "react-i18next";
+import { alert } from "@editor/components/toast";
+import type { FontPickFailure } from "@editor/tools/pdfTextEditor/hooks/useSelectionActions";
+
+const PICK_FAILURE_TEXT: Record<FontPickFailure, [string, string]> = {
+ needsShaping: [
+ "pdfTextEditor.fontPicker.needsShaping",
+ "The editor can't yet redraw this script's joined letters and vowel signs correctly, so that text was left in its current font.",
+ ],
+ serverFontFailed: [
+ "pdfTextEditor.fontPicker.serverFontFailed",
+ "That server font could not be downloaded. The text was left unchanged.",
+ ],
+ embeddingForbidden: [
+ "pdfTextEditor.fontPicker.embeddingForbidden",
+ "This font's licence does not allow embedding it in a PDF. The text was left unchanged.",
+ ],
+ embedFailed: [
+ "pdfTextEditor.fontPicker.embedFailed",
+ "This font could not be embedded in the PDF. The text was left unchanged.",
+ ],
+ noGlyphs: [
+ "pdfTextEditor.fontPicker.noGlyphs",
+ "This font has no characters for the selected text. The text was left unchanged.",
+ ],
+ missingGlyphs: [
+ "pdfTextEditor.fontPicker.missingGlyphs",
+ "This font is missing some of the selected characters, and they could not be kept in their current font. The text was left unchanged.",
+ ],
+ documentFontCannotDraw: [
+ "pdfTextEditor.fontPicker.documentFontCannotDraw",
+ "The editor can't draw this text in the document's own font, so it was left in its current font.",
+ ],
+ someLeftUnchanged: [
+ "pdfTextEditor.fontPicker.someLeftUnchanged",
+ "This font does not have the characters for some of the selected text. That text was left unchanged.",
+ ],
+ closestMatch: [
+ "pdfTextEditor.fontPicker.closestMatch",
+ "This font is missing some of the selected letters, so they are drawn in the closest matching font.",
+ ],
+ styleUnavailable: [
+ "pdfTextEditor.fontPicker.styleUnavailable",
+ "The selected text has no version of its font in that style, so it was left unchanged.",
+ ],
+ styleSkipped: [
+ "pdfTextEditor.fontPicker.styleSkipped",
+ "Some of the selected text has no version of its font in that style, so it was left unchanged.",
+ ],
+ partOfRunUnsupported: [
+ "pdfTextEditor.fontPicker.partOfRunUnsupported",
+ "This text can only be restyled as a whole. Select the box instead of some of its words.",
+ ],
+};
+
+/** Applies a font or style change and warns about whatever it could not do as asked. */
+export function useFontChangeWarning(): (
+ change: () => void | Promise<FontPickFailure | null>,
+) => Promise<void> {
+ const { t } = useTranslation();
+ return useCallback(
+ async (change) => {
+ const failure = await change();
+ if (!failure) return;
+ const [key, fallback] = PICK_FAILURE_TEXT[failure];
+ alert({
+ alertType: "warning",
+ title: t(key, fallback),
+ expandable: false,
+ });
+ },
+ [t],
+ );
+}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/pageViewTestSupport.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/pageViewTestSupport.tsx
new file mode 100644
index 0000000000..7f45f38061
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/pageViewTestSupport.tsx
@@ -0,0 +1,79 @@
+import type { ComponentProps } from "react";
+import { MantineProvider } from "@mantine/core";
+import { PageView } from "@editor/tools/pdfTextEditor/components/PageView";
+import type { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
+import type { Page } from "@editor/tools/pdfTextEditor/model/Page";
+import type { EditorStore } from "@editor/tools/pdfTextEditor/store/EditorStore";
+import type {
+ PageSnapshot,
+ TextRunSnapshot,
+} from "@editor/tools/pdfTextEditor/types";
+
+// Fixtures shared by the PageView tests. The mocks stay in the test files:
+// vi.mock is hoisted per file, so a helper cannot own them.
+
+/** Reports every observed page as on screen at once, so PageView paints it. */
+export class VisibleObserver {
+ constructor(private readonly callback: IntersectionObserverCallback) {}
+ observe(target: Element): void {
+ this.callback(
+ [{ isIntersecting: true, target } as IntersectionObserverEntry],
+ this as unknown as IntersectionObserver,
+ );
+ }
+ disconnect(): void {}
+ unobserve(): void {}
+}
+
+export function pageSnapshot(
+ live: Page,
+ runs: TextRunSnapshot[] = [],
+): PageSnapshot {
+ return {
+ pageIndex: 0,
+ width: live.width,
+ height: live.height,
+ dirty: false,
+ revision: live.revision,
+ runs,
+ images: [],
+ shapes: [],
+ display: live.display.toData(),
+ };
+}
+
+/** A document that hands out `live` for every page. Keep one per test: PageView repaints when it changes. */
+export function stubDocument(live: Page): EditorDocument {
+ return { page: () => live } as unknown as EditorDocument;
+}
+
+const STUB_STORE = {
+ setPageNearViewport: () => {},
+} as unknown as EditorStore;
+
+/** PageView over `page` at scale 1 in Grow, with nothing selected and no-op handlers. */
+export function stubbedPageView(
+ document: EditorDocument,
+ page: PageSnapshot,
+ props: Partial<ComponentProps<typeof PageView>> = {},
+) {
+ return (
+ <MantineProvider env="test">
+ <PageView
+ document={document}
+ store={STUB_STORE}
+ page={page}
+ scale={1}
+ widthMode="grow"
+ selectedRunIds={[]}
+ selectedImageIds={[]}
+ selectedShapeIds={[]}
+ onSelectRun={() => {}}
+ onSelectImage={() => {}}
+ onSelectShape={() => {}}
+ onEditRun={() => {}}
+ {...props}
+ />
+ </MantineProvider>
+ );
+}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/toolbar/FormatGroup.test.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/toolbar/FormatGroup.test.tsx
new file mode 100644
index 0000000000..acad60bea6
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/toolbar/FormatGroup.test.tsx
@@ -0,0 +1,227 @@
+import { MantineProvider } from "@mantine/core";
+import {
+ act,
+ fireEvent,
+ render,
+ screen,
+ waitFor,
+} from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+import { describe, expect, it, vi } from "vitest";
+
+const { alert } = vi.hoisted(() => ({ alert: vi.fn() }));
+vi.mock("@editor/components/toast", () => ({ alert }));
+vi.mock("@editor/tools/pdfTextEditor/components/FontFamilySelect", () => ({
+ FontFamilySelect: () => null,
+}));
+
+import { FormatGroup } from "@editor/tools/pdfTextEditor/components/toolbar/FormatGroup";
+import type { Controller } from "@editor/tools/pdfTextEditor/components/toolbar/toolbarShared";
+import { EMPTY_TOOLBAR } from "@editor/tools/pdfTextEditor/util/toolbarState";
+import type { ToolbarState } from "@editor/tools/pdfTextEditor/types";
+
+const BLACK = { r: 0, g: 0, b: 0, a: 255 };
+const RED = { r: 204, g: 0, b: 0, a: 255 };
+
+function controller(
+ fill: typeof BLACK,
+ onChangeFill: (hex: string) => void,
+): Controller {
+ return {
+ state: { ...EMPTY_TOOLBAR, fill, fontSize: 12 },
+ scanFont: undefined,
+ hasRunSelection: true,
+ selectionTextReadOnly: false,
+ onChangeFontFamily: vi.fn(),
+ onChangeFontSize: vi.fn(),
+ onChangeFill,
+ onChangeOutline: vi.fn(),
+ onToggleItalic: vi.fn(),
+ onChangeCase: vi.fn(),
+ } as unknown as Controller;
+}
+
+function formatGroup(fill: typeof BLACK, onChangeFill: (hex: string) => void) {
+ return (
+ <MantineProvider env="test">
+ <FormatGroup controller={controller(fill, onChangeFill)} />
+ </MantineProvider>
+ );
+}
+
+describe("FormatGroup fill colour field", () => {
+ it("keeps what the user is typing over when the toolbar catches up with an earlier pick", async () => {
+ const user = userEvent.setup();
+ const onChangeFill = vi.fn();
+ const ui = (fill: typeof BLACK) => formatGroup(fill, onChangeFill);
+ const { rerender } = render(ui(BLACK));
+ const field = screen.getByTestId<HTMLInputElement>("pdf-editor-colour");
+ act(() => field.focus());
+ field.setSelectionRange(0, field.value.length);
+
+ rerender(ui(RED));
+ await user.paste("#0000cc");
+
+ expect(field.value).toBe("#0000cc");
+ expect(onChangeFill).toHaveBeenLastCalledWith("#0000cc");
+ });
+
+ it("shows the selection's colour again once the field loses focus", () => {
+ const ui = (fill: typeof BLACK) => formatGroup(fill, vi.fn());
+ const { rerender } = render(ui(BLACK));
+ const field = screen.getByTestId<HTMLInputElement>("pdf-editor-colour");
+ act(() => field.focus());
+ rerender(ui(RED));
+ expect(field.value).toBe("#000000");
+
+ act(() => field.blur());
+ expect(field.value).toBe("#cc0000");
+ });
+});
+
+function styleController(
+ state: Partial<ToolbarState>,
+ actions: Partial<Controller> = {},
+): Controller {
+ return {
+ ...controller(BLACK, vi.fn()),
+ state: {
+ ...EMPTY_TOOLBAR,
+ fill: BLACK,
+ fontSize: 12,
+ ...state,
+ mixed: { ...EMPTY_TOOLBAR.mixed, ...state.mixed },
+ },
+ onToggleBold: vi.fn(async () => null),
+ onChangeFontWeight: vi.fn(async () => null),
+ ...actions,
+ };
+}
+
+function renderGroup(ctl: Controller) {
+ return render(
+ <MantineProvider env="test">
+ <FormatGroup controller={ctl} />
+ </MantineProvider>,
+ );
+}
+
+describe("FormatGroup style toggles", () => {
+ it("makes text bold from the Bold toggle beside Italic", async () => {
+ const ctl = styleController({ canBold: true, canItalic: true });
+ renderGroup(ctl);
+ const bold = screen.getByTestId("pdf-editor-bold");
+
+ expect(bold.nextElementSibling).toBe(
+ screen.getByTestId("pdf-editor-italic"),
+ );
+ expect(bold).toHaveAttribute("aria-pressed", "false");
+ await userEvent.click(bold);
+
+ expect(ctl.onToggleBold).toHaveBeenCalledTimes(1);
+ });
+
+ it("disables Bold and says why when the font has no bold face", async () => {
+ renderGroup(styleController({ canBold: false }));
+ const bold = screen.getByTestId("pdf-editor-bold");
+
+ expect(bold).toBeDisabled();
+ fireEvent.mouseEnter(bold);
+ expect(
+ await screen.findByText("pdfTextEditor.toolbar.boldUnavailable"),
+ ).toBeInTheDocument();
+ });
+
+ it("says when only the bold italic face is missing", () => {
+ renderGroup(
+ styleController({
+ italic: true,
+ canItalic: true,
+ canBold: false,
+ boldNeedsBoldItalic: true,
+ }),
+ );
+
+ fireEvent.mouseEnter(screen.getByTestId("pdf-editor-bold"));
+ return expect(
+ screen.findByText("pdfTextEditor.toolbar.noBoldItalic"),
+ ).resolves.toBeInTheDocument();
+ });
+
+ it("says the same on Italic for bold text", () => {
+ renderGroup(
+ styleController({
+ bold: true,
+ canBold: true,
+ canItalic: false,
+ italicNeedsBoldItalic: true,
+ }),
+ );
+
+ fireEvent.mouseEnter(screen.getByTestId("pdf-editor-italic"));
+ return expect(
+ screen.findByText("pdfTextEditor.toolbar.noBoldItalic"),
+ ).resolves.toBeInTheDocument();
+ });
+
+ it("shows a bold-only font as bold, locked", () => {
+ renderGroup(styleController({ bold: true, canBold: false }));
+ const bold = screen.getByTestId("pdf-editor-bold");
+
+ expect(bold).toBeDisabled();
+ expect(bold).toHaveAttribute("aria-pressed", "true");
+ });
+
+ it("shows a half-bold selection as mixed", () => {
+ renderGroup(
+ styleController({ canBold: true, mixed: { bold: true } as never }),
+ );
+
+ expect(screen.getByTestId("pdf-editor-bold")).toHaveAttribute(
+ "aria-pressed",
+ "mixed",
+ );
+ });
+
+ it("tells the user when the italic toggle left text as it was", async () => {
+ alert.mockReset();
+ const ctl = styleController(
+ { canItalic: true },
+ { onToggleItalic: vi.fn(async () => "styleSkipped" as const) },
+ );
+ renderGroup(ctl);
+
+ await userEvent.click(screen.getByTestId("pdf-editor-italic"));
+
+ await waitFor(() =>
+ expect(alert).toHaveBeenCalledWith({
+ alertType: "warning",
+ expandable: false,
+ title: "pdfTextEditor.fontPicker.styleSkipped",
+ }),
+ );
+ });
+});
+
+describe("FormatGroup weight menu", () => {
+ it("stays hidden for a family with only regular and bold", () => {
+ renderGroup(styleController({ weights: [] }));
+
+ expect(
+ screen.queryByTestId("pdf-editor-font-weight"),
+ ).not.toBeInTheDocument();
+ });
+
+ it("reaches a weight the toggles cannot", async () => {
+ Element.prototype.scrollIntoView = vi.fn();
+ const ctl = styleController({ weights: [300, 400, 700], weight: 400 });
+ renderGroup(ctl);
+
+ await userEvent.click(screen.getByTestId("pdf-editor-font-weight"));
+ await userEvent.click(
+ await screen.findByText("pdfTextEditor.fontPicker.weightLight"),
+ );
+
+ expect(ctl.onChangeFontWeight).toHaveBeenCalledWith(300);
+ });
+});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/components/toolbar/FormatGroup.tsx b/frontend/src/editor/core/tools/pdfTextEditor/components/toolbar/FormatGroup.tsx
index 36b333de4b..bfebe1a2f6 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/components/toolbar/FormatGroup.tsx
+++ b/frontend/src/editor/core/tools/pdfTextEditor/components/toolbar/FormatGroup.tsx
@@ -1,4 +1,4 @@
-import { useState } from "react";
+import { useRef, useState } from "react";
import { Icon } from "@editor/ui/Icon";
import {
ColorInput,
@@ -6,6 +6,7 @@ import {
Menu,
NumberInput,
Popover,
+ Select,
Tooltip,
} from "@mantine/core";
import { useTranslation } from "react-i18next";
@@ -16,30 +17,106 @@ import {
} from "@editor/tools/pdfTextEditor/model/Color";
import { familyOf } from "@editor/tools/pdfTextEditor/util/fontFamily";
import { FontFamilySelect } from "@editor/tools/pdfTextEditor/components/FontFamilySelect";
+import { useFontChangeWarning } from "@editor/tools/pdfTextEditor/components/fontPickFailure";
import {
NO_SHRINK,
type Controller,
} from "@editor/tools/pdfTextEditor/components/toolbar/toolbarShared";
+const WEIGHT_NAMES: Record<number, [string, string]> = {
+ 100: ["pdfTextEditor.fontPicker.weightThin", "Thin"],
+ 200: ["pdfTextEditor.fontPicker.weightExtraLight", "Extra light"],
+ 300: ["pdfTextEditor.fontPicker.weightLight", "Light"],
+ 400: ["pdfTextEditor.fontPicker.weightRegular", "Regular"],
+ 500: ["pdfTextEditor.fontPicker.weightMedium", "Medium"],
+ 600: ["pdfTextEditor.fontPicker.weightSemibold", "Semibold"],
+ 700: ["pdfTextEditor.fontPicker.weightBold", "Bold"],
+ 800: ["pdfTextEditor.fontPicker.weightExtraBold", "Extra bold"],
+ 900: ["pdfTextEditor.fontPicker.weightBlack", "Black"],
+};
+
+type TranslatedText = [key: string, fallback: string];
+
+interface ToggleTexts {
+ name: TranslatedText;
+ /** Why the toggle is off when the text is in the style and its font has no face without it. */
+ only: TranslatedText;
+ /** Why the toggle is off when the font has no face in the style. */
+ unavailable: TranslatedText;
+}
+
+const BOLD_TEXTS: ToggleTexts = {
+ name: ["pdfTextEditor.toolbar.bold", "Bold"],
+ only: ["pdfTextEditor.toolbar.boldOnly", "This font has only a bold version"],
+ unavailable: [
+ "pdfTextEditor.toolbar.boldUnavailable",
+ "No bold version of this font",
+ ],
+};
+
+const ITALIC_TEXTS: ToggleTexts = {
+ name: ["pdfTextEditor.toolbar.italic", "Italic"],
+ only: [
+ "pdfTextEditor.toolbar.italicOnly",
+ "This font has only an italic version",
+ ],
+ unavailable: [
+ "pdfTextEditor.toolbar.italicUnavailable",
+ "This font has no italic version. Load your device fonts or pick another font family.",
+ ],
+};
+
+const NO_BOLD_ITALIC: TranslatedText = [
+ "pdfTextEditor.toolbar.noBoldItalic",
+ "No bold italic version of this font",
+];
+
+/** A style toggle's look: filled when the whole selection has the style, outlined when only some of it does. */
+function toggleLook(on: boolean, mixed: boolean) {
+ if (mixed) return { variant: "secondary", accent: "default" } as const;
+ return on
+ ? ({ variant: "primary", accent: "default" } as const)
+ : ({ variant: "tertiary", accent: "neutral" } as const);
+}
+
interface FormatGroupProps {
controller: Controller;
touch?: boolean;
+ /**
+ * Set when the controls sit in another popover. Their own dropdowns then
+ * render inside it: one portalled out of it reads as a click outside, which
+ * closes the popover and the dropdown with it.
+ */
+ inPopover?: boolean;
}
-export function FormatGroup({ controller, touch = false }: FormatGroupProps) {
+export function FormatGroup({
+ controller,
+ touch = false,
+ inPopover = false,
+}: FormatGroupProps) {
const { t } = useTranslation();
const {
state,
scanFont,
hasRunSelection,
+ selectionTextReadOnly,
onChangeFontFamily,
onChangeFontSize,
onChangeFill,
onChangeOutline,
+ onToggleBold,
onToggleItalic,
+ onChangeFontWeight,
onChangeCase,
} = controller;
+ const warnAbout = useFontChangeWarning();
const [fillPickerOpen, setFillPickerOpen] = useState(false);
+ // What the colour field holds while it has focus. The toolbar can redraw a
+ // pick after the model has it, and that late value would replace the text
+ // the user is selecting or typing over.
+ const [fillDraft, setFillDraft] = useState<string | null>(null);
+ const fillFocusedRef = useRef(false);
if (!hasRunSelection) return null;
const fillHex = state.fill ? toCssHex(state.fill) : "#000000";
@@ -50,18 +127,72 @@ export function FormatGroup({ controller, touch = false }: FormatGroupProps) {
scanFont === undefined ? documentFamily : (scanFont?.family ?? null);
const inputSize = touch ? "lg" : "xs";
const buttonSize = touch ? "xl" : "sm";
+ const weightName = (weight: number) =>
+ WEIGHT_NAMES[weight]
+ ? t(...WEIGHT_NAMES[weight])
+ : t("pdfTextEditor.fontPicker.weightNumber", "Weight {{weight}}", {
+ weight,
+ });
+ const readOnlyNote = selectionTextReadOnly
+ ? t(
+ "pdfTextEditor.run.readOnlyOrderTitle",
+ "This line's text can't be edited: it mixes right-to-left and left-to-right text in an order the editor can't redraw safely",
+ )
+ : null;
+ const toggleTooltip = (
+ texts: ToggleTexts,
+ can: boolean,
+ needsBoldItalic: boolean,
+ on: boolean,
+ ) =>
+ readOnlyNote ??
+ t(
+ ...(can
+ ? texts.name
+ : needsBoldItalic
+ ? NO_BOLD_ITALIC
+ : on
+ ? texts.only
+ : texts.unavailable),
+ );
return (
<>
<FontFamilySelect
value={fontFamily}
+ fontId={scanFont === undefined ? state.fontFamily : null}
+ documentFamilies={state.documentFamilies}
scanned={
scanFont === undefined ? undefined : { label: scanFont?.label }
}
+ documentFontId={state.documentFontId}
onChange={onChangeFontFamily}
mixed={state.mixed.fontFamily}
+ disabled={selectionTextReadOnly}
touch={touch}
+ withinPortal={!inPopover}
/>
+ {state.weights.length > 0 && !state.mixed.fontFamily && (
+ <Select
+ size={inputSize}
+ w={touch ? 140 : 104}
+ data={state.weights.map((weight) => ({
+ value: String(weight),
+ label: weightName(weight),
+ }))}
+ value={state.weight === null ? null : String(state.weight)}
+ placeholder={t("pdfTextEditor.fontPicker.mixed", "Mixed")}
+ onChange={(next) => {
+ if (next) void warnAbout(() => onChangeFontWeight(Number(next)));
+ }}
+ allowDeselect={false}
+ comboboxProps={{ withinPortal: !inPopover }}
+ disabled={selectionTextReadOnly}
+ aria-label={t("pdfTextEditor.fontPicker.weight", "Font weight")}
+ data-testid="pdf-editor-font-weight"
+ style={NO_SHRINK}
+ />
+ )}
<NumberInput
size={inputSize}
w={touch ? 104 : 76}
@@ -82,6 +213,8 @@ export function FormatGroup({ controller, touch = false }: FormatGroupProps) {
const next = typeof value === "number" ? value : Number(value);
if (Number.isFinite(next) && next > 0) onChangeFontSize(next);
}}
+ disabled={selectionTextReadOnly}
+ title={readOnlyNote ?? undefined}
aria-label={t("pdfTextEditor.toolbar.fontSize", "Font size")}
data-testid="pdf-editor-font-size"
style={NO_SHRINK}
@@ -97,9 +230,10 @@ export function FormatGroup({ controller, touch = false }: FormatGroupProps) {
transition: "width 120ms ease-out",
},
}}
- value={fillHex}
+ value={fillDraft ?? fillHex}
fixOnBlur={false}
onChange={(next) => {
+ if (fillFocusedRef.current) setFillDraft(next);
if (!next) return;
const rgb = parseCssColor(next);
if (!rgb) return;
@@ -116,35 +250,49 @@ export function FormatGroup({ controller, touch = false }: FormatGroupProps) {
onChangeEnd={() =>
window.requestAnimationFrame(() => setFillPickerOpen(false))
}
- onFocus={() => setFillPickerOpen(true)}
+ onFocus={() => {
+ fillFocusedRef.current = true;
+ setFillDraft(fillHex);
+ setFillPickerOpen(true);
+ }}
onClick={() => setFillPickerOpen(true)}
- onBlur={() => setFillPickerOpen(false)}
+ onBlur={() => {
+ fillFocusedRef.current = false;
+ setFillDraft(null);
+ setFillPickerOpen(false);
+ }}
onKeyDown={(event) => {
if (event.key === "Escape" || event.key === "Enter") {
setFillPickerOpen(false);
}
}}
popoverProps={{
+ withinPortal: !inPopover,
opened: fillPickerOpen,
onChange: setFillPickerOpen,
transitionProps: { transition: "fade", duration: 0 },
}}
+ aria-expanded={fillPickerOpen}
aria-label={t("pdfTextEditor.toolbar.fontColour", "Font colour")}
data-testid="pdf-editor-colour"
style={NO_SHRINK}
/>
- <Popover position="bottom-start" withinPortal shadow="md">
+ <Popover position="bottom-start" withinPortal={!inPopover} shadow="md">
<Popover.Target>
<Tooltip
- label={t(
- "pdfTextEditor.toolbar.advancedColourTooltip",
- "Advanced colour (glyph outline)",
- )}
+ label={
+ readOnlyNote ??
+ t(
+ "pdfTextEditor.toolbar.advancedColourTooltip",
+ "Advanced colour (glyph outline)",
+ )
+ }
>
<Button
variant={outlineWidth > 0 ? "primary" : "tertiary"}
accent={outlineWidth > 0 ? "default" : "neutral"}
size={buttonSize}
+ disabled={selectionTextReadOnly}
aria-label={t(
"pdfTextEditor.toolbar.advancedColour",
"Advanced colour",
@@ -196,39 +344,61 @@ export function FormatGroup({ controller, touch = false }: FormatGroupProps) {
</Popover.Dropdown>
</Popover>
<Tooltip
- label={
- !state.canItalic
- ? t(
- "pdfTextEditor.toolbar.italicUnavailable",
- "This font has no italic version. Load your device fonts or pick another font family.",
- )
- : t("pdfTextEditor.toolbar.italic", "Italic")
- }
+ label={toggleTooltip(
+ BOLD_TEXTS,
+ state.canBold,
+ state.boldNeedsBoldItalic,
+ state.bold,
+ )}
+ >
+ <Button
+ {...toggleLook(state.bold, state.mixed.bold)}
+ size={buttonSize}
+ onClick={() => void warnAbout(onToggleBold)}
+ disabled={!state.canBold || selectionTextReadOnly}
+ aria-label={t(...BOLD_TEXTS.name)}
+ aria-pressed={state.mixed.bold ? "mixed" : state.bold}
+ data-testid="pdf-editor-bold"
+ style={NO_SHRINK}
+ leftSection={<Icon name="bold" size={20} />}
+ />
+ </Tooltip>
+ <Tooltip
+ label={toggleTooltip(
+ ITALIC_TEXTS,
+ state.canItalic,
+ state.italicNeedsBoldItalic,
+ state.italic,
+ )}
>
<Button
- variant={state.italic ? "primary" : "tertiary"}
- accent={state.italic ? "default" : "neutral"}
+ {...toggleLook(state.italic, state.mixed.italic)}
size={buttonSize}
- onClick={onToggleItalic}
- disabled={!state.canItalic}
- aria-label={t("pdfTextEditor.toolbar.italic", "Italic")}
+ onClick={() => void warnAbout(onToggleItalic)}
+ disabled={!state.canItalic || selectionTextReadOnly}
+ aria-label={t(...ITALIC_TEXTS.name)}
+ aria-pressed={state.mixed.italic ? "mixed" : state.italic}
data-testid="pdf-editor-italic"
style={NO_SHRINK}
leftSection={<Icon name="italic" size={20} />}
/>
</Tooltip>
- <Menu shadow="md" position="bottom-start" withinPortal>
+ <Menu shadow="md" position="bottom-start" withinPortal={!inPopover}>
<Menu.Target>
<Tooltip
- label={t(
- "pdfTextEditor.toolbar.changeCaseTooltip",
- "Change case (text runs only)",
- )}
+ label={
+ readOnlyNote ??
+ t(
+ "pdfTextEditor.toolbar.changeCaseTooltip",
+ "Change case (text runs only)",
+ )
+ }
>
<Button
variant="tertiary"
accent="neutral"
size={buttonSize}
+ disabled={selectionTextReadOnly}
aria-label={t("pdfTextEditor.toolbar.changeCase", "Change case")}
data-testid="pdf-editor-change-case"
style={NO_SHRINK}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/hooks/useDeferredPanelView.test.tsx b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useDeferredPanelView.test.tsx
new file mode 100644
index 0000000000..747e4f4116
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useDeferredPanelView.test.tsx
@@ -0,0 +1,69 @@
+import { describe, it, expect } from "vitest";
+import { render } from "@testing-library/react";
+import { useDeferredPanelView } from "@editor/tools/pdfTextEditor/hooks/useDeferredPanelView";
+import type { EditorViewState } from "@editor/tools/pdfTextEditor/store/EditorStore";
+import type { SelectionState } from "@editor/tools/pdfTextEditor/types";
+
+function select(runId: string): SelectionState {
+ return {
+ runIds: [runId],
+ imageIds: [],
+ shapeIds: [],
+ caret: null,
+ textRange: null,
+ formFieldId: null,
+ };
+}
+
+function viewState(overrides: Partial<EditorViewState> = {}): EditorViewState {
+ return {
+ pages: [],
+ dirty: false,
+ showRulers: false,
+ ...overrides,
+ } as unknown as EditorViewState;
+}
+
+function renderPanel() {
+ const seen: { state: EditorViewState; selection: SelectionState }[] = [];
+ function Panel(props: { state: EditorViewState; selection: SelectionState }) {
+ seen.push(useDeferredPanelView(props.state, props.selection));
+ return null;
+ }
+ const s0 = viewState();
+ const a = select("A");
+ const view = render(<Panel state={s0} selection={a} />);
+ return { seen, view, Panel, s0, a };
+}
+
+describe("useDeferredPanelView", () => {
+ it("describes a newly selected object on the first render after the change", () => {
+ const { seen, view, Panel, s0 } = renderPanel();
+ const b = select("B");
+ const before = seen.length;
+ view.rerender(<Panel state={s0} selection={b} />);
+ const after = seen.slice(before);
+ expect(after.length).toBeGreaterThan(0);
+ for (const v of after) expect(v.selection).toBe(b);
+ });
+
+ it("keeps the previous snapshot for the urgent render while the selection is unchanged", () => {
+ const { seen, view, Panel, s0, a } = renderPanel();
+ const s1 = viewState({ pages: [], dirty: true });
+ const before = seen.length;
+ view.rerender(<Panel state={s1} selection={a} />);
+ const after = seen.slice(before);
+ expect(after[0].state).toBe(s0);
+ expect(after[after.length - 1].state).toBe(s1);
+ });
+
+ it("shows a changed view setting on the first render after the change", () => {
+ const { seen, view, Panel, a } = renderPanel();
+ const s1 = viewState({ showRulers: true });
+ const before = seen.length;
+ view.rerender(<Panel state={s1} selection={a} />);
+ const after = seen.slice(before);
+ expect(after.length).toBeGreaterThan(0);
+ for (const v of after) expect(v.state).toBe(s1);
+ });
+});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/hooks/useDeferredPanelView.ts b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useDeferredPanelView.ts
new file mode 100644
index 0000000000..59289b868a
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useDeferredPanelView.ts
@@ -0,0 +1,38 @@
+import { useDeferredValue, useMemo } from "react";
+import type { EditorViewState } from "@editor/tools/pdfTextEditor/store/EditorStore";
+import type { SelectionState } from "@editor/tools/pdfTextEditor/types";
+
+export interface PanelView {
+ state: EditorViewState;
+ selection: SelectionState;
+}
+
+const TYPED_CONTENT_KEYS: ReadonlySet<string> = new Set<keyof EditorViewState>([
+ "pages",
+ "dirty",
+ "documentLanguage",
+ "languagesInUse",
+]);
+
+function onlyContentChanged(
+ stale: EditorViewState,
+ live: EditorViewState,
+): boolean {
+ for (const key of Object.keys(live) as (keyof EditorViewState)[]) {
+ if (!TYPED_CONTENT_KEYS.has(key) && stale[key] !== live[key]) return false;
+ }
+ return true;
+}
+
+/** Lags a keystroke only while the selection and view settings are unchanged: a toggle reading a stale setting flips it back. */
+export function useDeferredPanelView(
+ state: EditorViewState,
+ selection: SelectionState,
+): PanelView {
+ const live = useMemo(() => ({ state, selection }), [state, selection]);
+ const deferred = useDeferredValue(live);
+ return deferred.selection === selection &&
+ onlyContentChanged(deferred.state, state)
+ ? deferred
+ : live;
+}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/hooks/useDocumentFontCompletion.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useDocumentFontCompletion.test.ts
index 50c87697b3..0719e461b5 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/hooks/useDocumentFontCompletion.test.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useDocumentFontCompletion.test.ts
@@ -1,11 +1,15 @@
import { beforeEach, describe, expect, test, vi } from "vitest";
-import { renderHook, waitFor } from "@testing-library/react";
+import { act, renderHook, waitFor } from "@testing-library/react";
import { useDocumentFontCompletion } from "@editor/tools/pdfTextEditor/hooks/useDocumentFontCompletion";
-import { setClosestFont } from "@editor/tools/pdfTextEditor/util/documentFontCompletion";
+import {
+ fontCanBeCompleted,
+ setClosestFont,
+} from "@editor/tools/pdfTextEditor/util/documentFontCompletion";
import { matchableSample } from "@editor/tools/pdfTextEditor/util/matchableSample";
import { rankFacesForDrawnText } from "@editor/tools/pdfTextEditor/commands/scanTextEdit";
import { fitInSlices } from "@editor/tools/pdfTextEditor/commands/scanFitSlices";
import {
+ loadBundledScanFaces,
loadScriptScanFaces,
scanScriptsOf,
} from "@editor/tools/pdfTextEditor/util/scanFontLibrary";
@@ -16,7 +20,7 @@ import type {
} from "@editor/tools/pdfTextEditor/store/EditorStore";
vi.mock("@editor/tools/pdfTextEditor/util/documentFontCompletion", () => ({
- fontCanBeCompleted: () => true,
+ fontCanBeCompleted: vi.fn(() => true),
fontCompletionFor: () => null,
fontCompletionsGeneration: () => 0,
originalFontLookedUp: () => true,
@@ -98,12 +102,17 @@ function setup(pageCount: number) {
};
}
-function setupWithFonts(fontIds: string[]) {
- const doc = {
- module: {},
+function docWithOnePage(name = "first"): EditorDocument {
+ return {
+ module: { name },
loadedPages: () => [{ index: 0, runs: [] }],
} as unknown as EditorDocument;
- const store = { document: doc } as unknown as EditorStore;
+}
+
+function setupWithFonts(fontIds: string[]) {
+ const doc = docWithOnePage();
+ const holder = { document: doc };
+ const store = holder as unknown as EditorStore;
const pagesFor = (ids: string[]) =>
[
{
@@ -122,6 +131,10 @@ function setupWithFonts(fontIds: string[]) {
{ initialProps: { pages: pagesFor(fontIds) } },
);
return {
+ doc,
+ replaceDocument: (next: EditorDocument) => {
+ holder.document = next;
+ },
showFonts: (ids: string[]) => view.rerender({ pages: pagesFor(ids) }),
};
}
@@ -145,6 +158,7 @@ beforeEach(() => {
vi.mocked(rankFacesForDrawnText).mockReset();
vi.mocked(setClosestFont).mockReset();
vi.mocked(loadScriptScanFaces).mockClear();
+ vi.mocked(fontCanBeCompleted).mockClear();
vi.mocked(fitInSlices).mockReset();
vi.mocked(fitInSlices).mockImplementation(async (fit) => fit());
vi.mocked(rankFacesForDrawnText).mockReturnValue([
@@ -230,4 +244,24 @@ describe("useDocumentFontCompletion", () => {
expect(setClosestFont).toHaveBeenCalledWith(FONT, "Noto Sans JP"),
);
});
+
+ test("reads no font of a document that a newer one replaced while the matcher waited", async () => {
+ vi.mocked(matchableSample).mockReturnValue(null);
+ const held = deferred();
+ vi.mocked(loadBundledScanFaces).mockImplementationOnce(() => held.promise);
+ const { doc, replaceDocument, showFonts } = setupWithFonts([FONT]);
+ await waitFor(() => expect(loadBundledScanFaces).toHaveBeenCalled());
+
+ const next = docWithOnePage("second");
+ replaceDocument(next);
+ await act(async () => held.resolve());
+ showFonts(["F2"]);
+ await waitFor(() =>
+ expect(fontCanBeCompleted).toHaveBeenCalledWith(next.module, "F2"),
+ );
+ expect(fontCanBeCompleted).not.toHaveBeenCalledWith(
+ doc.module,
+ expect.anything(),
+ );
+ });
});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/hooks/useDocumentFontCompletion.ts b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useDocumentFontCompletion.ts
index 10729af84a..6348daaf64 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/hooks/useDocumentFontCompletion.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useDocumentFontCompletion.ts
@@ -140,7 +140,11 @@ export function useDocumentFontCompletion(
loadBundledScanFaces(),
loadDeviceScanFacesIfAllowed(),
]).catch(() => undefined);
- for (let fontId = nextFont(); fontId && live(); fontId = nextFont()) {
+ // live() before nextFont(): a font handle outlives its document only as a
+ // dangling pointer, and PDFium reading one crashes the tab.
+ while (live()) {
+ const fontId = nextFont();
+ if (!fontId) break;
const sample = matchableSample(doc, fontId);
if (!sample) {
unsampled.set(fontId, doc.loadedPages().length);
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/hooks/useDocumentLoader.ts b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useDocumentLoader.ts
index 6a5aa383f1..60a2d88f4b 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/hooks/useDocumentLoader.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useDocumentLoader.ts
@@ -25,124 +25,137 @@ const yieldToBrowser = () =>
/** Open a PDF in PDFium and lazily populate pages on first visibility. */
export function useDocumentLoader(store: EditorStore) {
return useCallback(
- async (file: File, password?: string): Promise<void> => {
- const documentPassword = password ?? getPdfAccess(file)?.password;
- const token = store.beginLoad();
- store.setLoading(true);
- store.setProgress({
- stage: `Reading ${file.name}`,
- current: 0,
- total: 0,
- });
+ (file: File, password?: string) => loadDocument(store, file, password),
+ [store],
+ );
+}
+
+/**
+ * Resolves true when the document on screen as this call settles is the one it
+ * opened from `file`, even if a newer load has started but not yet replaced it.
+ * On false `file` is not on screen (it failed, wants a password, or a newer
+ * document replaced it), so the caller must leave the filename and workbench
+ * file alone.
+ */
+export async function loadDocument(
+ store: EditorStore,
+ file: File,
+ password?: string,
+): Promise<boolean> {
+ let installed: EditorDocument | null = null;
+ const documentPassword = password ?? getPdfAccess(file)?.password;
+ const token = store.beginLoad();
+ store.setLoading(true);
+ store.setProgress({
+ stage: `Reading ${file.name}`,
+ current: 0,
+ total: 0,
+ });
+ try {
+ await yieldToBrowser();
+ const bytes = new Uint8Array(await file.arrayBuffer());
+ if (!store.isCurrentLoad(token)) return false;
+ store.setProgress({
+ stage: "Parsing PDF",
+ current: 0,
+ total: 0,
+ });
+ await yieldToBrowser();
+ const doc = await EditorDocument.open(bytes, documentPassword);
+ try {
+ if (!store.isCurrentLoad(token)) {
+ doc.dispose();
+ return false;
+ }
+ const access = rememberPdfAccess(
+ file,
+ readPdfiumAccess(doc.module, doc.docPtr, documentPassword ?? ""),
+ );
+ assertPdfSessionEditable(access);
+ } catch (error) {
+ doc.dispose();
+ throw error;
+ }
+ if (!store.isCurrentLoad(token)) {
+ // A newer load superseded us before we installed our doc - free
+ // it ourselves (setDocument never took ownership).
try {
- await yieldToBrowser();
- const bytes = new Uint8Array(await file.arrayBuffer());
- if (!store.isCurrentLoad(token)) return;
- store.setProgress({
- stage: "Parsing PDF",
- current: 0,
- total: 0,
- });
- await yieldToBrowser();
- const doc = await EditorDocument.open(bytes, documentPassword);
- try {
- if (!store.isCurrentLoad(token)) {
- doc.dispose();
- return;
- }
- const access = rememberPdfAccess(
- file,
- readPdfiumAccess(doc.module, doc.docPtr, documentPassword ?? ""),
- );
- assertPdfSessionEditable(access);
- } catch (error) {
- doc.dispose();
- throw error;
- }
- if (!store.isCurrentLoad(token)) {
- // A newer load superseded us before we installed our doc - free
- // it ourselves (setDocument never took ownership).
- try {
- doc.dispose();
- } catch {
- /* best-effort */
- }
- return;
- }
- await store.setDocument(doc);
+ doc.dispose();
+ } catch {
+ /* best-effort */
+ }
+ return false;
+ }
+ await store.setDocument(doc);
+ installed = doc;
- const total = doc.pageCount;
- const eager = Math.min(EAGER_PAGE_LIMIT, total);
- const snapshots: PageSnapshot[] = [];
- for (let i = 0; i < eager; i++) {
- store.setProgress({
- stage: `Reading page ${i + 1} of ${total}`,
- current: i,
- total,
- });
- await yieldToBrowser();
- // The check + synchronous read below run in one tick, so a
- // superseding load can only interpose here.
- if (!store.isCurrentLoad(token)) return;
- const page = doc.page(i);
- PdfiumTextReader.populate(doc, page, store.groupingMode);
- snapshots.push({
- pageIndex: i,
- width: page.width,
- height: page.height,
- dirty: false,
- revision: page.revision,
- runs: page.runs.map((r) => r.snapshot()),
- images: page.images.map((img) => img.snapshot()),
- shapes: page.shapes.map((shape) => shape.snapshot()),
- annotations: page.annotations,
- rules: page.rules,
- display: page.display.toData(),
- });
- }
- for (let i = eager; i < total; i++) {
- const page = doc.page(i);
- snapshots.push({
- pageIndex: i,
- width: page.width,
- height: page.height,
- dirty: false,
- revision: 0,
- runs: [],
- images: [],
- shapes: [],
- display: page.display.toData(),
- });
- }
- if (!store.isCurrentLoad(token)) return;
- store.publishPages(snapshots);
- store.setProgress({
- stage: "Ready",
- current: total,
- total,
- });
- } catch (err) {
- if (store.isCurrentLoad(token)) {
- // A password-protected PDF isn't a hard error.
- if (
- err instanceof PdfiumOpenError &&
- err.code === FPDF_ERR_PASSWORD
- ) {
- store.setPasswordRequired(file, documentPassword !== undefined);
- } else {
- store.setError(err instanceof Error ? err.message : String(err));
- }
- }
- } finally {
- // Only the winning load owns the loading/progress UI state.
- if (store.isCurrentLoad(token)) {
- store.setLoading(false);
- store.setProgress(null);
- }
+ const total = doc.pageCount;
+ const eager = Math.min(EAGER_PAGE_LIMIT, total);
+ const snapshots: PageSnapshot[] = [];
+ for (let i = 0; i < eager; i++) {
+ store.setProgress({
+ stage: `Reading page ${i + 1} of ${total}`,
+ current: i,
+ total,
+ });
+ await yieldToBrowser();
+ // The check + synchronous read below run in one tick, so a
+ // superseding load can only interpose here.
+ if (!store.isCurrentLoad(token)) return store.document === doc;
+ const page = doc.page(i);
+ PdfiumTextReader.populate(doc, page, store.groupingMode);
+ snapshots.push({
+ pageIndex: i,
+ width: page.width,
+ height: page.height,
+ dirty: false,
+ revision: page.revision,
+ runs: page.runs.map((r) => r.snapshot()),
+ images: page.images.map((img) => img.snapshot()),
+ shapes: page.shapes.map((shape) => shape.snapshot()),
+ annotations: page.annotations,
+ rules: page.rules,
+ display: page.display.toData(),
+ });
+ }
+ for (let i = eager; i < total; i++) {
+ const page = doc.page(i);
+ snapshots.push({
+ pageIndex: i,
+ width: page.width,
+ height: page.height,
+ dirty: false,
+ revision: 0,
+ runs: [],
+ images: [],
+ shapes: [],
+ display: page.display.toData(),
+ });
+ }
+ if (!store.isCurrentLoad(token)) return store.document === doc;
+ store.publishPages(snapshots);
+ store.setProgress({
+ stage: "Ready",
+ current: total,
+ total,
+ });
+ } catch (err) {
+ if (store.isCurrentLoad(token)) {
+ // A password-protected PDF isn't a hard error.
+ if (err instanceof PdfiumOpenError && err.code === FPDF_ERR_PASSWORD) {
+ store.setPasswordRequired(file, documentPassword !== undefined);
+ } else {
+ store.setError(err instanceof Error ? err.message : String(err));
}
- },
- [store],
- );
+ }
+ } finally {
+ // Only the winning load owns the loading/progress UI state.
+ if (store.isCurrentLoad(token)) {
+ store.setLoading(false);
+ store.setProgress(null);
+ }
+ }
+ return installed !== null && store.document === installed;
}
/** Read EVERY not-yet-loaded page in one pass and publish once. */
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/hooks/useEditorClipboard.ts b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useEditorClipboard.ts
index 7ec61067e6..e9ab86053f 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/hooks/useEditorClipboard.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useEditorClipboard.ts
@@ -1,5 +1,8 @@
import { useEffect, useRef } from "react";
-import { isFocusInContentEditable } from "@editor/tools/pdfTextEditor/util/dom";
+import {
+ isFocusInContentEditable,
+ isModalOpen,
+} from "@editor/tools/pdfTextEditor/util/dom";
export interface EditorClipboardCallbacks {
/** True when any run or image is selected (images cut without carrying text). */
@@ -96,7 +99,7 @@ export function useEditorClipboard(cbs: EditorClipboardCallbacks) {
const intoSink =
sink !== null && (e.target === sink || document.activeElement === sink);
// A caret inside a run (or in Find/Replace/password) keeps native paste.
- if (!intoSink && isFocusInContentEditable()) return;
+ if (!intoSink && (isFocusInContentEditable() || isModalOpen())) return;
const text = e.clipboardData?.getData("text/plain");
if (!text) return;
e.preventDefault();
@@ -112,7 +115,7 @@ export function useEditorClipboard(cbs: EditorClipboardCallbacks) {
pastePlain = e.shiftKey;
// A caret inside a run (or in Find/Replace/password) pastes natively
// into that field - don't pull focus out from under it.
- if (isFocusInContentEditable()) return;
+ if (isFocusInContentEditable() || isModalOpen()) return;
flushPending();
const restoreTo = document.activeElement as HTMLElement | null;
const sink = ensureSink();
@@ -131,7 +134,7 @@ export function useEditorClipboard(cbs: EditorClipboardCallbacks) {
if (key !== "c" && key !== "x") return;
// A caret inside a run (or in Find/Replace/password) keeps native
// copy/cut over its own text.
- if (isFocusInContentEditable()) return;
+ if (isFocusInContentEditable() || isModalOpen()) return;
if (!ref.current.hasSelection()) return;
flushPending();
const text = ref.current.getSelectedText();
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/hooks/useEditorKeyboardShortcuts.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useEditorKeyboardShortcuts.test.ts
new file mode 100644
index 0000000000..12f1c8d1a2
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useEditorKeyboardShortcuts.test.ts
@@ -0,0 +1,133 @@
+import { afterEach, describe, expect, test, vi } from "vitest";
+import { renderHook } from "@testing-library/react";
+import { useEditorKeyboardShortcuts } from "@editor/tools/pdfTextEditor/hooks/useEditorKeyboardShortcuts";
+import type { EditorStore } from "@editor/tools/pdfTextEditor/store/EditorStore";
+
+function setup() {
+ const store = {
+ selection: {
+ value: { runIds: ["p0-t0"], imageIds: [], shapeIds: [] },
+ },
+ getState: () => ({ pageCount: 1 }),
+ } as unknown as EditorStore;
+ const cbs = {
+ store,
+ onUndo: vi.fn(),
+ onRedo: vi.fn(),
+ onSave: vi.fn(),
+ onDelete: vi.fn(),
+ onDuplicate: vi.fn(),
+ onSelectAll: vi.fn(),
+ onToggleHelp: vi.fn(),
+ onOpenFind: vi.fn(),
+ onFindNext: vi.fn(),
+ onEscape: vi.fn(),
+ onMergeSelection: vi.fn(),
+ onToggleBold: vi.fn(),
+ onToggleItalic: vi.fn(),
+ };
+ renderHook(() => useEditorKeyboardShortcuts(cbs));
+ return cbs;
+}
+
+function openModal(): HTMLButtonElement {
+ const dialog = document.createElement("div");
+ dialog.setAttribute("role", "dialog");
+ dialog.setAttribute("aria-modal", "true");
+ const button = document.createElement("button");
+ dialog.append(button);
+ document.body.append(dialog);
+ button.focus();
+ return button;
+}
+
+const press = (key: string, init: KeyboardEventInit = {}) =>
+ window.dispatchEvent(
+ new KeyboardEvent("keydown", { key, cancelable: true, ...init }),
+ );
+
+afterEach(() => {
+ document.body.innerHTML = "";
+});
+
+describe("editor shortcuts behind a dialog", () => {
+ test("Delete, Escape and undo leave the selection alone while a dialog is open", () => {
+ const cbs = setup();
+ openModal();
+ press("Delete");
+ press("Backspace");
+ press("Escape");
+ press("z", { ctrlKey: true });
+ expect(cbs.onDelete).not.toHaveBeenCalled();
+ expect(cbs.onEscape).not.toHaveBeenCalled();
+ expect(cbs.onUndo).not.toHaveBeenCalled();
+ });
+
+ test("help and save still work while a dialog is open", () => {
+ const cbs = setup();
+ openModal();
+ press("?");
+ press("s", { ctrlKey: true });
+ expect(cbs.onToggleHelp).toHaveBeenCalledTimes(1);
+ expect(cbs.onSave).toHaveBeenCalledTimes(1);
+ });
+
+ test("Delete reaches the selection once the dialog is gone", () => {
+ const cbs = setup();
+ press("Delete");
+ expect(cbs.onDelete).toHaveBeenCalledTimes(1);
+ });
+});
+
+describe("help while editing text", () => {
+ // jsdom has no isContentEditable; the editor treats a focused text field the same way.
+ function focusText(): HTMLTextAreaElement {
+ const field = document.createElement("textarea");
+ document.body.append(field);
+ field.focus();
+ return field;
+ }
+
+ test("F1 opens the help with the caret in a line of text", () => {
+ const cbs = setup();
+ focusText();
+ press("F1");
+ expect(cbs.onToggleHelp).toHaveBeenCalledTimes(1);
+ });
+
+ test("? still types into the line instead of opening the help", () => {
+ const cbs = setup();
+ focusText();
+ press("?");
+ expect(cbs.onToggleHelp).not.toHaveBeenCalled();
+ });
+});
+
+describe("Bold and Italic", () => {
+ test("Ctrl+B and Ctrl+I restyle the selection, typing in a run included", () => {
+ const cbs = setup();
+ const run = document.createElement("div");
+ run.contentEditable = "true";
+ document.body.append(run);
+ run.focus();
+ const bold = new KeyboardEvent("keydown", {
+ key: "b",
+ ctrlKey: true,
+ cancelable: true,
+ });
+ window.dispatchEvent(bold);
+ press("I", { metaKey: true, shiftKey: true });
+ expect(cbs.onToggleBold).toHaveBeenCalledTimes(1);
+ expect(cbs.onToggleItalic).toHaveBeenCalledTimes(1);
+ expect(bold.defaultPrevented).toBe(true);
+ });
+
+ test("a field keeps Ctrl+B for itself", () => {
+ const cbs = setup();
+ const field = document.createElement("input");
+ document.body.append(field);
+ field.focus();
+ press("b", { ctrlKey: true });
+ expect(cbs.onToggleBold).not.toHaveBeenCalled();
+ });
+});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/hooks/useEditorKeyboardShortcuts.ts b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useEditorKeyboardShortcuts.ts
index b0df72c0ed..8fc95bbe00 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/hooks/useEditorKeyboardShortcuts.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useEditorKeyboardShortcuts.ts
@@ -3,6 +3,7 @@ import type { EditorStore } from "@editor/tools/pdfTextEditor/store/EditorStore"
import {
isFocusInContentEditable,
isFocusInFormField,
+ isModalOpen,
visiblePageNumber,
} from "@editor/tools/pdfTextEditor/util/dom";
import { currentEditorSession } from "@editor/tools/pdfTextEditor/store/EditorSession";
@@ -20,6 +21,8 @@ interface KeyboardShortcutCallbacks {
onFindNext: (reverse: boolean) => void;
onEscape: () => void;
onMergeSelection: () => void;
+ onToggleBold: () => void;
+ onToggleItalic: () => void;
}
/** Bind every editor-level keyboard shortcut to `window` for the session. */
@@ -37,6 +40,8 @@ export function useEditorKeyboardShortcuts(cbs: KeyboardShortcutCallbacks) {
onFindNext,
onEscape,
onMergeSelection,
+ onToggleBold,
+ onToggleItalic,
} = cbs;
useEffect(() => {
@@ -44,7 +49,9 @@ export function useEditorKeyboardShortcuts(cbs: KeyboardShortcutCallbacks) {
const meta = e.ctrlKey || e.metaKey;
if (!meta) return;
// Normalise: with Shift or CapsLock the letter arrives UPPERCASE.
- switch (e.key.toLowerCase()) {
+ const key = e.key.toLowerCase();
+ if (key !== "s" && isModalOpen()) return;
+ switch (key) {
case "z":
// Form fields (Find/Replace/password) keep their NATIVE undo.
if (isFocusInFormField()) return;
@@ -97,6 +104,14 @@ export function useEditorKeyboardShortcuts(cbs: KeyboardShortcutCallbacks) {
e.preventDefault();
onFindNext(e.shiftKey);
return;
+ case "b":
+ case "i":
+ if (isFocusInFormField()) return;
+ if (store.selection.value.runIds.length === 0) return;
+ e.preventDefault();
+ if (key === "b") onToggleBold();
+ else onToggleItalic();
+ return;
case "m":
if (store.selection.value.runIds.length < 2) return;
e.preventDefault();
@@ -111,12 +126,13 @@ export function useEditorKeyboardShortcuts(cbs: KeyboardShortcutCallbacks) {
function onPlainKey(e: KeyboardEvent) {
if (e.ctrlKey || e.metaKey || e.altKey) return;
- if (e.key === "?" || e.key === "F1") {
- if (isFocusInContentEditable()) return;
+ // "?" is a character that types into text; F1 types nothing, so it opens the help from anywhere.
+ if (e.key === "F1" || (e.key === "?" && !isFocusInContentEditable())) {
e.preventDefault();
onToggleHelp();
return;
}
+ if (isModalOpen()) return;
if (e.key === "F3") {
e.preventDefault();
onFindNext(e.shiftKey);
@@ -145,7 +161,7 @@ export function useEditorKeyboardShortcuts(cbs: KeyboardShortcutCallbacks) {
}
function onPageNav(e: KeyboardEvent) {
- if (isFocusInContentEditable()) return;
+ if (isFocusInContentEditable() || isModalOpen()) return;
const isHome = e.key === "Home" && (e.ctrlKey || e.metaKey);
const isEnd = e.key === "End" && (e.ctrlKey || e.metaKey);
if (e.key !== "PageDown" && e.key !== "PageUp" && !isHome && !isEnd) {
@@ -189,5 +205,7 @@ export function useEditorKeyboardShortcuts(cbs: KeyboardShortcutCallbacks) {
onFindNext,
onEscape,
onMergeSelection,
+ onToggleBold,
+ onToggleItalic,
]);
}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/hooks/useEditorSelection.ts b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useEditorSelection.ts
index 839fd6cd4b..fbb2eefe57 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/hooks/useEditorSelection.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useEditorSelection.ts
@@ -1,5 +1,6 @@
import { useCallback, useSyncExternalStore } from "react";
import type { EditorStore } from "@editor/tools/pdfTextEditor/store/EditorStore";
+import type { FindMatch } from "@editor/tools/pdfTextEditor/store/Selection";
import type { SelectionState } from "@editor/tools/pdfTextEditor/types";
/**
@@ -14,8 +15,8 @@ export function useEditorSelection(store: EditorStore): SelectionState {
return useSyncExternalStore(subscribe, () => store.selection.value);
}
-/** The run the find bar is pointing at, or null. */
-export function useHighlightedRunId(store: EditorStore): string | null {
+/** The occurrence the find bar is pointing at, or null. */
+export function useFindMatch(store: EditorStore): FindMatch | null {
const subscribe = useCallback(
(onChange: () => void) => store.selection.highlight.subscribe(onChange),
[store],
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/hooks/useFontEpoch.ts b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useFontEpoch.ts
new file mode 100644
index 0000000000..e5373b2f7c
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useFontEpoch.ts
@@ -0,0 +1,54 @@
+import { useSyncExternalStore } from "react";
+import { onEmbeddedFaceLoaded } from "@editor/tools/pdfTextEditor/util/embeddedFace";
+import { resetTextMetricsCache } from "@editor/tools/pdfTextEditor/util/textMetrics";
+
+let epoch = 0;
+const subscribers = new Set<() => void>();
+let stopWatching: (() => void) | null = null;
+
+function fontsChanged(): void {
+ resetTextMetricsCache();
+ epoch++;
+ for (const notify of [...subscribers]) notify();
+}
+
+// One watcher for every overlay: each reading `document.fonts.ready` and clearing the metrics cache for itself took most of a minute to open a page of 10,000 runs.
+function watchFonts(): () => void {
+ const stopFaces = onEmbeddedFaceLoaded(fontsChanged);
+ const fonts = typeof document === "undefined" ? undefined : document.fonts;
+ if (!fonts) return stopFaces;
+ let watching = true;
+ if (fonts.status === "loading")
+ void fonts.ready.then(() => {
+ if (watching) fontsChanged();
+ });
+ fonts.addEventListener("loadingdone", fontsChanged);
+ return () => {
+ watching = false;
+ stopFaces();
+ fonts.removeEventListener("loadingdone", fontsChanged);
+ };
+}
+
+function subscribe(notify: () => void): () => void {
+ subscribers.add(notify);
+ stopWatching ??= watchFonts();
+ return () => {
+ subscribers.delete(notify);
+ if (subscribers.size > 0) return;
+ stopWatching?.();
+ stopWatching = null;
+ };
+}
+
+const currentEpoch = () => epoch;
+
+/**
+ * Counts the times the fonts text is measured in have changed: a document or
+ * embedded face finishing loading. The text-metrics cache is already cleared
+ * when the count moves, once for every subscriber, so a measurement memoised
+ * on it is redone against the new faces.
+ */
+export function useFontEpoch(): number {
+ return useSyncExternalStore(subscribe, currentEpoch, currentEpoch);
+}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/hooks/useSelectionActions.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useSelectionActions.test.ts
index 671b3961b6..b49b512fbd 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/hooks/useSelectionActions.test.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useSelectionActions.test.ts
@@ -3,11 +3,38 @@ import path from "node:path";
import { act, renderHook, waitFor } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-const { get } = vi.hoisted(() => ({ get: vi.fn() }));
+const { get, losesText, lacksLetters, notRestored, loadScriptScanFaces } =
+ vi.hoisted(() => ({
+ get: vi.fn(),
+ losesText: new Set<string>(),
+ lacksLetters: new Set<string>(),
+ notRestored: new Set<string>(),
+ loadScriptScanFaces: vi.fn(async (_scripts: readonly string[]) => {}),
+ }));
+vi.mock(
+ "@editor/tools/pdfTextEditor/util/scanFontLibrary",
+ async (importOriginal) => ({
+ ...(await importOriginal<object>()),
+ loadScriptScanFaces,
+ }),
+);
vi.mock("@editor/services/apiClient", () => ({ default: { get } }));
vi.mock("@editor/tools/pdfTextEditor/commands/SetFontFamilyCommand", () => ({
SetFontFamilyCommand: class {
constructor(readonly opts: { runId: string; nextFamily: string }) {}
+
+ wouldLoseText(): boolean {
+ return losesText.has(this.opts.runId);
+ }
+
+ coverage(): "all" | "some" {
+ return lacksLetters.has(this.opts.runId) ? "some" : "all";
+ }
+
+ refusal(): "losesText" | "notRestored" | null {
+ if (this.wouldLoseText()) return "losesText";
+ return notRestored.has(this.opts.runId) ? "notRestored" : null;
+ }
},
}));
vi.mock(
@@ -36,6 +63,12 @@ import {
resetLocalFontsCache,
} from "@editor/tools/pdfTextEditor/util/localFonts";
import { resetDeviceFontEmbedCache } from "@editor/tools/pdfTextEditor/util/deviceFontEmbed";
+import {
+ noteDocumentFontStyle,
+ resetDocumentFontStyles,
+} from "@editor/tools/pdfTextEditor/util/documentFontStyle";
+import { _clearFontNameCacheForTests } from "@editor/tools/pdfTextEditor/charcode/FontHelpers";
+import type { WrappedPdfiumModule } from "@embedpdf/pdfium";
import {
prefitScanRun,
scanRunNeedsFit,
@@ -45,12 +78,21 @@ const REGULAR = "1".repeat(64);
const ITALIC = "2".repeat(64);
const HEBREW = "5".repeat(64);
-const HEBREW_TTF = readFileSync(
- path.resolve(
- __dirname,
- "../../../../../../../app/core/src/main/resources/static/fonts/NotoSansHebrew-Regular.ttf",
- ),
+const FONTS = path.resolve(
+ __dirname,
+ "../../../../../../../app/core/src/main/resources/static/fonts",
);
+const HEBREW_TTF = readFileSync(path.join(FONTS, "NotoSansHebrew-Regular.ttf"));
+const LATIN_TTF = readFileSync(path.join(FONTS, "LiberationSans-Regular.ttf"));
+
+function bytesOf(font: Buffer): { data: ArrayBuffer } {
+ return {
+ data: font.buffer.slice(
+ font.byteOffset,
+ font.byteOffset + font.byteLength,
+ ) as ArrayBuffer,
+ };
+}
function face(id: string, style: string, italic: boolean) {
return { id, style, bold: false, italic, weight: 400, postscriptName: "" };
@@ -72,6 +114,7 @@ interface FakeRun {
fontId: string;
text: string;
locked: boolean;
+ textReadOnly?: boolean;
fill: { r: number; g: number; b: number; a: number };
}
@@ -99,6 +142,8 @@ function fakeStore(
loadedPages: () => [{ runs }],
docPtr: 1,
ownedFont: (id: string) => owned.get(id),
+ findOwnedFont: (matches: (font: { id: string }) => boolean) =>
+ [...owned.values()].find(matches),
registerOwnedFont: (font: { id: string }) => owned.set(font.id, font),
recordEmbeddedFontFile: () => {},
module: {
@@ -113,9 +158,11 @@ function fakeStore(
let doc = openDocument();
const selection = { value: { runIds: selected } };
const dispatch = vi.fn();
+ const setError = vi.fn();
const store = {
selection,
dispatch,
+ setError,
get document() {
return doc;
},
@@ -123,6 +170,7 @@ function fakeStore(
return {
store,
dispatch,
+ setError,
select: (ids: string[]) => {
selection.value = { runIds: ids };
},
@@ -152,6 +200,18 @@ function serveFaces(serve: (id: string) => Promise<{ data: ArrayBuffer }>) {
});
}
+/** Serve every face from a download that stays pending until the returned call. */
+function holdDownloads(): (value: { data: ArrayBuffer }) => void {
+ let finish: (value: { data: ArrayBuffer }) => void = () => {};
+ serveFaces(
+ () =>
+ new Promise((resolve) => {
+ finish = resolve;
+ }),
+ );
+ return (value) => finish(value);
+}
+
function fontBytes(): { data: ArrayBuffer } {
return { data: new Uint8Array([0, 1, 0, 0]).buffer };
}
@@ -160,12 +220,36 @@ function actionsFor(store: EditorStore) {
return renderHook(() => useSelectionActions(store)).result.current;
}
+const ITALIC_FLAG = 64;
+
+/** A document font as PDFium describes it: its /BaseFont name and descriptor flags. */
+function documentFont(handle: number, baseFont: string, flags: number): void {
+ noteDocumentFontStyle(
+ {
+ FPDFFont_GetBaseFontName: (_font: number, buf: number) =>
+ buf ? 0 : baseFont.length + 1,
+ FPDFFont_GetFlags: () => flags,
+ pdfium: {
+ UTF8ToString: () => baseFont,
+ wasmExports: { malloc: () => 8, free: () => {} },
+ },
+ } as unknown as WrappedPdfiumModule,
+ handle,
+ );
+}
+
describe("useSelectionActions font changes", () => {
beforeEach(() => {
get.mockReset();
forgetServerFontList();
resetLocalFontsCache();
resetDeviceFontEmbedCache();
+ resetDocumentFontStyles();
+ _clearFontNameCacheForTests();
+ losesText.clear();
+ lacksLetters.clear();
+ notRestored.clear();
+ loadScriptScanFaces.mockClear();
});
afterEach(() => {
@@ -188,6 +272,97 @@ describe("useSelectionActions font changes", () => {
expect(dispatchedChanges(dispatch)).toEqual(["a:Times-Roman"]);
});
+ it("keeps bold italic text bold italic in the built-in family picked", async () => {
+ const { store, dispatch } = fakeStore(
+ [run("a", "pdf:7:TrebuchetMS-BoldItalic"), run("b", "base14:Helvetica")],
+ ["a", "b"],
+ );
+
+ expect(await actionsFor(store).changeFontFamily("Times-Roman")).toBeNull();
+
+ expect(dispatchedChanges(dispatch)).toEqual([
+ "a:Times-BoldItalic",
+ "b:Times-Roman",
+ ]);
+ });
+
+ it("applies a face named outright as it is", async () => {
+ const { store, dispatch } = fakeStore(
+ [run("a", "pdf:7:TrebuchetMS-BoldItalic")],
+ ["a"],
+ );
+
+ expect(await actionsFor(store).changeFontFamily("Times-Italic")).toBeNull();
+
+ expect(dispatchedChanges(dispatch)).toEqual(["a:Times-Italic"]);
+ });
+
+ it("keeps an italic run italic in a server family with an italic face", async () => {
+ serveFaces(async () => fontBytes());
+ await loadServerFonts();
+ const { store, dispatch } = fakeStore(
+ [run("a", "pdf:7:TrebuchetMS-Italic"), run("b", "base14:Helvetica")],
+ ["a", "b"],
+ );
+
+ expect(await actionsFor(store).changeFontFamily("Acme Sans")).toBeNull();
+
+ expect(dispatchedChanges(dispatch)).toEqual([
+ "a:Acme Sans Italic",
+ "b:Acme Sans",
+ ]);
+ });
+
+ it("keeps a run italic when only the PDF's own font name says so", async () => {
+ serveFaces(async () => fontBytes());
+ await loadServerFonts();
+ documentFont(7, "DAAAAA+Georgia-Italic", 0);
+ documentFont(8, "BAAAAA+Georgia", 0);
+ const { store, dispatch } = fakeStore(
+ [run("a", "pdf:7:Georgia"), run("b", "pdf:8:Georgia")],
+ ["a", "b"],
+ );
+
+ expect(await actionsFor(store).changeFontFamily("Acme Sans")).toBeNull();
+
+ expect(dispatchedChanges(dispatch)).toEqual([
+ "a:Acme Sans Italic",
+ "b:Acme Sans",
+ ]);
+ });
+
+ it("keeps a run italic when only its font descriptor says so", async () => {
+ serveFaces(async () => fontBytes());
+ await loadServerFonts();
+ documentFont(7, "ABCDEF+MinionPro-It", ITALIC_FLAG);
+ const noDescriptor = -1;
+ documentFont(8, "ABCDEF+MinionPro", noDescriptor);
+ const { store, dispatch } = fakeStore(
+ [run("a", "pdf:7:Minion Pro"), run("b", "pdf:8:Minion Pro")],
+ ["a", "b"],
+ );
+
+ expect(await actionsFor(store).changeFontFamily("Acme Sans")).toBeNull();
+
+ expect(dispatchedChanges(dispatch)).toEqual([
+ "a:Acme Sans Italic",
+ "b:Acme Sans",
+ ]);
+ });
+
+ it("leaves bold to the bold entries in the list", async () => {
+ serveFaces(async () => fontBytes());
+ await loadServerFonts();
+ const { store, dispatch } = fakeStore(
+ [run("a", "pdf:7:TrebuchetMS-Bold")],
+ ["a"],
+ );
+
+ expect(await actionsFor(store).changeFontFamily("Acme Sans")).toBeNull();
+
+ expect(dispatchedChanges(dispatch)).toEqual(["a:Acme Sans"]);
+ });
+
it("leaves a run locked while its font change was waiting", async () => {
const runs = [run("a", "base14:Helvetica")];
const { store, dispatch } = fakeStore(runs, ["a"]);
@@ -231,13 +406,7 @@ describe("useSelectionActions font changes", () => {
});
it("changes the runs that were selected when the font was picked", async () => {
- let finishDownload: (value: { data: ArrayBuffer }) => void = () => {};
- serveFaces(
- () =>
- new Promise((resolve) => {
- finishDownload = resolve;
- }),
- );
+ const finishDownload = holdDownloads();
await loadServerFonts();
const { store, dispatch, select } = fakeStore(
[run("a", "base14:Helvetica"), run("b", "base14:Helvetica")],
@@ -254,19 +423,15 @@ describe("useSelectionActions font changes", () => {
});
it("drops a font change when another document opened during the download", async () => {
- let finishDownload: (value: { data: ArrayBuffer }) => void = () => {};
- serveFaces(
- () =>
- new Promise((resolve) => {
- finishDownload = resolve;
- }),
- );
+ const finishDownload = holdDownloads();
await loadServerFonts();
const { store, dispatch, openAnotherDocument } = fakeStore(
[run("a", "base14:Helvetica")],
["a"],
);
+ const closed = vi.spyOn(store.document!.module, "FPDFText_LoadFont");
+
const picked = actionsFor(store).changeFontFamily("Acme Sans");
openAnotherDocument();
await vi.waitFor(() => expect(get).toHaveBeenCalledTimes(2));
@@ -274,16 +439,11 @@ describe("useSelectionActions font changes", () => {
expect(await picked).toBeNull();
expect(dispatch).not.toHaveBeenCalled();
+ expect(closed).not.toHaveBeenCalled();
});
it("skips runs removed during the download and records nothing when none remain", async () => {
- let finishDownload: (value: { data: ArrayBuffer }) => void = () => {};
- serveFaces(
- () =>
- new Promise((resolve) => {
- finishDownload = resolve;
- }),
- );
+ const finishDownload = holdDownloads();
await loadServerFonts();
const runs = [run("a", "base14:Helvetica"), run("b", "base14:Helvetica")];
const { store, dispatch } = fakeStore(runs, ["a", "b"]);
@@ -350,13 +510,7 @@ describe("useSelectionActions font changes", () => {
});
it("leaves a run locked during the download unchanged", async () => {
- let finishDownload: (value: { data: ArrayBuffer }) => void = () => {};
- serveFaces(
- () =>
- new Promise((resolve) => {
- finishDownload = resolve;
- }),
- );
+ const finishDownload = holdDownloads();
await loadServerFonts();
const runs = [run("a", "base14:Helvetica"), run("b", "base14:Helvetica")];
const { store, dispatch } = fakeStore(runs, ["a", "b"]);
@@ -389,18 +543,14 @@ describe("useSelectionActions font changes", () => {
});
it("refuses a font that has none of the selected characters", async () => {
- serveFaces(async () => ({
- data: HEBREW_TTF.buffer.slice(
- HEBREW_TTF.byteOffset,
- HEBREW_TTF.byteOffset + HEBREW_TTF.byteLength,
- ),
- }));
+ serveFaces(async () => bytesOf(HEBREW_TTF));
await loadServerFonts();
const english = fakeStore([run("a", "base14:Helvetica", "Hello")], ["a"]);
const mixed = fakeStore(
[run("b", "base14:Helvetica", "Hello שלום")],
["b"],
);
+ lacksLetters.add("b");
expect(
await actionsFor(english.store).changeFontFamily("Noto Sans Hebrew"),
@@ -409,9 +559,342 @@ describe("useSelectionActions font changes", () => {
expect(
await actionsFor(mixed.store).changeFontFamily("Noto Sans Hebrew"),
- ).toBeNull();
+ ).toBe("closestMatch");
expect(dispatchedChanges(mixed.dispatch)).toEqual(["b:Noto Sans Hebrew"]);
});
+
+ it("leaves text that needs shaping in its own font", async () => {
+ const hindi = fakeStore([run("a", "pdf:7:Mangal", "नमस्ते")], ["a"]);
+ const mixed = fakeStore(
+ [run("b", "pdf:7:Mangal", "नमस्ते"), run("c", "pdf:7:Arial", "Hello")],
+ ["b", "c"],
+ );
+
+ expect(await actionsFor(hindi.store).changeFontFamily("Times-Roman")).toBe(
+ "needsShaping",
+ );
+ expect(hindi.dispatch).not.toHaveBeenCalled();
+ expect(await actionsFor(mixed.store).changeFontFamily("Times-Roman")).toBe(
+ "needsShaping",
+ );
+ expect(dispatchedChanges(mixed.dispatch)).toEqual(["c:Times-Roman"]);
+ });
+
+ it("refuses a font that has only the digits and punctuation of a line", async () => {
+ serveFaces(async () => bytesOf(LATIN_TTF));
+ await loadServerFonts();
+ const heading = fakeStore(
+ [run("a", "pdf:7:DejaVu Serif", "Հոդված 1, 2.")],
+ ["a"],
+ );
+ const numbers = fakeStore([run("b", "pdf:7:DejaVu Serif", "1, 2.")], ["b"]);
+
+ expect(await actionsFor(heading.store).changeFontFamily("Acme Sans")).toBe(
+ "noGlyphs",
+ );
+ expect(heading.dispatch).not.toHaveBeenCalled();
+ expect(
+ await actionsFor(numbers.store).changeFontFamily("Acme Sans"),
+ ).toBeNull();
+ expect(dispatchedChanges(numbers.dispatch)).toEqual(["b:Acme Sans"]);
+ });
+
+ it("leaves a run upright when the italic cut has none of its letters", async () => {
+ serveFaces(async (id) =>
+ id === ITALIC ? bytesOf(HEBREW_TTF) : bytesOf(LATIN_TTF),
+ );
+ await loadServerFonts();
+ const { store, dispatch } = fakeStore(
+ [
+ run("a", "device:Acme Sans", "Hello"),
+ run("b", "device:Acme Sans", "שלום"),
+ ],
+ ["a", "b"],
+ );
+
+ await actionsFor(store).toggleItalic();
+
+ expect(dispatchedChanges(dispatch)).toEqual(["b:Acme Sans Italic"]);
+ });
+
+ it("refuses a built-in font that has none of a line's letters", async () => {
+ const korean = fakeStore(
+ [run("a", "pdf:7:Noto Sans KR", "모든 인류 구성원의 자유,")],
+ ["a"],
+ );
+ const symbols = fakeStore([run("b", "pdf:7:Symbols", "✓ → ≥")], ["b"]);
+ const numbers = fakeStore(
+ [run("c", "pdf:7:Noto Sans KR", "1,250.00")],
+ ["c"],
+ );
+
+ expect(await actionsFor(korean.store).changeFontFamily("Times-Bold")).toBe(
+ "noGlyphs",
+ );
+ expect(korean.dispatch).not.toHaveBeenCalled();
+ expect(await actionsFor(symbols.store).changeFontFamily("Helvetica")).toBe(
+ "noGlyphs",
+ );
+ expect(symbols.dispatch).not.toHaveBeenCalled();
+ expect(
+ await actionsFor(numbers.store).changeFontFamily("Helvetica"),
+ ).toBeNull();
+ expect(dispatchedChanges(numbers.dispatch)).toEqual(["c:Helvetica"]);
+ });
+
+ it("leaves a run the font has no letters for as it is and changes the rest", async () => {
+ const { store, dispatch } = fakeStore(
+ [
+ run("a", "pdf:7:Noto Sans", "Article 1"),
+ run("b", "pdf:8:Noto Sans KR", "모든 인류"),
+ ],
+ ["a", "b"],
+ );
+
+ expect(await actionsFor(store).changeFontFamily("Helvetica")).toBe(
+ "someLeftUnchanged",
+ );
+ expect(dispatchedChanges(dispatch)).toEqual(["a:Helvetica"]);
+ });
+
+ it("leaves a line the editor cannot redraw as it is, says so, and changes the rest", async () => {
+ const mixed = {
+ ...run("b", "pdf:8:Noto Sans", "ISO 50001"),
+ textReadOnly: true,
+ };
+ const { store, dispatch, setError } = fakeStore(
+ [run("a", "pdf:7:Noto Sans", "Article 1"), mixed],
+ ["a", "b"],
+ );
+ const actions = actionsFor(store);
+
+ expect(await actions.changeFontFamily("Helvetica")).toBeNull();
+ expect(dispatchedChanges(dispatch)).toEqual(["a:Helvetica"]);
+ expect(setError).toHaveBeenCalledTimes(1);
+
+ actions.changeFill("#ff0000");
+ await waitFor(() => expect(dispatch).toHaveBeenCalledTimes(2));
+ expect((dispatch.mock.calls[1][0] as Recorded).commands).toHaveLength(2);
+ expect(setError).toHaveBeenCalledTimes(1);
+ });
+
+ it("says why when the document font cannot draw the text it is put back on", async () => {
+ notRestored.add("a");
+ const { store, dispatch } = fakeStore(
+ [run("a", "base14:Helvetica", "Time (s)")],
+ ["a"],
+ );
+
+ expect(await actionsFor(store).changeFontFamily("pdf:7:DejaVuSans")).toBe(
+ "documentFontCannotDraw",
+ );
+ expect(dispatchedChanges(dispatch)).toEqual([]);
+ });
+
+ it("gives a run the plain family when the italic cut has none of its letters", async () => {
+ get.mockImplementation(async (url: string) => {
+ if (url === SERVER_FONTS_URL)
+ return {
+ data: {
+ families: [
+ {
+ family: "Mixed Sans",
+ faces: [
+ face(REGULAR, "Regular", false),
+ face(HEBREW, "Italic", true),
+ ],
+ },
+ ],
+ },
+ };
+ return url.endsWith(HEBREW) ? bytesOf(HEBREW_TTF) : fontBytes();
+ });
+ await loadServerFonts();
+ const { store, dispatch } = fakeStore(
+ [
+ run("a", "pdf:7:Georgia-Italic", "Hello"),
+ run("b", "pdf:7:Georgia-Italic", "שלום"),
+ ],
+ ["a", "b"],
+ );
+
+ expect(await actionsFor(store).changeFontFamily("Mixed Sans")).toBeNull();
+
+ expect(dispatchedChanges(dispatch)).toEqual([
+ "a:Mixed Sans",
+ "b:Mixed Sans Italic",
+ ]);
+ });
+
+ it("leaves a run that would lose letters as it is", async () => {
+ losesText.add("b");
+ const both = fakeStore(
+ [run("a", "pdf:7:Noto Sans"), run("b", "pdf:7:Noto Sans")],
+ ["a", "b"],
+ );
+ const alone = fakeStore([run("b", "pdf:7:Noto Sans")], ["b"]);
+
+ expect(await actionsFor(both.store).changeFontFamily("Helvetica")).toBe(
+ "someLeftUnchanged",
+ );
+ expect(dispatchedChanges(both.dispatch)).toEqual(["a:Helvetica"]);
+
+ expect(await actionsFor(alone.store).changeFontFamily("Helvetica")).toBe(
+ "missingGlyphs",
+ );
+ expect(alone.dispatch).not.toHaveBeenCalled();
+ expect(loadScriptScanFaces).not.toHaveBeenCalled();
+ });
+
+ it("fetches the script fonts for text a change would lose before giving up on it", async () => {
+ losesText.add("a");
+ loadScriptScanFaces.mockImplementationOnce(async () => {
+ losesText.clear();
+ });
+ lacksLetters.add("a");
+ const { store, dispatch } = fakeStore(
+ [run("a", "pdf:7:Noto Sans", "Total ภาษาไทย")],
+ ["a"],
+ );
+
+ expect(await actionsFor(store).changeFontFamily("Helvetica")).toBe(
+ "closestMatch",
+ );
+
+ expect(loadScriptScanFaces).toHaveBeenCalledWith(["thai"]);
+ expect(dispatchedChanges(dispatch)).toEqual(["a:Helvetica"]);
+ });
+
+ it("puts text back in the PDF's own font without loading any font bytes", async () => {
+ const { store, dispatch } = fakeStore(
+ [run("a", "device:Acme Sans")],
+ ["a"],
+ );
+
+ expect(
+ await actionsFor(store).changeFontFamily("pdf:7:Garamond"),
+ ).toBeNull();
+
+ expect(get).not.toHaveBeenCalled();
+ expect(dispatchedChanges(dispatch)).toEqual(["a:pdf:7:Garamond"]);
+ });
+
+ it("drops a font still loading once a later font change has been made", async () => {
+ const finishDownload = holdDownloads();
+ await loadServerFonts();
+ const { store, dispatch } = fakeStore(
+ [run("a", "device:Acme Sans")],
+ ["a"],
+ );
+ const actions = actionsFor(store);
+
+ const pending = actions.changeFontFamily("Acme Sans Italic");
+ await vi.waitFor(() => expect(get).toHaveBeenCalledTimes(2));
+ await actions.changeFontFamily("pdf:7:Garamond");
+ finishDownload(fontBytes());
+ await pending;
+
+ expect(dispatchedChanges(dispatch)).toEqual(["a:pdf:7:Garamond"]);
+ });
+
+ it("drops a font still loading once the runs were rebuilt under the same ids", async () => {
+ const finishDownload = holdDownloads();
+ await loadServerFonts();
+ const runs = [run("a", "base14:Helvetica")];
+ const { store, dispatch } = fakeStore(runs, ["a"]);
+
+ const picked = actionsFor(store).changeFontFamily("Acme Sans");
+ await vi.waitFor(() => expect(get).toHaveBeenCalledTimes(2));
+ runs[0] = { ...runs[0], text: "Hello\nworld" };
+ finishDownload(fontBytes());
+
+ expect(await picked).toBeNull();
+ expect(dispatch).not.toHaveBeenCalled();
+ });
+
+ it("still applies a font still loading for text a later change did not touch", async () => {
+ const finishDownload = holdDownloads();
+ await loadServerFonts();
+ const { store, dispatch, select } = fakeStore(
+ [run("a", "device:Acme Sans"), run("b", "device:Acme Sans")],
+ ["a"],
+ );
+ const actions = actionsFor(store);
+
+ const pending = actions.changeFontFamily("Acme Sans Italic");
+ await vi.waitFor(() => expect(get).toHaveBeenCalledTimes(2));
+ select(["b"]);
+ await actions.changeFontFamily("pdf:7:Garamond");
+ finishDownload(fontBytes());
+ await pending;
+
+ expect(dispatchedChanges(dispatch)).toEqual([
+ "b:pdf:7:Garamond",
+ "a:Acme Sans Italic",
+ ]);
+ });
+
+ it("makes a half-bold selection all bold", async () => {
+ const { store, dispatch } = fakeStore(
+ [run("a", "base14:Helvetica"), run("b", "base14:Helvetica-Bold")],
+ ["a", "b"],
+ );
+
+ expect(await actionsFor(store).toggleBold()).toBeNull();
+
+ expect(dispatchedChanges(dispatch)).toEqual(["a:Helvetica-Bold"]);
+ });
+
+ it("moves document text to the document's own bold face", async () => {
+ documentFont(7, "ABCDEF+Calibri", 0);
+ documentFont(8, "GHIJKL+Calibri-Bold", 0);
+ const { store, dispatch } = fakeStore(
+ [run("a", "pdf:7:Calibri"), run("b", "pdf:8:Calibri")],
+ ["a"],
+ );
+
+ expect(await actionsFor(store).toggleBold()).toBeNull();
+
+ expect(get).not.toHaveBeenCalled();
+ expect(dispatchedChanges(dispatch)).toEqual(["a:pdf:8:Calibri"]);
+ });
+
+ it("makes no bold up for a family that has no bold face, and says so", async () => {
+ documentFont(7, "ABCDEF+Garamond", 0);
+ const { store, dispatch } = fakeStore([run("a", "pdf:7:Garamond")], ["a"]);
+
+ expect(await actionsFor(store).toggleBold()).toBe("styleUnavailable");
+
+ expect(dispatch).not.toHaveBeenCalled();
+ });
+
+ it("warns that letters the bold face lacks are drawn in the closest match", async () => {
+ lacksLetters.add("a");
+ const { store, dispatch } = fakeStore(
+ [run("a", "base14:Helvetica", "Hello שלום")],
+ ["a"],
+ );
+
+ expect(await actionsFor(store).toggleBold()).toBe("closestMatch");
+
+ expect(dispatchedChanges(dispatch)).toEqual(["a:Helvetica-Bold"]);
+ });
+
+ it("says so when the italic toggle leaves some of the selection upright", async () => {
+ serveFaces(async (id) => {
+ if (id === ITALIC) throw new Error("gone");
+ return fontBytes();
+ });
+ await loadServerFonts();
+ const { store, dispatch } = fakeStore(
+ [run("a", "base14:Helvetica"), run("b", "device:Acme Sans")],
+ ["a", "b"],
+ );
+
+ expect(await actionsFor(store).toggleItalic()).toBe("styleSkipped");
+
+ expect(dispatchedChanges(dispatch)).toEqual(["a:Helvetica-Oblique"]);
+ });
});
describe("useSelectionActions on unfitted scanned text", () => {
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/hooks/useSelectionActions.ts b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useSelectionActions.ts
index 9095e2702f..4b4e13fdc8 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/hooks/useSelectionActions.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useSelectionActions.ts
@@ -1,26 +1,56 @@
-import { useCallback } from "react";
+import { useCallback, useRef } from "react";
import { DeleteImageCommand } from "@editor/tools/pdfTextEditor/commands/DeleteImageCommand";
import { ReplaceImageCommand } from "@editor/tools/pdfTextEditor/commands/ReplaceImageCommand";
import type { DecodedImage } from "@editor/utils/pdfiumBitmapUtils";
import { DeleteObjectCommand } from "@editor/tools/pdfTextEditor/commands/DeleteObjectCommand";
import { DeleteShapeCommand } from "@editor/tools/pdfTextEditor/commands/DeleteShapeCommand";
import { DuplicateRunCommand } from "@editor/tools/pdfTextEditor/commands/DuplicateRunCommand";
+import { unsafeRtlEditMessage } from "@editor/tools/pdfTextEditor/commands/readOnlyText";
import { SetColourCommand } from "@editor/tools/pdfTextEditor/commands/SetColourCommand";
import { SetTextOutlineCommand } from "@editor/tools/pdfTextEditor/commands/SetTextOutlineCommand";
import { SetFontFamilyCommand } from "@editor/tools/pdfTextEditor/commands/SetFontFamilyCommand";
import { SetFontSizeCommand } from "@editor/tools/pdfTextEditor/commands/SetFontSizeCommand";
+import {
+ rangeRefusal,
+ selectedFontStretches,
+ selectedPartOfRun,
+ StyleTextRangeCommand,
+ type FaceStretch,
+ type RangeRefusal,
+ type SelectedPart,
+} from "@editor/tools/pdfTextEditor/commands/StyleTextRangeCommand";
import { parseCssColor } from "@editor/tools/pdfTextEditor/model/Color";
import {
- deviceFontDrawsAnyOf,
+ drawsSomeOf,
+ familyCoverage,
loadDeviceFontInto,
+ visibleCodePoints,
} from "@editor/tools/pdfTextEditor/util/deviceFontEmbed";
+import {
+ loadScriptScanFaces,
+ scanScriptsOf,
+} from "@editor/tools/pdfTextEditor/util/scanFontLibrary";
import type { EditorStore } from "@editor/tools/pdfTextEditor/store/EditorStore";
import type { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
import {
- isItalicFamily,
+ isDocumentFontId,
nearestStandardFont,
} from "@editor/tools/pdfTextEditor/util/fontFamily";
-import { italicCapability } from "@editor/tools/pdfTextEditor/util/fontCapability";
+import {
+ faceKeepingStyle,
+ faceStyleOf,
+ familyOfFace,
+ knownDocumentFamilies,
+ restyledFace,
+ type FaceSources,
+ type FontFamilyEntry,
+ type StyleRequest,
+} from "@editor/tools/pdfTextEditor/util/fontFaces";
+import {
+ isBoldWeight,
+ type FaceStyle,
+} from "@editor/tools/pdfTextEditor/util/faceNames";
+import { isScanRun } from "@editor/tools/pdfTextEditor/commands/scanTextEdit";
import {
loadedExternalFonts,
loadExternalFont,
@@ -32,6 +62,7 @@ import type { Page } from "@editor/tools/pdfTextEditor/model/Page";
import type { TextRun } from "@editor/tools/pdfTextEditor/model/TextRun";
import type { ScanFitTarget } from "@editor/tools/pdfTextEditor/commands/scanFitSlices";
import { useDispatchAfterScanFit } from "@editor/tools/pdfTextEditor/hooks/useDispatchAfterScanFit";
+import { needsShaping } from "@editor/tools/pdfTextEditor/util/complexShaping";
/** The fields the selection actions read off a run they are about to change. */
interface SelectedRun {
@@ -40,18 +71,45 @@ interface SelectedRun {
fontId: string;
text: string;
fill: { r: number; g: number; b: number; a: number };
+ textReadOnly: boolean;
+ renderMode?: number;
}
+/** `redraws` is for an action that redraws, rescales or restyles text: it leaves out the lines the editor cannot redraw and says so. */
+type VisitSelectedRuns = (
+ visit: (run: SelectedRun, page: Page) => void,
+ redraws?: boolean,
+) => void;
+
export type FontPickFailure =
+ | "needsShaping"
| "serverFontFailed"
| "embeddingForbidden"
| "embedFailed"
- | "noGlyphs";
+ | "noGlyphs"
+ | "missingGlyphs"
+ | "someLeftUnchanged"
+ | "closestMatch"
+ | "styleUnavailable"
+ | "styleSkipped"
+ | "partOfRunUnsupported"
+ | "documentFontCannotDraw";
interface FamilyChange {
pageIndex: number;
runId: string;
family: string;
+ text: string;
+}
+
+/** How many runs a font change reached, how many it left as they were and why, and how many of the changed ones the new font lacks letters of. */
+interface FamilyChangeOutcome {
+ applied: number;
+ undrawable: number;
+ wouldLoseText: number;
+ notRestored: number;
+ unshapeable: number;
+ inClosestMatch: number;
}
/** Loads the family's bytes; the failure that must stop the pick, or null to go on. */
@@ -68,14 +126,131 @@ function tryEmbedDeviceFont(doc: EditorDocument, family: string): boolean {
return loadDeviceFontInto(doc, family) !== 0;
}
+function isDeviceFace(face: string): boolean {
+ return !isDocumentFontId(face) && nearestStandardFont(face) !== face;
+}
+
+/**
+ * Loads and embeds a device face ahead of the command that draws in it, as
+ * Command.apply cannot wait for bytes. Null when `doc` closed meanwhile.
+ */
+async function embedDeviceFace(
+ store: EditorStore,
+ doc: EditorDocument,
+ face: string,
+): Promise<boolean | null> {
+ const refused = await prepareExternalFont(face);
+ if (store.document !== doc) return null;
+ return !refused && tryEmbedDeviceFont(doc, face);
+}
+
async function fontPickFailure(
+ doc: EditorDocument | null,
family: string,
- text: string,
+ texts: string[],
): Promise<FontPickFailure | null> {
- if (nearestStandardFont(family) === family) return null;
- const refusal = await prepareExternalFont(family);
- if (refusal) return refusal;
- return deviceFontDrawsAnyOf(family, text) ? null : "noGlyphs";
+ if (nearestStandardFont(family) !== family) {
+ const refusal = await prepareExternalFont(family);
+ if (refusal) return refusal;
+ }
+ const draws = familyCoverage(doc, family);
+ return texts.length === 0 || texts.some((text) => drawsSomeOf(draws, text))
+ ? null
+ : "noGlyphs";
+}
+
+/** Null when the family is ready to draw at least one of `texts`, or when `doc` is no longer the open document, which callers check for themselves. */
+async function prepareFamily(
+ store: EditorStore,
+ doc: EditorDocument | null,
+ family: string,
+ texts: string[],
+): Promise<FontPickFailure | null> {
+ // Embedding is async and Command.apply is not, so warm the bytes first.
+ // A no-op for the built-in families.
+ const failure = await fontPickFailure(doc, family, texts);
+ if (failure) return failure;
+ // Another document may have opened during the download; this one's PDFium handle is then gone.
+ if (!doc || store.document !== doc) return null;
+ // Refuse here, as the command would fall back to a standard face the user never picked.
+ if (
+ nearestStandardFont(family) !== family &&
+ !tryEmbedDeviceFont(doc, family)
+ )
+ return "embedFailed";
+ return null;
+}
+
+function familyCommand(change: FamilyChange): SetFontFamilyCommand {
+ return new SetFontFamilyCommand({
+ pageIndex: change.pageIndex,
+ runId: change.runId,
+ nextFamily: change.family,
+ });
+}
+
+/**
+ * Fetch the script fonts that draw text a change would otherwise leave
+ * undrawn. Typed text gets them the same way, by being redrawn once they are
+ * in; a font change is refused instead of drawn short, so they are fetched first.
+ */
+async function loadScriptFacesFor(
+ doc: EditorDocument,
+ changes: FamilyChange[],
+): Promise<void> {
+ const lost = changes
+ .filter((change) => {
+ if (isDocumentFontId(change.family)) return false;
+ const covers = familyCoverage(doc, change.family);
+ return (
+ covers !== null &&
+ visibleCodePoints(change.text).some((cp) => !covers(cp))
+ );
+ })
+ .filter((change) => familyCommand(change).wouldLoseText(doc))
+ .map((change) => change.text)
+ .join("");
+ const scripts = scanScriptsOf(lost);
+ if (scripts.length > 0)
+ await loadScriptScanFaces(scripts).catch(() => undefined);
+}
+
+function faceSources(doc: EditorDocument | null): FaceSources {
+ const fontIds: string[] = [];
+ for (const page of doc?.loadedPages() ?? []) {
+ for (const run of page.runs) {
+ fontIds.push(run.fontId);
+ if (run.documentFont) fontIds.push(run.documentFont.fontId);
+ }
+ }
+ return {
+ documentFamilies: knownDocumentFamilies(fontIds),
+ externalFonts: loadedExternalFonts(),
+ };
+}
+
+/**
+ * The family the font list offers `family` as, standing for it by its regular
+ * face; null for a face named outright. A pick of it takes each run to the
+ * face nearest its own weight and slant.
+ */
+function listedFamily(
+ doc: EditorDocument | null,
+ family: string,
+): FontFamilyEntry | null {
+ const owner = familyOfFace(family, faceSources(doc));
+ return owner?.value === family ? owner : null;
+}
+
+/** The warning a font or style change owes the user, or null when it changed everything as asked. */
+function changeFailure(
+ outcome: FamilyChangeOutcome,
+ leftAsIs: number,
+): FontPickFailure | null {
+ if (outcome.unshapeable > 0) return "needsShaping";
+ if (leftAsIs > 0)
+ return outcome.applied > 0 ? "styleSkipped" : "styleUnavailable";
+ return outcome.inClosestMatch > 0 ? "closestMatch" : null;
}
function liveRuns(store: EditorStore): Map<string, TextRun> {
@@ -86,33 +261,71 @@ function liveRuns(store: EditorStore): Map<string, TextRun> {
return runs;
}
+/** The width a change to part of a run rewraps its lines at, as typing in it would. */
+function rewrapWidth(store: EditorStore, part: SelectedPart): number {
+ const { run, page } = part;
+ if (store.getState().widthMode === "wrap")
+ return run.wrapWidthPt ?? run.bounds.width;
+ return page.display.cropLeft + page.display.cropWidth - run.bounds.x;
+}
+
+/** What to tell the user when the selected characters cannot be restyled apart from the rest of their run; undefined when they can. */
+function refusalFailure(
+ store: EditorStore,
+ refusal: RangeRefusal | null,
+): FontPickFailure | null | undefined {
+ if (refusal === "rightToLeft") {
+ store.setError(unsafeRtlEditMessage());
+ return null;
+ }
+ if (refusal === "needsShaping") return "needsShaping";
+ if (refusal === "unsupported") return "partOfRunUnsupported";
+ return undefined;
+}
+
+function refusePart(
+ store: EditorStore,
+ part: SelectedPart,
+): FontPickFailure | null | undefined {
+ if (part.run.locked) return null;
+ const doc = store.document;
+ return refusalFailure(
+ store,
+ doc && rangeRefusal(doc, part.page, part.run, part.range),
+ );
+}
+
/** Bundle of callbacks that operate on the current selection. */
export function useSelectionActions(store: EditorStore) {
const { busy: fittingScan, dispatch: dispatchAfterScanFit } =
useDispatchAfterScanFit(store);
- const forEachSelectedRun = useCallback(
- (visit: (run: SelectedRun, page: Page) => void) => {
+ const forEachSelectedRun = useCallback<VisitSelectedRuns>(
+ (visit, redraws = false) => {
const sel = store.selection.value;
const doc = store.document;
if (!doc || sel.runIds.length === 0) return;
// Pre-index the selection for O(1) membership in the nested walk.
const selIds = new Set(sel.runIds);
+ let refused = false;
for (const page of doc.loadedPages()) {
for (const run of page.runs) {
// Locked runs are selectable but must not mutate.
- if (selIds.has(run.id) && !run.locked) visit(run, page);
+ if (!selIds.has(run.id) || run.locked) continue;
+ if (redraws && run.textReadOnly) refused = true;
+ else visit(run, page);
}
}
+ if (refused) store.setError(unsafeRtlEditMessage());
},
[store],
);
const dispatchPerRun = useCallback(
- (build: (run: SelectedRun) => Command | null) => {
+ (build: (run: SelectedRun) => Command | null, redraws = false) => {
const targets: ScanFitTarget[] = [];
forEachSelectedRun((run, page) => {
targets.push({ page, run: run as TextRun });
- });
+ }, redraws);
return dispatchAfterScanFit(targets, () => {
const live = liveRuns(store);
return targets.flatMap(({ run: target }) => {
@@ -134,6 +347,7 @@ export function useSelectionActions(store: EditorStore) {
runId: run.id,
nextSize: size,
}),
+ true,
);
},
[dispatchPerRun],
@@ -168,111 +382,369 @@ export function useSelectionActions(store: EditorStore) {
stroke: stroke ? { ...stroke, a: 255 } : null,
width,
}),
+ true,
);
},
[dispatchPerRun],
);
+ const fontRequests = useRef({
+ last: 0,
+ latestByRun: new Map<string, number>(),
+ });
+ const claimFontChange = useCallback(
+ (runs: SelectedRun[]) => {
+ const requests = fontRequests.current;
+ const request = ++requests.last;
+ const doc = store.document;
+ const claimed = new Map(runs.map((run) => [run.id, run]));
+ for (const run of runs) requests.latestByRun.set(run.id, request);
+ return () => {
+ // Run ids repeat across documents, so a change outliving its document would hit unrelated text.
+ if (!doc || store.document !== doc) return () => false;
+ // Regrouping rebuilds the runs under the same ids, so only the run object that was picked still means the same text.
+ const editable = new Set<string>();
+ for (const page of doc.loadedPages()) {
+ for (const run of page.runs)
+ if (!run.locked && claimed.get(run.id) === run)
+ editable.add(run.id);
+ }
+ return (runId: string) =>
+ editable.has(runId) && requests.latestByRun.get(runId) === request;
+ };
+ },
+ [store],
+ );
+
const dispatchFamilyChanges = useCallback(
async (
- doc: EditorDocument | null,
+ stillApplies: () => (runId: string) => boolean,
changes: FamilyChange[],
fit: ScanFitTarget[],
- ) => {
- if (store.document !== doc) return;
- await dispatchAfterScanFit(fit, () => {
- const live = liveRuns(store);
- return changes
- .filter((change) => {
- const run = live.get(change.runId);
- return !!run && !run.locked;
- })
- .map(
- (change) =>
- new SetFontFamilyCommand({
- pageIndex: change.pageIndex,
- runId: change.runId,
- nextFamily: change.family,
- }),
+ ): Promise<FamilyChangeOutcome> => {
+ const doc = store.document;
+ const shapeable = changes.filter((change) => !needsShaping(change.text));
+ // Run by run: one with none of its letters in the family would be named after a font it is not drawn in, so it stays as it is.
+ const drawable = shapeable.filter(
+ (change) =>
+ isDocumentFontId(change.family) ||
+ drawsSomeOf(familyCoverage(doc, change.family), change.text),
+ );
+ const changing = new Set(drawable.map((change) => change.runId));
+ const outcome = {
+ applied: 0,
+ undrawable: shapeable.length - drawable.length,
+ wouldLoseText: 0,
+ notRestored: 0,
+ unshapeable: changes.length - shapeable.length,
+ inClosestMatch: 0,
+ };
+ if (doc) await loadScriptFacesFor(doc, drawable);
+ if (store.document !== doc) return outcome;
+ await dispatchAfterScanFit(
+ fit.filter((target) => changing.has(target.run.id)),
+ () => {
+ // A font picked for a run while these bytes loaded wins; applying this one now would undo it.
+ const applies = stillApplies();
+ const open = store.document;
+ const commands = drawable
+ .filter((change) => applies(change.runId))
+ .map(familyCommand)
+ .map((command) => ({
+ command,
+ coverage: open ? command.coverage(open) : "all",
+ }));
+ const reachable = commands.filter((c) => c.coverage !== "none");
+ const refusals = reachable.map(({ command }) =>
+ open ? command.refusal(open) : null,
);
- });
+ const safe = reachable.filter((_, i) => refusals[i] === null);
+ outcome.undrawable += commands.length - reachable.length;
+ outcome.applied = safe.length;
+ outcome.wouldLoseText = refusals.filter(
+ (r) => r === "losesText",
+ ).length;
+ outcome.notRestored = refusals.filter(
+ (r) => r === "notRestored",
+ ).length;
+ outcome.inClosestMatch = safe.filter(
+ (c) => c.coverage === "some",
+ ).length;
+ return safe.map(({ command }) => command);
+ },
+ );
+ return outcome;
},
[store, dispatchAfterScanFit],
);
+ const restyleSelectedPart = useCallback(
+ async (
+ part: SelectedPart,
+ faceFor: (
+ fontIds: string[],
+ ) => (fontId: string) => string | null | undefined,
+ fallbackFace?: string,
+ ): Promise<FontPickFailure | null> => {
+ const doc = store.document;
+ if (!doc) return null;
+ const refused = refusePart(store, part);
+ if (refused !== undefined) return refused;
+ const stretches = selectedFontStretches(
+ doc,
+ part.page,
+ part.run,
+ part.range,
+ );
+ if (stretches.length === 0) return null;
+ const face = faceFor([...new Set(stretches.map((s) => s.fontId))]);
+ let leftAsIs = 0;
+ const faces: FaceStretch[] = [];
+ for (const stretch of stretches) {
+ const next = face(stretch.fontId);
+ if (next === undefined) continue;
+ if (next === null) leftAsIs++;
+ else faces.push({ start: stretch.start, end: stretch.end, face: next });
+ }
+ const ready = new Map<string, string | null>();
+ for (const { face: wanted } of faces) {
+ if (ready.has(wanted)) continue;
+ if (!isDeviceFace(wanted)) {
+ ready.set(wanted, wanted);
+ continue;
+ }
+ const embedded = await embedDeviceFace(store, doc, wanted);
+ if (embedded === null) return null;
+ ready.set(wanted, embedded ? wanted : (fallbackFace ?? null));
+ }
+ const usable = faces.flatMap((stretch) => {
+ const drawn = ready.get(stretch.face);
+ if (!drawn) leftAsIs++;
+ return drawn ? [{ ...stretch, face: drawn }] : [];
+ });
+ // The run may have been edited or regrouped while fonts loaded.
+ if (part.page.findRun(part.run.id) !== part.run) return null;
+ if (usable.length === 0) return leftAsIs > 0 ? "styleUnavailable" : null;
+ const command = new StyleTextRangeCommand({
+ pageIndex: part.page.index,
+ runId: part.run.id,
+ faces: usable,
+ wrapWidthPt: rewrapWidth(store, part),
+ });
+ const commandRefused = refusalFailure(store, command.refusal(doc));
+ if (commandRefused !== undefined) return commandRefused;
+ const coverage = command.coverage(doc);
+ if (coverage === "unchanged")
+ return leftAsIs > 0 ? "styleUnavailable" : null;
+ if (coverage === "none")
+ return leftAsIs > 0 ? "styleUnavailable" : "noGlyphs";
+ store.dispatch(command);
+ if (leftAsIs > 0) return "styleSkipped";
+ return coverage === "some" ? "closestMatch" : null;
+ },
+ [store],
+ );
+
const changeFontFamily = useCallback(
async (family: string): Promise<FontPickFailure | null> => {
const doc = store.document;
+ const part = selectedPartOfRun(doc, store.selection.value);
+ if (part) {
+ const refused = refusePart(store, part);
+ if (refused !== undefined) return refused;
+ const text = part.run.text.slice(part.range.start, part.range.end);
+ if (!isDocumentFontId(family)) {
+ const failure = await prepareFamily(store, doc, family, [text]);
+ if (failure) return failure;
+ if (store.document !== doc) return null;
+ }
+ const picked = listedFamily(doc, family);
+ return restyleSelectedPart(
+ part,
+ () => (fontId) =>
+ picked ? faceKeepingStyle(picked, faceStyleOf(fontId)) : family,
+ family,
+ );
+ }
const targets: SelectedRun[] = [];
const fit: ScanFitTarget[] = [];
forEachSelectedRun((run, page) => {
targets.push(run);
fit.push({ page, run: run as TextRun });
- });
+ }, true);
+ const stillApplies = claimFontChange(targets);
+ const picked = listedFamily(doc, family);
const changes = targets.map((run) => ({
pageIndex: run.pageIndex,
runId: run.id,
- family,
+ family:
+ picked && !isScanRun(run)
+ ? faceKeepingStyle(picked, faceStyleOf(run.fontId))
+ : family,
+ text: run.text,
}));
- // Embedding is async and Command.apply is not, so warm the bytes first.
- // A no-op for the built-in families.
- const failure = await fontPickFailure(
- family,
- targets.map((run) => run.text).join(""),
- );
- if (failure) return failure;
- if (store.document !== doc) return null;
- // Refuse here, as the command would fall back to a standard face the user never picked.
if (
- doc &&
- nearestStandardFont(family) !== family &&
- !tryEmbedDeviceFont(doc, family)
+ changes.length > 0 &&
+ changes.every((change) => needsShaping(change.text))
)
- return "embedFailed";
- await dispatchFamilyChanges(doc, changes, fit);
- return null;
+ return "needsShaping";
+ if (!isDocumentFontId(family)) {
+ const failure = await prepareFamily(
+ store,
+ doc,
+ family,
+ changes.map((change) => change.text),
+ );
+ if (failure) return failure;
+ if (store.document !== doc) return null;
+ const styled = new Set(
+ changes
+ .map((c) => c.family)
+ .filter((f) => f !== family && !isDocumentFontId(f)),
+ );
+ for (const face of styled) {
+ const texts = changes
+ .filter((c) => c.family === face)
+ .map((c) => c.text);
+ // A styled cut that will not load is not worth refusing the family the user picked.
+ if (await prepareFamily(store, doc, face, texts)) {
+ for (const change of changes)
+ if (change.family === face) change.family = family;
+ }
+ if (store.document !== doc) return null;
+ }
+ }
+ // A run whose letters the styled cut lacks may still have them in the family that was picked.
+ for (const change of changes) {
+ if (
+ change.family !== family &&
+ !drawsSomeOf(familyCoverage(doc, change.family), change.text)
+ )
+ change.family = family;
+ }
+ const unchanged = new Set(
+ targets
+ .filter((run, i) => changes[i].family === run.fontId)
+ .map((run) => run.id),
+ );
+ const outcome = await dispatchFamilyChanges(
+ stillApplies,
+ changes.filter((change) => !unchanged.has(change.runId)),
+ fit,
+ );
+ const { applied, undrawable, wouldLoseText, notRestored, unshapeable } =
+ outcome;
+ if (unshapeable > 0) return "needsShaping";
+ if (undrawable + wouldLoseText + notRestored === 0)
+ return outcome.inClosestMatch > 0 ? "closestMatch" : null;
+ if (applied > 0) return "someLeftUnchanged";
+ if (notRestored > 0) return "documentFontCannotDraw";
+ return wouldLoseText > 0 ? "missingGlyphs" : "noGlyphs";
},
- [store, forEachSelectedRun, dispatchFamilyChanges],
+ [
+ store,
+ forEachSelectedRun,
+ claimFontChange,
+ dispatchFamilyChanges,
+ restyleSelectedPart,
+ ],
);
- const toggleItalic = useCallback(async () => {
- const doc = store.document;
- const fonts = loadedExternalFonts();
- const targets: Array<
- FamilyChange & { device: boolean; fit: ScanFitTarget }
- > = [];
- forEachSelectedRun((run, page) => {
- const cap = italicCapability(
- run.fontId,
- !isItalicFamily(run.fontId),
- fonts,
+ const restyle = useCallback(
+ async (
+ request: (styles: FaceStyle[]) => StyleRequest,
+ ): Promise<FontPickFailure | null> => {
+ const doc = store.document;
+ const sources = faceSources(doc);
+ const part = selectedPartOfRun(doc, store.selection.value);
+ if (part)
+ return restyleSelectedPart(part, (fontIds) => {
+ const wanted = request(fontIds.map(faceStyleOf));
+ return (fontId) => restyledFace(fontId, wanted, sources);
+ });
+ const runs: Array<{ run: SelectedRun; fit: ScanFitTarget }> = [];
+ forEachSelectedRun((run, page) => {
+ runs.push({ run, fit: { page, run: run as TextRun } });
+ }, true);
+ if (!doc || runs.length === 0) return null;
+ const wanted = request(runs.map(({ run }) => faceStyleOf(run.fontId)));
+ let leftAsIs = 0;
+ const targets: Array<FamilyChange & { fit: ScanFitTarget }> = [];
+ for (const { run, fit } of runs) {
+ const face = restyledFace(run.fontId, wanted, sources);
+ if (face === undefined) continue;
+ // No real face in that style. Leave it alone: swapping the document's
+ // own font for Helvetica-Oblique is not making it italic.
+ if (face === null) {
+ leftAsIs++;
+ continue;
+ }
+ targets.push({
+ pageIndex: run.pageIndex,
+ runId: run.id,
+ family: face,
+ text: run.text,
+ fit,
+ });
+ }
+ const stillApplies = claimFontChange(
+ targets.map((target) => target.fit.run),
);
- // No real italic cut for this face. Leave it alone: swapping the
- // document's own font for Helvetica-Oblique is not making it italic.
- if (!cap.family) return;
- targets.push({
- pageIndex: run.pageIndex,
- runId: run.id,
- family: cap.family,
- device: cap.source === "device",
- fit: { page, run: run as TextRun },
- });
- });
- // Embedding is async and Command.apply is not, so warm the bytes first.
- const ready: Array<FamilyChange & { fit: ScanFitTarget }> = [];
- for (const target of targets) {
- if (target.device) {
- if (await prepareExternalFont(target.family)) continue;
- if (!doc || !tryEmbedDeviceFont(doc, target.family)) continue;
+ const ready: Array<FamilyChange & { fit: ScanFitTarget }> = [];
+ for (const target of targets) {
+ if (isDeviceFace(target.family)) {
+ const embedded = await embedDeviceFace(store, doc, target.family);
+ if (embedded === null) return null;
+ if (!embedded) {
+ leftAsIs++;
+ continue;
+ }
+ }
+ ready.push(target);
}
- ready.push(target);
- }
- await dispatchFamilyChanges(
- doc,
- ready,
- ready.map((target) => target.fit),
- );
- }, [store, forEachSelectedRun, dispatchFamilyChanges]);
+ const outcome = await dispatchFamilyChanges(
+ stillApplies,
+ ready,
+ ready.map((target) => target.fit),
+ );
+ return changeFailure(
+ outcome,
+ leftAsIs +
+ outcome.undrawable +
+ outcome.wouldLoseText +
+ outcome.notRestored,
+ );
+ },
+ [
+ store,
+ forEachSelectedRun,
+ claimFontChange,
+ dispatchFamilyChanges,
+ restyleSelectedPart,
+ ],
+ );
+
+ // A selection that is all one style toggles off; a mixed one goes all on.
+ const toggleBold = useCallback(
+ () =>
+ restyle((styles) => ({
+ bold: !styles.every((style) => isBoldWeight(style.weight)),
+ })),
+ [restyle],
+ );
+
+ const toggleItalic = useCallback(
+ () =>
+ restyle((styles) => ({
+ italic: !styles.every((style) => style.italic),
+ })),
+ [restyle],
+ );
+
+ const changeFontWeight = useCallback(
+ (weight: number) => restyle(() => ({ weight })),
+ [restyle],
+ );
const deleteSelection = useCallback(() => {
const sel = store.selection.value;
@@ -391,7 +863,9 @@ export function useSelectionActions(store: EditorStore) {
changeFill,
changeOutline,
changeFontFamily,
+ toggleBold,
toggleItalic,
+ changeFontWeight,
deleteSelection,
replaceSelectedImage,
replaceImageById,
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/hooks/useSelectionGeometry.test.tsx b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useSelectionGeometry.test.tsx
new file mode 100644
index 0000000000..7798824f52
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useSelectionGeometry.test.tsx
@@ -0,0 +1,111 @@
+import { describe, it, expect, vi } from "vitest";
+import { renderHook } from "@testing-library/react";
+import { useSelectionGeometry } from "@editor/tools/pdfTextEditor/hooks/useSelectionGeometry";
+import type {
+ EditorStore,
+ EditorViewState,
+} from "@editor/tools/pdfTextEditor/store/EditorStore";
+import type {
+ PageRect,
+ SelectionState,
+} from "@editor/tools/pdfTextEditor/types";
+
+function viewWith(run: PageRect, image: PageRect): EditorViewState {
+ return {
+ pages: [
+ {
+ pageIndex: 0,
+ runs: [{ id: "r1", bounds: run }],
+ images: [{ id: "i1", bounds: image }],
+ },
+ ],
+ } as unknown as EditorViewState;
+}
+
+function selected(ids: Partial<SelectionState>): SelectionState {
+ return {
+ runIds: [],
+ imageIds: [],
+ shapeIds: [],
+ caret: null,
+ textRange: null,
+ formFieldId: null,
+ ...ids,
+ };
+}
+
+const rect = (x: number, y: number): PageRect => ({
+ x,
+ y,
+ width: 50,
+ height: 10,
+});
+
+function geometryOverStaleSnapshot(selection: SelectionState) {
+ const stale = viewWith(rect(0, 0), rect(0, 0));
+ const live = viewWith(rect(10, 5), { x: 10, y: 5, width: 80, height: 40 });
+ const dispatch = vi.fn();
+ const store = {
+ getState: () => live,
+ dispatch,
+ } as unknown as EditorStore;
+ const { result } = renderHook(() =>
+ useSelectionGeometry(store, stale, selection),
+ );
+ return { single: result.current.single!, dispatch };
+}
+
+describe("useSelectionGeometry setters", () => {
+ it("move a text run from where it is now, not where the panel last drew it", () => {
+ const { single, dispatch } = geometryOverStaleSnapshot(
+ selected({ runIds: ["r1"] }),
+ );
+ single.setX(20);
+ single.setY(20);
+ expect(dispatch.mock.calls[0][0]).toMatchObject({ dx: 10, dy: 0 });
+ expect(dispatch.mock.calls[1][0]).toMatchObject({ dx: 0, dy: 15 });
+ });
+
+ it("keep an image's other edges where they are now", () => {
+ const { single, dispatch } = geometryOverStaleSnapshot(
+ selected({ imageIds: ["i1"] }),
+ );
+ single.setX(20);
+ expect(dispatch.mock.calls[0][0]).toMatchObject({
+ nextBounds: { x: 20, y: 5, width: 80, height: 40 },
+ });
+ });
+});
+
+describe("useSelectionGeometry width", () => {
+ const UPRIGHT = { a: 1, b: 0, c: 0, d: 1, e: 0, f: 0 };
+ const TURNED = { a: 0, b: 1, c: -1, d: 0, e: 0, f: 0 };
+
+ function widthFor(run: Record<string, unknown>) {
+ const state = {
+ pages: [
+ {
+ pageIndex: 0,
+ runs: [{ id: "r1", bounds: rect(0, 0), matrix: UPRIGHT, ...run }],
+ images: [],
+ },
+ ],
+ } as unknown as EditorViewState;
+ const store = { getState: () => state } as unknown as EditorStore;
+ const { result } = renderHook(() =>
+ useSelectionGeometry(store, state, selected({ runIds: ["r1"] })),
+ );
+ return result.current.single!.setWidth;
+ }
+
+ it("is editable for upright scanned text as for plain text", () => {
+ expect(widthFor({})).toBeTypeOf("function");
+ expect(widthFor({ renderMode: 3 })).toBeTypeOf("function");
+ });
+
+ it("stays off for read-only text and turned scanned text", () => {
+ expect(widthFor({ textReadOnly: true })).toBeUndefined();
+ expect(widthFor({ renderMode: 3, textReadOnly: true })).toBeUndefined();
+ expect(widthFor({ renderMode: 3, matrix: TURNED })).toBeUndefined();
+ });
+});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/hooks/useSelectionGeometry.ts b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useSelectionGeometry.ts
index 0c5d238f9a..a0683a5bdf 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/hooks/useSelectionGeometry.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useSelectionGeometry.ts
@@ -1,11 +1,18 @@
import { useMemo } from "react";
import { MoveTextRunCommand } from "@editor/tools/pdfTextEditor/commands/MoveTextRunCommand";
-import { ReflowWrapCommand } from "@editor/tools/pdfTextEditor/commands/ReflowWrapCommand";
-import { isScanRun } from "@editor/tools/pdfTextEditor/commands/scanTextEdit";
+import {
+ canResizeRun,
+ resizeRunCommand,
+} from "@editor/tools/pdfTextEditor/commands/resizeRun";
import { SetImageTransformCommand } from "@editor/tools/pdfTextEditor/commands/SetImageTransformCommand";
+import {
+ imageBoundsForVisible,
+ visibleImageBounds,
+} from "@editor/tools/pdfTextEditor/util/imageClip";
import type { EditorStore } from "@editor/tools/pdfTextEditor/store/EditorStore";
import type { EditorViewState } from "@editor/tools/pdfTextEditor/store/EditorStore";
import type {
+ ImageObjectSnapshot,
PageRect,
SelectionState,
} from "@editor/tools/pdfTextEditor/types";
@@ -30,6 +37,31 @@ export interface SelectionGeometry {
* Only meaningful for a single object - the fields would have to invent a
* value for a mixed selection, so the panel shows a hint instead.
*/
+// The panel may draw a deferred snapshot, so setters read bounds from the store when they run.
+function liveRunBounds(
+ store: EditorStore,
+ runId: string,
+ fallback: PageRect,
+): PageRect {
+ for (const page of store.getState().pages) {
+ const run = page.runs.find((r) => r.id === runId);
+ if (run) return run.bounds;
+ }
+ return fallback;
+}
+
+function liveImage(
+ store: EditorStore,
+ imageId: string,
+ fallback: ImageObjectSnapshot,
+): ImageObjectSnapshot {
+ for (const page of store.getState().pages) {
+ const img = page.images.find((i) => i.id === imageId);
+ if (img) return img;
+ }
+ return fallback;
+}
+
export function useSelectionGeometry(
store: EditorStore,
state: EditorViewState,
@@ -60,7 +92,7 @@ export function useSelectionGeometry(
new MoveTextRunCommand({
pageIndex,
runId,
- dx: next - bounds.x,
+ dx: next - liveRunBounds(store, runId, bounds).x,
dy: 0,
}),
),
@@ -70,22 +102,19 @@ export function useSelectionGeometry(
pageIndex,
runId,
dx: 0,
- dy: next - bounds.y,
+ dy: next - liveRunBounds(store, runId, bounds).y,
}),
),
// Narrowing a run is exactly the wrap gesture, so it reuses the
// same command the canvas resize handle drives.
- setWidth: isScanRun(run)
- ? undefined
- : (next) =>
- store.dispatch(
- new ReflowWrapCommand({
- pageIndex,
- runId,
- maxWidthPt: Math.max(1, next),
- explicit: true,
- }),
- ),
+ setWidth: canResizeRun(run)
+ ? (next) => {
+ const doc = store.document;
+ const cmd =
+ doc && resizeRunCommand(doc, pageIndex, runId, next);
+ if (cmd) store.dispatch(cmd);
+ }
+ : undefined,
},
};
}
@@ -97,15 +126,20 @@ export function useSelectionGeometry(
const img = page.images.find((i) => i.id === imageId);
if (!img) continue;
const pageIndex = page.pageIndex;
- const bounds = img.bounds;
- const set = (patch: Partial<PageRect>) =>
+ const bounds = visibleImageBounds(img);
+ const set = (patch: Partial<PageRect>) => {
+ const live = liveImage(store, imageId, img);
store.dispatch(
new SetImageTransformCommand({
pageIndex,
imageId,
- nextBounds: { ...bounds, ...patch },
+ nextBounds: imageBoundsForVisible(live, {
+ ...visibleImageBounds(live),
+ ...patch,
+ }),
}),
);
+ };
return {
single: {
bounds,
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/hooks/useToolbarController.ts b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useToolbarController.ts
index 3d433ccdc1..43eddcecb0 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/hooks/useToolbarController.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useToolbarController.ts
@@ -19,6 +19,10 @@ import {
subscribeScanFaces,
} from "@editor/tools/pdfTextEditor/util/scanFontLibrary";
import { deriveToolbarState } from "@editor/tools/pdfTextEditor/util/toolbarState";
+import {
+ rangeFontIds,
+ selectedPartOfRun,
+} from "@editor/tools/pdfTextEditor/commands/StyleTextRangeCommand";
import { useDocumentFontCompletion } from "@editor/tools/pdfTextEditor/hooks/useDocumentFontCompletion";
import {
loadedExternalFonts,
@@ -58,12 +62,38 @@ type AlignMode = "left" | "center-h" | "right" | "top" | "middle-v" | "bottom";
// Everything the contextual `Toolbar` needs, derived from the shared
// `EditorStore`.
+const CAN_UNDO = 1;
+const CAN_REDO = 2;
+
+// Read from the store, not the deferred state the bars render: a stale enabled redo gets clicked past the end of history.
+function useHistoryFlags(store: EditorStore): {
+ canUndo: boolean;
+ canRedo: boolean;
+} {
+ const subscribe = useCallback(
+ (onChange: () => void) => store.subscribe(onChange),
+ [store],
+ );
+ const read = useCallback(
+ () =>
+ (store.history.canUndo ? CAN_UNDO : 0) |
+ (store.history.canRedo ? CAN_REDO : 0),
+ [store],
+ );
+ const flags = useSyncExternalStore(subscribe, read, read);
+ return {
+ canUndo: (flags & CAN_UNDO) !== 0,
+ canRedo: (flags & CAN_REDO) !== 0,
+ };
+}
+
export function useToolbarController(
store: EditorStore,
state: EditorViewState,
selection: SelectionState,
) {
const sel = useSelectionActions(store);
+ const history = useHistoryFlags(store);
const imageA11y = useImageAccessibility(store, state, selection);
const textA11y = useTextAccessibility(store, state, selection);
const formFieldA11y = useFormFieldAccessibility(store, state, selection);
@@ -394,7 +424,7 @@ export function useToolbarController(
const cmds: EditTextCommand[] = [];
for (const p of doc.loadedPages()) {
for (const r of p.runs) {
- if (!selIds.has(r.id) || r.locked) continue;
+ if (!selIds.has(r.id) || r.locked || r.textReadOnly) continue;
const next = transform(r.text);
if (next === r.text) continue;
cmds.push(
@@ -426,9 +456,24 @@ export function useToolbarController(
useDocumentFontCompletion(store, state, selection, externalFonts);
+ // state.pages is unread but changes whenever a restyle redraws the selected characters.
+ const selectedFontIds = useMemo(() => {
+ const doc = store.document;
+ const part = selectedPartOfRun(doc, selection);
+ return doc && part
+ ? rangeFontIds(doc, part.page, part.run, part.range)
+ : null;
+ }, [store, selection, state.pages]);
+
const toolbarState = useMemo(
- () => deriveToolbarState(state.pages, selection, externalFonts),
- [state.pages, selection, externalFonts],
+ () =>
+ deriveToolbarState(
+ state.pages,
+ selection,
+ externalFonts,
+ selectedFontIds,
+ ),
+ [state.pages, selection, externalFonts, selectedFontIds],
);
const scanFacesVersion = useSyncExternalStore(
@@ -473,7 +518,15 @@ export function useToolbarController(
.find((r) => r.id === selection.runIds[0]);
// Mirrors AlignParagraphLinesCommand.canAlign, which gates on SLOTS: line
// count enabled the item for paragraphs the command then refused.
- return !!run && (run.paragraphSlotCount ?? 0) >= 2;
+ return !!run && (run.paragraphSlotCount ?? 0) >= 2 && !run.textReadOnly;
+ }, [state.pages, selection]);
+
+ const selectionTextReadOnly = useMemo(() => {
+ const ids = new Set(selection.runIds);
+ const runs = state.pages
+ .flatMap((p) => p.runs)
+ .filter((r) => ids.has(r.id));
+ return runs.length > 0 && runs.every((r) => r.textReadOnly);
}, [state.pages, selection]);
const onReplaceImage = useCallback(() => {
@@ -529,15 +582,17 @@ export function useToolbarController(
return {
state: toolbarState,
scanFont,
- canUndo: store.history.canUndo,
- canRedo: store.history.canRedo,
+ canUndo: history.canUndo,
+ canRedo: history.canRedo,
onUndo: () => store.undo(),
onRedo: () => store.redo(),
onChangeFontSize: sel.changeFontSize,
onChangeFill: sel.changeFill,
onChangeOutline: sel.changeOutline,
onChangeFontFamily: sel.changeFontFamily,
+ onToggleBold: sel.toggleBold,
onToggleItalic: sel.toggleItalic,
+ onChangeFontWeight: sel.changeFontWeight,
onDelete: sel.deleteSelection,
onToggleLock,
onChangeCase,
@@ -563,7 +618,9 @@ export function useToolbarController(
onTagFormField: formFieldA11y.tag,
onSetFormFieldDescription: formFieldA11y.setDescription,
selectionAllLocked,
+ selectionTextReadOnly,
hasRunSelection: selection.runIds.length > 0,
+ selectedRunIds: selection.runIds,
hasImageSelection: selection.imageIds.length > 0,
selectionCount:
selection.runIds.length +
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/hooks/useUnsavedChangesGuard.test.tsx b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useUnsavedChangesGuard.test.tsx
new file mode 100644
index 0000000000..1d432f2aef
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useUnsavedChangesGuard.test.tsx
@@ -0,0 +1,94 @@
+import { useState } from "react";
+import { flushSync } from "react-dom";
+import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
+import { render, act } from "@testing-library/react";
+
+vi.mock("@editor/contexts/ToolRegistryContext", () => ({
+ useToolRegistry: () => ({ allTools: {} }),
+}));
+
+import {
+ NavigationProvider,
+ useNavigation,
+} from "@editor/contexts/NavigationContext";
+import { useUnsavedChangesGuard } from "@editor/tools/pdfTextEditor/hooks/useUnsavedChangesGuard";
+
+let navigation: ReturnType<typeof useNavigation>;
+let setDirty: (dirty: boolean) => void;
+let liveDirty = false;
+const readDirty = () => liveDirty;
+
+function Editor() {
+ const [dirty, set] = useState(false);
+ setDirty = (next) => {
+ liveDirty = next;
+ set(next);
+ };
+ useUnsavedChangesGuard(dirty, readDirty);
+ return null;
+}
+
+let closeEditor: () => void;
+
+function Workbench() {
+ const [open, setOpen] = useState(true);
+ closeEditor = () => setOpen(false);
+ navigation = useNavigation();
+ return open ? <Editor /> : null;
+}
+
+function renderEditor() {
+ return render(
+ <NavigationProvider>
+ <Workbench />
+ </NavigationProvider>,
+ );
+}
+
+beforeEach(() => {
+ liveDirty = false;
+ vi.spyOn(console, "log").mockImplementation(() => {});
+});
+afterEach(() => vi.restoreAllMocks());
+
+describe("useUnsavedChangesGuard", () => {
+ it("holds navigation back while the deferred dirty flag is still pending", async () => {
+ renderEditor();
+ const leave = vi.fn();
+ await act(async () => {
+ flushSync(() => setDirty(true));
+ expect(navigation.hasUnsavedChanges).toBe(false);
+ navigation.requestNavigation(leave);
+ });
+ expect(leave).not.toHaveBeenCalled();
+ expect(navigation.pendingNavigation).toBe(leave);
+ });
+
+ it("lets navigation through once the edits are gone", () => {
+ renderEditor();
+ act(() => setDirty(true));
+ act(() => setDirty(false));
+ const leave = vi.fn();
+ act(() => navigation.requestNavigation(leave));
+ expect(leave).toHaveBeenCalledTimes(1);
+ });
+
+ it("lets navigation through once the user discards the edits", () => {
+ renderEditor();
+ act(() => setDirty(true));
+ expect(navigation.hasUnsavedChanges).toBe(true);
+ act(() => navigation.setHasUnsavedChanges(false));
+ const leave = vi.fn();
+ act(() => navigation.requestNavigation(leave));
+ expect(leave).toHaveBeenCalledTimes(1);
+ });
+
+ it("stops holding navigation back once the editor closes", () => {
+ renderEditor();
+ act(() => setDirty(true));
+ act(() => closeEditor());
+ const leave = vi.fn();
+ act(() => navigation.requestNavigation(leave));
+ expect(leave).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/hooks/useUnsavedChangesGuard.ts b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useUnsavedChangesGuard.ts
index 2164110658..23a5a76f0c 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/hooks/useUnsavedChangesGuard.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/hooks/useUnsavedChangesGuard.ts
@@ -1,5 +1,8 @@
-import { useEffect } from "react";
-import { useNavigationActions } from "@editor/contexts/NavigationContext";
+import { startTransition, useEffect, useLayoutEffect, useRef } from "react";
+import {
+ useNavigationActions,
+ useNavigationState,
+} from "@editor/contexts/NavigationContext";
// Guard unsaved edits on BOTH exit routes.
//
@@ -8,9 +11,24 @@ import { useNavigationActions } from "@editor/contexts/NavigationContext";
// this hook let the editor drop every edit silently. NavigationContext is the
// app's own in-app guard - it is what PageEditor uses - and it drives
// NavigationWarningModal.
-export function useUnsavedChangesGuard(dirty: boolean): void {
+/** `isDirty` must read the live state: navigation calls it while the `dirty` flag may still be pending. */
+export function useUnsavedChangesGuard(
+ dirty: boolean,
+ isDirty: () => boolean,
+): void {
const { actions } = useNavigationActions();
- const setHasUnsavedChanges = actions.setHasUnsavedChanges;
+ const {
+ setHasUnsavedChanges,
+ registerUnsavedChangesChecker,
+ unregisterUnsavedChangesChecker,
+ } = actions;
+ const { hasUnsavedChanges } = useNavigationState();
+ const flagCaughtUpRef = useRef(false);
+
+ useLayoutEffect(() => {
+ if (!dirty) flagCaughtUpRef.current = false;
+ else if (hasUnsavedChanges) flagCaughtUpRef.current = true;
+ }, [dirty, hasUnsavedChanges]);
useEffect(() => {
if (!dirty) return;
@@ -23,7 +41,14 @@ export function useUnsavedChangesGuard(dirty: boolean): void {
}, [dirty]);
useEffect(() => {
- setHasUnsavedChanges(dirty);
+ // Only covers the pending flag: once it has landed, a discard clears it while the store stays dirty.
+ registerUnsavedChangesChecker(() => isDirty() && !flagCaughtUpRef.current);
+ return () => unregisterUnsavedChangesChecker();
+ }, [isDirty, registerUnsavedChangesChecker, unregisterUnsavedChangesChecker]);
+
+ useEffect(() => {
+ // The flag re-renders most of the app; urgent, it holds the first typed letter off screen.
+ startTransition(() => setHasUnsavedChanges(dirty));
// Clear on unmount so a stale flag cannot block navigation after the
// editor is gone.
return () => setHasUnsavedChanges(false);
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/model/EditorDocument.ts b/frontend/src/editor/core/tools/pdfTextEditor/model/EditorDocument.ts
index 741df9f52c..365ce485ed 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/model/EditorDocument.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/model/EditorDocument.ts
@@ -5,6 +5,7 @@ import {
openRawDocument,
} from "@editor/services/pdfiumService";
import { Page } from "@editor/tools/pdfTextEditor/model/Page";
+import { documentClosed } from "@editor/tools/pdfTextEditor/pdfium/pointerCaches";
import {
PageStructure,
givenMcids,
@@ -35,9 +36,13 @@ import {
readFileArtifactKinds,
refreshArtifactTags,
} from "@editor/tools/pdfTextEditor/model/fileArtifactKinds";
+import {
+ formLiftHazards,
+ type FormNode,
+} from "@editor/tools/pdfTextEditor/pdfdoc/formLocalResources";
import { RawPdf } from "@editor/tools/pdfTextEditor/pdfdoc/raw";
import {
- readFileStructure,
+ fileStructureOf,
type FileStructure,
} from "@editor/tools/pdfTextEditor/pdfdoc/readFileStructure";
import {
@@ -95,6 +100,8 @@ export class EditorDocument {
private documentLangEdit: string | null | undefined;
/** The file's own structure tree; null when only PDFium's view is available. */
private readonly fileStructure: FileStructure | null;
+ /** See formLiftHazards; null when the file was not kept, so they are unknown. */
+ private readonly formHazards: Map<number, FormNode[]> | null;
private marked: boolean;
private readonly ownedFonts: Map<string, FontRef>;
private readonly _embeddedFontFiles: Uint8Array[] = [];
@@ -128,8 +135,10 @@ export class EditorDocument {
docPtr: number,
openedBytes: Uint8Array,
fileStructure: FileStructure | null,
+ formHazards: Map<number, FormNode[]> | null,
) {
this.module = module;
+ this.formHazards = formHazards;
this.docPtr = docPtr;
this.openedBytes = openedBytes;
this.fileStructure = fileStructure;
@@ -151,9 +160,23 @@ export class EditorDocument {
// PDFium already holds its own heap copy, so retaining these doubles the
// footprint; past a point the gradient repair is not worth that.
const keep = prepared.length <= MAX_RETAINED_BYTES ? prepared : EMPTY;
- const fileStructure =
- keep.length > 0 ? await readFileStructure(keep).catch(() => null) : null;
- return new EditorDocument(module, docPtr, keep, fileStructure);
+ const raw =
+ keep.length > 0 ? await RawPdf.parse(keep).catch(() => null) : null;
+ const fileStructure = raw ? safely(() => fileStructureOf(raw)) : null;
+ const formHazards = raw
+ ? await formLiftHazards(raw).catch(() => null)
+ : null;
+ return new EditorDocument(module, docPtr, keep, fileStructure, formHazards);
+ }
+
+ /**
+ * The forms page `pageIndex` draws, in drawing order, when one of them
+ * would draw differently lifted onto the page (see formLiftHazards);
+ * "none" when none would, and "unknown" when the file was not kept.
+ */
+ formHazardsOn(pageIndex: number): FormNode[] | "none" | "unknown" {
+ if (!this.formHazards) return "unknown";
+ return this.formHazards.get(pageIndex) ?? "none";
}
/** Page indices whose content stream has been regenerated this session. */
@@ -837,6 +860,17 @@ export class EditorDocument {
return this.ownedFonts.get(id);
}
+ findOwnedFont(matches: (font: FontRef) => boolean): FontRef | undefined {
+ for (const font of this.ownedFonts.values()) if (matches(font)) return font;
+ return undefined;
+ }
+
+ ownedFontAt(pointer: number): FontRef | undefined {
+ for (const font of this.ownedFonts.values())
+ if (font.pointer === pointer) return font;
+ return undefined;
+ }
+
/** Iterate loaded pages without forcing more page loads. */
loadedPages(): Page[] {
return Array.from(this.pageCache.values());
@@ -848,6 +882,7 @@ export class EditorDocument {
this.module.FPDF_CreateNewDocument(),
EMPTY,
null,
+ new Map(),
);
return { doc: this.scratch, page: this.scratch.blankPageLike(page) };
}
@@ -924,6 +959,7 @@ export class EditorDocument {
forgetArtifactKinds(this.module, this);
closeDocAndFreeBuffer(this.module, this.docPtr);
releaseScratch(this.module);
+ documentClosed();
}
}
@@ -1071,3 +1107,11 @@ function anchorsFirst(edits: Map<number, StructureEdit>): StructureEdit[] {
}
return ordered;
}
+
+function safely<T>(read: () => T): T | null {
+ try {
+ return read();
+ } catch {
+ return null;
+ }
+}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/model/ImageObject.ts b/frontend/src/editor/core/tools/pdfTextEditor/model/ImageObject.ts
index 71b2ce0689..f412e5c325 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/model/ImageObject.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/model/ImageObject.ts
@@ -12,6 +12,7 @@ export class ImageObject {
containerPtr: number;
bounds: PageRect;
matrix: Affine;
+ clip: PageRect | null;
dirty: boolean;
/** Session-only lock; see TextRun.locked. */
locked: boolean;
@@ -35,6 +36,7 @@ export class ImageObject {
this.containerPtr = init.containerPtr ?? 0;
this.bounds = init.bounds;
this.matrix = init.matrix;
+ this.clip = init.clip ?? null;
this.dirty = false;
this.locked = init.locked ?? false;
this.mcid = init.mcid ?? null;
@@ -51,6 +53,7 @@ export class ImageObject {
mcid: this.mcid ?? undefined,
artifact: this.artifact || undefined,
inForm: this.containerPtr !== 0 || undefined,
+ clip: this.clip ? { ...this.clip } : undefined,
};
}
}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/model/Page.ts b/frontend/src/editor/core/tools/pdfTextEditor/model/Page.ts
index aee2a7e969..34583de4ac 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/model/Page.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/model/Page.ts
@@ -2,10 +2,18 @@ import { TextRun } from "@editor/tools/pdfTextEditor/model/TextRun";
import { ImageObject } from "@editor/tools/pdfTextEditor/model/ImageObject";
import type { ShapeObject } from "@editor/tools/pdfTextEditor/model/ShapeObject";
import { DisplayTransform } from "@editor/tools/pdfTextEditor/model/DisplayTransform";
+import { unionRect } from "@editor/tools/pdfTextEditor/model/affine";
import type { AnnotationBox } from "@editor/tools/pdfTextEditor/model/AnnotationBox";
import type { TableModel } from "@editor/tools/pdfTextEditor/model/TableModel";
import type { WrappedPdfiumModule } from "@embedpdf/pdfium";
-import type { PageRuleSnapshot } from "@editor/tools/pdfTextEditor/types";
+import type { FormNode } from "@editor/tools/pdfTextEditor/pdfdoc/formLocalResources";
+import type {
+ PageRect,
+ PageRuleSnapshot,
+} from "@editor/tools/pdfTextEditor/types";
+
+// A bitmap more bounded edits behind than this is drawn whole.
+const MAX_TRACKED_REPAINTS = 64;
/** Wraps one PDFium page pointer. */
export class Page {
@@ -19,12 +27,6 @@ export class Page {
runs: TextRun[];
images: ImageObject[];
shapes: ShapeObject[];
- /**
- * Deleted shapes still inside a form XObject (object ptr -> form ptr). They
- * are hidden for now and removed on save: removal is the only change to a
- * form's children that PDFium writes back, and it cannot be undone.
- */
- pendingFormRemovals: Map<number, number>;
/** Text-carrying annotations: rendered by the canvas, not editable. */
annotations: AnnotationBox[];
// Bounding boxes of the thin filled/stroked paths the page draws - table
@@ -49,6 +51,14 @@ export class Page {
// the save-time repair needs this long after `dirty` was cleared.
regenerated: boolean;
shownInViewer: boolean;
+ /**
+ * The file's form XObjects behind the form objects drawn by the page itself,
+ * by object; set as the page is first read, and filled only on a page
+ * drawing one that cannot be lifted faithfully (see claimFormNodes).
+ */
+ formNodes: Map<number, FormNode> | null = null;
+ // Consecutive bounded edits, oldest first: each changed nothing outside its area.
+ private repaints: Array<{ from: number; to: number; area: PageRect }> = [];
constructor(opts: {
index: number;
@@ -66,7 +76,6 @@ export class Page {
this.runs = [];
this.images = [];
this.shapes = [];
- this.pendingFormRemovals = new Map();
this.annotations = [];
this.tables = [];
this.dirty = false;
@@ -108,6 +117,24 @@ export class Page {
this.revision += 1;
}
+ /** Revisions `from` to `to` changed nothing outside raw-space `area`; any later unnoted revision voids it. */
+ noteRepaintArea(from: number, to: number, area: PageRect): void {
+ if (this.repaints.at(-1)?.to !== from) this.repaints = [];
+ this.repaints.push({ from, to, area: { ...area } });
+ if (this.repaints.length > MAX_TRACKED_REPAINTS) this.repaints.shift();
+ }
+
+ /** What to redraw over a bitmap painted at revision `painted`, or null to draw the whole page. */
+ repaintAreaSince(painted: number): PageRect | null {
+ if (this.repaints.at(-1)?.to !== this.revision) return null;
+ const first = this.repaints.findIndex((r) => r.to > painted);
+ if (first < 0 || this.repaints[first].from > painted) return null;
+ return this.repaints
+ .slice(first)
+ .map((r) => r.area)
+ .reduce(unionRect);
+ }
+
/** Bump the snapshot revision WITHOUT marking the page dirty. */
bumpRevision(): void {
this.revision += 1;
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/model/ShapeObject.ts b/frontend/src/editor/core/tools/pdfTextEditor/model/ShapeObject.ts
index 701e7d49ae..017c56acec 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/model/ShapeObject.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/model/ShapeObject.ts
@@ -1,5 +1,4 @@
import type {
- Affine,
PageRect,
ShapeObjectSnapshot,
} from "@editor/tools/pdfTextEditor/types";
@@ -11,26 +10,18 @@ export class ShapeObject {
pdfiumObjPtr: number;
/** Owning form XObject, or 0 when the shape sits on the page. */
containerPtr: number;
- /** The page-level form that holds the container, or 0 on the page. */
- topLevelContainerPtr: number;
- /** Maps the container's local space to page space; identity on the page. */
- containerTransform: Affine;
bounds: PageRect;
constructor(
init: Omit<ShapeObjectSnapshot, "movable"> & {
pdfiumObjPtr: number;
containerPtr: number;
- topLevelContainerPtr: number;
- containerTransform: Affine;
},
) {
this.id = init.id;
this.pageIndex = init.pageIndex;
this.pdfiumObjPtr = init.pdfiumObjPtr;
this.containerPtr = init.containerPtr;
- this.topLevelContainerPtr = init.topLevelContainerPtr;
- this.containerTransform = init.containerTransform;
this.bounds = init.bounds;
}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/model/TextRun.ts b/frontend/src/editor/core/tools/pdfTextEditor/model/TextRun.ts
index 99ce06046c..7806ad861a 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/model/TextRun.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/model/TextRun.ts
@@ -5,11 +5,12 @@ import {
innermostMcid,
type TagMark,
} from "@editor/tools/pdfTextEditor/pdfium/PdfiumTagMarks";
-import type {
- Affine,
- PageRect,
- RGBA,
- TextRunSnapshot,
+import {
+ RENDER_MODE_INVISIBLE,
+ type Affine,
+ type PageRect,
+ type RGBA,
+ type TextRunSnapshot,
} from "@editor/tools/pdfTextEditor/types";
/** One line's worth of sub-run data inside a paragraph. */
@@ -58,6 +59,7 @@ export class TextRun {
// PDF text render mode (Tr): 0 fill, 1/2 stroke variants, 3 invisible (OCR
// layers over scans), 4-7 clipping.
renderMode: number;
+ hiddenText: boolean;
// Glyph outline (PDF stroke state), carried even when the render mode hides
// it, so a re-emit cannot silently drop an outlined heading's outline.
stroke: RGBA | null;
@@ -105,19 +107,30 @@ export class TextRun {
// Pointer to the LATEST background cover-rect emitted on the page for this
// run.
coverRectPtr: number;
+ /** The document font this run had before a family change, so it can be restored; null if unchanged. */
+ documentFont: { fontId: string; subset: boolean } | null;
/** Word-level edit state once an invisible OCR run over a scan is edited. */
scanEdit: ScanEditState | null;
/** Per-line sub-run snapshots for paragraph-aware partial edits. */
paragraphLineSlots: ParagraphLineSlot[];
- // Which visual lines start at a break the WRAP put there rather than one the
- // user typed. run.text spells both as a newline - it has to, or the line
+ // Which visual lines start at a soft break: one a wrap put there, or one the
+ // document's producer wrapped at its margin, rather than a line the author or
+ // user ended. run.text spells both as a newline - it has to, or the line
// count the painter and the box height read disagrees with the ink on the
- // page - so the difference lives here. Without it a reflow re-reads its own
- // soft breaks as forced ones and the paragraph can never re-flow again.
+ // page - so the difference lives here. Without it a reflow re-reads soft
+ // breaks as forced ones and widening the box can never rejoin them.
paragraphSoftStarts: boolean[];
+ /** The text `paragraphSoftStarts` was indexed for; read them through `softStartsOf`, which maps them onto edits since. */
+ paragraphSoftStartsText: string;
// Session-only lock: when true the run is skipped by all hit-tests (mouse,
// marquee, Ctrl+A) and edit gestures are no-ops.
locked: boolean;
+ /**
+ * True when the reader could not tell the reading order this line was drawn
+ * from: redrawing it from `text` would move its numbers and words, so an
+ * edit of the text is refused.
+ */
+ readingOrderUnsure: boolean;
/**
* Width the user resized the box to, in PDF points, or null to follow the
* ink. Kept apart from `bounds`, which a reflow sets to the glyphs' extent:
@@ -125,6 +138,14 @@ export class TextRun {
*/
wrapWidthPt: number | null;
+ /** True when an edit of the text would be refused; invisible OCR text is redrawn from its scan, not from its reading order. */
+ get textReadOnly(): boolean {
+ return (
+ this.readingOrderUnsure &&
+ (this.renderMode !== RENDER_MODE_INVISIBLE || this.hiddenText)
+ );
+ }
+
constructor(
init: TextRunSnapshot & {
pdfiumObjPtr: number;
@@ -143,6 +164,7 @@ export class TextRun {
this.fill = init.fill;
this.fontSubset = init.fontSubset;
this.renderMode = init.renderMode ?? 0;
+ this.hiddenText = init.hiddenText ?? false;
this.stroke = init.stroke ?? null;
this.strokeWidth = init.strokeWidth ?? 0;
this.charStartsX = null;
@@ -165,9 +187,12 @@ export class TextRun {
this.paragraphLeafContainers = [];
this.paragraphLineSlots = [];
this.paragraphSoftStarts = [];
+ this.paragraphSoftStartsText = init.text;
this.coverRectPtr = 0;
this.scanEdit = null;
+ this.documentFont = null;
this.locked = init.locked ?? false;
+ this.readingOrderUnsure = false;
this.wrapWidthPt = init.wrapWidthPt ?? null;
}
@@ -197,7 +222,9 @@ export class TextRun {
this.scanEdit?.override.style?.family ??
this.scanEdit?.override.family ??
this.scanEdit?.block?.style.family,
+ documentFontId: this.documentFont?.fontId,
renderMode: this.renderMode || undefined,
+ hiddenText: this.hiddenText || undefined,
stroke: this.stroke ? { ...this.stroke } : undefined,
strokeWidth: this.strokeWidth || undefined,
charStartsX: this.positionsCurrent()
@@ -212,7 +239,9 @@ export class TextRun {
paragraphSlotCount: this.paragraphLineSlots.length || undefined,
paragraphBaselines: this.lineBaselines(),
paragraphLineLefts: this.lineLefts(),
+ paragraphLineRights: this.lineRights(),
locked: this.locked || undefined,
+ textReadOnly: this.textReadOnly || undefined,
wrapWidthPt: this.wrapWidthPt ?? undefined,
mcid: innermostMcid(this.tagMarks) ?? undefined,
artifact: artifactMark(this.tagMarks) !== undefined || undefined,
@@ -236,6 +265,18 @@ export class TextRun {
? this.paragraphLineSlots.map((s) => s.matrixE)
: undefined;
}
+
+ private lineRights(): number[] | undefined {
+ const slots = this.paragraphLineSlots;
+ if (
+ slots.length === 0 ||
+ slots.some((s) => s.mergedFromBounds.length === 0)
+ )
+ return undefined;
+ return slots.map((s) =>
+ Math.max(...s.mergedFromBounds.map((b) => b.right)),
+ );
+ }
}
/** The innermost artifact mark: the one that says what the content is. */
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/model/affine.ts b/frontend/src/editor/core/tools/pdfTextEditor/model/affine.ts
index 701b437b80..4ca0a35cfc 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/model/affine.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/model/affine.ts
@@ -43,6 +43,17 @@ export function transformRectAABB(t: Affine, r: PageRect): PageRect {
};
}
+export function unionRect(a: PageRect, b: PageRect): PageRect {
+ const x = Math.min(a.x, b.x);
+ const y = Math.min(a.y, b.y);
+ return {
+ x,
+ y,
+ width: Math.max(a.x + a.width, b.x + b.width) - x,
+ height: Math.max(a.y + a.height, b.y + b.height) - y,
+ };
+}
+
/** Inverse of an affine, or identity when singular (degenerate linear part). */
export function invertAffine(t: Affine): Affine {
const det = t.a * t.d - t.b * t.c;
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/formLocalResources.ts b/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/formLocalResources.ts
new file mode 100644
index 0000000000..8774955b3b
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/formLocalResources.ts
@@ -0,0 +1,139 @@
+import { toLatin1 } from "@editor/tools/pdfTextEditor/pdfdoc/bytes";
+import { parseOps } from "@editor/tools/pdfTextEditor/pdfdoc/contentOps";
+import { dictKeys, type RawPdf } from "@editor/tools/pdfTextEditor/pdfdoc/raw";
+
+// Names PDFium writes back by name when it moves an object out of a form: they
+// keep meaning the same only when the page binds each to the same object.
+const NAMED_ON_THE_PAGE = ["ExtGState", "Properties"];
+// What PDFium cannot redraw from the page: a pattern is laid out in the form's
+// space, and a colour space other than RGB or grey is dropped.
+const NEVER_CARRIED = ["Pattern", "Shading", "ColorSpace"];
+const MAX_FORM_DEPTH = 8;
+
+/** One form XObject drawn by a page or by another form, as the file draws it. */
+export interface FormNode {
+ /**
+ * Whether the form's contents would draw differently on the page itself:
+ * its own resources bind a graphics state or marked-content property under
+ * a name the page binds to something else or not at all, set a soft mask,
+ * or need a pattern, shading or colour space.
+ */
+ changesDrawing: boolean;
+ /** The forms its content draws, in drawing order. */
+ forms: FormNode[];
+}
+
+/**
+ * For each page drawing a form whose contents would draw differently on the
+ * page itself, every form its content draws, in drawing order. A page that is
+ * absent draws none.
+ */
+export async function formLiftHazards(
+ pdf: RawPdf,
+): Promise<Map<number, FormNode[]>> {
+ const out = new Map<number, FormNode[]>();
+ const pages = pdf.pageNumbers();
+ for (let pageIndex = 0; pageIndex < pages.length; pageIndex++) {
+ const resources = pdf.pageInherited(pages[pageIndex], "Resources");
+ if (!resources || !drawsLocalForm(pdf, resources, resources, new Set(), 0))
+ continue;
+ const content = await pdf.pageContent(pages[pageIndex]);
+ out.set(
+ pageIndex,
+ content ? await formsDrawn(pdf, resources, resources, content, 0) : [],
+ );
+ }
+ return out;
+}
+
+async function formsDrawn(
+ pdf: RawPdf,
+ pageResources: string,
+ resources: string,
+ content: Uint8Array,
+ depth: number,
+): Promise<FormNode[]> {
+ const xobjects = pdf.resolve(resources, "XObject");
+ if (!xobjects || depth >= MAX_FORM_DEPTH) return [];
+ const nodes: FormNode[] = [];
+ for (const op of parseOps(toLatin1(content))) {
+ if (op.op !== "Do" || op.operands.length !== 1) continue;
+ const num = pdf.dictRef(xobjects, op.operands[0].slice(1));
+ if (num === null) continue;
+ const body = pdf.objectBody(num);
+ if (!body || pdf.dictName(body, "Subtype") !== "Form") continue;
+ const own = pdf.resolve(body, "Resources") ?? pageResources;
+ const inner = await pdf.streamData(num);
+ nodes.push({
+ changesDrawing: bindsLocally(pdf, pageResources, own),
+ forms: inner
+ ? await formsDrawn(pdf, pageResources, own, inner, depth + 1)
+ : [],
+ });
+ }
+ return nodes;
+}
+
+function drawsLocalForm(
+ pdf: RawPdf,
+ pageResources: string,
+ resources: string,
+ seen: Set<number>,
+ depth: number,
+): boolean {
+ if (depth >= MAX_FORM_DEPTH) return false;
+ const xobjects = pdf.resolve(resources, "XObject");
+ if (!xobjects) return false;
+ for (const name of dictKeys(xobjects) ?? []) {
+ const num = pdf.dictRef(xobjects, name);
+ if (num === null || seen.has(num)) continue;
+ seen.add(num);
+ const body = pdf.objectBody(num);
+ if (!body || pdf.dictName(body, "Subtype") !== "Form") continue;
+ const own = pdf.resolve(body, "Resources");
+ if (!own) continue;
+ if (bindsLocally(pdf, pageResources, own)) return true;
+ if (drawsLocalForm(pdf, pageResources, own, seen, depth + 1)) return true;
+ }
+ return false;
+}
+
+function bindsLocally(
+ pdf: RawPdf,
+ pageResources: string,
+ formResources: string,
+): boolean {
+ if (formResources === pageResources) return false;
+ for (const category of NEVER_CARRIED) {
+ const entries = pdf.resolve(formResources, category);
+ if (entries && (dictKeys(entries) ?? [""]).length > 0) return true;
+ }
+ for (const category of NAMED_ON_THE_PAGE) {
+ const local = pdf.resolve(formResources, category);
+ if (!local) continue;
+ const onPage = pdf.resolve(pageResources, category);
+ const names = dictKeys(local);
+ if (names === null) return true;
+ for (const name of names) {
+ const value = pdf.valueSpan(local, name)?.text ?? "";
+ const pageValue = onPage ? pdf.valueSpan(onPage, name)?.text : undefined;
+ if (pageValue === undefined || !sameValue(value, pageValue)) return true;
+ if (category === "ExtGState" && setsSoftMask(pdf, local, name))
+ return true;
+ }
+ }
+ return false;
+}
+
+function sameValue(a: string, b: string): boolean {
+ return a.replace(/\s+/g, " ").trim() === b.replace(/\s+/g, " ").trim();
+}
+
+// A soft mask is placed by the transform in force where `gs` runs, which is
+// the form's inside the form and the page's once its contents are lifted.
+function setsSoftMask(pdf: RawPdf, states: string, name: string): boolean {
+ const state = pdf.resolve(states, name);
+ if (!state) return false;
+ const mask = pdf.valueSpan(state, "SMask")?.text.trim();
+ return mask !== undefined && mask !== "/None";
+}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/passes/defineMissingGraphicsStates.ts b/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/passes/defineMissingGraphicsStates.ts
new file mode 100644
index 0000000000..ba2dedca80
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/passes/defineMissingGraphicsStates.ts
@@ -0,0 +1,188 @@
+import { toLatin1 } from "@editor/tools/pdfTextEditor/pdfdoc/bytes";
+import { parseOps } from "@editor/tools/pdfTextEditor/pdfdoc/contentOps";
+import {
+ dictKeys,
+ RawPdf,
+ referencedObject,
+ setDictEntry,
+} from "@editor/tools/pdfTextEditor/pdfdoc/raw";
+import {
+ appendRevision,
+ plainObject,
+ type RevisionObject,
+} from "@editor/tools/pdfTextEditor/pdfdoc/revision";
+
+/** Opacities of a page object, 0-255 as PDFium reports them. */
+export interface ObjectOpacity {
+ fill: number;
+ stroke: number;
+}
+
+/**
+ * The opacities of the objects page `pageIndex` draws with the transform
+ * `matrix` [a b c d e f]; empty when none matches.
+ */
+export type OpacityAt = (
+ pageIndex: number,
+ matrix: number[],
+) => ObjectOpacity[];
+
+/**
+ * Define every graphics state a regenerated page uses with `gs` but does not
+ * declare, from the opacities of the objects drawn with it.
+ *
+ * PDFium names the graphics state an object's opacity needs once per page and
+ * then reuses the name, but only the first object to use it holds it; once
+ * that object is gone the regenerated page drops the definition while later
+ * objects still name it, and every reader then draws them opaque. Each object
+ * PDFium writes sets its own transform with `cm` right after `gs`, which
+ * finds the objects a name was written for.
+ *
+ * Returns `bytes` when nothing is missing or the file cannot be read; a name
+ * whose objects disagree on their opacity, or cannot be found, is defined as
+ * a state that changes nothing, which is how every reader draws it already.
+ */
+export async function defineMissingGraphicsStates(
+ bytes: Uint8Array,
+ pages: number[],
+ opacityAt: OpacityAt,
+): Promise<Uint8Array> {
+ const pdf = await RawPdf.parse(bytes);
+ if (!pdf || pdf.encrypted) return bytes;
+ const edited = new Map<number, string>();
+ const added: RevisionObject[] = [];
+ let next = pdf.highestObjectNumber + 1;
+ const bodyOf = (num: number) => edited.get(num) ?? pdf.objectBody(num);
+
+ for (const pageIndex of [...new Set(pages)].sort((a, b) => a - b)) {
+ const pageNum = pdf.pageNumberAt(pageIndex);
+ if (pageNum === null) continue;
+ const content = await pdf.pageContent(pageNum);
+ if (!content) continue;
+ const resources = pdf.pageInherited(pageNum, "Resources") ?? "<< >>";
+ const states = pdf.resolve(resources, "ExtGState");
+ const declared = new Set(states ? (dictKeys(states) ?? []) : []);
+ const missing = matricesByMissingName(toLatin1(content), declared);
+ if (missing.size === 0) continue;
+
+ const entries: Array<[string, string]> = [];
+ for (const [name, matrices] of missing) {
+ const num = next++;
+ added.push({
+ num,
+ body: plainObject(stateFor(pageIndex, matrices, opacityAt)),
+ });
+ entries.push([name, `${num} 0 R`]);
+ }
+ const pageBody = bodyOf(pageNum);
+ if (!pageBody) continue;
+ const written = addStates(pdf, bodyOf, edited, pageNum, pageBody, entries);
+ if (!written) return bytes;
+ }
+ if (added.length === 0) return bytes;
+ const objects: RevisionObject[] = [
+ ...added,
+ ...[...edited].map(([num, body]) => ({ num, body: plainObject(body) })),
+ ];
+ return appendRevision(pdf, objects) ?? bytes;
+}
+
+function matricesByMissingName(
+ content: string,
+ declared: Set<string>,
+): Map<string, number[][]> {
+ const out = new Map<string, number[][]>();
+ const ops = parseOps(content);
+ for (let i = 0; i < ops.length; i++) {
+ const op = ops[i];
+ if (op.op !== "gs" || op.operands.length !== 1) continue;
+ const name = op.operands[0].slice(1);
+ if (declared.has(name)) continue;
+ const list = out.get(name) ?? [];
+ out.set(name, list);
+ for (let j = i + 1; j < ops.length && ops[j].op !== "Q"; j++) {
+ if (ops[j].op !== "cm") continue;
+ const matrix = ops[j].operands.map(Number);
+ if (matrix.length === 6 && matrix.every(Number.isFinite))
+ list.push(matrix);
+ break;
+ }
+ }
+ return out;
+}
+
+function stateFor(
+ pageIndex: number,
+ matrices: number[][],
+ opacityAt: OpacityAt,
+): string {
+ const found = new Map<string, ObjectOpacity>();
+ for (const matrix of matrices)
+ for (const opacity of opacityAt(pageIndex, matrix))
+ found.set(`${opacity.fill}/${opacity.stroke}`, opacity);
+ if (found.size !== 1) return "<< /Type /ExtGState >>";
+ const [{ fill, stroke }] = found.values();
+ return `<< /Type /ExtGState /ca ${alpha(fill)} /CA ${alpha(stroke)} >>`;
+}
+
+function alpha(value: number): string {
+ return String(Math.round((value / 255) * 1e6) / 1e6);
+}
+
+// Adds `entries` to the ExtGState of the page's own /Resources, following
+// whichever of the two is written by reference. False when there is no
+// dictionary to add them to.
+function addStates(
+ pdf: RawPdf,
+ bodyOf: (num: number) => string | null,
+ edited: Map<number, string>,
+ pageNum: number,
+ pageBody: string,
+ entries: Array<[string, string]>,
+): boolean {
+ const resources = pdf.valueSpan(pageBody, "Resources");
+ if (!resources) {
+ const inherited = pdf.pageInherited(pageNum, "Resources") ?? "<< >>";
+ const merged = withStates(pdf, bodyOf, edited, inherited, entries);
+ const page = merged && setDictEntry(pageBody, "Resources", merged);
+ if (!page) return false;
+ edited.set(pageNum, page);
+ return true;
+ }
+ const holderNum = referencedObject(resources.text.trim());
+ if (holderNum !== null) {
+ const holder = bodyOf(holderNum);
+ const merged = holder && withStates(pdf, bodyOf, edited, holder, entries);
+ if (!merged) return false;
+ edited.set(holderNum, merged);
+ return true;
+ }
+ const merged = withStates(pdf, bodyOf, edited, resources.text, entries);
+ const page = merged && setDictEntry(pageBody, "Resources", merged);
+ if (!page) return false;
+ edited.set(pageNum, page);
+ return true;
+}
+
+// `resources` with `entries` added to its ExtGState. When that dictionary is
+// written by reference, it is the referenced object that changes.
+function withStates(
+ pdf: RawPdf,
+ bodyOf: (num: number) => string | null,
+ edited: Map<number, string>,
+ resources: string,
+ entries: Array<[string, string]>,
+): string | null {
+ const span = pdf.valueSpan(resources, "ExtGState");
+ const statesNum = span ? referencedObject(span.text.trim()) : null;
+ let states = statesNum !== null ? bodyOf(statesNum) : (span?.text ?? "<< >>");
+ for (const [name, ref] of entries) {
+ states = states && setDictEntry(states, name, ref);
+ }
+ if (!states) return null;
+ if (statesNum !== null) {
+ edited.set(statesNum, states);
+ return resources;
+ }
+ return setDictEntry(resources, "ExtGState", states);
+}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/readFileStructure.ts b/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/readFileStructure.ts
index 93fb9ef6d6..59bd685804 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/readFileStructure.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/pdfdoc/readFileStructure.ts
@@ -79,7 +79,12 @@ export async function readFileStructure(
bytes: Uint8Array,
): Promise<FileStructure | null> {
const pdf = await RawPdf.parse(bytes);
- if (!pdf || pdf.encrypted) return null;
+ return pdf ? fileStructureOf(pdf) : null;
+}
+
+/** As readFileStructure, from a file already parsed. */
+export function fileStructureOf(pdf: RawPdf): FileStructure | null {
+ if (pdf.encrypted) return null;
const catalog = pdf.objectBody(pdf.rootNum);
if (!catalog) return null;
const treeRoot = pdf.dictRef(catalog, "StructTreeRoot");
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/pdfium/BackgroundSampler.ts b/frontend/src/editor/core/tools/pdfTextEditor/pdfium/BackgroundSampler.ts
index f58a885d2c..67d0dcdeec 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/pdfium/BackgroundSampler.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/pdfium/BackgroundSampler.ts
@@ -209,7 +209,7 @@ const GROUND_SHARE = 0.65;
const HIGHLIGHT_SHARE = 0.97;
const REVERSED_GROUND_MAX = 110;
const REVERSED_CONTRAST = 60;
-const DOT_GAP_SHARE = 0.2;
+const DOT_GAP_SHARE = 0.3;
// Faint anti-aliased edges still show once the paper around them is covered, so the extent uses a softer cut than the colour does.
function inkLevel(l: number, paper: number): number {
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/pdfium/LineGrouper.ts b/frontend/src/editor/core/tools/pdfTextEditor/pdfium/LineGrouper.ts
index 2c9c5c863d..8748e10210 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/pdfium/LineGrouper.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/pdfium/LineGrouper.ts
@@ -1,7 +1,13 @@
+import { hasRtl, isMostlyRtl } from "@editor/tools/pdfTextEditor/util/bidi";
import type { Page } from "@editor/tools/pdfTextEditor/model/Page";
import type { TextRun } from "@editor/tools/pdfTextEditor/model/TextRun";
+import type { PageGlyphs } from "@editor/tools/pdfTextEditor/pdfium/drawnGlyphs";
+import {
+ readDrawnLine,
+ type DrawnLine,
+} from "@editor/tools/pdfTextEditor/pdfium/drawnLine";
import { innermostMcid } from "@editor/tools/pdfTextEditor/pdfium/PdfiumTagMarks";
-import { RENDER_MODE_INVISIBLE } from "@editor/tools/pdfTextEditor/types";
+import { textLayer } from "@editor/tools/pdfTextEditor/types";
/** Cluster adjacent text runs on a page into "line groups". */
export interface LineGroupInfo {
@@ -20,8 +26,26 @@ export type BlockKey = (run: TextRun) => string;
export const SAME_BLOCK: BlockKey = () => "";
export const sameTextLayer = (a: TextRun, b: TextRun): boolean =>
- (a.renderMode === RENDER_MODE_INVISIBLE) ===
- (b.renderMode === RENDER_MODE_INVISIBLE);
+ textLayer(a.renderMode) === textLayer(b.renderMode);
+/** The advance of a space in the run's font, in ems, or null when the font cannot say. */
+export type SpaceAdvance = (run: TextRun) => number | null;
+
+const NO_SPACE_ADVANCE: SpaceAdvance = () => null;
+
+/** What the page draws beyond each object's own text. */
+export interface DrawnPage {
+ /** Where every glyph sits; null when the build cannot say. */
+ glyphs: PageGlyphs | null;
+ /** The objects that draw the rest of an object's glyph cluster and hold no text of their own, by that object. */
+ companions: ReadonlyMap<number, readonly number[]>;
+}
+
+const NOTHING_DRAWN: DrawnPage = { glyphs: null, companions: new Map() };
+// Digits and Latin letters keep their own order inside right-to-left text, which reversing a line's objects does not.
+const KEEPS_OWN_ORDER = /[0-9A-Za-z\u0660-\u0669\u06f0-\u06f9]/;
+const UPRIGHT_TOLERANCE = 0.02;
+// Glyphs of one line can sit a little off its baseline; an object running over two lines has some a whole line away.
+const ONE_LINE_EM = 0.6;
const BASELINE_TOLERANCE = 0.4;
// Two runs on the same baseline join the same line only when the horizontal gap
@@ -29,10 +53,19 @@ const BASELINE_TOLERANCE = 0.4;
const ABS_MAX_GAP_PT = 12;
const WORD_GAP_MIN_RATIO = 0.2;
+// A condensed font's whole space can be narrower than WORD_GAP_MIN_RATIO; past this share of it a gap still reads as one.
+const NARROW_SPACE_SHARE = 0.6;
const FALLBACK_SPACE_UNIT_RATIO = 0.5;
const MIN_SPACE_UNIT_RATIO = 0.3;
const MAX_SPACE_UNIT_RATIO = 1;
const MULTI_SPACE_UNITS = 1.7;
+// A font with no space glyph reports zero or its missing width (1em by default), so only a plausible advance is trusted.
+const MIN_FONT_SPACE_EM = 0.05;
+const MAX_FONT_SPACE_EM = 1;
+// Ink bounds add side bearings to a space, so one space in a wide font can read as up to this many of its advance.
+const MAX_JOIN_SPACES = 1.5;
+// Runs whose space widths differ by more than this share are in different fonts, and no one width counts every gap.
+const SAME_SPACE_TOLERANCE = 0.15;
function junctionGapRatio(prev: TextRun, cur: TextRun): number {
return gapRatio(
@@ -53,28 +86,201 @@ export function readsWordGap(gapPt: number, fontSize: number): boolean {
return gapRatio(gapPt, fontSize) > WORD_GAP_MIN_RATIO;
}
-function lineSpaceUnitRatio(members: TextRun[]): number {
+function clampSpaceUnit(ratio: number): number {
+ return Math.min(MAX_SPACE_UNIT_RATIO, Math.max(MIN_SPACE_UNIT_RATIO, ratio));
+}
+
+function fontSpaceEm(
+ members: TextRun[],
+ spaceAdvance: SpaceAdvance,
+): number | null {
+ let narrowest: number | null = null;
+ let widest: number | null = null;
+ for (const member of members) {
+ const em = spaceAdvance(member);
+ if (em === null || em < MIN_FONT_SPACE_EM || em >= MAX_FONT_SPACE_EM)
+ continue;
+ if (narrowest === null || em < narrowest) narrowest = em;
+ if (widest === null || em > widest) widest = em;
+ }
+ if (narrowest === null || widest === null) return null;
+ return widest - narrowest > SAME_SPACE_TOLERANCE * widest ? null : narrowest;
+}
+
+function minWordGapRatio(spaceEm: number | null): number {
+ return spaceEm !== null && spaceEm < WORD_GAP_MIN_RATIO
+ ? NARROW_SPACE_SHARE * spaceEm
+ : WORD_GAP_MIN_RATIO;
+}
+
+function lineSpaceUnit(
+ members: TextRun[],
+ spaceAdvance: SpaceAdvance,
+ minGap: number,
+): { ratio: number; fromFont: boolean } {
const wordGaps: number[] = [];
for (let i = 1; i < members.length; i++) {
const ratio = junctionGapRatio(members[i - 1], members[i]);
- if (ratio > WORD_GAP_MIN_RATIO) wordGaps.push(ratio);
+ if (ratio > minGap) wordGaps.push(ratio);
}
- if (wordGaps.length < 2) return FALLBACK_SPACE_UNIT_RATIO;
+ if (wordGaps.length < 2)
+ return { ratio: FALLBACK_SPACE_UNIT_RATIO, fromFont: false };
wordGaps.sort((a, b) => a - b);
- const lowerMedian = wordGaps[Math.floor((wordGaps.length - 1) / 2)];
- return Math.min(
- MAX_SPACE_UNIT_RATIO,
- Math.max(MIN_SPACE_UNIT_RATIO, lowerMedian),
- );
+ // Two unequal gaps cannot tell one space from several: the narrower may itself be a double space.
+ if (wordGaps.length === 2) {
+ const em = fontSpaceEm(members, spaceAdvance);
+ if (em !== null && wordGaps[1] - wordGaps[0] >= em)
+ return { ratio: em, fromFont: true };
+ }
+ return {
+ ratio: clampSpaceUnit(wordGaps[Math.floor((wordGaps.length - 1) / 2)]),
+ fromFont: false,
+ };
+}
+
+/**
+ * The width of one space at each junction of a line, as a share of the font
+ * size.
+ *
+ * The line's own gaps usually say it best, since justified text stretches
+ * every space alike. They cannot where the line mixes fonts, or holds too few
+ * gaps to tell one space from several: a word typed in a fallback font after
+ * the document's own sits a different distance away, and a median over such
+ * gaps reads three typed spaces as one. There each junction between two pieces
+ * in the same font is counted in that font's space instead, unless those
+ * junctions are all alike, which is justification, not typing.
+ */
+function junctionSpaceUnits(
+ members: TextRun[],
+ spaceAdvance: SpaceAdvance,
+ minGap: number,
+): number[] {
+ const line = lineSpaceUnit(members, spaceAdvance, minGap);
+ const own: Array<number | null> = [];
+ const counted: number[] = [];
+ for (let i = 1; i < members.length; i++) {
+ const em = fontSpaceEm([members[i - 1], members[i]], spaceAdvance);
+ own.push(em);
+ const gap = junctionGapRatio(members[i - 1], members[i]);
+ if (em !== null && gap > minGap) counted.push(gap / em);
+ }
+ const alike =
+ counted.length >= 3 &&
+ Math.max(...counted) < MULTI_SPACE_UNITS * Math.min(...counted);
+ const byFont =
+ !alike && (line.fromFont || fontSpaceEm(members, spaceAdvance) === null);
+ return own.map((em) => (byFont && em !== null ? em : line.ratio));
}
-function spacesForGap(gapRatio: number, unitRatio: number): number {
- if (gapRatio <= WORD_GAP_MIN_RATIO) return 0;
+function spacesForGap(
+ gapRatio: number,
+ unitRatio: number,
+ minGap: number,
+): number {
+ if (gapRatio <= minGap) return 0;
const units = gapRatio / unitRatio;
if (units < MULTI_SPACE_UNITS) return 1;
return Math.max(2, Math.round(units));
}
+function isUpright(run: TextRun): boolean {
+ const scale = Math.hypot(run.matrix.a, run.matrix.b);
+ return (
+ scale > 0 &&
+ run.matrix.a > 0 &&
+ Math.abs(run.matrix.b) / scale <= UPRIGHT_TOLERANCE
+ );
+}
+
+// A line holding right-to-left text, read from where its glyphs are drawn; null when it holds none or its glyphs cannot be placed on one upright baseline.
+function readMixedLine(
+ members: TextRun[],
+ glyphs: PageGlyphs | null,
+ spaceAdvance: SpaceAdvance,
+): DrawnLine | null {
+ if (!glyphs || !members.some((member) => hasRtl(member.text))) return null;
+ if (!members.every(isUpright)) return null;
+ const objects = members.map(
+ (member) => glyphs.byObject.get(member.pdfiumObjPtr) ?? [],
+ );
+ const fontSize = Math.max(...members.map((member) => member.fontSize), 4);
+ const baseline = objects[0][0]?.baseline ?? 0;
+ if (
+ objects.some(
+ (own) =>
+ own.length === 0 ||
+ own.some(
+ (glyph) =>
+ Math.abs(glyph.baseline - baseline) > ONE_LINE_EM * fontSize,
+ ),
+ )
+ )
+ return null;
+ const spaceEm = fontSpaceEm(members, spaceAdvance);
+ const minGap = minWordGapRatio(spaceEm);
+ return readDrawnLine(objects, glyphs.spaces, fontSize, (gapPt) =>
+ spacesForGap(
+ gapRatio(gapPt, fontSize),
+ spaceEm ?? FALLBACK_SPACE_UNIT_RATIO,
+ minGap,
+ ),
+ );
+}
+
+function applyMixedLine(group: LineGroupInfo, line: DrawnLine): void {
+ const { representative, members } = group;
+ const pieces = members.map((member, i) => ({
+ ptr: member.pdfiumObjPtr,
+ start: line.spans[i].start,
+ end: line.spans[i].end,
+ x: member.bounds.x,
+ right: member.bounds.x + member.bounds.width,
+ }));
+ const left = Math.min(...pieces.map(({ x }) => x));
+ const right = Math.max(...pieces.map((piece) => piece.right));
+ // A space drawn as an object of its own is a piece of the line too, or it stays where it was when the line moves.
+ for (const { ptr, start } of line.spaces)
+ pieces.push({ ptr, start, end: start + 1, x: left, right: left });
+ pieces.sort((a, b) => a.start - b.start);
+ representative.text = line.text;
+ representative.bounds = {
+ ...representative.bounds,
+ x: left,
+ width: Math.max(representative.bounds.width, right - left),
+ };
+ representative.mergedFromTexts = pieces.map(({ start, end }) =>
+ line.text.slice(start, end),
+ );
+ representative.mergedFromCharStarts = pieces.map(({ start }) => start);
+ representative.mergedFromBounds = pieces.map(({ x, right: end }) => ({
+ x,
+ right: end,
+ }));
+ representative.mergedFromPtrs = pieces.map(({ ptr }) => ptr);
+ representative.readingOrderUnsure = !line.faithful;
+}
+
+// A companion goes wherever its object goes: listed as a piece with no text of its own, every command that walks a line's objects takes it along.
+function addCompanions(
+ run: TextRun,
+ companions: ReadonlyMap<number, readonly number[]>,
+): void {
+ if (companions.size === 0) return;
+ for (let i = run.mergedFromPtrs.length - 1; i >= 0; i--) {
+ const own = companions.get(run.mergedFromPtrs[i]);
+ if (!own) continue;
+ const at = run.mergedFromCharStarts[i] + run.mergedFromTexts[i].length;
+ run.mergedFromPtrs.splice(i + 1, 0, ...own);
+ run.mergedFromTexts.splice(i + 1, 0, ...own.map(() => ""));
+ run.mergedFromCharStarts.splice(i + 1, 0, ...own.map(() => at));
+ run.mergedFromBounds.splice(
+ i + 1,
+ 0,
+ ...own.map(() => ({ ...run.mergedFromBounds[i] })),
+ );
+ }
+}
+
// True when a same-baseline cluster's glyphs overlap so heavily that it can't
// be normal running text.
function isDecorativeOverlap(members: TextRun[]): boolean {
@@ -107,9 +313,170 @@ function lineBlock(members: TextRun[], blockKey: BlockKey): string | null {
// Sort one container's runs top-to-bottom / left-to-right and merge
// same-baseline, close-together runs into line groups.
+// A word saved as its own object in a font whose space the file never draws has no space width to read.
+function meanLetterAdvancePt(runs: TextRun[]): number {
+ let letters = 0;
+ let width = 0;
+ for (const run of runs) {
+ letters += run.text.replace(/\s/g, "").length;
+ width += run.bounds.width;
+ }
+ return letters > 0 ? width / letters : 0;
+}
+
+// A superscript or subscript is set this much smaller than its line, within this many of the line's ems of its baseline, and this close to a neighbour.
+const SCRIPT_MAX_SIZE_RATIO = 0.85;
+const SCRIPT_MAX_BASELINE_EM = 0.5;
+const SCRIPT_MAX_GAP_EM = 0.25;
+
+function lineFontSize(group: LineGroupInfo): number {
+ return Math.max(...group.members.map((member) => member.fontSize));
+}
+
+function touchesHorizontally(
+ script: TextRun,
+ member: TextRun,
+ slack: number,
+): boolean {
+ const scriptRight = script.bounds.x + script.bounds.width;
+ const memberRight = member.bounds.x + member.bounds.width;
+ return (
+ Math.abs(script.bounds.x - memberRight) <= slack ||
+ Math.abs(member.bounds.x - scriptRight) <= slack
+ );
+}
+
+// The line a raised or lowered script belongs to, which the baseline band misses because the script sits off it.
+function scriptHost(
+ script: LineGroupInfo,
+ lines: readonly LineGroupInfo[],
+): LineGroupInfo | null {
+ const size = lineFontSize(script);
+ const baseline = script.representative.matrix.f;
+ for (const line of lines) {
+ if (line === script) continue;
+ const lineSize = lineFontSize(line);
+ if (size > lineSize * SCRIPT_MAX_SIZE_RATIO) continue;
+ const em = Math.max(lineSize, 4);
+ if (
+ Math.abs(baseline - line.representative.matrix.f) >
+ SCRIPT_MAX_BASELINE_EM * em
+ )
+ continue;
+ const slack = SCRIPT_MAX_GAP_EM * em;
+ if (
+ script.members.every((member) =>
+ line.members.some((host) => touchesHorizontally(member, host, slack)),
+ )
+ )
+ return line;
+ }
+ return null;
+}
+
+function attachScripts(lines: LineGroupInfo[]): void {
+ for (let i = lines.length - 1; i >= 0; i--) {
+ const script = lines[i];
+ if (script.members.length > 2) continue;
+ const host = scriptHost(script, lines);
+ if (!host) continue;
+ host.members.push(...script.members);
+ host.members.sort((a, b) => a.bounds.x - b.bounds.x);
+ lines.splice(i, 1);
+ }
+}
+
function groupPartitionIntoLines(
runs: TextRun[],
blockKey: BlockKey,
+ spaceAdvance: SpaceAdvance,
+ out: LineGroupInfo[],
+): void {
+ const lines: LineGroupInfo[] = [];
+ groupBaselineBands(runs, blockKey, spaceAdvance, lines);
+ attachScripts(lines);
+ out.push(...lines);
+}
+
+// A column gutter is wider than this many ems and this many of the line's spaces: wide for a word gap, narrow for a gutter.
+const GUTTER_MIN_EM = 0.6;
+const GUTTER_MIN_SPACES = 2.5;
+// Only the middle of the gap is probed, so the slightly uneven column edges of the rows around it still leave it clear.
+const GUTTER_PROBE_EM = 0.2;
+// Lines set either side of a gutter, at least this many ems of text on each side, run past the gap within one unbroken stretch of the page. Justified text never lines its word gaps up so, and a label beside its value is shorter.
+const GUTTER_MIN_LINES = 3;
+const COLUMN_MIN_EM = 8;
+
+// The page's baseline rows, top to bottom, and the row of each run in `sorted`.
+function baselineRows(sorted: readonly TextRun[]): {
+ rows: TextRun[][];
+ rowIndex: number[];
+} {
+ const rows: TextRun[][] = [];
+ const rowIndex: number[] = [];
+ for (const run of sorted) {
+ const row = rows[rows.length - 1];
+ if (
+ row &&
+ Math.abs(run.matrix.f - row[0].matrix.f) <=
+ BASELINE_TOLERANCE * Math.max(row[0].fontSize, 4)
+ )
+ row.push(run);
+ else rows.push([run]);
+ rowIndex.push(rows.length - 1);
+ }
+ return { rows, rowIndex };
+}
+
+// The width of text a row sets left and right of [lo, hi], or null when its text crosses into it.
+function textBeside(
+ row: readonly TextRun[],
+ lo: number,
+ hi: number,
+): { left: number; right: number } | null {
+ let left = 0;
+ let right = 0;
+ for (const run of row) {
+ if (!run.text.trim()) continue;
+ const end = run.bounds.x + run.bounds.width;
+ if (end <= lo) left += run.bounds.width;
+ else if (run.bounds.x >= hi) right += run.bounds.width;
+ else return null;
+ }
+ return { left, right };
+}
+
+/**
+ * Whether the gap from `left` to `right` on row `at` is a column gutter: a
+ * strip of the page the rows above and below it leave empty too, with columns
+ * of text set either side.
+ */
+function isColumnGutter(
+ rows: readonly TextRun[][],
+ at: number,
+ left: number,
+ right: number,
+ em: number,
+): boolean {
+ const mid = (left + right) / 2;
+ const half = Math.min(GUTTER_PROBE_EM * em, (right - left) / 4);
+ const minColumn = COLUMN_MIN_EM * em;
+ let lines = 0;
+ for (const step of [-1, 1]) {
+ for (let i = at + step; i >= 0 && i < rows.length; i += step) {
+ const beside = textBeside(rows[i], mid - half, mid + half);
+ if (!beside) break;
+ if (beside.left >= minColumn && beside.right >= minColumn) lines += 1;
+ if (lines >= GUTTER_MIN_LINES) return true;
+ }
+ }
+ return false;
+}
+
+function groupBaselineBands(
+ runs: TextRun[],
+ blockKey: BlockKey,
+ spaceAdvance: SpaceAdvance,
out: LineGroupInfo[],
): void {
const sorted = [...runs].sort((a, b) => {
@@ -121,9 +488,10 @@ function groupPartitionIntoLines(
if (Math.abs(yDiff) > Math.max(1, band)) return yDiff;
return a.bounds.x - b.bounds.x;
});
+ const { rows, rowIndex } = baselineRows(sorted);
let current: LineGroupInfo | null = null;
- for (const run of sorted) {
+ for (const [index, run] of sorted.entries()) {
if (!current) {
current = { representative: run, members: [run] };
out.push(current);
@@ -136,7 +504,22 @@ function groupPartitionIntoLines(
const gap = run.bounds.x - (prev.bounds.x + prev.bounds.width);
// The gap cap must scale with font size: an inter-word space in a 50pt
// heading is ~15-25pt, which a flat 12pt cap would treat as a line break.
- const maxGap = Math.max(ABS_MAX_GAP_PT, 0.5 * Math.max(ref.fontSize, 4));
+ const spaceEm = fontSpaceEm([prev], spaceAdvance);
+ const spacePt =
+ spaceEm === null
+ ? meanLetterAdvancePt(current.members)
+ : spaceEm * prev.fontSize;
+ // Spaces the text itself holds at the junction are drawn as part of the gap, not a column break.
+ const trailingSpaces = /\s+$/.exec(prev.text)?.[0].length ?? 0;
+ const literalSpaces =
+ trailingSpaces + (/^\s+/.exec(run.text)?.[0].length ?? 0);
+ const maxGap =
+ Math.max(
+ ABS_MAX_GAP_PT,
+ 0.5 * Math.max(ref.fontSize, 4),
+ MAX_JOIN_SPACES * spacePt,
+ ) +
+ literalSpaces * spacePt;
// A leading bullet is indented from its item by more than an inter-word
// space; let the item attach across that wider indent.
const effMaxGap = isBulletLead(prev)
@@ -144,8 +527,23 @@ function groupPartitionIntoLines(
: maxGap;
// Reject joining a run that starts far to the LEFT of the previous run's
// right edge - a right-column run must never absorb the left column.
- const minNegGap = 0.25 * Math.max(ref.fontSize, 4);
- const close = gap <= effMaxGap && gap >= -minNegGap;
+ // A word's own trailing space may overhang the next: OCR stretches each word, space and all, to its box.
+ const minNegGap =
+ 0.25 * Math.max(ref.fontSize, 4) + trailingSpaces * spacePt;
+ const em = Math.max(ref.fontSize, 4);
+ const close =
+ gap <= effMaxGap &&
+ gap >= -minNegGap &&
+ !(
+ gap > Math.max(GUTTER_MIN_EM * em, GUTTER_MIN_SPACES * spacePt) &&
+ isColumnGutter(
+ rows,
+ rowIndex[index],
+ prev.bounds.x + prev.bounds.width,
+ run.bounds.x,
+ em,
+ )
+ );
const block = lineBlock(current.members, blockKey);
const sameBlock =
@@ -160,13 +558,43 @@ function groupPartitionIntoLines(
}
}
+/** Each line's fonts, as the share of its letters each draws, so one odd piece at its start does not stand for the whole line. */
+export function lineFontIds(
+ groups: readonly LineGroupInfo[],
+): Map<TextRun, Map<string, number>> {
+ const out = new Map<TextRun, Map<string, number>>();
+ for (const { representative, members } of groups) {
+ const fontOf = new Map(members.map((m) => [m.pdfiumObjPtr, m.fontId]));
+ const letters = new Map<string, number>();
+ let total = 0;
+ representative.mergedFromPtrs.forEach((ptr, i) => {
+ const fontId = fontOf.get(ptr) ?? representative.fontId;
+ const count = (representative.mergedFromTexts[i] ?? "").replace(
+ /\s+/g,
+ "",
+ ).length;
+ letters.set(fontId, (letters.get(fontId) ?? 0) + count);
+ total += count;
+ });
+ for (const [fontId, count] of letters)
+ letters.set(fontId, total > 0 ? count / total : 1);
+ out.set(representative, letters);
+ }
+ return out;
+}
+
export class LineGrouper {
/** Group a page's runs and store the result back onto the page. */
- static apply(page: Page, blockKey: BlockKey = SAME_BLOCK): LineGroupInfo[] {
+ static apply(
+ page: Page,
+ blockKey: BlockKey = SAME_BLOCK,
+ spaceAdvance: SpaceAdvance = NO_SPACE_ADVANCE,
+ drawn: DrawnPage = NOTHING_DRAWN,
+ ): LineGroupInfo[] {
// Partition by form-xobject container and text layer BEFORE grouping: OCR words over printed ones would interleave in x.
const partitions = new Map<string, TextRun[]>();
for (const run of page.runs) {
- const key = `${run.containerPtr || 0}:${run.renderMode === RENDER_MODE_INVISIBLE}`;
+ const key = `${run.containerPtr || 0}:${textLayer(run.renderMode)}`;
const list = partitions.get(key);
if (list) list.push(run);
else partitions.set(key, [run]);
@@ -174,7 +602,7 @@ export class LineGrouper {
const groups: LineGroupInfo[] = [];
for (const partition of partitions.values()) {
- groupPartitionIntoLines(partition, blockKey, groups);
+ groupPartitionIntoLines(partition, blockKey, spaceAdvance, groups);
}
// Refine: a "line" whose glyphs heavily OVERLAP in x is not real running
@@ -195,6 +623,14 @@ export class LineGrouper {
// Mutate the representative's text/bounds to reflect the merged group and
// remember the underlying object pointers so ReplaceLineGroupCommand can.
for (const group of groups) {
+ const mixed = readMixedLine(group.members, drawn.glyphs, spaceAdvance);
+ if (mixed) {
+ const text = group.members.find((member) => !isBulletLead(member));
+ if (text && innermostMcid(group.representative.tagMarks) === null)
+ group.representative.tagMarks = text.tagMarks;
+ applyMixedLine(group, mixed);
+ continue;
+ }
if (group.members.length === 1) {
// A one-object line still needs its sub-run arrays. EditTextCommand's
// surgical path requires a non-empty mergedFromPtrs; without it even a
@@ -224,35 +660,53 @@ export class LineGrouper {
}));
// When the typesetter emitted a cursor jump instead of a literal space
// character, the two runs end up with content like ["Hello".
- const parts: string[] = [memberTexts[0]];
- const memberCharStarts: number[] = [0];
- let cumulativeLen = memberTexts[0].length;
- const spaceUnitRatio = lineSpaceUnitRatio(group.members);
+ const rtl = isMostlyRtl(memberTexts.join(""));
+ // Gaps between neighbours, in drawn order.
+ const gaps: string[] = [];
+ const minGap = minWordGapRatio(fontSpaceEm(group.members, spaceAdvance));
+ const spaceUnits = junctionSpaceUnits(
+ group.members,
+ spaceAdvance,
+ minGap,
+ );
for (let i = 1; i < group.members.length; i++) {
- const prev = group.members[i - 1];
- const cur = group.members[i];
- const prevTail = memberTexts[i - 1].slice(-1);
- const curHead = memberTexts[i].slice(0, 1);
const extraSpaces = spacesForGap(
- junctionGapRatio(prev, cur),
- spaceUnitRatio,
+ junctionGapRatio(group.members[i - 1], group.members[i]),
+ spaceUnits[i - 1],
+ minGap,
);
- const prevEndsInSpace = /\s/.test(prevTail);
- const curStartsWithSpace = /\s/.test(curHead);
+ // A right-to-left piece's trailing space is drawn on its left.
+ const [left, right] = rtl
+ ? [memberTexts[i], memberTexts[i - 1]]
+ : [memberTexts[i - 1], memberTexts[i]];
const alreadyHave =
- (prevEndsInSpace ? 1 : 0) + (curStartsWithSpace ? 1 : 0);
- const toInsert = Math.max(0, extraSpaces - alreadyHave);
- if (toInsert > 0) {
- parts.push(" ".repeat(toInsert));
- cumulativeLen += toInsert;
+ (/\s*$/.exec(left)?.[0].length ?? 0) +
+ (/^\s*/.exec(right)?.[0].length ?? 0);
+ gaps.push(" ".repeat(Math.max(0, extraSpaces - alreadyHave)));
+ }
+ // A right-to-left line reads from its rightmost piece; each piece already holds its own text in reading order.
+ const reading = rtl
+ ? group.members.map((_, i) => group.members.length - 1 - i)
+ : group.members.map((_, i) => i);
+ const parts: string[] = [];
+ const memberCharStarts: number[] = [];
+ let cumulativeLen = 0;
+ reading.forEach((member, k) => {
+ if (k > 0) {
+ const gap = gaps[Math.min(member, reading[k - 1])];
+ parts.push(gap);
+ cumulativeLen += gap.length;
}
memberCharStarts.push(cumulativeLen);
- parts.push(memberTexts[i]);
- cumulativeLen += memberTexts[i].length;
- }
+ parts.push(memberTexts[member]);
+ cumulativeLen += memberTexts[member].length;
+ });
const joined = parts.join("");
const last = group.members[group.members.length - 1];
- const left = group.representative.bounds.x;
+ const left = Math.min(
+ group.representative.bounds.x,
+ group.members[0].bounds.x,
+ );
const right = last.bounds.x + last.bounds.width;
group.representative.text = joined;
group.representative.bounds = {
@@ -262,13 +716,19 @@ export class LineGrouper {
};
// Per-sub-run texts + bounds so EditTextCommand's pure-deletion
// optimization can map joined-text chars back to their source.
- group.representative.mergedFromTexts = memberTexts;
- group.representative.mergedFromBounds = memberBounds;
+ group.representative.mergedFromTexts = reading.map((i) => memberTexts[i]);
+ group.representative.mergedFromBounds = reading.map(
+ (i) => memberBounds[i],
+ );
group.representative.mergedFromCharStarts = memberCharStarts;
- group.representative.mergedFromPtrs = group.members.map(
- (m) => m.pdfiumObjPtr,
+ group.representative.mergedFromPtrs = reading.map(
+ (i) => group.members[i].pdfiumObjPtr,
);
+ group.representative.readingOrderUnsure =
+ hasRtl(joined) && KEEPS_OWN_ORDER.test(joined);
}
+ for (const group of groups)
+ addCompanions(group.representative, drawn.companions);
// Replace the page's runs with just the representatives.
page.setRuns(groups.map((g) => g.representative));
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/pdfium/ParagraphGrouper.ts b/frontend/src/editor/core/tools/pdfTextEditor/pdfium/ParagraphGrouper.ts
index 10f977c8df..1644cee941 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/pdfium/ParagraphGrouper.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/pdfium/ParagraphGrouper.ts
@@ -1,3 +1,8 @@
+import {
+ RENDER_MODE_INVISIBLE,
+ textLayer,
+ type PageRect,
+} from "@editor/tools/pdfTextEditor/types";
import type { Page } from "@editor/tools/pdfTextEditor/model/Page";
import {
SAME_BLOCK,
@@ -9,6 +14,10 @@ import type {
TextRun,
} from "@editor/tools/pdfTextEditor/model/TextRun";
import { median } from "@editor/tools/pdfTextEditor/util/median";
+import {
+ softLineStarts,
+ type BreakLine,
+} from "@editor/tools/pdfTextEditor/pdfium/lineBreaks";
/** Cluster consecutive `LineGroup` representatives into "paragraphs". */
const MIN_LINE_FACTOR = 0.6;
@@ -22,6 +31,14 @@ const COLUMN_BASELINE_FRAC = 0.6;
const COLUMN_MIN_GAP_PT = 24;
// Left-edge clustering tolerance when splitting runs into columns.
const COLUMN_LEFT_TOLERANCE = 14;
+// A table cell reads as a few words; a line of running text is longer than this.
+const CELL_MAX_WORDS = 3;
+const CELL_MAX_CHARS = 24;
+
+/** Each line's fonts, as the share of its letters each draws. */
+type LineFonts = ReadonlyMap<TextRun, ReadonlyMap<string, number>>;
+/** A document font's own face name, or null when it has none. */
+type FaceOf = (fontId: string) => string | null;
export interface ParagraphInfo {
representative: TextRun;
@@ -30,10 +47,18 @@ export interface ParagraphInfo {
export class ParagraphGrouper {
/** `blockKey` must be the one LineGrouper grouped the page's lines by. */
- static apply(page: Page, blockKey: BlockKey = SAME_BLOCK): ParagraphInfo[] {
+ static apply(
+ page: Page,
+ blockKey: BlockKey = SAME_BLOCK,
+ lineFonts: LineFonts = new Map(),
+ faceOf: FaceOf = () => null,
+ ): ParagraphInfo[] {
const allLines = [...page.runs];
const paragraphs: ParagraphInfo[] = [];
+ const softStarts = new Map<ParagraphInfo, boolean[]>();
+ const cells = tableCells(allLines);
+ const scannedPairs = scannedLabelValueCells(allLines);
// Columns first: a reading-order sort across the whole page interleaves
// side-by-side columns into one bogus paragraph.
for (const column of segmentColumns(allLines)) {
@@ -42,12 +67,38 @@ export class ParagraphGrouper {
if (Math.abs(yDiff) > 0.5) return yDiff;
return a.bounds.x - b.bounds.x;
});
- groupColumnLines(sorted, blockKey, paragraphs);
+ // Each text layer on its own: a word typed over a scanned line sits between that line and the next, and would end their paragraph.
+ const grouped: ParagraphInfo[] = [];
+ for (const layerOf of [0, 1, 2]) {
+ const layer = sorted.filter(
+ (line) => textLayer(line.renderMode) === layerOf,
+ );
+ if (layer.length === 0) continue;
+ const from = grouped.length;
+ groupColumnLines(
+ layer,
+ blockKey,
+ grouped,
+ cells,
+ scannedPairs,
+ page.rules,
+ lineFonts,
+ faceOf,
+ );
+ for (const para of grouped.slice(from))
+ softStarts.set(para, documentSoftStarts(para.members, layer));
+ }
+ const order = new Map(sorted.map((line, i) => [line, i]));
+ grouped.sort(
+ (a, b) => order.get(a.representative)! - order.get(b.representative)!,
+ );
+ paragraphs.push(...grouped);
}
// Fold member bounds + text into the representative and drop the member
// runs from the page so the editor sees one overlay per paragraph.
for (const para of paragraphs) {
+ para.representative.paragraphSoftStartsText = para.representative.text;
if (para.members.length === 1) continue;
const rep = para.representative;
@@ -97,6 +148,11 @@ export class ParagraphGrouper {
rep.paragraphLeafPtrs = leafPtrs;
rep.paragraphLeafContainers = leafContainers;
rep.paragraphLineSlots = slots;
+ rep.paragraphSoftStarts = softStarts.get(para) ?? [];
+ rep.paragraphSoftStartsText = joinedText;
+ rep.readingOrderUnsure = para.members.some(
+ (member) => member.readingOrderUnsure,
+ );
}
page.setRuns(paragraphs.map((p) => p.representative));
@@ -104,6 +160,42 @@ export class ParagraphGrouper {
}
}
+// The column's wrap margin is the furthest right that a line starting at or
+// left of the paragraph reaches: a short paragraph's own widest line is not a
+// margin, so the short lines of a list or an indented block read as ended.
+function documentSoftStarts(members: TextRun[], column: TextRun[]): boolean[] {
+ const lines = members.map((m) => breakLine(m, m.fontSize));
+ if (lines.length < 2) return [];
+ const left = Math.min(...lines.map((l) => l.left));
+ return softLineStarts(
+ lines,
+ wrapMargin(column, left, members[0].fontSize || 12),
+ );
+}
+
+function breakLine(run: TextRun, fontSize: number): BreakLine {
+ return {
+ text: run.text,
+ left: run.bounds.x,
+ right: run.bounds.x + run.bounds.width,
+ fontSize,
+ };
+}
+
+/** The furthest right a line of `column` starting at or left of `left` reaches. */
+function wrapMargin(
+ column: readonly TextRun[],
+ left: number,
+ fontSize: number,
+): number {
+ const tolerance = Math.max(3, fontSize * 0.6);
+ return Math.max(
+ ...column
+ .filter((line) => line.bounds.x <= left + tolerance)
+ .map((line) => line.bounds.x + line.bounds.width),
+ );
+}
+
/** Build a `ParagraphLineSlot[]` from the paragraph's member runs. */
export function buildLineSlots(
members: TextRun[],
@@ -195,9 +287,112 @@ export function buildLineSlotsFromDescriptors(
// A run's visual font identity for grouping: family + rounded size.
// `run.fontId` is `pdf:<fontHandlePtr>:<family>`.
-function fontKey(run: TextRun): string {
- const family = run.fontId.slice(run.fontId.lastIndexOf(":") + 1);
- return `${family}@${Math.round(run.fontSize)}`;
+// A face's own name tells regular from bold where a name-table family does not.
+function fontKey(fontId: string, fontSize: number, faceOf: FaceOf): string {
+ const face = faceOf(fontId) ?? fontId.slice(fontId.lastIndexOf(":") + 1);
+ return `${face}@${Math.round(fontSize)}`;
+}
+
+// Typed words drawn in a fallback can outnumber a line's own letters; the line still belongs with a neighbour whose font draws a good share of both.
+const SHARED_FONT_MIN_SHARE = 0.25;
+
+function lineFontKeys(
+ run: TextRun,
+ lineFonts: LineFonts,
+ faceOf: FaceOf,
+): Set<string> {
+ const shares = lineFonts.get(run);
+ if (!shares || shares.size === 0)
+ return new Set([fontKey(run.fontId, run.fontSize, faceOf)]);
+ const most = Math.max(...shares.values());
+ return new Set(
+ [...shares]
+ .filter(([, share]) => share >= SHARED_FONT_MIN_SHARE || share === most)
+ .map(([fontId]) => fontKey(fontId, run.fontSize, faceOf)),
+ );
+}
+
+// OCR estimates each line's height from its own letters, so the lines of one paragraph come out up to a fifth apart (10 next to 12).
+const OCR_SIZE_RATIO = 1.3;
+// A scan fed in a couple of degrees off square still reads as upright lines.
+const OCR_UPRIGHT_SLOPE = 0.05;
+
+// A turned scan's words come out as runs of their own, which this vertical-stacking grouper must not join.
+function isUprightOcr(run: TextRun): boolean {
+ const { a, b } = run.matrix;
+ return (
+ run.renderMode === RENDER_MODE_INVISIBLE &&
+ a > 0 &&
+ Math.abs(b) <= OCR_UPRIGHT_SLOPE * a
+ );
+}
+
+// OCR stretches each word sideways to fit the scan, and a run's size carries its first word's stretch, so one line of an address reads half the size of the next. The upright scale is not stretched.
+function ocrHeight(run: TextRun): number {
+ const { a, b, c, d } = run.matrix;
+ const across = Math.hypot(a, b);
+ return across > 0 ? (run.fontSize / across) * Math.hypot(c, d) : 0;
+}
+
+// A line's own width tells its size where the OCR height does not: renderers set that height anywhere from 0.7 to 1 of the letters' size.
+const OCR_AVERAGE_ADVANCE_EM = 0.5;
+const OCR_MIN_MEASURED_CHARS = 4;
+
+function ocrLineSize(run: TextRun): number {
+ const line = run.text.split("\n")[0].trim();
+ const measured =
+ line.length >= OCR_MIN_MEASURED_CHARS
+ ? run.bounds.width / (line.length * OCR_AVERAGE_ADVANCE_EM)
+ : 0;
+ return Math.max(ocrHeight(run), measured);
+}
+
+function sameOcrSize(a: TextRun, b: TextRun): boolean {
+ const big = Math.max(ocrHeight(a), ocrHeight(b));
+ const small = Math.min(ocrHeight(a), ocrHeight(b));
+ return small > 0 && big / small <= OCR_SIZE_RATIO;
+}
+
+// Small scanned text set with a web page's loose leading sits further apart than its size allows, but a line that ran to the column's margin and carries on mid-sentence below is a wrapped paragraph whatever the leading.
+const OCR_WRAPPED_LINE_FACTOR = 2.6;
+const STARTS_MID_SENTENCE = /^\s*\p{Ll}/u;
+
+function continuesWrappedLine(
+ prev: TextRun,
+ line: TextRun,
+ column: readonly TextRun[],
+ size: number,
+): boolean {
+ if (!STARTS_MID_SENTENCE.test(line.text)) return false;
+ return softLineStarts(
+ [breakLine(prev, size), breakLine(line, size)],
+ wrapMargin(column, prev.bounds.x, size),
+ )[1];
+}
+
+function shareAFont(
+ a: TextRun,
+ b: TextRun,
+ lineFonts: LineFonts,
+ faceOf: FaceOf,
+): boolean {
+ if (isUprightOcr(a) && isUprightOcr(b))
+ return sameOcrSize(a, b) && shareAFace(a, b, lineFonts, faceOf);
+ const theirs = lineFontKeys(b, lineFonts, faceOf);
+ return [...lineFontKeys(a, lineFonts, faceOf)].some((key) => theirs.has(key));
+}
+
+function shareAFace(
+ a: TextRun,
+ b: TextRun,
+ lineFonts: LineFonts,
+ faceOf: FaceOf,
+): boolean {
+ const faceOnly = (key: string) => key.slice(0, key.lastIndexOf("@"));
+ const theirs = new Set([...lineFontKeys(b, lineFonts, faceOf)].map(faceOnly));
+ return [...lineFontKeys(a, lineFonts, faceOf)].some((key) =>
+ theirs.has(faceOnly(key)),
+ );
}
/** Split a page's line-runs into columns. */
@@ -256,6 +451,11 @@ function groupColumnLines(
sorted: TextRun[],
blockKey: BlockKey,
out: ParagraphInfo[],
+ cells: ReadonlySet<TextRun>,
+ scannedPairs: ReadonlySet<TextRun>,
+ rules: readonly PageRect[],
+ lineFonts: LineFonts,
+ faceOf: FaceOf,
): void {
let current: ParagraphInfo | null = null;
let currentDeltas: number[] = [];
@@ -270,7 +470,7 @@ function groupColumnLines(
continue;
}
const prev = current.members[current.members.length - 1];
- const sameFont = fontKey(prev) === fontKey(line);
+ const sameFont = shareAFont(prev, line, lineFonts, faceOf);
const sameColor =
prev.fill.r === line.fill.r &&
prev.fill.g === line.fill.g &&
@@ -279,9 +479,15 @@ function groupColumnLines(
let lineHeightOk: boolean;
if (currentDeltas.length === 0) {
+ const scanned = isUprightOcr(prev) && isUprightOcr(line);
+ const size = scanned ? ocrLineSize(line) : line.fontSize;
+ const maxFactor =
+ scanned && continuesWrappedLine(prev, line, sorted, size)
+ ? OCR_WRAPPED_LINE_FACTOR
+ : MAX_LINE_FACTOR;
lineHeightOk =
- baselineDelta >= MIN_LINE_FACTOR * line.fontSize &&
- baselineDelta <= MAX_LINE_FACTOR * line.fontSize;
+ baselineDelta >= MIN_LINE_FACTOR * size &&
+ baselineDelta <= maxFactor * size;
} else {
const med = median(currentDeltas);
const tol = MEDIAN_TOLERANCE * med;
@@ -294,6 +500,14 @@ function groupColumnLines(
deltaFromLeft <= MARGIN_INDENT_RIGHT;
const sameBlock = blockKey(prev) === blockKey(line);
+ // Stacked cells of a table are rows, each its own box, not one paragraph per column.
+ const tableRows =
+ (cells.has(prev) && cells.has(line)) ||
+ (scannedPairs.has(line) &&
+ current.members.every((member) => scannedPairs.has(member))) ||
+ (isUprightOcr(prev) &&
+ isUprightOcr(line) &&
+ ruledApart(prev, line, rules));
if (
sameFont &&
@@ -301,6 +515,7 @@ function groupColumnLines(
lineHeightOk &&
leftOk &&
sameBlock &&
+ !tableRows &&
sameTextLayer(prev, line)
) {
current.members.push(line);
@@ -315,6 +530,91 @@ function groupColumnLines(
}
}
+// A scanned table's borders are drawn, not read: a rule across both lines in the gap between them is a row border.
+function ruledApart(
+ above: TextRun,
+ below: TextRun,
+ rules: readonly PageRect[],
+): boolean {
+ const top = below.bounds.y + below.bounds.height;
+ const bottom = above.bounds.y;
+ const from = Math.max(above.bounds.x, below.bounds.x);
+ const to = Math.min(
+ above.bounds.x + above.bounds.width,
+ below.bounds.x + below.bounds.width,
+ );
+ return rules.some((rule) => {
+ const y = rule.y + rule.height / 2;
+ return (
+ rule.width > rule.height &&
+ y > top &&
+ y < bottom &&
+ rule.x <= from &&
+ rule.x + rule.width >= to
+ );
+ });
+}
+
+function isShortCell(line: TextRun): boolean {
+ const text = line.text.trim();
+ return (
+ text.length > 0 &&
+ text.length <= CELL_MAX_CHARS &&
+ text.split(/\s+/).length <= CELL_MAX_WORDS
+ );
+}
+
+// Short lines side by side on one baseline, three or more of them or one a number: the cells of a table row. Two short lines alone could be narrow columns of running text.
+function tableCells(lines: readonly TextRun[]): Set<TextRun> {
+ const cells = new Set<TextRun>();
+ for (const row of shortRows(lines))
+ if (row.length >= 3 || (row.length >= 2 && row.some(isNumberCell)))
+ for (const cell of row) cells.add(cell);
+ return cells;
+}
+
+// On a scan, two short lines on one baseline are more often a form's label and its value than narrow columns. They are cells only where every line above them in their block is one too: an address and a footer set side by side end in short lines of their own.
+function scannedLabelValueCells(lines: readonly TextRun[]): Set<TextRun> {
+ const cells = new Set<TextRun>();
+ for (const row of shortRows(lines))
+ if (row.length === 2 && row.every(isUprightOcr))
+ for (const cell of row) cells.add(cell);
+ return cells;
+}
+
+// Short lines grouped by baseline, keeping those set at least a column gap from another on theirs.
+function shortRows(lines: readonly TextRun[]): TextRun[][] {
+ const short = lines
+ .filter(isShortCell)
+ .sort((a, b) => b.matrix.f - a.matrix.f);
+ const rows: TextRun[][] = [];
+ for (let i = 0; i < short.length;) {
+ const row = [short[i]];
+ let j = i + 1;
+ while (
+ j < short.length &&
+ short[i].matrix.f - short[j].matrix.f <=
+ COLUMN_BASELINE_FRAC * Math.min(short[i].fontSize, short[j].fontSize)
+ )
+ row.push(short[j++]);
+ i = j;
+ rows.push(
+ row.filter((cell) =>
+ row.some(
+ (other) =>
+ other !== cell &&
+ Math.abs(other.bounds.x - cell.bounds.x) >= COLUMN_MIN_GAP_PT,
+ ),
+ ),
+ );
+ }
+ return rows;
+}
+
+function isNumberCell(line: TextRun): boolean {
+ return /^[-+(]?[$€£¥]?\d[\d.,\s%]*\)?$/.test(line.text.trim());
+}
+
function computeMedianLineHeight(members: TextRun[]): number {
if (members.length < 2) return members[0].fontSize * 1.2;
return medianLineHeightFromBaselines(
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/pdfium/PdfiumPageRenderer.ts b/frontend/src/editor/core/tools/pdfTextEditor/pdfium/PdfiumPageRenderer.ts
index 9a17fe7f13..c10ff64629 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/pdfium/PdfiumPageRenderer.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/pdfium/PdfiumPageRenderer.ts
@@ -1,5 +1,7 @@
import type { EditorDocument } from "@editor/tools/pdfTextEditor/model/EditorDocument";
import type { Page } from "@editor/tools/pdfTextEditor/model/Page";
+import { transformRectAABB } from "@editor/tools/pdfTextEditor/model/affine";
+import type { PageRect } from "@editor/tools/pdfTextEditor/types";
// A display ratio above this buys no visible sharpness for a PDF preview and
// doubles memory per step, so the raster stops following it there.
@@ -46,86 +48,166 @@ export class PdfiumPageRenderer {
page: Page,
scale: number,
): Promise<ImageData> {
- const m = doc.module;
- // No flush: FPDF_RenderPageBitmap draws from the in-memory object list, so
- // the preview is current without rewriting the content stream.
- const { width: w, height: h } = PdfiumPageRenderer.rasterSize(
+ const { width, height } = PdfiumPageRenderer.rasterSize(
page.width,
page.height,
scale,
);
+ return PdfiumPageRenderer.renderArea(doc, page, scale, {
+ x: 0,
+ y: 0,
+ width,
+ height,
+ });
+ }
+
+ /** The bitmap pixels {@link render} at `scale` draws raw page-space `raw` into, or null when none. */
+ static pixelsCovering(
+ page: Page,
+ scale: number,
+ raw: PageRect,
+ ): PageRect | null {
+ const full = PdfiumPageRenderer.rasterSize(page.width, page.height, scale);
+ const shown = transformRectAABB(page.display, raw);
+ const kx = full.width / page.width;
+ const ky = full.height / page.height;
+ const left = Math.max(0, Math.floor(shown.x * kx) - 1);
+ const top = Math.max(
+ 0,
+ Math.floor((page.height - shown.y - shown.height) * ky) - 1,
+ );
+ const right = Math.min(
+ full.width,
+ Math.ceil((shown.x + shown.width) * kx) + 1,
+ );
+ const bottom = Math.min(
+ full.height,
+ Math.ceil((page.height - shown.y) * ky) + 1,
+ );
+ if (right <= left || bottom <= top) return null;
+ return { x: left, y: top, width: right - left, height: bottom - top };
+ }
- // BGRA bitmap = format 1, fill white, then render with REVERSE_BYTE_ORDER
- // so the pixel buffer is RGBA-ordered for ImageData.
- const bitmapPtr = m.FPDFBitmap_Create(w, h, 1);
+ /** The pixels {@link render} would draw inside `area` (bitmap pixels, top-left origin), drawing nothing else. */
+ static async renderArea(
+ doc: EditorDocument,
+ page: Page,
+ scale: number,
+ area: PageRect,
+ ): Promise<ImageData> {
+ return drawArea(doc, page, scale, area);
+ }
+
+ /**
+ * {@link renderArea} as the page would look without object `objPtr`, or
+ * null when this build cannot hide an object. The object is hidden only for
+ * the duration of the call: the document, its history and its dirty state
+ * are left as they were.
+ */
+ static renderAreaWithout(
+ doc: EditorDocument,
+ page: Page,
+ scale: number,
+ area: PageRect,
+ objPtr: number,
+ ): ImageData | null {
+ const setActive = (doc.module as unknown as ActivityModule)
+ .FPDFPageObj_SetIsActive;
+ if (!setActive || !objPtr || !setActive(objPtr, false)) return null;
try {
- m.FPDFBitmap_FillRect(bitmapPtr, 0, 0, w, h, 0xffffffff);
- // FPDF_REVERSE_BYTE_ORDER = 0x10, FPDF_ANNOT = 0x01
- m.FPDF_RenderPageBitmap(
- bitmapPtr,
- page.pagePtr,
- 0,
- 0,
- w,
- h,
- 0,
- 0x01 | 0x10,
- );
- page.shownInViewer = true;
+ return drawArea(doc, page, scale, area);
+ } finally {
+ setActive(objPtr, true);
+ }
+ }
+}
- // Second pass for the form layer. A widget with no appearance stream is
- // drawn ONLY here - FPDF_ANNOT alone leaves such fields blank, which is
- // why they were invisible in the editor but fine in the viewer.
- const formEnv = doc.formEnvironment();
- if (formEnv) {
- doc.notifyFormPageLoaded(page);
- const formMod = m as unknown as {
- FPDF_FFLDraw?: (
- env: number,
- bitmap: number,
- pagePtr: number,
- startX: number,
- startY: number,
- sizeX: number,
- sizeY: number,
- rotate: number,
- flags: number,
- ) => void;
- };
- try {
- formMod.FPDF_FFLDraw?.(
- formEnv,
- bitmapPtr,
- page.pagePtr,
- 0,
- 0,
- w,
- h,
- 0,
- 0x01 | 0x10,
- );
- } catch {
- /* the page content is already drawn; the form layer is additive */
- }
- }
+interface ActivityModule {
+ FPDFPageObj_SetIsActive?: (obj: number, active: boolean) => boolean;
+}
+
+function drawArea(
+ doc: EditorDocument,
+ page: Page,
+ scale: number,
+ area: PageRect,
+): ImageData {
+ const m = doc.module;
+ // No flush needed: rendering reads the in-memory objects; the page is offset to the area and clipped.
+ const full = PdfiumPageRenderer.rasterSize(page.width, page.height, scale);
+ const w = Math.max(1, area.width);
+ const h = Math.max(1, area.height);
+
+ // BGRA bitmap = format 1, fill white, then render with REVERSE_BYTE_ORDER
+ // so the pixel buffer is RGBA-ordered for ImageData.
+ const bitmapPtr = m.FPDFBitmap_Create(w, h, 1);
+ try {
+ m.FPDFBitmap_FillRect(bitmapPtr, 0, 0, w, h, 0xffffffff);
+ // FPDF_REVERSE_BYTE_ORDER = 0x10, FPDF_ANNOT = 0x01
+ m.FPDF_RenderPageBitmap(
+ bitmapPtr,
+ page.pagePtr,
+ -area.x,
+ -area.y,
+ full.width,
+ full.height,
+ 0,
+ 0x01 | 0x10,
+ );
+ page.shownInViewer = true;
- const bufferPtr = m.FPDFBitmap_GetBuffer(bitmapPtr);
- const stride = m.FPDFBitmap_GetStride(bitmapPtr);
- const pixels = new Uint8ClampedArray(w * h * 4);
- const heap = new Uint8Array(
- (m.pdfium.wasmExports as unknown as { memory: WebAssembly.Memory })
- .memory.buffer,
- bufferPtr,
- stride * h,
- );
- for (let y = 0; y < h; y++) {
- const srcRow = y * stride;
- const dstRow = y * w * 4;
- pixels.set(heap.subarray(srcRow, srcRow + w * 4), dstRow);
+ // Second pass for the form layer. A widget with no appearance stream is
+ // drawn ONLY here - FPDF_ANNOT alone leaves such fields blank, which is
+ // why they were invisible in the editor but fine in the viewer.
+ const formEnv = doc.formEnvironment();
+ if (formEnv) {
+ doc.notifyFormPageLoaded(page);
+ const formMod = m as unknown as {
+ FPDF_FFLDraw?: (
+ env: number,
+ bitmap: number,
+ pagePtr: number,
+ startX: number,
+ startY: number,
+ sizeX: number,
+ sizeY: number,
+ rotate: number,
+ flags: number,
+ ) => void;
+ };
+ try {
+ formMod.FPDF_FFLDraw?.(
+ formEnv,
+ bitmapPtr,
+ page.pagePtr,
+ -area.x,
+ -area.y,
+ full.width,
+ full.height,
+ 0,
+ 0x01 | 0x10,
+ );
+ } catch {
+ /* the page content is already drawn; the form layer is additive */
}
- return new ImageData(pixels, w, h);
- } finally {
- m.FPDFBitmap_Destroy(bitmapPtr);
}
+
+ const bufferPtr = m.FPDFBitmap_GetBuffer(bitmapPtr);
+ const stride = m.FPDFBitmap_GetStride(bitmapPtr);
+ const pixels = new Uint8ClampedArray(w * h * 4);
+ const heap = new Uint8Array(
+ (m.pdfium.wasmExports as unknown as { memory: WebAssembly.Memory }).memory
+ .buffer,
+ bufferPtr,
+ stride * h,
+ );
+ for (let y = 0; y < h; y++) {
+ const srcRow = y * stride;
+ const dstRow = y * w * 4;
+ pixels.set(heap.subarray(srcRow, srcRow + w * 4), dstRow);
+ }
+ return new ImageData(pixels, w, h);
+ } finally {
+ m.FPDFBitmap_Destroy(bitmapPtr);
}
}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/pdfium/PdfiumTagMarks.ts b/frontend/src/editor/core/tools/pdfTextEditor/pdfium/PdfiumTagMarks.ts
index b1662089f3..baa27e08ab 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/pdfium/PdfiumTagMarks.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/pdfium/PdfiumTagMarks.ts
@@ -283,6 +283,17 @@ export function copyTagMarks(
applyTagMarks(m, docPtr, [to], readTagMarks(m, from));
}
+/** Names of the marked-content sequences `obj` is drawn inside. */
+export function markNamesOf(m: WrappedPdfiumModule, obj: number): string[] {
+ const names: string[] = [];
+ const count = m.FPDFPageObj_CountMarks(obj);
+ for (let i = 0; i < count; i++) {
+ const mark = m.FPDFPageObj_GetMark(obj, i);
+ if (mark) names.push(markName(m, mark));
+ }
+ return names;
+}
+
function markName(m: WrappedPdfiumModule, mark: number): string {
const lenPtr = scratchPtr(m, SCRATCH.tagNameLen, 4);
if (!m.FPDFPageObjMark_GetName(mark, 0, 0, lenPtr)) return "";
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/pdfium/PdfiumTextReader.ts b/frontend/src/editor/core/tools/pdfTextEditor/pdfium/PdfiumTextReader.ts
index 8c4c7a6079..6f1d1e8b15 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/pdfium/PdfiumTextReader.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/pdfium/PdfiumTextReader.ts
@@ -1,3 +1,9 @@
+import { claimFormNodes } from "@editor/tools/pdfTextEditor/commands/liftFromForm";
+import {
+ readPageGlyphs,
+ type PageGlyphs,
+} from "@editor/tools/pdfTextEditor/pdfium/drawnGlyphs";
+import { readObjectTexts } from "@editor/tools/pdfTextEditor/pdfium/objectTexts";
import {
drawnCodePoint,
drawnText,
@@ -5,26 +11,31 @@ import {
import type { WrappedPdfiumModule } from "@embedpdf/pdfium";
import { TextRun } from "@editor/tools/pdfTextEditor/model/TextRun";
import { ImageObject } from "@editor/tools/pdfTextEditor/model/ImageObject";
+import { readImageClip } from "@editor/tools/pdfTextEditor/util/imageClip";
import { ShapeObject } from "@editor/tools/pdfTextEditor/model/ShapeObject";
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 {
LineGrouper,
+ lineFontIds,
type BlockKey,
} from "@editor/tools/pdfTextEditor/pdfium/LineGrouper";
import { ParagraphGrouper } from "@editor/tools/pdfTextEditor/pdfium/ParagraphGrouper";
import { PdfiumAnnotationReader } from "@editor/tools/pdfTextEditor/pdfium/PdfiumAnnotationReader";
import { primeFontGlyphMap } from "@editor/tools/pdfTextEditor/charcode/CmapResolver";
-import type {
- Affine,
- GroupingMode,
- PageRect,
- PageRuleSnapshot,
- RGBA,
+import {
+ RENDER_MODE_INVISIBLE,
+ type Affine,
+ type GroupingMode,
+ type PageRect,
+ type PageRuleSnapshot,
+ type RGBA,
} from "@editor/tools/pdfTextEditor/types";
import { readUtf16 } from "@editor/services/pdfiumService";
+import { hasRtl } from "@editor/tools/pdfTextEditor/util/bidi";
import { registerEmbeddedFace } from "@editor/tools/pdfTextEditor/util/embeddedFace";
+import { noteDocumentFontStyle } from "@editor/tools/pdfTextEditor/util/documentFontStyle";
import {
SCRATCH,
scratchPtr,
@@ -64,6 +75,7 @@ export class PdfiumTextReader {
): void {
if (page.loaded) return;
doc.claimArtifactMarks(page.index);
+ claimFormNodes(doc, page);
const m = doc.module;
const pagePtr = page.pagePtr;
const count = m.FPDFPage_CountObjects(pagePtr);
@@ -73,6 +85,7 @@ export class PdfiumTextReader {
const rules: PageRuleSnapshot[] = [];
const fills: PageRuleSnapshot[] = [];
const shapes: ShapeObject[] = [];
+ const companions = new Map<number, number[]>();
// ONE text page for the whole walk: FPDFText_LoadPage runs full page text
// extraction, so opening it per text object made population O.
@@ -95,6 +108,7 @@ export class PdfiumTextReader {
0,
IDENTITY,
textPagePtr,
+ companions,
);
page.setRuns(runs);
@@ -105,9 +119,14 @@ 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);
- groupAndMeasure(doc, page, mode, textPagePtr);
+ markHiddenText(runs, [
+ ...images.map((image) => image.bounds),
+ ...shapes.map((shape) => shape.bounds),
+ ...fills,
+ ]);
+ groupAndMeasure(doc, page, mode, textPagePtr, companions);
} finally {
- m.FPDFText_ClosePage(textPagePtr);
+ closeTextPage(m, textPagePtr);
}
page.loaded = true;
}
@@ -143,9 +162,14 @@ export class PdfiumTextReader {
return [run];
}),
);
- groupAndMeasure(doc, scratch, mode, textPagePtr);
+ markHiddenText(scratch.runs, [
+ ...page.images.map((image) => image.bounds),
+ ...page.shapes.map((shape) => shape.bounds),
+ ...page.fills,
+ ]);
+ groupAndMeasure(doc, scratch, mode, textPagePtr, new Map());
} finally {
- m.FPDFText_ClosePage(textPagePtr);
+ closeTextPage(m, textPagePtr);
}
return scratch.runs;
}
@@ -164,7 +188,7 @@ export class PdfiumTextReader {
const geometry = collectCharGeometry(m, page, textPagePtr);
return geometry ? captureCharPositions(geometry) : new Set();
} finally {
- m.FPDFText_ClosePage(textPagePtr);
+ closeTextPage(m, textPagePtr);
}
}
}
@@ -178,12 +202,34 @@ function groupAndMeasure(
page: Page,
mode: GroupingMode,
textPagePtr: number,
+ companions: ReadonlyMap<number, readonly 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);
+ const lines = LineGrouper.apply(
+ page,
+ blockKey,
+ (run) => fontSpaceAdvanceEm(doc.module, run.pdfiumObjPtr),
+ {
+ // Only a page with right-to-left text is read by glyph, so every other page costs no second walk.
+ glyphs: page.runs.some((run) => hasRtl(run.text))
+ ? glyphsWithCompanions(doc.module, page, textPagePtr, companions)
+ : null,
+ companions,
+ },
+ );
+ if (mode === "auto") {
+ const faces = new Map<string, string | null>();
+ ParagraphGrouper.apply(page, blockKey, lineFontIds(lines), (fontId) => {
+ let face = faces.get(fontId);
+ if (face === undefined) {
+ face = faceNameOf(doc.module, fontId);
+ faces.set(fontId, face);
+ }
+ return face;
+ });
+ }
// 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);
@@ -193,6 +239,41 @@ function groupAndMeasure(
}
}
+// A glyph cluster drawn by several objects reaches as far as they do: the text page places it by the one object it gives the text to, which can be a vowel mark alone.
+function glyphsWithCompanions(
+ m: WrappedPdfiumModule,
+ page: Page,
+ textPagePtr: number,
+ companions: ReadonlyMap<number, readonly number[]>,
+): PageGlyphs | null {
+ const glyphs = readPageGlyphs(m, textPagePtr);
+ if (!glyphs) return null;
+ for (const run of page.runs) {
+ const own = glyphs.byObject.get(run.pdfiumObjPtr);
+ const rest = companions.get(run.pdfiumObjPtr);
+ if (!rest || own?.length !== 1 || run.containerPtr !== 0) continue;
+ for (const ptr of rest) {
+ const bounds = readBounds(m, ptr);
+ if (!bounds) continue;
+ own[0].left = Math.min(own[0].left, bounds.x);
+ own[0].right = Math.max(own[0].right, bounds.x + bounds.width);
+ }
+ }
+ return glyphs;
+}
+
+function fontSpaceAdvanceEm(
+ m: WrappedPdfiumModule,
+ objPtr: number,
+): number | null {
+ const fontPtr = objPtr ? m.FPDFTextObj_GetFont(objPtr) : 0;
+ if (!fontPtr) return null;
+ const widthPtr = scratchPtr(m, SCRATCH.readerSpaceWidth, 4);
+ // Font size 1 makes PDFium report the width in ems.
+ if (!m.FPDFFont_GetGlyphWidth(fontPtr, 0x20, 1, widthPtr)) return null;
+ return m.pdfium.getValue(widthPtr, "float");
+}
+
/** Every backing PDFium object pointer mapped to its post-grouping run. */
function indexRunsByObjectPtr(runs: TextRun[]): Map<number, TextRun> {
const map = new Map<number, TextRun>();
@@ -480,6 +561,71 @@ type PdfiumWithForms = WrappedPdfiumModule & {
FPDFFormObj_GetObject: (formObj: number, index: number) => number;
};
+const ACTUAL_TEXT = "ActualText";
+const FPDF_OBJECT_UNKNOWN = 0;
+
+/** The innermost mark on the object when it replaces the object's text with an ActualText, else 0. */
+function actualTextMark(m: WrappedPdfiumModule, objPtr: number): number {
+ const count = m.FPDFPageObj_CountMarks(objPtr);
+ if (count <= 0) return 0;
+ const mark = m.FPDFPageObj_GetMark(objPtr, count - 1);
+ if (!mark) return 0;
+ return m.FPDFPageObjMark_GetParamValueType(mark, ACTUAL_TEXT) ===
+ FPDF_OBJECT_UNKNOWN
+ ? 0
+ : mark;
+}
+
+/**
+ * The text objects inside one ActualText span, as a walk passes them. PDFium
+ * gives the span's whole text to one of its objects and none to the others,
+ * which would then belong to no run: a letter drawn apart from its vowel mark
+ * stays on the page when its line is moved, deleted or redrawn. It gives the
+ * text to a second object as well when something else on the line sorts
+ * between the two, and read as a run of its own that one would double the
+ * span's letters.
+ */
+class ActualTextSpan {
+ private mark = 0;
+ private owner = 0;
+ private ownerText = "";
+ private rest: number[] = [];
+
+ constructor(private readonly companions: Map<number, number[]>) {}
+
+ /**
+ * Whether the object repeats the text the span's first run already holds, so
+ * it is a companion of that run and not a run itself. `runText` is the text
+ * the object reads as a run, or null when it reads as none.
+ */
+ take(
+ objPtr: number,
+ mark: number,
+ runText: string | null,
+ hasNoText: (objPtr: number) => boolean,
+ ): boolean {
+ if (mark !== this.mark) {
+ this.mark = mark;
+ this.owner = 0;
+ this.ownerText = "";
+ this.rest = [];
+ }
+ if (mark === 0) return false;
+ const first = runText !== null && this.owner === 0;
+ const repeats =
+ runText !== null && !first && runText.trim() === this.ownerText;
+ if (first) {
+ this.owner = objPtr;
+ this.ownerText = runText.trim();
+ } else if (repeats || (runText === null && hasNoText(objPtr))) {
+ this.rest.push(objPtr);
+ }
+ if (this.owner && this.rest.length > 0)
+ this.companions.set(this.owner, this.rest);
+ return repeats;
+ }
+}
+
function walkObjects(
m: WrappedPdfiumModule,
pagePtr: number,
@@ -495,6 +641,7 @@ function walkObjects(
depth: number,
transform: Affine,
textPagePtr: number,
+ companions: Map<number, number[]>,
): void {
const MAX_DEPTH = 4;
const formModule = m as PdfiumWithForms;
@@ -504,6 +651,7 @@ function walkObjects(
path.length === 0 ? 0 : getFormContainer(m, pagePtr, path);
const topLevelContainerPtr =
path.length === 0 ? 0 : m.FPDFPage_GetObject(pagePtr, path[0]);
+ const span = new ActualTextSpan(companions);
for (let i = 0; i < count; i++) {
const objPtr =
path.length === 0
@@ -522,7 +670,13 @@ function walkObjects(
transform,
textPagePtr,
);
- if (run) {
+ const repeatsSpanText = span.take(
+ objPtr,
+ actualTextMark(m, objPtr),
+ run?.text ?? null,
+ (ptr) => readTextObjString(m, textPagePtr, ptr) === "",
+ );
+ if (run && !repeatsSpanText) {
run.containerPtr = containerPtr;
run.topLevelContainerPtr = topLevelContainerPtr;
// A form's MCIDs resolve against its own /StructParents, not the
@@ -540,10 +694,14 @@ function walkObjects(
if (path.length <= 1) {
// PDFium can save shape removals only in page-level forms.
const indexId = [...path, i].join("-");
- const shape = readShape(m, page, objPtr, indexId, transform, {
+ const shape = readShape(
+ m,
+ page,
+ objPtr,
+ indexId,
+ transform,
containerPtr,
- topLevelContainerPtr,
- });
+ );
if (shape) shapes.push(shape);
}
} else if (type === FPDF_PAGEOBJ_IMAGE) {
@@ -584,6 +742,7 @@ function walkObjects(
depth + 1,
childTransform,
textPagePtr,
+ companions,
);
}
}
@@ -901,6 +1060,26 @@ function readMatrix(m: WrappedPdfiumModule, objPtr: number): Affine {
/** Render modes that actually put stroke ink on the page. */
const STROKING_MODES = new Set([1, 2, 5, 6]);
+// OCR text over a scan is edited by redrawing the ink behind it, a picture or
+// letters drawn as outlines; invisible text with nothing drawn behind it has no
+// ink to redraw and is edited as text.
+function markHiddenText(
+ runs: readonly TextRun[],
+ drawn: readonly PageRect[],
+): void {
+ for (const run of runs) {
+ if (run.renderMode !== RENDER_MODE_INVISIBLE) continue;
+ const r = run.bounds;
+ run.hiddenText = !drawn.some(
+ (b) =>
+ b.x < r.x + r.width &&
+ b.x + b.width > r.x &&
+ b.y < r.y + r.height &&
+ b.y + b.height > r.y,
+ );
+ }
+}
+
// Outline colour and width, or null when the object does not stroke. PDFium
// reports a stroke colour for every text object, so the render mode decides.
function readStroke(
@@ -914,11 +1093,23 @@ function readStroke(
return { stroke, strokeWidth: readStrokeWidth(m, objPtr) };
}
+// Per text page, so a page is walked once however many objects are read from it; dropped when the page closes.
+const objectTextsByPage = new Map<number, Map<number, string> | null>();
+
+function closeTextPage(m: WrappedPdfiumModule, textPagePtr: number): void {
+ objectTextsByPage.delete(textPagePtr);
+ m.FPDFText_ClosePage(textPagePtr);
+}
+
function readTextObjString(
m: WrappedPdfiumModule,
textPagePtr: number,
objPtr: number,
): string {
+ if (!objectTextsByPage.has(textPagePtr))
+ objectTextsByPage.set(textPagePtr, readObjectTexts(m, textPagePtr));
+ const texts = objectTextsByPage.get(textPagePtr);
+ if (texts) return drawnText(texts.get(objPtr) ?? "");
// First call returns size in bytes for the UTF-16 buffer (including NUL).
const len = m.FPDFTextObj_GetText(objPtr, textPagePtr, 0, 0);
if (len <= 2) return "";
@@ -943,6 +1134,14 @@ function readFontNameVia(
return m.pdfium.UTF8ToString(buf);
}
+/** The face's /BaseFont without its subset tag ("Georgia-Bold"), or null when the font has none. */
+function faceNameOf(m: WrappedPdfiumModule, fontId: string): string | null {
+ const ptr = Number(/^pdf:(\d+)/.exec(fontId)?.[1]);
+ if (!ptr) return null;
+ const name = readFontNameVia(m, ptr, m.FPDFFont_GetBaseFontName);
+ return name == null ? null : SUBSET_TAG_RE.test(name) ? name.slice(7) : name;
+}
+
function readFontFamily(
m: WrappedPdfiumModule,
fontPtr: number,
@@ -1008,6 +1207,7 @@ function readTextRun(
if (fontPtr) primeFontGlyphMap(fontPtr, m);
// Make the same face available to the overlay as a CSS FontFace.
if (fontPtr) registerEmbeddedFace(m, fontPtr);
+ noteDocumentFontStyle(m, fontPtr, family);
// Treat the PDFium font handle pointer as a unique id within the doc.
const fontId = fontPtr ? `pdf:${fontPtr}` : `pdf:unknown-${id}`;
@@ -1061,7 +1261,7 @@ function readShape(
objPtr: number,
index: number | string,
transform: Affine,
- containers: { containerPtr: number; topLevelContainerPtr: number },
+ containerPtr: number,
): ShapeObject | null {
if (!isPainted(m, objPtr)) return null;
const localBounds = readBounds(m, objPtr);
@@ -1077,8 +1277,7 @@ function readShape(
id: `p${page.index}-s${index}`,
pageIndex: page.index,
pdfiumObjPtr: objPtr,
- ...containers,
- containerTransform: transform,
+ containerPtr,
bounds,
});
}
@@ -1118,6 +1317,7 @@ function readImage(
containerPtr,
mcid: tags.mcid ?? undefined,
artifact: tags.artifact || undefined,
+ clip: readImageClip(m, page.pagePtr, objPtr, containerPtr) ?? undefined,
});
}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/pdfium/drawnGlyphs.ts b/frontend/src/editor/core/tools/pdfTextEditor/pdfium/drawnGlyphs.ts
new file mode 100644
index 0000000000..8f13926093
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/pdfium/drawnGlyphs.ts
@@ -0,0 +1,136 @@
+/**
+ * What a page draws, glyph by glyph, with where each sits. PDFium's text page
+ * lists a line's characters in its own guess at reading order, which reverses
+ * words and digit groups on lines mixing directions; the pen positions it
+ * reports are the page's own, so a line read from them is in drawn order.
+ */
+import type { WrappedPdfiumModule } from "@embedpdf/pdfium";
+import {
+ drawnCodePoint,
+ drawnText,
+} from "@editor/tools/pdfTextEditor/pdfium/lineEndHyphen";
+import type { CharOriginModule } from "@editor/tools/pdfTextEditor/pdfium/objectTexts";
+import { hasRtl } from "@editor/tools/pdfTextEditor/util/bidi";
+import {
+ SCRATCH,
+ scratchPtr,
+} from "@editor/tools/pdfTextEditor/util/wasmScratch";
+
+export interface DrawnGlyph {
+ /** What the glyph says, in reading order: a letter with its marks, or the letters of a ligature. */
+ text: string;
+ /** The pen position it is drawn from. */
+ left: number;
+ /** Where its advance ends. */
+ right: number;
+ baseline: number;
+}
+
+/** A space drawn as an object of its own. */
+export interface SpaceGlyph extends DrawnGlyph {
+ ptr: number;
+}
+
+export interface PageGlyphs {
+ /** Each text object's glyphs, in the order the text page lists them. */
+ byObject: Map<number, DrawnGlyph[]>;
+ /** The objects that draw one space and nothing else. */
+ spaces: SpaceGlyph[];
+}
+
+interface GlyphModule extends CharOriginModule {
+ FPDFText_GetLooseCharBox?: (tp: number, i: number, rect: number) => boolean;
+}
+
+interface PlacedChar {
+ char: string;
+ x: number;
+ y: number;
+ boxLeft: number;
+ boxRight: number;
+}
+
+const SAME_PEN_PT = 0.01;
+const MARK = /\p{M}/u;
+
+// Characters sharing a pen position are one glyph's ActualText or ToUnicode string. PDFium hands a right-to-left ligature's letters back to front when it slices the glyph's box between them, left to right.
+function glyphText(chars: readonly PlacedChar[]): string {
+ const text = chars.map(({ char }) => char).join("");
+ const letters = chars.filter(({ char }) => !MARK.test(char));
+ const sliced = chars.every(
+ (c, i) => i === 0 || c.boxLeft > chars[i - 1].boxLeft + SAME_PEN_PT,
+ );
+ if (letters.length > 1 && sliced && hasRtl(text))
+ return chars
+ .map(({ char }) => char)
+ .reverse()
+ .join("");
+ return drawnText(text);
+}
+
+function glyphsOf(chars: readonly PlacedChar[]): DrawnGlyph[] {
+ const glyphs: DrawnGlyph[] = [];
+ let start = 0;
+ for (let i = 1; i <= chars.length; i++) {
+ const first = chars[start];
+ if (
+ i < chars.length &&
+ Math.abs(chars[i].x - first.x) < SAME_PEN_PT &&
+ Math.abs(chars[i].y - first.y) < SAME_PEN_PT
+ )
+ continue;
+ const cluster = chars.slice(start, i);
+ glyphs.push({
+ text: glyphText(cluster),
+ left: first.x,
+ right: Math.max(first.x, ...cluster.map(({ boxRight }) => boxRight)),
+ baseline: first.y,
+ });
+ start = i;
+ }
+ return glyphs;
+}
+
+/** The glyphs of every text object on a text page; null when this build cannot place a character. */
+export function readPageGlyphs(
+ m: WrappedPdfiumModule,
+ textPagePtr: number,
+): PageGlyphs | null {
+ const probe = m as unknown as GlyphModule;
+ const origin = probe.FPDFText_GetCharOrigin;
+ const looseBox = probe.FPDFText_GetLooseCharBox;
+ if (!origin || !looseBox || typeof m.FPDFText_GetTextObject !== "function")
+ return null;
+ const rect = scratchPtr(m, SCRATCH.readerCharRect, 16);
+ const xPtr = scratchPtr(m, SCRATCH.readerCharX, 8);
+ const yPtr = scratchPtr(m, SCRATCH.readerCharY, 8);
+ const chars = new Map<number, PlacedChar[]>();
+ const count = m.FPDFText_CountChars(textPagePtr);
+ for (let i = 0; i < count; i++) {
+ const ptr = m.FPDFText_GetTextObject(textPagePtr, i);
+ if (!ptr || m.FPDFText_IsGenerated(textPagePtr, i) === 1) continue;
+ const codePoint = drawnCodePoint(m.FPDFText_GetUnicode(textPagePtr, i));
+ if (!codePoint || !origin(textPagePtr, i, xPtr, yPtr)) continue;
+ const x = m.pdfium.getValue(xPtr, "double");
+ const y = m.pdfium.getValue(yPtr, "double");
+ const boxed = looseBox(textPagePtr, i, rect);
+ const list = chars.get(ptr) ?? [];
+ if (list.length === 0) chars.set(ptr, list);
+ list.push({
+ char: String.fromCodePoint(codePoint),
+ x,
+ y,
+ boxLeft: boxed ? m.pdfium.getValue(rect, "float") : x,
+ boxRight: boxed ? m.pdfium.getValue(rect + 8, "float") : x,
+ });
+ }
+ const byObject = new Map<number, DrawnGlyph[]>();
+ const spaces: SpaceGlyph[] = [];
+ for (const [ptr, placed] of chars) {
+ const glyphs = glyphsOf(placed);
+ byObject.set(ptr, glyphs);
+ if (glyphs.length === 1 && glyphs[0].text.trim() === "")
+ spaces.push({ ...glyphs[0], ptr });
+ }
+ return { byObject, spaces };
+}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/pdfium/drawnLine.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/pdfium/drawnLine.test.ts
new file mode 100644
index 0000000000..897a92aba7
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/pdfium/drawnLine.test.ts
@@ -0,0 +1,60 @@
+import { describe, expect, test } from "vitest";
+import type { DrawnGlyph } from "@editor/tools/pdfTextEditor/pdfium/drawnGlyphs";
+import { readDrawnLine } from "@editor/tools/pdfTextEditor/pdfium/drawnLine";
+
+const WIDTH = 6;
+
+// One object per string, set left to right with no gaps unless `gapBefore` names the object.
+function objects(texts: string[], gapBefore = -1): DrawnGlyph[][] {
+ let pen = 0;
+ return texts.map((text, i) => {
+ if (i === gapBefore) pen += WIDTH;
+ return [...text].map((char) => {
+ const glyph = { text: char, left: pen, right: pen + WIDTH, baseline: 0 };
+ pen += WIDTH;
+ return glyph;
+ });
+ });
+}
+
+const read = (drawn: DrawnGlyph[][]) =>
+ readDrawnLine(drawn, [], 12, (gapPt) => (gapPt > 2 ? 1 : 0));
+
+describe("readDrawnLine", () => {
+ test("reads right-to-left objects from the right and a number among them left to right", () => {
+ const line = read(objects(["ג", "1", "2", "ב", "א"]));
+
+ expect(line.text).toBe("אב12ג");
+ expect(line.faithful).toBe(true);
+ expect(line.spans.map(({ start }) => start)).toEqual([4, 2, 3, 1, 0]);
+ });
+
+ test("keeps the letters of one left-to-right object in the order they are drawn", () => {
+ const line = read(objects(["ב", "ISO 50001", "א"]));
+
+ expect(line.text).toBe("אISO 50001ב");
+ expect(line.spans[1]).toEqual({ start: 1, end: 10 });
+ });
+
+ test("turns a pair of brackets reported facing the same way to face each other", () => {
+ expect(read(objects(["(", "ב", "א", "("])).text).toBe("(אב)");
+ expect(read(objects([")", "1", "2", "("])).text).toBe("(12)");
+ });
+
+ test("reads a gap between two objects as a space", () => {
+ expect(read(objects(["ב", "א"], 1)).text).toBe("א ב");
+ });
+
+ test("puts a mark drawn as its own object after the letter it sits on", () => {
+ const [letter] = objects(["ש"]);
+ const mark = [{ text: "ָ", left: 3, right: 3, baseline: 0 }];
+
+ const line = read([mark, letter]);
+
+ expect(line.text).toBe("שָ");
+ expect(line.spans).toEqual([
+ { start: 2, end: 2 },
+ { start: 0, end: 2 },
+ ]);
+ });
+});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/pdfium/drawnLine.ts b/frontend/src/editor/core/tools/pdfTextEditor/pdfium/drawnLine.ts
new file mode 100644
index 0000000000..7b8e8aa6b0
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/pdfium/drawnLine.ts
@@ -0,0 +1,170 @@
+import type {
+ DrawnGlyph,
+ SpaceGlyph,
+} from "@editor/tools/pdfTextEditor/pdfium/drawnGlyphs";
+import { readingOrder } from "@editor/tools/pdfTextEditor/util/bidi";
+
+export interface DrawnLine {
+ /** The line in reading order. */
+ text: string;
+ /** For each object, the stretch of `text` it draws; an object whose glyphs all sit on another's letters has an empty one after them. */
+ spans: Array<{ start: number; end: number }>;
+ /** The space objects between the line's glyphs, each with the code unit of `text` it draws. */
+ spaces: Array<{ ptr: number; start: number }>;
+ /** False when redrawing `text` would not put every glyph back where it is, or an object's glyphs are not one stretch of it. */
+ faithful: boolean;
+}
+
+/** A glyph of a line with the index of the object drawing it. */
+export interface PlacedGlyph extends DrawnGlyph {
+ object: number;
+}
+
+const ALL_MARKS = /^\p{M}+$/u;
+const SAME_LINE_EM = 0.25;
+
+/**
+ * The glyphs of a line's objects from left to right. A mark drawn as an
+ * object of its own belongs to the letter whose advance it sits in, wherever
+ * its pen position sorts: it is folded into that letter, and `riders` gives
+ * the letter for each object left without a glyph.
+ */
+export function placeGlyphs(objects: ReadonlyArray<readonly DrawnGlyph[]>): {
+ glyphs: PlacedGlyph[];
+ riders: Map<number, PlacedGlyph>;
+} {
+ const placed = objects
+ .flatMap((glyphs, object) => glyphs.map((g) => ({ ...g, object })))
+ .sort((a, b) => a.left - b.left);
+ const letters = placed.filter(({ text }) => !ALL_MARKS.test(text));
+ const riders = new Map<number, PlacedGlyph>();
+ if (letters.length === 0) return { glyphs: placed, riders };
+ for (const mark of placed) {
+ if (!ALL_MARKS.test(mark.text)) continue;
+ let host = letters[0];
+ for (const letter of letters) {
+ if (mark.left >= letter.left && mark.left <= letter.right) {
+ host = letter;
+ break;
+ }
+ if (Math.abs(letter.left - mark.left) < Math.abs(host.left - mark.left))
+ host = letter;
+ }
+ host.text += mark.text;
+ if (!letters.some((letter) => letter.object === mark.object))
+ riders.set(mark.object, host);
+ }
+ return { glyphs: letters, riders };
+}
+
+const BRACKET_PAIRS = ["()", "[]", "{}"];
+
+function nests(brackets: readonly string[], open: string): boolean {
+ let depth = 0;
+ for (const bracket of brackets) {
+ depth += bracket === open ? 1 : -1;
+ if (depth < 0) return false;
+ }
+ return depth === 0;
+}
+
+// Drawn left to right, a pair always opens on the left whichever way its text reads. PDFium reports some bracket glyphs by the character they stand for and mirrors others, so a pair it turned is turned back to how it must be drawn.
+function facePairedBrackets(drawn: PlacedGlyph[]): void {
+ for (const [open, close] of BRACKET_PAIRS) {
+ const found = drawn.filter(({ text }) => text === open || text === close);
+ const faces = found.map(({ text }) => text);
+ if (found.length % 2 === 1 || nests(faces, open)) continue;
+ const turned = faces.map((face) => (face === open ? close : open));
+ found.forEach((glyph, i) => {
+ glyph.text = nests(turned, open) ? turned[i] : i % 2 === 0 ? open : close;
+ });
+ }
+}
+
+/**
+ * Read one line from where its glyphs are drawn. `objects` holds each of the
+ * line's objects' glyphs, `spaces` the page's space glyphs drawn as objects of
+ * their own, and `gapSpaces` says how many spaces a gap between two glyphs
+ * with no space glyph in it stands for.
+ */
+export function readDrawnLine(
+ objects: ReadonlyArray<readonly DrawnGlyph[]>,
+ spaces: readonly SpaceGlyph[],
+ fontSize: number,
+ gapSpaces: (gapPt: number) => number,
+): DrawnLine {
+ const { glyphs: letters, riders } = placeGlyphs(objects);
+ const drawn: Array<PlacedGlyph & { ptr?: number }> = [];
+ letters.forEach((glyph, i) => {
+ const before = letters[i - 1];
+ if (before) {
+ const between = spaces.filter(
+ (space) =>
+ space.left > before.left &&
+ space.left < glyph.left &&
+ Math.abs(space.baseline - glyph.baseline) < SAME_LINE_EM * fontSize,
+ );
+ for (const space of between) drawn.push({ ...space, object: -1 });
+ const inferred =
+ between.length > 0 ? 0 : gapSpaces(glyph.left - before.right);
+ for (let k = 0; k < inferred; k++)
+ drawn.push({
+ text: " ",
+ object: -1,
+ left: before.right,
+ right: glyph.left,
+ baseline: glyph.baseline,
+ });
+ }
+ drawn.push(glyph);
+ });
+
+ facePairedBrackets(drawn);
+ const read = readingOrder(drawn.map(({ text }) => text));
+ const starts: number[] = [];
+ let text = "";
+ read.order.forEach((unit, k) => {
+ drawn[unit].text = read.texts[k];
+ starts[unit] = text.length;
+ text += read.texts[k];
+ });
+
+ let faithful = read.faithful;
+ const spans = objects.map((_, object) => {
+ const own = drawn.flatMap((glyph, unit) =>
+ glyph.object === object ? [unit] : [],
+ );
+ if (own.length === 0) {
+ const host = riders.get(object);
+ if (!host) faithful = false;
+ const at = host
+ ? starts[drawn.indexOf(host)] + host.text.length
+ : text.length;
+ return { start: at, end: at };
+ }
+ return {
+ start: Math.min(...own.map((unit) => starts[unit])),
+ end: Math.max(
+ ...own.map((unit) => starts[unit] + drawn[unit].text.length),
+ ),
+ };
+ });
+ drawn.forEach((glyph, unit) => {
+ if (glyph.object < 0) return;
+ const inside = spans.some(
+ (span, object) =>
+ object !== glyph.object &&
+ starts[unit] >= span.start &&
+ starts[unit] < span.end,
+ );
+ if (inside) faithful = false;
+ });
+ return {
+ text,
+ spans,
+ spaces: drawn.flatMap((glyph, unit) =>
+ glyph.ptr ? [{ ptr: glyph.ptr, start: starts[unit] }] : [],
+ ),
+ faithful,
+ };
+}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/pdfium/lineBreaks.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/pdfium/lineBreaks.test.ts
new file mode 100644
index 0000000000..3a8e9afde4
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/pdfium/lineBreaks.test.ts
@@ -0,0 +1,120 @@
+import { describe, expect, it } from "vitest";
+import {
+ softLineStarts,
+ softStartsFor,
+} from "@editor/tools/pdfTextEditor/pdfium/lineBreaks";
+import { joinSoftLines } from "@editor/tools/pdfTextEditor/commands/scanLayout";
+
+const CHAR = 5;
+const line = (text: string, left = 0) => ({
+ text,
+ left,
+ right: left + text.length * CHAR,
+ fontSize: 10,
+});
+
+describe("softLineStarts", () => {
+ it("reads a line that ends at the margin as wrapped and a short one as ended", () => {
+ expect(
+ softLineStarts([
+ line("the quick brown fox jumps"),
+ line("over the lazy dog and"),
+ line("runs."),
+ line("A new sentence starts here"),
+ ]),
+ ).toEqual([false, true, true, false]);
+ });
+
+ it("keeps list items, table rows and indented lines apart", () => {
+ expect(
+ softLineStarts([
+ line("an item of the list goes"),
+ line("- second item of the list"),
+ line("indented continuation", 20),
+ line("| North | 4,100 | 3,950 |"),
+ line("| East | 7,520 | 6,880 |"),
+ ]),
+ ).toEqual([false, false, false, false, false]);
+ });
+
+ it("keeps a hyphenated line end, since joining cannot tell which hyphen to drop", () => {
+ expect(
+ softLineStarts([
+ line("a word that ends hyph-"),
+ line("enated at the margin of it"),
+ ]),
+ ).toEqual([false, false]);
+ });
+
+ it("keeps two short lines apart when the column's margin is further right", () => {
+ expect(
+ softLineStarts(
+ [line("First bullet item"), line("Second bullet item")],
+ 300,
+ ),
+ ).toEqual([false, false]);
+ });
+});
+
+describe("softStartsFor", () => {
+ it("keeps flags across typing before and after a break, and reads a typed break as hard", () => {
+ const flagged = "one two\nthree four\nfive";
+ const flags = [false, true, false];
+ expect(softStartsFor("one two!\nthree four\nfive", flagged, flags)).toEqual(
+ flags,
+ );
+ expect(
+ softStartsFor("one two\nthree\n four\nfive", flagged, flags),
+ ).toEqual([false, true, false, false]);
+ });
+
+ it("keeps an Enter typed next to a space hard, and a break that moved with a typed letter soft", () => {
+ expect(softStartsFor("one\n two three", "one two three", [])).toEqual([
+ false,
+ false,
+ ]);
+ expect(softStartsFor("one two\nthreex", "one two three", [])).toEqual([
+ false,
+ true,
+ ]);
+ });
+
+ it("keeps a rewrap's breaks soft and a typed break hard when both happened since", () => {
+ expect(
+ softStartsFor(
+ "one\ntwo three\nfour five\nsix",
+ "one two three four five six",
+ [false, false, false],
+ )
+ .map(String)
+ .join(),
+ ).toBe("false,true,true,true");
+ expect(
+ softStartsFor("one\ntwo three\n\nfour", "one two three four", []),
+ ).toEqual([false, true, true, false]);
+ });
+
+ it("reads a break that replaced a space as a rewrap's", () => {
+ expect(softStartsFor("one\ntwo three", "one two three", [])).toEqual([
+ false,
+ true,
+ ]);
+ });
+});
+
+describe("joinSoftLines", () => {
+ const upTo = (n: number) => (text: string) => text.length <= n;
+
+ it("pulls words up across soft breaks only, keeping every offset", () => {
+ const text = "one two\nthree four\nfive six";
+ const joined = joinSoftLines(text, [false, true, false], upTo(14));
+ expect(joined).toBe("one two three\nfour\nfive six");
+ expect(joined.length).toBe(text.length);
+ });
+
+ it("joins a whole line when only spaces follow its word", () => {
+ expect(
+ joinSoftLines("one\ntwo \nthree", [false, true, false], () => true),
+ ).toBe("one two \nthree");
+ });
+});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/pdfium/lineBreaks.ts b/frontend/src/editor/core/tools/pdfTextEditor/pdfium/lineBreaks.ts
new file mode 100644
index 0000000000..18881fc103
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/pdfium/lineBreaks.ts
@@ -0,0 +1,172 @@
+/**
+ * Tells the line breaks a document came with apart: soft where the producer
+ * wrapped a line because the next word would not fit before the margin, hard
+ * where the author ended the line. A reflow joins soft breaks and keeps hard
+ * ones, so widening a box rejoins only what the margin split.
+ *
+ * Unsure cases read hard, since a wrongly joined line is a visible edit the
+ * user did not ask for and a wrongly kept break is just today's behaviour.
+ */
+
+export interface BreakLine {
+ text: string;
+ left: number;
+ right: number;
+ fontSize: number;
+}
+
+const SPACE_EM = 0.25;
+const FIT_SLACK_EM = 0.3;
+const LEFT_TOLERANCE_EM = 0.6;
+const MIN_LEFT_TOLERANCE_PT = 3;
+
+const ITEM_OR_ROW_START =
+ /^\s*(?:[•·▪‣◦●○■□►➢✓✔*\-–—|]\s|\+[-=]|\(?(?:\d{1,3}|[a-z]|[ivxlc]{1,5})[.)]\s)/i;
+// A hyphen or soft hyphen at a line end may belong to the word ("well-
+// known") or only to the hyphenation; joining cannot tell which to keep.
+const ENDS_IN_HYPHEN = /[-­‐‑]\s*$/;
+
+/**
+ * One flag per line, true when the line starts at a soft break. Line 0 is
+ * never soft. `marginRight` is the right edge the column's text wraps at; the
+ * widest line of `lines` is used when it reaches further.
+ */
+export function softLineStarts(
+ lines: readonly BreakLine[],
+ marginRight = -Infinity,
+): boolean[] {
+ const flags = lines.map(() => false);
+ if (lines.length < 2) return flags;
+ const margin = Math.max(marginRight, ...lines.map((l) => l.right));
+ const bodyLeft = medianOf(lines.slice(1).map((l) => l.left));
+ for (let i = 1; i < lines.length; i++) {
+ const above = lines[i - 1];
+ const line = lines[i];
+ if (!above.text.trim() || !line.text.trim()) continue;
+ if (ENDS_IN_HYPHEN.test(above.text) || ITEM_OR_ROW_START.test(line.text))
+ continue;
+ const em = line.fontSize > 0 ? line.fontSize : 12;
+ const leftTolerance = Math.max(
+ MIN_LEFT_TOLERANCE_PT,
+ em * LEFT_TOLERANCE_EM,
+ );
+ if (Math.abs(line.left - bodyLeft) > leftTolerance) continue;
+ const nextWordEnd = above.right + em * SPACE_EM + firstWordWidth(line);
+ flags[i] = nextWordEnd > margin - em * FIT_SLACK_EM;
+ }
+ return flags;
+}
+
+function firstWordWidth(line: BreakLine): number {
+ const text = line.text.trim();
+ if (!text) return 0;
+ const word = text.split(/\s+/)[0];
+ return ((line.right - line.left) / text.length) * word.length;
+}
+
+function medianOf(values: number[]): number {
+ const sorted = [...values].sort((a, b) => a - b);
+ return sorted[Math.floor((sorted.length - 1) / 2)];
+}
+
+/**
+ * `flags` re-indexed onto the lines of `text`, when they were classified for
+ * `flaggedText`. The two are aligned letter by letter, a space and a break
+ * matching each other when nothing better does: a break that kept its place
+ * keeps its flag, one that took a space's place is a rewrap's and reads soft,
+ * and one with nothing to match was typed and reads hard.
+ */
+export function softStartsFor(
+ text: string,
+ flaggedText: string,
+ flags: readonly boolean[],
+): boolean[] {
+ if (text === flaggedText) return [...flags];
+ const oldFlagAt = new Map<number, boolean>();
+ let line = 0;
+ for (let i = 0; i < flaggedText.length; i++)
+ if (flaggedText[i] === "\n") oldFlagAt.set(i, flags[++line] ?? false);
+ const matched = alignGaps(text, flaggedText);
+ const out = [false];
+ for (let i = 0; i < text.length; i++) {
+ if (text[i] !== "\n") continue;
+ const j = matched.get(i);
+ if (j === undefined) out.push(false);
+ else out.push(flaggedText[j] === "\n" ? (oldFlagAt.get(j) ?? false) : true);
+ }
+ return out;
+}
+
+const MAX_ALIGN_CELLS = 4_000_000;
+
+// For each break in `text`, the position in `before` it lines up with, if any.
+function alignGaps(text: string, before: string): Map<number, number> {
+ const out = new Map<number, number>();
+ let head = 0;
+ const shortest = Math.min(text.length, before.length);
+ while (head < shortest && text[head] === before[head]) head++;
+ let tail = 0;
+ while (
+ tail < shortest - head &&
+ text[text.length - 1 - tail] === before[before.length - 1 - tail]
+ )
+ tail++;
+ const shift = before.length - text.length;
+ for (let i = 0; i < text.length; i++)
+ if (text[i] === "\n" && (i < head || i >= text.length - tail))
+ out.set(i, i < head ? i : i + shift);
+ const a = text.slice(head, text.length - tail);
+ const b = before.slice(head, before.length - tail);
+ if (!a.includes("\n")) return out;
+ if ((a.length + 1) * (b.length + 1) > MAX_ALIGN_CELLS) {
+ if (a.length === b.length)
+ for (let i = 0; i < a.length; i++)
+ if (a[i] === "\n" && isGap(b[i])) out.set(head + i, head + i);
+ return out;
+ }
+ const score = (x: string, y: string) =>
+ x === y ? 2 : isGap(x) && isGap(y) ? 1 : 0;
+ const width = b.length + 1;
+ const best = new Int32Array((a.length + 1) * width);
+ for (let i = a.length - 1; i >= 0; i--)
+ for (let j = b.length - 1; j >= 0; j--) {
+ const pair = score(a[i], b[j]);
+ best[i * width + j] = Math.max(
+ best[(i + 1) * width + j],
+ best[i * width + j + 1],
+ pair > 0 ? pair + best[(i + 1) * width + j + 1] : 0,
+ );
+ }
+ let i = 0;
+ let j = 0;
+ while (i < a.length && j < b.length) {
+ const pair = score(a[i], b[j]);
+ if (
+ pair > 0 &&
+ best[i * width + j] === pair + best[(i + 1) * width + j + 1]
+ ) {
+ if (a[i] === "\n") out.set(head + i, head + j);
+ i++;
+ j++;
+ } else if (best[i * width + j] === best[(i + 1) * width + j]) i++;
+ else j++;
+ }
+ return out;
+}
+
+function isGap(ch: string | undefined): boolean {
+ return ch === " " || ch === "\n";
+}
+
+/** `run`'s soft-start flags for the lines of its current text. */
+export function softStartsOf(run: {
+ text: string;
+ paragraphSoftStarts: readonly boolean[];
+ paragraphSoftStartsText: string;
+}): boolean[] {
+ return softStartsFor(
+ run.text,
+ run.paragraphSoftStartsText,
+ run.paragraphSoftStarts,
+ );
+}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/pdfium/lineEndHyphen.ts b/frontend/src/editor/core/tools/pdfTextEditor/pdfium/lineEndHyphen.ts
index 596f79c488..9f5132b4da 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/pdfium/lineEndHyphen.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/pdfium/lineEndHyphen.ts
@@ -7,6 +7,8 @@
* Every read of text or code points from a PDFium text page goes through here,
* so the run text and the per-glyph code points it is matched against agree.
*/
+import { marksAfterLetters } from "@editor/tools/pdfTextEditor/util/bidi";
+
const LINE_END_HYPHEN_MARKER = 0x0002;
const HYPHEN = 0x002d;
@@ -14,6 +16,7 @@ export function drawnCodePoint(codePoint: number): number {
return codePoint === LINE_END_HYPHEN_MARKER ? HYPHEN : codePoint;
}
+/** An object's text as drawn, with right-to-left marks back after their letters. */
export function drawnText(text: string): string {
- return text.replaceAll("\u0002", "-");
+ return marksAfterLetters(text.replaceAll("\u0002", "-"));
}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/pdfium/objectTexts.ts b/frontend/src/editor/core/tools/pdfTextEditor/pdfium/objectTexts.ts
new file mode 100644
index 0000000000..716b3f88f2
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/pdfium/objectTexts.ts
@@ -0,0 +1,83 @@
+import type { WrappedPdfiumModule } from "@embedpdf/pdfium";
+import {
+ SCRATCH,
+ scratchPtr,
+} from "@editor/tools/pdfTextEditor/util/wasmScratch";
+
+export interface CharOriginModule {
+ FPDFText_GetCharOrigin?: (
+ textPage: number,
+ index: number,
+ x: number,
+ y: number,
+ ) => boolean;
+}
+
+interface ObjectText {
+ text: string;
+ /** Baseline of the line being read, as PDFium tracks it. */
+ y: number;
+ /** How many non-space characters the page had drawn when this object last took one. */
+ seen: number;
+}
+
+const SPACE = 0x20;
+
+/**
+ * The text of every text object on a text page, keyed by object pointer, or
+ * null when this build cannot say which object a character belongs to.
+ *
+ * Each entry is what `FPDFTextObj_GetText` returns for that object. That call
+ * walks every character on the page for one object, so reading a page object
+ * by object costs objects times characters: seconds on a page of a few thousand
+ * labels. This walks the characters once, following the same rules: a space
+ * straight after an object's characters is added to them, and a line break
+ * goes in where the object's text resumes on another baseline after other
+ * text.
+ */
+export function readObjectTexts(
+ m: WrappedPdfiumModule,
+ textPagePtr: number,
+): Map<number, string> | null {
+ const origin = (m as unknown as CharOriginModule).FPDFText_GetCharOrigin;
+ if (!origin || typeof m.FPDFText_GetTextObject !== "function") return null;
+ const count = m.FPDFText_CountChars(textPagePtr);
+ const xPtr = scratchPtr(m, SCRATCH.readerCharX, 8);
+ const yPtr = scratchPtr(m, SCRATCH.readerCharY, 8);
+ const objects = new Map<number, ObjectText>();
+ let nonSpaces = 0;
+ // The object the last character belonged to, until another object's character follows.
+ let open: ObjectText | null = null;
+ for (let i = 0; i < count; i++) {
+ const unicode = m.FPDFText_GetUnicode(textPagePtr, i);
+ const ptr = m.FPDFText_GetTextObject(textPagePtr, i);
+ let owner = ptr ? (objects.get(ptr) ?? null) : null;
+ if (ptr && !owner) {
+ owner = { text: "", y: 0, seen: 0 };
+ objects.set(ptr, owner);
+ }
+ if (open && open !== owner) {
+ if (unicode === SPACE) {
+ open.text += " ";
+ open.seen = nonSpaces;
+ }
+ open = null;
+ }
+ const before = nonSpaces;
+ if (unicode !== SPACE) nonSpaces += 1;
+ if (!owner) continue;
+ const y = origin(textPagePtr, i, xPtr, yPtr)
+ ? m.pdfium.getValue(yPtr, "double")
+ : owner.y;
+ if (owner.y !== y && open !== owner && before > owner.seen) {
+ owner.y = y;
+ if (owner.text) owner.text += "\r\n";
+ }
+ if (unicode) owner.text += String.fromCodePoint(unicode);
+ owner.seen = nonSpaces;
+ open = owner;
+ }
+ const texts = new Map<number, string>();
+ for (const [ptr, object] of objects) texts.set(ptr, object.text);
+ return texts;
+}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/pdfium/pointerCaches.ts b/frontend/src/editor/core/tools/pdfTextEditor/pdfium/pointerCaches.ts
new file mode 100644
index 0000000000..2e12e3fdc7
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/pdfium/pointerCaches.ts
@@ -0,0 +1,20 @@
+/**
+ * Clearers for module-level caches keyed by PDFium page, font or object
+ * pointers. Closing a document frees its pointers and PDFium hands the same
+ * addresses to the next document, so an entry that outlives its document
+ * answers for whatever page or font takes its address.
+ *
+ * Imports nothing, so any cache module can register without an import cycle
+ * through EditorDocument.
+ */
+const clearers = new Set<() => void>();
+
+/** Run `clear` whenever a document closes; a cache module calls this once at load. */
+export function clearOnDocumentClose(clear: () => void): void {
+ clearers.add(clear);
+}
+
+/** Called by EditorDocument.dispose once its pages and document are closed. */
+export function documentClosed(): void {
+ for (const clear of clearers) clear();
+}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/store/EditorStore.ts b/frontend/src/editor/core/tools/pdfTextEditor/store/EditorStore.ts
index 082ac8bbf4..3b66b72a73 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/store/EditorStore.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/store/EditorStore.ts
@@ -14,12 +14,18 @@ import { resetFontHelperCaches } from "@editor/tools/pdfTextEditor/charcode/Font
import { resetCmapCache } from "@editor/tools/pdfTextEditor/charcode/CmapResolver";
import { resetContentStreamCache } from "@editor/tools/pdfTextEditor/charcode/ContentStreamResolver";
import {
+ forgetDroppedChars,
+ getDroppedBase14Chars,
resetCharCoverageCache,
resetDroppedBase14Chars,
resetOnPageAdvCache,
resetPerCharBranchPtrs,
} from "@editor/tools/pdfTextEditor/commands/editTextHelpers";
-import type { Command } from "@editor/tools/pdfTextEditor/commands/Command";
+import type {
+ Command,
+ PageRepaintArea,
+} from "@editor/tools/pdfTextEditor/commands/Command";
+import { unionRect } from "@editor/tools/pdfTextEditor/model/affine";
import type { FileId } from "@editor/types/file";
import { AdoptTableCommand } from "@editor/tools/pdfTextEditor/commands/AdoptTableCommand";
import {
@@ -32,10 +38,18 @@ import type {
GroupingMode,
PageSnapshot,
TableSnapshot,
+ TextRunSnapshot,
WidthMode,
} from "@editor/tools/pdfTextEditor/types";
import { resetEmbeddedFaces } from "@editor/tools/pdfTextEditor/util/embeddedFace";
import { resetFontCompletions } from "@editor/tools/pdfTextEditor/util/documentFontCompletion";
+import { resetDocumentFontStyles } from "@editor/tools/pdfTextEditor/util/documentFontStyle";
+import {
+ loadScriptScanFaces,
+ scanScriptsOf,
+ scriptFacesCover,
+ takeUndrawnScriptText,
+} from "@editor/tools/pdfTextEditor/util/scanFontLibrary";
/** Drop EVERY per-document charcode/glyph cache. */
function resetCharcodeCaches(): void {
@@ -51,6 +65,7 @@ function resetCharcodeCaches(): void {
// FontFaces are keyed by font pointer, which PDFium reuses across documents.
resetEmbeddedFaces();
resetFontCompletions();
+ resetDocumentFontStyles();
}
export type InteractionMode = "select" | "addText" | "addTable";
@@ -226,6 +241,10 @@ export class EditorStore {
this.patch({ mode });
}
+ toggleMode(mode: InteractionMode): void {
+ this.setMode(this.state.mode === mode ? "select" : mode);
+ }
+
setWidthMode(widthMode: WidthMode): void {
this.patch({ widthMode });
}
@@ -255,6 +274,12 @@ export class EditorStore {
return () => this.nearViewportListeners.delete(listener);
}
+ /** Returns whether find is now open. */
+ toggleFindOpen(): boolean {
+ this.setFindOpen(!this.state.findOpen);
+ return this.state.findOpen;
+ }
+
setHelpOpen(helpOpen: boolean): void {
if (this.state.helpOpen === helpOpen) return;
this.patch({ helpOpen });
@@ -442,15 +467,49 @@ export class EditorStore {
/** Apply a command via the history stack, re-snapshot, and notify. */
dispatch(cmd: Command): void {
if (!this.doc) return;
+ const before = cmd.repaintArea?.(this.doc) ?? null;
+ const fromRevision = before ? this.doc.page(before.pageIndex).revision : -1;
+ takeUndrawnScriptText();
+ const droppedBefore = new Set(getDroppedBase14Chars());
try {
this.history.execute(cmd, this.doc);
} catch (err) {
+ // A step taken back drew nothing, so the letters its attempt could not draw are not ones a save loses.
+ if (err instanceof HistoryStepError && err.documentIntact)
+ forgetDroppedChars(
+ getDroppedBase14Chars()
+ .filter((ch) => !droppedBefore.has(ch))
+ .join(""),
+ );
this.recoverFromBrokenStep(err);
return;
}
+ if (before) noteRepaintArea(this.doc, cmd, before, fromRevision);
this.resnapshot();
this.patch({ dirty: this.isDirty() });
this.schedulePositionRefresh();
+ const undrawn = takeUndrawnScriptText();
+ if (undrawn) void this.redrawOnceScriptFontsLoad(cmd, undrawn);
+ }
+
+ /** Redraw `cmd` and every step after it once fonts for `undrawn`'s scripts are in, so typed text its emit dropped appears. */
+ private async redrawOnceScriptFontsLoad(
+ cmd: Command,
+ undrawn: string,
+ ): Promise<void> {
+ const doc = this.doc;
+ await loadScriptScanFaces(scanScriptsOf(undrawn)).catch(() => undefined);
+ if (this.doc !== doc || !doc || this.state.loading) return;
+ if (!scriptFacesCover(undrawn)) return;
+ try {
+ if (!this.history.replayFrom(cmd, doc)) return;
+ } catch (err) {
+ this.recoverFromBrokenStep(err);
+ return;
+ }
+ forgetDroppedChars(undrawn);
+ this.resnapshot();
+ this.patch({ dirty: this.isDirty() });
}
private schedulePositionRefresh(): void {
@@ -492,6 +551,27 @@ export class EditorStore {
}, delay);
}
+ /**
+ * Run `runId` with the engine's pen positions for its current text, read
+ * now rather than at the debounced refresh. Re-reads every glyph on the
+ * page, so it is for the keystroke that needs a letter's real advance, not
+ * for every keystroke. Null when the run or the read is unavailable.
+ */
+ measureRun(pageIndex: number, runId: string): TextRunSnapshot | null {
+ const doc = this.doc;
+ if (!doc) return null;
+ const page = doc.page(pageIndex);
+ let changed: Set<TextRun>;
+ try {
+ changed = PdfiumTextReader.recapturePositions(doc, page);
+ } catch {
+ return null;
+ }
+ if (changed.size > 0)
+ this.refreshRunSnapshots(new Map([[pageIndex, changed]]));
+ return page.findRun(runId)?.snapshot() ?? null;
+ }
+
// Re-read one page's geometry from the engine immediately, keeping run ids.
// The debounced refresh above calls the same thing; this is the un-debounced
// entry point for callers that need it now (and for measuring its cost).
@@ -687,3 +767,20 @@ export class EditorStore {
this.listeners.clear();
}
}
+
+function noteRepaintArea(
+ doc: EditorDocument,
+ cmd: Command,
+ before: PageRepaintArea,
+ fromRevision: number,
+): void {
+ const after = cmd.repaintArea?.(doc);
+ if (!after || after.pageIndex !== before.pageIndex) return;
+ const page = doc.page(after.pageIndex);
+ if (page.revision === fromRevision) return;
+ page.noteRepaintArea(
+ fromRevision,
+ page.revision,
+ unionRect(before.area, after.area),
+ );
+}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/store/HistoryStack.ts b/frontend/src/editor/core/tools/pdfTextEditor/store/HistoryStack.ts
index ffee29fc36..fbe6c06df1 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/store/HistoryStack.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/store/HistoryStack.ts
@@ -147,6 +147,29 @@ export class HistoryStack {
return cmd;
}
+ /**
+ * Undo back past the step holding `cmd`, then redo up again, so every step
+ * from it on is drawn with what the document can draw now. False, changing
+ * nothing, when `cmd` is not in an applied step.
+ */
+ replayFrom(cmd: Command, doc: EditorDocument): boolean {
+ const index = this.undoStack.findIndex(
+ (step) =>
+ step === cmd ||
+ (step instanceof CompositeCommand && step.includes(cmd)),
+ );
+ if (index < 0) return false;
+ const steps = this.undoStack.length - index;
+ // A burst still being typed keeps joining its step across the redraw.
+ const coalesceKey = this.lastCoalesceKey;
+ const executedAt = this.lastExecuteAt;
+ for (let i = 0; i < steps; i++) this.undo(doc);
+ for (let i = 0; i < steps; i++) this.redo(doc);
+ this.lastCoalesceKey = coalesceKey;
+ this.lastExecuteAt = executedAt;
+ return true;
+ }
+
clear(): void {
this.undoStack.length = 0;
this.redoStack.length = 0;
@@ -159,9 +182,7 @@ export class HistoryStack {
}
/** Revert every command currently on the undo stack, in reverse order. */
- undoAll(
- doc: import("@editor/tools/pdfTextEditor/model/EditorDocument").EditorDocument,
- ): number {
+ undoAll(doc: EditorDocument): number {
let count = 0;
while (this.undoStack.length > 0) {
this.undo(doc);
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/store/Selection.ts b/frontend/src/editor/core/tools/pdfTextEditor/store/Selection.ts
index cdb71ad621..ccf0c5e95f 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/store/Selection.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/store/Selection.ts
@@ -5,27 +5,42 @@ import type {
// Singleton "find highlight" state, kept off the SelectionState (which is used
// for edit commands) so search highlights survive normal selection changes.
+/** The find-bar occurrence on show: a range of one run's text. */
+export interface FindMatch {
+ runId: string;
+ range: TextRange;
+}
+
+function sameMatch(a: FindMatch | null, b: FindMatch | null): boolean {
+ if (a === null || b === null) return a === b;
+ return (
+ a.runId === b.runId &&
+ a.range.start === b.range.start &&
+ a.range.end === b.range.end
+ );
+}
+
export class FindHighlight {
- private id: string | null = null;
- private listeners: Set<(id: string | null) => void> = new Set();
+ private match: FindMatch | null = null;
+ private listeners: Set<(match: FindMatch | null) => void> = new Set();
- set(runId: string | null): void {
- if (this.id === runId) return;
- this.id = runId;
+ set(match: FindMatch | null): void {
+ if (sameMatch(this.match, match)) return;
+ this.match = match;
// Snapshot + guard so one throwing/unsubscribing listener can't abort
// notification of the rest (see EditorStore.notify for the rationale).
for (const l of Array.from(this.listeners)) {
try {
- l(this.id);
+ l(this.match);
} catch {
/* one listener throwing must not stop the rest */
}
}
}
- get(): string | null {
- return this.id;
+ get(): FindMatch | null {
+ return this.match;
}
- subscribe(l: (id: string | null) => void): () => void {
+ subscribe(l: (match: FindMatch | null) => void): () => void {
this.listeners.add(l);
return () => this.listeners.delete(l);
}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/types.ts b/frontend/src/editor/core/tools/pdfTextEditor/types.ts
index d978676dbe..915d05bf0a 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/types.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/types.ts
@@ -3,8 +3,16 @@
import type { DisplayTransformData } from "@editor/tools/pdfTextEditor/model/DisplayTransform";
import type { AnnotationBox } from "@editor/tools/pdfTextEditor/model/AnnotationBox";
import type { Furniture } from "@editor/tools/pdfTextEditor/model/artifactKind";
+import type { FontFamilyEntry } from "@editor/tools/pdfTextEditor/util/fontFaces";
export const RENDER_MODE_INVISIBLE = 3;
+const RENDER_MODE_CLIP = 7;
+
+/** Which layer text belongs to: 1 invisible, 2 clip only, 0 drawn. Text of different layers is never one line or paragraph. */
+export function textLayer(renderMode: number | undefined): number {
+ if (renderMode === RENDER_MODE_INVISIBLE) return 1;
+ return renderMode === RENDER_MODE_CLIP ? 2 : 0;
+}
export interface RGBA {
r: number; // 0..255
@@ -64,8 +72,12 @@ export interface TextRunSnapshot {
fontSubset: boolean;
/** For scanned text, the family its ink is matched to or redrawn in; `fontId` there is only the OCR layer's font. */
scanFamily?: string;
+ /** The PDF's own font the run was in before its family was changed. */
+ documentFontId?: string;
/** PDF text render mode (Tr). 0/absent = normal fill; 3 = invisible. */
renderMode?: number;
+ /** Invisible text with nothing drawn behind it: hidden text, not an OCR layer over a scan. */
+ hiddenText?: boolean;
/** Outline colour, when the run's render mode strokes its glyphs. */
stroke?: RGBA;
/** Outline width in PDF points; 0/absent = hairline or unstroked. */
@@ -83,9 +95,13 @@ export interface TextRunSnapshot {
paragraphSlotCount?: number;
paragraphBaselines?: number[];
paragraphLineLefts?: number[];
+ /** Each line's right ink edge, parallel to paragraphLineLefts. */
+ paragraphLineRights?: number[];
// Editor-only metadata: when true the run cannot be selected or edited via
// mouse/keyboard.
locked?: boolean;
+ /** The text cannot be changed, though the run can still be selected, moved and deleted: the reader could not tell the order its line was drawn in. */
+ textReadOnly?: boolean;
/** Box width the user set by resize, in PDF points; absent = follow the ink. */
wrapWidthPt?: number;
/** The marked-content ID that ties the run's text into the structure tree. */
@@ -114,6 +130,11 @@ export interface ImageObjectSnapshot {
artifact?: boolean;
/** Drawn by a form XObject, whose marks are not the page's to change. */
inForm?: boolean;
+ /**
+ * Page-space box of the clips the image is drawn through; what shows is
+ * `bounds` cut to it. Absent when nothing clips the image.
+ */
+ clip?: PageRect;
}
// One ruling line the page draws, with the ink needed to reproduce it: a table
@@ -248,16 +269,31 @@ export interface TextRange {
export interface ToolbarState {
fontFamily: string | null;
+ /** The document fontId every selected run can be restored to, or null. */
+ documentFontId: string | null;
fontSize: number | null;
fill: RGBA | null;
bold: boolean;
italic: boolean;
/**
- * Whether an italic cut is actually reachable for every selected run - a
- * base-14 flip, or an installed face of the run's own family. False disables
- * the control instead of silently substituting Helvetica for the real font.
+ * Whether every selected run is in, or has a real face for, the style the
+ * toggle would give the whole selection: bold when any run is not bold, else
+ * regular. False disables the control instead of silently substituting
+ * Helvetica for the real font.
*/
+ canBold: boolean;
+ /** As {@link canBold}, for italic. */
canItalic: boolean;
+ /** Bold is off only because the italic text's family has a bold face but no bold italic one. */
+ boldNeedsBoldItalic: boolean;
+ /** Italic is off only because the bold text's family has an italic face but no bold italic one. */
+ italicNeedsBoldItalic: boolean;
+ /** The selection's weight (400 regular, 700 bold), or null when it is mixed. */
+ weight: number | null;
+ /** The weights the selection's family has, when it has more than regular and bold; else empty. */
+ weights: number[];
+ /** The document's own fonts, as families. */
+ documentFamilies: FontFamilyEntry[];
/** Glyph outline colour across the selection; null when unset or mixed. */
stroke: RGBA | null;
/** Glyph outline width in points; null when mixed. 0 means no outline. */
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/util/arabicShaping.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/util/arabicShaping.test.ts
new file mode 100644
index 0000000000..6882169027
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/util/arabicShaping.test.ts
@@ -0,0 +1,36 @@
+import { describe, expect, test } from "vitest";
+import {
+ needsArabicShaping,
+ shapeArabic,
+} from "@editor/tools/pdfTextEditor/util/arabicShaping";
+
+const codes = (text: string) =>
+ [...text].map((ch) => ch.codePointAt(0)!.toString(16));
+
+describe("shapeArabic", () => {
+ test.each([
+ ["بيت", ["fe91", "fef4", "fe96"]],
+ ["دار", ["fea9", "fe8d", "fead"]],
+ ["سلام", ["feb3", "fefc", "fee1"]],
+ ["لا", ["fefb"]],
+ ["ب ت", ["fe8f", "20", "fe95"]],
+ ])("joins %s", (text, expected) => {
+ expect(codes(shapeArabic(text).text)).toEqual(expected);
+ });
+
+ test("lets a mark sit between two letters without breaking the join", () => {
+ expect(codes(shapeArabic("بَت").text)).toEqual(["fe91", "64e", "fe96"]);
+ });
+
+ test("maps every shaped character back to what it shows, a ligature to both its letters", () => {
+ const { source, sourceEnd } = shapeArabic("سلام");
+ expect(source).toEqual([0, 1, 3]);
+ expect(sourceEnd).toEqual([1, 3, 4]);
+ });
+
+ test("leaves other text alone", () => {
+ expect(shapeArabic("hello שלום").text).toBe("hello שלום");
+ expect(needsArabicShaping("hello שלום")).toBe(false);
+ expect(needsArabicShaping("مرحبا")).toBe(true);
+ });
+});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/util/arabicShaping.ts b/frontend/src/editor/core/tools/pdfTextEditor/util/arabicShaping.ts
new file mode 100644
index 0000000000..2ac85a0cac
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/util/arabicShaping.ts
@@ -0,0 +1,150 @@
+/**
+ * Contextual Arabic letter forms from the Unicode presentation-form blocks.
+ * A PDF text object draws each character's own glyph, with no shaping engine
+ * between the text and the page, so Arabic written as base letters draws every
+ * letter in its isolated form. Fonts that map the presentation forms (Noto Sans
+ * Arabic, DejaVu Sans) draw the joined forms these code points name.
+ */
+import { codeUnitOffsets } from "@editor/tools/pdfTextEditor/util/bidi";
+
+// Isolated, final, initial, medial; right-joining letters have only the first two.
+const FORMS: Record<number, readonly number[]> = {
+ 0x0621: [0xfe80],
+ 0x0622: [0xfe81, 0xfe82],
+ 0x0623: [0xfe83, 0xfe84],
+ 0x0624: [0xfe85, 0xfe86],
+ 0x0625: [0xfe87, 0xfe88],
+ 0x0626: [0xfe89, 0xfe8a, 0xfe8b, 0xfe8c],
+ 0x0627: [0xfe8d, 0xfe8e],
+ 0x0628: [0xfe8f, 0xfe90, 0xfe91, 0xfe92],
+ 0x0629: [0xfe93, 0xfe94],
+ 0x062a: [0xfe95, 0xfe96, 0xfe97, 0xfe98],
+ 0x062b: [0xfe99, 0xfe9a, 0xfe9b, 0xfe9c],
+ 0x062c: [0xfe9d, 0xfe9e, 0xfe9f, 0xfea0],
+ 0x062d: [0xfea1, 0xfea2, 0xfea3, 0xfea4],
+ 0x062e: [0xfea5, 0xfea6, 0xfea7, 0xfea8],
+ 0x062f: [0xfea9, 0xfeaa],
+ 0x0630: [0xfeab, 0xfeac],
+ 0x0631: [0xfead, 0xfeae],
+ 0x0632: [0xfeaf, 0xfeb0],
+ 0x0633: [0xfeb1, 0xfeb2, 0xfeb3, 0xfeb4],
+ 0x0634: [0xfeb5, 0xfeb6, 0xfeb7, 0xfeb8],
+ 0x0635: [0xfeb9, 0xfeba, 0xfebb, 0xfebc],
+ 0x0636: [0xfebd, 0xfebe, 0xfebf, 0xfec0],
+ 0x0637: [0xfec1, 0xfec2, 0xfec3, 0xfec4],
+ 0x0638: [0xfec5, 0xfec6, 0xfec7, 0xfec8],
+ 0x0639: [0xfec9, 0xfeca, 0xfecb, 0xfecc],
+ 0x063a: [0xfecd, 0xfece, 0xfecf, 0xfed0],
+ 0x0641: [0xfed1, 0xfed2, 0xfed3, 0xfed4],
+ 0x0642: [0xfed5, 0xfed6, 0xfed7, 0xfed8],
+ 0x0643: [0xfed9, 0xfeda, 0xfedb, 0xfedc],
+ 0x0644: [0xfedd, 0xfede, 0xfedf, 0xfee0],
+ 0x0645: [0xfee1, 0xfee2, 0xfee3, 0xfee4],
+ 0x0646: [0xfee5, 0xfee6, 0xfee7, 0xfee8],
+ 0x0647: [0xfee9, 0xfeea, 0xfeeb, 0xfeec],
+ 0x0648: [0xfeed, 0xfeee],
+ 0x0649: [0xfeef, 0xfef0],
+ 0x064a: [0xfef1, 0xfef2, 0xfef3, 0xfef4],
+};
+// Lam followed by one of these alefs is written as a single ligature (isolated, final).
+const LAM = 0x0644;
+const LAM_ALEF: Record<number, readonly [number, number]> = {
+ 0x0622: [0xfef5, 0xfef6],
+ 0x0623: [0xfef7, 0xfef8],
+ 0x0625: [0xfef9, 0xfefa],
+ 0x0627: [0xfefb, 0xfefc],
+};
+const TATWEEL = 0x0640;
+// Harakat and other marks sit on a letter without breaking its joins.
+const TRANSPARENT = /[ؐ-ًؚ-ٰٟۖ-ۭ]/;
+
+function joinsForward(cp: number | undefined): boolean {
+ return cp === TATWEEL || (cp !== undefined && FORMS[cp]?.length === 4);
+}
+
+function joinsBack(cp: number | undefined): boolean {
+ return cp === TATWEEL || (cp !== undefined && (FORMS[cp]?.length ?? 0) >= 2);
+}
+
+/** True when the letters on either side of code unit `at` are written joined, whatever marks sit between them. */
+export function joinsAt(text: string, at: number): boolean {
+ let before = at - 1;
+ while (before >= 0 && TRANSPARENT.test(text[before])) before--;
+ let after = at;
+ while (after < text.length && TRANSPARENT.test(text[after])) after++;
+ return (
+ before >= 0 &&
+ after < text.length &&
+ joinsForward(text.codePointAt(before)) &&
+ joinsBack(text.codePointAt(after))
+ );
+}
+
+/** True when `text` holds an Arabic letter that has contextual forms. */
+export function needsArabicShaping(text: string): boolean {
+ for (const ch of text) if (FORMS[ch.codePointAt(0)!]) return true;
+ return false;
+}
+
+/**
+ * `text` with each Arabic letter in the form its neighbours call for, and for
+ * each character of the result the stretch of `text` it shows, as
+ * [`source`, `sourceEnd`).
+ */
+export function shapeArabic(text: string): {
+ text: string;
+ source: number[];
+ sourceEnd: number[];
+} {
+ const units = [...text];
+ const offsets = codeUnitOffsets(units);
+ const cps = units.map((unit) => unit.codePointAt(0)!);
+ const neighbourIndex = (from: number, step: 1 | -1): number => {
+ for (let i = from + step; i >= 0 && i < units.length; i += step)
+ if (!TRANSPARENT.test(units[i])) return i;
+ return -1;
+ };
+ const neighbour = (from: number, step: 1 | -1): number | undefined => {
+ const i = neighbourIndex(from, step);
+ return i < 0 ? undefined : cps[i];
+ };
+ let out = "";
+ const source: number[] = [];
+ const sourceEnd: number[] = [];
+ const emit = (cp: number, from: number, to = from) => {
+ const ch = String.fromCodePoint(cp);
+ out += ch;
+ for (let k = 0; k < ch.length; k++) {
+ source.push(offsets[from]);
+ sourceEnd.push(offsets[to] + units[to].length);
+ }
+ };
+ for (let i = 0; i < units.length; i++) {
+ const cp = cps[i];
+ const forms = FORMS[cp];
+ if (!forms) {
+ emit(cp, i);
+ continue;
+ }
+ const joinedBefore = joinsForward(neighbour(i, -1));
+ const next = neighbourIndex(i, 1);
+ const alef = cp === LAM && next >= 0 ? LAM_ALEF[cps[next]] : undefined;
+ if (alef) {
+ emit(alef[joinedBefore ? 1 : 0], i, next);
+ for (let k = i + 1; k < next; k++) emit(cps[k], k);
+ i = next;
+ continue;
+ }
+ const joinedAfter = forms.length === 4 && joinsBack(neighbour(i, 1));
+ const form =
+ joinedBefore && joinedAfter
+ ? 3
+ : joinedAfter
+ ? 2
+ : joinedBefore && forms.length >= 2
+ ? 1
+ : 0;
+ emit(forms[form], i);
+ }
+ return { text: out, source, sourceEnd };
+}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/util/bidi.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/util/bidi.test.ts
new file mode 100644
index 0000000000..c649fc378b
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/util/bidi.test.ts
@@ -0,0 +1,123 @@
+import { describe, expect, test } from "vitest";
+import {
+ hasRtl,
+ isRtlBase,
+ marksAfterLetters,
+ readingOrder,
+ visualOrder,
+} from "@editor/tools/pdfTextEditor/util/bidi";
+
+describe("visualOrder", () => {
+ test.each([
+ ["שלום עולם", "םלוע םולש"],
+ ["abc שלום def", "abc םולש def"],
+ ["שלום 123 עולם", "םלוע 123 םולש"],
+ ["שלום abc def עולם", "םלוע abc def םולש"],
+ ["(שלום)", "(םולש)"],
+ ["מחיר 1,250.00 היום", "םויה 1,250.00 ריחמ"],
+ ["plain latin", "plain latin"],
+ ["מחיר 100% היום", "םויה 100% ריחמ"],
+ ["המחיר ₪1,299.90 כולל", "ללוכ ₪1,299.90 ריחמה"],
+ ["הוא (12) שם", "םש (12) אוה"],
+ ["טלפון 03-555-1234 כאן", "ןאכ 03-555-1234 ןופלט"],
+ ["المبلغ 3.5% فقط", "طقف %3.5 غلبملا"],
+ ["السعر 12,450.75 ريال", "لاير 12,450.75 رعسلا"],
+ ["الأرقام ١٢٣ هنا", "انه ١٢٣ ماقرألا"],
+ ["تقرير ISO 50001", "ISO 50001 ريرقت"],
+ ["رقم A-2026/11 هنا", "انه A-2026/11 مقر"],
+ ["افتح report-2026.docx الآن", "نآلا report-2026.docx حتفا"],
+ ["quotes مرحبا (تجربة) here", "quotes (ةبرجت) ابحرم here"],
+ ["שלום \u200e+44 20\u200e עולם", "םלוע \u200e+44 20\u200e םולש"],
+ ])("draws %j as %j", (logical, visual) => {
+ expect(visualOrder(logical).visual).toBe(visual);
+ });
+
+ test("maps every drawn position back to the character it shows", () => {
+ const text = "Mixed: hello שלום world 123.";
+ const { visual, order } = visualOrder(text);
+ expect([...order].sort((a, b) => a - b)).toEqual(
+ [...text].map((_, i) => i),
+ );
+ order.forEach((logical, drawn) =>
+ expect(visual[drawn]).toBe(text[logical]),
+ );
+ });
+
+ test("keeps a surrogate pair in order", () => {
+ const { visual } = visualOrder("שלום 😀");
+ expect(visual).toBe("😀 םולש");
+ });
+});
+
+describe("direction", () => {
+ test.each([
+ ["שלום world", true],
+ ["hello עולם", false],
+ ["123 שלום", true],
+ ["", false],
+ ])("%j starts right-to-left: %s", (text, rtl) => {
+ expect(isRtlBase(text)).toBe(rtl);
+ });
+
+ test("finds right-to-left characters", () => {
+ expect(hasRtl("hello")).toBe(false);
+ expect(hasRtl("مرحبا")).toBe(true);
+ });
+});
+
+describe("combining marks on right-to-left letters", () => {
+ const reversed = (text: string) => [...text].reverse().join("");
+
+ test.each([
+ ["שָׁלוֹם", "ם" + "ו\u05b9" + "ל" + "ש\u05b8\u05c1"],
+ ["يُولَدُ", "د\u064f" + "ل\u064e" + "و" + "ي\u064f"],
+ ])("draws %j with each letter ahead of its marks", (logical, drawn) => {
+ expect(visualOrder(logical).visual).toBe(drawn);
+ });
+
+ test.each(["שָׁלוֹם עוֹלָם", "يُولَدُ جَمِيعُ النَّاسِ"])(
+ "reads %j back from the order it was drawn in",
+ (logical) => {
+ const read = reversed(visualOrder(logical).visual);
+ expect(marksAfterLetters(read)).toBe(logical);
+ },
+ );
+
+ test("leaves marks on left-to-right letters alone", () => {
+ const text = "cafe\u0301 שלום";
+ expect(marksAfterLetters(text)).toBe(text);
+ });
+});
+
+describe("readingOrder", () => {
+ const read = (drawn: string) => {
+ const { texts, faithful } = readingOrder([...drawn]);
+ return { text: texts.join(""), faithful };
+ };
+
+ test.each([
+ "بلغ الاستهلاك (في الربع) 12,450.75 كيلوواط [بزيادة 3.5%] حسب تقرير ISO 50001",
+ "استخدم برنامج LibreOffice Writer أو Word لفتح report-2026.docx الآن.",
+ "הטלפון הוא 03-555-1234 (שלוחה 12), והמחיר ₪1,299.90 לפי Open Source סעיף 4.",
+ "An English line quoting مرحبا بالعالم (تجربة) and שלום עולם then 1,234.",
+ "الأرقام ١٢٣٤٥٦٧٨٩٠ و۱۲۳۴ (فارسية).",
+ "plain latin, 12.5%",
+ ])("reads %j back from the order it is drawn in", (logical) => {
+ expect(read(visualOrder(logical).visual)).toEqual({
+ text: logical,
+ faithful: true,
+ });
+ });
+
+ test("keeps a letter and its marks together", () => {
+ const drawn = ["ם", "ו\u05b9", "ל", "ש\u05b8\u05c1"];
+
+ expect(readingOrder(drawn).texts.join("")).toBe("שָׁלוֹם");
+ });
+
+ test("says so when no reading order draws the line the way it is drawn", () => {
+ const rightToLeftParagraphOpeningWithLatin = "رايعملا وه ISO 50001";
+
+ expect(read(rightToLeftParagraphOpeningWithLatin).faithful).toBe(false);
+ });
+});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/util/bidi.ts b/frontend/src/editor/core/tools/pdfTextEditor/util/bidi.ts
new file mode 100644
index 0000000000..c3b7d2404d
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/util/bidi.ts
@@ -0,0 +1,452 @@
+/**
+ * Logical-to-visual reordering for one line of text, following the Unicode
+ * Bidirectional Algorithm (UAX #9) closely enough for plain paragraphs: base
+ * direction from the first strong character, levels for strong, number and
+ * neutral characters, reversal by level, and mirrored brackets. It does not
+ * handle explicit embedding controls or isolates.
+ *
+ * A PDF draws a text object's glyphs left to right in content order, so
+ * right-to-left text has to be written in visual order; readers reorder it
+ * back to logical order when extracting.
+ */
+
+const RTL = /[\u0590-\u08ff\u200f\ufb1d-\ufdff\ufe70-\ufefc]/;
+const MIRRORED: Record<string, string> = {
+ "(": ")",
+ ")": "(",
+ "[": "]",
+ "]": "[",
+ "{": "}",
+ "}": "{",
+ "<": ">",
+ ">": "<",
+ "«": "»",
+ "»": "«",
+ "‹": "›",
+ "›": "‹",
+};
+const OPENING_BRACKET: Record<string, string> = {
+ "(": ")",
+ "[": "]",
+ "{": "}",
+};
+const CLOSING_BRACKET: Record<string, string> = {
+ ")": "(",
+ "]": "[",
+ "}": "{",
+};
+// UAX #9 BD16 caps the stack of open brackets; a deeper nest is left unpaired.
+const MAX_OPEN_BRACKETS = 63;
+
+/** UAX #9 character classes; explicit embeddings and isolates are read as BN, paragraph and segment separators as WS. */
+type BidiClass =
+ | "L"
+ | "R"
+ | "AL"
+ | "EN"
+ | "ES"
+ | "ET"
+ | "AN"
+ | "CS"
+ | "NSM"
+ | "BN"
+ | "WS"
+ | "ON";
+
+const COMBINING_MARK = /\p{M}/u;
+const NONSPACING_MARK = /[\p{Mn}\p{Me}]/u;
+const LETTER = /\p{L}/u;
+const CURRENCY = /\p{Sc}/u;
+const SPACE_SEPARATOR = /\p{Zs}/u;
+const FORMAT_CONTROL = /\p{Cf}/u;
+
+function asciiClass(cp: number): BidiClass {
+ if ((cp >= 0x41 && cp <= 0x5a) || (cp >= 0x61 && cp <= 0x7a)) return "L";
+ if (cp >= 0x30 && cp <= 0x39) return "EN";
+ if (cp === 0x2b || cp === 0x2d) return "ES";
+ if (cp >= 0x23 && cp <= 0x25) return "ET";
+ if (cp === 0x2c || cp === 0x2e || cp === 0x2f || cp === 0x3a) return "CS";
+ if (cp === 0x20 || (cp >= 0x09 && cp <= 0x0d)) return "WS";
+ return cp < 0x20 || cp === 0x7f ? "BN" : "ON";
+}
+
+function arabicClass(cp: number): BidiClass {
+ if (cp <= 0x0605 || cp === 0x06dd || cp === 0x08e2) return "AN";
+ if (cp >= 0x0660 && cp <= 0x0669) return "AN";
+ if (cp === 0x066b || cp === 0x066c) return "AN";
+ if (cp >= 0x06f0 && cp <= 0x06f9) return "EN";
+ if (cp === 0x0609 || cp === 0x060a || cp === 0x066a) return "ET";
+ if (cp === 0x060c) return "CS";
+ if (cp === 0x0606 || cp === 0x0607 || cp === 0x060e || cp === 0x060f)
+ return "ON";
+ if (cp === 0x06de || cp === 0x06e9) return "ON";
+ return "AL";
+}
+
+function classOf(ch: string): BidiClass {
+ const cp = ch.codePointAt(0)!;
+ if (cp < 0x80) return asciiClass(cp);
+ if (cp === 0x200e) return "L";
+ if (cp === 0x200f) return "R";
+ if (NONSPACING_MARK.test(ch)) return "NSM";
+ if (cp >= 0x0590 && cp <= 0x05ff) return "R";
+ if (cp >= 0x0600 && cp <= 0x07bf) return arabicClass(cp);
+ if (cp >= 0x07c0 && cp <= 0x085f) return "R";
+ if (cp >= 0x0860 && cp <= 0x08ff) return arabicClass(cp);
+ if (cp >= 0xfb1d && cp <= 0xfb4f) return cp === 0xfb29 ? "ES" : "R";
+ if (cp >= 0xfb50 && cp <= 0xfdff)
+ return cp === 0xfd3e || cp === 0xfd3f ? "ON" : "AL";
+ if (cp >= 0xfe70 && cp <= 0xfefc) return "AL";
+ if (cp === 0x00a0 || cp === 0x202f || cp === 0x2044) return "CS";
+ if (cp === 0x00b0 || cp === 0x00b1 || (cp >= 0x2030 && cp <= 0x2034))
+ return "ET";
+ if (cp === 0x00b2 || cp === 0x00b3 || cp === 0x00b9) return "EN";
+ if (cp === 0x2070 || (cp >= 0x2074 && cp <= 0x2079)) return "EN";
+ if (cp >= 0x2080 && cp <= 0x2089) return "EN";
+ if (cp >= 0xff10 && cp <= 0xff19) return "EN";
+ if (cp === 0x2212 || cp === 0x207a || cp === 0x207b) return "ES";
+ if (CURRENCY.test(ch)) return "ET";
+ if (SPACE_SEPARATOR.test(ch) || cp === 0x2028 || cp === 0x2029) return "WS";
+ if (FORMAT_CONTROL.test(ch)) return "BN";
+ if (LETTER.test(ch)) return "L";
+ // Anything else with a letter's case reads left to right.
+ return ch.toLowerCase() !== ch.toUpperCase() ? "L" : "ON";
+}
+
+/** The code-unit offset of each of `chars`, the code points of one string in order. */
+export function codeUnitOffsets(chars: readonly string[]): number[] {
+ const offsets: number[] = [];
+ let offset = 0;
+ for (const ch of chars) {
+ offsets.push(offset);
+ offset += ch.length;
+ }
+ return offsets;
+}
+
+/** True when `text` holds any right-to-left character. */
+export function hasRtl(text: string): boolean {
+ return RTL.test(text);
+}
+
+/**
+ * `text` with each run of combining marks moved back after the right-to-left
+ * letter it sits on. A PDF draws a letter and then its marks; a reader reversing
+ * that visual order code point by code point puts the marks first (UAX #9 L3).
+ */
+export function marksAfterLetters(text: string): string {
+ if (!hasRtl(text)) return text;
+ const chars = [...text];
+ for (let i = 0; i < chars.length; i++) {
+ if (!COMBINING_MARK.test(chars[i])) continue;
+ let end = i;
+ while (end < chars.length && COMBINING_MARK.test(chars[end])) end++;
+ if (
+ end < chars.length &&
+ RTL.test(chars[end]) &&
+ !COMBINING_MARK.test(chars[end])
+ )
+ chars.splice(i, end - i + 1, ...chars.slice(i, end + 1).reverse());
+ i = end;
+ }
+ return chars.join("");
+}
+
+/** True when `text` has more right-to-left letters than left-to-right ones. */
+export function isMostlyRtl(text: string): boolean {
+ let balance = 0;
+ for (const ch of text) {
+ const cls = classOf(ch);
+ if (cls === "R" || cls === "AL") balance++;
+ else if (cls === "L") balance--;
+ }
+ return balance > 0;
+}
+
+/** True when the first strong character of `text` is right-to-left (UAX #9 P2). */
+export function isRtlBase(text: string): boolean {
+ for (const ch of text) {
+ const cls = classOf(ch);
+ if (cls === "R" || cls === "AL") return true;
+ if (cls === "L") return false;
+ }
+ return false;
+}
+
+type Strong = "L" | "R";
+
+function nearestStrong(
+ classes: readonly BidiClass[],
+ from: number,
+ step: 1 | -1,
+): Strong | null {
+ for (let i = from + step; i >= 0 && i < classes.length; i += step) {
+ const strong = strongOf(classes[i]);
+ if (strong !== null) return strong;
+ }
+ return null;
+}
+
+function strongOf(cls: BidiClass): Strong | null {
+ if (cls === "L") return "L";
+ return cls === "R" || cls === "EN" || cls === "AN" ? "R" : null;
+}
+
+// W1 to W7: marks take their letter's class, numbers and their separators settle, and what is left over turns neutral.
+function resolveWeak(classes: BidiClass[], sos: Strong): void {
+ let before: BidiClass = sos;
+ for (let i = 0; i < classes.length; i++) {
+ if (classes[i] === "NSM" || classes[i] === "BN") classes[i] = before;
+ before = classes[i];
+ }
+ let strong: BidiClass = sos;
+ for (let i = 0; i < classes.length; i++) {
+ const cls = classes[i];
+ if (cls === "EN" && strong === "AL") classes[i] = "AN";
+ else if (cls === "L" || cls === "R" || cls === "AL") strong = cls;
+ }
+ for (let i = 0; i < classes.length; i++)
+ if (classes[i] === "AL") classes[i] = "R";
+ for (let i = 1; i < classes.length - 1; i++) {
+ const prev = classes[i - 1];
+ if (prev !== classes[i + 1]) continue;
+ if (classes[i] === "ES" && prev === "EN") classes[i] = "EN";
+ else if (classes[i] === "CS" && (prev === "EN" || prev === "AN"))
+ classes[i] = prev;
+ }
+ for (let i = 0; i < classes.length; i++) {
+ if (classes[i] !== "ET") continue;
+ let end = i;
+ while (end < classes.length && classes[end] === "ET") end++;
+ const joined =
+ (i > 0 && classes[i - 1] === "EN") ||
+ (end < classes.length && classes[end] === "EN");
+ for (let j = i; j < end; j++) classes[j] = joined ? "EN" : "ON";
+ i = end - 1;
+ }
+ strong = sos;
+ for (let i = 0; i < classes.length; i++) {
+ const cls = classes[i];
+ if (cls === "ES" || cls === "CS") classes[i] = "ON";
+ else if (cls === "EN" && strong === "L") classes[i] = "L";
+ else if (cls === "L" || cls === "R") strong = cls;
+ }
+}
+
+// N0: a bracket pair takes the direction of the text it encloses, or of the text before it when it encloses only the opposite direction. Drawn order puts that text on either side, so `drawn` looks after the pair too.
+function resolveBrackets(
+ chars: readonly string[],
+ classes: BidiClass[],
+ embedding: Strong,
+ drawn: boolean,
+): void {
+ const open: number[] = [];
+ const pairs: Array<[number, number]> = [];
+ for (let i = 0; i < chars.length; i++) {
+ if (classes[i] !== "ON") continue;
+ if (OPENING_BRACKET[chars[i]]) {
+ if (open.length === MAX_OPEN_BRACKETS) break;
+ open.push(i);
+ continue;
+ }
+ const opener = CLOSING_BRACKET[chars[i]];
+ if (!opener) continue;
+ for (let k = open.length - 1; k >= 0; k--) {
+ if (chars[open[k]] !== opener) continue;
+ pairs.push([open[k], i]);
+ open.length = k;
+ break;
+ }
+ }
+ pairs.sort((a, b) => a[0] - b[0]);
+ const opposite: Strong = embedding === "L" ? "R" : "L";
+ for (const [from, to] of pairs) {
+ let inside: Strong | null = null;
+ for (let i = from + 1; i < to && inside !== embedding; i++)
+ inside = strongOf(classes[i]) ?? inside;
+ if (inside === null) continue;
+ let direction = embedding;
+ if (inside !== embedding) {
+ const before = nearestStrong(classes, from, -1) ?? embedding;
+ const after = drawn ? nearestStrong(classes, to, 1) : null;
+ if (before === opposite || after === opposite) direction = opposite;
+ }
+ classes[from] = direction;
+ classes[to] = direction;
+ }
+}
+
+// N1, N2: a run of neutrals takes the direction both its sides share, else the embedding direction.
+function resolveNeutrals(classes: BidiClass[], embedding: Strong): void {
+ for (let i = 0; i < classes.length; i++) {
+ if (classes[i] !== "ON" && classes[i] !== "WS") continue;
+ let end = i;
+ while (
+ end < classes.length &&
+ (classes[end] === "ON" || classes[end] === "WS")
+ )
+ end++;
+ const before = i > 0 ? strongOf(classes[i - 1]) : embedding;
+ const after = end < classes.length ? strongOf(classes[end]) : embedding;
+ const resolved = before === after && before !== null ? before : embedding;
+ for (let j = i; j < end; j++) classes[j] = resolved;
+ i = end - 1;
+ }
+}
+
+function resolveLevels(
+ chars: readonly string[],
+ base: number,
+ drawn = false,
+): number[] {
+ const original = chars.map(classOf);
+ const classes = [...original];
+ const embedding: Strong = base % 2 === 1 ? "R" : "L";
+ resolveWeak(classes, embedding);
+ resolveBrackets(chars, classes, embedding, drawn);
+ resolveNeutrals(classes, embedding);
+ // I1, I2.
+ const levels = classes.map((cls) => {
+ if (base % 2 === 0)
+ return cls === "R" ? base + 1 : cls === "L" ? base : base + 2;
+ return cls === "R" ? base : base + 1;
+ });
+ // L1: white space ending the line sits at the paragraph level.
+ for (let i = chars.length - 1; i >= 0; i--) {
+ if (original[i] !== "WS" && original[i] !== "BN") break;
+ levels[i] = base;
+ }
+ return levels;
+}
+
+// L2: from the highest level down to the lowest odd one, reverse every run at that level or above.
+function reorderByLevel(levels: readonly number[]): number[] {
+ const order = levels.map((_, i) => i);
+ const highest = Math.max(0, ...levels);
+ const lowestOdd = Math.min(
+ ...levels.filter((level) => level % 2 === 1),
+ highest + 1,
+ );
+ for (let level = highest; level >= lowestOdd; level--) {
+ for (let i = 0; i < order.length; i++) {
+ if (levels[order[i]] < level) continue;
+ let end = i;
+ while (end < order.length && levels[order[end]] >= level) end++;
+ order.splice(i, end - i, ...order.slice(i, end).reverse());
+ i = end - 1;
+ }
+ }
+ return order;
+}
+
+/**
+ * `text` in the order its characters are drawn left to right, and for each drawn
+ * position the index of the character in `text` it shows and whether it sits in
+ * a right-to-left run.
+ */
+export function visualOrder(
+ text: string,
+ rtlBase = isRtlBase(text),
+): { visual: string; order: number[]; rightToLeft: boolean[] } {
+ const chars = [...text];
+ const offsets = codeUnitOffsets(chars);
+ const levels = resolveLevels(chars, rtlBase ? 1 : 0);
+ const order = reorderByLevel(levels);
+ // L3: reversal left each right-to-left letter's marks ahead of it; a PDF draws the letter first.
+ for (let i = 0; i < order.length; i++) {
+ if (levels[order[i]] % 2 === 0 || !COMBINING_MARK.test(chars[order[i]]))
+ continue;
+ let end = i;
+ while (end < order.length && COMBINING_MARK.test(chars[order[end]])) end++;
+ if (end < order.length && order[end] < order[i])
+ order.splice(i, end - i + 1, ...order.slice(i, end + 1).reverse());
+ i = end;
+ }
+ const visual = order
+ .map((i) =>
+ levels[i] % 2 === 1 ? (MIRRORED[chars[i]] ?? chars[i]) : chars[i],
+ )
+ .join("");
+ const units = order.flatMap((i) => (chars[i].length === 2 ? [i, i] : [i]));
+ return {
+ visual,
+ order: order.flatMap((i) =>
+ chars[i].length === 2 ? [offsets[i], offsets[i] + 1] : [offsets[i]],
+ ),
+ rightToLeft: units.map((i) => levels[i] % 2 === 1),
+ };
+}
+
+function leadingLetter(piece: string): string {
+ for (const ch of piece) if (!COMBINING_MARK.test(ch)) return ch;
+ return piece;
+}
+
+function readFromBase(
+ drawn: readonly string[],
+ rtlBase: boolean,
+ bracketsJoinEitherSide: boolean,
+): { order: number[]; texts: string[]; faithful: boolean } {
+ const levels = resolveLevels(
+ drawn.map(leadingLetter),
+ rtlBase ? 1 : 0,
+ bracketsJoinEitherSide,
+ );
+ const order = reorderByLevel(levels);
+ const texts = order.map((piece) =>
+ levels[piece] % 2 === 1
+ ? (MIRRORED[drawn[piece]] ?? drawn[piece])
+ : drawn[piece],
+ );
+ const text = texts.join("");
+ const pieceAt = order.flatMap((piece, k) =>
+ Array.from({ length: texts[k].length }, () => piece),
+ );
+ const redrawn = visualOrder(text, rtlBase);
+ let faithful = isRtlBase(text) === rtlBase;
+ let expected = 0;
+ let last = -1;
+ redrawn.order.forEach((source, position) => {
+ const piece = pieceAt[source];
+ if (piece === last) return;
+ if (piece !== expected) faithful = false;
+ if (drawn[piece].length === 1 && redrawn.visual[position] !== drawn[piece])
+ faithful = false;
+ last = piece;
+ expected++;
+ });
+ return { order, texts, faithful: faithful && expected === drawn.length };
+}
+
+/**
+ * The reading order of a line given as the pieces drawn on it from left to
+ * right: `order` lists the pieces as they are read and `texts` holds what each
+ * says there, a mirrored bracket turned back. A piece is a letter with its
+ * marks, a ligature or a space, already in reading order inside.
+ *
+ * `faithful` is false when laying the result out again with
+ * {@link visualOrder} would not put every piece back where it was drawn; the
+ * order is then a best guess and the line must not be redrawn from it.
+ */
+export function readingOrder(drawn: readonly string[]): {
+ order: number[];
+ texts: string[];
+ faithful: boolean;
+} {
+ const rtlFirst = isMostlyRtl(drawn.join(""));
+ // Several reading orders can draw the same line; the one that keeps a bracketed aside with the phrase beside it is tried first.
+ const attempts = [
+ [rtlFirst, true],
+ [rtlFirst, false],
+ [!rtlFirst, true],
+ [!rtlFirst, false],
+ ] as const;
+ const [first, ...rest] = attempts;
+ const guess = readFromBase(drawn, ...first);
+ if (guess.faithful) return guess;
+ for (const [rtlBase, eitherSide] of rest) {
+ const read = readFromBase(drawn, rtlBase, eitherSide);
+ if (read.faithful) return read;
+ }
+ return guess;
+}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/util/clearingOffset.test.ts b/frontend/src/editor/core/tools/pdfTextEditor/util/clearingOffset.test.ts
new file mode 100644
index 0000000000..23601abbd4
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/util/clearingOffset.test.ts
@@ -0,0 +1,48 @@
+import { describe, expect, it } from "vitest";
+import { offsetClearing } from "@editor/tools/pdfTextEditor/util/clearingOffset";
+
+const rect = (left: number, top: number, right: number, bottom: number) => ({
+ left,
+ top,
+ right,
+ bottom,
+});
+const DROPDOWN = { left: 700, right: 1050, height: 80 };
+
+describe("offsetClearing", () => {
+ it("keeps the usual gap when nothing selected sits under the dropdown", () => {
+ expect(
+ offsetClearing(84, DROPDOWN, [rect(340, 400, 900, 430)], 8, 900),
+ ).toBe(8);
+ });
+
+ it("drops the dropdown below a selected line it would cover", () => {
+ expect(
+ offsetClearing(84, DROPDOWN, [rect(338, 137, 895, 184)], 8, 900),
+ ).toBe(184 + 8 - 84);
+ });
+
+ it("ignores selected text beside the dropdown", () => {
+ expect(
+ offsetClearing(84, DROPDOWN, [rect(100, 100, 650, 140)], 8, 900),
+ ).toBe(8);
+ });
+
+ it("clears every stacked line it would land on", () => {
+ expect(
+ offsetClearing(
+ 84,
+ DROPDOWN,
+ [rect(338, 200, 895, 230), rect(338, 100, 895, 150)],
+ 8,
+ 900,
+ ),
+ ).toBe(230 + 8 - 84);
+ });
+
+ it("keeps the usual gap when clearing the text would push it off screen", () => {
+ expect(
+ offsetClearing(84, DROPDOWN, [rect(338, 100, 895, 860)], 8, 900),
+ ).toBe(8);
+ });
+});
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/util/clearingOffset.ts b/frontend/src/editor/core/tools/pdfTextEditor/util/clearingOffset.ts
new file mode 100644
index 0000000000..fa32a8bce3
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/util/clearingOffset.ts
@@ -0,0 +1,28 @@
+export interface Box {
+ left: number;
+ top: number;
+ right: number;
+ bottom: number;
+}
+
+/**
+ * How far below its anchor a dropdown opens so it covers none of `keepVisible`,
+ * or just `gap` when clearing them would push it past `viewportHeight`.
+ */
+export function offsetClearing(
+ anchorBottom: number,
+ dropdown: { left: number; right: number; height: number },
+ keepVisible: Box[],
+ gap: number,
+ viewportHeight: number,
+): number {
+ let top = anchorBottom + gap;
+ const sorted = [...keepVisible].sort((a, b) => a.top - b.top);
+ for (const box of sorted) {
+ if (box.right <= dropdown.left || box.left >= dropdown.right) continue;
+ if (box.bottom <= top || box.top >= top + dropdown.height) continue;
+ top = box.bottom + gap;
+ }
+ if (top + dropdown.height > viewportHeight) return gap;
+ return top - anchorBottom;
+}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/util/complexShaping.ts b/frontend/src/editor/core/tools/pdfTextEditor/util/complexShaping.ts
new file mode 100644
index 0000000000..88d2e0aa8b
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/util/complexShaping.ts
@@ -0,0 +1,51 @@
+import i18n from "i18next";
+
+/**
+ * Text the editor cannot draw faithfully. A text object draws each code
+ * point's own glyph with nothing between the text and the page to apply a
+ * font's shaping tables, so these come out wrong rather than missing:
+ *
+ * - the vowel signs, viramas and subjoined letters of the Indic and other
+ * Brahmic scripts, which reorder, stack or form conjuncts;
+ * - every letter of a joining script with no presentation forms to write it
+ * in (Arabic has them, see arabicShaping);
+ * - Thai and Lao marks stacked on another mark, or set on a consonant whose
+ * ascender or descender the mark has to move clear of. A single mark on
+ * any other consonant sits where the font's default placement puts it,
+ * which is where shaping puts it too.
+ *
+ * Devanagari vowel signs that follow their consonant and join nothing are
+ * drawn right as they are.
+ */
+const CLUSTERING_SCRIPT =
+ /[\p{sc=Deva}\p{sc=Beng}\p{sc=Guru}\p{sc=Gujr}\p{sc=Orya}\p{sc=Taml}\p{sc=Telu}\p{sc=Knda}\p{sc=Mlym}\p{sc=Sinh}\p{sc=Tibt}\p{sc=Mymr}\p{sc=Khmr}\p{sc=Bali}\p{sc=Java}\p{sc=Sund}\p{sc=Lana}\p{sc=Tale}\p{sc=Cakm}\p{sc=Shrd}\p{sc=Takr}\p{sc=Gran}\p{sc=Newa}\p{sc=Mtei}\p{sc=Lepc}\p{sc=Limb}\p{sc=Bugi}\p{sc=Batk}\p{sc=Tglg}]/u;
+const STACKING_SCRIPT = /[\p{sc=Thai}\p{sc=Laoo}]/u;
+const TALL_OR_DEEP_THAI = /[\u0E0D\u0E10\u0E1B\u0E1D\u0E1F\u0E2C]/u;
+const JOINING_SCRIPT = /[\p{sc=Syrc}\p{sc=Nkoo}\p{sc=Mong}\p{sc=Adlm}]/u;
+const MARK = /\p{M}/u;
+// Every spacing Devanagari sign but the pre-base i matras, U+093F and U+094E.
+const DRAWN_IN_PLACE = /[\u0903\u093B\u093E\u0940\u0949-\u094C\u094F]/u;
+
+export function needsShaping(text: string): boolean {
+ let previous = "";
+ for (const ch of text) {
+ if (JOINING_SCRIPT.test(ch)) return true;
+ if (MARK.test(ch)) {
+ if (CLUSTERING_SCRIPT.test(ch) && !DRAWN_IN_PLACE.test(ch)) return true;
+ if (
+ STACKING_SCRIPT.test(ch) &&
+ (MARK.test(previous) || TALL_OR_DEEP_THAI.test(previous))
+ )
+ return true;
+ }
+ previous = ch;
+ }
+ return false;
+}
+
+export function needsShapingMessage(): string {
+ return i18n.t(
+ "pdfTextEditor.error.needsShaping",
+ "The editor can't yet draw this script's joined letters and vowel signs correctly, so this change was not made.",
+ );
+}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/util/deviceFontEmbed.ts b/frontend/src/editor/core/tools/pdfTextEditor/util/deviceFontEmbed.ts
index a1e04dd47b..32d1f4abc1 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/util/deviceFontEmbed.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/util/deviceFontEmbed.ts
@@ -11,8 +11,10 @@ import {
loadExternalFontBytes,
} from "@editor/tools/pdfTextEditor/util/externalFonts";
import {
+ encodesInBase14,
isBoldFamily,
isItalicFamily,
+ nearestStandardFont,
} from "@editor/tools/pdfTextEditor/util/fontFamily";
import {
SCRATCH,
@@ -58,8 +60,8 @@ interface DeviceFontModule {
) => boolean;
}
-/** Parsed cmap per family, so coverage is computed once per session. */
-const coverageByFamily = new Map<string, Set<number> | null>();
+/** Parsed cmap per font file: two faces can share a family name, and a document keeps the one it embedded. */
+let coverageByBytes = new WeakMap<Uint8Array, Set<number> | null>();
/** Families PDFium already refused for a document; never retried. */
let refusedByDoc = new WeakMap<EditorDocument, Set<string>>();
/** Successful device-font emits per document, keyed by owned-font id. */
@@ -76,7 +78,7 @@ function refusedFor(doc: EditorDocument): Set<string> {
/** Test hook: drop the per-session coverage and per-document memos. */
export function resetDeviceFontEmbedCache(): void {
- coverageByFamily.clear();
+ coverageByBytes = new WeakMap<Uint8Array, Set<number> | null>();
refusedByDoc = new WeakMap<EditorDocument, Set<string>>();
emitCountByDoc = new WeakMap<EditorDocument, Map<string, number>>();
}
@@ -92,11 +94,10 @@ export function fontCoverage(bytes: Uint8Array): Set<number> | null {
}
}
-function coverageOf(family: string, bytes: Uint8Array): Set<number> | null {
- const key = deviceFontIdFor(family);
- if (!coverageByFamily.has(key))
- coverageByFamily.set(key, fontCoverage(bytes));
- return coverageByFamily.get(key) ?? null;
+function coverageOf(bytes: Uint8Array): Set<number> | null {
+ if (!coverageByBytes.has(bytes))
+ coverageByBytes.set(bytes, fontCoverage(bytes));
+ return coverageByBytes.get(bytes) ?? null;
}
export function visibleCodePoints(text: string): number[] {
@@ -110,27 +111,34 @@ export function visibleCodePoints(text: string): number[] {
}
// Whether the face covers every visible code point; fails open to the width self-check.
-function deviceFontCovers(
- family: string,
- bytes: Uint8Array,
- text: string,
-): boolean {
- const coverage = coverageOf(family, bytes);
+function deviceFontCovers(bytes: Uint8Array, text: string): boolean {
+ const coverage = coverageOf(bytes);
if (!coverage) return true;
return visibleCodePoints(text).every((cp) => coverage.has(cp));
}
export function deviceFontCoverage(family: string): Set<number> | null {
const bytes = getExternalFontBytes(family);
- return bytes ? coverageOf(family, bytes) : null;
+ return bytes ? coverageOf(bytes) : null;
}
-export function deviceFontDrawsAnyOf(family: string, text: string): boolean {
- const bytes = getExternalFontBytes(family);
- const coverage = bytes ? coverageOf(family, bytes) : null;
- const codePoints = visibleCodePoints(text);
- if (!coverage || codePoints.length === 0) return true;
- return codePoints.some((cp) => coverage.has(cp));
+/**
+ * Whether `draws` has any letter of `text`, or any visible character of text
+ * with no letters. Letters decide because digits and punctuation are in every
+ * face: a line of another script would count as drawn by a face with none of
+ * its words.
+ */
+export function drawsSomeOf(
+ draws: ((codePoint: number) => boolean) | null,
+ text: string,
+): boolean {
+ if (!draws) return true;
+ const visible = visibleCodePoints(text);
+ const letters = visible.filter((cp) =>
+ /\p{L}/u.test(String.fromCodePoint(cp)),
+ );
+ const judged = letters.length > 0 ? letters : visible;
+ return judged.length === 0 || judged.some(draws);
}
// Read the family's font file so a later synchronous emit can embed it. The UI
@@ -174,12 +182,56 @@ function recordEmit(doc: EditorDocument, family: string): void {
// Embed `family` into `doc` once and return its font handle, or 0. Freed with
// the document, along with its backing WASM buffer.
+/** The family a device font this document loaded was read from, or null for any other font. */
+export function deviceFamilyOf(
+ doc: EditorDocument,
+ fontPtr: number,
+): string | null {
+ const font = fontPtr ? doc.ownedFontAt(fontPtr) : undefined;
+ return font?.id.startsWith(DEVICE_FONT_ID_PREFIX)
+ ? font.descriptor.family
+ : null;
+}
+
+// The bytes of each family a document embedded, by family name. A family keeps the face it was first embedded in for the
+// document's life: a server switch can offer a different face under the same name, and a redo must draw what was drawn.
+const embeddedBytes = new WeakMap<EditorDocument, Map<string, Uint8Array>>();
+
+function faceBytes(doc: EditorDocument, family: string): Uint8Array | null {
+ return (
+ embeddedBytes.get(doc)?.get(family) ?? getExternalFontBytes(family) ?? null
+ );
+}
+
+/**
+ * The code points an emit in `family` draws in that family's own face: the
+ * face `doc` holds under the name, else the loaded one. A standard font, like a
+ * family with no bytes loaded, draws what WinAnsi encodes. Null when the
+ * face's tables cannot be read, so nothing is known.
+ */
+export function familyCoverage(
+ doc: EditorDocument | null,
+ family: string,
+): ((codePoint: number) => boolean) | null {
+ if (nearestStandardFont(family) === family) return encodesInBase14;
+ const bytes = doc ? faceBytes(doc, family) : getExternalFontBytes(family);
+ if (!bytes || bytes.length === 0) return encodesInBase14;
+ const coverage = coverageOf(bytes);
+ return coverage ? (codePoint) => coverage.has(codePoint) : null;
+}
+
export function loadDeviceFontInto(
doc: EditorDocument,
family: string,
): number {
const id = deviceFontIdFor(family);
- const existing = doc.ownedFont(id);
+ const existing =
+ doc.ownedFont(id) ??
+ doc.findOwnedFont(
+ (font) =>
+ font.id.startsWith(DEVICE_FONT_ID_PREFIX) &&
+ font.descriptor.family === family,
+ );
if (existing) return existing.pointer;
const refused = refusedFor(doc);
// A refusal is permanent for this document; retrying would re-malloc the
@@ -212,6 +264,9 @@ export function loadDeviceFontInto(
return 0;
}
doc.recordEmbeddedFontFile(bytes);
+ let kept = embeddedBytes.get(doc);
+ if (!kept) embeddedBytes.set(doc, (kept = new Map()));
+ kept.set(family, bytes);
doc.registerOwnedFont(
new FontRef({
id,
@@ -251,21 +306,53 @@ export function loadDeviceFontInto(
}
}
-/** Right edge (PDF points) of an object's visible bbox, or 0 if unmeasurable. */
-function measureRightEdge(m: EditorDocument["module"], ptr: number): number {
+/** Horizontal extent (PDF points) of an object's visible bbox, or null if unmeasurable. */
+function measureInkSpan(
+ m: EditorDocument["module"],
+ ptr: number,
+): { left: number; right: number } | null {
const mod = m as unknown as DeviceFontModule;
- if (typeof mod.FPDFPageObj_GetBounds !== "function") return 0;
+ if (typeof mod.FPDFPageObj_GetBounds !== "function") return null;
const buf = scratchPtr(m, SCRATCH.editBoxA, 16);
try {
if (!mod.FPDFPageObj_GetBounds(ptr, buf, buf + 4, buf + 8, buf + 12)) {
- return 0;
+ return null;
}
- return m.pdfium.getValue(buf + 8, "float");
+ return {
+ left: m.pdfium.getValue(buf, "float"),
+ right: m.pdfium.getValue(buf + 8, "float"),
+ };
} catch {
- return 0;
+ return null;
}
}
+const COMBINING_MARK = /\p{M}/u;
+
+/**
+ * Whether an object just drawn at `x` came out too narrow to hold `text`, the
+ * sign of a face whose glyphs draw nothing. Combining marks advance the pen by
+ * nothing, so they are judged by having ink rather than by width.
+ */
+export function drawnTooNarrow(
+ m: EditorDocument["module"],
+ ptr: number,
+ text: string,
+ size: number,
+ x: number,
+): boolean {
+ const visible = visibleCodePoints(text);
+ if (visible.length === 0) return false;
+ const ink = measureInkSpan(m, ptr);
+ if (!ink) return true;
+ const advancing = visible.filter(
+ (cp) => !COMBINING_MARK.test(String.fromCodePoint(cp)),
+ ).length;
+ return advancing > 0
+ ? ink.right - x < advancing * size * 0.05
+ : ink.right <= ink.left;
+}
+
// Emit one text object in `family`'s embedded face. Returns 0 when the font is
// uncached, refused, lacks the glyphs, or measured ~0-wide - caller substitutes.
export function emitDeviceFontTextObject(
@@ -279,9 +366,9 @@ export function emitDeviceFontTextObject(
y: number,
): number {
if (text.length === 0) return 0;
- const bytes = getExternalFontBytes(family);
+ const bytes = faceBytes(doc, family);
if (!bytes || bytes.length === 0) return 0;
- if (!deviceFontCovers(family, bytes, text)) return 0;
+ if (!deviceFontCovers(bytes, text)) return 0;
const fontPtr = loadDeviceFontInto(doc, family);
if (!fontPtr) return 0;
const m = doc.module;
@@ -298,9 +385,7 @@ export function emitDeviceFontTextObject(
m.FPDFPageObj_SetFillColor(fp, fill.r, fill.g, fill.b, fill.a);
m.FPDFPageObj_Transform(fp, 1, 0, 0, 1, x, y);
m.FPDFPage_InsertObject(page.pagePtr, fp);
- const right = measureRightEdge(m, fp);
- const visible = text.replace(/\s+/g, "").length;
- if (visible > 0 && right - x < visible * size * 0.05) {
+ if (drawnTooNarrow(m, fp, text, size, x)) {
try {
m.FPDFPage_RemoveObject(page.pagePtr, fp);
} catch {
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/util/documentFontCompletion.ts b/frontend/src/editor/core/tools/pdfTextEditor/util/documentFontCompletion.ts
index 800330d16b..0988786f25 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/util/documentFontCompletion.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/util/documentFontCompletion.ts
@@ -18,6 +18,7 @@ import {
import { embeddedFontProgram } from "@editor/tools/pdfTextEditor/util/embeddedFace";
import { compareFontPrograms } from "@editor/tools/pdfTextEditor/util/fontProgramMatch";
import { readFontName } from "@editor/tools/pdfTextEditor/charcode/FontHelpers";
+import { clearOnDocumentClose } from "@editor/tools/pdfTextEditor/pdfium/pointerCaches";
// Which font draws the characters an embedded subset lacks: the same typeface when installed or served, else the closest available one.
@@ -30,7 +31,7 @@ export interface FontCompletion {
source: FontCompletionSource;
}
-// Keyed by PDFium font handle, unique only within one open document: EditorStore resets them with its other pointer-keyed caches.
+// Keyed by PDFium font handle, unique only within one open document: cleared when any document closes.
const completions = new Map<number, FontCompletion>();
const refused = new Set<number>();
const lookedUp = new Map<number, LocalFont[]>();
@@ -59,6 +60,7 @@ export function resetFontCompletions(): void {
lookingUp.clear();
changed();
}
+clearOnDocumentClose(resetFontCompletions);
function drawable(family: string): boolean {
return (
@@ -203,6 +205,9 @@ export async function resolveOriginalFonts(
if (!fonts || fonts.length === 0) return;
const ids = new Set(fontIds);
for (const fontId of ids) {
+ // Each pass reads the font through the document: once it closes, the
+ // handle is a dangling pointer and PDFium reading it crashes the tab.
+ if (!stillOpen()) return;
const handle = documentFontHandle(fontId);
if (lookedUp.get(handle) === fonts || lookingUp.has(handle)) continue;
if (!fontCanBeCompleted(m, fontId)) continue;
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/util/documentFontStyle.ts b/frontend/src/editor/core/tools/pdfTextEditor/util/documentFontStyle.ts
new file mode 100644
index 0000000000..242f20fc16
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/util/documentFontStyle.ts
@@ -0,0 +1,94 @@
+import type { WrappedPdfiumModule } from "@embedpdf/pdfium";
+import { readFontName } from "@editor/tools/pdfTextEditor/charcode/FontHelpers";
+import {
+ documentFontHandle,
+ isItalicFamily,
+ stripSubsetTag,
+} from "@editor/tools/pdfTextEditor/util/fontFamily";
+import {
+ BOLD_WEIGHT,
+ parseFaceName,
+} from "@editor/tools/pdfTextEditor/util/faceNames";
+import { clearOnDocumentClose } from "@editor/tools/pdfTextEditor/pdfium/pointerCaches";
+
+/** The Italic bit of a font descriptor's /Flags (ISO 32000-1, table 123). */
+const ITALIC_FLAG = 1 << 6;
+/** The ForceBold bit of a font descriptor's /Flags (ISO 32000-1, table 123). */
+const FORCE_BOLD_FLAG = 1 << 18;
+
+interface DocumentFontStyle {
+ fontId: string;
+ /** The family /BaseFont names; empty when the PDF gives no name. */
+ family: string;
+ italic: boolean;
+ weight: number;
+}
+
+// Keyed by PDFium font handle, unique only within one open document: cleared when any document closes.
+const styleByHandle = new Map<number, DocumentFontStyle>();
+
+export function resetDocumentFontStyles(): void {
+ styleByHandle.clear();
+}
+clearOnDocumentClose(resetDocumentFontStyles);
+
+/**
+ * Record a document font's weight and slant. A fontId names the family from
+ * the font's own name table when it has one, which leaves the style out
+ * ("Georgia" for Georgia Bold Italic), so the style is read from where the PDF
+ * states it: the /BaseFont name first, then the descriptor's flags.
+ */
+export function noteDocumentFontStyle(
+ m: WrappedPdfiumModule,
+ fontPtr: number,
+ family?: string,
+): void {
+ if (!fontPtr || styleByHandle.has(fontPtr)) return;
+ // PDFium answers -1 for a font with no descriptor, which has every bit set.
+ const flags = Math.max(0, m.FPDFFont_GetFlags(fontPtr));
+ const baseFont = readFontName(m, fontPtr) ?? "";
+ const named = parseFaceName(baseFont);
+ // Not the descriptor's FontWeight: PDFium estimates it from stem widths when
+ // it is missing, which reads regular faces as light or semibold.
+ const weight =
+ !named.weightStated && flags & FORCE_BOLD_FLAG ? BOLD_WEIGHT : named.weight;
+ styleByHandle.set(fontPtr, {
+ fontId: `pdf:${fontPtr}:${family ?? stripSubsetTag(baseFont)}`,
+ family: named.family,
+ italic:
+ named.italic || isItalicFamily(baseFont) || (flags & ITALIC_FLAG) !== 0,
+ weight,
+ });
+}
+
+/** The fontId of every document font read so far, whichever run it ended up in. */
+export function documentFontIds(): string[] {
+ return [...styleByHandle.values()].map((style) => style.fontId);
+}
+
+/** The fontId a document font was read under, or null for a font no page read has met. */
+export function documentFontIdAt(fontPtr: number): string | null {
+ return styleByHandle.get(fontPtr)?.fontId ?? null;
+}
+
+/** Whether a run's fontId names an italic face, by its name or by what its document font declares. */
+export function isItalicFont(fontId: string): boolean {
+ return (
+ isItalicFamily(fontId) ||
+ styleByHandle.get(documentFontHandle(fontId))?.italic === true
+ );
+}
+
+/**
+ * The family a document font's /BaseFont names, or null for any other font or
+ * one not read yet. A fontId names the family PDFium loaded, which for a font
+ * the PDF does not embed is the stand-in PDFium drew it with.
+ */
+export function documentFontFamily(fontId: string): string | null {
+ return styleByHandle.get(documentFontHandle(fontId))?.family || null;
+}
+
+/** The weight a document font declares, or null for any other font or one not read yet. */
+export function documentFontWeight(fontId: string): number | null {
+ return styleByHandle.get(documentFontHandle(fontId))?.weight ?? null;
+}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/util/dom.ts b/frontend/src/editor/core/tools/pdfTextEditor/util/dom.ts
index 5a71ae0a49..531c777e63 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/util/dom.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/util/dom.ts
@@ -18,6 +18,10 @@ export function isFocusInFormField(): boolean {
return tag === "INPUT" || tag === "TEXTAREA" || tag === "SELECT";
}
+export function isModalOpen(): boolean {
+ return document.querySelector('[aria-modal="true"]') !== null;
+}
+
// The page index of the page nearest the viewport centre.
export function visiblePageNumber(): number {
const pages = pageElements();
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/util/embeddedFace.ts b/frontend/src/editor/core/tools/pdfTextEditor/util/embeddedFace.ts
index 68220f677e..91e0a29abb 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/util/embeddedFace.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/util/embeddedFace.ts
@@ -3,6 +3,7 @@ import {
SCRATCH,
scratchPtr,
} from "@editor/tools/pdfTextEditor/util/wasmScratch";
+import { clearOnDocumentClose } from "@editor/tools/pdfTextEditor/pdfium/pointerCaches";
// The overlay used to collapse every document font to one of three generic CSS
// stacks, so editing text visibly changed its shape. PDFium will hand back the
@@ -155,3 +156,4 @@ export function resetEmbeddedFaces(): void {
faceBytesHeld = 0;
generation++;
}
+clearOnDocumentClose(resetEmbeddedFaces);
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/util/exactLayout.ts b/frontend/src/editor/core/tools/pdfTextEditor/util/exactLayout.ts
index 7abc350896..7017c8cc4f 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/util/exactLayout.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/util/exactLayout.ts
@@ -46,7 +46,22 @@ export function buildExactLines(
lines.push(built);
lineStart = i + 1;
}
- return lines.length > 0 ? lines : null;
+ if (lines.length === 0) return null;
+ // An empty line draws nothing, so it has no pen position of its own. It
+ // takes a neighbour's: page x 0 would put the whole box at the page edge.
+ return lines.map((line, i) =>
+ Number.isFinite(line.left)
+ ? line
+ : { ...line, left: neighbourLeft(lines, i) ?? 0 },
+ );
+}
+
+function neighbourLeft(lines: ExactLine[], at: number): number | null {
+ for (let i = at - 1; i >= 0; i -= 1)
+ if (Number.isFinite(lines[i].left)) return lines[i].left;
+ for (let i = at + 1; i < lines.length; i += 1)
+ if (Number.isFinite(lines[i].left)) return lines[i].left;
+ return null;
}
function buildLine(
@@ -60,7 +75,10 @@ function buildLine(
let end = to;
while (end > from && SPACE.has(text[end - 1])) end -= 1;
if (end === from)
- return { left: firstFinite(positions.starts, from, to) ?? 0, tokens: [] };
+ return {
+ left: firstFinite(positions.starts, from, to) ?? Number.NaN,
+ tokens: [],
+ };
const left = positions.starts[from];
if (!Number.isFinite(left)) return null;
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/util/exportPdf.ts b/frontend/src/editor/core/tools/pdfTextEditor/util/exportPdf.ts
index c5f3bdd2a3..717b0d9936 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/util/exportPdf.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/util/exportPdf.ts
@@ -12,11 +12,20 @@ import {
MarkInfoError,
applyMarked,
} from "@editor/tools/pdfTextEditor/pdfdoc/passes/markTagged";
+import {
+ defineMissingGraphicsStates,
+ type ObjectOpacity,
+} from "@editor/tools/pdfTextEditor/pdfdoc/passes/defineMissingGraphicsStates";
import { nameArtifactKinds } from "@editor/tools/pdfTextEditor/pdfdoc/passes/nameArtifactKinds";
import { repairStructure } from "@editor/tools/pdfTextEditor/pdfdoc/passes/repairStructure";
import { setDocumentLanguage } from "@editor/tools/pdfTextEditor/pdfdoc/passes/setDocumentLanguage";
import { preserveShadings } from "@editor/tools/pdfTextEditor/pdfdoc/passes/preserveShadings";
import { subsetEmbeddedFonts } from "@editor/tools/pdfTextEditor/pdfdoc/passes/subsetEmbeddedFonts";
+import { readMatrix } from "@editor/tools/pdfTextEditor/commands/textPieces";
+import {
+ readObjFill,
+ readObjStroke,
+} from "@editor/tools/pdfTextEditor/pdfium/PdfiumObjectColour";
import { PdfiumSave } from "@editor/tools/pdfTextEditor/pdfium/PdfiumSave";
import { writesArtifactKinds } from "@editor/tools/pdfTextEditor/pdfium/PdfiumTagMarks";
import {
@@ -138,8 +147,6 @@ async function serializeEdits(
doc: EditorDocument,
incremental: boolean,
): Promise<Uint8Array> {
- commitPendingFormRemovals(doc);
-
// Must be read AFTER serialize: serialize is what marks pages regenerated,
// so reading first always yielded an empty list and silently skipped the
// shading repair on the first save after an edit.
@@ -153,6 +160,9 @@ async function serializeEdits(
);
}
const regenerated = doc.regeneratedPages();
+ bytes = await defineMissingGraphicsStates(bytes, regenerated, (index, at) =>
+ opacitiesAt(doc, index, at),
+ );
if (regenerated.length > 0 && doc.openedBytes.length > 0) {
try {
@@ -169,25 +179,29 @@ async function serializeEdits(
return bytes;
}
-interface FormRemovalModule {
- FPDFFormObj_RemoveObject?: (form: number, obj: number) => boolean;
-}
+// Within what PDFium's six significant digits leave of a transform.
+const MATRIX_SLACK = 1e-3;
-/**
- * Remove the form children that DeleteShapeCommand only hid. Done here, on the
- * user's save, rather than in every serialize: other serializes (the charcode
- * probe) must not make a delete permanent while it can still be undone.
- */
-function commitPendingFormRemovals(doc: EditorDocument): void {
- const m = doc.module as unknown as FormRemovalModule;
- for (const page of doc.loadedPages()) {
- if (page.pendingFormRemovals.size === 0) continue;
- for (const [objPtr, formPtr] of page.pendingFormRemovals) {
- m.FPDFFormObj_RemoveObject?.(formPtr, objPtr);
- }
- page.pendingFormRemovals.clear();
- page.markNeedsGenerate();
+function opacitiesAt(
+ doc: EditorDocument,
+ pageIndex: number,
+ at: number[],
+): ObjectOpacity[] {
+ const m = doc.module;
+ const pagePtr = doc.page(pageIndex).pagePtr;
+ const out: ObjectOpacity[] = [];
+ for (let i = 0; i < m.FPDFPage_CountObjects(pagePtr); i++) {
+ const obj = m.FPDFPage_GetObject(pagePtr, i);
+ const matrix = obj ? readMatrix(m, obj) : null;
+ const same = matrix?.every(
+ (v, k) => Math.abs(v - at[k]) <= MATRIX_SLACK * Math.max(1, Math.abs(v)),
+ );
+ if (!same) continue;
+ const fill = readObjFill(m, obj);
+ const stroke = readObjStroke(m, obj);
+ if (fill && stroke) out.push({ fill: fill.a, stroke: stroke.a });
}
+ return out;
}
function pdfBlob(bytes: Uint8Array): Blob {
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/util/faceNames.ts b/frontend/src/editor/core/tools/pdfTextEditor/util/faceNames.ts
new file mode 100644
index 0000000000..6c9ee18738
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/util/faceNames.ts
@@ -0,0 +1,181 @@
+// Reads the family, weight and slant out of a font name as PDFs and font
+// sources spell it: "ABCDEF+Calibri-Bold", "Arial,BoldItalic", "Segoe UI
+// Semibold", "TimesNewRomanPS-BoldItalicMT", "Georgia-Bold-Italic".
+
+export const REGULAR_WEIGHT = 400;
+export const BOLD_WEIGHT = 700;
+
+/** Semibold and heavier read as bold, as CSS `bolder` and the font sources' own bold flags do. */
+export function isBoldWeight(weight: number): boolean {
+ return weight >= 600;
+}
+
+export interface FaceStyle {
+ weight: number;
+ italic: boolean;
+}
+
+export interface ParsedFaceName extends FaceStyle {
+ family: string;
+ /** Whether the name says its weight, "Regular" included; false leaves the weight to other sources. */
+ weightStated: boolean;
+}
+
+const WEIGHT_WORDS: Record<string, number> = {
+ thin: 100,
+ hairline: 100,
+ extralight: 200,
+ ultralight: 200,
+ light: 300,
+ ligh: 300,
+ semilight: 350,
+ book: 400,
+ regular: 400,
+ regu: 400,
+ normal: 400,
+ roman: 400,
+ medium: 500,
+ // URW's abbreviation in its base-35 clones (NimbusRomNo9L-Medi stands in for
+ // Times-Bold); the full word "Medium" stays a true 500.
+ medi: BOLD_WEIGHT,
+ semibold: 600,
+ demibold: 600,
+ demi: 600,
+ bold: 700,
+ extrabold: 800,
+ ultrabold: 800,
+ heavy: 800,
+ black: 900,
+ extrablack: 950,
+ ultrablack: 950,
+};
+
+const ITALIC_WORDS = ["italic", "oblique", "slanted", "ital", "slant", "it"];
+/** PostScript names end in these vendor marks ("Arial-BoldMT", "TimesNewRomanPSMT"). */
+const VENDOR_MARKS = ["psmt", "mt", "ps"];
+const MODIFIERS = new Set(["extra", "ultra", "semi", "demi"]);
+
+const STYLE_WORDS = [
+ ...Object.keys(WEIGHT_WORDS),
+ ...ITALIC_WORDS,
+ ...VENDOR_MARKS,
+].sort((a, b) => b.length - a.length);
+
+const CAMEL_STYLE_SUFFIX =
+ /^(.*?[a-z0-9]{2})((?:Thin|ExtraLight|UltraLight|Light|Medium|SemiBold|Semibold|DemiBold|Demibold|ExtraBold|Bold|Black|Heavy|Italic|Oblique)+)$/;
+
+interface TokenStyle {
+ weight: number | null;
+ italic: boolean;
+}
+
+/** The style a token spells out entirely, or null when any of it is not a style word. */
+function readStyleToken(token: string): TokenStyle | null {
+ const lower = token.toLowerCase();
+ const variable = /^wght([0-9a-f]+)$/.exec(lower);
+ if (variable) {
+ const weight = Math.round(parseInt(variable[1], 16) / 65536);
+ return weight > 0 && weight <= 1000 ? { weight, italic: false } : null;
+ }
+ const numbered = /^w([1-9])$/.exec(lower);
+ if (numbered) return { weight: Number(numbered[1]) * 100, italic: false };
+ let at = 0;
+ let weight: number | null = null;
+ let italic = false;
+ let words = 0;
+ while (at < lower.length) {
+ const word = STYLE_WORDS.find((w) => lower.startsWith(w, at));
+ if (!word) return null;
+ if (word in WEIGHT_WORDS) weight = WEIGHT_WORDS[word];
+ else if (ITALIC_WORDS.includes(word)) italic = true;
+ else if (at + word.length !== lower.length) return null;
+ at += word.length;
+ words++;
+ }
+ return words > 0 ? { weight, italic } : null;
+}
+
+function tokensOf(name: string): string[] {
+ const tokens = name
+ .replace(/^[A-Z]{6}\+/, "")
+ .split(/[\s,_-]+/)
+ .filter(Boolean);
+ const merged: string[] = [];
+ for (let i = 0; i < tokens.length; i++) {
+ const next = tokens[i + 1];
+ if (
+ MODIFIERS.has(tokens[i].toLowerCase()) &&
+ next &&
+ readStyleToken(tokens[i] + next)
+ ) {
+ merged.push(tokens[i] + next);
+ i++;
+ } else {
+ merged.push(tokens[i]);
+ }
+ }
+ return merged;
+}
+
+function isStyleAt(tokens: string[], index: number): boolean {
+ // "Times New Roman" is a family, not Times New in its roman cut.
+ if (
+ tokens[index].toLowerCase() === "roman" &&
+ tokens[index - 1]?.toLowerCase() === "new"
+ )
+ return false;
+ return readStyleToken(tokens[index]) !== null;
+}
+
+function withoutVendorMark(token: string): string {
+ return token.replace(/(?<=[a-z])(PSMT|MT|PS)$/, "");
+}
+
+/** The family a font name belongs to and the weight and slant it names. */
+export function parseFaceName(name: string): ParsedFaceName {
+ const tokens = tokensOf(name.trim());
+ if (tokens.length === 0)
+ return {
+ family: name.trim(),
+ weight: REGULAR_WEIGHT,
+ italic: false,
+ weightStated: false,
+ };
+ let split = tokens.findIndex((_, i) => i > 0 && isStyleAt(tokens, i));
+ if (split < 0) {
+ const last = tokens[tokens.length - 1];
+ const camel = CAMEL_STYLE_SUFFIX.exec(withoutVendorMark(last));
+ if (camel) {
+ tokens.splice(tokens.length - 1, 1, camel[1], camel[2]);
+ split = tokens.length - 1;
+ } else {
+ split = tokens.length;
+ }
+ }
+ const familyTokens = tokens.slice(0, split);
+ familyTokens[familyTokens.length - 1] = withoutVendorMark(
+ familyTokens[familyTokens.length - 1],
+ );
+ let weight: number | null = null;
+ let variableWeight: number | null = null;
+ let italic = false;
+ for (const token of tokens.slice(split)) {
+ const style = readStyleToken(token);
+ if (!style) continue;
+ if (/^wght/i.test(token)) variableWeight = style.weight;
+ else if (style.weight !== null) weight = style.weight;
+ italic ||= style.italic;
+ }
+ const stated = variableWeight ?? weight;
+ return {
+ family: familyTokens.join(" "),
+ weight: stated ?? REGULAR_WEIGHT,
+ italic,
+ weightStated: stated !== null,
+ };
+}
+
+/** Spelling- and spacing-blind key, so "Trebuchet MS", "TrebuchetMS" and "Trebuchet-MS" are one family. */
+export function familyKey(family: string): string {
+ return family.toLowerCase().replace(/[^\p{L}\p{N}]+/gu, "");
+}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/util/fallbackFont.ts b/frontend/src/editor/core/tools/pdfTextEditor/util/fallbackFont.ts
index 47ce1a5dfe..16c27bbc3e 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/util/fallbackFont.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/util/fallbackFont.ts
@@ -3,13 +3,12 @@ import type { Page } from "@editor/tools/pdfTextEditor/model/Page";
import type { RGBA } from "@editor/tools/pdfTextEditor/types";
import { FontRef } from "@editor/tools/pdfTextEditor/model/FontRef";
import { parseTrueTypeCmap } from "@editor/tools/pdfTextEditor/charcode/CmapResolver";
-import { visibleCodePoints } from "@editor/tools/pdfTextEditor/util/deviceFontEmbed";
+import {
+ drawnTooNarrow,
+ visibleCodePoints,
+} from "@editor/tools/pdfTextEditor/util/deviceFontEmbed";
import { writeUtf16 } from "@editor/services/pdfiumService";
import { BASE_PATH } from "@editor/constants/app";
-import {
- SCRATCH,
- scratchPtr,
-} from "@editor/tools/pdfTextEditor/util/wasmScratch";
/** Client-side Unicode fallback font. */
// BASE_PATH-prefixed: a bare "/fonts/..." 404s on subpath deployments
@@ -35,6 +34,11 @@ function fallbackFontCovers(text: string): boolean {
return visibleCodePoints(text).every((cp) => coverage.has(cp));
}
+/** True when the fallback font has loaded and has a glyph for every visible character of `text`. */
+export function fallbackFontDraws(text: string): boolean {
+ return isFallbackFontReady() && fallbackFontCovers(text);
+}
+
interface ExtendedPdfiumRuntime {
HEAPU8: Uint8Array;
}
@@ -136,13 +140,6 @@ export function loadFallbackFontInto(doc: EditorDocument): number {
}
}
-/** Right edge (PDF points) of an object's visible bbox, or 0 if unmeasurable. */
-function measureRightEdge(m: EditorDocument["module"], ptr: number): number {
- const buf = scratchPtr(m, SCRATCH.fallbackL, 16);
- if (!m.FPDFPageObj_GetBounds(ptr, buf, buf + 4, buf + 8, buf + 12)) return 0;
- return m.pdfium.getValue(buf + 8, "float");
-}
-
interface CreateTextObjModule {
FPDFPageObj_CreateTextObj?: (
doc: number,
@@ -180,9 +177,7 @@ export function emitFallbackTextObject(
m.FPDFPageObj_SetFillColor(fp, fill.r, fill.g, fill.b, fill.a);
m.FPDFPageObj_Transform(fp, 1, 0, 0, 1, x, y);
m.FPDFPage_InsertObject(page.pagePtr, fp);
- const right = measureRightEdge(m, fp);
- const visible = text.replace(/\s+/g, "").length;
- if (visible > 0 && right - x < visible * size * 0.05) {
+ if (drawnTooNarrow(m, fp, text, size, x)) {
try {
m.FPDFPage_RemoveObject(page.pagePtr, fp);
} catch {
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/util/fontCapability.ts b/frontend/src/editor/core/tools/pdfTextEditor/util/fontCapability.ts
index 8687ed89c6..3a4ec8d203 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/util/fontCapability.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/util/fontCapability.ts
@@ -1,95 +1,10 @@
-import {
- familyOf,
- flipItalic,
- isItalicFamily,
- nearestStandardFont,
-} from "@editor/tools/pdfTextEditor/util/fontFamily";
+import { familyOf } from "@editor/tools/pdfTextEditor/util/fontFamily";
import { helveticaVariantFor } from "@editor/tools/pdfTextEditor/util/helveticaVariant";
-import {
- faceStyleFlags,
- knownFamilyOf,
- pickRequestedFace,
- resolveRequested,
- type LocalFont,
-} from "@editor/tools/pdfTextEditor/util/localFonts";
import {
fontCompletionFor,
fontNameRefused,
} from "@editor/tools/pdfTextEditor/util/documentFontCompletion";
-import {
- getExternalFontBytes,
- loadedExternalFonts,
-} from "@editor/tools/pdfTextEditor/util/externalFonts";
-
-// Whether a style change is actually possible for a run's face, and in which
-// family. The toolbar asks before offering the control: replacing a document's
-// own typeface with Helvetica-Oblique is not "making it italic", it is losing
-// the font.
-
-export type StyleSource = "base14" | "device";
-
-export interface StyleCapability {
- /** Family to emit, or null when nothing available can render the style. */
- family: string | null;
- source: StyleSource | null;
-}
-
-const NONE: StyleCapability = { family: null, source: null };
-
-/** The installed face for `family` in the requested style, or null. */
-function deviceFaceFor(
- fonts: LocalFont[],
- family: string,
- italic: boolean,
-): string | null {
- const req = resolveRequested(fonts, family);
- if (!req.family) return null;
- const face = pickRequestedFace(fonts, { ...req, italic });
- if (!face) return null;
- // pickRequestedFace always returns SOMETHING from a matching family, so the
- // style has to be checked: a family with no italic cut answers with upright.
- const flags = faceStyleFlags(face);
- if (flags.italic !== italic) return null;
- return [req.family, req.bold ? "Bold" : "", italic ? "Italic" : ""]
- .filter(Boolean)
- .join(" ");
-}
-
-/** Base-14 flips in place unless an external family of that name exists; others need a real face. */
-export function italicCapability(
- fontId: string,
- italic: boolean,
- fonts: LocalFont[] | null = loadedExternalFonts(),
-): StyleCapability {
- const family = familyOf(fontId);
- if (!family) return NONE;
- const flipped = flipItalic(family, italic);
- if (flipped && !hasExternalFamily(fonts, family)) {
- return { family: flipped, source: "base14" };
- }
- if (!fonts || fonts.length === 0) return NONE;
- const device = deviceFaceFor(fonts, family, italic);
- return device ? { family: device, source: "device" } : NONE;
-}
-
-function hasExternalFamily(fonts: LocalFont[] | null, family: string): boolean {
- if (!fonts || nearestStandardFont(family) === family) return false;
- return knownFamilyOf(fonts, family) !== null;
-}
-
-/** Whether every one of these runs can be flipped to the other italic state. */
-export function canToggleItalic(
- fontIds: string[],
- fonts: LocalFont[] | null = loadedExternalFonts(),
-): boolean {
- if (fontIds.length === 0) return false;
- // Deduped: each miss costs a linear scan of every installed face, and a
- // select-all hands this thousands of runs sharing a handful of fonts - on
- // every keystroke, because the toolbar state is derived from the snapshot.
- return [...new Set(fontIds)].every(
- (id) => italicCapability(id, !isItalicFamily(id), fonts).family !== null,
- );
-}
+import { getExternalFontBytes } from "@editor/tools/pdfTextEditor/util/externalFonts";
/**
* The family an edited run re-emits in once its own font cannot author the
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/util/fontFaces.ts b/frontend/src/editor/core/tools/pdfTextEditor/util/fontFaces.ts
new file mode 100644
index 0000000000..0f5c3bac87
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/util/fontFaces.ts
@@ -0,0 +1,366 @@
+// Fonts as families of faces: the picker lists a family once, and the bold,
+// italic and weight controls move a run between the faces its family really
+// has. A face is only ever one that exists; nothing here synthesises a style.
+
+import {
+ BOLD_WEIGHT,
+ REGULAR_WEIGHT,
+ familyKey,
+ isBoldWeight,
+ parseFaceName,
+ type FaceStyle,
+ type ParsedFaceName,
+} from "@editor/tools/pdfTextEditor/util/faceNames";
+import {
+ familyOf,
+ isDocumentFontId,
+} from "@editor/tools/pdfTextEditor/util/fontFamily";
+import {
+ documentFontFamily,
+ documentFontIds,
+ documentFontWeight,
+ isItalicFont,
+} from "@editor/tools/pdfTextEditor/util/documentFontStyle";
+import {
+ faceStyleFlags,
+ type LocalFont,
+} from "@editor/tools/pdfTextEditor/util/localFonts";
+
+export interface FaceOption extends FaceStyle {
+ /** What a font change takes to draw in this face: a standard font name, an external face name, or a document fontId. */
+ value: string;
+}
+
+export interface FontFamilyEntry {
+ key: string;
+ label: string;
+ /** The face nearest the upright regular one, which stands for the family in the picker. */
+ value: string;
+ faces: FaceOption[];
+}
+
+/** One run font's view of the faces it can move to: the document's own faces and the loaded external ones. */
+export interface FaceSources {
+ documentFamilies: FontFamilyEntry[];
+ externalFonts: LocalFont[] | null;
+}
+
+export type ToggleRequest = { bold: boolean } | { italic: boolean };
+
+export type StyleRequest = ToggleRequest | { weight: number };
+
+type NamedFace = FaceOption & { family: string };
+
+const BUILT_IN_FACE_NAMES = [
+ "Helvetica",
+ "Helvetica-Bold",
+ "Helvetica-Oblique",
+ "Helvetica-BoldOblique",
+ "Times-Roman",
+ "Times-Bold",
+ "Times-Italic",
+ "Times-BoldItalic",
+ "Courier",
+ "Courier-Bold",
+ "Courier-Oblique",
+ "Courier-BoldOblique",
+];
+
+function distance(face: FaceStyle, want: FaceStyle): number {
+ return (
+ Math.abs(face.weight - want.weight) +
+ (face.italic === want.italic ? 0 : 1e4)
+ );
+}
+
+function nearest<T extends FaceStyle>(faces: T[], want: FaceStyle): T | null {
+ let best: T | null = null;
+ for (const face of faces)
+ if (!best || distance(face, want) < distance(best, want)) best = face;
+ return best;
+}
+
+function familyEntry(label: string, faces: NamedFace[]): FontFamilyEntry {
+ const unique: NamedFace[] = [];
+ for (const face of faces) {
+ if (
+ !unique.some((u) => u.weight === face.weight && u.italic === face.italic)
+ )
+ unique.push(face);
+ }
+ unique.sort(
+ (a, b) => Number(a.italic) - Number(b.italic) || a.weight - b.weight,
+ );
+ const regular =
+ nearest(unique, { weight: REGULAR_WEIGHT, italic: false }) ?? unique[0];
+ return {
+ key: familyKey(label),
+ label: regular.family || label,
+ value: regular.value,
+ faces: unique.map(({ value, weight, italic }) => ({
+ value,
+ weight,
+ italic,
+ })),
+ };
+}
+
+/** Faces grouped into families by name, in the order each family first appears. */
+function groupFaces(faces: NamedFace[]): FontFamilyEntry[] {
+ const byKey = new Map<string, NamedFace[]>();
+ for (const face of faces) {
+ const key = familyKey(face.family);
+ const members = byKey.get(key);
+ if (members) members.push(face);
+ else byKey.set(key, [face]);
+ }
+ return [...byKey.values()].map((members) =>
+ familyEntry(members[0].family, members),
+ );
+}
+
+export const BUILT_IN_FAMILIES: FontFamilyEntry[] = groupFaces(
+ BUILT_IN_FACE_NAMES.map((name) => ({ value: name, ...parseFaceName(name) })),
+);
+
+const BUILT_IN_KEYS = new Set(BUILT_IN_FAMILIES.map((entry) => entry.key));
+
+function statedWeight(text: string): number | null {
+ const parsed = parseFaceName(`x ${text}`);
+ return parsed.weightStated ? parsed.weight : null;
+}
+
+function externalWeight(font: LocalFont, named: ParsedFaceName): number {
+ const own = font.axes
+ ? (font.axes.weight ?? (font.axes.bold ? BOLD_WEIGHT : REGULAR_WEIGHT))
+ : (statedWeight(font.style) ??
+ statedWeight(font.postscriptName.split("-").slice(1).join(" ")) ??
+ (faceStyleFlags(font).bold ? BOLD_WEIGHT : REGULAR_WEIGHT));
+ // A family named for its weight ("Segoe UI Semibold") calls that cut "Regular".
+ return own !== REGULAR_WEIGHT || !named.weightStated ? own : named.weight;
+}
+
+// The picker name `pickLocalFontFace` resolves back to this face. Regular and
+// bold cuts go by family and style words; any other weight by its full name.
+function externalFaceValue(
+ font: LocalFont,
+ named: ParsedFaceName,
+ style: FaceStyle,
+): string {
+ const family = named.weightStated ? named.family : font.family;
+ if (style.weight === REGULAR_WEIGHT)
+ return style.italic ? `${family} Italic` : family;
+ if (style.weight === BOLD_WEIGHT)
+ return style.italic ? `${family} Bold Italic` : `${family} Bold`;
+ return font.fullName || `${font.family} ${font.style}`.trim();
+}
+
+const externalCache = new WeakMap<LocalFont[], FontFamilyEntry[]>();
+
+/** Server or device faces as families, sorted by name. Reference-stable per font list. */
+export function externalFamilies(fonts: LocalFont[] | null): FontFamilyEntry[] {
+ if (!fonts) return [];
+ const cached = externalCache.get(fonts);
+ if (cached) return cached;
+ const faces = fonts.flatMap((font) => {
+ if (!font.family) return [];
+ const named = parseFaceName(font.family);
+ const style = {
+ weight: externalWeight(font, named),
+ italic: named.italic || faceStyleFlags(font).italic,
+ };
+ return [
+ {
+ ...style,
+ family: named.family,
+ value: externalFaceValue(font, named, style),
+ },
+ ];
+ });
+ const families = groupFaces(faces).sort((a, b) =>
+ a.label.localeCompare(b.label, undefined, { sensitivity: "base" }),
+ );
+ externalCache.set(fonts, families);
+ return families;
+}
+
+/** The weight and slant of the face a run is drawn in. */
+export function faceStyleOf(fontId: string): FaceStyle {
+ const named = parseFaceName(familyOf(fontId));
+ return {
+ weight: documentFontWeight(fontId) ?? named.weight,
+ italic: named.italic || isItalicFont(fontId),
+ };
+}
+
+function familyNameOf(fontId: string): string {
+ return documentFontFamily(fontId) ?? parseFaceName(familyOf(fontId)).family;
+}
+
+export function fontFamilyKey(fontId: string): string {
+ return familyKey(familyNameOf(fontId));
+}
+
+/** The document's fonts as families: those `fontIds` name and every one read from its pages. */
+export function knownDocumentFamilies(
+ fontIds: Iterable<string>,
+): FontFamilyEntry[] {
+ return documentFamilies([...fontIds, ...documentFontIds()]);
+}
+
+/** The document fonts among `fontIds` as families. */
+export function documentFamilies(fontIds: Iterable<string>): FontFamilyEntry[] {
+ const faces: NamedFace[] = [];
+ for (const fontId of new Set(fontIds)) {
+ if (!isDocumentFontId(fontId)) continue;
+ // The font's own name for its family reads better ("Liberation Sans" over "LiberationSans") when it is the same family.
+ const named = parseFaceName(familyOf(fontId)).family;
+ const family = familyNameOf(fontId);
+ faces.push({
+ ...faceStyleOf(fontId),
+ family: familyKey(named) === familyKey(family) ? named : family,
+ value: fontId,
+ });
+ }
+ return groupFaces(faces);
+}
+
+/** The families a run's font can move within, the document's own faces first. */
+export function familiesOfFont(
+ fontId: string,
+ sources: FaceSources,
+): FontFamilyEntry[] {
+ const key = fontFamilyKey(fontId);
+ if (BUILT_IN_KEYS.has(key))
+ return BUILT_IN_FAMILIES.filter((entry) => entry.key === key);
+ const own = sources.documentFamilies.find((entry) => entry.key === key);
+ const external = externalFamilies(sources.externalFonts).find(
+ (entry) => entry.key === key,
+ );
+ // "Times New Roman" and "Courier New" with no face of their own still have the standard font they are drawn after.
+ const standard = BUILT_IN_FAMILIES.find((entry) => key.startsWith(entry.key));
+ return [own, external, standard].filter(
+ (entry): entry is FontFamilyEntry => !!entry,
+ );
+}
+
+function faceFor(
+ entry: FontFamilyEntry,
+ current: FaceStyle,
+ request: StyleRequest,
+): FaceOption | null {
+ if ("bold" in request) {
+ return nearest(
+ entry.faces.filter(
+ (f) =>
+ f.italic === current.italic &&
+ isBoldWeight(f.weight) === request.bold,
+ ),
+ {
+ weight: request.bold ? BOLD_WEIGHT : REGULAR_WEIGHT,
+ italic: current.italic,
+ },
+ );
+ }
+ if ("italic" in request) {
+ return nearest(
+ entry.faces.filter(
+ (f) =>
+ f.italic === request.italic &&
+ isBoldWeight(f.weight) === isBoldWeight(current.weight),
+ ),
+ { weight: current.weight, italic: request.italic },
+ );
+ }
+ return nearest(
+ entry.faces.filter((f) => f.weight === request.weight),
+ { weight: request.weight, italic: current.italic },
+ );
+}
+
+function alreadyStyled(current: FaceStyle, request: StyleRequest): boolean {
+ if ("bold" in request) return isBoldWeight(current.weight) === request.bold;
+ if ("italic" in request) return current.italic === request.italic;
+ return current.weight === request.weight;
+}
+
+/**
+ * The face a run's font takes on for `request`: undefined when it is already
+ * in that style, null when its family has no such face.
+ */
+export function restyledFace(
+ fontId: string,
+ request: StyleRequest,
+ sources: FaceSources,
+): string | null | undefined {
+ const current = faceStyleOf(fontId);
+ if (alreadyStyled(current, request)) return undefined;
+ for (const entry of familiesOfFont(fontId, sources)) {
+ const face = faceFor(entry, current, request);
+ if (face) return face.value;
+ }
+ return null;
+}
+
+/** Whether a run's family has any face of `request`'s weight or slant, whatever its other axis. */
+export function familyHasStyle(
+ fontId: string,
+ request: ToggleRequest,
+ sources: FaceSources,
+): boolean {
+ return familiesOfFont(fontId, sources).some((entry) =>
+ entry.faces.some((face) =>
+ "bold" in request
+ ? isBoldWeight(face.weight) === request.bold
+ : face.italic === request.italic,
+ ),
+ );
+}
+
+/** Whether every one of these runs is in `request`'s style or has a face for it. */
+export function canRestyle(
+ fontIds: string[],
+ request: StyleRequest,
+ sources: FaceSources,
+): boolean {
+ if (fontIds.length === 0) return false;
+ return [...new Set(fontIds)].every(
+ (id) => restyledFace(id, request, sources) !== null,
+ );
+}
+
+/** The face of `entry` nearest a run's own weight and slant, so picking a family keeps bold text bold. */
+export function faceKeepingStyle(
+ entry: FontFamilyEntry,
+ style: FaceStyle,
+): string {
+ const sameClass = entry.faces.filter(
+ (f) =>
+ f.italic === style.italic &&
+ isBoldWeight(f.weight) === isBoldWeight(style.weight),
+ );
+ return (nearest(sameClass, style) ?? nearest(entry.faces, style) ?? entry)
+ .value;
+}
+
+/** The family `value` is a face of, among every family the picker can list. */
+export function familyOfFace(
+ value: string,
+ sources: FaceSources,
+): FontFamilyEntry | null {
+ const all = [
+ ...sources.documentFamilies,
+ ...BUILT_IN_FAMILIES,
+ ...externalFamilies(sources.externalFonts),
+ ];
+ return (
+ all.find((entry) => entry.faces.some((f) => f.value === value)) ?? null
+ );
+}
+
+/** Whether a family has a weight beyond regular and bold, which the toggles alone cannot reach. */
+export function hasExtraWeights(entry: FontFamilyEntry): boolean {
+ return entry.faces.some(
+ (f) => f.weight !== REGULAR_WEIGHT && f.weight !== BOLD_WEIGHT,
+ );
+}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/util/growEdge.ts b/frontend/src/editor/core/tools/pdfTextEditor/util/growEdge.ts
new file mode 100644
index 0000000000..a80d3fd2bb
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/util/growEdge.ts
@@ -0,0 +1,78 @@
+import {
+ RENDER_MODE_INVISIBLE,
+ type TextRunSnapshot,
+} from "@editor/tools/pdfTextEditor/types";
+import { isMostlyRtl } from "@editor/tools/pdfTextEditor/util/bidi";
+
+// Typed text stops this many ems short of the next text on its rows.
+const EDGE_GAP_EM = 0.5;
+// Another box shares a row when they overlap by this share of the shorter one; the lines above and below touch only at their ascenders and descenders.
+const SAME_ROW_SHARE = 0.3;
+// A box starting this many ems inside the run's own already sits over it, as a superscript or an inline mark does, and is no edge to grow to.
+const OVERLAP_SLACK_EM = 0.25;
+
+/**
+ * How far text typed into a run in Grow may run before it must wrap, short of
+ * other text set beside it on its rows such as the next column, in PDF x.
+ * Left-to-right text grows to the right and right-to-left text to the left,
+ * so `side` says which way the edge lies.
+ */
+export interface GrowEdge {
+ side: "left" | "right";
+ x: number;
+}
+
+function sharesRow(run: TextRunSnapshot, other: TextRunSnapshot): boolean {
+ const top = Math.min(
+ run.bounds.y + run.bounds.height,
+ other.bounds.y + other.bounds.height,
+ );
+ const bottom = Math.max(run.bounds.y, other.bounds.y);
+ const shorter = Math.min(run.bounds.height, other.bounds.height);
+ return shorter > 0 && top - bottom > SAME_ROW_SHARE * shorter;
+}
+
+/** The edge other text sets `run` among `runs`, or null when none stands beside it. */
+export function growEdge(
+ run: TextRunSnapshot,
+ runs: readonly TextRunSnapshot[],
+): GrowEdge | null {
+ const em = Math.max(run.fontSize, 4);
+ const invisible = run.renderMode === RENDER_MODE_INVISIBLE;
+ const left = run.bounds.x;
+ const right = run.bounds.x + run.bounds.width;
+ const slack = OVERLAP_SLACK_EM * em;
+ const rtl = isMostlyRtl(run.text);
+ let nearest: number | null = null;
+ for (const other of runs) {
+ if (other.id === run.id || !other.text.trim()) continue;
+ if ((other.renderMode === RENDER_MODE_INVISIBLE) !== invisible) continue;
+ if (!sharesRow(run, other)) continue;
+ const otherRight = other.bounds.x + other.bounds.width;
+ if (rtl) {
+ if (otherRight > left + slack) continue;
+ if (nearest === null || otherRight > nearest) nearest = otherRight;
+ } else {
+ if (other.bounds.x < right - slack) continue;
+ if (nearest === null || other.bounds.x < nearest)
+ nearest = other.bounds.x;
+ }
+ }
+ if (nearest === null) return null;
+ const gap = EDGE_GAP_EM * em;
+ return rtl
+ ? { side: "left", x: nearest + gap }
+ : { side: "right", x: nearest - gap };
+}
+
+/** Every run's {@link growEdge}, by run id. */
+export function growEdges(
+ runs: readonly TextRunSnapshot[],
+): Map<string, GrowEdge> {
+ const out = new Map<string, GrowEdge>();
+ for (const run of runs) {
+ const edge = growEdge(run, runs);
+ if (edge) out.set(run.id, edge);
+ }
+ return out;
+}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/util/imageClip.ts b/frontend/src/editor/core/tools/pdfTextEditor/util/imageClip.ts
new file mode 100644
index 0000000000..5e3dc17946
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/util/imageClip.ts
@@ -0,0 +1,146 @@
+import type { WrappedPdfiumModule } from "@embedpdf/pdfium";
+import type { Affine, PageRect } from "@editor/tools/pdfTextEditor/types";
+import {
+ applyAffine,
+ composeAffine,
+} from "@editor/tools/pdfTextEditor/model/affine";
+import { chainTo } from "@editor/tools/pdfTextEditor/commands/liftFromForm";
+import { readMatrix } from "@editor/tools/pdfTextEditor/commands/textPieces";
+import {
+ SCRATCH,
+ scratchPtr,
+} from "@editor/tools/pdfTextEditor/util/wasmScratch";
+
+const IDENTITY: Affine = { a: 1, b: 0, c: 0, d: 1, e: 0, f: 0 };
+// Points of slack before a clip counts as hiding part of an image.
+const HIDES_SLACK_PT = 0.5;
+
+/** An image's bounds and the page-space box of the clips it is drawn through. */
+interface ClippedImage {
+ bounds: PageRect;
+ clip?: PageRect | null;
+}
+
+function intersectRect(a: PageRect, b: PageRect): PageRect {
+ const x = Math.max(a.x, b.x);
+ const y = Math.max(a.y, b.y);
+ return {
+ x,
+ y,
+ width: Math.max(0, Math.min(a.x + a.width, b.x + b.width) - x),
+ height: Math.max(0, Math.min(a.y + a.height, b.y + b.height) - y),
+ };
+}
+
+// The box around one object's clip in page space, or null when it has none.
+// A curve's control points bound the curve, so the box never cuts it.
+function clipBox(
+ m: WrappedPdfiumModule,
+ obj: number,
+ toPage: Affine,
+): PageRect | null {
+ const clip = m.FPDFPageObj_GetClipPath(obj);
+ if (!clip) return null;
+ const paths = m.FPDFClipPath_CountPaths(clip);
+ if (paths <= 0) return null;
+ const buf = scratchPtr(m, SCRATCH.liftClipPoint, 8);
+ let box: PageRect | null = null;
+ for (let path = 0; path < paths; path++) {
+ const xs: number[] = [];
+ const ys: number[] = [];
+ const count = m.FPDFClipPath_CountPathSegments(clip, path);
+ for (let i = 0; i < count; i++) {
+ const segment = m.FPDFClipPath_GetPathSegment(clip, path, i);
+ if (!segment || !m.FPDFPathSegment_GetPoint(segment, buf, buf + 4))
+ continue;
+ const p = applyAffine(
+ toPage,
+ m.pdfium.getValue(buf, "float"),
+ m.pdfium.getValue(buf + 4, "float"),
+ );
+ xs.push(p.x);
+ ys.push(p.y);
+ }
+ if (xs.length === 0) continue;
+ const x = Math.min(...xs);
+ const y = Math.min(...ys);
+ const pathBox = {
+ x,
+ y,
+ width: Math.max(...xs) - x,
+ height: Math.max(...ys) - y,
+ };
+ box = narrowTo(box, pathBox);
+ }
+ return box;
+}
+
+function narrowTo(box: PageRect | null, next: PageRect): PageRect {
+ return box ? intersectRect(box, next) : next;
+}
+
+function toAffine(matrix: Float32Array): Affine {
+ const [a, b, c, d, e, f] = matrix;
+ return { a, b, c, d, e, f };
+}
+
+/**
+ * The page-space box of the clips an image is drawn through: its own and
+ * those of every form that draws it. Null when nothing clips it.
+ */
+export function readImageClip(
+ m: WrappedPdfiumModule,
+ pagePtr: number,
+ objPtr: number,
+ containerPtr: number,
+): PageRect | null {
+ if (!objPtr) return null;
+ const chain = containerPtr ? (chainTo(m, pagePtr, containerPtr) ?? []) : [];
+ let toPage = IDENTITY;
+ let box: PageRect | null = null;
+ for (const form of chain) {
+ const formBox = clipBox(m, form, toPage);
+ if (formBox) box = narrowTo(box, formBox);
+ const matrix = readMatrix(m, form);
+ if (matrix) toPage = composeAffine(toPage, toAffine(matrix));
+ }
+ const own = clipBox(m, objPtr, toPage);
+ if (own) box = narrowTo(box, own);
+ return box;
+}
+
+/** What of an image shows on the page: its bounds cut to its clip. */
+export function visibleImageBounds(image: ClippedImage): PageRect {
+ return image.clip ? intersectRect(image.bounds, image.clip) : image.bounds;
+}
+
+/** True when the image's clip hides part of what it draws. */
+export function clipHidesImage(image: ClippedImage): boolean {
+ if (!image.clip) return false;
+ const shown = visibleImageBounds(image);
+ return (
+ shown.width < image.bounds.width - HIDES_SLACK_PT ||
+ shown.height < image.bounds.height - HIDES_SLACK_PT
+ );
+}
+
+/**
+ * The image bounds that put its visible part at `nextVisible`: the move or
+ * scale that takes the visible box from where it is to `nextVisible`, applied
+ * to the whole image, which carries its clip with it.
+ */
+export function imageBoundsForVisible(
+ image: ClippedImage,
+ nextVisible: PageRect,
+): PageRect {
+ const shown = visibleImageBounds(image);
+ const sx = shown.width > 1e-6 ? nextVisible.width / shown.width : 1;
+ const sy = shown.height > 1e-6 ? nextVisible.height / shown.height : 1;
+ const b = image.bounds;
+ return {
+ x: nextVisible.x + (b.x - shown.x) * sx,
+ y: nextVisible.y + (b.y - shown.y) * sy,
+ width: b.width * sx,
+ height: b.height * sy,
+ };
+}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/util/imagePixels.ts b/frontend/src/editor/core/tools/pdfTextEditor/util/imagePixels.ts
index f7530e167f..0a480e0f33 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/util/imagePixels.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/util/imagePixels.ts
@@ -102,3 +102,14 @@ function heapView(m: WrappedPdfiumModule): Uint8Array {
).memory;
return new Uint8Array(memory.buffer);
}
+
+/** The pixels of image `imageId` as the open document draws them, or null. */
+export function readShownImagePixels(
+ store: { document: EditorDocument | null },
+ pageIndex: number,
+ imageId: string,
+): ImagePixels | null {
+ const doc = store.document;
+ const ptr = doc?.page(pageIndex).findImage(imageId)?.pdfiumObjPtr ?? 0;
+ return doc && ptr ? readImageObjectPixels(doc, pageIndex, ptr) : null;
+}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/util/insertPageObject.ts b/frontend/src/editor/core/tools/pdfTextEditor/util/insertPageObject.ts
new file mode 100644
index 0000000000..9bf9fe5385
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/util/insertPageObject.ts
@@ -0,0 +1,39 @@
+import type { WrappedPdfiumModule } from "@embedpdf/pdfium";
+
+interface IndexedInsertModule {
+ FPDFPage_InsertObjectAtIndex?: (
+ page: number,
+ obj: number,
+ index: number,
+ ) => boolean | number;
+}
+
+/** PDFium's indexed insert, or undefined in a build without it. */
+export function indexedInsertOf(
+ m: WrappedPdfiumModule,
+): IndexedInsertModule["FPDFPage_InsertObjectAtIndex"] {
+ return (m as unknown as IndexedInsertModule).FPDFPage_InsertObjectAtIndex;
+}
+
+/**
+ * Puts a detached object on the page at `index` in content order, or last
+ * when `index` is negative, past the end of the page, or this build has no
+ * indexed insert.
+ *
+ * PDFium destroys an object it is asked to insert past the end, so an index
+ * recorded earlier is never passed through as it is: the page may have lost
+ * objects since, and the caller would be left holding a freed pointer.
+ */
+export function insertPageObjectAt(
+ m: WrappedPdfiumModule,
+ pagePtr: number,
+ objPtr: number,
+ index: number,
+): void {
+ const insertAt = indexedInsertOf(m);
+ if (index < 0 || !insertAt) {
+ m.FPDFPage_InsertObject(pagePtr, objPtr);
+ return;
+ }
+ insertAt(pagePtr, objPtr, Math.min(index, m.FPDFPage_CountObjects(pagePtr)));
+}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/util/localFonts.ts b/frontend/src/editor/core/tools/pdfTextEditor/util/localFonts.ts
index 30cae3d29a..dcdfcd0b43 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/util/localFonts.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/util/localFonts.ts
@@ -27,16 +27,6 @@ export interface LocalFont {
axes?: FaceAxes;
}
-export interface FontFamilyOption {
- value: string;
- label: string;
-}
-
-export interface LocalFontFamily {
- family: string;
- styles: string[];
-}
-
/** Feature detection only - never prompts and has no side effects. */
export function isLocalFontAccessSupported(): boolean {
return hasDeviceFontSource();
@@ -105,62 +95,6 @@ export function resetLocalFontsCache(): void {
bytesPending.clear();
}
-function compareNames(a: string, b: string): number {
- return a.localeCompare(b, undefined, { sensitivity: "base" });
-}
-
-/** Collapse the face list into families with styles, sorted and de-duplicated. */
-export function groupByFamily(fonts: LocalFont[]): LocalFontFamily[] {
- const byFamily = new Map<string, LocalFontFamily>();
- for (const font of fonts) {
- if (!font.family) continue;
- const key = font.family.toLowerCase();
- let entry = byFamily.get(key);
- if (!entry) {
- entry = { family: font.family, styles: [] };
- byFamily.set(key, entry);
- }
- const style = font.style;
- if (!style) continue;
- const seen = entry.styles.some(
- (s) => s.toLowerCase() === style.toLowerCase(),
- );
- if (!seen) entry.styles.push(style);
- }
- const families = [...byFamily.values()];
- for (const entry of families) entry.styles.sort(compareNames);
- families.sort((a, b) => compareNames(a.family, b.family));
- return families;
-}
-
-/** Picker options per family, plus a Bold entry where an upright bold cut exists; `taken` names are left out. */
-export function familyOptions(
- fonts: LocalFont[] | null,
- taken: string[],
-): FontFamilyOption[] {
- if (!fonts) return [];
- const hidden = new Set(taken.map(normaliseName));
- const families = groupByFamily(fonts);
- const listed = new Set([
- ...hidden,
- ...families.map(({ family }) => normaliseName(family)),
- ]);
- const withBold = new Set<string>();
- for (const font of fonts) {
- const flags = faceStyleFlags(font);
- if (flags.bold && !flags.italic) withBold.add(normaliseName(font.family));
- }
- return families.flatMap(({ family }) => {
- const key = normaliseName(family);
- if (hidden.has(key)) return [];
- const options = [{ value: family, label: family }];
- if (withBold.has(key) && !listed.has(normaliseName(`${family} Bold`))) {
- options.push({ value: `${family} Bold`, label: `${family} Bold` });
- }
- return options;
- });
-}
-
/** Case/separator-insensitive key, so "Segoe-UI" and "Segoe UI" are one name. */
export function normaliseName(name: string): string {
return name
@@ -192,7 +126,7 @@ export function splitRequested(requested: string): RequestedFace {
return { family: family || spaced, ...styleAxes(spaced) };
}
-export function knownFamilyOf(
+function knownFamilyOf(
fonts: LocalFont[],
requested: string,
): RequestedFace | null {
@@ -211,7 +145,7 @@ export function knownFamilyOf(
return best;
}
-export function resolveRequested(
+function resolveRequested(
fonts: LocalFont[],
requested: string,
): RequestedFace {
@@ -292,7 +226,7 @@ export function pickLocalFontFace(
);
}
-export function pickRequestedFace(
+function pickRequestedFace(
fonts: LocalFont[],
wanted: RequestedFace,
): LocalFont | null {
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/util/overlayPainter.ts b/frontend/src/editor/core/tools/pdfTextEditor/util/overlayPainter.ts
index a0122a8608..d9ea187c98 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/util/overlayPainter.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/util/overlayPainter.ts
@@ -138,17 +138,23 @@ function predictedAdvance(
sourceAdvancePx: number,
opts: PaintOptions,
): number | null {
- if (text === "" || source === "") return null;
- const sourceNatural = measureAdvancePx(source, opts.font);
- if (!(sourceNatural > 0) || !(sourceAdvancePx > 0)) return null;
- const ratio = sourceAdvancePx / sourceNatural;
+ if (text === "") return null;
const table = opts.advanceEm;
+ const sourceNatural = source ? measureAdvancePx(source, opts.font) : 0;
+ // A line's trailing space token has no advance of its own: the engine trims
+ // it. Letters typed into it are priced from the table alone.
+ const sized = sourceNatural > 0 && sourceAdvancePx > 0;
+ if (!sized && (!table || table.size === 0)) return null;
+ const ratio = sized ? sourceAdvancePx / sourceNatural : 1;
if (!table || table.size === 0) {
const natural = measureAdvancePx(text, opts.font);
return natural > 0 ? natural * ratio : null;
}
- let total = 0;
- for (const ch of text) {
+ // Letters typed after the token still advance the pen the document set its
+ // own letters to, so only what follows them is priced.
+ const kept = sized && text.startsWith(source) ? source.length : 0;
+ let total = kept > 0 ? sourceAdvancePx : 0;
+ for (const ch of text.slice(kept)) {
const em = table.get(ch);
total +=
em === undefined
@@ -191,6 +197,30 @@ function isLineBreak(node: Node): node is HTMLElement {
*/
function blockLines(element: HTMLElement): string[] {
if ((element.textContent ?? "") === "") return [""];
+ const lines = flowLines(element);
+ // A break that ends a block draws no line of its own: WebKit merges a line up into a blank one by putting its text in front of that block's filler break.
+ if (lines.length > 1 && lines.at(-1) === "" && endsWithBreak(element))
+ lines.pop();
+ return lines;
+}
+
+// Merging two lines with Backspace leaves the lower one as an inline span on the upper one's line, not a line of its own.
+const BLOCK_TAGS =
+ /^(DIV|P|LI|UL|OL|H[1-6]|BLOCKQUOTE|PRE|TABLE|TR|SECTION|ARTICLE)$/;
+
+function isLineElement(node: HTMLElement): boolean {
+ return node.hasAttribute(LINE_ATTR) || BLOCK_TAGS.test(node.tagName);
+}
+
+function endsWithBreak(node: Node): boolean {
+ let last: Node | null = node.lastChild;
+ while (last && last.nodeType !== Node.TEXT_NODE && last.lastChild)
+ last = last.lastChild;
+ return last instanceof HTMLElement && last.tagName === "BR";
+}
+
+/** The text under `element`, split at every <br>. */
+function flowLines(element: HTMLElement): string[] {
const lines: string[] = [""];
const walk = (node: Node): void => {
if (node.nodeType === Node.TEXT_NODE) {
@@ -233,6 +263,13 @@ export function readOverlayText(element: HTMLElement): string {
lastWasTrailingBr = true;
continue;
}
+ if (!isLineElement(node)) {
+ const [first, ...rest] = flowLines(node);
+ lines[lines.length - 1] += first;
+ lines.push(...rest);
+ lastWasTrailingBr = rest.length > 0 && endsWithBreak(node);
+ continue;
+ }
// Block children carry whole lines, so the seed is not one of them.
if (!sawBlock && lines.length === 1 && lines[0] === "") lines.length = 0;
sawBlock = true;
@@ -304,7 +341,10 @@ function plainOffset(
}
const host = document.createElement("div");
host.appendChild(range.cloneContents());
- // A <br> just before the caret is a real break, not the trailing filler readOverlayText drops.
+ // A <br> just before the caret is a real break, not the trailing filler readOverlayText drops, whether it ends the text or the line the caret is in.
+ const last = host.lastChild;
+ if (last instanceof HTMLElement && isLineElement(last))
+ last.appendChild(document.createTextNode(""));
host.appendChild(document.createTextNode(""));
const chars = readOverlayText(host).length;
// A caret parked on the container BETWEEN two line children sits at the
@@ -381,20 +421,52 @@ export function restoreCaretOffset(el: HTMLElement, offset: number): void {
setCollapsed(selection, at.node, at.offset);
}
+/** Run `paint`, which replaces the run's nodes, then put back the caret or selected range it held when `restore`. */
+export function repaintKeepingSelection(
+ el: HTMLElement,
+ restore: boolean,
+ paint: () => void,
+): void {
+ if (!restore) {
+ paint();
+ return;
+ }
+ // Reading the selection lays the page out, so a run that is not taking it back skips the read: a page of 5,000 runs painting in turn spent seconds re-laying itself out.
+ const selected = plainSelectionRange(el);
+ const caret = plainCaretOffset(el);
+ paint();
+ const range = selected && plainDomRange(el, selected);
+ const selection = window.getSelection();
+ if (range && selection) {
+ selection.removeAllRanges();
+ selection.addRange(range);
+ } else if (caret !== null) {
+ restoreCaretOffset(el, caret);
+ }
+}
+
const TEXT_RANGE_HIGHLIGHT = "pdf-editor-text-range";
+export const FIND_MATCH_HIGHLIGHT = "pdf-editor-find-match";
/**
- * Paint `range` as selected text, through the CSS Custom Highlight API, until
- * the returned cleanup runs. One range at a time: a later call replaces it.
- * Does nothing where the browser lacks the API.
+ * Paint `range` through the CSS Custom Highlight API, as selected text unless
+ * another highlight `name` is given, until the returned cleanup runs. One range
+ * per name: a later call replaces it. Does nothing where the browser lacks the API.
*/
-export function highlightTextRange(range: Range): () => void {
- if (typeof CSS === "undefined" || !("highlights" in CSS)) return () => {};
+export function canHighlightTextRanges(): boolean {
+ return typeof CSS !== "undefined" && "highlights" in CSS;
+}
+
+export function highlightTextRange(
+ range: Range,
+ name: string = TEXT_RANGE_HIGHLIGHT,
+): () => void {
+ if (!canHighlightTextRanges()) return () => {};
const highlight = new Highlight(range);
- CSS.highlights.set(TEXT_RANGE_HIGHLIGHT, highlight);
+ CSS.highlights.set(name, highlight);
return () => {
- if (CSS.highlights.get(TEXT_RANGE_HIGHLIGHT) === highlight) {
- CSS.highlights.delete(TEXT_RANGE_HIGHLIGHT);
+ if (CSS.highlights.get(name) === highlight) {
+ CSS.highlights.delete(name);
}
};
}
@@ -446,6 +518,8 @@ function domPosition(el: HTMLElement, offset: number): DomPoint {
} else if (isLineBreak(node)) {
if (node === lastContent) break;
hit = passLineBreak(cursor, node);
+ } else if (node instanceof HTMLElement && !isLineElement(node)) {
+ hit = passInline(cursor, node);
} else if (node instanceof HTMLElement) {
hit = passBlock(cursor, node, sawBlock || cursor.seen > 0);
sawBlock = true;
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/util/pageViewHandlers.ts b/frontend/src/editor/core/tools/pdfTextEditor/util/pageViewHandlers.ts
index 359df27d8d..e4360fd386 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/util/pageViewHandlers.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/util/pageViewHandlers.ts
@@ -7,6 +7,7 @@ import {
wrapScanText,
} from "@editor/tools/pdfTextEditor/commands/scanTextEdit";
import { ReflowWrapCommand } from "@editor/tools/pdfTextEditor/commands/ReflowWrapCommand";
+import { resizeRunCommand } from "@editor/tools/pdfTextEditor/commands/resizeRun";
import { MoveShapeCommand } from "@editor/tools/pdfTextEditor/commands/MoveShapeCommand";
import { InsertTextCommand } from "@editor/tools/pdfTextEditor/commands/InsertTextCommand";
import { InsertTableCommand } from "@editor/tools/pdfTextEditor/commands/InsertTableCommand";
@@ -74,33 +75,43 @@ function createHandlers(store: EditorStore) {
expandable: false,
});
},
+ onMeasureRun: (pageIndex: number, runId: string) =>
+ store.measureRun(pageIndex, runId),
onMoveRun: (pageIndex: number, runId: string, dx: number, dy: number) => {
store.dispatch(new MoveTextRunCommand({ pageIndex, runId, dx, dy }));
},
- onWrapRun: (pageIndex: number, runId: string, maxWidthPt: number) => {
+ onWrapRun: (
+ pageIndex: number,
+ runId: string,
+ maxWidthPt: number,
+ keepClearBelow?: boolean,
+ ): string | null | undefined => {
const doc = store.document;
const page = doc?.page(pageIndex);
const run = page?.findRun(runId);
- const wrapped =
- doc && page && run ? wrapScanText(doc, page, run, maxWidthPt) : null;
+ if (!doc || !page || !run) return undefined;
+ const wrapped = wrapScanText(doc, page, run, maxWidthPt);
if (wrapped !== null) {
- if (wrapped !== run?.text)
+ if (wrapped !== run.text)
store.dispatch(
new EditTextCommand({ pageIndex, runId, nextText: wrapped }),
);
- return;
+ return page.findRun(runId)?.text ?? wrapped;
}
- store.dispatch(new ReflowWrapCommand({ pageIndex, runId, maxWidthPt }));
+ const reflow = new ReflowWrapCommand({
+ pageIndex,
+ runId,
+ maxWidthPt,
+ keepClearBelow,
+ });
+ store.dispatch(reflow);
+ if (reflow.refusedForSpaceBelow) return null;
+ return page.findRun(runId)?.text ?? run.text;
},
onResizeRun: (pageIndex: number, runId: string, widthPt: number) => {
- store.dispatch(
- new ReflowWrapCommand({
- pageIndex,
- runId,
- maxWidthPt: widthPt,
- explicit: true,
- }),
- );
+ const doc = store.document;
+ const cmd = doc && resizeRunCommand(doc, pageIndex, runId, widthPt);
+ if (cmd) store.dispatch(cmd);
},
onPageClick: (pageIndex: number, pageX: number, pageY: number) => {
const { mode } = store.getState();
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/util/scanFontLibrary.ts b/frontend/src/editor/core/tools/pdfTextEditor/util/scanFontLibrary.ts
index 8da3334cce..51f03c5cb0 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/util/scanFontLibrary.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/util/scanFontLibrary.ts
@@ -24,6 +24,7 @@ import {
type FontMetrics,
} from "@editor/tools/pdfTextEditor/util/fontMetrics";
import { encodesInBase14 } from "@editor/tools/pdfTextEditor/util/fontFamily";
+import { getExternalFontBytes } from "@editor/tools/pdfTextEditor/util/externalFonts";
import { visibleCodePoints } from "@editor/tools/pdfTextEditor/util/deviceFontEmbed";
type FaceSource = "base14" | "bundled" | "device";
@@ -251,7 +252,7 @@ const SCRIPTS: ScriptFonts[] = [
},
{
script: "arabic",
- chars: /[\u0600-\u06ff\u0750-\u077f]/,
+ chars: /[\u0600-\u06ff\u0750-\u077f\ufb50-\ufdff\ufe70-\ufeff]/,
server: /Arabic/i,
device: ["Noto Naskh Arabic", "Geeza Pro", "Segoe UI"],
},
@@ -321,6 +322,49 @@ export function scanScriptsOf(text: string): Script[] {
return SCRIPTS.filter((s) => s.chars.test(text)).map((s) => s.script);
}
+function faceHas(face: Face, codePoint: number): boolean {
+ return face.metrics?.get(face.family)?.advances.has(codePoint) ?? false;
+}
+
+function scriptFaceCovering(codePoint: number): Face | undefined {
+ return scriptFaces.find(
+ (face) =>
+ faceHas(face, codePoint) && getExternalFontBytes(face.family) !== null,
+ );
+}
+
+/** A loaded script face whose embeddable bytes draw every visible character of `text`, or null. */
+export function scriptFaceFamilyFor(text: string): string | null {
+ const codePoints = visibleCodePoints(text);
+ if (codePoints.length === 0) return null;
+ const face = scriptFaceCovering(codePoints[0]);
+ return face && codePoints.every((cp) => faceHas(face, cp))
+ ? face.family
+ : null;
+}
+
+/** True when every visible character of `text` has a loaded script face to draw it. */
+export function scriptFacesCover(text: string): boolean {
+ return visibleCodePoints(text).every((cp) => !!scriptFaceCovering(cp));
+}
+
+let undrawnText = "";
+
+/** Record text an emit had to drop for want of a font of its script, and start loading that script's fonts. */
+export function noteUndrawnScriptText(text: string): void {
+ const scripts = scanScriptsOf(text);
+ if (scripts.length === 0) return;
+ undrawnText += text;
+ void loadScriptScanFaces(scripts).catch(() => undefined);
+}
+
+/** The text recorded by {@link noteUndrawnScriptText} since the last take. */
+export function takeUndrawnScriptText(): string {
+ const text = undrawnText;
+ undrawnText = "";
+ return text;
+}
+
let bundled: Face[] = [];
let scriptFaces: Face[] = [];
const neededScripts = new Set<Script>();
@@ -613,6 +657,7 @@ export function _setBundledScanFacesForTests(faces: Face[]): void {
}
export function _resetScanFacesForTests(): void {
+ undrawnText = "";
bundled = [];
scriptFaces = [];
neededScripts.clear();
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/util/selectedFontNote.ts b/frontend/src/editor/core/tools/pdfTextEditor/util/selectedFontNote.ts
index 07f424108a..f3cc682a97 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/util/selectedFontNote.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/util/selectedFontNote.ts
@@ -56,7 +56,8 @@ function collectSelectedRuns(
fontIds.add(run.fontId);
if (run.fontSubset) subsetFontIds.add(run.fontId);
text += run.text;
- if (run.renderMode === RENDER_MODE_INVISIBLE) scanned++;
+ if (run.renderMode === RENDER_MODE_INVISIBLE && !run.hiddenText)
+ scanned++;
}
return { fontIds, subsetFontIds, text, scanned };
}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/util/tableAdoption.ts b/frontend/src/editor/core/tools/pdfTextEditor/util/tableAdoption.ts
index 9a18ef4863..5ebc821503 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/util/tableAdoption.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/util/tableAdoption.ts
@@ -118,7 +118,7 @@ function looksScanned(
const run = page.findRun(id);
if (!run?.pdfiumObjPtr) continue;
seen++;
- if (run.renderMode === RENDER_MODE_INVISIBLE) {
+ if (run.renderMode === RENDER_MODE_INVISIBLE && !run.hiddenText) {
invisible++;
}
}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/util/tableDetection.ts b/frontend/src/editor/core/tools/pdfTextEditor/util/tableDetection.ts
index 86e906f91d..2861cef31b 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/util/tableDetection.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/util/tableDetection.ts
@@ -4,6 +4,7 @@ import type {
TableSnapshot,
TextRunSnapshot,
} from "@editor/tools/pdfTextEditor/types";
+import { hasRtl } from "@editor/tools/pdfTextEditor/util/bidi";
import { median } from "@editor/tools/pdfTextEditor/util/median";
// Recognizes tabular layouts from a page's text runs. PDF has no native table
@@ -31,6 +32,22 @@ const RULE_COVERAGE = 0.5;
const RULE_EDGE_MARGIN_PT = 12;
/** A gap this many times the table's usual row gap ends the table. */
const ROW_GAP_TOLERANCE = 2;
+// Turned text (a running watermark, a rotated axis label) has a box that says nothing about rows and columns.
+const TURNED_TEXT_RATIO = 0.02;
+// A column whose typical line is a sentence is running text; two of them side by side are a page of columns, not a table. Descriptive tables run to about 32 characters a line, article columns from about 37.
+const PROSE_LINE_CHARS = 35;
+const PROSE_COLUMNS_MAX = 1;
+// Text a table's own cells leave out but that sits inside its area means the "grid" is page layout around other text.
+const INTRUDER_SHARE = 0.15;
+const INTRUDER_MIN_CHARS = 6;
+// Where a line's ink can sit about its baseline, in ems: from its descenders to the marks above its letters, and short of the lines either side.
+const LINE_INK_BELOW_EM = 0.25;
+const LINE_INK_ABOVE_EM = 0.8;
+const INSET_EDGE_SLACK_PT = 0.5;
+// Two text stacks side by side, each on its own line pitch, pair lines into rows only by chance: rows hold one column's line as often as both, and the paired lines sit at a different height to each other row to row, where a table's cells, even skewed on a scan, keep one offset.
+const STACK_LONE_ROWS_MIN = 2;
+const STACK_OFFSET_SPREAD_EM = 0.25;
+const STACK_OFFSET_SAMPLES_MIN = 3;
export const DEFAULT_TABLE_OPTIONS: TableDetectionOptions = {
rowTolFactor: 0.6,
@@ -42,11 +59,15 @@ export const DEFAULT_TABLE_OPTIONS: TableDetectionOptions = {
interface Cand {
run: TextRunSnapshot;
+ /** Runs drawn inside this line: they share its cell and are no cells of their own. */
+ inset: TextRunSnapshot[];
+ text: string;
left: number;
right: number;
cx: number;
cy: number;
height: number;
+ baseline: number;
}
interface Row {
@@ -63,6 +84,7 @@ interface Row {
function toCandidates(run: TextRunSnapshot): Cand[] {
if (run.locked) return [];
if (!run.text || run.text.trim().length === 0) return [];
+ if (isTurned(run)) return [];
const { x, y, width, height } = run.bounds;
if (width <= 0 || height <= 0) return [];
const lines = run.paragraphLineCount ?? 1;
@@ -70,11 +92,14 @@ function toCandidates(run: TextRunSnapshot): Cand[] {
return [
{
run,
+ inset: [],
+ text: run.text,
left: x,
right: x + width,
cx: x + width / 2,
cy: y + height / 2,
height,
+ baseline: run.matrix.f,
},
];
}
@@ -82,11 +107,13 @@ function toCandidates(run: TextRunSnapshot): Cand[] {
}
// Split a multi-line run using the per-line geometry PDFium gave us. Baselines
-// and lefts are exact; only each line's width is estimated, from its share of
-// the longest line's character count.
+// and lefts are exact, and so are rights where the run carries them; otherwise
+// a line's width is estimated from its share of the longest line's characters.
function expandParagraph(run: TextRunSnapshot, lines: number): Cand[] {
const baselines = run.paragraphBaselines;
const lefts = run.paragraphLineLefts;
+ const rights =
+ run.paragraphLineRights?.length === lines ? run.paragraphLineRights : null;
const texts = run.text.split("\n");
// Without real baselines the line boxes would be guesswork, and a wrong row
// band is worse than no candidate.
@@ -105,20 +132,109 @@ function expandParagraph(run: TextRunSnapshot, lines: number): Cand[] {
for (let i = 0; i < lines; i++) {
if (lengths[i] === 0) continue;
const left = lefts?.[i] ?? x;
- const w = Math.max(1, (width * lengths[i]) / maxLen);
+ const w =
+ rights !== null && rights[i] > left
+ ? rights[i] - left
+ : Math.max(1, (width * lengths[i]) / maxLen);
const bottom = baselines[i] - descent;
out.push({
run,
+ inset: [],
+ text: texts[i],
left,
right: left + w,
cx: left + w / 2,
cy: bottom + lineHeight / 2,
height: lineHeight,
+ baseline: baselines[i],
});
}
return out;
}
+function isTurned(run: TextRunSnapshot): boolean {
+ const { a, b, c, d } = run.matrix;
+ return (
+ Math.abs(b) > TURNED_TEXT_RATIO * Math.abs(a) ||
+ Math.abs(c) > TURNED_TEXT_RATIO * Math.abs(d) ||
+ a <= 0 ||
+ d <= 0
+ );
+}
+
+function drawnInside(piece: Cand, line: Cand): boolean {
+ if (piece.run === line.run) return false;
+ if (piece.right - piece.left >= line.right - line.left) return false;
+ if (
+ piece.left < line.left - INSET_EDGE_SLACK_PT ||
+ piece.right > line.right + INSET_EDGE_SLACK_PT
+ )
+ return false;
+ const size = line.run.fontSize;
+ return (
+ piece.cy >= line.baseline - LINE_INK_BELOW_EM * size &&
+ piece.cy <= line.baseline + LINE_INK_ABOVE_EM * size
+ );
+}
+
+// A producer shaping right-to-left text can draw a letter of a word as an
+// object of its own, in another font or off the line's baseline, and it arrives
+// as a run inside the line it belongs to. Left as a candidate it reads as a
+// cell, and a page of such paragraphs as a sparse grid; folded into its line it
+// goes where that goes.
+//
+// Only lines holding right-to-left text take insets. Folding a stray run
+// elsewhere changes which rows count as holding several cells, and with it where
+// a block of rows starts, so text further down the page can turn into a grid.
+function foldInsetRuns(cands: Cand[]): Cand[] {
+ // Only the lines whose baseline a piece's centre can sit on are tried: detection reruns on every keystroke, and trying every pair is quadratic in the page's runs.
+ const byBaseline = cands
+ .filter((cand) => hasRtl(cand.text))
+ .sort((a, b) => a.baseline - b.baseline);
+ if (byBaseline.length === 0) return cands;
+ const largest = Math.max(...byBaseline.map((line) => line.run.fontSize));
+ const host = new Map<Cand, Cand>();
+ for (const piece of cands) {
+ const lowest = piece.cy - LINE_INK_ABOVE_EM * largest;
+ const highest = piece.cy + LINE_INK_BELOW_EM * largest;
+ let widest: Cand | null = null;
+ for (
+ let i = firstAtOrAbove(byBaseline, lowest);
+ i < byBaseline.length && byBaseline[i].baseline <= highest;
+ i++
+ ) {
+ const line = byBaseline[i];
+ if (!drawnInside(piece, line)) continue;
+ if (!widest || line.right - line.left > widest.right - widest.left)
+ widest = line;
+ }
+ if (widest) host.set(piece, widest);
+ }
+ if (host.size === 0) return cands;
+ for (const piece of host.keys()) {
+ let line = host.get(piece);
+ while (line && host.has(line)) line = host.get(line);
+ line?.inset.push(piece.run);
+ }
+ return cands.filter((cand) => !host.has(cand));
+}
+
+/** Index of the first of `byBaseline`, sorted ascending, whose baseline is at least `baseline`. */
+function firstAtOrAbove(byBaseline: Cand[], baseline: number): number {
+ let lo = 0;
+ let hi = byBaseline.length;
+ while (lo < hi) {
+ const mid = (lo + hi) >> 1;
+ if (byBaseline[mid].baseline < baseline) lo = mid + 1;
+ else hi = mid;
+ }
+ return lo;
+}
+
+function runIdsOf(cand: Cand): string[] {
+ return [cand.run.id, ...cand.inset.map((run) => run.id)];
+}
+
// Cluster candidates into rows by vertical-centre proximity, top-down.
function groupRows(cands: Cand[], rowTol: number): Row[] {
const sorted = [...cands].sort((a, b) => b.cy - a.cy);
@@ -647,13 +763,15 @@ function buildTable(
if (rows < opts.minRows || cols < opts.minCols) return null;
// Inner edges sit at the midpoint of the whitespace between tracks. The outer
- // ones get the SAME half-gap as a margin: taking the glyph extent instead
+ // ones get the same half-gap as a margin: taking the glyph extent instead
// makes the boundary graze the first and last row's text, which reads as a
// misdrawn grid on a table that has no printed border to check it against.
+ // Capped, because half of a gutter that spans most of the page puts the
+ // table's edge past the page's.
const colGaps: number[] = [];
for (let i = 1; i < cols; i++)
colGaps.push(bands[i].left - bands[i - 1].right);
- const colPad = Math.max(1, median(colGaps) / 2);
+ const colPad = Math.max(1, Math.min(median(colGaps) / 2, 2 * snapTol));
const derivedCols: number[] = [bands[0].left - colPad];
for (let i = 1; i < cols; i++) {
derivedCols.push((bands[i - 1].right + bands[i].left) / 2);
@@ -717,7 +835,7 @@ function buildTable(
for (const c of row.cands) {
const col = edgeIndex(colEdges, c.cx);
const list = map.get(col) ?? [];
- list.push(c.run.id);
+ list.push(...runIdsOf(c));
map.set(col, list);
}
return map;
@@ -769,6 +887,13 @@ function buildTable(
(r) => new Set(r.cands.map((c) => edgeIndex(colEdges, c.cx))).size >= 2,
).length;
if (rowsWithMultipleCols < 2) return null;
+ const columns = Array.from({ length: cols }, (): Cand[] => []);
+ for (const c of block.flatMap((row) => row.cands))
+ columns[edgeIndex(colEdges, c.cx)].push(c);
+ // Rows the page rules apart are a table however long their cells run.
+ if (!snappedRows.drawn && proseColumns(columns) > PROSE_COLUMNS_MAX)
+ return null;
+ if (!snappedRows.drawn && sideBySideStacks(block, colEdges)) return null;
const bounds: PageRect = {
x: colEdges[0],
@@ -803,6 +928,86 @@ function buildTable(
};
}
+function sideBySideStacks(block: Row[], colEdges: number[]): boolean {
+ const loneRows = new Map<number, number>();
+ const offsets = new Map<number, number[]>();
+ let pairedRows = 0;
+ for (const row of block) {
+ const firstByCol = new Map<number, Cand>();
+ for (const c of row.cands) {
+ const col = edgeIndex(colEdges, c.cx);
+ if (!firstByCol.has(col)) firstByCol.set(col, c);
+ }
+ const cols = [...firstByCol.keys()].sort((a, b) => a - b);
+ if (cols.length === 1) {
+ loneRows.set(cols[0], (loneRows.get(cols[0]) ?? 0) + 1);
+ continue;
+ }
+ pairedRows++;
+ for (let i = 1; i < cols.length; i++) {
+ const offset =
+ firstByCol.get(cols[i])!.baseline -
+ firstByCol.get(cols[i - 1])!.baseline;
+ const list = offsets.get(cols[i - 1]) ?? [];
+ list.push(offset);
+ offsets.set(cols[i - 1], list);
+ }
+ }
+ const lone = [...loneRows.values()];
+ const stackedColumns = lone.filter((n) => n >= STACK_LONE_ROWS_MIN).length;
+ const loneTotal = lone.reduce((sum, n) => sum + n, 0);
+ if (stackedColumns < 2 || loneTotal <= pairedRows) return false;
+ const em = median(block.flatMap((row) => row.cands.map((c) => c.height)));
+ return [...offsets.values()].some(
+ (list) =>
+ list.length >= STACK_OFFSET_SAMPLES_MIN &&
+ spread(list) > STACK_OFFSET_SPREAD_EM * em,
+ );
+}
+
+function spread(values: number[]): number {
+ const mean = values.reduce((sum, v) => sum + v, 0) / values.length;
+ return Math.sqrt(
+ values.reduce((sum, v) => sum + (v - mean) ** 2, 0) / values.length,
+ );
+}
+
+function proseColumns(columns: Cand[][]): number {
+ return columns.filter(
+ (column) =>
+ column.length >= 2 &&
+ median(column.map((c) => c.text.trim().length)) >= PROSE_LINE_CHARS,
+ ).length;
+}
+
+function visibleChars(cand: Cand): number {
+ return [cand.text, ...cand.inset.map((run) => run.text)].reduce(
+ (sum, text) => sum + text.replace(/\s+/g, "").length,
+ 0,
+ );
+}
+
+// Characters of upright page text the table leaves out of its cells yet covers.
+function intrudingChars(table: TableSnapshot, runs: TextRunSnapshot[]): number {
+ const own = new Set(table.cells.flatMap((cell) => cell.runIds));
+ const b = table.bounds;
+ let chars = 0;
+ for (const run of runs) {
+ if (own.has(run.id) || run.locked || isTurned(run)) continue;
+ const r = run.bounds;
+ const area = r.width * r.height;
+ if (area <= 0) continue;
+ const inside =
+ Math.max(0, Math.min(r.x + r.width, b.x + b.width) - Math.max(r.x, b.x)) *
+ Math.max(
+ 0,
+ Math.min(r.y + r.height, b.y + b.height) - Math.max(r.y, b.y),
+ );
+ if (inside > 0.5 * area) chars += run.text.replace(/\s+/g, "").length;
+ }
+ return chars;
+}
+
/** Recognize tables on one page from its text-run snapshots. */
export function detectTables(
runs: TextRunSnapshot[],
@@ -811,7 +1016,7 @@ export function detectTables(
rules: PageRect[] = [],
): TableSnapshot[] {
const opts = { ...DEFAULT_TABLE_OPTIONS, ...options };
- const cands = runs.flatMap(toCandidates);
+ const cands = foldInsetRuns(runs.flatMap(toCandidates));
if (cands.length < opts.minRows * opts.minCols) return [];
const medHeight = median(cands.map((c) => c.height)) || 1;
@@ -883,7 +1088,17 @@ export function detectTables(
rules,
Math.max(4, medHeight * 1.5),
);
- if (table) tables.push(table);
+ if (!table) continue;
+ const cellChars = block
+ .flatMap((row) => row.cands)
+ .reduce((sum, c) => sum + visibleChars(c), 0);
+ const intruding = intrudingChars(table, runs);
+ if (
+ intruding >= INTRUDER_MIN_CHARS &&
+ intruding >= INTRUDER_SHARE * cellChars
+ )
+ continue;
+ tables.push(table);
}
return tables;
}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/util/toolbarState.ts b/frontend/src/editor/core/tools/pdfTextEditor/util/toolbarState.ts
index d24aad9337..0d081c3d55 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/util/toolbarState.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/util/toolbarState.ts
@@ -1,8 +1,15 @@
+import { isBoldWeight } from "@editor/tools/pdfTextEditor/util/faceNames";
import {
- isBoldFamily,
- isItalicFamily,
-} from "@editor/tools/pdfTextEditor/util/fontFamily";
-import { canToggleItalic } from "@editor/tools/pdfTextEditor/util/fontCapability";
+ canRestyle,
+ faceStyleOf,
+ familyHasStyle,
+ familiesOfFont,
+ fontFamilyKey,
+ hasExtraWeights,
+ knownDocumentFamilies,
+ type FaceSources,
+ type ToggleRequest,
+} from "@editor/tools/pdfTextEditor/util/fontFaces";
import type { LocalFont } from "@editor/tools/pdfTextEditor/util/localFonts";
import type {
PageSnapshot,
@@ -13,11 +20,18 @@ import type {
export const EMPTY_TOOLBAR: ToolbarState = {
fontFamily: null,
+ documentFontId: null,
fontSize: null,
fill: null,
bold: false,
italic: false,
+ canBold: false,
canItalic: false,
+ boldNeedsBoldItalic: false,
+ italicNeedsBoldItalic: false,
+ weight: null,
+ weights: [],
+ documentFamilies: [],
stroke: null,
strokeWidth: null,
mixed: {
@@ -31,11 +45,17 @@ export const EMPTY_TOOLBAR: ToolbarState = {
},
};
-/** Collapse a multi-run selection into a single toolbar snapshot. */
+/**
+ * Collapse a multi-run selection into a single toolbar snapshot. `rangeFontIds`
+ * are the fonts drawing the characters selected inside the one selected run,
+ * when only some of its text is selected: the font controls then describe
+ * those characters, not the run.
+ */
export function deriveToolbarState(
pages: PageSnapshot[],
selection: SelectionState,
localFonts: LocalFont[] | null = null,
+ rangeFontIds: readonly string[] | null = null,
): ToolbarState {
if (selection.runIds.length === 0) return EMPTY_TOOLBAR;
const selected = pages
@@ -43,7 +63,12 @@ export function deriveToolbarState(
.filter((r) => selection.runIds.includes(r.id));
if (selected.length === 0) return EMPTY_TOOLBAR;
const first = selected[0];
- const sameFamily = selected.every((r) => r.fontId === first.fontId);
+ const inRange = rangeFontIds !== null && rangeFontIds.length > 0;
+ const fontId = inRange ? rangeFontIds[0] : first.fontId;
+ // Bold and regular words of one family are one family, as a word processor shows them.
+ const sameFamily = inRange
+ ? rangeFontIds.every((id) => fontFamilyKey(id) === fontFamilyKey(fontId))
+ : selected.every((r) => r.fontId === first.fontId);
const sameSize = selected.every((r) => r.fontSize === first.fontSize);
const sameFill = selected.every(
(r) =>
@@ -60,22 +85,58 @@ export function deriveToolbarState(
const sameStrokeWidth = selected.every(
(r) => (r.strokeWidth ?? 0) === firstStrokeWidth,
);
- const firstBold = isBoldFamily(first.fontId);
- const firstItalic = isItalicFamily(first.fontId);
- const sameBold = selected.every((r) => isBoldFamily(r.fontId) === firstBold);
- const sameItalic = selected.every(
- (r) => isItalicFamily(r.fontId) === firstItalic,
+ // Per font, not per run: a select-all hands this thousands of runs sharing a
+ // handful of fonts, on every keystroke.
+ const fontIds = inRange
+ ? [...new Set(rangeFontIds)]
+ : [...new Set(selected.map((r) => r.fontId))];
+ const styles = fontIds.map(faceStyleOf);
+ const allBold = styles.every((style) => isBoldWeight(style.weight));
+ const allItalic = styles.every((style) => style.italic);
+ const sameBold = allBold || styles.every((s) => !isBoldWeight(s.weight));
+ const sameItalic = allItalic || styles.every((style) => !style.italic);
+ const sameWeight = styles.every((s) => s.weight === styles[0].weight);
+ const sources: FaceSources = {
+ documentFamilies: knownDocumentFamilies(
+ pages.flatMap((p) =>
+ p.runs.flatMap((r) =>
+ r.documentFontId ? [r.fontId, r.documentFontId] : [r.fontId],
+ ),
+ ),
+ ),
+ externalFonts: localFonts,
+ };
+ const canBold = canRestyle(fontIds, { bold: !allBold }, sources);
+ const canItalic = canRestyle(fontIds, { italic: !allItalic }, sources);
+ const lacksOnlyBoldItalic = (request: ToggleRequest) =>
+ fontIds.every((id) => familyHasStyle(id, request, sources));
+ const family = sameFamily ? familiesOfFont(fontId, sources)[0] : null;
+ const documentFontId = first.documentFontId ?? null;
+ const sameDocumentFont = selected.every(
+ (r) => (r.documentFontId ?? null) === documentFontId,
);
return {
- fontFamily: first.fontId,
+ fontFamily: fontId,
+ documentFontId: sameDocumentFont ? documentFontId : null,
fontSize: sameSize ? first.fontSize : null,
fill: sameFill ? first.fill : null,
- bold: firstBold,
- italic: firstItalic,
- canItalic: canToggleItalic(
- selected.map((r) => r.fontId),
- localFonts,
- ),
+ bold: allBold,
+ italic: allItalic,
+ canBold,
+ canItalic,
+ boldNeedsBoldItalic:
+ !canBold && !allBold && allItalic && lacksOnlyBoldItalic({ bold: true }),
+ italicNeedsBoldItalic:
+ !canItalic &&
+ !allItalic &&
+ allBold &&
+ lacksOnlyBoldItalic({ italic: true }),
+ weight: sameWeight ? styles[0].weight : null,
+ weights:
+ family && hasExtraWeights(family)
+ ? [...new Set(family.faces.map((face) => face.weight))]
+ : [],
+ documentFamilies: sources.documentFamilies,
stroke: sameStroke ? firstStroke : null,
strokeWidth: sameStrokeWidth ? firstStrokeWidth : null,
mixed: {
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/util/typedAdvances.ts b/frontend/src/editor/core/tools/pdfTextEditor/util/typedAdvances.ts
new file mode 100644
index 0000000000..5d0f538cd6
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/util/typedAdvances.ts
@@ -0,0 +1,108 @@
+/**
+ * Prices typed text the way the PDF will draw it, so the overlay can lay out
+ * and wrap a keystroke's letters before the page has re-rendered them.
+ *
+ * The table holds the PDF's advance per em for each character the run has been
+ * measured with. A character missing from it is priced by `measureChar`, the
+ * browser's width in the overlay's font, which can be several percent off the
+ * PDF's; callers measure the run to fill the table before relying on a price.
+ */
+export type AdvanceTable = ReadonlyMap<string, number>;
+
+/** The characters of `text` the table has no price for, apart from line breaks. */
+export function unpricedChars(
+ text: string,
+ table: AdvanceTable | null,
+): Set<string> {
+ const missing = new Set<string>();
+ for (const ch of text) {
+ if (ch === "\n" || ch === "\r") continue;
+ if (!table?.has(ch)) missing.add(ch);
+ }
+ return missing;
+}
+
+/** `base` with every price in `learned` added; a character in both keeps the learned price. */
+export function mergeAdvances(
+ base: AdvanceTable | null,
+ learned: AdvanceTable | null,
+): Map<string, number> | null {
+ if (!base && !learned) return null;
+ return new Map([...(base ?? []), ...(learned ?? [])]);
+}
+
+/** Width in CSS px the PDF advances the pen across `line`, ignoring trailing spaces. */
+function pricedLineWidthPx(
+ line: string,
+ table: AdvanceTable | null,
+ fontSizePx: number,
+ measureChar: (ch: string) => number,
+): number {
+ let width = 0;
+ for (const ch of line.replace(/[ \t]+$/, "")) {
+ const em = table?.get(ch);
+ width += em === undefined ? measureChar(ch) : em * fontSizePx;
+ }
+ return width;
+}
+
+/** Pen positions the engine measured for `text`, in page points. */
+export interface MeasuredText {
+ text: string;
+ starts: readonly number[];
+ ends: readonly number[];
+}
+
+/**
+ * Width in CSS px of line `lineIndex` of `text`, ignoring trailing spaces:
+ * from the engine's positions for as much of the line as `measured` still
+ * describes, which is everything before the first character that changed,
+ * and priced from the table after that.
+ */
+export function lineWidthPx(
+ text: string,
+ lineIndex: number,
+ measured: MeasuredText | null,
+ table: AdvanceTable | null,
+ fontSizePx: number,
+ pxPerPt: number,
+ measureChar: (ch: string) => number,
+): number {
+ const lines = text.split("\n");
+ const line = lines[lineIndex] ?? "";
+ let lineStart = 0;
+ for (let i = 0; i < lineIndex; i += 1) lineStart += lines[i].length + 1;
+ const lineEnd = lineStart + line.replace(/[ \t\r]+$/, "").length;
+ const price = (from: number) =>
+ pricedLineWidthPx(
+ text.slice(from, lineEnd),
+ table,
+ fontSizePx,
+ measureChar,
+ );
+ if (!measured) return price(lineStart);
+ let same = 0;
+ const limit = Math.min(text.length, measured.text.length);
+ while (same < limit && text[same] === measured.text[same]) same += 1;
+ const known = Math.min(same, lineEnd);
+ const placed = (i: number) =>
+ Number.isFinite(measured.starts[i]) && Number.isFinite(measured.ends[i]);
+ let left = Infinity;
+ let inkRight = -Infinity;
+ for (let i = lineStart; i < known; i += 1) {
+ if (!placed(i)) continue;
+ left = Math.min(left, measured.starts[i]);
+ inkRight = Math.max(inkRight, measured.ends[i]);
+ }
+ if (!Number.isFinite(left)) return price(lineStart);
+ // Where the pen stands after the known part: the start of whatever the
+ // engine drew next on this line, or the ink's end when nothing follows.
+ const penAfter =
+ known < lineEnd &&
+ known < measured.text.length &&
+ measured.text[known] !== "\n" &&
+ placed(known)
+ ? measured.starts[known]
+ : inkRight;
+ return (penAfter - left) * pxPerPt + price(known);
+}
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/util/wasmScratch.ts b/frontend/src/editor/core/tools/pdfTextEditor/util/wasmScratch.ts
index b83299c83c..a0c7eba0f1 100644
--- a/frontend/src/editor/core/tools/pdfTextEditor/util/wasmScratch.ts
+++ b/frontend/src/editor/core/tools/pdfTextEditor/util/wasmScratch.ts
@@ -46,6 +46,9 @@ export const SCRATCH = {
reflowBbox: key(),
reflowMatrix: key(),
partialBbox: key(),
+ emitGlyphWidth: key(),
+ emitMatrix: key(),
+ partialFontName: key(),
imageMatrix: key(),
annotRect: key(),
shapeDrawMode: key(),
@@ -78,6 +81,7 @@ export const SCRATCH = {
readerReadTextA: key(),
readerReadTextB: key(),
readerSize: key(),
+ readerSpaceWidth: key(),
reflowText: key(),
charcodes: key(),
tagName: key(),
@@ -91,6 +95,13 @@ export const SCRATCH = {
splitFontSize: key(),
splitStrokeWidth: key(),
linkCharBox: key(),
+ glyphPoint: key(),
+ liftClipPoint: key(),
+ liftBounds: key(),
+ kernOriginX: key(),
+ kernOriginY: key(),
+ kernFontSize: key(),
+ kernGlyphWidth: key(),
} as const;
/** Structural minimum: any wrapper that exposes PDFium's wasm allocator. */
diff --git a/frontend/src/editor/core/tools/pdfTextEditor/util/wrapCaret.ts b/frontend/src/editor/core/tools/pdfTextEditor/util/wrapCaret.ts
new file mode 100644
index 0000000000..b0f24f6d1e
--- /dev/null
+++ b/frontend/src/editor/core/tools/pdfTextEditor/util/wrapCaret.ts
@@ -0,0 +1,38 @@
+const WHITESPACE = /\s/;
+
+/**
+ * Where `offset` in `before` lands in `after`, a re-wrap of the same text that
+ * may differ only in its whitespace. Counts the letters ahead of the offset and
+ * then as many of the spaces between them and the offset as `after` still has
+ * there, so a space turned into a line break leaves the caret after the same
+ * letter.
+ */
+export function offsetAcrossRewrap(
+ before: string,
+ offset: number,
+ after: string,
+): number {
+ let letters = 0;
+ let trailingSpaces = 0;
+ for (let i = 0; i < Math.min(offset, before.length); i += 1) {
+ if (WHITESPACE.test(before[i])) trailingSpaces += 1;
+ else {
+ letters += 1;
+ trailingSpaces = 0;
+ }
+ }
+ let at = 0;
+ while (letters > 0 && at < after.length) {
+ if (!WHITESPACE.test(after[at])) letters -= 1;
+ at += 1;
+ }
+ while (
+ trailingSpaces > 0 &&
+ at < after.length &&
+ WHITESPACE.test(after[at])
+ ) {
+ trailingSpaces -= 1;
+ at += 1;
+ }
+ return at;
+}
diff --git a/frontend/src/editor/desktop/tools/pdfTextEditor/util/localFontSource.test.ts b/frontend/src/editor/desktop/tools/pdfTextEditor/util/localFontSource.test.ts
index 0fd4083274..5af4e794b2 100644
--- a/frontend/src/editor/desktop/tools/pdfTextEditor/util/localFontSource.test.ts
+++ b/frontend/src/editor/desktop/tools/pdfTextEditor/util/localFontSource.test.ts
@@ -12,9 +12,9 @@ import {
} from "@editor/tools/pdfTextEditor/util/localFontSource";
import {
faceStyleFlags,
- familyOptions,
pickLocalFontFace,
} from "@editor/tools/pdfTextEditor/util/localFonts";
+import { externalFamilies } from "@editor/tools/pdfTextEditor/util/fontFaces";
const ARIAL = {
id: 7,
@@ -78,9 +78,11 @@ describe("desktop local font source", () => {
]);
expect(pickLocalFontFace(faces, "Arial")?.style).toBe("Standard");
expect(pickLocalFontFace(faces, "Arial Bold")?.style).toBe("Fett");
- expect(familyOptions(faces, []).map((o) => o.value)).toEqual([
+ expect(externalFamilies(faces)[0].faces.map((f) => f.value)).toEqual([
"Arial",
"Arial Bold",
+ "Arial Italic",
+ "Arial Bold Italic",
]);
});