diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index e8fa4adac6..38c28a80ec 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -4,10 +4,11 @@ Every asset PdfCraft includes, bundles or uses to build its published material, with its author, source and licence. The policy is in [AGENTS.md](AGENTS.md) §1. The machine-readable list, with the SHA-256 of every asset, is [ATTRIBUTION.toml](ATTRIBUTION.toml). Licence texts are kept beside the assets and summarised in [NOTICE](NOTICE). -## In this repository (257) +## In this repository (258) | Asset | Title | Author | Licence | Source | Used for | |---|---|---|---|---|---| +| `docs/images/pdfcraft-ocr-verify.png` | PdfCraft screenshot: OCR Verify screen | PdfCraft contributors (generated by `cargo xtask screenshots`) | MIT OR Apache-2.0 | this repository | README: OCR review. Shows only PdfCraft UI, its Lucide icons and a synthetic scanned page built from the embedded fonts, with a real recognition (the OCR models) loaded into the Verify screen | | `assets/icons/accessibility.svg` | Lucide icon "accessibility" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/accessibility.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs | | `assets/icons/align-left.svg` | Lucide icon "align-left" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/align-left.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs | | `assets/icons/align-center.svg` | Lucide icon "align-center" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/align-center.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs | diff --git a/ATTRIBUTION.toml b/ATTRIBUTION.toml index f998b6fc3d..99073babb1 100644 --- a/ATTRIBUTION.toml +++ b/ATTRIBUTION.toml @@ -10,6 +10,17 @@ # licence: SPDX expression from the allowlist in AGENTS.md §1.2. adobe_data = true marks the closed list of # Adobe-authored non-visual technical data allowed by AGENTS.md §1.1. +[[asset]] +path = "docs/images/pdfcraft-ocr-verify.png" +title = "PdfCraft screenshot: OCR Verify screen" +author = "PdfCraft contributors (generated by `cargo xtask screenshots`)" +source = "this repository" +licence = "MIT OR Apache-2.0" +licence_file = "LICENSE-MIT" +kind = "image" +usage = "README: OCR review. Shows only PdfCraft UI, its Lucide icons and a synthetic scanned page built from the embedded fonts, with a real recognition (the OCR models) loaded into the Verify screen" +sha256 = "ea7485b151e27ad3fd2a2dac079436ab11745d42032201a029bb20f819c6af8f" + [[asset]] path = "assets/icons/accessibility.svg" title = "Lucide icon \"accessibility\"" diff --git a/Cargo.lock b/Cargo.lock index 573b215b7c..8617c45522 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -143,6 +143,15 @@ dependencies = [ "zerocopy", ] +[[package]] +name = "aho-corasick" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" +dependencies = [ + "memchr", +] + [[package]] name = "aligned-vec" version = "0.6.4" @@ -1303,6 +1312,15 @@ dependencies = [ "zip", ] +[[package]] +name = "craft-web-host" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=2e2312ddaf21bc3d85cd3395d0955c7d239306f6#2e2312ddaf21bc3d85cd3395d0955c7d239306f6" +dependencies = [ + "wasm-bindgen", + "web-sys", +] + [[package]] name = "craft-winprint-gdi" version = "0.1.0" @@ -4324,6 +4342,7 @@ version = "0.18.1" dependencies = [ "chrono", "hayro-syntax", + "js-sys", "pdfcraft-crypt", "pdfcraft-filters", "pdfcraft-oracle", @@ -4331,6 +4350,7 @@ dependencies = [ "proptest", "serde_json", "thiserror 2.0.21", + "wasm-bindgen", ] [[package]] @@ -4507,6 +4527,7 @@ version = "0.18.1" dependencies = [ "ocrs", "pdfcraft-fonts", + "png 0.18.1", "rten", "tempfile", "thiserror 2.0.21", @@ -4598,6 +4619,7 @@ dependencies = [ name = "pdfcraft-redact" version = "0.18.1" dependencies = [ + "aho-corasick", "pdfcraft-annot", "pdfcraft-content", "pdfcraft-cos", @@ -4606,8 +4628,10 @@ dependencies = [ "pdfcraft-fonts", "pdfcraft-forms", "pdfcraft-model", + "pdfcraft-render", "pdfcraft-testkit", "pdfcraft-xfa", + "sha2 0.11.1", "thiserror 2.0.21", ] @@ -4702,6 +4726,7 @@ dependencies = [ "pdfcraft-engine", "pdfcraft-fonts", "pdfcraft-model", + "pdfcraft-ocr", "pdfcraft-platform", "pdfcraft-render", "pdfcraft-xfa", @@ -4729,6 +4754,7 @@ dependencies = [ name = "pdfcraft-web" version = "0.18.1" dependencies = [ + "craft-web-host", "eframe", "egui", "js-sys", diff --git a/README.md b/README.md index f9a41cb3ca..f488d160cc 100644 --- a/README.md +++ b/README.md @@ -253,6 +253,18 @@ Documents restricted by their author show a clear notice, and PdfCraft honours t +## Scan pages, then read the words back before trusting them + +**Scan & OCR ▸ Recognize text** turns a scan into searchable text — the current page, a range, or a folder of files written as searchable copies — with optional cleanup before reading (auto-rotate, deskew, denoise, binarize; word boxes map back to the original scan) and a second engine: an installed Tesseract joins the built-in one, merged per your strategy. A searchable result applies as one undoable step; the **Editable text** output opens the **OCR Verify screen** instead, where each word carries the engine's confidence as a colour, suspects are one keypress away, and corrections, a user dictionary and Re-OCR of a region or a page happen before Accept writes the new document. **Scan & OCR ▸ Correct recognized text** reviews any recognition there before it is applied. + +

+ The OCR Verify screen: a scanned note with each recognized word boxed in its confidence colour, the info strip reporting a 95% average confidence and one low-confidence word, and the confidence legend with its thresholds below +
+ The OCR Verify screen: words coloured by confidence — the legend spells the thresholds out — reviewed and corrected before anything is applied. +

+ +--- + ## Every tool, one keystroke away Press ⌘K to search every tool and command, or browse the **All tools** catalogue. Tools that are still in development are marked with the milestone that will ship them. diff --git a/ROADMAP.md b/ROADMAP.md index 49f7d4101d..820ceb0179 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -31,6 +31,7 @@ > **Last reviewed:** 2026-10-29 | **Last updated:** 2026-10-29 | **Change:** minor (M2: scans keep their strokes at screen size and are smoothed when zoomed; M7 #2517: a narrowed then widened paragraph keeps the typed spaces the wrap consumed, after save and reopen; estimates unchanged) > **Last reviewed:** 2026-10-28 | **Last updated:** 2026-10-28 | **Change:** minor (M10, #4119 partial: Enhance scanned file cleans scanned pages in place: background removal, edge shadow removal, despeckle; estimates unchanged) > **Last reviewed:** 2026-10-27 | **Last updated:** 2026-10-27 | **Change:** minor (M10: OCR model downloads use verified ONNX pairs with legacy discovery fallback; estimates unchanged) +> **Last reviewed:** 2026-10-25 | **Last updated:** 2026-10-25 | **Change:** minor (web: same-document host mode on the canvas, `data-host="page"`; estimates unchanged) > **Last reviewed:** 2026-10-25 | **Last updated:** 2026-10-25 | **Change:** minor (M14 localization current state: Arabic logical catalog, explicit RTL label direction and mirrored stock chrome; native/browser RTL workflows unqualified. Native release Hans face via LXGW WenKai Lite; estimates unchanged) > **Last reviewed:** 2026-10-23 · **Last updated:** 2026-10-23 · **Change:** minor (M7, #2636 partial: pasting added text boxes and images in the engine and through `content_copy`; estimates unchanged) > **Last reviewed:** 2026-10-23 · **Last updated:** 2026-10-23 · **Change:** minor (M11: image optimization accounts for page-local UserUnit; estimates unchanged) @@ -273,6 +274,7 @@ Ranked; detail and the full milestone table in [docs/roadmap.md](docs/roadmap.md - **2026-10-29 (M2):** Scanned pages look like the paper again. An image that doesn't ask for /Interpolate was shrunk by nearest-neighbour (since #635), which kept one sample in N per axis, so the text of a 300 dpi scan at 100% lost most of its strokes; it is now area-averaged to whole device pixels (on a 13-page 300 dpi scan every sample at 96–192 dpi is within 1 of the exact area average; it was up to 255 off). Enlarged, an image of page-scan size is smoothed bilinearly, so a zoomed scan has no staircases; icons, QR codes and pixel art keep hard pixels. Estimates unchanged. - **2026-10-26 (M11, JBIG2 symbols):** Lossless JBIG2 now stores each distinct mark of a black-and-white image once, as a symbol, and places its exact copies, when that is smaller than the generic region: on six pages of rendered 300 dpi text 28% of the generic region's size and 17% of Group 4's, and the same bits back through two independent decoders (hayro-jbig2 and Poppler). Scans, whose letters are seldom identical, gain little until refinement coding; a dictionary shared between pages (`/JBIG2Globals`) is next. Estimates unchanged. - **2026-10-25 (M5, comment replies):** One reply can be deleted from the Comments panel without its thread. On the selected card each reply has its own "…" menu (Edit, Copy text, Delete); Delete takes that reply with its pop-up and the replies to it, as `comment_delete` already did headlessly, and the comment and its other replies stay. The card stays selected, and the panel's editor stays open, on what they were on though the delete moved it in `/Annots`. Undo and Redo close the editor, since either can move what it was open on. A locked reply can't be deleted. Estimates unchanged. +- **2026-10-25 (web, same-document host mode):** A page that loads the PdfCraft web module into its own document (no iframe) can opt into the host bridge with `data-host="page"` on the app's canvas — the exact value `page`; any other value keeps the normal app with downloads, unless a same-origin framed `?host=parent` selects the parent bridge (unframed or cross-origin, `?host=parent` also keeps the normal app). It is the `?host=parent` bridge with the transport swapped: the same five messages travel as non-bubbling `CustomEvent`s on the canvas (`detail` holds the parent messages' fields without `type`; the host answers with a `pdfcraft:open` event), so saves reach the host instead of downloading and dirty and start-up-failure reporting are unchanged. Unit tests cover the opt-in rule; no parity or estimate changes. - **2026-10-24 (M10, #4158 partial):** Word, HTML, RTF and PowerPoint export keep a block that continues another on its line (an italic case name, a link, a superscript) as a run in its own style inside that paragraph, with the source's word space, instead of a paragraph of its own. Style changes that wrap onto the next line still split paragraphs (the reading blocks keep style boundaries). Estimates unchanged. - **2026-10-24 (M3, window move on Wayland, #3970 follow-up):** After a move or resize by PdfCraft's own title bar or edges, the button release given back to egui goes before the pointer leaving the window, so hover no longer sticks at the old place until the pointer moves. Found by CodeRabbit in review of #3970; a unit test covers it. Estimates unchanged. - **2026-10-24 (M14, #4253):** The annotation quick bar remembers Keep tool selected across restarts, including unpinning. Old and malformed settings keep safe defaults; the opt-in UI control channel reads and changes the same preference. Estimates unchanged. @@ -301,7 +303,11 @@ Ranked; detail and the full milestone table in [docs/roadmap.md](docs/roadmap.md Estimates unchanged. - **2026-10-21 (M3, window resize and move on Wayland):** With PdfCraft's own title bar on GNOME/Wayland, a second resize by a window edge, or a second move by the empty tab strip, works straight after the first; it waited for a click inside the window, because the compositor keeps the button's release from egui. A unit test covers the release given back; checked by hand in a test build. Estimates unchanged. - **2026-10-24 (M5, move preview):** A comment being moved is drawn where it goes while it is dragged (a rectangle or oval showed only its blue frame): the comment is rendered alone once as the drag starts and laid over the page, which shows it where it was until the move is applied. Engine `Document::comment_layer`; synthetic engine and UI regressions. Estimates unchanged. +- **2026-10-24 (M5, border shape):** Text boxes and Fill & Sign's typed text take an oval or a circle for their border (Comment Properties ▸ Border shape, Fill & Sign's toolbar): the text box keeps its place and the shape goes around it, the text centred, a circle snug around the text (its box no wider than the text needs); stored as /RD and /PCBorderShape and drawn in the appearance. comment_add / comment_edit / fill_sign_add `border_shape`. One new label in every catalog. Synthetic annot, UI and automation regressions. Estimates unchanged. - **2026-10-24 (M5, Escape in Fill & Sign):** Escape leaves a Fill & Sign tool as it leaves a comment tool: the first press closes the open type box, the next goes back to Select, so the Text tool no longer opens a box at every click with no way out by the keyboard. A synthetic UI regression covers the Text and Checkmark tools. Estimates unchanged. +- **2026-10-23 (M5, ortho):** Shift while drawing holds a line or arrow level or plumb, whichever is nearer (a CAD drawing's ortho mode), and each new side of connected lines, a polygon or a cloud from the corner before; dragging an end or corner with Shift is held the same way (it turned to 45° steps). `measure::snap::ortho`; `comment_add ortho`. Estimates unchanged. +- **2026-10-24 (M3, arrow keys on a wide page):** → / ← scroll a page wider than the window (a plan zoomed in) sideways a line at a time and turn the page at its edge, as ↓ / ↑ do in single-page view; ⌘→ / ⌘← turn it at once, and a page that fits across turns as before (#185). A synthetic viewer regression covers both. Estimates unchanged. +- **2026-10-24 (M5, part opacity):** Comment Properties sets a text box's text, border and fill, and a shape's line and fill, each at an opacity of its own (a see-through fill with an opaque line on a plan); stored as /CA, /ca (PDF 2.0) and /PCTextOpacity and drawn with separate graphics states, so other viewers show it. Make Properties Default and the settings carry it; comment_add / comment_edit `fill_opacity`, `text_opacity`. Four new labels in every catalog. Synthetic annot, UI and automation regressions. Estimates unchanged. - **2026-10-22 (M4, #3916 partial):** Document edits and Undo/Redo cancel an Organize page drag. Pointer-release regressions check exact page order and save/reopen. - **2026-10-22 (M10, #3752 paper):** CUPS jobs ask for the chosen paper in every size. The 13 sizes the Print dialog sent no paper for (A6, A0–A2, ARCH, ANSI C–E) use PWG 5101.1 names, checked against a synthetic PPD with `cupsfilter`, and `doc_print` to a printer sends the paper too. The macOS tray half (Auto Select instead of the PPD's default tray) is a craft-print change that needs a pin bump here. Estimates unchanged. @@ -323,6 +329,7 @@ Ranked; detail and the full milestone table in [docs/roadmap.md](docs/roadmap.md - **2026-10-20 (M11, #3507):** Image merging keeps trailing comments, split operands and graphics state across content streams. Synthetic tool tests check saved text, rendered regions and exact image rows. - **2026-10-17 (M8, gap 6, #2662):** A filled cover over a long line counts when it hides half of any one word, not only 40% of the line's words or box, so a black box over one number in a long line — or an unapplied redaction mark over it — no longer audits clean while the number is still extractable; a sliver under half of every word it touches and under 40% of the line is still not flagged +- **2026-10-13 (M10, OCR review, batch and two engines):** Scan & OCR gains a review step, a second engine and Unicode output. Recognition can clean the raster first (opt-in auto-rotate, deskew, denoise, binarize; word boxes map back to the scan) and read with the built-in ocrs engine, an installed tesseract program run as a fenced external process (a validated location that fails closed instead of falling back to the PATH, allow-listed languages, a private temp directory, timeout and output caps), or both: Automatic asks tesseract when the ocrs reading is weak or of unknown confidence, and a ROVER merge keeps the more confident word (an unscored ocrs word yields only to a tesseract word of 70 or more). The OCR Verify screen (Scan & OCR ▸ Correct recognized text) reviews a recognition before it is applied: confidence-coloured word boxes, corrections, a per-language user dictionary (a plain-text file in the preferences folder, so a word added from any document stays on disk after it closes), Re-OCR of a page or a region, Accept/Reject per page or whole. Pages accepted one by one each apply once; a region re-read moves the review marks of the words it keeps, and a whole-page re-read clears that page's marks (undoable in the panel). Output is searchable (an invisible layer, one undo step) or a NEW editable document of visible text. Words beyond WinAnsi are drawn in Type3 faces from craft-fonts with a ToUnicode map in the editable output (characters no bundled face has appear as '?'); the searchable layer writes them as Type3 fonts with empty character programs and a ToUnicode map, so extraction reads them back with no fonts and no substitutions; redaction removes that layer like any other text (tests in pdfcraft-redact; the end-to-end engine test needs the craft-fonts build input and is skipped without it). Batch runs skip pages that already have text unless forced, and skip whole files that have text only with the opt-in skip-files flag (off by default; Force OCR overrides both); they refuse two inputs of the same file name and existing outputs before reading anything, and report low-confidence pages at the settings' threshold. Headless: ocr_recognize (engine, strategy, preprocessing, region; the editable output goes to an `out` that must not exist yet, and `out` is refused for a searchable run), ocr_words, ocr_review_apply, ocr_dictionary, ocr_status and ocr_recognize_files. All 21 interface catalogs carry the new strings; the Lithuanian ones were added without native review. Reading with every cleaning step off passes the render through untouched, as on main (the 300 dpi normalization runs only when a cleaning step is on: enlarging a 72 dpi render 4x on its own made the models read "due: €250" as "ue: ?250"). Still missing: the deep scan clean-up options (descreen, background and edge-shadow removal), scan images in the editable output, matching the scanned typeface, and recognition quality beyond the tested English set. - **2026-10-13 (M10, #1757):** Office export keeps each dotted-leader contents entry in one paragraph, with its page number, instead of inferring table cells from its separate text objects. - **2026-10-22 (M6, calculation scripts):** The Calculate tab and a rename read simplified field notation only from a comment, where Acrobat writes it: a string that spells `BVCALC … EVCALC` is no longer taken for the notation, or rewritten by a rename. A `/` after the condition of `if`, `while`, `for` or `with` starts a regular expression, so a rename no longer rewrites a name inside one, and a quote inside one no longer hides the `getField` calls after it. Both found in review of #3550. A `//` comment ends at `\r`, U+2028 or U+2029 as well as `\n`, so in a script with `\r` line endings the code after one is no longer hidden from a rename, or taken for the notation. Estimates unchanged. - **2026-10-20 (M6, calculation order page):** Prepare a form ▸ Calculation order, a page of its own, lists the calculated fields in the order they calculate with their formulas and values, moved with Up/Down arrows (as Acrobat's Set Field Calculation Order), Alt+↑/↓ or by dragging. A card says what is wrong with the order and holds Fix order; a loop has a card of its own that opens one of its formulas. On the page, each calculated field shows its step, and arrows show what the field in focus reads and what reads it. Estimates unchanged. @@ -333,6 +340,7 @@ Ranked; detail and the full milestone table in [docs/roadmap.md](docs/roadmap.md - **2026-10-20 (M12, #3673):** Character encoding accepts Identity-H/V fonts with Adobe CJK collections and recognizes predefined non-Identity CMaps independently. Unknown CMaps and foreign registries remain refused; synthetic checker and read-only automation regressions passed after failing before the fix. Per-glyph mapping validation and embedded-font extraction remain separate. Estimates unchanged. - **2026-10-19 (M6, renames keep formulas):** Renaming a field renames it in every calculation that reads it, in the same undo step: `AFSimple_Calculate` field lists, simplified field notation (the comment and the JavaScript after it) and `getField` calls naming it in one string literal; the rest of each script is kept as written. A sum used to drop the renamed field, notation read it as 0 and a script kept a stale value. Field Properties says how many formulas changed and `form_set_props` lists them as `formulas_updated`. Names built at run time and other events' scripts are not rewritten. Estimates unchanged. - **2026-10-19 (M6, text field table):** Prepare a form ▸ Text field table drags out an area and adds rows and columns of named text fields as one undoable edit, laid out on the page as displayed, with a live preview, per-column name patterns and widths, and refusal before anything is added when a cell would be too small or a name taken; `form_add_field_table` does the same headlessly. `form.multiple-copies` is partial: copying an existing field into a grid is still missing. Estimates unchanged. +- **2026-10-17 (research):** Added a [PDF workflow research reference](docs/research/pdf-workflows/README.md): dated public-source locators, 20 workflow research domains, a pinned feature mapping and interaction evidence. Reference documentation; no feature statuses, milestone priorities or estimates changed. - **2026-10-16 (M7, #2516):** A paragraph number from `text_paragraphs` keeps naming the paragraph it listed after edits regroup the page: `text_edit`, `text_edit_layout` and `page_render`'s `hide_text_block` find it again by its text and box, and refuse one that was merged into a neighbour (the edited paragraph included) instead of rewriting the paragraph that took its number (`stale_paragraphs` lists the numbers gone). The inline editor's switch-paragraph click holds the same key. No stable identity across save and reopen yet (#2508). - **2026-10-19 (M7, #3591):** A background added to a page that already has one is painted over the old one instead of going under it and staying hidden. Behind the content, backgrounds come first, in the order added, and then behind-content watermarks, so a watermark added after a background no longer disappears. Synthetic regressions in `crates/edit` check the order. Estimates unchanged. @@ -344,9 +352,13 @@ Ranked; detail and the full milestone table in [docs/roadmap.md](docs/roadmap.md - **2026-10-20 (M3, #3541/#3620):** Comment hover follows the individual marked lines instead of the enclosing multiline rectangle, and overlapping comments follow paint order. Synthetic UI regressions cover all four text-markup kinds, page/view rotations, neighboring highlights, legacy rectangle fallback and unchanged PDF bytes. Estimates unchanged. - **2026-10-20 (M10, #3532 partial):** Vector printing retains existing widget artwork when its appearance lacks Subtype. A print-owned copy adds Form dispatch metadata. The source stream and all explicit subtypes stay unchanged. Synthetic source/output raster checks cover resources, selected/shared appearances, placement, flags and content modes. Appearance regeneration and physical printer validation remain outside this fix. Estimates unchanged. +- **2026-10-20 (M5, several comments):** Comment Properties opened on one of several selected comments, the context menu's Colour and the quick bar's colour change all of them as one undo step, each where the property applies (a font size to text boxes, a fill to shapes, a width to lines and shapes); one that stays locked keeps its look. Copied Fill & Sign ticks, crosses, dots and lines hang on the pointer as themselves rather than as empty boxes, and copied text boxes show their text (`FillMark::strokes` is shared by the appearance and the outline). Estimates unchanged. +- **2026-10-19 (M5, comments between documents):** Comments copy and paste, within and between documents: ⌘C with comments selected copies them as XFDF (each with its replies) to the app's and the system clipboard, ⌘V / Edit ▸ Paste comments / the page menu pastes them onto the current page as new comments under names of their own (`Edit::PasteComments`, `pdfcraft_xfdf::import_comments` with a target page and fresh names, so nothing is replaced and pasting twice gives two sets; `export_xfdf_comments` writes a selection with its replies). Several comments select at once (⌘-click, ⇧-click, on the page and in the panel); Delete removes them as one step and a drag moves them together. Connected lines, polygons and clouds finish from the right-click menu's Complete (Undo last point, Cancel drawing beside it), as other editors do. Tools `comments_copy` / `comments_paste`. Estimates unchanged. - **2026-10-20 (M5, arrow keys move comments):** With a comment selected, the arrow keys move it a screen pixel and ⌘/Ctrl or Shift and an arrow ten, instead of scrolling the view or turning the page; up is up on screen at any zoom and rotation, and each press is one undo step. Text markup and locked comments stay put. Estimates unchanged. +- **2026-10-20 (M8, #3647):** Apply prunes fully removed tiling patterns, then checks retained pattern resources for text, images and unreadable content before reporting success. Shared patterns, Form-owned and inherited patterns, and cells kept by another page cause an atomic refusal when safe removal cannot be shown. Synthetic saved-file and automation regressions cover refusal, preserved marks and undo, and vector-only controls. Estimates unchanged. + - **2026-10-20 (M1, PR #1143 review):** Repair-aware dictionary/preflight edits and snapshot restoration preserve both accepted generations of a damaged live slot. Such edits use the existing full-save fallback; classic and packed rewrites coalesce aliases so page-tree parent links retain one object identity. Explicit generation replacement remains single-generation. Materialized xref diagnostics inspect retained primary and hybrid rows before folding, retaining the 256-object cap plus summary and discarding abandoned-index notes. Synthetic red/green controls cover preflight, undo restoration, equal values, explicit narrowing, encryption packing and four save variants. Estimates unchanged. - **2026-10-19 (M14, #3373):** The main menu and its long submenus scroll in short windows, keeping their commands reachable. Estimates unchanged. diff --git a/apps/pdfcraft-cli/tests/it/batch_exit.rs b/apps/pdfcraft-cli/tests/it/batch_exit.rs new file mode 100644 index 0000000000..6dfb9f61e9 --- /dev/null +++ b/apps/pdfcraft-cli/tests/it/batch_exit.rs @@ -0,0 +1,111 @@ +//! The exit codes the CLI has today: `ExitCode::SUCCESS` (0) or `ExitCode::FAILURE` (1). +//! +//! Pinned here so that the exit-code contract is a visible, reviewed change when it comes: a +//! failed file, an outside-root path and a usage error all exit 1 today. + +use serde_json::Value; +use std::path::{Path, PathBuf}; +use std::process::{Command, Output}; + +const BIN: &str = env!("CARGO_BIN_EXE_pdfcraft-cli"); + +/// A fresh folder for one test, so the tests can run in parallel and leave nothing behind. +fn workdir(name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("pdfcraft-cli-exit-{}-{name}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + dir +} + +/// `batch` with `args`, run from the working directory `dir`. +fn batch(dir: &Path, args: &[&str]) -> Output { + Command::new(BIN).current_dir(dir).arg("batch").args(args).output().unwrap() +} + +/// `run --script --report` from the working directory `dir`: one JSON document for the run. +fn run_report(dir: &Path, script: &Path) -> Output { + Command::new(BIN).current_dir(dir).args(["run", "--script"]).arg(script).arg("--report").output().unwrap() +} + +/// The one JSON document a command prints on stdout. +fn reported(output: &Output) -> Value { + serde_json::from_slice(&output.stdout).unwrap() +} + +#[test] +fn batch_exits_0_when_every_file_succeeds() { + let dir = workdir("batch-ok"); + std::fs::write(dir.join("page.txt"), "Exit code page").unwrap(); + let output = batch(&dir, &["page.txt", "--steps", "convert", "--out-dir", "out"]); + assert_eq!(output.status.code(), Some(0), "{}", String::from_utf8_lossy(&output.stderr)); + let report = reported(&output); + assert_eq!(report["completed"], 1, "{report}"); + assert_eq!(report["failed"], 0, "{report}"); + assert!(dir.join("out/page.pdf").exists(), "the converted page is written"); + std::fs::remove_dir_all(&dir).unwrap(); +} + +#[test] +fn batch_exits_1_when_one_file_fails() { + let dir = workdir("batch-fail"); + std::fs::write(dir.join("bad.pdf"), "broken").unwrap(); + let output = batch(&dir, &["bad.pdf", "--steps", "convert", "--out-dir", "out"]); + assert_eq!(output.status.code(), Some(1), "{}", String::from_utf8_lossy(&output.stderr)); + let report = reported(&output); + assert_eq!(report["failed"], 1, "{report}"); + std::fs::remove_dir_all(&dir).unwrap(); +} + +#[test] +fn batch_usage_error_exits_1_and_creates_nothing() { + let dir = workdir("batch-usage"); + std::fs::write(dir.join("page.txt"), "Exit code page").unwrap(); + // Baseline: a usage error exits 1 today. A later change to the exit-code contract will + // update this assertion on purpose. + let output = batch(&dir, &["page.txt", "--out-dir", "out"]); + assert_eq!(output.status.code(), Some(1), "{}", String::from_utf8_lossy(&output.stderr)); + assert!(output.stdout.is_empty(), "a usage error prints to stderr, not a report on stdout"); + assert!(!output.stderr.is_empty(), "a usage error says what is wrong"); + assert!(!dir.join("out").exists(), "a refused batch creates no output"); + std::fs::remove_dir_all(&dir).unwrap(); +} + +#[test] +fn batch_outside_root_exits_1_and_creates_nothing() { + let dir = workdir("batch-outside-root"); + let output = Command::new(BIN) + .current_dir(&dir) + .args(["batch", "../outside.pdf", "--steps", "convert", "--out-dir", "out", "--root"]) + .arg(&dir) + .output() + .unwrap(); + assert_eq!(output.status.code(), Some(1), "{}", String::from_utf8_lossy(&output.stderr)); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!(stderr.contains("is outside the allowed directory"), "the input is refused by the root: {stderr}"); + assert!(output.stdout.is_empty(), "a refused batch prints no report"); + assert!(!dir.join("out").exists(), "a refused batch creates no output"); + std::fs::remove_dir_all(&dir).unwrap(); +} + +#[test] +fn run_script_report_exits_0_when_ok_and_1_when_a_step_fails() { + let dir = workdir("run-report"); + let script = dir.join("steps.json"); + let blank = serde_json::json!({ "tool": "doc_create", "args": { "from": "blank", "width": 100, "height": 100 } }); + let steps = serde_json::json!([blank.clone(), { "tool": "no_such_tool", "args": {} }]); + std::fs::write(&script, steps.to_string()).unwrap(); + + let failing = run_report(&dir, &script); + assert_eq!(failing.status.code(), Some(1), "{}", String::from_utf8_lossy(&failing.stderr)); + let report = reported(&failing); + assert_eq!(report["ok"], false, "{report}"); + assert_eq!(report["steps"][1]["status"], "error", "{report}"); + + std::fs::write(&script, serde_json::json!([blank]).to_string()).unwrap(); + let good = run_report(&dir, &script); + assert_eq!(good.status.code(), Some(0), "{}", String::from_utf8_lossy(&good.stderr)); + let report = reported(&good); + assert_eq!(report["ok"], true, "{report}"); + assert_eq!(report["steps"][0]["status"], "ok", "{report}"); + std::fs::remove_dir_all(&dir).unwrap(); +} diff --git a/apps/pdfcraft-cli/tests/it/main.rs b/apps/pdfcraft-cli/tests/it/main.rs index f0b87c97a7..30a6e25882 100644 --- a/apps/pdfcraft-cli/tests/it/main.rs +++ b/apps/pdfcraft-cli/tests/it/main.rs @@ -3,6 +3,7 @@ mod audit; mod automation_roots; mod batch; +mod batch_exit; mod check; mod edit; mod extract; diff --git a/apps/pdfcraft-web/Cargo.toml b/apps/pdfcraft-web/Cargo.toml index ad8243d594..56e10c0c29 100644 --- a/apps/pdfcraft-web/Cargo.toml +++ b/apps/pdfcraft-web/Cargo.toml @@ -11,10 +11,12 @@ workspace = true [dependencies] pdfcraft-ui-egui = { workspace = true } +# The host messages (storytold/craft-libs): one contract and one bridge for the web builds. +craft-web-host = { git = "https://github.com/storytold/craft-libs", rev = "2e2312ddaf21bc3d85cd3395d0955c7d239306f6", version = "0.1.0" } eframe = { workspace = true, features = ["default_fonts", "glow", "persistence", "accesskit"] } egui = { workspace = true, features = ["default_fonts", "monochrome_emoji_fonts"] } [target.'cfg(target_arch = "wasm32")'.dependencies] wasm-bindgen-futures = "0.4" -web-sys = { version = "0.3", features = ["Window", "Document", "Element", "HtmlCanvasElement", "HtmlElement", "Location", "Url", "UrlSearchParams", "Response", "Event", "MessageEvent", "EventTarget"] } +web-sys = { version = "0.3", features = ["Window", "Document", "Element", "HtmlCanvasElement", "HtmlElement", "Location", "Url", "UrlSearchParams", "Response", "Event", "MessageEvent", "EventTarget", "CustomEvent", "CustomEventInit"] } js-sys = "0.3" diff --git a/apps/pdfcraft-web/src/main.rs b/apps/pdfcraft-web/src/main.rs index 73d14f4a6c..ffa5a06068 100644 --- a/apps/pdfcraft-web/src/main.rs +++ b/apps/pdfcraft-web/src/main.rs @@ -5,18 +5,11 @@ #[cfg(target_arch = "wasm32")] fn main() { - use eframe::wasm_bindgen::JsCast; use pdfcraft_ui_egui::PdfCraftApp; let options = eframe::WebOptions { renderer: eframe::Renderer::Glow, ..Default::default() }; wasm_bindgen_futures::spawn_local(async move { - let Some(canvas) = web_sys::window() - .and_then(|w| w.document()) - .and_then(|d| d.get_element_by_id("pdfcraft")) - .and_then(|e| e.dyn_into::().ok()) - else { - return; - }; + let Some(canvas) = app_canvas() else { return }; let started = eframe::WebRunner::new() .start( canvas, @@ -54,11 +47,11 @@ fn main() { // eframe never raises a close request on a browser reload or tab close, so `guard_quit` never // prompts; ask the browser to confirm instead while a document has unsaved work (#812). warn_before_unload(app.unsaved_flag.clone()); - // `?host=parent`: a same-origin page embedding PdfCraft in an iframe (such - // as the Nextcloud app) passes files in and takes saves back (`host` below). - if query_param("host").as_deref() == Some("parent") - && let Some(bridge) = host::Bridge::new() - { + // Host modes (`host` below, over `craft-web-host`): `?host=parent`, a + // same-origin page embedding PdfCraft in an iframe (such as the Nextcloud + // app), or `data-host="page"` on the canvas, a host that runs the module in + // its own document. + if let Some(bridge) = app_canvas().as_ref().and_then(host::Bridge::connect) { // `?author=`: the host's name for the user signs their comments, // unless they chose a name in PdfCraft (the web default is "Guest"). if let Some(author) = query_param("author").map(|a| a.trim().to_string()).filter(|a| !a.is_empty()) @@ -81,9 +74,7 @@ fn main() { .await; if let Err(e) = started { eframe::web_sys::console::error_1(&e); - if query_param("host").as_deref() == Some("parent") - && let Some(bridge) = host::Bridge::new() - { + if let Some(bridge) = app_canvas().as_ref().and_then(host::Bridge::connect) { bridge.post_failed(&e.as_string().unwrap_or_else(|| format!("{e:?}"))); } } @@ -123,136 +114,116 @@ async fn fetch_bytes(url: &str) -> Result, String> { Ok(js_sys::Uint8Array::new(&buf).to_vec()) } -/// The `postMessage` bridge to a same-origin parent page. Messages are plain objects with a -/// `type`: +/// The app's canvas: the one element `index.html` and every embedding page must provide, with +/// the id the app looks up. +#[cfg(target_arch = "wasm32")] +fn app_canvas() -> Option { + use eframe::wasm_bindgen::JsCast; + web_sys::window()?.document()?.get_element_by_id("pdfcraft").and_then(|e| e.dyn_into::().ok()) +} + +/// Host modes: how the page embedding PdfCraft passes files in and takes saves back. The messages +/// and the two transports are `craft-web-host`'s (storytold/craft-libs), the same contract as the +/// other Craft apps' bridges, with the `pdfcraft:` prefix. This module is PdfCraft's part of it. /// -/// - `pdfcraft:ready` (to the parent): the app is listening; send files now. -/// - `pdfcraft:open` (from the parent): `{ name, bytes }`, where `bytes` is an `ArrayBuffer` or -/// `Uint8Array` holding a PDF. It opens in a tab, like a `?file=` URL. -/// - `pdfcraft:save` (to the parent): `{ name, saveAs, bytes }` when the user saves; `bytes` is -/// a transferred `ArrayBuffer`. The parent stores the file (and reports its own errors). -/// - `pdfcraft:dirty` (to the parent): `{ dirty }` whenever unsaved work appears or goes away. -/// - `pdfcraft:failed` (to the parent): `{ error }` when the app couldn't start. -/// -/// Only the parent window on the app's own origin is heard or answered. With a parent on -/// another origin there is no bridge: the app runs as if unframed and saves download. +/// - `?host=parent` is the `postMessage` bridge for a same-origin page that embeds PdfCraft in an +/// iframe (such as the Nextcloud app). With a parent on another origin there is no bridge: the +/// app runs as if unframed and saves download (#2167). `data-host="page"` on the app's canvas +/// is for a host that loads the module into its own document, with no iframe: the same messages +/// travel as DOM `CustomEvent`s on that canvas. `?host=parent` wins when both are present. +/// - `pdfcraft:ready` once the app is listening; send files now. PdfCraft reads bytes, so it +/// says `file: false` and a host sends `bytes`. +/// - `pdfcraft:open` (from the host): `{ name, bytes }` holding a PDF. It opens in a tab, like a +/// `?file=` URL; a file over [`host::MAX_OPEN_BYTES`] is refused before it is copied. +/// - `pdfcraft:save` (to the host): `{ name, saveAs, bytes }` when the user saves. The host stores +/// the file (and reports its own errors). +/// - `pdfcraft:dirty` whenever unsaved work appears or goes away, `pdfcraft:failed` when the app +/// couldn't start. #[cfg(target_arch = "wasm32")] mod host { - use eframe::wasm_bindgen::{JsCast, JsValue, closure::Closure}; + use std::rc::Rc; + + use craft_web_host::web::{FileData, Host, Message}; + + /// The app id in the host messages (`pdfcraft:ready`). + const APP: &str = "pdfcraft"; + + /// The name a file gets when the host sent none (the crate says `document` for a blank name). + const DEFAULT_NAME: &str = "document.pdf"; + + /// The largest file the host may hand over to open, checked before it is copied (the app's own readers have their own limits). + const MAX_OPEN_BYTES: u64 = 512 << 20; #[derive(Clone)] pub struct Bridge { - window: web_sys::Window, - parent: web_sys::Window, - origin: String, + host: Rc, } impl Bridge { - /// `None` when the page isn't framed (there is no parent to talk to), or when the parent - /// is on another origin: messages only go to this origin, so the browser would drop - /// every save without an error while the document showed as saved (#2167). - pub fn new() -> Option { - let window = web_sys::window()?; - let parent = window.parent().ok().flatten()?; - if js_sys::Object::is(&parent, &window) { - return None; - } - let origin = window.location().origin().ok()?; - // Reading another origin's location throws, which is `None` too. - if parent.location().origin().ok()? != origin { - return None; - } - Some(Self { window, parent, origin }) - } - - fn post(&self, message: &js_sys::Object, transfer: Option<&JsValue>) -> Result<(), String> { - let sent = match transfer { - Some(t) => self.parent.post_message_with_transfer(message, &self.origin, &js_sys::Array::of1(t)), - None => self.parent.post_message(message, &self.origin), - }; - sent.map_err(|e| e.as_string().unwrap_or_else(|| format!("{e:?}"))) + /// The bridge for this page, or `None` when PdfCraft isn't hosted: no `?host=parent` and + /// no `data-host="page"` on the canvas, an unframed `?host=parent` page, or a parent on + /// another origin (messages only go to this origin, so the browser would drop every save + /// without an error while the document showed as saved, #2167). + pub fn connect(canvas: &web_sys::HtmlCanvasElement) -> Option { + Some(Self { host: Rc::new(Host::connect(APP, canvas)?) }) } pub fn post_ready(&self) { - if let Some(m) = message(&[("type", "pdfcraft:ready".into()), ("version", env!("CARGO_PKG_VERSION").into())]) { - let _ = self.post(&m, None); - } + let _ = self.host.post_ready(env!("CARGO_PKG_VERSION"), false); } - /// The app couldn't start (no WebGL, for example): let the parent say so. + /// The app couldn't start (no WebGL, for example): let the host say so. pub fn post_failed(&self, error: &str) { - if let Some(m) = message(&[("type", "pdfcraft:failed".into()), ("error", error.into())]) { - let _ = self.post(&m, None); - } + let _ = self.host.post_failed(error, None); } - /// Hear `pdfcraft:open` from the parent and queue the file like a `?file=` download. + /// Hear `pdfcraft:open` and queue the file like a `?file=` download. pub fn listen(&self, inbox: pdfcraft_ui_egui::Inbox, ctx: egui::Context) { - let parent = self.parent.clone(); - let origin = self.origin.clone(); - let on_message = Closure::::new(move |event: web_sys::MessageEvent| { - if event.origin() != origin || !event.source().is_some_and(|s| js_sys::Object::is(&s, &parent)) { - return; + self.host.listen(move |message| { + if let Message::Open { name, data } = message { + queue_open(&name, &data, &inbox, &ctx); } - let data = event.data(); - if string(&data, "type").as_deref() != Some("pdfcraft:open") { - return; - } - let name = string(&data, "name").filter(|n| !n.trim().is_empty()).unwrap_or_else(|| "document.pdf".to_string()); - let Ok(bytes) = js_sys::Reflect::get(&data, &JsValue::from_str("bytes")) else { return }; - let bytes = if let Some(array) = bytes.dyn_ref::() { - array.to_vec() - } else if bytes.is_instance_of::() { - js_sys::Uint8Array::new(&bytes).to_vec() - } else { - return; - }; - if let Ok(mut q) = inbox.lock() { - q.push((name, bytes)); - } - ctx.request_repaint(); }); - if self.window.add_event_listener_with_callback("message", on_message.as_ref().unchecked_ref()).is_ok() { - // The listener lives as long as the page. - on_message.forget(); - } } pub fn save_fn(&self) -> pdfcraft_ui_egui::HostSaveFn { - let bridge = self.clone(); - Box::new(move |name: &str, bytes: &[u8], save_as: bool| { - let buffer = js_sys::Uint8Array::from(bytes).buffer(); - let m = - message(&[("type", "pdfcraft:save".into()), ("name", name.into()), ("saveAs", save_as.into()), ("bytes", buffer.clone().into())]) - .ok_or_else(|| "couldn't build the message".to_string())?; - bridge.post(&m, Some(&buffer)) - }) + let host = self.host.clone(); + Box::new(move |name: &str, bytes: &[u8], save_as: bool| host.post_save(name, bytes, None, save_as)) } pub fn dirty_fn(&self) -> pdfcraft_ui_egui::HostDirtyFn { - let bridge = self.clone(); + let host = self.host.clone(); + // A host starts out clean: the first report is a change only when it is dirty. let mut last = false; Box::new(move |dirty: bool| { if dirty != last { last = dirty; - if let Some(m) = message(&[("type", "pdfcraft:dirty".into()), ("dirty", dirty.into())]) { - let _ = bridge.post(&m, None); - } + host.post_dirty(dirty); } }) } } - fn message(fields: &[(&str, JsValue)]) -> Option { - let m = js_sys::Object::new(); - for (key, value) in fields { - js_sys::Reflect::set(&m, &JsValue::from_str(key), value).ok()?; + /// The `pdfcraft:open` payload, `{ name, bytes }` where `bytes` holds a PDF: queue it like a + /// `?file=` download and wake the app. The crate has cleaned the name (and cut it to 255 + /// characters); a blank one comes as `document` and becomes `document.pdf`. + fn queue_open(name: &str, data: &FileData, inbox: &pdfcraft_ui_egui::Inbox, ctx: &egui::Context) { + let name = if name == "document" { DEFAULT_NAME } else { name }.to_string(); + let FileData::Bytes(view) = data else { + eframe::web_sys::console::warn_1(&format!("PdfCraft: host file {name} came as a File; PdfCraft reads bytes only; not opened").into()); + return; + }; + // A file from the host is untrusted input: refuse an oversized one before copying it into the app's memory. + if data.size() > MAX_OPEN_BYTES as f64 { + eframe::web_sys::console::warn_1( + &format!("PdfCraft: host file is {} bytes, over the {} MiB host open limit; not opened", data.size(), MAX_OPEN_BYTES >> 20).into(), + ); + return; } - Some(m) - } - - fn string(data: &JsValue, key: &str) -> Option { - js_sys::Reflect::get(data, &JsValue::from_str(key)).ok()?.as_string() + if let Ok(mut q) = inbox.lock() { + q.push((name, view.to_vec())); + } + ctx.request_repaint(); } } diff --git a/apps/pdfcraft/src/main.rs b/apps/pdfcraft/src/main.rs index 5bc5c5c372..be2290d2f9 100644 --- a/apps/pdfcraft/src/main.rs +++ b/apps/pdfcraft/src/main.rs @@ -439,6 +439,8 @@ fn app_creator<'a>( if let Some(dir) = pdfcraft_ui_egui::RecoveryStore::default_dir() { app.enable_recovery(pdfcraft_ui_egui::RecoveryStore::new(dir)); } + // The OCR Verify screen stores its per-language dictionary beside recovery data. + app.ocr_verify.dictionary_dir = pdfcraft_ui_egui::default_dictionary_dir(); if let Some(state) = &cc.wgpu_render_state { let adapter = state.adapter.get_info(); let max_texture_dimension_2d = state.device.limits().max_texture_dimension_2d; diff --git a/contributors/people.toml b/contributors/people.toml index fecfb68c90..8ab196abc9 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -183,3 +183,6 @@ sync_github_name = true [people.Combiler01] sync_github_name = true + +[people.helenkwok] +real_name = "Helen Kwok" diff --git a/crates/annot/src/appearance.rs b/crates/annot/src/appearance.rs index 89c0f70f48..7148e9fc2e 100644 --- a/crates/annot/src/appearance.rs +++ b/crates/annot/src/appearance.rs @@ -232,6 +232,31 @@ fn rg_stroke(c: Rgb) -> String { format!("{} {} {} RG\n", n(c[0]), n(c[1]), n(c[2])) } +/// A FreeText's border colour where it has its own: the stroking colour in `/DA` (`RG`, or `G` +/// for grey). `None`: the border takes the text colour. +pub fn da_border(d: &Dict) -> Option { + let da = d.get(b"DA").and_then(|o| o.as_string()).map(|s| String::from_utf8_lossy(&s.bytes).into_owned())?; + let toks: Vec<&str> = da.split_whitespace().collect(); + let num = |i: usize| toks.get(i).and_then(|t| t.parse::().ok()).filter(|x| x.is_finite()); + let mut col = None; + for (i, t) in toks.iter().enumerate() { + match *t { + "RG" if i >= 3 => { + if let (Some(r), Some(g), Some(b)) = (num(i - 3), num(i - 2), num(i - 1)) { + col = Some([r, g, b].map(|x| x.clamp(0.0, 1.0))); + } + } + "G" if i >= 1 => { + if let Some(g) = num(i - 1) { + col = Some([g.clamp(0.0, 1.0); 3]); + } + } + _ => {} + } + } + col +} + /// `/DA` of a text box: (text colour, font size). Defaults to black 12 pt. pub fn parse_da(d: &Dict) -> (Rgb, f64) { let da = d.get(b"DA").and_then(|o| o.as_string()).map(|s| String::from_utf8_lossy(&s.bytes).into_owned()).unwrap_or_default(); @@ -262,19 +287,47 @@ pub fn parse_da(d: &Dict) -> (Rgb, f64) { (col.map(|x| x.clamp(0.0, 1.0)), size.min(400.0)) } -fn ext_gstate(opacity: f64, multiply: bool) -> Option { - if opacity >= 1.0 && !multiply { +/// How opaque a comment's parts are drawn, 0–1: its line or border (`/CA`); its fill or +/// background (`/ca`, which PDF 2.0 gives the non-stroking operations; without it, as the line); +/// and a text box's text (`/PCTextOpacity`, PdfCraft's own; without it, as the fill, since text +/// is filled too). A comment with only `/CA` is drawn at that opacity throughout, as before. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct PartOpacity { + pub line: f64, + pub fill: f64, + pub text: f64, +} + +/// The parts' opacities of the comment `d` (see [`PartOpacity`]). +pub fn part_opacity(d: &Dict) -> PartOpacity { + let get = |key: &[u8]| d.get(key).and_then(|o| o.as_f64()).filter(|x| x.is_finite()).map(|x| x.clamp(0.0, 1.0)); + let line = get(b"CA").unwrap_or(1.0); + let fill = get(b"ca").unwrap_or(line); + let text = get(b"PCTextOpacity").unwrap_or(fill); + PartOpacity { line, fill, text } +} + +/// `/GS0`: the line's opacity for strokes and the fill's for everything filled; `/GS1`, where the +/// text's differs from the fill's: the text's for its glyphs. +fn ext_gstate(parts: PartOpacity, multiply: bool) -> Option { + if parts.line >= 1.0 && parts.fill >= 1.0 && parts.text >= 1.0 && !multiply { return None; } - let mut gs = Dict::new(); - gs.set(b"Type".to_vec(), Object::name("ExtGState")); - if multiply { - gs.set(b"BM".to_vec(), Object::name("Multiply")); - } - gs.set(b"CA".to_vec(), Object::Real(opacity)); - gs.set(b"ca".to_vec(), Object::Real(opacity)); + let gs = |stroke: f64, fill: f64| { + let mut gs = Dict::new(); + gs.set(b"Type".to_vec(), Object::name("ExtGState")); + if multiply { + gs.set(b"BM".to_vec(), Object::name("Multiply")); + } + gs.set(b"CA".to_vec(), Object::Real(stroke)); + gs.set(b"ca".to_vec(), Object::Real(fill)); + Object::Dict(gs) + }; let mut res = Dict::new(); - res.set(b"GS0".to_vec(), Object::Dict(gs)); + res.set(b"GS0".to_vec(), gs(parts.line, parts.fill)); + if parts.text != parts.fill { + res.set(b"GS1".to_vec(), gs(parts.line, parts.text)); + } Some(res) } @@ -313,10 +366,18 @@ fn stamp_turn(d: &Dict) -> i64 { /// The page `/Rotate` a text box's or Fill & Sign text's lines are turned back by /// (`/PCTextRotate`, written when it is added to a turned page). -fn text_turn(d: &Dict) -> i64 { +pub(crate) fn text_turn(d: &Dict) -> i64 { d.get(b"PCTextRotate").and_then(Object::as_int).unwrap_or(0).rem_euclid(360) / 90 * 90 } +/// A FreeText's `/RD`: how far its text box lies inside `/Rect` from the left, bottom, right and +/// top. A distance a hair below 0 (rounding) reads as 0; `None` when one is negative or they can't +/// be read. +pub(crate) fn inset(d: &Dict) -> Option<[f64; 4]> { + let rd: [f64; 4] = nums(d, b"RD")?.try_into().ok()?; + rd.iter().all(|x| x.is_finite() && *x > -0.001).then(|| rd.map(|x| x.max(0.0))) +} + /// The first text [`build`] would draw in the standard fonts (Helvetica, WinAnsiEncoding) that /// they can't, which would come out as `?`: what it is (for the message) and the character. The /// text of a text box, callout or Fill & Sign text, a line's caption, a measurement's label, a @@ -391,7 +452,9 @@ struct AppearanceContext<'a> { subtype: &'a [u8], rect: [f64; 4], cloudy: bool, + /// The line's opacity (`parts.line`). opacity: f64, + parts: PartOpacity, stroke: Option, width: f64, } @@ -408,7 +471,7 @@ impl AppearanceDrawing { fn new(context: &AppearanceContext<'_>) -> Self { let mut drawing = Self::default(); if let Some(gs) = ext_gstate( - context.opacity, + context.parts, context.subtype == b"Highlight" || (context.subtype == b"Ink" && context.dict.name(b"IT") == Some(b"FreehandHighlight")), ) { drawing.resources.set(b"ExtGState".to_vec(), Object::Dict(gs)); @@ -455,7 +518,8 @@ fn appearance_context(d: &Dict) -> Option> { subtype, rect, cloudy, - opacity: d.get(b"CA").and_then(|o| o.as_f64()).unwrap_or(1.0).clamp(0.0, 1.0), + opacity: part_opacity(d).line, + parts: part_opacity(d), stroke: color(d, b"C")?, width: border_width(d), }) @@ -845,46 +909,25 @@ fn draw_stamp(context: &AppearanceContext<'_>, mut drawing: AppearanceDrawing) - let [x0, y0, x1, y1] = draw; let (w, h) = (x1 - x0, y1 - y0); let lw = w.min(h) * 0.12; + // The strokes come from `FillMark::strokes`, which a copy's outline draws too. + let path = |mark: crate::FillMark| { + let ops: Vec = mark + .strokes(draw) + .iter() + .flat_map(|s| s.iter().enumerate().map(|(i, p)| format!("{} {} {}", n(p[0]), n(p[1]), if i == 0 { "m" } else { "l" }))) + .collect(); + format!("{} S\n", ops.join(" ")) + }; match name { - b"PCCheck" => c.push_str(&format!( - "{}{} w 1 J 1 j\n{} {} m {} {} l {} {} l S\n", - rg_stroke(col), - n(lw), - n(x0 + w * 0.15), - n(y0 + h * 0.5), - n(x0 + w * 0.4), - n(y0 + h * 0.2), - n(x0 + w * 0.88), - n(y0 + h * 0.85) - )), - b"PCCross" => c.push_str(&format!( - "{}{} w 1 J\n{} {} m {} {} l {} {} m {} {} l S\n", - rg_stroke(col), - n(lw), - n(x0 + w * 0.18), - n(y0 + h * 0.18), - n(x1 - w * 0.18), - n(y1 - h * 0.18), - n(x0 + w * 0.18), - n(y1 - h * 0.18), - n(x1 - w * 0.18), - n(y0 + h * 0.18) - )), + b"PCCheck" => c.push_str(&format!("{}{} w 1 J 1 j\n{}", rg_stroke(col), n(lw), path(crate::FillMark::Check))), + b"PCCross" => c.push_str(&format!("{}{} w 1 J\n{}", rg_stroke(col), n(lw), path(crate::FillMark::Cross))), b"PCDot" => { let r = w.min(h) * 0.3; c.push_str(&rg(col)); c.push_str(&ellipse(x0 + w / 2.0 - r, y0 + h / 2.0 - r, x0 + w / 2.0 + r, y0 + h / 2.0 + r)); c.push_str("f\n"); } - b"PCLine" => c.push_str(&format!( - "{}{} w 1 J\n{} {} m {} {} l S\n", - rg_stroke(col), - n(h.clamp(0.5, 2.0)), - n(x0), - n(y0 + h / 2.0), - n(x1), - n(y0 + h / 2.0) - )), + b"PCLine" => c.push_str(&format!("{}{} w 1 J\n{}", rg_stroke(col), n(h.clamp(0.5, 2.0)), path(crate::FillMark::Line))), other => { // Only stamps PdfCraft made: others keep their own artwork. if !matches!(d.get(b"PCStamp"), Some(Object::Bool(true))) { @@ -902,14 +945,59 @@ fn draw_stamp(context: &AppearanceContext<'_>, mut drawing: AppearanceDrawing) - Some(form(rect, c.as_bytes(), res)) } +/// The oval or circle (`shape`) around a text box whose whole box is `full`: its background +/// and border go into `c`; returns the text box inside it. +#[allow(clippy::too_many_arguments)] +fn shaped_border( + d: &Dict, + shape: crate::BorderShape, + full: [f64; 4], + turn: i64, + bw: f64, + bg: Option, + line_color: Rgb, + c: &mut String, +) -> Option<[f64; 4]> { + // Laid out as displayed: a quarter turn swaps the sides' differences. + let rect = match inset(d) { + Some(rd) => { + let (dx, dy) = if matches!(turn, 90 | 270) { (rd[1], rd[0]) } else { (rd[0], rd[1]) }; + [full[0] + dx, full[1] + dy, full[2] - dx, full[3] - dy] + } + None => shape.inside(full, bw, full), + }; + if rect[2] - rect[0] < 1.0 || rect[3] - rect[1] < 1.0 { + return None; + } + let h = bw / 2.0; + let [x0, y0, x1, y1] = [full[0] + h, full[1] + h, full[2] - h, full[3] - h]; + let path = match shape { + crate::BorderShape::Circle => { + let (cx, cy, r) = ((x0 + x1) / 2.0, (y0 + y1) / 2.0, (x1 - x0).min(y1 - y0) / 2.0); + ellipse(cx - r, cy - r, cx + r, cy + r) + } + _ => ellipse(x0, y0, x1, y1), + }; + if let Some(bg) = bg { + c.push_str(&format!("{}{path}f\n", rg(bg))); + } + if bw > 0.0 { + c.push_str(&format!("{}{} w\n{}{path}S\n[] 0 d\n", rg_stroke(line_color), n(bw), dash(d))); + } + Some(rect) +} + fn draw_free_text(context: &AppearanceContext<'_>, mut drawing: AppearanceDrawing) -> Option { let d = context.dict; + let parts = context.parts; let rect = context.rect; let stroke = context.stroke; let mut c = std::mem::take(&mut drawing.content); let mut res = std::mem::take(&mut drawing.resources); let _tail = std::mem::take(&mut drawing.tail); let (text_color, size) = parse_da(d); + // The box's border and a callout's leader line: their own colour, else the text's. + let line_color = da_border(d).unwrap_or(text_color); let bg = stroke; let bw = if d.contains(b"BS") || d.contains(b"Border") { border_width(d) } else { 0.0 }; // A callout: the leader line (arrowhead at its first point), and the text box inside @@ -948,7 +1036,7 @@ fn draw_free_text(context: &AppearanceContext<'_>, mut drawing: AppearanceDrawin if pts.len() < 2 || pts.iter().any(|p| !p.0.is_finite() || !p.1.is_finite()) { return None; } - c.push_str(&format!("{}{}{} w 1 J 1 j\n", rg_stroke(text_color), rg(bg.unwrap_or([1.0; 3])), n(lw))); + c.push_str(&format!("{}{}{} w 1 J 1 j\n", rg_stroke(line_color), rg(bg.unwrap_or([1.0; 3])), n(lw))); for (i, p) in pts.iter().enumerate() { c.push_str(&format!("{} {} {}\n", n(p.0), n(p.1), if i == 0 { "m" } else { "l" })); } @@ -957,26 +1045,40 @@ fn draw_free_text(context: &AppearanceContext<'_>, mut drawing: AppearanceDrawin return None; } } - if let Some(bg) = bg { - c.push_str(&format!("{}{} {} {} {} re f\n", rg(bg), n(rect[0]), n(rect[1]), n(rect[2] - rect[0]), n(rect[3] - rect[1]))); - } - if bw > 0.0 { - let h = bw / 2.0; - c.push_str(&format!( - "{}{} w\n{}{} {} {} {} re S\n[] 0 d\n", - rg_stroke(text_color), - n(bw), - dash(d), - n(rect[0] + h), - n(rect[1] + h), - n(rect[2] - rect[0] - bw), - n(rect[3] - rect[1] - bw) - )); + // An oval or a circle (`/PCBorderShape`) around the text box, which is `/Rect` inset by + // `/RD` and keeps its place: background and border take the shape, the text is laid out + // in the text box as in a rectangle. + let shape = crate::BorderShape::of(d); + if shape != crate::BorderShape::Rectangle { + rect = shaped_border(d, shape, full, turn, bw, bg, line_color, &mut c)?; + } else { + if let Some(bg) = bg { + c.push_str(&format!("{}{} {} {} {} re f\n", rg(bg), n(rect[0]), n(rect[1]), n(rect[2] - rect[0]), n(rect[3] - rect[1]))); + } + if bw > 0.0 { + let h = bw / 2.0; + c.push_str(&format!( + "{}{} w\n{}{} {} {} {} re S\n[] 0 d\n", + rg_stroke(line_color), + n(bw), + dash(d), + n(rect[0] + h), + n(rect[1] + h), + n(rect[2] - rect[0] - bw), + n(rect[3] - rect[1] - bw) + )); + } } let text = d.get(b"Contents").and_then(|o| o.as_string()).map(PdfString::to_text).unwrap_or_default(); let pad = 2.0 + bw; let width = (rect[2] - rect[0] - 2.0 * pad).max(1.0); - let q = d.int(b"Q").unwrap_or(0); + // In an oval or a circle the lines are centred in the text box, up and down too. + let round = shape != crate::BorderShape::Rectangle; + let q = if round { 1 } else { d.int(b"Q").unwrap_or(0) }; + // The text at its own opacity, where it has one. + if parts.text != parts.fill { + c.push_str("/GS1 gs\n"); + } c.push_str(&format!( "{} {} {} {} re W n\nBT\n/Helv {} Tf\n{}", n(rect[0]), @@ -987,8 +1089,12 @@ fn draw_free_text(context: &AppearanceContext<'_>, mut drawing: AppearanceDrawin rg(text_color) )); let mut out = c.into_bytes(); + let lines = wrap(&text, size, width); let mut y = rect[3] - pad - size * 0.9; - for line in wrap(&text, size, width) { + if round { + y -= ((rect[3] - rect[1] - 2.0 * pad - lines.len() as f64 * size * 1.2) / 2.0).max(0.0); + } + for line in lines { if y < rect[1] - size { break; } diff --git a/crates/annot/src/appearance/symbols.rs b/crates/annot/src/appearance/symbols.rs index 3b33662524..3178f78e94 100644 --- a/crates/annot/src/appearance/symbols.rs +++ b/crates/annot/src/appearance/symbols.rs @@ -1,4 +1,4 @@ -use super::{Dict, Object, PdfString, Rgb, Stream, color, ext_gstate, form, literal, n, nums, rg, rg_stroke, text_width, win_ansi}; +use super::{Dict, Object, PartOpacity, PdfString, Rgb, Stream, color, ext_gstate, form, literal, n, nums, rg, rg_stroke, text_width, win_ansi}; /// The label and colour of a standard rubber stamp name (ISO 32000-2 Table 184), for a stamp /// another program wrote without an appearance. Names are matched byte for byte, as PDF names @@ -51,7 +51,7 @@ pub(crate) fn display_stamp(d: &Dict) -> Option { // A malformed `/C` falls back to the stamp's own colour rather than hiding the stamp. let stroke = color(d, b"C").flatten(); let mut res = Dict::new(); - if let Some(gs) = ext_gstate(opacity, false) { + if let Some(gs) = ext_gstate(PartOpacity { line: opacity, fill: opacity, text: opacity }, false) { res.set(b"ExtGState".to_vec(), Object::Dict(gs)); } // A stamp whose intent (`/IT`, PDF 2.0) is an image or a snapshot has no `/Name` to default. diff --git a/crates/annot/src/create.rs b/crates/annot/src/create.rs index 1904745e95..6376655ce9 100644 --- a/crates/annot/src/create.rs +++ b/crates/annot/src/create.rs @@ -1,6 +1,6 @@ use super::draw::draw_appearance; use super::lookup::{annot_dict, annot_ref, annots, fill_sign_shape, page_ref, set_annots}; -use super::modify::{n, rich_text}; +use super::modify::{free_text_da, n, rich_text, set_part_keys, shape_text_box}; use super::types::{ FLAG_NO_ROTATE, FLAG_NO_ZOOM, FLAG_PRINT, LineEnding, Markup, Meta, NOTE_SIZE, NewAnnotation, OverlayLook, Rgb, Shape, StampGroup, Style, }; @@ -214,8 +214,13 @@ pub fn add_annotation(doc: &mut Document, new: &NewAnnotation, meta: &Meta) -> R let rect = rect_for(&new.shape, style)?; let mut d = base_dict(new.shape.subtype(), rect, page, &new.contents, &new.author, meta); d.set(b"Subj".to_vec(), PdfString::text(subject(&new.shape))); - let opacity = style.opacity.clamp(0.0, 1.0); - set_non_opaque_style(&mut d, opacity); + if style.fill_opacity.into_iter().chain(style.text_opacity).any(|o| !o.is_finite()) { + return Err(AnnotError::Invalid("invalid opacity".into())); + } + let line = style.opacity.clamp(0.0, 1.0); + let fill = style.fill_opacity.map_or(line, |o| o.clamp(0.0, 1.0)); + let text = style.text_opacity.map_or(fill, |o| o.clamp(0.0, 1.0)); + set_part_keys(&mut d, appearance::PartOpacity { line, fill, text }); let border = |d: &mut Dict| { let mut bs = Dict::new(); bs.set(b"W".to_vec(), Object::Real(style.width.max(0.0))); @@ -380,20 +385,22 @@ pub fn add_annotation(doc: &mut Document, new: &NewAnnotation, meta: &Meta) -> R d.set(b"IT".to_vec(), Object::name("FreeTextTypeWriter")); } let size = if font_size.is_finite() && *font_size > 0.0 { font_size.clamp(1.0, 400.0) } else { 12.0 }; - let [r, g, b] = style.color.map(|x| x.clamp(0.0, 1.0)); - d.set(b"DA".to_vec(), PdfString::literal(format!("{} {} {} rg /Helv {} Tf", n(r), n(g), n(b), n(size)).into_bytes())); + d.set(b"DA".to_vec(), free_text_da(style.color, style.border_color, size)); d.set(b"Q".to_vec(), Object::Int(0)); if let Some(f) = style.fill { d.set(b"C".to_vec(), rgb(f)); } border(&mut d); rich_text(&mut d); - // The text is laid out for the page as displayed, like a stamp's label. if !matches!(new.shape, Shape::Callout { .. }) { + // The text is laid out for the page as displayed, like a stamp's label. let turn = pdfcraft_model::pages(doc).get(new.page).map_or(0, |p| p.rotation(doc)); if matches!(turn, 90 | 180 | 270) { d.set(b"PCTextRotate".to_vec(), Object::Int(turn)); } + // An oval or a circle goes around the text box, its text wrapped as displayed: + // after `/PCTextRotate`, which swaps the box's sides on a quarter-turned page. + shape_text_box(&mut d, rect, style.border_shape, style.width); } } _ => {} @@ -421,7 +428,7 @@ pub fn add_annotation(doc: &mut Document, new: &NewAnnotation, meta: &Meta) -> R } fn validate_style(style: &Style) -> Result<(), AnnotError> { - if !finite(&style.color) || !style.opacity.is_finite() || !style.width.is_finite() { + if !finite(&style.color) || style.border_color.is_some_and(|c| !finite(&c)) || !style.opacity.is_finite() || !style.width.is_finite() { return Err(AnnotError::Invalid("invalid style".into())); } Ok(()) @@ -443,12 +450,6 @@ fn set_redaction_properties(dict: &mut Dict, style: &Style, quads: &[[f64; 8]], } } -fn set_non_opaque_style(dict: &mut Dict, opacity: f64) { - if opacity < 1.0 { - dict.set(b"CA".to_vec(), Object::Real(opacity)); - } -} - fn add_popup(doc: &mut Document, parent: ObjRef, rect: Option<[f64; 4]>, annots: &mut Vec) -> Result<(), AnnotError> { let Some(rect) = rect else { return Ok(()) }; let mut popup = Dict::new(); diff --git a/crates/annot/src/info.rs b/crates/annot/src/info.rs index 1a54dbc077..ba181d7504 100644 --- a/crates/annot/src/info.rs +++ b/crates/annot/src/info.rs @@ -2,7 +2,7 @@ use super::create::finite; use super::draw::set_appearance; use super::lookup::{annot_dict, annot_ref, annotation_flags, annots, drawn_upright, is_fill_sign, page_ref, page_refs}; use super::modify::{fillable, touch, unlocked}; -use super::types::{FLAG_LOCKED, LineEnding, Meta, NoteIcon, Rgb}; +use super::types::{BorderShape, FLAG_LOCKED, LineEnding, Meta, NoteIcon, Rgb}; use super::{AnnotError, Dict, Document, ObjRef, Object, PdfString, appearance}; // ── reading ───────────────────────────────────────────────────────────────────────────────── @@ -217,6 +217,15 @@ pub struct Props { pub fill: Option, /// Text boxes, typewriter text and callouts: the `/DA` font size in points. pub font_size: Option, + /// Text boxes, typewriter text and callouts: the border's own colour (`None`: the text's). + pub border_color: Option, + /// Text boxes and typewriter text: the border's shape (callouts have none to choose). + pub border_shape: Option, + /// How opaque the fill is drawn, for a comment with a fill control (`opacity` is then its + /// line's or border's). + pub fill_opacity: Option, + /// How opaque a text box's, typewriter text's or callout's text is drawn. + pub text_opacity: Option, } /// The current properties of the comment at `(page, index)`. @@ -239,7 +248,7 @@ pub fn props(doc: &Document, page: usize, index: usize) -> Option { author: text_value(doc, d, b"T").unwrap_or_default(), subject: text_value(doc, d, b"Subj").unwrap_or_default(), color, - opacity: d.get(b"CA").and_then(|o| o.as_f64()).unwrap_or(1.0), + opacity: appearance::part_opacity(d).line, width, icon: (subtype == "Text").then(|| d.name(b"Name").and_then(|n| NoteIcon::from_name(&String::from_utf8_lossy(n))).unwrap_or(NoteIcon::Note)), modified: text_value(doc, d, b"M"), @@ -248,6 +257,10 @@ pub fn props(doc: &Document, page: usize, index: usize) -> Option { fillable: fillable(&subtype), fill: fill_of(d), font_size: (subtype == "FreeText").then(|| appearance::parse_da(d).1), + border_color: (subtype == "FreeText").then(|| appearance::da_border(d)).flatten(), + border_shape: (subtype == "FreeText" && !d.contains(b"CL")).then(|| BorderShape::of(d)), + fill_opacity: fillable(&subtype).then(|| appearance::part_opacity(d).fill), + text_opacity: (subtype == "FreeText").then(|| appearance::part_opacity(d).text), subtype, endings: line_endings_of(d), }) diff --git a/crates/annot/src/lib.rs b/crates/annot/src/lib.rs index 4f24d04b08..52c0aad74f 100644 --- a/crates/annot/src/lib.rs +++ b/crates/annot/src/lib.rs @@ -41,13 +41,14 @@ pub use lookup::{ pub use model3d::{Model3d, Model3dKind, model_3d, model_3d_annotations}; pub(crate) use modify::n; pub use modify::{ - add_reply, add_text_replacement, deletable, delete_annotation, erase_ink, fillable, goes_with, lift_annotation, move_annotation, set_contents, - set_fill, set_font_size, set_locked, set_marked, set_points, set_rect, set_review_state, set_style, with_replies_and_popups, + add_reply, add_text_replacement, deletable, delete_annotation, erase_ink, fillable, goes_with, lift_annotation, move_annotation, + set_border_color, set_border_shape, set_contents, set_fill, set_font_size, set_locked, set_marked, set_part_opacity, set_points, set_rect, + set_review_state, set_style, with_replies_and_popups, }; pub use threed::{Activation as Activation3d, MAX_MODEL_BYTES, ModelFormat, NewModel3d, PosterPicture, add_3d_model, check_model}; pub use types::{ - AttachIcon, FillMark, LineEnding, Markup, Meta, NOTE_SIZE, NewAnnotation, NoteIcon, OverlayFont, OverlayLook, ReviewState, Rgb, Shape, - StampGroup, StampKind, Style, StyleChange, TextReplacement, rect_quad, + AttachIcon, BorderShape, FillMark, LineEnding, Markup, Meta, NOTE_SIZE, NewAnnotation, NoteIcon, OverlayFont, OverlayLook, ReviewState, Rgb, + Shape, StampGroup, StampKind, Style, StyleChange, TextReplacement, rect_quad, }; pub mod appearance; diff --git a/crates/annot/src/modify.rs b/crates/annot/src/modify.rs index a615b8e013..c7d87be090 100644 --- a/crates/annot/src/modify.rs +++ b/crates/annot/src/modify.rs @@ -5,8 +5,8 @@ use super::draw::{draw_appearance, redraw_or_restore, set_appearance}; use super::info::{line_endings_of, text_value}; use super::lookup::{annot_dict, annot_ref, annotation_flags, annots, page_ref, set_annots}; use super::types::{ - FLAG_HIDDEN, FLAG_LOCKED, FLAG_NO_ROTATE, FLAG_NO_ZOOM, FLAG_PRINT, LineEnding, Markup, Meta, NewAnnotation, ReviewState, Rgb, Shape, Style, - StyleChange, TextReplacement, + BorderShape, FLAG_HIDDEN, FLAG_LOCKED, FLAG_NO_ROTATE, FLAG_NO_ZOOM, FLAG_PRINT, LineEnding, Markup, Meta, NewAnnotation, ReviewState, Rgb, + Shape, Style, StyleChange, TextReplacement, }; use super::{AnnotError, Dict, Document, HashMap, HashSet, ObjRef, Object, PdfString, appearance}; @@ -159,10 +159,13 @@ pub fn with_replies_and_popups(doc: &Document, list: &[Object], doomed: impl Int } /// Change a comment's text. Text boxes are redrawn to show it, and their rectangle follows the -/// new text: the wrap width and top edge stay, the height fits the wrapped lines. +/// new text: the wrap width and top edge stay, the height fits the wrapped lines. A circle snug +/// around its text stays snug around the new text, centred where it was. pub fn set_contents(doc: &mut Document, page: usize, index: usize, text: &str, meta: &Meta) -> Result<(), AnnotError> { let (_, r) = annot_ref(doc, page, index)?; - let free_text = annot_dict(doc, r).name(b"Subtype") == Some(b"FreeText"); + let d = annot_dict(doc, r); + let free_text = d.name(b"Subtype") == Some(b"FreeText"); + let snug = free_text && is_snug(&d); doc.update_dict(r, |d| { d.set(b"Contents".to_vec(), PdfString::text(text)); // The rich-text version follows the new plain text (text boxes), or would contradict it. @@ -177,8 +180,16 @@ pub fn set_contents(doc: &mut Document, page: usize, index: usize, text: &str, m // The box grows and shrinks with the text instead of clipping it. A locked box keeps its // text editable (as in Acrobat), so the re-fit ignores the lock. New text is drawn even // where the standard fonts can't draw some of it (marked and reported, see - // `draw_appearance`). - match fitted_box(doc, r, text) { + // `draw_appearance`). A circle snug around its text stays snug around the new text; one + // made larger by hand keeps its size, only growing for more lines. + let fit = if snug { + snug_refit(doc, r) + } else { + let d = annot_dict(doc, r); + let circle = text_box_of(&d).filter(|_| BorderShape::of(&d) == BorderShape::Circle); + fitted_box(doc, r, text).map(|fit| circle.map_or(fit, |old| [fit[0], fit[1].min(old[1]), fit[2], fit[3]])) + }; + match fit { Some(rect) => apply_text_box(doc, r, rect, meta, true)?, None => draw_appearance(doc, r)?, } @@ -197,11 +208,12 @@ fn fitted_box(doc: &Document, r: ObjRef, text: &str) -> Option<[f64; 4]> { let rect = nums(b"Rect").filter(|v| v.len() == 4 && v.iter().all(|x| x.is_finite()))?; let rect = [rect[0], rect[1], rect[2], rect[3]]; // A callout re-fits its text box (`/Rect` inset by `/RD`); the leader line keeps its place. + // So does a text box inside an oval or a circle. let tb = if d.contains(b"CL") { let rd = nums(b"RD").filter(|v| v.len() == 4 && v.iter().all(|x| *x >= 0.0))?; [rect[0] + rd[0], rect[1] + rd[1], rect[2] - rd[2], rect[3] - rd[3]] } else { - rect + text_box_of(&d).unwrap_or(rect) }; let (x0, top) = (tb[0].min(tb[2]), tb[1].max(tb[3])); let w = tb[2] - tb[0]; @@ -388,9 +400,134 @@ pub fn set_rect(doc: &mut Document, page: usize, index: usize, rect: [f64; 4], m if !matches!(subtype.as_str(), "Square" | "Circle" | "FreeText") { return Err(AnnotError::Invalid(format!("{subtype} comments can't be resized"))); } + // An oval's or a circle's frame is resized: its text box follows inside. + let shape = if subtype == "FreeText" { BorderShape::of(&d) } else { BorderShape::Rectangle }; + let rect = match (shape, text_box_of(&d)) { + (BorderShape::Rectangle, _) | (_, None) => rect, + // A circle's text box keeps its proportions and reaches the circle with its longer sides; + // the circle then goes around it again, never closer than its text allows. + (BorderShape::Circle, Some(was)) => { + let (o, w) = (normalize(rect), normalize(was)); + let (cx, cy, r) = ((o[0] + o[2]) / 2.0, (o[1] + o[3]) / 2.0, (o[2] - o[0]).min(o[3] - o[1]) / 2.0); + let (wx, wy) = ((w[2] - w[0]) / 2.0, (w[3] - w[1]) / 2.0); + let k = r / wx.max(wy).max(1e-6); + let (ix, iy) = ((wx * k).max(0.5), (wy * k).max(0.5)); + [cx - ix, cy - iy, cx + ix, cy + iy] + } + (shape, Some(was)) => shape.inside(rect, border_width_of(&d), was), + }; apply_text_box(doc, r, rect, meta, false) } +/// A FreeText's text box: `/Rect` inset by `/RD` for a callout or a text box inside an oval or a +/// circle, else `/Rect`. `None` when they can't be read. +pub(crate) fn text_box_of(d: &Dict) -> Option<[f64; 4]> { + let nums = |key: &[u8]| -> Option> { d.get(key)?.as_array()?.iter().map(|o| o.as_f64()).collect() }; + let rect = normalize(four(&nums(b"Rect")?)?); + if !d.contains(b"CL") && BorderShape::of(d) == BorderShape::Rectangle { + return Some(rect); + } + let rd = appearance::inset(d)?; + let tb = [rect[0] + rd[0], rect[1] + rd[1], rect[2] - rd[2], rect[3] - rd[3]]; + (tb[2] - tb[0] >= 1.0 && tb[3] - tb[1] >= 1.0).then_some(tb) +} + +/// Give text box or typewriter text `d`, whose text box is `tb`, the border `shape` (`width` +/// wide): `/Rect` around it, `/RD` and `/PCBorderShape`, or for a rectangle `/Rect` the text +/// box itself again. +pub(crate) fn shape_text_box(d: &mut Dict, tb: [f64; 4], shape: BorderShape, width: f64) { + // A circle goes around the text as the box lays it out. + let text = (shape == BorderShape::Circle).then(|| text_extent(d, displayed_sides(d, tb).0 - 2.0 * (2.0 + width.max(0.0)))); + let outer = shape.around(tb, width, text); + d.set(b"Rect".to_vec(), num_array(&outer)); + if shape == BorderShape::Rectangle { + d.remove(b"PCBorderShape"); + d.remove(b"RD"); + } else { + d.set(b"PCBorderShape".to_vec(), Object::name(shape.name())); + // A circle touching the text box's sides would put them a rounding error outside it. + let tb = normalize(tb); + let rd = [tb[0] - outer[0], tb[1] - outer[1], outer[2] - tb[2], outer[3] - tb[3]].map(|x| x.max(0.0)); + d.set(b"RD".to_vec(), num_array(&rd)); + } +} + +/// The width of the widest line and the height of the lines of FreeText `d`'s text, as its +/// appearance lays the text out `wrap` wide. +fn text_extent(d: &Dict, wrap: f64) -> [f64; 2] { + let text = d.get(b"Contents").and_then(|o| o.as_string()).map(PdfString::to_text).unwrap_or_default(); + let (_, size) = appearance::parse_da(d); + let lines = appearance::wrap(&text, size, wrap.max(1.0)); + let widest = lines.iter().map(|l| appearance::text_width(l, size)).fold(0.0, f64::max); + [widest, lines.len().max(1) as f64 * size * 1.2] +} + +/// The width and height of FreeText `d`'s text box `tb` as displayed: swapped on a page turned by +/// a quarter, where its text is laid out upright. +fn displayed_sides(d: &Dict, tb: [f64; 4]) -> (f64, f64) { + let tb = normalize(tb); + let (w, h) = (tb[2] - tb[0], tb[3] - tb[1]); + if matches!(appearance::text_turn(d), 90 | 270) { (h, w) } else { (w, h) } +} + +/// FreeText `d`'s text box `tb`, with a border `width` wide, made as large as its text wrapped +/// `wrap` wide needs (its widest line and its lines, inside the padding a box sized to its text +/// has) and centred where it was: a circle goes around this, not around a box wider than its text. +fn snug_text_box(d: &Dict, tb: [f64; 4], width: f64, wrap: f64) -> [f64; 4] { + let tb = normalize(tb); + let pad = 2.0 + width.max(0.0); + let [w, h] = text_extent(d, wrap); + let (hx, hy) = (w / 2.0 + pad + 2.0, h / 2.0 + pad + 1.0); + let (hx, hy) = if matches!(appearance::text_turn(d), 90 | 270) { (hy, hx) } else { (hx, hy) }; + let (cx, cy) = ((tb[0] + tb[2]) / 2.0, (tb[1] + tb[3]) / 2.0); + [cx - hx, cy - hy, cx + hx, cy + hy] +} + +/// Whether FreeText `d` is a circle whose text box is snug around its text ([`snug_text_box`]): +/// it then follows its text as that changes, where one made larger by hand keeps its size. +fn is_snug(d: &Dict) -> bool { + let Some(tb) = text_box_of(d).filter(|_| BorderShape::of(d) == BorderShape::Circle) else { return false }; + let width = border_width_of(d); + let s = snug_text_box(d, tb, width, displayed_sides(d, tb).0 - 2.0 * (2.0 + width)); + let tb = normalize(tb); + ((s[2] - s[0]) - (tb[2] - tb[0])).abs() < 0.5 && ((s[3] - s[1]) - (tb[3] - tb[1])).abs() < 0.5 +} + +/// The text box of a circle snug around its text for the text and size it has now: its lines up to +/// 300 pt wide, centred where it was. +fn snug_refit(doc: &Document, r: ObjRef) -> Option<[f64; 4]> { + let d = annot_dict(doc, r); + let width = border_width_of(&d); + Some(snug_text_box(&d, text_box_of(&d)?, width, 300.0 - 2.0 * (2.0 + width))) +} + +/// Give a text box or typewriter text an oval, a circle or a rectangle for its border, and redraw +/// it. Its text box keeps its place; the oval or circle goes around it. For a circle the text box +/// first shrinks to its text, its lines wrapped as they are. +pub fn set_border_shape(doc: &mut Document, page: usize, index: usize, shape: BorderShape, meta: &Meta) -> Result<(), AnnotError> { + let (_, r) = annot_ref(doc, page, index)?; + unlocked(doc, r)?; + let d = annot_dict(doc, r); + if d.name(b"Subtype") != Some(b"FreeText") || d.contains(b"CL") { + return Err(AnnotError::Invalid("only text boxes and typewriter text have a border shape".into())); + } + let tb = text_box_of(&d).ok_or_else(|| AnnotError::Invalid("the text box can't be read".into()))?; + let tb = match shape { + BorderShape::Circle => { + let width = border_width_of(&d); + snug_text_box(&d, tb, width, displayed_sides(&d, tb).0 - 2.0 * (2.0 + width)) + } + _ => tb, + }; + refuse_foreign_text(doc, &d)?; + let before = d; + doc.update_dict(r, |d| { + shape_text_box(d, tb, shape, border_width_of(d)); + touch(d, meta); + })?; + redraw_or_restore(doc, r, before) +} + /// At most this many points reshape a comment (a drawn polygon has a handful). const MAX_POINTS: usize = 100_000; @@ -503,6 +640,8 @@ fn apply_text_box(doc: &mut Document, r: ObjRef, rect: [f64; 4], meta: &Meta, ne } None => (rect, None), }; + let (shape, width) = (BorderShape::of(&d), border_width_of(&d)); + let free_text = d.name(b"Subtype") == Some(b"FreeText"); doc.update_dict(r, |d| { d.set(b"Rect".to_vec(), num_array(&outer)); match &cl { @@ -510,6 +649,8 @@ fn apply_text_box(doc: &mut Document, r: ObjRef, rect: [f64; 4], meta: &Meta, ne d.set(b"CL".to_vec(), num_array(l)); d.set(b"RD".to_vec(), num_array(&[rect[0] - outer[0], rect[1] - outer[1], outer[2] - rect[2], outer[3] - rect[3]])); } + // An oval or a circle goes around the text box again. + None if free_text => shape_text_box(d, rect, shape, width), None => { d.remove(b"RD"); } @@ -528,6 +669,8 @@ fn apply_text_box(doc: &mut Document, r: ObjRef, rect: [f64; 4], meta: &Meta, ne } } +/// The border width as the appearance draws it: `/BS /W`, else the third number of `/Border` +/// (another app's), else 1. fn border_width_of(d: &Dict) -> f64 { appearance::border_width(d) } @@ -558,7 +701,8 @@ fn ink_rect_for_width(d: &Dict, old_w: f64, w: f64) -> Option<[f64; 4]> { Some([inner[0] - base[0] - new_half, inner[1] - base[1] - new_half, inner[2] + base[2] + new_half, inner[3] + base[3] + new_half]) } -/// Change a comment's colour, opacity, line width and/or line endings, and redraw it. +/// Change a comment's colour, opacity (of the whole comment), line width and/or line endings, and +/// redraw it. pub fn set_style(doc: &mut Document, page: usize, index: usize, change: StyleChange, meta: &Meta) -> Result<(), AnnotError> { let StyleChange { color, opacity, width, endings } = change; let (_, r) = annot_ref(doc, page, index)?; @@ -581,25 +725,34 @@ pub fn set_style(doc: &mut Document, page: usize, index: usize, change: StyleCha } refuse_foreign_text(doc, &d)?; let free_text = subtype == "FreeText"; + // Typewriter text has no box of its own: a border goes around its text, so the box grows + // (or shrinks) by the change on every side and the text keeps its place and its lines. + // So does a text box inside an oval or a circle, which goes around it again. + let shape = if free_text { BorderShape::of(&d) } else { BorderShape::Rectangle }; + let typewriter = free_text && (d.name(b"IT") == Some(b"FreeTextTypeWriter") || shape != BorderShape::Rectangle) && !d.contains(b"CL"); + let regrow = width.filter(|_| typewriter).and_then(|w| { + let by = w.max(0.0) - if d.contains(b"BS") || d.contains(b"Border") { border_width_of(&d) } else { 0.0 }; + let rect = grow(text_box_of(&d)?, by); + (by != 0.0 && finite(&rect) && rect[2] - rect[0] >= 1.0 && rect[3] - rect[1] >= 1.0).then_some((rect, w.max(0.0))) + }); let before = d; doc.update_dict(r, |d| { + if let Some((rect, w)) = regrow { + shape_text_box(d, rect, shape, w); + } if let Some(c) = color { if free_text { let (_, size) = appearance::parse_da(d); - let [r, g, b] = c.map(|x| x.clamp(0.0, 1.0)); - d.set(b"DA".to_vec(), PdfString::literal(format!("{} {} {} rg /Helv {} Tf", n(r), n(g), n(b), n(size)).into_bytes())); + d.set(b"DA".to_vec(), free_text_da(c, appearance::da_border(d), size)); rich_text(d); } else { d.set(b"C".to_vec(), rgb(c)); } } + // The whole comment: its fill and text drop opacities of their own. if let Some(o) = opacity { let o = o.clamp(0.0, 1.0); - if o < 1.0 { - d.set(b"CA".to_vec(), Object::Real(o)); - } else { - d.remove(b"CA"); - } + set_part_keys(d, appearance::PartOpacity { line: o, fill: o, text: o }); } if let Some(w) = width { let old_w = border_width_of(d); @@ -629,6 +782,37 @@ pub fn set_style(doc: &mut Document, page: usize, index: usize, change: StyleCha redraw_or_restore(doc, r, before) } +/// A FreeText's `/DA`: the text colour, the border's own colour when it has one (the stroking +/// colour, `RG`), Helvetica at `size`. +pub(crate) fn free_text_da(text: Rgb, border: Option, size: f64) -> PdfString { + let [r, g, b] = text.map(|x| x.clamp(0.0, 1.0)); + let stroke = border.map(|c| c.map(|x| x.clamp(0.0, 1.0))).map(|[r, g, b]| format!("{} {} {} RG ", n(r), n(g), n(b))).unwrap_or_default(); + PdfString::literal(format!("{} {} {} rg {stroke}/Helv {} Tf", n(r), n(g), n(b), n(size)).into_bytes()) +} + +/// Give a text box, typewriter text or callout a border colour of its own (`None`: the text's +/// again), and redraw it. +pub fn set_border_color(doc: &mut Document, page: usize, index: usize, color: Option, meta: &Meta) -> Result<(), AnnotError> { + let (_, r) = annot_ref(doc, page, index)?; + unlocked(doc, r)?; + let d = annot_dict(doc, r); + if d.name(b"Subtype") != Some(b"FreeText") { + return Err(AnnotError::Invalid("only text boxes, typewriter text and callouts have a border colour".into())); + } + if color.is_some_and(|c| !finite(&c)) { + return Err(AnnotError::Invalid("invalid colour".into())); + } + refuse_foreign_text(doc, &d)?; + let before = d; + doc.update_dict(r, |d| { + let (text, size) = appearance::parse_da(d); + d.set(b"DA".to_vec(), free_text_da(text, color, size)); + rich_text(d); + touch(d, meta); + })?; + redraw_or_restore(doc, r, before) +} + /// Change the font size of a text box, typewriter text or callout (`/DA` keeps its colour; the /// rich-text strings follow) and redraw it. The box grows to hold the wrapped text at the new /// size and never shrinks, so a box the user drew large stays large. Sizes are 1 to 400 pt. @@ -643,26 +827,27 @@ pub fn set_font_size(doc: &mut Document, page: usize, index: usize, size: f64, m return Err(AnnotError::Invalid("font size must be 1\u{2013}400 pt".into())); } refuse_foreign_text(doc, &d)?; + let snug = is_snug(&d); let before = d; doc.update_dict(r, |d| { let (col, _) = appearance::parse_da(d); - d.set(b"DA".to_vec(), PdfString::literal(format!("{} {} {} rg /Helv {} Tf", n(col[0]), n(col[1]), n(col[2]), n(size)).into_bytes())); + d.set(b"DA".to_vec(), free_text_da(col, appearance::da_border(d), size)); rich_text(d); touch(d, meta); })?; let text = text_value(doc, &annot_dict(doc, r), b"Contents").unwrap_or_default(); - let result = match fitted_box(doc, r, &text) { - Some(fit) => { + let result = match (snug, if snug { snug_refit(doc, r) } else { fitted_box(doc, r, &text) }) { + // A circle snug around its text stays snug around it at the new size. + (true, Some(fit)) => apply_text_box(doc, r, fit, meta, false), + (false, Some(fit)) => { let cur = annot_dict(doc, r); - let nums: Vec = - cur.get(b"Rect").and_then(|o| o.as_array()).map(|a| a.iter().filter_map(|x| x.as_f64()).collect()).unwrap_or_default(); // Keep the top and sides; only the bottom edge moves, and only downwards. - match four(&nums).map(normalize) { + match text_box_of(&cur) { Some(old) if !cur.contains(b"CL") => apply_text_box(doc, r, [fit[0], fit[1].min(old[1]), fit[2], fit[3]], meta, false), _ => apply_text_box(doc, r, fit, meta, false), } } - None => redraw_or_restore(doc, r, before.clone()), + (_, None) => redraw_or_restore(doc, r, before.clone()), }; if result.is_err() { doc.set(r, Object::Dict(before)); @@ -707,6 +892,63 @@ pub fn set_fill(doc: &mut Document, page: usize, index: usize, fill: Option redraw_or_restore(doc, r, before) } +/// Draw a rectangle's, oval's, polygon's or text box's fill, or a text box's text, at an +/// opacity of its own (0–1), its line or border keeping the comment's (`/CA`), and redraw it. +/// `None` leaves that part as it is drawn now. The fill goes in `/ca` (PDF 2.0's opacity for +/// what is filled), the text in `/PCTextOpacity`, each only where it differs from the one it +/// would otherwise follow. +pub fn set_part_opacity(doc: &mut Document, page: usize, index: usize, fill: Option, text: Option, meta: &Meta) -> Result<(), AnnotError> { + let (_, r) = annot_ref(doc, page, index)?; + unlocked(doc, r)?; + let d = annot_dict(doc, r); + let subtype = String::from_utf8_lossy(d.name(b"Subtype").unwrap_or_default()).into_owned(); + if fill.is_some() && !fillable(&subtype) { + return Err(AnnotError::Invalid("only rectangles, ovals, polygons and text boxes have a fill of their own".into())); + } + if text.is_some() && subtype != "FreeText" { + return Err(AnnotError::Invalid("only text boxes, typewriter text and callouts have text of their own".into())); + } + if fill.into_iter().chain(text).any(|o| !o.is_finite()) { + return Err(AnnotError::Invalid("invalid opacity".into())); + } + // Check before changing anything: a stale appearance would contradict the new opacity. + if appearance::build(&d).is_none() { + return Err(AnnotError::Unsupported(subtype)); + } + refuse_foreign_text(doc, &d)?; + let before = d; + doc.update_dict(r, |d| { + let mut parts = appearance::part_opacity(d); + if let Some(f) = fill { + parts.fill = f.clamp(0.0, 1.0); + } + if let Some(t) = text { + parts.text = t.clamp(0.0, 1.0); + } + set_part_keys(d, parts); + touch(d, meta); + })?; + redraw_or_restore(doc, r, before) +} + +/// Write a comment's parts' opacities (see [`appearance::PartOpacity`]): the line's as `/CA`, the +/// fill's as `/ca` and the text's as `/PCTextOpacity`, each only where it differs from the one +/// it would otherwise follow (the fill the line, the text the fill), so a comment drawn at one +/// opacity keeps just `/CA`. +pub(crate) fn set_part_keys(d: &mut Dict, parts: appearance::PartOpacity) { + let appearance::PartOpacity { line, fill, text } = parts; + let mut put = |key: &[u8], value: f64, unless: f64| { + if value == unless { + d.remove(key); + } else { + d.set(key.to_vec(), Object::Real(value)); + } + }; + put(b"CA", line, 1.0); + put(b"ca", fill, line); + put(b"PCTextOpacity", text, fill); +} + /// Grow a line or polyline's rectangle so a non-`None` ending is not clipped. Idempotent. fn ensure_ending_room(d: &mut Dict) { let subtype = d.name(b"Subtype").unwrap_or_default(); diff --git a/crates/annot/src/tests.rs b/crates/annot/src/tests.rs index 2ff781a3a5..ff7f8925f0 100644 --- a/crates/annot/src/tests.rs +++ b/crates/annot/src/tests.rs @@ -2,6 +2,7 @@ use std::sync::Arc; use pdfcraft_cos::{Document, ObjRef, Object, SaveOptions, write_incremental}; +use super::modify::text_box_of; use super::*; /// Two pages. Page 1 has an inline Square annotation in a direct /Annots array; page 2 has an @@ -40,7 +41,7 @@ fn new(page: usize, shape: Shape) -> NewAnnotation { NewAnnotation { page, shape, - style: Style { color: [0.0, 0.4, 1.0], opacity: 1.0, width: 2.0, fill: None }, + style: Style { color: [0.0, 0.4, 1.0], opacity: 1.0, width: 2.0, fill: None, ..Style::default() }, contents: "hello".into(), author: "Ada".into(), } @@ -356,6 +357,296 @@ fn restyle_and_resize_redraw_the_appearance() { assert!(matches!(set_rect(&mut doc, 0, l, [0.0, 0.0, 5.0, 5.0], &meta("")), Err(AnnotError::Invalid(_)))); } +/// Typed text or a text box takes an oval or a circle for its border: the text box keeps its +/// place and the shape goes around it (`/Rect` grows, `/RD` holds the text box, `/PCBorderShape` +/// the shape); back to a rectangle, it is the text box it was. A resized frame takes its text box +/// along, a thicker border leaves it where it is. +#[test] +fn text_boxes_take_an_oval_or_a_circle_around_their_text() { + let close = |a: &[f64], b: &[f64]| a.len() == b.len() && a.iter().zip(b).all(|(x, y)| (x - y).abs() < 0.01); + let nums = |d: &Dict, k: &[u8]| -> Vec { + d.get(k).and_then(|o| o.as_array()).map(|a| a.iter().filter_map(|x| x.as_f64()).collect()).unwrap_or_default() + }; + // Where the text starts: its first line's text matrix. + let text_at = |doc: &Document, d: &Dict| ap_content(doc, d).lines().find(|l| l.ends_with(" Tm") || l.contains(" Tm ")).map(str::to_owned); + let mut doc = fixture(); + let mut tw = new(0, Shape::Typewriter { rect: [100.0, 100.0, 200.0, 120.0], font_size: 10.0 }); + tw.style.width = 1.0; + let t = add_annotation(&mut doc, &tw, &meta("t")).unwrap(); + // In an oval or a circle the text is centred in its text box (left-aligned in a box): one + // line of "hello" at 10 pt in the 100 × 20 text box centred on (150, 110), 3 pt from its top. + let centred = format!("1 0 0 1 {} {} Tm (hello) Tj", n(150.0 - appearance::text_width("hello", 10.0) / 2.0), n(107.0)); + assert!(text_at(&doc, &list(&doc, 0)[t]).is_some_and(|l| l.starts_with("1 0 0 1 103 ")), "a box: left-aligned"); + set_border_shape(&mut doc, 0, t, BorderShape::Oval, &meta("")).unwrap(); + let doc2 = reopen(&doc); + let d = &list(&doc2, 0)[t]; + // Around the 100 × 20 text box, centred: √2 its size, two points more for the 1 pt border. + let (ax, ay) = (50.0 * std::f64::consts::SQRT_2 + 2.0, 10.0 * std::f64::consts::SQRT_2 + 2.0); + assert!(close(&rect(d), &[150.0 - ax, 110.0 - ay, 150.0 + ax, 110.0 + ay]), "{:?}", rect(d)); + assert!(close(&nums(d, b"RD"), &[ax - 50.0, ay - 10.0, ax - 50.0, ay - 10.0]), "{:?}", nums(d, b"RD")); + assert_eq!(d.name(b"PCBorderShape"), Some(&b"Oval"[..])); + let ap = ap_content(&doc2, d); + assert!(ap.contains(" c\n") && ap.contains("S\n") && !ap.contains("re S"), "an oval, not a box: {ap}"); + assert_eq!(text_at(&doc2, d).as_deref(), Some(centred.as_str()), "the text keeps its place"); + assert_eq!(props(&doc2, 0, t).unwrap().border_shape, Some(BorderShape::Oval)); + // A circle around the text: the text box shrinks to "hello" with its padding, centred where it + // was, and the circle touches its sides (the text a point clear of the border inside). + set_border_shape(&mut doc, 0, t, BorderShape::Circle, &meta("")).unwrap(); + let d = &list(&doc, 0)[t]; + let hw = appearance::text_width("hello", 10.0) / 2.0; + let r = (hw + 5.0).max(hw.hypot(6.0) + 2.0); + assert!(close(&rect(d), &[150.0 - r, 110.0 - r, 150.0 + r, 110.0 + r]), "{:?}", rect(d)); + assert!(close(&nums(d, b"RD"), &[r - hw - 5.0, r - 10.0, r - hw - 5.0, r - 10.0]), "{:?}", nums(d, b"RD")); + assert_eq!(text_at(&doc, d).as_deref(), Some(centred.as_str())); + // A thicker border: the typed text's box grows by the change on every side, so its text keeps + // its place inside the thicker line (as with a rectangle), and the circle goes around that. + set_style(&mut doc, 0, t, StyleChange::new(None, None, Some(3.0), None), &meta("")).unwrap(); + let d = &list(&doc, 0)[t]; + assert_eq!(text_at(&doc, d).as_deref(), Some(centred.as_str())); + let r3 = (hw + 7.0).max(hw.hypot(6.0) + 4.0); + assert!(close(&rect(d), &[150.0 - r3, 110.0 - r3, 150.0 + r3, 110.0 + r3]), "{:?}", rect(d)); + // Its frame resized: the text box follows inside, keeping its proportions, its longer sides + // reaching the circle. + set_rect(&mut doc, 0, t, [150.0 - 2.0 * r3, 110.0 - 2.0 * r3, 150.0 + 2.0 * r3, 110.0 + 2.0 * r3], &meta("")).unwrap(); + let d = &list(&doc, 0)[t]; + let rd = nums(d, b"RD"); + let tb = [rect(d)[0] + rd[0], rect(d)[1] + rd[1], rect(d)[2] - rd[2], rect(d)[3] - rd[3]]; + assert!(((tb[2] - tb[0]) / (tb[3] - tb[1]) - (hw + 7.0) / 12.0).abs() < 0.01, "the text box keeps its proportions: {tb:?}"); + assert!(close(&rect(d), &[150.0 - 2.0 * r3, 110.0 - 2.0 * r3, 150.0 + 2.0 * r3, 110.0 + 2.0 * r3]), "{:?}", rect(d)); + // A rectangle again: the text box it has, nothing around it. + set_border_shape(&mut doc, 0, t, BorderShape::Rectangle, &meta("")).unwrap(); + let d = &list(&doc, 0)[t]; + assert!(close(&rect(d), &tb), "{:?} vs {tb:?}", rect(d)); + assert!(!d.contains(b"RD") && !d.contains(b"PCBorderShape")); + assert!(ap_content(&doc, d).contains("re S")); + + // A filled text box made with an oval: the background takes the shape too. + let mut tb = new(0, Shape::TextBox { rect: [300.0, 500.0, 400.0, 540.0], font_size: 12.0 }); + (tb.style.fill, tb.style.width, tb.style.border_shape) = (Some([1.0, 1.0, 0.6]), 1.0, BorderShape::Oval); + let b = add_annotation(&mut doc, &tb, &meta("b")).unwrap(); + let d = &list(&doc, 0)[b]; + assert_eq!(d.name(b"PCBorderShape"), Some(&b"Oval"[..])); + let ap = ap_content(&doc, d); + assert!(ap.contains("1 1 0.6 rg") && ap.contains(" c\nh\nf\n") && !ap.contains(" re f"), "{ap}"); + // A callout's border stays a rectangle. + let c = add_annotation( + &mut doc, + &new( + 0, + Shape::Callout { + rect: [300.0, 300.0, 400.0, 340.0], + knee: [280.0, 320.0], + point: [250.0, 280.0], + ending: LineEnding::OpenArrow, + font_size: 10.0, + }, + ), + &meta("c"), + ) + .unwrap(); + assert!(matches!(set_border_shape(&mut doc, 0, c, BorderShape::Oval, &meta("")), Err(AnnotError::Invalid(_)))); + assert_eq!(props(&doc, 0, c).unwrap().border_shape, None); + assert_eq!(BorderShape::parse("CIRCLE"), Some(BorderShape::Circle)); +} + +/// A circle goes snug around short text, as a number on a drawing is circled: the text box is no +/// wider than its text needs and the circle touches its sides, where one through the box's corners +/// stood well clear. It follows the text and its size as they change; one made larger by hand +/// keeps its size. +#[test] +fn a_circle_goes_snug_around_its_text_and_follows_it() { + let close = |a: (f64, f64), b: (f64, f64)| (a.0 - b.0).abs() < 0.01 && (a.1 - b.1).abs() < 0.01; + let mut doc = fixture(); + // "3" at 10 pt with a 1 pt border, in the box Fill & Sign sizes to it: the digit with 2 pt of + // padding and 4 pt to spare across, a line and 6 pt down, the border around that. + let w3 = appearance::text_width("3", 10.0); + let mut typed = new(0, Shape::Typewriter { rect: [100.0, 680.0, 110.0 + w3, 700.0], font_size: 10.0 }); + (typed.contents, typed.style.width, typed.style.border_shape) = ("3".into(), 1.0, BorderShape::Circle); + let t = add_annotation(&mut doc, &typed, &meta("t")).unwrap(); + let frame = |doc: &Document| { + let r = rect(&list(doc, 0)[t]); + ((r[2] - r[0], r[3] - r[1]), ((r[0] + r[2]) / 2.0, (r[1] + r[3]) / 2.0)) + }; + let centre = (105.0 + w3 / 2.0, 690.0); + // As tall as the box, 20 pt across: through the corners it was 29. + assert!(close(frame(&doc).0, (20.0, 20.0)) && close(frame(&doc).1, centre), "{:?}", frame(&doc)); + // The text box Fill & Sign gives a box to type into, 40 pt wide: a circle goes snug around its + // text there too. + let mut wide = typed.clone(); + wide.shape = Shape::Typewriter { rect: [300.0, 680.0, 342.0, 700.0], font_size: 10.0 }; + wide.style.border_shape = BorderShape::Rectangle; + let b = add_annotation(&mut doc, &wide, &meta("b")).unwrap(); + set_border_shape(&mut doc, 0, b, BorderShape::Circle, &meta("")).unwrap(); + let r = rect(&list(&doc, 0)[b]); + assert!(close((r[2] - r[0], r[3] - r[1]), (20.0, 20.0)), "{r:?}"); + // More text: the circle grows with it, about the same centre; less, and it shrinks back. + set_contents(&mut doc, 0, t, "123", &meta("")).unwrap(); + let w = appearance::text_width("123", 10.0) / 2.0; + let d = 2.0 * (w + 5.0).max(10.0).max(w.hypot(6.0) + 2.0); + assert!(close(frame(&doc).0, (d, d)) && close(frame(&doc).1, centre), "{:?}", frame(&doc)); + set_contents(&mut doc, 0, t, "3", &meta("")).unwrap(); + assert!(close(frame(&doc).0, (20.0, 20.0)) && close(frame(&doc).1, centre), "{:?}", frame(&doc)); + // A larger font: a larger circle, still snug. + set_font_size(&mut doc, 0, t, 20.0, &meta("")).unwrap(); + let w = appearance::text_width("3", 20.0) / 2.0; + let d = 2.0 * (w + 5.0).max(16.0).max(w.hypot(12.0) + 2.0); + assert!(close(frame(&doc).0, (d, d)) && close(frame(&doc).1, centre), "{:?}", frame(&doc)); + set_font_size(&mut doc, 0, t, 10.0, &meta("")).unwrap(); + assert!(close(frame(&doc).0, (20.0, 20.0)), "{:?}", frame(&doc)); + // Made larger by hand, it keeps its size as its text changes. + set_rect(&mut doc, 0, t, [centre.0 - 20.0, centre.1 - 20.0, centre.0 + 20.0, centre.1 + 20.0], &meta("")).unwrap(); + assert!(close(frame(&doc).0, (40.0, 40.0)), "{:?}", frame(&doc)); + set_contents(&mut doc, 0, t, "4", &meta("")).unwrap(); + assert!(close(frame(&doc).0, (40.0, 40.0)) && close(frame(&doc).1, centre), "{:?}", frame(&doc)); +} + +/// A circle around a line wider than it is tall touches its text box's sides: `/RD` is 0 there, +/// not a rounding error below it, and a hair below 0 still reads. (A text box that couldn't be +/// read stopped following its text, and its text wrapped in a narrower one.) The circle keeps its +/// centre as its text changes. +#[test] +fn a_circle_touching_its_text_box_keeps_following_its_text() { + let mut doc = fixture(); + // Sized to its text: 2 pt of padding and half a point to spare across, a line down. + let (w, h) = (appearance::text_width("Testtext", 12.0) + 4.5, 12.0 * 1.11 + 4.0); + let mut b = new(0, Shape::TextBox { rect: [210.79, 700.0 - h, 210.79 + w, 700.0], font_size: 12.0 }); + (b.contents, b.style.width) = ("Testtext".into(), 0.0); + let t = add_annotation(&mut doc, &b, &meta("t")).unwrap(); + // Circle, then a 1 pt border, which the circle grows by. + set_border_shape(&mut doc, 0, t, BorderShape::Circle, &meta("")).unwrap(); + set_style(&mut doc, 0, t, StyleChange::new(None, None, Some(1.0), None), &meta("")).unwrap(); + let lines = |doc: &Document| ap_content(doc, &list(doc, 0)[t]).matches(" Tj").count(); + let frame = |doc: &Document| { + let r = rect(&list(doc, 0)[t]); + ((r[2] - r[0], r[3] - r[1]), ((r[0] + r[2]) / 2.0, (r[1] + r[3]) / 2.0)) + }; + let rd = |doc: &Document| -> Vec { list(doc, 0)[t].get(b"RD").unwrap().as_array().unwrap().iter().map(|o| o.as_f64().unwrap()).collect() }; + assert!(rd(&doc).iter().all(|x| *x >= 0.0) && rd(&doc)[0] < 0.01, "touching the sides: {:?}", rd(&doc)); + assert_eq!(lines(&doc), 1, "Testtext on one line"); + let (wide, centre) = frame(&doc); + set_contents(&mut doc, 0, t, "KRS", &meta("")).unwrap(); + let (small, at) = frame(&doc); + assert!(small.0 < wide.0 - 10.0 && (small.0 - small.1).abs() < 0.01, "a smaller circle: {small:?} from {wide:?}"); + assert!((at.0 - centre.0).abs() < 0.01 && (at.1 - centre.1).abs() < 0.01, "about its centre: {at:?} {centre:?}"); + assert_eq!(lines(&doc), 1); + // A hair below 0, as rounding left it: still read, so the circle follows its text again. + let (_, r) = annot_ref(&mut doc, 0, t).unwrap(); + let mut was = rd(&doc); + was[0] = -2.8e-14; + doc.update_dict(r, |d| d.set(b"RD".to_vec(), num_array(&was))).unwrap(); + assert!(text_box_of(&list(&doc, 0)[t]).is_some()); + set_contents(&mut doc, 0, t, "Testtext", &meta("")).unwrap(); + assert!((frame(&doc).0.0 - wide.0).abs() < 0.01 && lines(&doc) == 1, "{:?}", frame(&doc)); + assert!(rd(&doc).iter().all(|x| *x >= 0.0), "{:?}", rd(&doc)); +} + +/// On a page turned a quarter, typed text is laid out as the page is shown (`/PCTextRotate`), and a +/// circle made with it goes around the text as shown: as large as around the same text on an +/// upright page. (Made before the turn was set, its text wrapped at the box's displayed height and +/// the circle went around several lines.) +#[test] +fn a_circle_made_on_a_turned_page_is_sized_as_on_an_upright_one() { + let w = appearance::text_width("12345", 10.0); + let typed = |rect: [f64; 4]| { + let mut t = new(0, Shape::Typewriter { rect, font_size: 10.0 }); + (t.contents, t.style.width, t.style.border_shape) = ("12345".into(), 1.0, BorderShape::Circle); + t + }; + let size = |doc: &Document, i: usize| { + let r = rect(&list(doc, 0)[i]); + (r[2] - r[0], r[3] - r[1]) + }; + let mut upright = fixture(); + let u = add_annotation(&mut upright, &typed([100.0, 680.0, 110.0 + w, 700.0]), &meta("u")).unwrap(); + for turn in [90, 270] { + let mut doc = fixture(); + let page = page_refs(&doc).unwrap()[0]; + doc.update_dict(page, |d| d.set(b"Rotate".to_vec(), Object::Int(turn))).unwrap(); + // The same box as shown: its sides swapped in user space. + let t = add_annotation(&mut doc, &typed([100.0, 680.0, 120.0, 690.0 + w]), &meta("t")).unwrap(); + assert_eq!(list(&doc, 0)[t].get(b"PCTextRotate").and_then(Object::as_int), Some(turn)); + let (turned, straight) = (size(&doc, t), size(&upright, u)); + assert!((turned.0 - straight.0).abs() < 0.01 && (turned.1 - straight.1).abs() < 0.01, "{turn}°: {turned:?}, upright {straight:?}"); + } +} + +/// A rectangle's fill, and a text box's border, background and text, each drawn at an opacity of +/// its own: the line's in `/CA`, the fill's in `/ca` (PDF 2.0), the text's in `/PCTextOpacity`, and +/// in the appearance `/GS0` (strokes at the line's, fills at the fill's) and `/GS1` for the text. +#[test] +fn parts_are_drawn_at_opacities_of_their_own() { + let num = |d: &Dict, k: &[u8]| d.get(k).and_then(|o| o.as_f64()); + let gstate = |doc: &Document, d: &Dict, name: &[u8]| -> Option<(f64, f64)> { + let n = d.get(b"AP").map(|a| doc.resolve(a)).and_then(|a| a.as_dict().and_then(|a| a.reference(b"N")))?; + let obj = doc.get(n); + let Object::Stream(s) = &*obj else { return None }; + let res = s.dict.get(b"Resources").map(|r| doc.resolve(r))?; + let gs = res.as_dict()?.get(b"ExtGState").map(|g| doc.resolve(g))?; + let gs = gs.as_dict()?.get(name).map(|g| doc.resolve(g))?; + let gs = gs.as_dict()?; + Some((gs.get(b"CA")?.as_f64()?, gs.get(b"ca")?.as_f64()?)) + }; + let mut doc = fixture(); + let r = add_annotation(&mut doc, &new(0, Shape::Rectangle { rect: [10.0, 10.0, 110.0, 60.0] }), &meta("r")).unwrap(); + set_fill(&mut doc, 0, r, Some([1.0, 1.0, 0.0]), &meta("")).unwrap(); + set_part_opacity(&mut doc, 0, r, Some(0.3), None, &meta("")).unwrap(); + let doc2 = reopen(&doc); + let d = &list(&doc2, 0)[r]; + assert_eq!((num(d, b"CA"), num(d, b"ca")), (None, Some(0.3)), "an opaque line, a fill of its own"); + assert_eq!(gstate(&doc2, d, b"GS0"), Some((1.0, 0.3))); + let ap = ap_content(&doc2, d); + assert!(ap.starts_with("/GS0 gs") && ap.contains("\nB\n"), "filled and stroked in one go: {ap}"); + let p = props(&doc2, 0, r).unwrap(); + assert_eq!((p.opacity, p.fill_opacity, p.text_opacity), (1.0, Some(0.3), None)); + // The whole comment's opacity (StyleAnnotation, the quick bar): the fill goes along again. + set_style(&mut doc, 0, r, StyleChange::new(None, Some(0.6), None, None), &meta("")).unwrap(); + let d = &list(&doc, 0)[r]; + assert_eq!((num(d, b"CA"), num(d, b"ca")), (Some(0.6), None)); + assert_eq!(props(&doc, 0, r).unwrap().fill_opacity, Some(0.6)); + + // A text box with its border opaque, its background at 20 % and its text opaque, as made. + let mut tb = new(0, Shape::TextBox { rect: [200.0, 600.0, 400.0, 650.0], font_size: 12.0 }); + tb.style.fill = Some([1.0, 1.0, 0.6]); + tb.style.width = 1.0; + (tb.style.fill_opacity, tb.style.text_opacity) = (Some(0.2), Some(1.0)); + let t = add_annotation(&mut doc, &tb, &meta("t")).unwrap(); + let doc2 = reopen(&doc); + let d = &list(&doc2, 0)[t]; + assert_eq!((num(d, b"CA"), num(d, b"ca"), num(d, b"PCTextOpacity")), (None, Some(0.2), Some(1.0))); + assert_eq!((gstate(&doc2, d, b"GS0"), gstate(&doc2, d, b"GS1")), (Some((1.0, 0.2)), Some((1.0, 1.0)))); + let ap = ap_content(&doc2, d); + let (gs1, text) = (ap.find("/GS1 gs\n").expect("the text's own state, an operator of its own"), ap.find("BT").expect("text")); + assert!(ap.find(" re f").is_some_and(|fill| fill < gs1) && gs1 < text, "background at 20 %, then the text at its own: {ap}"); + // A new fill opacity leaves the text as it is drawn. + set_part_opacity(&mut doc, 0, t, Some(0.5), None, &meta("")).unwrap(); + let d = &list(&doc, 0)[t]; + assert_eq!((num(d, b"ca"), num(d, b"PCTextOpacity")), (Some(0.5), Some(1.0))); + let p = props(&doc, 0, t).unwrap(); + assert_eq!((p.opacity, p.fill_opacity, p.text_opacity), (1.0, Some(0.5), Some(1.0))); + // All at one opacity again: only /CA stays. + set_part_opacity(&mut doc, 0, t, Some(1.0), Some(1.0), &meta("")).unwrap(); + let d = &list(&doc, 0)[t]; + assert_eq!((num(d, b"CA"), num(d, b"ca"), num(d, b"PCTextOpacity")), (None, None, None)); + + // Only the parts a comment has, and finite values; nothing changes when refused. + let l = add_annotation( + &mut doc, + &new(0, Shape::Line { from: [0.0, 0.0], to: [10.0, 10.0], start: LineEnding::None, end: LineEnding::None }), + &meta("l"), + ) + .unwrap(); + assert!(matches!(set_part_opacity(&mut doc, 0, l, Some(0.5), None, &meta("")), Err(AnnotError::Invalid(_))), "a line has no fill"); + assert!(matches!(set_part_opacity(&mut doc, 0, r, None, Some(0.5), &meta("")), Err(AnnotError::Invalid(_))), "a rectangle has no text"); + let before = list(&doc, 0)[r].clone(); + assert!(matches!(set_part_opacity(&mut doc, 0, r, Some(f64::NAN), None, &meta("")), Err(AnnotError::Invalid(_)))); + assert_eq!(list(&doc, 0)[r], before); + // Another app's comment with /CA alone is drawn at it throughout, as before. + assert_eq!( + appearance::part_opacity(&Dict::from_iter([(b"CA".to_vec(), Object::Real(0.4))])), + appearance::PartOpacity { line: 0.4, fill: 0.4, text: 0.4 } + ); +} + #[test] fn shapes_can_be_filled_and_unfilled() { let mut doc = fixture(); @@ -591,6 +882,85 @@ fn fill_and_sign_items_are_drawn() { assert!(set_style(&mut doc, 1, 0, StyleChange::new(Some([0.0; 3]), None, None, None), &meta("")).is_err()); } +/// A border chosen for typewriter text goes around it in the text's colour. Changing it grows or +/// shrinks the box on every side, so the text stays where it was typed; a text box keeps its box. +#[test] +fn a_typewriter_border_goes_around_its_text_which_stays_put() { + let mut doc = fixture(); + let shape = Shape::Typewriter { rect: [100.0, 700.0, 200.0, 716.0], font_size: 11.0 }; + let style = Style { width: 1.0, ..Style::default_for(&shape) }; + let t = add_annotation(&mut doc, &NewAnnotation { page: 1, shape, style, contents: "Ada".into(), author: "Ada".into() }, &meta("x")).unwrap(); + // The text starts 2 pt inside the border: 100 + 1 + 2 across, 716 - 1 - 2 - 0.9 em down. + let at = "1 0 0 1 103 703.1 Tm"; + let d = &list(&doc, 1)[t]; + let ap = ap_content(&doc, d); + assert!(ap.contains("1 w\n") && ap.contains(" re S"), "a 1 pt border: {ap}"); + assert!(ap.contains(at), "{ap}"); + for (width, expected) in [(2.0, [99.0, 699.0, 201.0, 717.0]), (0.0, [101.0, 701.0, 199.0, 715.0])] { + set_style(&mut doc, 1, t, StyleChange::new(None, None, Some(width), None), &meta("")).unwrap(); + let d = &list(&doc, 1)[t]; + assert_eq!(rect(d), expected, "{width} pt border"); + let ap = ap_content(&doc, d); + assert!(ap.contains(at), "{width} pt: the text keeps its place: {ap}"); + assert_eq!(ap.contains(" re S"), width > 0.0, "{width} pt: {ap}"); + } + let shape = Shape::TextBox { rect: [100.0, 600.0, 200.0, 650.0], font_size: 11.0 }; + let b = add_annotation(&mut doc, &new(1, shape), &meta("b")).unwrap(); + set_style(&mut doc, 1, b, StyleChange::new(None, None, Some(3.0), None), &meta("")).unwrap(); + assert_eq!(rect(&list(&doc, 1)[b]), [100.0, 600.0, 200.0, 650.0], "a text box keeps the box it was drawn with"); + // Another app's typed text with its width in /Border (no /BS): 4 pt, so 2 pt shrinks the box + // by 2 on every side, as it is drawn. + let shape = Shape::Typewriter { rect: [100.0, 500.0, 200.0, 530.0], font_size: 11.0 }; + let o = add_annotation( + &mut doc, + &NewAnnotation { page: 1, style: Style::default_for(&shape), shape: shape.clone(), contents: "Bo".into(), author: "Ada".into() }, + &meta("o"), + ) + .unwrap(); + let (_, r) = annot_ref(&mut doc, 1, o).unwrap(); + doc.update_dict(r, |d| { + d.remove(b"BS"); + d.set(b"Border".to_vec(), num_array(&[0.0, 0.0, 4.0])); + }) + .unwrap(); + set_style(&mut doc, 1, o, StyleChange::new(None, None, Some(2.0), None), &meta("")).unwrap(); + assert_eq!(rect(&list(&doc, 1)[o]), [102.0, 502.0, 198.0, 528.0], "the imported 4 pt border is read from /Border"); + // A border colour that isn't a colour is refused before anything is written. + let mut bad = NewAnnotation { page: 1, style: Style::default_for(&shape), shape, contents: "x".into(), author: "Ada".into() }; + bad.style.border_color = Some([f64::NAN, 0.0, 0.0]); + let before = list(&doc, 1).len(); + assert!(matches!(add_annotation(&mut doc, &bad, &meta("n")), Err(AnnotError::Invalid(_)))); + assert_eq!(list(&doc, 1).len(), before); +} + +/// Text keeps its colour and the border gets its own: the stroking colour in `/DA`, which a new +/// text colour or font size keeps, and which `None` gives back to the text's. +#[test] +fn a_text_border_can_have_its_own_colour() { + let mut doc = fixture(); + let shape = Shape::Typewriter { rect: [100.0, 700.0, 200.0, 716.0], font_size: 11.0 }; + let style = Style { color: [0.0, 0.5, 0.0], width: 1.0, border_color: Some([1.0, 0.0, 0.0]), ..Style::default_for(&shape) }; + let t = add_annotation(&mut doc, &NewAnnotation { page: 1, shape, style, contents: "Ada".into(), author: "Ada".into() }, &meta("x")).unwrap(); + let da = |doc: &Document| text(&list(doc, 1)[t], b"DA"); + assert_eq!(da(&doc), "0 0.5 0 rg 1 0 0 RG /Helv 11 Tf"); + let ap = ap_content(&doc, &list(&doc, 1)[t]); + assert!(ap.contains("1 0 0 RG\n1 w"), "the border in red: {ap}"); + assert!(ap.contains("0 0.5 0 rg"), "the text in green: {ap}"); + assert_eq!(props(&doc, 1, t).unwrap().border_color, Some([1.0, 0.0, 0.0])); + set_style(&mut doc, 1, t, StyleChange::new(Some([0.0, 0.0, 1.0]), None, None, None), &meta("")).unwrap(); + assert_eq!(da(&doc), "0 0 1 rg 1 0 0 RG /Helv 11 Tf", "a new text colour keeps the border's"); + set_font_size(&mut doc, 1, t, 14.0, &meta("")).unwrap(); + assert_eq!(da(&doc), "0 0 1 rg 1 0 0 RG /Helv 14 Tf", "so does a new size"); + set_border_color(&mut doc, 1, t, Some([0.5, 0.5, 0.5]), &meta("")).unwrap(); + assert!(ap_content(&doc, &list(&doc, 1)[t]).contains("0.5 0.5 0.5 RG\n1 w")); + set_border_color(&mut doc, 1, t, None, &meta("")).unwrap(); + assert_eq!(da(&doc), "0 0 1 rg /Helv 14 Tf"); + assert!(ap_content(&doc, &list(&doc, 1)[t]).contains("0 0 1 RG\n1 w"), "the text's colour again"); + assert_eq!(props(&doc, 1, t).unwrap().border_color, None); + let m = add_annotation(&mut doc, &new(0, Shape::Rectangle { rect: [10.0, 10.0, 50.0, 50.0] }), &meta("m")).unwrap(); + assert!(set_border_color(&mut doc, 0, m, Some([1.0, 0.0, 0.0]), &meta("")).is_err(), "a rectangle's colour is its border"); +} + #[test] fn author_subject_and_note_icon_change() { let mut doc = fixture(); @@ -873,8 +1243,8 @@ fn cloud_ys(path: &str) -> Vec { fn replace_text_groups_a_strikeout_and_a_caret() { let mut doc = fixture(); let quads = [[100.0, 720.0, 200.0, 720.0, 100.0, 706.0, 200.0, 706.0]]; - let red = Style { color: [0.89, 0.13, 0.13], opacity: 1.0, width: 1.0, fill: None }; - let blue = Style { color: [0.0, 0.47, 0.84], opacity: 1.0, width: 1.0, fill: None }; + let red = Style { color: [0.89, 0.13, 0.13], opacity: 1.0, width: 1.0, fill: None, ..Style::default() }; + let blue = Style { color: [0.0, 0.47, 0.84], opacity: 1.0, width: 1.0, fill: None, ..Style::default() }; let i = add_text_replacement( &mut doc, TextReplacement { diff --git a/crates/annot/src/types.rs b/crates/annot/src/types.rs index 522995b9f9..f6bcc68a7e 100644 --- a/crates/annot/src/types.rs +++ b/crates/annot/src/types.rs @@ -1,5 +1,5 @@ use super::create::normalize; -use super::{ObjRef, appearance}; +use super::{Dict, ObjRef, appearance}; pub type Rgb = [f64; 3]; @@ -124,6 +124,28 @@ impl FillMark { let (w, h) = if matches!(rotation.rem_euclid(360), 90 | 270) { (h, w) } else { (w, h) }; [at[0] - w / 2.0, at[1] - h / 2.0, at[0] + w / 2.0, at[1] + h / 2.0] } + + /// The mark whose `/Name` this is. + pub fn from_name(n: &[u8]) -> Option { + [FillMark::Check, FillMark::Cross, FillMark::Dot, FillMark::Line].into_iter().find(|m| m.name().as_bytes() == n) + } + + /// The pen strokes the mark is drawn with in `rect` (user space): what its appearance strokes, + /// and what a copy of it shows while it is being placed. The dot is a filled circle (radius + /// 0.3 × the shorter side, centred) and has none. + pub fn strokes(self, rect: [f64; 4]) -> Vec> { + let [x0, y0, x1, y1] = rect; + let (w, h) = (x1 - x0, y1 - y0); + match self { + FillMark::Check => vec![vec![[x0 + w * 0.15, y0 + h * 0.5], [x0 + w * 0.4, y0 + h * 0.2], [x0 + w * 0.88, y0 + h * 0.85]]], + FillMark::Cross => vec![ + vec![[x0 + w * 0.18, y0 + h * 0.18], [x1 - w * 0.18, y1 - h * 0.18]], + vec![[x0 + w * 0.18, y1 - h * 0.18], [x1 - w * 0.18, y0 + h * 0.18]], + ], + FillMark::Dot => Vec::new(), + FillMark::Line => vec![vec![[x0, y0 + h / 2.0], [x1, y0 + h / 2.0]]], + } + } } /// The stamps of Acrobat's stamp palette (drawn in PdfCraft's own style). @@ -566,6 +588,16 @@ pub struct Style { pub width: f64, /// Interior fill for rectangles and ovals (`/IC`), background for text boxes. pub fill: Option, + /// A text box's, typewriter text's or callout's border colour where it differs from the + /// text's (`None`: the text colour), the stroking colour in its `/DA`. + pub border_color: Option, + /// A text box's or typewriter text's border shape (a callout's is always a rectangle). + pub border_shape: BorderShape, + /// The fill's own opacity, 0–1 (`/ca`), where it differs from `opacity` (which is then the + /// line's or border's); `None`: as `opacity`. + pub fill_opacity: Option, + /// A text box's text's own opacity, 0–1 (`/PCTextOpacity`); `None`: as the fill's. + pub text_opacity: Option, } /// The style properties changed by one annotation edit. `None` leaves a property unchanged. @@ -597,7 +629,102 @@ pub struct TextReplacement<'a> { impl Default for Style { fn default() -> Self { - Self { color: [1.0, 0.82, 0.0], opacity: 1.0, width: 1.0, fill: None } + Self { + color: [1.0, 0.82, 0.0], + opacity: 1.0, + width: 1.0, + fill: None, + fill_opacity: None, + text_opacity: None, + border_color: None, + border_shape: BorderShape::Rectangle, + } + } +} + +/// The shape of a text box's or typewriter text's border (PdfCraft's `/PCBorderShape`, absent for +/// a rectangle). An oval or a circle goes around the text box, which keeps its place: `/Rect` +/// grows to hold it, centred on the text box, and `/RD` says where the text box is inside +/// (§12.5.6.6), as for a callout. Other apps that redraw the comment draw a rectangle. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum BorderShape { + #[default] + Rectangle, + Oval, + Circle, +} + +impl BorderShape { + pub const ALL: [BorderShape; 3] = [BorderShape::Rectangle, BorderShape::Oval, BorderShape::Circle]; + + pub fn name(self) -> &'static str { + match self { + BorderShape::Rectangle => "Rectangle", + BorderShape::Oval => "Oval", + BorderShape::Circle => "Circle", + } + } + + /// `rectangle`, `oval` or `circle`, in any case. + pub fn parse(s: &str) -> Option { + Self::ALL.into_iter().find(|b| b.name().eq_ignore_ascii_case(s)) + } + + /// The border shape of FreeText `d`: always a rectangle for a callout. + pub fn of(d: &Dict) -> Self { + if d.contains(b"CL") { + return BorderShape::Rectangle; + } + match d.name(b"PCBorderShape") { + Some(b"Oval") => BorderShape::Oval, + Some(b"Circle") => BorderShape::Circle, + _ => BorderShape::Rectangle, + } + } + + /// The rectangle this shape, with a border `width` wide, takes around text box `tb`, centred on + /// it: an oval through the text box's corners (`√2` its size), a point clear of the border; a + /// circle around the text's lines (`text`: the widest line's width and the lines' height, when + /// known), a point clear of the border and touching the text box's longer sides at least + /// (its corners, padding only, may lie outside), else through the box's corners; the text box + /// itself for a rectangle. + pub fn around(self, tb: [f64; 4], width: f64, text: Option<[f64; 2]>) -> [f64; 4] { + let tb = normalize(tb); + let (cx, cy, hx, hy) = ((tb[0] + tb[2]) / 2.0, (tb[1] + tb[3]) / 2.0, (tb[2] - tb[0]) / 2.0, (tb[3] - tb[1]) / 2.0); + let gap = width.max(0.0) + 1.0; + let (ax, ay) = match self { + BorderShape::Rectangle => return tb, + BorderShape::Oval => (hx * std::f64::consts::SQRT_2 + gap, hy * std::f64::consts::SQRT_2 + gap), + BorderShape::Circle => { + let r = match text { + Some([w, h]) => ((w / 2.0).hypot(h / 2.0) + gap).max(hx).max(hy), + None => hx.hypot(hy) + gap, + }; + (r, r) + } + }; + [cx - ax, cy - ay, cx + ax, cy + ay] + } + + /// The text box inside `outer` for this shape when none is recorded: the inverse of + /// [`Self::around`] for an oval, a box through a circle's corners for a circle, keeping the + /// proportions of `was` (the one it had). + pub(crate) fn inside(self, outer: [f64; 4], width: f64, was: [f64; 4]) -> [f64; 4] { + let o = normalize(outer); + let (cx, cy, hx, hy) = ((o[0] + o[2]) / 2.0, (o[1] + o[3]) / 2.0, (o[2] - o[0]) / 2.0, (o[3] - o[1]) / 2.0); + let gap = width.max(0.0) + 1.0; + let (ix, iy) = match self { + BorderShape::Rectangle => return o, + BorderShape::Oval => ((hx - gap) / std::f64::consts::SQRT_2, (hy - gap) / std::f64::consts::SQRT_2), + BorderShape::Circle => { + let w = normalize(was); + let (wx, wy) = ((w[2] - w[0]) / 2.0, (w[3] - w[1]) / 2.0); + let k = (hx.min(hy) - gap) / wx.hypot(wy).max(1e-6); + (wx * k, wy * k) + } + }; + let (ix, iy) = (ix.max(0.5), iy.max(0.5)); + [cx - ix, cy - iy, cx + ix, cy + iy] } } @@ -615,7 +742,7 @@ impl Style { } Shape::Callout { .. } => ([0.0, 0.0, 0.0], 1.0), Shape::Caret { .. } | Shape::Attachment { .. } => ([0.0, 0.47, 0.84], 1.0), - Shape::FreehandHighlight { .. } => return Self { color: [1.0, 0.94, 0.0], opacity: 0.35, width: 14.0, fill: None }, + Shape::FreehandHighlight { .. } => return Self { color: [1.0, 0.94, 0.0], opacity: 0.35, width: 14.0, ..Self::default() }, Shape::Ink { .. } => ([0.0, 0.4, 0.87], 2.0), Shape::TextBox { .. } | Shape::Typewriter { .. } => ([0.0, 0.0, 0.0], 0.0), Shape::Mark { .. } => ([0.0, 0.0, 0.0], 1.5), @@ -624,9 +751,9 @@ impl Style { Shape::CustomStamp { .. } => ([0.0, 0.0, 0.0], 0.0), Shape::TypedSignature { .. } => ([0.0, 0.0, 0.0], 0.0), // Red outline while marked; a black box once applied. - Shape::Redact { .. } => return Self { color: [0.89, 0.13, 0.13], opacity: 1.0, width: 1.0, fill: Some([0.0, 0.0, 0.0]) }, + Shape::Redact { .. } => return Self { color: [0.89, 0.13, 0.13], fill: Some([0.0, 0.0, 0.0]), ..Self::default() }, }; - Self { color, opacity: 1.0, width, fill: None } + Self { color, width, ..Self::default() } } } diff --git a/crates/automation/README.md b/crates/automation/README.md index d218fbcda6..db5b988394 100644 --- a/crates/automation/README.md +++ b/crates/automation/README.md @@ -281,3 +281,26 @@ navigation-history tool; use the opt-in UI control channel to navigate the displ (`#RRGGBB`, default black) for `text` and `date`. The colour is saved in the FreeText appearance and survives reopening. Other mark/signature types reject `color`; their appearance controls are separate. + +## Reviewing OCR headlessly + +`ocr_words {doc, retain_review: true}` reads words without editing the document and returns +`review`, plus pages and word boxes/confidences. Page and word positions are 1-based. +`region` can restrict recognition to one named page, using displayed-page points. Without +`retain_review`, word inspection remains stateless. + +Apply reviewed text with `ocr_review_apply {doc, review, corrections: [{page: 1, word: 1, +text: "Corrected"}]}`. Omitted words keep their text; empty text removes a word. Geometry +comes from the retained recognition, never caller input. The captured document guard rejects +stale/foreign results. Successful application consumes the handle and is one undoable step. +Use `output_mode: "editable", out: "reviewed.pdf"` to write a separate editable document, +or `discard: true` to release the result without applying it. Failed validation preserves the +review for correction or discard. A new retained recognition replaces that document's prior +handle; closing the document releases it. At most eight documents may retain reviews, with +65,536-word/4-MiB input bounds and a 65,536-page cap. + +`ocr_dictionary {path: "ocr-dictionary-en.txt", add: ["Quartz"], remove: ["old"]}` atomically +updates the same one-word-per-UTF-8-line format OCR Verify uses. Omit add/remove to read it. +The explicit path honors `--root`, including symlink confinement; choose the appropriate +per-language file used by the UI. Entries are case-insensitive and duplicate-free. Invalid +or oversized inputs fail before writing (65,536 words, 4 MiB, at most 1,024 bytes per word). diff --git a/crates/automation/src/a11y/ocr.rs b/crates/automation/src/a11y/ocr.rs index 82e521ddd5..2846aa44a6 100644 --- a/crates/automation/src/a11y/ocr.rs +++ b/crates/automation/src/a11y/ocr.rs @@ -1,98 +1,534 @@ use super::{Args, Automation, Result, ToolError, Value, child, failed, json, write_atomic}; impl Automation { - /// Recognition settings from the arguments: `dpi` (clamped to 72–600), `language` (refused - /// unless the models read it) and `skip_text_pages`, each left at its default when absent. + /// The settings every OCR tool shares: dpi, language, the engine/strategy choice, the four + /// preprocessing flags, the skip flags and the output mode — each named exactly as its tool + /// schema says. An unknown engine, strategy or mode is an honest error, never a silent + /// fallback: a tool run must not quietly do something other than what it was asked. pub(crate) fn ocr_settings(&self, a: &Args) -> Result { + use pdfcraft_engine::ocr::{EngineChoice, MergeStrategy, OutputMode}; let mut settings = pdfcraft_engine::ocr::OcrSettings::default(); if let Some(d) = a.opt_num("dpi")? { settings.dpi = d.clamp(72.0, 600.0) as f32; } if let Some(l) = a.opt_str("language")? { if !pdfcraft_engine::ocr::LANGUAGES.iter().any(|x| x.0 == l) { - return Err(ToolError::InvalidArgs(format!("unsupported language {l:?}"))); + return Err(ToolError::InvalidArgs(format!( + "unsupported language {l:?} (supported: {})", + pdfcraft_engine::ocr::LANGUAGES.iter().map(|(c, _)| *c).collect::>().join(", ") + ))); } settings.language = l.into(); } - if let Some(s) = a.opt_bool("skip_text_pages")? { - settings.skip_text_pages = s; + if let Some(e) = a.opt_str("engine")? { + settings.engine = match e.trim().to_ascii_lowercase().as_str() { + "ocrs" => EngineChoice::Ocrs, + "tesseract" => EngineChoice::Tesseract, + "auto" | "automatic" | "ensemble" => EngineChoice::Auto, + other => return Err(ToolError::InvalidArgs(format!("unsupported engine {other:?} (ocrs, tesseract or auto)"))), + }; + } + settings.strategy = match a.opt_str("strategy")? { + Some(s) => match s.trim().to_ascii_lowercase().as_str() { + "primary" | "primary-only" | "primary_only" => MergeStrategy::PrimaryOnly, + "confidence" | "confidence-weighted" | "confidence_weighted" => MergeStrategy::ConfidenceWeighted, + "rover" | "rover-vote" | "rover_vote" | "vote" => MergeStrategy::RoverVote, + other => return Err(ToolError::InvalidArgs(format!("unsupported strategy {other:?} (primary, confidence or rover)"))), + }, + // Unset: the engine choice decides (auto brings in the second engine when the + // first reading is weak; a named engine reads alone). + None => settings.engine.default_strategy(), + }; + if let Some(m) = a.opt_str("output_mode")? { + settings.output_mode = match m.trim().to_ascii_lowercase().as_str() { + "searchable" | "searchable-image" | "searchable_image" => OutputMode::Searchable, + "editable" | "editable-text" | "editable_text" => OutputMode::EditableText, + other => return Err(ToolError::InvalidArgs(format!("unsupported output mode {other:?} (searchable or editable)"))), + }; + } + for (key, flag) in [ + ("auto_rotate", &mut settings.auto_rotate), + ("deskew", &mut settings.deskew), + ("denoise", &mut settings.denoise), + ("binarize", &mut settings.binarize), + ] { + if let Some(on) = a.opt_bool(key)? { + *flag = on; + } + } + for (key, flag) in [ + ("skip_text_pages", &mut settings.skip_text_pages), + ("skip_text_files", &mut settings.skip_text_files), + ("force_ocr", &mut settings.force_ocr), + ] { + if let Some(on) = a.opt_bool(key)? { + *flag = on; + } } Ok(settings) } - /// Recognizes text in each of `paths` and writes the result under the same file name in - /// `folder`, reporting per file its output, word count and skipped pages, or its error. A - /// path outside the root refuses the whole call before any work starts. + /// The optional `region` argument ([x0, y0, x1, y1] in points from the top-left of the + /// displayed page) as the job's pixel crop, at the resolution that page is really read at. + /// A region reads exactly one page. + fn ocr_region( + &self, + a: &Args, + id: pdfcraft_engine::DocId, + page: usize, + settings: &pdfcraft_engine::ocr::OcrSettings, + ) -> Result> { + const BAD: &str = "region must be [x0, y0, x1, y1] in points"; + let Some(v) = a.get("region") else { return Ok(None) }; + let arr = v.as_array().ok_or_else(|| ToolError::InvalidArgs(BAD.into()))?; + if arr.len() != 4 { + return Err(ToolError::InvalidArgs(BAD.into())); + } + let mut pts = [0.0f64; 4]; + for (i, x) in arr.iter().enumerate() { + pts[i] = x.as_f64().filter(|f| f.is_finite()).ok_or_else(|| ToolError::InvalidArgs(BAD.into()))?; + } + let scale = f64::from( + self.session.ocr_job(id, &[page], settings.clone()).ok_or_else(|| failed("the document could not be read"))?.render_scale(page), + ); + let px: Vec = pts.iter().map(|p| scale * p).map(|p| if p.is_finite() { p } else { 0.0 }).map(|p| p as f32).collect(); + Ok(Some([px[0], px[1], px[2], px[3]])) + } + + /// The per-page result entries the OCR tools return: recognised text or why the page was + /// passed over. The text itself is only echoed when the document allows copying; the + /// counts and metadata always are. + fn ocr_pages_json(found: &[pdfcraft_engine::ocr::OcrPage], include_text: bool) -> Vec { + found + .iter() + .map(|p| match &p.skipped { + Some(why) => json!({ "page": p.page + 1, "skipped": why }), + None => { + let mut page = json!({ "page": p.page + 1, "words": p.words.len(), "already_on_page": p.already_on_page }); + // The editable output's substitution warnings (characters no font could + // show) are part of the result: reported per page, never dropped. + if !p.notes.is_empty() { + page["notes"] = json!(p.notes); + } + if include_text { + page["text"] = json!(p.text()); + } + page + } + }) + .collect() + } + pub(crate) fn ocr_recognize_files(&mut self, a: &Args) -> Result { let settings = self.ocr_settings(a)?; let folder = self.resolve(a.str("folder")?, true)?; - // A path that leaves the root refuses the whole call before any work starts, like the - // other tools (the write check passes missing files, which stay per-file errors below). + // A path that leaves the read root refuses the whole call before any work starts; + // a file that is merely missing stays a per-file error below. let paths = a.strs("paths")?; for p in &paths { self.resolve_for(p, crate::file_access::Access::Read, true)?; } - // Two inputs that would write the same output file overwrite each other while both report - // success, so the whole batch is refused here: before the folder is created, anything is - // read, or the OCR engines load. + // Two inputs of one file name (from different folders) would write the same output: + // the second would replace the first while both report success. The whole batch is + // refused up front — before the folder is created, anything is read or the engines + // load — naming the file, the way the default filesystem compares names. let targets: Vec = paths.iter().map(|p| child(&folder, &input_file_name(p))).collect(); let shared = shared_file_names(&targets); if !shared.is_empty() { return Err(ToolError::InvalidArgs(format!( - "more than one input would write to the same output file, so each would replace the one before it. Colliding file names: {}. Give each input a different file name, or run them in separate batches with different folders.", + "several paths share a file name, so their outputs in folder would overwrite each other (rename or run them separately): {}", shared.join(", ") ))); } std::fs::create_dir_all(&folder).map_err(|e| failed(e.to_string()))?; - let ocr = pdfcraft_engine::ocr::engine().map_err(failed)?; + let names: Vec = paths.iter().map(|p| input_file_name(p)).collect(); + // Collision pre-flight: a searchable copy never silently overwrites. Every target is + // checked before the first page is read; a collision aborts the whole batch with the + // names in the error. + let mut collisions = std::collections::BTreeSet::new(); + for name in names { + if child(&folder, &name).exists() { + collisions.insert(name); + } + } + if !collisions.is_empty() { + let mut list: Vec = collisions.iter().take(5).cloned().collect(); + if collisions.len() > list.len() { + list.push(format!("and {} more", collisions.len() - list.len())); + } + return Err(failed(format!( + "the output folder already holds {} (delete or move them, or choose another folder): {}", + if collisions.len() == 1 { "a file of that name" } else { "files of those names" }, + list.join(", ") + ))); + } + // The engines are built (and named if they cannot be) before the first file is read. + let recognizers = pdfcraft_engine::ocr::recognizers(&settings).map_err(failed)?; let mut out = Vec::new(); + let (mut ok, mut skipped_files, mut words) = (0usize, 0usize, 0usize); for p in paths { let name = input_file_name(p); let result = self.resolve(p, false).map_err(|e| e.to_string()).and_then(|src| crate::read_input_bytes(&src).map_err(|e| e.to_string())).and_then( - |bytes| pdfcraft_engine::ocr::recognize_file(&name, std::sync::Arc::new(bytes), None, settings.clone(), &ocr, |_, _| true), + |bytes| { + pdfcraft_engine::ocr::recognize_file(&name, std::sync::Arc::new(bytes), None, settings.clone(), &recognizers, |_, _| true) + }, ); - out.push(match result { + match result { Ok(r) => { + let skipped_pages: Vec = r.pages.iter().filter(|p| p.skipped.is_some()).map(|p| p.page + 1).collect(); + if r.skipped() { + // A file passed over by the skip-files option is its own bucket: its + // original is left alone and nothing is written. + skipped_files += 1; + out.push(json!({ "path": p, "skipped": r.file_skipped, "skipped_pages": skipped_pages })); + continue; + } let target = child(&folder, &name); write_atomic(&target, &r.bytes)?; - let skipped: Vec = r.pages.iter().filter(|p| p.skipped.is_some()).map(|p| p.page + 1).collect(); - json!({ "path": p, "output": target.to_string_lossy(), "words": r.words(), "skipped_pages": skipped }) + ok += 1; + words += r.words(); + let mut entry = json!({ "path": p, "output": target.to_string_lossy(), "words": r.words(), "skipped_pages": skipped_pages }); + // The batch's low-confidence note: at or under the settings' threshold (60 + // by default), on 1-based sorted pages. + let threshold = settings.low_confidence_threshold; + if let Some((count, pages)) = pdfcraft_engine::ocr::low_confidence_pages(&r.pages, threshold) { + entry["low_confidence"] = json!({ "count": count, "pages": pages, "threshold": threshold }); + } + out.push(entry); } - Err(e) => json!({ "path": p, "error": e }), - }); + Err(e) => out.push(json!({ "path": p, "error": e })), + } } - Ok(json!({ "files": out })) + Ok(json!({ "files": out, "recognized": ok, "words": words, "skipped_files": skipped_files })) } - /// Recognizes text on the open document's `pages` (every page when absent) and adds it, - /// reporting the total word count and, per page, why it was skipped or what it found. pub(crate) fn ocr_recognize(&mut self, a: &Args) -> Result { - let settings = self.ocr_settings(a)?; + use pdfcraft_engine::ocr::OutputMode; + let mut settings = self.ocr_settings(a)?; let pages = if a.opt_ints("pages")?.is_some() { self.pages(a, "pages")? } else { Vec::new() }; - let doc = self.doc(a)?; // Recognizing needs only permission to change the document; the words it found are // returned only when copying is allowed too. - let (id, copy) = (doc.id, doc.allows_copying()); - let found = self.session.recognize_text(id, &pages, settings).map_err(failed)?; + let (id, copy) = { + let doc = self.doc(a)?; + (doc.id, doc.allows_copying()) + }; + // The optional region reads exactly one page. + if a.get("region").is_some() { + if pages.len() != 1 { + return Err(ToolError::InvalidArgs("region reads one page: name it in pages".into())); + } + settings.region = self.ocr_region(a, id, pages[0], &settings)?; + } + // The editable output's destination is checked before anything runs: a NEW file, never + // the open source and never an existing file replaced silently. + let out = match settings.output_mode { + OutputMode::Searchable => { + // `out` belongs to the editable output; a searchable run writes into the open + // document, so an `out` here would be silently ignored (and never checked + // against the root). + if a.get("out").is_some() { + return Err(ToolError::InvalidArgs("out is only used with output_mode editable; remove it, or choose editable".into())); + } + None + } + OutputMode::EditableText => { + // The editable output writes the recognized text out of the document: a + // document that forbids copying refuses here, before anything runs. + self.doc_to_copy(a)?; + // A write: the file does not exist yet, and write_atomic makes its folder. + let out = self.resolve(a.str("out")?, true)?; + if let Some(source) = self.session.get(id).and_then(|d| d.path.clone()) + && let (Ok(a), Ok(b)) = (std::fs::canonicalize(&out), std::fs::canonicalize(&source)) + && a == b + { + return Err(failed("out is the source document; the editable output is a new file, so choose another path")); + } + if out.exists() { + return Err(failed(format!( + "out already exists ({}); the editable output is a new file, so choose a path that does not exist yet", + out.to_string_lossy() + ))); + } + Some(out) + } + }; + // Honest up front: the engines are built (and named if they cannot be) before anything + // is read or written. + let recognizers = pdfcraft_engine::ocr::recognizers(&settings).map_err(failed)?; + match out { + None => { + let found = self.session.recognize_text(id, &pages, settings).map_err(failed)?; + let words = found.iter().map(|p| p.words.len()).sum::(); + Ok(json!({ "words": words, "pages": Self::ocr_pages_json(&found, copy) })) + } + Some(out) => { + let job = self.session.ocr_job(id, &pages, settings).ok_or_else(|| failed("the document could not be read"))?; + let found = job.run(&recognizers, |_, _| true); + let bytes = self.session.editable_ocr_bytes(id, &found).map_err(failed)?; + // recognition can take minutes: a file created meanwhile is refused, not replaced + if let Some(folder) = out.parent() { + std::fs::create_dir_all(folder).map_err(failed)?; + } + crate::bates::publish_new(&out, &bytes)?; + Ok(json!({ + "out": out.to_string_lossy(), + "words": found.iter().map(|p| p.words.len()).sum::(), + "pages": Self::ocr_pages_json(&found, copy), + })) + } + } + } + + /// The words of a recognition, for reviewing without the GUI: text, box (points from the + /// top-left of the displayed page), confidence, band, and which words are suspects. + /// Changes nothing; needs the engines (ocr_status). + pub(crate) fn ocr_words(&mut self, a: &Args) -> Result { + let mut settings = self.ocr_settings(a)?; + let pages = if a.opt_ints("pages")?.is_some() { self.pages(a, "pages")? } else { Vec::new() }; + // The word list is the document's text, word by word: refused when the document + // forbids copying it out. + let id = self.doc_to_copy(a)?.id; + if a.get("region").is_some() { + if pages.len() != 1 { + return Err(ToolError::InvalidArgs("region reads one page: name it in pages".into())); + } + settings.region = self.ocr_region(a, id, pages[0], &settings)?; + } + let retain = a.opt_bool("retain_review")?.unwrap_or(false); + if retain && !self.ocr_reviews.contains_key(&id) && self.ocr_reviews.len() >= 8 { + return Err(failed("at most 8 OCR reviews may be retained; discard one first")); + } + let recognizers = pdfcraft_engine::ocr::recognizers(&settings).map_err(failed)?; + let job = self.session.ocr_job(id, &pages, settings.clone()).ok_or_else(|| failed("the document could not be read"))?; + let infos: std::collections::HashMap = + self.session.get(id).map(|d| d.info.pages.clone()).unwrap_or_default().into_iter().enumerate().collect(); + let guard = job.guard.clone(); + let found = job.run(&recognizers, |_, _| true); + if found.len() > 65536 { + return Err(failed("at most 65536 OCR review pages are allowed")); + } + pdfcraft_engine::ocr::validate_ocr_words(found.iter().flat_map(|p| &p.words)).map_err(failed)?; + let band_name = |band: pdfcraft_engine::ocr::ConfidenceBand| match band { + pdfcraft_engine::ocr::ConfidenceBand::High => "high", + pdfcraft_engine::ocr::ConfidenceBand::Medium => "medium", + pdfcraft_engine::ocr::ConfidenceBand::Low => "low", + }; + let mut suspects = 0usize; let list: Vec = found .iter() - .map(|p| match &p.skipped { - Some(why) => json!({ "page": p.page + 1, "skipped": why }), - None if copy => json!({ "page": p.page + 1, "words": p.words.len(), "already_on_page": p.already_on_page, "text": p.text() }), - None => json!({ "page": p.page + 1, "words": p.words.len(), "already_on_page": p.already_on_page }), + .map(|p| { + let info = infos.get(&p.page); + let words: Vec = p + .words + .iter() + .map(|w| { + let suspect = pdfcraft_engine::ocr::is_suspect(w.confidence); + if suspect { + suspects += 1; + } + // The word's corners in view space, as the box [x, y, w, h] in points + // from the top-left of the displayed page. + let view = |pt: [f64; 2]| info.map(|i| i.user_to_view(pt[0] as f32, pt[1] as f32)); + let corners = [ + view(w.origin), + view([w.origin[0] + w.across[0], w.origin[1] + w.across[1]]), + view([w.origin[0] + w.up[0], w.origin[1] + w.up[1]]), + view([w.origin[0] + w.across[0] + w.up[0], w.origin[1] + w.across[1] + w.up[1]]), + ]; + let xs: Vec = corners.iter().flatten().map(|v| v[0]).collect(); + let ys: Vec = corners.iter().flatten().map(|v| v[1]).collect(); + let (min_x, min_y) = (xs.iter().cloned().fold(f32::INFINITY, f32::min), ys.iter().cloned().fold(f32::INFINITY, f32::min)); + let (w_pt, h_pt) = ( + xs.iter().cloned().fold(f32::NEG_INFINITY, f32::max) - min_x, + ys.iter().cloned().fold(f32::NEG_INFINITY, f32::max) - min_y, + ); + json!({ + "text": w.text, + "box": [min_x, min_y, w_pt, h_pt], + "confidence": w.confidence.map(|c| (c * 10.0).round() / 10.0), + "band": w.confidence.map(|c| band_name(pdfcraft_engine::ocr::band_for(c))), + "suspect": suspect, + "source": w.source, + }) + }) + .collect(); + let mut page = + json!({ "page": p.page + 1, "already_on_page": p.already_on_page, "words": words, "mean_confidence": p.mean_confidence().map(|c| (c * 10.0).round() / 10.0) }); + if let Some(why) = &p.skipped { + page["skipped"] = json!(why); + } + page }) .collect(); - Ok(json!({ "words": found.iter().map(|p| p.words.len()).sum::(), "pages": list })) + let mut out = json!({ "words": found.iter().map(|p| p.words.len()).sum::(), "suspects": suspects, "pages": list }); + if retain { + self.next_ocr_review = + self.next_ocr_review.checked_add(1).filter(|n| *n <= i64::MAX as u64).ok_or_else(|| failed("OCR review handles exhausted"))?; + out["review"] = json!(self.next_ocr_review); + self.ocr_reviews.insert(id, crate::OcrReview { handle: self.next_ocr_review, guard, pages: found }); + } + Ok(out) + } + + /// Apply only caller corrections to retained original boxes, through the stored guard. + pub(crate) fn ocr_review_apply(&mut self, a: &Args) -> Result { + let id = self.doc(a)?.id; + let handle = a.int("review")?; + let review = self + .ocr_reviews + .get(&id) + .filter(|r| i64::try_from(r.handle).ok() == Some(handle)) + .ok_or_else(|| failed("unknown OCR review for this document; call ocr_words with retain_review"))?; + if a.opt_bool("discard")?.unwrap_or(false) { + if a.get("corrections").is_some() { + return Err(ToolError::InvalidArgs("discard cannot include corrections".into())); + } + self.ocr_reviews.remove(&id); + return Ok(json!({ "discarded": handle })); + } + if let Some(why) = self.session.stale_reason(&review.guard) { + return Err(failed(why)); + } + let corrections = a.get("corrections").map(|v| v.as_array().ok_or_else(|| Args::wrong("corrections", "an array"))).transpose()?; + if corrections.is_some_and(|c| c.len() > 65536) { + return Err(failed("at most 65536 OCR corrections are allowed")); + } + // Prevalidate and cap every replacement before cloning the retained result. + let mut edits = Vec::new(); + let mut bytes = 0usize; + let mut seen = std::collections::BTreeSet::new(); + let page_indices: std::collections::BTreeMap<_, _> = review.pages.iter().enumerate().map(|(i, p)| (p.page, i)).collect(); + for item in corrections.into_iter().flatten() { + if !item.is_object() || item.as_object().is_some_and(|o| o.keys().any(|k| !matches!(k.as_str(), "page" | "word" | "text"))) { + return Err(ToolError::InvalidArgs("corrections accept only page, word and text".into())); + } + let c = Args(item); + let page = + usize::try_from(c.int("page")?).ok().and_then(|p| p.checked_sub(1)).ok_or_else(|| Args::wrong("page", "a 1-based position"))?; + let word = + usize::try_from(c.int("word")?).ok().and_then(|w| w.checked_sub(1)).ok_or_else(|| Args::wrong("word", "a 1-based position"))?; + let text = c.str("text")?; + bytes = bytes.checked_add(text.len()).filter(|n| *n <= 4 * 1024 * 1024).ok_or_else(|| failed("OCR corrections exceed 4 MiB"))?; + if !seen.insert((page, word)) { + return Err(failed("duplicate OCR word correction")); + } + let pi = page_indices.get(&page).copied().ok_or_else(|| failed("page is not in this OCR review"))?; + if review.pages.get(pi).and_then(|p| p.words.get(word)).is_none() { + return Err(failed("word is not in this OCR review")); + } + edits.push((pi, word, text.to_owned())); + } + let mut pages = review.pages.clone(); + for (pi, wi, text) in edits { + if let Some(w) = pages.get_mut(pi).and_then(|p| p.words.get_mut(wi)) { + w.text = text; + } + } + pdfcraft_engine::ocr::validate_ocr_words(pages.iter().flat_map(|p| &p.words)).map_err(failed)?; + for page in &mut pages { + page.words.retain(|w| !w.text.trim().is_empty()); + } + if pages.iter().all(|p| p.words.is_empty()) { + return Err(failed("the OCR review has no words to apply")); + } + let out = match a.opt_str("output_mode")?.unwrap_or("searchable") { + "searchable" => { + if a.get("out").is_some() { + return Err(ToolError::InvalidArgs("out is only for editable output".into())); + } + let count = self.session.apply_ocr_checked(id, &pages, &review.guard).map_err(failed)?; + json!({ "applied": count, "review": handle }) + } + "editable" => { + // The editable output writes the review's words out of the document: a + // document that forbids copying refuses here (the review is kept). + self.doc_to_copy(a)?; + let target = self.resolve(a.str("out")?, true)?; + if self + .session + .get(id) + .and_then(|d| d.path.as_deref()) + .and_then(|p| std::fs::canonicalize(p).ok()) + .as_ref() + .is_some_and(|source| std::fs::canonicalize(&target).as_ref().ok() == Some(source)) + { + return Err(failed("out is the source document; choose a new file")); + } + // A NEW file: an existing one is never replaced silently (the review is kept). + if target.exists() { + return Err(failed(format!("out already exists ({}); choose a path that does not exist yet", target.to_string_lossy()))); + } + let bytes = self.session.editable_ocr_bytes(id, &pages).map_err(failed)?; + write_atomic(&target, &bytes)?; + json!({ "out": target.to_string_lossy(), "review": handle, "words": pages.iter().map(|p| p.words.len()).sum::() }) + } + _ => return Err(ToolError::InvalidArgs("output_mode must be searchable or editable".into())), + }; + self.ocr_reviews.remove(&id); + Ok(out) + } + + /// Read/update the same per-language dictionary file used by OCR Verify. + pub(crate) fn ocr_dictionary(&mut self, a: &Args) -> Result { + use pdfcraft_engine::ocr::dictionary; + use std::io::Read as _; + for key in ["add", "remove"] { + if let Some(value) = a.get(key) { + let values = value.as_array().ok_or_else(|| Args::wrong(key, "an array of strings"))?; + if values.len() > 65536 { + return Err(failed("at most 65536 dictionary words are allowed")); + } + } + } + let add = if a.get("add").is_some() { a.strs("add")? } else { Vec::new() }; + let remove = if a.get("remove").is_some() { a.strs("remove")? } else { Vec::new() }; + let writing = a.get("add").is_some() || a.get("remove").is_some(); + // Updating sorts, lower-cases and rewrites the file, so this tool names dictionary files only: + // pointed at `.env` or a README it would corrupt it. + let file = std::path::Path::new(a.str("path")?).file_name().and_then(|n| n.to_str()).unwrap_or(""); + let plain = file.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.')); + if file.len() > 64 || !plain || !file.starts_with("ocr-dictionary") || !file.ends_with(".txt") { + return Err(failed("path must name a dictionary file: ocr-dictionary-.txt (letters, digits, '-', '_' and '.' only)")); + } + let path = self.resolve(a.str("path")?, writing)?; + let mut input = String::new(); + match std::fs::File::open(&path) { + Ok(file) => { + file.take((dictionary::MAX_BYTES + 1) as u64).read_to_string(&mut input).map_err(|e| failed(format!("OCR dictionary: {e}")))?; + } + Err(e) if e.kind() == std::io::ErrorKind::NotFound && writing => {} + Err(e) => return Err(failed(format!("OCR dictionary: {e}"))), + } + let text = dictionary::update(&input, &add, &remove).map_err(failed)?; + if writing { + write_atomic(&path, text.as_bytes())?; + } + let words = dictionary::words(&text).map_err(failed)?; + Ok(json!({ "path": path.to_string_lossy(), "count": words.len(), "words": words })) } - /// Whether text recognition's models are installed, the directories searched for them (in - /// order), and the languages it reads, each as a code and a name. pub(crate) fn ocr_status(&self) -> Result { use pdfcraft_engine::ocr; let dirs: Vec = ocr::Models::search_dirs().iter().map(|d| d.to_string_lossy().into_owned()).collect(); let langs: Vec = ocr::LANGUAGES.iter().map(|(c, n)| json!({ "code": c, "name": n })).collect(); - Ok(json!({ "available": ocr::available(), "search_dirs": dirs, "languages": langs })) + let engines: Vec = ocr::engines_status() + .iter() + .map(|e| { + let mut v = json!({ "id": e.id, "available": e.available }); + if let Some(p) = &e.program { + v["path"] = json!(p); + } + if let Some(vv) = &e.version { + v["version"] = json!(vv); + } + if let Some(why) = &e.why_not { + v["unavailable"] = json!(why); + } + v + }) + .collect(); + Ok(json!({ "available": ocr::available(), "search_dirs": dirs, "languages": langs, "engines": engines })) } } diff --git a/crates/automation/src/batch.rs b/crates/automation/src/batch.rs index decb18d2b7..dd5ca6aec0 100644 --- a/crates/automation/src/batch.rs +++ b/crates/automation/src/batch.rs @@ -84,8 +84,8 @@ impl<'a> Recipe<'a> { match *step { "convert" => bytes = session.convert_to_pdf(name, &bytes)?.1, "ocr" => { - let engine = ocr::engine().map_err(failed)?; - let result = ocr::recognize_file(name, bytes, None, self.ocr.clone(), &engine, |_, _| true).map_err(failed)?; + let recognizers = ocr::recognizers(&self.ocr).map_err(failed)?; + let result = ocr::recognize_file(name, bytes, None, self.ocr.clone(), &recognizers, |_, _| true).map_err(failed)?; log.push( json!({"step":"ocr","words":result.words(),"skipped_pages":result.pages.iter().filter(|p| p.skipped.is_some()).count()}), ); diff --git a/crates/automation/src/bates.rs b/crates/automation/src/bates.rs index 3cd1d7849e..5267716e85 100644 --- a/crates/automation/src/bates.rs +++ b/crates/automation/src/bates.rs @@ -199,7 +199,7 @@ impl Automation { } /// Publish a PDF atomically while refusing a target created by another process after preflight. -fn publish_new(path: &Path, bytes: &[u8]) -> Result<()> { +pub(super) fn publish_new(path: &Path, bytes: &[u8]) -> Result<()> { let parent = path.parent().ok_or_else(|| failed("output has no parent directory"))?; let mut temp = tempfile::NamedTempFile::new_in(parent).map_err(failed)?; temp.write_all(bytes).map_err(failed)?; diff --git a/crates/automation/src/comments.rs b/crates/automation/src/comments.rs index 135d0868ee..78f4cefbe0 100644 --- a/crates/automation/src/comments.rs +++ b/crates/automation/src/comments.rs @@ -5,7 +5,9 @@ use std::collections::HashMap; -use pdfcraft_engine::{Edit, LineEnding, Markup, NewAnnotation, NoteIcon, ReviewState, Rgb, Shape, StampGroup, StampKind, Style, SummarySort}; +use pdfcraft_engine::{ + BorderShape, Edit, LineEnding, Markup, NewAnnotation, NoteIcon, ReviewState, Rgb, Shape, StampGroup, StampKind, Style, SummarySort, +}; use pdfcraft_render::{Annotation, PageInfo}; use serde_json::{Value, json}; @@ -190,6 +192,25 @@ impl Automation { "rect": crate::view_rect(&doc.info, c.page, c.shown_rect(doc.info.pages.get(c.page).map_or(0, |p| p.rotation))), "color": c.color.map(hex), }); + // A text box's or typed text's oval or circle (a rectangle is not reported). + if c.subtype == "FreeText" + && let Some(shape) = doc.comment_props(c.page, c.index).and_then(|p| p.border_shape).filter(|s| *s != BorderShape::Rectangle) + { + v["border_shape"] = json!(shape.name().to_ascii_lowercase()); + } + // How opaque it is drawn: as a whole, or its fill and text each at their own. + // Not for replies, which are drawn with the comment they answer. + if !c.is_reply() + && let Some(p) = doc.comment_props(c.page, c.index) + { + v["opacity"] = json!(p.opacity); + if let Some(f) = p.fill_opacity { + v["fill_opacity"] = json!(f); + } + if let Some(t) = p.text_opacity { + v["text_opacity"] = json!(t); + } + } // A line's ends, or the corners of connected lines, a polygon or a cloud, as // comment_edit's `points` takes them. // Unchanged on a page the viewer could not read, as `rect` is. @@ -253,6 +274,12 @@ impl Automation { if endings.is_some() && !matches!(kind, "line" | "arrow" | "polyline" | "callout") { return Err(ToolError::InvalidArgs("endings apply to a line, arrow, polyline or callout".into())); } + // Shift while drawing: each end or corner held level or plumb with the one before. + let ortho = a.opt_bool("ortho")?.unwrap_or(false); + if ortho && !matches!(kind, "line" | "arrow" | "polygon" | "cloud" | "polyline") { + return Err(ToolError::InvalidArgs("ortho applies to a line, arrow, polygon, cloud or polyline".into())); + } + let held = |last: [f64; 2], p: [f64; 2]| if ortho { pdfcraft_engine::measure::snap::ortho(last, p) } else { p }; let markup = match kind { "highlight" => Some(Markup::Highlight), "underline" => Some(Markup::Underline), @@ -325,7 +352,8 @@ impl Automation { Shape::TextBox { rect: rect_to_user(&info, a.need::<4>("rect", "a text box")?), font_size } } "line" | "arrow" => { - let (f, t) = (a.need::<2>("from", "a line")?, a.need::<2>("to", "a line")?); + let f = a.need::<2>("from", "a line")?; + let t = held(f, a.need::<2>("to", "a line")?); let [start, end] = ending_pair(kind, endings.as_deref())?; Shape::Line { from: to_user(&info, f[0], f[1]), to: to_user(&info, t[0], t[1]), start, end } } @@ -352,10 +380,15 @@ impl Automation { "polygon" | "cloud" | "polyline" => { let wrong = || ToolError::InvalidArgs(format!("{kind} needs `points`: an array of [x, y] points")); let pts = a.get("points").and_then(|p| p.as_array()).ok_or_else(wrong)?; + let mut last = None; let vertices = pts .iter() .map(|p| match p.as_array().map(|p| p.iter().map(|v| v.as_f64()).collect::>()).as_deref() { - Some([Some(x), Some(y)]) => Ok(to_user(&info, *x, *y)), + Some([Some(x), Some(y)]) => { + let p = last.map_or([*x, *y], |l| held(l, [*x, *y])); + last = Some(p); + Ok(to_user(&info, p[0], p[1])) + } _ => Err(wrong()), }) .collect::>>()?; @@ -425,9 +458,28 @@ impl Automation { if let Some(o) = a.opt_num("opacity")? { style.opacity = o.clamp(0.0, 1.0); } + // The fill's and a text box's text's own opacities (the line keeps `opacity`). + let (fill_opacity, text_opacity) = (a.opt_num("fill_opacity")?, a.opt_num("text_opacity")?); + let texts = matches!(shape, Shape::TextBox { .. } | Shape::Typewriter { .. } | Shape::Callout { .. }); + if fill_opacity.is_some() && !(texts || matches!(shape, Shape::Rectangle { .. } | Shape::Oval { .. } | Shape::Polygon { .. })) { + return Err(ToolError::InvalidArgs( + "fill_opacity applies to a rectangle, oval, polygon, cloud, text box, typewriter text or callout".into(), + )); + } + if text_opacity.is_some() && !texts { + return Err(ToolError::InvalidArgs("text_opacity applies to a text box, typewriter text or callout".into())); + } + style.fill_opacity = fill_opacity.map(|o| o.clamp(0.0, 1.0)); + style.text_opacity = text_opacity.map(|o| o.clamp(0.0, 1.0)); if let Some(w) = a.opt_num("width")? { style.width = w.max(0.0); } + if let Some(b) = border_shape(a)? { + if !matches!(shape, Shape::TextBox { .. } | Shape::Typewriter { .. }) { + return Err(ToolError::InvalidArgs("border_shape is for a text box or typewriter text".into())); + } + style.border_shape = b; + } let contents = a.opt_str("contents")?.unwrap_or_default().to_string(); let author = a.opt_str("author")?.unwrap_or(DEFAULT_AUTHOR).to_string(); // Replace Text: the struck-out text and a grouped caret holding `contents`. @@ -488,6 +540,7 @@ impl Automation { } pub(crate) fn fill_sign_add(&mut self, a: &Args) -> Result { + let border_shape = border_shape(a)?; use pdfcraft_engine::FillMark; let page = self.page(a)?; let info = self.doc(a)?.info.pages[page].clone(); @@ -515,6 +568,25 @@ impl Automation { if !(4.0..=300.0).contains(&size) { return Err(ToolError::InvalidArgs("font_size must be 4–300 pt".into())); } + let requested_border = a.opt_num("border")?; + if requested_border.is_some() && !matches!(kind, "text" | "date") { + return Err(ToolError::InvalidArgs("border is only for type text or date".into())); + } + let border = requested_border.unwrap_or(0.0); + if !(0.0..=12.0).contains(&border) { + return Err(ToolError::InvalidArgs("border must be 0–12 pt".into())); + } + let border_color = a.opt_str("border_color")?.map(parse_color).transpose()?; + if border_color.is_some() && border <= 0.0 { + return Err(ToolError::InvalidArgs("border_color needs a border".into())); + } + if border_shape.is_some() && !matches!(kind, "text" | "date") { + return Err(ToolError::InvalidArgs("border_shape is only for type text or date".into())); + } + // Without a border an oval or a circle would grow the box around nothing drawn. + if border_shape.is_some_and(|s| s != BorderShape::Rectangle) && border <= 0.0 { + return Err(ToolError::InvalidArgs("border_shape needs a border".into())); + } if let Some(path) = a.opt_str("path")? { if !matches!(kind, "signature" | "initials") || a.opt_str("text")?.is_some() { return Err(ToolError::InvalidArgs("path is only for an image signature or initials; pass either path or text".into())); @@ -538,13 +610,16 @@ impl Automation { let edit = image.edit(page, &info, at, kind == "initials", &author).ok_or_else(|| ToolError::InvalidArgs("at must be finite".into()))?; return self.apply(a, edit); } + // A circle goes around the text, so its box is no wider than the text needs. + let min_width = if border_shape == Some(BorderShape::Circle) { 0.0 } else { 20.0 }; let text_at = |t: &str| { let longest = t.lines().map(|line| pdfcraft_engine::annot_text::text_width(line, size)).fold(0.0, f64::max); - let w = (longest + 8.0).clamp(20.0, 600.0); + let w = (longest + 8.0).clamp(min_width, 600.0); let rows = pdfcraft_engine::annot_text::wrap(t, size, w - 4.0).len().max(1); let h = rows as f64 * size * 1.2 + 6.0; - let rect = pdfcraft_engine::text_box_at(i64::from(info.rotation), at, w, h).unwrap_or([at[0], at[1] - h, at[0] + w, at[1]]); - Shape::Typewriter { rect, font_size: size } + let [x0, y0, x1, y1] = pdfcraft_engine::text_box_at(i64::from(info.rotation), at, w, h).unwrap_or([at[0], at[1] - h, at[0] + w, at[1]]); + // A border goes around the box, so the text sits where it would without one. + Shape::Typewriter { rect: [x0 - border, y0 - border, x1 + border, y1 + border], font_size: size } }; let (shape, contents) = match kind { "text" => { @@ -590,6 +665,11 @@ impl Automation { if let Some(color) = requested_color { style.color = color; } + if matches!(shape, Shape::Typewriter { .. }) { + style.width = border; + style.border_color = border_color; + style.border_shape = border_shape.unwrap_or_default(); + } self.apply(a, Edit::AddAnnotation(NewAnnotation { page, shape, style, contents, author })) } @@ -656,6 +736,21 @@ impl Automation { let fill = if f.eq_ignore_ascii_case("none") { None } else { Some(parse_color(f)?) }; edits.push(Edit::FillAnnotation { page, index, fill }); } + if let Some(c) = a.opt_str("border_color")? { + let color = if c.eq_ignore_ascii_case("text") { None } else { Some(parse_color(c)?) }; + edits.push(Edit::BorderColorAnnotation { page, index, color }); + } + if let Some(shape) = border_shape(a)? { + edits.push(Edit::BorderShapeAnnotation { page, index, shape }); + } + // After `opacity`, which sets the whole comment's. + let (fill_opacity, text_opacity) = (a.opt_num("fill_opacity")?, a.opt_num("text_opacity")?); + if fill_opacity.into_iter().chain(text_opacity).any(|o| !(0.0..=1.0).contains(&o)) { + return Err(ToolError::InvalidArgs("fill_opacity and text_opacity are 0–1".into())); + } + if fill_opacity.is_some() || text_opacity.is_some() { + edits.push(Edit::PartOpacity { page, index, fill: fill_opacity, text: text_opacity }); + } if let Some(size) = a.opt_num("font_size")? { if !(1.0..=400.0).contains(&size) { return Err(ToolError::InvalidArgs("font_size must be 1–400 pt".into())); @@ -689,7 +784,7 @@ impl Automation { } if edits.is_empty() { return Err(ToolError::InvalidArgs( - "nothing to change: pass contents, color, opacity, width, fill, font_size, rect, move or points".into(), + "nothing to change: pass contents, color, opacity, fill_opacity, text_opacity, width, fill, border_color, border_shape, font_size, rect, move or points".into(), )); } let edit = if edits.len() == 1 { edits.remove(0) } else { Edit::Batch { label: "Edit comment".into(), edits } }; @@ -700,6 +795,49 @@ impl Automation { let (page, index) = self.comment_target(a)?; self.apply(a, Edit::DeleteAnnotation { page, index }) } + + /// The XFDF of the listed comments and their replies (`comments`: 1-based [page, index] pairs). + pub(crate) fn comments_copy(&self, a: &Args) -> Result { + let id = self.doc(a)?.id; + let all = self.comments(a)?; + let shape = || ToolError::InvalidArgs("comments: [[page, index], …] (1-based, as comment_list reports)".into()); + let list = a.get("comments").and_then(Value::as_array).ok_or_else(shape)?; + let mut which = Vec::with_capacity(list.len()); + for item in list { + let pair = item.as_array().filter(|p| p.len() == 2).and_then(|p| Some((p.first()?.as_u64()?, p.get(1)?.as_u64()?))); + let Some((page, index)) = pair.filter(|(p, i)| *p >= 1 && *i >= 1) else { return Err(shape()) }; + let (page, index) = (usize::try_from(page - 1).map_err(|_| shape())?, usize::try_from(index - 1).map_err(|_| shape())?); + if !all.iter().any(|c| c.page == page && c.index == index) { + return Err(failed(format!("there is no comment {} on page {} (see comment_list)", index + 1, page + 1))); + } + which.push((page, index)); + } + let xfdf = self.session.export_comments(id, &which).map_err(failed)?; + Ok(json!({ "xfdf": xfdf, "comments": which.len() })) + } + + /// Add the comments of `xfdf` (from `comments_copy`) to `page` as new comments. + pub(crate) fn comments_paste(&mut self, a: &Args) -> Result { + let page = self.page(a)?; + let xfdf = a.str("xfdf")?.to_owned(); + if !pdfcraft_engine::is_xfdf_comments(&xfdf) { + return Err(ToolError::InvalidArgs("xfdf: the text comments_copy returned (XFDF with )".into())); + } + let offset = match a.nums::<2>("at")? { + Some([x, y]) => { + let info = self.doc(a)?.info.pages.get(page).cloned().ok_or_else(|| failed(format!("no page {}", page + 1)))?; + let [cx, cy] = to_user(&info, x, y); + let b = + pdfcraft_engine::comments_bounds(&xfdf).ok_or_else(|| ToolError::InvalidArgs("xfdf: no comment with a rect to place".into()))?; + Some([cx - (b[0] + b[2]) / 2.0, cy - (b[1] + b[3]) / 2.0]) + } + None => None, + }; + let before = self.comments(a)?.len(); + let mut out = self.apply(a, Edit::PasteComments { xfdf, page, offset })?; + out["comments"] = json!(self.comments(a)?.len().saturating_sub(before)); + Ok(out) + } } impl Automation { @@ -744,6 +882,13 @@ impl Automation { } } +/// `border_shape`: `rectangle`, `oval` or `circle`. +fn border_shape(a: &Args) -> Result> { + a.opt_str("border_shape")? + .map(|s| BorderShape::parse(s).ok_or_else(|| ToolError::InvalidArgs(format!("unknown border_shape {s:?}: rectangle, oval or circle")))) + .transpose() +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/automation/src/dispatch.rs b/crates/automation/src/dispatch.rs index 45df846ebc..ebe2a93526 100644 --- a/crates/automation/src/dispatch.rs +++ b/crates/automation/src/dispatch.rs @@ -812,6 +812,9 @@ impl Automation { "form_set_actions" => self.form_set_actions(&a)?, "ocr_status" => self.ocr_status()?, "ocr_recognize_files" => self.ocr_recognize_files(&a)?, + "ocr_words" => self.ocr_words(&a)?, + "ocr_review_apply" => self.ocr_review_apply(&a)?, + "ocr_dictionary" => self.ocr_dictionary(&a)?, "accessibility_report" => self.a11y_report(&a)?, "accessibility_review_record" => self.a11y_review_record(&a)?, "accessibility_review_save" => self.a11y_review_save(&a)?, @@ -867,6 +870,8 @@ impl Automation { "comments_summarize" => self.comments_summarize(&a)?, "comment_edit" => self.comment_edit(&a)?, "comment_delete" => self.comment_delete(&a)?, + "comments_copy" => self.comments_copy(&a)?, + "comments_paste" => self.comments_paste(&a)?, other => return Err(ToolError::UnknownTool(other.into())), }; Ok(vec![Content::Json(out)]) diff --git a/crates/automation/src/documents.rs b/crates/automation/src/documents.rs index 979b041a73..f8c7988bbc 100644 --- a/crates/automation/src/documents.rs +++ b/crates/automation/src/documents.rs @@ -120,6 +120,7 @@ impl Automation { self.texts.remove(&id); self.listed.retain(|(d, _), _| *d != id); self.evicted.remove(&id); + self.ocr_reviews.remove(&id); Ok(json!({ "closed": id.0 })) } diff --git a/crates/automation/src/lib.rs b/crates/automation/src/lib.rs index 520d836b01..7e4443d244 100644 --- a/crates/automation/src/lib.rs +++ b/crates/automation/src/lib.rs @@ -76,6 +76,12 @@ pub(crate) use paths::{read_input, read_input_bytes}; #[cfg(test)] use paths::{write_atomic_synced, write_atomic_with}; +struct OcrReview { + handle: u64, + guard: pdfcraft_engine::ocr::OcrGuard, + pages: Vec, +} + /// A headless PdfCraft session driven by tool calls. pub struct Automation { session: Session, @@ -92,6 +98,9 @@ pub struct Automation { /// Documents that lost a listing to the cap. A page of one with no listing is refused rather /// than read as "a number is a position", which the page may no longer match. evicted: HashSet, + /// Review sessions held for `ocr_words` (a guard and the pages read), by document. + ocr_reviews: HashMap, + next_ocr_review: u64, } impl Default for Automation { @@ -110,6 +119,8 @@ impl Automation { texts: TextCache::default(), listed: HashMap::new(), evicted: HashSet::new(), + ocr_reviews: HashMap::new(), + next_ocr_review: 0, } } diff --git a/crates/automation/src/tools.rs b/crates/automation/src/tools.rs index e0c702011e..30d9c51384 100644 --- a/crates/automation/src/tools.rs +++ b/crates/automation/src/tools.rs @@ -5,6 +5,8 @@ use serde_json::{Value, json}; +use pdfcraft_engine::REDACT_PATTERNS; + use crate::ToolError; #[derive(Clone, Debug)] @@ -30,6 +32,12 @@ fn pages(what: &str) -> Value { json!({ "type": "array", "items": { "type": "integer", "minimum": 1 }, "minItems": 1, "description": format!("1-based page numbers {what}.") }) } +/// The Search & Redact pattern ids, from the engine's registry, so the advertised schema cannot +/// drift from the patterns the runtime accepts. +fn pattern_enum() -> Value { + json!({ "type": "string", "enum": REDACT_PATTERNS.iter().map(|p| p.id()).collect::>() }) +} + fn path(what: &str) -> Value { json!({ "type": "array", "items": { "type": "integer", "minimum": 1 }, "description": format!("{what}: 1-based positions from the top level, e.g. [2, 1] = the first child of the second bookmark.") }) } @@ -77,6 +85,12 @@ fn schema(props: Value, required: &[&str]) -> Value { json!({ "type": "object", "properties": props, "required": required, "additionalProperties": false }) } +/// The language codes the engines read, as the `language` enum — from the engine's own table, +/// so the schema and the validator can never disagree. +fn language_enum() -> Value { + Value::Array(pdfcraft_engine::ocr::LANGUAGES.iter().map(|(code, _)| json!(code)).collect()) +} + struct T { name: &'static str, title: &'static str, @@ -606,7 +620,7 @@ pub fn tools() -> Vec { t( "redact_mark", "Mark for redaction", - "Mark content for redaction (nothing is removed until redact_apply). One of: rect [x0, y0, x1, y1] (points from the top-left of the displayed page) with page; find (text, every match); words (a list of words or phrases, every match of each; the result's matched_words says how many marks each made); pattern (phone, email, credit-card, ssn, date: every match, Acrobat's Search & Redact patterns); whole_pages: true. find and words accept case_sensitive and whole_words (both default false). Select one page with page or multiple with pages (default all); do not pass both. rect requires page. overlay: text shown on the box once applied, or code_set (foia: U.S. FOIA (b)(1)(A)…(b)(9); privacy-act: U.S. Privacy Act (d)(5), (j)(1)…(k)(7)) with codes, shown as \"(b)(6), (b)(7)(C)\"; fill: box colour (default black). Undoable.", + "Mark content for redaction (nothing is removed until redact_apply). One of: rect [x0, y0, x1, y1] (points from the top-left of the displayed page) with page; find (text, every match); words (a list of words or phrases, every match of each; the result's matched_words says how many marks each made); pattern (phone, email, credit-card, ssn, date, iban: every match, Acrobat's Search & Redact patterns); whole_pages: true. find and words accept case_sensitive and whole_words (both default false). Select one page with page or multiple with pages (default all); do not pass both. rect requires page. overlay: text shown on the box once applied, or code_set (foia: U.S. FOIA (b)(1)(A)…(b)(9); privacy-act: U.S. Privacy Act (d)(5), (j)(1)…(k)(7)) with codes, shown as \"(b)(6), (b)(7)(C)\"; fill: box colour (default black). Undoable.", ) .with(schema( json!({ @@ -617,7 +631,7 @@ pub fn tools() -> Vec { "words": { "type": "array", "items": { "type": "string", "minLength": 1 }, "minItems": 1, "maxItems": 1000 }, "case_sensitive": { "type": "boolean", "description": "Match letter case for find or words (default false)." }, "whole_words": { "type": "boolean", "description": "Match whole words for find or words (default false)." }, - "pattern": { "type": "string", "enum": ["phone", "email", "credit-card", "ssn", "date"] }, + "pattern": pattern_enum(), "whole_pages": { "type": "boolean" }, "pages": pages("to search or mark (default: all); mutually exclusive with page, and not valid with rect"), "overlay": { "type": "string" }, @@ -859,9 +873,13 @@ pub fn tools() -> Vec { "icon": { "type": "string", "description": "note: Comment, Note, Help, Insert, Key, NewParagraph, Paragraph (the standard names), Check, Circle, Cross, CrossHairs, Star, RightArrow, UpArrow; attachment: PushPin, Paperclip, Graph, Tag." }, "color": color(), "fill": color(), - "opacity": { "type": "number", "minimum": 0, "maximum": 1 }, + "opacity": { "type": "number", "minimum": 0, "maximum": 1, "description": "The whole comment's opacity (its line or border's, where its fill or text has its own)." }, + "fill_opacity": { "type": "number", "minimum": 0, "maximum": 1, "description": "The fill's own opacity: rectangle, oval, polygon, cloud, text box, typewriter text or callout." }, + "text_opacity": { "type": "number", "minimum": 0, "maximum": 1, "description": "The text's own opacity: text box, typewriter text or callout." }, "width": { "type": "number", "minimum": 0, "description": "Line width in points." }, + "border_shape": { "type": "string", "enum": ["rectangle", "oval", "circle"], "description": "A text box's or typewriter text's border shape: an oval or a circle goes around the text box." }, "endings": { "type": "array", "items": { "type": "string", "enum": ["None", "Square", "Circle", "Diamond", "OpenArrow", "ClosedArrow", "Butt", "ROpenArrow", "RClosedArrow", "Slash"] }, "minItems": 1, "maxItems": 2, "description": "Line endings. Two names (start, end) for a line, arrow or polyline; one name for a callout." }, + "ortho": { "type": "boolean", "description": "line/arrow/polygon/cloud/polyline: hold each end or corner level or plumb with the one before, whichever is nearer (Shift while drawing)." }, "font_size": { "type": "number", "exclusiveMinimum": 0 }, }), &["doc", "page", "type"], @@ -992,13 +1010,17 @@ pub fn tools() -> Vec { json!({ "doc": doc(), "sort": { "type": "string", "enum": ["page", "author", "date", "type"] }, "out": save_out, "open": open }), &["doc"], )), - t("comment_edit", "Edit a comment", "Change a comment's text, colour, opacity, line width, font size (text box/typewriter/callout), fill (rectangle/oval/polygon/text box/callout; \"none\" removes it), rectangle (rectangle/oval/text box/stamp), position (`move` [dx, dy] in points) or shape (`points`: a line's two ends, or the corners of connected lines, a polygon or a cloud). Stamps keep their original appearance when resized. One undo step.").with(schema( + t("comment_edit", "Edit a comment", "Change a comment's text, colour, opacity (the whole comment's, or its fill's and text's own), line width, font size (text box/typewriter/callout), fill (rectangle/oval/polygon/text box/callout; \"none\" removes it), border colour (`border_color`, text box/typewriter/callout; \"text\" gives it the text's colour again), rectangle (rectangle/oval/text box/stamp), position (`move` [dx, dy] in points) or shape (`points`: a line's two ends, or the corners of connected lines, a polygon or a cloud). Stamps keep their original appearance when resized. One undo step.").with(schema( comment_ref(json!({ "contents": { "type": "string" }, "color": color(), - "opacity": { "type": "number", "minimum": 0, "maximum": 1 }, + "opacity": { "type": "number", "minimum": 0, "maximum": 1, "description": "The whole comment's opacity: its fill and text drop opacities of their own." }, + "fill_opacity": { "type": "number", "minimum": 0, "maximum": 1, "description": "The fill's own opacity (rectangle, oval, polygon, cloud, text box, typewriter text, callout); the line or border keeps the comment's." }, + "text_opacity": { "type": "number", "minimum": 0, "maximum": 1, "description": "The text's own opacity (text box, typewriter text, callout)." }, "width": { "type": "number", "minimum": 0 }, "fill": { "type": "string", "description": "Interior colour of a rectangle, oval, polygon, text box or callout: #RRGGBB, a colour name, or \"none\" for no fill." }, + "border_color": { "type": "string", "description": "A text box's, typewriter text's or callout's border colour: #RRGGBB, a colour name, or \"text\" for the text's colour." }, + "border_shape": { "type": "string", "enum": ["rectangle", "oval", "circle"], "description": "A text box's or typewriter text's border shape: an oval or a circle goes around the text, which keeps its place." }, "font_size": { "type": "number", "minimum": 1, "maximum": 400, "description": "Font size in points of a text box, typewriter text or callout; the box grows to hold the text." }, "rect": { "type": "array", "items": { "type": "number" }, "minItems": 4, "maxItems": 4 }, "move": point(), @@ -1009,6 +1031,25 @@ pub fn tools() -> Vec { t("comment_image_preview", "Preview image signature layers", "Return a PNG of the page without the selected image signature/initials (layer=background, default), or its embedded image with alpha (layer=image). Includes the displayed rectangle, document rotation, image_rotation (how far clockwise the image is shown turned) and annotation opacity. Cache these layers for live placement/resizing; commit once with comment_edit. Does not change the document or undo history.") .ro().with(schema(comment_ref(json!({ "layer": { "type": "string", "enum": ["background", "image"], "default": "background" }, "dpi": { "type": "number", "minimum": 1, "maximum": 600, "default": 96 } })), &["doc"])), t("comment_delete", "Delete a comment", "Delete a comment with its pop-up and replies, or one reply (its id, or page and index, from comment_list) with its pop-up and the replies to it; the comment and its other replies stay. Undoable.").destructive().with(schema(comment_ref(json!({})), &["doc"])), + t( + "comments_copy", + "Copy comments", + "The XFDF of these comments, each with its replies: what Copy puts on the clipboard. Paste it into this or another document with comments_paste. `comments`: [[page, index], …], 1-based as comment_list reports them.", + ) + .ro() + .with(schema( + json!({ + "doc": doc(), + "comments": { "type": "array", "items": { "type": "array", "items": { "type": "integer", "minimum": 1 }, "minItems": 2, "maxItems": 2 }, "minItems": 1 } + }), + &["doc", "comments"], + )), + t( + "comments_paste", + "Paste comments", + "Add the comments of an XFDF text (from comments_copy) to `page` as new comments: copies under names of their own, so nothing in the document is replaced and pasting twice gives two sets; replies keep their copied parent. `at` [x, y] (points, origin at the top-left of the displayed page, y down, as comment_add takes them) puts the centre of the copies' bounding box there; without it they keep their positions. Undoable.", + ) + .with(schema(json!({ "doc": doc(), "page": { "type": "integer", "minimum": 1 }, "xfdf": { "type": "string" }, "at": point() }), &["doc", "page", "xfdf"])), t( "doc_protect", "Protect with passwords", @@ -1339,31 +1380,79 @@ pub fn tools() -> Vec { )), t("js_enabled", "JavaScript on or off", "Preferences ▸ JavaScript ▸ Enable Acrobat JavaScript: set it with `enabled`, or read it. With JavaScript off, field scripts other than Acrobat's AF calls don't run.") .with(schema(json!({ "enabled": { "type": "boolean" } }), &[])), - t("ocr_recognize", "Recognize text (OCR)", "Scan & OCR ▸ Recognize text: render pages, read the words in them and add them as invisible text over the page image, so scanned pages become searchable and selectable (a searchable image; the image is not changed). Pages that already have text are skipped unless skip_text_pages is false; then pictures on those pages are read too, and recognised words that the page's own text already has (an earlier OCR layer included) are left out and counted as already_on_page. Returns each page's recognised text (left out when the document's security doesn't allow copying), word count or why it was skipped. Needs the OCR models (ocr_status). Undoable as one step.") + t("ocr_recognize", "Recognize text (OCR)", "Scan & OCR ▸ Recognize text: render pages, read the words in them and add them as invisible text over the page image, so scanned pages become searchable and selectable (a searchable image; the image is not changed). Pages that already have text are skipped unless skip_text_pages or force_ocr say otherwise; words overlapping existing text are omitted and counted as already_on_page. With output_mode \"editable\" nothing is applied: a NEW document of visible text at the recognised boxes is written to out (which must not be the source; empty pages stay blank). engine and strategy choose the readers (an engine that cannot run is an error named up front); the four preprocessing flags clean the raster first. region reads just that part of one page ([x0, y0, x1, y1] in points from the top-left of the displayed page). Returns each page's recognised text, word count or why it was skipped. Needs the engines (ocr_status). Searchable output is undoable as one step.") .cmd("ocr.recognize") .with(schema( json!({ "doc": doc(), "pages": pages("to recognise (default: all)"), "dpi": { "type": "number", "minimum": 72, "maximum": 600, "description": "Resolution pages are read at (default 300; a scanned page is read at most at its own resolution)." }, - "language": { "type": "string", "enum": ["en"], "description": "Document language (default en)." }, - "skip_text_pages": { "type": "boolean", "description": "Leave pages that already contain text alone (default true). false also reads pictures on such pages, without adding their text again." }, + "language": { "type": "string", "enum": language_enum(), "description": "Document language (default en)." }, + "engine": { "type": "string", "enum": ["auto", "ocrs", "tesseract"], "description": "Which engine reads the pages (default ocrs). auto: ocrs first and tesseract as the second engine, combined by strategy (only the engines that can run take part)." }, + "strategy": { "type": "string", "enum": ["primary", "confidence", "rover"], "description": "How two engines' readings combine: primary = the first engine alone; confidence = the second engine joins when the first reading's mean confidence is under 70 or unknown; rover = both always read, merged. Default: confidence with engine auto, primary otherwise." }, + "output_mode": { "type": "string", "enum": ["searchable", "editable"], "description": "searchable (default): invisible text over the pages of the open document. editable: a NEW _ocr-style file of visible text written to out; the source is not touched." }, + "out": { "type": "string", "description": "Where the editable output is written (required with output_mode editable; a new file: never the source path, never an existing file)." }, + "region": { "type": "array", "items": { "type": "number" }, "minItems": 4, "maxItems": 4, "description": "[x0, y0, x1, y1] in points from the top-left of the displayed page: read only that part. Needs exactly one page." }, + "skip_text_pages": { "type": "boolean", "description": "Leave pages that already contain text alone (default true)." }, + "skip_text_files": { "type": "boolean", "description": "Batch: leave whole files that already contain text alone (they come back skipped, not read)." }, + "force_ocr": { "type": "boolean", "description": "Read pages and files even when the skip options would leave them alone (default false)." }, + "auto_rotate": { "type": "boolean", "description": "Turn pages scanned sideways or upside down upright before reading (default false)." }, + "deskew": { "type": "boolean", "description": "Straighten skewed text lines before reading (default false)." }, + "denoise": { "type": "boolean", "description": "A 3×3 median filter against scan speckle (default false)." }, + "binarize": { "type": "boolean", "description": "Sauvola binarization: ink to black, paper to white (default false)." }, }), &["doc"], )), - t("ocr_recognize_files", "Recognize text in multiple files", "Scan & OCR ▸ Recognize text ▸ In multiple files: read every page of each PDF in paths and write the searchable result into folder under the same name (pages that already have text are left alone unless skip_text_pages is false, as in ocr_recognize). Two inputs that would write the same output file are refused before anything is read or written. Returns, per file, the output path, word count and skipped pages, or the error.") + t("ocr_words", "Words of a recognition (for review)", "The words a recognition finds, for inspection without the GUI: per page, each word's text, its box ([x, y, w, h] in points from the top-left of the displayed page), its confidence and band (high >= 90, medium 70–89, low < 70), which engine read it, and whether it is a suspect (low band). suspects counts the words a reviewer should look at first. Changes nothing on the document. retain_review returns a session-local handle for ocr_review_apply (one per document, at most eight; a new retained recognition replaces the old one). Needs the engines (ocr_status).") + .ro() + .with(schema( + json!({ + "doc": doc(), + "retain_review": { "type": "boolean" }, + "region": { "type": "array", "items": { "type": "number" }, "minItems": 4, "maxItems": 4 }, + "pages": pages("to read (default: all)"), + "dpi": { "type": "number", "minimum": 72, "maximum": 600 }, + "language": { "type": "string", "enum": language_enum() }, + "engine": { "type": "string", "enum": ["auto", "ocrs", "tesseract"] }, + "strategy": { "type": "string", "enum": ["primary", "confidence", "rover"] }, + "auto_rotate": { "type": "boolean" }, + "deskew": { "type": "boolean" }, + "denoise": { "type": "boolean" }, + "binarize": { "type": "boolean" }, + "skip_text_pages": { "type": "boolean", "description": "Leave pages that already contain text alone (default true)." }, + "force_ocr": { "type": "boolean", "description": "Read pages even when the skip options would leave them alone (default false)." }, + }), + &["doc"], + )), + t("ocr_review_apply", "Apply or discard reviewed OCR words", "Accept corrected recognition from ocr_words retain_review. Corrections use 1-based page/word positions and text only; empty text removes a word, omitted words keep their original text and boxes. The stored document guard refuses stale, foreign or consumed reviews. Searchable output is one undoable step; editable requires out and writes a new document (out must not exist yet; the review is kept when it does). discard releases the review without applying it. Input is capped at 65536 words and 4 MiB, never truncated.") + .cmd("ocr.correct") + .with(schema(json!({ "doc": doc(), "review": { "type": "integer", "minimum": 1 }, "discard": { "type": "boolean" }, "output_mode": { "type": "string", "enum": ["searchable", "editable"] }, "out": { "type": "string" }, + "corrections": { "type": "array", "maxItems": 65536, "items": { "type": "object", "additionalProperties": false, "properties": { "page": { "type": "integer", "minimum": 1 }, "word": { "type": "integer", "minimum": 1 }, "text": { "type": "string" } }, "required": ["page", "word", "text"] } } }), &["doc", "review"])), + t("ocr_dictionary", "Read or update an OCR review dictionary", "Read or add/remove words in an OCR Verify dictionary file (one case-insensitive word per UTF-8 line). Choose its per-language ocr-dictionary-.txt path. Paths honor root; updates are atomic. Refuses invalid words, over 65536 entries or over 4 MiB. No document changes.") + .destructive() + .cmd("ocr.correct") + .with(schema(json!({ "path": { "type": "string" }, "add": { "type": "array", "maxItems": 65536, "items": { "type": "string" } }, "remove": { "type": "array", "maxItems": 65536, "items": { "type": "string" } } }), &["path"])), + t("ocr_recognize_files", "Recognize text in multiple files", "Scan & OCR ▸ Recognize text ▸ In multiple files: read every page of each PDF in paths and write the searchable result into folder under the same name. skip_text_files leaves whole files that already contain text alone (they are their own skipped bucket, nothing is written); skip_text_pages leaves single text pages alone; force_ocr reads regardless of both. Every output name is checked before the first page is read: two paths sharing a file name (from different folders) are refused, and a file of that name already in folder aborts the batch, with the names in the error. Each written file carries a low_confidence note when words at or under 60 confidence sit on it (1-based sorted pages). Returns, per file, the output path, word count, skipped pages or the error, plus recognized/words/skipped_files totals. Needs the engines (ocr_status).") .cmd("ocr.recognize_batch") .with(schema( json!({ "paths": { "type": "array", "items": { "type": "string" }, "minItems": 1 }, "folder": { "type": "string" }, "dpi": { "type": "number", "minimum": 72, "maximum": 600 }, - "language": { "type": "string", "enum": ["en"] }, - "skip_text_pages": { "type": "boolean", "description": "Leave pages that already contain text alone (default true); see ocr_recognize." }, + "language": { "type": "string", "enum": language_enum() }, + "engine": { "type": "string", "enum": ["auto", "ocrs", "tesseract"] }, + "strategy": { "type": "string", "enum": ["primary", "confidence", "rover"] }, + "skip_text_pages": { "type": "boolean", "description": "Leave pages that already contain text alone (default true)." }, + "skip_text_files": { "type": "boolean", "description": "Leave whole files that already contain text alone (default false)." }, + "force_ocr": { "type": "boolean", "description": "Read even where the skip options would leave things alone (default false)." }, + "auto_rotate": { "type": "boolean" }, + "deskew": { "type": "boolean" }, + "denoise": { "type": "boolean" }, + "binarize": { "type": "boolean" }, }), &["paths", "folder"], )), - t("ocr_status", "OCR status", "Whether text recognition is available (its models are installed: release packages include them; a source build fetches them with `cargo xtask models`; PDFCRAFT_MODELS overrides), where it looks for them, and the languages it reads.") + t("ocr_status", "OCR status", "Whether text recognition is available, where it looks for models (release packages include them; a source build fetches them with `cargo xtask models`; PDFCRAFT_MODELS overrides), its languages, and the engines: ocrs (built in, models) and tesseract (an installed program, with its path).") .ro() .cmd("ocr.recognize") .with(schema(json!({}), &[])), @@ -1384,7 +1473,7 @@ pub fn tools() -> Vec { t( "fill_sign_add", "Fill & Sign: type text or place a mark", - "Fill in a form that has no fields, as Acrobat's Fill & Sign does: type text (`text`, default 10 pt; `font_size` 4–300 pt; optional `color` as #RRGGBB for text/date, default black), place a check, cross, dot or line, today's date (in Preferences ▸ Date format, see fill_sign_date_format, or `format`; `font_size` also applies), or a signature or initials (either `text` drawn in a script font, or `path` to a local PNG/JPEG image up to 4 MiB and 32 megapixels, scaled down to 4 megapixels, preserving transparency; with `scan: true`, `path` is instead a photo of a signature on paper, within the same limits: the signature is found, and the paper, shadows and table around it are removed, with `sensitivity` 0–100, default 50, picking up fainter ink when higher). `at` [x, y] is in points from the top-left of the page: text's top-left, mark's centre, signature's left edge centred vertically. Image signatures fit within 150 pt wide and 32 pt tall (24 pt for initials). Creates movable, undoable annotations. Typed text the standard fonts can't draw is saved and drawn as `?` (`warnings` in the result says so); a typed signature neither the script font nor its fallback can draw is refused (pass `path` instead).", + "Fill in a form that has no fields, as Acrobat's Fill & Sign does: type text (`text`, default 10 pt; `font_size` 4–300 pt; optional `color` as #RRGGBB for text/date, default black; `border` 0–12 pt around it, default none, in its colour or `border_color`), place a check, cross, dot or line, today's date (in Preferences ▸ Date format, see fill_sign_date_format, or `format`; `font_size` also applies), or a signature or initials (either `text` drawn in a script font, or `path` to a local PNG/JPEG image up to 4 MiB and 32 megapixels, scaled down to 4 megapixels, preserving transparency; with `scan: true`, `path` is instead a photo of a signature on paper, within the same limits: the signature is found, and the paper, shadows and table around it are removed, with `sensitivity` 0–100, default 50, picking up fainter ink when higher). `at` [x, y] is in points from the top-left of the page: text's top-left, mark's centre, signature's left edge centred vertically. Image signatures fit within 150 pt wide and 32 pt tall (24 pt for initials). Creates movable, undoable annotations. Typed text the standard fonts can't draw is saved and drawn as `?` (`warnings` in the result says so); a typed signature neither the script font nor its fallback can draw is refused (pass `path` instead).", ) .cmd("sign.fill.text") .with(schema( @@ -1396,6 +1485,9 @@ pub fn tools() -> Vec { "text": { "type": "string", "minLength": 1 }, "font_size": { "type": "number", "minimum": 4, "maximum": 300, "description": "For type text or date (default 10 pt)." }, "color": color(), + "border": { "type": "number", "minimum": 0, "maximum": 12, "description": "For type text or date: a border around it in points, in the text's colour (default 0, none)." }, + "border_color": { "type": "string", "description": "With border: its own colour, #RRGGBB or a colour name." }, + "border_shape": { "type": "string", "enum": ["rectangle", "oval", "circle"], "description": "With border, for type text or date: the border's shape (default rectangle); an oval or a circle goes around the text." }, "path": { "type": "string", "description": "PNG or JPEG for signature/initials; pass either path or text." }, "scan": { "type": "boolean", "description": "With path: scan a photo of a signature on paper (default false)." }, "sensitivity": { "type": "integer", "minimum": 0, "maximum": 100, "description": "With scan: how faint ink may be, 0–100 (default 50)." }, diff --git a/crates/automation/tests/it/action_failures.rs b/crates/automation/tests/it/action_failures.rs new file mode 100644 index 0000000000..b487103a21 --- /dev/null +++ b/crates/automation/tests/it/action_failures.rs @@ -0,0 +1,66 @@ +//! A step that fails fails its file: the file is reported with an error and nothing is written +//! for it. A step that finds nothing to do is still not a failure. + +use std::sync::Arc; + +use pdfcraft_automation::{Automation, Content}; +use pdfcraft_engine::Session; +use pdfcraft_engine::actions::{Action, Step, run_on}; +use serde_json::json; + +fn pdf() -> Vec { + Session::new().create_from_text("Original", "Original text").unwrap().as_ref().clone() +} + +fn one_step(step: Step) -> Action { + Action { name: "Custom".into(), description: String::new(), steps: vec![step], builtin: false } +} + +/// The standard fonts can't draw the character, so the watermark step fails and no file is produced. +#[test] +fn failing_watermark_step_fails_the_file_and_publishes_nothing() { + let r = run_on(&one_step(Step::AddWatermark("中".into())), "one.pdf", Arc::new(pdf()), |_, _| {}); + assert!(r.is_err(), "a failed step must fail its file: {r:?}"); +} + +/// A comment step on a document with no comments has nothing to do, which is not a failure. +#[test] +fn nothing_to_do_step_still_succeeds() { + let r = run_on(&one_step(Step::FlattenComments), "one.pdf", Arc::new(pdf()), |_, _| {}); + assert!(r.is_ok(), "a step with nothing to do is not a failure: {r:?}"); +} + +/// Through the tool: the failing file gets an error entry and no output, and the folder stays empty. +#[test] +fn action_run_marks_the_failing_file_as_error_without_output() { + let dir = tempfile::tempdir().unwrap(); + let input = dir.path().join("in"); + std::fs::create_dir_all(&input).unwrap(); + let in_file = input.join("one.pdf"); + std::fs::write(&in_file, pdf()).unwrap(); + let out = dir.path().join("out"); + let mut auto = Automation::new().with_root(dir.path()).unwrap(); + let reply = auto.call( + "action_run", + &json!({ + "paths": [in_file.to_string_lossy()], + "folder": out.to_string_lossy(), + "steps": [{ "step": "add_watermark", "arg": "中" }], + }), + ); + let report = match reply.unwrap().remove(0) { + Content::Json(value) => value, + other => panic!("expected a report: {other:?}"), + }; + let entry = &report["files"][0]; + assert!(entry["error"].is_string(), "{report}"); + assert!(entry.get("output").is_none(), "{report}"); + assert_eq!(std::fs::read_dir(&out).unwrap().count(), 0, "nothing is published for a failed file"); +} + +/// A removal step with nothing to remove keeps its existing note and succeeds. +#[test] +fn removal_step_with_nothing_to_remove_still_succeeds() { + let r = run_on(&one_step(Step::RemoveHiddenInformation), "one.pdf", Arc::new(pdf()), |_, _| {}); + assert!(r.is_ok(), "nothing to remove is not a failure: {r:?}"); +} diff --git a/crates/automation/tests/it/automation.rs b/crates/automation/tests/it/automation.rs index 6a0d254c71..bbbcef2528 100644 --- a/crates/automation/tests/it/automation.rs +++ b/crates/automation/tests/it/automation.rs @@ -843,10 +843,11 @@ fn arabic_ligature_actual_text_is_one_editable_word_through_save_reopen() { } /// Each of these writes to its required `path` and replaces an existing file there, so the MCP -/// annotations must not tell clients the call is read-only or harmless (#130). +/// annotations must not tell clients the call is read-only or harmless (#130). The OCR +/// dictionary's updates rewrite the file in place (lower-cased and sorted), so it counts too. #[test] fn file_writing_tools_are_not_read_only() { - for name in ["doc_export_data", "accessibility_report", "image_save"] { + for name in ["doc_export_data", "accessibility_report", "image_save", "ocr_dictionary"] { let t = tools().into_iter().find(|t| t.name == name).unwrap(); assert!(!t.read_only, "{name} writes a file but advertises read-only"); assert!(t.destructive, "{name} overwrites its path but advertises non-destructive"); @@ -1715,6 +1716,25 @@ fn mcp_default_lists_every_tool_and_has_no_meta_tools() { assert_eq!(rpc(&mut s, 3, "tools/call", json!({ "name": "tool_search" }))["error"]["code"], -32602); } +#[cfg(feature = "mcp")] +#[test] +/// `tools/list` advertises exactly the Search & Redact patterns the registry supports, in `pattern` +/// and by name in the description, so a schema-obeying client can select every one of them. +fn the_advertised_redact_mark_schema_offers_every_pattern() { + use pdfcraft_engine::REDACT_PATTERNS; + let registry: Vec<&str> = REDACT_PATTERNS.iter().map(|p| p.id()).collect(); + let mut s = McpServer::new(Automation::new()); + let list = rpc(&mut s, 1, "tools/list", json!({})); + let mark = list["result"]["tools"].as_array().unwrap().iter().find(|t| t["name"] == "redact_mark").expect("redact_mark is listed"); + let advertised: Vec<&str> = + mark["inputSchema"]["properties"]["pattern"]["enum"].as_array().unwrap().iter().map(|v| v.as_str().unwrap()).collect(); + assert_eq!(advertised, registry, "the advertised pattern enum must be the registry's ids"); + let description = mark["description"].as_str().unwrap(); + for id in ®istry { + assert!(description.contains(id), "the description must name {id}: {description}"); + } +} + #[cfg(feature = "mcp")] #[test] fn mcp_compact_lists_the_core_tools_and_two_meta_tools() { @@ -2135,6 +2155,104 @@ fn numbering_pages_through_tools() { assert!(matches!(a.call("page_number", &json!({ "doc": doc, "from": 1, "to": 1, "style": "klingon" })), Err(ToolError::InvalidArgs(_)))); } +/// Typed text and text boxes take an oval or a circle for their border through the tools; +/// comment_list reports it (a rectangle is not reported). Only typed text, dates and text boxes +/// have one, and only the three shapes. +#[test] +fn text_borders_take_an_oval_or_a_circle_through_the_tools() { + let dir = workdir("border-shape"); + let mut a = auto(&dir); + let doc = ok(&mut a, "doc_open", json!({ "path": "a.pdf" }))["doc"].as_u64().unwrap(); + ok( + &mut a, + "fill_sign_add", + json!({ "doc": doc, "page": 1, "type": "text", "at": [20, 40], "text": "12", "border": 1, "border_shape": "circle" }), + ); + ok( + &mut a, + "comment_add", + json!({ "doc": doc, "page": 1, "type": "textbox", "rect": [10, 200, 190, 240], "contents": "Hello", "width": 1, "border_shape": "Oval" }), + ); + let list = |a: &mut Automation| ok(a, "comment_list", json!({ "doc": doc, "page": 1 }))["comments"].as_array().unwrap().clone(); + let shapes: Vec = list(&mut a).iter().map(|c| c["border_shape"].clone()).collect(); + assert_eq!(shapes, [json!("circle"), json!("oval")]); + let typed = list(&mut a)[0].clone(); + // Snug around "12": the box no wider than the text needs, the circle as wide as that box. + let r: Vec = typed["rect"].as_array().unwrap().iter().map(|v| v.as_f64().unwrap()).collect(); + let w = pdfcraft_engine::annot_text::text_width("12", 10.0) + 10.0; + assert!((r[2] - r[0] - w).abs() < 0.05 && (r[3] - r[1] - w).abs() < 0.05, "{r:?}"); + ok(&mut a, "comment_edit", json!({ "doc": doc, "page": typed["page"], "index": typed["index"], "border_shape": "oval" })); + assert_eq!(list(&mut a)[0]["border_shape"], "oval"); + ok(&mut a, "comment_edit", json!({ "doc": doc, "page": typed["page"], "index": typed["index"], "border_shape": "rectangle" })); + assert!(list(&mut a)[0].get("border_shape").is_none(), "a rectangle is not reported"); + for (tool, args) in [ + ("fill_sign_add", json!({ "doc": doc, "page": 1, "type": "check", "at": [60, 60], "border_shape": "oval" })), + ("fill_sign_add", json!({ "doc": doc, "page": 1, "type": "text", "text": "7", "at": [60, 60], "border_shape": "circle" })), + ("comment_add", json!({ "doc": doc, "page": 1, "type": "rectangle", "rect": [80, 10, 120, 40], "border_shape": "oval" })), + ("comment_edit", json!({ "doc": doc, "page": typed["page"], "index": typed["index"], "border_shape": "star" })), + ] { + assert!(matches!(a.call(tool, &args), Err(ToolError::InvalidArgs(_))), "{args}"); + } + let callout = ok( + &mut a, + "comment_add", + json!({ "doc": doc, "page": 1, "type": "callout", "rect": [110, 100, 190, 140], "to": [40, 60], "contents": "Look" }), + ); + assert!(matches!( + a.call("comment_edit", &json!({ "doc": doc, "page": 1, "index": callout["comment"]["index"], "border_shape": "oval" })), + Err(ToolError::Failed(_)) + )); +} + +/// A rectangle's fill and a text box's text each take an opacity of their own through the tools +/// (the line or border keeps the comment's `opacity`); `opacity` sets the whole comment's again. +#[test] +fn comment_parts_take_opacities_of_their_own_through_the_tools() { + let dir = workdir("part-opacity"); + let mut a = auto(&dir); + let doc = ok(&mut a, "doc_open", json!({ "path": "a.pdf" }))["doc"].as_u64().unwrap(); + ok( + &mut a, + "comment_add", + json!({ "doc": doc, "page": 1, "type": "rectangle", "rect": [10, 10, 60, 40], "fill": "yellow", "fill_opacity": 0.25 }), + ); + ok( + &mut a, + "comment_add", + json!({ "doc": doc, "page": 1, "type": "textbox", "rect": [10, 200, 190, 240], "contents": "Hello", "fill": "#FFFF99", "width": 1, "fill_opacity": 0.2, "text_opacity": 1 }), + ); + let find = |a: &mut Automation, kind: &str| { + let list = ok(a, "comment_list", json!({ "doc": doc, "page": 1 })); + list["comments"].as_array().unwrap().iter().find(|c| c["type"] == kind).unwrap().clone() + }; + let rect = find(&mut a, "Square"); + assert_eq!((rect["opacity"].as_f64(), rect["fill_opacity"].as_f64(), rect.get("text_opacity")), (Some(1.0), Some(0.25), None)); + let tb = find(&mut a, "FreeText"); + assert_eq!((tb["opacity"].as_f64(), tb["fill_opacity"].as_f64(), tb["text_opacity"].as_f64()), (Some(1.0), Some(0.2), Some(1.0))); + // The fill changes, the text stays; an undo step. + ok(&mut a, "comment_edit", json!({ "doc": doc, "page": tb["page"], "index": tb["index"], "fill_opacity": 0.5 })); + let tb = find(&mut a, "FreeText"); + assert_eq!((tb["fill_opacity"].as_f64(), tb["text_opacity"].as_f64()), (Some(0.5), Some(1.0))); + assert_eq!(ok(&mut a, "edit_undo", json!({ "doc": doc }))["undone"], "Change comment properties"); + ok(&mut a, "edit_redo", json!({ "doc": doc })); + // The whole comment's opacity: everything at it again. + ok(&mut a, "comment_edit", json!({ "doc": doc, "page": rect["page"], "index": rect["index"], "opacity": 0.6 })); + let rect = find(&mut a, "Square"); + assert_eq!((rect["opacity"].as_f64(), rect["fill_opacity"].as_f64()), (Some(0.6), Some(0.6))); + // Only the parts a comment has, at 0–1. + for (tool, args) in [ + ("comment_add", json!({ "doc": doc, "page": 1, "type": "line", "from": [0, 0], "to": [50, 50], "fill_opacity": 0.5 })), + ("comment_add", json!({ "doc": doc, "page": 1, "type": "rectangle", "rect": [80, 10, 120, 40], "text_opacity": 0.5 })), + ("comment_edit", json!({ "doc": doc, "page": rect["page"], "index": rect["index"], "fill_opacity": 2 })), + ] { + assert!(matches!(a.call(tool, &args), Err(ToolError::InvalidArgs(_))), "{args}"); + } + assert!(matches!( + a.call("comment_edit", &json!({ "doc": doc, "page": rect["page"], "index": rect["index"], "text_opacity": 0.5 })), + Err(ToolError::Failed(_)) + )); +} + #[test] fn comments_through_tools() { let dir = workdir("comments"); @@ -2464,6 +2582,16 @@ fn copy_restricted_text_stays_in_the_document() { } let restyled = ok(&mut a, "text_edit", json!({ "doc": re, "page": 1, "paragraph": 1, "size": 30 })); assert!(!restyled.to_string().contains("Page"), "{restyled}"); + // A path that would carry the page's words OUT of the document — the editable output, or + // the review word list — is refused on a copy-restricted document (no engines needed). + match a.call("ocr_recognize", &json!({ "doc": re, "output_mode": "editable", "out": "copy.pdf" })) { + Err(ToolError::Failed(m)) => assert!(m.contains("don't allow copying"), "{m}"), + other => panic!("the editable output is refused: {other:?}"), + } + match a.call("ocr_words", &json!({ "doc": re })) { + Err(ToolError::Failed(m)) => assert!(m.contains("don't allow copying"), "{m}"), + other => panic!("ocr_words is refused: {other:?}"), + } if ok(&mut a, "ocr_status", json!({}))["available"] != true { eprintln!("skipped the OCR part: OCR models not installed"); return; @@ -4026,6 +4154,48 @@ fn fill_sign_text_and_date_colours_are_saved_and_validated() { } } +#[test] +fn fill_sign_text_border_is_saved_and_validated() { + let dir = workdir("fill-sign-text-border"); + let mut a = auto(&dir); + let doc = ok(&mut a, "doc_open", json!({ "path": "a.pdf" }))["doc"].as_u64().unwrap(); + ok(&mut a, "fill_sign_add", json!({ "doc": doc, "page": 1, "type": "text", "at": [20, 40], "text": "Plain" })); + ok(&mut a, "fill_sign_add", json!({ "doc": doc, "page": 1, "type": "text", "at": [20, 80], "text": "Plain", "border": 1.5 })); + let comments = ok(&mut a, "comment_list", json!({ "doc": doc })); + let width = |k: usize| { + let rect = comments["comments"][k]["rect"].as_array().unwrap(); + rect[2].as_f64().unwrap() - rect[0].as_f64().unwrap() + }; + assert!((width(1) - width(0) - 3.0).abs() < 1e-6, "1.5 pt on each side: {comments}"); + ok(&mut a, "doc_save", json!({ "doc": doc, "path": "framed.pdf" })); + let saved = std::fs::read(dir.join("framed.pdf")).unwrap(); + let pdf = pdfcraft_cos::Document::open(std::sync::Arc::new(saved)).unwrap(); + let page = pdfcraft_model::pages(&pdf).remove(0); + let annotations = pdf.resolve(page.dict.get(b"Annots").unwrap()); + let annotation = pdf.resolve(annotations.as_array().unwrap().get(1).unwrap()); + let bs = annotation.as_dict().unwrap().get(b"BS").unwrap().as_dict().unwrap().get(b"W").unwrap().as_f64().unwrap(); + assert_eq!(bs, 1.5, "saved annotation has the requested border"); + // Its own colour, then the text's again through comment_edit. + ok( + &mut a, + "fill_sign_add", + json!({ "doc": doc, "page": 1, "type": "text", "at": [20, 160], "text": "Red", "border": 1, "border_color": "#ff0000" }), + ); + let list = ok(&mut a, "comment_list", json!({ "doc": doc, "page": 1 })); + let red = list["comments"].as_array().unwrap().iter().find(|c| c["contents"] == "Red").unwrap()["index"].clone(); + ok(&mut a, "comment_edit", json!({ "doc": doc, "page": 1, "index": red, "border_color": "text" })); + assert!( + a.call("fill_sign_add", &json!({ "doc": doc, "page": 1, "type": "text", "at": [20, 200], "text": "No", "border_color": "red" })).is_err(), + "no border" + ); + for (kind, border) in [("text", -1.0), ("text", 13.0), ("check", 1.0)] { + assert!(matches!( + a.call("fill_sign_add", &json!({ "doc": doc, "page": 1, "type": kind, "at": [20, 120], "text": "No", "border": border })), + Err(ToolError::InvalidArgs(_)) + )); + } +} + #[test] fn image_signatures_through_tools_preserve_transparency_and_survive_save() { let dir = workdir("image-signatures"); @@ -4670,6 +4840,35 @@ fn redacting_italian_international_slash_numbers_through_tools() { std::fs::remove_dir_all(dir).unwrap(); } +#[test] +/// A client obeying the advertised schema can select iban, and the mark made through the tool +/// covers the spaced number and nothing else. +fn redacting_an_iban_through_tools() { + let table = tools(); + let advertised: Vec<&str> = table.iter().find(|t| t.name == "redact_mark").unwrap().input_schema["properties"]["pattern"]["enum"] + .as_array() + .unwrap() + .iter() + .map(|v| v.as_str().unwrap()) + .collect(); + assert!(advertised.contains(&"iban"), "the advertised redact_mark schema must offer iban: {advertised:?}"); + let dir = workdir("redact-iban"); + std::fs::write(dir.join("invoice.txt"), "Pay DE89 3704 0044 0532 0130 00 today\nAccount 12345678 is ours\nTotal due").unwrap(); + let mut a = auto(&dir); + let doc = ok(&mut a, "doc_create", json!({ "from": "text", "path": "invoice.txt" }))["doc"].as_u64().unwrap(); + let marked = ok(&mut a, "redact_mark", json!({ "doc": doc, "pattern": "iban" })); + assert_eq!(marked["marked"], 1, "the spaced German sample IBAN needs one mark"); + assert!(page_text(&mut a, doc)[0].contains("DE89 3704 0044 0532 0130 00"), "marks alone remove nothing"); + assert_eq!(ok(&mut a, "redact_apply", json!({ "doc": doc }))["applied"], 1); + ok(&mut a, "doc_save", json!({ "doc": doc, "path": "redacted.pdf" })); + let reopened = ok(&mut a, "doc_open", json!({ "path": "redacted.pdf" }))["doc"].as_u64().unwrap(); + let text = &page_text(&mut a, reopened)[0]; + assert!(!text.contains("DE89") && !text.contains("0532"), "{text}"); + assert!(text.lines().any(|line| line.trim() == "Pay"), "only the label before the number remains: {text}"); + assert!(text.contains("Account 12345678") && text.contains("Total due"), "text without an IBAN remains: {text}"); + std::fs::remove_dir_all(dir).unwrap(); +} + /// One page with the text "Secret 1234" and a Redact annotation that has neither a usable /// QuadPoints array nor a Rect, so there is no area to redact. fn redact_pdf_with_unreadable_mark() -> Vec { @@ -6494,6 +6693,44 @@ fn drawing_comments_through_tools() { assert!(matches!(png[0], Content::Png { .. })); } +/// comment_add `ortho`, Shift's hold while drawing: a line's end is held level or plumb with its +/// start, and each corner of connected lines or a polygon with the corner before. +#[test] +fn lines_and_corners_are_held_level_or_plumb_through_the_tool() { + let dir = workdir("ortho"); + let mut a = auto(&dir); + let doc = ok(&mut a, "doc_open", json!({ "path": "a.pdf" }))["doc"].as_u64().unwrap(); + for args in [ + json!({ "type": "line", "from": [20, 40], "to": [120, 52], "ortho": true }), + json!({ "type": "arrow", "from": [180, 40], "to": [170, 140], "ortho": true }), + json!({ "type": "polyline", "points": [[20, 200], [90, 210], [95, 260], [130, 250]], "ortho": true }), + json!({ "type": "line", "from": [20, 280], "to": [120, 290] }), + ] { + let mut args = args; + args.as_object_mut().unwrap().extend([("doc".to_string(), json!(doc)), ("page".to_string(), json!(1))]); + ok(&mut a, "comment_add", args); + } + let list = ok(&mut a, "comment_list", json!({ "doc": doc, "page": 1 })); + // In the order added: the list isn't sorted by index. + let mut listed = list["comments"].as_array().unwrap().clone(); + listed.sort_by_key(|c| c["index"].as_u64()); + let points: Vec> = + listed.iter().map(|c| c["points"].as_array().unwrap().iter().map(|p| [p[0].as_f64().unwrap(), p[1].as_f64().unwrap()]).collect()).collect(); + let want: [&[[f64; 2]]; 4] = [ + &[[20.0, 40.0], [120.0, 40.0]], + &[[180.0, 40.0], [180.0, 140.0]], + &[[20.0, 200.0], [90.0, 200.0], [90.0, 260.0], [130.0, 260.0]], + &[[20.0, 280.0], [120.0, 290.0]], + ]; + assert_eq!(points.len(), want.len(), "{points:?}"); + for (got, want) in points.iter().zip(want) { + assert_eq!(got.len(), want.len(), "{got:?}"); + assert!(got.iter().zip(want).all(|(g, w)| (g[0] - w[0]).abs() < 0.01 && (g[1] - w[1]).abs() < 0.01), "{got:?} for {want:?}"); + } + let refused = a.call("comment_add", &json!({ "doc": doc, "page": 1, "type": "rectangle", "rect": [10, 10, 50, 50], "ortho": true })); + assert!(matches!(refused, Err(ToolError::InvalidArgs(_))), "ortho is for lines and corners: {refused:?}"); +} + #[test] fn signing_with_an_image_typed_or_drawn_graphic_through_tools() { let dir = workdir("signing-graphic"); @@ -7277,6 +7514,8 @@ fn ocr_tools_make_a_scan_searchable() { let mut a = auto(&dir); let status = ok(&mut a, "ocr_status", json!({})); assert_eq!(status["languages"][0]["code"], "en"); + assert_eq!(status["engines"][0]["id"], "ocrs", "{status}"); + assert!(status["engines"][1]["id"] == "tesseract" && status["engines"][1]["available"].is_boolean(), "{status}"); if status["available"] != true { eprintln!("skipped: OCR models not installed"); return; @@ -7291,6 +7530,64 @@ fn ocr_tools_make_a_scan_searchable() { let again = ok(&mut a, "ocr_recognize", json!({ "doc": scan, "pages": [1] })); assert!(again["pages"][0]["skipped"].is_string(), "{again}"); assert!(matches!(a.call("ocr_recognize", &json!({ "doc": scan, "language": "xx" })), Err(ToolError::InvalidArgs(_)))); + // An engine that cannot run is named up front, before anything is read. + if status["engines"][1]["available"] != true { + let why = a.call("ocr_recognize", &json!({ "doc": scan, "engine": "tesseract", "skip_text_pages": false })).unwrap_err(); + assert!(matches!(why, ToolError::Failed(_)), "{why}"); + assert!(why.to_string().contains("tesseract"), "{why}"); + } + // ocr_words: the recognition's words with confidence, band and suspects, changing nothing. + // ocrs reports no confidences, so `auto` + a confidence merge is asked for when the second + // engine is there to supply them; without it confidence and band are honestly null. + ok(&mut a, "doc_close", json!({ "doc": scan, "discard_changes": true })); + let scan = ok(&mut a, "doc_create", json!({ "from": "images", "paths": [png.to_string_lossy()] }))["doc"].as_u64().unwrap(); + let mut args = json!({ "doc": scan }); + if status["engines"][1]["available"] == true { + args["engine"] = json!("auto"); + args["strategy"] = json!("confidence"); + } + let words = ok(&mut a, "ocr_words", args); + assert!(words["words"].as_u64().unwrap() >= 4, "{words}"); + let first = &words["pages"][0]["words"][0]; + assert!(first["text"].is_string() && first["box"].as_array().is_some_and(|b| b.len() == 4), "{words}"); + if status["engines"][1]["available"] == true { + let with_confidence = words["pages"][0]["words"] + .as_array() + .expect("words") + .iter() + .filter(|w| w["confidence"].is_number() && w["band"].as_str().is_some()) + .count(); + assert!(with_confidence >= 4, "the second engine's confidences arrive: {words}"); + } else { + assert!(first["confidence"].is_null() && first["band"].is_null() && first["suspect"] == false, "{words}"); + } + assert!(a.call("edit_undo", &json!({ "doc": scan })).is_err(), "ocr_words changes nothing, so there is no undo"); +} + +/// An editable-text recognition writes a NEW file of visible text, never the source. +#[test] +fn ocr_recognize_editable_output_writes_visible_text() { + let dir = workdir("ocr-editable"); + let mut a = auto(&dir); + if ok(&mut a, "ocr_status", json!({}))["available"] != true { + eprintln!("skipped: OCR models not installed"); + return; + } + let text = ok(&mut a, "doc_create", json!({ "from": "text", "text": "Editable output words" }))["doc"].as_u64().unwrap(); + ok(&mut a, "doc_export_images", json!({ "doc": text, "folder": "scan", "dpi": 150, "pages": [1] })); + let png = std::fs::read_dir(dir.join("scan")).unwrap().next().unwrap().unwrap().path(); + let scan = ok(&mut a, "doc_create", json!({ "from": "images", "paths": [png.to_string_lossy()] }))["doc"].as_u64().unwrap(); + ok(&mut a, "doc_save", json!({ "doc": scan, "path": "src/scan.pdf" })); + // The output never lands on the source. + let why = a.call("ocr_recognize", &json!({ "doc": scan, "pages": [1], "output_mode": "editable", "out": "src/scan.pdf" })).unwrap_err(); + assert!(why.to_string().contains("source"), "{why}"); + let r = ok(&mut a, "ocr_recognize", json!({ "doc": scan, "pages": [1], "output_mode": "editable", "out": "out/ocr.pdf" })); + assert!(r["words"].as_u64().unwrap() >= 3, "{r}"); + let ocr = ok(&mut a, "doc_open", json!({ "path": "out/ocr.pdf" }))["doc"].as_u64().unwrap(); + // The text is visible (the engine may misread a letter at this dpi — look for a word that + // survives). + let found = ok(&mut a, "text_find", json!({ "doc": ocr, "query": "output" })); + assert!(found["count"].as_u64() >= Some(1), "the new file's text is visible: {found}"); } /// #1028: `skip_text_pages: false` reads a picture on a page that has its own text, and the @@ -7333,6 +7630,46 @@ fn ocr_recognize_files_refuses_paths_outside_the_root() { assert!(!dir.join("out").exists(), "nothing was started"); } +/// Two inputs of one file name from different folders would write the same output in the +/// batch folder: the batch is refused up front, with or without the OCR engines, naming the +/// file, and nothing is written. +#[test] +fn ocr_recognize_files_refuses_inputs_that_share_a_file_name() { + let dir = workdir("ocr-files-same-name"); + let mut a = auto(&dir); + let doc = ok(&mut a, "doc_open", json!({ "path": "a.pdf" }))["doc"].as_u64().unwrap(); + ok(&mut a, "doc_save", json!({ "doc": doc, "path": "one/scan.pdf" })); + ok(&mut a, "doc_save", json!({ "doc": doc, "path": "two/scan.pdf" })); + let r = a.call("ocr_recognize_files", &json!({ "paths": ["one/scan.pdf", "two/scan.pdf"], "folder": "out" })); + assert!(matches!(&r, Err(ToolError::InvalidArgs(m)) if m.contains("scan.pdf") && m.contains("overwrite")), "{r:?}"); + assert!(std::fs::read_dir(dir.join("out")).map_or(true, |mut d| d.next().is_none()), "nothing was written"); +} + +/// `out` belongs to the editable output. A searchable run (the default) writes into the open +/// document, so an `out` is refused rather than silently ignored, with or without the engines. +#[test] +fn ocr_recognize_refuses_an_out_that_nothing_would_use() { + let dir = workdir("ocr-out-ignored"); + let mut a = auto(&dir); + let doc = ok(&mut a, "doc_open", json!({ "path": "a.pdf" }))["doc"].as_u64().unwrap(); + let r = a.call("ocr_recognize", &json!({ "doc": doc, "out": "../outside.pdf" })); + assert!(matches!(&r, Err(ToolError::InvalidArgs(m)) if m.contains("editable")), "{r:?}"); + assert!(!dir.join("../outside.pdf").exists()); +} + +/// The editable output is a NEW file: an existing `out` is refused before anything runs (with +/// or without the engines), and the file is left as it was. +#[test] +fn ocr_recognize_editable_output_never_replaces_an_existing_file() { + let dir = workdir("ocr-editable-exists"); + let mut a = auto(&dir); + let doc = ok(&mut a, "doc_open", json!({ "path": "a.pdf" }))["doc"].as_u64().unwrap(); + std::fs::write(dir.join("taken.pdf"), b"keep me").unwrap(); + let r = a.call("ocr_recognize", &json!({ "doc": doc, "output_mode": "editable", "out": "taken.pdf" })); + assert!(matches!(&r, Err(e) if e.to_string().contains("already exists")), "{r:?}"); + assert_eq!(std::fs::read(dir.join("taken.pdf")).unwrap(), b"keep me"); +} + #[test] fn ocr_recognize_files_writes_searchable_copies() { let dir = workdir("ocr-files"); @@ -7346,9 +7683,22 @@ fn ocr_recognize_files_writes_searchable_copies() { let png = std::fs::read_dir(dir.join("scan")).unwrap().next().unwrap().unwrap().path(); let scan = ok(&mut a, "doc_create", json!({ "from": "images", "paths": [png.to_string_lossy()] }))["doc"].as_u64().unwrap(); ok(&mut a, "doc_save", json!({ "doc": scan, "path": "in/scan.pdf" })); + // A file that already has text: the skip-files option passes it over as its own bucket. + let typed = ok(&mut a, "doc_create", json!({ "from": "text", "text": "Already typed" }))["doc"].as_u64().unwrap(); + ok(&mut a, "doc_save", json!({ "doc": typed, "path": "in/typed.pdf" })); + // Collision pre-flight: the existing out/scan.pdf (written below) stops a rerun. let r = ok(&mut a, "ocr_recognize_files", json!({ "paths": ["in/scan.pdf", "missing.pdf"], "folder": "out" })); assert!(r["files"][0]["words"].as_u64().unwrap() >= 3, "{r}"); assert!(r["files"][1]["error"].is_string(), "{r}"); + let why = a.call("ocr_recognize_files", &json!({ "paths": ["in/scan.pdf"], "folder": "out" })).unwrap_err(); + assert!(matches!(why, ToolError::Failed(_)), "{why}"); + assert!(why.to_string().contains("scan.pdf"), "{why}"); + // The skip-files bucket and the low-confidence note. + let r = ok(&mut a, "ocr_recognize_files", json!({ "paths": ["in/typed.pdf", "in/scan.pdf"], "folder": "out2", "skip_text_files": true })); + assert_eq!(r["skipped_files"].as_u64(), Some(1), "{r}"); + assert!(r["files"][0]["skipped"].is_string(), "{r}"); + assert_eq!(r["recognized"].as_u64(), Some(1), "{r}"); + assert!(r["files"][1]["output"].is_string(), "{r}"); let out = ok(&mut a, "doc_open", json!({ "path": "out/scan.pdf" }))["doc"].as_u64().unwrap(); let found = ok(&mut a, "text_find", json!({ "doc": out, "query": "recognition" })); assert!(found.to_string().contains("\"page\""), "{found}"); @@ -7358,18 +7708,6 @@ fn ocr_recognize_files_writes_searchable_copies() { /// the second output replaces the first while both results report success. The batch is refused /// up front, naming the file, before the folder is created, anything is read or the OCR engines /// load, so the outcome is the same with or without the models installed. -#[test] -fn ocr_recognize_files_refuses_inputs_that_share_a_file_name() { - let dir = workdir("ocr-files-same-name"); - let mut a = auto(&dir); - let doc = ok(&mut a, "doc_open", json!({ "path": "a.pdf" }))["doc"].as_u64().unwrap(); - ok(&mut a, "doc_save", json!({ "doc": doc, "path": "one/scan.pdf" })); - ok(&mut a, "doc_save", json!({ "doc": doc, "path": "two/scan.pdf" })); - let r = a.call("ocr_recognize_files", &json!({ "paths": ["one/scan.pdf", "two/scan.pdf"], "folder": "out" })); - assert!(matches!(&r, Err(ToolError::InvalidArgs(m)) if m.contains("scan.pdf")), "{r:?}"); - assert!(!dir.join("out").exists(), "nothing was started: the output folder was not created"); -} - /// File names are compared without regard to case on Windows and macOS (`scan.pdf` and `Scan.PDF` /// are one file there), and exactly elsewhere, where they are two files and the batch is not /// refused. @@ -10583,6 +10921,162 @@ fn simple_rule_scan_drawn(content: &[u8]) -> Vec { write_full(&doc, &SaveOptions::default()).unwrap() } +/// Reviewing headlessly: corrections keep the boxes, a stale or foreign review is refused, and +/// applying consumes the handle (the pages already accepted were applied once). +#[test] +fn ocr_review_corrections_keep_boxes_are_guarded_and_apply_once() { + fn render(a: &mut Automation, doc: u64) -> Vec { + let mut result = a.call("page_render", &json!({ "doc": doc, "page": 1, "dpi": 72 })).unwrap(); + match result.remove(0) { + Content::Png { data, .. } => data, + other => panic!("expected a rendered page, got {other:?}"), + } + } + let dir = workdir("ocr-review"); + let mut a = auto(&dir); + if ok(&mut a, "ocr_status", json!({}))["available"] != true { + eprintln!("skipped: OCR models not installed"); + return; + } + let text = ok(&mut a, "doc_create", json!({ "from": "text", "text": "Review these original words" }))["doc"].as_u64().unwrap(); + ok(&mut a, "doc_export_images", json!({ "doc": text, "folder": "scan", "dpi": 150, "pages": [1] })); + let png = std::fs::read_dir(dir.join("scan")).unwrap().next().unwrap().unwrap().path(); + let scan = ok(&mut a, "doc_create", json!({ "from": "images", "paths": [png.to_string_lossy()] }))["doc"].as_u64().unwrap(); + let before = render(&mut a, scan); + let found = ok(&mut a, "ocr_words", json!({ "doc": scan, "retain_review": true })); + assert!(found["words"].as_u64().unwrap() >= 3, "{found}"); + let review = found["review"].as_u64().unwrap(); + assert!(page_text(&mut a, scan).iter().all(String::is_empty)); + for args in [ + json!({ "doc": text, "review": review }), + json!({ "doc": scan, "review": review, "corrections": [{"page":1,"word":999999,"text":"bad"}] }), + json!({ "doc": scan, "review": review, "corrections": [{"page":1,"word":1,"text":"bad","origin":[0,0]}] }), + json!({ "doc": scan, "review": review, "corrections": [{"page":1,"word":1,"text":"a".repeat(4*1024*1024+1)}] }), + json!({ "doc": scan, "review": review, "corrections": [{"page":1,"word":1,"text":"a"},{"page":1,"word":1,"text":"b"}] }), + ] { + assert!(a.call("ocr_review_apply", &args).is_err()); + assert!(page_text(&mut a, scan).iter().all(String::is_empty)); + } + let result = ok( + &mut a, + "ocr_review_apply", + json!({ "doc": scan, "review": review, "corrections": [{"page":1,"word":1,"text":"日本語"},{"page":1,"word":2,"text":""}] }), + ); + assert!(result["applied"].as_u64().unwrap() >= 2); + let extracted = page_text(&mut a, scan).join("\n"); + assert!(extracted.contains("日本語"), "{extracted}"); + assert_eq!(render(&mut a, scan), before, "corrected text remains invisible at its original geometry"); + assert!(a.call("ocr_review_apply", &json!({ "doc": scan, "review": review })).is_err(), "consumed reviews cannot be replayed"); + ok(&mut a, "edit_undo", json!({ "doc": scan })); + assert!(page_text(&mut a, scan).iter().all(String::is_empty)); + assert!(a.call("edit_undo", &json!({ "doc": scan })).is_err(), "review acceptance is one undo step"); + + let found = ok(&mut a, "ocr_words", json!({ "doc": scan, "retain_review": true })); + let stale = found["review"].as_u64().unwrap(); + ok(&mut a, "page_rotate", json!({ "doc": scan, "pages": [1], "degrees": 90 })); + let error = a.call("ocr_review_apply", &json!({ "doc": scan, "review": stale })).unwrap_err().to_string(); + assert!(error.contains("changed since recognition"), "{error}"); + assert!(page_text(&mut a, scan).iter().all(String::is_empty)); + ok(&mut a, "ocr_review_apply", json!({ "doc": scan, "review": stale, "discard": true })); + assert!(a.call("ocr_review_apply", &json!({ "doc": scan, "review": stale })).is_err()); + ok(&mut a, "edit_undo", json!({ "doc": scan })); + + let first = ok(&mut a, "ocr_words", json!({ "doc": scan, "retain_review": true }))["review"].as_u64().unwrap(); + let second = ok(&mut a, "ocr_words", json!({ "doc": scan, "retain_review": true }))["review"].as_u64().unwrap(); + assert_ne!(first, second); + assert!(a.call("ocr_review_apply", &json!({ "doc": scan, "review": first })).is_err()); + ok( + &mut a, + "ocr_review_apply", + json!({ "doc": scan, "review": second, "output_mode": "editable", "out": "reviewed.pdf", "corrections": [{"page":1,"word":1,"text":"Corrected"}] }), + ); + assert!(page_text(&mut a, scan).iter().all(String::is_empty)); + let output = ok(&mut a, "doc_open", json!({ "path": "reviewed.pdf" }))["doc"].as_u64().unwrap(); + assert!(page_text(&mut a, output).join("\n").contains("Corrected")); + // The editable output is a new file: an existing one is refused and the review is kept. + let third = ok(&mut a, "ocr_words", json!({ "doc": scan, "retain_review": true }))["review"].as_u64().unwrap(); + let again = a.call("ocr_review_apply", &json!({ "doc": scan, "review": third, "output_mode": "editable", "out": "reviewed.pdf" })); + assert!(matches!(&again, Err(e) if e.to_string().contains("already exists")), "{again:?}"); + ok(&mut a, "ocr_review_apply", json!({ "doc": scan, "review": third, "discard": true })); +} + +#[test] +fn ocr_dictionary_updates_are_atomic_bounded_and_confined() { + let dir = workdir("ocr-dictionary"); + let mut a = auto(&dir); + let path = "ocr-dictionary-en.txt"; + let out = ok(&mut a, "ocr_dictionary", json!({ "path": path, "add": ["Quartz", "quartz", "日本語"] })); + assert_eq!(out["count"], 2); + assert_eq!(pdfcraft_engine::ocr::dictionary::words(&std::fs::read_to_string(dir.join(path)).unwrap()).unwrap().len(), 2); + let before = std::fs::read(dir.join(path)).unwrap(); + for args in [ + json!({ "path": path, "add": ["a\nb"] }), + json!({ "path": path, "add": ["x".repeat(1025)] }), + json!({ "path": path, "add": ["İ".repeat(512)] }), + json!({ "path": path, "add": vec!["x"; 65537] }), + json!({ "path": "../outside-ocr-dictionary.txt", "add": ["x"] }), + ] { + assert!(a.call("ocr_dictionary", &args).is_err()); + } + assert_eq!(std::fs::read(dir.join(path)).unwrap(), before); + assert_eq!(ok(&mut a, "ocr_dictionary", json!({ "path": path, "remove": ["QUARTZ"] }))["words"], json!(["日本語"])); + assert_eq!(ok(&mut a, "ocr_dictionary", json!({ "path": path }))["count"], 1); + std::fs::write(dir.join("ocr-dictionary-large.txt"), vec![b'a'; 4 * 1024 * 1024 + 1]).unwrap(); + let too_big = a.call("ocr_dictionary", &json!({ "path": "ocr-dictionary-large.txt", "add": ["x"] })).unwrap_err().to_string(); + assert!(!too_big.contains("must name a dictionary file"), "refused for its size, not its name: {too_big}"); + assert_eq!(std::fs::metadata(dir.join("ocr-dictionary-large.txt")).unwrap().len(), 4 * 1024 * 1024 + 1); +} + +/// The tool rewrites what it is pointed at (lower-cased, sorted), so it only takes dictionary file +/// names: another small text file under the root is neither read nor changed. +#[test] +fn ocr_dictionary_refuses_files_that_are_not_dictionaries() { + let dir = workdir("ocr-dictionary-names"); + let mut a = auto(&dir); + let env = b"TOKEN=Zebra +APPLE=1 +"; + for name in [".env", "notes.txt", "ocr-dictionary-en.md", "ocr-dictionary-e n.txt", "sub/readme.txt"] { + if let Some(parent) = std::path::Path::new(name).parent() { + std::fs::create_dir_all(dir.join(parent)).unwrap(); + } + std::fs::write(dir.join(name), env).unwrap(); + for args in [json!({ "path": name }), json!({ "path": name, "add": [] }), json!({ "path": name, "add": ["x"] })] { + let err = a.call("ocr_dictionary", &args).unwrap_err().to_string(); + assert!(err.contains("must name a dictionary file"), "{name} {args}: {err}"); + } + assert_eq!(std::fs::read(dir.join(name)).unwrap(), env, "{name} is untouched"); + } +} + +#[test] +fn ocr_retained_reviews_have_eight_document_cap_and_close_releases_slot() { + let dir = workdir("ocr-review-cap"); + let mut a = auto(&dir); + if ok(&mut a, "ocr_status", json!({}))["available"] != true { + eprintln!("skipped: OCR models not installed"); + return; + } + let mut docs = Vec::new(); + let mut handles = Vec::new(); + for _ in 0..9 { + let doc = ok(&mut a, "doc_create", json!({"from":"text", "text":"Already recognized text"}))["doc"].as_u64().unwrap(); + docs.push(doc); + } + for doc in docs.iter().take(8) { + handles.push(ok(&mut a, "ocr_words", json!({"doc":doc,"retain_review":true}))["review"].as_u64().unwrap()); + } + let error = a.call("ocr_words", &json!({"doc":docs[8],"retain_review":true})).unwrap_err().to_string(); + assert!(error.contains("at most 8"), "{error}"); + let replacement = ok(&mut a, "ocr_words", json!({"doc":docs[0],"retain_review":true}))["review"].as_u64().unwrap(); + assert_ne!(replacement, handles[0]); + assert!(a.call("ocr_review_apply", &json!({"doc":docs[0],"review":handles[0],"discard":true})).is_err()); + ok(&mut a, "doc_close", json!({"doc":docs[0],"discard_changes":true})); + assert!(a.call("ocr_review_apply", &json!({"doc":docs[0],"review":replacement})).is_err()); + let final_handle = ok(&mut a, "ocr_words", json!({"doc":docs[8],"retain_review":true}))["review"].as_u64().unwrap(); + ok(&mut a, "ocr_review_apply", json!({"doc":docs[8],"review":final_handle,"discard":true})); +} + #[test] fn editor_crop_group_move_and_arrange_survive_added_item_deletion_through_tools() { let dir = workdir("editor-crop-group-arrange"); @@ -10927,3 +11421,49 @@ fn a_bad_bookmark_tree_is_refused_whole_and_names_the_node() { assert!(!out.exists()); assert_eq!(ok(&mut a, "bookmark_list", json!({ "doc": doc }))["bookmarks"], json!([])); } + +/// Copy and paste comments between documents through the tools: the copies carry their replies, +/// land on the asked-for page under their own names (a second paste gives a second set), and a +/// plain text is refused. +#[test] +fn comments_copy_and_paste_between_documents_through_tools() { + let dir = workdir("comments-clipboard"); + let mut a = auto(&dir); + let src = ok(&mut a, "doc_open", json!({ "path": "a.pdf" }))["doc"].as_u64().unwrap(); + ok(&mut a, "comment_add", json!({ "doc": src, "page": 2, "type": "note", "at": [30, 30], "contents": "Please review", "author": "Ada" })); + ok(&mut a, "comment_add", json!({ "doc": src, "page": 2, "type": "rectangle", "rect": [20, 20, 80, 60], "contents": "Box" })); + ok(&mut a, "comment_reply", json!({ "doc": src, "page": 2, "index": 1, "text": "Done", "author": "Bob" })); + // Positions as comment_list reports them (a note's pop-up takes a position of its own). + let listed = ok(&mut a, "comment_list", json!({ "doc": src, "page": 2 })); + let pairs: Vec = listed["comments"].as_array().unwrap().iter().map(|c| json!([c["page"], c["index"]])).collect(); + assert_eq!(pairs.len(), 2, "{listed}"); + let copied = ok(&mut a, "comments_copy", json!({ "doc": src, "comments": pairs })); + assert_eq!(copied["comments"], 2); + let xfdf = copied["xfdf"].as_str().unwrap().to_owned(); + assert!(xfdf.contains("inreplyto=") && xfdf.contains("> = + placed["comments"].as_array().unwrap().iter().map(|c| c["rect"].as_array().unwrap().iter().map(|v| v.as_f64().unwrap()).collect()).collect(); + let (x0, y0, x1, y1) = + rects.iter().fold((f64::MAX, f64::MAX, f64::MIN, f64::MIN), |(a, b, c, d), r| (a.min(r[0]), b.min(r[1]), c.max(r[2]), d.max(r[3]))); + assert!(((x0 + x1) / 2.0 - 100.0).abs() < 1.0 && ((y0 + y1) / 2.0 - 150.0).abs() < 1.0, "centred at [100, 150]: {rects:?}"); + assert!(matches!(a.call("comments_paste", &json!({ "doc": dst, "page": 1, "xfdf": "hello" })), Err(ToolError::InvalidArgs(_)))); + assert!(a.call("comments_copy", &json!({ "doc": src, "comments": [[9, 9]] })).is_err(), "no such comment"); + assert!(matches!(a.call("comments_copy", &json!({ "doc": src, "comments": [[2]] })), Err(ToolError::InvalidArgs(_)))); + assert_eq!(ok(&mut a, "comment_list", json!({ "doc": src }))["comments"].as_array().unwrap().len(), 2, "the source is untouched"); +} diff --git a/crates/automation/tests/it/batch_failures.rs b/crates/automation/tests/it/batch_failures.rs new file mode 100644 index 0000000000..f993d85eab --- /dev/null +++ b/crates/automation/tests/it/batch_failures.rs @@ -0,0 +1,89 @@ +//! A batch run that fails a file publishes only the completed outputs, and a +//! publish the file system refuses publishes nothing. + +use pdfcraft_automation::{Automation, Content}; +use pdfcraft_engine::Session; +use serde_json::{Value, json}; + +fn result(auto: &mut Automation, args: Value) -> Value { + match auto.call("doc_batch", &args).unwrap().remove(0) { + Content::Json(value) => value, + _ => panic!("expected a report"), + } +} + +fn pdf() -> Vec { + Session::new().create_from_text("Original", "Original text").unwrap().as_ref().clone() +} + +/// Sets a folder's permission bits. +#[cfg(unix)] +fn set_mode(path: &std::path::Path, mode: u32) { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(path, std::fs::Permissions::from_mode(mode)).unwrap(); +} + +/// Puts back the write permission the temporary folder needs before it is removed. +#[cfg(unix)] +struct RestoreMode(std::path::PathBuf); + +#[cfg(unix)] +impl Drop for RestoreMode { + fn drop(&mut self) { + use std::os::unix::fs::PermissionsExt; + let _ = std::fs::set_permissions(&self.0, std::fs::Permissions::from_mode(0o755)); + } +} + +#[test] +fn failed_inputs_publish_only_completed_outputs() { + let dir = tempfile::tempdir().unwrap(); + std::fs::create_dir(dir.path().join("input")).unwrap(); + std::fs::write(dir.path().join("input/good.pdf"), pdf()).unwrap(); + std::fs::write(dir.path().join("input/bad.pdf"), "not a pdf").unwrap(); + let mut auto = Automation::new().with_root(dir.path()).unwrap(); + let report = result(&mut auto, json!({"paths":["input"],"steps":["optimize"],"out_dir":"out","recursive":false})); + assert_eq!(report["completed"], 1, "{report}"); + assert_eq!(report["failed"], 1, "{report}"); + let files = report["files"].as_array().unwrap(); + assert_eq!(files.len(), 2, "{report}"); + let bad = files.iter().find(|file| file["path"].as_str().is_some_and(|path| path.ends_with("bad.pdf"))).unwrap(); + assert_eq!(bad["status"], "error", "{report}"); + assert!(bad["output"].is_null(), "a failed file reports no output: {report}"); + let names: Vec = + std::fs::read_dir(dir.path().join("out")).unwrap().map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned()).collect(); + // Publish stages its bytes under a dot-prefixed name in the output folder, so + // no entry carrying that prefix may survive the run. + for name in &names { + assert!(!name.starts_with('.'), "temporary name left behind: {name} ({names:?})"); + } + assert_eq!(names, vec!["good.pdf".to_string()], "only the completed output is published"); +} + +#[cfg(unix)] +#[test] +fn read_only_output_folder_publishes_nothing() { + let dir = tempfile::tempdir().unwrap(); + std::fs::create_dir(dir.path().join("input")).unwrap(); + std::fs::write(dir.path().join("input/good.pdf"), pdf()).unwrap(); + let out = dir.path().join("out"); + std::fs::create_dir(&out).unwrap(); + set_mode(&out, 0o555); + let _restore = RestoreMode(out.clone()); + // A root process ignores the mode bits, and then the assertions below would + // pass without testing the refusal. Fail loudly instead of skipping. + assert!(std::fs::write(out.join("probe"), b"").is_err(), "run as a non-root user: the read-only output folder accepted a new file"); + let mut auto = Automation::new().with_root(dir.path()).unwrap(); + let report = result(&mut auto, json!({"paths":["input"],"steps":["optimize"],"out_dir":"out","recursive":false})); + assert_eq!(report["completed"], 0, "{report}"); + assert_eq!(report["failed"], 1, "{report}"); + let files = report["files"].as_array().unwrap(); + assert_eq!(files.len(), 1, "{report}"); + // Publish cannot create its staging file in a folder it may not write, so + // the entry carries the system's error and no output. + assert_eq!(files[0]["status"], "error", "{report}"); + assert!(files[0]["output"].is_null(), "a refused publish reports no output: {report}"); + let error = files[0]["error"].as_str().unwrap(); + assert!(!error.is_empty(), "{report}"); + assert_eq!(std::fs::read_dir(&out).unwrap().count(), 0, "the refused publish writes nothing into the read-only folder: {report}"); +} diff --git a/crates/automation/tests/it/batch_secrets.rs b/crates/automation/tests/it/batch_secrets.rs new file mode 100644 index 0000000000..08223f0955 --- /dev/null +++ b/crates/automation/tests/it/batch_secrets.rs @@ -0,0 +1,84 @@ +//! Tool results and errors from the folder tools carry no known test password. +//! +//! The passwords are set on the document and passed to the tool, and must never come back out: a +//! result that echoes one has leaked it into logs, transcripts and MCP callers. + +use pdfcraft_automation::{Automation, Content}; +use pdfcraft_engine::{Changes, Edit, Protection, Session}; +use serde_json::{Value, json}; + +/// The known test passwords; neither may appear in a result or an error. +const OPEN_PASSWORD: &str = "PLANT-OPEN-5f2c9a"; +const OWNER_PASSWORD: &str = "PLANT-OWNER-71de0b"; + +/// A one-page PDF locked with the known test passwords. +/// +/// The open password is the only way in. The batch bates tool rewrites page content, and +/// `Changes::None` forbids that, so this fixture permits every change except extracting pages; +/// the restrictions stay real, since the open password never lifts them. +fn protected_pdf() -> Vec { + let mut session = Session::new(); + let bytes = session.create_from_text("Batch secrets", "Planted password test").unwrap(); + let id = session.open("locked.pdf", None, bytes, None).unwrap(); + session + .apply( + id, + Edit::Protect(Protection { + open_password: Some(OPEN_PASSWORD.into()), + permissions_password: Some(OWNER_PASSWORD.into()), + changes: Changes::AnyExceptExtract, + ..Default::default() + }), + ) + .unwrap(); + session.save_bytes(id).unwrap().as_ref().clone() +} + +fn json_result(a: &mut Automation, tool: &str, args: Value) -> Value { + match a.call(tool, &args) { + Ok(mut content) => match content.remove(0) { + Content::Json(value) => value, + other => panic!("{tool}: expected JSON, got {other:?}"), + }, + Err(error) => panic!("{tool} {args}: {error}"), + } +} + +#[test] +fn results_and_errors_hold_no_planted_password_for_bates_or_batch() { + let dir = tempfile::tempdir().unwrap(); + std::fs::write(dir.path().join("locked.pdf"), protected_pdf()).unwrap(); + let mut a = Automation::new().with_root(dir.path()).unwrap(); + + // The right open password: numbering succeeds and reports the numbers only. + let numbered = + json_result(&mut a, "doc_bates_multi", json!({"files":[{"input":"locked.pdf","output":"locked-numbered.pdf","password":OPEN_PASSWORD}]})); + assert_eq!(numbered["completed"], 1, "{numbered}"); + assert_eq!(numbered["files"][0]["status"], "ok", "{numbered}"); + // The report carries the per-file entry the Bates tool builds, so a field added to that entry + // lands in the text checked below. + assert_eq!(numbered["files"][0]["first"], 1, "{numbered}"); + assert!(numbered["files"][0]["output"].as_str().is_some_and(|path| path.ends_with("locked-numbered.pdf")), "{numbered}"); + assert!(dir.path().join("locked-numbered.pdf").exists(), "the numbered copy is written"); + + // The wrong open password: the tool refuses the file with an error. + let refused = match a + .call("doc_bates_multi", &json!({"files":[{"input":"locked.pdf","output":"locked-refused.pdf","password":"not-the-open-password"}]})) + { + Err(error) => error.to_string(), + Ok(value) => panic!("a wrong open password must be refused: {value:?}"), + }; + + // The folder job refuses the encrypted file without a password, in its per-file report. + let batch = json_result(&mut a, "doc_batch", json!({"paths":["locked.pdf"],"steps":["optimize"],"out_dir":"out"})); + assert_eq!(batch["failed"], 1, "{batch}"); + assert_eq!(batch["files"][0]["status"], "error", "{batch}"); + assert!(batch["files"][0]["error"].as_str().is_some_and(|text| !text.is_empty()), "{batch}"); + assert!(!dir.path().join("out/locked.pdf").exists(), "a refused file publishes nothing"); + + for report in [serde_json::to_string(&numbered).unwrap(), refused, serde_json::to_string(&batch).unwrap()] { + for secret in [OPEN_PASSWORD, OWNER_PASSWORD] { + assert!(!report.contains(secret), "a result or error echoed a planted password: {report}"); + } + } +} diff --git a/crates/automation/tests/it/main.rs b/crates/automation/tests/it/main.rs index 3122fe5825..13f24013cd 100644 --- a/crates/automation/tests/it/main.rs +++ b/crates/automation/tests/it/main.rs @@ -1,10 +1,13 @@ //! The crate's integration tests, linked into one test binary. +mod action_failures; mod attachment_key; mod automation; mod automation_roots; mod backdrop; mod batch; +mod batch_failures; +mod batch_secrets; mod button_caption; mod form_bulk; mod hostile_args; diff --git a/crates/automation/tests/pattern_redaction.rs b/crates/automation/tests/pattern_redaction.rs new file mode 100644 index 0000000000..667779cef6 --- /dev/null +++ b/crates/automation/tests/pattern_redaction.rs @@ -0,0 +1,146 @@ +//! Rectangle redaction must not report a pattern-cell secret safely removed (#3647). + +use std::sync::Arc; + +use pdfcraft_automation::{Automation, Content}; +use pdfcraft_cos::{Dict, Document, Object, Stream}; +use pdfcraft_engine::DocId; +use serde_json::{Value, json}; + +fn tool(automation: &mut Automation, name: &str, args: Value) -> Value { + match automation.call(name, &args).unwrap().remove(0) { + Content::Json(value) => value, + other => panic!("expected JSON: {other:?}"), + } +} + +/// `retained`: paint with the pattern once more, away from the mark (x 290..340 lies right of it). +/// A path the mark hits is removed whole (F-008) and a pattern nothing surviving paints with is +/// pruned, so only a pattern that some surviving paint still uses reaches the guard. +fn fixture(cell: &[u8], partial: bool, compressed: bool, retained: bool) -> Vec { + let mut pattern = Dict::from_iter([ + (b"Type".to_vec(), Object::name("Pattern")), + (b"PatternType".to_vec(), Object::Int(1)), + (b"PaintType".to_vec(), Object::Int(1)), + (b"TilingType".to_vec(), Object::Int(1)), + (b"BBox".to_vec(), Object::Array(vec![0.into(), 0.into(), 500.into(), 300.into()])), + (b"XStep".to_vec(), Object::Int(500)), + (b"YStep".to_vec(), Object::Int(300)), + ]); + pattern.set( + b"Resources".to_vec(), + Object::Dict(Dict::from_iter([( + b"Font".to_vec(), + Object::Dict(Dict::from_iter([(b"F1".to_vec(), Object::Ref(pdfcraft_cos::ObjRef::new(4, 0)))])), + )])), + ); + let width = if partial { 400 } else { 170 }; + let survivor = if retained { " 290 115 50 30 re f" } else { "" }; + let content = format!("BT /F1 20 Tf 40 250 Td (PUBLIC) Tj ET /Pattern cs /P0 scn 35 110 {width} 35 re f{survivor}"); + let mut page_stream = Vec::new(); + pdfcraft_cos::serialize(&Object::Stream(Stream::from_raw(Dict::new(), content.into_bytes())), &mut page_stream); + let mut pattern_stream = Vec::new(); + let stream = if compressed { Stream::flate(pattern, cell) } else { Stream::from_raw(pattern, cell.to_vec()) }; + pdfcraft_cos::serialize(&Object::Stream(stream), &mut pattern_stream); + let objects = [ + b"<< /Type /Catalog /Pages 2 0 R >>".to_vec(), + b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_vec(), + b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 500 300] /Contents 5 0 R /Resources << /Font << /F1 4 0 R >> /Pattern << /P0 6 0 R >> >> >>" + .to_vec(), + b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>".to_vec(), + page_stream, + pattern_stream, + ]; + let mut bytes = b"%PDF-1.7\n".to_vec(); + let mut offsets = Vec::new(); + for (index, object) in objects.iter().enumerate() { + offsets.push(bytes.len()); + bytes.extend(format!("{} 0 obj\n", index + 1).as_bytes()); + bytes.extend(object); + bytes.extend(b"\nendobj\n"); + } + let xref = bytes.len(); + bytes.extend(format!("xref\n0 {}\n0000000000 65535 f \n", objects.len() + 1).as_bytes()); + for offset in offsets { + bytes.extend(format!("{offset:010} 00000 n \n").as_bytes()); + } + bytes.extend(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objects.len() + 1).as_bytes()); + bytes +} + +fn saved_has_secret(bytes: Vec) -> bool { + let document = Document::open(Arc::new(bytes)).unwrap(); + document.object_numbers().into_iter().any(|num| { + let object = document.try_get(num).unwrap(); + matches!(&*object, Object::Stream(stream) if stream.decoded().unwrap().windows(10).any(|part| part == b"CELLSECRET")) + }) +} + +#[test] +fn pattern_redaction_tools_remove_or_refuse_without_leaking_or_changing_undo() { + let dir = tempfile::tempdir().unwrap(); + for (partial, retained) in [(false, false), (true, false), (true, true)] { + for compressed in [false, true] { + let cell = b"BT /F1 20 Tf 40 120 Td (CELLSECRET) Tj ET BT /F1 20 Tf 300 120 Td (SAFE) Tj ET"; + let bytes = fixture(cell, partial, compressed, retained); + assert!(saved_has_secret(bytes.clone())); + std::fs::write(dir.path().join("input.pdf"), bytes).unwrap(); + let mut automation = Automation::new().with_root(dir.path()).unwrap().with_clock(|| 1_700_000_000); + let id = tool(&mut automation, "doc_open", json!({"path": "input.pdf"}))["doc"].as_u64().unwrap(); + tool(&mut automation, "redact_mark", json!({"doc": id, "page": 1, "rect": [30, 150, 215, 195]})); + let before = automation.session().get(DocId(id)).unwrap().bytes.clone(); + let pixels = automation.render_pixels(id, 1, 1.0).unwrap(); + match automation.call("redact_apply", &json!({"doc": id})) { + Ok(_) => { + assert!(!retained, "a text-bearing cell still in use must not be reported safe (partial: {partial})"); + tool(&mut automation, "doc_save", json!({"doc": id, "path": "redacted.pdf"})); + assert!( + !saved_has_secret(std::fs::read(dir.path().join("redacted.pdf")).unwrap()), + "successful apply/save left the pattern-cell text recoverable" + ); + } + Err(error) => { + assert!(retained, "a pattern nothing surviving paints with should apply (partial: {partial}): {error}"); + assert!(error.to_string().contains("tiling pattern"), "{error}"); + assert!(!error.to_string().contains("CELLSECRET")); + let document = automation.session().get(DocId(id)).unwrap(); + assert_eq!(document.bytes, before); + assert_eq!(document.redaction_marks(), 1); + assert_eq!(document.can_undo(), Some("Add redaction mark")); + assert_eq!(automation.render_pixels(id, 1, 1.0).unwrap(), pixels); + tool(&mut automation, "edit_undo", json!({"doc": id})); + assert_eq!(automation.session().get(DocId(id)).unwrap().redaction_marks(), 0); + } + } + } + } +} + +#[test] +fn pattern_redaction_vector_control_saves_reopens_and_preserves_outside_pixels() { + let dir = tempfile::tempdir().unwrap(); + // The guard's control: the cell is plain vectors and a paint outside the mark still uses it, + // so it is inspected and kept, not refused, and what that paint draws is unchanged. + let bytes = fixture(b"0.2 0.4 0.6 rg 40 120 15 15 re f 300 120 30 20 re f", true, true, true); + std::fs::write(dir.path().join("vectors.pdf"), bytes).unwrap(); + let mut automation = Automation::new().with_root(dir.path()).unwrap().with_clock(|| 1_700_000_000); + let id = tool(&mut automation, "doc_open", json!({"path": "vectors.pdf"}))["doc"].as_u64().unwrap(); + let (width, height, original) = automation.render_pixels(id, 1, 1.0).unwrap(); + tool(&mut automation, "redact_mark", json!({"doc": id, "page": 1, "rect": [30, 150, 215, 195]})); + let applied = tool(&mut automation, "redact_apply", json!({"doc": id})); + assert_eq!(applied["applied"], 1); + let save = tool(&mut automation, "doc_save", json!({"doc": id, "path": "vectors-redacted.pdf"})); + assert_eq!(save["incremental"], false); + let reopened = tool(&mut automation, "doc_open", json!({"path": "vectors-redacted.pdf"}))["doc"].as_u64().unwrap(); + let (new_width, new_height, actual) = automation.render_pixels(reopened, 1, 1.0).unwrap(); + assert_eq!((new_width, new_height), (width, height)); + for (index, (before, after)) in original.as_chunks::<4>().0.iter().zip(actual.as_chunks::<4>().0).enumerate() { + let (x, y) = (index % width as usize, index / width as usize); + if x >= 280 { + assert_eq!(before, after, "unmarked pattern pixels changed at {x},{y}"); + } + if (35..205).contains(&x) && (155..190).contains(&y) { + assert_eq!(after, &[0, 0, 0, 255], "marked interior must be black"); + } + } +} diff --git a/crates/compare/src/lib.rs b/crates/compare/src/lib.rs index 91245cbc21..26a50eaf71 100644 --- a/crates/compare/src/lib.rs +++ b/crates/compare/src/lib.rs @@ -41,6 +41,8 @@ pub struct Side { /// The page the change is on (for a pure insertion or deletion, where the other side's /// words would have been). pub page: usize, + /// The page its last word is on: words changed across a page break are one change. + pub last_page: usize, pub rects: Vec<[f64; 4]>, /// For an empty side (the other side's words were inserted or deleted): the box of the /// word next to where they would be. @@ -245,6 +247,7 @@ fn side(words: &[&Word], neighbour: Option<&Word>) -> Side { Side { text: words.iter().map(|w| w.text.as_str()).collect::>().join(" "), page: words.first().or(neighbour.as_ref()).map_or(0, |w| w.page), + last_page: words.last().or(neighbour.as_ref()).map_or(0, |w| w.page), rects: rects(words), near: if words.is_empty() { neighbour.map(|w| w.rect) } else { None }, } @@ -349,6 +352,17 @@ mod tests { assert_eq!(c.count(Kind::Inserted), 2); } + #[test] + fn a_change_across_a_page_break_knows_both_pages() { + let mut old = words("alpha beta", 0); + old.extend(words("gamma delta", 1)); + let mut new = words("alpha one", 0); + new.extend(words("two delta", 1)); + let c = compare(&old, &new); + assert_eq!(c.changes.len(), 1); + assert_eq!((c.changes[0].new.page, c.changes[0].new.last_page), (0, 1)); + } + #[test] fn deletions_across_pages_keep_their_pages() { let mut old = words("alpha beta gamma", 0); diff --git a/crates/cos/Cargo.toml b/crates/cos/Cargo.toml index a2fb3f4c4e..0bf2e894d2 100644 --- a/crates/cos/Cargo.toml +++ b/crates/cos/Cargo.toml @@ -15,6 +15,13 @@ thiserror = { workspace = true } # PDF date strings (`pdf_date`) go through chrono (no hand-rolled calendar code). chrono = { workspace = true } +# On the web, a rewrite's fresh file identifier takes its entropy from the browser +# (`crypto.getRandomValues`). Both crates are already in the dependency tree of the web shell +# (`js-sys` 0.3 / `wasm-bindgen` 0.2); native builds compile neither. +[target.'cfg(target_arch = "wasm32")'.dependencies] +js-sys = "0.3" +wasm-bindgen = "0.2" + [dev-dependencies] pdfcraft-oracle = { workspace = true } pdfcraft-testkit = { workspace = true } diff --git a/crates/cos/README.md b/crates/cos/README.md index 398b161625..9f5fb56725 100644 --- a/crates/cos/README.md +++ b/crates/cos/README.md @@ -62,7 +62,9 @@ another. Edits never touch the original bytes. not expand compact xref ranges; the winning xref entry remains authoritative for free slots. Compressed objects require generation zero. Explicit `set` overlays accept only the supplied generation; `set_existing` and `update_dict` retain both accepted generations of a - damaged live slot, including through snapshots, and require full rewrite. Headers beyond + damaged live slot, including through snapshots, and require full rewrite. + `accepted_generations(num)` lists the generations a slot accepts, so code comparing two + revisions can tell whether a reference still reaches the same slot. Headers beyond this bounded probe are not additionally recovered. Materialized primary and hybrid rows are diagnosed before folding, so a newer row does not hide a retained disagreement. - **Tolerant, never fatal.** The lexer works on a byte slice and a position; it allocates nothing @@ -89,6 +91,14 @@ into compressed object streams with a cross-reference stream (PDF 1.5+); turning classic table any reader accepts. Both forms map accepted xref/header aliases to one output object, retaining shared identity such as page-tree parent links; unrelated generations stay null. +A full save keeps the file's `/ID` as it is, unless the document asked for a new identifier with +`Document::require_full_save_with_new_id` (redaction and sanitizing do). Then both strings are +regenerated, and `SaveOptions::id_entropy` can supply entropy for reproducible output (tests pin +output this way). Without it the identifier mixes in fresh entropy from the host — the browser's +`crypto.getRandomValues` on the web, the operating system's random hash seed on the desktop — so a +fresh copy of the program cannot reproduce it. An encrypted file keeps the first string, because its +key is derived from it. + Dictionaries keep their key order and streams keep their *encoded* bytes, so rewritten objects stay recognisable in a diff and byte-stable when re-serialized. diff --git a/crates/cos/src/document.rs b/crates/cos/src/document.rs index e52aba2ce3..e5ce531f67 100644 --- a/crates/cos/src/document.rs +++ b/crates/cos/src/document.rs @@ -71,6 +71,9 @@ pub struct Document { encryption_changed: bool, /// Set by edits that must not leave earlier revisions in the file (redaction). full_save: bool, + /// The next full save also gives the file a new identifier (`/ID`), see + /// [`Document::require_full_save_with_new_id`]. + new_id: bool, /// The handler and `/Encrypt` object number that saves use, when encryption changed. out_security: Option>, out_encrypt_num: Option, diff --git a/crates/cos/src/document/objects.rs b/crates/cos/src/document/objects.rs index 8d9917d749..458840de3a 100644 --- a/crates/cos/src/document/objects.rs +++ b/crates/cos/src/document/objects.rs @@ -175,6 +175,30 @@ impl Document { } } + /// The generations a reference to `num` may carry and still resolve (see [`Self::get`]), + /// sorted: none for a free or unknown slot, else the slot's generation, and for a damaged + /// file slot (or a repair-aware edit of one) also the generation its object header carries. + /// Code comparing revisions (signature validation) uses it to tell whether the references + /// that reached an object in one revision still reach the same slot in another. + pub fn accepted_generations(&self, num: u32) -> Vec { + // Mirrors `reference_matches`, which stays allocation-free for every lookup. + let mut generations = match self.overlay.get(&num) { + Some(Slot::Set(generation, _)) => vec![*generation], + Some(Slot::RepairedSet(generation, alias, _)) => vec![*generation, *alias], + Some(Slot::Freed(_)) => Vec::new(), + None => match self.entries.lookup(num, &self.data) { + Some(XrefEntry::InFile { offset, generation }) => { + std::iter::once(generation).chain(self.indexed_header_reference(num, offset).map(|h| h.generation)).collect() + } + Some(XrefEntry::InStream { .. }) => vec![0], + None | Some(XrefEntry::Free { .. }) => Vec::new(), + }, + }; + generations.sort_unstable(); + generations.dedup(); + generations + } + pub(super) fn try_get_reference(&self, r: ObjRef) -> Result, CosError> { if !self.reference_matches(r) { return Ok(Arc::new(Object::Null)); diff --git a/crates/cos/src/document/open.rs b/crates/cos/src/document/open.rs index 7a4337c8da..3bf6677e99 100644 --- a/crates/cos/src/document/open.rs +++ b/crates/cos/src/document/open.rs @@ -35,6 +35,7 @@ impl Document { unfound: Arc::default(), encryption_changed: false, full_save: false, + new_id: false, out_security: None, out_encrypt_num: None, }; @@ -121,6 +122,7 @@ impl Document { unfound: Arc::default(), encryption_changed: false, full_save: false, + new_id: false, out_security: None, out_encrypt_num: None, }; @@ -290,12 +292,25 @@ impl Document { self.full_save = true; } + /// Like [`Document::require_full_save`], and the rewritten file also gets a new file identifier + /// (`/ID`), so that a redacted or sanitized copy never claims to be its source (ISO 32000-2 + /// §14.4). An encrypted file keeps the first string of its identifier, which its key depends on. + pub fn require_full_save_with_new_id(&mut self) { + self.full_save = true; + self.new_id = true; + } + /// The next save must rewrite the whole file (see [`Document::require_full_save`]). /// Repair-aware edits retaining two accepted generations cannot use one incremental slot. pub fn full_save_required(&self) -> bool { self.full_save || self.overlay.values().any(|slot| matches!(slot, Slot::RepairedSet(..))) } + /// The next full save gives the file a new identifier (see [`Document::require_full_save_with_new_id`]). + pub fn new_id_required(&self) -> bool { + self.new_id + } + /// Security was set or removed since the document was opened (the next save applies it). pub fn encryption_changed(&self) -> bool { self.encryption_changed diff --git a/crates/cos/src/lib.rs b/crates/cos/src/lib.rs index 8e051e4578..32a6f6d8b3 100644 --- a/crates/cos/src/lib.rs +++ b/crates/cos/src/lib.rs @@ -30,7 +30,7 @@ pub use parser::{Lexer, is_whitespace, parse_indirect}; pub use pdfcraft_crypt::{ Algorithm, Auth, Method as CryptMethod, NewEncryption, Permissions, SecurityHandler, effective_password, pdfdoc_byte, pdfdoc_char, }; -pub use writer::{SaveOptions, pdf_date, serialize, write_full, write_incremental}; +pub use writer::{SaveOptions, pdf_date, reachable_objects, serialize, write_full, write_incremental}; #[derive(Debug, thiserror::Error, Clone, PartialEq)] pub enum CosError { diff --git a/crates/cos/src/writer.rs b/crates/cos/src/writer.rs index 6c4c71580a..0af74f7bab 100644 --- a/crates/cos/src/writer.rs +++ b/crates/cos/src/writer.rs @@ -167,11 +167,17 @@ pub struct SaveOptions { /// before adding it, with [`Document::free_unlinked_additions`]. Full saves always leave /// these out. pub drop_unlinked: bool, + /// Entropy for the file identifier of a rewrite that asks for a new one (see + /// [`Document::require_full_save_with_new_id`]). Given, the identifier depends only on this and + /// on the written bytes, so the same save gives the same file; tests use it to pin output. + /// Without it, fresh entropy from the host (the operating system on native targets, the + /// browser on WebAssembly) is mixed in. + pub id_entropy: Option<[u8; 16]>, } impl Default for SaveOptions { fn default() -> Self { - Self { mod_date: None, id_seed: 0x5052_494E_5443_5241, object_streams: true, drop_unlinked: false } + Self { mod_date: None, id_seed: 0x5052_494E_5443_5241, object_streams: true, drop_unlinked: false, id_entropy: None } } } @@ -267,16 +273,12 @@ pub fn write_incremental(doc: &Document, opts: &SaveOptions) -> Result, Ok(file) } -/// Write only reachable objects, renumbered from 1, with a table or cross-reference stream. -pub fn write_full(doc: &Document, opts: &SaveOptions) -> Result, CosError> { - if doc.stream_limited() { - return Err(CosError::ReadOnlyLimit); - } - // A full traversal must not fill the editor's shared caches (which undo snapshots also - // own). Parsed objects and decoded object streams are temporary working data here. - let mut reader = doc.object_reader(); - stamp_mod_date(&mut reader.document, opts); - let trailer_in = reader.document.trailer().clone(); +/// The objects [`write_full`] writes: everything reachable from the trailer's /Root, /Info and +/// /Encrypt and from its unknown entries, breadth-first, with the new number each gets +/// (aliases of one slot included) and, in visit order, whether it is a stream. +type SaveOrder = (HashMap, Vec<(ObjRef, bool)>); + +fn full_save_order(reader: &mut ObjectReader, trailer_in: &Dict) -> Result { // Breadth-first walk from the trailer, assigning new numbers in visit order. let mut map: HashMap = HashMap::new(); // Record the type while traversing so classifying packed objects needs no second parse. @@ -320,6 +322,30 @@ pub fn write_full(doc: &Document, opts: &SaveOptions) -> Result, CosErro order.push((canonical, matches!(*o, Object::Stream(_)))); visit_refs(&o, &mut queue); } + Ok((map, order)) +} + +/// The object numbers a full save of `doc` would write: exactly the objects [`write_full`] +/// reaches from the trailer, object streams included. For a check that something removed from a +/// document cannot reach the saved file through a reference nobody looked for. +pub fn reachable_objects(doc: &Document) -> Result, CosError> { + let mut reader = doc.object_reader(); + let trailer_in = reader.document.trailer().clone(); + let (_, order) = full_save_order(&mut reader, &trailer_in)?; + Ok(order.into_iter().map(|(r, _)| r.num).collect()) +} + +/// Write only reachable objects, renumbered from 1, with a table or cross-reference stream. +pub fn write_full(doc: &Document, opts: &SaveOptions) -> Result, CosError> { + if doc.stream_limited() { + return Err(CosError::ReadOnlyLimit); + } + // A full traversal must not fill the editor's shared caches (which undo snapshots also + // own). Parsed objects and decoded object streams are temporary working data here. + let mut reader = doc.object_reader(); + stamp_mod_date(&mut reader.document, opts); + let trailer_in = reader.document.trailer().clone(); + let (map, order) = full_save_order(&mut reader, &trailer_in)?; let version = reader.document.version().chars().take(3).collect::(); let version = if opts.object_streams && version.as_str() < "1.5" { "1.5".to_string() } else { version }; let mut out = Vec::new(); @@ -383,26 +409,7 @@ pub fn write_full(doc: &Document, opts: &SaveOptions) -> Result, CosErro } } batch.flush(&reader.document, &mut next, &mut rows, &mut out)?; - let mut trailer = Dict::new(); - for key in [&b"Root"[..], b"Info", b"Encrypt"] { - if let Some(r) = trailer_in.reference(key).and_then(|r| map.get(&r)) { - trailer.set(key.to_vec(), Object::Ref(ObjRef::new(*r, 0))); - } - } - if let Some(encrypt @ Object::Dict(_)) = trailer_in.get(b"Encrypt") { - trailer.set(b"Encrypt".to_vec(), renumber(encrypt, &map)); - } - if let Some(id) = trailer_in.get(b"ID") { - trailer.set(b"ID".to_vec(), direct_id(&reader.document, id)); - } - for (key, value) in trailer_in.iter() { - if !trailer_key_rewritten(key) { - trailer.set(key.clone(), renumber(value, &map)); - } - } - if reader.document.output_security().0.is_none() { - ensure_id(&mut trailer, opts, reader.document.bytes()); - } + let mut trailer = full_save_trailer(&reader.document, &trailer_in, &map, opts, &out); if opts.object_streams { write_xref_stream(&mut out, 0, &mut trailer, rows, next); } else { @@ -421,6 +428,34 @@ pub fn write_full(doc: &Document, opts: &SaveOptions) -> Result, CosErro Ok(out) } +/// Assemble the full rewrite's trailer and apply its identifier policy. +fn full_save_trailer(doc: &Document, trailer_in: &Dict, map: &HashMap, opts: &SaveOptions, out: &[u8]) -> Dict { + let mut trailer = Dict::new(); + for key in [&b"Root"[..], b"Info", b"Encrypt"] { + if let Some(r) = trailer_in.reference(key).and_then(|r| map.get(&r)) { + trailer.set(key.to_vec(), Object::Ref(ObjRef::new(*r, 0))); + } + } + if let Some(encrypt @ Object::Dict(_)) = trailer_in.get(b"Encrypt") { + trailer.set(b"Encrypt".to_vec(), renumber(encrypt, map)); + } + if let Some(id) = trailer_in.get(b"ID") { + trailer.set(b"ID".to_vec(), direct_id(doc, id)); + } + for (key, value) in trailer_in.iter() { + if !trailer_key_rewritten(key) { + trailer.set(key.clone(), renumber(value, map)); + } + } + if doc.output_security().0.is_none() { + ensure_id(&mut trailer, opts, doc.bytes()); + } + if doc.new_id_required() { + regenerate_id(&mut trailer, opts, out, doc.output_security().0.is_some()); + } + trailer +} + /// Object `r` read again for writing. The traversal read it once and only kept its number, so /// a second read that fails, finds nothing or finds a different kind of object must fail the /// save rather than write `null` in its place. @@ -669,6 +704,136 @@ fn ensure_id(trailer: &mut Dict, opts: &SaveOptions, content: &[u8]) { trailer.set(b"ID".to_vec(), Object::Array(vec![s.clone(), s])); } +/// Give a rewritten file a new identifier (§14.4), so that a redacted or sanitized copy does not +/// claim to be its source. An encrypted file keeps the first string, which its key is derived from, +/// and gets a new second one. When there is no such string (no `/ID`, one entry, or a first entry +/// that is not a string) the reader takes the empty string as the key input (`Document::first_id`), +/// so the empty string is written first and the key stays valid. +fn regenerate_id(trailer: &mut Dict, opts: &SaveOptions, written: &[u8], encrypted: bool) { + let fresh = Object::String(PdfString { bytes: new_id_bytes(opts, written), hex: true }); + let pair = if encrypted { + let first = match trailer.get(b"ID") { + Some(Object::Array(a)) => match a.first() { + Some(Object::String(s)) => Object::String(s.clone()), + _ => Object::String(PdfString { bytes: Vec::new(), hex: true }), + }, + _ => Object::String(PdfString { bytes: Vec::new(), hex: true }), + }; + vec![first, fresh] + } else { + vec![fresh.clone(), fresh] + }; + trailer.set(b"ID".to_vec(), Object::Array(pair)); +} + +/// FNV-1a over 64 bits, with its published offset basis and prime. The identifier is built from it +/// rather than from `std`'s `DefaultHasher`, whose algorithm the standard library does not specify. +const FNV_OFFSET: u64 = 0xcbf2_9ce4_8422_2325; +const FNV_PRIME: u64 = 0x0000_0100_0000_01b3; + +fn fnv1a(state: u64, bytes: &[u8]) -> u64 { + bytes.iter().fold(state, |h, b| (h ^ u64::from(*b)).wrapping_mul(FNV_PRIME)) +} + +/// Sixteen bytes for a file identifier, one 8-byte half per lane. The bytes are a pure function of +/// `SaveOptions::id_entropy`, `id_seed` and the written file: the hash is FNV-1a (above) and every +/// integer is written as a fixed-width big-endian value, so the same input gives the same identifier +/// on every platform and toolchain. Without entropy only the salt changes (see `id_salt`). FNV is +/// not collision-resistant against chosen content; the identifier only has to be unique, not secret. +/// Every written byte is hashed, once, in a single traversal of the output. +fn new_id_bytes(opts: &SaveOptions, written: &[u8]) -> Vec { + let salt = id_salt(opts); + let length = u64::try_from(written.len()).unwrap_or(u64::MAX); + let mut halves = [0u8, 1].map(|lane| { + let mut h = fnv1a(FNV_OFFSET, &salt.to_be_bytes()); + h = fnv1a(h, &[lane]); + h = fnv1a(h, &opts.id_seed.to_be_bytes()); + fnv1a(h, &length.to_be_bytes()) + }); + for chunk in written.chunks(4096) { + for h in &mut halves { + *h = fnv1a(*h, chunk); + } + } + halves.iter().flat_map(|h| h.to_be_bytes()).collect() +} + +/// The salt of an identifier. With caller entropy it is a fixed hash of that entropy (deterministic, +/// for tests and callers who pin output). Without it the salt is fresh: on WebAssembly from the +/// browser ([`browser_salt`], so two fresh web apps that write the same bytes cannot share an +/// identifier), and elsewhere from the standard library's random hash keys — seeded by the operating +/// system, so separate processes differ — mixed with a process-wide counter, which separates +/// successive calls in one process. +fn id_salt(opts: &SaveOptions) -> u64 { + use std::hash::BuildHasher; + use std::sync::atomic::{AtomicU64, Ordering}; + static COUNTER: AtomicU64 = AtomicU64::new(0); + match &opts.id_entropy { + Some(entropy) => fnv1a(FNV_OFFSET, entropy), + None => { + #[cfg(target_arch = "wasm32")] + if let Some(salt) = browser_salt() { + return salt; + } + std::collections::hash_map::RandomState::new().hash_one(COUNTER.fetch_add(1, Ordering::Relaxed)) + } + } +} + +/// One byte from one `Math.random` draw: the draw (in [0, 1)) scaled to [0, 256), integer part +/// taken. The quotient is in [0, 256), so a saturating cast never wraps; a NaN or infinite draw +/// (which a conforming engine never returns) folds in as 0. No input can panic here. +#[cfg(any(target_arch = "wasm32", test))] +fn draw_byte(random: f64) -> u8 { + (random * 256.0).floor().rem_euclid(256.0) as u8 +} + +/// The `Math.random` fallback's mixing: one salt byte per draw (see [`draw_byte`]), folded through +/// FNV-1a exactly like the Web Crypto bytes, so all sixteen bytes of the fold carry entropy from +/// the draws. Pure and platform-independent, so the native test target can exercise it; on wasm +/// each draw comes from `Math.random`. +#[cfg(any(target_arch = "wasm32", test))] +fn salt_from_draws(draws: &[f64; 16]) -> u64 { + let mut bytes = [0u8; 16]; + for (byte, draw) in bytes.iter_mut().zip(draws) { + *byte = draw_byte(*draw); + } + fnv1a(FNV_OFFSET, &bytes) +} + +/// Fresh salt entropy from the browser, on WebAssembly. `crypto.getRandomValues` (Web Crypto, the +/// browser's secure generator, available in windows and workers alike) gives sixteen bytes, folded +/// into one salt. When that API is missing or refuses the call, `Math.random` is mixed instead +/// ([`salt_from_draws`]: sixteen draws, so the salt's full width carries entropy) — browsers seed +/// it afresh for every document, so a fresh instance still cannot reproduce another's salt. Only +/// where neither is reachable does the caller fall back to its `RandomState` salt, whose keys are +/// fixed at compile time on `wasm32-unknown-unknown` — the state before browser entropy was wired +/// in. +#[cfg(target_arch = "wasm32")] +fn browser_salt() -> Option { + use wasm_bindgen::JsCast; + let crypto = js_sys::Reflect::get(&js_sys::global(), &wasm_bindgen::JsValue::from_str("crypto")) + .ok() + .filter(|crypto| !crypto.is_undefined() && !crypto.is_null()); + if let Some(crypto) = crypto { + let fill = js_sys::Reflect::get(&crypto, &wasm_bindgen::JsValue::from_str("getRandomValues")) + .ok() + .and_then(|fill| fill.dyn_into::().ok()); + if let Some(fill) = fill { + let bytes = js_sys::Uint8Array::new_with_length(16); + if fill.call1(&crypto, &bytes).is_ok() { + return Some(fnv1a(FNV_OFFSET, &bytes.to_vec())); + } + } + } + // Web Crypto is missing or refused the call: degrade to `Math.random` rather than giving up. + let mut draws = [0.0; 16]; + for draw in &mut draws { + *draw = js_sys::Math::random(); + } + Some(salt_from_draws(&draws)) +} + /// A PDF date string for "now" given seconds since the Unix epoch (UTC). pub fn pdf_date(unix_secs: i64) -> String { let (days, secs) = (unix_secs.div_euclid(86_400), unix_secs.rem_euclid(86_400)); @@ -711,6 +876,56 @@ mod tests { use proptest::prelude::*; + #[test] + fn the_same_entropy_and_bytes_give_the_same_identifier_on_every_platform() { + // Computed from the formula outside this crate: fixed-width big-endian fields and FNV-1a. + let opts = super::SaveOptions { id_entropy: Some([0x42; 16]), id_seed: 7, ..super::SaveOptions::default() }; + let want = [0x96, 0xf8, 0xcb, 0x7d, 0x5b, 0xb0, 0x09, 0xc8, 0x92, 0xc9, 0xb7, 0x51, 0xdf, 0xe6, 0xab, 0xd1]; + assert_eq!(super::new_id_bytes(&opts, b"%PDF-1.7\n"), want); + } + + #[test] + fn fnv1a_is_the_published_64_bit_algorithm() { + // Published FNV-1a (64 bit) test vectors, so the identifier can be reproduced outside this crate. + assert_eq!(super::fnv1a(super::FNV_OFFSET, b""), 0xcbf2_9ce4_8422_2325); + assert_eq!(super::fnv1a(super::FNV_OFFSET, b"a"), 0xaf63_dc4c_8601_ec8c); + assert_eq!(super::fnv1a(super::FNV_OFFSET, b"foobar"), 0x8594_4171_f739_67e8); + } + + #[test] + fn math_random_draws_fill_the_whole_salt_width() { + // Draw i = (i + 1/2)/256 scales to the integer i, so the fold's byte i proves draw i landed + // there: all sixteen bytes carry their own draw's entropy (the fallback once shifted four + // draws into one word, leaving the other four bytes of the fold constant). + let draws: [f64; 16] = std::array::from_fn(|i| (i as f64 + 0.5) / 256.0); + let bytes: Vec = (0..16).collect(); + assert_eq!(super::salt_from_draws(&draws), super::fnv1a(super::FNV_OFFSET, &bytes)); + } + + #[test] + fn every_math_random_draw_reaches_the_salt() { + let base = [0.5; 16]; + let baseline = super::salt_from_draws(&base); + for i in 0..16 { + let mut draws = base; + draws[i] = 0.75; + assert_ne!(super::salt_from_draws(&draws), baseline, "draw {i} did not reach the salt"); + } + } + + #[test] + fn a_math_random_draw_outside_its_range_still_mixes_without_panicking() { + // A conforming `Math.random` stays in [0, 1), but the mixing must not panic outside it. + assert_eq!(super::draw_byte(0.0), 0); + assert_eq!(super::draw_byte(0.5), 128); + assert_eq!(super::draw_byte(255.5 / 256.0), 255); + assert_eq!(super::draw_byte(-0.5 / 256.0), 255); + assert_eq!(super::draw_byte(-1.0), 0); + assert_eq!(super::draw_byte(2.0), 0); + assert_eq!(super::draw_byte(f64::NAN), 0); + assert_eq!(super::draw_byte(f64::INFINITY), 0); + } + use super::*; use crate::Lexer; diff --git a/crates/cos/tests/file_identifier.rs b/crates/cos/tests/file_identifier.rs new file mode 100644 index 0000000000..313d56257b --- /dev/null +++ b/crates/cos/tests/file_identifier.rs @@ -0,0 +1,276 @@ +//! The file identifier (`/ID`, ISO 32000-2 §14.4) of a full save. An ordinary save keeps the +//! identifier the file has and writes the same bytes twice. A rewrite the document asked for (after +//! redaction or sanitizing) gives the file a new pair. An encrypted file keeps its first string, +//! because its file key is derived from it. + +use std::sync::Arc; + +use pdfcraft_cos::{Algorithm, Document, NewEncryption, Object, PdfString, SaveOptions, write_full, write_incremental}; +use pdfcraft_testkit::Pdf; + +const ID_HEX: &str = "/ID [<00112233445566778899AABBCCDDEEFF> <00112233445566778899AABBCCDDEEFF>]"; +const ID_BYTES: [u8; 16] = [0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF]; + +/// One page whose content holds a secret, with `entry` added to the trailer (for example an `/ID`). +fn source_with(entry: Option<&str>) -> Vec { + let pdf = Pdf::new() + .obj("<< /Type /Catalog /Pages 2 0 R >>") + .obj("<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 200 200] >>") + .obj("<< /Type /Page /Parent 2 0 R /Contents 4 0 R /Resources << /Font << /F1 5 0 R >> >> >>") + .stream("", "BT /F1 12 Tf 20 100 Td (TOPSECRET) Tj ET") + .obj("<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>"); + match entry { + Some(entry) => pdf.trailer_entry(entry).build(), + None => pdf.build(), + } +} + +/// [`source_with`] with the standard identifier, or none. +fn source(with_id: bool) -> Vec { + source_with(with_id.then_some(ID_HEX)) +} + +/// A one-page file whose 70,000-byte content stream ends in `last`. Two of these built with +/// different last bytes have the same length and differ only past the first 64 KiB. +fn large_source(last: u8) -> Vec { + let mut content = vec![b' '; 70_000]; + content.push(last); + Pdf::new() + .obj("<< /Type /Catalog /Pages 2 0 R >>") + .obj("<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 200 200] >>") + .obj("<< /Type /Page /Parent 2 0 R /Contents 4 0 R /Resources << /Font << /F1 5 0 R >> >> >>") + .stream("", content) + .obj("<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>") + .build() +} + +fn reopen(bytes: Vec) -> Document { + Document::open(Arc::new(bytes)).unwrap() +} + +/// The strings of the trailer's `/ID` (empty when there is none). +fn id_strings(doc: &Document) -> Vec> { + match doc.trailer().get(b"ID") { + Some(Object::Array(a)) => a.iter().map(|s| s.as_string().map(|s| s.bytes.clone()).unwrap_or_default()).collect(), + _ => Vec::new(), + } +} + +#[test] +fn an_ordinary_save_keeps_the_identifier_and_writes_the_same_bytes() { + let doc = reopen(source(true)); + let opts = SaveOptions::default(); + let saved = write_full(&doc, &opts).unwrap(); + assert_eq!(saved, write_full(&doc, &opts).unwrap(), "unchanged inputs produce identical bytes"); + assert_eq!(id_strings(&reopen(saved)), vec![ID_BYTES.to_vec(), ID_BYTES.to_vec()]); + let appended = reopen(write_incremental(&doc, &opts).unwrap()); + assert_eq!(id_strings(&appended), vec![ID_BYTES.to_vec(), ID_BYTES.to_vec()]); +} + +#[test] +fn an_ordinary_save_of_a_file_without_an_identifier_creates_the_same_one_every_time() { + let doc = reopen(source(false)); + let opts = SaveOptions::default(); + let saved = write_full(&doc, &opts).unwrap(); + assert_eq!(saved, write_full(&doc, &opts).unwrap(), "unchanged inputs produce identical bytes"); + let ids = id_strings(&reopen(saved)); + assert_eq!(ids.len(), 2); + assert!(ids.iter().all(|s| s.len() == 16), "{ids:?}"); +} + +#[test] +fn a_rewrite_the_document_asked_for_gets_a_new_identifier() { + let mut doc = reopen(source(true)); + doc.require_full_save_with_new_id(); + assert!(doc.full_save_required() && doc.new_id_required()); + let opts = SaveOptions::default(); + for saved in [write_incremental(&doc, &opts).unwrap(), write_full(&doc, &opts).unwrap()] { + let ids = id_strings(&reopen(saved)); + assert_eq!(ids.len(), 2); + for id in &ids { + assert_eq!(id.len(), 16); + assert_ne!(id.as_slice(), ID_BYTES.as_slice(), "the copy must not claim the source's identifier"); + } + } + // Every save is a new identity, not the same one again. + let first = id_strings(&reopen(write_full(&doc, &opts).unwrap())); + let second = id_strings(&reopen(write_full(&doc, &opts).unwrap())); + assert_ne!(first, second); +} + +#[test] +fn a_rewrite_without_an_identifier_still_gets_one() { + let mut doc = reopen(source(false)); + doc.require_full_save_with_new_id(); + let ids = id_strings(&reopen(write_full(&doc, &SaveOptions::default()).unwrap())); + assert_eq!(ids.len(), 2); + assert!(ids.iter().all(|s| s.len() == 16), "{ids:?}"); +} + +#[test] +fn caller_entropy_makes_the_new_identifier_reproducible() { + let mut doc = reopen(source(true)); + doc.require_full_save_with_new_id(); + let with = |entropy: u8| SaveOptions { id_entropy: Some([entropy; 16]), ..SaveOptions::default() }; + let first = write_full(&doc, &with(1)).unwrap(); + assert_eq!(first, write_full(&doc, &with(1)).unwrap(), "the same entropy gives the same bytes"); + let other = write_full(&doc, &with(2)).unwrap(); + assert_ne!(id_strings(&reopen(first)), id_strings(&reopen(other)), "different entropy gives a different identifier"); +} + +#[test] +fn an_encrypted_rewrite_keeps_the_first_identifier_string_its_key_depends_on() { + for algorithm in [Algorithm::Rc4_128, Algorithm::Aes128, Algorithm::Aes256] { + let mut doc = reopen(source(true)); + doc.set_encryption(&NewEncryption { + algorithm, + user_password: "user", + owner_password: "owner", + permissions: -1, + encrypt_metadata: true, + seed: [5; 32], + }) + .unwrap(); + let protected = write_full(&doc, &SaveOptions::default()).unwrap(); + let before = Document::open_with_password(Arc::new(protected), Some("user")).unwrap(); + + let mut doc = before.clone(); + doc.require_full_save_with_new_id(); + let out = write_incremental(&doc, &SaveOptions::default()).unwrap(); + // The output opens with the same password only if its first identifier string is unchanged. + let back = Document::open_with_password(Arc::new(out), Some("user")).unwrap(); + let (old, new) = (id_strings(&before), id_strings(&back)); + assert_eq!(new.len(), 2, "{algorithm:?}"); + assert_eq!(new.first(), old.first(), "{algorithm:?}: the key depends on the first string"); + assert_ne!(new.get(1), old.get(1), "{algorithm:?}: the second string is new"); + } +} + +/// The `/ID` shapes whose key the reader takes as the empty string: none at all, one entry, and a +/// first entry that is not a string. +fn unusable_ids() -> Vec<(&'static str, Option)> { + let empty = Object::String(PdfString::literal(Vec::new())); + vec![ + ("absent", None), + ("one entry", Some(Object::Array(vec![empty.clone()]))), + ("first entry not a string", Some(Object::Array(vec![Object::Int(7), empty]))), + ] +} + +/// An encrypted file whose key is derived from the empty string, with its trailer `/ID` replaced by `id`. +fn protected_with_id(algorithm: Algorithm, id: Option) -> Vec { + let mut doc = reopen(source_with(Some("/ID [<> <>]"))); + doc.set_encryption(&NewEncryption { + algorithm, + user_password: "user", + owner_password: "owner", + permissions: -1, + encrypt_metadata: true, + seed: [5; 32], + }) + .unwrap(); + match id { + Some(id) => doc.trailer_mut().set(b"ID".to_vec(), id), + None => { + doc.trailer_mut().remove(b"ID"); + } + } + write_full(&doc, &SaveOptions::default()).unwrap() +} + +#[test] +fn an_encrypted_rewrite_without_a_usable_identifier_still_gets_a_new_one() { + // The key is derived from the first string of /ID, and a missing /ID, a one-entry /ID and a + // first entry that is not a string all count as the empty string. The rewrite keeps that + // (empty) first string, so the file still opens with its password, and writes a new second one. + for algorithm in [Algorithm::Rc4_128, Algorithm::Aes128, Algorithm::Aes256] { + for (shape, id) in unusable_ids() { + let before = Document::open_with_password(Arc::new(protected_with_id(algorithm, id)), Some("user")).unwrap(); + let mut doc = before.clone(); + doc.require_full_save_with_new_id(); + let out = write_incremental(&doc, &SaveOptions::default()).unwrap(); + let back = Document::open_with_password(Arc::new(out), Some("user")).unwrap(); + let ids = id_strings(&back); + let previous = id_strings(&before); + assert_eq!(ids.len(), 2, "{algorithm:?}, {shape}: the rewrite writes a pair"); + assert!(ids.first().is_some_and(|s| s.is_empty()), "{algorithm:?}, {shape}: the first string is the one the key uses"); + assert_eq!(ids.get(1).map(Vec::len), Some(16), "{algorithm:?}, {shape}"); + assert_ne!(ids.get(1), previous.get(1), "{algorithm:?}, {shape}: the second string is new"); + } + } +} + +/// The standard fixture rewritten for a new identifier, with `id_entropy` of 0x42. +fn fixed_entropy_rewrite() -> Vec { + let mut doc = reopen(source(true)); + doc.require_full_save_with_new_id(); + write_full(&doc, &SaveOptions { id_entropy: Some([0x42; 16]), ..SaveOptions::default() }).unwrap() +} + +#[test] +fn a_fixed_entropy_gives_the_same_identifier_every_time() { + // The formula itself is pinned on fixed bytes in the writer's tests. The written file is not the + // same on every platform, so no identifier of a rewrite can be pinned here. + let first = id_strings(&reopen(fixed_entropy_rewrite())); + assert_eq!(first.len(), 2); + assert!(first.iter().all(|s| s.len() == 16), "{first:?}"); + assert_eq!(first, id_strings(&reopen(fixed_entropy_rewrite()))); +} + +#[test] +fn the_identifier_depends_on_the_whole_rewritten_file() { + // Same caller entropy and same length; the two rewrites differ only in one byte of a stream + // that lies past the first 64 KiB of the output. Their identifiers must still differ. + let opts = SaveOptions { id_entropy: Some([9; 16]), ..SaveOptions::default() }; + let rewrite = |last: u8| { + let mut doc = reopen(large_source(last)); + doc.require_full_save_with_new_id(); + write_full(&doc, &opts).unwrap() + }; + let (a, b) = (rewrite(b'A'), rewrite(b'B')); + assert_eq!(a.len(), b.len(), "the two rewrites have the same length"); + let first_difference = a.iter().zip(&b).position(|(x, y)| x != y).unwrap_or(usize::MAX); + assert!(first_difference > 64 * 1024, "the rewrites first differ at byte {first_difference}, inside the first 64 KiB"); + assert_ne!(id_strings(&reopen(a)), id_strings(&reopen(b)), "content past 64 KiB must change the identifier"); +} + +/// Where [`stand_in_for_a_fresh_process`] writes its rewrite. +const ID_PROBE: &str = "PDFCRAFT_TEST_ID_PROBE"; + +/// The child half of [`separate_fresh_processes_get_different_identifiers`]: it runs alone, in its +/// own process, and writes a default-path rewrite of the standard fixture to the file the parent +/// named. Without the variable it is a plain no-op. +#[test] +fn stand_in_for_a_fresh_process() { + let Some(path) = std::env::var_os(ID_PROBE) else { return }; + let mut doc = reopen(source(true)); + doc.require_full_save_with_new_id(); + std::fs::write(path, write_full(&doc, &SaveOptions::default()).unwrap()).unwrap(); +} + +#[test] +fn separate_fresh_processes_get_different_identifiers() { + // The default identifier is meant to differ between fresh instances of the whole save pipeline, + // not only between two calls in one process (which the counter already separates). On the native + // test target a fresh instance is a fresh process, whose hash keys the operating system seeds; + // the fix under test runs on WebAssembly, where no browser test harness exists — there the + // browser's `crypto.getRandomValues` stands in for this seeding, and this test cannot see it. + let exe = std::env::current_exe().unwrap(); + let probe = |name: &str| { + let path = std::env::temp_dir().join(format!("pdfcraft-id-probe-{}-{name}.pdf", std::process::id())); + let out = std::process::Command::new(&exe) + .args(["--exact", "stand_in_for_a_fresh_process", "--nocapture", "--"]) + .env(ID_PROBE, &path) + .output() + .expect("run this test's own binary as a child"); + assert!(out.status.success(), "{name}: the child failed: {}", String::from_utf8_lossy(&out.stderr)); + let saved = std::fs::read(&path).unwrap_or_else(|e| panic!("{name}: the child wrote its file: {e}")); + let ids = id_strings(&reopen(saved)); + assert_eq!(ids.len(), 2, "{name}"); + assert!(ids.iter().all(|s| s.len() == 16), "{name}: {ids:?}"); + let _ = std::fs::remove_file(&path); + ids + }; + let (first, second) = (probe("a"), probe("b")); + assert_ne!(first, second, "two fresh processes must not share an identifier"); +} diff --git a/crates/cos/tests/it/generations.rs b/crates/cos/tests/it/generations.rs index 3d56628c93..bbe2ff0b33 100644 --- a/crates/cos/tests/it/generations.rs +++ b/crates/cos/tests/it/generations.rs @@ -473,3 +473,38 @@ fn restoring_explicit_sets_removes_old_generation_aliases() { } } } + +/// `accepted_generations` lists exactly the generations `get` resolves, for every kind of slot: +/// a clean file slot, a damaged one (row and header disagree), a repair-aware edit, a plain +/// edit, a freed slot, a free row, an object stream member and an unknown number. +#[test] +fn accepted_generations_are_the_generations_get_resolves() { + let agrees = |doc: &Document, num: u32, expected: &[u16]| { + assert_eq!(doc.accepted_generations(num), expected, "object {num}"); + for generation in 0..8 { + let live = !matches!(*doc.get(ObjRef::new(num, generation)), Object::Null); + assert_eq!(live, expected.contains(&generation), "object {num} generation {generation}"); + } + }; + let doc = Document::open(contradictory_entry(false)).unwrap(); + agrees(&doc, 1, &[0]); + agrees(&doc, 3, &[0, 1]); + agrees(&doc, 9, &[]); + let mut repaired = doc.clone(); + repaired.set_existing(ObjRef::new(3, 0), Object::Int(77)).unwrap(); + agrees(&repaired, 3, &[0, 1]); + let mut narrowed = doc.clone(); + narrowed.set(ObjRef::new(3, 2), Object::Int(99)); + agrees(&narrowed, 3, &[2]); + let mut freed = doc.clone(); + freed.free(ObjRef::new(3, 0)); + agrees(&freed, 3, &[]); + agrees(&Document::open(contradictory_entry(true)).unwrap(), 3, &[]); + let mut doc = + Document::open(object_file(&[(1, 0, "<< /Type /Catalog /Pages 2 0 R >>"), (2, 0, "<< /Type /Pages /Kids [] /Count 0 >>")])).unwrap(); + let member = doc.add(Object::Dict(Default::default())); + doc.update_dict(ObjRef::new(1, 0), |c| c.set(b"Extra".to_vec(), Object::Ref(member))).unwrap(); + let packed = Document::open(Arc::new(write_full(&doc, &SaveOptions { object_streams: true, ..SaveOptions::default() }).unwrap())).unwrap(); + assert!(matches!(packed.xref_entry(member.num), Some(XrefEntry::InStream { .. })), "the member is in an object stream"); + agrees(&packed, member.num, &[0]); +} diff --git a/crates/create/src/lib.rs b/crates/create/src/lib.rs index 6346e85120..53a587728f 100644 --- a/crates/create/src/lib.rs +++ b/crates/create/src/lib.rs @@ -92,6 +92,26 @@ pub fn blank(width: f64, height: f64, pages: usize) -> Result)]) -> Result { + if pages.is_empty() || pages.len() > 10_000 { + return Err(CreateError::Invalid("invalid page count".into())); + } + if pages.iter().any(|(w, h, _, _)| !(w.is_finite() && h.is_finite() && (3.0..=MAX_SIDE).contains(w) && (3.0..=MAX_SIDE).contains(h))) { + return Err(CreateError::Invalid("invalid page size".into())); + } + let mut doc = Document::new_empty(); + let mut tree = Pages::of(&doc)?; + for (w, h, resources, content) in pages { + let content = if content.is_empty() { None } else { Some(content.clone()) }; + tree.add(&mut doc, *w, *h, resources.clone(), content); + } + tree.finish(&mut doc)?; + Ok(doc) +} + // ── images ────────────────────────────────────────────────────────────────────────────────── /// An image ready to embed: its XObject dictionary, encoded data, optional soft mask, the ICC diff --git a/crates/crypt/src/lib.rs b/crates/crypt/src/lib.rs index ff92d9af66..e697bc8553 100644 --- a/crates/crypt/src/lib.rs +++ b/crates/crypt/src/lib.rs @@ -82,17 +82,24 @@ pub enum Auth { User, } -/// Permission bits from `/P` (§7.6.4.2, Table 22). Owners have every permission. +/// Permission flags from `/P`, read the way the handler's revision reads them (ISO 32000-1:2008, +/// Table 22). Owners have every permission. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct Permissions { pub bits: i32, pub owner: bool, + /// The `/R` value of the handler that read `bits`. + pub revision: i64, } impl Permissions { fn bit(&self, n: u32) -> bool { self.owner || (self.bits >> (n - 1)) & 1 == 1 } + /// Revision 3 and later read the full flag list of Table 22; revision 2 has its own. + fn is_revision_3_or_later(&self) -> bool { + self.revision >= 3 + } pub fn print(&self) -> bool { self.bit(3) } @@ -107,17 +114,22 @@ impl Permissions { self.bit(6) } pub fn fill_forms(&self) -> bool { - self.bit(9) || self.bit(6) + if self.is_revision_3_or_later() { self.bit(9) || self.bit(6) } else { self.bit(6) } } + /// Revision 2 covers accessibility with the copy flag (bit 5); revision 3 and later with bit 10. pub fn extract_for_accessibility(&self) -> bool { - self.bit(10) + if self.is_revision_3_or_later() { self.bit(10) } else { self.bit(5) } } - /// Insert, rotate or delete pages; create bookmarks and thumbnails. + /// Insert, rotate or delete pages; create bookmarks and thumbnails. Revision 3 and later grant + /// it by bit 11 alone. Table 22 defines bit 11 for those revisions only, so at revision 2 the + /// modify flag (bit 4) covers it. pub fn assemble(&self) -> bool { - self.bit(11) || self.bit(4) + if self.is_revision_3_or_later() { self.bit(11) } else { self.bit(4) } } + /// Revision 3 and later need bit 3 as well as bit 12. Table 22 defines bit 12 for those + /// revisions only: at revision 2 the print flag (bit 3) is all there is. pub fn print_high_quality(&self) -> bool { - self.bit(12) + if self.is_revision_3_or_later() { self.print() && self.bit(12) } else { self.print() } } } @@ -250,7 +262,7 @@ impl SecurityHandler { /// edited `/P` grants nothing extra. Without a readable `/Perms`, `/P` applies as before. pub fn permissions(&self) -> Permissions { let bits = self.perms_p().map_or(self.dict.p, |p| self.dict.p & p); - Permissions { bits, owner: self.auth == Auth::Owner } + Permissions { bits, owner: self.auth == Auth::Owner, revision: self.dict.r } } /// `/P` as `/Perms` holds it: AES-256 ECB of one block (= CBC with a zero IV), marked `adb`. diff --git a/crates/crypt/src/tests.rs b/crates/crypt/src/tests.rs index 6064176d78..09a88ed129 100644 --- a/crates/crypt/src/tests.rs +++ b/crates/crypt/src/tests.rs @@ -240,11 +240,11 @@ fn unsupported_handlers_are_reported() { #[test] fn permission_bits_follow_table_22() { - let p = Permissions { bits: -3904, owner: false }; // 0xFFFFF0C0: only reserved bits set + let p = Permissions { bits: -3904, owner: false, revision: 3 }; // 0xFFFFF0C0: only reserved bits set assert!(!p.print() && !p.modify() && !p.copy() && !p.annotate() && !p.assemble()); - let p = Permissions { bits: -1, owner: false }; + let p = Permissions { bits: -1, owner: false, revision: 3 }; assert!(p.print() && p.modify() && p.copy() && p.annotate() && p.assemble() && p.fill_forms()); - let p = Permissions { bits: 0, owner: true }; + let p = Permissions { bits: 0, owner: true, revision: 3 }; assert!(p.modify(), "owners ignore /P"); } diff --git a/crates/crypt/tests/it/main.rs b/crates/crypt/tests/it/main.rs index 8b39bf1956..e7742bbd75 100644 --- a/crates/crypt/tests/it/main.rs +++ b/crates/crypt/tests/it/main.rs @@ -1,4 +1,5 @@ //! The crate's integration tests, linked into one test binary. +mod permissions_revision; mod proptests; mod qpdf_literals; diff --git a/crates/crypt/tests/it/permissions_revision.rs b/crates/crypt/tests/it/permissions_revision.rs new file mode 100644 index 0000000000..bad709cd51 --- /dev/null +++ b/crates/crypt/tests/it/permissions_revision.rs @@ -0,0 +1,126 @@ +//! The permission accessors of `pdfcraft_crypt::Permissions`, checked against the flag table of +//! ISO 32000-1:2008 (Table 22). Expected values come from that table only. +//! +//! Bit n has the mask `1 << (n - 1)`. Readers use bits 3 to 6 and 9 to 12 and ignore the rest. + +use pdfcraft_crypt::{Algorithm, Auth, NewEncryption, Permissions, SecurityHandler, create}; + +const ID: &[u8] = b"0123456789abcdef"; +const T: bool = true; +const F: bool = false; + +/// The eight accessors in this order: print, high-quality print, modify, copy, accessibility, +/// annotate, fill forms, assemble. +fn cells(p: &Permissions) -> [bool; 8] { + [p.print(), p.print_high_quality(), p.modify(), p.copy(), p.extract_for_accessibility(), p.annotate(), p.fill_forms(), p.assemble()] +} + +/// Creates a file with `flags` at revision `revision`, opens it with the user password, and +/// returns the user's permissions. +fn user_view(alg: Algorithm, revision: i64, flags: i32) -> Permissions { + let made = create( + &NewEncryption { algorithm: alg, user_password: "user", owner_password: "owner", permissions: flags, encrypt_metadata: true, seed: [42; 32] }, + ID, + ) + .expect("the handler is created"); + assert_eq!(made.dict().r, revision, "the algorithm writes revision {revision}"); + let opened = SecurityHandler::open(made.dict().clone(), ID, Some("user")).expect("the user password opens the file"); + assert_eq!(opened.auth(), Auth::User, "the user password gives user access"); + opened.permissions() +} + +/// Revision 3 and later: each row is a flag word and the expected eight cells. +const REVISION_3_ROWS: &[(&str, i32, [bool; 8])] = &[ + ("every meaningful flag set, ignored flags clear", -196, [T, T, T, T, T, T, T, T]), + ("every flag set, ignored flags set too", -1, [T, T, T, T, T, T, T, T]), + ("reserved flags only", -4096, [F, F, F, F, F, F, F, F]), + ("ignored flags set, meaningful flags clear", -3901, [F, F, F, F, F, F, F, F]), + ("modify flag clear", -9, [T, T, F, T, T, T, T, T]), + ("copy flag clear", -17, [T, T, T, F, T, T, T, T]), + ("annotate flag clear", -33, [T, T, T, T, T, F, T, T]), + ("annotate and fill-existing flags clear", -289, [T, T, T, T, T, F, F, T]), + ("annotate flag set, fill-existing flag clear", -257, [T, T, T, T, T, T, T, T]), + ("accessibility flag clear", -513, [T, T, T, T, F, T, T, T]), + ("high-quality flag clear, print flag set", -2049, [T, F, T, T, T, T, T, T]), + ("bits 3 to 12 set, reserved bits clear", 4092, [T, T, T, T, T, T, T, T]), + ("positive flag word, bit 32 clear", 2_147_483_647, [T, T, T, T, T, T, T, T]), + ("revision 2 example read at revision 3", -44, [T, T, F, T, T, F, T, T]), +]; + +#[test] +fn revision_three_rows_hold_through_a_created_and_reopened_file() { + for (name, bits, want) in REVISION_3_ROWS { + assert_eq!(cells(&user_view(Algorithm::Rc4_128, 3, *bits)), *want, "{name}: flag word {bits:#010x}"); + } +} + +#[test] +fn owner_access_gives_every_flag() { + let made = create( + &NewEncryption { + algorithm: Algorithm::Rc4_128, + user_password: "user", + owner_password: "owner", + permissions: 0, + encrypt_metadata: true, + seed: [42; 32], + }, + ID, + ) + .expect("the handler is created"); + assert_eq!(made.auth(), Auth::Owner, "the owner password gives owner access"); + assert_eq!(cells(&made.permissions()), [T; 8]); +} + +#[test] +fn revision_two_print_modify_copy_and_annotate_follow_the_table() { + for (bits, want) in [(-4, [T, T, T, T]), (-44, [T, F, T, F]), (-17, [T, T, F, T])] { + let p = user_view(Algorithm::Rc4_40, 2, bits); + assert_eq!([p.print(), p.modify(), p.copy(), p.annotate()], want, "revision 2, flag word {bits}"); + } +} + +#[test] +fn revision_two_with_every_flag_set_grants_accessibility_and_form_filling() { + let p = user_view(Algorithm::Rc4_40, 2, -4); + assert!(p.extract_for_accessibility(), "bit 5 is set, and at revision 2 it covers accessibility"); + assert!(p.fill_forms(), "bit 6 is set"); +} + +#[test] +fn revision_three_assembly_needs_its_own_flag() { + let p = user_view(Algorithm::Rc4_128, 3, -1025); + assert!(p.modify(), "bit 4 is set"); + assert!(!p.assemble(), "assembly needs bit 11; bit 4 alone does not grant it"); +} + +#[test] +fn revision_three_high_quality_print_needs_the_print_flag() { + let p = user_view(Algorithm::Rc4_128, 3, -5); + assert!(!p.print(), "bit 3 is clear"); + assert!(!p.print_high_quality(), "high-quality print needs bit 3 and bit 12"); +} + +#[test] +fn revision_two_accessibility_follows_the_copy_flag() { + let p = user_view(Algorithm::Rc4_40, 2, -17); + assert!(!p.copy(), "bit 5 is clear"); + assert!(!p.extract_for_accessibility(), "at revision 2 accessibility is bit 5"); +} + +#[test] +fn revision_two_form_filling_ignores_bit_nine() { + let p = user_view(Algorithm::Rc4_40, 2, -44); + assert!(!p.annotate(), "bit 6 is clear"); + assert!(!p.fill_forms(), "at revision 2 form filling is bit 6 alone"); +} + +#[test] +fn revision_two_ignores_the_flags_only_later_revisions_define() { + // Bit 4 is clear and bit 11 set: bit 11 means nothing at revision 2, so assembly stays refused. + let p = user_view(Algorithm::Rc4_40, 2, -44); + assert!(!p.assemble(), "at revision 2 assembly is bit 4 alone"); + // Bit 3 is set and bit 12 clear: printing at revision 2 has one quality. + let p = user_view(Algorithm::Rc4_40, 2, -2049); + assert!(p.print_high_quality(), "at revision 2 high-quality print is bit 3 alone"); +} diff --git a/crates/edit/src/lib.rs b/crates/edit/src/lib.rs index b95c4296f9..2a0add8d12 100644 --- a/crates/edit/src/lib.rs +++ b/crates/edit/src/lib.rs @@ -78,7 +78,7 @@ pub(crate) use place::undrawable; #[cfg(test)] use place::{ISOLATION_MAX_DEPTH, OLD_WRAP_CLOSE, WRAP_CLOSE, WRAP_OPEN, is_wrap_close, page_fonts, stream_bytes, stream_tag, tagged, wrapper_role}; use place::{Reach, check, check_on_top, contents, draw_on_top, lift_on_top, page_list, place_tagged, revealed_under_paint}; -pub use place::{stamp, undrawable_message}; +pub use place::{add_type3_fonts, stamp, stamp_with_fonts, undrawable_message}; #[cfg(test)] mod marked_isolation_tests; diff --git a/crates/edit/src/place.rs b/crates/edit/src/place.rs index 27ed7b3793..6460aab066 100644 --- a/crates/edit/src/place.rs +++ b/crates/edit/src/place.rs @@ -478,14 +478,79 @@ pub(crate) fn place_inside_wrapper(doc: &mut Document, page: &pdfcraft_model::Pa /// it away); the original content is wrapped in q/Q first. Used for applied redaction boxes. /// Returns the new content stream. pub fn stamp(doc: &mut Document, page: usize, tag: &str, content: Vec) -> Result { + stamp_with_fonts(doc, page, tag, &mut pdfcraft_fonts::TextPlan::default(), |_| content) +} + +/// Draw the content `make` builds on top of a page, with standard Helvetica as `/PCHelv` and +/// the plan's Type3 fonts added to the page's resources first (so the content can reference +/// them by the names the plan carries). The original content is wrapped in q/Q first; the +/// stream is tagged `tag` (not a mark kind, so Remove never takes it away). This is how the +/// OCR text layers get their Unicode faces (see [`add_type3_fonts`]). Returns the new content +/// stream. +pub fn stamp_with_fonts( + doc: &mut Document, + page: usize, + tag: &str, + plan: &mut pdfcraft_fonts::TextPlan, + make: impl FnOnce(&pdfcraft_fonts::TextPlan) -> Vec, +) -> Result { let all = page_list(doc); check(&[page], all.len())?; check_on_top(doc, &all[page])?; + add_type3_fonts(doc, page, plan)?; + let content = make(plan); + let all = page_list(doc); add_resources(doc, &all[page], None, Some(&content))?; let p = page_list(doc).swap_remove(page); place_tagged(doc, &p, tag, content, false) } +/// Add the plan's Type3 fonts to a page's (0-based) resources, building each font once and +/// sharing the object with every page that uses it. Fills in each planned font's resource name +/// (`PCOcr`, `PCOcr1`, … — a name free on the page being registered: a font built for an +/// earlier page keeps its name only where that name is free or already that font) and object; +/// the content generators read the names from the plan, so this must run before they are +/// called for each page. +pub fn add_type3_fonts(doc: &mut Document, page: usize, plan: &mut pdfcraft_fonts::TextPlan) -> Result<(), EditError> { + if plan.fonts.is_empty() { + return Ok(()); + } + let all = page_list(doc); + check(&[page], all.len())?; + let p = &all[page]; + let mut res = p.dict.get(b"Resources").map(|r| doc.resolve(r)).and_then(|r| r.as_dict().cloned()).unwrap_or_default(); + let mut fonts = res.get(b"Font").map(|f| doc.resolve(f)).and_then(|f| f.as_dict().cloned()).unwrap_or_default(); + for i in 0..plan.fonts.len() { + let object = match plan.fonts[i].object { + Some(r) => { + // Built for an earlier page under a name that was free THERE. On this page the + // name may already be another font (the page's own, or an earlier OCR layer's): + // then this page gets a free name of its own, and the plan carries it for the + // content written next. + let taken = fonts.get(plan.fonts[i].name.as_bytes()).is_some_and(|o| o.as_ref() != Some(r)); + if taken { + plan.fonts[i].name = super::text::unique_font_name(&fonts, "PCOcr"); + } + r + } + None => { + let glyphs = plan.fonts[i].glyphs.iter().map(|(ch, g)| (*ch, super::text::glyph_path(g), g.width)).collect::>(); + let dict = super::text::type3_font_dict(doc, &glyphs)?; + let r = doc.add(Object::Dict(dict)); + plan.fonts[i].name = super::text::unique_font_name(&fonts, "PCOcr"); + plan.fonts[i].object = Some(r); + r + } + }; + fonts.set(plan.fonts[i].name.as_bytes().to_vec(), Object::Ref(object)); + } + res.set(b"Font".to_vec(), Object::Dict(fonts)); + // The page gets its own (possibly copied) resources; shared dictionaries stay untouched. + let obj = p.obj; + doc.update_dict(obj, |d| d.set(b"Resources".to_vec(), Object::Dict(res)))?; + Ok(()) +} + pub(crate) fn begin(kind: MarkKind, subtype: &str, matrix: [f64; 6]) -> String { format!( "q\n/Artifact <> BDC\n{} {} {} {} {} {} cm\n", diff --git a/crates/edit/src/tests.rs b/crates/edit/src/tests.rs index cbea5c21d2..22fbd6e8ae 100644 --- a/crates/edit/src/tests.rs +++ b/crates/edit/src/tests.rs @@ -3514,7 +3514,10 @@ fn page_content_bytes(doc: &Document, page: usize) -> Vec { } } -/// A page drawing image XObject /Im0 at 100,100 size 200 × 100 (pixels 4 × 2). +/// A page drawing image XObject /Im0 at 100,100 size 200 × 100 (pixels 4 × 2), on a real optional +/// content layer: the catalog's `/OCProperties` declares object 7 as the only OCG and the page +/// resources' `/Properties` maps `/L0` to it, so `/OC /L0 BDC` marks a valid optional-content +/// member rather than a dangling name. fn image_page() -> Document { image_page_with("q 200 0 0 100 100 100 cm /Im0 Do Q BT /F1 12 Tf 72 700 Td (Caption) Tj ET") } @@ -3534,12 +3537,13 @@ fn remove_crop(doc: &mut Document, page: usize, index: usize) -> Result<(), Edit fn image_page_with(content: &str) -> Document { let objs: Vec = vec![ - "<< /Type /Catalog /Pages 2 0 R >>".into(), + "<< /Type /Catalog /Pages 2 0 R /OCProperties << /OCGs [7 0 R] /D << /Order [7 0 R] >> >> >>".into(), "<< /Type /Pages /Kids [3 0 R] /Count 1 >>".into(), - "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 600 800] /Contents 4 0 R /Resources << /Font << /F1 5 0 R >> /XObject << /Im0 6 0 R >> /ExtGState << /GS0 << /Type /ExtGState /ca 0.5 /CA 0.5 >> /GSalpha << /Type /ExtGState /ca 0.6 >> /GSblend << /Type /ExtGState /BM /Multiply >> /GS_translucent << /Type /ExtGState /ca 0.5 >> >> >> >>".into(), + "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 600 800] /Contents 4 0 R /Resources << /Font << /F1 5 0 R >> /XObject << /Im0 6 0 R >> /ExtGState << /GS0 << /Type /ExtGState /ca 0.5 /CA 0.5 >> /GSalpha << /Type /ExtGState /ca 0.6 >> /GSblend << /Type /ExtGState /BM /Multiply >> /GS_translucent << /Type /ExtGState /ca 0.5 >> >> /Properties << /L0 7 0 R >> >> >>".into(), format!("<< /Length {} >>\nstream\n{content}\nendstream", content.len()), "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>".into(), "<< /Type /XObject /Subtype /Image /Width 4 /Height 2 /ColorSpace /DeviceGray /BitsPerComponent 8 /Length 8 >>\nstream\n\u{0}\u{0}\u{0}\u{0}\u{0}\u{0}\u{0}\u{0}\nendstream".into(), + "<< /Type /OCG /Name (Layer 0) >>".into(), ]; let mut out = b"%PDF-1.7\n".to_vec(); let mut offs = Vec::new(); @@ -3753,6 +3757,30 @@ fn repeated_group_moves_of_a_cropped_image_change_one_clip_transform() { assert_eq!(caption, ["Caption"]); } +#[test] +fn moving_an_image_inside_marked_content_leaves_every_sequence_intact() { + // `translate_images` changes the image's own `cm`; its `Do` stays where it was, so a moved + // image stays in the sequence that tags it (an image on a layer sits in `/OC … BDC`). + for content in [ + "/P <> BDC q 100 0 0 100 50 50 cm /Im0 Do Q EMC /P <> BDC BT /F1 12 Tf 72 700 Td (Text) Tj ET EMC", + "/OC /L0 BDC q 100 0 0 100 50 50 cm /Im0 Do Q EMC /P <> BDC BT /F1 12 Tf 72 700 Td (Text) Tj ET EMC", + ] { + let mut doc = image_page_with(content); + let before = images::page_images(&doc, 0).unwrap()[0].rect; + images::translate_images(&mut doc, 0, &[0], [10.0, 0.0]).unwrap(); + let after = images::page_images(&doc, 0).unwrap()[0].rect; + assert!(close(after, [before[0] + 10.0, before[1], before[2] + 10.0, before[3]]), "{content}: {after:?}"); + let ops = pdfcraft_content::parse(&page_content_bytes(&doc, 0)).ops; + let count = |name: &str| ops.iter().filter(|op| op.is(name)).count(); + assert_eq!((count("BDC"), count("EMC")), (2, 2), "{content}: both sequences remain"); + let first = ops.iter().position(|op| op.is("BDC")).unwrap(); + let end = ops.iter().position(|op| op.is("EMC")).unwrap(); + let image = ops.iter().position(|op| op.is("Do")).unwrap(); + assert!(first < image && image < end, "{content}: the image is still inside its own sequence"); + assert!(!ops[end..].iter().any(|op| op.is("Do")), "{content}: the other sequence gained no image"); + } +} + #[test] fn page_images_move_turn_replace_and_delete() { let mut doc = image_page(); @@ -10229,6 +10257,86 @@ fn styled_existing_justification_is_refused_instead_of_silently_left_aligning() assert_eq!(page_content_bytes(&reopen(&doc), 0), before); } +/// The OCR stamp path registers the plan's Type3 faces (a free `PCOcr…` name per stamp, so a +/// page that is OCR'd twice keeps both layers' fonts), and the stamped codes extract back +/// through the font's ToUnicode CMap. +#[test] +fn stamp_with_fonts_registers_the_planned_type3_faces() { + if without_craft_fonts("stamp_with_fonts_registers_the_planned_type3_faces") { + return; + } + let mut doc = text_page("BT /F2 12 Tf 72 700 Td (ab) Tj ET"); + let mut plan = pdfcraft_fonts::TextPlan::for_words(["日本"]); + assert_eq!(plan.missing(), 0); + stamp_with_fonts(&mut doc, 0, "OCR", &mut plan, |p| { + let codes: Vec = p.encoding(0).iter().map(|&(_, c)| c).collect(); + let mut c = format!("BT 3 Tr /PCHelv 1 Tf\n/{} 1 Tf 100 700 Td ", p.fonts[0].name).into_bytes(); + c.extend_from_slice(&pdfcraft_fonts::literal(&codes)); + c.extend_from_slice(b" Tj ET"); + c + }) + .unwrap(); + assert!(plan.fonts[0].name.starts_with("PCOcr"), "{:?}", plan.fonts[0].name); + // The registered font carries a ToUnicode CMap; the engine's own reader decodes the run. + let reopened = Document::open(Arc::new(write_incremental(&doc, &SaveOptions::default()).unwrap())).unwrap(); + let lines = text::text_lines(&reopened, 0).unwrap(); + assert!(lines.iter().any(|l| l.text.contains("日本")), "{lines:?}"); + // A second stamp on the same page takes the next free name; the first layer's font stands. + let mut second = pdfcraft_fonts::TextPlan::for_words(["語"]); + stamp_with_fonts(&mut doc, 0, "OCR", &mut second, |p| format!("BT 3 Tr /{} 1 Tf 100 600 Td (\u{1}) Tj ET", p.fonts[0].name).into_bytes()) + .unwrap(); + assert_eq!(second.fonts[0].name, format!("{}1", plan.fonts[0].name)); +} + +/// A Type3 face built for page 1 is reused on page 2, but page 2 already has a font under the +/// name page 1 gave it: page 2's own font keeps its name, and the shared face is registered on +/// page 2 under a free one that the plan carries for page 2's content. (The plan is written out +/// by hand, so this runs without the craft-fonts build input.) +#[test] +fn a_reused_type3_face_never_replaces_a_later_page_s_font_of_the_same_name() { + let mut doc = build(&[ + "<< /Type /Catalog /Pages 2 0 R >>", + "<< /Type /Pages /Kids [3 0 R 4 0 R] /Count 2 >>", + "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 600 800] /Contents 5 0 R >>", + "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 600 800] /Contents 6 0 R /Resources << /Font << /PCOcr 7 0 R >> >> >>", + &stream("", ""), + &stream("", "BT /PCOcr 12 Tf 72 700 Td (own) Tj ET"), + "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>", + ]); + let glyph = pdfcraft_fonts::GlyphOutline { contours: vec![vec![[0.1, 0.0], [0.9, 0.0], [0.5, 0.8]]], width: 1.0, bbox: [0.1, 0.0, 0.9, 0.8] }; + let mut plan = pdfcraft_fonts::TextPlan::default(); + plan.fonts.push(pdfcraft_fonts::PlannedType3 { family: "Test", glyphs: vec![('日', glyph)], name: String::new(), object: None }); + let draw = |p: &pdfcraft_fonts::TextPlan| format!("BT 3 Tr /{} 1 Tf 100 600 Td (\u{1}) Tj ET", p.fonts[0].name).into_bytes(); + stamp_with_fonts(&mut doc, 0, "OCR", &mut plan, draw).unwrap(); + assert_eq!(plan.fonts[0].name, "PCOcr", "free on page 1"); + let face = plan.fonts[0].object.expect("built once"); + stamp_with_fonts(&mut doc, 1, "OCR", &mut plan, draw).unwrap(); + assert_ne!(plan.fonts[0].name, "PCOcr", "page 2 already has a PCOcr"); + let page2 = &pdfcraft_model::pages(&doc)[1]; + let res = doc.resolve(page2.dict.get(b"Resources").unwrap()); + let fonts = doc.resolve(res.as_dict().unwrap().get(b"Font").unwrap()); + let fonts = fonts.as_dict().unwrap(); + assert_eq!(fonts.get(b"PCOcr").and_then(|o| o.as_ref()), Some(pdfcraft_cos::ObjRef::new(7, 0)), "page 2's own font keeps its name"); + assert_eq!(fonts.get(plan.fonts[0].name.as_bytes()).and_then(|o| o.as_ref()), Some(face), "the shared face, under a free name"); + assert_eq!(plan.fonts[0].object, Some(face), "still built once"); +} + +#[test] +fn planned_type3_charproc_has_valid_metrics_and_encloses_its_ink() { + let glyph = pdfcraft_fonts::GlyphOutline { + contours: vec![vec![[-0.1001, -0.2001], [0.9001, 1.1001]]], + width: 0.8, + bbox: [-0.1001, -0.2001, 0.9001, 1.1001], + }; + let parsed = pdfcraft_content::parse(&text::glyph_path(&glyph)); + assert_eq!(parsed.skipped, 0); + let metrics = &parsed.ops[0]; + assert!(metrics.is("d1")); + assert_eq!(metrics.operands.len(), 6); + assert_eq!((metrics.num(0), metrics.num(1)), (Some(800.0), Some(0.0))); + assert_eq!((metrics.num(2), metrics.num(3), metrics.num(4), metrics.num(5)), (Some(-101.0), Some(-201.0), Some(901.0), Some(1101.0))); +} + #[test] fn image_arrange_refuses_crossed_scope_boundaries_without_changes() { for content in ["/P <> BDC q 10 0 0 10 0 0 cm /Im0 Do EMC Q /Im0 Do", "q /P <> BDC /Im0 Do Q EMC /Im0 Do"] { diff --git a/crates/edit/src/text.rs b/crates/edit/src/text.rs index 0fb00324b6..3d1626a576 100644 --- a/crates/edit/src/text.rs +++ b/crates/edit/src/text.rs @@ -52,6 +52,7 @@ use fallback::{ }; #[cfg(test)] use fallback::{add_type3_font, is_type3_fallback}; +pub(crate) use fallback::{glyph_path, type3_font_dict, unique_font_name}; use interp::{Origin, Paint, union}; use lines::page_dict; pub(crate) use lines::{FormBudget, content_streams, content_streams_within, dict_in_place, form_call, resource_dict, rewritten_contents, splice}; diff --git a/crates/edit/src/text/fallback.rs b/crates/edit/src/text/fallback.rs index 78f9014a20..469d1739d4 100644 --- a/crates/edit/src/text/fallback.rs +++ b/crates/edit/src/text/fallback.rs @@ -493,6 +493,92 @@ pub(super) fn add_type3_font(doc: &mut Document, fonts_res: &mut Dict, face: &Cr name } +/// A glyph's CharProc body at 1000 units per em, with a six-operand `d1` and its actual ink box. +pub(crate) fn glyph_path(glyph: &pdfcraft_fonts::GlyphOutline) -> Vec { + let scale = 1000.0; + let b = if glyph.contours.is_empty() { [0.0; 4] } else { glyph.bbox }; + let mut out = format!( + "{} 0 {} {} {} {} d1\n", + pdf_num(glyph.width * scale), + pdf_num((b[0] * scale).floor()), + pdf_num((b[1] * scale).floor()), + pdf_num((b[2] * scale).ceil()), + pdf_num((b[3] * scale).ceil()) + ) + .into_bytes(); + for contour in &glyph.contours { + let Some(first) = contour.first() else { continue }; + out.extend_from_slice(format!("{} {} m\n", pdf_num(first[0] * scale), pdf_num(first[1] * scale)).as_bytes()); + for p in contour.iter().skip(1) { + out.extend_from_slice(format!("{} {} l\n", pdf_num(p[0] * scale), pdf_num(p[1] * scale)).as_bytes()); + } + out.extend_from_slice(b"h\n"); + } + out.extend_from_slice(b"f\n"); + out +} + +/// A resource name free in `fonts_res`: `base`, then `base1`, `base2`, … (a page that was +/// OCR'd twice keeps both layers' fonts distinct). +pub(crate) fn unique_font_name(fonts_res: &Dict, base: &str) -> String { + let mut name = String::from(base); + let mut suffix = 0usize; + while fonts_res.contains(name.as_bytes()) { + suffix = suffix.saturating_add(1); + name = format!("{base}{suffix}"); + } + name +} + +/// The Type3 font dictionary for `(character, CharProc body, advance in em)` glyphs, codes from +/// 1: one CharProc per code, `/Differences` glyph names, real `/Widths`, and a `/ToUnicode` CMap +/// so the text extracts back (this is what makes the output Unicode-correct, not just visible). +pub(crate) fn type3_font_dict(doc: &mut Document, glyphs: &[(char, Vec, f64)]) -> Result { + let mut charprocs = Dict::new(); + let mut differences = vec![Object::Int(1)]; + let mut widths = Vec::with_capacity(glyphs.len()); + let mut cmap = String::from( + "/CIDInit /ProcSet findresource begin\n12 dict begin\nbegincmap\n/CMapType 2 def\n1 begincodespacerange\n<01> \nendcodespacerange\n", + ); + cmap.push_str(&format!("{} beginbfchar\n", glyphs.len())); + let mut codes = Vec::with_capacity(glyphs.len()); + for (i, (ch, path, width)) in glyphs.iter().enumerate() { + let code = u8::try_from(i + 1).map_err(|_| EditError::Invalid("too many unique characters for one font".into()))?; + let glyph_name = format!("g{code:02X}"); + let mut pd = Dict::new(); + pd.set(b"Length".to_vec(), path.len() as i64); + let proc_ref = doc.add(Object::Stream(Stream::from_raw(pd, path.clone()))); + charprocs.set(glyph_name.as_bytes().to_vec(), Object::Ref(proc_ref)); + differences.push(Object::name(&glyph_name)); + widths.push(Object::Real((width * 1000.0).round())); + cmap.push_str(&format!("<{code:02X}> <{}>\n", unicode_hex(*ch))); + codes.push((*ch, code, *width)); + } + cmap.push_str("endbfchar\nendcmap\nCMapName currentdict /CMap defineresource pop\nend\nend\n"); + let mut cmap_dict = Dict::new(); + cmap_dict.set(b"Length".to_vec(), cmap.len() as i64); + let cmap_ref = doc.add(Object::Stream(Stream::from_raw(cmap_dict, cmap.into_bytes()))); + let mut encoding = Dict::new(); + encoding.set(b"Type".to_vec(), Object::name("Encoding")); + encoding.set(b"Differences".to_vec(), Object::Array(differences)); + let mut font = Dict::new(); + font.set(b"Type".to_vec(), Object::name("Font")); + font.set(b"Subtype".to_vec(), Object::name("Type3")); + font.set(b"Name".to_vec(), Object::name("PCFallback")); + font.set(b"FontBBox".to_vec(), Object::Array(vec![Object::Int(0), Object::Int(-300), Object::Int(1000), Object::Int(1000)])); + font.set( + b"FontMatrix".to_vec(), + Object::Array(vec![Object::Real(0.001), Object::Int(0), Object::Int(0), Object::Real(0.001), Object::Int(0), Object::Int(0)]), + ); + font.set(b"FirstChar".to_vec(), Object::Int(1)); + font.set(b"LastChar".to_vec(), Object::Int(codes.len() as i64)); + font.set(b"Widths".to_vec(), Object::Array(widths)); + font.set(b"Encoding".to_vec(), Object::Dict(encoding)); + font.set(b"CharProcs".to_vec(), Object::Dict(charprocs)); + font.set(b"ToUnicode".to_vec(), Object::Ref(cmap_ref)); + Ok(font) +} + /// The runs that show `text` in the fallback: consecutive characters in one font form one run, so /// a font is switched only where the text moves to another font. `None` if a character has no code. pub(super) fn type3_encode(fallback: &Type3Fallback, text: &str) -> Option)>> { diff --git a/crates/engine/src/actions.rs b/crates/engine/src/actions.rs index 3e942f6a2f..249279e09d 100644 --- a/crates/engine/src/actions.rs +++ b/crates/engine/src/actions.rs @@ -197,14 +197,14 @@ fn apply_step(s: &mut Session, id: DocId, step: &Step, log: &mut Vec) -> return Ok(None); } }; - // Steps that find nothing to do (no comments to flatten, …) aren't failures. A removal step - // that didn't remove is: the file would be passed on as cleaned with the data still in it. + // A step that finds nothing to do is not a failure. Any other error fails the file, so nothing is + // published for it: the file would otherwise be passed on without the step it was asked to apply. let removes = matches!(step, Step::RemoveHiddenInformation | Step::Sanitize); match s.apply(id, edit) { Ok(()) => log.push(step.label().to_string()), Err(EditError::Redact(pdfcraft_redact::RedactError::NothingToApply)) if removes => log.push(format!("{}: nothing to remove", step.label())), - Err(e) if removes => return Err(e), - Err(e) => log.push(format!("{}: {e}", step.label())), + Err(EditError::Redact(pdfcraft_redact::RedactError::NothingToApply)) => log.push(format!("{}: nothing to do", step.label())), + Err(e) => return Err(e), } Ok(None) } diff --git a/crates/engine/src/catalog.rs b/crates/engine/src/catalog.rs index 47394a7bb5..d6be8fd4eb 100644 --- a/crates/engine/src/catalog.rs +++ b/crates/engine/src/catalog.rs @@ -267,7 +267,7 @@ pub static TOOL_GROUPS: &[ToolGroup] = &[ item("In multiple files", "files", "ocr.recognize_batch", Ready), item("Enhance scanned file", "sparkles", "ocr.enhance", Ready), item("Enhance camera image", "camera", "ocr.enhance_camera", Ready), - item("Correct recognized text", "text-select", "ocr.correct", Planned("M10")), + item("Correct recognized text", "text-select", "ocr.correct", Ready), ], }], }, diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs index bd229656a6..7cee14657e 100644 --- a/crates/engine/src/commands.rs +++ b/crates/engine/src/commands.rs @@ -220,6 +220,10 @@ pub const COMMANDS: &[CommandSpec] = &[ // Alt-drag for moving windows (several Linux window managers). // Copy events stay with the frontend so focused text inputs and page clipboard routing keep ownership. c("edit.copy", "Copy", EDIT, None, Copying, "copy"), + // Comments travel between documents as XFDF (M14): ⌘C with comments selected copies them, + // ⌘V pastes the copies onto the current page; the strip's Copy/Paste in the menus too. + c("comment.copy", "Copy comments", EDIT, None, Document, "copy"), + c("comment.paste", "Paste comments", EDIT, None, Annotate, "clipboard-paste"), c("edit.column_select", "Column select", EDIT, None, Document, "text-select"), c("edit.snapshot", "Take a snapshot", EDIT, None, Copying, "camera"), c("view.full_screen", "Full screen mode", VIEW, Some(Shortcut::cmd("L")), Document, "maximize"), @@ -357,6 +361,7 @@ pub const COMMANDS: &[CommandSpec] = &[ c("ocr.enhance_camera", "Enhance camera image", None, None, Modification, "camera"), c("ocr.enhance", "Enhance scanned file…", None, None, Modification, "sparkles"), c("ocr.recognize_batch", "Recognize text in multiple files…", None, None, Nothing, "files"), + c("ocr.correct", "Correct recognized text…", None, None, Document, "text-select"), c("a11y.check", "Check for accessibility…", None, None, Document, "accessibility"), c("a11y.find_untagged", "Find untagged content", None, None, Document, "search"), c("a11y.autotag", "Automatically tag PDF", None, None, Document, "tag"), diff --git a/crates/engine/src/compare.rs b/crates/engine/src/compare.rs index fe5af55706..de739101d5 100644 --- a/crates/engine/src/compare.rs +++ b/crates/engine/src/compare.rs @@ -63,6 +63,15 @@ impl Session { Ok(pdfcraft_compare::compare(&a.words(), &b.words())) } + /// [`Session::compare`], keeping the changes on `pages` of `new` (0-based; empty: every page). + pub fn compare_pages(&self, old: DocId, new: DocId, pages: &[usize]) -> Result { + let mut c = self.compare(old, new)?; + if !pages.is_empty() { + c.changes.retain(|ch| pages.iter().any(|page| (ch.new.page..=ch.new.last_page).contains(page))); + } + Ok(c) + } + /// Visual compare: regions where page n of `new` looks different from page n of `old` /// (rendered at `dpi`), as (page, user-space box in `new`). pub fn compare_visual(&self, old: DocId, new: DocId, dpi: f32) -> Result, EditError> { @@ -95,7 +104,12 @@ impl Session { /// The compare report as a new PDF (not opened). pub fn compare_report(&self, old: DocId, new: DocId) -> Result>, EditError> { - let c = self.compare(old, new)?; + self.compare_report_of(old, new, &[]) + } + + /// [`Session::compare_report`] of the changes on `pages` ([`Session::compare_pages`]). + pub fn compare_report_of(&self, old: DocId, new: DocId, pages: &[usize]) -> Result>, EditError> { + let c = self.compare_pages(old, new, pages)?; let name = |id| self.get(id).map(|d| d.name.clone()).unwrap_or_default(); self.create_report("Compare Report", &pdfcraft_compare::report(&c, &name(old), &name(new))) } @@ -104,7 +118,12 @@ impl Session { /// (blue, green) and a note where text was deleted (red), authored "Compare". One undoable /// step; returns how many comments were added. pub fn mark_differences(&mut self, old: DocId, new: DocId) -> Result { - let c = self.compare(old, new)?; + self.mark_differences_of(old, new, &[]) + } + + /// [`Session::mark_differences`] of the changes on `pages` ([`Session::compare_pages`]). + pub fn mark_differences_of(&mut self, old: DocId, new: DocId, pages: &[usize]) -> Result { + let c = self.compare_pages(old, new, pages)?; let mut edits = Vec::new(); for ch in &c.changes { let color = colour(ch.kind); diff --git a/crates/engine/src/dates.rs b/crates/engine/src/dates.rs index c9382c1b02..5ede67c811 100644 --- a/crates/engine/src/dates.rs +++ b/crates/engine/src/dates.rs @@ -582,6 +582,18 @@ pub fn date_language(code: &str) -> Option<&'static DateLanguage> { DATE_LANGUAGES.iter().find(|l| l.code.eq_ignore_ascii_case(code.trim())) } +/// Form date fields (`AFDate_FormatEx`, `util.printd`, `util.scand`) write month and weekday +/// names in date language `code` from now on, as a localized Acrobat writes its own language's: +/// `dd-mmm-yy` is `18-ott-26` in Italian (#5303). An unknown code is English. +pub fn use_form_date_language(code: &str) { + let l = date_language(code).unwrap_or(&DATE_LANGUAGES[0]); + let names = pdfcraft_forms::af::DateNames { months: l.months, months_short: l.months_short, days: l.days, days_short: l.days_short }; + if pdfcraft_forms::af::date_names() != names { + pdfcraft_forms::af::set_date_names(names); + pdfcraft_js::set_date_names(l.months, l.months_short, l.days, l.days_short); + } +} + /// The characters of `text` that Fill & Sign can't write into a PDF yet, each once. Its text is /// drawn in Helvetica with WinAnsi encoding (Western European letters), so anything else (`ř`, /// Japanese, Chinese) would become `?` in the file. diff --git a/crates/engine/src/document.rs b/crates/engine/src/document.rs index fa98a18417..279dc8d563 100644 --- a/crates/engine/src/document.rs +++ b/crates/engine/src/document.rs @@ -539,7 +539,7 @@ impl Document { _ => "Attachments only", }; let pending = editor.cos.encryption_changed(); - let permissions = if pending { pdfcraft_cos::Permissions { bits: h.permissions().bits, owner: false } } else { h.permissions() }; + let permissions = if pending { pdfcraft_cos::Permissions { owner: false, ..h.permissions() } } else { h.permissions() }; Some(SecuritySummary { method: method.into(), owner: h.auth() == pdfcraft_cos::Auth::Owner && !pending, permissions, pending }) } diff --git a/crates/engine/src/edit.rs b/crates/engine/src/edit.rs index 40745f8c2a..1bcf24108f 100644 --- a/crates/engine/src/edit.rs +++ b/crates/engine/src/edit.rs @@ -3,10 +3,11 @@ use std::sync::Arc; use crate::{ - AddedContent, AddedText, Background, BoxSpec, EditError, FieldProps, FieldValue, FillMark, HeaderFooter, Hidden, ImageEdit, InitialView, Label, - LineEnding, LinkAction, LinkStyle, MarkFile, MarkKind, Markup, NewAnnotation, NewField, NoteIcon, ObjectTarget, PageBox, Protection, ReviewState, - Rgb, Shape, Standard, Style, TabOrder, TransitionSpec, Watermark, a11y, copy_image, decode_data_file, embed_image, field_table, fit_picture, - image_content_type, is_xfa_data_file, js, mark_source, measure, model_poster, open_source, strip_xfa, unrestricted, xfa, xfa_after_data_change, + AddedContent, AddedText, Background, BorderShape, BoxSpec, EditError, FieldProps, FieldValue, FillMark, HeaderFooter, Hidden, ImageEdit, + InitialView, Label, LineEnding, LinkAction, LinkStyle, MarkFile, MarkKind, Markup, NewAnnotation, NewField, NoteIcon, ObjectTarget, PageBox, + Protection, ReviewState, Rgb, Shape, Standard, Style, TabOrder, TransitionSpec, Watermark, a11y, copy_image, decode_data_file, embed_image, + field_table, fit_picture, image_content_type, is_xfa_data_file, js, mark_source, measure, model_poster, open_source, strip_xfa, unrestricted, + xfa, xfa_after_data_change, }; mod labels; @@ -263,12 +264,35 @@ pub enum Edit { index: usize, fill: Option, }, + /// Draw a rectangle's, oval's, polygon's or text box's fill, or a text box's text, at an + /// opacity of its own (0–1), the line or border keeping the comment's; `None` leaves that + /// part as it is. `StyleAnnotation`'s opacity sets the whole comment's. + PartOpacity { + page: usize, + index: usize, + fill: Option, + text: Option, + }, /// Change the font size (pt) of a text box, typewriter text or callout. FontSizeAnnotation { page: usize, index: usize, size: f64, }, + /// Give a text box, typewriter text or callout a border colour of its own (`None`: the + /// text's again). + BorderColorAnnotation { + page: usize, + index: usize, + color: Option, + }, + /// Give a text box or typewriter text an oval, a circle or a rectangle for its border: the + /// text box keeps its place, the oval or circle goes around it. + BorderShapeAnnotation { + page: usize, + index: usize, + shape: BorderShape, + }, /// Comment properties ▸ General / note icon. SetAnnotationInfo { page: usize, @@ -561,6 +585,15 @@ pub enum Edit { name: String, bytes: Arc>, }, + /// Paste copied comments (XFDF from [`Session::export_comments`]) onto `page` as new + /// comments: copies under names of their own, so nothing is replaced and pasting twice + /// gives two sets; replies keep their copied parent. + PasteComments { + xfdf: String, + page: usize, + /// Where the copies go: moved by (dx, dy) in user space, or at their own positions. + offset: Option<[f64; 2]>, + }, /// Remove Hidden Information: the chosen categories. RemoveHidden { which: Vec, diff --git a/crates/engine/src/edit/labels.rs b/crates/engine/src/edit/labels.rs index e0ec47a2ba..615ac0fea5 100644 --- a/crates/engine/src/edit/labels.rs +++ b/crates/engine/src/edit/labels.rs @@ -71,6 +71,7 @@ pub const EDIT_LABELS: &[&str] = &[ "Add stamp", "Add 3D model", "Delete comment", + "Paste comments", "Edit comment", "Reply", "Set status None", @@ -211,6 +212,7 @@ impl Edit { Edit::AddCustomStamp { .. } => Label::of("Add stamp"), Edit::AddModel3d { .. } => Label::of("Add 3D model"), Edit::DeleteAnnotation { .. } => Label::of("Delete comment"), + Edit::PasteComments { .. } => Label::of("Paste comments"), Edit::SetAnnotationContents { .. } => Label::of("Edit comment"), Edit::ReplyToAnnotation { .. } => Label::of("Reply"), // The state's name is part of the wording: a language may need to agree it with the rest. @@ -230,9 +232,13 @@ impl Edit { Edit::MoveAnnotation { .. } => Label::of("Move comment"), Edit::ReshapeAnnotation { .. } => Label::of("Reshape comment"), Edit::ResizeAnnotation { .. } => Label::of("Resize comment"), - Edit::StyleAnnotation { .. } | Edit::FillAnnotation { .. } | Edit::FontSizeAnnotation { .. } | Edit::SetAnnotationInfo { .. } => { - Label::of("Change comment properties") - } + Edit::StyleAnnotation { .. } + | Edit::FillAnnotation { .. } + | Edit::PartOpacity { .. } + | Edit::FontSizeAnnotation { .. } + | Edit::BorderColorAnnotation { .. } + | Edit::BorderShapeAnnotation { .. } + | Edit::SetAnnotationInfo { .. } => Label::of("Change comment properties"), Edit::SetFieldValue { name, .. } => Label::with("Fill in {name}", name.as_str()), Edit::SetFieldImage { name, .. } => Label::with("Set the image of {name}", name.as_str()), Edit::ResetForm { .. } => Label::of("Clear form"), diff --git a/crates/engine/src/edit/run.rs b/crates/engine/src/edit/run.rs index c11904a74e..4719de302f 100644 --- a/crates/engine/src/edit/run.rs +++ b/crates/engine/src/edit/run.rs @@ -49,6 +49,7 @@ pub(crate) fn check_permission(edit: &Edit, p: &pdfcraft_cos::Permissions) -> Re } Edit::AddMeasurement(_) | Edit::AddAnnotation(_) + | Edit::PasteComments { .. } | Edit::AddCustomStamp { .. } | Edit::AddModel3d { .. } | Edit::DeleteAnnotation { .. } @@ -64,7 +65,10 @@ pub(crate) fn check_permission(edit: &Edit, p: &pdfcraft_cos::Permissions) -> Re | Edit::ResizeAnnotation { .. } | Edit::StyleAnnotation { .. } | Edit::FillAnnotation { .. } + | Edit::PartOpacity { .. } | Edit::FontSizeAnnotation { .. } + | Edit::BorderColorAnnotation { .. } + | Edit::BorderShapeAnnotation { .. } | Edit::SetAnnotationInfo { .. } | Edit::SetMeasurementScale { .. } => { if p.annotate() { @@ -495,6 +499,14 @@ pub(crate) fn run_edit(doc: &mut pdfcraft_cos::Document, edit: &Edit, cx: &mut E Edit::AddAnnotation(a) => { pdfcraft_annot::add_annotation(doc, a, &cx.meta())?; } + Edit::PasteComments { xfdf, page, offset } => { + // Names from the edit's own id generator: unique to this paste within the document. + let prefix = cx.meta().id; + let report = pdfcraft_xfdf::import_comments(doc, xfdf, Some(*page), Some(&prefix), *offset)?; + if report.comments == 0 { + return Err(EditError::Invalid("the clipboard holds no comments".into())); + } + } Edit::AddCustomStamp { page, rect, name, file, author } => { let src = mark_source(doc, file)?; let (sw, sh) = (src.size.0.max(1.0), src.size.1.max(1.0)); @@ -575,7 +587,10 @@ pub(crate) fn run_edit(doc: &mut pdfcraft_cos::Document, edit: &Edit, cx: &mut E )?; } Edit::FillAnnotation { page, index, fill } => pdfcraft_annot::set_fill(doc, *page, *index, *fill, &cx.meta())?, + Edit::PartOpacity { page, index, fill, text } => pdfcraft_annot::set_part_opacity(doc, *page, *index, *fill, *text, &cx.meta())?, Edit::FontSizeAnnotation { page, index, size } => pdfcraft_annot::set_font_size(doc, *page, *index, *size, &cx.meta())?, + Edit::BorderColorAnnotation { page, index, color } => pdfcraft_annot::set_border_color(doc, *page, *index, *color, &cx.meta())?, + Edit::BorderShapeAnnotation { page, index, shape } => pdfcraft_annot::set_border_shape(doc, *page, *index, *shape, &cx.meta())?, Edit::SetAnnotationInfo { page, index, author, subject, icon } => { pdfcraft_annot::set_info(doc, *page, *index, author.as_deref(), subject.as_deref(), *icon, &cx.meta())?; } @@ -703,7 +718,7 @@ pub(crate) fn run_edit(doc: &mut pdfcraft_cos::Document, edit: &Edit, cx: &mut E Edit::RemoveStandardId { standard } => pdfcraft_organize::remove_standard_id(doc, *standard)?, Edit::SetDocumentScript { name, script } => pdfcraft_forms::set_document_script(doc, name, script.as_deref())?, Edit::AddOcrText { page, words } => { - pdfcraft_edit::stamp(doc, *page, "OCR", pdfcraft_ocr::text_layer(words))?; + crate::ocr::layer::add_text(doc, *page, words)?; } Edit::EnhanceScan { images } => crate::scan_clean::write_back(doc, images)?, Edit::EditPageImage { page, index, change } => run_edit_page_image(doc, *page, *index, change)?, diff --git a/crates/engine/src/history.rs b/crates/engine/src/history.rs index 416cdc1d54..ce51df5e61 100644 --- a/crates/engine/src/history.rs +++ b/crates/engine/src/history.rs @@ -53,6 +53,7 @@ pub(crate) fn scope_of(edit: &Edit) -> Scope { Edit::AddAnnotation(a) if matches!(a.shape, Shape::Attachment { .. }) => Scope::Full, Edit::AddMeasurement(_) | Edit::AddAnnotation(_) + | Edit::PasteComments { .. } | Edit::AddCustomStamp { .. } | Edit::AddModel3d { .. } | Edit::DeleteAnnotation { .. } @@ -68,7 +69,10 @@ pub(crate) fn scope_of(edit: &Edit) -> Scope { | Edit::ResizeAnnotation { .. } | Edit::StyleAnnotation { .. } | Edit::FillAnnotation { .. } + | Edit::PartOpacity { .. } | Edit::FontSizeAnnotation { .. } + | Edit::BorderColorAnnotation { .. } + | Edit::BorderShapeAnnotation { .. } | Edit::SetAnnotationInfo { .. } => Scope::Comments, Edit::AddLink { .. } | Edit::SetLink { .. } | Edit::DeleteLink { .. } | Edit::RemoveLinks { .. } | Edit::AddLinks { .. } => Scope::Links, Edit::SetFieldValue { .. } | Edit::ResetForm { .. } | Edit::SetFieldImage { .. } | Edit::ApplyScriptChanges { .. } => Scope::Form, diff --git a/crates/engine/src/js.rs b/crates/engine/src/js.rs index d1ee5c15b0..cc78785815 100644 --- a/crates/engine/src/js.rs +++ b/crates/engine/src/js.rs @@ -199,6 +199,24 @@ impl Scripts for JsRunner { /// Run field `target`'s script for `event` over the form's fields, keeping what it showed and /// asked for; a refusal carries its last message. fn run(&mut self, event: FieldEvent, script: &str, target: &Field, value: &str, fields: &[Field]) -> ScriptResult { + // As in Acrobat, a failing script leaves the value alone (the error goes to the console). + self.run_logged(event, script, target, value, fields, true).unwrap_or_else(|| ScriptResult { + rc: true, + value: value.to_string(), + changes: Vec::new(), + message: None, + }) + } + + fn rerun_with_english_dates(&mut self, event: FieldEvent, script: &str, target: &Field, value: &str, fields: &[Field]) -> Option { + pdfcraft_js::with_english_printd(true, || self.run_logged(event, script, target, value, fields, false)) + } +} + +impl JsRunner { + /// [`Scripts::run`], keeping what the script showed and asked for only when `log`; `None` + /// when the script failed. + fn run_logged(&mut self, event: FieldEvent, script: &str, target: &Field, value: &str, fields: &[Field], log: bool) -> Option { let states: Vec<_> = fields .iter() .map(|f| { @@ -212,17 +230,18 @@ impl Scripts for JsRunner { let states = std::sync::Arc::new(states); let ev = pdfcraft_js::Event::field(event.name(), &target.name, value); let o = pdfcraft_js::run_shared(script, &ev, &self.doc, std::sync::Arc::clone(&states), &self.doc_scripts, Limits::default()); - self.output.absorb(&o); - if o.error.is_some() { - // As in Acrobat, a failing script leaves the value alone (the error goes to the console). - return ScriptResult { rc: true, value: value.to_string(), changes: Vec::new(), message: None }; + if log { + self.output.absorb(&o); } - ScriptResult { + if o.error.is_some() { + return None; + } + Some(ScriptResult { rc: o.rc, value: o.value.clone(), changes: changes(&states, &o.changed), message: (!o.rc).then(|| o.alerts.last().map(|m| m.text.clone())).flatten(), - } + }) } } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 59cb539fa1..99b2fdac69 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -115,8 +115,8 @@ pub use pdfcraft_fonts::{MAX_SIGNATURE_CHARS, ScriptOutline, script_missing, scr pub use pdfcraft_annot::appearance as annot_text; pub use pdfcraft_annot::links::{Highlight as LinkHighlight, LinkAction, LinkItem, LinkStyle}; pub use pdfcraft_annot::{ - Activation3d, AppearanceCache, AttachIcon, FillMark, LineEnding, Markup, NOTE_SIZE, NewAnnotation, NoteIcon, OverlayFont, OverlayLook, - Props as CommentProps, ReviewState, Rgb, Shape, StampGroup, StampKind, Style, rect_quad, + Activation3d, AppearanceCache, AttachIcon, BorderShape, FillMark, LineEnding, Markup, NOTE_SIZE, NewAnnotation, NoteIcon, OverlayFont, + OverlayLook, Props as CommentProps, ReviewState, Rgb, Shape, StampGroup, StampKind, Style, rect_quad, }; pub use pdfcraft_annot::{MAX_MODEL_BYTES as MAX_3D_MODEL_BYTES, ModelFormat as Model3dFormat}; pub use pdfcraft_forms::detect; @@ -131,6 +131,7 @@ pub use pdfcraft_redact::sanitize::{HIDDEN, Hidden}; pub use pdfcraft_sign as sign; pub use pdfcraft_sign::{SignOptions, SignatureInfo, Status as SignatureStatus, TrustStore}; pub use pdfcraft_xfdf::Format as DataFormat; +pub use pdfcraft_xfdf::{Outline as CommentOutline, comment_count, comment_outlines, comments_bounds, is_xfdf_comments}; use bookmarks::outline_rows; pub use bookmarks::{BookmarkPage, BookmarkRow}; diff --git a/crates/engine/src/ocr.rs b/crates/engine/src/ocr.rs index 6b9869cead..18ea331d41 100644 --- a/crates/engine/src/ocr.rs +++ b/crates/engine/src/ocr.rs @@ -3,16 +3,104 @@ //! //! Recognition is slow (about a second a page), so it is split from the edit: [`Session::ocr_job`] //! captures what it needs, [`OcrJob::run`] works anywhere (the UI runs it on a worker thread) and -//! [`Session::apply_ocr`] applies the result as one undoable step. +//! [`Session::apply_ocr`] applies the result as one undoable step. The result is only applied +//! while the document is still the one that was read — [`Session::apply_ocr_checked`] refuses a +//! stale result with a named reason instead of writing into a changed document. use std::sync::{Arc, Mutex}; +#[cfg(not(target_arch = "wasm32"))] +use std::time::{Duration, Instant}; use pdfcraft_render::{PageInfo, PageRenderer, RenderConfig, RenderRequest, RequestKind}; -pub use pdfcraft_ocr::{LANGUAGES, Models, Ocr, OcrError, PlacedWord}; +pub use pdfcraft_ocr::{ + ConfidenceBand, LANGUAGES, MergeStrategy, Models, Ocr, OcrError, PlacedWord, Recognizer, band_for, is_suspect, low_confidence, +}; use crate::{DocId, Edit, EditError, Session}; +pub mod dictionary; +pub(crate) mod layer; + +/// Bound recognition/review inputs before cloning or planning glyphs. +pub fn validate_ocr_words<'a>(words: impl IntoIterator) -> Result { + layer::validate_words(words).map_err(|e| e.to_string()) +} + +/// Which recognition engine to use. The default is ocrs, the pure-Rust engine; "Automatic" is +/// an ensemble — ocrs reading first, Tesseract as a second opinion, merged per the strategy — +/// when both are available. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +pub enum EngineChoice { + /// The pure-Rust ocrs engine (the default). + #[default] + Ocrs, + /// The installed `tesseract` binary, as an external process. + Tesseract, + /// Ensemble: the default engine first, the other one as a secondary when available. + Auto, +} + +impl EngineChoice { + /// Parse a choice; unknown names fall back to the default (ocrs), like Acrobat's dialogs + /// fall back for unknown persisted values. + pub fn parse(s: &str) -> EngineChoice { + match s.trim().to_ascii_lowercase().as_str() { + "tesseract" => EngineChoice::Tesseract, + "auto" | "automatic" | "ensemble" => EngineChoice::Auto, + _ => EngineChoice::Ocrs, + } + } + + /// The strategy this choice reads with when none was chosen. Automatic exists to bring in + /// the second engine, so it asks it when the first reading is weak or of unknown + /// confidence ([`MergeStrategy::ConfidenceWeighted`]); a single named engine reads alone. + pub fn default_strategy(self) -> MergeStrategy { + match self { + EngineChoice::Auto => MergeStrategy::ConfidenceWeighted, + EngineChoice::Ocrs | EngineChoice::Tesseract => MergeStrategy::PrimaryOnly, + } + } + + /// The name settings and tools use for this choice. + pub fn name(self) -> &'static str { + match self { + EngineChoice::Ocrs => "ocrs", + EngineChoice::Tesseract => "tesseract", + EngineChoice::Auto => "auto", + } + } +} + +/// What to produce from a recognition. **Searchable** (the default) adds the existing +/// invisible-text layer on the original page; **EditableText** writes a *new* document with the +/// reviewed words as visible text and no scan image (the writer is the Verify screen's; the mode +/// is plumbed through here). Unknown mode strings mean Searchable. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +pub enum OutputMode { + #[default] + Searchable, + EditableText, +} + +impl OutputMode { + /// Parse a mode name (trimmed, case-insensitive); unknown strings mean Searchable. + pub fn parse(s: &str) -> OutputMode { + match s.trim().to_ascii_lowercase().as_str() { + "editable" | "editable-text" | "editable_text" | "editabletext" => OutputMode::EditableText, + _ => OutputMode::Searchable, + } + } + + /// The name settings and tools use for this mode. + pub fn name(self) -> &'static str { + match self { + OutputMode::Searchable => "searchable", + OutputMode::EditableText => "editable", + } + } +} + /// Recognize Text settings. #[derive(Clone, Debug, PartialEq)] pub struct OcrSettings { @@ -29,6 +117,40 @@ pub struct OcrSettings { /// that is read, so a scan with a few comments on it is still a scan. `false`: everything /// the page shows. pub native_text_only: bool, + /// Leave whole files that already have text alone (the batch flow's "Skip files that + /// already contain text"; a skipped file is its own result bucket, never an OCR success). + pub skip_text_files: bool, + /// Read pages even when the skip options would leave them alone ("Force OCR (override + /// skip options)"). + pub force_ocr: bool, + /// Which engine reads the pages. + pub engine: EngineChoice, + /// How the engines' readings combine (see [`MergeStrategy`]). + pub strategy: MergeStrategy, + /// Preprocessing, all off by default (a scan is passed through as rendered): + /// straighten pages scanned at 90°/180°/270°. + pub auto_rotate: bool, + /// Preprocessing: straighten skewed text lines. + pub deskew: bool, + /// Preprocessing: 3×3 median filter. + pub denoise: bool, + /// Preprocessing: Sauvola binarization. + pub binarize: bool, + /// What to produce (searchable text layer, or a new editable document). + pub output_mode: OutputMode, + /// Restrict recognition to this rectangle of the rendered page image, in pixels + /// `[x0, y0, x1, y1]` (the Verify screen's "Re-OCR this region"). + pub region: Option<[f32; 4]>, + /// The batch note's separate per-word threshold: words with `0 <= conf <= threshold` are + /// counted for "N low-confidence word(s) on page(s) …" (see [`low_confidence`]; unrelated + /// to the review overlay's bands, which use [`band_for`]). + pub low_confidence_threshold: f32, + /// Where the Tesseract program lives, when the user configured it (a preference — the + /// `PDFCRAFT_TESSERACT` environment variable is the fallback in the engine; never taken + /// from document data). A configured path must be absolute to an existing, executable + /// file; an invalid configuration makes the engine unavailable rather than silently + /// searching the PATH. `None` means the PATH search decides. + pub tesseract_path: Option, } /// A recognised word whose box is at least this much covered by the page's own text is that @@ -56,7 +178,24 @@ fn covered(word: [f32; 4], text: &[[f32; 4]]) -> f32 { impl Default for OcrSettings { fn default() -> Self { - OcrSettings { dpi: 300.0, language: "en".into(), skip_text_pages: true, native_text_only: false } + OcrSettings { + dpi: 300.0, + language: "en".into(), + skip_text_pages: true, + native_text_only: false, + skip_text_files: false, + force_ocr: false, + engine: EngineChoice::default(), + strategy: MergeStrategy::default(), + auto_rotate: false, + deskew: false, + denoise: false, + binarize: false, + output_mode: OutputMode::default(), + region: None, + low_confidence_threshold: 60.0, + tesseract_path: None, + } } } @@ -69,31 +208,406 @@ pub struct OcrPage { pub already_on_page: usize, /// Why the page was not read, if it was skipped. pub skipped: Option, + /// Notes about a partial reading: the words stand, but something on the way did not (an + /// ensemble partner failed and the page keeps the primary engine's reading alone). + pub notes: Vec, } impl OcrPage { pub fn text(&self) -> String { self.words.iter().map(|w| w.text.as_str()).collect::>().join(" ") } -} -/// The recogniser, loaded once (it takes a moment) and shared. -pub fn engine() -> Result, String> { - static OCR: Mutex>> = Mutex::new(None); - let mut slot = OCR.lock().unwrap_or_else(std::sync::PoisonError::into_inner); - if let Some(o) = slot.as_ref() { - return Ok(o.clone()); + /// Mean of the confidences the page's words report (`None` when none do). + pub fn mean_confidence(&self) -> Option { + let (sum, n) = self.words.iter().filter_map(|w| w.confidence).fold((0.0f64, 0usize), |(s, n), c| (s + c as f64, n + 1)); + (n > 0).then_some((sum / n as f64) as f32) + } + + /// The words to flag for review: their confidence is in the Low band ([`band_for`]). + /// Excluded are words the caller wants gone — removed words, words in the user dictionary, + /// skipped words — which is review state, so this reports the indices and the reviewer + /// filters them. + pub fn suspects(&self) -> Vec { + self.words.iter().enumerate().filter(|(_, w)| pdfcraft_ocr::is_suspect(w.confidence)).map(|(i, _)| i).collect() } - let o = Arc::new(Ocr::find().map_err(|e| e.to_string())?); - *slot = Some(o.clone()); - Ok(o) } -/// Whether the recognition models are installed. -pub fn available() -> bool { +/// The engines a job reads with: one primary and, for ensemble strategies, an optional +/// secondary. +pub struct Recognizers { + pub primary: Arc, + pub secondary: Option>, +} + +struct EngineCache { + ocrs: Option>, +} + +/// How long a negative engine probe (no program there) is remembered. A short TTL, not +/// forever: a tesseract installed while the app runs is found by the next job, without a +/// restart. An engine that was found is remembered for the session. +#[cfg(not(target_arch = "wasm32"))] +const NEGATIVE_TTL: Duration = Duration::from_secs(30); + +/// The remembered Tesseract probe: the configured location it answers for, the engine it +/// found (`None` for a probe that failed), and when that probe happened. +#[cfg(not(target_arch = "wasm32"))] +struct CachedTesseract { + key: Option, + found: Option>, + at: Instant, +} + +/// Whether a probe result still counts: a found engine for the session, a failed probe until +/// [`NEGATIVE_TTL`] passes (split out so tests can pass the clock). +#[cfg(not(target_arch = "wasm32"))] +fn probe_fresh(found: bool, at: Instant, now: Instant) -> bool { + found || now.duration_since(at) < NEGATIVE_TTL +} + +/// The remembered Tesseract probe (one slot: the last location asked about). +#[cfg(not(target_arch = "wasm32"))] +static TESSERACT_PROBE: Mutex> = Mutex::new(None); + +/// Whether a background probe, started for the UI by [`tesseract_engine_now`], is running now. +/// At most one runs at a time. +#[cfg(not(target_arch = "wasm32"))] +static PROBING: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + +/// The Tesseract engine: found once (it answers `--list-langs` through a process) and then +/// remembered, per configured path; a failed probe is retried after [`NEGATIVE_TTL`]. No +/// static mutex is held while the discovery process runs: the cache is read under the lock, +/// released for the probe, and the result is written back when it arrives (concurrent probes +/// of the same location may both run; the last write wins and both answers are valid). A +/// user-configured path (`settings.tesseract_path`, else the `PDFCRAFT_TESSERACT` +/// environment variable) is validated before any process starts; an invalid configuration is +/// unavailable rather than a PATH fallback. This waits for the probe: the UI thread uses +/// [`tesseract_engine_now`]. +#[cfg(not(target_arch = "wasm32"))] +fn tesseract_engine(configured: Option<&str>) -> Option> { + if let Cached::Fresh(found) = cached_tesseract(configured) { + return found; + } + let key = configured.map(str::to_string); + // The probe (a `--list-langs` process, up to the timeout) runs outside every static mutex. + let found = match configured { + Some(path) => pdfcraft_ocr::tesseract::TesseractCli::at(std::path::PathBuf::from(path)).map(|t| Arc::new(t) as Arc), + None => pdfcraft_ocr::tesseract::TesseractCli::find().map(|t| Arc::new(t) as Arc), + }; + *TESSERACT_PROBE.lock().unwrap_or_else(|e| e.into_inner()) = Some(CachedTesseract { key, found: found.clone(), at: Instant::now() }); + found +} + +/// What the UI may know about the Tesseract probe without waiting for it. +#[cfg(not(target_arch = "wasm32"))] +enum Probe { + /// An answer: the engine, or `None` when there is none. It may be an old one that a + /// background probe is refreshing. + Known(Option>), + /// No answer yet: the first background probe is running (or could not be started). + Pending, +} + +/// What the cache holds for a location. +#[cfg(not(target_arch = "wasm32"))] +enum Cached { + /// A usable answer (see [`probe_fresh`]). + Fresh(Option>), + /// A failed probe older than [`NEGATIVE_TTL`]: still the best known answer, but due again. + Stale(Option>), + /// Nothing for this location. + Missing, +} + +/// [`tesseract_engine`] for the UI thread, which must never wait on a process: the cached +/// answer is returned at once, and when it is missing or due for a retry one background thread +/// runs the probe (it fills the cache). The answer is [`Probe::Pending`] only until the first +/// probe of a location lands, so a retry never makes the choice flicker. +#[cfg(not(target_arch = "wasm32"))] +fn tesseract_engine_now(configured: Option<&str>) -> Probe { + let known = match cached_tesseract(configured) { + Cached::Fresh(found) => return Probe::Known(found), + Cached::Stale(found) => Some(found), + Cached::Missing => None, + }; + if !PROBING.swap(true, std::sync::atomic::Ordering::AcqRel) { + let configured = configured.map(str::to_string); + let started = std::thread::Builder::new().name("pdfcraft-tesseract-probe".into()).spawn(move || { + let _ = tesseract_engine(configured.as_deref()); + PROBING.store(false, std::sync::atomic::Ordering::Release); + }); + if started.is_err() { + PROBING.store(false, std::sync::atomic::Ordering::Release); + } + } + known.map_or(Probe::Pending, Probe::Known) +} + +/// Whether the Tesseract probe is running in the background right now. The interface asks it +/// while it shows an engine choice that read as "still checking", to look again soon. +pub fn engine_probe_running() -> bool { + #[cfg(not(target_arch = "wasm32"))] + { + PROBING.load(std::sync::atomic::Ordering::Acquire) + } + #[cfg(target_arch = "wasm32")] + { + false + } +} + +/// What the cache holds for `configured`. Never starts a process. +#[cfg(not(target_arch = "wasm32"))] +fn cached_tesseract(configured: Option<&str>) -> Cached { + let slot = TESSERACT_PROBE.lock().unwrap_or_else(|e| e.into_inner()); + cache_lookup(slot.as_ref(), configured, Instant::now()) +} + +/// [`cached_tesseract`] over an explicit slot and clock (so tests can pass both). +#[cfg(not(target_arch = "wasm32"))] +fn cache_lookup(slot: Option<&CachedTesseract>, configured: Option<&str>, now: Instant) -> Cached { + match slot { + Some(c) if c.key.as_deref() == configured => { + if probe_fresh(c.found.is_some(), c.at, now) { + Cached::Fresh(c.found.clone()) + } else { + Cached::Stale(c.found.clone()) + } + } + _ => Cached::Missing, + } +} + +/// Whether the ocrs models are installed, remembered like the Tesseract probe (found: for the +/// session; missing: for [`NEGATIVE_TTL`]), so per-frame UI checks do not search the disk. +#[cfg(not(target_arch = "wasm32"))] +fn models_installed_cached() -> bool { + static MODELS: Mutex> = Mutex::new(None); + let mut slot = MODELS.lock().unwrap_or_else(|e| e.into_inner()); + if let Some((found, at)) = *slot + && probe_fresh(found, at, Instant::now()) + { + return found; + } + let found = Models::find().is_some(); + *slot = Some((found, Instant::now())); + found +} + +/// The web build has no disk search worth caching. +#[cfg(target_arch = "wasm32")] +fn models_installed_cached() -> bool { Models::find().is_some() } +/// The program's `--version` line, remembered per program path for the session (`ocr_status` +/// asks every time it is called; the version of an installed binary does not change under a +/// running app often enough to start a process each time). +#[cfg(not(target_arch = "wasm32"))] +fn tesseract_version(program: &str) -> Option { + static VERSIONS: Mutex)>> = Mutex::new(Vec::new()); + if let Some((_, v)) = VERSIONS.lock().unwrap_or_else(|e| e.into_inner()).iter().find(|(p, _)| p == program) { + return v.clone(); + } + // Validated (absolute, existing, executable) before the process starts; run outside the lock. + let path = std::path::PathBuf::from(program); + let version = pdfcraft_ocr::tesseract::program_is_usable(&path).then(|| pdfcraft_ocr::tesseract::TesseractCli::new(path).version()).flatten(); + let mut cache = VERSIONS.lock().unwrap_or_else(|e| e.into_inner()); + if cache.len() < 16 && !cache.iter().any(|(p, _)| p == program) { + cache.push((program.to_string(), version.clone())); + } + version +} + +/// The Tesseract program the engine would run, named for `ocr_status`: the user-configured +/// location when one is set, else what the PATH search resolves to. This function itself +/// starts no process (the PATH search only looks at files), so a path here says where the +/// engine looks, not that a program answers there; [`engines_status`], which reports it, does +/// run the cached `--list-langs` probe and a cached `--version`. `None` when nothing is +/// configured and the PATH holds no `tesseract` (or, on the web, when there is no process to +/// run). +#[cfg(not(target_arch = "wasm32"))] +pub fn tesseract_program_path(configured: Option<&str>) -> Option { + match configured { + Some(p) => Some(p.to_string()), + None => pdfcraft_ocr::tesseract::path_search().map(|p| p.to_string_lossy().into_owned()), + } +} + +/// One engine's status, for `ocr_status`: whether it can run, why not when it cannot, and for +/// Tesseract the program it would run and that program's version (both `None` on the web). +#[derive(Clone, Debug, PartialEq)] +pub struct EngineStatus { + pub id: &'static str, + pub available: bool, + pub why_not: Option, + pub program: Option, + pub version: Option, +} + +/// The engines' status, in the order the Engine dropdown lists them: ocrs (built in), then +/// tesseract (the external program). Tesseract's availability is judged the same way +/// [`recognizers`] judges it under the default settings: the `PDFCRAFT_TESSERACT` environment +/// variable when set, else the PATH. This waits for the (cached) Tesseract probe; the tools +/// and tests call it, never the UI thread. +pub fn engines_status() -> Vec { + engines_status_for(&OcrSettings::default()) +} + +/// [`engines_status`] for the location a job's `settings` name: `settings.tesseract_path` when +/// set, else the environment variable, else the PATH, as [`recognizers`] decides it. (No tool +/// takes a location, because an agent must not choose which program runs; the tools report the +/// default settings.) +pub fn engines_status_for(settings: &OcrSettings) -> Vec { + let ocrs = Models::find().is_some(); + let mut out = vec![EngineStatus { id: "ocrs", available: ocrs, why_not: (!ocrs).then(models_missing), program: None, version: None }]; + #[cfg(not(target_arch = "wasm32"))] + { + let configured = configured_tesseract(settings); + let configured = configured.as_deref(); + let available = tesseract_engine(configured).is_some(); + let program = tesseract_program_path(configured); + // The version is a `--version` run against the validated program path, remembered per + // path; a program that answers `--list-langs` but not `--version` still counts as + // available. + let version = if available { program.as_deref().and_then(tesseract_version) } else { None }; + let why_not = (!available).then(|| match configured { + Some(p) => format!("the configured tesseract location is not an absolute path to an existing, executable file: {p}"), + None => tesseract_unavailable(), + }); + out.push(EngineStatus { id: "tesseract", available, why_not, program, version }); + } + #[cfg(target_arch = "wasm32")] + { + let _ = settings; + out.push(EngineStatus { id: "tesseract", available: false, why_not: Some(tesseract_unavailable()), program: None, version: None }); + } + out +} + +/// The web build never spawns processes, so it never has Tesseract. +#[cfg(target_arch = "wasm32")] +fn tesseract_engine(configured: Option<&str>) -> Option> { + let _ = configured; + None +} + +/// The configured Tesseract location: the user preference wins; the environment variable is +/// the fallback (a preference file rarely survives onto another machine). Both are user +/// choices — this is never taken from document data. +fn configured_tesseract(settings: &OcrSettings) -> Option { + settings.tesseract_path.clone().or_else(|| std::env::var_os("PDFCRAFT_TESSERACT").map(|v| v.to_string_lossy().into_owned())) +} + +/// The engine selector: builds each engine once and hands out the pair `settings.engine` +/// asks for. "Automatic" is an ensemble when both engines are available; a named engine that +/// cannot start fails with its cause named. +pub fn recognizers(settings: &OcrSettings) -> Result { + // The Tesseract probe (a `--list-langs` process) runs before any static mutex is taken, so + // recognition on other threads is never blocked behind someone's discovery. A job that + // names its engines never starts it: only Tesseract and Automatic read anything from it, + // so an ocrs-only job pays no process and no wait. + let configured = configured_tesseract(settings); + let tesseract = + if matches!(settings.engine, EngineChoice::Tesseract | EngineChoice::Auto) { tesseract_engine(configured.as_deref()) } else { None }; + static ENGINES: Mutex> = Mutex::new(None); + let mut slot = ENGINES.lock().unwrap_or_else(|e| e.into_inner()); + let cache = slot.get_or_insert_with(|| EngineCache { ocrs: None }); + if cache.ocrs.is_none() { + // Cheap to re-attempt while the models are missing; expensive work is cached forever. + cache.ocrs = pdfcraft_ocr::OcrsRecognizer::find().ok().map(|r| Arc::new(r) as Arc); + } + let ocrs = cache.ocrs.clone(); + match settings.engine { + EngineChoice::Ocrs => Ok(Recognizers { primary: ocrs.ok_or_else(models_missing)?, secondary: None }), + EngineChoice::Tesseract => Ok(Recognizers { primary: tesseract.ok_or_else(tesseract_unavailable)?, secondary: None }), + EngineChoice::Auto => match (ocrs, tesseract) { + (Some(p), s) => Ok(Recognizers { primary: p, secondary: s }), + (None, Some(p)) => Ok(Recognizers { primary: p, secondary: None }), + (None, None) => Err(models_missing()), + }, + } +} + +/// Why Tesseract cannot run, named for the user. +#[cfg(not(target_arch = "wasm32"))] +fn tesseract_unavailable() -> String { + "the tesseract program was not found (install it, or add it to the PATH)".into() +} + +/// Why Tesseract cannot run, named for the user (the web build has no processes). +#[cfg(target_arch = "wasm32")] +fn tesseract_unavailable() -> String { + "the tesseract engine is not available in the web build".into() +} + +/// Why the ocrs engine cannot run, in the end-user wording the UI catalogs translate (the +/// same text as [`pdfcraft_ocr::OcrError::NoModels`]: no developer commands in front of users). +fn models_missing() -> String { + pdfcraft_ocr::OcrError::NoModels.to_string() +} + +/// Whether recognition can run at all: the ocrs models are installed, or (off the web) a +/// Tesseract program is found. This may run the Tesseract probe (a process, cached) and so +/// waits for it: tools and tests call it; the UI asks [`engine_unavailable_reason`], which +/// never waits. +pub fn available() -> bool { + let configured = std::env::var_os("PDFCRAFT_TESSERACT").map(|v| v.to_string_lossy().into_owned()); + Models::find().is_some() || tesseract_engine(configured.as_deref()).is_some() +} + +/// Why `engine` cannot run right now, named for the UI's tooltips (the Engine dropdown +/// disables the choice with this text); `None` when it can. The app UI has no Tesseract +/// location field of its own, so this judges the environment variable, exactly like +/// [`available`] (no tool takes a per-job location either; `OcrSettings::tesseract_path` is +/// for library callers, and [`recognizers`] validates it on its own). +/// +/// Called on the UI thread every frame, so it never waits on a process: the answers are +/// cached ([`NEGATIVE_TTL`] for a missing engine, refreshed in the background), and until the +/// first Tesseract probe lands the choice reads as "still checking" (see +/// [`engine_probe_running`], to ask for another frame meanwhile). +pub fn engine_unavailable_reason(engine: EngineChoice) -> Option { + let ocrs = models_installed_cached(); + #[cfg(not(target_arch = "wasm32"))] + let tesseract = { + let configured = std::env::var_os("PDFCRAFT_TESSERACT").map(|v| v.to_string_lossy().into_owned()); + match tesseract_engine_now(configured.as_deref()) { + Probe::Known(Some(_)) => Ok(()), + Probe::Known(None) => Err(tesseract_unavailable()), + Probe::Pending => Err(tesseract_checking()), + } + }; + #[cfg(target_arch = "wasm32")] + let tesseract: Result<(), String> = Err(tesseract_unavailable()); + match engine { + EngineChoice::Ocrs => (!ocrs).then(models_missing), + EngineChoice::Tesseract => tesseract.err(), + EngineChoice::Auto => match (ocrs, tesseract) { + (true, _) | (false, Ok(())) => None, + (false, Err(why)) => Some(format!("{}; {why}", models_missing())), + }, + } +} + +/// Why Tesseract cannot be chosen yet: its probe is still running in the background. +#[cfg(not(target_arch = "wasm32"))] +fn tesseract_checking() -> String { + "still checking whether the tesseract program can run; try again in a moment".into() +} + +/// What a started job expects of the document when its result is applied: the same open +/// document, unchanged. [`Session::stale_reason`] names any difference it finds. +#[derive(Clone)] +pub struct OcrGuard { + pub(crate) doc: DocId, + pub(crate) pages: usize, + pub(crate) revisions: usize, + /// The document's working bytes when the job started; any edit rewrites them, so a shared + /// `Arc` pointer means "untouched". + pub(crate) bytes: Arc>, +} + /// Everything recognition needs from a document, detached from the session. pub struct OcrJob { bytes: Arc>, @@ -104,40 +618,162 @@ pub struct OcrJob { native: Vec>, pub pages: Vec, pub settings: OcrSettings, + /// What to check before applying this job's result. + pub guard: OcrGuard, +} + +/// A page's "has text" probe for skip-text: at least one non-blank text run. A failed probe +/// (the text layer could not be read) never enables a skip. +fn page_has_text(text: Option<&Arc>) -> bool { + text.is_some_and(|t| t.glyphs.iter().any(|g| !g.text.trim().is_empty())) +} + +/// Clamp a region to the image, snapping outward to whole pixels. `None` when nothing of it +/// is inside the image (empty, inverted, NaN, or wholly outside). +pub fn clamp_region(region: [f32; 4], width: u32, height: u32) -> Option<[u32; 4]> { + let (w, h) = (f64::from(width), f64::from(height)); + if region.iter().any(|v| !v.is_finite()) { + return None; + } + let (x0, y0, x1, y1) = (region[0] as f64, region[1] as f64, region[2] as f64, region[3] as f64); + let (x0, y0) = ((x0.floor().max(0.0).min(w)) as u32, (y0.floor().max(0.0).min(h)) as u32); + let (x1, y1) = ((x1.ceil().max(0.0).min(w)) as u32, (y1.ceil().max(0.0).min(h)) as u32); + (x1 > x0 && y1 > y0).then_some([x0, y0, x1, y1]) +} + +/// Map a recognized word from its source page's user space into the editable output's page +/// user space (the new page is the source's displayed size, unrotated): user → view → new +/// user. The box never moves relative to what the reviewer saw. +fn editable_word(w: &PlacedWord, info: &PageInfo) -> PlacedWord { + let to_new = |p: [f64; 2]| { + let v = info.user_to_view(p[0] as f32, p[1] as f32); + [f64::from(v[0]), f64::from(info.height) - f64::from(v[1])] + }; + let origin = to_new(w.origin); + let br = to_new([w.origin[0] + w.across[0], w.origin[1] + w.across[1]]); + let tl = to_new([w.origin[0] + w.up[0], w.origin[1] + w.up[1]]); + PlacedWord { + text: w.text.clone(), + origin, + across: [br[0] - origin[0], br[1] - origin[1]], + up: [tl[0] - origin[0], tl[1] - origin[1]], + ..w.clone() + } } impl OcrJob { + /// The pixels-per-point this job renders `page` at (the real render dpi is this times 72). + /// The Verify screen uses it to express a region picked on its own preview in the pixels + /// the job will actually read. A scan is read at its own resolution (enlarging it only + /// blurs the letters), at most the chosen one. + pub fn render_scale(&self, page: usize) -> f32 { + let wanted = self.settings.dpi.clamp(72.0, 600.0) / 72.0; + let Some(native) = self.native.get(page).copied().flatten() else { return wanted }; + // A scan whose page is larger than a sheet (often a box given in pixels, one point per + // pixel, #1848) is measured as if shrunk to one: otherwise 1 px/pt is already its full + // image, and no "Downsample to" choice could ask for less. + let fit = self.infos.get(page).map_or(1.0, |i| (SHEET / i.width.max(i.height).max(1e-3)).min(1.0)); + native.clamp(fit, wanted * fit) + } + + /// Whether any of the job's pages already has text (at least one non-blank run): the + /// batch flow's "Skip files that already contain text" probe. A failed probe never + /// enables a skip, so a page whose text cannot be read counts as no text there. + pub fn has_text(&self) -> bool { + let mut r = PageRenderer::new(self.bytes.clone(), RenderConfig { password: self.password.as_deref().map(Arc::from), ..Default::default() }); + self.pages.iter().any(|&page| { + let t = r.render(RenderRequest { page, kind: RequestKind::Text, scale: 1.0, ..Default::default() }); + page_has_text(t.text.as_ref()) + }) + } + /// Read the pages. `progress(done, total)` is called before each page; returning `false` /// stops (the pages read so far are returned). - pub fn run(self, ocr: &Ocr, mut progress: impl FnMut(usize, usize) -> bool) -> Vec { + pub fn run(self, recognizers: &Recognizers, mut progress: impl FnMut(usize, usize) -> bool) -> Vec { let config = RenderConfig { password: self.password.as_deref().map(Arc::from), hide_comments: self.settings.native_text_only, ..Default::default() }; let mut r = PageRenderer::new(self.bytes.clone(), config); let mut out = Vec::new(); let total = self.pages.len(); + let options = pdfcraft_ocr::RecognizeOptions { language: self.settings.language.clone() }; for (done, &page) in self.pages.iter().enumerate() { if !progress(done, total) { break; } let Some(info) = self.infos.get(page) else { continue }; - let skip = |why: &str| OcrPage { page, words: Vec::new(), already_on_page: 0, skipped: Some(why.into()) }; + let skip = |why: &str| OcrPage { page, words: Vec::new(), already_on_page: 0, skipped: Some(why.into()), notes: Vec::new() }; // The boxes of the page's own text (an earlier OCR layer's included), in view space. let existing: Vec<[f32; 4]> = r .render(RenderRequest { page, kind: RequestKind::Text, scale: 1.0, ..Default::default() }) .text .map(|t| t.glyphs.iter().filter(|g| !g.text.trim().is_empty()).map(|g| g.rect).collect()) .unwrap_or_default(); - if self.settings.skip_text_pages && !existing.is_empty() { + if self.settings.skip_text_pages && !self.settings.force_ocr && !existing.is_empty() { out.push(skip("the page already contains text")); continue; } - let shot = r.render(RenderRequest { page, scale: self.scale(page, info), ..Default::default() }); + // A scan is read at its own resolution (enlarging it only blurs the letters), at + // most the chosen one. + let scale = self.render_scale(page); + let shot = r.render(RenderRequest { page, scale, ..Default::default() }); if let Some(e) = shot.error { out.push(skip(&e)); continue; } - let lines = match ocr.recognize(&shot.rgba, shot.width, shot.height) { - Ok(l) => l, + let full = match pdfcraft_ocr::OcrImage::new(shot.width, shot.height, shot.rgba.to_vec()) { + Ok(img) => img, + Err(e) => { + out.push(skip(&e.to_string())); + continue; + } + }; + // The optional region: crop the rendered page, clamped; an empty region skips the + // page with a named reason (nothing was asked of it). + let (image, offset) = match self.settings.region { + None => (full, [0.0f32; 2]), + Some(region) => match clamp_region(region, shot.width, shot.height) { + Some([x0, y0, x1, y1]) => match crop(&full, x0, y0, x1, y1) { + Some(c) => (c, [x0 as f32, y0 as f32]), + None => { + out.push(skip("the selected region is empty")); + continue; + } + }, + None => { + out.push(skip("the selected region is outside the page")); + continue; + } + }, + }; + // Preprocessing sits between the page raster and recognition; its word boxes come + // back in processed coordinates and are mapped to the ORIGINAL raster's before + // placement. The render dpi is the real one (pixels per point × 72), never a + // fixed value. + let pre = pdfcraft_ocr::preprocess::preprocess( + image, + scale * 72.0, + &pdfcraft_ocr::preprocess::PreprocessOptions { + auto_rotate: self.settings.auto_rotate, + deskew: self.settings.deskew, + denoise: self.settings.denoise, + binarize: self.settings.binarize, + }, + ); + let (image, inverse) = match pre { + Ok(p) => (p.image, p.inverse_transform), + Err(e) => { + out.push(skip(&e.to_string())); + continue; + } + }; + let outcome = match pdfcraft_ocr::recognize_with_strategy( + recognizers.primary.as_ref(), + recognizers.secondary.as_deref(), + self.settings.strategy, + &image, + &options, + ) { + Ok(o) => o, Err(e) => { out.push(skip(&e.to_string())); continue; @@ -145,30 +781,69 @@ impl OcrJob { }; let scale = shot.width as f32 / info.width.max(1e-3); let to_user = |x: f32, y: f32| { - let [u, v] = info.view_to_user(x / scale, y / scale); + // processed pixels → original raster pixels (the exact inverse) → past the + // region crop → page view space. + let (ox, oy) = inverse.apply(f64::from(x), f64::from(y)); + let [u, v] = info.view_to_user((ox as f32 + offset[0]) / scale, (oy as f32 + offset[1]) / scale); [u as f64, v as f64] }; - // Words the page's own text already has are not added a second time. - let (fresh, already): (Vec<_>, Vec<_>) = - lines.iter().flat_map(|l| &l.words).partition(|w| covered(w.rect.map(|v| v / scale), &existing) < ALREADY_ON_PAGE); - let words = fresh.into_iter().map(|w| PlacedWord::place(w, to_user)).collect(); - out.push(OcrPage { page, words, already_on_page: already.len(), skipped: None }); + // Validate recognition geometry and compare against existing text in view space, + // undoing preprocessing and region offsets before testing overlap. + let (fresh, already): (Vec<_>, Vec<_>) = outcome.lines.iter().flat_map(|l| &l.words).filter(|w| box_writable(w)).partition(|w| { + let [l, t, r, b] = w.rect; + let bounds = [(l, t), (r, t), (r, b), (l, b)].into_iter().fold( + [f32::INFINITY, f32::INFINITY, f32::NEG_INFINITY, f32::NEG_INFINITY], + |mut bounds, (x, y)| { + let (x, y) = inverse.apply(f64::from(x), f64::from(y)); + let x = (x as f32 + offset[0]) / scale; + let y = (y as f32 + offset[1]) / scale; + bounds[0] = bounds[0].min(x); + bounds[1] = bounds[1].min(y); + bounds[2] = bounds[2].max(x); + bounds[3] = bounds[3].max(y); + bounds + }, + ); + covered(bounds, &existing) < ALREADY_ON_PAGE + }); + let words = fresh.into_iter().map(|w| PlacedWord::place(w, to_user)).collect::>(); + let mut notes = outcome.notes; + // Only visible editable output needs display glyphs. Searchable output preserves + // every Unicode character with empty Type3 programs and ToUnicode maps. + if self.settings.output_mode == OutputMode::EditableText && !words.is_empty() { + let missing = pdfcraft_fonts::TextPlan::for_words(words.iter().map(|w| w.text.as_str())).missing(); + if missing > 0 { + notes.push(format!("{missing} characters had no font that could show them and appear as ? in the output")); + } + } + out.push(OcrPage { page, words, already_on_page: already.len(), skipped: None, notes }); } progress(total, total); out } +} - /// The render scale (pixels per point) `page` is read at. A scan is read at its own - /// resolution (enlarging it only blurs the letters), at most the chosen one. - fn scale(&self, page: usize, info: &PageInfo) -> f32 { - let wanted = self.settings.dpi.clamp(72.0, 600.0) / 72.0; - let Some(native) = self.native.get(page).copied().flatten() else { return wanted }; - // A scan whose page is larger than a sheet (often a box given in pixels, one point per - // pixel, #1848) is measured as if shrunk to one: otherwise 1 px/pt is already its full - // image, and no "Downsample to" choice could ask for less. - let fit = (SHEET / info.width.max(info.height).max(1e-3)).min(1.0); - native.clamp(fit, wanted * fit) +/// Whether a word's pixel box may reach the content stream: width and height (right − left, +/// bottom − top) must be positive and finite. Anything else — a zero, negative, NaN or +/// infinite size — is dropped before placement rather than written into the page. +fn box_writable(word: &pdfcraft_ocr::Word) -> bool { + let [l, t, r, b] = word.rect; + let (width, height) = (r - l, b - t); + width > 0.0 && height > 0.0 && width.is_finite() && height.is_finite() +} + +/// Crop `[x0, y0, x1, y1]` out of `image` as a new [`OcrImage`] (the sides are already clamped +/// by [`clamp_region`]). +fn crop(image: &pdfcraft_ocr::OcrImage, x0: u32, y0: u32, x1: u32, y1: u32) -> Option { + let (w, h) = (x1.checked_sub(x0)?, y1.checked_sub(y0)?); + let stride = image.width() as usize * 4; + let mut out = Vec::with_capacity((w as usize).checked_mul(h as usize)?.checked_mul(4)?); + for y in y0..y1 { + let start = y as usize * stride + x0 as usize * 4; + let row = image.rgba().get(start..start + (x1 - x0) as usize * 4)?; + out.extend_from_slice(row); } + pdfcraft_ocr::OcrImage::new(w, h, out).ok() } impl Session { @@ -193,7 +868,8 @@ impl Session { .reduce(f32::max) }) .collect(); - Some(OcrJob { bytes: doc.bytes.clone(), password: doc.password.clone(), infos: doc.info.pages.clone(), native, pages, settings }) + let guard = OcrGuard { doc: id, pages: all, revisions: doc.revision_ends().len(), bytes: doc.bytes.clone() }; + Some(OcrJob { bytes: doc.bytes.clone(), password: doc.password.clone(), infos: doc.info.pages.clone(), native, pages, settings, guard }) } /// Add the words found by [`OcrJob::run`] as one undoable step. Returns the number of words. @@ -207,14 +883,129 @@ impl Session { Ok(words) } + /// Why a job's result may not be applied to this session any more: the document was closed, + /// edited, re-saved, or its pages changed since the job started. `None` means it is safe. + pub fn stale_reason(&self, guard: &OcrGuard) -> Option { + let Some(doc) = self.get(guard.doc) else { + return Some("the document is no longer open".into()); + }; + if !Arc::ptr_eq(&doc.bytes, &guard.bytes) { + return Some("the document changed since recognition started".into()); + } + let now = doc.info.pages.len(); + if now != guard.pages { + return Some(format!("the page count changed from {} to {} since recognition started", guard.pages, now)); + } + let revisions = doc.revision_ends().len(); + if revisions != guard.revisions { + let had = guard.revisions; + return Some(format!("the document gained revisions ({had} → {revisions}) since recognition started")); + } + None + } + + /// What applying a result to document `id` expects of it right now. After a checked apply + /// succeeds the document has changed (that apply is its newest edit), so a caller that + /// applies more of the same review in further steps (page by page) takes a fresh guard + /// here; any other edit in between still makes the next apply stale. + pub fn ocr_guard(&self, id: DocId) -> Option { + let doc = self.get(id)?; + Some(OcrGuard { doc: id, pages: doc.info.pages.len(), revisions: doc.revision_ends().len(), bytes: doc.bytes.clone() }) + } + + /// [`Self::apply_ocr`], but only while the document is still the one that was read; a stale + /// result is refused with a named reason and nothing is written. + pub fn apply_ocr_checked(&mut self, id: DocId, found: &[OcrPage], guard: &OcrGuard) -> Result { + if guard.doc != id { + return Err("the result belongs to another document".into()); + } + if let Some(why) = self.stale_reason(guard) { + return Err(why); + } + self.apply_ocr(id, found).map_err(|e| e.to_string()) + } + + /// The editable-text output: a NEW document with the recognized words as VISIBLE text at + /// their original boxes and no scan image — one page per source page, blank where nothing + /// was recognized, each page the displayed size of its source. The open document is never + /// touched; the caller chooses where the bytes are written. Refuses when there are no + /// words at all (an empty document would silently lose the scan's content). + pub fn editable_ocr_bytes(&self, id: DocId, found: &[OcrPage]) -> Result>, String> { + let doc = self.get(id).ok_or("no such document")?; + let words = layer::validate_words(found.iter().flat_map(|p| &p.words)).map_err(|e| e.to_string())?; + if words == 0 { + return Err("the recognition found no words, so there is no editable text to write".into()); + } + // The words per page, in user space; and one plan over all of them, so a face's Type3 + // font is built once and shared by every page that uses it. + let page_words: Vec> = (0..doc.info.pages.len()) + .map(|p| { + let Some(info) = doc.info.pages.get(p) else { return Vec::new() }; + found.iter().find(|f| f.page == p).map(|f| f.words.iter().map(|w| editable_word(w, info)).collect()).unwrap_or_default() + }) + .collect(); + layer::validate_words(page_words.iter().flatten()).map_err(|e| e.to_string())?; + let mut plan = pdfcraft_fonts::TextPlan::for_words(page_words.iter().flat_map(|ws| ws.iter().map(|w| w.text.as_str()))); + let pages: Vec<(f64, f64, pdfcraft_cos::Dict, Vec)> = (0..doc.info.pages.len()) + .map(|p| { + let info = doc.info.pages.get(p); + (info.map_or(612.0, |i| f64::from(i.width)), info.map_or(792.0, |i| f64::from(i.height)), pdfcraft_cos::Dict::new(), Vec::new()) + }) + .collect(); + let mut created = pdfcraft_create::from_contents(&pages).map_err(|e| e.to_string())?; + // One shared Helvetica for every page: added once into the new document, then linked + // from each page's resources as /PCHelv (the name the text layers draw with). The + // plan's fonts are linked per page too; their objects are shared. + let mut font = pdfcraft_cos::Dict::new(); + font.set(b"Type".to_vec(), pdfcraft_cos::Object::name("Font")); + font.set(b"Subtype".to_vec(), pdfcraft_cos::Object::name("Type1")); + font.set(b"BaseFont".to_vec(), pdfcraft_cos::Object::name("Helvetica")); + font.set(b"Encoding".to_vec(), pdfcraft_cos::Object::name("WinAnsiEncoding")); + let fr = created.add(font); + // The page tree's kids, direct array or indirect reference (a fresh create document + // keeps /Kids inline) — the output's pages are linked through them. + let kids = created + .root() + .and_then(|r| created.get(r).as_dict().cloned()) + .and_then(|d| d.reference(b"Pages")) + .and_then(|p| created.get(p).as_dict().cloned()) + .and_then(|d| match d.get(b"Kids").map(|k| created.resolve(k)).as_deref() { + Some(pdfcraft_cos::Object::Array(a)) => Some(a.clone()), + Some(pdfcraft_cos::Object::Ref(r)) => created.get(*r).as_array().cloned(), + _ => None, + }); + for (pi, kid) in kids.into_iter().flatten().enumerate() { + let pdfcraft_cos::Object::Ref(page) = kid else { continue }; + let _ = created.update_dict(page, |d| { + let mut res = d.get(b"Resources").and_then(|o| o.as_dict().cloned()).unwrap_or_default(); + let mut fonts = res.get(b"Font").and_then(|o| o.as_dict().cloned()).unwrap_or_default(); + fonts.set(b"PCHelv".to_vec(), pdfcraft_cos::Object::Ref(fr)); + res.set(b"Font".to_vec(), pdfcraft_cos::Object::Dict(fonts)); + d.set(b"Resources".to_vec(), pdfcraft_cos::Object::Dict(res)); + }); + // The page's content is written after the fonts carry their resource names, so + // the runs can reference them. + if page_words.get(pi).is_some_and(|ws| !ws.is_empty()) { + pdfcraft_edit::add_type3_fonts(&mut created, pi, &mut plan).map_err(|e| e.to_string())?; + let word_offset = page_words.iter().take(pi).map(Vec::len).sum(); + let content = pdfcraft_ocr::visible_text_layer_at(&page_words[pi], &plan, word_offset); + let mut dict = pdfcraft_cos::Dict::new(); + dict.set(b"PCMark".to_vec(), pdfcraft_cos::Object::name("OCR")); + let stream = created.add(pdfcraft_cos::Object::Stream(pdfcraft_cos::Stream::flate(dict, &content))); + let _ = created.update_dict(page, |d| d.set(b"Contents".to_vec(), pdfcraft_cos::Object::Ref(stream))); + } + } + self.write_new(&created).map_err(|e| e.to_string()) + } + /// Recognise text on `pages` and add it, in one call (the CLI and agents use this). pub fn recognize_text(&mut self, id: DocId, pages: &[usize], settings: OcrSettings) -> Result, String> { let job = self.ocr_job(id, pages, settings).ok_or("no such document")?; if let Some(why) = self.get(id).and_then(|d| d.read_only_reason.clone()) { return Err(why); } - let ocr = engine()?; - let found = job.run(&ocr, |_, _| true); + let recognizers = recognizers(&job.settings)?; + let found = job.run(&recognizers, |_, _| true); self.apply_ocr(id, &found).map_err(|e| e.to_string())?; Ok(found) } @@ -226,22 +1017,68 @@ pub struct FileResult { /// The new file (incrementally saved), or the original when nothing was recognised. pub bytes: Arc>, pub pages: Vec, + /// Why the whole file was left alone ("Skip files that already contain text"): a skipped + /// file is its own result bucket, never counted as an OCR success. + pub file_skipped: Option, } impl FileResult { pub fn words(&self) -> usize { self.pages.iter().map(|p| p.words.len()).sum() } + + /// Whether the file was passed over entirely (never an OCR success). + pub fn skipped(&self) -> bool { + self.file_skipped.is_some() + } +} + +/// The output names a multi-file run would write more than once: the batch writes every +/// result into one folder under its input's file name, so two inputs of the same name from +/// different folders would overwrite each other. Compared case-insensitively (the Windows and +/// macOS file systems are), in first-seen order, each listed once. +pub fn duplicate_output_names<'a>(names: impl IntoIterator) -> Vec { + let mut seen = std::collections::HashSet::new(); + let mut listed = std::collections::HashSet::new(); + let mut out = Vec::new(); + for name in names { + let key = name.to_lowercase(); + if !seen.insert(key.clone()) && listed.insert(key) { + out.push(name.to_string()); + } + } + out +} + +/// The batch note's data: how many words sit at or under `threshold` ([`low_confidence`], the +/// separate batch rule), and the 1-based, sorted pages they are on. `None` when there are +/// none, so a note is only written when there is something to review. +pub fn low_confidence_pages(pages: &[OcrPage], threshold: f32) -> Option<(usize, Vec)> { + let (mut count, mut page_numbers) = (0usize, Vec::new()); + for p in pages { + if p.skipped.is_some() { + continue; + } + let on_page = p.words.iter().filter(|w| w.confidence.is_some_and(|c| pdfcraft_ocr::low_confidence(c, threshold))).count(); + if on_page > 0 { + count += on_page; + page_numbers.push(p.page + 1); + } + } + page_numbers.sort_unstable(); + (count > 0).then_some((count, page_numbers)) } /// Recognize text in multiple files: one PDF's bytes in, the searchable PDF out. `progress` -/// works as for [`OcrJob::run`]. +/// works as for [`OcrJob::run`]. A file that the skip-files option passes over comes back with +/// [`FileResult::file_skipped`] set and its original bytes; the caller decides what to do with +/// it, but it is never an OCR success. pub fn recognize_file( name: &str, bytes: Arc>, password: Option<&str>, settings: OcrSettings, - ocr: &Ocr, + recognizers: &Recognizers, progress: impl FnMut(usize, usize) -> bool, ) -> Result { let mut s = Session::new(); @@ -249,15 +1086,31 @@ pub fn recognize_file( if let Some(why) = s.get(id).and_then(|d| d.read_only_reason.clone()) { return Err(why); } - let job = s.ocr_job(id, &[], settings).ok_or("the document could not be read")?; - let pages = job.run(ocr, progress); + let job = s.ocr_job(id, &[], settings.clone()).ok_or("the document could not be read")?; + // The skip-files probe runs before any engine work: a file with text needs no engine at + // all, and the original bytes come back unchanged. + if settings.skip_text_files && !settings.force_ocr && job.has_text() { + let pages = job + .pages + .iter() + .map(|&page| OcrPage { + already_on_page: 0, + page, + words: Vec::new(), + skipped: Some("the file already contains text".into()), + notes: Vec::new(), + }) + .collect(); + return Ok(FileResult { bytes, pages, file_skipped: Some("the file already contains text".into()) }); + } + let pages = job.run(recognizers, progress); if s.apply_ocr(id, &pages).map_err(|e| e.to_string())? == 0 { - return Ok(FileResult { bytes, pages }); + return Ok(FileResult { bytes, pages, file_skipped: None }); } // Checked like a save before the caller writes it (#2166). let bytes = s.save_bytes(id).map_err(|e| e.to_string())?; s.check_save(id, &bytes).map_err(|e| e.to_string())?; - Ok(FileResult { bytes, pages }) + Ok(FileResult { bytes, pages, file_skipped: None }) } #[cfg(test)] @@ -282,28 +1135,6 @@ mod tests { assert_eq!(covered([100.5, 52.0, 134.0, 61.0], &[]), 0.0); } - /// #1848: an A4 scan at 300 dpi whose page box is its pixel size (2480 x 3508 pt, one pixel - /// per point) gets a smaller bitmap for each lower "Downsample to" choice, and a low-resolution - /// letter page is still never shrunk below one pixel per point. - #[test] - fn downsample_shrinks_a_page_box_given_in_pixels() { - let mut s = Session::new(); - let page = |w: u32, h: u32| export::encode_png(w, h, &vec![255; (w * h * 4) as usize]).unwrap(); - let bytes = s.create_from_images(&[("a4.png".into(), page(2480, 3508)), ("letter.png".into(), page(612, 792))]).unwrap(); - let id = s.open("scan.pdf", None, bytes, None).unwrap(); - let mut r = PageRenderer::new(s.get(id).unwrap().bytes.clone(), RenderConfig::default()); - for (dpi, a4) in [(72.0, [595, 842]), (150.0, [1240, 1754]), (300.0, [2480, 3508]), (600.0, [2480, 3508])] { - let job = s.ocr_job(id, &[], OcrSettings { dpi, ..Default::default() }).unwrap(); - for (page, want) in [(0, a4), (1, [612, 792])] { - let scale = job.scale(page, &job.infos[page]); - let shot = r.render(RenderRequest { page, scale, ..Default::default() }); - assert!(shot.error.is_none(), "{:?}", shot.error); - let near = |got: u32, want: u32| got.abs_diff(want) <= 1; - assert!(near(shot.width, want[0]) && near(shot.height, want[1]), "{dpi} dpi, page {page}: {}x{}", shot.width, shot.height); - } - } - } - #[test] fn coverage_of_overlapping_or_broken_boxes_stays_between_zero_and_one() { // A glyph drawn twice (fake bold) does not cover more than the whole word. @@ -317,4 +1148,846 @@ mod tests { let c = covered([0.0, 0.0, 10.0, 10.0], &broken); assert!((0.0..=1.0).contains(&c), "{c}"); } + use crate::tests::fixture; + use pdfcraft_render::TextGlyph; + + fn glyph(text: &str) -> TextGlyph { + TextGlyph { text: text.into(), rect: [0.0, 0.0, 1.0, 1.0], quad: [[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0]], direction: [1.0, 0.0] } + } + + /// The skip-text probe: at least one non-blank run; blank-only or missing text never + /// enables a skip. + #[test] + fn has_text_probe_needs_one_non_blank_run() { + let none: Option> = None; + assert!(!page_has_text(none.as_ref()), "a failed probe never enables a skip"); + assert!(!page_has_text(Some(Arc::new(pdfcraft_render::PageText::default())).as_ref())); + let blank = pdfcraft_render::PageText { glyphs: vec![glyph(" "), glyph("")], ..Default::default() }; + assert!(!page_has_text(Some(Arc::new(blank)).as_ref())); + let has = pdfcraft_render::PageText { glyphs: vec![glyph(" "), glyph("a")], ..Default::default() }; + assert!(page_has_text(Some(Arc::new(has)).as_ref())); + } + + #[test] + fn output_mode_parsing_falls_back_to_searchable() { + assert_eq!(OutputMode::parse("editable"), OutputMode::EditableText); + assert_eq!(OutputMode::parse(" Editable-Text "), OutputMode::EditableText); + assert_eq!(OutputMode::parse("searchable"), OutputMode::Searchable); + assert_eq!(OutputMode::parse("nonsense"), OutputMode::Searchable, "unknown strings mean Searchable"); + assert_eq!(OutputMode::parse(""), OutputMode::Searchable); + } + + #[test] + fn engine_choice_parsing() { + assert_eq!(EngineChoice::parse("tesseract"), EngineChoice::Tesseract); + assert_eq!(EngineChoice::parse(" AUTO "), EngineChoice::Auto); + assert_eq!(EngineChoice::parse("ocrs"), EngineChoice::Ocrs); + assert_eq!(EngineChoice::parse("wat"), EngineChoice::Ocrs, "unknown names fall back to the default"); + assert_eq!(EngineChoice::default().name(), "ocrs"); + } + + /// Automatic reads with the second engine when the first is unsure unless a strategy was + /// chosen: "Primary only" would never run it. A named engine reads alone. + #[test] + fn automatic_defaults_to_the_confidence_weighted_strategy() { + assert_eq!(EngineChoice::Auto.default_strategy(), MergeStrategy::ConfidenceWeighted); + assert_eq!(EngineChoice::Ocrs.default_strategy(), MergeStrategy::PrimaryOnly); + assert_eq!(EngineChoice::Tesseract.default_strategy(), MergeStrategy::PrimaryOnly); + } + + /// Settings default to today's behavior: ocrs, PrimaryOnly, no preprocessing, searchable. + #[test] + fn settings_default_to_the_ocrs_status_quo() { + let s = OcrSettings::default(); + assert_eq!(s.engine, EngineChoice::Ocrs); + assert_eq!(s.strategy, MergeStrategy::PrimaryOnly); + assert_eq!(s.output_mode, OutputMode::Searchable); + assert!(!s.auto_rotate && !s.deskew && !s.denoise && !s.binarize); + assert_eq!(s.region, None); + assert_eq!(s.low_confidence_threshold, 60.0); + assert_eq!(s.tesseract_path, None, "no configured tesseract path by default: the PATH decides"); + } + + /// A configured tesseract path that is not an absolute, existing, executable file makes + /// the Tesseract choice unavailable — the explicit setting is never silently replaced by + /// a PATH search (and this holds whatever this machine has installed). + #[test] + fn an_invalid_configured_tesseract_path_is_unavailable_not_a_fallback() { + let bogus = OcrSettings { engine: EngineChoice::Tesseract, tesseract_path: Some("not/a/program".into()), ..Default::default() }; + match recognizers(&bogus) { + Ok(r) => panic!("a bogus configured path must not resolve: {:?}", r.primary.id()), + Err(e) => assert!(e.contains("tesseract"), "{e}"), + } + } + + /// A failed engine probe is remembered only for the negative TTL — a program installed + /// while the app runs is found by a later job, without a restart — while a found engine is + /// remembered for the session. + #[test] + fn a_negative_probe_expires_a_found_engine_does_not() { + let now = Instant::now(); + let old = now.checked_sub(Duration::from_secs(31)).unwrap(); + assert!(!probe_fresh(false, old, now), "past the TTL the probe is retried"); + assert!(probe_fresh(false, now - Duration::from_secs(5), now), "a fresh failure is not re-probed"); + assert!(probe_fresh(true, old, now), "a found engine is kept"); + } + + /// `ocr_status` and a job judge the same location: one named by the job's settings is the + /// one reported (here an invalid one, so no process starts and the answer is the same on + /// every machine). + #[test] + fn the_status_follows_the_location_a_job_names() { + let bogus = OcrSettings { tesseract_path: Some("not/a/program".into()), ..Default::default() }; + let tesseract = engines_status_for(&bogus).into_iter().find(|e| e.id == "tesseract").expect("tesseract is always listed"); + assert!(!tesseract.available, "{tesseract:?}"); + assert!(tesseract.why_not.as_deref().is_some_and(|why| why.contains("not/a/program")), "{tesseract:?}"); + assert_eq!(tesseract.program.as_deref(), Some("not/a/program")); + } + + /// What the interface sees of the cache: a fresh answer as is, an expired failed probe as + /// the best known answer (shown while it is retried, so the choice does not flicker), and + /// nothing for a location nobody asked about. + #[test] + fn the_cache_lookup_keeps_a_stale_answer_and_knows_its_location() { + let now = Instant::now(); + let old = now.checked_sub(Duration::from_secs(31)).unwrap(); + let failed = |key: Option<&str>, at| CachedTesseract { key: key.map(str::to_string), found: None, at }; + assert!(matches!(cache_lookup(None, None, now), Cached::Missing)); + assert!(matches!(cache_lookup(Some(&failed(None, now)), None, now), Cached::Fresh(None))); + assert!(matches!(cache_lookup(Some(&failed(None, old)), None, now), Cached::Stale(None))); + assert!(matches!(cache_lookup(Some(&failed(Some("/x"), now)), None, now), Cached::Missing), "another location is another question"); + let found = CachedTesseract { key: None, found: Some(Arc::new(Fake::new())), at: old }; + assert!(matches!(cache_lookup(Some(&found), None, now), Cached::Fresh(Some(_))), "a found engine stays fresh"); + } + + /// Engine discovery never deadlocks or corrupts the cache: concurrent lookups with + /// different configured locations (all invalid, so they are refused before any process + /// starts) all finish. + #[test] + fn concurrent_engine_lookups_all_finish() { + let handles: Vec<_> = (0..8) + .map(|i| { + std::thread::spawn(move || { + let configured = if i % 2 == 0 { Some(format!("not/a/program-{i}")) } else { None }; + let _ = tesseract_engine(configured.as_deref()); + }) + }) + .collect(); + for h in handles { + h.join().expect("no panic, no deadlock"); + } + } + + /// The preprocessing flags are not just plumbing: a page read with all four on still + /// yields the same words, in the same places (needs the models). + #[test] + fn preprocessing_flags_flow_through_the_job() { + if !available() { + eprintln!("skipped: no OCR engine available"); + return; + } + let mut s = Session::new().with_clock(|| 1_700_000_000); + let text = s.create_from_text("t", "The quick brown fox jumps over the lazy dog.").unwrap(); + let id = s.open("text.pdf", None, text, None).unwrap(); + let png = crate::export::Exporter::new(s.get(id).unwrap()).png(0, 150.0).unwrap(); + let scan = s.create_from_images(&[("scan.png".into(), png)]).unwrap(); + let id = s.open("scan.pdf", None, scan, None).unwrap(); + let settings = OcrSettings { auto_rotate: true, deskew: true, denoise: true, binarize: true, ..Default::default() }; + let found = s.recognize_text(id, &[], settings).unwrap(); + let text = crate::tests::page_texts(&s, id)[0].to_lowercase(); + // Binarizing an anti-aliased render thins the thin strokes, so edge letters drop + // ("lazy" reads as "azy", "brown" as "rown"); the match rests on what stays stable — + // the middle of "quick" (some CPUs' kernels read the model's "q" as an "a", the same + // "uick" the OCR test in crate::tests pins) and whole short words. + for w in ["uick", "fox", "over"] { + assert!(text.contains(w), "{text}"); + } + // The words were placed, meaning boxes survived the trip back to raster coordinates. + assert!(!found[0].words.is_empty()); + } + + /// suspects(): only Low-band words, by index. + #[test] + fn page_suspects_are_the_low_band_words() { + let word = |t: &str, c: Option| PlacedWord { + text: t.into(), + origin: [0.0; 2], + across: [1.0, 0.0], + up: [0.0, 1.0], + confidence: c, + source: "ocrs".into(), + }; + let page = OcrPage { + already_on_page: 0, + page: 0, + words: vec![word("a", Some(95.0)), word("b", Some(50.0)), word("c", None), word("d", Some(69.0))], + skipped: None, + notes: Vec::new(), + }; + assert_eq!(page.suspects(), vec![1, 3]); + let mean = page.mean_confidence().unwrap_or_default(); + assert!((mean - 71.333).abs() < 0.01, "{mean}"); + } + + /// Region clamping: interior kept, negative extents snapped outward, garbage refused. + #[test] + fn regions_clamp_and_refuse_garbage() { + assert_eq!(clamp_region([10.0, 10.0, 20.0, 20.0], 100, 100), Some([10, 10, 20, 20])); + assert_eq!(clamp_region([-5.0, -5.5, 20.4, 20.0], 100, 100), Some([0, 0, 21, 20]), "snapped outward, clamped to the image"); + assert_eq!(clamp_region([50.0, 50.0, 200.0, 200.0], 100, 100), Some([50, 50, 100, 100])); + assert_eq!(clamp_region([10.0, 10.0, 10.0, 20.0], 100, 100), None, "empty"); + assert_eq!(clamp_region([20.0, 10.0, 10.0, 20.0], 100, 100), None, "inverted"); + assert_eq!(clamp_region([f32::NAN, 0.0, 1.0, 1.0], 100, 100), None, "NaN"); + assert_eq!(clamp_region([-20.0, -20.0, -5.0, -5.0], 100, 100), None, "wholly outside"); + } + + /// A word box only reaches the content stream with positive, finite geometry: NaN, + /// infinite, negative and zero-sized boxes are dropped before placement, so nothing + /// non-finite is ever stamped onto the page. + #[test] + fn non_finite_and_negative_word_boxes_are_dropped_before_placement() { + let word = |rect: [f32; 4]| pdfcraft_ocr::Word::new("w", rect, "ocrs"); + for (why, rect) in [ + ("NaN width", [f32::NAN, 0.0, 10.0, 10.0]), + ("NaN height", [0.0, 0.0, 10.0, f32::NAN]), + ("infinite right", [0.0, 0.0, f32::INFINITY, 10.0]), + ("1e39 height overflows to inf", [0.0, 0.0, 10.0, 1e39f64 as f32]), + ("negative width", [10.0, 0.0, 0.0, 10.0]), + ("negative height", [0.0, 10.0, 10.0, 0.0]), + ("zero size", [5.0, 5.0, 5.0, 5.0]), + ] { + assert!(!box_writable(&word(rect)), "{why}: {rect:?}"); + } + assert!(box_writable(&word([0.0, 0.0, 10.0, 10.0])), "a sane box is placed"); + } + + /// A crop takes exactly the asked pixels (this feeds words back to page space, so edges + /// matter). + #[test] + fn crops_take_the_asked_pixels() { + let img = pdfcraft_ocr::OcrImage::new(3, 2, (0..6).flat_map(|p| vec![p as u8; 4]).collect()).unwrap(); + let c = crop(&img, 1, 0, 3, 2).unwrap(); + assert_eq!((c.width(), c.height()), (2, 2)); + assert_eq!(c.rgba()[0], 1, "the crop starts at x=1"); + assert_eq!(c.rgba()[4], 2, "the first row's second column is x=2"); + assert_eq!(c.rgba()[8], 4, "the second row starts at y=1"); + } + + /// The stale guard: edits and closing are named and the result is refused; a page-count or + /// revision difference is named too (any edit rewrites the working bytes, so those branches + /// are reached with a hand-built guard). + #[test] + fn stale_results_are_named_and_refused() { + let mut s = Session::new(); + let id = s.open("t.pdf", None, Arc::new(fixture(2)), None).unwrap(); + let job = s.ocr_job(id, &[], OcrSettings::default()).unwrap(); + assert_eq!(s.stale_reason(&job.guard), None, "freshly captured"); + // Any edit rewrites the working bytes. + s.apply(id, Edit::AddOcrText { page: 0, words: vec![] }).unwrap(); + assert_eq!(s.stale_reason(&job.guard).as_deref(), Some("the document changed since recognition started")); + assert!(s.apply_ocr_checked(id, &[], &job.guard).is_err(), "a stale result is never applied"); + // A fresh guard passes. + let fresh = s.ocr_job(id, &[], OcrSettings::default()).unwrap(); + assert_eq!(s.stale_reason(&fresh.guard), None); + // A page count and a revision count from another life are named too. + let doc = s.get(id).unwrap(); + let (bytes, revisions) = (doc.bytes.clone(), doc.revision_ends().len()); + let guard = OcrGuard { doc: id, pages: 5, revisions, bytes }; + assert!(s.stale_reason(&guard).is_some_and(|r| r.contains("page count changed")), "{}", s.stale_reason(&guard).unwrap()); + let guard = OcrGuard { doc: id, pages: 2, revisions: revisions + 3, bytes: s.get(id).unwrap().bytes.clone() }; + assert!(s.stale_reason(&guard).is_some_and(|r| r.contains("revisions")), "{}", s.stale_reason(&guard).unwrap()); + // A guard for a different document refuses up front. + let other = s.open("other.pdf", None, Arc::new(fixture(1)), None).unwrap(); + let cross = s.apply_ocr_checked(other, &[], &fresh.guard); + assert!(cross.as_ref().is_err_and(|e| e.contains("another document")), "{cross:?}"); + // And so is a closed document. + s.close(id); + assert_eq!(s.stale_reason(&fresh.guard).as_deref(), Some("the document is no longer open")); + } + + /// The stale guard, exercised end to end through the recognition flow itself (the flow the + /// UI's Verify screen and the automation's two-phase path drive): capture a job on a + /// synthetic scanned page, run the recognition, edit the document, and the captured result + /// is refused with its named reason and nothing written; a fresh recognition over the + /// edited document applies. + #[test] + fn stale_results_are_refused_end_to_end_through_the_recognition_flow() { + if !available() { + eprintln!("skipped: no OCR engine available"); + return; + } + let mut s = Session::new().with_clock(|| 1_700_000_000); + let text = s.create_from_text("t", "The quick brown fox jumps over the lazy dog.").unwrap(); + let id = s.open("text.pdf", None, text, None).unwrap(); + let png = crate::export::Exporter::new(s.get(id).unwrap()).png(0, 150.0).unwrap(); + let scan = s.create_from_images(&[("scan.png".into(), png)]).unwrap(); + let id = s.open("scan.pdf", None, scan, None).unwrap(); + + // Recognize: the job (carrying its guard) is captured first, then the reading runs. + let job = s.ocr_job(id, &[], OcrSettings::default()).unwrap(); + let guard = job.guard.clone(); + let r = recognizers(&job.settings).unwrap(); + let found = job.run(&r, |_, _| true); + assert!(!found[0].words.is_empty(), "the scan was read: {:?}", found[0].skipped); + + // The document is edited while the result sits around; any edit rewrites the bytes. + s.apply(id, Edit::AddOcrText { page: 0, words: vec![] }).unwrap(); + + // Applying the now-stale result is refused with its named reason and writes nothing. + let after_edit = s.get(id).unwrap().bytes.clone(); + assert!(!Arc::ptr_eq(&after_edit, &guard.bytes), "the edit rewrote the working bytes"); + let revisions = s.get(id).unwrap().revision_ends().len(); + let why = s.apply_ocr_checked(id, &found, &guard).unwrap_err(); + assert_eq!(why, "the document changed since recognition started", "{why}"); + assert_eq!(s.get(id).unwrap().revision_ends().len(), revisions, "the refusal wrote no revision"); + assert!(Arc::ptr_eq(&s.get(id).unwrap().bytes, &after_edit), "the refused apply wrote nothing"); + assert!(crate::tests::page_texts(&s, id)[0].trim().is_empty(), "no text layer landed"); + + // A fresh recognition over the current document applies: same flow, valid now. + let job = s.ocr_job(id, &[], OcrSettings::default()).unwrap(); + let guard = job.guard.clone(); + assert_eq!(s.stale_reason(&guard), None, "a fresh job is not stale"); + let found = job.run(&r, |_, _| true); + let words = s.apply_ocr_checked(id, &found, &guard).unwrap(); + assert!(words > 0, "the re-run found the words again"); + let text = crate::tests::page_texts(&s, id)[0].to_lowercase(); + assert!(text.contains("fox"), "{text}"); + } + + /// The selector refuses an unusable engine with its cause named, and resolves the ensemble + /// when both engines exist (here: whatever this machine has for ocrs and tesseract). + #[test] + fn selector_names_the_missing_engine() { + let tesseract = OcrSettings { engine: EngineChoice::Tesseract, ..Default::default() }; + match recognizers(&tesseract) { + Ok(r) => assert_eq!(r.primary.id(), "tesseract"), + Err(e) => assert!(e.contains("tesseract"), "{e}"), + } + let ocrs = OcrSettings { engine: EngineChoice::Ocrs, ..Default::default() }; + match recognizers(&ocrs) { + Ok(r) => assert_eq!(r.primary.id(), "ocrs"), + Err(e) => assert!(e.contains("models"), "{e}"), + } + } + + /// An ocrs-only choice never starts the Tesseract probe: the probe is a `--list-langs` + /// process, and a job that names its engine needs no reading from Tesseract. The test's + /// fake program touches a marker file when it runs, so the probe's start is observable; + /// it needs a Unix shell, like the other process fixtures. + #[cfg(unix)] + #[test] + fn an_ocrs_only_choice_never_probes_tesseract() { + use std::os::unix::fs::PermissionsExt; + let probe = |name: &str| { + let dir = std::env::temp_dir().join(format!("pdfcraft-ocr-probe-{}-{name}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let program = dir.join("fake-tesseract"); + std::fs::write(&program, "#!/bin/sh\ntouch \"$0.probed\"\nexit 1\n").unwrap(); + let mut perms = std::fs::metadata(&program).unwrap().permissions(); + perms.set_mode(0o755); + std::fs::set_permissions(&program, perms).unwrap(); + (dir.join("fake-tesseract.probed"), program.to_string_lossy().into_owned()) + }; + // An ocrs-only job: the configured location stays untouched. + let (marker, program) = probe("ocrs-only"); + let ocrs_only = OcrSettings { engine: EngineChoice::Ocrs, tesseract_path: Some(program), ..Default::default() }; + let _ = recognizers(&ocrs_only); + assert!(!marker.exists(), "an ocrs-only job must not start the tesseract probe"); + std::fs::remove_file(marker.parent().unwrap().join("fake-tesseract")).ok(); + + // A Tesseract job does validate its program (that is how it is found usable). + let (marker, program) = probe("tesseract"); + let wants = OcrSettings { engine: EngineChoice::Tesseract, tesseract_path: Some(program), ..Default::default() }; + let _ = recognizers(&wants); + assert!(marker.exists(), "a tesseract job probes its program"); + } + + /// A fake engine for the batch skip logic: reads one confident word from anything, counts + /// its calls, and never touches the filesystem. + struct Fake { + calls: std::sync::atomic::AtomicUsize, + } + + impl Fake { + fn new() -> Fake { + Fake { calls: std::sync::atomic::AtomicUsize::new(0) } + } + fn calls(&self) -> usize { + self.calls.load(std::sync::atomic::Ordering::SeqCst) + } + } + + impl Recognizer for Fake { + fn id(&self) -> &'static str { + "fake" + } + fn available(&self) -> bool { + true + } + fn languages(&self) -> Vec<(String, String)> { + vec![("en".into(), "English".into())] + } + fn recognize(&self, _image: &pdfcraft_ocr::OcrImage, _options: &pdfcraft_ocr::RecognizeOptions) -> Result, OcrError> { + self.calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + Ok(vec![pdfcraft_ocr::Line { words: vec![pdfcraft_ocr::Word::new("word", [1.0, 1.0, 9.0, 9.0], "fake").with_confidence(95.0)] }]) + } + } + + fn fake_recognizers() -> (Recognizers, Arc) { + let fake = Arc::new(Fake::new()); + (Recognizers { primary: fake.clone(), secondary: None }, fake) + } + + /// Skip-files: a file that already has text is passed over entirely — the engine never + /// runs, the original bytes come back, and the result is its own skipped bucket. + #[test] + fn skip_files_passes_text_files_over_without_running_the_engine() { + let s = Session::new(); + let bytes = s.create_from_text("t", "Already typed here").unwrap(); + let (r, fake) = fake_recognizers(); + let settings = OcrSettings { skip_text_files: true, ..Default::default() }; + let out = recognize_file("t.pdf", bytes.clone(), None, settings, &r, |_, _| true).unwrap(); + assert_eq!(fake.calls(), 0, "the engine never ran"); + assert_eq!(out.bytes.as_ptr(), bytes.as_ptr(), "the original bytes came back"); + assert_eq!(out.file_skipped.as_deref(), Some("the file already contains text")); + assert!(out.skipped() && out.words() == 0); + } + + /// Force OCR overrides the file skip: the file is read even though it has text, and the + /// result is an OCR success (new bytes, words placed), never a skipped bucket. + #[test] + fn force_ocr_overrides_the_file_skip() { + let s = Session::new(); + let bytes = s.create_from_text("t", "Already typed here").unwrap(); + let (r, fake) = fake_recognizers(); + let settings = OcrSettings { skip_text_files: true, force_ocr: true, ..Default::default() }; + let out = recognize_file("t.pdf", bytes, None, settings, &r, |_, _| true).unwrap(); + assert_eq!(fake.calls(), 1); + assert_eq!(out.file_skipped, None); + assert_eq!(out.words(), 1); + assert!(!out.bytes.is_empty()); + } + + /// Force OCR also overrides the per-page skip: a page with text is read anyway. + #[test] + fn force_ocr_overrides_the_page_skip() { + let s = Session::new(); + let bytes = s.create_from_text("t", "A page with text").unwrap(); + let (r, fake) = fake_recognizers(); + let settings = OcrSettings { force_ocr: true, ..Default::default() }; + let out = recognize_file("t.pdf", bytes, None, settings, &r, |_, _| true).unwrap(); + assert_eq!(fake.calls(), 1, "the page's own text did not stop the run"); + assert_eq!(out.pages[0].skipped, None); + } + + /// The per-page skip stays the default: with force off, a text page is passed over (and a + /// second run over a searchable output is a no-op — nothing left to read). + #[test] + fn page_skip_leaves_text_pages_alone_and_a_rerun_is_a_noop() { + let s = Session::new(); + let bytes = s.create_from_text("t", "A page with text").unwrap(); + let (r, fake) = fake_recognizers(); + let out = recognize_file("t.pdf", bytes, None, OcrSettings::default(), &r, |_, _| true).unwrap(); + assert_eq!(fake.calls(), 0); + assert_eq!(out.pages[0].skipped.as_deref(), Some("the page already contains text")); + assert_eq!(out.words(), 0); + // Second run over the same (already text-bearing) file: skipped pages again, no calls. + let again = recognize_file("t.pdf", out.bytes, None, OcrSettings::default(), &r, |_, _| true).unwrap(); + assert_eq!(fake.calls(), 0); + assert_eq!(again.pages[0].skipped.as_deref(), Some("the page already contains text")); + } + + /// Two inputs of one name (from different folders, or differing only in case) would + /// write the same output: both are found, each once. + #[test] + fn duplicate_output_names_are_found_case_insensitively() { + assert!(duplicate_output_names(["a.pdf", "b.pdf"]).is_empty()); + assert_eq!(duplicate_output_names(["a.pdf", "b.pdf", "A.PDF", "b.pdf", "a.pdf"]), ["A.PDF", "b.pdf"]); + } + + /// The batch note's data: counts words at or under the threshold per page (1-based, sorted; + /// skipped pages never contribute), and says nothing when there is nothing to review. + #[test] + fn low_confidence_pages_counts_the_batch_rule() { + let word = |c: f32| PlacedWord { + text: "w".into(), + origin: [0.0; 2], + across: [1.0, 0.0], + up: [0.0, 1.0], + confidence: Some(c), + source: "ocrs".into(), + }; + let page = |n: usize, confs: &[f32], skipped: Option<&str>| OcrPage { + already_on_page: 0, + page: n, + words: confs.iter().map(|c| word(*c)).collect(), + skipped: skipped.map(str::to_string), + notes: Vec::new(), + }; + let pages = vec![ + page(0, &[95.0, 40.0], None), + page(1, &[60.0, 60.5, 10.0], None), + page(2, &[59.0], Some("skipped pages never count")), + page(3, &[0.0], None), + ]; + let (count, pages_on) = low_confidence_pages(&pages, 60.0).unwrap(); + assert_eq!((count, pages_on), (4, vec![1, 2, 4]), "60 counts, 60.5 does not, the skipped page is left out"); + let all_high = vec![page(0, &[95.0, 90.5], None)]; + assert_eq!(low_confidence_pages(&all_high, 60.0), None, "no low-confidence words, no note"); + } + + /// The editable writer: refuses an empty payload, writes the words as visible text at + /// their boxes on pages of the source's displayed size, adds no scan image, and never + /// touches the open document. + #[test] + fn editable_writer_refuses_empty_and_writes_visible_words() { + let mut s = Session::new(); + let id = s.open("src.pdf", None, Arc::new(fixture(2)), None).unwrap(); + assert!( + s.editable_ocr_bytes(id, &[OcrPage { already_on_page: 0, page: 0, words: vec![], skipped: None, notes: Vec::new() }]).is_err(), + "zero words are refused" + ); + let info = s.get(id).unwrap().info.pages[0].clone(); + // A word in the source page's user space, high on the page (the fixture's pages are + // 200 x 300 pt, so the box stays inside them). + let w = PlacedWord { + text: "Editable".into(), + origin: [20.0, 200.0], + across: [120.0, 0.0], + up: [0.0, 12.0], + confidence: Some(88.0), + source: "ocrs".into(), + }; + let found = vec![ + OcrPage { already_on_page: 0, page: 0, words: vec![w], skipped: None, notes: Vec::new() }, + OcrPage { already_on_page: 0, page: 1, words: vec![], skipped: None, notes: Vec::new() }, + ]; + let before = s.get(id).unwrap().bytes.clone(); + let bytes = s.editable_ocr_bytes(id, &found).unwrap(); + // The open document was never touched. + assert!(Arc::ptr_eq(&s.get(id).unwrap().bytes, &before), "the source bytes are the same allocation"); + let mut out = Session::new(); + let oid = out.open("ocr.pdf", None, bytes, None).unwrap(); + let otext = crate::tests::page_texts(&out, oid)[0].clone().to_lowercase(); + assert!(otext.contains("editable"), "{otext}"); + let odoc = out.get(oid).unwrap(); + assert_eq!(odoc.info.pages.len(), 2, "the blank source page stays a page"); + assert!(crate::tests::page_texts(&out, oid)[1].trim().is_empty(), "the page with no words stays blank"); + assert!(odoc.page_images(0).is_empty(), "no scan image is carried over"); + let (w, h) = (odoc.info.pages[0].width, odoc.info.pages[0].height); + assert_eq!((w, h), (info.width, info.height), "pages keep the source's displayed size"); + } + + /// The editable writer maps through a rotated source page: a word drawn in user space + /// reads upright on the new page, and the new page has the source's displayed size. + #[test] + fn editable_writer_maps_rotated_pages() { + let mut s = Session::new().with_clock(|| 1_700_000_000); + let text = s.create_from_text("t", "rotated source").unwrap(); + let id = s.open("r.pdf", None, text, None).unwrap(); + s.apply(id, Edit::RotatePages { pages: vec![0], degrees: 90 }).unwrap(); + let info = s.get(id).unwrap().info.pages[0].clone(); + assert_eq!(info.rotation, 90); + // The word sits at view (20, 48)..(120, 60) on the displayed page; its box comes in + // user space, exactly as recognition left it. + let (o, br, tl) = (info.view_to_user(20.0, 60.0), info.view_to_user(120.0, 60.0), info.view_to_user(20.0, 48.0)); + let w = PlacedWord { + text: "Word".into(), + origin: [f64::from(o[0]), f64::from(o[1])], + across: [f64::from(br[0] - o[0]), f64::from(br[1] - o[1])], + up: [f64::from(tl[0] - o[0]), f64::from(tl[1] - o[1])], + confidence: None, + source: "ocrs".into(), + }; + let bytes = s.editable_ocr_bytes(id, &[OcrPage { already_on_page: 0, page: 0, words: vec![w], skipped: None, notes: Vec::new() }]).unwrap(); + let mut out = Session::new(); + let oid = out.open("ocr.pdf", None, bytes, None).unwrap(); + let otext = crate::tests::page_texts(&out, oid)[0].clone(); + assert!(otext.contains("Word"), "{otext}"); + // The new page is the displayed size (portrait, not the rotated-away landscape). + let oinfo = out.get(oid).unwrap().info.pages[0].clone(); + assert_eq!((oinfo.width, oinfo.height), (info.width, info.height)); + } + + /// The searchable layer round-trips the recognized words through the engine's own + /// extraction, characters beyond WinAnsi included, without needing any display fonts. + #[test] + fn searchable_layer_round_trips_non_win_ansi_words() { + let mut s = Session::new().with_clock(|| 1_700_000_000); + let id = s.open("src.pdf", None, Arc::new(fixture(1)), None).unwrap(); + let word = PlacedWord { + text: "日本語".into(), + origin: [20.0, 250.0], + across: [80.0, 0.0], + up: [0.0, 10.0], + confidence: None, + source: "ocrs".into(), + }; + s.apply(id, Edit::AddOcrText { page: 0, words: vec![word] }).unwrap(); + let text = crate::tests::page_texts(&s, id)[0].clone(); + assert!(text.contains("日本語"), "{text}"); + } + + /// The fontless searchable layer retains its original pixels, handles multiple code + /// fonts and supplementary Unicode, and does not replace existing resource names. + #[test] + fn searchable_unicode_preserves_pixels_save_undo_and_resources() { + let mut s = Session::new().with_clock(|| 1_700_000_000); + let id = s.open("src.pdf", None, Arc::new(fixture(1)), None).unwrap(); + let before = crate::export::Exporter::new(s.get(id).unwrap()).png(0, 72.0).unwrap(); + let mut lines = vec!["中文 English 2026".to_string()]; + let chars: Vec = (0x4e00..0x4f10).filter_map(char::from_u32).chain(['𠮷']).collect(); + lines.extend(chars.chunks(90).map(|c| c.iter().collect())); + let text = lines.join("\n"); + let words: Vec<_> = lines + .iter() + .enumerate() + .map(|(i, line)| PlacedWord { + text: line.clone(), + origin: [20.0, 80.0 - 10.0 * i as f64], + across: [160.0, 0.0], + up: [0.0, 5.0], + confidence: None, + source: "test".into(), + }) + .collect(); + s.apply(id, Edit::AddOcrText { page: 0, words: words.clone() }).unwrap(); + assert!(crate::tests::page_texts(&s, id)[0].contains(&text)); + assert_eq!(crate::export::Exporter::new(s.get(id).unwrap()).png(0, 72.0).unwrap(), before); + let saved = s.save_bytes(id).unwrap(); + let reopened = s.open("searchable.pdf", None, saved, None).unwrap(); + assert!(crate::tests::page_texts(&s, reopened)[0].contains(&text)); + assert_eq!(crate::export::Exporter::new(s.get(reopened).unwrap()).png(0, 72.0).unwrap(), before); + s.undo(id).unwrap(); + assert!(!crate::tests::page_texts(&s, id)[0].contains(&text)); + s.redo(id).unwrap(); + let mut second = words[0].clone(); + second.text = "另一行".into(); + second.origin[1] = 100.0; + s.apply(id, Edit::AddOcrText { page: 0, words: vec![second] }).unwrap(); + let extracted = crate::tests::page_texts(&s, id)[0].clone(); + assert!(extracted.contains(&text) && extracted.contains("另一行"), "{extracted}"); + } + + #[test] + fn searchable_unicode_rejects_excessive_or_non_finite_input_atomically() { + let mut s = Session::new(); + let id = s.open("src.pdf", None, Arc::new(fixture(1)), None).unwrap(); + let word = + PlacedWord { text: "日".into(), origin: [20.0, 80.0], across: [30.0, 0.0], up: [0.0, 5.0], confidence: None, source: "test".into() }; + let before = crate::tests::page_texts(&s, id); + let mut non_finite = word.clone(); + non_finite.origin[0] = f64::NAN; + let mut overflow = word.clone(); + overflow.origin[0] = f64::MAX; + overflow.across[0] = f64::MAX; + let mut too_long = word.clone(); + too_long.text = "a".repeat(4 * 1024 * 1024 + 1); + for words in [vec![non_finite], vec![overflow], vec![too_long], vec![word; 65537]] { + assert!(s.apply(id, Edit::AddOcrText { page: 0, words }).is_err()); + assert_eq!(crate::tests::page_texts(&s, id), before); + } + } + + #[test] + fn editable_export_refuses_invalid_or_excessive_aggregate_input_without_changing_source() { + let mut s = Session::new(); + let id = s.open("src.pdf", None, Arc::new(fixture(2)), None).unwrap(); + let before = s.save_bytes(id).unwrap(); + let word = + PlacedWord { text: "word".into(), origin: [20.0, 80.0], across: [30.0, 0.0], up: [0.0, 5.0], confidence: None, source: "test".into() }; + let page = |page, words| OcrPage { already_on_page: 0, page, words, skipped: None, notes: Vec::new() }; + let mut invalid = word.clone(); + invalid.origin[0] = f64::INFINITY; + let mut long = word.clone(); + long.text = "a".repeat(2 * 1024 * 1024 + 1); + for found in [ + vec![page(0, vec![invalid])], + vec![page(0, vec![long.clone()]), page(1, vec![long])], + vec![page(0, vec![word.clone(); 32768]), page(1, vec![word; 32769])], + ] { + assert!(s.editable_ocr_bytes(id, &found).is_err()); + assert_eq!(s.save_bytes(id).unwrap(), before); + } + } + + /// The editable output carries non-WinAnsi words as visible text that extraction reads + /// back, in a face beyond Helvetica when the build has one. + #[test] + fn editable_output_round_trips_non_win_ansi_words() { + let mut s = Session::new().with_clock(|| 1_700_000_000); + let id = s.open("src.pdf", None, Arc::new(fixture(1)), None).unwrap(); + let w = PlacedWord { + text: "Привет".into(), + origin: [20.0, 250.0], + across: [80.0, 0.0], + up: [0.0, 10.0], + confidence: None, + source: "ocrs".into(), + }; + let bytes = s.editable_ocr_bytes(id, &[OcrPage { already_on_page: 0, page: 0, words: vec![w], skipped: None, notes: Vec::new() }]).unwrap(); + let mut out = Session::new(); + let oid = out.open("ocr.pdf", None, bytes, None).unwrap(); + let text = crate::tests::page_texts(&out, oid)[0].clone(); + if pdfcraft_fonts::CRAFT_FONTS.is_empty() { + assert!(text.contains("??????"), "{text}"); + } else { + assert!(text.contains("Привет"), "{text}"); + } + } + + /// The editable output's VISIBLE layer — a Type3 run for the Cyrillic word, Helvetica for + /// the Latin one — is redacted end to end: a mark over the Cyrillic word removes exactly + /// it (the renderer's extractor no longer reads it, before or after a save and reopen), and + /// the Latin word elsewhere on the page stays. + #[test] + fn the_editable_type3_layer_is_redacted_end_to_end() { + if pdfcraft_fonts::CRAFT_FONTS.is_empty() { + eprintln!("skipping: built without craft-fonts (set CRAFT_FONTS_DIR to run it)"); + return; + } + let mut s = Session::new().with_clock(|| 1_700_000_000); + let id = s.open("src.pdf", None, Arc::new(fixture(1)), None).unwrap(); + let word = |text: &str, y: f64, w: f64| PlacedWord { + text: text.into(), + origin: [20.0, y], + across: [w, 0.0], + up: [0.0, 10.0], + confidence: None, + source: "ocrs".into(), + }; + let words = vec![word("Привет", 250.0, 80.0), word("Hello", 100.0, 50.0)]; + let bytes = s.editable_ocr_bytes(id, &[OcrPage { already_on_page: 0, page: 0, words, skipped: None, notes: Vec::new() }]).unwrap(); + let mut out = Session::new().with_clock(|| 1_700_000_000); + let oid = out.open("ocr.pdf", None, bytes, None).unwrap(); + let before = crate::tests::page_texts(&out, oid)[0].clone(); + assert!(before.contains("Привет") && before.contains("Hello"), "{before}"); + let shape = crate::Shape::Redact { + quads: vec![pdfcraft_annot::rect_quad([10.0, 240.0, 110.0, 270.0])], + overlay: String::new(), + look: Default::default(), + }; + let mark = Edit::AddAnnotation(crate::NewAnnotation { + page: 0, + style: crate::Style::default_for(&shape), + shape, + contents: String::new(), + author: "Ada".into(), + }); + out.apply(oid, mark).unwrap(); + out.apply(oid, Edit::ApplyRedactions { pages: None }).unwrap(); + let after = crate::tests::page_texts(&out, oid)[0].clone(); + assert!(!after.contains("Привет") && !after.contains("Пр"), "the Type3 word is gone: {after}"); + assert!(after.contains("Hello"), "the word outside the mark stays: {after}"); + // Reopened from the saved bytes, an independent read finds the same. + let saved = out.save_bytes(oid).unwrap(); + let mut again = Session::new(); + let aid = again.open("r.pdf", None, saved, None).unwrap(); + let reread = crate::tests::page_texts(&again, aid)[0].clone(); + assert!(!reread.contains("Привет") && reread.contains("Hello"), "{reread}"); + } + + /// A shared document plan serves a multi-page editable export: each page's words must be + /// written with their OWN encodings (the plan's offset for that page), so page 2 never + /// shows page 1's text. + #[test] + fn editable_output_keeps_each_pages_own_words() { + if pdfcraft_fonts::CRAFT_FONTS.is_empty() { + eprintln!("skipping: built without craft-fonts (set CRAFT_FONTS_DIR to run it)"); + return; + } + let mut s = Session::new().with_clock(|| 1_700_000_000); + let id = s.open("src.pdf", None, Arc::new(fixture(2)), None).unwrap(); + let word = |text: &str| PlacedWord { + text: text.into(), + origin: [20.0, 250.0], + across: [80.0, 0.0], + up: [0.0, 10.0], + confidence: None, + source: "ocrs".into(), + }; + // Different scripts, so each page's words live in different planned fonts (and page 2 + // would inherit page 1's codes under page-local indexing into the shared plan). + let found = vec![ + OcrPage { already_on_page: 0, page: 0, words: vec![word("日本語")], skipped: None, notes: Vec::new() }, + OcrPage { already_on_page: 0, page: 1, words: vec![word("Привет")], skipped: None, notes: Vec::new() }, + ]; + let bytes = s.editable_ocr_bytes(id, &found).unwrap(); + let mut out = Session::new(); + let oid = out.open("ocr.pdf", None, bytes, None).unwrap(); + let texts = crate::tests::page_texts(&out, oid); + assert!(texts[0].contains("日本語") && !texts[0].contains("Привет"), "{texts:?}"); + assert!(texts[1].contains("Привет") && !texts[1].contains("日本語"), "{texts:?}"); + } + + /// Redacting a recognized page takes the Unicode searchable layer away for good: the + /// apply's own verification passes over the Type3 font and an independent extractor finds + /// nothing, including in builds with no display fonts. + #[test] + fn redaction_removes_the_unicode_searchable_layer() { + let mut s = Session::new().with_clock(|| 1_700_000_000); + let id = s.open("src.pdf", None, Arc::new(fixture(1)), None).unwrap(); + let word = PlacedWord { + text: "日本語のテキスト".into(), + origin: [20.0, 250.0], + across: [100.0, 0.0], + up: [0.0, 10.0], + confidence: None, + source: "ocrs".into(), + }; + s.apply(id, Edit::AddOcrText { page: 0, words: vec![word] }).unwrap(); + assert!(crate::tests::page_texts(&s, id)[0].contains("日本語")); + let shape = pdfcraft_annot::Shape::Redact { + quads: vec![pdfcraft_annot::rect_quad([18.0, 248.0, 122.0, 262.0])], + overlay: String::new(), + look: Default::default(), + }; + let mark = Edit::AddAnnotation(pdfcraft_annot::NewAnnotation { + page: 0, + style: pdfcraft_annot::Style::default_for(&shape), + shape, + contents: String::new(), + author: "Ada".into(), + }); + s.apply(id, mark).unwrap(); + s.apply(id, Edit::ApplyRedactions { pages: None }).unwrap(); + assert!(!crate::tests::page_texts(&s, id)[0].contains("日本語"), "the layer is gone, not just hidden"); + } + + /// The job's render scale is what the run actually renders at: the chosen dpi, or the + /// page image's own resolution when that is lower. + #[test] + fn render_scale_matches_the_job_resolution() { + let mut s = Session::new(); + let text = s.create_from_text("t", "scale probe").unwrap(); + let id = s.open("t.pdf", None, text, None).unwrap(); + let job = s.ocr_job(id, &[0], OcrSettings { dpi: 144.0, ..Default::default() }).unwrap(); + assert!((job.render_scale(0) - 2.0).abs() < 1e-4, "144 dpi = 2 px/pt, got {}", job.render_scale(0)); + let job = s.ocr_job(id, &[0], OcrSettings { dpi: 600.0, ..Default::default() }).unwrap(); + assert!((job.render_scale(0) - 600.0 / 72.0).abs() < 1e-4, "a text page has no image, so the wanted dpi wins"); + let page = job.pages[0]; + assert_eq!(page, 0); + } + + /// #1848: an A4 scan at 300 dpi whose page box is its pixel size (2480 x 3508 pt, one pixel + /// per point) gets a smaller bitmap for each lower "Downsample to" choice, and a low-resolution + /// letter page is still never shrunk below one pixel per point. + #[test] + fn downsample_shrinks_a_page_box_given_in_pixels() { + let mut s = Session::new(); + let page = |w: u32, h: u32| export::encode_png(w, h, &vec![255; (w * h * 4) as usize]).unwrap(); + let bytes = s.create_from_images(&[("a4.png".into(), page(2480, 3508)), ("letter.png".into(), page(612, 792))]).unwrap(); + let id = s.open("scan.pdf", None, bytes, None).unwrap(); + let mut r = PageRenderer::new(s.get(id).unwrap().bytes.clone(), RenderConfig::default()); + for (dpi, a4) in [(72.0, [595, 842]), (150.0, [1240, 1754]), (300.0, [2480, 3508]), (600.0, [2480, 3508])] { + let job = s.ocr_job(id, &[], OcrSettings { dpi, ..Default::default() }).unwrap(); + for (page, want) in [(0, a4), (1, [612, 792])] { + let scale = job.render_scale(page); + let shot = r.render(RenderRequest { page, scale, ..Default::default() }); + assert!(shot.error.is_none(), "{:?}", shot.error); + let near = |got: u32, want: u32| got.abs_diff(want) <= 1; + assert!(near(shot.width, want[0]) && near(shot.height, want[1]), "{dpi} dpi, page {page}: {}x{}", shot.width, shot.height); + } + } + } } diff --git a/crates/engine/src/ocr/dictionary.rs b/crates/engine/src/ocr/dictionary.rs new file mode 100644 index 0000000000..cbefa9f7b5 --- /dev/null +++ b/crates/engine/src/ocr/dictionary.rs @@ -0,0 +1,80 @@ +//! The UI dictionary format: one case-insensitive word per UTF-8 line. +use std::collections::BTreeSet; + +pub const MAX_BYTES: usize = 4 * 1024 * 1024; +const MAX_WORDS: usize = 65536; + +fn word(value: &str) -> Result { + let value = value.trim(); + if value.is_empty() || value.len() > 1024 || value.chars().any(char::is_control) { + return Err("dictionary words must be nonempty single lines of at most 1024 bytes".into()); + } + let normalized = value.to_lowercase(); + if normalized.len() > 1024 { + return Err("normalized dictionary words must be at most 1024 bytes".into()); + } + Ok(normalized) +} + +pub fn words(text: &str) -> Result, String> { + if text.len() > MAX_BYTES { + return Err("OCR dictionary exceeds 4 MiB".into()); + } + let mut words = BTreeSet::new(); + for line in text.lines().filter(|line| !line.trim().is_empty()) { + words.insert(word(line)?); + if words.len() > MAX_WORDS { + return Err("OCR dictionary exceeds 65536 words".into()); + } + } + Ok(words) +} + +/// Normalize, update and bound the complete dictionary before the caller writes it. +pub fn update(text: &str, add: &[&str], remove: &[&str]) -> Result { + if add.len() > MAX_WORDS || remove.len() > MAX_WORDS { + return Err("OCR dictionary exceeds 65536 words".into()); + } + let mut entries = words(text)?; + for value in remove { + entries.remove(&word(value)?); + } + for value in add { + entries.insert(word(value)?); + if entries.len() > MAX_WORDS { + return Err("OCR dictionary exceeds 65536 words".into()); + } + } + let mut out = String::new(); + for entry in entries { + if out.len().checked_add(entry.len()).and_then(|n| n.checked_add(1)).is_none_or(|n| n > MAX_BYTES) { + return Err("OCR dictionary exceeds 4 MiB".into()); + } + out.push_str(&entry); + out.push('\n'); + } + Ok(out) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn dictionary_updates_round_trip_and_refuse_expanding_normalization() { + let text = update("Quartz\n日本語\n", &["QUARTZ", "extra"], &["日本語"]).unwrap(); + assert_eq!(text, "extra\nquartz\n"); + assert_eq!(words(&text).unwrap(), BTreeSet::from(["extra".into(), "quartz".into()])); + assert!(update("original\n", &[&"İ".repeat(512)], &[]).unwrap_err().contains("normalized")); + assert!(update("original\n", &["two\nlines"], &[]).is_err()); + } + + #[test] + fn dictionary_limits_cover_existing_and_added_entries() { + let full: String = (0..65536).map(|i| format!("word{i}\n")).collect(); + assert_eq!(words(&full).unwrap().len(), 65536); + assert!(update(&full, &["extra"], &[]).is_err()); + assert_eq!(update(&full, &["extra"], &["word0"]).unwrap().lines().count(), 65536); + assert!(words(&"a".repeat(MAX_BYTES + 1)).is_err()); + } +} diff --git a/crates/engine/src/ocr/layer.rs b/crates/engine/src/ocr/layer.rs new file mode 100644 index 0000000000..ec2bac5fa8 --- /dev/null +++ b/crates/engine/src/ocr/layer.rs @@ -0,0 +1,145 @@ +//! Unicode search text has no visible glyphs. A generated Type 3 font supplies advance widths +//! and a ToUnicode map, with empty character programs; no display font is needed or embedded. +//! Adapted from the searchable-layer implementation in #433 (32e09fbe). + +use std::collections::BTreeMap; + +use pdfcraft_cos::{Dict, Document, Object, Stream}; +use pdfcraft_edit::EditError; +use pdfcraft_ocr::PlacedWord; + +/// Refuse oversized text or invalid geometry before cloning words or allocating fonts. +/// These limits apply to the complete input, including all editable export pages. +pub(crate) fn validate_words<'a>(words: impl IntoIterator) -> Result { + let mut count = 0usize; + let mut length = 0usize; + for w in words { + count += 1; + length = length.checked_add(w.text.len()).ok_or_else(|| EditError::Invalid("OCR text layer is too large".into()))?; + if count > 65536 || length > 4 * 1024 * 1024 { + return Err(EditError::Invalid("OCR text layer is too large".into())); + } + if !w.origin.iter().chain(&w.across).chain(&w.up).all(|v| v.is_finite()) + || !w.across[0].hypot(w.across[1]).is_finite() + || !w.up[0].hypot(w.up[1]).is_finite() + || (0..2).any(|i| !(w.origin[i] + 0.2 * w.up[i]).is_finite() || !(w.origin[i] + w.across[i] + 0.2 * w.up[i]).is_finite()) + { + return Err(EditError::Invalid("OCR text coordinates must be finite".into())); + } + } + Ok(count) +} + +pub(crate) fn add_text(doc: &mut Document, page: usize, words: &[PlacedWord]) -> Result<(), EditError> { + validate_words(words)?; + // Keep the existing Latin layout, including Helvetica's proportional advance widths. + if words.iter().all(|w| { + w.text + .chars() + .all(|c| matches!(c, '\u{20}'..='\u{7e}' | '\u{a0}'..='\u{ff}' | '€' | '‚' | '„' | '…' | '‘' | '’' | '“' | '”' | '•' | '–' | '—' | '™')) + }) { + pdfcraft_edit::stamp(doc, page, "OCR", pdfcraft_ocr::text_layer(words, &pdfcraft_fonts::TextPlan::default()))?; + return Ok(()); + } + let p = pdfcraft_model::pages(doc).get(page).cloned().ok_or_else(|| EditError::Invalid("OCR page does not exist".into()))?; + let mut res = p.dict.get(b"Resources").map(|r| doc.resolve(r)).and_then(|r| r.as_dict().cloned()).unwrap_or_default(); + let mut fonts = res.get(b"Font").map(|f| doc.resolve(f)).and_then(|f| f.as_dict().cloned()).unwrap_or_default(); + let chars: Vec = words.iter().flat_map(|w| w.text.chars()).collect::>().into_iter().collect(); + // Match the extractor's em box (-200..800). Baselines below are offset by 0.2 em, + // so search/selection rectangles span the detected image box. + let blank = doc.add(Object::Stream(Stream::from_raw(Dict::new(), b"1000 0 0 -200 1000 800 d1\n".to_vec()))); + let mut codes = BTreeMap::new(); + let mut names = Vec::new(); + for (index, chunk) in chars.chunks(255).enumerate() { + let mut name = format!("PCOcr{index}"); + while fonts.contains(name.as_bytes()) { + name.push('x'); + } + let mut differences = vec![Object::Int(1)]; + let mut procs = Dict::new(); + let mut cmap = String::from( + "/CIDInit /ProcSet findresource begin\n12 dict begin\nbegincmap\n/CIDSystemInfo << /Registry (PdfCraft) /Ordering (Unicode) /Supplement 0 >> def\n/CMapName /PdfCraftOCR def\n/CMapType 2 def\n1 begincodespacerange\n<01> \nendcodespacerange\n", + ); + for (batch, part) in chunk.chunks(100).enumerate() { + cmap.push_str(&format!("{} beginbfchar\n", part.len())); + for (i, ch) in part.iter().enumerate() { + let code = (batch * 100 + i + 1) as u8; + let glyph = format!("g{code:02X}"); + differences.push(Object::name(&glyph)); + procs.set(glyph.into_bytes(), Object::Ref(blank)); + let mut units = [0u16; 2]; + let hex: String = ch.encode_utf16(&mut units).iter().map(|u| format!("{u:04X}")).collect(); + cmap.push_str(&format!("<{code:02X}> <{hex}>\n")); + codes.insert(*ch, (index, code)); + } + cmap.push_str("endbfchar\n"); + } + cmap.push_str("endcmap\nCMapName currentdict /CMap defineresource pop\nend\nend\n"); + let map = doc.add(Object::Stream(Stream::flate(Dict::new(), cmap.as_bytes()))); + let mut encoding = Dict::new(); + encoding.set(b"Type".to_vec(), Object::name("Encoding")); + encoding.set(b"Differences".to_vec(), Object::Array(differences)); + let mut font = Dict::new(); + font.set(b"Type".to_vec(), Object::name("Font")); + font.set(b"Subtype".to_vec(), Object::name("Type3")); + font.set(b"FontBBox".to_vec(), Object::Array(vec![0.into(), (-200).into(), 1000.into(), 800.into()])); + font.set(b"FontMatrix".to_vec(), Object::Array(vec![Object::Real(0.001), 0.into(), 0.into(), Object::Real(0.001), 0.into(), 0.into()])); + font.set(b"FirstChar".to_vec(), Object::Int(1)); + font.set(b"LastChar".to_vec(), Object::Int(chunk.len() as i64)); + font.set(b"Widths".to_vec(), Object::Array(vec![Object::Int(1000); chunk.len()])); + font.set(b"Encoding".to_vec(), Object::Dict(encoding)); + font.set(b"CharProcs".to_vec(), Object::Dict(procs)); + font.set(b"Resources".to_vec(), Object::Dict(Dict::new())); + font.set(b"ToUnicode".to_vec(), Object::Ref(map)); + fonts.set(name.as_bytes().to_vec(), Object::Ref(doc.add(Object::Dict(font)))); + names.push(name); + } + res.set(b"Font".to_vec(), Object::Dict(fonts)); + doc.update_dict(p.obj, |d| d.set(b"Resources".to_vec(), Object::Dict(res)))?; + // `3 Tr` and the font are graphics state, which `ET` doesn't reset: like + // `pdfcraft_ocr::text_layer` (#3029), the text is drawn inside `q … Q` so the invisible + // rendering mode cannot leak into later content streams on the page. + let mut content = String::from("/OCR BMC\nq\nBT\n3 Tr\n"); + for w in words { + let count = w.text.chars().count(); + if count == 0 || w.up[0].hypot(w.up[1]) <= 0.0 || w.across[0].hypot(w.across[1]) <= 0.0 { + continue; + } + let mut start = 0; + let mut run = Vec::new(); + let mut font_index = None; + let emit = |content: &mut String, font: usize, start: usize, run: &[u8]| { + let n = count as f64; + let at = start as f64 / n; + let hex: String = run.iter().map(|b| format!("{b:02X}")).collect(); + content.push_str(&format!( + "/{} 1 Tf\n{} {} {} {} {} {} Tm <{hex}> Tj\n", + names[font], + w.across[0] / n, + w.across[1] / n, + w.up[0], + w.up[1], + w.origin[0] + at * w.across[0] + 0.2 * w.up[0], + w.origin[1] + at * w.across[1] + 0.2 * w.up[1] + )); + }; + for (i, ch) in w.text.chars().enumerate() { + let Some(&(font, code)) = codes.get(&ch) else { continue }; + if let Some(previous) = font_index + && previous != font + { + emit(&mut content, previous, start, &run); + run.clear(); + start = i; + } + font_index = Some(font); + run.push(code); + } + if let Some(font) = font_index { + emit(&mut content, font, start, &run); + } + } + content.push_str("ET\nQ\nEMC\n"); + pdfcraft_edit::stamp(doc, page, "OCR", content.into_bytes())?; + Ok(()) +} diff --git a/crates/engine/src/scan_fields.rs b/crates/engine/src/scan_fields.rs index a1574e9463..05906d75b2 100644 --- a/crates/engine/src/scan_fields.rs +++ b/crates/engine/src/scan_fields.rs @@ -186,10 +186,14 @@ impl Session { if !ocr::available() { return Vec::new(); } - let (Ok(engine), Some(job)) = (ocr::engine(), self.ocr_job(id, &[page], ocr::OcrSettings::default())) else { + let settings = ocr::OcrSettings::default(); + let Some(job) = self.ocr_job(id, &[page], settings.clone()) else { return Vec::new(); }; - job.run(&engine, |_, _| true) + let Ok(recognizers) = ocr::recognizers(&settings) else { + return Vec::new(); + }; + job.run(&recognizers, |_, _| true) .into_iter() .flat_map(|p| p.words) .filter_map(|w| { diff --git a/crates/engine/src/session/files.rs b/crates/engine/src/session/files.rs index 553ddd6aa3..44bed85cde 100644 --- a/crates/engine/src/session/files.rs +++ b/crates/engine/src/session/files.rs @@ -114,6 +114,19 @@ impl Session { .map_err(EditError::Write) } + /// XFDF with these comments (0-based page, position in the page's `/Annots`) and their + /// replies: what Copy puts on the clipboard; [`Edit::PasteComments`] takes it back in. + pub fn export_comments(&self, id: DocId, which: &[(usize, usize)]) -> Result { + let doc = self.get(id).ok_or(EditError::NoDocument)?; + let cos = match doc.editor.as_ref() { + Some(e) => e.cos.clone(), + None => { + pdfcraft_cos::Document::open_with_password(doc.bytes.clone(), doc.password.as_deref()).map_err(|e| EditError::Write(e.to_string()))? + } + }; + guard(|| pdfcraft_xfdf::export_xfdf_comments(&cos, which, &doc.name)).map_err(EditError::Write) + } + /// The print-ready PDF for `settings` (sheets laid out for the paper; see `pdfcraft-print`). pub fn print_pdf(&self, id: DocId, settings: &print::Settings) -> Result, EditError> { let doc = self.get(id).ok_or(EditError::NoDocument)?; @@ -384,7 +397,7 @@ impl Session { /// A new file (Combine, Extract, Split, Create) as bytes, checked like a save before anyone /// writes it (#1698, #2166): it reopens, and shows the pages it was built from. - fn write_new(&self, doc: &pdfcraft_cos::Document) -> Result>, EditError> { + pub(crate) fn write_new(&self, doc: &pdfcraft_cos::Document) -> Result>, EditError> { let bytes = self.write_unchecked(doc)?; let expected = pdfcraft_organize::page_count(doc)?; pdfcraft_cos::Document::open(bytes.clone()).map_err(|e| EditError::Reopen(e.to_string()))?; diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 6c54131d02..5b6fb01b9e 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -623,12 +623,12 @@ fn a_3d_model_needs_the_comments_permission_and_changes_the_comments() { activation: Activation3d::default(), name: String::new(), }; - let p = pdfcraft_cos::Permissions { bits: 0, owner: false }; + let p = pdfcraft_cos::Permissions { bits: 0, owner: false, revision: 3 }; assert_eq!(check_permission(&edit, &p), Err(EditError::NotPermitted("comments"))); assert_eq!(crate::history::scope_of(&edit), crate::history::Scope::Comments); } -fn page_texts(s: &Session, id: DocId) -> Vec { +pub(crate) fn page_texts(s: &Session, id: DocId) -> Vec { let doc = s.get(id).unwrap(); let config = pdfcraft_render::RenderConfig { password: doc.password.as_deref().map(Arc::from), ..Default::default() }; let mut r = pdfcraft_render::PageRenderer::new(doc.bytes.clone(), config); @@ -2211,7 +2211,7 @@ fn rect_comment(page: usize, rect: [f64; 4]) -> Edit { Edit::AddAnnotation(NewAnnotation { page, shape: Shape::Rectangle { rect }, - style: Style { color: [1.0, 0.0, 0.0], opacity: 1.0, width: 2.0, fill: Some([1.0, 0.0, 0.0]) }, + style: Style { color: [1.0, 0.0, 0.0], opacity: 1.0, width: 2.0, fill: Some([1.0, 0.0, 0.0]), ..Style::default() }, contents: "Look here".into(), author: "Reviewer".into(), }) @@ -5841,6 +5841,10 @@ fn comparing_two_versions_of_a_document() { let got: Vec<(compare::Kind, &str, &str)> = c.changes.iter().map(|x| (x.kind, x.old.text.as_str(), x.new.text.as_str())).collect(); assert_eq!(got, [(compare::Kind::Replaced, "Monday.", "Tuesday."), (compare::Kind::Replaced, "days.", "days of invoice.")], "{got:?}"); assert!(s.compare(old, old).unwrap().identical()); + // limited to pages of the new file: both changes are on the first + assert_eq!(s.compare_pages(old, new, &[]).unwrap().changes.len(), 2); + assert_eq!(s.compare_pages(old, new, &[0]).unwrap().changes.len(), 2); + assert!(s.compare_pages(old, new, &[1]).unwrap().identical()); let report = s.compare_report(old, new).unwrap(); let rid = s.open("report.pdf", None, report, None).unwrap(); @@ -6048,7 +6052,7 @@ fn measurement_edits_are_transactional_and_honour_annotation_permissions() { assert!(session.get(id).unwrap().measurements().unwrap().measurements.is_empty()); session.redo(id).unwrap(); assert_eq!(session.get(id).unwrap().bytes, before); - let p = pdfcraft_cos::Permissions { bits: 0, owner: false }; + let p = pdfcraft_cos::Permissions { bits: 0, owner: false, revision: 3 }; assert_eq!(check_permission(&Edit::AddMeasurement(m), &p), Err(EditError::NotPermitted("comments"))); assert_eq!( check_permission( @@ -7322,12 +7326,13 @@ fn datasets_streams(bytes: &Arc>) -> usize { /// and noted. #[test] fn hostile_xfa_open_scripts_are_merged_capped_kept_from_printing_and_noted() { - // On open: a calculate setting its own value 50 000 times, an initialize script showing a - // thousand messages and asking to print, open a link and save. + // On open: a calculate setting its own value 20 000 times (50 000 sat right at the 1 s + // unasked-script timeout and abandoned whenever the test machine was loaded), an + // initialize script showing a thousand messages and asking to print, open a link and save. let tpl = pdfcraft_xfa::fixtures::scripted_template() .replace( r#""#, - r#""#, + r#""#, ) .replace( r#"if (qty.rawValue === null) qty.rawValue = 2;"#, @@ -7337,9 +7342,11 @@ fn hostile_xfa_open_scripts_are_merged_capped_kept_from_printing_and_noted() { let mut s = Session::new().with_clock(|| 1_700_000_000); let started = std::time::Instant::now(); let id = s.open("hostile.pdf", None, bytes, None).expect("opens"); - assert!(started.elapsed() < std::time::Duration::from_secs(5), "{:?}", started.elapsed()); + // 30 s and not 5 s: the run is wall-clock timed and a loaded test machine (all suites in + // parallel) can take several seconds for the 20 000 iterations; a real hang still fails. + assert!(started.elapsed() < std::time::Duration::from_secs(30), "{:?}", started.elapsed()); let doc = s.get(id).unwrap(); - assert_eq!(doc.form.iter().find(|f| f.name == "total").unwrap().value, vec!["49999".to_string()]); + assert_eq!(doc.form.iter().find(|f| f.name == "total").unwrap().value, vec!["19999".to_string()]); // One datasets stream for the scripts' revision, not one per value set. assert!(datasets_streams(&doc.bytes) <= 3, "{} datasets streams", datasets_streams(&doc.bytes)); // What opening changed is noted with the form's other XFA notes. @@ -10185,6 +10192,42 @@ fn need_appearances_buttons_are_displayed_from_their_captions() { } } +/// Copy and paste: the copies of a comment and its reply land on the asked-for page of another +/// document under names of their own (nothing replaced; a second paste gives a second set), +/// undo takes a paste away as one step, and a clipboard without comments is refused. +#[test] +fn pasting_copied_comments_adds_copies_that_undo_as_one_step() { + let (mut s, id) = session_with(2); + s.apply(id, rect_comment(1, [80.0, 80.0, 120.0, 120.0])).unwrap(); + s.apply(id, Edit::ReplyToAnnotation { page: 1, index: 0, text: "Done".into(), author: "Ada".into() }).unwrap(); + let xfdf = s.export_comments(id, &[(1, 0)]).unwrap(); + assert!(xfdf.contains(" MutexGuard<'static, ()> { + static LOCK: Mutex<()> = Mutex::new(()); + let lock = LOCK.lock().unwrap_or_else(PoisonError::into_inner); + use_form_date_language("en"); + lock +} + +/// `util.printd(fmt)` of 18 October 2026, then of what `util.scand(fmt, typed)` reads. +fn printd(fmt: &str, typed: &str) -> String { + let doc = DocInfo { file_name: "form.pdf".into(), num_pages: 1, page: 0, info: Vec::new(), xfa: false }; + let script = format!("event.value = util.printd('{fmt}', new Date(2026, 9, 18)) + '|' + util.printd('{fmt}', util.scand('{fmt}', '{typed}'));"); + let o = run(&script, &Event::field("Format", "date", ""), &doc, &[], &[], Limits::default()); + assert_eq!(o.error, None); + o.value +} + +#[test] +fn form_dates_follow_the_date_language() { + let _names = names_lock(); + let oct18 = DateTime { y: 2026, m: 10, d: 18, hh: 0, mm: 0, ss: 0 }; + let dd_mmm_yy = Format::Date("dd-mmm-yy".into()); + // English until the app says otherwise. + assert_eq!(format_date(oct18, "dd-mmm-yy dddd ddd mmmm"), "18-Oct-26 Sunday Sun October"); + use_form_date_language("it"); + // AFDate_FormatEx("dd-mmm-yy"), what the issue's form used. + assert_eq!(format_value(&dd_mmm_yy, "18-10-26"), "18-ott-26"); + assert_eq!(format_date(oct18, "dddd d mmmm yyyy, ddd"), "domenica 18 ottobre 2026, dom"); + // What it writes reads back, and so does English typing. + assert_eq!(parse_date("18-ott-26", "dd-mmm-yy"), Some(oct18)); + assert_eq!(parse_date("18 ottobre 2026", "dd mmmm yyyy"), Some(oct18)); + assert_eq!(parse_date("18-Oct-26", "dd-mmm-yy"), Some(oct18)); + assert!(keystroke(&dd_mmm_yy, "date", "18-ott-26").is_ok()); + // util.printd writes Italian names; util.scand reads them. + assert_eq!(printd("dd-mmm-yy", "18-ott-26"), "18-ott-26|18-ott-26"); + assert_eq!(printd("dd-mmm-yy", "18-Oct-26"), "18-ott-26|18-ott-26", "English typing reads too"); + assert_eq!(printd("dddd d mmmm yyyy", "domenica 18 ottobre 2026"), "domenica 18 ottobre 2026|domenica 18 ottobre 2026"); + // German short names end in a dot; they are written and read whole. + use_form_date_language("de"); + assert_eq!(format_value(&dd_mmm_yy, "18-10-26"), "18-Okt.-26"); + assert_eq!(parse_date("18-Okt.-26", "dd-mmm-yy"), Some(oct18)); + // An unknown language is English again. + use_form_date_language("xx"); + assert_eq!(format_value(&dd_mmm_yy, "18-10-26"), "18-Oct-26"); + assert_eq!(printd("dd-mmm-yy", "18-Oct-26"), "18-Oct-26|18-Oct-26"); + every_date_language_reads_back_what_it_writes(); + // Hostile typing never panics and stays quick: long, odd and mixed-script text. + use_form_date_language("th"); + let junk = ["", " ", "ม.", "ม.ค.ม.ค.ม.ค.", "\u{0}", "1月1月1月", "tháng tháng", "Ottobre", "🙂ott🙂", "İstanbul ott 26"]; + for t in junk.iter().map(|s| s.to_string()).chain(["ม.ค.1".repeat(5000), "9".repeat(100_000)]) { + let started = std::time::Instant::now(); + let _ = parse_date(&t, "dd-mmm-yy"); + let _ = keystroke(&dd_mmm_yy, "date", &t); + assert!(started.elapsed() < std::time::Duration::from_secs(2), "{} chars took {:?}", t.len(), started.elapsed()); + } + use_form_date_language("en"); +} + +/// An English weekday typed before the month fills the format's weekday, so a month name that +/// the date language shares with a weekday (Italian, Spanish, Romanian and Albanian "mar") is +/// still read as the month: "Tue 17 Mar 2026" read as "Tue 17 Tuesday 2026" (#5303). +#[test] +fn an_english_weekday_before_a_shared_month_name_reads_as_english() { + let _names = names_lock(); + let doc = DocInfo { file_name: "form.pdf".into(), num_pages: 1, page: 0, info: Vec::new(), xfa: false }; + let mar17 = DateTime { y: 2026, m: 3, d: 17, hh: 0, mm: 0, ss: 0 }; + let mut bad = Vec::new(); + for language in ["it", "es", "ro", "sq"] { + use_form_date_language(language); + let ddd_d_mmm = "ddd d mmm yyyy"; + let typed = [ + // What the language writes, then English, then English and localized mixed. + (ddd_d_mmm, format_date(mar17, ddd_d_mmm)), + (ddd_d_mmm, "Tue 17 Mar 2026".into()), + (ddd_d_mmm, "Tuesday 17 Mar 2026".into()), + (ddd_d_mmm, "tue 17 mar 2026".into()), + (ddd_d_mmm, format!("Tue 17 {}", format_date(mar17, "mmm yyyy"))), + (ddd_d_mmm, format!("{} 17 Mar 2026", format_date(mar17, "ddd"))), + ("mmm d yyyy ddd", "Mar 17 2026 Tue".into()), + ("dddd d mmmm yyyy", "Tuesday 17 March 2026".into()), + ]; + for (fmt, text) in typed { + if parse_date(&text, fmt) != Some(mar17) { + bad.push(format!("{language} forms {fmt}: {text:?} -> {:?}", parse_date(&text, fmt))); + } + let script = format!("var d = util.scand('{fmt}', {text:?}); event.value = d ? util.printd('yyyy-mm-dd', d) : 'null';"); + let o = run(&script, &Event::field("Format", "date", ""), &doc, &[], &[], Limits::default()); + if o.value != "2026-03-17" { + bad.push(format!("{language} scand {fmt}: {text:?} -> {:?} {:?}", o.value, o.error)); + } + } + } + use_form_date_language("en"); + assert!(bad.is_empty(), "{}", bad.join("; ")); +} + +/// Every date language: what a date field writes reads back as the same date, for each date +/// letter that writes a name, through the form path and through `util.scand`. Called from the +/// one test, which owns the process-wide names. +fn every_date_language_reads_back_what_it_writes() { + let doc = DocInfo { file_name: "form.pdf".into(), num_pages: 1, page: 0, info: Vec::new(), xfa: false }; + let mut bad = Vec::new(); + for l in pdfcraft_engine::dates::DATE_LANGUAGES.iter() { + use_form_date_language(l.code); + for m in 1..=12u32 { + let dt = DateTime { y: 2026, m, d: 18, hh: 0, mm: 0, ss: 0 }; + for fmt in ["dd-mmm-yy", "d mmmm yyyy", "dddd, mmmm d, yyyy", "ddd d mmm yyyy", "mmm d, yyyy ddd", "yyyymmmdd"] { + let text = format_date(dt, fmt); + // A short month ending in a number ("Thg 1") glued to the day is ambiguous + // ("Thg 118": January 18 or November 8): nothing can read it back. + if fmt == "yyyymmmdd" && l.months_short.iter().any(|n| n.ends_with(|c: char| c.is_ascii_digit())) { + continue; + } + if parse_date(&text, fmt).map(|p| (p.y, p.m, p.d)) != Some((2026, m, 18)) { + bad.push(format!("{} forms {fmt}: {text:?}", l.code)); + } + let script = format!("var d = util.scand('{fmt}', {text:?}); event.value = d ? util.printd('yyyy-mm-dd', d) : 'null';"); + let o = run(&script, &Event::field("Format", "date", ""), &doc, &[], &[], Limits::default()); + if o.value != format!("2026-{m:02}-18") { + bad.push(format!("{} scand {fmt}: {text:?} -> {:?} {:?}", l.code, o.value, o.error)); + } + } + } + } + use_form_date_language("en"); + assert!(bad.is_empty(), "{} failures:\n{}", bad.len(), bad.iter().take(40).cloned().collect::>().join("\n")); +} + +/// A form whose text fields are each `(name, font, format script)`: `/Helv` is Helvetica with +/// WinAnsi, `/Song` a Chinese font with a Unicode CMap, which also holds Cyrillic. +fn form(fields: &[(&str, &str, &str)]) -> Document { + let n = fields.len(); + let first = 6; + let refs = |from: usize| (from..from + n).map(|i| format!("{i} 0 R")).collect::>().join(" "); + let mut objs: Vec = vec![ + "<< /Type /Catalog /Pages 2 0 R /AcroForm 4 0 R >>".into(), + "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 600 800] >>".into(), + format!("<< /Type /Page /Parent 2 0 R /Annots [{}] >>", refs(first)), + format!("<< /Fields [{}] /DA (/Helv 0 Tf 0 g) /DR << /Font << /Helv 5 0 R /Song {} 0 R >> >> >>", refs(first), first + n), + "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>".into(), + ]; + for (i, (name, font, js)) in fields.iter().enumerate() { + let js = js.replace('\\', "\\\\").replace('(', "\\(").replace(')', "\\)"); + let y = 700 - 30 * i; + objs.push(format!( + "<< /Type /Annot /Subtype /Widget /FT /Tx /T ({name}) /DA (/{font} 10 Tf 0 g) /Rect [50 {y} 300 {}] /P 3 0 R /AA << /F << /S /JavaScript /JS ({js}) >> >> >>", + y + 20 + )); + } + objs.push("<< /Type /Font /Subtype /Type0 /BaseFont /STSong-Light /Encoding /UniGB-UCS2-H /DescendantFonts [<< /Type /Font /Subtype /CIDFontType0 /BaseFont /STSong-Light /CIDSystemInfo << /Registry (Adobe) /Ordering (GB1) /Supplement 4 >> >>] >>".into()); + let mut out = b"%PDF-1.7 +" + .to_vec(); + let mut offsets = Vec::new(); + for (i, o) in objs.iter().enumerate() { + offsets.push(out.len()); + out.extend_from_slice( + format!( + "{} 0 obj +{o} +endobj +", + i + 1 + ) + .as_bytes(), + ); + } + let xref = out.len(); + out.extend_from_slice( + format!( + "xref +0 {} +0000000000 65535 f +", + objs.len() + 1 + ) + .as_bytes(), + ); + for o in offsets { + out.extend_from_slice( + format!( + "{o:010} 00000 n +" + ) + .as_bytes(), + ); + } + out.extend_from_slice( + format!( + "trailer +<< /Size {} /Root 1 0 R >> +startxref +{xref} +%%EOF +", + objs.len() + 1 + ) + .as_bytes(), + ); + Document::open(Arc::new(out)).expect("opens") +} + +/// The content of field `name`'s normal appearance. +fn appearance(doc: &Document, name: &str) -> Vec { + let all = pdfcraft_forms::fields(doc); + let f = all.iter().find(|f| f.name == name).expect("field"); + let widget = doc.get(f.widgets[0].obj); + let normal = widget.as_dict().and_then(|d| d.get(b"AP")).and_then(|a| doc.resolve(a).as_dict().and_then(|a| a.reference(b"N"))).expect("/AP /N"); + match &*doc.get(normal) { + Object::Stream(s) => s.decoded().expect("decodes"), + other => panic!("not a stream: {other:?}"), + } +} + +/// What a Unicode-CMap (UCS-2) font is given for `text`. +fn ucs2(text: &str) -> Vec { + text.encode_utf16().flat_map(u16::to_be_bytes).collect() +} + +fn contains(hay: &[u8], needle: &[u8]) -> bool { + hay.windows(needle.len()).any(|w| w == needle) +} + +/// Fills `form`'s field `name` with 18 October 2026 through the JavaScript runner. +fn fill(doc: &mut Document, name: &str) { + fill_with(doc, name, "18-10-26"); +} + +/// Fills `form`'s field `name` with `value` through the JavaScript runner. +fn fill_with(doc: &mut Document, name: &str, value: &str) { + let mut js = JsRunner::new(doc, "form.pdf"); + pdfcraft_forms::set_value_with(doc, name, &FieldValue::Text(value.into()), &mut js).expect("fills"); +} + +/// Month names in the date language that no font of the field can draw are drawn in English, +/// never as `?` ("18-????.-26" in Russian); a font that holds them keeps them (#5303). +#[test] +fn date_names_no_field_font_can_draw_are_drawn_in_english() { + let _names = names_lock(); + let date = "AFDate_FormatEx(\"dd-mmm-yy\");"; + let fields = [("helv", "Helv", date), ("song", "Song", date)]; + for (language, local) in [("ru", "окт."), ("cs", "říj"), ("ja", "10月"), ("el", "Οκτ")] { + use_form_date_language(language); + let mut doc = form(&fields); + fill(&mut doc, "helv"); + fill(&mut doc, "song"); + let helv = appearance(&doc, "helv"); + assert!(contains(&helv, b"(18-Oct-26) Tj"), "{language}: {}", String::from_utf8_lossy(&helv)); + assert!(!helv.contains(&b'?'), "{language}: {}", String::from_utf8_lossy(&helv)); + assert!(pdfcraft_forms::undrawn_fields(&doc).is_empty(), "{language}"); + let song = appearance(&doc, "song"); + assert!(contains(&song, &ucs2(&format!("18-{local}-26"))), "{language} keeps its name: {song:?}"); + } + // Names Helvetica holds are kept: Italian "ott". + use_form_date_language("it"); + let mut doc = form(&fields); + fill(&mut doc, "helv"); + assert!(contains(&appearance(&doc, "helv"), b"(18-ott-26) Tj")); + use_form_date_language("en"); +} + +/// A Format script's `util.printd` is run again with English names for a field whose fonts +/// can't draw the date language's, and kept where they can (#5303). +#[test] +fn format_scripts_print_dates_in_english_where_the_field_cannot_draw_them() { + let _names = names_lock(); + let script = "event.value = event.value ? util.printd(\"dd-mmm-yy\", util.scand(\"dd-mm-yy\", event.value)) + \" !\" : \"\";"; + let fields = [("helv", "Helv", script), ("song", "Song", script)]; + use_form_date_language("ru"); + let mut doc = form(&fields); + fill(&mut doc, "helv"); + fill(&mut doc, "song"); + let helv = appearance(&doc, "helv"); + assert!(contains(&helv, b"(18-Oct-26 !) Tj"), "{}", String::from_utf8_lossy(&helv)); + assert!(!helv.contains(&b'?'), "{}", String::from_utf8_lossy(&helv)); + assert!(pdfcraft_forms::undrawn_fields(&doc).is_empty()); + assert!(contains(&appearance(&doc, "song"), &ucs2("18-окт.-26 !"))); + // A script whose text has no English either keeps it, reported as undrawn. + let greeting = [("hi", "Helv", "event.value = \"Привет \" + util.printd(\"mmm\", new Date(2026, 9, 18));")]; + let mut doc = form(&greeting); + fill(&mut doc, "hi"); + assert_eq!(pdfcraft_forms::undrawn_fields(&doc), [("hi".to_string(), 'П')]); + // The English run is the appearance's alone: scripts go on printing the date language. + assert_eq!(printd("dd-mmm-yy", "18-окт.-26"), "18-окт.-26|18-окт.-26"); + use_form_date_language("en"); +} + +/// A Format script's English run is kept when it ran, even where it prints the stored value +/// again: a Helvetica field storing "18-Oct-26", printed again as `dd-mmm-yy`, showed +/// "18-????.-26" in Russian. A script that fails keeps what it showed, reported undrawn (#5303). +#[test] +fn an_english_run_that_prints_the_stored_value_is_drawn() { + let _names = names_lock(); + let script = "event.value = util.printd(\"dd-mmm-yy\", util.scand(\"dd-mmm-yy\", event.value));"; + use_form_date_language("ru"); + let mut doc = form(&[("helv", "Helv", script), ("fails", "Helv", "throw new Error(\"no\");")]); + fill_with(&mut doc, "helv", "18-Oct-26"); + let helv = appearance(&doc, "helv"); + assert!(contains(&helv, b"(18-Oct-26) Tj"), "{}", String::from_utf8_lossy(&helv)); + assert!(!helv.contains(&b'?'), "{}", String::from_utf8_lossy(&helv)); + assert!(pdfcraft_forms::undrawn_fields(&doc).is_empty()); + fill_with(&mut doc, "fails", "18-окт.-26"); + assert_eq!(pdfcraft_forms::undrawn_fields(&doc), [("fails".to_string(), 'о')]); + use_form_date_language("en"); +} + +/// What `util.scand(fmt, text)` reads, as `yyyy-mm-dd`, or `null`. +fn scanned(fmt: &str, text: &str) -> String { + let doc = DocInfo { file_name: "form.pdf".into(), num_pages: 1, page: 0, info: Vec::new(), xfa: false }; + let script = format!("var d = util.scand('{fmt}', {text:?}); event.value = d ? util.printd('yyyy-mm-dd', d) : 'null';"); + let o = run(&script, &Event::field("Format", "date", ""), &doc, &[], &[], Limits::default()); + assert_eq!(o.error, None); + o.value +} + +/// A short weekday typed without its dot ("mar" for French "mar.", Tuesday) is the weekday where +/// the format has one, not the English "Mar" (March) that is the only other name of its length: +/// "mar 6 janv 2026" read as no date in French and Romanian (#5303). +#[test] +fn a_short_weekday_typed_without_its_dot_is_the_weekday() { + let _names = names_lock(); + let mut bad = Vec::new(); + let cases = [ + ("fr", "ddd d mmm yyyy", "Mar 6 janv 2026", "2026-01-06"), + ("fr", "ddd d mmm yyyy", "mar 17 mars 2026", "2026-03-17"), + ("fr", "mmm d yyyy ddd", "janv 6 2026 mar", "2026-01-06"), + ("fr", "ddd dd/mm/yyyy", "mar 06/01/2026", "2026-01-06"), + ("ro", "ddd d mmm yyyy", "mar 6 ian 2026", "2026-01-06"), + ("ro", "ddd dd/mm/yyyy", "mar 06/01/2026", "2026-01-06"), + ]; + for (language, fmt, text, want) in cases { + use_form_date_language(language); + let got = scanned(fmt, text); + if got != want { + bad.push(format!("{language} scand {fmt}: {text:?} -> {got}")); + } + let read = parse_date(text, fmt).map(|d| format!("{:04}-{:02}-{:02}", d.y, d.m, d.d)); + if read.as_deref() != Some(want) { + bad.push(format!("{language} forms {fmt}: {text:?} -> {read:?}")); + } + } + use_form_date_language("en"); + assert!(bad.is_empty(), "{}", bad.join("; ")); +} + +/// A weekday left out of a format with one ("17 mar 2026" for "ddd d mmm yyyy") lets a name the +/// date language shares between a weekday and a month be the month: Italian, Spanish and +/// Albanian "mar" (Tuesday, March) and Albanian "sht" (Saturday, September) were read as the +/// weekday, leaving no month (#5303). Typed weekdays still go first. +#[test] +fn a_shared_name_is_the_month_when_the_weekday_is_left_out() { + let _names = names_lock(); + let mut bad = Vec::new(); + let cases = [ + ("it", "ddd d mmm yyyy", "17 Mar 2026", (2026, 3, 17)), + ("es", "ddd d mmm yyyy", "17 Mar 2026", (2026, 3, 17)), + ("sq", "ddd d mmm yyyy", "17 Mar 2026", (2026, 3, 17)), + ("it", "ddd d mmm yyyy", "17 mar 2026", (2026, 3, 17)), + ("it", "dddd, mmmm d, yyyy", "mar 17, 2026", (2026, 3, 17)), + ("it", "dddd, mmm d, yyyy", "mar 17 2026", (2026, 3, 17)), + ("sq", "ddd d mmm yyyy", "5 sht 2026", (2026, 9, 5)), + ("it", "ddd d mmm yyyy", "mar 17 Mar 2026", (2026, 3, 17)), + ("it", "ddd d mmm yyyy", "mar 17 mar 2026", (2026, 3, 17)), + ]; + for (language, fmt, text, want) in cases { + use_form_date_language(language); + let read = parse_date(text, fmt).map(|d| (d.y, d.m, d.d)); + if read != Some(want) { + bad.push(format!("{language} forms {fmt}: {text:?} -> {read:?}")); + } + if keystroke(&Format::Date(fmt.into()), "date", text).is_err() { + bad.push(format!("{language} keystroke {fmt}: {text:?} refused")); + } + } + use_form_date_language("en"); + assert!(bad.is_empty(), "{}", bad.join("; ")); +} + +/// Turkish names typed in capitals are read: lower-casing letter by letter made "MAYIS" "mayis" +/// (not "mayıs"), "SALI" "sali" and "EKİM" "eki̇m" (an i with a dot above), so no name matched. +/// Dotted, dotless and capital i are one letter when names are read (#5303). +#[test] +fn turkish_names_typed_in_capitals_are_read() { + let _names = names_lock(); + use_form_date_language("tr"); + let mut bad = Vec::new(); + for (fmt, text, want) in [ + ("d mmmm yyyy", "1 MAYIS 2026", (2026, 5, 1)), + ("d mmmm yyyy", "1 EKİM 2026", (2026, 10, 1)), + ("d mmmm yyyy", "1 Ekim 2026", (2026, 10, 1)), + ("d mmm yyyy", "1 EKİ 2026", (2026, 10, 1)), + ("dddd d mmmm yyyy", "SALI 6 OCAK 2026", (2026, 1, 6)), + ("dddd d mmmm yyyy", "Salı 6 Ocak 2026", (2026, 1, 6)), + ] { + let read = parse_date(text, fmt).map(|d| (d.y, d.m, d.d)); + if read != Some(want) { + bad.push(format!("forms {fmt}: {text:?} -> {read:?}")); + } + let (y, m, d) = want; + let got = scanned(fmt, text); + if got != format!("{y:04}-{m:02}-{d:02}") { + bad.push(format!("scand {fmt}: {text:?} -> {got}")); + } + } + // English is read as before, capitals and all. + use_form_date_language("en"); + for (fmt, text) in [("d mmmm yyyy", "1 APRIL 2026"), ("dddd d mmmm yyyy", "FRIDAY 1 MAY 2026"), ("d mmm yyyy", "1 MAY 2026")] { + if parse_date(text, fmt).is_none() || scanned(fmt, text) == "null" { + bad.push(format!("en {fmt}: {text:?}")); + } + } + assert!(bad.is_empty(), "{}", bad.join("; ")); +} + +/// #5464 review: Greek names typed in capitals end in a capital Σ, which is the final ς of the +/// name ("ΙΑΝΟΥΆΡΙΟΣ" for "Ιανουάριος"); they read as they did before names were folded. +#[test] +fn greek_names_typed_in_capitals_are_read() { + let _names = names_lock(); + use_form_date_language("el"); + let mut bad = Vec::new(); + for (fmt, text, want) in [ + ("d mmmm yyyy", "1 ΙΑΝΟΥΆΡΙΟΣ 2026", (2026, 1, 1)), + ("d mmmm yyyy", "1 Ιανουάριος 2026", (2026, 1, 1)), + ("d mmmm yyyy", "1 ιανουάριοσ 2026", (2026, 1, 1)), + ("mmmm d, yyyy", "ΜΆΙΟΣ 5, 2026", (2026, 5, 5)), + ("dddd, mmmm d, yyyy", "FRIDAY, ΙΑΝΟΥΆΡΙΟΣ 2, 2026", (2026, 1, 2)), + ] { + let read = parse_date(text, fmt).map(|d| (d.y, d.m, d.d)); + if read != Some(want) { + bad.push(format!("forms {fmt}: {text:?} -> {read:?}")); + } + let (y, m, d) = want; + let got = scanned(fmt, text); + if got != format!("{y:04}-{m:02}-{d:02}") { + bad.push(format!("scand {fmt}: {text:?} -> {got}")); + } + } + assert!(bad.is_empty(), "{}", bad.join("; ")); +} diff --git a/crates/engine/tests/it/ocr_edit.rs b/crates/engine/tests/it/ocr_edit.rs index 53ca309326..2d358e327e 100644 --- a/crates/engine/tests/it/ocr_edit.rs +++ b/crates/engine/tests/it/ocr_edit.rs @@ -12,7 +12,14 @@ const WORD: [u32; 4] = [40, 40, 100, 60]; /// A 200 × 100 pt "scan" on tinted paper, with OCR text over its word. fn scanned() -> (Session, pdfcraft_engine::DocId) { - scanned_with(vec![PlacedWord { text: "John".into(), origin: [40.0, 40.0], across: [60.0, 0.0], up: [0.0, 20.0] }]) + scanned_with(vec![PlacedWord { + text: "John".into(), + origin: [40.0, 40.0], + across: [60.0, 0.0], + up: [0.0, 20.0], + confidence: None, + source: "ocrs".into(), + }]) } fn scanned_with(words: Vec) -> (Session, pdfcraft_engine::DocId) { @@ -86,11 +93,18 @@ fn an_explicit_colour_is_kept_for_the_new_text() { /// descender line when it has descenders, up to the cap height. fn scanned_word(text: &str, x0: f64, x1: f64, baseline: f64, size: f64) -> PlacedWord { let low = if text.chars().any(|c| "gjpqy".contains(c)) { 0.21 * size } else { 0.0 }; - PlacedWord { text: text.into(), origin: [x0, baseline - low], across: [x1 - x0, 0.0], up: [0.0, 0.718 * size + low] } + PlacedWord { + text: text.into(), + origin: [x0, baseline - low], + across: [x1 - x0, 0.0], + up: [0.0, 0.718 * size + low], + confidence: None, + source: "ocrs".into(), + } } fn word(text: &str, x0: f64, x1: f64, baseline: f64) -> PlacedWord { - PlacedWord { text: text.into(), origin: [x0, baseline], across: [x1 - x0, 0.0], up: [0.0, 10.0] } + PlacedWord { text: text.into(), origin: [x0, baseline], across: [x1 - x0, 0.0], up: [0.0, 10.0], confidence: None, source: "ocrs".into() } } /// OCR words keep the scan's layout: a phrase is one paragraph, a value in the next table cell and diff --git a/crates/fonts/README.md b/crates/fonts/README.md index b20b930a91..096f1a263e 100644 --- a/crates/fonts/README.md +++ b/crates/fonts/README.md @@ -59,7 +59,12 @@ set). Without that variable `CRAFT_FONTS` is empty and everything below copes: and shaped Thai Add Text content. Harfrust positions stacked vowel/tone marks and decomposes Sara Am; cluster ToUnicode entries preserve the original text. The shared Type 3 writer embeds outlines, so reopening does not depend on installed fonts. +- `craft_glyph(face, ch)` and `face_has(bytes, ch)`: bounded outlines and glyph coverage for any bundled face. - `SHIPPORI_MINCHO`: Shippori Mincho's bytes, or `None`. +- `TextPlan::for_words`: how the OCR output writes text beyond WinAnsi — per word the first + face (document face first) whose glyphs cover it, planned once per page into Type 3 fonts + (codes, advances, `?` stand-ins) that `pdfcraft-edit` registers and the `pdfcraft-ocr` layers + draw with; characters no face has are counted (`missing`) so the output reports them. Generated Japanese Type 3 fonts record the fallback face's family and style in an indirect `FontDescriptor`. `pdf::Metrics::base_font` uses its `FontName` when the Type 3 dictionary has diff --git a/crates/fonts/src/lib.rs b/crates/fonts/src/lib.rs index 61061f5509..45cb843ab0 100644 --- a/crates/fonts/src/lib.rs +++ b/crates/fonts/src/lib.rs @@ -14,6 +14,7 @@ pub mod embedding; mod encodings; pub mod fallback; pub mod pdf; +pub mod plan; mod script; mod shaping; pub mod source_shaping; @@ -24,8 +25,10 @@ pub use craft::{ document_japanese_font_for_style, document_japanese_fonts_for_style, document_latin_fonts, document_thai_font, ui_arabic_fonts, ui_chinese_fonts, ui_cjk_fonts, ui_devanagari_fonts, ui_hebrew_fonts, ui_japanese_fonts, ui_telugu_fonts, ui_thai_fonts, }; +pub use plan::{MAX_PLAN_GLYPHS, MAX_TYPE3_GLYPHS, PlannedType3, TextPlan}; pub use script::{ - GlyphError, GlyphOutline, INTER_REGULAR, MAX_SIGNATURE_CHARS, ScriptOutline, japanese_glyph, japanese_glyph_from, script_missing, script_outline, + GlyphError, GlyphOutline, INTER_REGULAR, MAX_SIGNATURE_CHARS, ScriptOutline, craft_glyph, face_has, japanese_glyph, japanese_glyph_from, + script_missing, script_outline, }; pub use shaping::{ ShapedCluster, ShapedScript, arabic_glyph, arabic_has, hebrew_has, shape_arabic, shape_hebrew, shape_thai, shaped_glyph, thai_has, @@ -273,6 +276,16 @@ pub fn set_undrawn_mark(d: &mut pdfcraft_cos::Dict, c: Option) { } } +/// The byte used by Unicode text plans, from the shared WinAnsi table (tabs become spaces). +pub fn win_ansi_char(c: char) -> Option { + if c == '\t' { Some(b' ') } else { win_ansi_byte(c) } +} + +/// Whether every character can be represented without substitution in WinAnsi. +pub fn fits_win_ansi(s: &str) -> bool { + s.chars().all(win_ansi_encodable) +} + /// Bytes as a PDF literal string, `(` … `)`, with delimiters escaped. pub fn literal(bytes: &[u8]) -> Vec { let mut out = Vec::with_capacity(bytes.len() + 2); diff --git a/crates/fonts/src/plan.rs b/crates/fonts/src/plan.rs new file mode 100644 index 0000000000..9c22a38fd3 --- /dev/null +++ b/crates/fonts/src/plan.rs @@ -0,0 +1,338 @@ +//! Planning visible Unicode text output for OCR: which characters the standard WinAnsi +//! fonts show as is, which need a Type3 font drawn from the craft-fonts faces, and which have +//! no glyph anywhere (written as `?` — and counted, never silently dropped). +//! +//! The plan is a pure function of the words ([`TextPlan::for_words`]). The content generators +//! (`pdfcraft_ocr::text_layer` / `visible_text_layer`) read the per-character codes and +//! advances from it, and whoever registers the fonts (`pdfcraft_edit::add_type3_fonts`) fills +//! in each face's resource name and object. The build must work without craft-fonts too: there +//! [`CRAFT_FONTS`] is empty, nothing can be planned, and every non-WinAnsi character is +//! reported as a substitution instead. + +use std::collections::HashMap; + +use pdfcraft_cos::ObjRef; + +use crate::{CraftFont, GlyphOutline, craft_glyph, document_japanese_font, face_has, fits_win_ansi, win_ansi_char}; + +/// Unique characters per Type3 font: the same bound the text-editing fallback uses, so one +/// hostile word cannot balloon into thousands of glyph streams. A face with more characters +/// simply gets another font. +pub const MAX_TYPE3_GLYPHS: usize = 240; + +/// Planned glyphs per plan in total (10 full fonts). A page's recognition cannot realistically +/// exceed it; hostile input beyond it degrades to `?` substitutions, which are counted. +pub const MAX_PLAN_GLYPHS: usize = 2400; + +/// One planned Type3 font: the glyphs of one craft-fonts face, one character per code +/// (`code = position + 1`, as in the text-editing fallback). `name` and `object` are filled in +/// when the font is added to a page's resources; until then the content generators fall back to +/// the WinAnsi path for the words that reference it. +pub struct PlannedType3 { + /// The face family the glyphs are drawn from ("Shippori Mincho"). + pub family: &'static str, + /// (character, outline with its advance) per code, in code order. + pub glyphs: Vec<(char, GlyphOutline)>, + /// The resource name the content references (`PCOcr`, `PCOcr1`, …); empty until registered. + pub name: String, + /// The built font object, shared by every page that uses the font; set at registration. + pub object: Option, +} + +impl PlannedType3 { + fn new(family: &'static str) -> Self { + PlannedType3 { family, glyphs: Vec::new(), name: String::new(), object: None } + } + + fn push(&mut self, ch: char, glyph: GlyphOutline) -> u8 { + self.glyphs.push((ch, glyph)); + self.glyphs.len() as u8 + } +} + +/// How the text layers write a plan's characters: each planned character is a +/// `(font index, code)` pair in its font's encoding; a character no face had a glyph for is +/// either the font's `?` code or absent from the run (both counted in [`TextPlan::missing`]). +#[derive(Default)] +pub struct TextPlan { + /// One planned font per face chunk, in first-use order. + pub fonts: Vec, + /// Per input word: `(font, code)` per character; empty for a word the standard WinAnsi + /// fonts write as is (or for which nothing could be planned). + words: Vec>, + /// character → where its glyph lives, across all fonts (codes are font-local). + index: HashMap, + /// Characters with no code in their word's font: they appear as `?` (or, when not even a + /// `?` glyph exists, are left out) and are reported, never silently lost. + missing: usize, +} + +impl TextPlan { + /// Plan the output for `words`, in order: characters the WinAnsi fonts can't show get codes + /// in Type3 fonts built from the craft-fonts faces (the document face preferred, then the + /// rest of the build input in manifest order); a word whose face can't show a character + /// substitutes its `?`. Faces are chosen per word, so a word of one script stays one face; + /// characters already planned for an earlier word keep their code. Built without + /// craft-fonts, the plan reports every non-WinAnsi character as a substitution. + pub fn for_words<'a>(words: impl IntoIterator) -> TextPlan { + let faces = document_faces(); + let mut coverage = Coverage::default(); + let mut plan = TextPlan::default(); + for word in words { + if fits_win_ansi(word) { + // The WinAnsi path substitutes '?' behind the caller's back; count it. + plan.missing += word.chars().filter(|&c| win_ansi_char(c).is_none()).count(); + plan.words.push(Vec::new()); + continue; + } + let Some(face) = choose_face(&faces, word, &mut coverage) else { + // No face for this word's script: the WinAnsi path writes '?' for what it + // can't encode. + plan.missing += word.chars().filter(|&c| win_ansi_char(c).is_none()).count(); + plan.words.push(Vec::new()); + continue; + }; + let mut enc: Vec<(usize, u8)> = Vec::with_capacity(word.len()); + let mut run: Option = None; + for ch in word.chars() { + if let Some(&where_) = plan.index.get(&ch) { + enc.push(where_); + run = Some(where_.0); + continue; + } + if let Ok(glyph) = craft_glyph(face, ch) + && plan.planned_glyphs() < MAX_PLAN_GLYPHS + && let Some((fi, code)) = plan.add_glyph(face, ch, glyph) + { + plan.index.insert(ch, (fi, code)); + enc.push((fi, code)); + run = Some(fi); + continue; + } + // The face has no glyph for the character (or the plan is full): substitute + // the font's '?', in the font the surrounding run is set in. + if let Some((fi, code)) = plan.question_mark(face, run.filter(|&f| plan.fonts[f].family == face.family)) { + enc.push((fi, code)); + run = Some(fi); + } + plan.missing += 1; + } + plan.words.push(enc); + } + plan + } + + /// The encoding of word `i` (parallel to the slice [`Self::for_words`] planned): a list of + /// `(font, code)` per character, or an empty slice for a word the WinAnsi fonts write. + /// Out-of-range indexes degrade to the empty slice rather than panicking — callers pass the + /// same word list they planned with. + pub fn encoding(&self, word: usize) -> &[(usize, u8)] { + self.words.get(word).map(Vec::as_slice).unwrap_or_default() + } + + /// How many characters no font could show (they appear as `?`, or are left out when the + /// word's face has no `?` glyph either). + pub fn missing(&self) -> usize { + self.missing + } + + /// The advance of one planned code, in em units (the Type3 glyphs' own widths). `0.0` for + /// anything out of range. + pub fn advance(&self, font: usize, code: u8) -> f64 { + self.fonts.get(font).and_then(|f| f.glyphs.get(usize::from(code).checked_sub(1)?)).map_or(0.0, |(_, g)| g.width) + } + + /// The sum of the advances of a word's planned codes, in em units. + pub fn advance_of(&self, encoding: &[(usize, u8)]) -> f64 { + encoding.iter().map(|&(f, c)| self.advance(f, c)).sum() + } + + /// Whether every font the encoding references has been registered (has a resource name). + /// Unregistered plans fall back to the WinAnsi path, the same output as before the + /// Unicode mapping existed. + pub fn registered(&self, encoding: &[(usize, u8)]) -> bool { + encoding.iter().all(|&(f, _)| self.fonts.get(f).is_some_and(|font| !font.name.is_empty())) + } + + /// Characters with a planned glyph so far. + fn planned_glyphs(&self) -> usize { + self.fonts.iter().map(|f| f.glyphs.len()).sum() + } + + /// Add a glyph to the face's current font (a fresh one when that font is full). + fn add_glyph(&mut self, face: &CraftFont, ch: char, glyph: GlyphOutline) -> Option<(usize, u8)> { + let fi = self.font_of_face(face.family)?; + let code = self.fonts[fi].push(ch, glyph); + Some((fi, code)) + } + + /// The index of the face's open font, or a fresh one. `None` without craft-fonts (the + /// face itself comes from there, so this cannot happen for a planned face). + fn font_of_face(&mut self, family: &'static str) -> Option { + if let Some(fi) = self.fonts.iter().rposition(|f| f.family == family && f.glyphs.len() < MAX_TYPE3_GLYPHS) { + return Some(fi); + } + if self.fonts.len() >= MAX_PLAN_GLYPHS / MAX_TYPE3_GLYPHS { + return None; + } + self.fonts.push(PlannedType3::new(family)); + Some(self.fonts.len() - 1) + } + + /// The code of the font's `?` stand-in, adding the glyph when the font lacks it. + /// `prefer` is the run's current font; `None` without craft-fonts. + fn question_mark(&mut self, face: &CraftFont, prefer: Option) -> Option<(usize, u8)> { + if let Some(fi) = prefer + && let Some(code) = self.fonts[fi].glyphs.iter().position(|(c, _)| *c == '?') + { + return Some((fi, code as u8 + 1)); + } + let fi = self.font_of_face(face.family)?; + if let Some(code) = self.fonts[fi].glyphs.iter().position(|(c, _)| *c == '?') { + return Some((fi, code as u8 + 1)); + } + let glyph = craft_glyph(face, '?').ok()?; + let code = self.fonts[fi].push('?', glyph); + Some((fi, code)) + } +} + +/// The faces that can draw document text, in preference order: the Japanese document face +/// (serif document text) first, then the rest of the build input in manifest order. +fn document_faces() -> Vec<&'static CraftFont> { + let mut out = Vec::new(); + if let Some(d) = document_japanese_font() { + out.push(d); + } + for f in crate::CRAFT_FONTS { + if !out.iter().any(|d| std::ptr::eq(*d, f)) { + out.push(f); + } + } + out +} + +/// The face for a word: the first (in preference order) whose glyphs cover every character, +/// else the one covering the most characters (ties go to the earlier face). `None` when no +/// face covers any character of the word. +fn choose_face<'f>(faces: &[&'f CraftFont], word: &str, coverage: &mut Coverage) -> Option<&'f CraftFont> { + if let Some(f) = faces.iter().enumerate().find(|(i, f)| word.chars().all(|c| coverage.has(*i, f, c))).map(|(_, f)| *f) { + return Some(f); + } + faces + .iter() + .enumerate() + .map(|(i, f)| (word.chars().filter(|&c| coverage.has(i, f, c)).count(), std::cmp::Reverse(i), *f)) + .max_by(|a, b| (a.0, a.1).cmp(&(b.0, b.1))) + .filter(|(covered, _, _)| *covered > 0) + .map(|(_, _, f)| f) +} + +/// Which faces have a glyph for which characters, remembered for one plan: a page of words +/// asks the same (face, character) pairs over and over, and each fresh answer parses the font. +#[derive(Default)] +struct Coverage { + known: std::collections::HashMap<(usize, char), bool>, + lookups: usize, +} + +impl Coverage { + /// Whether face number `i` (`face`) has `ch`; asks the font once per pair. + fn has(&mut self, i: usize, face: &CraftFont, ch: char) -> bool { + *self.known.entry((i, ch)).or_insert_with(|| { + self.lookups += 1; + face_has(face.bytes, ch) + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Face coverage is asked once per (face, character): repeating words cost no new font + /// lookups. + #[test] + fn face_coverage_is_remembered_per_face_and_character() { + let faces = document_faces(); + let Some(face) = faces.first() else { + eprintln!("skipping: built without craft-fonts (set CRAFT_FONTS_DIR to run it)"); + return; + }; + let mut coverage = Coverage::default(); + let first = (0..50).map(|_| choose_face(&faces, "日本語", &mut coverage)).last().flatten(); + assert!(first.is_some()); + assert!(coverage.lookups <= faces.len() * 3, "{} lookups for 3 characters", coverage.lookups); + assert_eq!(coverage.has(0, face, '日'), face_has(face.bytes, '日')); + } + + /// A page's vocabulary: German umlauts are WinAnsi, and a character no bundled face has + /// (here an emoji) is counted wherever it appears. + #[test] + fn win_ansi_words_get_no_encoding_and_count_only_real_losses() { + let plan = TextPlan::for_words(["Zürcher", "café", "size"]); + assert!(plan.words.iter().all(Vec::is_empty), "all WinAnsi: no Type3 fonts needed"); + assert!(plan.fonts.is_empty()); + assert_eq!(plan.missing(), 0); + let none = TextPlan::for_words(["plain text"]); + assert_eq!(none.missing(), 0); + // U+1F600 has no WinAnsi code and no glyph in any bundled face (with craft-fonts the + // JIS faces even cover the snowman): counted, shown as '?'. + let emoji = TextPlan::for_words(["\u{1f600}!"]); + assert_eq!(emoji.missing(), 1); + } + + #[test] + fn without_craft_fonts_every_non_win_ansi_character_is_reported() { + if !crate::CRAFT_FONTS.is_empty() { + eprintln!("built with craft-fonts: the planning tests with faces cover this instead"); + return; + } + let plan = TextPlan::for_words(["Привет", "日本", "abc"]); + assert!(plan.words.iter().all(Vec::is_empty)); + assert!(plan.fonts.is_empty()); + assert_eq!(plan.missing(), 8, "six Cyrillic + two CJK characters, each reported"); + } + + #[test] + fn encodings_are_aligned_and_total_the_advances() { + if crate::CRAFT_FONTS.is_empty() { + eprintln!("skipping: built without craft-fonts (set CRAFT_FONTS_DIR to run it)"); + assert!(TextPlan::for_words(["日本"]).fonts.is_empty()); + return; + } + let plan = TextPlan::for_words(["日本語", "語"]); + assert_eq!(plan.encoding(0).len(), 3); + assert_eq!(plan.encoding(1).len(), 1); + // 語 planned once keeps its code (and font) in both words. + let (f, c) = plan.encoding(1)[0]; + assert_eq!(plan.encoding(0)[2], (f, c), "the repeated character keeps its code"); + assert!(plan.advance(f, c) > 0.0); + assert_eq!(plan.advance(f, 0), 0.0, "codes start at 1"); + assert_eq!(plan.encoding(7), &[], "out of range degrades to the WinAnsi path"); + assert!(plan.advance_of(plan.encoding(0)) > plan.advance_of(plan.encoding(1))); + } + + #[test] + fn hostile_input_stays_bounded() { + // Thousands of DISTINCT characters: the covered ones fill fonts up to the caps, the + // rest are reported substitutions. + let word: String = (0..4000u32).filter_map(|i| char::from_u32(0x4e00 + i)).collect(); + let plan = TextPlan::for_words([word.as_str()]); + assert!(plan.planned_glyphs() <= MAX_PLAN_GLYPHS); + assert!(plan.fonts.iter().all(|f| f.glyphs.len() <= MAX_TYPE3_GLYPHS)); + assert!(plan.missing() > 0, "characters beyond the caps are reported, never silently dropped"); + } + + #[test] + fn substitution_and_unknown_scripts_come_out_counted() { + if crate::CRAFT_FONTS.is_empty() { + eprintln!("skipping: built without craft-fonts (set CRAFT_FONTS_DIR to run it)"); + return; + } + let plan = TextPlan::for_words(["日本\u{1f4a9}語"]); + // The emoji has no glyph in any bundled face; the kana/kanji do. + assert_eq!(plan.missing(), 1); + assert_eq!(plan.encoding(0).len(), 4, "the emoji still has an encoding: the font's ?"); + } +} diff --git a/crates/fonts/src/script.rs b/crates/fonts/src/script.rs index 70fc6ce092..94a8a93b8c 100644 --- a/crates/fonts/src/script.rs +++ b/crates/fonts/src/script.rs @@ -134,6 +134,17 @@ impl OutlinePen for Flatten { } } +/// Whether the face has a glyph for `ch` (a cheap character-map probe, no outline work). +pub fn face_has(bytes: &[u8], ch: char) -> bool { + FontRef::new(bytes).is_ok_and(|font| font.charmap().map(ch).is_some()) +} + +/// Return one glyph of `face` (a craft-fonts face), bounded so hostile replacement text cannot +/// allocate unbounded outline data. +pub fn craft_glyph(face: &crate::CraftFont, ch: char) -> Result { + glyph_in_face(face.bytes, ch) +} + /// Return one glyph of the Japanese document face ([`crate::document_japanese_font`], Shippori /// Mincho from craft-fonts), bounded so hostile replacement text cannot allocate unbounded /// outline data. [`GlyphError::NoFont`] when the build has no Japanese face. @@ -145,7 +156,11 @@ pub fn japanese_glyph(ch: char) -> Result { /// The bounded outline and advance from the explicitly selected craft-fonts face. /// Uses the same complexity and missing-glyph checks as [`japanese_glyph`]. pub fn japanese_glyph_from(face: &crate::CraftFont, ch: char) -> Result { - let Ok(font) = FontRef::new(face.bytes) else { return Err(GlyphError::Missing) }; + glyph_in_face(face.bytes, ch) +} + +fn glyph_in_face(bytes: &[u8], ch: char) -> Result { + let Ok(font) = FontRef::new(bytes) else { return Err(GlyphError::Missing) }; let loc = LocationRef::default(); let metrics = font.metrics(Size::unscaled(), loc); let scale = 1.0 / metrics.units_per_em.max(1) as f64; diff --git a/crates/forms/src/af.rs b/crates/forms/src/af.rs index 86c7971c31..f5167374d1 100644 --- a/crates/forms/src/af.rs +++ b/crates/forms/src/af.rs @@ -20,7 +20,10 @@ mod script; #[cfg(test)] use calc::{Notation, eval_notation, notation_name, notation_tokens, unique}; pub use calc::{calculate, calculation_reads, notation_js, reads_built_names, rename_in_calculation}; -pub use format::{DATE_PRESETS, DateTime, TIME_PRESETS, format_date, format_value, js_number, keystroke, make_number, parse_date, validate}; +pub use format::{ + DATE_PRESETS, DateNames, DateTime, ENGLISH_DATE_NAMES, TIME_PRESETS, date_names, format_date, format_date_in, format_value, format_value_in, + js_number, keystroke, make_number, parse_date, set_date_names, validate, +}; use script::{Arg, call}; pub use script::{NOTATION_NOT_STORABLE, calculate_js, format_js, notation_storable, parse_calculate, parse_format, parse_validate, validate_js}; diff --git a/crates/forms/src/af/format.rs b/crates/forms/src/af/format.rs index df4720bec7..37d2163cb0 100644 --- a/crates/forms/src/af/format.rs +++ b/crates/forms/src/af/format.rs @@ -89,6 +89,165 @@ const MONTHS: [&str; 12] = ["January", "February", "March", "April", "May", "Jun const DAYS: [&str; 7] = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]; +/// The month and weekday names `mmmm`, `mmm`, `dddd` and `ddd` write (weekdays from Sunday), as +/// a localized Acrobat writes them in its own language (#5303). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct DateNames { + pub months: [&'static str; 12], + pub months_short: [&'static str; 12], + pub days: [&'static str; 7], + pub days_short: [&'static str; 7], +} + +/// English, the names until the app sets others. +pub const ENGLISH_DATE_NAMES: DateNames = DateNames { + months: MONTHS, + months_short: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], + days: DAYS, + days_short: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"], +}; + +static DATE_NAMES: std::sync::RwLock = std::sync::RwLock::new(ENGLISH_DATE_NAMES); + +/// Sets the names date formats write from now on (the app's date language); typed dates are read +/// in them and in English. +pub fn set_date_names(names: DateNames) { + *DATE_NAMES.write().unwrap_or_else(std::sync::PoisonError::into_inner) = names; +} + +/// The names date formats write. +pub fn date_names() -> DateNames { + *DATE_NAMES.read().unwrap_or_else(std::sync::PoisonError::into_inner) +} + +/// `text` with the month and weekday names of `lists` (in the order months, short months, +/// weekdays, short weekdays) written as their English names, so a parser that reads English +/// reads them. The longest name wins at each place, case ignored, and only a whole name: one +/// that doesn't continue a word, nor end in a digit that a number continues. A name may hold +/// digits ("10月"), spaces ("tháng 10"), dots ("ม.ค.") or combining vowel signs, which a +/// word-by-word reader would split (#5303). Where a weekday and a month share a name (Italian +/// "mar"), the order of the format's name fields (`mmm`, `ddd`) decides. English names are +/// found too, so that one typed ("Tue" before "Mar") fills its field of the format as a +/// localized one does. +fn english_names(text: &str, fmt: &str, lists: [&[&str]; 4]) -> String { + const EN: [&[&str]; 4] = [&MONTHS, &MONTHS, &DAYS, &DAYS]; + // No date is this long: hostile text is left as it is rather than scanned name by name. + if text.len() > MAX_DATE_TEXT_BYTES { + return text.to_string(); + } + let chars: Vec = text.chars().collect(); + let typed_english: [&[&str]; 4] = [&MONTHS, &ENGLISH_DATE_NAMES.months_short, &DAYS, &ENGLISH_DATE_NAMES.days_short]; + // Each name as folded chars, whether it is a month, and its English name. + let mut names: Vec<(Vec, bool, &str)> = Vec::new(); + for (k, (list, en)) in lists.into_iter().zip(EN).chain(typed_english.into_iter().zip(EN)).enumerate() { + for (name, english) in list.iter().zip(en.iter()) { + // A short name ending in a dot ("mar.") is also read typed without it, as the same + // kind of name, so that where it equals another ("Mar", March) the format decides. + let bare = name.trim_end_matches('.'); + for name in std::iter::once(*name).chain((bare.len() < name.len()).then_some(bare)) { + let n: Vec = name.chars().map(fold).collect(); + if !n.is_empty() && n.len() <= MAX_NAME_CHARS { + names.push((n, k % 4 < 2, english)); + } + } + } + } + names.sort_by_key(|(n, ..)| std::cmp::Reverse(n.len())); + // The format's name fields in order: true for a month, false for a weekday. + let f: Vec = fmt.chars().collect(); + let mut expected = Vec::new(); + let mut j = 0; + while let Some(&c) = f.get(j) { + let run = f.get(j..).map_or(1, |r| r.iter().take_while(|x| **x == c).count()).max(1); + if run >= 3 && (c == 'm' || c == 'd') { + expected.push(c == 'm'); + } + j = j.saturating_add(run); + } + let mut slot = 0; + // A name's first letter may not continue a word; its last may not run on into a letter, nor + // (a digit) into a number. + let letter = |c: Option<&char>| c.is_some_and(|c| c.is_alphabetic()); + let mut out = String::with_capacity(text.len()); + let mut i = 0; + while let Some(&c) = chars.get(i) { + let fits = |n: &Vec| { + let end = i.saturating_add(n.len()); + let first = n.first().and_then(|e| e.chars().next()); + let last = n.last().and_then(|e| e.chars().next()); + chars.get(i..end).is_some_and(|t| t.iter().map(|c| fold(*c)).eq(n.iter().cloned())) + && !(first.is_some_and(char::is_alphabetic) && letter(i.checked_sub(1).and_then(|p| chars.get(p)))) + && !match last { + Some(l) if l.is_ascii_digit() => chars.get(end).is_some_and(char::is_ascii_digit), + Some(l) if l.is_alphabetic() => letter(chars.get(end)), + _ => false, + } + }; + let longest = names.iter().find(|(n, ..)| fits(n)).map(|(n, ..)| n.len()); + let hit = longest.and_then(|len| { + let mut same = names.iter().filter(|(n, ..)| n.len() == len && fits(n)); + let want = expected.get(slot).copied(); + let all: Vec<_> = same.by_ref().collect(); + all.iter().find(|(_, month, _)| Some(*month) == want).or_else(|| all.first()).copied() + }); + match hit { + Some((n, month, english)) => { + if expected.get(slot) == Some(month) { + slot += 1; + } + // Apart from what touches it ("10月18"), but no space added at either end. + if out.ends_with(char::is_alphanumeric) { + out.push(' '); + } + out.push_str(english); + i = i.saturating_add(n.len()); + if chars.get(i).is_some_and(|c| c.is_alphanumeric()) { + out.push(' '); + } + } + None => { + out.push(c); + i += 1; + } + } + } + out +} + +/// `c` as names are compared: lower case, with the capital I and the Turkish dotted and dotless +/// i all "i", and a combining dot above (U+0307) dropped, so that "EKİM", "SALI" and "MAYIS" are +/// Turkish "Ekim", "Salı" and "Mayıs", which lower-casing alone makes "ekim" with a dotted i, +/// "sali" and "mayis" (#5303). The Greek final sigma is a sigma, since a capital Σ, which +/// lower-cases to σ on its own, ends "ΙΑΝΟΥΆΡΙΟΣ" for "Ιανουάριος". One piece for each char, so +/// positions in the text stay aligned. +fn fold(c: char) -> String { + match c { + 'I' | 'ı' | 'İ' => "i".to_string(), + 'ς' => "σ".to_string(), + _ => c.to_lowercase().filter(|&l| l != '\u{307}').collect(), + } +} + +/// `s` [`fold`]ed char by char. +fn folded(s: &str) -> String { + s.chars().map(fold).collect() +} + +/// Typed dates longer than this are not searched for names. +const MAX_DATE_TEXT_BYTES: usize = 1024; + +/// Names longer than this are not looked for (settings are trusted, but a cap keeps the scan cheap). +const MAX_NAME_CHARS: usize = 32; + +/// The month (1 to 12) a typed word names: a start of at least three letters of a month's name, +/// or its whole short name, in `names` or in English. +fn month_named(word: &str, names: &DateNames) -> Option { + let w = folded(word); + let starts = |list: &[&str; 12]| list.iter().position(|m| w.chars().count() >= 3 && folded(m).starts_with(&w)); + let whole = |list: &[&str; 12]| list.iter().position(|m| folded(m).trim_end_matches('.') == w); + starts(&names.months).or_else(|| whole(&names.months_short)).or_else(|| starts(&MONTHS)).map(|i| i as u32 + 1) +} + /// A date and time read from text. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct DateTime { @@ -202,7 +361,20 @@ fn order(fmt: &str) -> Vec { /// Parse typed text against a date/time format (AFDate_KeystrokeEx's leniency: any /// separators, month names, two-digit years). `None` when it isn't a valid date. pub fn parse_date(text: &str, fmt: &str) -> Option { - let t = text.trim(); + let names = date_names(); + let lists: [&[&str]; 4] = [&names.months, &names.months_short, &names.days, &names.days_short]; + // Weekdays are shown, not typed (see `order`): where the format has one but none was typed, a + // name the language shares between a weekday and a month (Italian "mar") is the month, as + // the names are read again with no weekday expected (#5303). + read_date(&english_names(text, fmt, lists), fmt, &names).or_else(|| { + let no_weekday = fmt.replace("dddd", " ").replace("ddd", " "); + (no_weekday != fmt).then(|| read_date(&english_names(text, &no_weekday, lists), fmt, &names)).flatten() + }) +} + +/// [`parse_date`] of `english`, typed text whose month and weekday names are English. +fn read_date(english: &str, fmt: &str, names: &DateNames) -> Option { + let t = english.trim(); if t.is_empty() { return None; } @@ -223,10 +395,8 @@ pub fn parse_date(text: &str, fmt: &str) -> Option { } if cur.starts_with(|c: char| c.is_ascii_digit()) { nums.push_back(std::mem::take(cur)); - } else if cur.len() >= 3 - && let Some(i) = MONTHS.iter().position(|m| m.to_lowercase().starts_with(&cur.to_lowercase())) - { - *month = Some(i as u32 + 1); + } else if let Some(m) = month_named(cur, names) { + *month = Some(m); } cur.clear(); }; @@ -337,6 +507,11 @@ pub fn parse_date(text: &str, fmt: &str) -> Option { /// Format a date/time with Acrobat's date format letters. pub fn format_date(dt: DateTime, fmt: &str) -> String { + format_date_in(dt, fmt, &date_names()) +} + +/// [`format_date`] with month and weekday names from `names`. +pub fn format_date_in(dt: DateTime, fmt: &str, names: &DateNames) -> String { let chars: Vec = fmt.chars().collect(); let mut out = String::new(); let mut i = 0; @@ -354,9 +529,9 @@ pub fn format_date(dt: DateTime, fmt: &str) -> String { ('y', _) => { let _ = write!(out, "{:02}", dt.y.rem_euclid(100)); } - ('m', 3..) => match MONTHS.get((dt.m as usize).wrapping_sub(1)) { - Some(name) if n >= 4 => out.push_str(name), - Some(name) => out.push_str(name.get(..3).unwrap_or(name)), + ('m', 3..) => match (dt.m as usize).checked_sub(1).and_then(|i| names.months.get(i).zip(names.months_short.get(i))) { + Some((name, _)) if n >= 4 => out.push_str(name), + Some((_, short)) => out.push_str(short), None => { let _ = write!(out, "{}", dt.m); } @@ -368,8 +543,8 @@ pub fn format_date(dt: DateTime, fmt: &str) -> String { let _ = write!(out, "{}", dt.m); } ('d', 3..) => { - let name = DAYS.get(weekday(dt.y, dt.m, dt.d)).copied().unwrap_or_default(); - out.push_str(if n >= 4 { name } else { name.get(..3).unwrap_or(name) }); + let list = if n >= 4 { &names.days } else { &names.days_short }; + out.push_str(list.get(weekday(dt.y, dt.m, dt.d)).copied().unwrap_or_default()); } ('d', 2) => { let _ = write!(out, "{:02}", dt.d); @@ -451,6 +626,11 @@ fn apply_mask(mask: &str, text: &str) -> Option { /// The text shown for a value (the Format event). pub fn format_value(f: &Format, value: &str) -> String { + format_value_in(f, value, &date_names()) +} + +/// [`format_value`] with month and weekday names from `names`. +pub fn format_value_in(f: &Format, value: &str, names: &DateNames) -> String { if value.is_empty() { return String::new(); } @@ -479,7 +659,7 @@ pub fn format_value(f: &Format, value: &str) -> String { ), None => value.to_string(), }, - Format::Date(fmt) | Format::Time(fmt) => parse_date(value, fmt).map_or_else(|| value.to_string(), |dt| format_date(dt, fmt)), + Format::Date(fmt) | Format::Time(fmt) => parse_date(value, fmt).map_or_else(|| value.to_string(), |dt| format_date_in(dt, fmt, names)), Format::Special(n) => apply_mask(SPECIAL_MASKS[(*n).min(3) as usize], value).unwrap_or_else(|| value.to_string()), Format::Mask(m) => apply_mask(m, value).unwrap_or_else(|| value.to_string()), } diff --git a/crates/forms/src/appearance.rs b/crates/forms/src/appearance.rs index c9ff86d17a..8403b729d9 100644 --- a/crates/forms/src/appearance.rs +++ b/crates/forms/src/appearance.rs @@ -739,8 +739,18 @@ pub fn value_overflow(doc: &Document, f: &Field, w: &Widget) -> Option field_appearance_fit(doc, f, w, &f.value, true).2 } +/// Whether `text` draws in widget `wd` of `f` with no `?`: in the field's `/DR` font when that +/// holds it, as [`field_appearance_fit`] picks, or else in the Helvetica (WinAnsi) stand-in. +fn draws(doc: &Document, f: &Field, wd: &Dict, text: &str) -> bool { + let da = parse_da(wd.get(b"DA").and_then(|o| doc.resolve(o).as_string().map(|s| s.to_text())).as_deref().unwrap_or(&f.da)); + let enc = dr_font(doc, &da.font).map(|(_, enc)| enc).filter(|enc| enc.can_encode(text)).unwrap_or(FontText::WinAnsi); + enc.first_unencodable(text).is_none() +} + /// [`field_appearance_drawn`], and whether the text drawn is cut off by the box. fn field_appearance_fit(doc: &Document, f: &Field, w: &Widget, values: &[String], format: bool) -> (Stream, Option, Option) { + let wobj = doc.get(w.obj); + let wd = wobj.as_dict().cloned().unwrap_or_default(); // The Format event: what is shown, not what is stored. let formatted: Vec; let values = if format @@ -748,13 +758,16 @@ fn field_appearance_fit(doc: &Document, f: &Field, w: &Widget, values: &[String] && values.len() == 1 && f.actions.format != crate::af::Format::None { - formatted = vec![crate::af::format_value(&f.actions.format, &values[0])]; + let shown = crate::af::format_value(&f.actions.format, &values[0]); + // Month and weekday names in the date language that no font here can draw ("окт." in + // Helvetica) are drawn in English rather than as `?` (#5303). + let english = || crate::af::format_value_in(&f.actions.format, &values[0], &crate::af::ENGLISH_DATE_NAMES); + let dated = matches!(f.actions.format, crate::af::Format::Date(_) | crate::af::Format::Time(_)); + formatted = vec![if !dated || draws(doc, f, &wd, &shown) { shown } else { english() }]; &formatted[..] } else { values }; - let wobj = doc.get(w.obj); - let wd = wobj.as_dict().cloned().unwrap_or_default(); let (page_w, page_h) = ((w.rect[2] - w.rect[0]).max(1.0), (w.rect[3] - w.rect[1]).max(1.0)); let place = placement(mk_rotation(doc, &wd), page_w, page_h); let (width, height) = (place.layout_w, place.layout_h); diff --git a/crates/forms/src/scripting.rs b/crates/forms/src/scripting.rs index 7dd7bfde6c..31e6812e6b 100644 --- a/crates/forms/src/scripting.rs +++ b/crates/forms/src/scripting.rs @@ -60,6 +60,21 @@ pub struct ScriptResult { pub trait Scripts { /// Run `script` for `event` on `target`, whose value is `value`; `fields` is the whole form. fn run(&mut self, event: FieldEvent, script: &str, target: &Field, value: &str, fields: &[Field]) -> ScriptResult; + + /// [`Self::run`] again for an appearance, with dates written in English names (`util.printd`) + /// because no font of the field can draw the date language's (#5303); what it logs was + /// already logged by the first run. `None` when it can't: no English dates here, or the + /// script failed. What it returns is what the script made, even when that is the value. + fn rerun_with_english_dates( + &mut self, + _event: FieldEvent, + _script: &str, + _target: &Field, + _value: &str, + _fields: &[Field], + ) -> Option { + None + } } /// No script engine (or JavaScript turned off): scripts change nothing. @@ -98,6 +113,13 @@ pub(crate) fn formatted(doc: &Document, f: &Field, value: &str, scripts: &mut dy Some(r.value) } +/// [`formatted`] with dates in English names, for widgets whose fonts can't draw the date +/// language's; `None` when the field has no Format script or the English run didn't happen. +pub(crate) fn formatted_in_english(doc: &Document, f: &Field, value: &str, scripts: &mut dyn Scripts) -> Option { + let js = f.actions.scripts.format.as_ref()?; + scripts.rerun_with_english_dates(FieldEvent::Format, js, f, value, &fields(doc)).map(|r| r.value) +} + /// Apply script changes to other fields (values written without re-running their scripts; /// read-only, required and visibility as flags). `except` is the event's own field, whose value /// the event sets. diff --git a/crates/forms/src/values.rs b/crates/forms/src/values.rs index cf191c2240..9d670e62db 100644 --- a/crates/forms/src/values.rs +++ b/crates/forms/src/values.rs @@ -426,9 +426,24 @@ fn redraw(doc: &mut Document, f: &Field, values: &[String], scripts: &mut dyn Sc }; let in_place = f.kind == FieldKind::Text && f.has(flags::PASSWORD); let mut undrawn = false; + // The Format script again with English month and weekday names, once, for widgets whose + // fonts can't draw the date language's (#5303). + let mut english: Option> = None; for w in &f.widgets { let (stream, missing) = match &shown { - Some(s) => appearance::field_appearance_drawn(doc, f, w, std::slice::from_ref(s), false), + Some(s) => { + let drawn = appearance::field_appearance_drawn(doc, f, w, std::slice::from_ref(s), false); + // Taken when the English run happened and draws whole, even where it is the + // stored value ("18-Oct-26" printed again from itself). + let again = match (&drawn.1, values) { + (Some(_), [one]) => english.get_or_insert_with(|| scripting::formatted_in_english(doc, f, one, scripts)).as_ref(), + _ => None, + }; + match again.map(|e| appearance::field_appearance_drawn(doc, f, w, std::slice::from_ref(e), false)) { + Some(english) if english.1.is_none() => english, + _ => drawn, + } + } None => appearance::field_appearance_drawn(doc, f, w, values, true), }; undrawn |= missing.is_some(); diff --git a/crates/js/fuzz/Cargo.toml b/crates/js/fuzz/Cargo.toml new file mode 100644 index 0000000000..373028192e --- /dev/null +++ b/crates/js/fuzz/Cargo.toml @@ -0,0 +1,24 @@ +[package] +name = "pdfcraft-js-fuzz" +version = "0.0.0" +publish = false +edition = "2024" +license = "MIT OR Apache-2.0" + +[package.metadata] +cargo-fuzz = true + +# Detached from the PdfCraft workspace: run with `cargo +nightly fuzz run run_script` +# from crates/js/. +[workspace] + +[dependencies] +libfuzzer-sys = "0.4" +pdfcraft-js = { path = ".." } + +[[bin]] +name = "run_script" +path = "fuzz_targets/run_script.rs" +test = false +doc = false +bench = false diff --git a/crates/js/fuzz/fuzz_targets/run_script.rs b/crates/js/fuzz/fuzz_targets/run_script.rs new file mode 100644 index 0000000000..57ccb9ea66 --- /dev/null +++ b/crates/js/fuzz/fuzz_targets/run_script.rs @@ -0,0 +1,26 @@ +//! Feeds arbitrary bytes, read as a script, to the JavaScript run entry with fixed event and document values. +//! +//! The run's result is discarded: the target only checks that no input panics or hangs past the limits. +#![no_main] + +use libfuzzer_sys::fuzz_target; +use pdfcraft_js::{DocInfo, Event, Limits, run}; + +/// The largest script the target runs (64 KiB); larger inputs are skipped. +const MAX_INPUT: usize = 64 << 10; + +fuzz_target!(|data: &[u8]| { + if data.len() > MAX_INPUT { + return; + } + let script = String::from_utf8_lossy(data).into_owned(); + let event = Event { + name: "Keystroke".into(), + kind: "Field".into(), + target: Some("field1".into()), + value: "value".into(), + change: String::new(), + will_commit: true, + }; + let _outcome = run(&script, &event, &DocInfo::default(), &[], &[], Limits::default()); +}); diff --git a/crates/js/src/format.rs b/crates/js/src/format.rs index 7f207b1916..26e2fad989 100644 --- a/crates/js/src/format.rs +++ b/crates/js/src/format.rs @@ -134,6 +134,177 @@ const MONTHS: [&str; 12] = ["January", "February", "March", "April", "May", "Jun const DAYS: [&str; 7] = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]; +/// Month and weekday names (weekdays from Sunday): full, then short. +type Names = ([&'static str; 12], [&'static str; 12], [&'static str; 7], [&'static str; 7]); + +const ENGLISH: Names = ( + MONTHS, + ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], + DAYS, + ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"], +); + +static NAMES: std::sync::RwLock = std::sync::RwLock::new(ENGLISH); + +/// Sets the month and weekday names `util.printd` writes for `mmmm`, `mmm`, `dddd` and `ddd` +/// (weekdays from Sunday), as a localized Acrobat writes its own language's (#5303). +/// `util.scand` reads them as well as English. +pub fn set_date_names(months: [&'static str; 12], months_short: [&'static str; 12], days: [&'static str; 7], days_short: [&'static str; 7]) { + *NAMES.write().unwrap_or_else(std::sync::PoisonError::into_inner) = (months, months_short, days, days_short); +} + +/// `text` with the month and weekday names of `lists` (in the order months, short months, +/// weekdays, short weekdays) written as their English names, so a parser that reads English +/// reads them. The longest name wins at each place, case ignored, and only a whole name: one +/// that doesn't continue a word, nor end in a digit that a number continues. A name may hold +/// digits ("10月"), spaces ("tháng 10"), dots ("ม.ค.") or combining vowel signs, which a +/// word-by-word reader would split (#5303). Where a weekday and a month share a name (Italian +/// "mar"), the order of the format's name fields (`mmm`, `ddd`) decides. English names are +/// found too, so that one typed ("Tue" before "Mar") fills its field of the format as a +/// localized one does. +fn english_names(text: &str, fmt: &str, lists: [&[&str]; 4]) -> String { + const EN: [&[&str]; 4] = [&MONTHS, &MONTHS, &DAYS, &DAYS]; + // No date is this long: hostile text is left as it is rather than scanned name by name. + if text.len() > MAX_DATE_TEXT_BYTES { + return text.to_string(); + } + let chars: Vec = text.chars().collect(); + let typed_english: [&[&str]; 4] = [&ENGLISH.0, &ENGLISH.1, &ENGLISH.2, &ENGLISH.3]; + // Each name as folded chars, whether it is a month, and its English name. + let mut names: Vec<(Vec, bool, &str)> = Vec::new(); + for (k, (list, en)) in lists.into_iter().zip(EN).chain(typed_english.into_iter().zip(EN)).enumerate() { + for (name, english) in list.iter().zip(en.iter()) { + // A short name ending in a dot ("mar.") is also read typed without it, as the same + // kind of name, so that where it equals another ("Mar", March) the format decides. + let bare = name.trim_end_matches('.'); + for name in std::iter::once(*name).chain((bare.len() < name.len()).then_some(bare)) { + let n: Vec = name.chars().map(fold).collect(); + if !n.is_empty() && n.len() <= MAX_NAME_CHARS { + names.push((n, k % 4 < 2, english)); + } + } + } + } + names.sort_by_key(|(n, ..)| std::cmp::Reverse(n.len())); + // The format's name fields in order: true for a month, false for a weekday. + let f: Vec = fmt.chars().collect(); + let mut expected = Vec::new(); + let mut j = 0; + while let Some(&c) = f.get(j) { + let run = f.get(j..).map_or(1, |r| r.iter().take_while(|x| **x == c).count()).max(1); + if run >= 3 && (c == 'm' || c == 'd') { + expected.push(c == 'm'); + } + j = j.saturating_add(run); + } + let mut slot = 0; + // A name's first letter may not continue a word; its last may not run on into a letter, nor + // (a digit) into a number. + let letter = |c: Option<&char>| c.is_some_and(|c| c.is_alphabetic()); + let mut out = String::with_capacity(text.len()); + let mut i = 0; + while let Some(&c) = chars.get(i) { + let fits = |n: &Vec| { + let end = i.saturating_add(n.len()); + let first = n.first().and_then(|e| e.chars().next()); + let last = n.last().and_then(|e| e.chars().next()); + chars.get(i..end).is_some_and(|t| t.iter().map(|c| fold(*c)).eq(n.iter().cloned())) + && !(first.is_some_and(char::is_alphabetic) && letter(i.checked_sub(1).and_then(|p| chars.get(p)))) + && !match last { + Some(l) if l.is_ascii_digit() => chars.get(end).is_some_and(char::is_ascii_digit), + Some(l) if l.is_alphabetic() => letter(chars.get(end)), + _ => false, + } + }; + let longest = names.iter().find(|(n, ..)| fits(n)).map(|(n, ..)| n.len()); + let hit = longest.and_then(|len| { + let mut same = names.iter().filter(|(n, ..)| n.len() == len && fits(n)); + let want = expected.get(slot).copied(); + let all: Vec<_> = same.by_ref().collect(); + all.iter().find(|(_, month, _)| Some(*month) == want).or_else(|| all.first()).copied() + }); + match hit { + Some((n, month, english)) => { + if expected.get(slot) == Some(month) { + slot += 1; + } + // Apart from what touches it ("10月18"), but no space added at either end. + if out.ends_with(char::is_alphanumeric) { + out.push(' '); + } + out.push_str(english); + i = i.saturating_add(n.len()); + if chars.get(i).is_some_and(|c| c.is_alphanumeric()) { + out.push(' '); + } + } + None => { + out.push(c); + i += 1; + } + } + } + out +} + +/// `c` as names are compared: lower case, with the capital I and the Turkish dotted and dotless +/// i all "i", and a combining dot above (U+0307) dropped, so that "EKİM", "SALI" and "MAYIS" are +/// Turkish "Ekim", "Salı" and "Mayıs", which lower-casing alone makes "ekim" with a dotted i, +/// "sali" and "mayis" (#5303). The Greek final sigma is a sigma, since a capital Σ, which +/// lower-cases to σ on its own, ends "ΙΑΝΟΥΆΡΙΟΣ" for "Ιανουάριος". One piece for each char, so +/// positions in the text stay aligned. +fn fold(c: char) -> String { + match c { + 'I' | 'ı' | 'İ' => "i".to_string(), + 'ς' => "σ".to_string(), + _ => c.to_lowercase().filter(|&l| l != '\u{307}').collect(), + } +} + +/// `s` [`fold`]ed char by char. +fn folded(s: &str) -> String { + s.chars().map(fold).collect() +} + +/// Typed dates longer than this are not searched for names. +const MAX_DATE_TEXT_BYTES: usize = 1024; + +/// Names longer than this are not looked for (settings are trusted, but a cap keeps the scan cheap). +const MAX_NAME_CHARS: usize = 32; + +fn names() -> Names { + *NAMES.read().unwrap_or_else(std::sync::PoisonError::into_inner) +} + +std::thread_local! { + /// Whether `util.printd` on this thread writes English names, whatever the date language. + static PRINTD_ENGLISH: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +/// Runs `run` with `util.printd` writing English month and weekday names when `english` (scripts +/// it starts carry this to their own thread): for an appearance whose fonts can't draw the date +/// language's names, which would come out as `?` (#5303). `util.scand` still reads both. +pub fn with_english_printd(english: bool, run: impl FnOnce() -> R) -> R { + struct Restore(bool); + impl Drop for Restore { + fn drop(&mut self) { + PRINTD_ENGLISH.with(|e| e.set(self.0)); + } + } + let _restore = Restore(PRINTD_ENGLISH.with(|e| e.replace(english))); + run() +} + +/// Whether [`with_english_printd`] is on for this thread. +pub(crate) fn printd_english() -> bool { + PRINTD_ENGLISH.with(std::cell::Cell::get) +} + +/// The names `util.printd` writes. +fn printd_names() -> Names { + if printd_english() { ENGLISH } else { names() } +} + /// `util.printd(cFormat, oDate)`: yyyy yy mmmm mmm mm m dddd ddd dd d HH H hh h MM M ss s tt, /// and the numeric formats 0 (D:yyyymmddHHMMss), 1 (yyyy.mm.dd HH:MM:ss) and 2 (m/d/yy h:MM:ss tt). pub(crate) fn printd(_: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult { @@ -161,6 +332,7 @@ pub(crate) fn printd(_: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResu let (y, mo, day, wd, h, mi, sec) = (part("getFullYear")?, part("getMonth")?, part("getDate")?, part("getDay")?, part("getHours")?, part("getMinutes")?, part("getSeconds")?); let mut out = String::new(); + let (months, months_short, days, days_short) = printd_names(); let b = fmt.as_bytes(); let mut i = 0; while i < b.len() { @@ -186,13 +358,13 @@ pub(crate) fn printd(_: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResu } } b'm' => match run { - r if r >= 4 => out.push_str(MONTHS[mo as usize % 12]), - 3 => out.push_str(&MONTHS[mo as usize % 12][..3]), + r if r >= 4 => out.push_str(months.get(mo.rem_euclid(12) as usize).copied().unwrap_or_default()), + 3 => out.push_str(months_short.get(mo.rem_euclid(12) as usize).copied().unwrap_or_default()), n => push_num(&mut out, mo + 1, n), }, b'd' => match run { - r if r >= 4 => out.push_str(DAYS[wd as usize % 7]), - 3 => out.push_str(&DAYS[wd as usize % 7][..3]), + r if r >= 4 => out.push_str(days.get(wd.rem_euclid(7) as usize).copied().unwrap_or_default()), + 3 => out.push_str(days_short.get(wd.rem_euclid(7) as usize).copied().unwrap_or_default()), n => push_num(&mut out, day, n), }, b'H' => push_num(&mut out, h, run), @@ -435,11 +607,13 @@ fn scan_date(fmt: &str, text: &str, this_year: i32) -> Option { p += 1; } (ScanPart::Field { unit: DateUnit::MonthName, .. }, ScanToken::Letters(l)) => { - v.mo = Some(named(&MONTHS, l)?.saturating_add(1)); + let (months, months_short, ..) = names(); + v.mo = Some(named(&months, l).or_else(|| named(&months_short, l)).or_else(|| named(&MONTHS, l))?.saturating_add(1)); p += 1; } (ScanPart::Field { unit: DateUnit::Weekday, .. }, ScanToken::Letters(l)) => { - named(&DAYS, l)?; + let (.., days, days_short) = names(); + named(&days, l).or_else(|| named(&days_short, l)).or_else(|| named(&DAYS, l))?; p += 1; } (ScanPart::Field { unit: DateUnit::AmPm, .. }, ScanToken::Letters(l)) => { @@ -509,10 +683,11 @@ fn scan_date(fmt: &str, text: &str, this_year: i32) -> Option { /// The index of the name `word` is, in full or as its first three letters, in any case. fn named(names: &[&str], word: &str) -> Option { - let word = word.to_lowercase(); + let word = folded(word); let i = names.iter().position(|n| { - let n = n.to_lowercase(); - word == n || n.get(..3) == Some(word.as_str()) + let n = folded(n); + // A short name may end in a dot ("Okt."); three letters may be cut from any name. + word == n || word == n.trim_end_matches('.') || n.chars().take(3).collect::() == word })?; u32::try_from(i).ok() } @@ -524,6 +699,8 @@ pub(crate) fn scand(_: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResul return Ok(JsValue::null()); }; let fmt = text(&arg(args, 0), ctx)?; + let (months, months_short, days, days_short) = names(); + let typed = english_names(&typed, &fmt, [&months, &months_short, &days, &days_short]); let date = JsDate::new(ctx); let this_year = date.get_full_year(ctx)?.to_number(ctx)?; let this_year = if this_year.is_finite() { this_year as i32 } else { 2000 }; diff --git a/crates/js/src/lib.rs b/crates/js/src/lib.rs index 93f57e7528..0bf4032efd 100644 --- a/crates/js/src/lib.rs +++ b/crates/js/src/lib.rs @@ -44,6 +44,7 @@ mod run; #[cfg(test)] pub(crate) use format::PRINTD_SCANNED; use format::{printd, printf, printx, scand}; +pub use format::{set_date_names, with_english_printd}; pub(crate) use globals::menu_item; use globals::platform; use host::{arg, as_number, error, function, s, text}; diff --git a/crates/js/src/run.rs b/crates/js/src/run.rs index 07c0e984bb..ab7e32ed53 100644 --- a/crates/js/src/run.rs +++ b/crates/js/src/run.rs @@ -129,11 +129,13 @@ pub fn run_shared(script: &str, event: &Event, doc: &DocInfo, fields: Arc thread.join().unwrap_or_else(|_| failed("the script stopped with an internal error".into())), Err(e) => failed(format!("the script engine could not start: {e}")), diff --git a/crates/measure/src/snap.rs b/crates/measure/src/snap.rs index 930ffe3053..b26c389e96 100644 --- a/crates/measure/src/snap.rs +++ b/crates/measure/src/snap.rs @@ -189,6 +189,12 @@ pub fn constrain(last: Point, point: Point) -> Point { let angle = (v[1].atan2(v[0]) / std::f64::consts::FRAC_PI_4).round() * std::f64::consts::FRAC_PI_4; [last[0] + length * angle.cos(), last[1] + length * angle.sin()] } +/// Hold a proposed vertex level or plumb with the last vertex, whichever is nearer (a CAD +/// drawing's ortho mode): the vertex slides onto that axis rather than turning onto it. +pub fn ortho(last: Point, point: Point) -> Point { + let v = sub(point, last); + if v[0].abs() >= v[1].abs() { [point[0], last[1]] } else { [last[0], point[1]] } +} struct Walker<'a> { doc: &'a Document, geometry: Geometry, diff --git a/crates/measure/src/tests.rs b/crates/measure/src/tests.rs index 5b277e5546..88906910c7 100644 --- a/crates/measure/src/tests.rs +++ b/crates/measure/src/tests.rs @@ -449,6 +449,16 @@ fn listing_skips_repeated_refs_and_caps_what_it_keeps() { assert!(!listing.measurements.is_empty()); } #[test] +fn ortho_holds_a_vertex_level_or_plumb_with_the_last() { + let last = [10.0, 20.0]; + assert_eq!(snap::ortho(last, [50.0, 27.0]), [50.0, 20.0], "mostly across: level"); + assert_eq!(snap::ortho(last, [-30.0, 13.0]), [-30.0, 20.0], "to the left too"); + assert_eq!(snap::ortho(last, [14.0, 80.0]), [10.0, 80.0], "mostly up: plumb"); + assert_eq!(snap::ortho(last, [8.0, -40.0]), [10.0, -40.0], "and down"); + assert_eq!(snap::ortho(last, [30.0, 40.0]), [30.0, 20.0], "a tie stays level"); + assert_eq!(snap::ortho(last, last), last); +} +#[test] fn a_stream_over_the_byte_budget_uses_it_up_once() { // 50 references to one Flate stream that inflates past the 16 MiB budget decode once. let big = pdfcraft_cos::Stream::flate(Dict::new(), &vec![b' '; 17 << 20]); diff --git a/crates/ocr/Cargo.toml b/crates/ocr/Cargo.toml index 750e78b96d..1b04dbb522 100644 --- a/crates/ocr/Cargo.toml +++ b/crates/ocr/Cargo.toml @@ -16,5 +16,9 @@ ocrs = { version = "0.13.1", default-features = false, features = ["rten"] } rten = { version = "0.26.0", default-features = false, features = ["onnx_format", "rten_format"] } thiserror.workspace = true +[target.'cfg(not(target_arch = "wasm32"))'.dependencies] +# The page image is handed to the external tesseract process as a PNG. +png = "0.18" + [dev-dependencies] tempfile = "3.27" diff --git a/crates/ocr/README.md b/crates/ocr/README.md new file mode 100644 index 0000000000..cd33b186cf --- /dev/null +++ b/crates/ocr/README.md @@ -0,0 +1,104 @@ +# pdfcraft-ocr + +Layer L4 (may use `fonts` for the text layers' metrics): Scan & OCR — recognising the words in +a page raster and turning them back into page content (execution plan M10). + +```rust +// The caller renders a page to pixels and hands them over: +let image = OcrImage::new(w, h, rgba)?; // validated by construction +let lines = recognizer.recognize(&image, &options)?; // Vec: words in reading order +let placed: Vec = …; // PlacedWord::place maps boxes to user space +// The editable output draws real glyphs: plan the words, register the display faces into the +// plan (`pdfcraft_edit::add_type3_fonts`), then generate the layer. An unregistered plan falls +// back to WinAnsi, and characters no registered face has become '?'. +let plan = TextPlan::for_words(placed.iter().map(|w| w.text.as_str())); +add_type3_fonts(&mut doc, page, &mut plan)?; // names the plan's fonts on the page +let layer = visible_text_layer(&placed, &plan); // visible text: the editable output +// The searchable layer needs no display fonts: the engine's own layer (engine::ocr::layer) +// keeps every Unicode character with empty Type3 programs and a ToUnicode map beyond WinAnsi. +``` + +- **Engines behind one trait.** A [`Recognizer`] reports its `id`, whether it is `available`, + the languages it reads, and reads `Vec` from an image. Two exist: the pure-Rust + `OcrsRecognizer` (the `ocrs` crate, MIT/Apache-2.0, with its pre-trained models, + CC-BY-SA-4.0, fetched by `cargo xtask models`; found via `$PDFCRAFT_MODELS` or `models/` + beside the executable — see ATTRIBUTION.toml), and — off the web build — + `tesseract::TesseractCli`, which drives an installed `tesseract` binary as an external + process: never linked, bundled or downloaded. Implementations are shared across threads + (`Send + Sync`); nothing spawns on wasm32. +- **The tesseract process is fenced in.** The program comes from a user-configured location or + the PATH, never from document data (the engine validates a configured path as an absolute + path to an existing executable file before it is used). The language code is allow-listed + (`tesseract::language_code`, 12 codes) before anything reaches a process; the page image + goes to a private temp file (a fresh 0700 directory holding a 0600 file on Unix) that is + deleted afterwards; the run has a 120 s timeout, a 64 MiB output cap and a 50 000-word + reading cap (an incomplete reading is rejected rather than applied); every failure comes back through `OcrError` with its cause named. A configured + location that is invalid fails closed (it is never replaced by the PATH search). Availability + is probed with `--list-langs` (its list is read from stdout, or from stderr where older + versions print it); a failed probe is remembered for 30 s, so an install that appears later + is found without a restart. Known limit: at the timeout or the output cap only the direct + child is killed; a wrapper script's own children may outlive it. +- **Confidence drives review.** One classifier (`band_for`) puts a word in the High + (≥ 90), Medium (70–89) or Low (< 70) band — the review overlay's colours, the legend and the + counts; the batch flag rule (`low_confidence`, default threshold 60) is deliberately a + separate threshold. The `ocrs` models report no confidence (its words carry `None`); + a reading whose confidence is unknown is treated as unknown, never as good. +- **Two engines can be merged (ROVER).** Strategies: `PrimaryOnly` (the default), and two + ensembles — `ConfidenceWeighted` (the secondary engine joins when the primary's mean + confidence is under 70 or unknown; an empty primary keeps the fast path) and `RoverVote` + (both engines always run). The merge lets every primary word adopt the best-overlapping + unused secondary word at IoU ≥ 0.5; the higher confidence wins text, box and confidence (a + tie keeps the primary; against a primary word of unknown confidence — ocrs — the secondary + wins only at 70 or more, `UNKNOWN_CONFIDENCE_BAR`), the survivor is named `"ROVER"`, and + unclaimed secondary words are + appended under their engine's name. A merge is capped at 100 M word-pair comparisons (over + it, the primary reading stands alone), and a failing partner degrades to the primary with a + recorded note — a page is never skipped because a partner could not read it. +- **Preprocessing between the raster and recognition**, a pure function in fixed order: DPI + normalization to 300 (only when one of the steps below is on, since they are calibrated for + it; with all of them off the raster is read exactly as rendered, and a scan at or above 300 + is left alone), then the opt-in steps — + orientation (90°/180°/270° from projection-profile banding), deskew (± 5°, shear-scored, + below 0.1° is a no-op), denoise (3×3 median) and binarization (Sauvola, window 8, k 0.34). + Every geometric step composes one exact affine `InverseTransform`, and callers map every + word box back to the original raster before placing it. The heuristics are conservative and + panic-free: too small to judge, blank, or no clear winner is a no-op, never a guess. +- **Searchable output preserves Unicode without display fonts.** The engine uses empty + Type3 character programs and `/ToUnicode` maps for non-WinAnsi words, leaving the scan + unchanged. WinAnsi words use `/PCHelv`; the `/OCR` layer is fitted to each word's box. +- **Editable output uses display glyphs.** `visible_text_layer` writes visible text whose + size comes from the box height and whose horizontal scaling uses real font advances. + Beyond WinAnsi, attributed craft-fonts faces supply outline Type3 glyphs with `/ToUnicode`. + Uncovered characters become `?` and are reported in editable output notes; searchable + output retains them. The engine refuses nonfinite geometry or oversized input before + planning fonts: 4 MiB of text and 65,536 words, across all pages for editable export. + Empty geometry is skipped; rotated words carry `across`/`up` vectors and retain direction. +- **Hostile input is rejected, not panicked at.** `OcrImage` holds private, validated state: + non-zero sides, a 10 000-pixel side cap, a 64-megapixel area cap (checked arithmetic — the + counts come from documents, so they are untrusted), and an exact buffer length. + +## Where it is wired + +The engine's `ocr` module renders pages into `OcrImage`s, runs jobs (`OcrJob::run`) and applies +the words: searchable-image mode draws the invisible layer over the page's own image and leaves +that image untouched; editable mode writes a NEW `_ocr.pdf` of visible text (the scan +image is not carried over, the source is never overwritten). Skip probes keep pages — and +whole files — that already contain text out of the work unless Force OCR overrides them. A +searchable result applies as one undoable step; the Editable text output opens the OCR Verify +screen first, and Scan & OCR ▸ Correct recognized text reviews any recognition there before it +is applied (confidence-coloured boxes, corrections, a per-language user dictionary — a +plain-text file in the preferences folder, so words added from a document persist on disk +outside it until removed — Re-OCR of a region or a page, Accept/Reject), a +multiple-file run writes searchable copies as it goes, and the automation tools `ocr_recognize`, +`ocr_words`, `ocr_status` and `ocr_recognize_files` expose recognition headlessly. +`ocr_words` with `retain_review` returns a bounded session-local handle; `ocr_review_apply` +applies text corrections at the stored original boxes through its stale-document guard, +or discards the result. Empty corrections remove words. Searchable acceptance is one undo +step; editable acceptance writes a separate file. `ocr_dictionary` reads or atomically +updates the UI's per-language dictionary format through an explicitly root-confined path. + +Not yet: languages beyond the tested set (the `ocrs` models read only unaccented Latin; the +Tesseract side is bounded by its allow-list and whatever its installed language packs cover), +OCR in the browser (the tesseract module is compiled out for wasm32), the deep scan-cleanup +options (descreen, background removal, edge-shadow removal), and editable glyph coverage +beyond the available attributed faces. diff --git a/crates/ocr/src/confidence.rs b/crates/ocr/src/confidence.rs new file mode 100644 index 0000000000..1c0de605f5 --- /dev/null +++ b/crates/ocr/src/confidence.rs @@ -0,0 +1,106 @@ +//! Confidence: one classifier ([`band_for`]) drives the review overlay, the legend, the counts +//! and the uncertain-word navigation; the batch rule ([`low_confidence`]) is a separate +//! threshold with its own range check. The two rules are deliberately never merged. + +/// The three confidence bands (the review overlay's green / yellow / red). +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub enum ConfidenceBand { + Low, + Medium, + High, +} + +impl ConfidenceBand { + /// The legend line for this band, so the meaning never rests on colour alone. + pub fn legend(self) -> &'static str { + match self { + ConfidenceBand::High => "HIGH (>= 90%)", + ConfidenceBand::Medium => "MEDIUM (70-89%)", + ConfidenceBand::Low => "LOW (< 70%)", + } + } +} + +/// The one classifier: `>= 90` is High, `70..=89` Medium, `< 70` Low. Out-of-range values +/// clamp (negative → Low, above 100 → High); NaN is Low. +pub fn band_for(confidence: f32) -> ConfidenceBand { + if confidence >= 90.0 { + ConfidenceBand::High + } else if confidence >= 70.0 { + ConfidenceBand::Medium + } else { + ConfidenceBand::Low + } +} + +/// The batch rule, separate from [`band_for`]: a word is flagged when `0 <= conf <= threshold` +/// (default 60). Negative or above-threshold values are not flagged; NaN is not. +pub fn low_confidence(confidence: f32, threshold: f32) -> bool { + (0.0..=threshold).contains(&confidence) +} + +/// A word whose confidence lands in the Low band — a suspect for review. A word without a +/// reported confidence has no signal and is never a suspect. +pub fn is_suspect(confidence: Option) -> bool { + confidence.is_some_and(|c| band_for(c) == ConfidenceBand::Low) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The boundary matrix: 89 and 90, 69 and 70 straddle the bands. + #[test] + fn bands_straddle_the_boundaries() { + assert_eq!(band_for(89.0), ConfidenceBand::Medium); + assert_eq!(band_for(90.0), ConfidenceBand::High); + assert_eq!(band_for(69.0), ConfidenceBand::Low); + assert_eq!(band_for(70.0), ConfidenceBand::Medium); + assert_eq!(band_for(0.0), ConfidenceBand::Low); + assert_eq!(band_for(100.0), ConfidenceBand::High); + } + + /// Out-of-range values clamp, and NaN lands in the Low band instead of comparing equal to + /// nothing. + #[test] + fn out_of_range_confidences_clamp() { + assert_eq!(band_for(-0.5), ConfidenceBand::Low, "negative → Low"); + assert_eq!(band_for(1000.0), ConfidenceBand::High, "above 100 → High"); + assert_eq!(band_for(f32::NAN), ConfidenceBand::Low); + assert_eq!(band_for(f32::NEG_INFINITY), ConfidenceBand::Low); + assert_eq!(band_for(f32::INFINITY), ConfidenceBand::High); + } + + /// The batch threshold is its own rule: everything in `0..=threshold` flags, including + /// words band_for calls Medium (60 < 70), and negatives never do. + #[test] + fn batch_threshold_is_separate_from_the_bands() { + assert!(low_confidence(60.0, 60.0), "at the threshold it flags"); + assert!(low_confidence(0.0, 60.0)); + assert!(!low_confidence(60.5, 60.0)); + assert!(!low_confidence(-1.0, 60.0), "negative confidences are out of the rule's range"); + assert!(!low_confidence(f32::NAN, 60.0)); + // The rules disagree on real values: 65 is inside the Low band yet outside the batch + // rule with the default threshold (60), which is why the two must not be merged. + assert!(!low_confidence(65.0, 60.0)); + assert_eq!(band_for(65.0), ConfidenceBand::Low); + } + + /// Unconfident words are not suspects; Low-band words are. + #[test] + fn suspects_need_a_low_band_confidence() { + assert!(!is_suspect(None)); + assert!(!is_suspect(Some(95.0))); + assert!(!is_suspect(Some(70.0))); + assert!(is_suspect(Some(69.9))); + assert!(is_suspect(Some(0.0))); + } + + /// The legend names the thresholds, so the overlay never rests on colour alone. + #[test] + fn legend_text_matches_the_classifier() { + assert_eq!(ConfidenceBand::High.legend(), "HIGH (>= 90%)"); + assert_eq!(ConfidenceBand::Medium.legend(), "MEDIUM (70-89%)"); + assert_eq!(ConfidenceBand::Low.legend(), "LOW (< 70%)"); + } +} diff --git a/crates/ocr/src/lib.rs b/crates/ocr/src/lib.rs index 7f58270e1a..ff5b920dca 100644 --- a/crates/ocr/src/lib.rs +++ b/crates/ocr/src/lib.rs @@ -1,35 +1,50 @@ //! pdfcraft-ocr — Scan & OCR ▸ Recognize text (L4). //! -//! Recognition runs the ocrs engine (MIT/Apache-2.0) with its pre-trained models (CC-BY-SA-4.0, -//! fetched by `cargo xtask models`; see ATTRIBUTION.toml). The caller renders a page to pixels; -//! [`Ocr::recognize`] finds the words in them, and [`text_layer`] turns words placed in user space -//! into page content: invisible text (rendering mode 3) over each word, so the page becomes a +//! The caller renders a page to pixels ([`OcrImage`]) and hands it to a [`Recognizer`]. Two +//! engines exist: the pure-Rust `OcrsRecognizer` (ocrs, MIT/Apache-2.0, with its pre-trained +//! models, CC-BY-SA-4.0, fetched by `cargo xtask models`; see ATTRIBUTION.toml) and — off the +//! web — `tesseract::TesseractCli`, which drives an installed `tesseract` binary as an external +//! process. `merge` combines two engines' readings (ROVER), `preprocess` cleans the raster up +//! between rendering and recognition, and [`text_layer`] turns words placed in user space into +//! page content: invisible text (rendering mode 3) over each word, so the page becomes a //! searchable image (Acrobat's "Searchable Image (Exact)": the image is left untouched). //! -//! The models read the Latin alphabet (English and other languages written without accents). +//! Visible editable output uses [`pdfcraft_fonts::TextPlan`] and optional craft-fonts glyph +//! outlines; unsupported visible characters become `?` and are counted. The engine's invisible +//! searchable layer uses empty Type3 programs and ToUnicode maps, preserving Unicode without +//! display fonts. WinAnsi-only invisible text keeps the standard Helvetica layout here. +//! +//! The ocrs models read the Latin alphabet (English and other languages written without +//! accents); Tesseract (the `tesseract` module, off the web build) reads whatever its installed +//! language packs cover. #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] -use std::path::{Path, PathBuf}; +pub mod confidence; +pub mod merge; +mod ocrs; +pub mod preprocess; +#[cfg(not(target_arch = "wasm32"))] +pub mod tesseract; +pub use confidence::{ConfidenceBand, band_for, is_suspect, low_confidence}; +pub use merge::{MergeStrategy, StrategyOutcome, mean_confidence, recognize_with_strategy, rover_merge}; +pub use ocrs::{ALPHABET, DETECTION_MODEL, LANGUAGES, Models, Ocr, OcrsRecognizer, RECOGNITION_MODEL}; + +pub use pdfcraft_fonts::TextPlan; pub use pdfcraft_fonts::helvetica_width; -/// The model files, as named in ATTRIBUTION.toml. -pub const DETECTION_MODEL: &str = "text-detection.onnx"; -pub const RECOGNITION_MODEL: &str = "text-recognition.onnx"; +/// Hard cap on either side of an image any code in this crate will touch, in pixels; larger +/// images are rejected with [`OcrError::ImageTooLarge`] instead of being processed. +pub const MAX_SIDE: u32 = 10_000; -/// The recognition model's alphabet, as it was trained (ocrs-models' `DEFAULT_ALPHABET`): its -/// output classes follow this order. The ocrs crate's own copy has an `E` where the training had -/// `€`, which made a scanned "€250" read as "E250". -pub const ALPHABET: &str = " 0123456789!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~€ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; - -/// The languages the models read (ISO 639-1); all use the Latin alphabet without accents. -pub const LANGUAGES: &[(&str, &str)] = &[("en", "English")]; +/// Hard cap on an image's TOTAL area, in pixels (64 MP): sides under [`MAX_SIDE`] can still +/// multiply out to a raster no engine should have to read; larger images are rejected with +/// [`OcrError::ImageTooLarge`] instead of being processed. +pub const MAX_PIXELS: u32 = 64_000_000; #[derive(Debug, thiserror::Error)] pub enum OcrError { - /// Shown to end users (release packages ship the models; a source build fetches them with - /// `cargo xtask models`). The UI catalogs key this exact text. #[error("the text recognition models are not installed (reinstall PdfCraft, or set PDFCRAFT_MODELS to the folder that holds them)")] NoModels, #[error("loading {0}: {1}")] @@ -38,52 +53,93 @@ pub enum OcrError { Recognize(String), #[error("the image is empty")] EmptyImage, + #[error("the image is larger than the {MAX_SIDE}-pixel side or {MAX_PIXELS}-pixel limit")] + ImageTooLarge, + #[error("the image buffer holds {got} bytes, expected {want} for {width}x{height} RGBA")] + ImageSize { got: usize, want: usize, width: u32, height: u32 }, + #[error("the tesseract program is not available: {0}")] + NoTesseract(String), + #[error("tesseract did not finish within {0} seconds")] + Timeout(u64), + #[error("tesseract produced more than {0} bytes of output")] + OutputTooLarge(u64), + #[error("tesseract failed: {0}")] + Process(String), } -/// Where the two model files are. -#[derive(Clone, Debug, PartialEq)] -pub struct Models { - pub detection: PathBuf, - pub recognition: PathBuf, +/// An RGBA8 raster, row-major, top-left origin: what the engines read. The fields are private +/// so the invariants (non-zero, capped, exactly `width * height * 4` bytes) hold by +/// construction: an [`OcrImage`] in hand has always been validated, whatever produced it. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct OcrImage { + width: u32, + height: u32, + rgba: Vec, } -impl Models { - /// A complete model pair in `dir`, preferring current ONNX files over legacy RTEN files. - /// An incomplete update never mixes formats or hides an intact legacy pair. - pub fn in_dir(dir: &Path) -> Option { - [(DETECTION_MODEL, RECOGNITION_MODEL), ("text-detection.rten", "text-recognition.rten")].into_iter().find_map(|(detection, recognition)| { - let m = Models { detection: dir.join(detection), recognition: dir.join(recognition) }; - (m.detection.is_file() && m.recognition.is_file()).then_some(m) - }) - } - - /// Look for the models: `$PDFCRAFT_MODELS`, then where the release packages install them - /// beside the executable ([`Models::dirs_beside_exe`]), then the source tree's `assets/models/`. - pub fn find() -> Option { - Self::search_dirs().iter().find_map(|d| Self::in_dir(d)) - } - - /// The directories [`Models::find`] looks in, in order. - pub fn search_dirs() -> Vec { - let mut dirs = Vec::new(); - if let Some(d) = std::env::var_os("PDFCRAFT_MODELS") { - dirs.push(PathBuf::from(d)); +impl OcrImage { + /// Validate the sides ([`MAX_SIDE`]) and total area ([`MAX_PIXELS`]) and that `rgba` holds + /// exactly `width * height * 4` bytes (checked arithmetic; the counts come from documents, + /// so they are untrusted). + pub fn new(width: u32, height: u32, rgba: Vec) -> Result { + if width == 0 || height == 0 { + return Err(OcrError::EmptyImage); } - if let Some(exe) = std::env::current_exe().ok().and_then(|e| e.parent().map(Path::to_path_buf)) { - dirs.extend(Self::dirs_beside_exe(&exe)); + if width > MAX_SIDE || height > MAX_SIDE { + return Err(OcrError::ImageTooLarge); + } + let pixels = (width as usize).checked_mul(height as usize).ok_or(OcrError::ImageTooLarge)?; + if pixels > MAX_PIXELS as usize { + return Err(OcrError::ImageTooLarge); + } + match pixels.checked_mul(4) { + Some(want) if rgba.len() == want => Ok(OcrImage { width, height, rgba }), + Some(want) => Err(OcrError::ImageSize { got: rgba.len(), want, width, height }), + None => Err(OcrError::ImageTooLarge), } - dirs.push(Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets/models")); - dirs } - /// Where the release packages put the models, relative to the directory holding the - /// executable (packaging/*): - /// - `models/` beside it: the Windows MSI and portable zip; - /// - `../Resources/models`: the macOS app bundle (`Contents/MacOS` → `Contents/Resources`); - /// - `../share/pdfcraft/models`: the FHS-style trees (`bin/` → `share/`) of the Linux - /// deb/rpm/tar.gz/AppImage/Flatpak and the FreeBSD tarball, wherever they are installed. - pub fn dirs_beside_exe(exe_dir: &Path) -> Vec { - vec![exe_dir.join("models"), exe_dir.join("../Resources/models"), exe_dir.join("../share/pdfcraft/models")] + /// The image's width, in pixels. + pub fn width(&self) -> u32 { + self.width + } + + /// The image's height, in pixels. + pub fn height(&self) -> u32 { + self.height + } + + /// The RGBA bytes, row-major, exactly `width * height * 4` of them. + pub fn rgba(&self) -> &[u8] { + &self.rgba + } + + /// The smallest side, in pixels. + pub fn min_side(&self) -> u32 { + self.width.min(self.height) + } + + /// One RGBA byte at integer pixel (`x`, `y`), edges clamped; 255 (white) outside. Only + /// whole-pixel positions and channel 0–3 make sense; anything else reads clamped. + pub fn byte(&self, x: f64, y: f64, ch: usize) -> u8 { + let stride = self.width as usize * 4; + if stride == 0 || self.height == 0 || ch > 3 { + return 255; + } + let xi = (x.round().max(0.0) as usize).min(self.width as usize - 1); + let yi = (y.round().max(0.0) as usize).min(self.height as usize - 1); + self.rgba.get(yi * stride + xi * 4 + ch).copied().unwrap_or(255) + } + + /// The grayscale value of the pixel at (`x`, `y`), 0 (ink) … 255 (paper), with the borders + /// clamped (edges replicate). `None` only when the image is empty. + pub fn gray(&self, x: i64, y: i64) -> Option { + let x = x.clamp(0, self.width as i64 - 1); + let y = y.clamp(0, self.height as i64 - 1); + let row = y as usize * self.width as usize * 4; + let o = row + x as usize * 4; + let px = self.rgba.get(o..o + 4)?; + Some(((299 * px[0] as u32 + 587 * px[1] as u32 + 114 * px[2] as u32) / 1000) as u8) } } @@ -92,6 +148,26 @@ impl Models { pub struct Word { pub text: String, pub rect: [f32; 4], + /// How sure the engine is, 0–100, when it reports a confidence at all (`None`: the ocrs + /// engine does not). + pub confidence: Option, + /// Which engine read this word: the recogniser's [`Recognizer::id`], or `"ROVER"` when two + /// engines were merged and the surviving text is the merged choice. + pub source: String, +} + +impl Word { + pub fn new(text: impl Into, rect: [f32; 4], source: &str) -> Word { + Word { text: text.into(), rect, confidence: None, source: source.into() } + } + + /// Set the confidence (builder style), clamped to the documented 0–100 scale (a negative + /// value is 0, anything over 100 is 100). NaN means no confidence was reported (`None`), + /// the same unknown the engines that report nothing carry. + pub fn with_confidence(mut self, confidence: f32) -> Word { + self.confidence = if confidence.is_nan() { None } else { Some(confidence.clamp(0.0, 100.0)) }; + self + } } /// A recognised line of words, in reading order. @@ -106,63 +182,34 @@ impl Line { } } -/// A loaded recogniser. Loading takes a moment; keep one and reuse it. -pub struct Ocr { - engine: ocrs::OcrEngine, +/// What a recogniser needs to know beyond the pixels. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct RecognizeOptions { + /// Language code from [`LANGUAGES`] (`"en"`, `"de"`, …). Engines map it to their own codes + /// (Tesseract: `tesseract::language_code`, allow-listed before anything reaches a process); + /// unknown codes fall back to the engine's default. + pub language: String, } -impl Ocr { - pub fn load(models: &Models) -> Result { - let load = |p: &Path| rten::Model::load_file(p).map_err(|e| OcrError::Load(p.display().to_string(), e.to_string())); - let params = ocrs::OcrEngineParams { - detection_model: Some(load(&models.detection)?), - recognition_model: Some(load(&models.recognition)?), - alphabet: Some(ALPHABET.into()), - ..Default::default() - }; - let engine = ocrs::OcrEngine::new(params).map_err(|e| OcrError::Load("ocr engine".into(), e.to_string()))?; - Ok(Ocr { engine }) +impl Default for RecognizeOptions { + fn default() -> Self { + RecognizeOptions { language: "en".into() } } +} - /// Load the models found by [`Models::find`]. - pub fn find() -> Result { - Self::load(&Models::find().ok_or(OcrError::NoModels)?) - } - - /// Recognise the text in an RGBA (or RGB, or grey) image, `width` × `height` pixels. - pub fn recognize(&self, pixels: &[u8], width: u32, height: u32) -> Result, OcrError> { - if width == 0 || height == 0 || pixels.is_empty() { - return Err(OcrError::EmptyImage); - } - // ocrs wants 1 or 3 channels. - let rgb: std::borrow::Cow<[u8]> = if pixels.len() == (width * height * 4) as usize { - pixels.as_chunks::<4>().0.iter().flat_map(|p| [p[0], p[1], p[2]]).collect::>().into() - } else { - pixels.into() - }; - let err = |e: &dyn std::fmt::Display| OcrError::Recognize(e.to_string()); - let source = ocrs::ImageSource::from_bytes(&rgb, (width, height)).map_err(|e| err(&e))?; - let input = self.engine.prepare_input(source).map_err(|e| err(&e))?; - let found = self.engine.detect_words(&input).map_err(|e| err(&e))?; - let lines = self.engine.find_text_lines(&input, &found); - let read = self.engine.recognize_text(&input, &lines).map_err(|e| err(&e))?; - use ocrs::TextItem; - Ok(read - .into_iter() - .flatten() - .map(|line| Line { - words: line - .words() - .map(|w| { - let r = w.bounding_rect(); - Word { text: w.to_string(), rect: [r.left() as f32, r.top() as f32, r.right() as f32, r.bottom() as f32] } - }) - .filter(|w| !w.text.trim().is_empty()) - .collect(), - }) - .filter(|l| !l.words.is_empty()) - .collect()) - } +/// One text-recognition engine. Implementations are shared across threads +/// (`Arc`); `available` and `recognize` may spawn processes only off the web +/// build (see the `tesseract` module). +pub trait Recognizer: Send + Sync { + /// The engine's short name (`"ocrs"`, `"tesseract"`): what [`Word::source`] carries and + /// what settings and tools name it by. + fn id(&self) -> &'static str; + /// Whether this engine can run right now (models installed, binary found). + fn available(&self) -> bool; + /// The languages it reads, as `(code, name)` pairs (`"en"`, `"English"`). + fn languages(&self) -> Vec<(String, String)>; + /// Read the words in `image`, in reading order. + fn recognize(&self, image: &OcrImage, options: &RecognizeOptions) -> Result, OcrError>; } /// A word placed on a page, in PDF user space: the bottom-left corner of its box, and the @@ -173,6 +220,10 @@ pub struct PlacedWord { pub origin: [f64; 2], pub across: [f64; 2], pub up: [f64; 2], + /// Confidence 0–100, when the engine reported one. + pub confidence: Option, + /// Which engine read this word (see [`Word::source`]). + pub source: String, } impl PlacedWord { @@ -183,7 +234,14 @@ impl PlacedWord { let o = to_user(l, b); let br = to_user(r, b); let tl = to_user(l, t); - PlacedWord { text: word.text.clone(), origin: o, across: [br[0] - o[0], br[1] - o[1]], up: [tl[0] - o[0], tl[1] - o[1]] } + PlacedWord { + text: word.text.clone(), + origin: o, + across: [br[0] - o[0], br[1] - o[1]], + up: [tl[0] - o[0], tl[1] - o[1]], + confidence: word.confidence, + source: word.source.clone(), + } } } @@ -214,32 +272,193 @@ fn num(v: f64) -> String { if s == "-0" { "0".into() } else { s.into() } } -/// Page content that writes `words` as invisible text in `/PCHelv` (standard Helvetica, -/// WinAnsiEncoding), each word stretched to its box so selection and search highlight the -/// right place. Marked content `/OCR` so it can be told apart from the page's own text. -pub fn text_layer(words: &[PlacedWord]) -> Vec { +/// One run of a word's planned characters in one Type3 font: the resource name, the codes to +/// show (one byte per character), and the run's start as an offset in em units from the word's +/// origin (the accumulated advances of the runs before it). +struct PlannedRun { + font: String, + codes: Vec, + start: f64, +} + +/// The planned runs of word `i` (the same index [`pdfcraft_fonts::TextPlan::for_words`] planned +/// the words with), or `None` when the word is drawn in Helvetica: every character has a +/// WinAnsi code, or nothing could be planned/registered for it (the pre-Unicode output). +fn planned_runs(plan: &pdfcraft_fonts::TextPlan, word: usize) -> Option<(Vec, f64)> { + let enc = plan.encoding(word); + if enc.is_empty() || !plan.registered(enc) { + return None; + } + let mut runs: Vec = Vec::new(); + let mut total = 0.0; + for &(f, code) in enc { + let font = plan.fonts[f].name.as_str(); + match runs.last_mut() { + Some(last) if last.font == font => last.codes.push(code), + _ => runs.push(PlannedRun { font: font.to_string(), codes: vec![code], start: total }), + } + total += plan.advance(f, code); + } + (total.is_finite() && total > 0.0).then_some((runs, total)) +} + +/// Page content that writes `words` as VISIBLE text at their original boxes: the +/// editable-text output's page content. WinAnsi words are set in `/PCHelv` (standard +/// Helvetica); words with characters beyond WinAnsi are set in the plan's Type3 fonts, one run +/// per font. Each word fills its box — the font size comes from the box height and the +/// horizontal scaling is computed from the real advances of the font that draws the word +/// (Helvetica's approximated, the Type3 faces' exact) and emitted as an explicit `Tz` +/// percentage. Words whose box is empty (or whose text has no measurable width) are skipped; a +/// page that ends up with nothing simply shows nothing. +pub fn visible_text_layer(words: &[PlacedWord], plan: &pdfcraft_fonts::TextPlan) -> Vec { + visible_text_layer_at(words, plan, 0) +} + +/// Visible text for words starting at `word_offset` in a shared document plan. +pub fn visible_text_layer_at(words: &[PlacedWord], plan: &pdfcraft_fonts::TextPlan, word_offset: usize) -> Vec { + // The rendering mode and the font are graphics state, which `ET` doesn't reset: without + // `q … Q` they would stay set for every later content stream on the page, so text added + // after OCR (a header or footer) drew invisibly (#3029). + let mut out = b"/OCR BMC\nq\nBT\n0 Tr\n/PCHelv 1 Tf\n".to_vec(); + // The font and size the text state is set in, so a Tf is written only when they change. + // (The header's size-1 Helvetica covers layers of WinAnsi words only.) + let mut current: Option<(String, f64)> = Some(("PCHelv".to_string(), 1.0)); + for (i, w) in words.iter().enumerate() { + let height = w.up[0].hypot(w.up[1]); + let across = w.across[0].hypot(w.across[1]); + let (ux, uy) = (w.across[0] / across, w.across[1] / across); + let (vx, vy) = (w.up[0] / height, w.up[1] / height); + if !across.is_finite() + || !height.is_finite() + || across <= 0.0 + || height <= 0.0 + || !ux.is_finite() + || !vx.is_finite() + || !w.origin.iter().all(|v| v.is_finite()) + { + continue; + } + let size = height / BOX_EM; + let runs = planned_runs(plan, word_offset.saturating_add(i)); + // The word's natural advance at this size: Helvetica's approximation, or the exact sum + // of the planned glyphs' widths. + let natural = runs.as_ref().map_or_else(|| helvetica_width(&w.text, size), |(_, total)| total * size); + if natural.is_nan() || natural <= 0.0 { + continue; + } + // Horizontal scaling as a percentage of the natural advance at this size, so the word + // lands exactly on its box (100 = no scaling; a long box on a short word stretches it). + let tz = (across / natural * 100.0).max(1.0); + // The baseline sits above the box's bottom edge by the descender depth. + let o = [w.origin[0] + vx * DESCENT * size, w.origin[1] + vy * DESCENT * size]; + out.extend_from_slice(format!("{} Tz ", num(tz)).as_bytes()); + match &runs { + None => { + if current.as_ref().is_some_and(|(f, s)| f != "PCHelv" || *s != size) { + out.extend_from_slice(format!("/PCHelv {} Tf ", num(size)).as_bytes()); + current = Some(("PCHelv".to_string(), size)); + } + out.extend_from_slice(format!("{} {} {} {} {} {} Tm ", num(ux), num(uy), num(vx), num(vy), num(o[0]), num(o[1])).as_bytes()); + out.extend(pdfcraft_fonts::literal(&pdfcraft_fonts::win_ansi(&w.text))); + out.extend_from_slice(b" Tj\n"); + } + Some((planned, total)) => { + for run in planned { + if current.as_ref().is_some_and(|(f, s)| *f != run.font || *s != size) { + out.extend_from_slice(format!("/{} {} Tf ", run.font, num(size)).as_bytes()); + current = Some((run.font.clone(), size)); + } + // The run's origin: the word's baseline plus the across vector scaled by + // the advances before this run (the stretch applies to runs alike). + let frac = run.start / total; + out.extend_from_slice( + format!( + "{} {} {} {} {} {} Tm ", + num(ux), + num(uy), + num(vx), + num(vy), + num(o[0] + w.across[0] * frac), + num(o[1] + w.across[1] * frac) + ) + .as_bytes(), + ); + out.extend(pdfcraft_fonts::literal(&run.codes)); + out.extend_from_slice(b" Tj\n"); + } + } + } + } + out.extend_from_slice(b"ET\nQ\nEMC\n"); + out +} + +/// Page content that writes `words` as invisible text (rendering mode 3), each word stretched +/// to its box so selection and search highlight the right place. WinAnsi words are set in +/// `/PCHelv` (standard Helvetica); words with characters beyond WinAnsi are set in the plan's +/// Type3 fonts, one run per font, with the same exact box fit. Marked content `/OCR` so it can +/// be told apart from the page's own text. +pub fn text_layer(words: &[PlacedWord], plan: &pdfcraft_fonts::TextPlan) -> Vec { // `3 Tr` and the font are graphics state, which `ET` doesn't reset: without `q … Q` they // would stay set for every later content stream on the page, so text added after OCR (a // header or footer) drew invisibly (#3029). let mut out = b"/OCR BMC\nq\nBT\n3 Tr\n/PCHelv 1 Tf\n".to_vec(); - for w in words { - let width = helvetica_width(&w.text, 1.0); + let mut current: Option<(String, f64)> = Some(("PCHelv".to_string(), 1.0)); + for (i, w) in words.iter().enumerate() { + let runs = planned_runs(plan, i); + let width = runs.as_ref().map_or_else(|| helvetica_width(&w.text, 1.0), |(_, total)| *total); let height = w.up[0].hypot(w.up[1]); - if width <= 0.0 || height <= 0.0 { + let across = w.across[0].hypot(w.across[1]); + // Only positive, finite geometry reaches the content stream: a zero-sized box cannot + // be drawn, and a NaN or infinite one would put non-finite numbers on the page. (NaN + // fails every comparison, so the positivity checks already refuse it; the finiteness + // checks keep that property explicit.) + if width <= 0.0 || !(height > 0.0 && height.is_finite()) || !(across > 0.0 && across.is_finite()) || !w.origin.iter().all(|v| v.is_finite()) { continue; } - // The em square: the word's own ink (cap height or x-height, descenders or not) spans the - // box, so the text is as tall as the scanned word; its width is stretched to fit the word. - let (top, bottom) = ink_extent(&w.text); + // The em square. Helvetica words: the word's own ink (cap height or x-height, + // descenders or not) spans the box, so the text is as tall as the scanned word. Planned + // (Type3) words: those Helvetica letter heights do not describe the face, so the box spans + // the ascender-descender height. Either way the width is stretched to fit the word. + let (top, bottom) = if runs.is_some() { (BOX_EM - DESCENT, -DESCENT) } else { ink_extent(&w.text) }; let em = [w.up[0] / (top - bottom), w.up[1] / (top - bottom)]; - let ax = [w.across[0] / width, w.across[1] / width]; let o = [w.origin[0] - em[0] * bottom, w.origin[1] - em[1] * bottom]; - let m = [ax[0], ax[1], em[0], em[1], o[0], o[1]]; - let nums: Vec = m.iter().map(|v| num(*v)).collect(); - out.extend_from_slice(nums.join(" ").as_bytes()); - out.extend_from_slice(b" Tm "); - out.extend(pdfcraft_fonts::literal(&pdfcraft_fonts::win_ansi(&w.text))); - out.extend_from_slice(b" Tj\n"); + match &runs { + None => { + let ax = [w.across[0] / width, w.across[1] / width]; + if current.as_ref().is_some_and(|(f, s)| f != "PCHelv" || *s != 1.0) { + out.extend_from_slice(b"/PCHelv 1 Tf "); + current = Some(("PCHelv".to_string(), 1.0)); + } + let m = [ax[0], ax[1], em[0], em[1], o[0], o[1]]; + let nums: Vec = m.iter().map(|v| num(*v)).collect(); + out.extend_from_slice(nums.join(" ").as_bytes()); + out.extend_from_slice(b" Tm "); + out.extend(pdfcraft_fonts::literal(&pdfcraft_fonts::win_ansi(&w.text))); + out.extend_from_slice(b" Tj\n"); + } + Some((planned, total)) => { + for run in planned { + if current.as_ref().is_some_and(|(f, s)| *f != run.font || *s != 1.0) { + out.extend_from_slice(format!("/{} 1 Tf ", run.font).as_bytes()); + current = Some((run.font.clone(), 1.0)); + } + let m = [ + w.across[0] / total, + w.across[1] / total, + em[0], + em[1], + o[0] + w.across[0] * run.start / total, + o[1] + w.across[1] * run.start / total, + ]; + let nums: Vec = m.iter().map(|v| num(*v)).collect(); + out.extend_from_slice(nums.join(" ").as_bytes()); + out.extend_from_slice(b" Tm "); + out.extend(pdfcraft_fonts::literal(&run.codes)); + out.extend_from_slice(b" Tj\n"); + } + } + } } out.extend_from_slice(b"ET\nQ\nEMC\n"); out @@ -253,10 +472,22 @@ mod tests { fn places_words_through_the_mapping() { // 2 pixels per point, page 612 × 792, y flipped. let to_user = |x: f32, y: f32| [x as f64 / 2.0, 792.0 - y as f64 / 2.0]; - let w = PlacedWord::place(&Word { text: "Hello".into(), rect: [100.0, 200.0, 300.0, 240.0] }, to_user); + let w = PlacedWord::place(&Word::new("Hello", [100.0, 200.0, 300.0, 240.0], "ocrs"), to_user); assert_eq!(w.origin, [50.0, 672.0]); assert_eq!(w.across, [100.0, 0.0]); assert_eq!(w.up, [0.0, 20.0]); + assert_eq!(w.source, "ocrs"); + assert_eq!(w.confidence, None); + } + + /// Confidence and source survive placement. + #[test] + fn placed_words_carry_confidence_and_source() { + let to_user = |x: f32, y: f32| [x as f64, y as f64]; + let w = Word::new("Hi", [1.0, 2.0, 3.0, 4.0], "tesseract").with_confidence(87.5); + let p = PlacedWord::place(&w, to_user); + assert_eq!(p.confidence, Some(87.5)); + assert_eq!(p.source, "tesseract"); } /// The text layer is Helvetica in WinAnsiEncoding: every character the model can recognise @@ -267,10 +498,27 @@ mod tests { assert_eq!(pdfcraft_fonts::first_undrawable(ALPHABET), None); } + /// `with_confidence` is clamped to the documented 0–100 scale: negatives (and −inf) are 0, + /// anything over 100 (and +inf) is 100, in-scale values pass through, and NaN means no + /// confidence was reported — the same `None` unknown the unreporting engines carry. + #[test] + fn with_confidence_clamps_and_treats_nan_as_unknown() { + let c = |v: f32| Word::new("w", [0.0; 4], "ocrs").with_confidence(v).confidence; + assert_eq!(c(0.0), Some(0.0)); + assert_eq!(c(50.0), Some(50.0)); + assert_eq!(c(100.0), Some(100.0)); + assert_eq!(c(-1.0), Some(0.0), "negatives clamp to 0"); + assert_eq!(c(f32::NEG_INFINITY), Some(0.0)); + assert_eq!(c(150.0), Some(100.0), "over 100 clamps to 100"); + assert_eq!(c(f32::INFINITY), Some(100.0)); + assert_eq!(c(f32::NAN), None, "NaN is unknown, not a confidence"); + assert_eq!(c(f32::EPSILON), Some(f32::EPSILON), "in-scale values are untouched"); + } + #[test] fn text_layer_is_invisible_text_fitted_to_each_box() { - let w = PlacedWord { text: "Hi".into(), origin: [10.0, 20.0], across: [30.0, 0.0], up: [0.0, 9.3] }; - let s = String::from_utf8(text_layer(&[w])).unwrap(); + let w = PlacedWord { text: "Hi".into(), origin: [10.0, 20.0], across: [30.0, 0.0], up: [0.0, 9.3], confidence: None, source: "ocrs".into() }; + let s = String::from_utf8(text_layer(&[w], &TextPlan::default())).unwrap(); assert!(s.contains("3 Tr") && s.contains("/PCHelv 1 Tf"), "{s}"); let width = helvetica_width("Hi", 1.0); // "Hi" has no descender: its box spans the cap height, from the baseline up. @@ -283,8 +531,8 @@ mod tests { /// after it on the page starts from the graphics state it had before. #[test] fn the_layer_restores_the_graphics_state_it_changes() { - let w = PlacedWord { text: "Hi".into(), origin: [10.0, 20.0], across: [30.0, 0.0], up: [0.0, 9.3] }; - let s = String::from_utf8(text_layer(&[w])).unwrap(); + let w = PlacedWord { text: "Hi".into(), origin: [10.0, 20.0], across: [30.0, 0.0], up: [0.0, 9.3], confidence: None, source: "ocrs".into() }; + let s = String::from_utf8(text_layer(&[w], &TextPlan::default())).unwrap(); let mut depth = 0_i32; for token in s.split_ascii_whitespace() { match token { @@ -309,78 +557,200 @@ mod tests { assert_eq!(ink_extent("Gallus.Ze@camtel.cm"), (CAP_HEIGHT, 0.0)); assert_eq!(ink_extent("Corporation"), (CAP_HEIGHT, -DESCENT)); assert_eq!(ink_extent("--"), (BOX_EM - DESCENT, -DESCENT)); - let w = PlacedWord { text: "gap".into(), origin: [0.0, 100.0], across: [20.0, 0.0], up: [0.0, 7.3] }; - let s = String::from_utf8(text_layer(&[w])).unwrap(); + let w = PlacedWord { text: "gap".into(), origin: [0.0, 100.0], across: [20.0, 0.0], up: [0.0, 7.3], confidence: None, source: "ocrs".into() }; + let s = String::from_utf8(text_layer(&[w], &TextPlan::default())).unwrap(); let em = 7.3 / (X_HEIGHT + DESCENT); assert!(s.contains(&format!(" 0 0 {} 0 {} Tm (gap) Tj", num(em), num(100.0 + em * DESCENT))), "{s}"); } + /// A word whose box is not positive, finite geometry never reaches the content stream: + /// NaN, infinite and zero-sized boxes are dropped, so the layer never carries non-finite + /// numbers. + #[test] + fn text_layer_refuses_non_finite_and_degenerate_boxes() { + let word = |across: [f64; 2], up: [f64; 2], origin: [f64; 2]| PlacedWord { + text: "Hi".into(), + origin, + across, + up, + confidence: Some(90.0), + source: "tesseract".into(), + }; + for (why, w) in [ + ("NaN across", word([f64::NAN, 0.0], [0.0, 9.3], [0.0; 2])), + ("NaN up", word([30.0, 0.0], [f64::NAN, 1.0], [0.0; 2])), + ("inf up", word([30.0, 0.0], [0.0, f64::INFINITY], [0.0; 2])), + ("inf origin", word([30.0, 0.0], [0.0, 9.3], [0.0, f64::INFINITY])), + ("zero across", word([0.0, 0.0], [0.0, 9.3], [0.0; 2])), + ("NaN origin", word([30.0, 0.0], [0.0, 9.3], [0.0, f64::NAN])), + ] { + let s = String::from_utf8(text_layer(&[w], &TextPlan::default())).unwrap(); + assert_eq!(s, "/OCR BMC\nq\nBT\n3 Tr\n/PCHelv 1 Tf\nET\nQ\nEMC\n", "{why}: {s}"); + assert!(!s.contains("NaN") && !s.contains("inf"), "{why}: {s}"); + } + } + + /// The editable-text layer draws visible text whose horizontal scaling is an explicit + /// percentage computed from real Helvetica metrics: `Tz` × natural advance = box width. + #[test] + fn visible_text_layer_scales_by_a_percentage_of_real_metrics() { + let w = PlacedWord { text: "Hi".into(), origin: [10.0, 20.0], across: [40.0, 0.0], up: [0.0, 9.3], confidence: None, source: "ocrs".into() }; + let s = String::from_utf8(visible_text_layer(&[w], &TextPlan::default())).unwrap(); + assert!(s.contains("0 Tr"), "visible, not invisible: {s}"); + let size = 9.3 / BOX_EM; + let natural = helvetica_width("Hi", size); + let tz = 40.0 / natural * 100.0; + assert!(s.contains(&format!("{} Tz", num(tz))), "{s}"); + assert!(s.contains("(Hi) Tj"), "{s}"); + assert!(s.starts_with("/OCR BMC") && s.ends_with("EMC\n")); + } + + /// Degenerate boxes and words with no measurable width are skipped, never divide by zero. + #[test] + fn visible_text_layer_skips_degenerate_words() { + let word = |across: [f64; 2], up: [f64; 2], text: &str| PlacedWord { + text: text.into(), + origin: [0.0; 2], + across, + up, + confidence: None, + source: "ocrs".into(), + }; + let words = vec![ + word([0.0, 0.0], [0.0, 9.0], "flat"), + word([10.0, 0.0], [0.0, 0.0], "short"), + word([f64::NAN, 0.0], [0.0, 9.0], "nan"), + word([10.0, 0.0], [0.0, 9.0], ""), + word([10.0, 0.0], [0.0, 9.0], "Hi"), + ]; + let s = String::from_utf8(visible_text_layer(&words, &TextPlan::default())).unwrap(); + assert_eq!(s.matches("Tj").count(), 1, "only the one drawable word is written: {s}"); + } + + /// A word whose ORIGIN is not finite never reaches the visible layer either: a NaN or + /// infinite origin would put "NaN"/"inf" into the content stream. + #[test] + fn visible_text_layer_refuses_non_finite_origins() { + let word = + |origin: [f64; 2]| PlacedWord { text: "Hi".into(), origin, across: [10.0, 0.0], up: [0.0, 9.0], confidence: None, source: "ocrs".into() }; + for (why, origin) in [("NaN x", [f64::NAN, 100.0]), ("inf y", [10.0, f64::INFINITY]), ("NaN both", [f64::NAN; 2])] { + let s = String::from_utf8(visible_text_layer(&[word(origin)], &TextPlan::default())).unwrap(); + assert!(!s.contains("NaN") && !s.contains("inf"), "{why}: {s}"); + assert_eq!(s.matches("Tj").count(), 0, "{why}: {s}"); + } + } + + /// After a Type3 word the text state goes back to Helvetica: the Latin words around a + /// planned word must not inherit its font. + #[test] + fn helvetica_is_restored_after_a_planned_word() { + if pdfcraft_fonts::CRAFT_FONTS.is_empty() { + eprintln!("skipping: built without craft-fonts (set CRAFT_FONTS_DIR to run it)"); + return; + } + let word = |text: &str| PlacedWord { + text: text.into(), + origin: [10.0, 20.0], + across: [60.0, 0.0], + up: [0.0, 9.3], + confidence: None, + source: "ocrs".into(), + }; + let words = [word("Hi"), word("日本"), word("Ho")]; + let mut plan = TextPlan::for_words(["Hi", "日本", "Ho"]); + for (i, font) in plan.fonts.iter_mut().enumerate() { + font.name = format!("PCOcr{i}"); + } + let s = String::from_utf8(text_layer(&words, &plan)).unwrap(); + assert!(s.contains("/PCOcr0 1 Tf"), "{s}"); + // The last Helvetica selection comes after the Type3 run, and the Latin word after it + // is drawn in Helvetica, not left in the planned font. + assert!(s.rfind("/PCOcr0 1 Tf").unwrap_or(0) < s.rfind("/PCHelv 1 Tf").unwrap_or(usize::MAX), "{s}"); + // The `Q` closes the `q … Q` scope that keeps `3 Tr` from leaking into later content. + assert!(s.ends_with("Tm (Ho) Tj\nET\nQ\nEMC\n"), "{s}"); + // The visible layer restores Helvetica with the word's size. + let v = String::from_utf8(visible_text_layer(&words, &plan)).unwrap(); + assert!(v.rfind("/PCOcr0").unwrap_or(0) < v.rfind("/PCHelv").unwrap_or(usize::MAX), "{v}"); + assert!(v.contains("(Ho) Tj"), "{v}"); + } + + /// Words with characters beyond WinAnsi draw in the plan's Type3 font, one run, with the + /// same exact box fit as the Helvetica words (the matrix x-axis spans across / advance). + #[test] + fn planned_words_draw_in_their_font_with_the_same_exact_fit() { + if pdfcraft_fonts::CRAFT_FONTS.is_empty() { + eprintln!("skipping: built without craft-fonts (set CRAFT_FONTS_DIR to run it)"); + return; + } + let w = + PlacedWord { text: "日本".into(), origin: [10.0, 20.0], across: [60.0, 0.0], up: [0.0, 9.3], confidence: None, source: "ocrs".into() }; + let mut plan = TextPlan::for_words(["日本"]); + // The names the registrar (pdfcraft_edit::add_type3_fonts) fills in — this crate + // cannot reach it, so the test sets them where it reads them. + for (i, font) in plan.fonts.iter_mut().enumerate() { + font.name = format!("PCOcr{i}"); + } + let codes: Vec = plan.encoding(0).iter().map(|&(_, c)| c).collect(); + assert_eq!(codes.len(), 2, "{codes:?}"); + let total = plan.advance_of(plan.encoding(0)); + let s = String::from_utf8(text_layer(std::slice::from_ref(&w), &plan)).unwrap(); + assert!(s.contains("/PCOcr0 1 Tf"), "{s}"); + assert!(s.contains(&format!("{} 0 0 10 10 22.1 Tm ", num(60.0 / total))), "{s}"); + assert!(s.contains(&format!("Tm {} Tj\n", String::from_utf8_lossy(&pdfcraft_fonts::literal(&codes)))), "{s}"); + // The visible layer: size from the box height, Tz from the Type3's own advance. + let v = String::from_utf8(visible_text_layer(std::slice::from_ref(&w), &plan)).unwrap(); + let size = 9.3 / BOX_EM; + assert!(v.contains(&format!("/PCOcr0 {} Tf ", num(size))), "{v}"); + assert!(v.contains(&format!("{} Tz", num(60.0 / (total * size) * 100.0))), "{v}"); + } + + /// Without planned characters (an empty plan: built without craft-fonts, or before the + /// fonts are registered) the WinAnsi path stands, '?' included. + #[test] + fn unplanned_words_fall_back_to_win_ansi_question_marks() { + let w = + PlacedWord { text: "日本".into(), origin: [10.0, 20.0], across: [60.0, 0.0], up: [0.0, 9.3], confidence: None, source: "ocrs".into() }; + let s = String::from_utf8(text_layer(&[w], &TextPlan::default())).unwrap(); + assert!(s.contains("(??) Tj"), "{s}"); + assert!(!s.contains("PCOcr"), "{s}"); + } + + /// A character no face has a glyph for becomes the font's '?', still in the run, counted + /// by the plan. + #[test] + fn substitutions_are_written_as_the_font_s_question_mark() { + if pdfcraft_fonts::CRAFT_FONTS.is_empty() { + eprintln!("skipping: built without craft-fonts (set CRAFT_FONTS_DIR to run it)"); + return; + } + let w = PlacedWord { + text: "日\u{1f4a9}語".into(), + origin: [0.0, 0.0], + across: [60.0, 0.0], + up: [0.0, 9.3], + confidence: None, + source: "ocrs".into(), + }; + let mut plan = TextPlan::for_words(["日\u{1f4a9}語"]); + for (i, font) in plan.fonts.iter_mut().enumerate() { + font.name = format!("PCOcr{i}"); + } + assert_eq!(plan.missing(), 1, "the emoji has no glyph anywhere"); + assert_eq!(plan.encoding(0).len(), 3, "it still gets an encoding: the font's ?"); + let codes: Vec = plan.encoding(0).iter().map(|&(_, c)| c).collect(); + let s = String::from_utf8(text_layer(&[w], &plan)).unwrap(); + assert!(s.contains(&format!("Tm {} Tj\n", String::from_utf8_lossy(&pdfcraft_fonts::literal(&codes)))), "{s}"); + } + #[test] fn rotated_pages_keep_the_reading_direction() { // A page turned 90°: image x runs up the page. let to_user = |x: f32, y: f32| [y as f64, x as f64]; - let w = PlacedWord::place(&Word { text: "Up".into(), rect: [0.0, 0.0, 50.0, 10.0] }, to_user); + let w = PlacedWord::place(&Word::new("Up", [0.0, 0.0, 50.0, 10.0], "ocrs"), to_user); assert_eq!(w.across, [0.0, 50.0]); assert_eq!(w.up, [-10.0, 0.0]); } - /// The current ONNX pair wins when an installation also retains both legacy models. - #[test] - fn model_discovery_prefers_the_complete_onnx_pair() { - let dir = tempfile::tempdir().unwrap(); - for file in ["text-detection.onnx", "text-recognition.onnx"] { - std::fs::write(dir.path().join(file), b"model").unwrap(); - } - let expected = Some(Models { detection: dir.path().join("text-detection.onnx"), recognition: dir.path().join("text-recognition.onnx") }); - assert_eq!(Models::in_dir(dir.path()), expected, "a complete ONNX pair is sufficient"); - for file in ["text-detection.rten", "text-recognition.rten"] { - std::fs::write(dir.path().join(file), b"model").unwrap(); - } - assert_eq!(Models::in_dir(dir.path()), expected, "the complete ONNX pair takes precedence over legacy models"); - } - - /// An interrupted ONNX update still permits an intact legacy pair in the same directory. - #[test] - fn model_discovery_falls_back_to_legacy_when_the_onnx_pair_is_incomplete() { - for current in ["text-detection.onnx", "text-recognition.onnx"] { - let dir = tempfile::tempdir().unwrap(); - for file in [current, "text-detection.rten", "text-recognition.rten"] { - std::fs::write(dir.path().join(file), b"model").unwrap(); - } - assert_eq!( - Models::in_dir(dir.path()), - Some(Models { detection: dir.path().join("text-detection.rten"), recognition: dir.path().join("text-recognition.rten") }), - "{current} alone must not hide a complete legacy pair" - ); - } - } - - /// Detection and recognition must come from one complete format pair, never a mixed update. - #[test] - fn model_discovery_refuses_mixed_format_pairs() { - for pair in [["text-detection.onnx", "text-recognition.rten"], ["text-detection.rten", "text-recognition.onnx"]] { - let dir = tempfile::tempdir().unwrap(); - for file in pair { - std::fs::write(dir.path().join(file), b"model").unwrap(); - } - assert_eq!(Models::in_dir(dir.path()), None, "{pair:?} is not a complete model pair"); - } - } - - /// Existing source builds and PDFCRAFT_MODELS overrides retain their complete RTEN pair. - #[test] - fn model_discovery_keeps_legacy_only_installations() { - let dir = tempfile::tempdir().unwrap(); - assert_eq!(Models::in_dir(dir.path()), None); - std::fs::write(dir.path().join("text-detection.rten"), b"model").unwrap(); - assert_eq!(Models::in_dir(dir.path()), None, "one legacy model is incomplete"); - std::fs::write(dir.path().join("text-recognition.rten"), b"model").unwrap(); - assert_eq!( - Models::in_dir(dir.path()), - Some(Models { detection: dir.path().join("text-detection.rten"), recognition: dir.path().join("text-recognition.rten") }) - ); - } - /// #103: every release package's layout puts the models where the installed app looks. /// Mirrors packaging/{windows/package.ps1,macos/package.sh,linux/package.sh,freebsd/package.sh}. #[test] @@ -443,6 +813,47 @@ mod tests { assert!(word.rect[0] >= 10.0 && word.rect[0] < 60.0, "{word:?}"); } + /// The recognised words name their engine. + #[test] + fn ocrs_recognizer_names_its_words() { + let Ok(rec) = OcrsRecognizer::find() else { + eprintln!("skipped: OCR models not installed"); + return; + }; + assert_eq!(rec.id(), "ocrs"); + assert!(rec.languages().iter().any(|(c, n)| c == "en" && n == "English"), "{:?}", rec.languages()); + let (w, h, px) = test_image::hello(); + let image = OcrImage::new(w, h, px).unwrap(); + let lines = rec.recognize(&image, &RecognizeOptions::default()).unwrap(); + let words: Vec<&Word> = lines.iter().flat_map(|l| &l.words).collect(); + assert!(!words.is_empty()); + assert!(words.iter().all(|w| w.source == "ocrs"), "{words:?}"); + } + + /// Hostile images are rejected with errors, never panics: zero sides, sides over the cap, + /// totals over the area cap (even with legal sides), buffers that do not fit, counts that + /// overflow. + #[test] + fn hostile_image_dimensions_are_rejected_not_panicked_at() { + assert!(matches!(OcrImage::new(0, 10, vec![]), Err(OcrError::EmptyImage))); + assert!(matches!(OcrImage::new(10, 0, vec![]), Err(OcrError::EmptyImage))); + assert!(matches!(OcrImage::new(u32::MAX, u32::MAX, vec![]), Err(OcrError::ImageTooLarge))); + assert!(matches!(OcrImage::new(MAX_SIDE + 1, 1, vec![0; 4]), Err(OcrError::ImageTooLarge))); + // 10 000 × 7 000 = 70 MP: legal on both sides, over the 64 MP area cap (no allocation + // is needed to reject it — the buffer is never inspected). + assert!(matches!(OcrImage::new(MAX_SIDE, 7000, vec![]), Err(OcrError::ImageTooLarge))); + // 8 000 × 8 000 = exactly the area cap: accepted shape (the short buffer proves the + // cap check passed), while one more row is refused. + assert!(matches!(OcrImage::new(8000, 8000, vec![0; 16]), Err(OcrError::ImageSize { .. }))); + assert!(matches!(OcrImage::new(8000, 8001, vec![0; 16]), Err(OcrError::ImageTooLarge))); + assert!(matches!(OcrImage::new(2, 2, vec![0; 15]), Err(OcrError::ImageSize { .. }))); + let ok = OcrImage::new(2, 2, vec![255; 16]).unwrap(); + assert_eq!((ok.width(), ok.height()), (2, 2)); + assert_eq!(ok.rgba().len(), 16); + assert_eq!(ok.gray(5, 5), Some(255), "clamped reads stay inside"); + assert_eq!(ok.gray(-1, -1), Some(255)); + } + mod test_image { /// "HELLO WORLD" drawn with blocky 5×7 letters, 4 pixels per dot, black on white. pub fn hello() -> (u32, u32, Vec) { diff --git a/crates/ocr/src/merge.rs b/crates/ocr/src/merge.rs new file mode 100644 index 0000000000..58fc17a4e5 --- /dev/null +++ b/crates/ocr/src/merge.rs @@ -0,0 +1,583 @@ +//! Combining engines. "ROVER" merges two engines' readings of one page: every primary word +//! adopts the best-overlapping unused secondary word when their boxes agree enough (IoU, below); +//! the higher confidence wins the text, box and confidence (a tie keeps the primary; against a +//! primary of unknown confidence the secondary must reach [`UNKNOWN_CONFIDENCE_BAR`]) and the +//! surviving word is named `"ROVER"`; secondary words nothing claimed are appended, keeping +//! their own engine's name. + +use crate::{Line, OcrError, OcrImage, RecognizeOptions, Recognizer, Word}; + +/// How the chosen engines combine. The default is [`MergeStrategy::PrimaryOnly`] with the +/// default engine (ocrs), which is today's behavior. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +pub enum MergeStrategy { + /// Only the primary engine runs. + #[default] + PrimaryOnly, + /// The secondary engine joins only when the primary's reading looks weak: its mean word + /// confidence is under 70, or its confidence is unknown (words were read but none reports + /// a confidence — the ocrs engine). An unknown reading is never counted as 100; an empty + /// primary keeps the fast path (no words, nothing to double-check). + ConfidenceWeighted, + /// Both engines always run and their readings merge (with no secondary engine this + /// degrades to primary only). + RoverVote, +} + +/// The mean of the confidences the words report, 0–100; `None` when the reading's confidence +/// is UNKNOWN — words were read but none reports a confidence (the ocrs engine's words). +/// Unknown is never counted as 100: there is no low-confidence signal, but a reading whose +/// confidence nobody knows is not therefore confident, so a confidence-weighted strategy +/// answers it by asking the secondary engine. An empty reading is `Some(100.0)`: no words +/// were read, so there is nothing to double-check and the fast path stands. +pub fn mean_confidence(lines: &[Line]) -> Option { + let mut total = 0usize; + let mut reported = (0.0f64, 0usize); + for word in lines.iter().flat_map(|l| &l.words) { + total += 1; + if let Some(c) = word.confidence { + reported.0 += c as f64; + reported.1 += 1; + } + } + match (total, reported.1) { + (0, _) => Some(100.0), + (_, 0) => None, + (_, n) => Some((reported.0 / n as f64) as f32), + } +} + +/// Intersection over union of two `[left, top, right, bottom]` boxes. An empty intersection is +/// 0; degenerate or NaN boxes give 0 rather than panicking or poisoning the comparison. +pub fn iou(a: &[f32; 4], b: &[f32; 4]) -> f64 { + let l = a[0].max(b[0]); + let t = a[1].max(b[1]); + let r = a[2].min(b[2]); + let btm = a[3].min(b[3]); + if !(r > l && btm > t) { + return 0.0; // disjoint, touching, inverted, or NaN (all comparisons false) + } + let inter = (r - l) as f64 * (btm - t) as f64; + let area = |x: &[f32; 4]| ((x[2] - x[0]).max(0.0) as f64) * ((x[3] - x[1]).max(0.0) as f64); + let union = area(a) + area(b) - inter; + if union <= 0.0 { + return 0.0; + } + inter / union +} + +/// The most primary×secondary word comparisons one ROVER merge will attempt. Known limit: a +/// merge over this cap is skipped — the primary reading stands alone, and the skip is noted, +/// never silent — so two enormous readings cannot turn the merge into quadratic work without +/// end. A real page is a few hundred words on each side, orders of magnitude under the cap. +pub const ROVER_MAX_COMPARISONS: usize = 100_000_000; + +/// Whether the two readings are too large to merge: their word counts multiply past +/// [`ROVER_MAX_COMPARISONS`]. Shared by [`rover_merge`] (which then keeps the primary) and +/// [`recognize_with_strategy`] (which then notes the skip). +fn over_cap(primary: &[Line], secondary: &[Line]) -> bool { + let primary_words: usize = primary.iter().map(|l| l.words.len()).sum(); + let secondary_words: usize = secondary.iter().map(|l| l.words.len()).sum(); + primary_words.saturating_mul(secondary_words) > ROVER_MAX_COMPARISONS +} + +/// The confidence a secondary word needs to replace a primary word whose confidence is +/// unknown (the ocrs engine reports none). It is the bar under which a reading counts as weak +/// ([`MergeStrategy::ConfidenceWeighted`] asks the second engine below it): a word the second +/// engine itself calls weak does not displace a reading nobody scored. +pub const UNKNOWN_CONFIDENCE_BAR: f32 = 70.0; + +/// True when the secondary word's confidence `a` beats the primary's `b`. Both known: the +/// strictly higher one wins (a tie keeps the primary). A known confidence against an unknown +/// primary wins only at or above [`UNKNOWN_CONFIDENCE_BAR`]: an unknown confidence is neither +/// 0 nor 100, so a 5% reading must not replace it, while a confident one may. NaN never wins, +/// and with no confidence on the secondary side the primary stands. +fn higher(a: Option, b: Option) -> bool { + match (a, b) { + (Some(a), Some(b)) => a.partial_cmp(&b) == Some(std::cmp::Ordering::Greater), + (Some(a), None) => a >= UNKNOWN_CONFIDENCE_BAR, + _ => false, + } +} + +/// Merge the two engines' readings. Primary words keep their order and lines; a word is +/// replaced by its overlapping secondary (IoU >= 0.5) only when that secondary is more +/// confident, and either way the merged word's [`Word::source`] is `"ROVER"`. Secondary words +/// no primary claimed are appended, in their own reading order and lines, under their own +/// engine's name (`secondary_id`). Known limit: over [`ROVER_MAX_COMPARISONS`] comparisons +/// (word counts multiplied) the primary reading is kept as is, unmerged; the strategy runner +/// names that skip in a note. +pub fn rover_merge(primary: Vec, secondary: Vec, secondary_id: &str) -> Vec { + if over_cap(&primary, &secondary) { + return primary; // over the comparison cap: the primary stands alone + } + let mut primary = primary; + // The secondary's words, marked `None` once a primary word claimed them, grouped by their + // own lines so the unclaimed ones can be appended in order. + let mut unused: Vec>> = secondary.into_iter().map(|l| l.words.into_iter().map(Some).collect()).collect(); + for line in &mut primary { + for word in &mut line.words { + // The best-overlapping unused secondary word, if any beats IoU 0.5. + let mut best: Option<(f64, usize, usize)> = None; + for (li, words) in unused.iter().enumerate() { + for (wi, slot) in words.iter().enumerate() { + let Some(w) = slot else { continue }; + let score = iou(&word.rect, &w.rect); + if score >= 0.5 && best.is_none_or(|(b, _, _)| score > b) { + best = Some((score, li, wi)); + } + } + } + let Some((_, li, wi)) = best else { continue }; + let claimed = unused.get_mut(li).and_then(|l| l.get_mut(wi)).and_then(|slot| slot.take()); + let Some(claim) = claimed else { continue }; + if higher(claim.confidence, word.confidence) { + *word = Word { source: "ROVER".into(), ..claim }; + } else { + // Tie (or the primary wins): keep the primary's text, box and confidence, but + // record that this reading is the engines' agreed one. + word.source = "ROVER".into(); + } + } + } + // Append the secondary words nothing claimed, line by line, under their engine's name + // (`secondary_id` backfills words that name no source of their own). + let mut merged = primary; + for line in unused { + let words: Vec = line + .into_iter() + .flatten() + .map(|mut w| { + if w.source.is_empty() { + w.source = secondary_id.into(); + } + w + }) + .collect(); + if !words.is_empty() { + merged.push(Line { words }); + } + } + merged +} + +/// What a strategy run produced: the merged (or primary-only) reading, whether the secondary +/// engine's reading is part of it, and the notes recorded along the way. +#[derive(Clone, Debug, PartialEq, Default)] +pub struct StrategyOutcome { + pub lines: Vec, + /// Whether the secondary engine's reading is part of `lines`: true only when the merge + /// actually happened. A secondary that failed, or whose reading was discarded over the + /// comparison cap, is `false`, with a note in [`StrategyOutcome::notes`] saying why. + pub secondary_ran: bool, + /// Why the page's reading is partial, if it is. The secondary engine is an enhancement, + /// never a gate: when it is configured but fails, the primary reading is kept and the + /// failure is noted here — a page is never skipped because a partner could not read it. + /// Only a primary failure is an [`OcrError`]. + pub notes: Vec, +} + +/// The note recorded when an ensemble partner fails: the page keeps the primary reading and +/// the cause is named for the report. +fn degraded_note(id: &str, error: &OcrError) -> String { + format!("the {id} engine failed ({error}) — the page keeps the primary reading alone") +} + +/// The note recorded when the two readings are too large to merge: the page keeps the primary +/// reading alone and the discarded partner reading is named, never silent. +fn cap_note(id: &str, primary_words: usize, secondary_words: usize) -> String { + format!( + "the readings were too large to merge ({primary_words} × {secondary_words} comparisons, over the cap of {ROVER_MAX_COMPARISONS}) — the page keeps the primary reading alone and the {id} reading is unused" + ) +} + +/// Run the engines per `strategy` and merge. See [`StrategyOutcome`] for what comes back. +pub fn recognize_with_strategy( + primary: &dyn Recognizer, + secondary: Option<&dyn Recognizer>, + strategy: MergeStrategy, + image: &OcrImage, + options: &RecognizeOptions, +) -> Result { + // The shared shape of the ensemble strategies: the primary has read, the secondary joins + // or fails (a failure degrades to the primary, with a note). + let join = |p: Vec, sec: &dyn Recognizer| match sec.recognize(image, options) { + // Over the comparison cap the merge is skipped: the secondary's reading was read but + // is not part of the result, so the outcome says so — primary only, honestly not + // merged, with the skip named. + Ok(s) if over_cap(&p, &s) => { + let (primary_words, secondary_words) = (p.iter().map(|l| l.words.len()).sum::(), s.iter().map(|l| l.words.len()).sum::()); + StrategyOutcome { lines: p, secondary_ran: false, notes: vec![cap_note(sec.id(), primary_words, secondary_words)] } + } + Ok(s) => StrategyOutcome { lines: rover_merge(p, s, sec.id()), secondary_ran: true, notes: Vec::new() }, + Err(e) => StrategyOutcome { lines: p, secondary_ran: false, notes: vec![degraded_note(sec.id(), &e)] }, + }; + match strategy { + MergeStrategy::PrimaryOnly => Ok(StrategyOutcome { lines: primary.recognize(image, options)?, secondary_ran: false, notes: Vec::new() }), + MergeStrategy::RoverVote => match secondary { + None => Ok(StrategyOutcome { lines: primary.recognize(image, options)?, secondary_ran: false, notes: Vec::new() }), + Some(sec) => { + let p = primary.recognize(image, options)?; + Ok(join(p, sec)) + } + }, + MergeStrategy::ConfidenceWeighted => { + let p = primary.recognize(image, options)?; + match mean_confidence(&p) { + // Confident enough — or an empty reading: the primary stands alone. + Some(mean) if mean >= UNKNOWN_CONFIDENCE_BAR => Ok(StrategyOutcome { lines: p, secondary_ran: false, notes: Vec::new() }), + // A weak mean, or an unknown confidence (words, none reported): the secondary + // runs. + _ => match secondary { + None => Ok(StrategyOutcome { lines: p, secondary_ran: false, notes: Vec::new() }), + Some(sec) => Ok(join(p, sec)), + }, + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::atomic::{AtomicUsize, Ordering}; + + /// A fake engine: returns canned lines, counts recognize calls, never available. + struct Fake { + id: &'static str, + lines: Vec, + calls: AtomicUsize, + fail: bool, + } + + impl Fake { + fn new(id: &'static str, words: &[(&str, [f32; 4], f32)]) -> Fake { + Fake { + id, + lines: vec![Line { words: words.iter().map(|(t, r, c)| Word::new(*t, *r, id).with_confidence(*c)).collect() }], + calls: AtomicUsize::new(0), + fail: false, + } + } + + fn empty(id: &'static str) -> Fake { + Fake { id, lines: Vec::new(), calls: AtomicUsize::new(0), fail: false } + } + + /// An engine like ocrs: words, but no confidence reported on any of them. + fn unknown(id: &'static str, n: usize) -> Fake { + Fake { + id, + lines: vec![Line { + words: (0..n).map(|i| Word::new(format!("w{i}"), [i as f32 * 10.0, 0.0, i as f32 * 10.0 + 8.0, 10.0], id)).collect(), + }], + calls: AtomicUsize::new(0), + fail: false, + } + } + } + + impl Recognizer for Fake { + fn id(&self) -> &'static str { + self.id + } + fn available(&self) -> bool { + !self.fail + } + fn languages(&self) -> Vec<(String, String)> { + vec![] + } + fn recognize(&self, _image: &OcrImage, _options: &RecognizeOptions) -> Result, OcrError> { + self.calls.fetch_add(1, Ordering::SeqCst); + if self.fail { + return Err(OcrError::Recognize("the fake engine failed".into())); + } + Ok(self.lines.clone()) + } + } + + fn image() -> OcrImage { + OcrImage::new(4, 4, vec![255; 64]).unwrap() + } + + fn words(lines: &[Line]) -> Vec<&Word> { + lines.iter().flat_map(|l| &l.words).collect() + } + + #[test] + fn iou_of_disjoint_touching_and_nan_boxes_is_zero() { + let a = [0.0, 0.0, 10.0, 10.0]; + assert_eq!(iou(&a, &[20.0, 0.0, 30.0, 10.0]), 0.0, "disjoint"); + assert_eq!(iou(&a, &[10.0, 0.0, 20.0, 10.0]), 0.0, "touching edges are an empty intersection"); + assert_eq!(iou(&a, &[f32::NAN, 0.0, 10.0, 10.0]), 0.0, "NaN boxes score 0, not a panic"); + assert_eq!(iou(&a, &a), 1.0, "identical boxes"); + assert!((iou(&a, &[5.0, 0.0, 15.0, 10.0]) - 1.0 / 3.0).abs() < 1e-9, "half overlap is IoU 1/3"); + } + + /// With nothing on the primary side, every secondary word is appended under the secondary + /// engine's own name. + #[test] + fn rover_appends_everything_when_the_primary_is_empty() { + let primary = Vec::new(); + let secondary = vec![Line { words: vec![Word::new("sole", [0.0, 0.0, 9.0, 9.0], "tesseract").with_confidence(80.0)] }]; + let merged = rover_merge(primary, secondary, "tesseract"); + assert_eq!(words(&merged).len(), 1); + assert_eq!(merged[0].words[0].text, "sole"); + assert_eq!(merged[0].words[0].source, "tesseract", "unclaimed words keep their own engine"); + } + + /// Non-overlapping secondary words never displace primary words; they are appended. + #[test] + fn rover_appends_non_overlapping_secondary_words() { + let primary = vec![Line { words: vec![Word::new("kept", [0.0, 0.0, 10.0, 10.0], "ocrs").with_confidence(50.0)] }]; + let secondary = vec![Line { words: vec![Word::new("extra", [100.0, 100.0, 120.0, 110.0], "tesseract").with_confidence(99.0)] }]; + let merged = rover_merge(primary, secondary, "tesseract"); + let w = words(&merged); + assert_eq!(w.len(), 2); + assert_eq!((w[0].text.as_str(), w[0].source.as_str()), ("kept", "ocrs"), "the more confident but disjoint word does not win"); + assert_eq!((w[1].text.as_str(), w[1].source.as_str()), ("extra", "tesseract")); + } + + /// The higher-confidence word of an overlapping pair wins text, box and confidence, and is + /// named ROVER. + #[test] + fn rover_higher_confidence_wins_and_is_named_rover() { + let primary = vec![Line { words: vec![Word::new("helo", [0.0, 0.0, 10.0, 10.0], "ocrs").with_confidence(60.0)] }]; + let secondary = vec![Line { words: vec![Word::new("hello", [1.0, 0.0, 11.0, 10.0], "tesseract").with_confidence(95.0)] }]; + let merged = rover_merge(primary, secondary, "tesseract"); + let w = words(&merged); + assert_eq!(w.len(), 1, "the secondary word was claimed, not appended"); + assert_eq!(w[0].text, "hello"); + assert_eq!(w[0].rect, [1.0, 0.0, 11.0, 10.0]); + assert_eq!(w[0].confidence, Some(95.0)); + assert_eq!(w[0].source, "ROVER"); + } + + /// A tie keeps the primary word (still named ROVER, as an agreed reading). + #[test] + fn rover_tie_keeps_the_primary() { + let primary = vec![Line { words: vec![Word::new("primary", [0.0, 0.0, 10.0, 10.0], "ocrs").with_confidence(80.0)] }]; + let secondary = vec![Line { words: vec![Word::new("secondary", [0.0, 0.0, 10.0, 10.0], "tesseract").with_confidence(80.0)] }]; + let merged = rover_merge(primary, secondary, "tesseract"); + let w = words(&merged); + assert_eq!(w.len(), 1); + assert_eq!(w[0].text, "primary"); + assert_eq!(w[0].source, "ROVER"); + } + + /// Boxes under the 0.5 IoU bar never merge, even when the secondary is more confident. + #[test] + fn rover_below_half_iou_does_not_merge() { + let primary = vec![Line { words: vec![Word::new("kept", [0.0, 0.0, 10.0, 10.0], "ocrs").with_confidence(50.0)] }]; + // IoU 10·10 / (100 + 169 - 25) = 100/244 ≈ 0.41 < 0.5. + let secondary = vec![Line { words: vec![Word::new("other", [5.0, 0.0, 23.0, 20.0], "tesseract").with_confidence(99.0)] }]; + let merged = rover_merge(primary, secondary, "tesseract"); + let w = words(&merged); + assert_eq!(w.len(), 2); + assert_eq!(w[0].text, "kept"); + assert_eq!(w[0].source, "ocrs"); + } + + /// Merged words keep their line; the merge never panics on NaN boxes. + #[test] + fn rover_survives_nan_boxes() { + let primary = vec![Line { words: vec![Word::new("nan", [f32::NAN, 0.0, 10.0, 10.0], "ocrs").with_confidence(50.0)] }]; + let secondary = vec![Line { words: vec![Word::new("real", [0.0, 0.0, 10.0, 10.0], "tesseract").with_confidence(90.0)] }]; + let merged = rover_merge(primary, secondary, "tesseract"); + let w = words(&merged); + assert_eq!(w.len(), 2, "a NaN primary box merges with nothing"); + assert_eq!(w[0].text, "nan"); + assert_eq!(w[1].text, "real"); + } + + /// Only reported confidences count. An empty reading is Some(100) (nothing to + /// double-check); words without a single confidence are UNKNOWN (`None`), never 100. + #[test] + fn mean_confidence_distinguishes_empty_from_unknown() { + assert_eq!(mean_confidence(&[]), Some(100.0)); + assert_eq!(mean_confidence(&[Line { words: vec![Word::new("a", [0.0; 4], "ocrs")] }]), None, "words, no confidences: unknown"); + let lines = vec![Line { + words: vec![ + Word::new("a", [0.0; 4], "e").with_confidence(40.0), + Word::new("b", [0.0; 4], "e").with_confidence(80.0), + Word::new("c", [0.0; 4], "e"), + ], + }]; + assert_eq!(mean_confidence(&lines), Some(60.0), "reported confidences are averaged"); + } + + /// ROVER's preference needs a meaningful comparison: a known confidence beats an unknown + /// one (the ocrs primary yields to a confident tesseract reading), and None vs None keeps + /// the primary. + #[test] + fn rover_known_confidence_beats_unknown_and_none_vs_none_keeps_the_primary() { + let primary = vec![Line { words: vec![Word::new("helo", [0.0, 0.0, 10.0, 10.0], "ocrs")] }]; + let secondary = vec![Line { words: vec![Word::new("hello", [0.0, 0.0, 10.0, 10.0], "tesseract").with_confidence(95.0)] }]; + let merged = rover_merge(primary, secondary, "tesseract"); + assert_eq!( + (merged[0].words[0].text.as_str(), merged[0].words[0].confidence, merged[0].words[0].source.as_str()), + ("hello", Some(95.0), "ROVER") + ); + let primary = vec![Line { words: vec![Word::new("primary", [0.0, 0.0, 10.0, 10.0], "ocrs")] }]; + let secondary = vec![Line { words: vec![Word::new("secondary", [0.0, 0.0, 10.0, 10.0], "tesseract")] }]; + let merged = rover_merge(primary, secondary, "tesseract"); + assert_eq!( + (merged[0].words[0].text.as_str(), merged[0].words[0].source.as_str()), + ("primary", "ROVER"), + "unknown vs unknown is not a comparison: the primary stands" + ); + } + + /// Over the comparison cap the merge is skipped and the primary reading stands alone (a + /// documented known limit, bounding the merge's quadratic core). + #[test] + fn rover_over_the_comparison_cap_keeps_the_primary() { + // 11 000 × 11 000 = 121 M comparisons > the 100 M cap. + let words = |id: &str| (0..11_000).map(|i| Word::new(format!("w{i}"), [i as f32, 0.0, i as f32 + 5.0, 10.0], id)).collect::>(); + let primary = vec![Line { words: words("ocrs") }]; + let secondary = vec![Line { words: words("tesseract") }]; + let merged = rover_merge(primary, secondary, "tesseract"); + assert_eq!(merged.len(), 1); + assert!(merged[0].words.iter().all(|w| w.source == "ocrs"), "every primary word stands, unmerged"); + assert_eq!(merged[0].words.len(), 11_000); + // Under the cap, merging still happens (a small overlap is replaced and named ROVER). + let small_primary = vec![Line { words: vec![Word::new("kept", [0.0, 0.0, 10.0, 10.0], "ocrs").with_confidence(50.0)] }]; + let small_secondary = vec![Line { words: vec![Word::new("wins", [0.0, 0.0, 10.0, 10.0], "tesseract").with_confidence(95.0)] }]; + let merged = rover_merge(small_primary, small_secondary, "tesseract"); + assert_eq!((merged[0].words[0].text.as_str(), merged[0].words[0].source.as_str()), ("wins", "ROVER")); + } + + /// Over the comparison cap the merge is skipped honestly at the strategy level: the page + /// keeps the primary reading alone, the skip is named in a note, and `secondary_ran` does + /// not claim the discarded reading is part of the result (though the secondary really did + /// run — its work was spent, its reading unused). + #[test] + fn rover_cap_hit_reports_primary_only_with_a_note_and_an_honest_flag() { + let mut primary = Fake::empty("ocrs"); + primary.lines = + vec![Line { words: (0..11_000).map(|i| Word::new(format!("w{i}"), [i as f32, 0.0, i as f32 + 5.0, 10.0], "ocrs")).collect() }]; + let mut secondary = Fake::empty("tesseract"); + secondary.lines = + vec![Line { words: (0..11_000).map(|i| Word::new(format!("w{i}"), [i as f32, 0.0, i as f32 + 5.0, 10.0], "tesseract")).collect() }]; + let outcome = recognize_with_strategy(&primary, Some(&secondary), MergeStrategy::RoverVote, &image(), &RecognizeOptions::default()).unwrap(); + assert_eq!(secondary.calls.load(Ordering::SeqCst), 1, "the secondary really ran"); + assert_eq!(outcome.lines.len(), 1); + assert_eq!(outcome.lines[0].words.len(), 11_000, "primary only"); + assert!(outcome.lines[0].words.iter().all(|w| w.source == "ocrs"), "every primary word stands, unmerged"); + assert!(!outcome.secondary_ran, "the secondary's reading is not part of the result"); + assert_eq!(outcome.notes.len(), 1, "{:?}", outcome.notes); + assert!(outcome.notes[0].contains("merge"), "{:?}", outcome.notes[0]); + assert!(outcome.notes[0].contains("tesseract"), "{:?}", outcome.notes[0]); + // Under the cap the same strategy merges and reports the secondary honestly. + let primary = Fake::new("ocrs", &[("kept", [0.0, 0.0, 10.0, 10.0], 50.0)]); + let secondary = Fake::new("tesseract", &[("wins", [0.0, 0.0, 10.0, 10.0], 95.0)]); + let outcome = recognize_with_strategy(&primary, Some(&secondary), MergeStrategy::RoverVote, &image(), &RecognizeOptions::default()).unwrap(); + assert!(outcome.secondary_ran && outcome.notes.is_empty()); + assert_eq!((outcome.lines[0].words[0].text.as_str(), outcome.lines[0].words[0].source.as_str()), ("wins", "ROVER")); + } + + #[test] + fn primary_only_never_runs_the_secondary() { + let primary = Fake::new("ocrs", &[("w", [0.0; 4], 90.0)]); + let secondary = Fake::empty("tesseract"); + let outcome = + recognize_with_strategy(&primary, Some(&secondary), MergeStrategy::PrimaryOnly, &image(), &RecognizeOptions::default()).unwrap(); + assert_eq!(primary.calls.load(Ordering::SeqCst), 1); + assert_eq!(secondary.calls.load(Ordering::SeqCst), 0); + assert!(!outcome.secondary_ran); + assert!(outcome.notes.is_empty()); + assert_eq!(words(&outcome.lines).len(), 1); + } + + #[test] + fn confidence_weighted_runs_the_secondary_only_on_a_weak_primary() { + let weak = Fake::new("ocrs", &[("w", [0.0; 4], 40.0)]); + let strong = Fake::new("ocrs", &[("w", [0.0; 4], 95.0)]); + let secondary = Fake::empty("tesseract"); + let outcome = + recognize_with_strategy(&weak, Some(&secondary), MergeStrategy::ConfidenceWeighted, &image(), &RecognizeOptions::default()).unwrap(); + assert!(outcome.secondary_ran, "mean 40 < 70 → the secondary joins"); + let outcome = + recognize_with_strategy(&strong, Some(&secondary), MergeStrategy::ConfidenceWeighted, &image(), &RecognizeOptions::default()).unwrap(); + assert!(!outcome.secondary_ran, "mean 95 >= 70 → primary alone"); + // An empty primary counts as 100: no signal, no secondary run. + let empty = Fake::empty("ocrs"); + let outcome = + recognize_with_strategy(&empty, Some(&secondary), MergeStrategy::ConfidenceWeighted, &image(), &RecognizeOptions::default()).unwrap(); + assert!(!outcome.secondary_ran); + assert_eq!(secondary.calls.load(Ordering::SeqCst), 1, "only the weak page ran the secondary"); + } + + /// The ocrs engine reports no confidences: unknown is not 100, so the secondary runs — + /// and its known reading wins the overlapping word (the ensemble's whole point). + #[test] + fn confidence_weighted_runs_the_secondary_on_an_unknown_primary() { + let ocrs_like = Fake::unknown("ocrs", 1); + let secondary = Fake::new("tesseract", &[("hello", [0.0, 0.0, 10.0, 10.0], 95.0)]); + let outcome = + recognize_with_strategy(&ocrs_like, Some(&secondary), MergeStrategy::ConfidenceWeighted, &image(), &RecognizeOptions::default()).unwrap(); + assert!(outcome.secondary_ran, "an unknown confidence asks the secondary"); + assert_eq!((outcome.lines[0].words[0].text.as_str(), outcome.lines[0].words[0].confidence), ("hello", Some(95.0))); + assert_eq!(outcome.lines[0].words[0].source, "ROVER"); + assert_eq!(secondary.calls.load(Ordering::SeqCst), 1); + } + + /// Against a primary word of unknown confidence, a secondary word wins only when it is + /// confident (at or above the weak-reading bar): a 5% reading does not replace a word nobody + /// scored, a 70% one does. The merged word is named ROVER either way. + #[test] + fn an_unknown_primary_word_yields_only_to_a_confident_secondary() { + let merge = |conf: f32| { + let secondary = vec![Line { words: vec![Word::new("other", [0.0, 0.0, 10.0, 10.0], "tesseract").with_confidence(conf)] }]; + let primary = Fake::unknown("ocrs", 1).lines; + rover_merge(primary, secondary, "tesseract").remove(0).words.remove(0) + }; + let weak = merge(5.0); + assert_eq!((weak.text.as_str(), weak.confidence, weak.source.as_str()), ("w0", None, "ROVER"), "a 5% word keeps the primary"); + let below = merge(UNKNOWN_CONFIDENCE_BAR - 0.5); + assert_eq!(below.text, "w0"); + let at_bar = merge(UNKNOWN_CONFIDENCE_BAR); + assert_eq!((at_bar.text.as_str(), at_bar.confidence), ("other", Some(UNKNOWN_CONFIDENCE_BAR)), "a confident word wins"); + let nan = merge(f32::NAN); + assert_eq!(nan.text, "w0", "NaN (unknown after clamping) never wins"); + } + + #[test] + fn rover_vote_always_runs_both_and_degrades_without_a_secondary() { + let primary = Fake::new("ocrs", &[("w", [0.0; 4], 95.0)]); + let secondary = Fake::empty("tesseract"); + let outcome = recognize_with_strategy(&primary, Some(&secondary), MergeStrategy::RoverVote, &image(), &RecognizeOptions::default()).unwrap(); + assert!(outcome.secondary_ran); + assert_eq!(secondary.calls.load(Ordering::SeqCst), 1); + // No secondary: primary only. + let outcome = recognize_with_strategy(&primary, None, MergeStrategy::RoverVote, &image(), &RecognizeOptions::default()).unwrap(); + assert!(!outcome.secondary_ran); + } + + /// A configured secondary that fails degrades to the primary reading, with the failure + /// recorded as a note — never a skipped page, never a silently partial reading without a + /// trace. Both ensemble strategies degrade; a primary failure is still an error. + #[test] + fn a_failing_secondary_degrades_to_the_primary_with_a_note() { + let mut secondary = Fake::empty("tesseract"); + secondary.fail = true; + let primary = Fake::new("ocrs", &[("w", [0.0; 4], 95.0)]); + let outcome = recognize_with_strategy(&primary, Some(&secondary), MergeStrategy::RoverVote, &image(), &RecognizeOptions::default()).unwrap(); + assert_eq!(words(&outcome.lines).len(), 1, "the primary reading stands"); + assert_eq!(outcome.lines[0].words[0].text, "w"); + assert!(!outcome.secondary_ran); + assert_eq!(outcome.notes.len(), 1); + assert!(outcome.notes[0].contains("tesseract"), "{:?}", outcome.notes[0]); + // The confidence-weighted strategy degrades the same way on its weak path. + let weak = Fake::new("ocrs", &[("w", [0.0; 4], 40.0)]); + let outcome = + recognize_with_strategy(&weak, Some(&secondary), MergeStrategy::ConfidenceWeighted, &image(), &RecognizeOptions::default()).unwrap(); + assert_eq!(words(&outcome.lines).len(), 1); + assert_eq!(outcome.notes.len(), 1, "{:?}", outcome.notes); + // A failing primary is still an error: there is nothing to degrade to. + let mut failing_primary = Fake::new("ocrs", &[("w", [0.0; 4], 95.0)]); + failing_primary.fail = true; + let r = recognize_with_strategy(&failing_primary, Some(&secondary), MergeStrategy::RoverVote, &image(), &RecognizeOptions::default()); + assert!(r.is_err()); + } +} diff --git a/crates/ocr/src/ocrs.rs b/crates/ocr/src/ocrs.rs new file mode 100644 index 0000000000..7f8feb47c4 --- /dev/null +++ b/crates/ocr/src/ocrs.rs @@ -0,0 +1,251 @@ +//! The pure-Rust engine: the ocrs crate with its pre-trained models, wrapped as a +//! [`Recognizer`] (`OcrsRecognizer`). Reading is offline and local; the models do not report a +//! confidence, so its words have `confidence: None`. + +use std::path::{Path, PathBuf}; + +use super::{Line, MAX_PIXELS, MAX_SIDE, OcrError, OcrImage, RecognizeOptions, Recognizer, Word}; + +/// The validated byte length of a `width` × `height` RGBA raster, with the same caps +/// [`OcrImage::new`] applies: zero sides are empty, sides over [`MAX_SIDE`] or totals over +/// [`MAX_PIXELS`] are too large. `Ocr::recognize` takes raw dimensions (they come from +/// callers, ultimately from documents, so they are untrusted), and the naive +/// `width * height * 4` overflows `u32` for absurd values — the caps are checked first, in +/// `usize`, so nothing overflows and nothing huge is ever touched. +fn checked_len(width: u32, height: u32) -> Result { + if width == 0 || height == 0 { + return Err(OcrError::EmptyImage); + } + if width > MAX_SIDE || height > MAX_SIDE { + return Err(OcrError::ImageTooLarge); + } + let pixels = (width as usize).checked_mul(height as usize).ok_or(OcrError::ImageTooLarge)?; + if pixels > MAX_PIXELS as usize { + return Err(OcrError::ImageTooLarge); + } + pixels.checked_mul(4).ok_or(OcrError::ImageTooLarge) +} + +/// The languages the models read (ISO 639-1); all use the Latin alphabet without accents. +pub const LANGUAGES: &[(&str, &str)] = &[("en", "English")]; + +/// The model files, as named in ATTRIBUTION.toml. +pub const DETECTION_MODEL: &str = "text-detection.onnx"; +pub const RECOGNITION_MODEL: &str = "text-recognition.onnx"; + +pub const ALPHABET: &str = " 0123456789!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~€ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; + +/// Where the two model files are. +#[derive(Clone, Debug, PartialEq)] +pub struct Models { + pub detection: PathBuf, + pub recognition: PathBuf, +} + +impl Models { + pub fn dirs_beside_exe(exe_dir: &Path) -> Vec { + vec![exe_dir.join("models"), exe_dir.join("../Resources/models"), exe_dir.join("../share/pdfcraft/models")] + } + + /// The models in `dir`, preferring current ONNX files over legacy RTEN files. An incomplete + /// update never mixes formats or hides an intact legacy pair. + pub fn in_dir(dir: &Path) -> Option { + [(DETECTION_MODEL, RECOGNITION_MODEL), ("text-detection.rten", "text-recognition.rten")].into_iter().find_map(|(detection, recognition)| { + let m = Models { detection: dir.join(detection), recognition: dir.join(recognition) }; + (m.detection.is_file() && m.recognition.is_file()).then_some(m) + }) + } + + /// Look for the models: `$PDFCRAFT_MODELS`, then `models/` beside the executable (and + /// `Resources/models` in a macOS bundle), then the source tree's `assets/models/`. + pub fn find() -> Option { + Self::search_dirs().iter().find_map(|d| Self::in_dir(d)) + } + + /// The directories [`Models::find`] looks in, in order. + pub fn search_dirs() -> Vec { + let mut dirs = Vec::new(); + if let Some(d) = std::env::var_os("PDFCRAFT_MODELS") { + dirs.push(PathBuf::from(d)); + } + if let Some(exe) = std::env::current_exe().ok().and_then(|e| e.parent().map(Path::to_path_buf)) { + dirs.extend(Self::dirs_beside_exe(&exe)); + } + dirs.push(Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets/models")); + dirs + } +} + +/// A loaded recogniser. Loading takes a moment; keep one and reuse it. +pub struct Ocr { + engine: ocrs::OcrEngine, +} + +impl Ocr { + pub fn load(models: &Models) -> Result { + let load = |p: &Path| rten::Model::load_file(p).map_err(|e| OcrError::Load(p.display().to_string(), e.to_string())); + let params = ocrs::OcrEngineParams { + detection_model: Some(load(&models.detection)?), + recognition_model: Some(load(&models.recognition)?), + alphabet: Some(ALPHABET.into()), + ..Default::default() + }; + let engine = ocrs::OcrEngine::new(params).map_err(|e| OcrError::Load("ocr engine".into(), e.to_string()))?; + Ok(Ocr { engine }) + } + + /// Load the models found by [`Models::find`]. + pub fn find() -> Result { + Self::load(&Models::find().ok_or(OcrError::NoModels)?) + } + + /// Recognise the text in an RGBA (or RGB, or grey) image, `width` × `height` pixels. + pub fn recognize(&self, pixels: &[u8], width: u32, height: u32) -> Result, OcrError> { + if pixels.is_empty() { + return Err(OcrError::EmptyImage); + } + let want = checked_len(width, height)?; + // ocrs wants 1 or 3 channels. + let rgb: std::borrow::Cow<[u8]> = if pixels.len() == want { + pixels.as_chunks::<4>().0.iter().flat_map(|p| [p[0], p[1], p[2]]).collect::>().into() + } else { + pixels.into() + }; + let err = |e: &dyn std::fmt::Display| OcrError::Recognize(e.to_string()); + let source = ocrs::ImageSource::from_bytes(&rgb, (width, height)).map_err(|e| err(&e))?; + let input = self.engine.prepare_input(source).map_err(|e| err(&e))?; + let found = self.engine.detect_words(&input).map_err(|e| err(&e))?; + let lines = self.engine.find_text_lines(&input, &found); + let read = self.engine.recognize_text(&input, &lines).map_err(|e| err(&e))?; + use ocrs::TextItem; + Ok(read + .into_iter() + .flatten() + .map(|line| Line { + words: line + .words() + .map(|w| { + let r = w.bounding_rect(); + Word::new(w.to_string(), [r.left() as f32, r.top() as f32, r.right() as f32, r.bottom() as f32], "ocrs") + }) + .filter(|w| !w.text.trim().is_empty()) + .collect(), + }) + .filter(|l| !l.words.is_empty()) + .collect()) + } +} + +/// The ocrs engine as a [`Recognizer`] (the default engine). +pub struct OcrsRecognizer { + engine: Ocr, +} + +impl OcrsRecognizer { + /// Load the models from `models`. + pub fn load(models: &Models) -> Result { + Ok(OcrsRecognizer { engine: Ocr::load(models)? }) + } + + /// Load the models found by [`Models::find`]. + pub fn find() -> Result { + Self::load(&Models::find().ok_or(OcrError::NoModels)?) + } +} + +impl Recognizer for OcrsRecognizer { + fn id(&self) -> &'static str { + "ocrs" + } + + fn available(&self) -> bool { + Models::find().is_some() + } + + fn languages(&self) -> Vec<(String, String)> { + LANGUAGES.iter().map(|(c, n)| ((*c).to_string(), (*n).to_string())).collect() + } + + fn recognize(&self, image: &OcrImage, _options: &RecognizeOptions) -> Result, OcrError> { + self.engine.recognize(image.rgba(), image.width(), image.height()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Raw dimensions are untrusted (they come from callers, ultimately from documents): zero + /// sides, sides or pixel totals over the caps, and products that would overflow the naive + /// `width * height * 4` are errors, never panics, before anything is touched. + #[test] + fn raw_dimensions_are_capped_and_checked_not_panicked_at() { + assert!(matches!(checked_len(0, 10), Err(OcrError::EmptyImage))); + assert!(matches!(checked_len(10, 0), Err(OcrError::EmptyImage))); + assert!(matches!(checked_len(MAX_SIDE + 1, 1), Err(OcrError::ImageTooLarge))); + // 65536² would wrap u32 in the old `width * height * 4`; the side cap refuses it first. + assert!(matches!(checked_len(u32::MAX, u32::MAX), Err(OcrError::ImageTooLarge))); + // Legal sides whose product is over the 64 MP area cap. + assert!(matches!(checked_len(MAX_SIDE, 7000), Err(OcrError::ImageTooLarge))); + assert_eq!(checked_len(2, 2).unwrap(), 16); + // Exactly the area cap fits: 8000 × 8000 = 64 MP. + assert_eq!(checked_len(8000, 8000).unwrap(), 8000usize * 8000 * 4); + } + + /// The current ONNX pair wins when an installation also retains both legacy models. + #[test] + fn model_discovery_prefers_the_complete_onnx_pair() { + let dir = tempfile::tempdir().unwrap(); + for file in ["text-detection.onnx", "text-recognition.onnx"] { + std::fs::write(dir.path().join(file), b"model").unwrap(); + } + let expected = Some(Models { detection: dir.path().join("text-detection.onnx"), recognition: dir.path().join("text-recognition.onnx") }); + assert_eq!(Models::in_dir(dir.path()), expected, "a complete ONNX pair is sufficient"); + for file in ["text-detection.rten", "text-recognition.rten"] { + std::fs::write(dir.path().join(file), b"model").unwrap(); + } + assert_eq!(Models::in_dir(dir.path()), expected, "the complete ONNX pair takes precedence over legacy models"); + } + + /// An interrupted ONNX update still permits an intact legacy pair in the same directory. + #[test] + fn model_discovery_falls_back_to_legacy_when_the_onnx_pair_is_incomplete() { + for current in ["text-detection.onnx", "text-recognition.onnx"] { + let dir = tempfile::tempdir().unwrap(); + for file in [current, "text-detection.rten", "text-recognition.rten"] { + std::fs::write(dir.path().join(file), b"model").unwrap(); + } + assert_eq!( + Models::in_dir(dir.path()), + Some(Models { detection: dir.path().join("text-detection.rten"), recognition: dir.path().join("text-recognition.rten") }), + "{current} alone must not hide a complete legacy pair" + ); + } + } + + /// Detection and recognition must come from one complete format pair, never a mixed update. + #[test] + fn model_discovery_refuses_mixed_format_pairs() { + for pair in [["text-detection.onnx", "text-recognition.rten"], ["text-detection.rten", "text-recognition.onnx"]] { + let dir = tempfile::tempdir().unwrap(); + for file in pair { + std::fs::write(dir.path().join(file), b"model").unwrap(); + } + assert_eq!(Models::in_dir(dir.path()), None, "{pair:?} is not a complete model pair"); + } + } + + /// Existing source builds and PDFCRAFT_MODELS overrides retain their complete RTEN pair. + #[test] + fn model_discovery_keeps_legacy_only_installations() { + let dir = tempfile::tempdir().unwrap(); + assert_eq!(Models::in_dir(dir.path()), None); + std::fs::write(dir.path().join("text-detection.rten"), b"model").unwrap(); + assert_eq!(Models::in_dir(dir.path()), None, "one legacy model is incomplete"); + std::fs::write(dir.path().join("text-recognition.rten"), b"model").unwrap(); + assert_eq!( + Models::in_dir(dir.path()), + Some(Models { detection: dir.path().join("text-detection.rten"), recognition: dir.path().join("text-recognition.rten") }) + ); + } +} diff --git a/crates/ocr/src/preprocess.rs b/crates/ocr/src/preprocess.rs new file mode 100644 index 0000000000..280ee73fec --- /dev/null +++ b/crates/ocr/src/preprocess.rs @@ -0,0 +1,973 @@ +//! Preprocessing: a pure function between the page raster and recognition, in fixed order — +//! (a) DPI normalization, then the four opt-in steps (b) orientation, (c) deskew, (d) denoise, +//! (e) binarization. Normalization exists for those steps (their windows and thresholds are +//! calibrated for 300 dpi), so it runs only when at least one of them is on: with every step +//! off the raster is handed to the engines exactly as it was rendered. (Enlarging a render +//! on its own changes what the models read: a 72 dpi scan of "due: €250" read as "ue: ?250" +//! after a 4× bilinear enlargement.) Everything is plain Rust on the RGBA raster: no +//! Leptonica, no process, no new dependencies. +//! +//! Every geometric step records its inverse; the result carries one exact +//! [`InverseTransform`] (an affine map, composed in f64), and callers map every word box +//! through it back to the *original* raster coordinates before placing the words. +//! +//! The heuristics are deliberately conservative and panic-free: an image too small to judge, +//! a blank page, or a score without a clear margin is a no-op, never a guess. + +use crate::{MAX_PIXELS, MAX_SIDE, OcrError, OcrImage}; + +/// The four opt-in steps. All off by default: a scan is passed through as rendered. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct PreprocessOptions { + /// Detect pages scanned at 90°/180°/270° and turn them upright. + pub auto_rotate: bool, + /// Straighten skewed text lines. + pub deskew: bool, + /// 3×3 median filter (salt-and-pepper noise). + pub denoise: bool, + /// Sauvola binarization (window 8, k 0.34). + pub binarize: bool, +} + +impl PreprocessOptions { + /// Whether any step is on (and so the raster is normalized to 300 dpi first). + pub fn any(&self) -> bool { + self.auto_rotate || self.deskew || self.denoise || self.binarize + } +} + +/// A preprocessed raster: the image to recognize, the exact way back to the input raster, and +/// the resolution the image now stands for. +#[derive(Debug)] +pub struct Preprocessed { + pub image: OcrImage, + /// Maps pixel coordinates in [`Preprocessed::image`] back to the input raster's. + pub inverse_transform: InverseTransform, + /// The image's resolution in dots per inch: 300 after normalization (only when a step is + /// on), or the source's own + /// when it already rendered at 300 or more. + pub dpi: f32, +} + +/// Preprocess `image` (rendered at `source_dpi`) per `options`, in the fixed order. The image +/// is consumed: the common path (every step off, or a no-op) hands the raster back without +/// copying it, and a step that rewrites pixels replaces it. +pub fn preprocess(image: OcrImage, source_dpi: f32, options: &PreprocessOptions) -> Result { + let mut current = image; + let mut inverse = InverseTransform::identity(); + // (a) DPI normalization: for the steps below, a scan under 300 dpi is enlarged by 300/src so + // they see letter-sized strokes. With every step off nothing is resampled. A broken dpi + // (zero, negative, NaN) is left alone. + let mut dpi = if source_dpi.is_finite() && source_dpi >= 1.0 { source_dpi } else { 300.0 }; + if options.any() && dpi < 300.0 { + let scale = f64::from(300.0 / dpi); + current = resize_bilinear(¤t, scale)?; + inverse = compose(&inverse, &InverseTransform::scale(1.0 / scale)); + dpi = 300.0; + } + // (b) Orientation: turn 90/180/270 scans upright (opt-in, skipped for small images). + if options.auto_rotate { + let (w, h) = (current.width, current.height); + let turns = detect_orientation(¤t); + if turns != 0 { + current = rotate_quarter_turns(¤t, turns); + inverse = compose(&inverse, &inverse_quarter_turns(turns, w, h)); + } + } + // (c) Deskew: straighten skewed lines (opt-in; no-op under 64 px, blank, or without a + // clear margin or below 0.1°). + if options.deskew + && let Some(angle) = estimate_skew(¤t) + { + let (straightened, back) = deskew_rotate(¤t, angle); + current = straightened; + inverse = compose(&inverse, &back); + } + // (d) Denoise: 3×3 median with edge clamping (opt-in; dimensions never change). + if options.denoise { + current = median3(¤t); + } + // (e) Binarize: Sauvola (window 8, k 0.34) via an integral image (opt-in); dark ink stays + // dark and paper stays light. + if options.binarize { + current = sauvola(¤t); + } + Ok(Preprocessed { image: current, inverse_transform: inverse, dpi }) +} + +/// An affine map `(x, y) → (a·x + c·y + e, b·x + d·y + f)`, composed in f64 so mapping a +/// word box back is exact up to float rounding. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct InverseTransform { + a: f64, + b: f64, + c: f64, + d: f64, + e: f64, + f: f64, +} + +impl InverseTransform { + pub fn identity() -> InverseTransform { + InverseTransform { a: 1.0, b: 0.0, c: 0.0, d: 1.0, e: 0.0, f: 0.0 } + } + + fn scale(s: f64) -> InverseTransform { + InverseTransform { a: s, b: 0.0, c: 0.0, d: s, e: 0.0, f: 0.0 } + } + + /// `compose(outer, inner)` maps `p` to `outer(inner(p))`: the accumulated inverse of the + /// earlier steps is the outer map (their spaces come later in the round trip), so each + /// step calls `compose(&inverse, &this_step_inverse)`. The scale step, for instance, + /// happens first, so its inverse is applied last: `scale⁻¹(rotate⁻¹(p))`. + fn compose_(outer: &InverseTransform, inner: &InverseTransform) -> InverseTransform { + InverseTransform { + a: outer.a * inner.a + outer.c * inner.b, + b: outer.b * inner.a + outer.d * inner.b, + c: outer.a * inner.c + outer.c * inner.d, + d: outer.b * inner.c + outer.d * inner.d, + e: outer.a * inner.e + outer.c * inner.f + outer.e, + f: outer.b * inner.e + outer.d * inner.f + outer.f, + } + } + + /// Map a point from the processed image back to the input raster. + pub fn apply(&self, x: f64, y: f64) -> (f64, f64) { + (self.a * x + self.c * y + self.e, self.b * x + self.d * y + self.f) + } + + /// Map a word box `[left, top, right, bottom]` back to the input raster: the four corners + /// go through [`Self::apply`] and their bounding box is rounded outward to whole pixels. + /// A box with no finite corners comes back unchanged (garbage in, garbage out — never a + /// panic). + pub fn map_rect(&self, rect: [f32; 4]) -> [f32; 4] { + let corners = [(rect[0], rect[1]), (rect[2], rect[1]), (rect[0], rect[3]), (rect[2], rect[3])]; + let mut lo = (f64::INFINITY, f64::INFINITY); + let mut hi = (f64::NEG_INFINITY, f64::NEG_INFINITY); + let mut finite = false; + for (x, y) in corners { + if !(x.is_finite() && y.is_finite()) { + continue; + } + let (mx, my) = self.apply(f64::from(x), f64::from(y)); + if mx.is_finite() && my.is_finite() { + finite = true; + lo = (lo.0.min(mx), lo.1.min(my)); + hi = (hi.0.max(mx), hi.1.max(my)); + } + } + if !finite { + return rect; + } + [lo.0.floor() as f32, lo.1.floor() as f32, hi.0.ceil() as f32, hi.1.ceil() as f32] + } +} + +/// The step inverses compose in pipeline order: each new step's inverse is applied *after* +/// the inverses accumulated so far. +fn compose(outer: &InverseTransform, inner: &InverseTransform) -> InverseTransform { + InverseTransform::compose_(outer, inner) +} + +/// The size `width` x `height` becomes under `scale`, refused (before any buffer exists) when +/// a side is under one pixel or over [`MAX_SIDE`], or the area is over [`MAX_PIXELS`]: two +/// sides under the side cap can still ask for hundreds of megabytes, which `OcrImage::new` +/// would only refuse after they were allocated. +fn scaled_size(width: u32, height: u32, scale: f64) -> Result<(u32, u32), OcrError> { + let new_w = (f64::from(width) * scale).ceil(); + let new_h = (f64::from(height) * scale).ceil(); + if !(1.0..=f64::from(MAX_SIDE)).contains(&new_w) || !(1.0..=f64::from(MAX_SIDE)).contains(&new_h) { + return Err(OcrError::ImageTooLarge); + } + let (nw, nh) = (new_w as u32, new_h as u32); + if (nw as usize).checked_mul(nh as usize).is_none_or(|pixels| pixels > MAX_PIXELS as usize) { + return Err(OcrError::ImageTooLarge); + } + Ok((nw, nh)) +} + +/// Bilinear resize by `scale`, clamped at the edges; the result stays inside [`scaled_size`]'s +/// limits (the side cap and the area cap). +fn resize_bilinear(image: &OcrImage, scale: f64) -> Result { + let (nw, nh) = scaled_size(image.width, image.height, scale)?; + let mut out = vec![255u8; (nw as usize).checked_mul(nh as usize).and_then(|p| p.checked_mul(4)).ok_or(OcrError::ImageTooLarge)?]; + for (y, row) in out.chunks_exact_mut(4 * nw as usize).enumerate() { + for (x, px) in row.as_chunks_mut::<4>().0.iter_mut().enumerate() { + // The source position of the destination pixel's centre, and the four + // neighbours bilinear interpolation blends (positions clamp at the edges). + let sx = (x as f64 + 0.5) / scale - 0.5; + let sy = (y as f64 + 0.5) / scale - 0.5; + let (x0, y0) = (sx.floor().max(0.0), sy.floor().max(0.0)); + let (fx, fy) = (sx - x0, sy - y0); + for (ch, o) in px.iter_mut().enumerate() { + let blend = |dx: f64, dy: f64| f64::from(image.byte(x0 + dx, y0 + dy, ch)); + let v = blend(0.0, 0.0) * (1.0 - fx) * (1.0 - fy) + + blend(1.0, 0.0) * fx * (1.0 - fy) + + blend(0.0, 1.0) * (1.0 - fx) * fy + + blend(1.0, 1.0) * fx * fy; + *o = v.round().clamp(0.0, 255.0) as u8; + } + } + } + OcrImage::new(nw, nh, out) +} + +/// Grayscale (Rec.601 luma) of every pixel. +fn grayscale(image: &OcrImage) -> Vec { + image.rgba.as_chunks::<4>().0.iter().map(|p| ((299 * p[0] as u32 + 587 * p[1] as u32 + 114 * p[2] as u32) / 1000).min(255) as u8).collect() +} + +/// How the page must be turned (quarter turns, clockwise) to read upright. +type QuarterTurns = u32; + +/// Detect the correction for pages scanned sideways or upside down. Method (documented, +/// panic-free, no OCR): ink is everything darker than the midpoint between the darkest and +/// lightest pixel; for each candidate correction (0/90/180/270 clockwise) the ink's row +/// profile is taken and scored by how sharply it bands (Σ Δ², the projection-profile score: +/// upright text lines band sharply, turned text does not). The best-banding axis wins when it +/// beats the other axis by a factor of 1.3; within the winning axis the line bands' +/// bottom-heaviness (real text carries more ink below each line's middle — baselines and +/// descenders) picks the quarter turn, with a 4%-of-ink margin. Anything less clear is a +/// no-op (`0`), and images under 32 px are never judged. +fn detect_orientation(image: &OcrImage) -> QuarterTurns { + if image.min_side() < 32 { + return 0; + } + let gray = grayscale(image); + let (Some(lo), Some(hi)) = (gray.iter().min(), gray.iter().max()) else { return 0 }; + let t = (*lo as u32 + *hi as u32) / 2; + let ink: Vec = gray.iter().map(|&g| (g as u32) < t).collect(); + let (w, h) = (image.width as usize, image.height as usize); + let total: u64 = ink.iter().filter(|i| **i).count() as u64; + if total == 0 { + return 0; + } + // The ink grid rotated by k quarter turns (clockwise), as row profiles. + let mut scores = [0.0f64; 4]; + let mut asyms = [0.0f64; 4]; + for k in 0u32..4 { + let k = k as usize; + let profile = rotated_row_profile(&ink, w, h, k as u32); + scores[k] = profile.windows(2).map(|p| (p[1] as f64 - p[0] as f64).powi(2)).sum(); + asyms[k] = band_bottom_heaviness(&profile); + } + // 0 and 180 share one profile shape (reversed), as do 90 and 270: pick the axis first. + let (vertical_pair, horizontal_pair) = ((scores[0], scores[2]), (scores[1], scores[3])); + let row_axis = vertical_pair.0.max(vertical_pair.1); + let column_axis = horizontal_pair.0.max(horizontal_pair.1); + if row_axis >= column_axis { + if row_axis < column_axis * 1.3 { + return 0; // the axes are too close to call + } + if asyms[0] > 0.15 * total as f64 { + 0 + } else if asyms[2] > 0.15 * total as f64 { + 2 + } else { + 0 // the bands are not clearly bottom-heavy either way: no-op + } + } else { + if column_axis < row_axis * 1.3 { + return 0; + } + if asyms[1] > 0.15 * total as f64 { + 1 + } else if asyms[3] > 0.15 * total as f64 { + 3 + } else { + 0 + } + } +} + +/// The row profile of the ink grid after `k` quarter turns clockwise. +fn rotated_row_profile(ink: &[bool], w: usize, h: usize, k: u32) -> Vec { + // The rotated image is `w` pixels tall for odd k and `h` for even k; its row index is + // always the new y of the source pixel. + let len = if k.is_multiple_of(2) { h } else { w }; + let mut profile = vec![0u64; len]; + for (y, row) in ink.chunks_exact(w).enumerate() { + for (x, on) in row.iter().enumerate() { + if !on { + continue; + } + // Where does (x, y) land after k quarter turns clockwise? + let ny = match k { + 1 => x, + 2 => h - 1 - y, + 3 => w - 1 - x, + _ => y, + }; + if let Some(p) = profile.get_mut(ny) { + *p += 1; + } + } + } + profile +} + +/// Sum over text-line bands of (ink in the band's lower half − ink in its upper half): +/// positive when the bands carry more ink near their bottoms, as real text does. +fn band_bottom_heaviness(profile: &[u64]) -> f64 { + let mut asym = 0.0; + let mut start: Option = None; + for (i, &p) in profile.iter().chain(std::iter::once(&0)).enumerate() { + match (start, p > 0) { + (None, true) => start = Some(i), + (Some(s), false) => { + let mid = (s + i) / 2; + let lower: u64 = profile.get(s..i).map_or(0, |b| b[mid.saturating_sub(s)..].iter().sum()); + let upper: u64 = profile.get(s..i).map_or(0, |b| b[..mid.saturating_sub(s)].iter().sum()); + asym += lower as f64 - upper as f64; // signed: a top-heavy band scores below zero + start = None; + } + _ => {} + } + } + asym +} + +/// Rotate the raster `k` quarter turns clockwise (an exact pixel permutation). +fn rotate_quarter_turns(image: &OcrImage, k: QuarterTurns) -> OcrImage { + let (w, h) = (image.width as usize, image.height as usize); + let (nw, nh) = if k.is_multiple_of(2) { (image.width, image.height) } else { (image.height, image.width) }; + let mut out = vec![255u8; nw as usize * nh as usize * 4]; + for (y, row) in image.rgba.chunks_exact(w * 4).enumerate() { + for (x, px) in row.as_chunks::<4>().0.iter().enumerate() { + let (nx, ny) = match k { + 1 => (h - 1 - y, x), + 2 => (w - 1 - x, h - 1 - y), + 3 => (y, w - 1 - x), + _ => (x, y), + }; + if let Some(dst) = out.get_mut((ny * nw as usize + nx) * 4..(ny * nw as usize + nx) * 4 + 4) { + dst.copy_from_slice(px); + } + } + } + OcrImage::new(nw, nh, out).unwrap_or_else(|_| image.clone()) +} + +/// The inverse of a `k`-quarter-turn correction: where each corrected pixel came from. +fn inverse_quarter_turns(k: QuarterTurns, old_w: u32, old_h: u32) -> InverseTransform { + let (w, h) = (f64::from(old_w), f64::from(old_h)); + match k { + // Forward (content moves): (x, y) ↦ (h−1−y, x) for one turn clockwise. + 1 => InverseTransform { a: 0.0, b: -1.0, c: 1.0, d: 0.0, e: 0.0, f: h - 1.0 }, + 2 => InverseTransform { a: -1.0, b: 0.0, c: 0.0, d: -1.0, e: w - 1.0, f: h - 1.0 }, + 3 => InverseTransform { a: 0.0, b: 1.0, c: -1.0, d: 0.0, e: w - 1.0, f: 0.0 }, + _ => InverseTransform::identity(), + } +} + +/// Estimate the skew of the text lines, in degrees (−5…5, positive: lines run downhill to the +/// right). Method (documented, panic-free): for each candidate angle the ink is sheared into a +/// row profile (`r = y − (x − cx)·tan φ`); the projection-profile score (Σ profile²) peaks +/// where the shear realigns the lines. `None` — leave the page alone — when the image is under +/// 64 px on a side, blank, the winner is under 0.1°, or the winner does not clearly beat +/// leaving the page as is (score < 1.02 × the 0° score). +fn estimate_skew(image: &OcrImage) -> Option { + if image.min_side() < 64 { + return None; + } + let gray = grayscale(image); + let (Some(lo), Some(hi)) = (gray.iter().min(), gray.iter().max()) else { return None }; + let t = (*lo as u32 + *hi as u32) / 2; + let ink: Vec = gray.iter().map(|&g| (g as u32) < t).collect(); + if !ink.iter().any(|i| *i) { + return None; // a blank page has no skew + } + let (w, h) = (image.width, image.height); + let cx = f64::from(w) / 2.0; + let max_shift = (f64::from(w) / 2.0 * 5f64.to_radians().tan()).ceil() as i64 + 2; + let score = |phi_deg: f64| -> f64 { + let slope = phi_deg.to_radians().tan(); + let mut profile = vec![0u64; (h as i64 + 2 * max_shift + 1) as usize]; + for (y, row) in ink.chunks_exact(w as usize).enumerate() { + for (x, on) in row.iter().enumerate() { + if !on { + continue; + } + let r = y as f64 - (x as f64 - cx) * slope; + let idx = r.round() as i64 + max_shift; + if let Some(p) = profile.get_mut(idx as usize) { + *p += 1; + } + } + } + profile.iter().map(|p| (*p as f64).powi(2)).sum() + }; + let mut best = (0.0f64, score(0.0)); + let mut phi = -5.0; + while phi <= 5.0 + 1e-9 { + let s = score(phi); + if s > best.1 { + best = (phi, s); + } + phi += 0.25; + } + let (angle, best_score) = best; + if angle.abs() < 0.1 || best_score < 1.02 * score(0.0) { + return None; // straight enough, or no clear winner: no-op + } + Some(angle) +} + +/// Rotate the content by `−angle` about the centre (the deskew correction), nearest-neighbour +/// with white fill; also returns the exact dest→src map (the correction's inverse). +fn deskew_rotate(image: &OcrImage, angle_deg: f64) -> (OcrImage, InverseTransform) { + let phi = angle_deg.to_radians(); + let (cos, sin) = (phi.cos(), phi.sin()); + let (w, h) = (image.width, image.height); + let (cx, cy) = (f64::from(w) / 2.0, f64::from(h) / 2.0); + let back = InverseTransform { a: cos, b: sin, c: -sin, d: cos, e: cx - cos * cx + sin * cy, f: cy - sin * cx - cos * cy }; + let mut out = vec![255u8; w as usize * h as usize * 4]; + for (y, row) in out.chunks_exact_mut(w as usize * 4).enumerate() { + for (x, px) in row.as_chunks_mut::<4>().0.iter_mut().enumerate() { + let (sx, sy) = back.apply(x as f64, y as f64); + let (xi, yi) = (sx.round() as i64, sy.round() as i64); + if xi < 0 || yi < 0 || xi >= w as i64 || yi >= h as i64 { + continue; // outside the scan: white fill + } + if let Some(src) = image.rgba.get((yi as usize * w as usize + xi as usize) * 4..(yi as usize * w as usize + xi as usize) * 4 + 4) { + px.copy_from_slice(src); + } + } + } + (OcrImage::new(w, h, out).unwrap_or_else(|_| image.clone()), back) +} + +/// 3×3 median filter on each colour channel, edges clamped (border pixels replicate); +/// dimensions and alpha are unchanged. +fn median3(image: &OcrImage) -> OcrImage { + let (w, h) = (image.width as usize, image.height as usize); + let mut out = image.rgba.clone(); + for (i, dst) in out.as_chunks_mut::<4>().0.iter_mut().enumerate() { + let (x, y) = (i % w, i / w); + let mut rgba = [255u8; 3]; + for (ch, v) in rgba.iter_mut().enumerate() { + let mut window = [0u8; 9]; + for (n, (dx, dy)) in [(-1i64, -1i64), (0, -1), (1, -1), (-1, 0), (0, 0), (1, 0), (-1, 1), (0, 1), (1, 1)].iter().enumerate() { + let nx = ((x as i64) + dx).clamp(0, w as i64 - 1) as usize; + let ny = ((y as i64) + dy).clamp(0, h as i64 - 1) as usize; + window[n] = image.byte(nx as f64, ny as f64, ch); + } + window.sort_unstable(); + *v = window[4]; + } + let alpha = dst[3]; + dst.copy_from_slice(&[rgba[0], rgba[1], rgba[2], alpha]); + } + OcrImage::new(image.width, image.height, out).unwrap_or_else(|_| image.clone()) +} + +/// The Sauvola ink mask: local thresholding with the documented window — 8 pixels wide, the +/// 8 pixels from −4 to +3 (the end is exclusive, so `x0..x1` is exactly `x−4..=x+3`), k 0.34 — +/// through an integral image. A pixel is ink when its grey is at or under the local +/// threshold. +fn sauvola_mask(image: &OcrImage) -> Vec { + let (w, h) = (image.width as usize, image.height as usize); + let gray = grayscale(image); + // Integral sums and square sums, (w+1)×(h+1), so any window sum is four lookups. + let stride = w + 1; + let mut sums = vec![0u64; stride * (h + 1)]; + let mut squares = vec![0u64; stride * (h + 1)]; + for (y, row) in gray.chunks_exact(w).enumerate() { + let (mut row_sum, mut row_sq) = (0u64, 0u64); + for (x, &g) in row.iter().enumerate() { + row_sum += u64::from(g); + row_sq += u64::from(g) * u64::from(g); + let above = sums.get(y * stride + x + 1).copied().unwrap_or(0); + let above_sq = squares.get(y * stride + x + 1).copied().unwrap_or(0); + if let (Some(s), Some(sq)) = (sums.get_mut((y + 1) * stride + x + 1), squares.get_mut((y + 1) * stride + x + 1)) { + *s = above + row_sum; + *sq = above_sq + row_sq; + } + } + } + let (k, r) = (0.34f64, 128.0f64); + let half = 4usize; + let mut ink = vec![false; w * h]; + for (y, row) in ink.chunks_exact_mut(w).enumerate() { + for (x, dst) in row.iter_mut().enumerate() { + let (x0, y0) = (x.saturating_sub(half), y.saturating_sub(half)); + // Exclusive end: the window covers −4..=+3, 8 pixels on a side (an end of + // `x + half + 1` would make it 9 and disagree with the documented window). + let (x1, y1) = ((x + half).min(w), (y + half).min(h)); + let n = ((x1 - x0) * (y1 - y0)) as f64; + let sum = rect_sum(&sums, stride, x0, y0, x1, y1); + let sq = rect_sum(&squares, stride, x0, y0, x1, y1); + let mean = sum / n; + let var = (sq / n - mean * mean).max(0.0); + let threshold = mean * (1.0 + k * (var.sqrt() / r - 1.0)); + *dst = matches!(gray.get(y * w + x), Some(&g) if f64::from(g) <= threshold); + } + } + ink +} + +/// Sauvola binarization through [`sauvola_mask`], followed by a one-pixel dilation of the ink: +/// ink goes to black, paper to white, alpha preserved. +fn sauvola(image: &OcrImage) -> OcrImage { + let (w, h) = (image.width as usize, image.height as usize); + // One dilation keeps anti-aliased strokes whole: a thresholded edge pixel that flaked off + // rejoins its stroke (slightly bold beats broken, for reading). + let ink = dilate1(&sauvola_mask(image), w, h); + let mut out = image.rgba.clone(); + for (i, px) in out.as_chunks_mut::<4>().0.iter_mut().enumerate() { + let v = if ink.get(i).copied().unwrap_or(false) { 0u8 } else { 255u8 }; + if let Some(dst) = px.get_mut(..3) { + dst.copy_from_slice(&[v, v, v]); + } + } + OcrImage::new(image.width, image.height, out).unwrap_or_else(|_| image.clone()) +} + +/// Grow the ink mask by one pixel (8-neighbourhood, edges clamped by the bounds checks). +fn dilate1(ink: &[bool], w: usize, h: usize) -> Vec { + let mut out = ink.to_vec(); + for y in 0..h { + for x in 0..w { + if !ink.get(y * w + x).copied().unwrap_or(false) { + continue; + } + for dy in [-1isize, 0, 1] { + for dx in [-1isize, 0, 1] { + let (nx, ny) = (x as isize + dx, y as isize + dy); + if nx < 0 || ny < 0 || nx >= w as isize || ny >= h as isize { + continue; + } + if let Some(o) = out.get_mut(ny as usize * w + nx as usize) { + *o = true; + } + } + } + } + } + out +} + +fn rect_sum(table: &[u64], stride: usize, x0: usize, y0: usize, x1: usize, y1: usize) -> f64 { + let a = table.get(y1 * stride + x1).copied().unwrap_or(0); + let b = table.get(y0 * stride + x1).copied().unwrap_or(0); + let c = table.get(y1 * stride + x0).copied().unwrap_or(0); + let d = table.get(y0 * stride + x0).copied().unwrap_or(0); + (a + d - b - c) as f64 +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Sides under MAX_SIDE whose area passes MAX_PIXELS (9500 × 9500, 90 MP) are refused + /// when the size is worked out, before the 360 MB buffer is allocated rather than after. + #[test] + fn an_upscale_over_the_area_cap_is_refused_before_allocating() { + assert!(matches!(scaled_size(1000, 1000, 9.5), Err(OcrError::ImageTooLarge))); + assert_eq!(scaled_size(1000, 1000, 2.0).unwrap(), (2000, 2000), "under the caps it still scales"); + assert_eq!(scaled_size(8000, 8000, 1.0).unwrap(), (8000, 8000), "exactly 64 MP is allowed"); + assert!(matches!(scaled_size(8001, 8000, 1.0), Err(OcrError::ImageTooLarge)), "one row over is not"); + assert!(matches!(scaled_size(1000, 1000, 10.5), Err(OcrError::ImageTooLarge)), "a side over MAX_SIDE"); + assert!(matches!(scaled_size(1000, 1000, 0.0), Err(OcrError::ImageTooLarge)), "a side under one pixel"); + assert!(matches!(scaled_size(1000, 1000, f64::NAN), Err(OcrError::ImageTooLarge))); + let small = OcrImage::new(100, 100, vec![255; 100 * 100 * 4]).unwrap(); + assert!(matches!(resize_bilinear(&small, 100.5), Err(OcrError::ImageTooLarge))); + assert_eq!(resize_bilinear(&small, 2.0).unwrap().width, 200); + } + + fn white(w: u32, h: u32) -> OcrImage { + OcrImage::new(w, h, vec![255; (w * h * 4) as usize]).unwrap() + } + + /// Ink bounding box of a raster (None when blank). + fn ink_bbox(image: &OcrImage) -> Option<[f32; 4]> { + let gray = grayscale(image); + let (Some(lo), Some(hi)) = (gray.iter().min(), gray.iter().max()) else { return None }; + let t = (*lo as u32 + *hi as u32) / 2; + let (mut l, mut tp, mut r, mut b) = (u32::MAX, u32::MAX, 0u32, 0u32); + let mut any = false; + for (i, &g) in gray.iter().enumerate() { + if (g as u32) >= t { + continue; + } + any = true; + let (x, y) = ((i as u32) % image.width, (i as u32) / image.width); + l = l.min(x); + r = r.max(x); + tp = tp.min(y); + b = b.max(y); + } + any.then_some([l as f32, tp as f32, r as f32, b as f32]) + } + + /// A horizontal line of three bottom-heavy block glyphs (L shapes) on white — the fixture + /// for orientation detection (240 × 64 at 300 dpi). + fn l_line() -> OcrImage { + let (w, h) = (240u32, 64u32); + let mut img = white(w, h); + for gx in [20u32, 100, 180] { + fill(&mut img, gx, 12, 12, 40); + fill(&mut img, gx, 40, 36, 12); + } + img + } + + fn fill(img: &mut OcrImage, x0: u32, y0: u32, w: u32, h: u32) { + for y in y0..y0 + h { + for x in x0..x0 + w { + let o = ((y * img.width + x) * 4) as usize; + if let Some(p) = img.rgba.get_mut(o..o + 3) { + p.copy_from_slice(&[0, 0, 0]); + } + } + } + } + + /// The same fixture pre-rotated by k quarter turns clockwise, built independently of the + /// crate's rotation (so the test cannot pass by a shared bug). + fn rotated(k: u32) -> OcrImage { + let src = l_line(); + let (w, h) = (src.width as usize, src.height as usize); + let (nw, nh) = if k.is_multiple_of(2) { (src.width, src.height) } else { (src.height, src.width) }; + let mut out = white(nw, nh); + for (y, row) in src.rgba.chunks_exact(w * 4).enumerate() { + for (x, px) in row.as_chunks::<4>().0.iter().enumerate() { + if px[0] != 0 { + continue; + } + let (nx, ny) = match k { + 1 => (h - 1 - y, x), + 2 => (w - 1 - x, h - 1 - y), + 3 => (y, w - 1 - x), + _ => (x, y), + }; + fill(&mut out, nx as u32, ny as u32, 1, 1); + } + } + out + } + + /// A ruled fixture sheared by `degrees` (lines running downhill to the right for positive + /// angles): four 8-px bars across a 300 × 120 page. + fn sheared(degrees: f64) -> OcrImage { + let (w, h) = (300u32, 120u32); + let mut img = white(w, h); + let slope = degrees.to_radians().tan(); + for (base, height) in [(20u32, 8u32), (45, 8), (70, 8), (95, 8)] { + for x in 20..280u32 { + let y = (base as f64 + (x as f64 - 150.0) * slope).round().clamp(0.0, f64::from(h - height - 1)) as u32; + fill(&mut img, x, y, 1, height); + } + } + img + } + + /// With the four opt-in flags off and a dpi at or above 300, the raster passes through + /// untouched and the inverse transform is exact. + #[test] + fn flags_off_and_adequate_dpi_is_an_identity_pass_through() { + let src = l_line(); + let p = preprocess(src.clone(), 300.0, &PreprocessOptions::default()).unwrap(); + assert_eq!(p.image.rgba, src.rgba); + assert_eq!(p.dpi, 300.0); + assert_eq!(p.inverse_transform, InverseTransform::identity()); + assert_eq!(p.inverse_transform.map_rect([3.0, 7.0, 41.0, 19.0]), [3.0, 7.0, 41.0, 19.0]); + } + + /// With a step on, a scan below 300 dpi is enlarged by 300/src first, and its boxes map + /// back to the original raster. + #[test] + fn low_dpi_scans_are_upscaled_for_the_steps_and_boxes_map_back() { + let src = white(100, 50); + let on = PreprocessOptions { denoise: true, ..Default::default() }; + let p = preprocess(src.clone(), 150.0, &on).unwrap(); + assert_eq!((p.image.width, p.image.height), (200, 100)); + assert_eq!(p.dpi, 300.0); + assert_eq!(p.inverse_transform.map_rect([0.0, 0.0, 200.0, 100.0]), [0.0, 0.0, 100.0, 50.0]); + assert_eq!(p.inverse_transform.apply(2.0, 4.0), (1.0, 2.0)); + // 300 and 600 dpi are not resampled; a broken dpi is left alone. + assert_eq!(preprocess(src.clone(), 600.0, &on).unwrap().image.width, 100); + assert_eq!(preprocess(src, f32::NAN, &on).unwrap().image.width, 100); + } + + /// With every step off a low-dpi render is read exactly as rendered: not resampled, with + /// the identity as its way back. (Reading a 72 dpi scan through a 4x enlargement changed + /// what the models read: "due: \€250" came back as "ue: ?250".) + #[test] + fn with_every_step_off_a_low_dpi_render_is_not_resampled() { + let src = l_line(); + let p = preprocess(src.clone(), 72.0, &PreprocessOptions::default()).unwrap(); + assert_eq!(p.image.rgba, src.rgba); + assert_eq!((p.image.width, p.image.height), (src.width, src.height)); + assert_eq!(p.dpi, 72.0, "the render's own resolution"); + assert_eq!(p.inverse_transform, InverseTransform::identity()); + } + + /// The upscale refuses to break the side cap. + #[test] + fn upscaling_respects_the_side_cap() { + let src = white(9999, 10); + let r = preprocess(src, 72.0, &PreprocessOptions { denoise: true, ..Default::default() }); + assert!(matches!(r, Err(OcrError::ImageTooLarge)), "upscale past the cap: {r:?}"); + } + + /// An upright page is left alone by the orientation detector. + #[test] + fn upright_pages_are_not_rotated() { + let p = preprocess(l_line(), 300.0, &PreprocessOptions { auto_rotate: true, ..Default::default() }).unwrap(); + assert_eq!(p.inverse_transform, InverseTransform::identity()); + } + + /// Pages scanned at 90/180/270 are detected, turned upright, and their word boxes map back + /// onto the scanned raster's ink. + #[test] + fn quarter_turns_are_detected_corrected_and_mapped_back() { + for k in 1..=3 { + let scanned = rotated(k); + let p = preprocess(scanned.clone(), 300.0, &PreprocessOptions { auto_rotate: true, ..Default::default() }).unwrap(); + let corrected = ink_bbox(&p.image).unwrap_or_else(|| panic!("k={k}: the corrected page still has ink")); + // The corrected reading is a horizontal line again: wider than tall. + assert!(corrected[2] - corrected[0] > corrected[3] - corrected[1], "k={k}: {corrected:?}"); + // And the box maps back onto the scanned raster's own ink box. + let back = p.inverse_transform.map_rect(corrected); + let original = ink_bbox(&scanned).unwrap(); + for i in 0..4 { + assert!((back[i] - original[i]).abs() <= 2.0, "k={k}: {back:?} vs {original:?}"); + } + } + } + + /// Images under 32 px on a side are never judged; the step is a no-op. + #[test] + fn tiny_images_skip_orientation() { + let src = white(31, 31); + let p = preprocess(src, 300.0, &PreprocessOptions { auto_rotate: true, ..Default::default() }).unwrap(); + assert_eq!(p.inverse_transform, InverseTransform::identity()); + } + + /// Blank pages are inconclusive: every step leaves them alone. + #[test] + fn blank_pages_are_a_noop() { + let src = white(200, 200); + let p = preprocess(src, 300.0, &PreprocessOptions { auto_rotate: true, deskew: true, denoise: true, binarize: true }).unwrap(); + assert_eq!(p.inverse_transform, InverseTransform::identity()); + } + + /// The skew estimator sees a 3° shear (either direction) and leaves a straight page alone. + #[test] + fn skew_is_estimated_and_straight_pages_are_left_alone() { + for degrees in [3.0, -3.0] { + let angle = estimate_skew(&sheared(degrees)).unwrap_or_else(|| panic!("{degrees}° should be found")); + assert!((angle - degrees).abs() <= 0.5, "{degrees}°: got {angle}"); + } + assert!(estimate_skew(&sheared(0.0)).is_none(), "a straight page is a no-op"); + assert!(estimate_skew(&l_line()).is_none(), "glyph lines without a shear are a no-op"); + } + + /// Deskew straightens ±3° lines (the vertical span tightens) and the centre maps back to + /// itself. + #[test] + fn deskew_corrects_plus_and_minus_three_degrees() { + for degrees in [3.0, -3.0] { + let src = sheared(degrees); + let before = ink_bbox(&src).unwrap(); + let p = preprocess(src.clone(), 300.0, &PreprocessOptions { deskew: true, ..Default::default() }).unwrap(); + let after = ink_bbox(&p.image).unwrap(); + assert!(after[3] - after[1] < before[3] - before[1], "{degrees}°: {before:?} → {after:?}"); + // The exact inverse maps the corrected centre back to the scanned centre. + let (cx, cy) = (f64::from(src.width) / 2.0, f64::from(src.height) / 2.0); + let (bx, by) = p.inverse_transform.apply(cx, cy); + assert!((bx - cx).abs() < 1.0 && (by - cy).abs() < 1.0, "{degrees}°: ({bx}, {by})"); + } + } + + /// Deskew no-ops on small images (under 64 px) — the detector is never consulted. + #[test] + fn small_images_skip_deskew() { + let src = white(63, 63); + let p = preprocess(src, 300.0, &PreprocessOptions { deskew: true, ..Default::default() }).unwrap(); + assert_eq!(p.inverse_transform, InverseTransform::identity()); + } + + /// The median filter removes isolated specks, keeps solid strokes, and never changes the + /// dimensions. + #[test] + fn denoise_removes_specks_and_keeps_dimensions() { + let mut src = white(32, 32); + fill(&mut src, 15, 15, 1, 1); // salt + fill(&mut src, 4, 4, 5, 5); // a solid stroke + let p = preprocess(src, 300.0, &PreprocessOptions { denoise: true, ..Default::default() }).unwrap(); + assert_eq!((p.image.width, p.image.height), (32, 32)); + assert_eq!(p.image.byte(15.0, 15.0, 0), 255, "an isolated speck is gone"); + assert_eq!(p.image.byte(6.0, 6.0, 0), 0, "the inside of a solid block stays"); + assert_eq!(p.inverse_transform, InverseTransform::identity()); + } + + /// Sauvola keeps the polarity (dark ink stays dark, paper stays light) and the metadata. + /// The fixture is a thin grey stroke: its windows mix ink and paper, so the local + /// threshold separates them (a perfectly flat mid-tone area has no contrast and whitens, + /// which is Sauvola working as designed). + #[test] + fn binarize_keeps_polarity_and_metadata() { + let (w, h) = (64u32, 64u32); + let mut src = white(w, h); + for y in 26..30 { + for x in 8..56 { + let o = ((y * w + x) * 4) as usize; + if let Some(p) = src.rgba.get_mut(o..o + 3) { + p.copy_from_slice(&[70, 70, 70]); // a grey scan's ink, far below paper + } + } + } + let p = preprocess(src, 300.0, &PreprocessOptions { binarize: true, ..Default::default() }).unwrap(); + assert_eq!((p.image.width, p.image.height), (w, h)); + assert_eq!(p.dpi, 300.0); + assert_eq!(p.image.byte(30.0, 28.0, 0), 0, "ink stays dark"); + assert_eq!(p.image.byte(2.0, 2.0, 0), 255, "paper stays light"); + for px in p.image.rgba.as_chunks::<4>().0.iter() { + assert!((px[0] == 0 || px[0] == 255) && px[0] == px[1] && px[1] == px[2], "{px:?}"); + } + } + + /// The inverse transform composes: an upscaled, turned, deskewed page maps corrected + /// points back inside the original raster. + #[test] + fn inverse_transform_maps_points_back_through_every_step() { + let scanned = rotated(1); // a page photographed on its side + let p = preprocess(scanned.clone(), 150.0, &PreprocessOptions { auto_rotate: true, deskew: true, ..Default::default() }).unwrap(); + let (w, h) = (f64::from(p.image.width), f64::from(p.image.height)); + for (x, y) in [(0.0, 0.0), (w - 1.0, 0.0), (0.0, h - 1.0), (w - 1.0, h - 1.0), (w / 2.0, h / 2.0)] { + let (bx, by) = p.inverse_transform.apply(x, y); + assert!((-2.0..=f64::from(scanned.width) + 2.0).contains(&bx), "x {x} → {bx}"); + assert!((-2.0..=f64::from(scanned.height) + 2.0).contains(&by), "y {y} → {by}"); + } + // The scale step, alone, is exact. + assert_eq!(InverseTransform::scale(0.5).apply(4.0, 10.0), (2.0, 5.0)); + } + + /// A realistic letter page (one line of type on white, at 300 dpi) reads as upright: the + /// row axis bands decisively sharper than the column axis, and the near-balanced + /// bottom-heaviness of real mixed-case text is below the 15% flip bar, so the page is left + /// alone rather than risk flipping a good scan upside down. + #[test] + fn realistic_letter_pages_are_left_upright() { + let (w, h) = (1200u32, 1650u32); + let mut img = white(w, h); + let mut x = 120u32; + let base = 300u32; + let mut seed = 7u64; + let mut rnd = || { + seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + (seed >> 33) as u32 + }; + while x < 1000 { + let word = rnd() % 5 + 2; + for _ in 0..word { + let kind = rnd() % 4; + let wl = rnd() % 8 + 3; + match kind { + 0 => fill(&mut img, x, base - 20, wl, 20), // x-height + 1 => fill(&mut img, x, base - 34, wl, 34), // ascender + 2 => fill(&mut img, x, base - 20, wl, 28), // descender + _ => { + fill(&mut img, x, base - 20, 2, 20); + fill(&mut img, x + 3, base - 14, 2, 14); // stems + } + } + x += wl + 2; + } + x += 12; // space + } + assert_eq!(detect_orientation(&img), 0); + let p = preprocess(img, 300.0, &PreprocessOptions { auto_rotate: true, ..Default::default() }).unwrap(); + assert_eq!(p.inverse_transform, InverseTransform::identity()); + } + + /// Hostile inputs are errors or no-ops, never panics: 1×1 rasters, all-black pages, NaN + /// boxes through the inverse map. + #[test] + fn hostile_inputs_never_panic() { + let tiny = white(1, 1); + let all = PreprocessOptions { auto_rotate: true, deskew: true, denoise: true, binarize: true }; + let p = preprocess(tiny, 300.0, &all).unwrap(); + assert_eq!((p.image.width, p.image.height), (1, 1)); + // All-black: no paper, nothing to judge. + let mut black = white(80, 80); + for px in black.rgba.as_chunks_mut::<4>().0 { + px.copy_from_slice(&[0, 0, 0, 255]); + } + let p = preprocess(black, 300.0, &all).unwrap(); + assert_eq!(p.inverse_transform, InverseTransform::identity(), "all-black is inconclusive"); + // NaN boxes never poison downstream math: the finite corners bound the mapped box, + // and a box with no finite corners comes back unchanged. + let mapped = p.inverse_transform.map_rect([f32::NAN, 0.0, 5.0, 5.0]); + assert!(mapped.iter().all(|v| v.is_finite()), "{mapped:?}"); + let unchanged = InverseTransform::identity().map_rect([f32::NAN; 4]); + assert!(unchanged.iter().all(|v| v.is_nan()), "{unchanged:?}"); + } + + /// The one-pixel dilation is load-bearing, pinned with a fixture that fragments without + /// it: a thin anti-aliased-looking stroke on a grey scan (alternating dark and light + /// pixels) — the raw Sauvola mask drops the light runs (the local window sits on a grey + /// page, so the threshold falls below them), while the binarized image keeps the stroke + /// whole. + #[test] + fn binarize_without_the_dilation_the_stroke_fragments_and_with_it_stays_whole() { + let (w, h) = (64u32, 64u32); + let mut src = white(w, h); + let set = |img: &mut OcrImage, x: u32, y: u32, v: u8| { + let o = ((y * w + x) * 4) as usize; + if let Some(p) = img.rgba.get_mut(o..o + 3) { + p.copy_from_slice(&[v, v, v]); + } + }; + for px in src.rgba.as_chunks_mut::<4>().0.iter_mut() { + px[..3].copy_from_slice(&[210, 210, 210]); // a grey scan's paper + } + // The stroke: one pixel tall, alternating dark (reads as ink) and light (an + // anti-aliased shoulder the threshold alone drops) in runs of two. + for x in 8..56u32 { + let v = if (x / 2) % 2 == 0 { 110 } else { 170 }; + set(&mut src, x, 32, v); + } + let mask = sauvola_mask(&src); + let at = |x: u32, y: u32| mask[y as usize * w as usize + x as usize]; + let dropped: Vec = (12..52).filter(|&x| !at(x, 32)).collect(); + assert!(!dropped.is_empty(), "without the dilation the stroke fragments: these stroke pixels fall under the threshold at {dropped:?}"); + let p = preprocess(src, 300.0, &PreprocessOptions { binarize: true, ..Default::default() }).unwrap(); + // With the dilation the stroke is whole: every position on it has ink within its + // 8-neighbourhood. + for x in 12..=51u32 { + let ink_near = (-1i32..=1).any(|dy| { + (-1i32..=1).any(|dx| { + let (nx, ny) = (x as i32 + dx, 32 + dy); + p.image.byte(f64::from(nx), f64::from(ny), 0) == 0 + }) + }); + assert!(ink_near, "the stroke is broken at x={x}"); + } + } + + /// The deskew inverse, checked at OFF-CENTRE points (the centre maps to itself under any + /// rotation, so it cannot catch a wrong sign): a point on a straightened line maps back + /// onto the sheared source line, uphill and downhill. + #[test] + fn deskew_inverse_maps_off_centre_points_back_onto_the_source_line() { + for degrees in [3.0, -3.0] { + let src = sheared(degrees); + let p = preprocess(src, 300.0, &PreprocessOptions { deskew: true, ..Default::default() }).unwrap(); + let slope = degrees.to_radians().tan(); + // The corrected first line sits at y = 20 (the fixture's base); the same ink was + // at 20 + (x − 150)·slope in the source. Well off centre on purpose. The + // rotation moves x a little too (it mixes in y: at most sin(5°)·40 ≈ 3.5 px + // here), so the line is checked at the mapped x — a wrong sign still misses it + // by ±(x−150)·slope, 6+ px at these offsets. + for x in [30.0f64, 150.0, 270.0] { + let (sx, sy) = p.inverse_transform.apply(x, 20.0); + assert!((sx - x).abs() < 4.0, "{degrees}° x={x}: mapped to ({sx}, {sy})"); + let expected = 20.0 + (sx - 150.0) * slope; + assert!((sy - expected).abs() < 2.0, "{degrees}° x={x}: ({sx}, {sy}), the source line is at {expected}"); + } + } + } +} diff --git a/crates/ocr/src/tesseract.rs b/crates/ocr/src/tesseract.rs new file mode 100644 index 0000000000..9fbcc574d8 --- /dev/null +++ b/crates/ocr/src/tesseract.rs @@ -0,0 +1,1022 @@ +//! The Tesseract engine: an installed `tesseract` binary driven as an optional external +//! process (`tesseract stdout -l tsv`), never linked, never bundled, never +//! downloaded. The whole module is compiled out for wasm32, where nothing may spawn. +//! +//! Security posture (hard rules): the program path comes from the PATH or a user-configured +//! location, never from document data; the language code is allow-listed before it reaches a +//! process; the page image goes to a private temp file (a fresh 0700 directory holding a 0600 +//! file on Unix) that is deleted afterwards; the run has a timeout and an output size cap; and +//! every failure comes back through [`OcrError`] with its cause named. + +use std::io::Write; +use std::path::{Path, PathBuf}; +use std::sync::Mutex; +use std::sync::atomic::{AtomicU8, Ordering}; +use std::time::{Duration, Instant}; + +use super::{Line, OcrError, OcrImage, RecognizeOptions, Recognizer, Word}; + +/// How long one recognition may run before the process is killed. +const TIMEOUT: Duration = Duration::from_secs(120); +/// How much TSV output is accepted before the run is abandoned. +const MAX_OUTPUT: u64 = 64 * 1024 * 1024; +/// How much of the program's stderr is read back (its end): enough for a `--list-langs` list +/// printed there, small enough that error text stays a message, not a memory DoS. +const MAX_STDERR: u64 = 256 * 1024; +/// The most words one TSV reading may hold. Known limit: a reading with more words than this +/// is truncated at the cap — corrupt or runaway output must not become unbounded memory in +/// the word list, the text layer and the review UI. +pub const MAX_WORDS: usize = 50_000; +/// Tesseract's code for each language PdfCraft offers (ISO 639-1 → tessdata name). Only these +/// codes ever reach the process, whatever the settings say. +pub const LANGUAGE_CODES: &[(&str, &str)] = &[ + ("en", "eng"), + ("de", "deu"), + ("fr", "fra"), + ("es", "spa"), + ("it", "ita"), + ("pt", "por"), + ("ru", "rus"), + ("zh", "chi_sim"), + ("ja", "jpn"), + ("ko", "kor"), + ("ar", "ara"), + ("nl", "nld"), +]; + +/// English names for [`LANGUAGE_CODES`] (dropdowns show code + name). +pub const LANGUAGE_NAMES: &[(&str, &str)] = &[ + ("en", "English"), + ("de", "German"), + ("fr", "French"), + ("es", "Spanish"), + ("it", "Italian"), + ("pt", "Portuguese"), + ("ru", "Russian"), + ("zh", "Chinese (Simplified)"), + ("ja", "Japanese"), + ("ko", "Korean"), + ("ar", "Arabic"), + ("nl", "Dutch"), +]; + +/// Map a settings language code to a Tesseract one: trimmed, case-insensitive, allow-listed; +/// anything unknown falls back to `"eng"`. +pub fn language_code(code: &str) -> &'static str { + let c = code.trim().to_ascii_lowercase(); + LANGUAGE_CODES.iter().find(|(k, _)| *k == c).map(|(_, v)| *v).unwrap_or("eng") +} + +/// The user-configured program location, when valid: `$PDFCRAFT_TESSERACT` (a user +/// preference, never taken from document data). An invalid value — relative, missing, a +/// directory, not executable — means unavailable: an explicit setting is never silently +/// replaced by a PATH search. +pub fn configured_path() -> Option { + let value = std::env::var_os("PDFCRAFT_TESSERACT")?; + let program = PathBuf::from(value); + program_is_executable(&program).then_some(program) +} + +/// The program [`TesseractCli::find`] would run: a set `configured` location (the value of +/// `PDFCRAFT_TESSERACT`) decides alone, so an invalid one yields `None` and `search` (the PATH) +/// is not even consulted; only when nothing is configured does `search` decide. +fn locate(configured: Option, search: impl FnOnce() -> Option) -> Option { + match configured { + Some(value) => Some(PathBuf::from(value)).filter(|program| program_is_executable(program)), + None => search(), + } +} + +/// The first `tesseract` on the PATH that is an existing executable file. Entries that are not +/// absolute are refused: a relative PATH entry resolves against the caller's working +/// directory, which is neither stable nor a safe place to find a program. Also named by +/// `ocr_status` (the engine reports where it would look, without probing). +pub fn path_search() -> Option { + path_search_in(std::env::split_paths(&std::env::var_os("PATH")?)) +} + +/// [`path_search`] over an explicit directory list (so tests can pass one). +fn path_search_in(dirs: impl Iterator) -> Option { + for dir in dirs.filter(|d| d.is_absolute()) { + for name in program_file_names() { + let candidate = dir.join(name); + if program_is_executable(&candidate) { + return Some(candidate); + } + } + } + None +} + +/// The file names an installed `tesseract` binary goes by. +fn program_file_names() -> &'static [&'static str] { + #[cfg(windows)] + { + &["tesseract.exe"] + } + #[cfg(not(windows))] + { + &["tesseract"] + } +} + +/// Whether `program` is a usable program location (see [`program_is_executable`]); callers +/// that run a validated program by path (the engine's `--version` query) check it first. +pub fn program_is_usable(program: &Path) -> bool { + program_is_executable(program) +} + +/// Whether `program` is a usable configured location: an absolute path to an existing, +/// executable FILE (on Unix the executable bits must be set; elsewhere being a file is what +/// the OS requires). A directory or a missing file is simply unavailable — never a panic. +fn program_is_executable(program: &Path) -> bool { + if !program.is_absolute() || !program.is_file() { + return false; + } + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + std::fs::metadata(program).is_ok_and(|m| m.permissions().mode() & 0o111 != 0) + } + #[cfg(not(unix))] + { + true + } +} + +/// One row of Tesseract's TSV output. `level` 5 rows are the words; `conf` is −1 on the header +/// rows (page, block, paragraph, line), which are not words. +struct TsvRow<'a> { + level: &'a str, + block: u32, + par: u32, + line: u32, + left: f32, + top: f32, + width: f32, + height: f32, + conf: f32, + text: &'a str, +} + +/// Parse one TSV row; `None` for anything unreadable (short rows, non-numeric fields), which +/// is skipped rather than trusted. A row with non-finite numbers or a negative width or height +/// is not a word either: geometry like that is output corruption, and trusting it puts NaN +/// into word boxes and on to the page. +fn tsv_row(row: &str) -> Option> { + let c: Vec<&str> = row.split('\t').collect(); + if c.len() < 12 { + return None; + } + let (block, par, line) = (c[2].trim().parse().ok()?, c[3].trim().parse().ok()?, c[4].trim().parse().ok()?); + let (left, top): (f32, f32) = (c[6].trim().parse().ok()?, c[7].trim().parse().ok()?); + let (width, height, conf): (f32, f32, f32) = (c[8].trim().parse().ok()?, c[9].trim().parse().ok()?, c[10].trim().parse().ok()?); + if !left.is_finite() || !top.is_finite() || !width.is_finite() || !height.is_finite() || !conf.is_finite() { + return None; // NaN/inf anywhere in the numbers + } + if width < 0.0 || height < 0.0 { + return None; // a word box has a non-negative size + } + Some(TsvRow { level: c[0], block, par, line, left, top, width, height, conf, text: c[11] }) +} + +/// Parse `tesseract … tsv` output into lines of words. Rows with confidence −1 are the +/// structural header rows and never become words; consecutive word rows that share their +/// (block, paragraph, line) form one [`Line`], in output (reading) order. Confidence clamps +/// into 0–100. Known limit: past [`MAX_WORDS`] the rest of the reading is dropped (truncated, +/// not an error — the words before the cap are still placed). +pub fn parse_tsv(tsv: &str) -> Vec { + parse_tsv_bounded(tsv).0 +} + +/// The parser utility keeps its bounded-prefix API; recognition also checks completeness. +fn parse_tsv_bounded(tsv: &str) -> (Vec, bool) { + let mut lines: Vec = Vec::new(); + let mut key: Option<(u32, u32, u32)> = None; + let mut words = 0usize; + for row in tsv.lines() { + let Some(r) = tsv_row(row) else { continue }; + if r.level != "5" || r.conf < 0.0 || r.text.trim().is_empty() { + continue; + } + if words >= MAX_WORDS { + return (lines, true); + } + let this = (r.block, r.par, r.line); + if key != Some(this) { + lines.push(Line::default()); + key = Some(this); + } + let word = Word::new(r.text, [r.left, r.top, r.left + r.width, r.top + r.height], "tesseract").with_confidence(r.conf.clamp(0.0, 100.0)); + if let Some(last) = lines.last_mut() { + last.words.push(word); + words += 1; + } + } + (lines, false) +} + +/// Parse `tesseract --list-langs` output: the header line ("List of available languages…"), +/// then one code per line. Lines with spaces are not codes (a header, a warning) and are left +/// out. +pub fn parse_list_langs(out: &str) -> Vec { + out.lines() + .skip_while(|l| !l.trim().is_empty() && l.trim().starts_with("List of available")) + .map(|l| l.trim().to_string()) + .filter(|l| !l.is_empty() && !l.contains(char::is_whitespace)) + .collect() +} + +/// The languages a `--list-langs` run reported: its stdout, or, when that holds none, its +/// stderr (Tesseract 3.x prints the list there). +pub fn list_langs_from(stdout: &str, stderr: &str) -> Vec { + let codes = parse_list_langs(stdout); + if codes.is_empty() { parse_list_langs(stderr) } else { codes } +} + +/// The first non-empty line of what `tesseract --version` printed: on stdout, or on stderr +/// where older versions print it. +fn version_line(stdout: &str, stderr: &str) -> Option { + let first = |text: &str| text.lines().map(str::trim).find(|line| !line.is_empty()).map(str::to_owned); + first(stdout).or_else(|| first(stderr)) +} + +/// The Tesseract program. Build one (via [`TesseractCli::find`] for the PATH copy, or +/// [`TesseractCli::new`] for a user-configured path) and reuse it: `--list-langs` runs at most +/// once. +pub struct TesseractCli { + program: PathBuf, + /// The timeout and the output cap are fields so tests can shorten them. + timeout: Duration, + max_output: u64, + /// Whether `--list-langs` has succeeded yet: 0 untried, 1 yes, 2 no. + probed: AtomicU8, + langs: Mutex>, +} + +impl TesseractCli { + /// The program at `path` (a user preference; never taken from document data). + pub fn new(program: PathBuf) -> TesseractCli { + TesseractCli { program, timeout: TIMEOUT, max_output: MAX_OUTPUT, probed: AtomicU8::new(0), langs: Mutex::new(Vec::new()) } + } + + /// The program this engine runs (`ocr_status` names it). + pub fn program(&self) -> &std::path::Path { + &self.program + } + + /// The program at a user-configured `path`, if it is usable there: only an absolute path + /// to an existing, executable file is accepted (a directory, a missing file or a relative + /// path is unavailable, never a panic), and it must answer `--list-langs`. + pub fn at(program: PathBuf) -> Option { + if !program_is_executable(&program) { + return None; + } + let t = TesseractCli::new(program); + let langs = t.list_langs().ok()?; + *t.langs.lock().unwrap_or_else(|e| e.into_inner()) = langs; + t.probed.store(1, Ordering::Relaxed); + Some(t) + } + + /// The program this machine offers, if it answers `--list-langs`: the user-configured + /// location ([`configured_path`] / `$PDFCRAFT_TESSERACT`) when valid, else the first + /// absolute PATH entry that holds an executable `tesseract`. + /// + /// # The PATH-lookup risk + /// + /// Resolving through the PATH trusts every directory on it: a binary planted earlier on + /// the PATH runs as a subprocess with this application's privileges — it sees the page + /// image and anything the process can reach. The language code and the page image still + /// never come from document data, but a user who handles untrusted documents should pin + /// the exact program with `PDFCRAFT_TESSERACT`, which is validated (absolute, existing, + /// executable file) before any process starts. + /// + /// A `PDFCRAFT_TESSERACT` that is set but invalid fails closed: it is never replaced by + /// the PATH search. + pub fn find() -> Option { + TesseractCli::at(locate(std::env::var_os("PDFCRAFT_TESSERACT"), path_search)?) + } + + /// Run `tesseract --list-langs` and parse it; also decides [`TesseractCli::available`]. + fn list_langs(&self) -> Result, OcrError> { + let (out, err) = self.run_capture(&["--list-langs"], self.timeout, self.max_output)?; + let codes = list_langs_from(&out, &err); + if codes.is_empty() { + return Err(OcrError::NoTesseract("--list-langs reported no languages".into())); + } + Ok(codes + .into_iter() + .map(|c| { + let name = LANGUAGE_NAMES.iter().find(|(k, _)| *k == c.as_str()).map(|(_, n)| (*n).to_string()).unwrap_or_else(|| c.clone()); + (c, name) + }) + .collect()) + } + + /// The program's first `--version` line (named by `ocr_status`); `None` when the program + /// does not answer. Not cached: status asks rarely, and a re-install mid-session should + /// show up without a restart. + pub fn version(&self) -> Option { + let (out, err) = self.run_capture(&["--version"], self.timeout, self.max_output).ok()?; + version_line(&out, &err) + } + + /// Run the program with fixed argv, its stdout in a private temp file, under `timeout` + /// seconds and an output cap of `max_output` bytes. Returns the (capped) stdout. + fn run(&self, args: &[&str], timeout: Duration, max_output: u64) -> Result { + self.run_capture(args, timeout, max_output).map(|(out, _)| out) + } + + /// [`Self::run`], also returning what the program wrote to stderr (up to + /// [`MAX_STDERR`] bytes, its end kept): some Tesseract versions print the `--list-langs` + /// list there instead of on stdout. + fn run_capture(&self, args: &[&str], timeout: Duration, max_output: u64) -> Result<(String, String), OcrError> { + let dir = TempDir::create()?; + let out_path = dir.path.join("out.txt"); + let err_path = dir.path.join("err.txt"); + let out_file = std::fs::File::create(&out_path).map_err(|e| OcrError::Process(format!("creating the output file failed: {e}")))?; + // stderr goes to a file, not a pipe: an undrained pipe fills (around 64 KiB) and then + // blocks the child mid-write, which a watcher can only read as a timeout. A file never + // blocks; it is read back as a short tail after the run. + let err_file = std::fs::File::create(&err_path).map_err(|e| OcrError::Process(format!("creating the error file failed: {e}")))?; + // Known limit: only the direct child is killed at the timeout or on an early cap. A + // wrapper script's children (grandchildren of this process) may survive the kill; the + // cap and the timeout still bound what this run reads and how long it waits. + let mut child = + std::process::Command::new(&self.program) + .args(args) + .stdin(std::process::Stdio::null()) + .stdout(out_file) + .stderr(err_file) + .current_dir(&dir.path) + // A minimal environment: nothing from the document or the caller's shell beyond + // what an installed tesseract needs — its data prefix, the PATH (bare-name lookup + // and DLL loading), the Windows system root, and a temp dir it may write to. + .env_clear() + .envs(std::env::vars().filter(|(k, _)| { + k.eq_ignore_ascii_case("TESSDATA_PREFIX") || k.eq_ignore_ascii_case("PATH") || k.eq_ignore_ascii_case("SystemRoot") + })) + .env("TMP", &dir.path) + .env("TEMP", &dir.path) + .spawn() + .map_err(|e| OcrError::NoTesseract(format!("{} could not start: {e}", self.program.display())))?; + let started = Instant::now(); + let status = loop { + match child.try_wait() { + Ok(Some(status)) => break Ok(status), + Ok(None) => { + // The output caps are enforced while the child runs: a flood is killed as + // soon as a file passes its cap, not after it has finished writing. The + // read-back below caps what this run KEEPS of stderr; this cap bounds what + // the child can write there in the first place. + if std::fs::metadata(&out_path).map(|m| m.len()).unwrap_or(0) > max_output + || std::fs::metadata(&err_path).map(|m| m.len()).unwrap_or(0) > MAX_STDERR + { + let _ = child.kill(); + let _ = child.wait(); + break Err(OcrError::OutputTooLarge(max_output)); + } + if started.elapsed() >= timeout { + let _ = child.kill(); + let _ = child.wait(); + break Err(OcrError::Timeout(timeout.as_secs())); + } + std::thread::sleep(Duration::from_millis(20)); + } + Err(e) => { + let _ = child.kill(); + let _ = child.wait(); + break Err(OcrError::Process(format!("waiting for {} failed: {e}", self.program.display()))); + } + } + }; + let status = status?; + // Whatever the exit, the stderr tail names the cause (capped: error text stays a + // message, not a memory DoS). + let stderr = std::fs::File::open(&err_path) + .and_then(|mut f| { + use std::io::{Read, Seek, SeekFrom}; + let len = f.metadata()?.len().min(MAX_STDERR); + f.seek(SeekFrom::End(-(len as i64)))?; + let mut buf = Vec::with_capacity(len as usize); + f.take(len).read_to_end(&mut buf)?; + Ok::<_, std::io::Error>(buf) + }) + .unwrap_or_default(); + let stderr = String::from_utf8_lossy(&stderr).into_owned(); + // The message names only the end of it. + let tail = stderr.char_indices().rev().nth(2047).map_or(0, |(i, _)| i); + let note = stderr.get(tail..).unwrap_or_default().trim(); + if !status.success() { + return Err(OcrError::Process(format!( + "{} exited with {}: {}", + self.program.display(), + status.code().map(|c| c.to_string()).unwrap_or_else(|| "a signal".into()), + if note.is_empty() { "no error message" } else { note } + ))); + } + let len = std::fs::metadata(&out_path).map(|m| m.len()).unwrap_or(0); + if len > max_output { + return Err(OcrError::OutputTooLarge(max_output)); + } + let bytes = std::fs::read(&out_path).map_err(|e| OcrError::Process(format!("reading the output failed: {e}")))?; + Ok((String::from_utf8_lossy(&bytes).into_owned(), stderr)) + } + + /// Retry `--list-langs` once (an install may have appeared since the last try). + fn refresh(&self) -> Result<(), OcrError> { + let langs = self.list_langs()?; + *self.langs.lock().unwrap_or_else(|e| e.into_inner()) = langs; + self.probed.store(1, Ordering::Relaxed); + Ok(()) + } +} + +impl Recognizer for TesseractCli { + fn id(&self) -> &'static str { + "tesseract" + } + + /// Whether the program answers `--list-langs` (remembered; one process at most after the + /// first call). + fn available(&self) -> bool { + match self.probed.load(Ordering::Relaxed) { + 1 => true, + 2 => false, + _ => self.refresh().is_ok(), + } + } + + fn languages(&self) -> Vec<(String, String)> { + if self.probed.load(Ordering::Relaxed) == 2 { + return Vec::new(); + } + let langs = self.langs.lock().unwrap_or_else(|e| e.into_inner()); + if langs.is_empty() { + drop(langs); + return self.refresh().map_or(Vec::new(), |()| self.langs.lock().unwrap_or_else(|e| e.into_inner()).clone()); + } + langs.clone() + } + + /// Write the page as a PNG and read it back as TSV. + fn recognize(&self, image: &OcrImage, options: &RecognizeOptions) -> Result, OcrError> { + let lang = language_code(&options.language); + let png = encode_png(image)?; + let dir = TempDir::create()?; + let png_path = dir.path.join("page.png"); + { + let mut f = std::fs::File::create(&png_path).map_err(|e| OcrError::Process(format!("creating the image file failed: {e}")))?; + set_private(&mut f); + f.write_all(&png).map_err(|e| OcrError::Process(format!("writing the image failed: {e}")))?; + } + // Fixed argv, no shell: tesseract stdout -l tsv. + let tsv = self.run(&[&png_path.to_string_lossy(), "stdout", "-l", lang, "tsv"], self.timeout, self.max_output)?; + let (lines, truncated) = parse_tsv_bounded(&tsv); + if truncated { + return Err(OcrError::Recognize(format!("the {MAX_WORDS}-word limit was exceeded; the incomplete reading was rejected"))); + } + Ok(lines) + } +} + +/// Encode an RGBA raster as PNG (the interchange format Tesseract reads best). +fn encode_png(image: &OcrImage) -> Result, OcrError> { + let mut out = Vec::new(); + let mut enc = png::Encoder::new(&mut out, image.width, image.height); + enc.set_color(png::ColorType::Rgba); + enc.set_depth(png::BitDepth::Eight); + let mut writer = enc.write_header().map_err(|e| OcrError::Process(format!("encoding the page image failed: {e}")))?; + writer.write_image_data(&image.rgba).map_err(|e| OcrError::Process(format!("encoding the page image failed: {e}")))?; + writer.finish().map_err(|e| OcrError::Process(format!("encoding the page image failed: {e}")))?; + Ok(out) +} + +/// Make a just-created file owner-only, where the OS supports it (Unix). Windows relies on the +/// user's private %TEMP% ACLs; the fresh directory keeps other sessions' files out of sight. +fn set_private(f: &mut std::fs::File) { + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let _ = f.set_permissions(std::fs::Permissions::from_mode(0o600)); + } + #[cfg(not(unix))] + let _ = f; +} + +/// A fresh directory under the system temp dir, deleted (with its contents) when dropped. +/// On Unix it is created 0700, so the page image inside is private. +struct TempDir { + path: PathBuf, +} + +impl TempDir { + fn create() -> Result { + // The recognizer is shared across threads (`Arc`), so two `recognize` calls can run at + // once, and on a coarse clock they can read the same nanosecond. One counter value per + // attempt keeps the names of one process apart without trusting the clock. + static SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let nanos = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_nanos()).unwrap_or(0); + // Created owner-only in one step on Unix (no window in which the directory exists with + // the default, wider mode); `create` refuses a path that already exists. + let mut builder = std::fs::DirBuilder::new(); + #[cfg(unix)] + { + use std::os::unix::fs::DirBuilderExt; + builder.mode(0o700); + } + // Elsewhere the default mode stands (Windows relies on the user's private %TEMP% ACLs). + #[cfg(not(unix))] + let _ = &mut builder; + // A leftover directory of an earlier process with the same pid can still take a name; + // that one collision is retried with the next counter value, anything else is fatal. + for _ in 0..4 { + let seq = SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + let path = std::env::temp_dir().join(format!("pdfcraft-ocr-{}-{nanos}-{seq}", std::process::id())); + match builder.create(&path) { + Ok(()) => return Ok(TempDir { path }), + Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue, + Err(e) => return Err(OcrError::Process(format!("creating the private temp directory failed: {e}"))), + } + } + Err(OcrError::Process("creating the private temp directory failed: every candidate name already exists".into())) + } +} + +impl Drop for TempDir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.path); + } +} + +#[cfg(test)] +mod tests { + use super::*; + // The Unix process tests below build fake scripts and name their paths. + #[cfg(unix)] + use std::path::Path; + + /// Several directories alive at once never share a name: the recognizer is shared across + /// threads (`Arc`), so two `recognize` calls can create their directories concurrently, + /// and the counter in the name — not the clock alone — tells them apart. + #[test] + fn temp_directories_alive_at_once_have_distinct_names() { + let dirs: Vec = (0..32).map(|_| TempDir::create().expect("create")).collect(); + let distinct: std::collections::BTreeSet = dirs.iter().map(|d| d.path.clone()).collect(); + assert_eq!(distinct.len(), dirs.len(), "{:?}", dirs.iter().map(|d| &d.path).collect::>()); + } + + /// A tiny image with one dark square (a synthetic "word"); the Unix process tests use it. + #[cfg(unix)] + fn blot(w: u32, h: u32, x0: u32, y0: u32, bw: u32, bh: u32) -> OcrImage { + let mut rgba = vec![255u8; (w * h * 4) as usize]; + for y in y0..(y0 + bh).min(h) { + for x in x0..(x0 + bw).min(w) { + let o = ((y * w + x) * 4) as usize; + rgba[o..o + 3].copy_from_slice(&[0, 0, 0]); + } + } + OcrImage::new(w, h, rgba).unwrap() + } + + /// The literal TSV fixture: two header rows (conf −1) and two lines of words. + const TSV: &str = "level\tpage\tblock\tpar\tline\tword\tleft\ttop\twidth\theight\tconf\ttext +1\t1\t0\t0\t0\t0\t0\t0\t100\t50\t-1\t +5\t1\t1\t1\t1\t1\t10\t10\t40\t12\t96.5\tHello +5\t1\t1\t1\t1\t2\t55\t10\t30\t12\t91.0\tworld +5\t1\t1\t2\t2\t1\t10\t30\t20\t12\t42.123\tsecond"; + + #[test] + fn tsv_parses_words_into_lines() { + let lines = parse_tsv(TSV); + assert_eq!(lines.len(), 2, "two (block, par, line) groups: {lines:?}"); + let first = &lines[0].words; + assert_eq!(first.len(), 2); + assert_eq!(first[0].text, "Hello"); + assert_eq!(first[0].rect, [10.0, 10.0, 50.0, 22.0], "left + width, top + height"); + assert_eq!(first[0].confidence, Some(96.5)); + assert_eq!(first[0].source, "tesseract"); + assert_eq!(first[1].text, "world"); + assert_eq!(lines[1].words.len(), 1, "a new par starts a new line"); + assert_eq!(lines[1].words[0].text, "second"); + assert_eq!(lines[1].words[0].confidence, Some(42.123)); + } + + /// Conf −1 rows and level ≠ 5 rows are structure, not words; blank text is dropped. + #[test] + fn tsv_treats_header_rows_and_blank_text_as_not_words() { + let tsv = "5\t1\t1\t1\t1\t1\t0\t0\t10\t10\t-1\tskipped\n\ + 4\t1\t1\t1\t1\t0\t0\t0\t10\t10\t95.0\tline row\n\ + 5\t1\t1\t1\t1\t1\t0\t0\t10\t10\t95.0\t \n\ + 5\t1\t1\t1\t1\t2\t0\t0\t10\t10\t88\tkept"; + let lines = parse_tsv(tsv); + assert_eq!(lines.len(), 1, "{lines:?}"); + assert_eq!(lines[0].words.len(), 1); + assert_eq!(lines[0].words[0].text, "kept"); + } + + /// Garbage rows (short, non-numeric) are skipped; CRLF endings survive; boxes saturate + /// instead of overflowing. + #[test] + fn tsv_skips_garbage_and_never_panics() { + let lines = parse_tsv("not a tsv row\n\n5\t1\t1\n5\t1\t1\t1\t1\t1\tx\ty\tw\th\tzzz\ttext\r\n"); + assert!(lines.is_empty(), "{lines:?}"); + let big = parse_tsv(&format!("5\t1\t1\t1\t1\t1\t{}\t0\t{}\t10\t50\tbig", u32::MAX, u32::MAX)); + let rect = big[0].words[0].rect; + assert!(rect[2].is_finite() && rect[3].is_finite(), "no overflow: {rect:?}"); + // A row whose text field is empty yields no words. + assert!(parse_tsv("5\t1\t1\t1\t1\t1\t1\t1\t2\t2\t50\t\t").is_empty()); + } + + /// Non-finite numbers and negative sizes are not words: a row with NaN/inf coordinates or + /// a negative width/height never reaches the output (and so never reaches the content + /// stream). `1e39` overflows f32 to infinity, so it is refused the same way. + #[test] + fn tsv_rejects_non_finite_and_negative_geometry() { + let row = |left: &str, top: &str, w: &str, h: &str, conf: &str| format!("5\t1\t1\t1\t1\t1\t{left}\t{top}\t{w}\t{h}\t{conf}\tword"); + for (why, r) in [ + ("NaN left", row("NaN", "0", "10", "10", "50")), + ("NaN width", row("0", "0", "NaN", "10", "50")), + ("NaN height", row("0", "0", "10", "NaN", "50")), + ("NaN confidence", row("0", "0", "10", "10", "NaN")), + ("inf left", row("inf", "0", "10", "10", "50")), + ("inf width", row("0", "0", "inf", "10", "50")), + ("1e39 width overflows to inf", row("0", "0", "1e39", "10", "50")), + ("negative width", row("0", "0", "-10", "10", "50")), + ("negative height", row("0", "0", "10", "-10", "50")), + ] { + let lines = parse_tsv(&r); + assert!(lines.is_empty(), "{why}: {lines:?}"); + } + // A sane row still parses. + assert_eq!(parse_tsv(&row("0", "0", "10", "10", "50"))[0].words[0].text, "word"); + } + + /// A reading longer than the word cap is truncated at [`MAX_WORDS`] (a known limit, not an + /// error): the words before the cap are kept, the rest is dropped. + #[test] + fn tsv_truncates_readings_past_the_word_cap() { + let mut tsv = String::new(); + for i in 0..MAX_WORDS + 5 { + tsv.push_str(&format!("5\t1\t1\t1\t1\t{}\t{}\t10\t40\t12\t96.5\tw{i}\n", i % 7 + 1, i % 500)); + } + let lines = parse_tsv(&tsv); + let count: usize = lines.iter().map(|l| l.words.len()).sum(); + assert_eq!(count, MAX_WORDS, "truncated at the cap"); + assert_eq!(lines.last().and_then(|l| l.words.last()).map(|w| w.text.as_str()), Some(&*format!("w{}", MAX_WORDS - 1))); + } + + #[test] + fn language_table_maps_and_falls_back() { + assert_eq!(language_code("en"), "eng"); + assert_eq!(language_code(" EN "), "eng", "trimmed, case-insensitive"); + assert_eq!(language_code("de"), "deu"); + assert_eq!(language_code("ZH"), "chi_sim"); + assert_eq!(language_code("ja"), "jpn"); + assert_eq!(language_code("ko"), "kor"); + assert_eq!(language_code("nl"), "nld"); + assert_eq!(language_code("klingon"), "eng", "unknown → eng"); + assert_eq!(language_code(""), "eng"); + // The security property: whatever the settings say, only allow-listed codes reach a + // process. + for code in ["en", "de", "fr", "es", "it", "pt", "ru", "zh", "ja", "ko", "ar", "nl", "klingon", "", " eng ", "EN/;rm"] { + let mapped = language_code(code); + assert!(LANGUAGE_CODES.iter().any(|(_, v)| *v == mapped), "{code:?} → {mapped:?} is not allow-listed"); + } + } + + #[test] + fn list_langs_come_from_stderr_when_stdout_has_none() { + let listing = "List of available languages in \"/usr/share/tessdata/\" (2):\neng\nosd\n"; + assert_eq!(list_langs_from(listing, ""), ["eng", "osd"]); + assert_eq!(list_langs_from("", listing), ["eng", "osd"], "3.x prints the list on stderr"); + assert_eq!(list_langs_from("", "Error opening data file\n"), Vec::::new(), "a warning is not a language"); + assert_eq!(list_langs_from("eng\n", "deu\n"), ["eng"], "stdout wins when it has the list"); + } + + /// The private temp directory is created owner-only (Unix) and removed on drop. + #[test] + fn temp_dir_is_private_and_removed() { + let dir = TempDir::create().unwrap(); + let path = dir.path.clone(); + assert!(path.is_dir()); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + assert_eq!(std::fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o700); + } + drop(dir); + assert!(!path.exists()); + } + + /// A set `PDFCRAFT_TESSERACT` decides alone: when it is invalid, [`TesseractCli::find`] does + /// not fall back to a PATH copy (which would run a program the user did not name); the PATH + /// search only runs when nothing is configured. + #[test] + fn an_invalid_configured_program_fails_closed() { + let Ok(real) = std::env::current_exe() else { return }; + let searched = std::cell::Cell::new(false); + let on_path = || { + searched.set(true); + Some(real.clone()) + }; + assert_eq!(locate(None, on_path), Some(real.clone()), "nothing configured: the PATH search decides"); + assert!(searched.get()); + searched.set(false); + assert_eq!(locate(Some(real.clone().into_os_string()), on_path), Some(real.clone()), "a valid location is used as is"); + assert!(!searched.get(), "and the PATH is not searched"); + let dir = real.parent().map(Path::to_path_buf).unwrap_or_default().into_os_string(); + for bad in [std::ffi::OsString::from("relative/tesseract"), std::ffi::OsString::from(""), dir, "/no/such/program-0123456789".into()] { + assert_eq!(locate(Some(bad.clone()), on_path), None, "{bad:?} is invalid, so there is no program"); + assert!(!searched.get(), "{bad:?}: an invalid location never falls back to the PATH"); + } + } + + #[test] + fn the_version_comes_from_stdout_or_stderr() { + assert_eq!(version_line("tesseract 5.4.0\n leptonica-1.84\n", ""), Some("tesseract 5.4.0".into())); + assert_eq!(version_line("", "\ntesseract 4.0.0\n"), Some("tesseract 4.0.0".into()), "older versions print it on stderr"); + assert_eq!(version_line(" \n", ""), None); + } + + #[test] + fn list_langs_output_parses() { + let out = "List of available languages in \"C:\\Program Files\\Tesseract-OCR\\tessdata/\" (2):\neng\nosd\n"; + assert_eq!(parse_list_langs(out), vec!["eng".to_string(), "osd".to_string()]); + assert_eq!(parse_list_langs("List of available languages (1):\neng\n"), vec!["eng".to_string()]); + assert!(parse_list_langs("").is_empty()); + } + + /// The real binary, when it is installed: a run end to end, with words that carry a + /// confidence and the engine's name (skipped where `tesseract` is missing). + #[test] + fn recognize_runs_the_installed_binary() { + let Some(t) = TesseractCli::find() else { + eprintln!("skipped: the tesseract program is not installed"); + return; + }; + assert_eq!(t.id(), "tesseract"); + assert!(t.available()); + // 300 dpi-ish block capitals, black on white. + let (w, h, rgba) = hello_world_image(); + let image = OcrImage::new(w, h, rgba).unwrap(); + let lines = t.recognize(&image, &RecognizeOptions::default()).unwrap(); + let text: Vec = lines.iter().map(Line::text).collect(); + assert!(text.iter().any(|t| t.to_uppercase().contains("HELL")), "{text:?}"); + let words: Vec<&Word> = lines.iter().flat_map(|l| &l.words).collect(); + assert!(words.iter().all(|w| w.source == "tesseract")); + assert!(words.iter().all(|w| matches!(w.confidence, Some(c) if (0.0..=100.0).contains(&c))), "{words:?}"); + } + + /// `available`/`languages` come from `--list-langs` (skipped without the binary). + #[test] + fn languages_come_from_list_langs() { + let Some(t) = TesseractCli::find() else { + eprintln!("skipped: the tesseract program is not installed"); + return; + }; + let langs = t.languages(); + assert!(!langs.is_empty()); + assert!(langs.iter().all(|(c, n)| !c.is_empty() && !n.is_empty()), "{langs:?}"); + } + + #[cfg(unix)] + #[test] + fn recognize_refuses_a_truncated_reading() { + let dir = TempDir::create().unwrap(); + let script = dir.path.join("synthetic-recognizer"); + let mut tsv = String::new(); + for i in 0..=MAX_WORDS { + use std::fmt::Write as _; + writeln!(tsv, "5\t1\t1\t1\t1\t{i}\t0\t0\t1\t1\t95\tword{i}").unwrap(); + } + let exact = tsv.lines().take(MAX_WORDS).collect::>().join("\n"); + std::fs::write(dir.path.join("reading.tsv"), tsv).unwrap(); + std::fs::write(&script, "#!/bin/sh\ncat \"$(dirname \"$0\")/reading.tsv\"\n").unwrap(); + make_executable(&script); + let recognizer = TesseractCli::new(script); + let result = recognizer.recognize(&blot(8, 8, 0, 0, 4, 4), &RecognizeOptions::default()); + let status = result.as_ref().map(|lines| lines.iter().map(|line| line.words.len()).sum::()).map_err(ToString::to_string); + assert!( + matches!(result, Err(OcrError::Recognize(ref reason)) if reason.contains("word limit")), + "a capped reading must be reported, never accepted as complete: {status:?}" + ); + std::fs::write(dir.path.join("reading.tsv"), exact).unwrap(); + let complete = recognizer.recognize(&blot(8, 8, 0, 0, 4, 4), &RecognizeOptions::default()).unwrap(); + assert_eq!(complete.iter().map(|line| line.words.len()).sum::(), MAX_WORDS); + } + + /// A hung binary is killed at the timeout and reported (Unix: a fake `tesseract` script; + /// this test needs a real process, so it is off the web and off Windows). + #[cfg(unix)] + #[test] + fn a_hung_program_is_killed_at_the_timeout() { + let dir = std::env::temp_dir().join(format!("pdfcraft-ocr-test-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let script = dir.join("tesseract-hang"); + std::fs::write(&script, "#!/bin/sh\nsleep 30\n").unwrap(); + make_executable(&script); + let mut t = TesseractCli::new(script); + t.timeout = Duration::from_millis(500); + let started = Instant::now(); + let r = t.recognize(&blot(8, 8, 0, 0, 4, 4), &RecognizeOptions::default()); + assert!(matches!(r, Err(OcrError::Timeout(_))), "{r:?}"); + assert!(started.elapsed() < Duration::from_secs(10), "killed, not waited out"); + let _ = std::fs::remove_dir_all(&dir); + } + + /// Output past the cap kills the run EARLY, while the child is still writing (Unix only, + /// same fake-script trick): the script floods far past the cap and would sleep for 30 s + /// after; a cap checked only after the exit would come back as a timeout instead. + #[cfg(unix)] + #[test] + fn flooding_output_is_capped_and_killed_early() { + let dir = std::env::temp_dir().join(format!("pdfcraft-ocr-test-cap-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let script = dir.join("tesseract-flood"); + std::fs::write(&script, "#!/bin/sh\nhead -c 100000000 /dev/zero | tr '\\0' 'x'\nsleep 30\n").unwrap(); + make_executable(&script); + let mut t = TesseractCli::new(script); + t.max_output = 1024; + t.timeout = Duration::from_secs(20); + let started = Instant::now(); + let r = t.recognize(&blot(8, 8, 0, 0, 4, 4), &RecognizeOptions::default()); + assert!(matches!(r, Err(OcrError::OutputTooLarge(_))), "{r:?}"); + assert!(started.elapsed() < Duration::from_secs(10), "killed early, at {:?}", started.elapsed()); + let _ = std::fs::remove_dir_all(&dir); + } + + /// An stderr flood does not block the child, so it does not cause a false timeout (Unix + /// only): the script writes megabytes of stderr — far more than a pipe would swallow — + /// then exits successfully with a small output, which must come back as a reading. + #[cfg(unix)] + #[test] + fn an_stderr_flood_does_not_cause_a_false_timeout() { + let dir = std::env::temp_dir().join(format!("pdfcraft-ocr-test-err-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let script = dir.join("tesseract-err-flood"); + // (below MAX_STDERR, past which the child is stopped: `an_stderr_flood_is_killed_while_the_child_runs`) + std::fs::write(&script, "#!/bin/sh\nhead -c 200000 /dev/zero | tr '\\0' 'e' >&2\necho flooded away\n").unwrap(); + make_executable(&script); + let mut t = TesseractCli::new(script); + t.timeout = Duration::from_secs(10); + let r = t.recognize(&blot(8, 8, 0, 0, 4, 4), &RecognizeOptions::default()); + assert!(r.is_ok(), "stderr flood must not fail the run: {r:?}"); + let _ = std::fs::remove_dir_all(&dir); + } + + /// The child runs with a minimal environment (its data prefix, the PATH, the Windows + /// system root, and a temp dir), never the caller's whole environ. This is checked with a + /// script that prints its own environ as the "TSV" (Unix only). + #[cfg(unix)] + #[test] + fn the_child_gets_a_minimal_environment() { + let dir = std::env::temp_dir().join(format!("pdfcraft-ocr-test-env-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let script = dir.join("tesseract-env"); + std::fs::write(&script, "#!/bin/sh\nenv | grep -v '^_='\n").unwrap(); + make_executable(&script); + let t = TesseractCli::new(script); + let png = encode_png(&blot(8, 8, 0, 0, 4, 4)).unwrap(); + std::fs::write(dir.join("page.png"), png).unwrap(); + let png_arg = dir.join("page.png").to_string_lossy().into_owned(); + let tsv = t.run(&[png_arg.as_str(), "stdout", "-l", "eng", "tsv"], t.timeout, t.max_output).unwrap(); + for (why, name) in [("the child's temp dir", "TMP="), ("temp", "TEMP="), ("lookup path", "PATH=")] { + assert!(tsv.contains(name), "{why} must be passed: {tsv}"); + } + // cargo always sets CARGO_* for the test process; env_clear must drop them. + assert!(!tsv.contains("CARGO_"), "the caller's environment must not leak: {tsv}"); + let _ = std::fs::remove_dir_all(&dir); + } + + #[cfg(unix)] + fn make_executable(p: &Path) { + use std::os::unix::fs::PermissionsExt; + let _ = std::fs::set_permissions(p, std::fs::Permissions::from_mode(0o755)); + } + + /// The temp directory and its contents are gone after a run (private files do not linger). + #[cfg(unix)] + #[test] + fn temp_files_are_deleted_and_private() { + let dir = TempDir::create().unwrap(); + assert!(dir.path.is_dir()); + std::fs::write(dir.path.join("x"), b"secret").unwrap(); + let p = dir.path.clone(); + drop(dir); + assert!(!p.exists(), "the temp directory is deleted after use"); + } + + /// A configured program location is only usable as an absolute path to an existing, + /// executable file: a relative path, a missing file and a directory are unavailable (and + /// [`TesseractCli::at`] refuses them without spawning anything). + #[test] + fn a_configured_program_must_be_an_absolute_executable_file() { + assert!(!program_is_executable(Path::new(".")), "relative"); + assert!(!program_is_executable(Path::new("definitely/missing/tesseract")), "missing"); + let temp = std::env::temp_dir(); + assert!(!program_is_executable(&temp), "a directory is not a program"); + let file = temp.join(format!("pdfcraft-ocr-not-a-program-{}", std::process::id())); + std::fs::write(&file, b"").unwrap(); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let _ = std::fs::set_permissions(&file, std::fs::Permissions::from_mode(0o644)); + assert!(!program_is_executable(&file), "a file without executable bits is not a program"); + } + #[cfg(not(unix))] + assert!(program_is_executable(&file), "an existing file is usable on this platform"); + let _ = std::fs::remove_file(&file); + // `at` validates before any process starts, so these are None and not panics. + assert!(TesseractCli::at(PathBuf::from(".")).is_none()); + assert!(TesseractCli::at(temp).is_none()); + assert!(TesseractCli::at(PathBuf::from("definitely/missing/tesseract")).is_none()); + } + + /// The PATH search resolves through absolute entries only and skips relative ones: a + /// relative PATH entry would resolve against the caller's working directory. + #[test] + fn path_search_skips_relative_entries() { + let dir = std::env::temp_dir().join(format!("pdfcraft-ocr-path-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let program = dir.join(program_file_names()[0]); + std::fs::write(&program, b"").unwrap(); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let _ = std::fs::set_permissions(&program, std::fs::Permissions::from_mode(0o755)); + } + let found = path_search_in([PathBuf::from("relative/dir"), PathBuf::from("definitely/missing"), dir.clone()].into_iter()); + assert_eq!(found.as_deref(), Some(program.as_path()), "the absolute entry with the program wins, relative entries are skipped"); + let none = path_search_in([PathBuf::from("relative/dir")].into_iter()); + assert_eq!(none, None, "only relative entries: nothing is found"); + let _ = std::fs::remove_dir_all(&dir); + } + + /// "HELLO" as blocky 5×7 glyphs, 8 pixels per dot with wide tracking, at roughly 300 dpi + /// scale (each dot ~10 px): big enough for Tesseract's word detector. + fn hello_world_image() -> (u32, u32, Vec) { + const GLYPHS: &[&str] = &[ + "X...X", "X...X", "X...X", "XXXXX", "X...X", "X...X", "X...X", // H + ]; + // Draw the five glyphs of HELLO with per-letter shapes for E, L, L, O. + const E: &[&str] = &["XXXXX", "X....", "X....", "XXXX.", "X....", "X....", "XXXXX"]; + const L: &[&str] = &["X....", "X....", "X....", "X....", "X....", "X....", "XXXXX"]; + const O: &[&str] = &[".XXX.", "X...X", "X...X", "X...X", "X...X", "X...X", ".XXX."]; + let letters: [&[&str]; 5] = [GLYPHS, E, L, L, O]; + let (dot, x0, y0, advance) = (8u32, 40u32, 40u32, 7u32 * 8); + let w = x0 * 2 + advance * 5; + let h = y0 * 2 + 7 * dot; + let mut rgba = vec![255u8; (w * h * 4) as usize]; + for (i, rows) in letters.iter().enumerate() { + for (ry, row) in rows.iter().enumerate() { + for (rx, b) in row.bytes().enumerate() { + if b != b'X' { + continue; + } + for dy in 0..dot { + for dx in 0..dot { + let x = x0 + i as u32 * advance + rx as u32 * dot + dx; + let y = y0 + ry as u32 * dot + dy; + let o = ((y * w + x) * 4) as usize; + rgba[o..o + 3].copy_from_slice(&[0, 0, 0]); + } + } + } + } + } + (w, h, rgba) + } +} + +#[cfg(all(test, unix))] +mod process_tests { + use super::*; + + /// A stderr flood is killed at the cap while the child still runs, not accepted until it + /// exits (an endless writer would otherwise run out the whole timeout and fill the disk). + /// The fixture needs a Unix shell, like the other process fixtures. + #[test] + fn a_stderr_flood_is_killed_while_the_child_runs() { + let dir = std::env::temp_dir().join(format!("pdfcraft-tesseract-flood-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let program = dir.join("flood-tesseract"); + std::fs::write(&program, "#!/bin/sh\nwhile true; do echo aaaaaaaaaaaaaaaaaaaaaaaa >&2; done\n").unwrap(); + use std::os::unix::fs::PermissionsExt; + let mut perms = std::fs::metadata(&program).unwrap().permissions(); + perms.set_mode(0o755); + std::fs::set_permissions(&program, perms).unwrap(); + let t = TesseractCli::new(program); + let started = std::time::Instant::now(); + let err = t.run_capture(&["--list-langs"], Duration::from_secs(60), 1024 * 1024).unwrap_err(); + assert!(matches!(err, OcrError::OutputTooLarge(_)), "{err}"); + assert!(started.elapsed() < Duration::from_secs(30), "killed at the cap, not at the timeout"); + let _ = std::fs::remove_dir_all(&dir); + } +} diff --git a/crates/preflight/fuzz/Cargo.toml b/crates/preflight/fuzz/Cargo.toml new file mode 100644 index 0000000000..0e9e77f105 --- /dev/null +++ b/crates/preflight/fuzz/Cargo.toml @@ -0,0 +1,32 @@ +[package] +name = "pdfcraft-preflight-fuzz" +version = "0.0.0" +publish = false +edition = "2024" +license = "MIT OR Apache-2.0" + +[package.metadata] +cargo-fuzz = true + +# Detached from the PdfCraft workspace: run with `cargo +nightly fuzz run verify` +# from crates/preflight/. +[workspace] + +[dependencies] +libfuzzer-sys = "0.4" +pdfcraft-cos = { path = "../../cos" } +pdfcraft-preflight = { path = ".." } + +[[bin]] +name = "verify" +path = "fuzz_targets/verify.rs" +test = false +doc = false +bench = false + +[[bin]] +name = "convert" +path = "fuzz_targets/convert.rs" +test = false +doc = false +bench = false diff --git a/crates/preflight/fuzz/fuzz_targets/convert.rs b/crates/preflight/fuzz/fuzz_targets/convert.rs new file mode 100644 index 0000000000..6340bd585e --- /dev/null +++ b/crates/preflight/fuzz/fuzz_targets/convert.rs @@ -0,0 +1,21 @@ +//! Feeds arbitrary bytes to `convert` at level A2b; the report it returns is discarded. +#![no_main] + +use std::sync::Arc; + +use libfuzzer_sys::fuzz_target; +use pdfcraft_cos::Document; +use pdfcraft_preflight::{Level, convert}; + +/// Largest input the target parses; a longer input is dropped before `Document::open` copies it. +const MAX_INPUT: usize = 16 << 20; + +fuzz_target!(|data: &[u8]| { + if data.len() > MAX_INPUT { + return; + } + let Ok(mut doc) = Document::open(Arc::new(data.to_vec())) else { + return; + }; + let _ = convert(&mut doc, Level::A2b); +}); diff --git a/crates/preflight/fuzz/fuzz_targets/verify.rs b/crates/preflight/fuzz/fuzz_targets/verify.rs new file mode 100644 index 0000000000..7d02aa3ca4 --- /dev/null +++ b/crates/preflight/fuzz/fuzz_targets/verify.rs @@ -0,0 +1,22 @@ +//! Feeds arbitrary bytes to `verify` at both levels; the issue list it returns is discarded. +#![no_main] + +use std::sync::Arc; + +use libfuzzer_sys::fuzz_target; +use pdfcraft_cos::Document; +use pdfcraft_preflight::{Level, verify}; + +/// Largest input the target parses; a longer input is dropped before `Document::open` copies it. +const MAX_INPUT: usize = 16 << 20; + +fuzz_target!(|data: &[u8]| { + if data.len() > MAX_INPUT { + return; + } + let Ok(doc) = Document::open(Arc::new(data.to_vec())) else { + return; + }; + let _a2b = verify(&doc, Level::A2b); + let _a3b = verify(&doc, Level::A3b); +}); diff --git a/crates/preflight/src/lib.rs b/crates/preflight/src/lib.rs index 1fb7272b33..5fdec67fac 100644 --- a/crates/preflight/src/lib.rs +++ b/crates/preflight/src/lib.rs @@ -877,6 +877,9 @@ pub fn convert(doc: &mut Document, level: Level) -> Result Document { + let mut out = b"%PDF-1.7\n".to_vec(); + let mut offsets = Vec::new(); + for (i, o) in objs.iter().enumerate() { + offsets.push(out.len()); + out.extend_from_slice(format!("{} 0 obj\n{o}\nendobj\n", i + 1).as_bytes()); + } + let xref = out.len(); + out.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objs.len() + 1).as_bytes()); + for o in offsets { + out.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes()); + } + out.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R {trailer_extra} >>\nstartxref\n{xref}\n%%EOF\n", objs.len() + 1).as_bytes()); + Document::open(std::sync::Arc::new(out)).unwrap() +} + +/// One page whose `/Annots` lists a Sound annotation (forbidden by clause 6.3.1) and a link. +fn page_with_a_forbidden_sound_annotation() -> Document { + build( + &[ + "<< /Type /Catalog /Pages 2 0 R >>", + "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 200 200] >>", + "<< /Type /Page /Parent 2 0 R /Annots [4 0 R 5 0 R] >>", + "<< /Type /Annot /Subtype /Sound /Rect [10 10 30 30] /P 3 0 R /F 4 >>", + "<< /Type /Annot /Subtype /Link /Rect [40 40 60 60] /P 3 0 R /F 4 /Border [0 0 0] >>", + ], + "", + ) +} + +/// The forbidden annotation is reported before `convert` and by neither `convert` nor a later +/// `verify` afterwards: the object it took off the page is no longer an annotation. +#[test] +fn convert_removes_the_forbidden_annotation_clause_6_3_1() { + let mut doc = page_with_a_forbidden_sound_annotation(); + let before = verify(&doc, Level::A2b); + assert!(before.iter().any(|i| i.clause == "6.3.1"), "the fixture starts with the finding: {before:#?}"); + let report = convert(&mut doc, Level::A2b).unwrap(); + assert!(!report.remaining.iter().any(|i| i.clause == "6.3.1"), "6.3.1 remains after convert: {:#?}", report.remaining); + let after = verify(&doc, Level::A2b); + assert!(!after.iter().any(|i| i.clause == "6.3.1"), "6.3.1 is reported after convert: {after:#?}"); +} + +/// The page keeps its other annotation: only the forbidden one leaves `/Annots`. +#[test] +fn convert_keeps_the_other_annotations_on_the_page() { + let mut doc = page_with_a_forbidden_sound_annotation(); + convert(&mut doc, Level::A2b).unwrap(); + let page = doc.get(ObjRef::new(3, 0)); + let dict = page.as_dict().expect("the page is a dictionary"); + let annots = doc.resolve(dict.get(b"Annots").expect("the page has /Annots")); + let kept: Vec = annots.as_array().expect("the page's /Annots is an array").iter().filter_map(Object::as_ref).collect(); + assert_eq!(kept, vec![ObjRef::new(5, 0)]); +} diff --git a/crates/preflight/tests/known_answers.rs b/crates/preflight/tests/known_answers.rs new file mode 100644 index 0000000000..23d503dc62 --- /dev/null +++ b/crates/preflight/tests/known_answers.rs @@ -0,0 +1,403 @@ +//! What `verify` answers for each clause it implements, pinned as a known answer. +//! +//! Each test builds a small file by hand, from the shape the clause describes rather than from +//! anything this repository saves, so a bug shared between the verifier and the writer cannot make a +//! case pass. Two things in the file are not hand-written: the output intent profiles come from +//! `icc::srgb()`, the crate's own sRGB generator, and the encrypted document in the 6.1.3 case is +//! encrypted by the object layer, because writing an encryption dictionary by hand would restate the +//! rules under test. +//! +//! The clause strings are the verifier's own citations, pinned here as `lib.rs` writes them. They +//! have not been compared with the text of the profile yet, so a number that does not name the rule +//! it is attached to is a finding about the verifier and not about this file. +//! +//! The positive case expects no issue under the clause and the negative case expects one; both are +//! asserted by clause string, so a later change that alters an answer fails here first. Cases where +//! the verifier is known to disagree with the standard are left out on purpose and recorded as gaps +//! where the change that adds them is reviewed. Nothing here is a conformance claim. + +use pdfcraft_cos::{Algorithm, Document, NewEncryption}; +use pdfcraft_preflight::{Level, convert, declared, icc, verify}; + +/// A document from hand-written objects and extra trailer entries (copied from the crate's unit +/// tests). +fn build(objs: &[&str], trailer_extra: &str) -> Document { + let mut out = b"%PDF-1.7\n".to_vec(); + let mut offsets = Vec::new(); + for (i, o) in objs.iter().enumerate() { + offsets.push(out.len()); + out.extend_from_slice(format!("{} 0 obj\n{o}\nendobj\n", i + 1).as_bytes()); + } + let xref = out.len(); + out.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objs.len() + 1).as_bytes()); + for o in offsets { + out.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes()); + } + out.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R {trailer_extra} >>\nstartxref\n{xref}\n%%EOF\n", objs.len() + 1).as_bytes()); + Document::open(std::sync::Arc::new(out)).unwrap() +} + +/// The byte-order mark an XMP packet's `xpacket` instruction names. +const BOM: char = '\u{feff}'; + +/// The XMP packet identifying a file as `part`/`conformance`, with `title` as its `dc:title`. +fn xmp(part: u8, conformance: &str, title: Option<&str>) -> String { + let title = match title { + Some(t) => format!(" {t}\n"), + None => String::new(), + }; + format!( + r#" + + + + {part} + {conformance} +{title} + + +"# + ) +} + +/// The XMP packet of a PDF/A-2b file, with `title` as its title when one is given. +fn a2b_packet(title: Option<&str>) -> String { + xmp(2, "B", title) +} + +/// The catalog's `/Metadata` stream object holding `packet`. +fn xmp_object(packet: &str) -> String { + format!("<< /Type /Metadata /Subtype /XML /Length {} >>\nstream\n{packet}\nendstream", packet.len()) +} + +/// A content stream object holding `content`. +fn content(content: &str) -> String { + format!("<< /Length {} >>\nstream\n{content}\nendstream", content.len()) +} + +/// An ASCII-hex stream object holding `bytes`, with `dict` as its other entries. +fn hex_stream(dict: &str, bytes: &[u8]) -> String { + let hex: String = bytes.iter().map(|b| format!("{b:02X}")).collect(); + let data = format!("{hex}>"); + format!("<< /Filter /ASCIIHexDecode {dict} /Length {} >>\nstream\n{data}\nendstream", data.len()) +} + +/// A 128-byte ICC header for a four-component profile, with no `/N` so the header decides. +fn cmyk_profile_header() -> Vec { + let mut header = vec![0u8; 128]; + header[0..4].copy_from_slice(&128u32.to_be_bytes()); + header[16..20].copy_from_slice(b"CMYK"); + header[20..24].copy_from_slice(b"XYZ "); + header[36..40].copy_from_slice(b"acsp"); + header +} + +/// The catalog's `/OutputIntents`: a `GTS_PDFA1` intent naming the profile in object `n`. +fn output_intent(n: usize) -> String { + let condition = "/OutputConditionIdentifier (sRGB IEC61966-2.1)"; + let intent = format!("<< /Type /OutputIntent /S /GTS_PDFA1 {condition} /DestOutputProfile {n} 0 R >>"); + format!("/OutputIntents [{intent}]") +} + +/// An embedded font program stream object, compressed with `filter` when one is given. Its bytes +/// are not read by any rule: a font program is data, not content. +fn font_program(filter: Option<&str>) -> String { + let filter = match filter { + Some(filter) => format!("/Filter {filter} "), + None => String::new(), + }; + format!("<< /Length1 4 {filter}/Length 4 >>\nstream\nabcd\nendstream") +} + +/// An image XObject that asks to be interpolated, or does not. +fn image(interpolate: bool) -> String { + format!( + "<< /Type /XObject /Subtype /Image /Width 1 /Height 1 /ColorSpace /DeviceGray /BitsPerComponent 8 /Interpolate {interpolate} /Length 1 >>\nstream\n\u{0}\nendstream" + ) +} + +/// A document whose catalog (object 1) carries `catalog_extra` and, when `packet` is given, the +/// metadata object 3; whose page tree (object 2) holds the single page `page` (object 4); and whose +/// objects 5 onwards are `more`, which `page` and `catalog_extra` refer to by number. An absent +/// `packet` leaves object 3 empty. The page must resolve, so a case that loses it fails instead of +/// passing because no rule ever reached it. +fn page_document(page: &str, packet: Option<&str>, catalog_extra: &str, more: &[&str], trailer_extra: &str) -> Document { + let metadata = match packet { + Some(packet) => xmp_object(packet), + None => "null".to_owned(), + }; + let catalog = match packet { + Some(_) => format!("<< /Type /Catalog /Pages 2 0 R /Metadata 3 0 R {catalog_extra} >>"), + None => format!("<< /Type /Catalog /Pages 2 0 R {catalog_extra} >>"), + }; + let pages = "<< /Type /Pages /Kids [4 0 R] /Count 1 /MediaBox [0 0 200 200] >>"; + let mut objs = vec![catalog.as_str(), pages, metadata.as_str(), page]; + objs.extend_from_slice(more); + let doc = build(&objs, trailer_extra); + assert_eq!(pdfcraft_model::pages(&doc).len(), 1, "the page of this case does not resolve"); + doc +} + +/// Asserts that `verify` reports `clause` for `doc`. +fn assert_reported(doc: &Document, level: Level, clause: &str) { + let issues = verify(doc, level); + assert!(issues.iter().any(|i| i.clause == clause), "no {clause} issue in {issues:#?}"); +} + +/// Asserts that `verify` reports nothing under `clause` for `doc`. +fn assert_not_reported(doc: &Document, level: Level, clause: &str) { + let found: Vec<_> = verify(doc, level).into_iter().filter(|i| i.clause == clause).collect(); + assert!(found.is_empty(), "{clause} was reported: {found:#?}"); +} + +#[test] +fn xmp_metadata_is_required_clause_6_6_2_1() { + let page = "<< /Type /Page /Parent 2 0 R >>"; + let packet = a2b_packet(None); + let identified = page_document(page, Some(packet.as_str()), "", &[], ""); + assert_not_reported(&identified, Level::A2b, "6.6.2.1"); + assert_eq!(declared(&identified).pdfa, Some((2, "B".into()))); + let bare = page_document(page, None, "", &[], ""); + assert_reported(&bare, Level::A2b, "6.6.2.1"); +} + +#[test] +fn the_declared_part_and_conformance_must_be_the_level_clause_6_6_4() { + let page = "<< /Type /Page /Parent 2 0 R >>"; + let matching = a2b_packet(None); + let doc = page_document(page, Some(matching.as_str()), "", &[], ""); + assert_not_reported(&doc, Level::A2b, "6.6.4"); + for (part, conformance) in [(3, "B"), (2, "A")] { + let packet = xmp(part, conformance, None); + let doc = page_document(page, Some(packet.as_str()), "", &[], ""); + assert_reported(&doc, Level::A2b, "6.6.4"); + assert_eq!(declared(&doc).pdfa, Some((part, conformance.to_owned()))); + } +} + +#[test] +fn the_xmp_title_must_match_the_information_dictionary_clause_6_6_3() { + let page = "<< /Type /Page /Parent 2 0 R >>"; + let info = "/Info << /Title (Report) >>"; + let matching = a2b_packet(Some("Report")); + let doc = page_document(page, Some(matching.as_str()), "", &[], info); + assert_not_reported(&doc, Level::A2b, "6.6.3"); + let differing = a2b_packet(Some("Draft")); + let doc = page_document(page, Some(differing.as_str()), "", &[], info); + assert_reported(&doc, Level::A2b, "6.6.3"); +} + +#[test] +fn the_trailer_must_not_name_encryption_clause_6_1_3() { + let page = "<< /Type /Page /Parent 2 0 R >>"; + let packet = a2b_packet(None); + let plain = page_document(page, Some(packet.as_str()), "", &[], ""); + assert_not_reported(&plain, Level::A2b, "6.1.3"); + // An encrypted file's keys are not written out by hand here, so the /Encrypt dictionary comes + // from the object layer; the rule under test only asks whether the trailer names one. + let mut encrypted = page_document(page, Some(packet.as_str()), "", &[], ""); + let params = NewEncryption { + algorithm: Algorithm::Aes256, + user_password: "", + owner_password: "owner", + permissions: -4, + encrypt_metadata: true, + seed: [7; 32], + }; + encrypted.set_encryption(¶ms).unwrap(); + assert_reported(&encrypted, Level::A2b, "6.1.3"); + let report = convert(&mut encrypted, Level::A2b).unwrap(); + assert!(!report.remaining.iter().any(|i| i.clause == "6.1.3"), "{:#?}", report.remaining); +} + +#[test] +fn device_colour_needs_an_output_intent_clause_6_2_3() { + let page = "<< /Type /Page /Parent 2 0 R /Contents 5 0 R /Resources << >> >>"; + let packet = a2b_packet(None); + let rgb = content("1 0 0 rg 10 10 20 20 re f"); + let doc = page_document(page, Some(packet.as_str()), "", &[rgb.as_str()], ""); + assert_reported(&doc, Level::A2b, "6.2.3"); + let none = content("q Q"); + let doc = page_document(page, Some(packet.as_str()), "", &[none.as_str()], ""); + assert_not_reported(&doc, Level::A2b, "6.2.3"); +} + +#[test] +fn device_rgb_needs_an_rgb_output_intent_clause_6_2_4_3() { + let page = "<< /Type /Page /Parent 2 0 R /Contents 5 0 R /Resources << >> >>"; + let packet = a2b_packet(None); + let rgb = content("1 0 0 rg 10 10 20 20 re f"); + let srgb = hex_stream("/N 3", &icc::srgb()); + let doc = page_document(page, Some(packet.as_str()), &output_intent(6), &[rgb.as_str(), srgb.as_str()], ""); + assert_not_reported(&doc, Level::A2b, "6.2.4.3"); + // The intent is there, so the neighbour rule about device colour without one stays quiet. + assert_not_reported(&doc, Level::A2b, "6.2.3"); + let cmyk = hex_stream("", &cmyk_profile_header()); + let doc = page_document(page, Some(packet.as_str()), &output_intent(6), &[rgb.as_str(), cmyk.as_str()], ""); + assert_reported(&doc, Level::A2b, "6.2.4.3"); +} + +#[test] +fn the_catalog_must_not_have_additional_actions_clause_6_5_2() { + let page = "<< /Type /Page /Parent 2 0 R >>"; + let packet = a2b_packet(None); + let plain = page_document(page, Some(packet.as_str()), "", &[], ""); + assert_not_reported(&plain, Level::A2b, "6.5.2"); + let acting = page_document(page, Some(packet.as_str()), "/AA << /WC << /S /GoTo >> >>", &[], ""); + assert_reported(&acting, Level::A2b, "6.5.2"); +} + +#[test] +fn the_catalog_must_not_have_document_javascript_clause_6_5_1() { + let page = "<< /Type /Page /Parent 2 0 R >>"; + let packet = a2b_packet(None); + let plain = page_document(page, Some(packet.as_str()), "", &[], ""); + assert_not_reported(&plain, Level::A2b, "6.5.1"); + // An empty name tree is enough: an action object here would report the same clause, and this + // case is about the catalog's own entry. + let tree = "/Names << /JavaScript << /Names [] >> >>"; + let scripted = page_document(page, Some(packet.as_str()), tree, &[], ""); + assert_reported(&scripted, Level::A2b, "6.5.1"); +} + +#[test] +fn the_form_must_not_ask_viewers_for_appearances_clause_6_4_1() { + let page = "<< /Type /Page /Parent 2 0 R >>"; + let packet = a2b_packet(None); + let plain = page_document(page, Some(packet.as_str()), "/AcroForm << /Fields [] >>", &[], ""); + assert_not_reported(&plain, Level::A2b, "6.4.1"); + let asking = "/AcroForm << /Fields [] /NeedAppearances true >>"; + let doc = page_document(page, Some(packet.as_str()), asking, &[], ""); + assert_reported(&doc, Level::A2b, "6.4.1"); +} + +#[test] +fn forbidden_annotation_types_are_reported_clause_6_3_1() { + let page = "<< /Type /Page /Parent 2 0 R /Annots [5 0 R] >>"; + let packet = a2b_packet(None); + let link = "<< /Type /Annot /Subtype /Link /Rect [10 10 30 30] /P 4 0 R /F 4 >>"; + let doc = page_document(page, Some(packet.as_str()), "", &[link], ""); + assert_not_reported(&doc, Level::A2b, "6.3.1"); + let sound = "<< /Type /Annot /Subtype /Sound /Rect [10 10 30 30] /P 4 0 R /F 4 >>"; + let doc = page_document(page, Some(packet.as_str()), "", &[sound], ""); + assert_reported(&doc, Level::A2b, "6.3.1"); +} + +#[test] +fn annotations_must_print_and_not_hide_clause_6_3_2() { + let page = "<< /Type /Page /Parent 2 0 R /Annots [5 0 R] >>"; + let packet = a2b_packet(None); + let appearance = "<< /Type /XObject /Subtype /Form /BBox [0 0 20 20] /Length 0 >>\nstream\n\nendstream"; + let printing = "<< /Type /Annot /Subtype /Square /Rect [10 10 30 30] /P 4 0 R /F 4 /AP << /N 6 0 R >> >>"; + let doc = page_document(page, Some(packet.as_str()), "", &[printing, appearance], ""); + assert_not_reported(&doc, Level::A2b, "6.3.2"); + let unprinted = "<< /Type /Annot /Subtype /Square /Rect [10 10 30 30] /P 4 0 R /F 0 /AP << /N 6 0 R >> >>"; + let doc = page_document(page, Some(packet.as_str()), "", &[unprinted, appearance], ""); + assert_reported(&doc, Level::A2b, "6.3.2"); + let hidden = "<< /Type /Annot /Subtype /Square /Rect [10 10 30 30] /P 4 0 R /F 6 /AP << /N 6 0 R >> >>"; + let doc = page_document(page, Some(packet.as_str()), "", &[hidden, appearance], ""); + assert_reported(&doc, Level::A2b, "6.3.2"); +} + +#[test] +fn annotations_need_an_appearance_stream_clause_6_3_3() { + let page = "<< /Type /Page /Parent 2 0 R /Annots [5 0 R] >>"; + let packet = a2b_packet(None); + let appearance = "<< /Type /XObject /Subtype /Form /BBox [0 0 20 20] /Length 0 >>\nstream\n\nendstream"; + let with = "<< /Type /Annot /Subtype /Square /Rect [10 10 30 30] /P 4 0 R /F 4 /AP << /N 6 0 R >> >>"; + let doc = page_document(page, Some(packet.as_str()), "", &[with, appearance], ""); + assert_not_reported(&doc, Level::A2b, "6.3.3"); + let without = "<< /Type /Annot /Subtype /Square /Rect [10 10 30 30] /P 4 0 R /F 4 >>"; + let doc = page_document(page, Some(packet.as_str()), "", &[without], ""); + assert_reported(&doc, Level::A2b, "6.3.3"); +} + +#[test] +fn lzw_compressed_streams_are_reported_clause_6_1_7_2() { + let page = "<< /Type /Page /Parent 2 0 R /Contents 5 0 R /Resources << /Font << /F1 6 0 R >> >> >>"; + let packet = a2b_packet(None); + let text = content("BT /F1 12 Tf 10 10 Td (Hi) Tj ET"); + let font = "<< /Type /Font /Subtype /TrueType /BaseFont /Sans /FirstChar 72 /LastChar 105 /Widths [500 500] /FontDescriptor 7 0 R >>"; + let descriptor = "<< /Type /FontDescriptor /FontName /Sans /Flags 32 /FontFile2 8 0 R >>"; + let flate = font_program(Some("/FlateDecode")); + let doc = page_document(page, Some(packet.as_str()), "", &[text.as_str(), font, descriptor, flate.as_str()], ""); + assert_not_reported(&doc, Level::A2b, "6.1.7.2"); + // The neighbour rule holds: the font still reads as embedded. + assert_not_reported(&doc, Level::A2b, "6.2.11.4"); + let lzw = font_program(Some("/LZWDecode")); + let doc = page_document(page, Some(packet.as_str()), "", &[text.as_str(), font, descriptor, lzw.as_str()], ""); + assert_reported(&doc, Level::A2b, "6.1.7.2"); +} + +#[test] +fn streams_must_not_read_external_files_clause_6_1_7_1() { + let page = "<< /Type /Page /Parent 2 0 R >>"; + let packet = a2b_packet(None); + let held = "<< /Length 4 >>\nstream\nabcd\nendstream"; + let doc = page_document(page, Some(packet.as_str()), "", &[held], ""); + assert_not_reported(&doc, Level::A2b, "6.1.7.1"); + // A stream object nothing refers to: the rule looks at every stream in the file. + let external = "<< /Length 4 /F (data.bin) >>\nstream\nabcd\nendstream"; + let doc = page_document(page, Some(packet.as_str()), "", &[external], ""); + assert_reported(&doc, Level::A2b, "6.1.7.1"); +} + +#[test] +fn images_must_not_be_interpolated_clause_6_2_8() { + let page = "<< /Type /Page /Parent 2 0 R /Contents 6 0 R /Resources << /XObject << /Im0 5 0 R >> >> >>"; + let packet = a2b_packet(None); + let drawing = content("q 10 0 0 10 0 0 cm /Im0 Do Q"); + let smooth = image(true); + let doc = page_document(page, Some(packet.as_str()), "", &[smooth.as_str(), drawing.as_str()], ""); + assert_reported(&doc, Level::A2b, "6.2.8"); + let crisp = image(false); + let doc = page_document(page, Some(packet.as_str()), "", &[crisp.as_str(), drawing.as_str()], ""); + assert_not_reported(&doc, Level::A2b, "6.2.8"); +} + +#[test] +fn postscript_xobjects_are_reported_clause_6_2_9() { + let plain = "<< /Type /Page /Parent 2 0 R /Contents 5 0 R >>"; + let with = "<< /Type /Page /Parent 2 0 R /Contents 5 0 R /Resources << /XObject << /PS0 6 0 R >> >> >>"; + let packet = a2b_packet(None); + let drawing = content("q Q"); + let doc = page_document(plain, Some(packet.as_str()), "", &[drawing.as_str()], ""); + assert_not_reported(&doc, Level::A2b, "6.2.9"); + let postscript = "<< /Type /XObject /Subtype /PS /Length 0 >>\nstream\n\nendstream"; + let doc = page_document(with, Some(packet.as_str()), "", &[drawing.as_str(), postscript], ""); + assert_reported(&doc, Level::A2b, "6.2.9"); +} + +#[test] +fn fonts_must_be_embedded_clause_6_2_11_4() { + let page = "<< /Type /Page /Parent 2 0 R /Resources << /Font << /F1 5 0 R >> >> >>"; + let packet = a2b_packet(None); + let embedded = "<< /Type /Font /Subtype /TrueType /BaseFont /Sans /FontDescriptor 6 0 R >>"; + let descriptor = "<< /Type /FontDescriptor /FontName /Sans /Flags 32 /FontFile2 7 0 R >>"; + let program = font_program(None); + let doc = page_document(page, Some(packet.as_str()), "", &[embedded, descriptor, program.as_str()], ""); + assert_not_reported(&doc, Level::A2b, "6.2.11.4"); + let missing = "<< /Type /Font /Subtype /TrueType /BaseFont /Sans >>"; + let doc = page_document(page, Some(packet.as_str()), "", &[missing], ""); + assert_reported(&doc, Level::A2b, "6.2.11.4"); +} + +/// A file built by hand, apart from its output profile, with everything the verifier asks for: an +/// XMP packet naming PDF/A-2b with a title that matches the document information, an sRGB output +/// intent and a blank page. It checks that the rules agree with each other, which is not by itself a +/// conformance claim. +#[test] +fn minimal_document_has_no_verifier_issues() { + let page = "<< /Type /Page /Parent 2 0 R >>"; + let packet = a2b_packet(Some("Report")); + let profile = hex_stream("/N 3", &icc::srgb()); + let info = "/Info << /Title (Report) >>"; + let mut doc = page_document(page, Some(packet.as_str()), &output_intent(5), &[profile.as_str()], info); + let issues = verify(&doc, Level::A2b); + assert!(issues.is_empty(), "{issues:#?}"); + assert_eq!(declared(&doc).pdfa, Some((2, "B".into()))); + assert_eq!(declared(&doc).output_intents, ["sRGB IEC61966-2.1"]); + let report = convert(&mut doc, Level::A2b).unwrap(); + assert!(report.remaining.is_empty(), "{:#?}", report.remaining); + assert_eq!(declared(&doc).pdfa, Some((2, "B".into()))); +} diff --git a/crates/redact/Cargo.toml b/crates/redact/Cargo.toml index fe21d13b32..149d8d8295 100644 --- a/crates/redact/Cargo.toml +++ b/crates/redact/Cargo.toml @@ -9,6 +9,7 @@ license.workspace = true workspace = true [dependencies] +aho-corasick = "1" pdfcraft-cos = { workspace = true } pdfcraft-content = { workspace = true } pdfcraft-fonts = { workspace = true } @@ -20,6 +21,10 @@ pdfcraft-xfa = { workspace = true } # CCITT Group 4 and JBIG2 encoding for cleared one-bit images. pdfcraft-filters = { workspace = true } thiserror = { workspace = true } +sha2 = "0.11" [dev-dependencies] pdfcraft-testkit = { workspace = true } +# The redacted page is rendered in `tests::a_page_whose_pruned_pattern_is_still_selected_renders`: +# layer 3 from layer 4, a dev dependency only. +pdfcraft-render = { workspace = true } diff --git a/crates/redact/README.md b/crates/redact/README.md index db9f46b8c9..f78f819c03 100644 --- a/crates/redact/README.md +++ b/crates/redact/README.md @@ -60,6 +60,15 @@ resume after it would be a guess. A Redact annotation with neither a usable `/Qu `/Rect` makes it fail with `RedactError::UnreadableMark` before anything changes, instead of skipping that mark. The count covers the marks on the pages being applied. +Tiling-pattern cells are separate streams. Applying a mark removes a pattern resource when no +surviving paint uses it. If a cell remains reachable after rewriting the selected pages and may +contain text, images, replacement descriptions, or unreadable content, Apply refuses with a +`RedactError::Pattern` and restores the document and pending marks. This includes patterns owned +by Forms and patterns inherited by Forms. Vector-only retained cells remain supported. The +bounded check is conservative: an unrelated retained pattern on a selected page can also cause +refusal when its content cannot be proven safe. If a selected page had a pattern resource, the +check covers all pages after rewriting so another page cannot keep the same cell in the saved PDF. + Before changing any page, `apply` prepares the redaction appearances with a shared 8 MiB budget for their uncompressed PDF content across the selected pages. It bounds repeated-text counts and working line buffers before allocating them, and measures and encodes each repeated diff --git a/crates/redact/fuzz/Cargo.toml b/crates/redact/fuzz/Cargo.toml new file mode 100644 index 0000000000..716aa7715a --- /dev/null +++ b/crates/redact/fuzz/Cargo.toml @@ -0,0 +1,25 @@ +[package] +name = "pdfcraft-redact-fuzz" +version = "0.0.0" +publish = false +edition = "2024" +license = "MIT OR Apache-2.0" + +[package.metadata] +cargo-fuzz = true + +# Detached from the PdfCraft workspace: run with `cargo +nightly fuzz run apply` +# from crates/redact/. +[workspace] + +[dependencies] +libfuzzer-sys = "0.4" +pdfcraft-cos = { path = "../../cos" } +pdfcraft-redact = { path = ".." } + +[[bin]] +name = "apply" +path = "fuzz_targets/apply.rs" +test = false +doc = false +bench = false diff --git a/crates/redact/fuzz/fuzz_targets/apply.rs b/crates/redact/fuzz/fuzz_targets/apply.rs new file mode 100644 index 0000000000..347e5ed120 --- /dev/null +++ b/crates/redact/fuzz/fuzz_targets/apply.rs @@ -0,0 +1,24 @@ +//! Feeds arbitrary bytes, read as a PDF, to the redaction marks and the apply entry. +//! +//! Results are discarded: the target checks that no input panics. +#![no_main] + +use std::sync::Arc; + +use libfuzzer_sys::fuzz_target; +use pdfcraft_cos::Document; +use pdfcraft_redact::{apply, marks}; + +/// The largest input the target opens (16 MiB); larger inputs are skipped. +const MAX_INPUT: usize = 16 << 20; + +fuzz_target!(|data: &[u8]| { + if data.len() > MAX_INPUT { + return; + } + let Ok(mut doc) = Document::open(Arc::new(data.to_vec())) else { + return; + }; + let _count = marks(&doc).len(); + let _result = apply(&mut doc, None); +}); diff --git a/crates/redact/src/image.rs b/crates/redact/src/image.rs index 4b3c44b0fd..a99e179895 100644 --- a/crates/redact/src/image.rs +++ b/crates/redact/src/image.rs @@ -12,7 +12,7 @@ use pdfcraft_cos::{Dict, Document, ImageBudget, Object, Stream}; /// Most pixels an image may have to be cleared in place (larger ones are removed), or to be stored /// again without shared `/JBIG2Globals` (see [`without_globals`]). -const MAX_PIXELS: u64 = pdfcraft_cos::MAX_REDACTED_IMAGE_PIXELS; +pub(crate) const MAX_PIXELS: u64 = pdfcraft_cos::MAX_REDACTED_IMAGE_PIXELS; fn components(doc: &Document, s: &Stream) -> Option { let cs = doc.resolve(s.dict.get(b"ColorSpace")?); diff --git a/crates/redact/src/interp.rs b/crates/redact/src/interp.rs index 460085a320..b0a7257cb3 100644 --- a/crates/redact/src/interp.rs +++ b/crates/redact/src/interp.rs @@ -31,7 +31,7 @@ mod prune; use layers::strip_hidden_layers; use prune::{clip_out, extgstate_font, prune_form_resources}; -pub(crate) use prune::{prune, prune_properties, resource_ops, unlink_doomed}; +pub(crate) use prune::{prune, prune_patterns, prune_properties, resource_ops, unlink_doomed, unlink_pruned_patterns}; /// How deep this pass follows form XObjects. A form past it is removed rather than walked, which /// is the fail-safe choice for a redaction -- marked content inside a form we cannot read would @@ -53,6 +53,23 @@ pub(crate) enum Mode { Verify, } +/// A run of glyphs cut out under a region, kept for the redaction proof +/// ([`Snapshot::capture`](crate::verify::Snapshot::capture)). +pub(crate) struct Removed { + /// Index of the region (in `Scope::rects`) the run lay under. + pub(crate) rect: usize, + /// The character codes as they stood in the string. + pub(crate) raw: Vec, + /// What the font says they showed (codes without a known meaning are left out). + pub(crate) text: String, + /// How many character codes the run holds (a composite font's codes are several bytes). + pub(crate) codes: usize, + /// Which text operator showed it, counted from the start of the page. + pub(crate) op: usize, + /// Where in that operator it starts: the operand's place in a `TJ` array, and the byte in it. + pub(crate) at: (usize, usize), +} + #[derive(Clone)] struct Gs { ctm: Matrix, @@ -68,6 +85,17 @@ struct Gs { scale: f64, leading: f64, rise: f64, + /// The tiling or shading pattern selected as the fill colour (`/Name scn`), and as the stroke + /// colour (`/Name SCN`). Part of the graphics state, so `q`/`Q` save and restore them with + /// everything else. A pattern's cell is a content stream of its own and this pass does not + /// enter it, so a pattern whose only painting was removed has to leave the page's resources + /// or its drawing stays in the file (#3647). + fill_pattern: Option>, + stroke_pattern: Option>, + /// The current font is a Type 3 font without `/Resources`: its glyph descriptions look their + /// names up in this scope's resources (ISO 32000-2 §9.6.4), so a shown glyph may paint with + /// any of this scope's patterns. + type3_inherits: bool, } /// What processing a scope produced. @@ -85,6 +113,16 @@ pub(crate) struct Output { /// dictionaries may name them too (an inherited or shared /Resources, or the caller's when a /// form has none of its own): [`unlink_doomed`] removes those entries. pub doomed: Vec, + /// Pattern resource names a painting operator that survived the rewrite still uses. A name + /// this scope saw selected but never painted with afterwards is pruned from the page's + /// `/Resources /Pattern`, so a cell whose only drawing was redacted does not stay in the + /// saved file (#3647). + pub patterns_seen: Vec>, + pub patterns_painted: Vec>, + /// A Type 3 glyph without resources of its own was shown in this scope or a nested form, + /// through a font set by `Tf` or an ExtGState: which of the page's patterns it paints with is + /// not tracked, so the page keeps them all. + pub keeps_all_patterns: bool, /// Original property values retired by this scope or a nested form. Other resource holders /// may still name them; unlink only entries no surviving content uses. pub retired_properties: Vec, @@ -124,6 +162,12 @@ pub(crate) struct Scope<'a> { xobject_oc_cache: HashMap, /// Content removed from hidden layers (blocks and XObjects). pub layer_blocks: usize, + /// Collects the glyph runs removed under a region in apply mode (`None` = not collected). + /// The redaction proof's snapshot is what sets it: it must know what applying is about to + /// remove, by the interpreter's own judgement, without trusting anything else to it. + pub removed: Option>, + /// How many text operators have been shown, for [`Removed::op`]. + shown: usize, fonts: HashMap, Rc>, used_names: Vec>, depth: usize, @@ -149,6 +193,8 @@ impl<'a> Scope<'a> { ocmd_cache: HashMap::new(), xobject_oc_cache: HashMap::new(), layer_blocks: 0, + removed: None, + shown: 0, fonts: HashMap::new(), used_names: Vec::new(), depth: 0, @@ -169,21 +215,33 @@ impl<'a> Scope<'a> { self.rects.iter().any(|r| contains(*r, b, 0.01)) } - /// Does a glyph box count as under a region? Any real overlap does (more than a fifth of + /// Which regions a glyph box counts as under? Any real overlap does (more than a fifth of /// the glyph or a point, whichever is less, in both directions), so neighbours that only /// touch an edge survive while partly covered glyphs go. Degenerate boxes (zero-size text) - /// count when their origin is inside. - fn glyph_hit(&self, b: [f64; 4], origin: (f64, f64)) -> bool { + /// count when their origin is inside. Empty = under no region (a glyph kept). A glyph may + /// lie under several regions at once (overlapping marks); each is reported. + fn glyph_rects(&self, b: [f64; 4], origin: (f64, f64)) -> Vec { let (gw, gh) = (b[2] - b[0], b[3] - b[1]); if gw < 0.01 || gh < 0.01 { - return self.rects.iter().any(|r| origin.0 >= r[0] && origin.0 <= r[2] && origin.1 >= r[1] && origin.1 <= r[3]); + return self + .rects + .iter() + .enumerate() + .filter(|(_, r)| origin.0 >= r[0] && origin.0 <= r[2] && origin.1 >= r[1] && origin.1 <= r[3]) + .map(|(i, _)| i) + .collect(); } let (mx, my) = ((gw * 0.2).min(1.0), (gh * 0.2).min(1.0)); - self.rects.iter().any(|r| { - let ox = b[2].min(r[2]) - b[0].max(r[0]); - let oy = b[3].min(r[3]) - b[1].max(r[1]); - ox > mx && oy > my - }) + self.rects + .iter() + .enumerate() + .filter(|(_, r)| { + let ox = b[2].min(r[2]) - b[0].max(r[0]); + let oy = b[3].min(r[3]) - b[1].max(r[1]); + ox > mx && oy > my + }) + .map(|(i, _)| i) + .collect() } } @@ -223,6 +281,24 @@ struct Glyph { /// Advance in unscaled text space (before `Th`). advance: f64, hit: bool, + /// The regions it lies under (empty for hidden text). + rects: Vec, +} + +/// Record the patterns an operator paints with, so [`prune_patterns`] keeps them. Only path +/// painting knows exactly what it draws and whether the paint survived; text, images and forms +/// are recorded as they are met, which can keep a pattern whose paint was in fact all redacted, +/// and with it the pattern's cell. A cell that carries text or images is then refused by +/// `pattern_guard`; a vector-only cell stays in the file though nothing shows it +/// (`a_pattern_painted_only_by_redacted_text_keeps_its_vector_cell`). Dropping a pattern something +/// still draws with would lose paint from the page instead. +fn uses_patterns(out: &mut Output, gs: &Gs, fills: bool, strokes: bool) { + if fills && let Some(n) = &gs.fill_pattern { + out.patterns_painted.push(n.clone()); + } + if strokes && let Some(n) = &gs.stroke_pattern { + out.patterns_painted.push(n.clone()); + } } /// Process a scope's content streams (state flows from one stream to the next). @@ -238,6 +314,9 @@ pub(crate) fn process(doc: &mut Document, scope: &mut Scope<'_>, streams: &[Vec< scale: 1.0, leading: 0.0, rise: 0.0, + fill_pattern: None, + stroke_pattern: None, + type3_inherits: false, }; process_from(doc, scope, streams, resources, gs) } @@ -338,6 +417,8 @@ struct Walk { fonts_res: Dict, ext_gstates: Dict, xobjects: Dict, + /// This scope's pattern names, which a Type 3 glyph without resources may paint with. + patterns: Vec>, fallback: Rc, /// The current path: its operators, its bounding box in user space, and whether it clips. path: Vec, @@ -356,6 +437,7 @@ impl Walk { fonts_res: res_dict(doc, resources, b"Font"), ext_gstates: res_dict(doc, resources, b"ExtGState"), xobjects: res_dict(doc, resources, b"XObject"), + patterns: res_dict(doc, resources, b"Pattern").iter().map(|(n, _)| n.to_vec()).collect(), fallback: Rc::new(Metrics::fallback()), path: Vec::new(), path_box: None, @@ -394,6 +476,39 @@ impl Walk { b"BI" => Self::inline_image(&self.gs, scope, &mut self.out, op, piece), b"sh" if scope.mode == Mode::Apply => Self::shading(&self.gs, scope, op, piece), b"Do" => self.draw_xobject(doc, scope, resources, op, piece), + // `/Name scn` selects a pattern as the fill colour; numbers select a plain colour + // and clear it. `cs` with a space other than /Pattern clears it too. + b"scn" | b"SCN" => { + let fill = o == b"scn"; + let picked = op.operands.last().and_then(Object::as_name).map(<[u8]>::to_vec); + if let Some(name) = &picked { + self.out.patterns_seen.push(name.clone()); + } + if fill { + self.gs.fill_pattern = picked; + } else { + self.gs.stroke_pattern = picked; + } + Some(op) + } + b"cs" | b"CS" => { + if op.name(0) != Some(b"Pattern") { + if o == b"cs" { + self.gs.fill_pattern = None; + } else { + self.gs.stroke_pattern = None; + } + } + Some(op) + } + b"g" | b"rg" | b"k" => { + self.gs.fill_pattern = None; + Some(op) + } + b"G" | b"RG" | b"K" => { + self.gs.stroke_pattern = None; + Some(op) + } _ => Some(op), }; piece.ops.extend(kept); @@ -425,6 +540,12 @@ impl Walk { let clips = std::mem::replace(&mut self.clip, false); let hit = scope.mode == Mode::Apply && op.op.as_slice() != b"n" && bbox.is_some_and(|b| scope.hits(b)); if !hit { + // The paint survives, so the pattern it draws with is still in use. `n` paints + // nothing, so it uses none. A hit path is removed whole (F-008), pattern and all. + let o = op.op.as_slice(); + let strokes = matches!(o, b"S" | b"s" | b"B" | b"B*" | b"b" | b"b*"); + let fills = matches!(o, b"f" | b"F" | b"f*" | b"B" | b"B*" | b"b" | b"b*"); + uses_patterns(&mut self.out, &self.gs, fills, strokes); piece.ops.extend(body); piece.ops.push(op); return; @@ -458,6 +579,8 @@ impl Walk { _ => { if let Some((font, vertical, size)) = op.name(0).and_then(|n| extgstate_font(doc, scope, &self.ext_gstates, n, &self.fallback)) { (self.gs.font, self.gs.vertical, self.gs.size) = (font, vertical, size); + // As for `Tf`: a Type 3 font without /Resources paints through this scope's. + self.gs.type3_inherits = op.name(0).is_some_and(|n| extgstate_type3_inherits(doc, &self.ext_gstates, n)); } } } @@ -468,6 +591,7 @@ impl Walk { let Some(name) = op.name(0) else { return }; let font_dict = self.fonts_res.get(name).and_then(|f| doc.resolve(f).as_dict().cloned()); self.gs.vertical = font_dict.as_ref().is_some_and(|d| is_vertical(doc, d)); + self.gs.type3_inherits = font_dict.as_ref().is_some_and(|d| type3_without_resources(doc, d)); self.gs.font = match scope.fonts.get(name) { Some(f) => f.clone(), None => { @@ -516,6 +640,16 @@ impl Walk { /// `Tj`, `TJ`, `'` and `"`: glyphs under a region are cut out (or counted, when verifying). fn show_text(&mut self, scope: &mut Scope<'_>, op: Op, piece: &mut Piece) -> Option { + // Text paints with the fill pattern, and with the stroke pattern in the stroking render + // modes. Mode 3 paints nothing and mode 7 only clips. + let mode = self.gs.render_mode; + uses_patterns(&mut self.out, &self.gs, matches!(mode, 0 | 2 | 4 | 6), matches!(mode, 1 | 2 | 5 | 6)); + // A Type 3 glyph without resources of its own paints through this scope's: keep every + // pattern it could select, as with a form that has no /Resources. + if self.gs.type3_inherits { + self.out.patterns_painted.extend(self.patterns.iter().cloned()); + self.out.keeps_all_patterns = true; + } let o = op.op.as_slice(); if o == b"\"" { self.gs.word_spacing = op.num(0).unwrap_or(self.gs.word_spacing); @@ -569,6 +703,8 @@ impl Walk { /// An inline image under a region is removed (or counted, when verifying). fn inline_image(gs: &Gs, scope: &mut Scope<'_>, out: &mut Output, op: Op, piece: &mut Piece) -> Option { + // An image mask paints with the fill colour, pattern included. + uses_patterns(out, gs, true, false); if !scope.hits(gs.ctm.bbox([0.0, 0.0, 1.0, 1.0])) { return Some(op); } @@ -593,6 +729,9 @@ impl Walk { } fn draw_xobject(&mut self, doc: &mut Document, scope: &mut Scope<'_>, resources: &Dict, op: Op, piece: &mut Piece) -> Option { + // An image mask paints with the fill colour, and a form's content is interpreted with a + // graphics state of its own, so a pattern it inherits from here is never recorded inside it. + uses_patterns(&mut self.out, &self.gs, true, true); let Some(new) = xobject(doc, scope, &op, &self.gs, resources, &mut self.xobjects, &mut self.out) else { return Some(op) }; piece.changed = true; piece.ops.extend(new); @@ -644,11 +783,14 @@ fn clean_replacements(doc: &Document, resources: &Dict, original: &[Op], process /// Lay out a shown string (or `TJ` array) glyph by glyph, advancing `tm`. Returns the `TJ` /// items with the glyphs under a region replaced by displacements, and how many were removed. -fn show(scope: &Scope<'_>, gs: &Gs, tm: &mut Matrix, items: &[Object]) -> (Vec, usize) { +/// In apply mode the runs removed under each region are also handed to `scope.removed`. +fn show(scope: &mut Scope<'_>, gs: &Gs, tm: &mut Matrix, items: &[Object]) -> (Vec, usize) { let f = &gs.font; let size = gs.size; let mut out: Vec = Vec::new(); let mut removed = 0; + scope.shown += 1; + let op = scope.shown; let push_num = |out: &mut Vec, v: f64| { if v == 0.0 { return; @@ -661,7 +803,7 @@ fn show(scope: &Scope<'_>, gs: &Gs, tm: &mut Matrix, items: &[Object]) -> (Vec { let bytes = &s.bytes; @@ -674,18 +816,50 @@ fn show(scope: &Scope<'_>, gs: &Gs, tm: &mut Matrix, items: &[Object]) -> (Vec { let degenerate = b[2] - b[0] < 0.01 && b[3] - b[1] < 0.01; matches!(gs.render_mode, 3 | 7) || !(overlaps(page, b, 0.0) || degenerate) } - None => scope.glyph_hit(b, origin), + None => { + rects = scope.glyph_rects(b, origin); + !rects.is_empty() + } }; - glyphs.push(Glyph { bytes: pos..pos + len, advance, hit }); + glyphs.push(Glyph { bytes: pos..pos + len, advance, hit, rects }); *tm = Matrix::translate(advance * gs.scale, 0.0).then(tm); pos += len; } + if scope.mode == Mode::Apply + && let Some(sink) = scope.removed.as_mut() + { + // Consecutive removed glyphs under one region are one run, recorded for + // every region the glyphs lie under: overlapping marks each account for + // their own share of what was cut. + let mut under: Vec = glyphs.iter().flat_map(|g| g.rects.iter().copied()).collect(); + under.sort_unstable(); + under.dedup(); + for r in under { + let mut k = 0; + while let Some(g) = glyphs.get(k) { + if !g.rects.contains(&r) { + k += 1; + continue; + } + let mut end = k; + while glyphs.get(end + 1).is_some_and(|n| n.rects.contains(&r)) { + end += 1; + } + let span = g.bytes.start..glyphs.get(end).map_or(g.bytes.end, |l| l.bytes.end); + let at = (place, span.start); + let raw = bytes.get(span).unwrap_or_default().to_vec(); + sink.push(Removed { rect: r, text: f.decode(&raw), raw, codes: end - k + 1, op, at }); + k = end + 1; + } + } + } let mut run: Vec = Vec::new(); for g in &glyphs { if g.hit { @@ -850,8 +1024,18 @@ fn xobject( out.ambiguous |= inner.ambiguous; out.doomed.extend_from_slice(&inner.doomed); out.retired_properties.extend(inner.retired_properties); + // A Type 3 glyph without resources shown inside the form may paint with the page's + // patterns (the renderer resolves its names there), whether or not the form has + // /Resources of its own. + out.keeps_all_patterns |= inner.keeps_all_patterns; out.tag_changes.extend(inner.tag_changes); out.error = inner.error.or(out.error.take()); + // A form without /Resources of its own paints with its caller's patterns, so what it + // still paints keeps the caller's entry. Only the painted side is passed up: a name + // the form selected but no longer paints with is left for the caller to keep. + if own.is_none() { + out.patterns_painted.extend(inner.patterns_painted); + } if scope.mode == Mode::Verify { return None; } @@ -918,3 +1102,18 @@ fn xobject( _ => None, } } + +/// Whether the ExtGState `name` sets a Type 3 font that has no `/Resources` of its own. +fn extgstate_type3_inherits(doc: &Document, ext_gstates: &Dict, name: &[u8]) -> bool { + let Some(state) = ext_gstates.get(name).map(|s| doc.resolve(s)) else { return false }; + let Some(font) = state.as_dict().and_then(|d| d.get(b"Font")).map(|f| doc.resolve(f)) else { return false }; + let Some(reference) = font.as_array().and_then(|a| a.first()) else { return false }; + let dict = doc.resolve(reference); + dict.as_dict().is_some_and(|d| type3_without_resources(doc, d)) +} + +/// A Type 3 font whose glyph descriptions use the resources of whatever shows them: no +/// `/Resources`, or `/Resources null`, which is the same thing. +fn type3_without_resources(doc: &Document, font: &Dict) -> bool { + font.name(b"Subtype") == Some(b"Type3") && font.get(b"Resources").is_none_or(|r| matches!(&*doc.resolve(r), Object::Null)) +} diff --git a/crates/redact/src/interp/prune.rs b/crates/redact/src/interp/prune.rs index 6ca5ea2803..188af03abe 100644 --- a/crates/redact/src/interp/prune.rs +++ b/crates/redact/src/interp/prune.rs @@ -355,3 +355,139 @@ pub(super) fn extgstate_font( }; Some((metrics, vertical, size)) } + +/// Drop every `/Pattern` entry this scope saw selected but no surviving painting operator drew +/// with. The `scn` that selected it stays in the content, so the page names a pattern its +/// resources no longer hold; nothing surviving paints with that colour, and +/// `a_page_whose_pruned_pattern_is_still_selected_renders` pins that the page still renders and +/// that operators after the stale selector still draw. A pattern's cell is a content stream of its own which +/// this pass does not enter, so a pattern whose only painting was redacted would otherwise keep +/// its drawing -- text included -- in the saved file (#3647). A pattern some surviving paint +/// still uses, or one the scope never saw, is left alone. +/// `/Pattern` may be an indirect object like any other value, so it is resolved: reading the +/// reference itself as a dictionary found none and pruned nothing, leaving the cell in the file. +/// What is written back is a dictionary of this page's own, so pruning never reaches through a +/// `/Pattern` dictionary another page shares. The pattern objects dropped are added to `pruned`, +/// for [`unlink_pruned_patterns`]. +pub(crate) fn prune_patterns(doc: &Document, res: &mut Dict, seen: &[Vec], painted: &[Vec], pruned: &mut Vec) -> usize { + let Some(mut pat) = res.get(b"Pattern").map(|p| doc.resolve(p)).and_then(|p| p.as_dict().cloned()) else { return 0 }; + let mut dropped = 0; + for n in seen { + if !painted.contains(n) + && let Some(value) = pat.get(n) + { + // Every object along the reference chain: a name can lead to a reference-valued + // object whose value is the cell, and the cell is what must not stay reachable. + let mut next = value.as_ref(); + for _ in 0..MAX_DEPTH { + let Some(reference) = next else { break }; + pruned.push(reference); + next = match &*doc.get(reference) { + Object::Ref(r) => Some(*r), + _ => None, + }; + } + pat.remove(n); + dropped += 1; + } + } + if dropped > 0 { + if pat.is_empty() { + res.remove(b"Pattern"); + } else { + res.set(b"Pattern".to_vec(), Object::Dict(pat)); + } + } + dropped +} + +/// Unlink the patterns a page's rewrite pruned (`pruned`) from page-tree nodes whose +/// `/Resources` no page inherits any more: a full save keeps whatever Root still reaches, so a +/// `/Pages` node above the page that still names the cell would keep it in the file. That happens +/// when the page's nearest holder was retired but a holder further up, which it shadowed, still +/// names the pattern. A holder some page still inherits from is left alone; whatever stays +/// reachable is checked by `pattern_guard`, which refuses a retained cell it cannot prove safe. +/// When any node's `/Parent` disagrees with where the `/Kids` tree puts it (or the root has +/// one), which holder a page inherits from is ambiguous and a node may be reached only through +/// `/Parent`, so nothing is unlinked and the guard, which follows `/Parent` too, decides. +pub(crate) fn unlink_pruned_patterns(doc: &mut Document, pruned: &[ObjRef]) -> Result<(), RedactError> { + if pruned.is_empty() { + return Ok(()); + } + let pruned: HashSet = pruned.iter().copied().collect(); + let Some(top) = doc.root().and_then(|root| doc.get(root).as_dict().and_then(|d| d.reference(b"Pages"))) else { return Ok(()) }; + // Every node with a /Resources of its own, and whether any page inherits from it (it is the + // nearest holder above a page, or the page itself). Cycles are cut as in `unlink_doomed`. + let mut holders: Vec<(ObjRef, bool)> = Vec::new(); + let mut seen = HashSet::new(); + let mut consistent = true; + let mut stack: Vec<(ObjRef, Option, Option)> = vec![(top, None, None)]; + seen.insert(top); + while let Some((node, parent, mut holder)) = stack.pop() { + let obj = doc.get(node); + let Some(d) = obj.as_dict() else { continue }; + // Every node's /Parent must be the node /Kids reached it from, and the root has none. + // A node reached only through a /Parent link is then impossible here; when the links + // disagree, the guard inspects every node they reach instead. A /Parent that is not a + // reference (a direct dictionary, written inline by a full save) never agrees. + let agrees = match d.get(b"Parent") { + None => parent.is_none(), + Some(Object::Ref(r)) => Some(*r) == parent, + Some(_) => false, + }; + if !agrees { + consistent = false; + break; + } + if d.contains(b"Resources") { + holders.push((node, false)); + holder = Some(holders.len() - 1); + } + let is_pages = d.name(b"Type") == Some(b"Pages") || (d.contains(b"Kids") && d.name(b"Type") != Some(b"Page")); + if is_pages { + // Borrowed, not copied: a /Kids array can be shared by many hostile nodes. + let kids_object = d.get(b"Kids").map(|k| doc.resolve(k)); + for kid in kids_object.as_deref().and_then(Object::as_array).into_iter().flatten().filter_map(Object::as_ref) { + // A node reached twice (a shared /Kids entry or a cycle) has a /Parent that agrees + // with at most one of the nodes above it. + if !seen.insert(kid) || seen.len() > 1_000_000 { + consistent = false; + break; + } + stack.push((kid, Some(node), holder)); + } + if !consistent { + break; + } + } else if let Some(h) = holder.and_then(|i| holders.get_mut(i)) { + h.1 = true; + } + } + if !consistent { + return Ok(()); + } + for (node, inherited) in holders { + if inherited { + continue; + } + let Some(mut res) = doc.get(node).as_dict().and_then(|d| d.get(b"Resources")).and_then(|r| doc.resolve(r).as_dict().cloned()) else { + continue; + }; + let mut pat = res_dict(doc, &res, b"Pattern"); + let names: Vec> = pat.iter().filter(|(_, v)| v.as_ref().is_some_and(|r| pruned.contains(&r))).map(|(n, _)| n.to_vec()).collect(); + if names.is_empty() { + continue; + } + for n in &names { + pat.remove(n); + } + if pat.is_empty() { + res.remove(b"Pattern"); + } else { + res.set(b"Pattern".to_vec(), Object::Dict(pat)); + } + // A private copy on this node: the dictionary object may be shared with other nodes. + doc.update_dict(node, |d| d.set(b"Resources".to_vec(), Object::Dict(res)))?; + } + Ok(()) +} diff --git a/crates/redact/src/lib.rs b/crates/redact/src/lib.rs index 41ac47357e..6d323004ad 100644 --- a/crates/redact/src/lib.rs +++ b/crates/redact/src/lib.rs @@ -22,15 +22,21 @@ pub mod codes; mod image; mod interp; mod overlay; +mod pattern_guard; pub mod patterns; pub mod sanitize; mod tags; #[cfg(test)] mod tests; +#[cfg(test)] +mod tests_verify; pub(crate) mod type3; pub(crate) mod type3_tables; +pub mod verify; use interp::{Mode, Scope, process}; +pub use pattern_guard::PatternProblem; +pub use verify::{Proof, ProofOptions, Snapshot}; pub type Rgb = [f64; 3]; @@ -49,6 +55,8 @@ pub enum RedactError { #[error("redaction could not be verified: {0} item(s) were still found under the marks, so nothing was changed")] Residue(usize), /// A mark's overlay text has a character Helvetica can't draw; nothing was redacted. + #[error("page {page} cannot be redacted safely: {reason}; nothing was changed")] + Pattern { page: usize, reason: PatternProblem }, #[error("{0}")] Undrawable(String), #[error( @@ -59,6 +67,11 @@ pub enum RedactError { "redaction appearance has invalid geometry or exceeds the 8 MiB budget; reduce the marked area, turn off repeated text or apply fewer pages at once (nothing was redacted)" )] OverlayLimit, + /// A stream the redaction created to draw the marks' boxes and labels can't be read back, so + /// the proof can't tell it apart from content that was there before and nothing can be + /// exempted from the sweep. + #[error("a stream the redaction created can't be read back, so the result can't be proven")] + OverlayUnreadable, /// The structure tree couldn't be cleaned completely (#3302): an element written in place that /// would need changing, an element whose inherited page can't be found, or a tree too large to /// walk. Tags that kept the removed text or annotation would undo the redaction. @@ -137,6 +150,8 @@ fn overlay_look(doc: &Document, d: &Dict) -> pdfcraft_annot::OverlayLook { /// What [`apply`] removed. #[derive(Clone, Debug, Default, PartialEq)] pub struct Report { + /// Patterns dropped from a page's resources because nothing painted with them any more. + pub patterns_removed: usize, pub marks: usize, pub pages: usize, pub glyphs: usize, @@ -164,7 +179,7 @@ pub struct Report { pub overlays: Vec, } -fn rect_of(doc: &Document, o: Option<&Object>) -> Option<[f64; 4]> { +pub(crate) fn rect_of(doc: &Document, o: Option<&Object>) -> Option<[f64; 4]> { let v: Vec = doc.resolve(o?).as_array()?.iter().filter_map(|x| doc.resolve(x).as_f64()).collect(); (v.len() == 4 && v.iter().all(|x| x.is_finite())).then(|| [v[0].min(v[2]), v[1].min(v[3]), v[0].max(v[2]), v[1].max(v[3])]) } @@ -388,6 +403,38 @@ pub fn apply(doc: &mut Document, pages: Option<&[usize]>) -> Result Option> { + const MAX_REFERENCES: usize = 16_384; + let mut references = HashSet::new(); + let Some(ap) = annotation.get(b"AP") else { return Some(references) }; + if let Some(reference) = ap.as_ref() { + references.insert(reference); + } + let resolved_ap = doc.resolve(ap); + let Some(appearances) = resolved_ap.as_dict() else { return Some(references) }; + for key in [b"N".as_slice(), b"R", b"D"] { + let Some(value) = appearances.get(key) else { continue }; + if let Some(reference) = value.as_ref() { + references.insert(reference); + } + let resolved = doc.resolve(value); + if let Object::Dict(states) = &*resolved { + for (_, state) in states.iter() { + if let Some(reference) = state.as_ref() { + references.insert(reference); + if references.len() > MAX_REFERENCES { + return None; + } + } + } + } + } + Some(references) +} + /// [`apply`] without the copy: an error can leave `doc` part redacted. fn apply_to(doc: &mut Document, pages: Option<&[usize]>) -> Result { let images = pdfcraft_cos::ImageBudget::new(doc); @@ -420,6 +467,16 @@ fn apply_within(doc: &mut Document, pages: Option<&[usize]>, images: pdfcraft_co // content rewriting and verification instead of scanning all marks for every page. let groups: Vec<_> = chosen.chunk_by(|a, b| a.page == b.page).filter_map(|group| group.first().map(|mark| (mark.page, group))).collect(); let by_page: Vec<_> = groups.iter().map(|(page, _)| *page).collect(); + // A pattern pruned from a selected page can remain reachable through another page's + // resources. When a selected page had patterns, inspect every page after the rewrite. + let source_pages = pdfcraft_model::pages(doc); + let shared_pattern_possible = by_page.iter().any(|&pi| { + source_pages + .get(pi) + .and_then(|page| page.dict.get(b"Resources")) + .map(|resources| doc.resolve(resources)) + .is_some_and(|resources| resources.as_dict().is_some_and(|dict| dict.get(b"Pattern").is_some())) + }); // Budget failures must leave even a direct library caller's document untouched. let mut remaining = overlay::MAX_BYTES; let overlays = groups @@ -439,6 +496,9 @@ fn apply_within(doc: &mut Document, pages: Option<&[usize]>, images: pdfcraft_co widget_owner, removed_everywhere: HashSet::new(), images, + removed_appearances: HashSet::new(), + appearance_scan_limit: false, + pruned_patterns: Vec::new(), }; for &(pi, page_marks) in &groups { let page = pdfcraft_model::pages(doc).swap_remove(pi); @@ -449,7 +509,18 @@ fn apply_within(doc: &mut Document, pages: Option<&[usize]>, images: pdfcraft_co if applying.images.refused() > 0 { return Err(RedactError::ImagesPastAllowance); } - let Applying { mut report, doomed_fields, doomed_xobjects, retired_properties, mut removed_everywhere, mut images, .. } = applying; + let Applying { + mut report, + doomed_fields, + doomed_xobjects, + retired_properties, + mut removed_everywhere, + mut images, + mut removed_appearances, + mut appearance_scan_limit, + pruned_patterns, + .. + } = applying; // 2b. Replies and pop-ups of a removed annotation can be listed on another page than their // parent: their `/IRT` or `/Parent` would keep the removed comment reachable. @@ -472,6 +543,19 @@ fn apply_within(doc: &mut Document, pages: Option<&[usize]>, images: pdfcraft_co d.get(b"IRT").and_then(Object::as_ref).is_some_and(|x| removed_everywhere.contains(&x)) && d.name(b"Subtype") != Some(b"Widget"); let is_popup = d.get(b"Parent").and_then(Object::as_ref).is_some_and(|x| removed_everywhere.contains(&x)); if removed_everywhere.contains(&r) || is_reply || is_popup { + // A reply or pop-up removed here can share its appearance with an annotation + // that stays on an unselected page, like one removed under a mark: the + // all-pages pattern check must see it. + if !appearance_scan_limit { + match appearance_refs(doc, d) { + Some(references) => removed_appearances.extend(references), + None => appearance_scan_limit = true, + } + if removed_appearances.len() > 16_384 { + appearance_scan_limit = true; + removed_appearances.clear(); + } + } if removed_everywhere.insert(r) { grew = true; if is_reply { @@ -532,6 +616,8 @@ fn apply_within(doc: &mut Document, pages: Option<&[usize]>, images: pdfcraft_co // A removed image or form must not stay reachable through another resource dictionary (an // inherited or shared /Resources): a full save keeps whatever is still referenced. interp::unlink_doomed(doc, &doomed_xobjects, &retired_properties)?; + // Likewise a pruned pattern: a /Pages node above the page can still name its cell. + interp::unlink_pruned_patterns(doc, &pruned_patterns)?; report.images_restored = restore_shared_jbig2(doc, &doomed_xobjects, &mut images)?; // 5. Verify: nothing readable may remain under a region. @@ -554,8 +640,32 @@ fn apply_within(doc: &mut Document, pages: Option<&[usize]>, images: pdfcraft_co if residue > 0 { return Err(RedactError::Residue(residue)); } - // The previous revision still holds the removed content: the next save must rewrite. - doc.require_full_save(); + // The interpreter can remove a pattern's paint while another use keeps the cell reachable. + // Inspect the finished selected pages, including rewritten Forms, and all pages if a removed + // pattern or appearance may still be shared. Retained unsafe cells refuse the redaction; + // `apply` runs on a copy, so the refusal leaves the caller's document as it was. + let shared_appearance_possible = appearance_scan_limit + || !removed_appearances.is_empty() + && pdfcraft_model::pages(doc).iter().enumerate().any(|(index, page)| { + !by_page.contains(&index) + && annots_of(doc, &page.dict).iter().any(|annotation| { + doc.resolve(annotation).as_dict().is_some_and(|dict| { + appearance_refs(doc, dict).is_none_or(|refs| refs.iter().any(|reference| removed_appearances.contains(reference))) + }) + }) + }); + let first_page = by_page.first().map_or(1, |p| p + 1); + let check_pages = + if shared_pattern_possible || shared_appearance_possible { (0..pdfcraft_model::pages(doc).len()).collect::>() } else { by_page }; + // A pruned pattern may also stay named by a /Pages node no page inherits from, or by one a + // page with a broken /Parent link still reaches: then every page-tree node is inspected too. + pattern_guard::check(doc, &check_pages, shared_pattern_possible || !pruned_patterns.is_empty())?; + // Whatever reference keeps a pruned pattern in the file -- one no walk above follows -- the + // full save would write it: prove it safe or refuse. + pattern_guard::check_pruned_unreachable(doc, &pruned_patterns, first_page)?; + // The previous revision still holds the removed content: the next save must rewrite, and the + // rewritten file is a different file from its source, so it gets a new identifier. + doc.require_full_save_with_new_id(); Ok(report) } @@ -640,6 +750,13 @@ struct Applying { removed_everywhere: HashSet, /// What clearing images may spend, across the run's pages. images: pdfcraft_cos::ImageBudget, + /// Appearance streams of the annotations removed, on any page: one shared with a kept + /// annotation keeps a pruned pattern's cell reachable (see `pattern_guard`). + removed_appearances: HashSet, + /// Too many appearance references to track: the pattern guard inspects every page. + appearance_scan_limit: bool, + /// Pattern objects pruned from a page's resources, which page-tree nodes may still name. + pruned_patterns: Vec, } /// Step 1 for one page: rewrites its content so nothing readable stays under a mark, and cleans the tags it no longer shows. @@ -650,7 +767,7 @@ fn redact_page_content( page: &pdfcraft_model::Page, rects: &[[f64; 4]], ) -> Result<(), RedactError> { - let Applying { report, doomed_xobjects, retired_properties, images, .. } = applying; + let Applying { report, doomed_xobjects, retired_properties, images, pruned_patterns, .. } = applying; // 1. Content. let mut budget = pdfcraft_cos::DecodeBudget::page(); let (list, data) = page_streams_within(doc, &page.dict, pi, &mut budget)?; @@ -723,6 +840,11 @@ fn redact_page_content( }, pi, )?; + // A pattern this page selected but no surviving paint draws leaves its resources, so + // its cell -- a content stream this pass does not enter -- cannot stay in the file. + // A Type 3 glyph without resources paints with patterns nobody tracked: keep them all. + let painted = if out.keeps_all_patterns { &out.patterns_seen } else { &out.patterns_painted }; + report.patterns_removed += interp::prune_patterns(doc, &mut res, &out.patterns_seen, painted, pruned_patterns); retired_properties.extend(interp::prune_properties(doc, &mut res, &cleaned_data)?); type3::prune_type3_from_resources(doc, &mut res, &cleaned_data)?; doc.update_dict(page.obj, |d| { @@ -751,7 +873,7 @@ fn remove_page_annotations( rects: &[[f64; 4]], page_marks: &[&Mark], ) -> Result<(), RedactError> { - let Applying { report, doomed_fields, widget_owner, removed_everywhere, .. } = applying; + let Applying { report, doomed_fields, widget_owner, removed_everywhere, removed_appearances, appearance_scan_limit, .. } = applying; // 2. Annotations: the marks, and whatever lies under them (with their pop-ups). let annots = annots_of(doc, &doc.get(page.obj).as_dict().cloned().unwrap_or_default()); let mut removed: Vec = Vec::new(); @@ -809,6 +931,25 @@ fn remove_page_annotations( } } removed_everywhere.extend(removed.iter().copied()); + // A removed annotation's appearance streams can be shared with a kept one on another page, + // which would keep a pruned pattern's cell reachable: remember them for the pattern guard. + for reference in &removed { + if *appearance_scan_limit { + break; + } + if let Some(annotation) = doc.get(*reference).as_dict() { + match appearance_refs(doc, annotation) { + Some(references) => { + removed_appearances.extend(references); + if removed_appearances.len() > 16_384 { + *appearance_scan_limit = true; + removed_appearances.clear(); + } + } + None => *appearance_scan_limit = true, + } + } + } // Pop-ups dropped with their parent below count too: a reply on another page may answer one. for a in &annots { let Some(r) = a.as_ref() else { continue }; diff --git a/crates/redact/src/pattern_guard.rs b/crates/redact/src/pattern_guard.rs new file mode 100644 index 0000000000..96b865e3da --- /dev/null +++ b/crates/redact/src/pattern_guard.rs @@ -0,0 +1,496 @@ +//! Refuse pattern content that remains reachable after redaction (#3647). +//! +//! Pattern cells paint through a path, not `Do`, so clipping/removing the path does not remove +//! their bytes. Inspect the rewritten pages' resource graphs before committing the +//! working copy. This is deliberately conservative: an unused text/image-bearing pattern is +//! refused too. A plain vector pattern remains supported. The bounded read-only pass follows +//! the fail-closed approach proposed in PR #162. + +use std::collections::HashSet; + +use pdfcraft_cos::{Dict, Document, ObjRef, Object, Stream}; + +use crate::RedactError; + +/// How deep the walk may recurse. Every step down (a reference, an array, a dictionary, a stream, +/// a resources map) is one frame, and a nested form costs about four of them: the 50-deep chain +/// in `a_deeply_nested_form_keeps_the_text_nobody_marked` peaks at 200. The interpreter follows +/// forms as deep as the renderer and Edit text read (`interp::MAX_DEPTH`, #3645), so this must +/// reach at least that far, or the guard would refuse a document the redaction itself handles. +/// Total work is bounded separately by `MAX_OBJECTS`, and 512 frames stay far inside a thread's +/// stack. +const MAX_DEPTH: usize = 512; +const _: () = assert!(MAX_DEPTH >= 8 * crate::interp::MAX_DEPTH, "the guard must walk past the deepest form the interpreter follows"); +const MAX_OBJECTS: usize = 16_384; +const MAX_STREAM_BYTES: usize = 1 << 20; +const MAX_TOTAL_BYTES: usize = 8 << 20; +const MAX_FILTERS: usize = 16; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)] +pub enum PatternProblem { + #[error("a tiling pattern carries text or images that cannot be removed safely")] + Content, + #[error("pattern resources or content cannot be read completely")] + Unreadable, + #[error("pattern inspection exceeded its resource, depth or decoded-content budget")] + Limit, +} + +struct Guard { + left: usize, + bytes_left: usize, + seen: HashSet<(ObjRef, bool)>, + active: HashSet<(ObjRef, bool)>, +} + +impl Guard { + fn new() -> Self { + Self { left: MAX_OBJECTS, bytes_left: MAX_TOTAL_BYTES, seen: HashSet::new(), active: HashSet::new() } + } + + fn charge(&mut self, depth: usize) -> Result<(), PatternProblem> { + self.left = self.left.checked_sub(1).ok_or(PatternProblem::Limit)?; + if depth > MAX_DEPTH { + return Err(PatternProblem::Limit); + } + Ok(()) + } + + fn walk(&mut self, doc: &Document, object: &Object, inside: bool, depth: usize) -> Result<(), PatternProblem> { + self.charge(depth)?; + match object { + Object::Ref(reference) => { + let key = (*reference, inside); + if inside && self.active.contains(&key) { + return Err(PatternProblem::Unreadable); + } + if !self.seen.insert(key) { + return Ok(()); + } + let value = doc.try_get(reference.num).map_err(|_| PatternProblem::Unreadable)?; + self.active.insert(key); + let result = self.walk(doc, &value, inside, depth + 1); + self.active.remove(&key); + result + } + Object::Array(values) => { + for value in values { + self.walk(doc, value, inside, depth + 1)?; + } + Ok(()) + } + Object::Dict(dict) => self.dictionary(doc, dict, inside, false, depth + 1), + Object::Stream(stream) => { + if inside { + let subtype = resolved(doc, stream.dict.get(b"Subtype"))?; + let pattern_type = resolved(doc, stream.dict.get(b"PatternType"))?; + if subtype.as_name() == Some(b"Image") { + return Err(PatternProblem::Content); + } + if subtype.as_name() == Some(b"Form") { + if resolved(doc, stream.dict.get(b"Subtype2"))? != Object::Null || resolved(doc, stream.dict.get(b"Ref"))? != Object::Null { + return Err(PatternProblem::Unreadable); + } + self.content(doc, stream)?; + } else if pattern_type.as_int() == Some(1) { + self.content(doc, stream)?; + } + } + self.dictionary(doc, &stream.dict, inside, true, depth + 1) + } + _ => Ok(()), + } + } + + fn dictionary(&mut self, doc: &Document, dict: &Dict, inside: bool, stream: bool, depth: usize) -> Result<(), PatternProblem> { + // Stream dictionaries include appearance and soft-mask streams whose consumers + // may infer Form semantics without /Subtype. Resource-map names, in contrast, + // are arbitrary and must not be mistaken for dictionary field names. + let subtype = resolved(doc, dict.get(b"Subtype"))?; + let pattern_type = resolved(doc, dict.get(b"PatternType"))?; + let owns_resources = stream || matches!(subtype.as_name(), Some(b"Form" | b"Type3")) || pattern_type.as_int() == Some(1); + for (key, value) in dict.iter() { + if owns_resources && key.as_slice() == b"Resources" { + self.resources(doc, value, inside, depth + 1)?; + } else if inside || !owns_resources { + self.walk(doc, value, inside, depth + 1)?; + } + } + Ok(()) + } + + fn resources(&mut self, doc: &Document, object: &Object, inside: bool, depth: usize) -> Result<(), PatternProblem> { + self.charge(depth)?; + let object = resolved(doc, Some(object))?; + // A Form's null Resources is equivalent to an absent entry: it uses the already + // inspected caller resources. Tiling-pattern resources are required separately. + if object == Object::Null { + return Ok(()); + } + let Some(resources) = object.as_dict() else { return Err(PatternProblem::Unreadable) }; + for (category, value) in resources.iter() { + // Resource dictionaries may include large embedded fonts and colour tables. Only + // structures that can own another pattern cell need recursive inspection. + if !matches!(category.as_slice(), b"Pattern" | b"XObject" | b"Font" | b"Properties" | b"ExtGState") { + continue; + } + if category.as_slice() == b"Font" { + let fonts = resolved(doc, Some(value))?; + let Some(fonts) = fonts.as_dict() else { return Err(PatternProblem::Unreadable) }; + for (_, font) in fonts.iter() { + self.charge(depth)?; + let font = resolved(doc, Some(font))?; + let Some(dict) = font.as_dict() else { return Err(PatternProblem::Unreadable) }; + if resolved(doc, dict.get(b"Subtype"))?.as_name() == Some(b"Type3") + && let Some(resources) = dict.get(b"Resources") + { + self.resources(doc, resources, inside, depth + 1)?; + } + } + continue; + } + if matches!(category.as_slice(), b"Pattern" | b"XObject" | b"Properties" | b"ExtGState") && resolved(doc, Some(value))? == Object::Null { + continue; + } + if category.as_slice() == b"Pattern" { + let object = resolved(doc, Some(value))?; + let Some(patterns) = object.as_dict() else { return Err(PatternProblem::Unreadable) }; + for (_, pattern) in patterns.iter() { + self.charge(depth)?; + let object = resolved(doc, Some(pattern))?; + if object == Object::Null { + continue; + } + let Some(dict) = object.as_dict() else { return Err(PatternProblem::Unreadable) }; + let kind = resolved(doc, dict.get(b"PatternType"))?; + match (kind.as_int(), &object) { + (Some(1), Object::Stream(_)) => { + // Do not guess a fallback for a malformed cell, which different + // readers may resolve differently. Pattern resources are mandatory. + if resolved(doc, dict.get(b"Resources"))?.as_dict().is_none() { + return Err(PatternProblem::Unreadable); + } + } + (Some(2), Object::Dict(_)) => {} + _ => return Err(PatternProblem::Unreadable), + } + self.walk(doc, pattern, true, depth + 1)?; + } + } else { + if (inside && matches!(category.as_slice(), b"XObject" | b"Properties")) || category.as_slice() == b"ExtGState" { + let object = resolved(doc, Some(value))?; + let Some(entries) = object.as_dict() else { return Err(PatternProblem::Unreadable) }; + for (_, entry) in entries.iter() { + self.charge(depth)?; + let object = resolved(doc, Some(entry))?; + if object == Object::Null { + continue; + } + if category.as_slice() == b"Properties" { + let Some(properties) = object.as_dict() else { return Err(PatternProblem::Unreadable) }; + replacement_text(doc, properties)?; + } else if category.as_slice() == b"ExtGState" { + let Some(state) = object.as_dict() else { return Err(PatternProblem::Unreadable) }; + match resolved(doc, state.get(b"SMask"))? { + Object::Null => {} + Object::Name(name) if name == b"None" => {} + Object::Dict(mask) => { + let group = resolved(doc, mask.get(b"G"))?; + let Object::Stream(group) = group else { return Err(PatternProblem::Unreadable) }; + readable_form(doc, &group)?; + if let Some(value) = mask.get(b"G") { + self.walk(doc, value, inside, depth + 1)?; + } + } + _ => return Err(PatternProblem::Unreadable), + } + } else { + let Object::Stream(stream) = object else { return Err(PatternProblem::Unreadable) }; + let subtype = resolved(doc, stream.dict.get(b"Subtype"))?; + if subtype.as_name() == Some(b"Image") { + return Err(PatternProblem::Content); + } + readable_form(doc, &stream)?; + } + } + } + if category.as_slice() == b"XObject" { + let entries = resolved(doc, Some(value))?; + let Some(entries) = entries.as_dict() else { return Err(PatternProblem::Unreadable) }; + for (_, entry) in entries.iter() { + self.charge(depth)?; + let object = resolved(doc, Some(entry))?; + if let Object::Stream(stream) = object + && resolved(doc, stream.dict.get(b"Subtype"))?.as_name() == Some(b"Form") + { + self.walk(doc, entry, inside, depth + 1)?; + } + } + } + } + } + Ok(()) + } + + fn content(&mut self, doc: &Document, stream: &Stream) -> Result<(), PatternProblem> { + // Strict decoding with a small bound, unlike the tolerant general reader. Normalize + // indirect filter declarations before using Stream::filters, which accepts direct data. + let normalized = normalized_stream(doc, stream)?; + let chain = normalized.filters(); + let max = MAX_STREAM_BYTES.min(self.bytes_left); + if chain.is_empty() && normalized.raw.len() > max { + return Err(PatternProblem::Limit); + } + let data = pdfcraft_filters::decode(&chain, &normalized.raw, max).map_err(|error| match error { + pdfcraft_filters::FilterError::LimitExceeded(_) => PatternProblem::Limit, + _ => PatternProblem::Unreadable, + })?; + self.bytes_left = self.bytes_left.checked_sub(data.len()).ok_or(PatternProblem::Limit)?; + let parsed = pdfcraft_content::parse(&data); + if parsed.skipped != 0 { + return Err(PatternProblem::Unreadable); + } + for op in parsed.ops { + self.charge(0)?; + if matches!(op.op.as_slice(), b"BDC" | b"DP") { + for operand in &op.operands { + if let Some(properties) = resolved(doc, Some(operand))?.as_dict() { + replacement_text(doc, properties)?; + } + } + } + match op.op.as_slice() { + b"Tj" | b"TJ" | b"'" | b"\"" | b"BI" => return Err(PatternProblem::Content), + // Unknown operators cannot establish that no hidden content was skipped. + b"q" | b"Q" | b"cm" | b"w" | b"J" | b"j" | b"M" | b"d" | b"ri" | b"i" | b"gs" | b"m" | b"l" | b"c" | b"v" | b"y" | b"h" | b"re" + | b"S" | b"s" | b"f" | b"F" | b"f*" | b"B" | b"B*" | b"b" | b"b*" | b"n" | b"W" | b"W*" | b"BT" | b"ET" | b"Tc" | b"Tw" | b"Tz" + | b"TL" | b"Tf" | b"Tr" | b"Ts" | b"Td" | b"TD" | b"Tm" | b"T*" | b"d0" | b"d1" | b"CS" | b"cs" | b"SC" | b"SCN" | b"sc" | b"scn" + | b"G" | b"g" | b"RG" | b"rg" | b"K" | b"k" | b"sh" | b"Do" | b"MP" | b"DP" | b"BMC" | b"BDC" | b"EMC" | b"BX" | b"EX" => {} + _ => return Err(PatternProblem::Unreadable), + } + } + Ok(()) + } +} + +fn readable_form(doc: &Document, stream: &Stream) -> Result<(), PatternProblem> { + // PS, Form/Subtype2 PS, reference XObjects and unknown/missing subtypes cannot be + // proven free of recoverable pattern content by the PDF content parser. + if resolved(doc, stream.dict.get(b"Subtype"))?.as_name() != Some(b"Form") + || resolved(doc, stream.dict.get(b"Subtype2"))? != Object::Null + || resolved(doc, stream.dict.get(b"Ref"))? != Object::Null + { + return Err(PatternProblem::Unreadable); + } + Ok(()) +} + +fn replacement_text(doc: &Document, properties: &Dict) -> Result<(), PatternProblem> { + for key in [b"ActualText".as_slice(), b"Alt", b"E"] { + if resolved(doc, properties.get(key))? != Object::Null { + return Err(PatternProblem::Content); + } + } + Ok(()) +} + +fn resolved(doc: &Document, value: Option<&Object>) -> Result { + let mut value = value.cloned().unwrap_or(Object::Null); + for _ in 0..MAX_DEPTH { + let Object::Ref(reference) = value else { return Ok(value) }; + value = (*doc.try_get(reference.num).map_err(|_| PatternProblem::Unreadable)?).clone(); + } + Err(PatternProblem::Limit) +} + +fn normalized_stream(doc: &Document, stream: &Stream) -> Result { + if stream.dict.contains(b"F") || stream.dict.contains(b"FFilter") || stream.dict.contains(b"FDecodeParms") || stream.dict.contains(b"DP") { + return Err(PatternProblem::Unreadable); + } + let mut normalized = stream.clone(); + let filter = resolved(doc, stream.dict.get(b"Filter"))?; + let names = match &filter { + Object::Null => Vec::new(), + Object::Name(_) => vec![filter], + Object::Array(values) if values.len() <= MAX_FILTERS => values.iter().map(|v| resolved(doc, Some(v))).collect::, _>>()?, + _ => return Err(PatternProblem::Unreadable), + }; + if names.iter().any(|name| name.as_name().is_none()) { + return Err(PatternProblem::Unreadable); + } + let parms = resolved(doc, stream.dict.get(b"DecodeParms"))?; + let parms = match parms { + Object::Null => vec![Object::Null; names.len()], + Object::Dict(_) if names.len() == 1 => vec![parms], + Object::Array(values) if values.len() == names.len() => values, + _ => return Err(PatternProblem::Unreadable), + }; + let parms = parms + .iter() + .map(|value| { + let value = resolved(doc, Some(value))?; + let Object::Dict(mut dict) = value else { + return if value == Object::Null { Ok(value) } else { Err(PatternProblem::Unreadable) }; + }; + for key in [b"Predictor".as_slice(), b"Colors", b"BitsPerComponent", b"Columns", b"EarlyChange"] { + if let Some(value) = dict.get(key) { + let value = resolved(doc, Some(value))?; + if value.as_int().is_none() { + return Err(PatternProblem::Unreadable); + } + dict.set(key.to_vec(), value); + } + } + if !matches!(dict.int(b"Predictor").unwrap_or(1), 1 | 2 | 10..=15) + || dict.int(b"Colors").unwrap_or(1) <= 0 + || dict.int(b"Columns").unwrap_or(1) <= 0 + || !matches!(dict.int(b"BitsPerComponent").unwrap_or(8), 1 | 2 | 4 | 8 | 16) + || !matches!(dict.int(b"EarlyChange").unwrap_or(1), 0 | 1) + { + return Err(PatternProblem::Unreadable); + } + Ok(Object::Dict(dict)) + }) + .collect::, _>>()?; + normalized.dict.set(b"Filter".to_vec(), Object::Array(names)); + normalized.dict.set(b"DecodeParms".to_vec(), Object::Array(parms)); + Ok(normalized) +} + +/// Page-tree nodes a walk of the tree may visit, pages included, before it refuses: the page tree +/// is walked whole elsewhere too (`pdfcraft_model::pages`, `unlink_doomed`), so a long document +/// must not refuse here. +const MAX_TREE_NODES: usize = 1_000_000; + +/// Every node a full save reaches through the page tree -- down `/Kids` and up the `/Parent` of +/// every node visited, page or `/Pages`, so a node reached only through a `/Parent` link counts +/// too -- that has `/Resources` of its own and is not one of the document's pages: those are +/// walked with their effective resources. Cycles are cut by the seen-set. Holders are bounded by +/// `MAX_OBJECTS`, pages are not. +fn tree_holders(doc: &Document) -> Result, PatternProblem> { + let Some(top) = doc.root().and_then(|root| doc.get(root).as_dict().and_then(|d| d.reference(b"Pages"))) else { return Ok(Vec::new()) }; + let pages: HashSet = pdfcraft_model::pages(doc).iter().map(|p| p.obj).collect(); + // The `/Resources` values to inspect. A direct `/Parent` dictionary is written inline by a + // full save, so it is a node like any other: its resources, `/Parent` and `/Kids` count. + let mut holders = Vec::new(); + let mut seen = HashSet::new(); + seen.insert(top); + let mut stack = vec![top]; + let mut inline: Vec = Vec::new(); + // One node: queue what it links to that was not seen yet (so a /Kids array shared by many + // nodes costs its length once per node, never a copy), and keep its resources. + let mut visit = + |dict: &Dict, is_page: bool, stack: &mut Vec, inline: &mut Vec, holders: &mut Vec| -> Result<(), PatternProblem> { + match dict.get(b"Parent") { + Some(Object::Ref(parent)) => { + if seen.insert(*parent) { + stack.push(*parent); + } + } + Some(Object::Dict(parent)) => { + if inline.len() >= MAX_DEPTH { + return Err(PatternProblem::Limit); + } + inline.push(parent.clone()); + } + _ => {} + } + if let Some(resources) = dict.get(b"Resources") + && !is_page + { + holders.push(resources.clone()); + if holders.len() > MAX_OBJECTS { + return Err(PatternProblem::Limit); + } + } + let is_pages = dict.name(b"Type") == Some(b"Pages") || (dict.contains(b"Kids") && dict.name(b"Type") != Some(b"Page")); + if is_pages { + let kids_object = match dict.get(b"Kids") { + Some(Object::Ref(reference)) => Some(doc.try_get(reference.num).map_err(|_| PatternProblem::Unreadable)?), + _ => None, + }; + let kids = match &kids_object { + Some(object) => object.as_array(), + None => dict.get(b"Kids").and_then(Object::as_array), + }; + for kid in kids.into_iter().flatten().filter_map(Object::as_ref) { + if seen.insert(kid) { + stack.push(kid); + } + } + } + if seen.len() > MAX_TREE_NODES { + return Err(PatternProblem::Limit); + } + Ok(()) + }; + loop { + if let Some(node) = stack.pop() { + let object = doc.try_get(node.num).map_err(|_| PatternProblem::Unreadable)?; + if let Some(dict) = object.as_dict() { + visit(dict, pages.contains(&node), &mut stack, &mut inline, &mut holders)?; + } + } else if let Some(dict) = inline.pop() { + visit(&dict, false, &mut stack, &mut inline, &mut holders)?; + } else { + break; + } + } + Ok(holders) +} + +/// Validate the requested pages before `apply` commits its working copy. With `tree`, the +/// `/Resources` of every page-tree node above the pages is inspected as well: a node no page +/// inherits from, or one a page with a broken `/Parent` link still reaches, can keep a pruned +/// cell in the saved file. +pub(crate) fn check(doc: &Document, selected: &[usize], tree: bool) -> Result<(), RedactError> { + if tree && let Some(&first) = selected.first() { + let page = first.saturating_add(1); + let holders = tree_holders(doc).map_err(|reason| RedactError::Pattern { page, reason })?; + for resources in holders { + let mut guard = Guard::new(); + guard.resources(doc, &resources, false, 0).map_err(|reason| RedactError::Pattern { page, reason })?; + } + } + let pages = pdfcraft_model::pages(doc); + for &index in selected { + let Some(page) = pages.get(index) else { return Err(RedactError::Unreadable(index.saturating_add(1))) }; + let mut guard = Guard::new(); + let checked = (|| { + if let Some(resources) = page.dict.get(b"Resources") { + guard.resources(doc, resources, false, 0)?; + } + // Kept appearance streams may own their own pattern resources. + for annotation in crate::annots_of(doc, &page.dict) { + let object = resolved(doc, Some(&annotation))?; + if let Some(appearance) = object.as_dict().and_then(|dict| dict.get(b"AP")) { + guard.walk(doc, appearance, false, 0)?; + } + } + Ok(()) + })(); + checked.map_err(|reason| RedactError::Pattern { page: index.saturating_add(1), reason })?; + } + Ok(()) +} + +/// The backstop after every other check: a full save writes whatever the trailer reaches, by any +/// reference at all -- a stray resource category, a key on a page, a direct /Parent, `/AcroForm +/// /DR`, `/PieceInfo` -- and the walks above follow only the references they know. A pattern +/// pruned from a page that a full save would still write must therefore be proven safe like any +/// retained cell (vector-only), or the redaction is refused. Costs one walk of the reachable +/// objects, and only when a pattern was pruned. +pub(crate) fn check_pruned_unreachable(doc: &Document, pruned: &[ObjRef], page: usize) -> Result<(), RedactError> { + if pruned.is_empty() { + return Ok(()); + } + let reachable = pdfcraft_cos::reachable_objects(doc)?; + let mut guard = Guard::new(); + let mut checked = HashSet::new(); + for &pattern in pruned { + if reachable.contains(&pattern.num) && checked.insert(pattern.num) { + guard.walk(doc, &Object::Ref(pattern), true, 0).map_err(|reason| RedactError::Pattern { page, reason })?; + } + } + Ok(()) +} diff --git a/crates/redact/src/patterns.rs b/crates/redact/src/patterns.rs index 59e623a7e7..9662602671 100644 --- a/crates/redact/src/patterns.rs +++ b/crates/redact/src/patterns.rs @@ -1,5 +1,5 @@ //! Search & Redact patterns (Acrobat's Find Text ▸ Patterns): phone numbers, email addresses, -//! credit card numbers, US Social Security numbers and dates. Each matcher works on a page's +//! credit card numbers, US Social Security numbers, dates and IBANs. Each matcher works on a page's //! text as characters and returns character ranges; callers map them to glyphs and areas. use std::ops::Range; @@ -11,9 +11,10 @@ pub enum Pattern { CreditCard, Ssn, Date, + Iban, } -pub const PATTERNS: [Pattern; 5] = [Pattern::Phone, Pattern::Email, Pattern::CreditCard, Pattern::Ssn, Pattern::Date]; +pub const PATTERNS: [Pattern; 6] = [Pattern::Phone, Pattern::Email, Pattern::CreditCard, Pattern::Ssn, Pattern::Date, Pattern::Iban]; impl Pattern { pub fn label(self) -> &'static str { @@ -23,6 +24,7 @@ impl Pattern { Pattern::CreditCard => "Credit Cards", Pattern::Ssn => "Social Security Numbers", Pattern::Date => "Dates", + Pattern::Iban => "IBAN Numbers", } } @@ -33,6 +35,7 @@ impl Pattern { Pattern::CreditCard => "credit-card", Pattern::Ssn => "ssn", Pattern::Date => "date", + Pattern::Iban => "iban", } } @@ -397,6 +400,173 @@ fn date(s: &[char], i: usize) -> Option { Some(k2 + y - i) } +/// An IBAN (ISO 13616): a two-letter country code, two check digits and the rest +/// of the country's exact length in letters and digits, either compact or in the +/// printed groups of four. A space is accepted only after a full group, so an +/// ordinary word after a code ("BA37 leaves at noon") ends the run. Valid iff the +/// number is one modulo 97 after moving the first four characters to the end. The +/// country code must be in the registry, and an alphanumeric character glued to +/// the end rejects the match. +fn iban(s: &[char], i: usize) -> Option { + if !(s.get(i).copied().is_some_and(|c| c.is_ascii_alphabetic()) + && s.get(i + 1).copied().is_some_and(|c| c.is_ascii_alphabetic()) + && s.get(i + 2).copied().is_some_and(|c| c.is_ascii_digit()) + && s.get(i + 3).copied().is_some_and(|c| c.is_ascii_digit())) + { + return None; + } + // Not the tail of a longer alphanumeric run. + if s.get(i.wrapping_sub(1)).is_some_and(|c| c.is_alphanumeric()) { + return None; + } + let country: String = s.iter().skip(i).take(2).map(char::to_ascii_uppercase).collect(); + let len = iban_length(&country)?; + // The IBAN's characters uppercased, read up to the country's length. + let mut digits = Vec::with_capacity(len); + let mut j = i; + let mut after_space = false; + while digits.len() < len { + match s.get(j) { + Some(c) if c.is_ascii_alphanumeric() => { + digits.push(c.to_ascii_uppercase()); + after_space = false; + } + // A single space between two groups of four. + Some(&' ') if digits.len() % 4 == 0 && !after_space => after_space = true, + _ => return None, + } + j += 1; + } + // Reject an IBAN glued directly to trailing alphanumerics ("...00ABC"). + // A space-separated suffix ("...00 123") is not part of the IBAN. + if s.get(j).is_some_and(|c| c.is_alphanumeric()) { + return None; + } + iban_check(&digits).then_some(j - i) +} + +/// Whether `digits` is a valid IBAN: move the first four characters to the end, +/// replace letters by two digits (A = 10, ..., Z = 35), and the number must be +/// one modulo 97. +fn iban_check(digits: &[char]) -> bool { + let mut rem = 0u32; + for c in digits.iter().skip(4).chain(digits.iter().take(4)).copied() { + let value = iban_value(c); + // A letter stands for two decimal digits (A = 10, ..., Z = 35), + // a digit for one. + rem = if c.is_ascii_digit() { (rem * 10 + value) % 97 } else { (rem * 100 + value) % 97 }; + } + rem == 1 +} + +/// The value of an IBAN character: a digit is itself, a letter is 10 (A) to 35 (Z). +fn iban_value(c: char) -> u32 { + match c { + '0'..='9' => c as u32 - '0' as u32, + _ => c as u32 - 'A' as u32 + 10, + } +} + +/// The exact length of an IBAN for each country code of the SWIFT IBAN registry +/// (release 99, December 2024), counting letters and digits only. A country code +/// that is not listed has no IBANs, so nothing starting with it is matched. +const IBAN_LENGTHS: [(&str, usize); 89] = [ + ("AD", 24), + ("AE", 23), + ("AL", 28), + ("AT", 20), + ("AZ", 28), + ("BA", 20), + ("BE", 16), + ("BG", 22), + ("BH", 22), + ("BI", 27), + ("BR", 29), + ("BY", 28), + ("CH", 21), + ("CR", 22), + ("CY", 28), + ("CZ", 24), + ("DE", 22), + ("DJ", 27), + ("DK", 18), + ("DO", 28), + ("EE", 20), + ("EG", 29), + ("ES", 24), + ("FI", 18), + ("FK", 18), + ("FO", 18), + ("FR", 27), + ("GB", 22), + ("GE", 22), + ("GI", 23), + ("GL", 18), + ("GR", 27), + ("GT", 28), + ("HN", 28), + ("HR", 21), + ("HU", 28), + ("IE", 22), + ("IL", 23), + ("IQ", 23), + ("IS", 26), + ("IT", 27), + ("JO", 30), + ("KW", 30), + ("KZ", 20), + ("LB", 28), + ("LC", 32), + ("LI", 21), + ("LT", 20), + ("LU", 20), + ("LV", 21), + ("LY", 25), + ("MC", 27), + ("MD", 24), + ("ME", 22), + ("MK", 19), + ("MN", 20), + ("MR", 27), + ("MT", 31), + ("MU", 30), + ("NI", 28), + ("NL", 18), + ("NO", 15), + ("OM", 23), + ("PK", 24), + ("PL", 28), + ("PS", 29), + ("PT", 25), + ("QA", 29), + ("RO", 24), + ("RS", 22), + ("RU", 33), + ("SA", 24), + ("SC", 31), + ("SD", 18), + ("SE", 24), + ("SI", 19), + ("SK", 24), + ("SM", 27), + ("SO", 23), + ("ST", 25), + ("SV", 28), + ("TL", 23), + ("TN", 24), + ("TR", 26), + ("UA", 29), + ("VA", 22), + ("VG", 24), + ("XK", 20), + ("YE", 30), +]; + +/// The length of an IBAN of `country`, if the registry lists it. +fn iban_length(country: &str) -> Option { + IBAN_LENGTHS.iter().find(|(code, _)| *code == country).map(|&(_, len)| len) +} + /// Character ranges of `text` matching `pattern`. pub fn find(pattern: Pattern, text: &[char]) -> Vec> { let f: fn(&[char], usize) -> Option = match pattern { @@ -405,6 +575,7 @@ pub fn find(pattern: Pattern, text: &[char]) -> Vec> { Pattern::CreditCard => credit_card, Pattern::Ssn => ssn, Pattern::Date => date, + Pattern::Iban => iban, }; let mut out = Vec::new(); let mut i = 0; @@ -665,4 +836,187 @@ mod tests { let s: Vec = "\u{130}\u{131}I\u{15E}".chars().collect(); assert_eq!(s.iter().copied().map(fold).collect::(), "iii\u{15F}"); } + + #[test] + fn iban_matches_compact_spaced_and_rejects_near_matches() { + assert_eq!(Pattern::from_id("iban").map(Pattern::id), Some("iban")); + + // Spaced and compact IBANs match, a wrong check digit is rejected ("DE89 + // 3704 0044 0532 0130 00" and "DE89370400440532013000" match, "...01" + // does not). + if let Some(iban_pattern) = Pattern::from_id("iban") { + // Spaced IBAN (valid German IBAN: DE89 3704 0044 0532 0130 00) + assert_eq!(found(iban_pattern, "DE89 3704 0044 0532 0130 00"), vec!["DE89 3704 0044 0532 0130 00"]); + // Compact IBAN (same number, no spaces) + assert_eq!(found(iban_pattern, "DE89370400440532013000"), vec!["DE89370400440532013000"]); + // Wrong check digit should not match (DE89...01 instead of DE89...00) + assert_eq!(found(iban_pattern, "DE89 3704 0044 0532 0130 01"), Vec::::new()); + // Near match: IBAN followed by extra digits should match only the IBAN + assert_eq!(found(iban_pattern, "DE89 3704 0044 0532 0130 00 123"), vec!["DE89 3704 0044 0532 0130 00"]); + } + } + + #[test] + fn iban_rejects_unknown_country_code_wrong_length_and_glued_tail() { + if let Some(iban_pattern) = Pattern::from_id("iban") { + // Unknown country code: the check digits pass mod-97, but ISO 13616 defines no length for XX. + assert_eq!(found(iban_pattern, "XX65000000000000000000"), Vec::::new()); + // DE is 22 characters long. This 15-character number passes mod-97 but has + // the wrong national length, so it must be rejected. + assert_eq!(found(iban_pattern, "DE8300000000000"), Vec::::new()); + // A valid IBAN glued directly to trailing alphanumerics is not an IBAN. + assert_eq!(found(iban_pattern, "DE89370400440532013000ABC"), Vec::::new()); + assert_eq!(found(iban_pattern, "ABCDE89370400440532013000"), Vec::::new()); + // Letters in place of the two check digits. + assert_eq!(found(iban_pattern, "DEAB 3704 0044 0532 0130 00"), Vec::::new()); + // A space-separated suffix does not glue to the IBAN. + assert_eq!(found(iban_pattern, "DE89 3704 0044 0532 0130 00 123"), vec!["DE89 3704 0044 0532 0130 00"]); + } + } + + #[test] + fn iban_accepts_spaces_only_between_groups_of_four() { + // A code followed by ordinary words: the words end the run, so nothing is marked. + for s in [ + "Flight BA37 leaves at noon from gate four", + "Flight BA30 leaves at noon", + "Gate BA45 leaves at noon", + "BA72 have water are word", + "GB00 their an her make that", + "SI30 write can all more", + ] { + assert_eq!(found(Pattern::Iban, s), Vec::::new(), "{s}"); + } + // A valid IBAN with a space in the wrong place, or two spaces, is not marked. + for s in ["DE89 3704 0044 0532 013 000", "DE89 3704 0044 0532 0 13000", "DE8 9370 4004 4053 2013 000", "DE89 3704 0044 0532 0130 00"] { + assert_eq!(found(Pattern::Iban, s), Vec::::new(), "{s}"); + } + // Any group boundary may be a space or not, and the IBAN inside a sentence is marked alone. + assert_eq!(found(Pattern::Iban, "DE893704 0044 0532013000"), vec!["DE893704 0044 0532013000"]); + assert_eq!(found(Pattern::Iban, "Pay to DE89 3704 0044 0532 0130 00 today"), vec!["DE89 3704 0044 0532 0130 00"]); + } + + /// One example IBAN per country of the SWIFT IBAN registry (release 99). + const IBAN_REGISTRY_EXAMPLES: [&str; IBAN_LENGTHS.len()] = [ + "AD1200012030200359100100", + "AE070331234567890123456", + "AL47212110090000000235698741", + "AT611904300234573201", + "AZ21NABZ00000000137010001944", + "BA391290079401028494", + "BE68539007547034", + "BG80BNBG96611020345678", + "BH67BMAG00001299123456", + "BI4210000100010000332045181", + "BR1800360305000010009795493C1", + "BY13NBRB3600900000002Z00AB00", + "CH9300762011623852957", + "CR05015202001026284066", + "CY17002001280000001200527600", + "CZ6508000000192000145399", + "DE89370400440532013000", + "DJ2100010000000154000100186", + "DK5000400440116243", + "DO28BAGR00000001212453611324", + "EE382200221020145685", + "EG380019000500000000263180002", + "ES9121000418450200051332", + "FI2112345600000785", + "FK88SC123456789012", + "FO6264600001631634", + "FR1420041010050500013M02606", + "GB29NWBK60161331926819", + "GE29NB0000000101904917", + "GI75NWBK000000007099453", + "GL8964710001000206", + "GR1601101250000000012300695", + "GT82TRAJ01020000001210029690", + "HN88CABF00000000000250005469", + "HR1210010051863000160", + "HU42117730161111101800000000", + "IE29AIBK93115212345678", + "IL620108000000099999999", + "IQ98NBIQ850123456789012", + "IS140159260076545510730339", + "IT60X0542811101000000123456", + "JO94CBJO0010000000000131000302", + "KW81CBKU0000000000001234560101", + "KZ86125KZT5004100100", + "LB62099900000001001901229114", + "LC55HEMM000100010012001200023015", + "LI21088100002324013AA", + "LT121000011101001000", + "LU280019400644750000", + "LV80BANK0000435195001", + "LY83002048000020100120361", + "MC5811222000010123456789030", + "MD24AG000225100013104168", + "ME25505000012345678951", + "MK07250120000058984", + "MN121234123456789123", + "MR1300020001010000123456753", + "MT84MALT011000012345MTLCAST001S", + "MU17BOMM0101101030300200000MUR", + "NI45BAPR00000013000003558124", + "NL91ABNA0417164300", + "NO9386011117947", + "OM810180000001299123456", + "PK36SCBL0000001123456702", + "PL61109010140000071219812874", + "PS92PALS000000000400123456702", + "PT50000201231234567890154", + "QA58DOHB00001234567890ABCDEFG", + "RO49AAAA1B31007593840000", + "RS35260005601001611379", + "RU0304452522540817810538091310419", + "SA0380000000608010167519", + "SC18SSCB11010000000000001497USD", + "SD2129010501234001", + "SE4550000000058398257466", + "SI56263300012039086", + "SK3112000000198742637541", + "SM86U0322509800000000270100", + "SO211000001001000100141", + "ST68000100010051845310112", + "SV62CENR00000000000000700025", + "TL380080012345678910157", + "TN5910006035183598478831", + "TR330006100519786457841326", + "UA213223130000026007233566001", + "VA59001123000012345678", + "VG96VPVG0000012345678901", + "XK051212012345678906", + "YE15CBYE0001018861234567891234", + ]; + + /// `iban` in the printed form: groups of four separated by single spaces. + fn printed(iban: &str) -> String { + iban.chars().collect::>().chunks(4).map(|group| group.iter().collect::()).collect::>().join(" ") + } + + #[test] + fn iban_registry_examples_cover_every_country_and_length() { + let from_examples: Vec<(&str, usize)> = IBAN_REGISTRY_EXAMPLES.iter().map(|e| (&e[..2], e.len())).collect(); + assert_eq!(from_examples.as_slice(), IBAN_LENGTHS.as_slice()); + } + + #[test] + fn iban_matches_the_registry_example_of_every_country() { + for example in IBAN_REGISTRY_EXAMPLES { + assert_eq!(found(Pattern::Iban, example), vec![example], "compact {example}"); + let spaced = printed(example); + assert_eq!(found(Pattern::Iban, &spaced), vec![spaced.clone()], "printed {spaced}"); + } + } + + #[test] + fn iban_rejects_a_registry_example_with_one_digit_changed() { + for example in IBAN_REGISTRY_EXAMPLES { + // The last digit becomes the next digit, so the country, the length and the layout stay the same. + let Some(at) = example.rfind(|c: char| c.is_ascii_digit()) else { continue }; + let digit = example[at..=at].parse::().unwrap_or(0); + let changed = format!("{}{}{}", &example[..at], (digit + 1) % 10, &example[at + 1..]); + assert_eq!(found(Pattern::Iban, &changed), Vec::::new(), "{changed}"); + } + } } diff --git a/crates/redact/src/sanitize.rs b/crates/redact/src/sanitize.rs index 6fd4354300..f8088e0bba 100644 --- a/crates/redact/src/sanitize.rs +++ b/crates/redact/src/sanitize.rs @@ -674,16 +674,21 @@ pub fn remove_hidden(doc: &mut Document, which: &[Hidden]) -> Result