#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.
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>
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>
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>
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.*
## 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.
## 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.
## 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.
## 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.
## 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).
## 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.
## What this changes
Email redaction no longer drops the part of an address before an apostrophe. The email scanner's `local` closure in `crates/redact/src/patterns.rs` did not accept an apostrophe in the local part. It treated `'` as a boundary and started the match after it, so for `o'brien@example.com` only `brien@example.com` matched. Search and Redact share that span, so the leading `o'` stayed visible.
The local part may now contain an apostrophe, but a match cannot start on one. `o'brien@example.com` and `'john'@example.com` are now matched as `o'brien@example.com` and `john'@example.com`. A quote around an address (`'john@example.com'`) stays outside the match.
No linked issue. Found while testing `crates/redact/src/patterns.rs:216` (email, `local` closure).
## How you verified it
- [ ] `cargo fmt --check`
- [ ] 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)
- Regression test `patterns::tests::email_local_part_may_contain_an_apostrophe` covers all three cases. It fails on `main` without the fix and passes with it (`cargo test -p pdfcraft-redact email_local_part_may_contain_an_apostrophe`).
- `cargo xtask ci` passes.
## Never-crash
- [ ] No new `unwrap`/`expect`/`panic!`/`unreachable!`/`todo!` outside tests, unless it is provably infallible with a comment saying why
- [ ] No indexing or slicing with input-derived positions (`get`, and strings only at char boundaries); checked or saturating arithmetic; allocations sized by input are capped; recursion is bounded
- [ ] No `unsafe`
- [ ] Any crash this fixes has a small synthetic regression test
## Provenance
- [ ] No asset from an Adobe product, and no Adobe icon recreated, traced or imitated
- [ ] No font files committed here (they live in [storytold/craft-fonts](https://github.com/storytold/craft-fonts))
- [ ] No GPL/AGPL code copied in (MuPDF, Ghostscript, Poppler, veraPDF and DSS may only be run as external oracle processes)
- [ ] Behaviour comes from the specification or black-box observation, not from reading another implementation's source
- [ ] Every new asset has an `ATTRIBUTION.toml` entry and `cargo xtask assets` passes
## Security
- [ ] `--root` confinement still holds on every path, including ones reached by nested tool dispatch
- [ ] MCP and the UI control channel stay opt-in, loopback-only and token-authenticated
- [ ] No new outbound network access
## Parity and reach
- [ ] `parity/acrobat-features.toml` updated in this PR, with `notes` saying what is still missing
- [ ] Reachable headlessly through an `automation` tool where that applies, so agents can drive it and not just the UI
- [ ] Docs updated if this changes a documented behaviour (`docs/`, crate README)
## Anything a reviewer should look at first
- A quote right before the local part, as in `'john'@example.com`, stays outside the match, so that leading quote stays visible after Redact. Matching it would also pick up the quote around quoted addresses. This is a deliberate restraint.
- The domain scan and the other patterns are unchanged.
🤖 Generated with AI by [ApolloOffice](https://github.com/Silvertree2010/ApolloOffice), see the Co-Authored-By trailers for the models
## What this changes
XFA templates often draw a vertical divider as a `<line>` with `h` but no `w`, and a horizontal one with `w` but no `h`, while still declaring `slope="/"`. A width-less draw was measured as wide as its row and every line was drawn corner to corner along its slope, so these dividers came out as diagonals running across the form to the page edge. DAF Form 988 shows it on all 3 pages: its 66 vertical separators are all width-less lines.
- `layout/measure.rs`: a line draw without a width is as wide as its stroke (clamped to 0.1 to 20pt, as it is drawn) plus its margin, capped at the available width, so a separator sits at its own x.
- `layout/draw.rs`: a line without a width is vertical and one without a height is horizontal, whatever its slope says. A line whose box is no wider or no taller than twice its drawn stroke runs along the box's longer side, so a zero-height line is horizontal. Only a box with room for its stroke both ways follows `slope`.
- `tests.rs`: `xfa_line_without_width_is_vertical_and_without_height_is_horizontal` covers six shapes: no width, no height, 1pt high, 1pt wide, a 48x72pt box with a 25pt stroke (drawn 20pt, so it still follows its slope) and 2pt by 0pt. It also pins the width-less line's x.
## How you verified it
- `cargo test -p pdfcraft-xfa`: 314 passed. The new test fails with either half of the fix reverted.
- `cargo test -p pdfcraft-engine xfa`: 86 passed.
- `cargo fmt --all -- --check` and `cargo clippy -p pdfcraft-xfa --all-targets -- -D warnings`: clean.
- DAF Form 988 laid out with `render_into`: 66 diagonal lines on `main`, none with this change (66 vertical, 68 horizontal).
- [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)
## 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 (`get`, and strings only at char boundaries); checked or saturating arithmetic; allocations sized by input are capped; recursion is bounded
- [x] No `unsafe`
- [x] Any crash this fixes has a small synthetic regression test
## Provenance
- [x] No asset from an Adobe product, and no Adobe icon recreated, traced or imitated
- [x] No font files committed here (they live in [storytold/craft-fonts](https://github.com/storytold/craft-fonts))
- [x] No GPL/AGPL code copied in — MuPDF, Ghostscript, Poppler, veraPDF and DSS may only be run as external oracle processes
- [x] Behaviour comes from the specification or black-box observation, **not** from reading another implementation's source
- [x] Every new asset has an `ATTRIBUTION.toml` entry and `cargo xtask assets` passes
## Security
- [x] `--root` confinement still holds on every path, including ones reached by nested tool dispatch
- [x] MCP and the UI control channel stay opt-in, loopback-only and token-authenticated
- [x] No new outbound network access (that decision is the owner's)
## Parity and reach
- [ ] `parity/acrobat-features.toml` updated in this PR, with `notes` saying what is *still* missing — `shipped` means "exists and tested", not "as good as Acrobat"
- [ ] Reachable headlessly through an `automation` tool where that applies (`AGENTS.md` §3), so agents can drive it and not just the UI
- [x] Docs updated if this changes a documented behaviour (`docs/`, crate README)
## Anything a reviewer should look at first
The thin-box rule in `draw_draw`: it compares the box with twice the drawn (clamped) stroke and picks the longer side, so hairline borders never come out diagonal and a degenerate box never yields a zero-length segment.
**Update on 2026-11-03 (`db57e7de`).** Merged main `ecdd1e65` and preserved both sets of parity evidence. The picker now uses the public `ComboBox::show_ui` response to track the open menu and clear its search when it closes. All 30 print UI tests passed locally on macOS arm64, including the three printer-picker regressions. Formatting and `cargo xtask parity` passed. [CI](https://github.com/storytold/pdfcraft/actions/runs/41673448570) and [SonarCloud](https://github.com/storytold/pdfcraft/actions/runs/41673448592) track this commit.
## What this changes
Fixes#4399.
The printer picker opens a wider, taller menu with a name filter. Long device names wrap, while Search and Save as PDF stay visible as the device list scrolls. Search ignores case, trims surrounding spaces and keeps the current destination until a row is chosen. Reopening clears the filter and brings the selected device into view.
The large-fleet test now checks that the selected row is between Search and Save as PDF after reopening, without manually scrolling at that point. This catches a broken automatic reveal instead of hiding it with a test-side scroll.
## How you verified it
- At `d14aed41`, the [hosted gate](https://github.com/storytold/pdfcraft/actions/runs/40305529036/job/121513571419) passes: 5,194 tests, 21 skipped. All three `printer_picker` tests explicitly pass, including the new reopening visibility assertion. Formatting, strict Clippy, layers, assets, parity and wasm checks pass in that gate.
- CodeRabbit's refreshed documentation check passes at 100%; both remaining test helpers are documented.
- The three original UI regressions failed against the original production module. They cover a 120-device fleet, Unicode/case matching, selection, reopening, no matches, long names and a 1024×768 window. A separate earlier before/after check caught an initially clipped Save as PDF row by physically clicking it.
- Earlier macOS validation inspected headless captures and exercised the real Print dialog through its control channel. Those are earlier-run results, not a new native macOS run on this head.
- The current local Windows Cargo 1.95 run cannot resolve the pinned craft-menu manifest and does not reach the UI tests. Runtime validation of this latest test update is the hosted gate above; no local test pass is claimed.
## Safety, provenance and reach
- [x] No new panicking shortcuts, unsafe code or input-derived indexing.
- [x] No new assets, fonts or dependencies.
- [x] Existing printer discovery, properties and print submission paths are used.
- [x] Automation remains available through `printers`, `printer_options` and `doc_print`; UI controls remain opt-in.
- [x] Printer-selection parity evidence and M10 progress notes are updated.
## Limits of verification
Physical printing was not tested. Keyboard injection into the earlier background native macOS window did not enter text; filter typing and selection were verified through egui_kittest.
AI assistance: implementation, tests and validation used Codex.
## Follow-up after #6806
The main mixed-script font change landed in #6806. This PR covers the remaining case where the source font lacks only a variation selector (U+FE00–U+FE0F). A visible letter now selects the fallback face. The regression compares implicit and explicit fallback in two source fonts, including character spacing, alignment, and save/reopen.
Verified locally on macOS arm64 with the CI-pinned craft-fonts input: `cargo test --locked -p pdfcraft-edit` and `cargo test --locked -p pdfcraft-automation --test it mixed_script` passed, as did formatting, scoped Clippy, the layer and asset checks, and the UI WebAssembly build.
<!-- evening-module-refresh-20261027:start -->
**Latest compatibility update (2026-10-27):** [d10080eb](https://github.com/PerchAnton/pdfcraft/commit/d10080eb060d112d75bbcfd0a74e4e0bab38af61) includes main `1dd2737b` through a normal merge.
Source/fallback helpers follow the extracted text modules. The original per-rewrite advance cache, source spaces and batched missing-glyph fallback are preserved. The cache regressions were run with the pinned optional OFL font input.
Local macOS arm64 / Rust 1.99.1: focused regression tests, formatting, scoped all-target Clippy with `-D warnings`, layering and scoped WebAssembly checks pass. Assets and parity checks also pass. Hosted CI is tracked separately on this head. Temporary build outputs and fixtures are cleaned after validation.
<!-- evening-module-refresh-20261027:end -->
<!-- integration-refresh-20261025:start -->
**Latest integration checks (2026-10-25):** head `54423364bba795cff0b56e7c8f168f355062e3bb` includes main `418ac6a2af49b7ac2fed44ca2cae8d5d1d2cec0d` through a normal merge. On macOS arm64 with Rust 1.99.1, 980 scoped tests pass (0 failed, 5 ignored). Formatting, scoped all-target Clippy with `-D warnings`, layers, assets, parity, and the scoped wasm check pass. Test executables and fixtures were removed after each target. Full-workspace and other-platform checks belong to CI on this head. Six permitted OFL craft-fonts faces at release pin `3d9ab3a1` were SHA-256 verified for the font-dependent regressions.
<!-- integration-refresh-20261025:end -->
## What this changes
Fixes#2750.
Adding `шалом` to an upright, single-style Helvetica paragraph used to redraw the Latin text in the fallback face. Keep source fonts now preserves characters with actual source glyphs and batches only missing glyphs in Type 3 fallback fonts. Unencodable boundary spaces remain real, extractable fallback glyphs; source spaces with glyphs keep their face. Original font dictionaries stay intact.
Mixed-run classification and width measurement share a per-character cache within one paragraph rewrite. It stores both source advances and missing-glyph results for that rewrite's metrics, size and character spacing. Wrapping, alignment, justification and underline measurements reuse these widths; the normalized `Tw = 0` state, scaling and summation order stay consistent with drawing. The cache never survives into another rewrite.
## How you verified it
<!-- pdfcraft-conflict-refresh-20261019:start -->
**Current integration verification (2026-10-19):** main `43550c44` is included through a normal merge, preserving published history. Current head [5ea12797](https://github.com/PerchAnton/pdfcraft/commit/5ea127978fce56e64b93e70e7172cda5a193c41c).
Both roadmaps retain every current-main record and estimate, with only this PR's own status, progress and single milestone-row additions. Automatically merged hunks in the touched modules were reviewed.
**732 scoped tests passed, 0 failed, 4 ignored** (edit, engine and automation). Formatting, strict scoped all-target Clippy, scoped WebAssembly and layers/assets/parity pass; whitespace and both roadmap MD028 scans pass. Checks ran on macOS with Rust 1.95, the existing low-disk profile, two Cargo jobs, locked offline dependencies and command timeouts. Optional fonts use the verified release pin `3d9ab3a1`; no new assets or persistent build settings.
These are the checks of the refreshed branch. Broader/native UI observations below are historical; full-workspace and other operating-system checks belong to current-head hosted CI and are tracked separately.
<!-- pdfcraft-conflict-refresh-20261019:end -->
The deterministic work-budget regression was actually RED before caching: 32 source-character measurements for eight distinct characters. It now passes eight cases across two fonts, short/repeated drafts, narrow/maximum-width frames, justification and underlines. A separate saved-document test checks cache isolation across fonts, sizes, spacing and scale against the saved font metrics, wrapped baselines and underline endpoints. Existing extraction, font preservation, fallback batching and refusal regressions pass.
### Reproducible performance probe
`cargo test -p pdfcraft-edit --lib mixed_script_paragraph_rewrite_timing_probe --profile low-disk --locked --offline -j 2 -- --ignored --nocapture`
macOS arm64, Rust 1.95.0, the same existing optimized development profile and release-pinned craft-fonts `3d9ab3a132ed0eff457e424226a435a901da30d3`. Medians of three full `rewrite_block` calls, excluding fixture open, Cargo and extraction. Input repeats `The quick brown fox шалом ` with centre alignment, underline, `Tc = 1.25` and `Tz = 80`.
| UTF-8 bytes | Frame width (pt) | Before (ms) | Cached (ms) | Speedup |
|---|---|---|---|---|
| 992 | 480 | 3.845 | 0.730 | 5.27x |
| 15872 | 480 | 26.913 | 5.333 | 5.05x |
| 63488 | 480 | 103.914 | 19.830 | 5.24x |
| 15872 | 14400 | 418.305 | 28.449 | 14.7x |
Baseline production code is head `7de05471`. These are synthetic measurements, not release-build or 4 MB draft results. Normal tests enforce a deterministic measurement budget rather than a wall-clock threshold. Greedy wrapping still scans candidates, and final run encoding remains necessary.
## Never-crash, provenance and security
- [x] No new production panic paths, input-derived slicing or unsafe code. UTF-8 encoding uses a fixed four-byte buffer; cache keys are distinct input characters.
- [x] Contributor-original synthetic fixtures only; no Adobe assets, font binaries or copied copyleft implementation.
- [x] Existing atomic refusal, root confinement and opt-in MCP/control behaviour are retained; no new network or permission surface.
## Parity and reach
Existing `text_edit`, `text_edit_layout`, CLI and MCP reach this path. Both roadmaps retain one product note with unchanged estimates; text-editing parity remains partial.
## Anything a reviewer should look at first
This applies to upright single-style paragraphs in Keep source fonts mode. Explicit family/weight changes and turned/RTL/visual-order text retain their selection paths. The separate styled-path one-font-per-character issue (#2592), wider glyph coverage (#2593), unused-resource cleanup (#2487) and a different wrapping algorithm remain outside this PR.