From 88e91b49847803cb1974e8ccc29db7a6097c609b Mon Sep 17 00:00:00 2001 From: Steven Gates <15987463+stozo04@users.noreply.github.com> Date: Mon, 30 Nov 2026 12:58:41 -0600 Subject: [PATCH] Let Edit mode replace text that Folio can't read Fonts without a usable character map extract as control codes, so the edit box held invisible characters that could not be saved. These lines now start with an empty box, are redrawn in the bundled font and stay centered where the original was. Fixes #120 Co-Authored-By: Claude Sonnet 5.5 --- scripts/smoke-reader-tools.mjs | 111 +++++++++++++++++++++++++++++++++ src/ContentEditor.tsx | 36 +++++++---- src/arabicLayout.ts | 2 +- src/contentEditor.worker.ts | 41 +++++++++--- src/linePlacement.test.ts | 32 ++++++++++ src/linePlacement.ts | 15 +++++ src/textDirection.ts | 3 + 7 files changed, 219 insertions(+), 21 deletions(-) create mode 100644 src/linePlacement.test.ts create mode 100644 src/linePlacement.ts diff --git a/scripts/smoke-reader-tools.mjs b/scripts/smoke-reader-tools.mjs index 6f094cb..44258f8 100644 --- a/scripts/smoke-reader-tools.mjs +++ b/scripts/smoke-reader-tools.mjs @@ -803,6 +803,116 @@ async function checkArabicEditing(app, page, folder, shots) { console.log("ok Arabic ligatures, diacritics, and numbers survive editing, saving, and reopening"); } +// Type 3 digits with meaningless glyph names and no ToUnicode map, so text extraction returns control codes. +function unreadableTextPdf(glyphScale = 0.001, fontSize = 24, placement = "70 100 Td") { + const digits = ["abcdefg", "fgbc", "abged", "abgcd", "fgbc", "afgcd"]; + const bars = { a: "100 640 300 80", b: "340 360 80 320", c: "340 40 80 320", d: "100 0 300 80", + e: "80 40 80 320", f: "80 360 80 320", g: "100 320 300 80" }; + const shapes = [digits[5], digits[2], "dot", digits[3], digits[0]].map(shape => + shape === "dot" ? "180 0 120 120 re f" : [...shape].map(bar => `${bars[bar]} re f`).join(" ")); + const stream = s => `<< /Length ${s.length} >>\nstream\n${s}\nendstream`; + const names = shapes.map((_, i) => `/q${i}`); + return testPdf([ + "<< /Type /Catalog /Pages 2 0 R >>", "<< /Type /Pages /Count 1 /Kids [3 0 R] >>", + "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Resources << /Font << /F 4 0 R >> >> /Contents 5 0 R >>", + `<< /Type /Font /Subtype /Type3 /FontBBox [0 0 500 720] /FontMatrix [${glyphScale} 0 0 ${glyphScale} 0 0] /FirstChar 1 /LastChar 5 ` + + `/Widths [500 500 500 500 500] /Encoding << /Differences [1 ${names.join(" ")}] >> /Resources << >> ` + + `/CharProcs << ${names.map((name, i) => `${name} ${i + 6} 0 R`).join(" ")} >> >>`, + stream(`BT /F ${fontSize} Tf ${placement} <0102030405> Tj ET`), + ...shapes.map(shape => stream(`500 0 d0 ${shape}`)), + ]); +} + +async function checkUnreadableEditing(app, page, folder, shots) { + const open = async (name, bytes) => { + await app.evaluate(({ BrowserWindow }, file) => BrowserWindow.getAllWindows()[0].webContents.send( + "folio:open-file", { name: file.name, data: Buffer.from(file.bytes) }), { name, bytes: Array.from(Buffer.from(bytes)) }); + await page.window.waitForFunction(name => document.title.startsWith(name), name); + await page.getByRole("button", { name: "Edit mode", exact: true }).click(); + }; + const sheet = page.locator('.page[data-page-number="1"]'); + const targets = sheet.locator(".folio-content-target"); + const item = name => sheet.getByRole("button", { name, exact: true }); + const input = sheet.getByRole("textbox", { name: "Edit text on page" }); + const middle = async locator => { + const [box, paper] = await Promise.all([locator.boundingBox(), sheet.boundingBox()]); + return (box.x + box.width / 2 - paper.x) / paper.width; + }; + const assertCentered = async (name, expected) => { + await item(name).waitFor(); + const actual = await middle(item(name)); + assert.ok(Math.abs(actual - expected) < 0.01, `${name} is centered at ${actual}, not ${expected}`); + }; + + await open("Unreadable text.pdf", unreadableTextPdf()); + await targets.first().waitFor(); + const center = await middle(targets.first()); + await targets.first().click(); + assert.equal(await input.inputValue(), "", "unreadable codes are not offered for editing"); + assert.equal(await input.getAttribute("placeholder"), "New text"); + assert.equal(await sheet.locator(".folio-old-text").count(), 0, "the original stays visible"); + await page.getByText("Folio can't read this text. Type its replacement; the font will change.").waitFor(); + await page.screenshot({ path: path.join(shots, "unreadable-edit.png") }); + for (const nothing of ["", " "]) { + await input.fill(nothing); + await input.press("Enter"); + await input.waitFor({ state: "detached" }); + await targets.first().click(); + assert.equal(await input.inputValue(), "", "a blank box leaves the line alone"); + } + await input.fill("73.25"); + await input.press("Enter"); + await assertCentered("73.25", center); + await page.screenshot({ path: path.join(shots, "unreadable-edit-after.png") }); + await item("73.25").click(); + await input.fill("123,456.78"); + await input.press("Enter"); + await assertCentered("123,456.78", center); + const file = path.join(folder, "unreadable-copy.pdf"); + await captureDownload(app, file); + await page.getByRole("button", { name: "Save copy", exact: true }).click(); + assert.equal(await app.evaluate(() => globalThis.folioReordered), "completed"); + await open("Reopened replacement.pdf", readFileSync(file)); + await item("123,456.78").click(); + assert.equal(await input.inputValue(), "123,456.78"); + await input.fill("9.10"); + await input.press("Enter"); + await assertCentered("9.10", center); + await captureDownload(app, path.join(folder, "unreadable-edited-again.pdf")); + await page.getByRole("button", { name: "Save copy", exact: true }).click(); + assert.equal(await app.evaluate(() => globalThis.folioReordered), "completed"); + + await open("Small Type 3 size.pdf", unreadableTextPdf(0.01, 2.4)); + const originalHeight = (await targets.first().boundingBox()).height; + await targets.first().click(); + await input.fill("73.25"); + await input.press("Enter"); + await item("73.25").waitFor(); + const replacementHeight = (await item("73.25").boundingBox()).height; + assert.ok(replacementHeight > originalHeight * 0.7, `replacement is ${replacementHeight}px tall, original ${originalHeight}px`); + + // A tilted line's page-aligned box is much taller than its text, which must not inflate the replacement. + await open("Tilted text.pdf", unreadableTextPdf(0.001, 24, "0.866 0.5 -0.5 0.866 70 80 Tm")); + await targets.first().click(); + const typed = await input.evaluate(el => parseFloat(el.style.fontSize)); + const pageScale = (await sheet.boundingBox()).width / 200; + assert.ok(Math.abs(typed / pageScale - 24) < 1, `tilted text is edited at ${typed / pageScale}pt, not 24pt`); + await input.press("Escape"); + + const words = "BT /F 16 Tf 20 150 Td (This is an exam-) Tj 0 -20 Td (ple of split words.) Tj ET"; + await open("Split word.pdf", testPdf([ + "<< /Type /Catalog /Pages 2 0 R >>", "<< /Type /Pages /Count 1 /Kids [3 0 R] >>", + "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Resources << /Font << /F 4 0 R >> >> /Contents 5 0 R >>", + "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>", `<< /Length ${words.length} >>\nstream\n${words}\nendstream`, + ])); + await item("This is an exam-").click(); + assert.equal(await input.inputValue(), "This is an exam-", "a word split by a hyphen stays readable"); + await input.fill("This is one exam-"); + await input.press("Enter"); + await item("This is one exam-").waitFor(); + console.log("ok unreadable text can be replaced, stays centered, and survives saving and reopening"); +} + export function linkHistoryPdf() { const content = "BT /F 16 Tf 40 1100 Td (Follow a PDF link, then go Back.) Tj ET"; return testPdf([ @@ -1462,6 +1572,7 @@ export async function checkReaderTools(app, page, folder, shots) { await checkImageInsertion(app, page, folder, shots); await checkRightToLeftEditing(app, page, shots); await checkArabicEditing(app, page, folder, shots); + await checkUnreadableEditing(app, page, folder, shots); await checkLinkHistory(app, page, shots); await checkPageExport(app, page, folder, shots); await checkOrganizePages(app, page, folder, shots); diff --git a/src/ContentEditor.tsx b/src/ContentEditor.tsx index fb7922b..d0e24c1 100644 --- a/src/ContentEditor.tsx +++ b/src/ContentEditor.tsx @@ -6,7 +6,8 @@ import type { EventBus, PDFViewer } from "./viewer"; import type { Change, EditorReply, EditorRequest, EditTarget } from "./contentEditor.worker"; import type { PdfChange } from "./versionHistory"; import { ImagePlacement, type ImageDraft } from "./ImagePlacement"; -import { isArabicText, unsupportedDirection, RIGHT_TO_LEFT_MESSAGE } from "./textDirection"; +import { isCentered, lineMiddle } from "./linePlacement"; +import { isArabicText, isUnreadableText, unsupportedDirection, RIGHT_TO_LEFT_MESSAGE, UNREADABLE_MESSAGE } from "./textDirection"; export interface ContentEditorHandle { finish: () => Promise; deselect: () => boolean } interface Surface { page: number; host: HTMLDivElement; viewport: PageViewport } @@ -30,7 +31,9 @@ function paperColor(surface: Surface, target: EditTarget) { return 'rgb(' + [r,g,b].join(" ") + ')'; } -function inputStyle(t: EditTarget, v: PageViewport, paper: string): CSSProperties { +const OVER_THE_LINE = -0.88, UNDER_THE_LINE = 0.5; + +function inputStyle(t: EditTarget, v: PageViewport, paper: string, keepLineVisible: boolean) { const s = t.style!, [x,y] = s.origin; const [ox,oy] = v.convertToViewportPoint(x,y); const [ex,ey] = v.convertToViewportPoint(x+s.axis[0], y+s.axis[1]); @@ -38,11 +41,15 @@ function inputStyle(t: EditTarget, v: PageViewport, paper: string): CSSPropertie const size = Math.max(1, Math.hypot(ux-ox,uy-oy)); const angle = Math.atan2(ey-oy,ex-ox), box = rectangle(t,v); const width = Math.abs(Math.cos(angle))*box.width + Math.abs(Math.sin(angle))*box.height; - const anchor = s.anchor ? v.convertToViewportPoint(s.anchor[0], s.anchor[1]) : [ox,oy]; + const centered = isCentered(t); + const [px,py] = centered ? lineMiddle(t) : s.anchor ?? s.origin; + const anchor = v.convertToViewportPoint(px, py); + const across = centered ? "-50%" : s.anchor ? "-100%" : "0"; + const drop = keepLineVisible ? UNDER_THE_LINE : OVER_THE_LINE; return { left: anchor[0], top: anchor[1], minWidth: Math.max(width+4, size), fontSize: size, fontFamily: s.flags & 1 ? "monospace" : s.flags & 2 ? "serif" : "sans-serif", - fontWeight: s.bold ? 700 : 400, fontStyle: s.flags & 64 ? "italic" : "normal", color: s.color, background: paper, - transform: 'rotate(' + angle + 'rad) ' + (s.anchor ? 'translate(-100%, -0.88em)' : 'translateY(-0.88em)') }; + fontWeight: s.bold ? 700 : 400, fontStyle: s.flags & 64 ? "italic" : "normal", color: s.color, background: paper, textAlign: centered ? "center" : undefined, + transform: `rotate(${angle}rad) translate(${across}, ${drop}em)` } satisfies CSSProperties; } export function ContentEditor({ ref, nextSelection, pdf, viewer, bus, snapshot, apply, onDirty, imageDraft, setImageDraft }: { @@ -67,7 +74,8 @@ export function ContentEditor({ ref, nextSelection, pdf, viewer, bus, snapshot, draftRef.current = imageDraft; const selectedRef = useRef(selected); selectedRef.current = selected; - const modified = selected?.target.kind === "text" && value !== selected.target.label; + const unreadable = selected?.target.kind === "text" && isUnreadableText(selected.target.label); + const modified = selected?.target.kind === "text" && (unreadable ? value.trim() !== "" : value !== selected.target.label); const dirty = !!modified || !!imageDraft || busy; useEffect(() => { onDirty(dirty); return () => onDirty(false); }, [dirty, onDirty]); @@ -144,7 +152,7 @@ export function ContentEditor({ ref, nextSelection, pdf, viewer, bus, snapshot, w.postMessage({ page, change, snapshot: data } satisfies EditorRequest); }); const detail: PdfChange = change.kind === "text" - ? { kind: "text", page, before: selected!.target.label, after: change.text } + ? { kind: "text", page, before: unreadable ? "Unreadable text" : selected!.target.label, after: change.text } : { kind: "image", page, fileName: change.file.name, inserted: change.kind === "insertImage" }; return worker.current === w && await apply(result, detail); } catch (e) { @@ -173,8 +181,9 @@ export function ContentEditor({ ref, nextSelection, pdf, viewer, bus, snapshot, selectedRef.current = null; setSelected(null); setError(RIGHT_TO_LEFT_MESSAGE); return; } - setError(""); setValue(target.label); setSelected({ page: s.page, target, paper: target.style ? paperColor(s,target) : "" }); - if (!target.style || target.fitted || isArabicText(target.label)) return; + const startsEmpty = isUnreadableText(target.label); + setError(""); setValue(startsEmpty ? "" : target.label); setSelected({ page: s.page, target, paper: target.style ? paperColor(s,target) : "" }); + if (!target.style || target.fitted || startsEmpty || isArabicText(target.label)) return; // Use the same embedded or system font as the page renderer while the caret is visible. const origin = target.style.origin; void pdf.getPage(s.page).then(async page => { @@ -231,10 +240,11 @@ export function ContentEditor({ ref, nextSelection, pdf, viewer, bus, snapshot, }} />)} {imageDraft?.page === s.page && } {selected?.page === s.page && (selected.target.kind === "text" ? <> -
+ {!unreadable &&
} { setValue(e.target.value); setError(""); }} onKeyDown={e => { @@ -255,7 +265,7 @@ export function ContentEditor({ ref, nextSelection, pdf, viewer, bus, snapshot,
} -
{error || (busy ? "Applying edit…" : +
{error || (busy ? "Applying edit…" : unreadable ? UNREADABLE_MESSAGE : !imageDraft && surfaces.length > 0 && surfaces.every(s => targets.get(s.page)?.length === 0) ? "No editable text or images on this page." : "")}
; } diff --git a/src/arabicLayout.ts b/src/arabicLayout.ts index b13d04d..2a2274a 100644 --- a/src/arabicLayout.ts +++ b/src/arabicLayout.ts @@ -11,7 +11,7 @@ function fontBytes(url: string) { let promise = fonts.get(url); if (!promise) { promise = fetch(url).then(async response => { - if (!response.ok) throw new Error("Couldn't load the font for Arabic editing."); + if (!response.ok) throw new Error("Couldn't load the editing font."); return new Uint8Array(await response.arrayBuffer()); }).catch(error => { fonts.delete(url); throw error; }); fonts.set(url, promise); diff --git a/src/contentEditor.worker.ts b/src/contentEditor.worker.ts index 211787a..b007d10 100644 --- a/src/contentEditor.worker.ts +++ b/src/contentEditor.worker.ts @@ -3,13 +3,15 @@ import { init, type WrappedPdfiumModule } from "@embedpdf/pdfium"; import wasmUrl from "@embedpdf/pdfium/pdfium.wasm?url"; import { checkPdfSize } from "./pdfInput"; import { replacePageImage, insertPageImage } from "./pdfImageEdit"; -import { isArabicText, unsupportedDirection, RIGHT_TO_LEFT_MESSAGE } from "./textDirection"; +import { isArabicText, isUnreadableText, unsupportedDirection, RIGHT_TO_LEFT_MESSAGE } from "./textDirection"; +import { isCentered, lineMiddle } from "./linePlacement"; export interface EditTarget { index: number; end: number; ordinal?: number; fitted?: { width: number; baseline: number }; + centered?: boolean; kind: "text" | "image"; label: string; /** Unrotated PDF coordinates, shared with pdf.js's page viewport. */ @@ -76,6 +78,8 @@ function markString(m: WrappedPdfiumModule, mark: number, key: string, scratch: ? m.pdfium.UTF16ToString(out) as string : ""); } +const CENTERED_MARK = "FolioCenteredLine"; + function lineForm(m: WrappedPdfiumModule, obj: number, index: number, box: number[], ptr: number): EditTarget | undefined { for (let i = 0; i < m.FPDFPageObj_CountMarks(obj); i++) { const mark = m.FPDFPageObj_GetMark(obj, i); @@ -90,7 +94,8 @@ function lineForm(m: WrappedPdfiumModule, obj: number, index: number, box: numbe const matrix = Array.from(m.pdfium.HEAPF32.subarray(ptr/4, ptr/4+6)) as number[]; const [a,dy,c,d,x,y] = matrix; const origin = [x+c*baseline, y+d*baseline]; - return { index, end: index, kind: "text", box, label, fitted: { width, baseline }, + const centered = !!markString(m, mark, CENTERED_MARK, ptr); + return { index, end: index, kind: "text", box, label, centered, fitted: { width, baseline }, style: { matrix: [a,dy,c,d,...origin], origin, anchor: [origin[0]+a*width,origin[1]+dy*width], axis: [a,dy], size: size*Math.hypot(c,d), flags: 0, bold: !!bold, color: `rgb(${r} ${g} ${b})` } }; } @@ -106,7 +111,8 @@ function objectText(m: WrappedPdfiumModule, page: number) { for (let i = 0; i < count; i++) { if (m.FPDFText_IsGenerated(textPage, i)) continue; const object = m.FPDFText_GetTextObject(textPage, i); - const code = m.FPDFText_GetUnicode(textPage, i); + // PDFium reports a hyphen that splits a word across lines as a control code. + const code = m.FPDFText_IsHyphen(textPage, i) === 1 ? "-".charCodeAt(0) : m.FPDFText_GetUnicode(textPage, i); if (!object || code <= 0 || code > 0x10ffff) continue; const entry = chars.get(object); if (entry) entry.label += String.fromCodePoint(code); @@ -116,6 +122,23 @@ function objectText(m: WrappedPdfiumModule, page: number) { } finally { m.FPDFText_ClosePage(textPage); } } +const TALLEST_PLAUSIBLE_LINE = 1.5, GLYPH_HEIGHT_PER_SIZE = 0.72; + +// A Type 3 font sets its own glyph scale, so its nominal size can be far smaller than the text on the page. +function fitSizeToGlyphs(m: WrappedPdfiumModule, page: number, { index, end, style }: EditTarget) { + if (style!.size <= 0) return; + const height = buffer(m, 32, quad => { + let tallest = 0; + for (let i = index; i <= end; i++) { + if (!m.FPDFPageObj_GetRotatedBounds(m.FPDFPage_GetObject(page, i), quad)) continue; + const [x1,y1,,,,,x4,y4] = m.pdfium.HEAPF32.subarray(quad/4, quad/4+8); + tallest = Math.max(tallest, Math.hypot(x4-x1, y4-y1)); + } + return tallest; + }); + if (height > style!.size * TALLEST_PLAUSIBLE_LINE) style!.size = height / GLYPH_HEIGHT_PER_SIZE; +} + function pageView(m: WrappedPdfiumModule, page: number) { const count = m.FPDFPage_CountObjects(page); if (count > 20000) throw new Error("This page has too many objects to edit."); @@ -190,6 +213,8 @@ function pageView(m: WrappedPdfiumModule, page: number) { } }); + for (const target of targets) if (target.style && isUnreadableText(target.label)) fitSizeToGlyphs(m, page, target); + for (const [target, parts] of pieces) { if (!isArabicText(target.label)) continue; // PDFium enumerates characters in reading order, but page objects are often painted left to right. @@ -226,7 +251,7 @@ function save(m: WrappedPdfiumModule, doc: number) { // Keep the shaped glyphs together as a vector form, in the original object's stacking position. // The standard ActualText entry preserves the logical string, including marks and ligatures. -async function replaceArabic(m: WrappedPdfiumModule, doc: number, page: number, target: EditTarget, text: string) { +async function redrawLine(m: WrappedPdfiumModule, doc: number, page: number, target: EditTarget, text: string) { if (text.length > 32767 || /[\u0000-\u001f]/u.test(text)) throw new Error("Enter a single line of text."); if (unsupportedDirection(target.label) || unsupportedDirection(text)) throw new Error(RIGHT_TO_LEFT_MESSAGE); const style = target.style!, [a,b,c,d,x,y] = style.matrix!; @@ -253,8 +278,9 @@ async function replaceArabic(m: WrappedPdfiumModule, doc: number, page: number, let inserted = false; try { const anchor = style.anchor; - const left = anchor ? anchor[0]-a*line.width : x; - const base = anchor ? anchor[1]-b*line.width : y; + const middle = isCentered(target) ? lineMiddle(target) : undefined; + const left = middle ? middle[0]-a*line.width/2 : anchor ? anchor[0]-a*line.width : x; + const base = middle ? middle[1]-b*line.width/2 : anchor ? anchor[1]-b*line.width : y; buffer(m, 24, ptr => { m.pdfium.HEAPF32.set([a,b,c,d,left-c*line.baseline,base-d*line.baseline], ptr/4); if (!m.FPDFPageObj_SetMatrix(form, ptr)) throw new Error("Couldn't place the edited text."); @@ -266,6 +292,7 @@ async function replaceArabic(m: WrappedPdfiumModule, doc: number, page: number, view.setUint16(0, 0xfeff); for (let i = 0; i < text.length; i++) view.setUint16(2+i*2, text.charCodeAt(i)); const tagged = mark && m.FPDFPageObjMark_SetStringParam(doc, form, mark, "FolioArabicLine", metadata) + && (!middle || m.FPDFPageObjMark_SetStringParam(doc, form, mark, CENTERED_MARK, "1")) && buffer(m, logical.length, ptr => { m.pdfium.HEAPU8.set(logical,ptr); return m.FPDFPageObjMark_SetBlobParam(doc,form,mark,"ActualText",ptr,logical.length); @@ -331,7 +358,7 @@ self.onmessage = async ({ data }: MessageEvent) => { const target = targets.find(t => t.index === change.index && t.kind === change.kind); if (!target) throw new Error("Select the item again."); if (change.kind === "image") return replacePageImage(snapshot, page, target.ordinal!, imageCount, change.file); - if (target.fitted || isArabicText(target.label) || isArabicText(change.text)) await replaceArabic(m, doc, handle, target, change.text); + if (target.fitted || isUnreadableText(target.label) || isArabicText(target.label) || isArabicText(change.text)) await redrawLine(m, doc, handle, target, change.text); else replaceText(m, handle, target, change.text); if (!m.FPDFPage_GenerateContent(handle)) throw new Error("Couldn't write this page."); return save(m, doc); diff --git a/src/linePlacement.test.ts b/src/linePlacement.test.ts new file mode 100644 index 0000000..15cffb2 --- /dev/null +++ b/src/linePlacement.test.ts @@ -0,0 +1,32 @@ +import { describe, expect, it } from "vitest"; +import type { EditTarget } from "./contentEditor.worker"; +import { isCentered, lineMiddle } from "./linePlacement"; +import { isUnreadableText } from "./textDirection"; + +const line = (label: string, extra: Partial = {}): EditTarget => ({ + index: 0, end: 0, kind: "text", label, box: [10, 18, 50, 34], + style: { origin: [10, 20], axis: [1, 0], size: 12, flags: 0, bold: false, color: "rgb(0 0 0)" }, ...extra, +}); + +describe("replacement line placement", () => { + it("centers unreadable lines and their replacements only", () => { + expect(isCentered(line("\u0001\u0002"))).toBe(true); + expect(isCentered(line("73.25", { centered: true }))).toBe(true); + expect(isCentered(line("Total", { fitted: { width: 40, baseline: 3 } }))).toBe(false); + expect(isCentered(line("Total"))).toBe(false); + }); + it("finds the middle of the line on its baseline", () => { + expect(lineMiddle(line("x"))).toEqual([30, 20]); + }); + it("uses a redrawn line's own width", () => { + expect(lineMiddle(line("x", { fitted: { width: 30, baseline: 3 } }))).toEqual([25, 20]); + }); + it("does not treat tabs as unreadable", () => { + expect(isUnreadableText("Name:\tValue")).toBe(false); + expect(isUnreadableText("\u0006\u0090")).toBe(true); + }); + it("follows a vertical baseline", () => { + const style = { ...line("x").style!, origin: [20, 10], axis: [0, 1] }; + expect(lineMiddle(line("x", { box: [8, 10, 24, 50], style }))).toEqual([20, 30]); + }); +}); diff --git a/src/linePlacement.ts b/src/linePlacement.ts new file mode 100644 index 0000000..5b0a837 --- /dev/null +++ b/src/linePlacement.ts @@ -0,0 +1,15 @@ +import type { EditTarget } from "./contentEditor.worker"; +import { isUnreadableText } from "./textDirection"; + +/** A redrawn line has its own width, so it keeps the middle of the line it replaces rather than its left edge. */ +export function isCentered(target: EditTarget) { + return !!target.centered || isUnreadableText(target.label); +} + +/** The point on the line's baseline halfway across it, in unrotated PDF coordinates. */ +export function lineMiddle({ box, style, fitted }: EditTarget): [number, number] { + const [x, y] = style!.origin, [a, b] = style!.axis; + if (fitted) return [x + a * fitted.width / 2, y + b * fitted.width / 2]; + const along = (((box[0] + box[2]) / 2 - x) * a + ((box[1] + box[3]) / 2 - y) * b) / (a * a + b * b); + return [x + a * along, y + b * along]; +} diff --git a/src/textDirection.ts b/src/textDirection.ts index aa374e7..2ab3785 100644 --- a/src/textDirection.ts +++ b/src/textDirection.ts @@ -1,5 +1,8 @@ // Other RTL scripts stay protected until the editor can shape and round-trip them. const RIGHT_TO_LEFT = /[\u0590-\u08ff\ufb1d-\ufdff\ufe70-\ufefc\u{10800}-\u{10fff}\u{1e800}-\u{1efff}]/u; +// Fonts without a usable character map come out as control codes instead of the words on the page. +export function isUnreadableText(text: string) { return /[^\P{Cc}\t]/u.test(text); } +export const UNREADABLE_MESSAGE = "Folio can't read this text. Type its replacement; the font will change."; export const RIGHT_TO_LEFT_MESSAGE = "Folio can't edit right-to-left text in this script yet."; export function hasRightToLeft(text: string) { return RIGHT_TO_LEFT.test(text); } export function isArabicText(text: string) { return /\p{Script_Extensions=Arabic}/u.test(text); }