Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
111 changes: 111 additions & 0 deletions scripts/smoke-reader-tools.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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([
Expand Down Expand Up @@ -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);
Expand Down
36 changes: 23 additions & 13 deletions src/ContentEditor.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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<boolean>; deselect: () => boolean }
interface Surface { page: number; host: HTMLDivElement; viewport: PageViewport }
Expand All @@ -30,19 +31,25 @@ 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]);
const [ux,uy] = v.convertToViewportPoint(x,y+s.size);
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 }: {
Expand All @@ -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]);

Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -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 => {
Expand Down Expand Up @@ -231,10 +240,11 @@ export function ContentEditor({ ref, nextSelection, pdf, viewer, bus, snapshot,
}} />)}
{imageDraft?.page === s.page && <ImagePlacement draft={imageDraft} viewport={s.viewport} onChange={setImageDraft} disabled={busy} />}
{selected?.page === s.page && (selected.target.kind === "text" ? <>
<div className="folio-old-text" style={{ ...rectangle(selected.target,s.viewport), background: selected.paper }} />
{!unreadable && <div className="folio-old-text" style={{ ...rectangle(selected.target,s.viewport), background: selected.paper }} />}
<input ref={input} className="folio-inline-text" dir="auto" aria-label="Edit text on page" maxLength={32767}
style={{ ...inputStyle(selected.target,s.viewport,selected.paper),
...(selected.target.fitted || isArabicText(selected.target.label) || isArabicText(value)
placeholder={unreadable ? "New text" : undefined}
style={{ ...inputStyle(selected.target,s.viewport,selected.paper, unreadable),
...(unreadable || selected.target.fitted || isArabicText(selected.target.label) || isArabicText(value)
? { fontFamily: "FolioArabic, sans-serif" } : face?.target === selected.target ? { fontFamily: face.family } : {}) }} value={value} readOnly={busy}
onChange={e => { setValue(e.target.value); setError(""); }}
onKeyDown={e => {
Expand All @@ -255,7 +265,7 @@ export function ContentEditor({ ref, nextSelection, pdf, viewer, bus, snapshot,
<button type="button" className="btn" disabled={busy} onClick={() => { setImageDraft(null); setError(""); }}>Cancel</button>
<button type="button" className="btn primary" disabled={busy} onClick={() => void finish()}>Place image</button>
</div>}
<div className="folio-edit-status" role={error ? "alert" : "status"}>{error || (busy ? "Applying edit…" :
<div className="folio-edit-status" role={error ? "alert" : "status"}>{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." : "")}</div>
</>;
}
2 changes: 1 addition & 1 deletion src/arabicLayout.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
Loading