Commit Graph
2115 Commits
Author SHA1 Message Date
FredApps f53cab766c Merge main into #4538 2026-11-26 20:27:19 +01:00
FredApps c7020ab493 Merge main into #4369
# Conflicts:
#	parity/acrobat-features.toml
2026-11-26 19:06:19 +01:00
FredApps 448cd37405 Merge main into #4538
# Conflicts:
#	parity/acrobat-features.toml
2026-11-26 19:06:02 +01:00
FredApps 1e05eefeae Merge main into #4369 2026-11-27 00:10:52 +07:00
FredApps e4144bfdde Merge main into #4538 2026-11-27 00:09:02 +07:00
FredApps a462b8c6ad Merge main into #4522 2026-11-27 00:01:37 +07:00
FredApps e334d6d4be Merge pull request #4527 from EricKaden/fix/xfa-ready-events
XFA: ready events run in the other viewer's order, and layout:ready again after a new layout
2026-11-26 17:50:24 +01:00
FredApps 36d9fd7268 Merge pull request #3280 from ahmadmuj/fix/pdfcraft-3221-stm-refusal
Refuse unsafe stream-qualified tag mutations
2026-11-26 17:48:11 +01:00
FredApps d3428827db Merge pull request #2763 from kavishkashehan726-sudo/claude/serene-hawking-sk6w13
fix(engine): validate signed XFA forms as the file was read (#2759)
2026-11-26 17:37:19 +01:00
FredApps 328a1bca2b Merge main into #4538 2026-11-26 17:33:12 +01:00
FredApps 781ab07f8c Merge main into #4369 2026-11-26 23:23:46 +07:00
FredApps cb061454b2 Merge main into #4522 2026-11-26 23:20:14 +07:00
FredApps 0b47a83928 Merge main into #4527 2026-11-26 23:05:58 +07:00
FredApps c7b433206c Merge main into #3280
alt.rs: main now resolves indirect structure kids (#5611), checks the parent and computes the new parent /K before it reads the page, and marks content through decode_page_streams/Marked (damaged streams refuse). This PR's mutation_mcids ownership checks replace main's has_child_structure + mcids in both actions, and its reachable-parent check runs with main's parent checks, before any write. Since main validates the parent first, the missing-/P + missing-content case now refuses with NoParent (test renamed), still without mutation. tools.rs and roadmap keep main's text plus this PR's refusal notes.
2026-11-26 23:00:01 +07:00
FredApps c2bd7c14b7 Merge pull request #4604 from mtlcl410/fix/xfa-script-relayout-full-refresh
M12: an XFA form laid out again by its scripts rebuilds its pages in the view (#4603)
2026-11-26 16:51:38 +01:00
FredApps cd7b5cefd0 Merge main into #2763
main split the engine's lib.rs into modules; the as-opened validation is ported: Editor::as_opened and AsOpened in history.rs, editor_signatures in doc_state.rs (used wherever an editor's signatures are validated), the as-read capture in open.rs, and mark_saved clearing it in session/save.rs. The test also pins the saved status (dynamic Invalid, static Valid).
2026-11-26 22:46:38 +07:00
FredApps 8351a4a991 Merge pull request #7158 from KenM76/feat/print-marks-bleeds
Print: printer's marks and bleed on the printed sheets (doc_print marks)
2026-11-26 16:26:42 +01:00
FredApps 497809244f Merge main into #4522 2026-11-26 22:22:03 +07:00
FredApps 2ebe4e6ac3 Merge main into #4369 2026-11-26 22:14:30 +07:00
FredApps d3850a77b0 Merge pull request #7704 from alehel/codex/fix-watermark-visible-crop
Fix PDF watermark source clipping to visible page bounds
2026-11-26 15:37:24 +01:00
FredApps 8723f5ba4a Merge main into #4604 2026-11-26 21:24:21 +07:00
FredApps 43a96eb390 Merge main into #7158
# Conflicts:
#	crates/automation/src/tools.rs
2026-11-26 21:03:58 +07:00
FredApps e550b6bc45 Merge pull request #7818 from KenM76/feat/suggest-outline
feat(bookmarks): suggest an outline for review (#6020)
2026-11-26 14:23:57 +01:00
FredApps 6f1c601a38 Merge pull request #7810 from KenM76/feat/autotag-pagination
Auto-tag marks running headers, footers and page numbers as pagination artifacts (#7065)
2026-11-26 14:12:01 +01:00
FredApps ada013f042 Merge main into #7704
docs/roadmap.md change-log table: kept this PR's 2026-11-18 row and main's new 2026-10-16 row.
2026-11-26 20:03:47 +07:00
FredApps 257407147d Merge main into #2896
Main split organize/src/import.rs into import/{carry,combine,copy,fields}.rs and already made set_attachments UTF-16-safe and indirect-/Names-safe (this PR's other two hunks), so those take main's version. Ported the PR's core change: insert_file_pages now merges the source's catalog attachments via carry::collect_attachments + attachments::entries (made pub(crate)) + set_attachments. PR's engine regression test file kept as-is; parity evidence/notes merged onto main's entries (it/ paths); ROADMAP/docs entries added to main's text. cargo check -p pdfcraft-organize -p pdfcraft-engine --tests passes locally.
2026-11-26 19:53:56 +07:00
FredApps b5e23f1323 Merge branch 'main' into feat/suggest-outline 2026-11-26 13:23:29 +01:00
FredApps dc3aab8af9 Merge branch 'main' into feat/autotag-pagination 2026-11-26 13:23:18 +01:00
FredApps b0944dce35 Merge branch 'main' into codex/fix-watermark-visible-crop 2026-11-26 13:23:12 +01:00
Dylan M. Taylor f4e722029f parity: point evidence at the craft-port UI tests
The craft framework UI port (#8160) removed or renamed many legacy egui UI
tests, leaving 157 evidence references that no longer resolve. Point 62 of
them at the port's equivalent tests, drop the 95 with no equivalent and say
in each entry's notes which tests are still to replace. Two features lost
their only test and drop from shipped to partial: comment.connector-lines and
misc.ui-screenshots.
2026-11-23 15:47:34 -05:00
KenM76andClaude Opus 5.5 6481545e4a fix(engine): treat a bold word inside one run of prose as emphasis
A producer may draw a sentence as one text run with a gap and paint the
bold word into it. The prose box then spans the word instead of ending
beside it, so the overlap limit rejected it and the word was suggested
as a heading. Prose whose box spans the line on its row now counts as
beside it; the row, size, style and lower-case conditions are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 02:31:07 -05:00
Dylan M. Taylor 333b287a8b Production merge skeleton: upstream/main 9b3e6d6f3 into area/app-1 6cfe35235, conflict markers left in (42 files; 4 modify/delete keep the port's deletion) 2026-11-22 22:39:00 -05:00
KenM76andClaude Opus 5.5 d8e0bc1e90 fix(engine): a bold word set smaller than its sentence is not a heading
The beside test required the same size, so a 9 pt bold keyword in 10 pt
prose (RFC 9110 page 16, reported on #6020) was suggested again. A line
now counts as inside a sentence when the prose beside it is no smaller
than it; a heading set larger than run-in text beside it stays a heading.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 00:49:38 -05:00
KenM76andClaude Opus 5.5 7f153466a3 fix(engine): text beside an italic word still sets the body size
Blocks set inside a sentence were removed before the heading rules ran.
The check is symmetric, so prose beside an italic word was removed too,
and a page of such paragraphs lost its body text: the body size became the
heading's, and the heading was dropped. Inline blocks now stay in the
evidence, counting toward the body style, but marked as having no letters,
which the rules never take as a heading.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 14:43:38 -05:00
KenM76andClaude Opus 5.5 67f6269142 fix(engine): a bold word inside a sentence is not a suggested heading
A bold run inside a paragraph is a text line of its own, so the layout
fallback saw a short bold block where the body is regular and proposed it
as a bookmark. A line now counts as set inside a sentence when prose sits
beside it on the same row: boxes sharing at least half the shorter one's
height, side by side, at most half an em apart, at the same size, in
another style, with a lower-case letter. Such blocks are left out like
captions. The lower-case test keeps a bold title after its section number,
the half-height overlap keeps a heading over tightly set text, and the
half-em gap keeps a heading across a narrow gutter.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 14:08:44 -05:00
FredApps b50a17f717 Merge pull request #7180 from rezaprama/fix/redact-unreadable-annotations
fix(redact): refuse annotations with unreadable bounds
2026-11-20 21:04:09 +07:00
FredApps c05499f707 Merge pull request #2923 from regendorf-ux/pr/tab-rename
Rename the open file from its tab (Rename… and double-click), with names that work on every system (#2102, #2867)
2026-11-20 21:03:47 +07:00
KenM76andClaude Opus 5.5 d148ea61f7 Bound running text by each string's whole run
The extent of a text object now covers each shown string from its origin
to where it advances (widths, Tc, Tw, Tz, TJ) and from its baseline to one
font size above, in any orientation of Tm and cm, so text turned to run out
of a band no longer counts as lying inside it. An object with a glyph whose
width the font does not declare, text with no font, or a non-finite corner
has no extent and is never running text.

Metrics::width_declared tells /Widths, /W, explicit /DW and a named
standard-14 face from /MissingWidth, the implied DW and guessed faces.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 20:24:13 -05:00
KenM76andClaude Opus 5.5 5efa2d51a6 Merge origin/main into feat/autotag-pagination
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 19:27:54 -05:00
KenM76andClaude Opus 5.5 d93cdf718e Merge main into the branch
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 18:01:57 -05:00
KenM76andClaude Opus 5.5 2980cfca6a fix(bookmarks): report every way a suggested outline can miss headings
bookmark_suggest's pages_read counted a page whose text could not be
read (its content past the page decode allowance) as read, and the
layout cap of 10,000 bookmarks dropped headings without setting
truncated. read_lines now counts the pages it read; the suggestion
carries truncated when pages were not read or more headings than the
cap were found, and the tool returns that. Caption leads (Figure, Fig.,
Table, Chart, Exhibit, Plate) now match in any case, so "FIGURE 3:" is
not suggested as a heading.

Tests: captions_match_in_any_case,
more_headings_than_the_cap_are_reported,
a_page_whose_text_cant_be_read_is_not_counted; each fails with its fix
reverted.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 18:01:56 -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
KenM76andClaude Opus 5.5 3a8fbb8c62 feat(bookmarks): suggest an outline for review (#6020)
bookmark_suggest proposes a bookmark tree for the whole document without
changing it: the tagged headings when there are some, or else headings
found from the text's size and weight by Auto-tag's heading rules, with
wrapped headings joined and captions left out. The result is in
bookmark_export's form, so it is reviewed as data and applied with
bookmark_import in one undoable step.

Part of #6020. Adapted from pdfcer (MIT, same author) at ccb49b46.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 16:46:29 -05:00
Dylan M. Taylor fb17d70f76 pdf-shell-w18: net change of 3 commits
- pdf-shell-w18: written by an agent
- pdf-shell-w18: finished by an agent
- pdf-shell-w18: review fixes (review-1)
2026-11-18 16:15:24 -05:00
KenM76andClaude Opus 5.5 1b9fa432f0 feat(a11y): mark running headers and footers as pagination artifacts
Auto-tag Apply finds text that repeats near the top or bottom edge of
most pages before assigning roles: the same text, digits and lone roman
numerals aside, within 4 units of the same height, on at least 40% of
the pages and at least two. It wraps that text in
/Artifact <</Type /Pagination /Subtype /Header|/Footer>> BDC ... EMC
with no MCID instead of tagging it (ISO 32000-2 14.8.2.2). A group of
changing, heading-sized text is left as headings. Running text is left
out of the body style and heading levels, MCIDs number the tagged
objects only, and AutoTagResult counts headers and footers.

a11y::running_text lists the findings without changing the document;
accessibility_autotag_apply returns them as running_text and
running_count, and its note says so.

Adapted from pdfcer (MIT, same author) at ccb49b46, block_layout.rs,
with distinct pages counted instead of objects.

Closes #7065

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 14:59:31 -05:00
KenM76andClaude Opus 5.5 9201dd03b5 Merge main into the branch
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 09:58:40 -05:00
alehel 2af0f4045c M7: clip PDF watermark sources to visible page bounds (#7687) 2026-11-18 13:13:10 +01: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
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
Livio Oswald 55983f1f92 M12: forms show and add pages from page templates (#1429)
## What this changes

Part of #1429. The form in that report keeps pages it shows on demand as **page templates**: the name dictionary's `/Templates` tree names pages kept out of the page tree, and `/Pages` names visible ones (ISO 32000-2 §7.7.4). Until now their fields were listed as unplaced, and the form's JavaScript could not reach them, so buttons that add a page or show a section did nothing.

- **organize**: `templates`, `spawn_template` and `set_template_hidden`.
  - A spawned page is a copy of the template page.
  - With renaming, its fields become fields of their own under `P<page>.<template>.<name>`.
  - Without renaming, its widgets join the template's fields and share their values. A template field that is its own widget is split into field + widget first.
  - Hiding a template takes its page out of the tree, keeps what it inherited (MediaBox, Resources, …) and refuses to hide the last page.
- **js**: `this.templates`, `getTemplate(name)`, `Template.name`, `Template.hidden` (setting it shows or hides the page), `Template.spawn(nPage, bRename, bOverlay)` and `spawnPageFromTemplate`, with positional or named arguments and the documented defaults (0 / true / true). Non-number pages are clamped.
- **engine**: new `Edit::SpawnTemplate` and `Edit::SetTemplateHidden`.
  - Both are checked against the assemble permission and applied in the same undo step as the script's field changes.
  - Only a button's or the console's script may change the pages. A field's own scripts (format, keystroke, validate, calculate) are told so on the console.
  - At most 100 template pages per script run, because each spawn copies the document. A loop that asks for more stops there with one console note.
- **automation**: `page_templates` (read-only), `page_template_spawn` and `page_template_set_hidden`.
- Undo labels translated in all 34 catalogues.

Not in this PR:
- `bOverlay` true (laying a template over an existing page). The script is told so on the console once and nothing changes.
- `createTemplate` / `removeTemplate`.
- An Organize-panel UI for templates.
- `numPages` is not updated inside the running script.
- Mouse Up actions on radio buttons and checkboxes (the other half of #1429) are in the open #2546.

## How you verified it

- [x] `cargo fmt --check`
- [x] clippy with `-D warnings` on the crates I changed (organize, js, engine, automation, ui-egui)
- [x] tests pass on the crates I changed

  | Crate | Result |
  |---|---|
  | organize | 188 passed |
  | js | 97 passed |
  | engine lib | 382 passed |
  | engine it | 21 passed |
  | automation | 45 + 282 passed |
  | ui-egui i18n | 65 passed |

- [x] `cargo xtask layers`, `cargo xtask assets` and `cargo xtask parity`

**Tests.**
- organize has 9 unit tests: listing, renamed and shared spawns, appending past the end, show/hide, the last page and unknown names refused, hostile template trees, repeated unrenamed copies, and inherited attributes kept when hiding.
- js has 5 tests: listing, `spawn` defaults, both argument forms, `hidden` read back, and clamping.
- engine has 5 integration tests: one undo step, renamed and shared spawns surviving save + reopen, overlay noted, field scripts refused, and the 100-page budget.
- automation has 2 tool tests.

Each behaviour was seen failing by reverting it:
- no renaming
- no field sharing
- no MediaBox fallback
- hidden page dropping inherited attributes
- no budget
- field scripts allowed to spawn
- requests not applied
- wrong default flags

Under a loaded machine `tests::xfa_model::a_slow_engine_start_does_not_count_against_the_script` (an existing timing test) failed once and passes on its own. It is not touched here.

## Never-crash

- [x] No new `unwrap`/`expect`/`panic!`/`unreachable!`/`todo!` outside tests, unless it is provably infallible with a comment saying why
- [x] No indexing or slicing with input-derived positions; checked or saturating arithmetic; allocations sized by input are capped; recursion is bounded
  - Name trees are capped at 4096 names.
  - Field walks are capped at 32 levels and 100 000 nodes, with seen-sets.
  - Spawns are capped at 100 per script run.
  - Template names are clipped and charged to the script's output budget.
- [x] No `unsafe`
- [x] Any crash this fixes has a small synthetic regression test (no crash fixed; the hostile-tree test covers cyclic and malformed `/Templates`)

## Provenance

- [x] No asset from an Adobe product, and no Adobe icon recreated, traced or imitated
- [x] No font files committed here
- [x] No GPL/AGPL code copied in
- [x] Behaviour comes from the specification or black-box observation, **not** from reading another implementation's source. The sources are ISO 32000-2 §7.7.4 and §12.7.6 and the public Acrobat JavaScript API reference for `Template`/`spawnPageFromTemplate`.
- [x] Every new asset has an `ATTRIBUTION.toml` entry and `cargo xtask assets` passes (no new assets)

## Security

- [x] `--root` confinement still holds on every path, including ones reached by nested tool dispatch (the new tools take a document id, no paths)
- [x] MCP and the UI control channel stay opt-in, loopback-only and token-authenticated
- [x] No new outbound network access

## Parity and reach

- [x] `parity/acrobat-features.toml` updated: `organize.page-templates` is now `partial`, with notes on what is still missing
- [x] Reachable headlessly through an `automation` tool (`page_templates`, `page_template_spawn`, `page_template_set_hidden`, and `js_run` for scripts)
- [x] Docs updated if this changes a documented behaviour (crate doc comments)

## Anything a reviewer should look at first

- `share_fields_with_originals` in `crates/organize/src/import/fields.rs`: how an unrenamed copy's widgets are reparented onto the template's fields. When a template field is its own widget, it is split into a field with two widget kids.
- The 100-page budget per script run in `crates/engine/src/js.rs`. Each spawn copies the document, so a `for` loop over `spawn` in a hostile form is bounded there.
2026-11-18 16:32:59 +07:00