Commit Graph
5889 Commits
Author SHA1 Message Date
wstockandClaude Fable 5.1 f0bbce5b30 Issue #2385: audit finds thick strokes, black highlights and white boxes over text (#2408)
* Issue #2385: audit finds thick strokes, black highlights and white boxes over text

Three ways of hiding text that a reader sees as redacted were reported clean
while the text stayed extractable:

- a thick stroke along the text (`0 G 20 w 70 705 m 400 705 l S`, marker
  style): the walker now tracks the stroking color, the line width and `/CA`,
  and a single axis-aligned `m`/`l` segment stroked opaquely counts as the
  rectangle it paints (half the width each side);
- an opaque `/Highlight` annotation dark enough to hide the text (`/C [0 0 0]`):
  the annotation pass now reads highlights too (color from `/C`, `/CA`,
  Hidden/NoView skipped) and reports them as `covered-text`;
- an opaque white rectangle after dark text (`1 g 70 695 330 20 re f`): its
  own kind, `hidden-under-white` (relative luminance of the paint >= 0.9; the
  `0.9 g` table shading stays unflagged), so callers can decide.

The `doc_audit_redactions` tool description lists the new covers and kind;
the module docs state the limits (slanted or bent strokes, other filled
paths, shadings and patterns are still out of scope).

Tests: thick_stroke_over_text_is_a_cover, black_highlight_annotation_over_
text_is_a_cover, white_rectangle_over_text_is_reported_as_hidden_under_white
(the report's three cases, with the hairline, yellow, translucent, hidden and
outlined negatives); graphics_state_carries_across_streams now expects the
white kind for its white rectangle.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011K1peyrh5MdZ6ttHkVq8Gh

* audit: ExtGState /LW and omitted alphas, stroke width across the CTM, white first, highlight quads (#2385 review)

- gs sets /LW as the line width, and a /ca or /CA the dictionary leaves out
  keeps its earlier value (ISO 32000-2 8.4.5) instead of resetting to opaque.
- A stroke's width is measured across the segment after the CTM, so a
  non-uniform scale no longer widens horizontal and vertical strokes alike.
- A white cover is hidden-under-white even over white text, which the
  contrast check had classified as covered-text.
- An opaque Highlight hides what its /QuadPoints paint, not its /Rect; the
  /Rect stays the fallback when there are no usable quads.

Tests: ext_gstate_sets_line_width_and_keeps_omitted_alphas,
stroke_width_follows_a_non_uniform_ctm_across_the_segment,
white_cover_over_white_text_is_hidden_under_white,
highlight_covers_its_quad_points_not_its_rect

* audit: document that a Highlight is judged by its dictionary, not its /AP

Developed with AI assistance (Claude Code).

* audit: a white Square is hidden-under-white; a hidden Redact mark is still unapplied (#2385 review)

An opaque /Square with a white interior went through the dark-cover
contrast test and was passed over, although it hides the text as a white
rectangle in the content does: it is reported as HiddenUnderWhite, like
that rectangle. The Hidden/NoView skip applied to every annotation, so an
unapplied /Redact mark with either flag was no longer reported, which main
reports: the flags hide the mark, not the text, so the skip is for the
cover annotations only.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011K1peyrh5MdZ6ttHkVq8Gh

* audit: a stroke's round or square caps are part of the cover (#2385 review)

`stroked_rect` left the caps out, so a `1 J` / `2 J` marker line (or `/LC` in
an ExtGState) painted half a line width past each end that the audit did not
count: text under a cap stayed extractable and unreported. The cap is tracked
like the width (`J`, `/LC`, cumulative, saved by `q`), and an axis-aligned
stroke is lengthened by the pen's extent along it, `w/2 · |Mᵀ d̂|` after the
CTM (the across-width is `w/2 · |Mᵀ n̂|`, the same rule). A round cap counts by
its box. Butt caps, the default, add nothing.

Test `stroke_caps_lengthen_the_cover`: butt, round, square, back to butt,
vertical, a 4× scale along the stroke, a shear (√2), `/LC` with `/LW`, `Q`
restoring it, and a stroke that reaches `IBAN` only by its cap.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011K1peyrh5MdZ6ttHkVq8Gh

* audit: charge a highlight's quads against the comparison bound

A highlight is compared with every line of its page once per quad, but was
charged for one cover: a /Highlight with many /QuadPoints did page_cost x quads
work for the price of page_cost. hidden_text now spends page_cost per area.

QuadPoints is read only for highlights, and its length is checked before the
numbers are collected.

Developed with AI assistance (Claude Code).

---------

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-11-19 08:20:37 -06:00
Dylan M. Taylor 44aaf2d003 Merge main preserving RTF safety and PPTX parity fixes 2026-11-18 21:06:36 -05:00
FredApps 5b8cb8ab61 Merge pull request #7830 from storytold/fix/pptx-parity-20261119
Restore plain PPTX tables and shared-writer regression checks
2026-11-19 08:12:39 +07:00
FredApps 21a9d8b1be Merge pull request #7825 from FredApps/test/button-script-completion
test(ui): await native button-script completion
2026-11-19 07:36:44 +07:00
Dylan M. Taylor 93a34204e3 Preserve plain PPTX tables and validate shared-writer semantics 2026-11-18 19:23:10 -05:00
Dylan M. Taylor 8f4f4ea9c5 Cut over pptx export to craft-pptx (#7823)
* cut over pptx export to craft-pptx (storytold/craft-libs#792)

* style(export): run cargo fmt on pptx.rs
2026-11-18 18:57:36 -05:00
FredApps 60ca578c37 test(ui): await native button script completion 2026-11-19 00:37:30 +01:00
Dylan M. Taylor 8d14c81be2 Bound aggregate input work for rotated RTF picture probes 2026-11-18 18:07:30 -05:00
kiwi4boy f77ad824ee Merge main (#7814, which landed steps 1 and 2) and keep the RTF picture fixes
#7814 brought this branch's first two commits to main inside step 2, but not the three
fixes made here since: the RTF picture budget that counts every placement, rotations baked
into the pictures, pictures fitted to the text height, and the pages that lost a picture
reported through truncated_pages. They now sit in step 2's Builder: RTF's flow_doc gives
it a pictures::Budget, and Word's word_doc doesn't, so Word keeps its own limits
(room_for) and turns positioned pictures through their float. The text-height fit is in
the shared picture(), so Word's flowing pictures fit too.

The truncated_pages doc now says what RTF reports: pictures lost to its own limits or a
rotation it couldn't bake. A picture no format can encode is left out of all of them.
2026-11-18 17:28:58 -05:00
Dylan M. Taylorandkiwi4boy d03b99ea54 Export: Word through craft-docx, from the shared word model (rebased #7592) (#7814)
* export: write RTF through craft-rtf's full writer, from the word model

The pages are mapped onto a craft_wordmodel::Document (as_word.rs, the
mapping the DOCX export will share), and craft_rtf::doc::export writes
it. Over the small writer this keeps, in RTF:
- pictures, inline (the engine no longer leaves them out for RTF);
- each page's size, as a section per page (blank pages kept);
- Heading 1 and 2 styles;
- the title;
- hard line breaks inside a paragraph or cell (storytold/pdfcraft#4723).
It also fixes two bugs: \cellx was the absolute page x, so every column
edge sat one left margin too far right, and tables that touched became
one (NIST CSF 2.0 came out with 28 tables instead of 68).

craft-rtf, craft-wordmodel, craft-docx and craft-mime are pinned together
at one craft-libs commit: doc::export takes its own revision's Document.

* export: pin craft-libs main with push_text, the header-row fix and the RTF generator name

craft-rtf, craft-wordmodel, craft-docx and craft-mime move to craft-libs
b8eaa8e2, which has storytold/craft-libs#1946, #1947 and #1950. The
mapping appends through Paragraph::push_text/push_object, tables keep
the default look, and the RTF names PdfCraft as its generator.

* export: write Word through craft-docx, from the shared word model

as_docx.rs no longer writes WordprocessingML itself: as_word::word_doc
maps the pages onto a craft_wordmodel::Document and craft_docx::write
writes it. The decisions stay the same: a page with rotated text or
overlapping text keeps its layout as positioned text boxes and pictures
(watermark-sized text behind, pictures over it, other text on top), the
other pages flow, each page is a section of its own size, a shared page
colour is the document's, the PDF's language goes in the slot Word keeps
for its script, and the media limits are unchanged.

Over the hand-written package this gains:
- a VML fallback for every text box, so Word 2007 opens positioned pages;
- rotated text as a turned text box Word draws as a line;
- the body font named (Arial), with a font table saying it is a sans;
- PdfCraft as the application in docProps/app.xml;
- a picture drawn many times stored once.

The tests that matched XML read the package back through craft-docx.

* parity: the Word export through craft-docx, checked in Word 16, Word 2007 and LibreOffice

* chore: update Cargo.lock after rebasing #7592

---------

Co-authored-by: kiwi4boy <kiwi4boy@gmail.com>
2026-11-18 17:11:01 -05:00
FredApps f9bfa19e74 test: keep startup password assertions independent of worker order 2026-11-18 21:26:45 +01:00
Dylan M. Taylor ac8c44517d Fit RTF pictures within page bounds and report omitted media 2026-11-18 14:57:09 -05:00
Dylan M. Taylor 1cd10fb9b2 Merge current main while preserving RTF and HTML media regressions 2026-11-18 14:06:43 -05:00
Dylan M. Taylor 0b50bddc84 Bound RTF picture expansion and bake image rotations before embedding 2026-11-18 14:05:40 -05:00
FredApps bad6ac7fa2 Merge pull request #7779 from FredApps/chore/778-xfa-merged-pin
Use merged XFA namespace and BOM safety fixes
2026-11-19 00:57:14 +07:00
Dylan M. Taylor b11d37c0ed Merge pull request #7795 from storytold/fix/shared-ocsp-wrapper-pin-20261118
fix(sign): consume standard OCSP certificate wrapper parsing
2026-11-18 12:36:28 -05:00
FredApps fe16ea4834 fix(xfa): classify shared namespace admission as too large 2026-11-18 18:07:30 +01:00
FredApps 39b3f45a9d Merge current main to validate the #778 dependency pin with baseline repairs 2026-11-18 17:07:47 +01:00
Dylan M. Taylor 3f1088afe2 Keep the OCSP parity oracle independent for embedded certificates 2026-11-18 11:01:52 -05:00
Dylan M. Taylor c9c4eb94e8 Keep the DER tag import where the test oracles use it 2026-11-18 10:43:09 -05:00
FredApps 6d95958ccc Use merged XFA namespace and BOM safety fixes 2026-11-18 16:08:32 +01:00
Dylan M. Taylor 34d6706088 Pin shared PKCS7 adapters to merged parts API 2026-11-18 09:58:51 -05:00
Dylan M. Taylor d79a0fdc3d Merge main into shared OCSP adapter, retaining CRL parity coverage 2026-11-18 09:58:06 -05:00
Dylan M. Taylor 70c7cebde8 Merge remote-tracking branch 'base-src/main' into pr-7646
# Conflicts:
#	Cargo.lock
2026-11-18 09:50:17 -05:00
Dylan M. Taylor e835554187 Merge pull request #7655 from storytold/refactor/shared-x509
Sign: parse x509 through shared PKCS7 components
2026-11-18 09:47:14 -05:00
Dylan M. Taylor 78706fe8c0 Merge pull request #7654 from storytold/refactor/shared-crl
Sign: parse crl through shared PKCS7 components
2026-11-18 09:47:10 -05:00
Dylan M. Taylor 7c15cb5019 Merge pull request #7642 from storytold/refactor/shared-xfa-xml
XFA: use shared namespace-aware XML DOM
2026-11-18 09:47:03 -05:00
Dylan M. Taylor 2801898667 Merge pull request #7637 from storytold/refactor/shared-timestamp-request
Sign: use shared RFC 3161 request reader
2026-11-18 09:46:59 -05:00
Dylan M. Taylor b24a313ff5 Merge remote-tracking branch 'origin/main' into pr-7656 2026-11-18 09:12:07 -05:00
Dylan M. Taylor 4085380014 Merge remote-tracking branch 'origin/main' into pr-7655 2026-11-18 09:12:03 -05:00
Dylan M. Taylor babccf53e7 Merge remote-tracking branch 'origin/main' into pr-7654 2026-11-18 09:11:58 -05:00
Dylan M. Taylor b26c0c529f Merge remote-tracking branch 'origin/main' into pr-7646 2026-11-18 09:11:54 -05:00
Dylan M. Taylor 8d0ed386c0 Merge remote-tracking branch 'origin/main' into pr-7642 2026-11-18 09:11:50 -05:00
Dylan M. Taylor b7887ea0d1 Merge remote-tracking branch 'origin/main' into pr-7637 2026-11-18 09:09:10 -05:00
Dylan M. Taylor add7f7b509 Merge remote-tracking branch 'origin/pr7702-current' into fix/xfa-count-cache-20261117 2026-11-18 08:35:44 -05:00
FredApps 64c10d450c Merge main into onee/fix-annot-tests 2026-11-18 19:51:06 +07:00
FredApps 562c428c6f test(annot): retain current opacity and review-state semantics (#7721)
* test(annot): retain current opacity and review-state semantics

* style: wrap fixture imports at repository width
2026-11-18 19:08:31 +07:00
FredApps e56b03fbae test(annot): assert URL scan work instead of wall-clock speed (#7695) 2026-11-18 17:41:12 +07:00
FredApps f8211b6aaf Merge main into onee/fix-annot-tests 2026-11-18 17:14:34 +07:00
Dylan M. Taylor 30c1e449f3 fix(export): package a repeated picture once in PPTX and bound HTML embedded pictures (#5933)
* fix(export): package repeated PPTX pictures once and bound HTML embedded images

* test: make reused PPTX picture reading order explicit
2026-11-18 05:10:11 -05:00
FredApps ae30592466 Update annotation tests after SaveOptions, Style, LinkAction, and Shape changes
#2523's tests were written against earlier field lists. Later work added
id_entropy, border and opacity style fields, a zoom on page links, and a
line on custom stamps, so cargo xtask ci now fails at clippy on main.

The tests keep the same intent: page links still use Fit Page, the view they
had before they carried a zoom, and the extra style and stamp fields take
their defaults.
2026-11-18 16:55:06 +07:00
Valentin Klein 894904616d Form-data import says when the form refused every value
Importing form data whose only value the form refuses now fails and names the field, instead of reporting success.

Fixes #7409

<details><summary>Details for review</summary>

**Cause:** the issue's analysis is right. `pdfcraft_xfdf::apply_values` records refused fields in `Report::rejected` and the library deliberately returns `Ok(report)`. The engine's `ImportData` handler (`crates/engine/src/edit/run.rs`) only looked at skipped comment appearances and dropped `rejected`, so the edit committed as an ordinary Import step: dirty, an Undo entry, and Redo cleared.

**Fix:**
- If the file gave values for known fields and the form refused all of them (no field and no comment taken), the import returns a new `DataError::Refused` (shown as "the form refused every value in the file, so nothing was imported: "Choice""). Nothing is committed, so Undo, Redo and the dirty state stay as they were, like the existing "nothing matches this document" case. The tools and the UI already show the edit error.
- If some values took and others were refused, the import still applies the valid ones, as the issue allows, and the repair log names the refused fields (first five, then a count).
- `doc_import_data` (CLI/MCP) returns the repair entries that import appended in `import_repairs` (empty when everything was taken), so a caller sees a refused value without calling `doc_info`.
- The library's own behaviour is unchanged.

**Tests** (`crates/engine/src/tests.rs`; and `crates/automation/tests/it/automation.rs`: `form_data_import_response_names_the_fields_the_form_refused`, which checks the response of a full, a mixed and an all-refused import): `form_data_the_form_refuses_is_reported_and_leaves_the_document_alone`. A combo with options A and B, Undo leaves Redo available, then importing `Choice=INVALID` must fail naming "Choice" with Undo/Redo and the value unchanged; a second import with `Choice=INVALID` plus `Notes=hello` applies Notes and names only Choice in the repair log. It fails without the fix (I checked this).

Checked: `cargo test -p pdfcraft-engine -p pdfcraft-xfdf -p pdfcraft-automation`: xfdf 130 pass, engine 779 pass, automation 451 pass. The 7 engine failures and 10 automation failures (OCR models, plus `file_processing_keeps_javascript_off_for_xfa_open_scripts` and `copy_restricted_text_stays_in_the_document`) fail the same way without my change. Clippy `-D warnings --all-targets` is clean for engine and automation; `pdfcraft-xfdf` has one existing `collapsible_match` finding at `xfdf.rs:326` on current upstream/main that I did not touch. rustfmt is clean. I did not run the CLI/MCP end to end.

</details>
2026-11-18 16:39:21 +07:00
Valentin Klein 996d34f432 A hidden layer stays hidden after a full Save As
A layer I hid stays hidden in the open document after a full Save As.

Fixes #7411

<details><summary>Details for review</summary>

**Cause:** the issue's analysis is right. A full save rewrites the file and renumbers its objects, then `mark_saved` refreshes the open document. The refresh looked old layer choices up by the old object number, and the renderer's layer overrides (`config.layers`) still named the old numbers, so the hidden layer came back as shown. An incremental save keeps the numbers, which is why it was unaffected.

**Fix:** `mark_saved` now knows when the saved bytes are a rewrite (it already computed that to reset the script runtime). In that case the refresh carries the visibility over by layer name (the nth layer with a name maps to the nth layer with that name, the writer keeps the `/OCGs` order) and rebuilds the renderer's overrides with the new numbers. Name matching also avoids an old number being reused by a different layer. The undo history survives the save, so undo and redo bring back a graph with the old numbers; when the restored layer numbers differ from the open document's, they use the same carry-over by name. Other refreshes are unchanged.

**Test** (`crates/engine/src/tests.rs`): `a_full_save_as_keeps_the_layer_choices_of_the_open_document` hides one of two layers whose objects get renumbered by the rewrite, saves in full, and checks both the layer list and the rendered pixels. Without the fix it fails with the hidden layer shown again (I checked this). `undo_and_redo_after_a_full_save_as_keep_the_hidden_layer_hidden` hides a layer after an edit, saves in full, then undoes and redoes, checking the layer list and the pixels each time (it fails without the undo/redo carry-over).

Checked: `cargo test -p pdfcraft-engine` (779 unit tests pass in the lib, the other test binaries pass; 7 OCR tests fail here because of the OCR setup on my machine, unrelated to layers), clippy `-D warnings --all-targets`, rustfmt, `xtask layers`. I did not run the native app.

</details>
2026-11-18 16:38:39 +07:00
Valentin Klein 439401188d Double-clicking a one-letter word selects only that word
Double-clicking a one-letter word in the paragraph editor now selects only that word, so typing replaces just it.

Fixes #7413

<details><summary>Details for review</summary>

**Cause:** the paragraph editor uses `egui::TextEdit`, whose double-click selection combines previous-word and next-word navigation around the nearest caret. With the caret at the start of a word (or end of one) the previous-word step skips the space and lands in the neighbouring word, so the left half of `a` in `Take a calm walk.` selected `Take a`. I confirmed the cause in the pinned egui fork (`select_word_at`) and that the issue's analysis matches. The fork is a pinned dependency, so I fixed it in PdfCraft rather than in egui.

**Fix:** after the editor is shown, a double-click is narrowed to the word under the caret: the word that starts at the caret, or the one that ends at it. This reuses egui's own word boundaries (`ccursor_previous_word`/`ccursor_next_word`), so what counts as a word is unchanged. Only a double-click with the pointer over a word glyph is narrowed; one on a space is left to egui (the caret a space hit reduces to ends the word before it). The added-text editor (`content_ui.rs`) gets the same correction. The other multiline boxes (comments, form fields, fill and sign, dialogs) are left as they are: they are short notes and fields, not page text, and most are added with `ui.add`, which returns no galley to test the pointer against. Right-to-left runs are a known limit: there the glyph test finds no glyph and egui's selection is kept. Shift-double-clicks are left to egui too (it extends the selection then). Shift-clicks and Shift-double-clicks that follow a narrowed double-click, in a row and in either direction, keep the word selected until a plain click or new selection: egui's word anchor cannot be set from outside and `set_char_range` clears it, so the click is completed in PdfCraft to give the result egui gives after its own double-click.

**Tests** (`crates/ui-egui/src/tools/edit_text_ui.rs`):
- `a_double_click_at_a_word_edge_means_that_word`
- `double_clicking_a_one_letter_word_selects_only_that_word` (drives a real `TextEdit` with a double-click 20% into the `a`; without the fix it selects `Take a`, I checked this)
- `a_shift_double_click_keeps_the_extended_selection` (with Shift held, the selection egui extends is kept; without the Shift check it is cut to `a`)
- `a_shift_click_after_the_narrowed_double_click_keeps_the_word` (Shift-click and Shift-double-click before, after and inside the narrowed word, compared with egui's own double-click of `calm`; without the completion a Shift-click before `a` selects `ke ` and drops it)
- `shift_clicks_in_a_row_keep_extending_from_the_narrowed_word` and `shift_double_clicks_in_a_row_extend_by_words_from_the_narrowed_word` (before, after, before again in one box, compared with egui's own double-click of `calm`; with the anchor dropped after the first extension the later clicks lose `a`)
- `a_one_letter_word_that_starts_a_wrapped_row_is_narrowed` (a narrow box where `a` starts the second row; at a soft wrap the end of a row and the start of the next share an index)
- `a_key_that_moves_the_selection_ends_the_word_anchor` (double-click `a`, Shift+Right, then Shift-click before: extends from the selection's own start as egui does)
- `a_double_click_on_a_space_is_left_to_egui` (four points across the space after `Take`: the selection equals egui's own; without the glyph check the left half selects `Take`)

Checked: `cargo test -p pdfcraft-ui-egui` (1021 unit tests pass, plus the integration tests), clippy `-D warnings --all-targets`, rustfmt, `xtask layers`, `xtask assets`. Ten integration tests (`ocr::*`, `comments::the_selection_bar_stays_inside_the_pages_area`, `editing::a_custom_property_whose_name_the_tools_refuse_is_listed_and_left_alone`) fail the same way on current upstream/main without my change. I did not run the native app by hand.

</details>
2026-11-18 16:37:57 +07:00
chamber074 79b76e609b fix(forms): draw field text the field font cannot hold from the bundled face instead of ?
Fixes #3913 (also reported as #6822, closed as its duplicate).

## What was wrong

The field value was never lost: `/V` is stored losslessly as UTF-16BE, and PdfCraft sets `/NeedAppearances`, which is why other viewers show the Greek correctly. The `?` is only in the appearance PdfCraft draws itself: when the field's `/DR` font can't encode the text, `field_appearance_fit` falls back to Helvetica/WinAnsi, and every character outside WinAnsi is drawn as `?` (and reported through the "This field's font can't draw…" notice).

## The fix

At that fallback decision, characters that neither the field's font nor Helvetica holds but the bundled Inter face does (Latin, Greek, Cyrillic) are now drawn as Type 3 glyphs built from Inter — the same mechanism Thai text already uses in field appearances. Characters no available face holds (e.g. CJK in a Helvetica field) are still drawn as `?` and reported, exactly as before. Text the field's font holds is byte-for-byte unchanged, and no font resource is added in that case.

## Behaviour change to be aware of

Date names in Russian, Czech, Greek, etc. in Helvetica fields (#5303) are now drawn in the date language rather than falling back to English — the "a font that holds them keeps them" rule applied to the bundled face. Japanese still falls back to English. Push-button captions are unchanged (still `?`); same mechanism, possible follow-up.

## Tests

- New forms test `greek_a_field_font_cannot_hold_is_drawn_from_the_bundled_face`: Greek, mixed Latin+Greek (multiline), and exact-WinAnsi strings in a `/Helv` field; asserts the `/V` bytes, no `?` in the appearance, a `PCLa` Type 3 font with ToUnicode, and no undrawn report; a CJK character is still reported. It fails on unmodified code and passes with this change.
- New fonts unit test for splitting a line between the standard font and Inter.
- Updated the engine signature test and the #5303 `form_date_language` tests where they pinned the old `?` behaviour.

Verified locally: `cargo test` for fonts, forms, edit and engine — 1,813 passed, 0 failed; `cargo fmt --check` clean; clippy clean on the touched crates.

*Disclosure: this change was drafted with AI assistance (Claude) under my direction; the diff was reviewed and the verification above was run before opening this PR.*
2026-11-18 16:37:14 +07:00
Michael Higgins febd6dc2b6 fix(sign): an unlisted body or an entry that leads nowhere is no permitted change (#6754)
## What this changes

Fixes #6754.

A revision appended after signing could change what a signed page shows while `classify_changes` reported only permitted changes. The update carried a new body for the page's content stream that no cross-reference section lists, plus an entry, named from the trailer, that points at no object. cos kept reading the signed content object (its entry had not changed), and read the new number as null, which `classify` drops. The renderer instead rebuilds its object index from the file's `N G obj` headers when an entry leads to no object (`vendor/hayro-syntax/src/xref.rs`, `repair` / `fallback_xref_map_inner`), and there the last header for a number wins, so the page drew the unlisted body.

`crates/sign/src/pdf/changes.rs` now refuses both halves, each on its own:

- **An entry that does not locate its own object.** Every object whose place changed since signing must have an entry that `xref_entry_is_exact` accepts, whatever the object reads as. Before, this was checked only when the content equalled the signed object's. Reported as `other changes`.
- **A body the reader does not read.** `unlisted_bodies` scans the bytes after the signed revision for `N G obj` headers. For each number and generation, the last header there must be where the current entry for that number points. Otherwise the renderer's rebuilt index may draw it. Reported as `page content` when the number had a signed page role, else `other changes`. This holds whatever triggers the rebuild, including a damaged entry the signed file already had. The scan is linear and bounded: past 2^20 distinct headers the appended bytes are not judged and the change is refused.

The scan finds more headers than the renderer's (it does not skip dictionaries or check that an object follows), so it errs towards refusing. A writer that lists what it writes is unaffected.

## How you verified it

- `cargo fmt --check -p pdfcraft-sign`
- `cargo clippy -p pdfcraft-sign --all-targets -- -D warnings`
- `cargo test -p pdfcraft-sign --test it`: 144 passed, 2 ignored.
- `cargo test -p pdfcraft-sign --lib`: 116 passed, 1 ignored. `shared_annotation_arrays_are_judged_in_bounded_time` (30,000 rewritten pages, 20 s budget) took 11.6 s and 14.4 s with the fix and 13.2 s with `changes.rs` at `main`, on the same machine under similar load: the scan and the extra entry check cost nothing measurable there.

New test `an_unlisted_object_body_or_an_entry_that_points_at_no_object_is_not_permitted` in `crates/sign/tests/it/pdf.rs`, for a P=1 certification and an approval signature:

- the issue's shape (unlisted content body, plus an entry for `/Info 60 0 R` that points at the section's own `xref` keyword) is Invalid, `page content`;
- the entry alone is Invalid, `other changes`;
- the unlisted body beside an honestly listed object is Invalid, `page content`;
- an honest revision that lists what it adds stays Valid.

**Seen failing before the fix:** with `changes.rs` at `main`, the test fails on its first case with `Allowed([])` and status Valid.

## Never-crash

- [x] No new `unwrap`/`expect`/`panic!`/`unreachable!`/`todo!` outside tests
- [x] No indexing or slicing with input-derived positions (`get` throughout); offsets use checked or saturating arithmetic; the header map is capped
- [x] No `unsafe`
- [x] Not a crash fix

## Provenance

- [x] No assets, fonts or copied code
- [x] Behaviour from ISO 32000-2 §7.5 and §12.8.2.2, and from observing the vendored renderer's repair path

## Anything a reviewer should look at first

- **What is still not modelled.** The renderer's repair scan also files the members of any `/Type /ObjStm` stream it meets (last one wins, unless a plain header exists for the number), attributes a headerless object-stream dictionary to the last header it saw, and keeps the last trailer-like dictionary whose `/Root` has `/Pages`. An appended object stream holding a forged member for an object the signed file kept only in an object stream, or a trailing `<< /Root … >>`, could still diverge once something else makes the renderer rebuild. This PR closes the issue's trigger (an entry that leads nowhere) and the unlisted plain body. The general fix, as the issue says, is to judge changes with the renderer's own object resolution. I have not covered those here, to keep this to the issue; they need their own issue.
- **Kind for a misplaced entry.** It stays `other changes`, as the existing `a_cross_reference_entry_that_misses_its_object_is_not_an_unchanged_object` expects, even for a signed page's content object: what the renderer draws there is unknown, not known to be new content.
2026-11-18 16:36:32 +07:00
Michael Higgins 6da8fa27ed fix(redact): redact an XObject or font whose /Subtype is a reference (#6750)
## What this changes

Fixes #6750 (audit F-9).

Redaction kept an image under a mark when the image's `/Subtype` was an indirect reference (`/Subtype 8 0 R`, object 8 being `/Image`). `xobject()` in `crates/redact/src/interp.rs` matched on `s.dict.name(b"Subtype")`, and `Dict::name` does not follow references. The image fell through to `_ => None`, so the `Do`, the resource entry and the samples stayed in the saved file under the black box. The renderer still draws such an image.

- `xobject()` resolves `/Subtype` before matching, so an image or form named by reference is redacted like a direct one.
- `is_vertical()` does the same for a Type0 font, so vertical text in a font with a referenced `/Subtype` still makes Apply refuse rather than pass.
- The `_` arm now fails closed. An XObject with no `/Subtype`, or one the redactor doesn't read, is removed in Apply when its placement hits a mark. Verify counts it as residue there. Its placement is the unit square an image fills, or the `/BBox` under its `/Matrix` when it has one. Apply counts it in `forms_removed` and sets `removed_cut`, as it does for a form it cannot read. A placement outside every mark is left alone.

Related open PRs, checked for overlap: #5849 resolves `/Subtype` on annotations in `lib.rs`, and #5662 resolves an indirect `/Subtype /Form` in `prune.rs`. Neither touches `xobject()` or `is_vertical()`.

## How you verified it

- [x] `cargo fmt --check` (clean)
- [ ] clippy with `-D warnings` on `pdfcraft-redact`: **not run locally**
- [ ] tests pass on `pdfcraft-redact`: **not run locally with the fix**, see below

**What ran.** With the three new or extended tests in place and `interp.rs` reverted to `main`, I ran `cargo test -p pdfcraft-redact --lib -- an_image_whose_subtype an_xobject_of_unknown vertical_writing_text`. All three failed on the expected assertions:
- `an_image_whose_subtype_is_a_reference_is_redacted`: the direct `/Subtype /Image` control passed, then the `8 0 R` case failed with `images_removed: 0`.
- `an_xobject_of_unknown_subtype_under_a_mark_goes`: the verifier counted 0, expected 1.
- `vertical_writing_text_under_a_mark_fails_closed`: the referenced `/Subtype /Type0` case did not refuse.

**What did not run.** Local builds were stopped for this change before the run with the fix completed. I have **not** seen these tests pass with the fix, nor run the rest of the crate's tests or clippy. I'm relying on CI for those. This PR is a draft until CI passes.

## Never-crash

- [x] No new `unwrap`/`expect`/`panic!`/`unreachable!`/`todo!` outside tests
- [x] No indexing with input-derived positions (the `/BBox` is read with a slice pattern)
- [x] No `unsafe`

## Parity and reach

No parity change: this hardens the existing Apply Redactions behaviour.

## Anything a reviewer should look at first

The fail-closed `_` arm. It removes an unclassifiable XObject only where a placement hits a mark, never elsewhere. Verify counts it as residue, so the post-apply check would refuse if Apply ever left one.
2026-11-18 16:35:49 +07:00
Michael Higgins d5bcb41099 fix(sign): a change to a field a signature locks invalidates it (#6757)
## What this changes

Fixes #6757.

Validation read only DocMDP references. A signature field's `/Lock` (ISO 32000-2 §12.7.5.5) and the FieldMDP references in its value (§12.8.2.4) were ignored. So changing a locked field after an approval signature read as a permitted form fill, and the signature stayed **Valid**.

After this change:
- `crates/sign/src/pdf/locks.rs` (new) reads both from the **signed revision**: `All`, `Include` and `Exclude`. A listed name also covers the fields below it, so `address` covers `address.city` but not `addressee`. Both sources count, because signers write one or the other or both.
- The locked fields are compared between the signed revision and the document as it is now. That covers each field's dictionary and every dictionary above it (an inherited `/V` is its value too), plus its widgets. Tree links (`/Kids`, `/Parent`, `/P`) are left out of the comparison, and a page is compared by reference only, because adding an annotation rewrites it.
- A locked field that changed, disappeared, or gained a second field under its name adds the new change kind `kind::LOCKED_FIELD` ("locked field") to a **Disallowed** modification. The signature is then Invalid, whatever `classify_changes` called the change.
- A lock that is present but can't be read (an unknown `/Action`, a FieldMDP reference with no parameters, a non-dictionary `/Lock`), or a form too large to compare within the listing's caps, leaves the signature **Unknown**, never Valid. The detail is the existing "The signature could not be checked ({})." wording.
- New fields added under a locked field, and the form's `/NeedAppearances` (plus `/DA`, `/DR` and `/Q` when a locked field has no appearance of its own), count as changes to it. The signature's own field is compared when its lock covers it.
- `classify_changes` and `changes.rs` are unchanged. The check is wired in `finish_validation` (`validate.rs`).
- `parity`: `sign.field-mdp` moves from `planned` to `partial`, with what's still missing.

Related: #4809 makes *filling* refuse locked fields in PdfCraft's own form UI. The `sign` crate can't depend on `forms`, so this PR doesn't share its `signature_locks`. The lock reading follows the same rules (action, prefix matching, both sources) independently, and the two can be merged into one reader later. The two PRs touch different files.

## How you verified it

Run locally (Windows), scoped to `pdfcraft-sign`:

- [x] `cargo fmt --check -p pdfcraft-sign`
- [x] `cargo clippy -p pdfcraft-sign --all-targets -- -D warnings`: clean
- [x] `cargo test -p pdfcraft-sign --no-fail-fast`: integration 154 passed. Lib 120 passed, 1 failed: `shared_annotation_arrays_are_judged_in_bounded_time` (20 s limit) took 25 to 34 s. That test calls `classify_changes` directly, which this PR doesn't touch, and it fails the same way on unmodified `origin/main` on this machine (42 s), which was heavily loaded. CI should settle it.
- [x] `cargo xtask parity`: ok
- [x] Rerun on 78a860fda (head, includes a38542ab1 and the catalog fix from review): `cargo fmt --check -p pdfcraft-sign`, `cargo clippy -p pdfcraft-sign --all-targets -- -D warnings` (clean), `cargo test -p pdfcraft-sign` (lib 122 passed, including the timing test this time; integration 154 passed).
- [ ] `cargo xtask layers` / `assets`: not run (no crate boundary or asset touched)

**Tests.** `crates/sign/tests/it/field_locks.rs` signs a form with an approval signature whose field carries a `/Lock`, then appends an update:
- `changing_a_field_the_signature_locks_invalidates_it`: `Include [amount]`. Changing `amount`'s `/V`, its `/V` and `/AP`, or only its appearance stream makes the signature Invalid with `locked field`. Changing the unlocked `note` stays Valid (form fill).
- `exclude_locks_every_field_it_does_not_name`, `all_locks_every_field`, `a_locked_parent_locks_its_kids`, `removing_or_shadowing_a_locked_field_changes_it`.
- From review (fd11fcb6c), each seen failing on the first commit: `a_reference_cycle_in_a_locked_field_ends` (overflowed the stack), `an_all_lock_covers_the_signatures_own_widget`, `a_new_field_below_a_locked_one_changes_it`, `the_form_defaults_a_locked_field_is_drawn_with_are_locked_too` and `an_unreadable_lock_leaves_a_later_fill_unknown`.
- Control: `without_a_lock_the_same_change_is_a_form_fill`.
- Unit tests in `locks.rs`: a FieldMDP reference in the signature value locks fields, names cover kids only and match exactly as written, an unreadable lock (bad `/Fields` or `/Reference`, too many locks) is "unchecked" rather than "no lock".

I watched them fail: before the fix, 5 of the 6 integration tests failed (all reported Valid, as the issue describes) and the control passed. With the `locked_fields` call reverted once, the same 5 went red again.

## Never-crash

- [x] No new `unwrap`/`expect`/`panic!`/`unreachable!`/`todo!` outside tests
- [x] No input-derived indexing. The field walk keeps a seen-set and uses the listing's caps (`MAX_FIELDS`, `MAX_ENTRIES`, `MAX_NAME_BYTES`, `MAX_FIELD_NAME_BYTES`) plus a depth limit of 64. The comparison is bounded to 2^18 visited objects, every reference followed counts toward the depth limit, and reference pairs are memoised, so cycles end. Lock matching is one set lookup per node per lock, with at most 16 locks. Hitting any cap gives Unknown, not Valid.
- [x] No `unsafe`

## Provenance

- [x] No assets
- [x] Behaviour from ISO 32000-2 (§12.7.5.5, §12.8.2.4) and the issue's trace

## Parity and reach

- [x] `sign.field-mdp` → `partial`. Notes say what's missing: writing a lock when signing, refusing to fill a locked field (#4809), and the `/Lock /P` permissions.
- [x] Reachable headlessly: `sign_list` reports the verdict and the modification kinds.

## Anything a reviewer should look at first

- **`All` locks other signature fields too.** Signing a second, still-empty signature field after a signature with `Action /All` counts as a change to a locked field, so the first signature becomes Invalid. That is how I read §12.7.5.5, where the lock names fields and a signature field is one. If you'd rather exempt signing an empty signature field, it's a one-line filter in `locked_fields`.
- **The comparison is strict.** Any change to a locked field's dictionaries or widgets counts, including a re-encoded but identical appearance stream. I chose to err toward Invalid on these.
- **New change kind.** `kind::LOCKED_FIELD` is in `kind::ALL`, so interfaces will look up a new word ("locked field"). It shows in English until craft-i18n translates it.
2026-11-18 16:34:54 +07:00
.CooCoo 0293facd77 Tests: frame budgets scale with a calibration workload on slow machines
## What this changes

UI frame-budget tests scale the 40 ms budget against a fixed workload of 18 million integer updates. Calibration runs before and after each round's frames, each run taking the fastest of three trials, and the faster of the two runs sets that round's budget. A 17 ms reference sets the scale, capped at three times the base budget. Calibration does not call egui or PdfCraft.

Each frame measurement uses the budget calculated for that round. The `PERF` lines include both calibration durations, scale factor, budget, average frame time, and worst frame time. The wheel-input frame test checks against the same calibrated budget.

## How you verified it

- [x] `cargo fmt --check`
- [x] clippy with `-D warnings` on the crates I changed
- [x] tests pass on the crates I changed
- [ ] `cargo xtask layers` and `cargo xtask assets` (if you touched crate boundaries or any asset)

- `cargo fmt --all -- --check`
- `cargo clippy -p pdfcraft-ui-egui --all-targets -- -D warnings`
- `cargo test -p pdfcraft-ui-egui --test perf -- --nocapture --test-threads=1`

On Windows, the four performance tests passed with calibration between 16.33 and 16.57 ms, factor 1.00, and a 40 ms budget. A temporary 45 ms delay in every measured step made the comments test fail in all three rounds, with a best average of 47.81 ms. Scaling calibration and average frame durations by 2.5 passed all four tests with budgets between 96.40 and 98.17 ms. Both temporary changes were removed.

On 17dca72, `cargo test -p pdfcraft-ui-egui --test perf -- --nocapture --test-threads=1` passed 5 tests on Windows with calibration between 17.34 and 17.60 ms and budgets between 40.80 and 41.17 ms. `contention_during_one_calibration_does_not_raise_the_budget` fails when only the calibration before the frames sets the budget.

On 0baf089 (`main` at 5aaa818 merged in), the same command passed 7 tests on Windows with calibration between 16.86 and 17.33 ms and budgets between 40 and 40.47 ms, and `cargo check --workspace --tests` passed. `the_returned_budget_is_the_selected_rounds_faster_calibration` drives the rounds with fixed calibrations and averages and fails when only the calibration before the frames sets the budget.
2026-11-18 16:34:15 +07:00
huppiflupp bff4be14c3 M10: Recognize text finds small print on large pages (tiled detection)
## What this changes

Recognize text now finds small print on large, dense pages (newspapers, small print, blurred photos).

The ocrs detection model reads a fixed 600 × 800 pixel input, so ocrs shrinks every page to that size before detecting words. A full page at 300 dpi (2480 × 3508) is shrunk about four times, and small letters disappear. With this change:

- **When (size):** an axis is cut in two when the page is at least twice the detector's input along it (width ≥ 1200 px, height ≥ 1600 px for the ocrs models). Any full page at 300 dpi becomes 2 × 2 tiles; a landscape page may become 2 × 1. The input size is read from the detection model when it loads. Pages below that size (72 to 150 dpi renders, screenshots) are read exactly as before and cost nothing extra.
- **When (text size):** a page that passes the size rule is tiled only if its text is small once the page is shrunk to the detector's input, decided by a cheap pixel signal, the **line pitch** (`crates/ocr/src/pitch.rs`). The page is box-averaged to a grey copy of at most 1600 px a side and cut into a 6 × 6 grid of blocks. In each block, the ink is summed per pixel row, the slow trend (shading, pictures) is removed with a moving average, and the autocorrelation is taken. The block autocorrelations are averaged, and the first strong peak is the pitch. Lines in columns that don't line up still agree on the period, and blank blocks are skipped. The same runs on pixel columns for sideways pages, and the axis with the stronger peak wins. The pitch is converted to detector pixels (pitch × 800 / page height). The rule:
  - pitch **under 9 detector pixels**: tile;
  - ink but **no clear line spacing** (no autocorrelation peak above 0.05): tile, because the measurement showed these pages (blurred, creased, oblique or moiré photos) gain on average;
  - large print, and blank pages: detect whole, as before.
  It costs 6.6 ms per page on average (median 5.1 ms, max 45 ms) and reads every pixel once.
- **How:** tiles overlap by 4 % of the page on each side of a cut. Words are **detected** tile by tile. A word is kept only by the tile whose core cell (its share of the page without the overlap) holds its centre, so a word in an overlap counts once. The words are moved back to page pixels, and then lines are formed and **recognised on the whole page** as before. Lines that cross a cut stay single lines, and recognition reads the same pixels it read before.
- The edge cells reach to infinity, so every finite word centre belongs to exactly one tile, including boxes that stick out past the page.

The change is small and lives in `crates/ocr/src/tiles.rs` plus a `detect_words` step in `Ocr::recognize`. While I was there I also made the existing RGBA length check use checked arithmetic (`width * height * 4` was a `u32` product).

### Measured

MDPBench de/es/fr (480 pages), official evaluation with CDM off, `en` recogniser. I ran the same harness build with and without the change (the baseline reproduces the earlier one exactly):

| | Digital | Photo | All | Time per page |
|---|---|---|---|---|
| before | 78.9 | 41.5 | 50.8 | 0.39 s (190 s total) |
| tiling every large page (this PR's first commit) | 80.4 | 42.8 | 52.2 | 0.58 s (281 s total) |
| **tiling only small or unclear print (this PR)** | **81.2** | **42.9** | **52.5** | 0.54 s (259 s total) |
| earlier prototype (full OCR per tile, outside the app) | 81.4 | 42.4 | 52.1 | n/a |

The three rows of this PR come from one harness binary with the rule switched by an environment variable. Each was timed twice (190/191, 281/281, 259/259 s). Per language, the line-pitch rule against tiling every large page: DE 62.9 vs 62.7, ES 47.9 vs 47.8, FR 46.8 vs 46.1. It tiles **214 of the 457** pages that pass the size rule.

**How the rule was chosen.** I measured first, in Python on the per-page scores of the official evaluation (`overall` per page, base vs. tiled). Per-page score gain from tiling, by measured pitch:

| pitch (detector px) | pages | mean gain | pages gaining / losing > 0.02 |
|---|---|---|---|
| < 4 | 40 | +0.018 | 10 / 4 |
| 4–6 | 40 | **+0.114** | 24 / 2 |
| 6–10 | 82 | +0.004 | 10 / 6 |
| 10–14 | 80 | **−0.013** | 5 / 26 |
| 14–35 | 144 | −0.003 | 22 / 25 |
| no clear line spacing | 82 | +0.029 | – |

The gain sits at small pitch, and pitches of 10–14 detector pixels (ordinary body text on a full page) **lose** a little when tiled. Picking tiled or base per page by this rule, and running the official evaluation on that mix, predicted exactly what the Rust build then scored (52.5 / 81.2 / 42.9). Thresholds between 8 and 10 give 52.4–52.5. Treating "no clear spacing" as "don't tile" instead gives 52.0 with only 132 pages tiled. The choice is tuned on these 480 pages, so take the last few tenths with that in mind.

**Time.** The saving is smaller than the page count suggests. The pages that stay tiled are the dense ones, where tiling finds many more words, and recognising those words costs more than the three extra detector runs. Tiling every large page cost +91 s. The pitch rule costs +69 s, so it removes about a quarter of the overhead and still scores higher.

Word recall in the benchmark's own per-kind table, before → after: de digital 61.9 → 78.5 %, fr digital 17.8 → 24.5 %, de/es/fr photos 38.1/37.7/10.1 → 42.1/43.2/12.6 %. Sideways photos are unchanged; those need rotation, which is a separate PR.

Detection runs four times instead of once on a tiled page (machine: Ryzen AI Max+ 395, CPU).

### How it composes with the open OCR PRs

- #5157 (reading order) ends `recognize` in `layout::reading_order`. This PR changes only the detection step before `find_text_lines`, so tiles are merged before lines are formed and before reading order runs, which is the order we want. I measured both together: the numbers above come from a harness tree that has #5157's reading order applied. The two diffs touch neighbouring lines in `recognize`, so whichever merges second needs a trivial rebase.
- #5171 (layout regions) and #5058 (line padding) work on lines and regions after detection, so they compose the same way.

## How you verified it

- [x] `cargo fmt --check`
- [x] `cargo clippy -p pdfcraft-ocr --all-targets -- -D warnings`
- [x] `cargo test -p pdfcraft-ocr`: 26 passed, **with the OCR models installed** (CI has none, so CI skips the model-backed tests). With the models, I also ran the OCR tests of `pdfcraft-engine` (`ocr`, `recogni` filters) and `pdfcraft-automation` (`ocr`, `scan`) locally, and all pass.
- [x] `cargo xtask layers`, `cargo xtask assets`, `cargo xtask parity`

**Tests.**
- Unit tests, no models (`crates/ocr/src/tiles.rs`): the tile geometry for small pages and for A4 at 300 dpi; every word centre, on cuts, edges and outside the page, belongs to exactly one tile, and NaN or infinity belongs to none; cropping, including out-of-range and overflowing crops, returns `None` without panicking.
- Unit tests, no models (`crates/ocr/src/pitch.rs`), on synthetic A4 pages at 300 dpi: a blank page is not tiled; large print (lines every 100 px, 22.8 detector px) is not; small print (every 30 px, 6.8 detector px) is, in grey, RGB and RGBA alike; sideways small print (lines running down the page) is; noise (ink without lines) is; the first strong autocorrelation peak is the pitch, not its multiple; empty, 1-pixel, short or long buffers, 0 or 5 channels, overflowing sizes, a zero-sized detector and slivers give an answer without panicking.
- Model-backed test `finds_small_print_on_a_large_page`: an A4 page at 300 dpi with four lines of small print. One sits inside a tile, one crosses the vertical cut, one is half in the overlap, and one crosses the horizontal cut. Each line must come back as exactly two words at the right place in page pixels.
- **Seen failing by reverting the fix:**
  - Detection on the whole page instead of tiles: 5 words instead of 8, unreadable ("FIOWOR", "In3").
  - Keeping every tile's words without the centre-in-core rule: 14 instead of 8, because the lines in the overlaps doubled.
  - Finite edge cells: `every_word_centre_belongs_to_exactly_one_tile` fails.
  - Never cutting: the geometry tests fail.
  - Line-pitch rule, each mutation reverted afterwards: tiling every page (the first commit's behaviour) fails `a_blank_page_is_not_tiled` and `large_print_is_not_tiled`. Never tiling on a measured pitch fails `small_print_is_tiled` and `sideways_small_print_is_tiled`. Rows only, without the column profile, fails `sideways_small_print_is_tiled`. Taking the strongest peak instead of the first strong one fails `the_first_strong_peak_is_the_pitch`. Not tiling unclear pages fails `ink_without_lines_is_tiled`. No detrending fails four tests. With the threshold lowered to 5 detector pixels, the model-backed `finds_small_print_on_a_large_page` finds 5 words instead of 8, so it exercises the rule too (its page measures 5.8).

## Never-crash

- [x] No new `unwrap`/`expect`/`panic!`/`unreachable!`/`todo!` outside tests
- [x] No indexing or slicing with input-derived positions: crops use checked arithmetic and `get`; tile bounds are clamped to the page; float-to-int casts are of values clamped to `0..=len`. The pitch measure checks that the buffer matches width × height × channels with checked arithmetic, reads pixels through iterators and `get`, and works on at most 1600 × 1600 values whatever the page size. It divides only by non-zero counts, so it returns an answer for any input.
- [x] No `unsafe`
- [x] n/a, this fixes no crash

## Provenance

- [x] No asset from an Adobe product
- [x] No font files
- [x] No GPL/AGPL code
- [x] Behaviour comes from our own measurements on MDPBench. The approach (overlapping tiles, keep by centre; line pitch from the autocorrelation of a projection profile) is a generic technique, not read from another implementation.
- [x] No new assets. One new dependency edge, `rten-imageproc` 0.26 (MIT/Apache-2.0), which was already in the tree through `ocrs`.

## Security

- [x] No path handling changed
- [x] No MCP or control channel changes
- [x] No network access

## Parity and reach

- [x] `ocr.recognize-text` notes say when pages are tiled (size and line pitch), and that the model-backed test runs only where the models are installed. The tiling and pitch unit tests are evidence.
- [x] Reachable headlessly: this is inside `Ocr::recognize`, so `ocr_recognize` and `ocr_recognize_files` get it unchanged.
- [x] No documented behaviour changed

## Anything a reviewer should look at first

- **The tiling rule:** an axis is cut only if each half still fills the detector's input, so a tile is never padded. A lower threshold would also tile mid-size pages. I kept it conservative so that small pages cost nothing. The prototype tiled every page; under this rule, 468 of the 481 benchmark images are cut along at least one axis and 337 along both.
- **The line-pitch rule (`pitch.rs`).** Its constants (1600 px working size, 6 × 6 blocks, peak floor 0.05, first peak ≥ 60 % of the strongest, 9 detector px) were chosen on MDPBench as described above. "No clear line spacing → tile" is deliberate. My first idea was the opposite, but the measurement favoured tiling.
- **Detect per tile, recognise on the whole page**, rather than full OCR per tile like the prototype. This is simpler: there are no lines to stitch back together and no rows to re-sort. It scores about the same as the prototype (all 52.2 vs 52.1, photo 42.8 vs 42.4, digital 80.4 vs 81.4).
2026-11-18 16:33:38 +07:00