diff --git a/.cargo/config.toml b/.cargo/config.toml
index 5592118f6c..a1caaeaa38 100644
--- a/.cargo/config.toml
+++ b/.cargo/config.toml
@@ -1,2 +1,7 @@
[alias]
xtask = "run -p xtask --"
+
+# WebAssembly SIMD (every current browser has it; there's no runtime detection on wasm). The OCR
+# engine's kernels (rten-simd) and other vectorised code only use it when compiled in.
+[target.wasm32-unknown-unknown]
+rustflags = ["-C", "target-feature=+simd128"]
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 9403a1e044..4b44d79b68 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -19,7 +19,14 @@ concurrency:
cancel-in-progress: false
jobs:
+ # Regenerates contributors/contributors.json for the release commit; every build bundles it.
+ credits:
+ permissions:
+ contents: read
+ pull-requests: read
+ uses: storytold/craft-common-actions/.github/workflows/refresh-contributors.yml@main
release:
+ needs: credits
# Intentionally tracked at @main (not SHA-pinned) so org-wide CI improvements, security fixes, and build optimizations propagate without PR churn across all craftapp repos.
uses: storytold/craft-common-actions/.github/workflows/release.yml@main
with:
@@ -27,6 +34,7 @@ jobs:
app-title: PdfCraft
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
version: ${{ inputs.version }}
+ contributors-artifact: ${{ needs.credits.outputs.artifact-name }}
secrets:
APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }}
APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }}
diff --git a/AGENTS.md b/AGENTS.md
index c228c4185b..066cad3597 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -1,4 +1,4 @@
-
+
## House rules
These apply in every Craft repository. A later rule may be stricter, not weaker. The source is `standards/house-rules-core.md` in `storytold/craft-contrib`. Propose changes there, not in a copy.
@@ -19,7 +19,7 @@ These apply in every Craft repository. A later rule may be stricter, not weaker.
14. **Keep pull requests moving.** Concurrent pull requests are fine; unanswered actionable feedback is not. Respond in 7 days, a reminder at 14, closure eligible at 30, from when an actionable request waits on the author. Suggestions and unconfirmed bot findings do not start the clock. A fix, explanation or agreed plan resets it; unrelated activity does not. Waiting on a reviewer or maintainer pauses it and does not count against the author. A maintainer decides closure; it is never automatic. Reuse search results, do not poll, and stop at a rate limit.
15. **No agent attribution.** A pull request does not say an agent wrote it. A repository rule may not require that.
-
+
## Rust Craft repositories
These apply to native Craft apps and to shared Rust libraries. Select them by repository type. A repository that merely contains some Rust does not take this block. Rules later in a repository's file may be stricter, but not weaker. The source is `standards/house-rules-rust.md` in [storytold/craft-contrib](https://github.com/storytold/craft-contrib).
@@ -40,6 +40,7 @@ Dependencies and assets use SPDX identifiers. An expression is allowed when ever
- `BSD-2-Clause`
- `BSD-3-Clause`
- `Apache-2.0`
+- `Unicode-3.0`
- `OFL-1.1`
- `Ubuntu-font-1.0`
- `Bitstream-Vera`
@@ -83,7 +84,7 @@ An **asset** is any non-code material that the project includes, ships, embeds,
### 1.2 Only open, provable licences
Every asset must be one of:
-- **Open source:** ISC, MIT, BSD-2-Clause, BSD-3-Clause, Apache-2.0, OFL-1.1, Ubuntu-Font-1.0 or Bitstream-Vera.
+- **Open source:** ISC, MIT, BSD-2-Clause, BSD-3-Clause, Apache-2.0, OFL-1.1, Ubuntu-Font-1.0, Bitstream-Vera or Unicode-3.0 (Unicode, Inc. data such as ICU4X's line-breaking dictionaries; already allowed for code in `deny.toml`).
- **Creative Commons:** CC0-1.0, CC-BY-4.0 or CC-BY-SA-4.0.
- **Public domain.**
- **Contributor-original:** created, photographed or generated by a contributor who owns it and licenses it under the project licence (`MIT OR Apache-2.0`).
@@ -173,7 +174,7 @@ PdfCraft opens files from strangers, and people trust it with their work. A malf
- **Layering.** Nothing below L7 depends on egui/winit/eframe/rfd. `cos`, `filters`, `crypt` and `arlington` stay standalone.
- **Page input.** Page modules read `PagePointer` (`crates/ui-egui/src/page_pointer.rs`), never egui's raw pointer state. `page_pointer::tests::page_modules_read_the_pointer_only_through_page_pointer` enforces it.
- **Page cursor.** Page modules claim the cursor for what is under the pointer (`view.cursor.claim`, `crates/ui-egui/src/canvas/page_cursor.rs`) and never set it themselves. `page_pointer::tests::page_modules_claim_the_cursor_and_never_set_it` enforces it.
-- **Page presses.** A page module decides what is under a point in one hit test (`Hit` in `crates/ui-egui/src/canvas/page_router.rs`) and acts on a press only through that router. `page_pointer::tests::page_modules_act_on_a_press_only_through_the_router` enforces it.
+- **Page presses.** A page module decides what is under a point in one hit test (`Hit` in `crates/ui-egui/src/canvas/page_router.rs`) and acts on a press only through that router. Modules never read the router; they are told. `page_pointer::tests::page_modules_act_on_a_press_only_through_the_router` enforces it.
- **Fidelity.** The PDF object graph is the model. Preserve unknown data. Saves are incremental unless a full rewrite is required. Never silently drop or repair data without recording it.
- **Fonts** are the optional build input `CRAFT_FONTS_DIR`. Code using `pdfcraft_fonts::CRAFT_FONTS` must work when it is empty.
- **Quality gates** before every commit: `cargo fmt --check`, clippy with `-D warnings`, the tests, `cargo xtask layers`, `cargo xtask assets`, and the wasm check. New workspace crates include `workspace = true` under `[lints]`. Scope `cargo clippy -p --all-targets -- -D warnings` and `cargo test -p ` to the crates you touched; the workspace sweep is CI's job.
diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md
index 38c28a80ec..cfc16f78f4 100644
--- a/ATTRIBUTION.md
+++ b/ATTRIBUTION.md
@@ -45,7 +45,7 @@ Every asset PdfCraft includes, bundles or uses to build its published material,
| `assets/icons/chevron-up.svg` | Lucide icon "chevron-up" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/chevron-up.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/chevrons-left.svg` | Lucide icon "chevrons-left" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/chevrons-left.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/chevrons-right.svg` | Lucide icon "chevrons-right" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/chevrons-right.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
-| `assets/icons/circle-check.svg` | Lucide icon "circle-check" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/circle-check.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
+| `assets/icons/circle-check.svg` | Lucide icon "circle-check" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/circle-check.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs; drawn as PDF path data by crates/sign/src/status_layers.rs into displayed signature status layers |
| `assets/icons/circle-dashed.svg` | Lucide icon "circle-dashed" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/circle-dashed.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/circle-dot.svg` | Lucide icon "circle-dot" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/circle-dot.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/circle-help.svg` | Lucide icon "circle-help" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/circle-help.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
@@ -174,7 +174,7 @@ Every asset PdfCraft includes, bundles or uses to build its published material,
| `assets/icons/text-select.svg` | Lucide icon "text-select" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/text-select.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/trash-2.svg` | Lucide icon "trash-2" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/trash-2.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/trash.svg` | Lucide icon "trash" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/trash.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
-| `assets/icons/triangle-alert.svg` | Lucide icon "triangle-alert" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/triangle-alert.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
+| `assets/icons/triangle-alert.svg` | Lucide icon "triangle-alert" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/triangle-alert.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs; drawn as PDF path data by crates/sign/src/status_layers.rs into displayed signature status layers |
| `assets/icons/type.svg` | Lucide icon "type" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/type.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/underline.svg` | Lucide icon "underline" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/underline.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/undo-2.svg` | Lucide icon "undo-2" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/undo-2.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
@@ -184,7 +184,7 @@ Every asset PdfCraft includes, bundles or uses to build its published material,
| `assets/icons/x.svg` | Lucide icon "x" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/x.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/zoom-in.svg` | Lucide icon "zoom-in" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/zoom-in.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/zoom-out.svg` | Lucide icon "zoom-out" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/zoom-out.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
-| `assets/fonts/Inter-Regular.ttf` | Inter Regular | The Inter Project Authors (Rasmus Andersson) | OFL-1.1 | https://github.com/rsms/inter | UI font, embedded in the app; demo PDF labels; slanted fallback glyphs in Fill & Sign typed signatures for characters Dancing Script lacks (Cyrillic, Greek), drawn as filled paths |
+| `assets/fonts/Inter-Regular.ttf` | Inter Regular | The Inter Project Authors (Rasmus Andersson) | OFL-1.1 | https://github.com/rsms/inter | UI font, embedded in the app; demo PDF labels; slanted fallback glyphs in Fill & Sign typed signatures for characters Dancing Script lacks (Cyrillic, Greek), drawn as filled paths; embedded into displayed signature status captions beyond WinAnsi by crates/sign/src/status_layers.rs |
| `assets/fonts/Inter-Medium.ttf` | Inter Medium | The Inter Project Authors (Rasmus Andersson) | OFL-1.1 | https://github.com/rsms/inter | UI font, embedded in the app; demo PDF labels |
| `assets/fonts/Inter-SemiBold.ttf` | Inter SemiBold | The Inter Project Authors (Rasmus Andersson) | OFL-1.1 | https://github.com/rsms/inter | UI font, embedded in the app; demo PDF labels |
| `assets/fonts/JetBrainsMono-Regular.ttf` | JetBrains Mono Regular | The JetBrains Mono Project Authors | OFL-1.1 | https://github.com/JetBrains/JetBrainsMono | UI monospace font; demo PDF code |
@@ -249,7 +249,7 @@ Every asset PdfCraft includes, bundles or uses to build its published material,
| `assets/icons/thumbs-up.svg` | Lucide icon "thumbs-up" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/thumbs-up.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/thumbs-down.svg` | Lucide icon "thumbs-down" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/thumbs-down.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/message-square-plus.svg` | Lucide icon "message-square-plus" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/message-square-plus.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
-| `assets/icons/circle-x.svg` | Lucide icon "circle-x" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/circle-x.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
+| `assets/icons/circle-x.svg` | Lucide icon "circle-x" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/circle-x.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs; drawn as PDF path data by crates/sign/src/status_layers.rs into displayed signature status layers |
| `crates/ui-egui/tests/data/form.pdf` | One-page AcroForm test fixture (text, check box, radio group, combo box) | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: hand-written PDF objects, no third-party content | Form-filling UI tests (crates/ui-egui/tests/it/forms.rs, commands.rs) |
| `assets/icons/pentagon.svg` | Lucide icon "pentagon" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/pentagon.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/message-square-quote.svg` | Lucide icon "message-square-quote" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/message-square-quote.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
@@ -267,7 +267,7 @@ Every asset PdfCraft includes, bundles or uses to build its published material,
| `assets/icons/a-large-small.svg` | Lucide icon "a-large-small" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/a-large-small.svg) | UI icon, embedded via crates/ui-egui/src/widgets/icon_data.rs |
| `assets/icons/move-horizontal.svg` | Lucide icon "move-horizontal" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/move-horizontal.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
-## Compiled in through dependencies (6)
+## Compiled in through dependencies (7)
| Crate | File | Title | Author | Licence | Source | Used for |
|---|---|---|---|---|---|---|
@@ -277,6 +277,7 @@ Every asset PdfCraft includes, bundles or uses to build its published material,
| `epaint_default_fonts` 0.37.0 | `fonts/emoji-icon-font.ttf` | emoji-icon-font | John Slegers | MIT | https://github.com/jslegers/emoji-icon-font | egui monochrome fallback font (egui feature monochrome_emoji_fonts) |
| `epaint_default_fonts` 0.37.0 | `fonts/egui-icons.ttf` | egui icons (monochrome emoji-icon-font subset) | John Slegers | MIT | https://github.com/jslegers/emoji-icon-font | Small special-icon subset embedded by egui default_fonts; retained in FontDefinitions::default(). Provenance: https://github.com/storytold/egui/blob/6d518fc799681571963842f95b55a6b68431b15a/crates/epaint_default_fonts/fonts/egui-icons.txt; complete MIT copyright and permission text in NOTICE. |
| `hayro-interpret` 0.7.0 | `src/font/generated/metrics.rs` | Standard-14 font metrics and encodings (as Rust tables) (non-visual data, AGENTS.md §1.1) | Adobe (Core 14 AFM metrics, PDF specification encodings); tables by The Hayro Authors | MIT OR Apache-2.0 | ISO 32000-2 Annex D; Adobe Core14 AFM files (via vendored hayro-interpret) | Glyph widths and encodings for non-embedded standard fonts. Non-visual data, allowed by AGENTS.md §1.1 |
+| `icu_segmenter_data` 2.3.0 | `data/segmenter_dictionary_extended_v1.rs.data` | Southeast Asian word dictionaries for line breaking (Thai, Lao, Khmer, Burmese) | The ICU4X Project Developers; word lists from the ICU project (Unicode, Inc.) | Unicode-3.0 | https://github.com/unicode-org/icu4x (via icu_segmenter_data) | Word boundaries for wrapping Thai text in Edit text and Add text (crates/edit/src/linebreak.rs). Non-visual data; the line segmenter loads only these dictionaries, not the Chinese and Japanese one |
## Downloaded at build time (22)
@@ -314,4 +315,4 @@ Not in this repository and never downloaded by it: compiled in only when the bui
| Input | Option | Title | Author | Licence | Source | Attribution | Used for |
|---|---|---|---|---|---|---|---|
| `craft-i18n` | `CRAFT_I18N_DIR` | Interface translations: the craft-i18n catalogs (locales//common.tsv and pdfcraft.tsv) of the 34 languages PdfCraft offers besides English | The craft-i18n translators, including every translator of PdfCraft's former in-repo catalogs (crates/ui-egui/src/i18n/*.tsv, migrated at pdfcraft@ecdd1e6) | MIT OR Apache-2.0 | https://github.com/storytold/craft-i18n (pinned by commit in craft-i18n.rev, which CI, releases and the flatpak manifests read) | https://github.com/storytold/craft-i18n/blob/main/ATTRIBUTION.md | Interface text in languages other than English, embedded by crates/ui-egui/build.rs and looked up through craft-libs' craft-i18n crate; a build without CRAFT_I18N_DIR is English only. Clean-room translations from PdfCraft's English interface labels |
-| `craft-fonts` | `CRAFT_FONTS_DIR` | Japanese fonts: BIZ UDPGothic (Regular, Bold), Shippori Mincho, BIZ UDMincho; native Simplified Chinese font: LXGW WenKai Lite; Arabic font: Noto Sans Arabic | The BIZ UDGothic and BIZ UDMincho Project Authors (Morisawa Inc.), The Shippori Mincho Project Authors (FONTDASU), LXGW and the original Klee Project Authors / Fontworks (LXGW WenKai Lite), The Noto Project Authors (Noto Sans Arabic) | OFL-1.1 | https://github.com/storytold/craft-fonts (pinned by commit in .github/workflows/release.yml and .github/workflows/ci.yml); LXGW WenKai Lite from https://github.com/lxgw/LxgwWenKai-Lite/releases/tag/v1.530 (commit b712c83d98acf977bacfb7fb010207802808bda9) | https://github.com/storytold/craft-fonts/blob/main/ATTRIBUTION.md | Japanese fallback in the interface (BIZ UDPGothic first) and Japanese glyphs in edited PDF text (Shippori Mincho); Simplified Chinese interface fallback on native builds only (LXGW WenKai Lite Regular, font SHA-256 f799a538a3355877e597a0ae04050e897932c9ae7689eb9227c2953c5dd549ea, OFL SHA-256 0333a85fe077b6849f8e417acc44e8bd879442ceb681e271acf93e2d57fd4e2e, read from fonts/simplified-chinese-manifest.txt and never embedded on wasm); Arabic interface text, file names and document titles (Noto Sans Arabic); the web build embeds BIZ UDPGothic Regular and the pinned small Arabic, Hebrew, Thai and Devanagari faces; the selected craft-fonts revision contains no Telugu face. Other non-Japanese CJK faces retain the general 4 MiB cap; the reviewed native-only LXGW fallback has a separate 16 MiB cap. Open-source OFL releases are permitted under current AGENTS.md §1.1 |
+| `craft-fonts` | `CRAFT_FONTS_DIR` | Japanese fonts: BIZ UDPGothic (Regular, Bold), Shippori Mincho, BIZ UDMincho; native Simplified Chinese font: LXGW WenKai Lite; Arabic font: Noto Sans Arabic | The BIZ UDGothic and BIZ UDMincho Project Authors (Morisawa Inc.), The Shippori Mincho Project Authors (FONTDASU), LXGW and the original Klee Project Authors / Fontworks (LXGW WenKai Lite), The Noto Project Authors (Noto Sans Arabic) | OFL-1.1 | https://github.com/storytold/craft-fonts (pinned by commit in .github/workflows/release.yml and .github/workflows/ci.yml); LXGW WenKai Lite from https://github.com/lxgw/LxgwWenKai-Lite/releases/tag/v1.530 (commit b712c83d98acf977bacfb7fb010207802808bda9) | https://github.com/storytold/craft-fonts/blob/main/ATTRIBUTION.md | Japanese fallback in the interface (BIZ UDPGothic first) and Japanese glyphs in edited PDF text (Shippori Mincho); Simplified Chinese interface fallback on native builds only (LXGW WenKai Lite Regular, font SHA-256 f799a538a3355877e597a0ae04050e897932c9ae7689eb9227c2953c5dd549ea, OFL SHA-256 0333a85fe077b6849f8e417acc44e8bd879442ceb681e271acf93e2d57fd4e2e, read from fonts/simplified-chinese-manifest.txt and never embedded on wasm); Arabic interface text, file names and document titles (Noto Sans Arabic); status captions of named-layer signatures in Arabic, Japanese, Thai and Devanagari, drawn as filled outlines into the display copy by crates/sign/src/status_layers.rs; the web build embeds BIZ UDPGothic Regular and the pinned small Arabic, Hebrew, Thai and Devanagari faces; the selected craft-fonts revision contains no Telugu face. Other non-Japanese CJK faces retain the general 4 MiB cap; the reviewed native-only LXGW fallback has a separate 16 MiB cap. Open-source OFL releases are permitted under current AGENTS.md §1.1 |
diff --git a/ATTRIBUTION.toml b/ATTRIBUTION.toml
index 99073babb1..67b588f25e 100644
--- a/ATTRIBUTION.toml
+++ b/ATTRIBUTION.toml
@@ -425,7 +425,7 @@ source = "https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icon
licence = "ISC AND MIT"
licence_file = "assets/icons/LICENSE-lucide.txt"
kind = "icon"
-usage = "UI icon, embedded via crates/ui-egui/src/icon_data.rs"
+usage = "UI icon, embedded via crates/ui-egui/src/icon_data.rs; drawn as PDF path data by crates/sign/src/status_layers.rs into displayed signature status layers"
sha256 = "201e790f3a05c65b2c4b0f952c9b9e1f35cd1c5b21698b3f4be131883fe90bc8"
[[asset]]
@@ -1844,7 +1844,7 @@ source = "https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icon
licence = "ISC AND MIT"
licence_file = "assets/icons/LICENSE-lucide.txt"
kind = "icon"
-usage = "UI icon, embedded via crates/ui-egui/src/icon_data.rs"
+usage = "UI icon, embedded via crates/ui-egui/src/icon_data.rs; drawn as PDF path data by crates/sign/src/status_layers.rs into displayed signature status layers"
sha256 = "55aa37e0b73e7f8cd906952dbdeb96283c6595ca64aba240a17f3455cb989114"
[[asset]]
@@ -1954,7 +1954,7 @@ source = "https://github.com/rsms/inter"
licence = "OFL-1.1"
licence_file = "assets/fonts/OFL-Inter.txt"
kind = "font"
-usage = "UI font, embedded in the app; demo PDF labels; slanted fallback glyphs in Fill & Sign typed signatures for characters Dancing Script lacks (Cyrillic, Greek), drawn as filled paths"
+usage = "UI font, embedded in the app; demo PDF labels; slanted fallback glyphs in Fill & Sign typed signatures for characters Dancing Script lacks (Cyrillic, Greek), drawn as filled paths; embedded into displayed signature status captions beyond WinAnsi by crates/sign/src/status_layers.rs"
sha256 = "40d692fce188e4471e2b3cba937be967878f631ad3ebbbdcd587687c7ebe0c82"
[[asset]]
@@ -2263,6 +2263,18 @@ adobe_data = true
usage = "Glyph widths and encodings for non-embedded standard fonts. Non-visual data, allowed by AGENTS.md §1.1"
sha256 = "2ec9e608573eda459de1e1d9bda3bb494315e36bee885acc88912a11fe0caa41"
+[[bundled]]
+crate = "icu_segmenter_data"
+version = "2.3.0"
+path = "data/segmenter_dictionary_extended_v1.rs.data"
+title = "Southeast Asian word dictionaries for line breaking (Thai, Lao, Khmer, Burmese)"
+author = "The ICU4X Project Developers; word lists from the ICU project (Unicode, Inc.)"
+source = "https://github.com/unicode-org/icu4x (via icu_segmenter_data)"
+licence = "Unicode-3.0"
+kind = "data"
+usage = "Word boundaries for wrapping Thai text in Edit text and Add text (crates/edit/src/linebreak.rs). Non-visual data; the line segmenter loads only these dictionaries, not the Chinese and Japanese one"
+sha256 = "cad3821ca44fdb88ed856ff3336444aa200afe7b9d19e34ac28ae6a4459d4c6d"
+
[[fetched]]
file = "PlayfairDisplay[wght].ttf"
url = "https://raw.githubusercontent.com/google/fonts/9710da1eacb3be272583c3224dcb70f9da6eadbb/ofl/playfairdisplay/PlayfairDisplay%5Bwght%5D.ttf"
@@ -3004,7 +3016,7 @@ source = "https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icon
licence = "ISC AND MIT"
licence_file = "assets/icons/LICENSE-lucide.txt"
kind = "icon"
-usage = "UI icon, embedded via crates/ui-egui/src/icon_data.rs"
+usage = "UI icon, embedded via crates/ui-egui/src/icon_data.rs; drawn as PDF path data by crates/sign/src/status_layers.rs into displayed signature status layers"
sha256 = "ef1fec17d88794ba6c34c5cf63bdadbd234b3d4dffbcc3d55468b47e3f398472"
[[asset]]
@@ -3142,7 +3154,7 @@ source = "https://github.com/storytold/craft-fonts (pinned by commit in .github/
licence = "OFL-1.1"
attribution = "https://github.com/storytold/craft-fonts/blob/main/ATTRIBUTION.md"
kind = "font"
-usage = "Japanese fallback in the interface (BIZ UDPGothic first) and Japanese glyphs in edited PDF text (Shippori Mincho); Simplified Chinese interface fallback on native builds only (LXGW WenKai Lite Regular, font SHA-256 f799a538a3355877e597a0ae04050e897932c9ae7689eb9227c2953c5dd549ea, OFL SHA-256 0333a85fe077b6849f8e417acc44e8bd879442ceb681e271acf93e2d57fd4e2e, read from fonts/simplified-chinese-manifest.txt and never embedded on wasm); Arabic interface text, file names and document titles (Noto Sans Arabic); the web build embeds BIZ UDPGothic Regular and the pinned small Arabic, Hebrew, Thai and Devanagari faces; the selected craft-fonts revision contains no Telugu face. Other non-Japanese CJK faces retain the general 4 MiB cap; the reviewed native-only LXGW fallback has a separate 16 MiB cap. Open-source OFL releases are permitted under current AGENTS.md §1.1"
+usage = "Japanese fallback in the interface (BIZ UDPGothic first) and Japanese glyphs in edited PDF text (Shippori Mincho); Simplified Chinese interface fallback on native builds only (LXGW WenKai Lite Regular, font SHA-256 f799a538a3355877e597a0ae04050e897932c9ae7689eb9227c2953c5dd549ea, OFL SHA-256 0333a85fe077b6849f8e417acc44e8bd879442ceb681e271acf93e2d57fd4e2e, read from fonts/simplified-chinese-manifest.txt and never embedded on wasm); Arabic interface text, file names and document titles (Noto Sans Arabic); status captions of named-layer signatures in Arabic, Japanese, Thai and Devanagari, drawn as filled outlines into the display copy by crates/sign/src/status_layers.rs; the web build embeds BIZ UDPGothic Regular and the pinned small Arabic, Hebrew, Thai and Devanagari faces; the selected craft-fonts revision contains no Telugu face. Other non-Japanese CJK faces retain the general 4 MiB cap; the reviewed native-only LXGW fallback has a separate 16 MiB cap. Open-source OFL releases are permitted under current AGENTS.md §1.1"
[[asset]]
path = "crates/sign/tests/data/x509-rsa-sha1.pdf"
diff --git a/Cargo.lock b/Cargo.lock
index a0218b5748..faa65678d7 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1243,7 +1243,7 @@ dependencies = [
[[package]]
name = "craft-print"
version = "0.1.0"
-source = "git+https://github.com/storytold/craft-libs?rev=787a7a0f972fd1d7a7618fdbeca3a5267a0407ff#787a7a0f972fd1d7a7618fdbeca3a5267a0407ff"
+source = "git+https://github.com/storytold/craft-libs?rev=7ee35a9fbd47af572d55fd63dbf0333d1f00da17#7ee35a9fbd47af572d55fd63dbf0333d1f00da17"
dependencies = [
"craft-winprint-gdi",
"log",
@@ -1289,7 +1289,7 @@ dependencies = [
[[package]]
name = "craft-update"
version = "0.1.0"
-source = "git+https://github.com/storytold/craft-libs?rev=787a7a0f972fd1d7a7618fdbeca3a5267a0407ff#787a7a0f972fd1d7a7618fdbeca3a5267a0407ff"
+source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d"
dependencies = [
"chrono",
"dunce",
@@ -1312,10 +1312,21 @@ dependencies = [
"zip",
]
+[[package]]
+name = "craft-web-api"
+version = "0.1.0"
+source = "git+https://github.com/storytold/craft-libs?rev=fd5e2feff6ea25bed371a99cc732b3968d621505#fd5e2feff6ea25bed371a99cc732b3968d621505"
+dependencies = [
+ "js-sys",
+ "serde_json",
+ "wasm-bindgen",
+ "wasm-bindgen-futures",
+]
+
[[package]]
name = "craft-web-host"
version = "0.1.0"
-source = "git+https://github.com/storytold/craft-libs?rev=2e2312ddaf21bc3d85cd3395d0955c7d239306f6#2e2312ddaf21bc3d85cd3395d0955c7d239306f6"
+source = "git+https://github.com/storytold/craft-libs?rev=fd5e2feff6ea25bed371a99cc732b3968d621505#fd5e2feff6ea25bed371a99cc732b3968d621505"
dependencies = [
"wasm-bindgen",
"web-sys",
@@ -1324,7 +1335,7 @@ dependencies = [
[[package]]
name = "craft-winprint-gdi"
version = "0.1.0"
-source = "git+https://github.com/storytold/winprint.rs?rev=417ac3c4d14d3da5485a99c7d5ce8f05664ec312#417ac3c4d14d3da5485a99c7d5ce8f05664ec312"
+source = "git+https://github.com/storytold/winprint.rs?rev=64e7afd4d1483512385012c340ecaaaf0f3beb7f#64e7afd4d1483512385012c340ecaaaf0f3beb7f"
dependencies = [
"windows-sys 0.61.2",
]
@@ -3122,6 +3133,28 @@ dependencies = [
"zerovec",
]
+[[package]]
+name = "icu_segmenter"
+version = "2.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "82d07aafccd67af15d02512a6adf5896fbc5ed00f2e99b471d2efa14016db3db"
+dependencies = [
+ "icu_collections",
+ "icu_locale_fallback",
+ "icu_provider",
+ "icu_segmenter_data",
+ "potential_utf",
+ "smallvec",
+ "utf8_iter",
+ "zerovec",
+]
+
+[[package]]
+name = "icu_segmenter_data"
+version = "2.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ae293c039020f9ec10710af98d29ce6aa2051486638b49c9a6409f3b4a9e98ad"
+
[[package]]
name = "idna"
version = "1.1.0"
@@ -4254,7 +4287,6 @@ version = "0.19.0"
dependencies = [
"pdfcraft-content",
"pdfcraft-cos",
- "pdfcraft-filters",
"pdfcraft-fonts",
"pdfcraft-model",
"thiserror 2.0.21",
@@ -4267,6 +4299,7 @@ dependencies = [
"hayro-syntax",
"pdfcraft-cos",
"pdfcraft-fonts",
+ "pdfcraft-geom",
"pdfcraft-model",
"thiserror 2.0.21",
]
@@ -4389,6 +4422,7 @@ name = "pdfcraft-edit"
version = "0.19.0"
dependencies = [
"hayro-syntax",
+ "icu_segmenter",
"kurbo 0.13.1",
"pdfcraft-annot",
"pdfcraft-content",
@@ -4529,10 +4563,22 @@ dependencies = [
"pdfcraft-fonts",
"png 0.18.1",
"rten",
+ "serde_json",
+ "sha2 0.11.1",
"tempfile",
"thiserror 2.0.21",
]
+[[package]]
+name = "pdfcraft-ocr-worker"
+version = "0.18.1"
+dependencies = [
+ "js-sys",
+ "pdfcraft-ocr",
+ "wasm-bindgen",
+ "web-sys",
+]
+
[[package]]
name = "pdfcraft-optimize"
version = "0.19.0"
@@ -4546,6 +4592,7 @@ dependencies = [
"pdfcraft-render",
"proptest",
"thiserror 2.0.21",
+ "thread-priority",
"zune-jpeg",
]
@@ -4627,10 +4674,12 @@ dependencies = [
"pdfcraft-filters",
"pdfcraft-fonts",
"pdfcraft-forms",
+ "pdfcraft-geom",
"pdfcraft-model",
"pdfcraft-render",
"pdfcraft-testkit",
"pdfcraft-xfa",
+ "regex",
"sha2 0.11.1",
"thiserror 2.0.21",
]
@@ -4649,9 +4698,12 @@ dependencies = [
"lopdf",
"pdfcraft-cos",
"pdfcraft-fonts",
+ "pdfcraft-geom",
+ "pdfcraft-testkit",
"serde",
"skrifa 0.44.0",
"thiserror 2.0.21",
+ "unicode-bidi",
]
[[package]]
@@ -4676,9 +4728,11 @@ dependencies = [
"p521",
"pbkdf2",
"pdfcraft-annot",
+ "pdfcraft-content",
"pdfcraft-cos",
"pdfcraft-fonts",
"pdfcraft-model",
+ "pdfcraft-testkit",
"rc2",
"ripemd",
"rsa",
@@ -4754,11 +4808,13 @@ dependencies = [
name = "pdfcraft-web"
version = "0.19.0"
dependencies = [
+ "craft-web-api",
"craft-web-host",
"eframe",
"egui",
"js-sys",
"pdfcraft-ui-egui",
+ "serde_json",
"wasm-bindgen-futures",
"web-sys",
]
@@ -4781,10 +4837,12 @@ dependencies = [
name = "pdfcraft-xfdf"
version = "0.19.0"
dependencies = [
+ "base64 0.23.1",
"pdfcraft-annot",
"pdfcraft-cos",
"pdfcraft-forms",
"pdfcraft-model",
+ "proptest",
"roxmltree 0.21.2",
"thiserror 2.0.21",
]
@@ -5507,6 +5565,29 @@ dependencies = [
"bitflags 2.13.2",
]
+[[package]]
+name = "regex"
+version = "1.13.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d"
+dependencies = [
+ "aho-corasick",
+ "memchr",
+ "regex-automata",
+ "regex-syntax",
+]
+
+[[package]]
+name = "regex-automata"
+version = "0.4.18"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2"
+dependencies = [
+ "aho-corasick",
+ "memchr",
+ "regex-syntax",
+]
+
[[package]]
name = "regex-syntax"
version = "0.8.11"
@@ -6879,6 +6960,20 @@ dependencies = [
"syn 3.0.6",
]
+[[package]]
+name = "thread-priority"
+version = "3.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8d2e834949be5111506bb252643498af1514f600d9e1dceedaa42afae155b67f"
+dependencies = [
+ "bitflags 2.13.2",
+ "cfg-if",
+ "libc",
+ "log",
+ "rustversion",
+ "windows",
+]
+
[[package]]
name = "tiff"
version = "0.11.3"
@@ -8209,7 +8304,7 @@ dependencies = [
[[package]]
name = "winprint"
version = "0.2.1"
-source = "git+https://github.com/storytold/winprint.rs?rev=5f80b9baf6b58937c401656634e42d33f00ddf49#5f80b9baf6b58937c401656634e42d33f00ddf49"
+source = "git+https://github.com/storytold/winprint.rs?rev=51934db382f225454cf152a8657eb03789be63c4#51934db382f225454cf152a8657eb03789be63c4"
dependencies = [
"flate2",
"fmt-derive",
@@ -8671,7 +8766,6 @@ dependencies = [
"nix",
"typed-path",
"windows-sys 0.61.2",
- "zopfli",
]
[[package]]
@@ -8686,18 +8780,6 @@ version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
-[[package]]
-name = "zopfli"
-version = "0.8.4"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "aaf7fc5d30c28483d93805c4a5e12b05bbb52407fa67c5f8bd552374cd01fb11"
-dependencies = [
- "bumpalo",
- "crc32fast",
- "log",
- "simd-adler32",
-]
-
[[package]]
name = "zune-core"
version = "0.5.3"
diff --git a/Cargo.toml b/Cargo.toml
index a9c3487c55..d992acf2ba 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -24,11 +24,11 @@ craft-keymap = { git = "https://github.com/storytold/craft-libs", version = "0.1
# the commit in `craft-i18n.rev`). Already in the tree through craft-ui.
craft-i18n = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "787a7a0f972fd1d7a7618fdbeca3a5267a0407ff" }
# Shared system spooler; document composition remains in pdfcraft-print.
-craft-print = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "787a7a0f972fd1d7a7618fdbeca3a5267a0407ff" }
+craft-print = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "7ee35a9fbd47af572d55fd63dbf0333d1f00da17" }
# Whether a path stored in a document may be opened (GoToR link targets).
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "787a7a0f972fd1d7a7618fdbeca3a5267a0407ff" }
# craft-update: app-specific pretend versions apply to startup and manual checks.
-craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "787a7a0f972fd1d7a7618fdbeca3a5267a0407ff", features = ["egui"] }
+craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "1b34eba41e62138fc2438d2734523b302840b45d", features = ["egui"] }
# internal
pdfcraft-geom = { path = "crates/geom", version = "0.19.0" }
pdfcraft-filters = { path = "crates/filters", version = "0.19.0" }
@@ -70,7 +70,11 @@ pdfcraft-prc-render = { path = "crates/prc-render", version = "0.19.0" }
hayro = "0.7.1"
hayro-syntax = "0.7.2"
lopdf = "0.45"
-flate2 = { version = "1.1", default-features = false, features = ["rust_backend"] }
+# zlib-rs: miniz_oxide took about 1.7 µs for every fixed-Huffman block, empty or not
+# (`pdfcraft_filters::FLATE_READ_WORK`). Other dependencies still build flate2's default
+# miniz_oxide backend; flate2 prefers zlib-rs when both are built, as the Windows build already did
+# through craft-update. `flate::tests::a_copy_from_before_the_start_is_damage` shows which runs.
+flate2 = { version = "1.1", default-features = false, features = ["zlib-rs"] }
weezl = "0.2"
# CCITT Group 4 encoding (pdfcraft-filters); already in the tree through tiff.
fax = "0.2.7"
@@ -80,6 +84,9 @@ hayro-jbig2 = "0.3"
# foundation
thiserror = "2"
+# Linear-time matching (no backtracking) for caller-supplied redaction patterns. `perf-dfa` gives
+# the lazy-DFA cache that `RegexBuilder::dfa_size_limit` bounds (the limit is inert without it).
+regex = { version = "1", default-features = false, features = ["std", "unicode", "perf-dfa"] }
serde = { version = "1", features = ["derive", "rc"] }
serde_json = "1"
log = "0.4"
diff --git a/LICENSES.toml b/LICENSES.toml
index 0617ca5d57..ac54d9f702 100644
--- a/LICENSES.toml
+++ b/LICENSES.toml
@@ -16,7 +16,7 @@ sha256 = "cd7032ea33b71427f188e34ffb4aee9d6868a57fd196037c5c8b2be03a2a0352"
[[document]]
source = "NOTICE"
destination = "NOTICE"
-sha256 = "9f854f730719af962cd840529324d089e05e68a30bd245c50e33f96e009b4314"
+sha256 = "d9ba162ad2bc95d22ab9885065e253bb823bd6795068828e7b39858344b660eb"
[[document]]
source = "assets/app-icon/LICENSE-document.txt"
@@ -60,6 +60,13 @@ destination = "licenses/CMap-LICENSE.txt"
sha256 = "742665db9c8e1bc72603c6d319ca3e90b83bd6d95202f0cd4ef11068a07a9c29"
origin = "https://static.crates.io/crates/hayro-cmap/hayro-cmap-0.1.0.crate#assets/LICENSE.txt"
+[[document]]
+source = "licenses/ICU4X-LICENSE.txt"
+licences = ["Unicode-3.0"]
+destination = "licenses/ICU4X-LICENSE.txt"
+sha256 = "f367c1b8e1aa262435251e442901da4607b4650e0e63a026f5044473ecfb90f2"
+origin = "https://static.crates.io/crates/icu_segmenter_data/icu_segmenter_data-2.3.0.crate#LICENSE"
+
[[document]]
source = "licenses/egui-Hack-Regular.txt"
licences = ["MIT", "Bitstream-Vera"]
@@ -164,3 +171,9 @@ crate = "hayro-interpret"
path = "src/font/generated/metrics.rs"
licence = "MIT OR Apache-2.0"
documents = ["vendor/hayro-interpret/LICENSE-MIT", "vendor/hayro-interpret/LICENSE-APACHE"]
+
+[[bundled]]
+crate = "icu_segmenter_data"
+path = "data/segmenter_dictionary_extended_v1.rs.data"
+licence = "Unicode-3.0"
+documents = ["licenses/ICU4X-LICENSE.txt"]
diff --git a/NOTICE b/NOTICE
index e8f31ade2f..eed2d654b0 100644
--- a/NOTICE
+++ b/NOTICE
@@ -36,6 +36,9 @@ list (author, source, license) is in ATTRIBUTION.md.
- egui default fonts (epaint_default_fonts, via eframe) — Ubuntu Light (Ubuntu Font Licence 1.0),
Hack (MIT / Bitstream Vera licence), Noto Emoji (SIL OFL 1.1), emoji-icon-font (MIT).
- Colour profile in hayro-interpret — CGATS001Compat-v2-micro.icc (CC0-1.0, Clinton Ingram).
+- ICU4X line-breaking data (icu_segmenter_data, via crates.io) — Unicode-3.0. Its Thai, Lao, Khmer
+ and Burmese word dictionaries are compiled in for wrapping Thai text; notice below, full licence in
+ licenses/ICU4X-LICENSE.txt.
Required notices:
@@ -48,6 +51,32 @@ Required notices:
(https://github.com/adobe-type-tools/cmap-resources/blob/master/LICENSE.txt). Neither the name of
Adobe nor the names of its contributors are used to endorse or promote this product.
+ ICU4X segmenter data (bundled by icu_segmenter_data 2.3.0; word lists, not visual assets):
+ Copyright © 2020-2024 Unicode, Inc. Portions adapted from ICU4C and/or ICU4J:
+ ICU 1.8.1 to ICU 57.1 © 1995-2016 International Business Machines Corporation and others.
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy of data files and any
+ associated documentation (the "Data Files") or software and any associated documentation (the
+ "Software") to deal in the Data Files or Software without restriction, including without
+ limitation the rights to use, copy, modify, merge, publish, distribute, and/or sell copies of the
+ Data Files or Software, and to permit persons to whom the Data Files or Software are furnished to
+ do so, provided that either (a) this copyright and permission notice appear with all copies of
+ the Data Files or Software, or (b) this copyright and permission notice appear in associated
+ Documentation.
+
+ THE DATA FILES AND SOFTWARE ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+ PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS.
+
+ IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM,
+ OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
+ USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
+ ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THE DATA FILES OR SOFTWARE.
+
+ Except as contained in this notice, the name of a copyright holder shall not be used in
+ advertising or otherwise to promote the sale, use or other dealings in these Data Files or
+ Software without prior written authorization of the copyright holder.
+
Showcase PDF (built by `cargo xtask demo-pdf`, not committed): fonts are downloaded at build time from
google/fonts at a pinned commit, verified by SHA-256, all under the SIL Open Font License 1.1 — see the
"Downloaded at build time" table in ATTRIBUTION.md.
diff --git a/README.md b/README.md
index f488d160cc..7ca789c6e0 100644
--- a/README.md
+++ b/README.md
@@ -499,6 +499,12 @@ didn't have a menu yet (0.6.0 and earlier for the PDF menu, 0.2.1 and earlier fo
adds it, as a first install would. Use the MSI for your architecture. Per-user installation
overrides are not supported.
+To install somewhere other than the default `ArtCraft\PdfCraft` folder, change the folder on the
+welcome screen (type it, or Browse…) or pass it on the command line:
+`INSTALLFOLDER="D:\Apps\PdfCraft"`. It is installed for whoever the first screen chose (`ALLUSERS=1`
+on the command line for everyone). An upgrade keeps the folder the installed version uses unless
+the command line gives another one.
+
**Pin the checksum, not just the version.** Release candidates of a version share its MSI version
(MSI versions are numbers only, so 1.2.3-rc.1 and 1.2.3 are both 1.2.3), and the installer lets an
MSI of the same version replace the installed one without asking. Two different `0.7.1` MSIs can't
diff --git a/ROADMAP.md b/ROADMAP.md
index 820ceb0179..c2c7c6ad62 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -1,8 +1,16 @@
# PdfCraft roadmap
+> **Last reviewed:** 2026-11-08 | **Last updated:** 2026-11-08 | **Change:** patch (M10 #6514: refresh craft-print to 7ee35a9f, PDF loader to 51934db3 and public GDI kept at 64e7afd4 after #605 merged; preserve crash fix and stream-test repairs; new-graph CI pending; estimates unchanged)
+
+> **Last reviewed:** 2026-11-07 | **Last updated:** 2026-11-07 | **Change:** patch (M10: file-backed Windows PDF loading without whole-job buffering or per-chunk async waits; approved dependency chain retains #5006; physical output still unqualified; estimates unchanged)
+
+> **Last reviewed:** 2026-11-05 | **Last updated:** 2026-11-05 | **Change:** patch (M7 #2964: directly edit Thai source text inside supported Form XObjects; estimates unchanged)
+
> **Last reviewed:** 2026-11-03 | **Last updated:** 2026-11-03 | **Change:** patch (M5 #5850 review: indirect typewriter intent and composer edits preserve outer whitespace; movement regression commits by outside click; estimates unchanged)
> **Last reviewed:** 2026-11-03 | **Last updated:** 2026-11-03 | **Change:** patch (M5 #5850: Enter adds Fill & Sign line breaks; outside clicks commit, Escape cancels, and saved multiline appearances retain their text and height; estimates unchanged)
+> **Last reviewed:** 2026-10-31 | **Last updated:** 2026-10-31 | **Change:** minor (M3/M4, #5330: Crop pages is directly available in the document quick toolbar; estimates unchanged)
+
> **Last reviewed:** 2026-11-01 | **Last updated:** 2026-11-01 | **Change:** patch (M7, PR #2155 further review: inherited drawing/text state, affine image gestures, paste/selection ownership, no-op scripts and menu permissions; estimates unchanged)
@@ -190,27 +198,28 @@ What's strong and missing in each: [target-app-parity.md](docs/target-app-parity
## Languages
-Twelve key languages (historical % snapshot vs 2,143 keys, except Vietnamese, Brazilian
-Portuguese and Spanish vs the current union). Detail and script notes: [localization-parity.md](docs/localization-parity.md).
+Twelve key languages: the share of the 2,897 strings in the i18n report's denominator (the interface's strings plus every catalog key), from
+`cargo xtask i18n-report` on 2026-11-03. Detail and script notes: [localization-parity.md](docs/localization-parity.md).
| Language | Code | Strings | Status |
|---|---|---|---|
| English | `en` | 100% | full |
-| Simplified Chinese | `zh-hans` | 97.4% | partial (native LXGW WenKai Lite; no Hans face in the web build, #826) |
-| Spanish | `es` | 100% of current union | partial (dialogs / tooltips; no help) |
-| Hindi | `hi` | 0% | none |
-| Arabic | `ar` | 100% | partial (logical catalog, explicit RTL labels, mirrored stock chrome; native/browser/IME workflows unqualified) |
-| French | `fr` | 99.3% | partial |
-| Portuguese (Brazil) | `pt-br` | 100% of current union | partial |
-| Indonesian | `id` | 0% | none |
-| Japanese | `ja` | 99.1% | partial |
-| German | `de` | 99.3% | partial |
-| Korean | `ko` | 0% | none |
-| Vietnamese | `vi` | 100% of current union | partial (dialogs / tooltips; no help) |
+| Simplified Chinese | `zh-hans` | 88.4% | partial (native LXGW WenKai Lite; no Hans face in the web build, #826) |
+| Spanish | `es` | 98.4% | partial (dialogs / tooltips; no help) |
+| Hindi | `hi` | 97.5% | partial (Devanagari rendering unqualified) |
+| Arabic | `ar` | 97.9% | partial (logical catalog, explicit RTL labels, mirrored stock chrome; native/browser/IME workflows unqualified) |
+| French | `fr` | 98.4% | partial |
+| Portuguese (Brazil) | `pt-br` | 98.4% | partial |
+| Indonesian | `id` | 97.5% | partial |
+| Japanese | `ja` | 89.6% | partial |
+| German | `de` | 89.7% | partial |
+| Korean | `ko` | 97.5% | partial (no Hangul UI face) |
+| Vietnamese | `vi` | 98.4% | partial (dialogs / tooltips; no help) |
Also shipped: Traditional Chinese, Russian, Bulgarian, Telugu, Hungarian, Ukrainian, Italian,
-Kazakh, Polish, Slovenian, Greek, Turkish, Lithuanian, Romanian and Czech: **15 more catalogs**
-(24 interface languages including English).
+Kazakh, Polish, Slovenian, Greek, Turkish, Lithuanian, Finnish, Albanian, Catalan, Romanian,
+Norwegian Bokmål, Persian, Central Kurdish, Thai, Lao and Czech: **23 more catalogs**
+(35 interface languages including English).
## Upcoming
@@ -229,20 +238,33 @@ Ranked; detail and the full milestone table in [docs/roadmap.md](docs/roadmap.md
| 8 | 1.0 polish: performance, right-to-left, missing languages, keyboard-only (M14) | 55–95 |
## Progress log
+- **2026-10-13 (M8, redact by regex):** `redact_mark` takes `regex` (caller expression, linear-time engine, length/size/nesting caps, empty-matching refused) with optional `validate` (luhn, mod97, iban). Headless only; issue #1886.
+- **2026-11-08 (M5, comment exchange):** Comments keep their formatting and appearance through XFDF and FDF. XFDF export and import carry rich text, default style, border width, style and dash pattern, rotation, justification, fringe, line leaders and captions, the caret symbol and redaction overlay text as XFDF 3.0 (ISO 19444-1) names them, and a stamp's appearance as `` (the DICT/STREAM/DATA encoding, bounded); copy and paste carries every comment's appearance. FDF export keeps a stamp's /AP with its forms and images, as XFDF does, and FDF import keeps any /AP the file carries (ISO 32000-2 §12.7.8.3.4). The intent goes out as both `intent` and `IT`. An unreadable XFDF appearance is left out, said in the import report and the repair log, and the comment is drawn by PdfCraft; an FDF past the import budget is refused whole. A redaction mark is always drawn by PdfCraft.
+
+- **2026-11-07 (M2, #6449):** A non-embedded Times New Roman set as a TrueType CID font (`TimesNewRoman,Bold`, `TimesNewRomanPSMT` and the other faces) draws the glyphs its codes name, as the non-embedded Arial does: its first 258 glyphs follow the same standard Macintosh order, which the embedded Times New Roman subsets of a public French form confirm in 941 of 942 `/ToUnicode` entries (vendored hayro-interpret patch 88). That form drew "Salarié(e) du régime général" as "Salari²*g+f w't²i lo g'ì²p²tcn" and "changement" as "ej angement". Times and Times New Roman MT Std are not read this way.
+
+- **2026-11-05 (M2, #5889):** A non-embedded Arial set as a TrueType CID font (`CIDFontType2`, `Identity-H`, as Word and PDFMaker write it) draws the glyphs its codes name. Those codes are glyph indexes in the author's Arial, whose first 258 glyphs follow the standard Macintosh order, so the standard substitute now draws each glyph by name (vendored hayro-interpret patch 76). Before, it took each code as one of its own glyph indexes, and "Low Power" drew as "@ck 'Dck Yf". Arial Narrow, Black and Unicode MS, and `CIDFontType0` fonts, are not read this way. Copying or searching those runs still needs a `/ToUnicode`.
+
+- **2026-11-07 (M7, #2964 / #3185):** Supported Form text can be prepared for direct editing; groups left grouped (unsafe compositing, text nested past eight levels) are reported. Legacy Thai keeps the original font programs, Regular/Bold and text settings, also across same-face subsets; the narrow THSarabunPSK map repair is checked glyph by glyph against the font program; cross-family replacement is explicit. Builds on #3067 and #2811. Unsafe groups and mixed contextual styles remain partial; estimates unchanged.
- **2026-10-28 (M10, #4119 partial):** Scan & OCR ▸ Enhance scanned file cleans scanned pages in place: background removal (level 0–100, as the camera clean-up), edge shadow removal (book gutters, copier borders) and despeckle. Each scan image is decoded, cleaned and written back into its own object at the same size and colour space (JPEG stays JPEG, others lossless, 1-bit stays 1-bit), so the OCR text layer, comments and links stay; one undo step, shared images once, unsupported images (CMYK, indexed, JPEG 2000, JBIG2, CCITT, broken data) reported. `page_enhance_scan` drives it headlessly. Not yet an option of Recognize text. Estimates unchanged.
+- **2026-11-07 (M10, `ocr.ocr-web`, port onto #977):** Web OCR rebuilt on main's engines and preprocessing (#977). `OcrJob::run` is now `OcrJob::steps` a page at a time: the page renders, crops to the region and cleans each page, a Web Worker runs ocrs on the result, and `OcrShot::place` maps the words back through the region and preprocessing. Every strategy reads like this when only one engine is present, and the web build has only ocrs. The downloaded models are installed into the engine cache (`ocr::install`), so the Verify screen and the engine-status checks see them too. The batch keeps main's skipped-files bucket, low-confidence notes and cancel. The translations moved to craft-i18n (storytold/craft-i18n#141). The Verify screen starts the model download itself and runs once the models land; before, on a fresh page it failed with the desktop's "set PDFCRAFT_MODELS" message. Known limits: the cleaning steps, and the Verify screen's Run OCR and re-reads, run on the page. Estimates unchanged.
+
- **2026-11-03 (M11, shared JBIG2 dictionary):** With Monochrome Images set to JBIG2, Optimize has up to 16 JBIG2 images share one symbol dictionary (`/JBIG2Globals`), the letters found on more than one page stored once, when that is smaller (`pdfcraft_filters::encode_jbig2_shared`). Eight pages of 10 pt text rendered at 300 dpi take 41% less in Helvetica and 42% in Times than coded alone, 10% in Courier; groups of 16 save 45%, of 32 only 47%. Only images redaction can store again without the dictionary share one (image masks and DeviceGray named directly, at most 64 Mi pixels), and redacting one stores the rest of its group so, which the group bounds to 15.
- **2026-11-03 (M5, #5850 review):** Resolve indirect IT when recognizing typewriter contents and Fill & Sign marks. Comment listing and property lookup retain their existing direct-Subtype behavior. A real double-click Edit composer preserves the typewriter’s text as written; ordinary comment edits keep trimming. Regressions cover direct Subtype with indirect intent, save/reopen, raw posted contents and same-index comments on different pages. The existing live-movement test now commits its setup with an outside click rather than Enter. Estimates unchanged.
- **2026-11-03 (M5, #5850):** Fill & Sign Enter inserts a line break in a growing editor; clicking outside commits and Escape cancels. Nonempty text keeps leading, internal and trailing line breaks. The headless fill_sign_add path sizes its typewriter box for the same wrapped lines so saved appearances show every row. Production-order keyboard and engine save/reopen/render regressions exercise the UI and headless callers. Estimates unchanged.
+- **2026-11-03 (community, M7, Thai word breaking):** Thai rows end between words, found with ICU4X's dictionary line segmenter (`icu_segmenter` 2.3, compiled dictionary data, no LSTM model; Unicode-3.0), instead of only at spaces when rewrapping and at any cluster in Add text. A row never starts with a following vowel, tone or other mark, Mai Yamok or Paiyannoi, nor ends with a leading vowel; a word wider than the row still breaks between clusters, and the spaces where an Add text row ends are dropped as in Latin text. Rewrapping existing text works out the breaks once per run of non-space characters. Rewriting a paragraph into Thai still needs a source font with the Thai glyphs (there is no Thai fallback face for it yet). The compiled dictionaries (Thai, Lao, Khmer, Burmese) add about 1.8 MB to a stripped release binary. Estimates unchanged.
- **2026-11-03 (M7, #5835):** In image crop mode, a right-click on the image, its crop box or its handles keeps the crop and opens no menu, so the menu no longer switches as the pointer moves. A right-click elsewhere clears the selection and opens the page menu. UI tests cover all four page rotations, overlapping images, a 45° image, and a check that the Done/Cancel/Remove Crop pills at a page edge still keep the crop.
-- **2026-11-02 (M12, #1297):** `model_add` embeds a U3D or PRC file, recognised by its header, as a 3D annotation with a chosen activation and a poster (an image or PDF page fitted in the box, or a labelled frame); an older file's catalog `/Version` is raised to what the model needs. Views, a rendered poster and a UI command are later steps. Estimates unchanged.
+- **2026-11-03 (M14 docs, #5805):** `docs/localization-parity.md` and the Languages table here count every catalog with `cargo xtask i18n-report`: the share of the 2,897 strings in its denominator, on `14ae839a`. The catalog-union measure it replaces had grown to 2,895 keys and left four catalogs at "100%" that were 44 keys short. Hindi, Indonesian and Korean are listed with their catalogs (97.5% each) instead of 0, and Thai, Lao and Central Kurdish join the table. The ≈ 68% localization score is not re-scored.
- **2026-11-02 (M10, #5743):** macOS print jobs name their title and owner (`com.apple.print.JobInfo.PMJobName`, `PMJobOwner`), as the system print dialog does, because a Kyocera filter crashes on a job without them. Checked by a test and through `doc_print` against a stand-in `lp`; not yet on a physical printer.
+- **2026-11-02 (M3, #5708):** Pages shorter than the window sit in its middle, one page or row at a time and when scrolling continuously with every page in view.
+- **2026-11-02 (M3, #5716):** A snapshot is drawn at 300 ppi, or at the zoom if that is finer, so one taken zoomed out stays readable; an area too large for one 4096-pixel tile comes out as fine as a tile allows (about 147 ppi for 2000 pt). A choice of resolution and a selection that stays active remain.
- **2026-11-02 (M14, #5737, #5460):** Preferences can turn off the update check at start. It stays on by default, and Help ▸ Check for updates still asks.
- **2026-11-01 (M7, #5657):** Header/footer, watermark and background additions and replacements stage the complete call before committing. Synthetic later-page failures preserve exact incremental bytes, object count, dirty state and allocation cursor; success controls retain other marks and shared/inherited resources. Estimates unchanged.
@@ -256,6 +278,7 @@ Ranked; detail and the full milestone table in [docs/roadmap.md](docs/roadmap.md
- 2026-11-01: PR #2155 review follow-up preserves editor crops through group moves and keeps arranged artwork outside added-item streams; unsafe nested-tag extraction is refused. Image handles and flips follow page orientation, added images accept general transforms, and clipboard/text/Home/font-discovery edge cases have focused regressions. Candidate only; estimates unchanged.
- 2026-11-01: PR #2155 maintainer edits remove redundant image/text helpers and add regressions for crop ownership, arrange scope/state fidelity, clipboard precedence, crop-drag bounds, and font scanning. Transform and Unicode-script tools complete the headless paths.
+- **2026-10-31 (M3/M4, #5330):** The document quick toolbar offers Crop pages directly through the existing page.crop command, with the command’s assembly-permission check and an active-tool highlight. The existing crop, undo and headless page_set_box paths are unchanged. No toolbar customization or new shortcut. Estimates unchanged.
- **2026-10-18 (M3, #1354, local candidate):** Integrated --two-paged with current main, retaining upstream modal/picker ownership and single-tab reuse. Native launch/opening/password regressions, negative checks against the old wrapper, visual inspection, formatting, strict scoped Clippy, layers, assets, parity and scoped WASM compilation pass. Three existing socket tests are unavailable in this workspace; one existing network test remains ignored. No push or GitHub merge; estimates unchanged.
- **2026-10-31 (M2, PR #4172 review):** Added same-machine pixel oracles for GBK Song, Hei, Kai and FangSong, including all four subset-prefixed Founder aliases. Reference PDFs use explicit Unicode mappings and independently selected installed faces; font data and rasters remain in memory. All eight cases ran; wrong-glyph and wrong-family production mutations each failed the new assertion and were restored. Validation: 422 renderer unit tests, renderer all-target Clippy with -D warnings, formatting, layers/assets/parity and renderer WASM checks passed; existing optional-patch/WASM warnings and parity notes remain. Estimates unchanged.
@@ -266,6 +289,7 @@ Ranked; detail and the full milestone table in [docs/roadmap.md](docs/roadmap.md
- **2026-10-27 (M2, PR #4172 module-split conflicts):** Integrated main 1dd2737b, retaining viewer-only CJK fallback in split session modules and Combine thumbnail workers, and moving renderer regressions to the new test module. Validation: 798 scoped tests passed (371 engine, 412 renderer, 15 Combine; two existing engine tests ignored); scoped all-target Clippy with -D warnings, formatting, layers, assets, parity and renderer/engine WASM checks passed. Estimates unchanged.
+- **2026-10-27 (M10, `ocr.ocr-web`, rebase fix):** The web build loads OCR models only when their SHA-256 matches `ATTRIBUTION.toml`. With ONNX loading now on, rten's parser spins forever on some bytes that aren't a model (a corrupt or wrong download), so a bad file now fails at once instead of hanging a worker.
- **2026-10-27 (M10, OCR models):** Model staging downloads and verifies the ONNX pair after the upstream RTEN URL brownout; runtime discovery prefers complete ONNX pairs per directory, retains complete RTEN fallback and preserves directory precedence.
- **2026-10-26 (M2, PR #4172):** Reconciled current main, preserving its Japanese serif/weight selection and both branches' progress records. Installed CJK viewer and preview fallback remains display-only; estimates unchanged.
@@ -277,6 +301,8 @@ Ranked; detail and the full milestone table in [docs/roadmap.md](docs/roadmap.md
- **2026-10-25 (web, same-document host mode):** A page that loads the PdfCraft web module into its own document (no iframe) can opt into the host bridge with `data-host="page"` on the app's canvas — the exact value `page`; any other value keeps the normal app with downloads, unless a same-origin framed `?host=parent` selects the parent bridge (unframed or cross-origin, `?host=parent` also keeps the normal app). It is the `?host=parent` bridge with the transport swapped: the same five messages travel as non-bubbling `CustomEvent`s on the canvas (`detail` holds the parent messages' fields without `type`; the host answers with a `pdfcraft:open` event), so saves reach the host instead of downloading and dirty and start-up-failure reporting are unchanged. Unit tests cover the opt-in rule; no parity or estimate changes.
- **2026-10-24 (M10, #4158 partial):** Word, HTML, RTF and PowerPoint export keep a block that continues another on its line (an italic case name, a link, a superscript) as a run in its own style inside that paragraph, with the source's word space, instead of a paragraph of its own. Style changes that wrap onto the next line still split paragraphs (the reading blocks keep style boundaries). Estimates unchanged.
- **2026-10-24 (M3, window move on Wayland, #3970 follow-up):** After a move or resize by PdfCraft's own title bar or edges, the button release given back to egui goes before the pointer leaving the window, so hover no longer sticks at the old place until the pointer moves. Found by CodeRabbit in review of #3970; a unit test covers it. Estimates unchanged.
+- **2026-10-26 (M10, `ocr.ocr-web`, review fix):** On the web, Edit on a scanned page starts the OCR model download, and the page is read once the models load; it was taken for no scan and left unread until the document changed.
+- **2026-10-24 (M10, `ocr.ocr-web`, review fix):** On the web, single-file and multiple-file OCR running at once no longer lose a page: the workers' answers go to the run that sent each page, instead of to whichever run collected first, and a cancelled run's late answers are let go. Regression tests cover both start orders and cancellation. Files chosen for Recognize Text in Multiple Files before the models have downloaded now wait for them instead of having to be chosen again, and idle workers close on time even when nothing is happening on the page, a full minute after their last page comes back rather than after it was handed out (checked by hand in Firefox); estimates unchanged.
- **2026-10-24 (M14, #4253):** The annotation quick bar remembers Keep tool selected across restarts, including unpinning. Old and malformed settings keep safe defaults; the opt-in UI control channel reads and changes the same preference. Estimates unchanged.
- **2026-10-22 (M7, #2517):** A partial rewrite of the last paragraph closes its marker after that paragraph's last `ET`, so a row left in the source stays in the paragraph. When the next paragraph shares the text object, the marker closes before that neighbour instead of after the shared `ET`. The extra marker is not added across two marked-content regions. Estimates unchanged.
- **2026-10-15 (M7, #2517):** A blank line between paragraphs stays a paragraph break. An explicit `TL` is the measured baseline gap. Without one, three or more rows at a repeated step stay one paragraph, and a single wider gap stays a break. Adding a row, even when an earlier row is left in the source, does not absorb the next paragraph on a later edit. Estimates unchanged.
@@ -315,6 +341,7 @@ Ranked; detail and the full milestone table in [docs/roadmap.md](docs/roadmap.md
- **2026-10-22 (M14, macOS association recovery candidate):** Successful desktop open/save/sign can queue recovery of an existing per-file binding to the running PDFCraft bundle through NSWorkspace. Metadata-only watcher changes retain undo and avoid false overwrite prompts; real same-length/same-mtime edits remain protected. Rebased on 0.12.0 and reuses #3042's shared atomic metadata preservation; the bounded recovery parser does not narrow save limits. Prior native Preview TEST-signature and Finder workflows passed on macOS 27.0.1; other versions remain unqualified. Estimates unchanged.
- **2026-10-13 (M7, free image rotation):** A selected page image has a rotate knob (Shift: 15 degree steps) and `image_edit` a `rotate_by` action; the angle is written as one undoable `cm`. Snapping to page edges while moving is in #1740; resize snapping is not done. Estimates unchanged.
+- **2026-10-20 (M9 #79 review, M2, M8):** text extraction reads a marked-content /ActualText that marks no glyph where it paints (paths and images, cut to what is visible, along the direction they are drawn), so words drawn as outlines can be found, copied and exported; OCR and scan field detection still count such a page as having no text of its own. Redaction strips /ActualText, /Alt, /E and /T from inline marked content around paint it clips, as it already did around paint it removed, so a partly redacted outlined word leaves no name in the file. Named-layer recognition also needs the layer form to draw n1 and n3. Estimates unchanged.
- **2026-10-20 (M4, initial view):** Window and interface options read indirect boolean ViewerPreferences values. Synthetic regressions cover true/false, direct/indirect preference dictionaries and save/reopen; malformed entries retain false defaults. Estimates unchanged.
- **2026-10-20 (M3, #3535):** Escape with a menu open closes the menu and keeps the text selection; the next Escape clears it, as before. One keypress used to do both. A synthetic UI regression checks it. Estimates unchanged.
- **2026-10-16 (M3, close prompt keyboard):** The "Save changes?" prompt opens with Save chosen (Enter saves, as before) and the arrow keys and Tab / Shift+Tab move the choice to Cancel or Don't save, shown with a focus ring; Enter or Space press the chosen button and Escape still cancels. Before, Enter always saved whatever was Tab-focused. Estimates unchanged.
@@ -405,6 +432,8 @@ Ranked; detail and the full milestone table in [docs/roadmap.md](docs/roadmap.md
- **2026-10-16 (M10, #1201 partial):** Lossless image export applies each component's Decode pair. Indexed values round and clip before palette lookup. Color-key masks keep raw samples. The existing 16-bit precision limit remains. JPEG and mask Decode, ICC transforms, and calibrated colors remain outside this fix. Estimates unchanged.
- **2026-10-16 (M3, #2739):** Wrapped revision buttons stay above Binding in Document Properties. A synthetic regression checks control bounds and opens a saved revision at two viewport widths. Estimates unchanged.
- **2026-10-19 (M7, tracked text):** Editable paragraphs and object labels distinguish repeated glyph tracking from word gaps in TJ arrays and separately positioned glyphs. Synthetic regressions cover character spacing, horizontal scaling, rotated baselines, larger word gaps, and rows of one-glyph words or cells (inferred tracking is capped at half an em, so `a b c` and digit or Y/N columns keep their spaces). Estimates unchanged.
+- **2026-10-16 (M9, #79):** a signature appearance that follows the named-layer convention (its /N draws one Form that holds and draws n1 and n3) shows the signature's real state: n1, n3 and n4 are redrawn in the display copy with the panel's icons and a caption in the interface language (Helvetica; else shaped in embedded Inter, or in a craft-fonts face for Arabic, Japanese and Telugu; else English, as Chinese always is). Exports, both print modes and the CLI's render show the redrawn state; saves never do. Every signature keeps its badge, since a document can clip or cover its own layers. Estimates unchanged.
+- **2026-10-16 (M9):** the page validation overlay moves to the widget's bottom-right corner as it lies on the page (so it turns with the page and the view) and takes a quarter of the widget's shorter side, at most 48 screen points, so it annotates the signer's artwork from a corner instead of covering the middle of it; a field too small for a legible mark keeps its outline, a rectangle the screen cannot place is not drawn at all, and the whole widget answers the pointer. Estimates unchanged.
- **2026-10-16 (M5, #2669, item 5):** The Comments panel groups replies by name and counts all page roots once per frame. Estimates unchanged.
- **2026-10-16 (M7, #2140):** Header & footer (and Bates numbering, which uses the same dialog) can shrink the page content so the header and footer don't cover it: the original content is scaled evenly into the band they leave free, centred across, also on rotated pages; Remove and Update take the scaling away, and margins that leave no room are refused. Dialog checkbox with a preview of the band, `shrink` on `doc_header_footer`, all catalogs. Annotations and added text and images are not moved yet. Estimates unchanged.
- **2026-10-20 (M14, Spanish catalog gaps):** `es.tsv` gains the 143 `(context, English)` keys the other catalogs carried and it was missing, so Spanish covers the whole bundled key union like Lithuanian and Vietnamese: calendar months and weekdays, the `certificate` context, X.509 key usages, signature-revision and digital-ID lines, password validation, eight plural messages, the combine-from-folder strings, the rendering and stale-file notices and the shortcut-spelled tooltips. Counts in `localization-parity.md` re-measured against the current union (`vi` restated against it for the same reason). Status stays `partial`: no translated help, and OS details stay outside the catalog. Estimates unchanged.
@@ -423,6 +452,7 @@ Ranked; detail and the full milestone table in [docs/roadmap.md](docs/roadmap.md
- **2026-10-14 (M12, reading colours, #2059):** Pending page backgrounds use the document's reading colour immediately, preventing white flashes while scrolling to uncached pages. A headless canvas regression covers three pending pages in every preset and a custom background. Estimates unchanged.
- **2026-10-15 (community, M6, #2608):** In Prepare a form the selected field moves with the arrow keys: a point per press, ten with Shift, as the object nudge and dragging it do. Each press is one undo step ("Change field properties"), and the keys no longer turn the page while a field is selected. Estimates unchanged.
- **2026-10-15 (M3, closable community card):** The ArtCraft community card on Home has a close button that hides it for the rest of the run; it returns on the next launch, and its links stay in the top bar's Discord button and the Help menu. A UI regression covers closing and the fresh-launch default. Estimates unchanged.
+- **2026-10-15 (M14, MSI install folder, #1139):** The Windows installer's welcome dialog has an "Install to" row with a native folder browser, starting on the folder chosen for the per-user or per-machine scope (the recorded one on an update). `test-msi.ps1` checks the dialog wiring: both Install buttons set the folder before the dialog closes, and Browse's OK and Cancel. Estimates unchanged.
- **2026-10-13 (community, M3, #1569 review):** Pixel-only Wayland wheel, wheel-tilt and continuous input use standalone moved events, so Ctrl zoom does not remain latched after the modifier is released (#991); vendored winit patch (13), with a policy test. Estimates unchanged.
- **2026-10-18 (M1, PR #1143 repair policy):** A live in-file reference resolves when its generation matches the xref row or a same-number header at that indexed offset. Neither-match and free slots remain null, including when old object bytes remain. Opening records bounded xref/header disagreements without parsing object bodies or expanding compact xref rows. Synthetic controls cover read order, clones, overlays, dictionary edits, full classic/packed saves and an independent reader of incremental output. **Correction to the 2026-10-15 note below:** its async-opening-test sentence was not evidenced by this COS change; no fresh async-opening or GUI validation is claimed. The full-reference stream-length recursion key is defensive hardening, not an independently isolated regression fix. Estimates unchanged.
- **2026-10-15 (M1, PR #1143 refresh):** COS reference lookups and full saves distinguish complete object references, so stale generations cannot expose replacement content. Snapshot restoration also keeps edits to objects with nonzero generations before incremental saves. Synthetic regressions cover caches, overlays, snapshots, stream lengths and classic/packed saves. Current upstream async-opening test corrections are included. Estimates unchanged.
@@ -553,6 +583,8 @@ Ranked; detail and the full milestone table in [docs/roadmap.md](docs/roadmap.md
Newest first: the date, what moved, and the new overall estimate.
- **2026-10-28 (M10, #1595):** Export to Markdown: `doc_export_office` with a `.md` or `.markdown` path writes CommonMark with GitHub pipe tables (headings, paragraphs with bold and italic, tables with their first row as the header, a rule between pages); text that Markdown would read as markup is escaped. Images, lists and links are not in the export's layout model and are left out. No menu item yet. Estimates unchanged.
+- **2026-10-12 (M10, `ocr.ocr-web`):** OCR in the browser, partly. The web zip carries the text recognition models in `models/` beside `index.html`; the first time Recognize Text is needed the web build downloads them (about 12 MB, with a spinner, an error and a retry). Pages are rendered on the page and read in Web Workers (up to two at once, so the page keeps responding), built with WebAssembly SIMD: 8.5 s a page instead of 20.5 s in wasmtime, still about 17× native. Where workers can't start, the page reads the pages itself. No automated browser test yet. Estimates unchanged.
+- **2026-10-12 (M10, `ocr.ocr-web`):** Web OCR shipped: reading scanned pages in Web Workers was checked by hand in a browser (4-page synthetic scan). Still no automated browser test, and a page reads about 17× slower than native.
- **2026-10-12 (M3, GNOME title bar, #553):** On GNOME's Wayland session, whose compositor draws no window frames (it offers no `zxdg_decoration_manager_v1`), PdfCraft no longer shows winit's fallback title bar: it turns the frame off and the tab strip becomes the header bar, as in GNOME's own apps. Minimize, maximize/restore and close are drawn in Adwaita's style, in the order and on the side GNOME's `button-layout` names (Fedora's default shows only close); the window's edges and corners resize it, and a hairline outlines it while it isn't maximized. Preferences ▸ Use system title bar (shown only there) gives the window back winit's frame at once, without a restart (part of #1001), and `PDFCRAFT_TITLEBAR=app|system` overrides the choice. KDE, Sway, Hyprland, COSMIC and X11 keep the frame their desktop draws. Not done: right-clicking the header bar doesn't open GNOME's window menu (egui can't ask for it), the window has no shadow or rounded corners, the resize edges lie just inside the window rather than outside it, and Windows still uses its system frame (the rest of #1001). Estimates unchanged.
- **2026-10-12 (M0, build label):** A local or patched build can carry a label, set at compile time with `PDFCRAFT_BUILD_LABEL`: `pdfcraft --version`, `pdfcraft-cli --version`, About and the log show `0.7.1 (titlebar)`, and `packaging/linux/package.sh` names the files `pdfcraft-0.7.1-titlebar-…` and makes the .rpm/.deb release `1.titlebar`, which upgrades over the release of the same version (and the next release over it). The version itself is unchanged, so the update check still compares it with published releases. Unlabelled builds are as before. Estimates unchanged.
- **2026-10-11 (M6, #1208):** Dropdown and list-box Field Properties expose the existing Left/Center/Right alignment picker. Existing alignment stays intact until changed; cancel, undo/redo and save/reopen are covered through the real UI without changing options, values or flags. Estimates unchanged.
@@ -788,11 +820,15 @@ Newest first: the date, what moved, and the new overall estimate.
| Date | Change | Summary |
|---|---|---|
+| 2026-11-08 | patch | M10 #6514/#636: retain main's public GDI Git revision (64e7afd4) to preserve downstream Rust type identity, update the internal PDF loader independently, and refresh the application dependency/lockfile. New-graph CI pending; estimates unchanged. |
+| 2026-11-08 | patch | M10 #6514: refresh the craft-print and winprint/GDI pins after #605 merged; retain the Direct2D crash fix and stream-test cleanup repairs, record single-page HUAWEI output with its diagnostic limits, and rerun CI for the new dependency graph. Estimates unchanged. |
+| 2026-11-07 | patch | M10 #6514: load Windows PDF print jobs on demand through a read-only file stream, avoiding StorageFile access denial, whole-file buffering and per-chunk async waits; approved dependencies retain the #5006 crash fix. Regression tests pass; physical output remains unqualified; estimates unchanged. |
| 2026-11-03 | patch | M5 #5850 review: indirect typewriter intent and composer edits preserve outer whitespace; movement regression commits by outside click; estimates unchanged. |
| 2026-11-03 | patch | M5 #5850: Enter adds Fill & Sign line breaks; outside clicks commit, Escape cancels, and saved multiline appearances retain their text and height; estimates unchanged. |
| 2026-11-01 | patch | M7 #5657: header/footer, watermark and background operations commit all selected pages together; later-page errors preserve marks, content, shared/inherited resources and pending edits; estimates unchanged. |
| 2026-10-28 | patch | M2, PR #4172: integrate main 5af10276 and retain both roadmap histories; viewer-only CJK and print/output font policies and estimates unchanged. |
| 2026-10-27 | minor | M10: OCR stages SHA-256-verified ONNX models after the upstream RTEN URL brownout; discovery prefers a complete ONNX pair per directory, falls back to a complete RTEN pair, and never mixes formats or directories; language/web limits and estimates unchanged. |
+| 2026-10-20 | minor | M9 #79 review, M2, M8: /ActualText that marks no glyph extracts where it paints, as far as it is visible; redaction strips /ActualText around paint it clips; named-layer recognition needs the layer form to draw n1 and n3. Estimates unchanged. |
| 2026-10-23 | minor | M8, #3205 follow-up: phone-pattern redaction includes the +39 country code on labelled Italian geographic numbers with a slash; dates, protocol identifiers and whole-run guards remain. Estimates unchanged. |
| 2026-10-23 | minor | M11: image downsampling measures physical resolution after page-local UserUnit scaling, including shared nested forms; synthetic measurement and optimization regressions. Estimates unchanged. |
| 2026-10-23 | minor | M10: Word table cells use the grid columns they span, including cells after a merged cell; synthetic export regression and CLI reproduction. Estimates unchanged. |
@@ -807,6 +843,8 @@ Newest first: the date, what moved, and the new overall estimate.
| 2026-10-18 | minor | M1, #1143: a live reference may match the xref generation or a same-number header at its indexed offset; neither-match and free slots remain null. Bounded repair diagnostics and synthetic cache, free-slot, edit and classic/packed save regressions; estimates unchanged. |
| 2026-10-18 | minor | M5, PR #1971: nested source `/Page` and `/Pages` dictionaries export as null without traversing page content or the page tree. Synthetic saved/reopened three-page regression retains unrelated metadata and aliases. FDF import semantics, copied-graph limits and estimates unchanged. |
| 2026-10-15 | minor | M5: budget retained FDF entries before cloning; discovery keeps lazy array owners and annotation positions, with alias/cache-eviction stress fixtures. Limits cover the copied graph; source parsing/page discovery retain existing COS/parser limits, with no total source-memory bound. FDF import semantics and estimates unchanged. |
+| 2026-10-16 | minor | M9 #79: named-layer signature appearances show the signature's real state in the display copy, exports and both print modes, never in saves; captions follow the interface language. Estimates unchanged. |
+| 2026-10-16 | minor | M9: the page validation overlay moves to the widget's bottom-right corner as it lies on the page and stops growing past 48 screen points, so it annotates the signer's artwork from a corner instead of covering the middle of it; a field under 32 screen points keeps its outline. Estimates unchanged. |
| 2026-10-15 | minor | M7: the Edit text caret is as tall as the row it is on in a region with several sizes; estimates unchanged. |
| 2026-10-18 | minor | M4, PR #1919 review: repeated page indices apply each rotation to the latest page-local value, preserving indirect/inherited angles. Synthetic adjacent/interleaved duplicates retain siblings and page contents through incremental and full saves. Estimates unchanged. |
| 2026-10-18 | minor | M3, #3149: page replacement cancels render demand collected for the previous geometry; all viewer raster upload paths reject empty or oversized textures before cache eviction. Synthetic regressions reproduce the reported 1880×2350 upload at a 2048 limit, retain cached images and unsaved edits, and resume bounded backdrops and tiles. Estimates unchanged. |
diff --git a/apps/pdfcraft-cli/src/commands.rs b/apps/pdfcraft-cli/src/commands.rs
index 9d0b2057f0..86b31bafd3 100644
--- a/apps/pdfcraft-cli/src/commands.rs
+++ b/apps/pdfcraft-cli/src/commands.rs
@@ -8,6 +8,9 @@ pub(crate) fn read(path: &str) -> Result>, String> {
std::fs::read(path).map(Arc::new).map_err(|e| format!("{path}: {e}"))
}
+/// `info FILE`: a JSON summary of the document as the app opens it (pages, fields, metadata, the
+/// standards it declares, and the notes about damage repaired while opening it), with none of
+/// its scripts run.
pub(crate) fn info(args: &[String]) -> Result<(), CliError> {
validate_options("info", args, INFO_OPTIONS)?;
let path = *positional(args, INFO_OPTIONS).first().ok_or("info: missing file")?;
@@ -18,24 +21,33 @@ pub(crate) fn info(args: &[String]) -> Result<(), CliError> {
let mut info = inspect(bytes.clone(), render_password.as_deref()).map_err(|e| e.to_string())?;
let pdf_pages = info.pages.len();
let acroform_fields = info.fields.len();
+ // The document as the app opens it: the notes about damage repaired while opening, which the
+ // app shows in Document Properties, and for a dynamic XFA form the laid-out pages and fields.
+ // Inspection runs none of the document's scripts: an XFA form's initialize and calculate
+ // scripts, which the app runs on opening, are left alone, as with JavaScript turned off.
+ let mut session = pdfcraft_engine::Session::new();
+ session.set_javascript(false);
+ let opened = session.open("info.pdf", None, bytes.clone(), password).ok().and_then(|id| session.get(id));
// Dynamic XFA forms: say what laying the template out gives (what the app shows).
- let xfa_layout = (info.xfa == Some(pdfcraft_render::Xfa::Dynamic))
- .then(|| {
- let mut s = pdfcraft_engine::Session::new();
- let id = s.open("info.pdf", None, bytes.clone(), password).ok()?;
- let d = s.get(id)?;
- d.xfa.as_ref().map(|x| {
- info = d.info.clone();
- // The in-memory layout is an appended revision, not the file being inspected.
- info.file_size = bytes.len();
- serde_json::json!({ "pages": x.pages, "fields": x.fields, "warnings": x.warnings })
- })
+ let xfa_layout = opened.filter(|_| info.xfa == Some(pdfcraft_render::Xfa::Dynamic)).and_then(|d| {
+ d.xfa.as_ref().map(|x| {
+ info = d.info.clone();
+ // The in-memory layout is an appended revision, not the file being inspected.
+ info.file_size = bytes.len();
+ serde_json::json!({ "pages": x.pages, "fields": x.fields, "warnings": x.warnings })
})
- .flatten();
- // What the document declares as a standard, read the way the Standards panel reads it, so
- // `info` and the app agree. A file that declares nothing leaves these null and empty.
- let declared =
- pdfcraft_cos::Document::open_with_password(bytes.clone(), password).map(|doc| pdfcraft_preflight::declared(&doc)).unwrap_or_default();
+ });
+ // What the document declares as a standard, as the Standards panel reads it, and the notes
+ // Document Properties shows, which include what the app repaired after reading the objects (a
+ // page tree rebuilt from the pages found by scanning), both from the session's own reading. A
+ // file the app cannot open is read once more for what the object reader declares and repaired.
+ // A file that declares nothing leaves the standards null and empty.
+ let (declared, repairs) = match opened {
+ Some(d) => (d.standards(), d.repair_log()),
+ None => pdfcraft_cos::Document::open_with_password(bytes.clone(), password)
+ .map(|cos| (pdfcraft_preflight::declared(&cos), cos.repair_log().to_vec()))
+ .unwrap_or_default(),
+ };
let json = serde_json::json!({
"file": path,
"pdf_version": info.pdf_version,
@@ -56,6 +68,7 @@ pub(crate) fn info(args: &[String]) -> Result<(), CliError> {
"custom_properties": info.custom.len(),
"page_labels": info.pages.iter().take(8).map(|p| p.label.clone()).collect::>(),
"warnings": info.warnings,
+ "repairs": repairs,
});
stdout_line(format_args!("{}", serde_json::to_string_pretty(&json).unwrap_or_default()))?;
Ok(())
@@ -366,8 +379,9 @@ pub(crate) fn render(args: &[String]) -> Result<(), CliError> {
Some("pam") => None,
_ => return Err(format!("render: --out {out}: use a .png, .jpg, .tif or .pam name").into()),
};
- // The app renders a display copy that draws comments missing their /AP streams; the CLI
- // must agree with it (and with independent viewers), while keeping the file it reads intact.
+ // The app renders a display copy that draws comments missing their /AP streams and the state
+ // of named-layer signatures (here with no trusted certificates); the CLI must agree with it
+ // (and with independent viewers), while keeping the file it reads intact.
let bytes = read(path)?;
let password = flag(args, "--password");
// The renderer takes only the user password of R2–R4 files; `Session::open` and the display
@@ -407,6 +421,12 @@ pub(crate) fn render(args: &[String]) -> Result<(), CliError> {
let _ =
writeln!(std::io::stderr().lock(), "warning: page {page}: a colour that could not be computed was painted in a fallback colour");
}
+ pdfcraft_render::RenderWarning::Type3WidthsMissing => {
+ let _ = writeln!(
+ std::io::stderr().lock(),
+ "warning: page {page}: a Type 3 font has no /Widths; its glyphs were spaced by the widths their glyph procedures give"
+ );
+ }
}
}
Ok(())
diff --git a/apps/pdfcraft-cli/tests/it/info_repairs.rs b/apps/pdfcraft-cli/tests/it/info_repairs.rs
new file mode 100644
index 0000000000..72e8bed1a3
--- /dev/null
+++ b/apps/pdfcraft-cli/tests/it/info_repairs.rs
@@ -0,0 +1,75 @@
+//! `info` lists the notes about damage repaired while opening, as the app shows them in Document
+//! Properties and as `doc_info` reports them in `repairs`: a rebuilt cross-reference index, and a
+//! page tree rebuilt from the pages found by scanning (a note the app adds after reading).
+
+use std::process::Command;
+
+const BIN: &str = env!("CARGO_BIN_EXE_pdfcraft-cli");
+
+/// A PDF with `pages` pages, each drawing a rectangle (a page found by scanning has content), and
+/// `catalog` as object 1; `startxref` points at its cross-reference table, or at `bad_startxref`.
+fn fixture(catalog: &str, pages: usize, bad_startxref: Option) -> Vec {
+ let content = "0 0 0 rg 10 10 40 20 re f";
+ let kids: String = (0..pages).map(|i| format!("{} 0 R ", 4 + i)).collect();
+ let mut objs = vec![
+ catalog.to_string(),
+ format!("<< /Type /Pages /Kids [{kids}] /Count {pages} >>"),
+ format!("<< /Length {} >>\nstream\n{content}\nendstream", content.len()),
+ ];
+ objs.extend((0..pages).map(|_| "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 120 60] /Contents 3 0 R >>".to_string()));
+ let mut out = b"%PDF-1.7\n".to_vec();
+ let mut offsets = Vec::new();
+ for (i, o) in objs.iter().enumerate() {
+ offsets.push(out.len());
+ out.extend_from_slice(format!("{} 0 obj\n{o}\nendobj\n", i + 1).as_bytes());
+ }
+ let xref = out.len();
+ out.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objs.len() + 1).as_bytes());
+ for off in &offsets {
+ out.extend_from_slice(format!("{off:010} 00000 n \n").as_bytes());
+ }
+ let start = bad_startxref.unwrap_or(xref);
+ out.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{start}\n%%EOF\n", objs.len() + 1).as_bytes());
+ out
+}
+
+const CATALOG: &str = "<< /Type /Catalog /Pages 2 0 R >>";
+
+fn info_of(bytes: &[u8], name: &str) -> serde_json::Value {
+ let dir = std::env::temp_dir().join(format!("pdfcraft-info-repairs-{}-{name}", std::process::id()));
+ std::fs::create_dir_all(&dir).unwrap();
+ let path = dir.join("f.pdf");
+ std::fs::write(&path, bytes).unwrap();
+ let out = Command::new(BIN).args(["info", path.to_str().unwrap()]).output().unwrap();
+ assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
+ let json = serde_json::from_slice(&out.stdout).expect("info prints JSON");
+ let _ = std::fs::remove_dir_all(&dir);
+ json
+}
+
+fn repairs(json: &serde_json::Value) -> Vec {
+ json["repairs"].as_array().unwrap_or_else(|| panic!("no repairs array: {json}")).iter().map(|l| l.as_str().unwrap().to_string()).collect()
+}
+
+#[test]
+fn info_lists_a_rebuilt_cross_reference_index() {
+ // `startxref` points into the middle of an object, so the index is rebuilt from the headers.
+ let json = info_of(&fixture(CATALOG, 1, Some(20)), "xref");
+ assert_eq!(json["pages"], serde_json::json!(1), "{json}");
+ let lines = repairs(&json);
+ assert!(lines.iter().any(|l| l.contains("rebuilt cross-reference index")), "{lines:?}");
+}
+
+#[test]
+fn info_lists_a_page_tree_the_app_rebuilt_by_scanning() {
+ // The catalog names a page tree object the file does not have (#1656).
+ let json = info_of(&fixture("<< /Type /Catalog /Pages 9 0 R >>", 2, None), "pagetree");
+ let lines = repairs(&json);
+ assert!(lines.iter().any(|l| l.contains("page tree is missing")), "{lines:?}");
+}
+
+#[test]
+fn info_lists_no_repairs_for_a_sound_file() {
+ let json = info_of(&fixture(CATALOG, 1, None), "sound");
+ assert_eq!(json["repairs"], serde_json::json!([]), "{json}");
+}
diff --git a/apps/pdfcraft-cli/tests/it/main.rs b/apps/pdfcraft-cli/tests/it/main.rs
index 30a6e25882..7b7292fe45 100644
--- a/apps/pdfcraft-cli/tests/it/main.rs
+++ b/apps/pdfcraft-cli/tests/it/main.rs
@@ -8,6 +8,7 @@ mod check;
mod edit;
mod extract;
mod help;
+mod info_repairs;
mod info_standards;
mod mcp_compact;
mod options;
diff --git a/apps/pdfcraft-cli/tests/it/xfa.rs b/apps/pdfcraft-cli/tests/it/xfa.rs
index 1b5ff7bc9d..4d5df67535 100644
--- a/apps/pdfcraft-cli/tests/it/xfa.rs
+++ b/apps/pdfcraft-cli/tests/it/xfa.rs
@@ -7,6 +7,11 @@ use std::sync::Arc;
const BIN: &str = env!("CARGO_BIN_EXE_pdfcraft-cli");
fn fixture(test: &str) -> PathBuf {
+ fixture_with(test, "")
+}
+
+/// The two-page form, with `event` inside its `name` field.
+fn fixture_with(test: &str, event: &str) -> PathBuf {
let xdp = r#"
@@ -15,11 +20,12 @@ fn fixture(test: &str) -> PathBuf {
First XFA page
- Ada
+ Ada {event}
Second XFA page
- "#;
+"#
+ .replace("{event}", event);
let objects = [
"<< /Type /Catalog /Pages 2 0 R /NeedsRendering true /AcroForm << /XFA 5 0 R /Fields [] >> >>".to_string(),
"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".into(),
@@ -67,6 +73,21 @@ fn info_reports_the_laid_out_pages_and_fields() {
assert_eq!(std::fs::read(path).unwrap(), original, "inspection must not write the layout to the input");
}
+/// `info` inspects an untrusted file: a form's initialize script, which the app runs on opening
+/// and which here would change the field's value, does not run.
+#[test]
+fn info_runs_none_of_the_forms_scripts() {
+ let script = r#" "#;
+ let path = fixture_with("info-script", script);
+ let output = Command::new(BIN).arg("info").arg(&path).output().unwrap();
+ success(&output);
+ let info: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
+ assert_eq!(info["xfa_layout"]["pages"], 2, "the form is still laid out: {info}");
+ let warnings = info["warnings"].as_array().unwrap();
+ assert!(!warnings.iter().any(|w| w.as_str().is_some_and(|w| w.contains("scripts changed it on opening"))), "{warnings:?}");
+ assert_eq!(info["repairs"], serde_json::json!([]), "{info}");
+}
+
#[test]
fn text_reads_the_layout_including_a_page_absent_from_the_placeholder() {
let path = fixture("text");
@@ -134,3 +155,21 @@ fn a_laid_out_form_keeps_the_original_copy_permissions() {
assert_eq!(info["file_size"], original.len());
assert_eq!(std::fs::read(path).unwrap(), original);
}
+
+/// A damaged dynamic XFA form: `info` lists the cross-reference index rebuilt while opening it,
+/// as Document Properties does after the form is laid out as one more revision.
+#[test]
+fn info_lists_the_repairs_of_a_laid_out_form() {
+ let path = fixture("info-damaged");
+ let bytes = std::fs::read(&path).unwrap();
+ let at = bytes.windows(10).rposition(|w| w == b"startxref\n").unwrap() + 10;
+ let mut damaged = bytes[..at].to_vec();
+ damaged.extend_from_slice(b"20\n%%EOF\n");
+ std::fs::write(&path, &damaged).unwrap();
+ let output = Command::new(BIN).arg("info").arg(&path).output().unwrap();
+ success(&output);
+ let info: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
+ assert_eq!(info["xfa_layout"]["pages"], 2, "the form is still laid out: {info}");
+ let repairs = info["repairs"].as_array().unwrap();
+ assert!(repairs.iter().any(|l| l.as_str().is_some_and(|l| l.contains("rebuilt cross-reference index"))), "{repairs:?}");
+}
diff --git a/apps/pdfcraft-ocr-worker/Cargo.toml b/apps/pdfcraft-ocr-worker/Cargo.toml
new file mode 100644
index 0000000000..7360c13440
--- /dev/null
+++ b/apps/pdfcraft-ocr-worker/Cargo.toml
@@ -0,0 +1,18 @@
+[package]
+name = "pdfcraft-ocr-worker"
+description = "PdfCraft in the browser: the Web Worker that recognises text (wasm32; trunk builds it with pdfcraft-web)"
+version.workspace = true
+edition.workspace = true
+license.workspace = true
+publish = false
+
+[lints]
+workspace = true
+
+[dependencies]
+pdfcraft-ocr = { workspace = true }
+
+[target.'cfg(target_arch = "wasm32")'.dependencies]
+wasm-bindgen = "0.2"
+js-sys = "0.3"
+web-sys = { version = "0.3", features = ["DedicatedWorkerGlobalScope", "MessageEvent"] }
diff --git a/apps/pdfcraft-ocr-worker/src/main.rs b/apps/pdfcraft-ocr-worker/src/main.rs
new file mode 100644
index 0000000000..a22099e27c
--- /dev/null
+++ b/apps/pdfcraft-ocr-worker/src/main.rs
@@ -0,0 +1,101 @@
+//! PdfCraft in the browser: the Web Worker that recognises text, so reading a scanned page doesn't
+//! stop the page responding and several pages are read at once. Trunk builds it alongside
+//! `pdfcraft-web` (see apps/pdfcraft-web/index.html); the page starts and feeds the workers
+//! (crates/ui-egui/src/workflows/ocr_ui.rs).
+//!
+//! Messages are plain objects with a `type`:
+//!
+//! - `ready` (to the page): the worker is listening; send the models now.
+//! - `models` (from the page): `{ detection, recognition }`, each a `Uint8Array` holding a model
+//! file. Answered with `loaded`, or `failed` with an `error`.
+//! - `page` (from the page): `{ id, width, height, pixels }`, the RGBA pixels of a rendered page
+//! as a `Uint8Array`. Answered with `lines` `{ id, lines }`, the recognised lines as
+//! `pdfcraft_ocr::lines_to_json` writes them, or `failed` `{ id, error }`.
+
+#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
+
+#[cfg(target_arch = "wasm32")]
+fn main() {
+ use wasm_bindgen::{JsCast, closure::Closure};
+
+ let Ok(scope) = js_sys::global().dyn_into::() else {
+ return;
+ };
+ let reply_to = scope.clone();
+ let mut ocr = None;
+ let on_message = Closure::::new(move |e: web_sys::MessageEvent| {
+ let _ = reply_to.post_message(&worker::handle(&mut ocr, &e.data()));
+ });
+ scope.set_onmessage(Some(on_message.as_ref().unchecked_ref()));
+ // The handler lives as long as the worker.
+ on_message.forget();
+ let _ = scope.post_message(&worker::message(&[("type", "ready".into())]));
+}
+
+#[cfg(not(target_arch = "wasm32"))]
+fn main() {
+ eprintln!("pdfcraft-ocr-worker runs in a browser: trunk builds it with pdfcraft-web");
+}
+
+#[cfg(target_arch = "wasm32")]
+mod worker {
+ use pdfcraft_ocr::Ocr;
+ use wasm_bindgen::{JsCast, JsValue};
+
+ /// The models are about 12 MB together.
+ const MAX_MODEL_BYTES: u32 = 64 << 20;
+ /// The renderer keeps pages far smaller; anything larger isn't a page.
+ const MAX_PIXEL_BYTES: u64 = 1 << 30;
+
+ pub fn message(fields: &[(&str, JsValue)]) -> JsValue {
+ let o = js_sys::Object::new();
+ for (k, v) in fields {
+ let _ = js_sys::Reflect::set(&o, &(*k).into(), v);
+ }
+ o.into()
+ }
+
+ /// Answer one message from the page.
+ pub fn handle(ocr: &mut Option, data: &JsValue) -> JsValue {
+ let get = |k: &str| js_sys::Reflect::get(data, &k.into()).unwrap_or(JsValue::UNDEFINED);
+ let id = get("id");
+ let reply = match get("type").as_string().as_deref() {
+ Some("models") => load(&get("detection"), &get("recognition")).map(|o| {
+ *ocr = Some(o);
+ message(&[("type", "loaded".into())])
+ }),
+ Some("page") => match ocr.as_ref() {
+ None => Err("the text recognition models aren't loaded".into()),
+ Some(o) => recognize(o, &get("width"), &get("height"), &get("pixels"))
+ .map(|lines| message(&[("type", "lines".into()), ("id", id.clone()), ("lines", lines.into())])),
+ },
+ _ => Err("unknown message".into()),
+ };
+ reply.unwrap_or_else(|error| message(&[("type", "failed".into()), ("id", id), ("error", error.into())]))
+ }
+
+ fn bytes(v: &JsValue, max: u64) -> Result, String> {
+ let a = v.dyn_ref::().ok_or("expected a Uint8Array")?;
+ if u64::from(a.length()) > max {
+ return Err(format!("{} bytes is too large", a.length()));
+ }
+ Ok(a.to_vec())
+ }
+
+ fn load(detection: &JsValue, recognition: &JsValue) -> Result {
+ let max = u64::from(MAX_MODEL_BYTES);
+ Ocr::from_bytes(bytes(detection, max)?, bytes(recognition, max)?).map_err(|e| e.to_string())
+ }
+
+ fn recognize(ocr: &Ocr, width: &JsValue, height: &JsValue, pixels: &JsValue) -> Result {
+ let side = |v: &JsValue| v.as_f64().filter(|v| v.fract() == 0.0 && (1.0..=f64::from(u32::MAX)).contains(v)).map(|v| v as u32);
+ let (Some(w), Some(h)) = (side(width), side(height)) else {
+ return Err("the page size is not a positive whole number".into());
+ };
+ let px = bytes(pixels, MAX_PIXEL_BYTES)?;
+ if u64::from(w).checked_mul(u64::from(h)).and_then(|n| n.checked_mul(4)) != Some(px.len() as u64) {
+ return Err("the pixels don't match the page size".into());
+ }
+ ocr.recognize(&px, w, h).map(|lines| pdfcraft_ocr::lines_to_json(&lines)).map_err(|e| e.to_string())
+ }
+}
diff --git a/apps/pdfcraft-web/Cargo.toml b/apps/pdfcraft-web/Cargo.toml
index 56e10c0c29..ad5b62229c 100644
--- a/apps/pdfcraft-web/Cargo.toml
+++ b/apps/pdfcraft-web/Cargo.toml
@@ -12,9 +12,12 @@ workspace = true
[dependencies]
pdfcraft-ui-egui = { workspace = true }
# The host messages (storytold/craft-libs): one contract and one bridge for the web builds.
-craft-web-host = { git = "https://github.com/storytold/craft-libs", rev = "2e2312ddaf21bc3d85cd3395d0955c7d239306f6", version = "0.1.0" }
+# The page command API (storytold/craft-libs#413): window.pdfcraft over the UI control channel.
+craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "fd5e2feff6ea25bed371a99cc732b3968d621505", version = "0.1.0" }
+craft-web-host = { git = "https://github.com/storytold/craft-libs", rev = "fd5e2feff6ea25bed371a99cc732b3968d621505", version = "0.1.0" }
eframe = { workspace = true, features = ["default_fonts", "glow", "persistence", "accesskit"] }
egui = { workspace = true, features = ["default_fonts", "monochrome_emoji_fonts"] }
+serde_json = { workspace = true }
[target.'cfg(target_arch = "wasm32")'.dependencies]
wasm-bindgen-futures = "0.4"
diff --git a/apps/pdfcraft-web/Trunk.toml b/apps/pdfcraft-web/Trunk.toml
index 563c2267c1..f03ccc6ea1 100644
--- a/apps/pdfcraft-web/Trunk.toml
+++ b/apps/pdfcraft-web/Trunk.toml
@@ -9,3 +9,10 @@ filehash = true
[serve]
addresses = ["127.0.0.1"]
port = 8766
+
+# Trunk leaves the OCR worker's files unhashed and unnamed in index.html: hash them and name the
+# worker for the page (xtask/src/web.rs).
+[[hooks]]
+stage = "post_build"
+command = "cargo"
+command_arguments = ["xtask", "web-worker-link"]
diff --git a/apps/pdfcraft-web/index.html b/apps/pdfcraft-web/index.html
index 46b3a25e21..f93bb0812d 100644
--- a/apps/pdfcraft-web/index.html
+++ b/apps/pdfcraft-web/index.html
@@ -5,6 +5,8 @@
PdfCraft
+
+
"#
+ )
+ };
+ let tpl = format!(
+ r#"
+{}{}{}
+{}
+{} {}
+ "#,
+ ready("sheet", "this.rawValue = xfa.layout.sheet(this) + 1"),
+ ready("sheets", "this.rawValue = xfa.layout.sheetCount()"),
+ ready("bare", "this.rawValue = xfa.layout.sheet(this)"),
+ rich("inDraw"),
+ rich("inCaption"),
+ rich("inValue"),
+ );
+ let (tpl, _) = parse(&tpl).unwrap();
+ assert_eq!(tpl.embedded.iter().map(String::as_str).collect::>(), ["inCaption", "inDraw", "inValue"]);
+ assert_eq!(tpl.page_roles, vec![("sheet".to_string(), PageRole::Number), ("sheets".to_string(), PageRole::Count)]);
+}
+
+/// An embedded sheet number is the page's own on every page, not a constant 1, and the sheet
+/// count is the number of pages.
+#[test]
+fn an_embedded_sheet_number_counts_the_pages() {
+ let span = |id: &str| format!(r##" "##);
+ let ready = |id: &str, script: &str| {
+ format!(
+ r#" "#
+ )
+ };
+ let tpl = format!(
+ r#"
+
+ {}{}
+ Sheet {} of {}
+
+first
+second
+ "#,
+ ready("sheet", "this.rawValue = xfa.layout.sheet(this)+1"),
+ ready("sheets", "this.rawValue = xfa.layout.sheetCount()"),
+ span("sheet"),
+ span("sheets")
+ );
+ let form = layout_xml(&tpl).unwrap();
+ assert_eq!(form.pages.len(), 2);
+ for (i, page) in form.pages.iter().enumerate() {
+ let shown = texts(page).join(" ");
+ assert!(shown.contains(&format!("Sheet {} of 2", i + 1)), "page {}: {shown}", i + 1);
+ }
+}
+
+/// A FormCalc script names the field `$`, and a field may have a ready script that does
+/// something else before the one that gives the sheet number: both still play the role.
+#[test]
+fn sheet_roles_are_read_from_formcalc_and_from_any_ready_script() {
+ let tpl = r#"
+
+
+
+
+
+
+
+
+ "#;
+ let (tpl, _) = parse(tpl).unwrap();
+ // FormCalc names methods case-insensitively, JavaScript does not.
+ assert_eq!(
+ tpl.page_roles,
+ vec![
+ ("fc".to_string(), PageRole::Number),
+ ("fcCase".to_string(), PageRole::Number),
+ ("fcCount".to_string(), PageRole::Count),
+ ("second".to_string(), PageRole::Number)
+ ]
+ );
+}
+
+/// The data paths of embedded fields are the ones scripts write: a page area's field under the
+/// area, as master pages lay it out; a field in a repeating row by name, whatever its instance.
+#[test]
+fn embedded_fields_are_known_by_the_data_paths_scripts_write() {
+ let span = |id: &str| format!(r##" "##);
+ let tpl = format!(
+ r#"
+
+
+ Stamp {}
+
+
+
+ Amount {}
+
+
+ "#,
+ span("stamp"),
+ span("amount")
+ );
+ let (tpl, _) = parse(&tpl).unwrap();
+ let names = |v: &[&str]| v.iter().map(|s| s.to_string()).collect::>();
+ assert_eq!(tpl.embedded_paths.iter().cloned().collect::>(), [names(&["form", "row", "amount"]), names(&["front", "stamp"])]);
+ assert!(crate::script::field_is_embedded(&tpl, "front[0].stamp[0]"), "a page area's field");
+ assert!(crate::script::field_is_embedded(&tpl, "form[0].row[3].amount[0]"), "any row");
+ assert!(!crate::script::field_is_embedded(&tpl, "form[0].plain[0]"));
+}
+
+/// Text embedding a field shows the value the data gives it: each row of a repeating subform
+/// its own row's, a page area's field the value scripts write under the area, a multi-select
+/// list its picks, a date in its display picture (XFA 3.3 p. 221) in every row; a row without
+/// data shows the template's default, not the first row's value.
+#[test]
+fn embedded_text_shows_each_instances_data() {
+ let span = |id: &str| format!(r##" "##);
+ let rich = |label: &str, id: &str| {
+ format!(r#"{label} {}
"#, span(id))
+ };
+ let xml = format!(
+ r#"
+
+
+
+ {}
+
+
+ none
+ date{{MM/DD/YYYY}}
+ {}
+ {}
+
+A B
+{}
+
+
+
+Paid
+ "#,
+ rich("Stamp", "stamp"),
+ rich("Amount", "amount"),
+ rich("Due", "due"),
+ rich("Picks", "picks")
+ );
+ let (tpl, _) = parse(&xml).unwrap();
+ let data = parse_datasets(&xml).unwrap();
+ let form = crate::layout::layout(&tpl, Some(&data)).unwrap();
+ let all: Vec = form.pages.iter().flat_map(texts).collect();
+ let joined = all.join(" | ");
+ for want in ["Stamp Paid", "Amount 10", "Amount 20", "Amount none", "Due 11/04/2026", "Due 12/25/2026", "Picks A"] {
+ assert!(joined.contains(want), "{want} in {joined}");
+ }
+ assert!(joined.contains('B'), "both picks: {joined}");
+}
+
#[test]
fn the_template_parses_with_fonts_captions_and_rich_text() {
let (tpl, warnings) = parse(&template(2)).unwrap();
@@ -188,6 +353,46 @@ fn the_template_parses_with_fonts_captions_and_rich_text() {
assert!(last.break_before_page);
}
+/// A page area that declares far more content areas than any real master keeps only the first
+/// 128, with a warning. `split_block` walks every content area of a page before starting a new
+/// one, re-scanning the unplaced items each time, so tens of thousands of them cost time
+/// quadratic in a splittable subform's paragraphs. Capping the count bounds that walk.
+#[test]
+fn a_page_area_keeps_at_most_a_hundred_and_twenty_eight_content_areas() {
+ let areas = (0..200).map(|i| format!("", i)).collect::();
+ let xml = format!(
+ r##"
+
+
+
+
+ {areas}
+
+
+
+
+"##
+ );
+ let (tpl, warnings) = parse(&xml).unwrap();
+ let ps = tpl.root.page_set.as_ref().unwrap();
+ assert_eq!(ps.areas[0].content.len(), 128, "the content areas are capped");
+ assert!(warnings.iter().any(|w| w.contains("content areas")), "a warning records the cap: {warnings:?}");
+ // Still said after a hundred other warnings (CodeRabbit review on #5844): images that can't
+ // be decoded, parsed before the page set, fill the warnings' shared cap first.
+ let bad = "!!! ".repeat(120);
+ let crowded = xml.replace("", &format!("{bad}"));
+ let (_, warnings) = parse(&crowded).unwrap();
+ assert!(warnings.len() > 100, "the other warnings came first: {}", warnings.len());
+ assert!(warnings.iter().any(|w| w.contains("content areas")), "the cap is still recorded");
+ // Many capped page areas say it once, found without scanning every warning (it comes first).
+ let page_area = |n: usize| format!(r#" {areas} "#);
+ let many: String = (0..50).map(page_area).collect();
+ let crowded = crowded.replacen(&page_area(0).replace("p0", "front"), &many, 1);
+ let (_, warnings) = parse(&crowded).unwrap();
+ assert_eq!(warnings.iter().filter(|w| w.contains("content areas")).count(), 1, "said once");
+ assert!(warnings[0].contains("content areas"), "kept first: {:?}", warnings.first());
+}
+
#[test]
fn rich_text_max_length_reaches_the_field_and_layout() {
for (attribute, expected) in [
@@ -678,6 +883,98 @@ fn empty_repeating_subforms_spend_the_layout_budget() {
assert!(layout_xml(&tpl).is_ok());
}
+#[test]
+fn a_block_split_across_very_many_pages_spends_the_layout_budget() {
+ // One-point content areas slice a flowed subform's paragraphs one line to a page, so the
+ // block is split across hundreds of pages; split_block rescans the still-unplaced
+ // paragraphs once per page, which is quadratic in their number. Fewer paragraphs than this
+ // lay out (188 pages here), so the page limit does not catch it; the rescans spend the
+ // work budget instead.
+ let areas: String = (0..128).map(|i| format!("")).collect();
+ let paras: String = (0..2500).map(|i| format!("Paragraph number {i} with a few words to fill a line.
")).collect();
+ let tpl = format!(
+ "\
+ {areas} \
+ \
+ {paras} \
+ "
+ );
+ match layout_xml(&tpl) {
+ // It says what ran out, not that the form is nested too deeply (CodeRabbit review on #5844).
+ Err(XfaError::TooLarge(m)) => assert!(m.contains("split across"), "{m}"),
+ other => panic!("a block split across very many pages must be refused: {other:?}"),
+ }
+}
+
+#[test]
+fn large_text_drawn_in_many_instances_spends_the_draw_budget() {
+ // A draw whose text overflows its fixed height is re-measured up to six times to shrink it,
+ // and a repeating subform draws it once per instance. Large text drawn in many instances
+ // used to cost one full text layout per instance per pass, for seconds of work on a small
+ // file; each pass now counts its characters against the draw budget.
+ let words = "word ".repeat(4000); // 20,000 characters
+ let draw = format!("{words} ");
+ let many =
+ format!("{draw} ");
+ assert!(matches!(layout_xml(&many), Err(XfaError::TooLarge(_))), "large text in many instances must be refused");
+ // One copy of the same draw lays out: the budget does not reject an ordinary form.
+ let one = format!("{draw} ");
+ assert!(layout_xml(&one).is_ok(), "a single large draw must lay out");
+}
+
+/// The draw budget counts the values of embedded fields as well as the text around them: a short
+/// text embedding a long value, drawn in many instances, is as much work as the value written out
+/// each time (CodeRabbit review on #5852).
+#[test]
+fn embedded_values_drawn_in_many_instances_spend_the_draw_budget() {
+ let value = "word ".repeat(4000); // 20,000 characters
+ let span = r##" "##;
+ let draw = format!(
+ r#"x {span}
"#
+ );
+ let field = format!(r#"{value} "#);
+ let many =
+ format!(r#"{field} {draw} "#);
+ assert!(matches!(layout_xml(&many), Err(XfaError::TooLarge(_))), "a long embedded value in many instances must be refused");
+ // One copy lays out: the budget does not reject an ordinary form.
+ let one = format!(r#"{field}{draw} "#);
+ assert!(layout_xml(&one).is_ok(), "a single draw embedding a long value must lay out");
+}
+
+/// The last layout pass of a draw counts against the budget too: a draw that fits is measured
+/// once and laid out once, each pass expanding its embedded value, and when the form's last draw
+/// crosses the budget in that final pass it is still refused (CodeRabbit review on #5852).
+#[test]
+fn the_draw_that_crosses_the_budget_in_its_last_pass_is_refused() {
+ // 15,000 characters: with the 1 MiB test budget, the tenth such draw crosses it during its
+ // final layout pass, after every check before that pass has passed.
+ let value = "word ".repeat(3000);
+ let span = r##" "##;
+ let form = |n: usize| {
+ format!(
+ r#"{value} x {span}
"#
+ )
+ };
+ assert!(layout_xml(&form(9)).is_ok());
+ assert!(matches!(layout_xml(&form(10)), Err(XfaError::TooLarge(_))), "the draw crossing the budget in its last pass must be refused");
+}
+
+/// Once a fit pass spends the budget, no more passes are made: a draw that doesn't fit and embeds
+/// a long value is measured once, not seven times, before it is refused (CodeRabbit review on
+/// #5852).
+#[test]
+fn fit_passes_stop_once_the_draw_budget_is_spent() {
+ let value = "word ".repeat(text::MAX_EMBEDDED / 5 + 1000);
+ let span = r##" "##;
+ let tpl = format!(
+ r#"{value} x {span}
"#
+ );
+ crate::layout::EMBED_COPIED.with(|c| c.set(0));
+ assert!(matches!(layout_xml(&tpl), Err(XfaError::TooLarge(_))));
+ let copied = crate::layout::EMBED_COPIED.with(|c| c.get());
+ assert!(copied <= 2 * text::MAX_EMBEDDED as u64, "{copied} bytes copied: more passes after the budget was spent");
+}
+
#[test]
fn a_packet_stream_listed_many_times_is_read_once() {
let mut doc = Document::open(Arc::new(shell(" "))).unwrap();
@@ -2802,6 +3099,20 @@ fn a_flowed_subform_is_as_tall_as_its_content_whatever_its_minimum_height() {
assert!((top("") - flowed - (216.0 - 14.4)).abs() < 0.01, "{} against {flowed}", top(""));
}
+#[test]
+fn a_caption_beside_a_check_box_wraps_in_its_reserve() {
+ // A 7.5in check box whose right-hand caption reserves 6.5in: two lines of text, not one or
+ // two words to a line in the 1in the box keeps. The field after it follows directly.
+ let words = "Applicant does not authorize the office to permit a participating office access to the application as filed. ".repeat(2);
+ let body = format!(
+ r#"{words} "#
+ );
+ let form = layout_xml(&one_area_form(r#"layout="tb""#, &body)).unwrap();
+ let w = widgets(&form.pages[0]);
+ let gap = w[1].rect.y - w[0].rect.y;
+ assert!(gap < 72.0, "the check box took {gap}pt");
+}
+
#[test]
fn the_form_packet_restores_a_caption_a_script_changed() {
let body = r#"Show Bar "#;
@@ -3957,7 +4268,12 @@ fn embedded_values_are_copied_out_only_as_far_as_the_budget() {
"#
);
crate::layout::EMBED_COPIED.with(|c| c.set(0));
- layout_xml(&tpl).unwrap();
+ // The draw budget counts embedded values too (1 MiB in tests), so it may stop the draw
+ // before its last pass; either way no more than this is copied out.
+ match layout_xml(&tpl) {
+ Ok(_) | Err(XfaError::TooLarge(_)) => {}
+ Err(e) => panic!("{e:?}"),
+ }
let copied = crate::layout::EMBED_COPIED.with(|c| c.get());
// The draw is measured at most seven times before it is laid out once.
assert!(copied <= 8 * text::MAX_EMBEDDED as u64 + 8 * 4 * 201, "{copied} bytes of embedded values copied");
@@ -4587,3 +4903,126 @@ fn a_template_inside_the_data_is_not_the_form() {
let real = " ";
assert_eq!(parse(real).unwrap().0.root.common.name.as_deref(), Some("form1"));
}
+
+/// A multi-select choice list is bound to a data group of `value` elements, one per pick, and its
+/// value is theirs joined by newlines (XFA 3.3 p. 198). New picks replace the group's `value`
+/// elements, values off the list included, as Acrobat discards them (p. 199): the group was left
+/// as it was, so the old picks came back on reading, in the datasets and in the scripts' data.
+#[test]
+fn a_multi_select_lists_data_group_takes_its_new_picks() {
+ let shell =
+ crate::fixtures::static_shell("rye barley wheat ");
+ let mut doc = Document::open(Arc::new(shell)).unwrap();
+ let path = som_to_path("form1[0].page1[0].grains[0]");
+ assert!(write_data_value(&mut doc, &path, "wheat\nmillet & oats").unwrap().written);
+ let data = crate::script::data_of(&doc).unwrap();
+ assert_eq!(data.value_at(&path).as_deref(), Some("wheat\nmillet & oats"));
+ assert_eq!(data.count(&path, "value"), 2, "one value element per pick");
+ assert!(!write_data_value(&mut doc, &path, "wheat\nmillet & oats").unwrap().written, "the same picks change nothing");
+ assert!(write_data_value(&mut doc, &path, "").unwrap().written);
+ assert_eq!(crate::script::data_of(&doc).unwrap().value_at(&path).as_deref(), Some(""), "nothing picked");
+ // Emptied, the group is marked as one (XFA 3.3 p. 150), so it is still written as picks.
+ let xdp = crate::read_packets(&doc).unwrap().unwrap().xdp;
+ assert!(xdp.contains(" "), "{xdp}");
+ assert!(
+ write_data_value(
+ &mut doc,
+ &path,
+ "rye
+millet"
+ )
+ .unwrap()
+ .written
+ );
+ assert_eq!(crate::script::data_of(&doc).unwrap().count(&path, "value"), 2, "picks again, not text");
+ // A pick split or led by a comment is read whole: the same pick is no change, and clearing
+ // a pick that reads as empty through its first segment alone still clears it.
+ let commented =
+ crate::fixtures::static_shell("rye wheat ");
+ let mut doc = Document::open(Arc::new(commented)).unwrap();
+ assert!(
+ !write_data_value(
+ &mut doc,
+ &path,
+ "rye
+wheat"
+ )
+ .unwrap()
+ .written,
+ "the same picks, read past the comments"
+ );
+ assert_eq!(
+ crate::script::data_of(&doc).unwrap().value_at(&path).as_deref(),
+ Some(
+ "rye
+wheat"
+ ),
+ "and read back without them"
+ );
+ assert!(write_data_value(&mut doc, &path, "").unwrap().written, "cleared");
+ assert_eq!(crate::script::data_of(&doc).unwrap().count(&path, "value"), 0);
+ // Where `xfa` names another namespace and `pcxfa` is taken too, the marker's prefix is a free
+ // one, declared on the group, so no attribute in scope changes meaning.
+ let shadowed = crate::fixtures::static_shell(
+ "rye ",
+ );
+ let mut doc = Document::open(Arc::new(shadowed)).unwrap();
+ assert!(write_data_value(&mut doc, &path, "").unwrap().written);
+ let xdp = crate::read_packets(&doc).unwrap().unwrap().xdp;
+ assert!(xdp.contains("xmlns:pcxfa1=\"http://www.xfa.org/schema/xfa-data/1.0/\" pcxfa1:dataNode=\"dataGroup\""), "{xdp}");
+ assert!(xdp.contains("xmlns:pcxfa=\"urn:taken\" pcxfa:note=\"x\""), "the taken prefix keeps its namespace: {xdp}");
+ // With every candidate prefix taken, no marker can be written: the group keeps its pick
+ // and the skip is reported, rather than emptied into what would load as a data value.
+ let taken: String = (0..16).map(|i| if i == 0 { " xmlns:pcxfa=\"urn:t\"".to_string() } else { format!(" xmlns:pcxfa{i}=\"urn:t\"") }).collect();
+ let crowded =
+ crate::fixtures::static_shell(&format!("rye "));
+ let mut doc = Document::open(Arc::new(crowded)).unwrap();
+ let r = write_data_value(&mut doc, &path, "").unwrap();
+ assert!(!r.written && r.warnings.iter().any(|w| w.contains("structured content")), "{:?}", r.warnings);
+ assert_eq!(crate::script::data_of(&doc).unwrap().value_at(&path).as_deref(), Some("rye"));
+ // One `value` whose text holds a line break is one pick, not the two it would join to.
+ let one = crate::fixtures::static_shell(
+ "one
+two ",
+ );
+ let mut doc = Document::open(Arc::new(one)).unwrap();
+ assert!(
+ write_data_value(
+ &mut doc, &path, "one
+two"
+ )
+ .unwrap()
+ .written,
+ "two picks replace the one"
+ );
+ assert_eq!(crate::script::data_of(&doc).unwrap().count(&path, "value"), 2);
+ // The in-memory data, which scripts read before the packet is written, follows the same rule.
+ let mut tree = crate::script::data_of(
+ &Document::open(Arc::new(crate::fixtures::static_shell("rye "))).unwrap(),
+ )
+ .unwrap();
+ tree.apply(&DataOp::Value { path: path.clone(), text: "millet\nwheat".into() });
+ assert_eq!(tree.value_at(&path).as_deref(), Some("millet\nwheat"));
+ // Emptied in memory, the group still takes picks, not text.
+ tree.apply(&DataOp::Value { path: path.clone(), text: String::new() });
+ assert_eq!((tree.count(&path, "value"), tree.value_at(&path).as_deref()), (0, Some("")));
+ tree.apply(&DataOp::Value { path: path.clone(), text: "rye\nmillet".into() });
+ assert_eq!((tree.count(&path, "value"), tree.text_at(&path)), (2, Some("")), "picks again, not text");
+ assert_eq!(tree.value_at(&path).as_deref(), Some("rye\nmillet"));
+ let tree_of = |data: &str| crate::script::data_of(&Document::open(Arc::new(crate::fixtures::static_shell(data))).unwrap()).unwrap();
+ // A group read emptied, as the packet writer marks it, takes picks the same way.
+ let mut tree = tree_of(" ");
+ tree.apply(&DataOp::Value { path: path.clone(), text: "rye\nmillet".into() });
+ assert_eq!(tree.count(&path, "value"), 2);
+ // A node holding anything but `value` leaves is not a list's picks: it is left as it was,
+ // as the packet writer leaves it (and reports the skip).
+ for structured in [
+ "rye x ",
+ "rye ",
+ ] {
+ let mut tree = tree_of(structured);
+ let before = tree.clone();
+ tree.apply(&DataOp::Value { path: path.clone(), text: "millet".into() });
+ assert_eq!(tree, before, "{structured}");
+ }
+}
diff --git a/crates/xfdf/Cargo.toml b/crates/xfdf/Cargo.toml
index f868c95719..d82e75394e 100644
--- a/crates/xfdf/Cargo.toml
+++ b/crates/xfdf/Cargo.toml
@@ -14,4 +14,8 @@ pdfcraft-annot = { workspace = true }
pdfcraft-forms = { workspace = true }
pdfcraft-model = { workspace = true }
roxmltree = "0.21"
+base64 = "0.23"
thiserror = { workspace = true }
+
+[dev-dependencies]
+proptest = { workspace = true }
diff --git a/crates/xfdf/README.md b/crates/xfdf/README.md
index d286a457c3..0c823c2ee0 100644
--- a/crates/xfdf/README.md
+++ b/crates/xfdf/README.md
@@ -14,9 +14,30 @@ let report = import(&mut doc, &bytes)?; // XFDF, FDF, XML, CSV o
name, author, subject, dates, flags, colours, opacity, width, icon, quads, line ends, ink,
default appearance, callouts (`callout`, `fringe`, `intent`, `head`), pop-ups and reply threads
(`inreplyto`); field values nested by name, with text preserved across XML comments and processing instructions.
+ Formatting travels both ways as XFDF 3.0 names it: rich text (``, the `/RC`
+ XHTML as markup; plain text in it is the comment's text), default style (``),
+ border width, style and dash pattern (`width`, `style`, `dashes`; also from an older `/Border`
+ array), cloudy borders (`style="cloudy"`, `intensity`), `rotation`, `justification` (free text
+ `left`/`centered`/`right`, redaction `0`–`2`), `fringe` (`/RD`) on every type, line leaders and
+ captions (`leaderLength`, `leaderExtend`, `leader-offset`, `caption`, `caption-style`,
+ `caption-offset-h`/`-v`), the caret `symbol` and redaction `overlay-text`/`overlay-text-repeat`.
+ The intent (`/IT`) is written as both `intent` and `IT`, and either is read.
+- **Appearances** (``, `appearance.rs`): a stamp's `/AP`, as XFDF 3.0 defines it for
+ stamps, base 64 of the dictionary written as `DICT`/`STREAM`/`ARRAY`/`NAME`/`INT`/`FIXED`/`BOOL`/
+ `STRING`/`NULL` elements with stream data in `DATA` (XFDF 3.0 "Stream encoding": `filtered`/`ascii`
+ or `raw`/`hex`), the shape XFDF files from other tools carry. Copy and paste carries every
+ comment's appearance but a redaction mark's, which PdfCraft always draws and import never
+ reads. Import keeps an appearance it can read and otherwise draws the comment and records the reason in
+ `Report::skipped` (the engine puts it in the repair log); it refuses one over 16 MiB, 64 MiB per
+ import, 64 nesting levels or 100,000 values. Export leaves out one past those limits or whose
+ rect has no area, and stops at the 64 MiB an import reads; where `/AS` selects one of several
+ states, the selected stream is written (and import, with no `/AS` in XFDF, refuses a normal
+ appearance of several states). Import and FDF import are all or nothing: on an error the
+ document is left as it was.
- **FDF**: fields (with `/Kids` hierarchies) and indirect comments. Nested annotation values
- are copied under FDF object numbers; shared references and cycles remain shared. Document
- links and appearances are excluded. Source `/Page` and `/Pages` dictionaries become null
+ are copied under FDF object numbers; shared references and cycles remain shared. A stamp's appearance
+ (`/AP`, with the forms and images it draws) is copied, as in XFDF, and an `/AP` in the file comes
+ back on import as objects of the document (a stream shared by several comments once); document links are excluded. Source `/Page` and `/Pages` dictionaries become null
at every copy depth, so nested destination actions cannot carry the source page tree or content.
Type names may be indirect; lookup checks each reference generation, is iterative, stops at
cycles and refuses chains beyond
@@ -28,7 +49,9 @@ let report = import(&mut doc, &bytes)?; // XFDF, FDF, XML, CSV o
levels or a conservative 64 MiB serialization budget instead of exporting partial data.
These are copied-graph limits: source parsing and page discovery retain their existing
COS/parser limits, with no total source-memory bound. Unknown indirect streams retain their
- encoded bytes. FDF import semantics are unchanged.
+ encoded bytes. FDF import copies a comment's streams only when the comment lands on a page, and
+ refuses the file (nothing imported) when its comments expand past 1,000,000 values or 64 MiB, or
+ nest more than 256 levels, rather than import part of an appearance.
- **Form data**: Acrobat's XML (`xfdf:original` keeps names that aren't XML names), CSV and
tab-delimited text (a row of names, a row of values).
@@ -44,7 +67,7 @@ tables remains heuristic. Both write a cell that a spreadsheet would run as a fo
or `+` or `-` when it isn't a plain number) with a leading `'`; CSV import takes off the `'` that
export added, so exported data imports back unchanged.
-Import replaces comments with the same `/NM` (and drops the replaced comment's pop-up), draws
-appearances PdfCraft can draw, and sets values through the form's own checks (formats,
+Import replaces comments with the same `/NM` (and drops the replaced comment's pop-up), keeps the
+appearance the file carries or draws one where PdfCraft can, and sets values through the form's own checks (formats,
validation, recalculation); read-only fields take imported values, as in Acrobat. XML is read
with `roxmltree`.
diff --git a/crates/xfdf/src/appearance.rs b/crates/xfdf/src/appearance.rs
new file mode 100644
index 0000000000..3690a19f42
--- /dev/null
+++ b/crates/xfdf/src/appearance.rs
@@ -0,0 +1,377 @@
+//! A comment's appearance dictionary (`/AP`) in XFDF.
+//!
+//! ISO 19444-1 (XFDF 3.0, "appearance") carries a stamp's `/AP` as a base 64 encoded string. What
+//! the string holds is the dictionary written as XML, one element per PDF object: `DICT`, `STREAM`,
+//! `ARRAY`, `NAME`, `INT`, `FIXED` (a real number), `BOOL`, `STRING` and `NULL`, each with its
+//! dictionary key in `KEY` and a simple value in `VAL`; a stream's data is a `DATA` element whose
+//! `MODE` and `ENCODING` follow XFDF 3.0 "Stream encoding" (`filtered`/`ascii` for short printable
+//! data, `raw`/`hex` otherwise). That is what the XFDF files in the wild hold (for example the
+//! stamps attached to PDFBOX-4437 and PDFBOX-4478). Indirect objects are written in place, so the
+//! XML is self-contained.
+//!
+//! Both directions are bounded: the decoded XML, the stream data, the nesting and the number of
+//! values. Anything unreadable makes the whole appearance unusable; the caller then records it and
+//! draws the comment from its other entries.
+
+use base64::Engine as _;
+
+use super::common::{check_form_xml_depth, esc, parse_form_xml};
+use super::{Dict, Document, ObjRef, Object, PdfString};
+
+/// At most this much decoded XML in one appearance (and at most this much XML is written for one).
+pub(crate) const MAX_APPEARANCE_BYTES: usize = 16 << 20;
+/// At most this much appearance data (decoded XML) in one import, over all of its comments.
+pub(crate) const MAX_IMPORT_APPEARANCE_BYTES: usize = 64 << 20;
+/// How deeply objects may nest inside one appearance.
+const MAX_NESTING: usize = 64;
+/// How many PDF values one appearance may hold.
+const MAX_VALUES: usize = 100_000;
+/// XFDF 3.0 "Stream encoding": data shorter than this that is all printable ASCII is written as it
+/// is (`filtered`/`ascii`); everything else as hexadecimal (`raw`/`hex`).
+const ASCII_DATA_LIMIT: usize = 4096;
+
+/// The base 64 `` text for annotation `d`'s appearance dictionary, or `None` when it
+/// has no normal appearance stream or is past the limits (the comment is then exported without
+/// one).
+///
+/// XFDF has no appearance state (`/AS`), so where `/N`, `/R` or `/D` holds one stream per state
+/// only the selected state's stream is written (ISO 32000-2 §12.5.5: `/AS` picks it); a normal
+/// appearance with no selected stream has nothing to draw and nothing is written.
+///
+/// `budget` is what the export may still write (decoded XML), shared by all of its comments, as
+/// import reads at most [`MAX_IMPORT_APPEARANCE_BYTES`]: an appearance past it is left out rather
+/// than written for import to skip. It is charged for what is written.
+pub(crate) fn encode(doc: &Document, d: &Dict, budget: &mut usize) -> Option {
+ if !has_appearance(doc, d) {
+ return None;
+ }
+ let ap = d.get(b"AP").map(|a| doc.resolve(a))?;
+ let mut ap = ap.as_dict()?.clone();
+ let state = d.get(b"AS").and_then(|s| doc.resolve(s).as_name().map(<[u8]>::to_vec));
+ for key in [b"N".as_slice(), b"R", b"D"] {
+ let Some(entry) = ap.get(key).map(|e| doc.resolve(e)) else { continue };
+ let Object::Dict(states) = entry.as_ref() else { continue };
+ match state.as_deref().and_then(|s| states.get(s)).cloned() {
+ Some(selected) => ap.set(key.to_vec(), selected),
+ None if key == b"N" => return None,
+ None => {
+ ap.remove(key);
+ }
+ }
+ }
+ let limit = MAX_APPEARANCE_BYTES.min(*budget);
+ let mut writer = Writer { doc, out: String::new(), values: MAX_VALUES, path: Vec::new(), limit };
+ writer.dict(Some(b"AP"), &ap, 0)?;
+ // The checks while writing leave room for the closing tags and line breaks: the finished XML
+ // must fit what the reader accepts, or the comment would arrive without its appearance.
+ if writer.out.len() > limit {
+ return None;
+ }
+ *budget = budget.saturating_sub(writer.out.len());
+ let b64 = base64::engine::general_purpose::STANDARD.encode(writer.out.as_bytes());
+ // Line breaks every 76 characters, as base 64 text usually has them; the reader skips them.
+ let mut wrapped = String::with_capacity(b64.len() + b64.len() / 76 + 1);
+ for (i, c) in b64.chars().enumerate() {
+ if i > 0 && i % 76 == 0 {
+ wrapped.push('\n');
+ }
+ wrapped.push(c);
+ }
+ Some(wrapped)
+}
+
+struct Writer<'a> {
+ doc: &'a Document,
+ out: String,
+ values: usize,
+ /// The references being written, so a reference back to one of them ends the cycle.
+ path: Vec,
+ /// At most this much XML.
+ limit: usize,
+}
+
+impl Writer<'_> {
+ fn key_attr(key: Option<&[u8]>) -> String {
+ key.map(|k| format!(" KEY=\"{}\"", esc(&pdfcraft_forms::name_text(k)))).unwrap_or_default()
+ }
+
+ fn spend(&mut self, depth: usize) -> Option<()> {
+ if depth > MAX_NESTING || self.out.len() > self.limit {
+ return None;
+ }
+ self.values = self.values.checked_sub(1)?;
+ Some(())
+ }
+
+ fn dict(&mut self, key: Option<&[u8]>, d: &Dict, depth: usize) -> Option<()> {
+ self.spend(depth)?;
+ self.out.push_str(&format!("\n", Self::key_attr(key)));
+ for (k, v) in d.iter() {
+ self.value(Some(k), v, depth + 1)?;
+ }
+ self.out.push_str(" \n");
+ Some(())
+ }
+
+ fn value(&mut self, key: Option<&[u8]>, o: &Object, depth: usize) -> Option<()> {
+ self.spend(depth)?;
+ let k = Self::key_attr(key);
+ match o {
+ Object::Ref(r) => {
+ if self.path.contains(r) {
+ // A cycle: the object is already being written further up.
+ self.out.push_str(&format!(" \n"));
+ return Some(());
+ }
+ self.path.push(*r);
+ let target = self.doc.get(*r);
+ let written = self.value(key, &target, depth + 1);
+ self.path.pop();
+ written?;
+ }
+ Object::Null => self.out.push_str(&format!(" \n")),
+ Object::Bool(b) => self.out.push_str(&format!("\n")),
+ Object::Int(i) => self.out.push_str(&format!("\n")),
+ // Rust prints the shortest decimal that reads back as the same number, never with an
+ // exponent; a non-finite number (which PDF can't hold) is written as 0.
+ Object::Real(r) => self.out.push_str(&format!("\n", if r.is_finite() { *r } else { 0.0 })),
+ Object::Name(n) => self.out.push_str(&format!("\n", esc(&pdfcraft_forms::name_text(n)))),
+ Object::String(s) => match std::str::from_utf8(&s.bytes) {
+ // Text XML can hold as it is (`esc` would drop other control characters).
+ Ok(t) if t.chars().all(|c| !(c < ' ' && !matches!(c, '\t' | '\n' | '\r')) && c != '\u{FFFE}' && c != '\u{FFFF}') => {
+ self.out.push_str(&format!("\n", esc(t)));
+ }
+ _ => self.out.push_str(&format!("\n", hex_of(&s.bytes, false))),
+ },
+ Object::Array(a) => {
+ self.out.push_str(&format!("\n"));
+ for v in a {
+ self.value(None, v, depth + 1)?;
+ }
+ self.out.push_str(" \n");
+ }
+ // A page (or the page tree) reached from the appearance is the source document's, not
+ // the comment's: written in place it would carry every page along.
+ // `/Type` may itself be a reference (`resolve` follows a bounded number of them).
+ Object::Dict(d) if d.get(b"Type").is_some_and(|t| matches!(self.doc.resolve(t).as_name(), Some(b"Page" | b"Pages"))) => {
+ self.out.push_str(&format!(" \n"));
+ }
+ Object::Dict(d) => self.dict(key, d, depth)?,
+ Object::Stream(s) => {
+ // XFDF 3.0 counts a carriage return as printable, but XML reads one, alone or before
+ // a line feed, as a line feed (XML 1.0 §2.11): data holding one is written as
+ // hexadecimal so it comes back byte for byte (the 4 KiB rule "is not a rule").
+ let printable = s.raw.iter().all(|&b| (b > 32 && b < 127) || b == b'\n');
+ let ascii = s.raw.len() < ASCII_DATA_LIMIT && printable && !s.dict.contains(b"Filter");
+ // The data, in the encoding it is written in, must fit what is left of the budget
+ // (as text it is at least its own length; the finished XML is checked again).
+ let size = if ascii { s.raw.len() } else { s.raw.len().saturating_mul(2) };
+ if size.saturating_add(self.out.len()) > self.limit {
+ return None;
+ }
+ self.out.push_str(&format!("\n"));
+ // `Length` follows from the data.
+ for (dk, dv) in s.dict.iter().filter(|(dk, _)| dk.as_slice() != b"Length") {
+ self.value(Some(dk), dv, depth + 1)?;
+ }
+ if ascii {
+ // Printable ASCII is valid UTF-8.
+ let text = String::from_utf8_lossy(&s.raw);
+ self.out.push_str(&format!("{} \n", esc_data(&text)));
+ } else {
+ self.out.push_str(&format!("{} \n", hex_of(&s.raw, true)));
+ }
+ self.out.push_str(" \n");
+ }
+ }
+ Some(())
+ }
+}
+
+/// XFDF 3.0 "Stream encoding", method 1: the XML control characters as entities; line breaks stay.
+fn esc_data(s: &str) -> String {
+ s.replace('&', "&").replace('<', "<").replace('>', ">").replace('"', """)
+}
+
+/// Bytes as upper-case hexadecimal, with a line feed after every 80 characters when `wrap`.
+fn hex_of(bytes: &[u8], wrap: bool) -> String {
+ const DIGITS: &[u8; 16] = b"0123456789ABCDEF";
+ let mut out = String::with_capacity(bytes.len().saturating_mul(2).saturating_add(bytes.len() / 40));
+ for (i, b) in bytes.iter().enumerate() {
+ if wrap && i > 0 && i % 40 == 0 {
+ out.push('\n');
+ }
+ out.push(char::from(DIGITS[usize::from(b >> 4)]));
+ out.push(char::from(DIGITS[usize::from(b & 15)]));
+ }
+ out
+}
+
+/// Hexadecimal digits back to bytes, ignoring white space; `None` for any other character or an
+/// odd number of digits.
+fn bytes_of_hex(text: &str) -> Option> {
+ let digits: Vec = text.bytes().filter(|b| !b.is_ascii_whitespace()).collect();
+ if !digits.len().is_multiple_of(2) {
+ return None;
+ }
+ let value = |c: u8| char::from(c).to_digit(16).and_then(|d| u8::try_from(d).ok());
+ digits.as_chunks::<2>().0.iter().map(|[h, l]| Some(value(*h)? << 4 | value(*l)?)).collect()
+}
+
+/// An appearance read from XFDF, before it is put into a document.
+#[derive(Debug, PartialEq)]
+pub(crate) enum Node {
+ Value(Object),
+ Array(Vec),
+ Dict(Vec<(Vec, Node)>),
+ Stream(Vec<(Vec, Node)>, Vec),
+}
+
+/// Read the text of an `` element: base 64, then the XML it holds. `budget` is what
+/// the import may still read (decoded bytes) and is charged. The result is the `/AP` dictionary,
+/// with a normal appearance (`/N`) that is one stream: XFDF has no appearance state (`/AS`), so a
+/// dictionary of states would leave nothing selected to draw (ISO 32000-2 §12.5.5).
+pub(crate) fn decode(text: &str, budget: &mut usize) -> Result {
+ let limit = MAX_APPEARANCE_BYTES.min(*budget);
+ // Base 64 is 4 characters for 3 bytes: refuse a text that decodes past the limit before
+ // decoding it.
+ let mut compact = String::new();
+ for c in text.chars().filter(|c| !c.is_whitespace()) {
+ if compact.len() / 4 * 3 > limit {
+ return Err(format!("the appearance is larger than {} MiB", limit >> 20));
+ }
+ compact.push(c);
+ }
+ let engine = base64::engine::GeneralPurpose::new(
+ &base64::alphabet::STANDARD,
+ base64::engine::GeneralPurposeConfig::new().with_decode_padding_mode(base64::engine::DecodePaddingMode::Indifferent),
+ );
+ let bytes = engine.decode(compact.as_bytes()).map_err(|e| format!("the appearance is not base 64: {e}"))?;
+ if bytes.len() > limit {
+ return Err(format!("the appearance is larger than {} MiB", limit >> 20));
+ }
+ *budget = budget.saturating_sub(bytes.len());
+ let xml = std::str::from_utf8(&bytes).map_err(|_| "the appearance is not UTF-8 text".to_string())?;
+ let xml = xml.trim_start_matches('\u{feff}');
+ check_form_xml_depth(xml).map_err(|e| e.to_string())?;
+ let parsed = parse_form_xml(xml).map_err(|e| format!("the appearance is not XML: {e}"))?;
+ let root = parsed.root_element();
+ if !root.tag_name().name().eq_ignore_ascii_case("DICT") {
+ return Err("the appearance is not a dictionary".into());
+ }
+ let mut values = MAX_VALUES;
+ let node = read(root, 0, &mut values)?;
+ let usable = match &node {
+ Node::Dict(entries) => entries.iter().any(|(k, v)| k.as_slice() == b"N" && matches!(v, Node::Stream(..))),
+ _ => false,
+ };
+ if !usable {
+ return Err("the appearance has no normal appearance stream".into());
+ }
+ Ok(node)
+}
+
+fn attr<'a>(node: roxmltree::Node<'a, '_>, name: &str) -> Option<&'a str> {
+ node.attributes().find(|a| a.name().eq_ignore_ascii_case(name)).map(|a| a.value())
+}
+
+fn read(node: roxmltree::Node, depth: usize, values: &mut usize) -> Result {
+ if depth > MAX_NESTING {
+ return Err(format!("the appearance nests objects more than {MAX_NESTING} deep"));
+ }
+ *values = values.checked_sub(1).ok_or_else(|| format!("the appearance holds more than {MAX_VALUES} values"))?;
+ let tag = node.tag_name().name().to_ascii_uppercase();
+ let val = || attr(node, "VAL").ok_or_else(|| format!("{tag} has no VAL"));
+ let entries = |values: &mut usize| -> Result, Node)>, String> {
+ let mut out = Vec::new();
+ for child in node.children().filter(|c| c.is_element() && !c.tag_name().name().eq_ignore_ascii_case("DATA")) {
+ let key = attr(child, "KEY").ok_or_else(|| format!("an entry of {tag} has no KEY"))?;
+ out.push((pdfcraft_forms::name_bytes(key), read(child, depth + 1, values)?));
+ }
+ Ok(out)
+ };
+ Ok(match tag.as_str() {
+ "DICT" => Node::Dict(entries(values)?),
+ "ARRAY" => {
+ let mut items = Vec::new();
+ for child in node.children().filter(|c| c.is_element()) {
+ items.push(read(child, depth + 1, values)?);
+ }
+ Node::Array(items)
+ }
+ "STREAM" => {
+ let mut dict = entries(values)?;
+ let data = node.children().find(|c| c.is_element() && c.tag_name().name().eq_ignore_ascii_case("DATA")).ok_or("a stream has no DATA")?;
+ let text: String = data.children().filter(|c| c.is_text()).filter_map(|c| c.text()).collect();
+ let bytes = match attr(data, "ENCODING").map(str::to_ascii_lowercase).as_deref() {
+ Some("hex") => bytes_of_hex(&text).ok_or("stream data is not hexadecimal")?,
+ Some("ascii") | None => text.into_bytes(),
+ Some(other) => return Err(format!("unknown stream encoding {other}")),
+ };
+ // `filtered` data is already decoded: the filters no longer apply to it.
+ if attr(data, "MODE").is_some_and(|m| m.eq_ignore_ascii_case("filtered")) {
+ dict.retain(|(k, _)| !matches!(k.as_slice(), b"Filter" | b"DecodeParms" | b"FFilter" | b"FDecodeParms"));
+ }
+ dict.retain(|(k, _)| k.as_slice() != b"Length");
+ Node::Stream(dict, bytes)
+ }
+ "NAME" => Node::Value(Object::Name(pdfcraft_forms::name_bytes(val()?))),
+ "INT" => Node::Value(Object::Int(val()?.trim().parse::().map_err(|_| "INT is not an integer")?)),
+ "FIXED" => {
+ let v = val()?.trim().parse::().ok().filter(|v| v.is_finite()).ok_or("FIXED is not a number")?;
+ Node::Value(Object::Real(v))
+ }
+ "BOOL" => Node::Value(Object::Bool(match val()?.trim() {
+ "true" => true,
+ "false" => false,
+ _ => return Err("BOOL is neither true nor false".into()),
+ })),
+ "STRING" => {
+ let v = val()?;
+ let bytes = if attr(node, "ENCODING").is_some_and(|e| e.eq_ignore_ascii_case("hex")) {
+ bytes_of_hex(v).ok_or("STRING is not hexadecimal")?
+ } else {
+ v.as_bytes().to_vec()
+ };
+ Node::Value(Object::String(PdfString::literal(bytes)))
+ }
+ "NULL" => Node::Value(Object::Null),
+ other => return Err(format!("unknown appearance element {other}")),
+ })
+}
+
+/// Put a read appearance into `doc`: each stream becomes an object of its own. Returns the `/AP`
+/// value. Null dictionary entries are left out (ISO 32000-2 §7.3.7: they mean the entry is absent).
+pub(crate) fn materialize(doc: &mut Document, node: Node) -> Object {
+ let dict = |doc: &mut Document, entries: Vec<(Vec, Node)>| {
+ let mut d = Dict::new();
+ for (k, v) in entries {
+ let v = materialize(doc, v);
+ if !matches!(v, Object::Null) {
+ d.set(k, v);
+ }
+ }
+ d
+ };
+ match node {
+ Node::Value(o) => o,
+ Node::Array(items) => Object::Array(items.into_iter().map(|n| materialize(doc, n)).collect()),
+ Node::Dict(entries) => Object::Dict(dict(doc, entries)),
+ Node::Stream(entries, raw) => {
+ let d = dict(doc, entries);
+ Object::Ref(doc.add(Object::Stream(pdfcraft_cos::Stream { dict: d, raw: raw.into() })))
+ }
+ }
+}
+
+/// Whether an annotation dictionary carries an appearance the document can draw: `/AP` with a
+/// normal appearance that is a stream, or a dictionary of streams (one per state).
+pub(crate) fn has_appearance(doc: &Document, d: &Dict) -> bool {
+ let Some(ap) = d.get(b"AP").map(|a| doc.resolve(a)) else { return false };
+ let Some(normal) = ap.as_dict().and_then(|ap| ap.get(b"N")).map(|n| doc.resolve(n)) else { return false };
+ match normal.as_ref() {
+ Object::Stream(_) => true,
+ Object::Dict(states) => !states.is_empty() && states.iter().all(|(_, s)| matches!(doc.resolve(s).as_ref(), Object::Stream(_))),
+ _ => false,
+ }
+}
diff --git a/crates/xfdf/src/fdf.rs b/crates/xfdf/src/fdf.rs
index ceb4ad99eb..dffd3f9098 100644
--- a/crates/xfdf/src/fdf.rs
+++ b/crates/xfdf/src/fdf.rs
@@ -86,13 +86,16 @@ impl<'a> FdfCopy<'a> {
Ok(())
}
- /// Skip source-document links and appearances without cloning their values. The
- /// dictionary and every retained entry are charged before any owned copy is made.
+ /// Skip source-document links without cloning their values. A stamp's appearance (`/AP`) is
+ /// copied with its streams and resources, so the stamp looks the same where it is imported;
+ /// other comments carry their formatting entries and leave the appearance out, as XFDF does.
+ /// The dictionary and every retained entry are charged before any owned copy is made.
fn annotation_dict(&mut self, dict: &Dict) -> Result {
self.charge_value(0)?;
+ let stamp = dict.name(b"Subtype") == Some(b"Stamp".as_slice());
let mut out = Dict::new();
for (key, value) in dict.iter() {
- if matches!(key.as_slice(), b"P" | b"AP" | b"Popup" | b"IRT" | b"Parent" | b"FS" | b"Sound") {
+ if matches!(key.as_slice(), b"P" | b"Popup" | b"IRT" | b"Parent" | b"FS" | b"Sound") || (key.as_slice() == b"AP" && !stamp) {
continue;
}
self.dict_entry(&mut out, key, value, 1)?;
@@ -202,7 +205,7 @@ impl<'a> FdfCopy<'a> {
}
}
-/// FDF with field values and/or comments (appearances are not carried). Each comment is an
+/// FDF with field values and/or comments, a stamp with its appearance. Each comment is an
/// indirect object of the FDF, so a reply's `/IRT` can point at its parent's object there
/// (§12.7.8.3.1). Nested values are copied and renumbered, including shared or cyclic graphs.
/// Source `/Page` and `/Pages` dictionaries become null at every copy depth.
@@ -356,27 +359,69 @@ impl ImportBudget {
}
}
+/// Where [`deep`] copies to: the document, and the streams already copied into it (by their
+/// reference in the FDF), so a stream two comments share is copied once.
+struct DeepTarget<'a> {
+ doc: &'a mut Document,
+ streams: HashMap,
+}
+
+/// How deeply [`deep`] follows a comment's objects, references included. A form that draws a form
+/// costs four levels (the reference, the stream's dictionary, `/Resources`, `/XObject`), and
+/// export writes a chain of them however long, so this leaves room for one sixty forms deep.
+const MAX_COPY_DEPTH: usize = 4 * MAX_DEPTH;
+
/// Copy an object out of another document, resolving references. A reference back to an object
-/// being copied becomes null.
-fn deep(src: &Document, o: &Object, depth: usize, path: &mut Vec, budget: &mut ImportBudget) -> Result {
+/// being copied becomes null. A stream (an appearance and the images and forms it draws) becomes
+/// an object of `dst`, its data charged to the budget. Objects nested past [`MAX_COPY_DEPTH`] are
+/// an error, not a partial copy: the comment would arrive with part of its appearance missing.
+fn deep(
+ src: &Document,
+ dst: &mut DeepTarget,
+ o: &Object,
+ depth: usize,
+ path: &mut Vec,
+ budget: &mut ImportBudget,
+) -> Result {
budget.spend(1, 0)?;
- if depth > 16 {
- return Ok(Object::Null);
+ if depth > MAX_COPY_DEPTH {
+ return Err(DataError::Malformed(format!("a comment's objects nest more than {MAX_COPY_DEPTH} levels deep")));
}
Ok(match o {
Object::Ref(r) => {
if path.contains(r) {
return Ok(Object::Null);
}
+ if let Some(copied) = dst.streams.get(r) {
+ return Ok(Object::Ref(*copied));
+ }
+ let target = src.get(*r);
+ if let Object::Stream(stream) = target.as_ref() {
+ budget.spend(0, stream.raw.len())?;
+ path.push(*r);
+ let dict = deep(src, dst, &Object::Dict(stream.dict.clone()), depth + 1, path, budget);
+ path.pop();
+ let Object::Dict(mut dict) = dict? else { return Ok(Object::Null) };
+ dict.remove(b"Length");
+ let copied = dst.doc.add(Object::Stream(pdfcraft_cos::Stream { dict, raw: stream.raw.clone() }));
+ dst.streams.insert(*r, copied);
+ return Ok(Object::Ref(copied));
+ }
path.push(*r);
- let copy = deep(src, &src.get(*r), depth + 1, path, budget);
+ let copy = deep(src, dst, &target, depth + 1, path, budget);
path.pop();
copy?
}
- Object::Array(a) => Object::Array(a.iter().map(|x| deep(src, x, depth + 1, path, budget)).collect::>()?),
+ Object::Array(a) => Object::Array(a.iter().map(|x| deep(src, dst, x, depth + 1, path, budget)).collect::>()?),
+ // A page or page tree the comment reaches is the file's, not the comment's: copied in, it
+ // would bring its contents along (as export, which nulls them; `resolve` bounds the hops
+ // of an indirect /Type).
+ Object::Dict(d) if d.get(b"Type").is_some_and(|t| matches!(src.resolve(t).as_name(), Some(b"Page" | b"Pages"))) => Object::Null,
Object::Dict(d) => {
- Object::Dict(d.iter().map(|(k, v)| Ok((k.clone(), deep(src, v, depth + 1, path, budget)?))).collect::>()?)
+ Object::Dict(d.iter().map(|(k, v)| Ok((k.clone(), deep(src, dst, v, depth + 1, path, budget)?))).collect::>()?)
}
+ // A stream is always an indirect object (ISO 32000-2 §7.3.8); one held directly is not
+ // read.
Object::Stream(_) => Object::Null,
Object::String(s) => {
budget.spend(0, s.bytes.len())?;
@@ -469,8 +514,17 @@ pub(crate) fn import_fdf(doc: &mut Document, bytes: &[u8]) -> Result = pdfcraft_model::pages(doc).iter().map(|p| p.obj).collect();
let mut placed: HashMap = HashMap::new();
let mut later: HashMap, Option)> = HashMap::new();
+ let mut copied_streams: HashMap = HashMap::new();
for a in body.get(b"Annots").map(|a| fdf.resolve(a)).and_then(|a| a.as_array().cloned()).unwrap_or_default() {
let Some(mut src) = fdf.resolve(&a).as_dict().cloned() else { continue };
+ // Only a comment of a known type on a page of this document is copied in: its streams
+ // become objects of the document.
+ let on_page = src.get(b"Page").and_then(|p| fdf.resolve(p).as_int()).and_then(|p| usize::try_from(p).ok()).is_some_and(|p| p < pages.len());
+ let known =
+ src.get(b"Subtype").map(|s| fdf.resolve(s)).is_some_and(|s| s.as_name().is_some_and(|s| SUBTYPES.iter().any(|(x, _)| x.as_bytes() == s)));
+ if !on_page || !known {
+ continue;
+ }
// The parent is another comment: link it below rather than copying it in.
let irt = src.get(b"IRT").cloned();
src.remove(b"IRT");
@@ -479,8 +533,19 @@ pub(crate) fn import_fdf(doc: &mut Document, bytes: &[u8]) -> Result = a.as_ref().into_iter().collect();
- let Object::Dict(mut d) = deep(&fdf, &Object::Dict(src), 0, &mut path, &mut budget)? else { continue };
+ let mut target = DeepTarget { doc: &mut *doc, streams: std::mem::take(&mut copied_streams) };
+ let copy = deep(&fdf, &mut target, &Object::Dict(src), 0, &mut path, &mut budget);
+ copied_streams = target.streams;
+ let Object::Dict(mut d) = copy? else { continue };
let Some(page) = d.get(b"Page").and_then(Object::as_int).and_then(|p| usize::try_from(p).ok()).and_then(|p| pages.get(p).copied()) else {
continue;
};
diff --git a/crates/xfdf/src/lib.rs b/crates/xfdf/src/lib.rs
index c42d414918..984d1cdbe5 100644
--- a/crates/xfdf/src/lib.rs
+++ b/crates/xfdf/src/lib.rs
@@ -2,8 +2,10 @@
//!
//! - **XFDF** (ISO 19444-1, Acrobat's "Export all to data file" / "Import comments", and form
//! data): comments with their geometry, colours, flags, authors, dates, replies, pop-ups,
-//! ink, quadrilaterals, line ends and callouts; field values, nested by name.
-//! - **FDF** (ISO 32000-2 §12.7.8): fields and comments in PDF syntax.
+//! ink, quadrilaterals, line ends, callouts, formatting (rich text, default style, border
+//! style and dashes, rotation, justification, fringe, line leaders) and a stamp's appearance;
+//! field values, nested by name.
+//! - **FDF** (ISO 32000-2 §12.7.8): fields and comments in PDF syntax, with their appearances.
//! - Form data as **XML**, **CSV** and **tab-delimited text** (Acrobat's Export data formats).
//!
//! Import merges: a comment whose name (`/NM`) already exists on its page replaces it; field
@@ -18,6 +20,7 @@ use std::io::Write as _;
use pdfcraft_cos::{Dict, Document, ObjRef, Object, PdfString};
use pdfcraft_forms::{FieldKind, FieldValue};
+mod appearance;
mod common;
mod fdf;
mod xfdf;
@@ -36,6 +39,8 @@ use xfdf::{apply_values, import_xfdf};
#[cfg(test)]
mod tests;
+#[cfg(test)]
+mod tests_format;
#[derive(Debug, thiserror::Error, PartialEq)]
pub enum DataError {
@@ -85,6 +90,9 @@ pub struct Report {
pub fields: usize,
/// Field values the form refused (format, validation, unknown options).
pub rejected: Vec,
+ /// What the import left out of a comment it did import, each as "name: why" (an appearance
+ /// it could not read: the comment is drawn from its other entries instead).
+ pub skipped: Vec,
}
/// Form data as XML, CSV or tab-delimited text (Acrobat's Export data formats).
@@ -330,8 +338,15 @@ fn tab_delimited(t: &str) -> Result)>, DataError> {
}
/// Import comments and/or field values from XFDF, FDF, XML, CSV or tab-delimited text
-/// (detected from the content).
+/// (detected from the content). All or nothing: on an error `doc` is left as it was.
pub fn import(doc: &mut Document, bytes: &[u8]) -> Result {
+ let mut work = doc.clone();
+ let report = import_into(&mut work, bytes)?;
+ *doc = work;
+ Ok(report)
+}
+
+fn import_into(doc: &mut Document, bytes: &[u8]) -> Result {
let report = if bytes.starts_with(b"%FDF") {
import_fdf(doc, bytes)?
} else {
diff --git a/crates/xfdf/src/tests.rs b/crates/xfdf/src/tests.rs
index 96e9179faa..2c1c06c988 100644
--- a/crates/xfdf/src/tests.rs
+++ b/crates/xfdf/src/tests.rs
@@ -143,9 +143,9 @@ fn values(doc: &Document) -> Vec<(String, Vec)> {
fields(doc).into_iter().map(|f| (f.name, f.value)).collect()
}
-/// #2666: Replace Text writes a StrikeOut and a Caret that replies to it. XFDF names a reply by
-/// the `/NM` of what it replies to, so when both carried one id the caret's `inreplyto` was its
-/// own `name`: importing it found a comment replying to itself and the pair was lost.
+/// #2666: Replace Text writes a Caret and a StrikeOut grouped under it. XFDF names the link by
+/// the `/NM` of the annotation it points at, so when both carried one id the `inreplyto` was the
+/// strikeout's own `name`: importing it found a comment replying to itself and the pair was lost.
#[test]
fn a_replace_text_pair_survives_an_xfdf_round_trip() {
let mut src = blank();
@@ -170,8 +170,8 @@ fn a_replace_text_pair_survives_an_xfdf_round_trip() {
let xfdf = export_xfdf(&src, true, false, "a.pdf");
assert!(xfdf.contains("name=\"strike\"") && xfdf.contains("name=\"caret\""), "each gets its own name: {xfdf}");
- assert!(xfdf.contains("inreplyto=\"strike\""), "the caret replies to the strikeout: {xfdf}");
- assert!(!xfdf.contains("inreplyto=\"caret\""), "never a reply to itself");
+ assert!(xfdf.contains("inreplyto=\"caret\""), "the strikeout is grouped under the caret: {xfdf}");
+ assert!(!xfdf.contains("inreplyto=\"strike\""), "never a reply to itself");
let mut dst = blank();
let r = import(&mut dst, xfdf.as_bytes()).unwrap();
@@ -180,6 +180,135 @@ fn a_replace_text_pair_survives_an_xfdf_round_trip() {
let kinds: Vec<&str> = found.iter().map(|s| s.subtype.as_str()).collect();
assert!(kinds.contains(&"StrikeOut") && kinds.contains(&"Caret"), "{kinds:?}");
assert_eq!(comment_view(&dst), comment_view(&src), "the pair and its thread survive");
+ // Review on #5689 (CodeRabbit): the intents travel too, so the imported pair is still
+ // Replace Text, and deleting its strikeout takes the caret and its replacement with it.
+ assert!(xfdf.contains("intent=\"Replace\"") && xfdf.contains("intent=\"StrikeOutTextEdit\""), "{xfdf}");
+ let strike = summaries(&dst).into_iter().find(|s| s.subtype == "StrikeOut").expect("the strikeout");
+ pdfcraft_annot::delete_annotation(&mut dst, 0, strike.index).unwrap();
+ assert!(summaries(&dst).iter().all(|s| s.subtype != "Caret"), "the caret goes with the strikeout");
+}
+
+/// Review on #5689 (CodeRabbit): XFDF links a reply to its target by the target's `name`, so a
+/// group whose primary has no `/NM` lost its `inreplyto` on export and came back as two loose
+/// comments. Both layouts: the caret primary (this PR) and the strikeout primary (older files).
+#[test]
+fn an_unnamed_group_primary_gets_an_export_only_name() {
+ for caret_primary in [true, false] {
+ let mut src = blank();
+ let quads = [[100.0, 720.0, 200.0, 720.0, 100.0, 706.0, 200.0, 706.0]];
+ let style = Style { color: [0.89, 0.13, 0.13], opacity: 1.0, width: 1.0, fill: None, ..Style::default() };
+ let unnamed = Meta { date: None, id: String::new() };
+ add_text_replacement(
+ &mut src,
+ TextReplacement {
+ page: 0,
+ quads: &quads,
+ replacement: "new words",
+ author: "Ada",
+ strike: &style,
+ caret: &style,
+ strike_meta: &unnamed,
+ caret_meta: &unnamed,
+ },
+ )
+ .unwrap();
+ let page = pdfcraft_model::pages(&src)[0].obj;
+ let annots = src.get(page).as_dict().unwrap().get(b"Annots").and_then(|a| src.resolve(a).as_array().cloned()).unwrap();
+ let refs: Vec = annots.iter().filter_map(Object::as_ref).collect();
+ let is = |doc: &Document, r: ObjRef, s: &[u8]| doc.get(r).as_dict().and_then(|d| d.name(b"Subtype")) == Some(s);
+ let strike = *refs.iter().find(|r| is(&src, **r, b"StrikeOut")).unwrap();
+ let caret = *refs.iter().find(|r| is(&src, **r, b"Caret")).unwrap();
+ let (primary, sub) = if caret_primary { (caret, strike) } else { (strike, caret) };
+ if !caret_primary {
+ src.update_dict(strike, |d| {
+ d.remove(b"IRT");
+ d.remove(b"RT");
+ })
+ .unwrap();
+ src.update_dict(caret, |d| {
+ d.set(b"IRT".to_vec(), Object::Ref(strike));
+ d.set(b"RT".to_vec(), Object::name("Group"));
+ })
+ .unwrap();
+ }
+ // A comment already named what the made-up name would be: the two must not collide.
+ let clash = format!("pdfcraft-export-{}-{}", primary.num, primary.generation);
+ let note = NewAnnotation {
+ page: 0,
+ shape: Shape::Note { at: [300.0, 300.0], icon: Default::default() },
+ style: style.clone(),
+ contents: "note".into(),
+ author: "Ada".into(),
+ };
+ add_annotation(&mut src, ¬e, &Meta { date: None, id: clash.clone() }).unwrap();
+
+ let xfdf = export_xfdf(&src, true, false, "a.pdf");
+ let doc = roxmltree::Document::parse(&xfdf).unwrap();
+ let el = |t: &str| doc.descendants().find(|n| n.has_tag_name(t)).unwrap_or_else(|| panic!("no <{t}>: {xfdf}"));
+ let (tag, sub_tag) = if caret_primary { ("caret", "strikeout") } else { ("strikeout", "caret") };
+ let name = el(tag).attribute("name").unwrap_or_else(|| panic!("the unnamed primary gets a name ({caret_primary}): {xfdf}"));
+ assert_eq!(el(sub_tag).attribute("inreplyto"), Some(name), "{xfdf}");
+ assert_ne!(name, clash, "a made-up name never repeats a real /NM");
+ assert_eq!(doc.descendants().filter(|n| n.attribute("name") == Some(name)).count(), 1, "{xfdf}");
+ assert!(src.get(primary).as_dict().unwrap().get(b"NM").is_none(), "the name is for the export only");
+ assert!(src.get(sub).as_dict().unwrap().get(b"NM").is_none());
+
+ let mut dst = blank();
+ import(&mut dst, xfdf.as_bytes()).unwrap();
+ // The imported subordinate is grouped under the imported primary again.
+ let dpage = pdfcraft_model::pages(&dst)[0].obj;
+ let dannots = dst.get(dpage).as_dict().unwrap().get(b"Annots").and_then(|a| dst.resolve(a).as_array().cloned()).unwrap();
+ let drefs: Vec = dannots.iter().filter_map(Object::as_ref).collect();
+ let (p_sub, s_sub): (&[u8], &[u8]) = if caret_primary { (b"Caret", b"StrikeOut") } else { (b"StrikeOut", b"Caret") };
+ let dprimary = *drefs.iter().find(|r| is(&dst, **r, p_sub)).unwrap();
+ let dsub = *drefs.iter().find(|r| is(&dst, **r, s_sub)).unwrap();
+ let irt = dst.get(dsub).as_dict().unwrap().get(b"IRT").and_then(Object::as_ref);
+ assert_eq!(irt, Some(dprimary), "the group survives the round trip ({caret_primary})");
+ }
+}
+
+/// An annotation written inline in `/Annots` (a direct dictionary, not a reference) is exported
+/// under its `/NM` too, so a made-up name must not repeat it either.
+#[test]
+fn an_export_only_name_never_repeats_an_inline_annotations_nm() {
+ let mut src = blank();
+ let quads = [[100.0, 720.0, 200.0, 720.0, 100.0, 706.0, 200.0, 706.0]];
+ let style = Style { color: [0.89, 0.13, 0.13], opacity: 1.0, width: 1.0, fill: None, ..Style::default() };
+ let unnamed = Meta { date: None, id: String::new() };
+ add_text_replacement(
+ &mut src,
+ TextReplacement {
+ page: 0,
+ quads: &quads,
+ replacement: "new words",
+ author: "Ada",
+ strike: &style,
+ caret: &style,
+ strike_meta: &unnamed,
+ caret_meta: &unnamed,
+ },
+ )
+ .unwrap();
+ let page = pdfcraft_model::pages(&src)[0].obj;
+ let mut annots = src.get(page).as_dict().unwrap().get(b"Annots").and_then(|a| src.resolve(a).as_array().cloned()).unwrap();
+ let primary =
+ annots.iter().filter_map(Object::as_ref).find(|r| src.get(*r).as_dict().and_then(|d| d.name(b"Subtype")) == Some(&b"Caret"[..])).unwrap();
+ // An inline note already named what the made-up name would be.
+ let clash = format!("pdfcraft-export-{}-{}", primary.num, primary.generation);
+ let mut note = Dict::new();
+ note.set(b"Type".to_vec(), Object::name("Annot"));
+ note.set(b"Subtype".to_vec(), Object::name("Text"));
+ note.set(b"NM".to_vec(), PdfString::text(&clash));
+ note.set(b"Rect".to_vec(), Object::Array(vec![300.into(), 300.into(), 320.into(), 320.into()]));
+ annots.push(Object::Dict(note));
+ src.update_dict(page, |p| p.set(b"Annots".to_vec(), Object::Array(annots))).unwrap();
+
+ let xfdf = export_xfdf(&src, true, false, "a.pdf");
+ let doc = roxmltree::Document::parse(&xfdf).unwrap();
+ let caret = doc.descendants().find(|n| n.has_tag_name("caret")).unwrap_or_else(|| panic!("no : {xfdf}"));
+ let name = caret.attribute("name").unwrap_or_else(|| panic!("the unnamed primary gets a name: {xfdf}"));
+ assert_ne!(name, clash, "a made-up name never repeats an inline annotation's /NM: {xfdf}");
+ assert_eq!(doc.descendants().filter(|n| n.attribute("name") == Some(&clash[..])).count(), 1, "{xfdf}");
}
#[test]
@@ -438,8 +567,10 @@ fn fdf_keeps_replies_and_review_status_on_their_note() {
// Every cross-reference entry points at its object (other readers trust the table).
let tail = std::str::from_utf8(&fdf[fdf.windows(5).position(|w| w == b"xref\n").unwrap()..]).unwrap();
let xref: usize = tail.lines().skip_while(|l| *l != "startxref").nth(1).unwrap().parse().unwrap();
- assert!(fdf[xref..].starts_with(b"xref\n0 6\n"), "{tail}");
- for (num, line) in tail.lines().skip(3).take(5).enumerate() {
+ // The root, the four comments and their appearance streams.
+ let count: usize = tail.lines().nth(1).and_then(|l| l.strip_prefix("0 ")).unwrap().parse().unwrap();
+ assert!(fdf[xref..].starts_with(b"xref\n") && count >= 6, "{tail}");
+ for (num, line) in tail.lines().skip(3).take(count - 1).enumerate() {
let at: usize = line[..10].parse().unwrap();
assert!(fdf[at..].starts_with(format!("{} 0 obj\n", num + 1).as_bytes()), "object {}: {line}", num + 1);
}
@@ -2155,6 +2286,19 @@ fn importing_comments_as_copies_adds_them_on_the_page_with_fresh_names() {
assert_eq!(summaries(&other).len(), 4, "the named import replaced its own earlier copy");
}
+/// Comment import never takes the file's field values, whatever the placement (a non-finite
+/// offset, which is ignored, and no page or prefix made it the full import).
+#[test]
+fn comment_import_leaves_field_values_alone() {
+ let xfdf = r#"from the file "#;
+ for offset in [Some([f64::NAN, 0.0]), None] {
+ let mut doc = one_field_named("Name", "mine");
+ let r = import_comments(&mut doc, xfdf, None, None, offset).unwrap();
+ assert_eq!((r.comments, r.fields), (1, 0), "{offset:?}: {r:?}");
+ assert_eq!(values(&doc), [("Name".to_string(), vec!["mine".to_string()])], "{offset:?}");
+ }
+}
+
/// Other tools write comments straight into the page's `/Annots` array, without an object of
/// their own: they copy like any other, and two source comments sharing a name give two copies.
#[test]
diff --git a/crates/xfdf/src/tests_format.rs b/crates/xfdf/src/tests_format.rs
new file mode 100644
index 0000000000..35a9735ede
--- /dev/null
+++ b/crates/xfdf/src/tests_format.rs
@@ -0,0 +1,1216 @@
+//! Comment formatting and appearances through XFDF (ISO 19444-1, XFDF 3.0) and FDF
+//! (ISO 32000-2 §12.7.8): each property both ways, appearance streams with their resources, and
+//! files that are malformed or too large.
+
+use std::sync::Arc;
+
+use base64::Engine as _;
+use pdfcraft_cos::{SaveOptions, Stream, write_full};
+use proptest::prelude::*;
+
+use super::*;
+
+/// A document with `n` empty pages.
+fn pages(n: usize) -> Document {
+ let mut doc = Document::new_empty();
+ let root = doc.get(doc.root().unwrap()).as_dict().unwrap().reference(b"Pages").unwrap();
+ let mut kids = Vec::new();
+ for _ in 0..n {
+ let mut p = Dict::new();
+ p.set(b"Type".to_vec(), Object::name("Page"));
+ p.set(b"Parent".to_vec(), Object::Ref(root));
+ p.set(b"MediaBox".to_vec(), Object::Array(vec![0.into(), 0.into(), 600.into(), 800.into()]));
+ kids.push(Object::Ref(doc.add(p)));
+ }
+ doc.update_dict(root, |d| {
+ d.set(b"Count".to_vec(), Object::Int(kids.len() as i64));
+ d.set(b"Kids".to_vec(), Object::Array(kids));
+ })
+ .unwrap();
+ doc
+}
+
+fn page_ref(doc: &Document, i: usize) -> ObjRef {
+ pdfcraft_model::pages(doc)[i].obj
+}
+
+/// Add an annotation dictionary to page 0 as an object of its own.
+fn put(doc: &mut Document, mut d: Dict) -> ObjRef {
+ let page = page_ref(doc, 0);
+ d.set(b"Type".to_vec(), Object::name("Annot"));
+ d.set(b"P".to_vec(), Object::Ref(page));
+ let r = doc.add(Object::Dict(d));
+ doc.update_dict(page, |p| match p.get_mut(b"Annots") {
+ Some(Object::Array(a)) => a.push(Object::Ref(r)),
+ _ => p.set(b"Annots".to_vec(), Object::Array(vec![Object::Ref(r)])),
+ })
+ .unwrap();
+ r
+}
+
+fn nums(v: &[f64]) -> Object {
+ Object::Array(v.iter().map(|x| Object::Real(*x)).collect())
+}
+
+fn annot(sub: &str, nm: &str, rect: [f64; 4]) -> Dict {
+ let mut d = Dict::new();
+ d.set(b"Subtype".to_vec(), Object::name(sub));
+ d.set(b"NM".to_vec(), PdfString::text(nm));
+ d.set(b"Rect".to_vec(), nums(&rect));
+ d.set(b"F".to_vec(), Object::Int(4));
+ d
+}
+
+/// The imported annotation named `nm`.
+fn named(doc: &Document, nm: &str) -> Dict {
+ let r = xfdf::find_by_name(doc, nm).unwrap_or_else(|| panic!("no comment {nm}"));
+ doc.get(r).as_dict().unwrap().clone()
+}
+
+fn f64s(doc: &Document, o: Option<&Object>) -> Vec {
+ o.map(|o| doc.resolve(o)).and_then(|o| o.as_array().map(|a| a.iter().filter_map(|x| doc.resolve(x).as_f64()).collect())).unwrap_or_default()
+}
+
+fn text(doc: &Document, d: &Dict, k: &[u8]) -> Option {
+ d.get(k).and_then(|o| doc.resolve(o).as_string().map(|s| s.to_text()))
+}
+
+fn sub_dict(doc: &Document, d: &Dict, k: &[u8]) -> Dict {
+ d.get(k).map(|o| doc.resolve(o)).and_then(|o| o.as_dict().cloned()).unwrap_or_default()
+}
+
+const RICH: &str = r#"Bold & plain
two
"#;
+
+/// A free text comment with every formatting entry XFDF 3.0 gives an element or attribute for.
+fn formatted_freetext() -> Dict {
+ let mut d = annot("FreeText", "ft", [100.0, 100.0, 300.0, 200.0]);
+ d.set(b"Contents".to_vec(), PdfString::text("Bold & plain\rtwo"));
+ d.set(b"RC".to_vec(), PdfString::text(RICH));
+ d.set(b"DA".to_vec(), PdfString::literal(b"0 0 1 rg /Helv 14 Tf".to_vec()));
+ d.set(b"DS".to_vec(), PdfString::text("font: Helvetica,sans-serif 14.0pt; text-align:right; color:#0000FF"));
+ d.set(b"Q".to_vec(), Object::Int(2));
+ d.set(b"Rotate".to_vec(), Object::Int(90));
+ d.set(b"RD".to_vec(), nums(&[1.5, 2.0, 3.0, 4.0]));
+ let mut bs = Dict::new();
+ bs.set(b"W".to_vec(), Object::Real(2.0));
+ bs.set(b"S".to_vec(), Object::name("D"));
+ bs.set(b"D".to_vec(), nums(&[3.0, 2.0]));
+ d.set(b"BS".to_vec(), Object::Dict(bs));
+ d
+}
+
+fn formatted_line() -> Dict {
+ let mut d = annot("Line", "ln", [50.0, 50.0, 250.0, 120.0]);
+ d.set(b"L".to_vec(), nums(&[60.0, 60.0, 240.0, 60.0]));
+ d.set(b"LL".to_vec(), Object::Real(-12.0));
+ d.set(b"LLE".to_vec(), Object::Real(3.0));
+ d.set(b"LLO".to_vec(), Object::Real(1.5));
+ d.set(b"Cap".to_vec(), Object::Bool(true));
+ d.set(b"CP".to_vec(), Object::name("Top"));
+ d.set(b"CO".to_vec(), nums(&[4.0, -2.0]));
+ d.set(b"IT".to_vec(), Object::name("LineDimension"));
+ let mut bs = Dict::new();
+ bs.set(b"W".to_vec(), Object::Real(1.0));
+ bs.set(b"S".to_vec(), Object::name("D"));
+ bs.set(b"D".to_vec(), nums(&[4.0, 3.0, 2.0, 3.0]));
+ d.set(b"BS".to_vec(), Object::Dict(bs));
+ d
+}
+
+fn round_trip_xfdf(src: &Document) -> (String, Document) {
+ let xml = export_xfdf(src, true, false, "src.pdf");
+ let mut dst = pages(2);
+ import(&mut dst, xml.as_bytes()).unwrap();
+ (xml, dst)
+}
+
+#[test]
+fn free_text_formatting_is_exported_as_xfdf_elements_and_attributes() {
+ let mut src = pages(1);
+ put(&mut src, formatted_freetext());
+ let xml = export_xfdf(&src, true, false, "src.pdf");
+ for want in [
+ r#"justification="right""#,
+ r#"rotation="90""#,
+ r#"width="2""#,
+ r#"style="dash""#,
+ r#"dashes="3,2""#,
+ r#"fringe="1.5,2,3,4""#,
+ "font: Helvetica,sans-serif 14.0pt; text-align:right; color:#0000FF ",
+ // The rich text's element, as markup and without its XML declaration.
+ r#"Bold & plain
, the comment's text is the rich text's.
+ assert_eq!(text(&dst, &a, b"Contents").as_deref(), Some("Hello there"));
+ let bs = sub_dict(&dst, &a, b"BS");
+ assert_eq!(bs.name(b"S"), Some(b"D".as_slice()));
+ assert_eq!(f64s(&dst, bs.get(b"D")), vec![3.0, 2.0]);
+ let b = named(&dst, "b");
+ assert_eq!(b.get(b"LL").and_then(Object::as_f64), Some(10.0));
+ assert_eq!(b.get(b"LLE").and_then(Object::as_f64), Some(2.0));
+ assert_eq!(b.get(b"LLO").and_then(Object::as_f64), Some(1.0));
+}
+
+#[test]
+fn plain_rich_text_is_the_comments_text_and_paragraphs_become_lines() {
+ let xml = r#"
+just text
+
+
+ one
+ two
+
+
+ "#;
+ let mut dst = pages(1);
+ import(&mut dst, xml.as_bytes()).unwrap();
+ let p = named(&dst, "p");
+ assert_eq!(text(&dst, &p, b"Contents").as_deref(), Some("just text"));
+ assert!(!p.contains(b"RC"));
+ assert_eq!(text(&dst, &named(&dst, "q"), b"Contents").as_deref(), Some("one\rtwo"));
+}
+
+#[test]
+fn rich_text_that_is_not_xml_survives_as_text() {
+ let mut src = pages(1);
+ let mut d = annot("Text", "bad", [10.0, 10.0, 30.0, 30.0]);
+ d.set(b"Contents".to_vec(), PdfString::text("x"));
+ d.set(b"RC".to_vec(), PdfString::text("unclosed & raw"));
+ put(&mut src, d);
+ let (xml, dst) = round_trip_xfdf(&src);
+ assert!(xml.contains("<p>unclosed & raw "), "{xml}");
+ let d = named(&dst, "bad");
+ assert_eq!(text(&dst, &d, b"RC").as_deref(), Some("
unclosed & raw"));
+ assert_eq!(text(&dst, &d, b"Contents").as_deref(), Some("x"));
+}
+
+/// An image stamp: its appearance draws an image XObject from its resources.
+fn image_stamp(doc: &mut Document, nm: &str, sub: &str) -> (Vec, Vec) {
+ let pixels: Vec = (0..=255u8).cycle().take(3 * 16 * 16).collect();
+ let mut im = Dict::new();
+ im.set(b"Type".to_vec(), Object::name("XObject"));
+ im.set(b"Subtype".to_vec(), Object::name("Image"));
+ im.set(b"Width".to_vec(), Object::Int(16));
+ im.set(b"Height".to_vec(), Object::Int(16));
+ im.set(b"ColorSpace".to_vec(), Object::name("DeviceRGB"));
+ im.set(b"BitsPerComponent".to_vec(), Object::Int(8));
+ let im = doc.add(Object::Stream(Stream { dict: im, raw: pixels.clone().into() }));
+ let content = b"q 200 0 0 100 0 0 cm /Im0 Do Q".to_vec();
+ let mut xo = Dict::new();
+ xo.set(b"Im0".to_vec(), Object::Ref(im));
+ let mut res = Dict::new();
+ res.set(b"XObject".to_vec(), Object::Dict(xo));
+ let mut form = Dict::new();
+ form.set(b"Type".to_vec(), Object::name("XObject"));
+ form.set(b"Subtype".to_vec(), Object::name("Form"));
+ form.set(b"BBox".to_vec(), nums(&[0.0, 0.0, 200.0, 100.0]));
+ form.set(b"Resources".to_vec(), Object::Dict(res));
+ form.set(b"Name".to_vec(), PdfString::text("logo"));
+ let n = doc.add(Object::Stream(Stream { dict: form, raw: content.clone().into() }));
+ let mut ap = Dict::new();
+ ap.set(b"N".to_vec(), Object::Ref(n));
+ let mut d = annot(sub, nm, [100.0, 500.0, 300.0, 600.0]);
+ d.set(b"Name".to_vec(), Object::name("Draft"));
+ d.set(b"AP".to_vec(), Object::Dict(ap));
+ put(doc, d);
+ (content, pixels)
+}
+
+/// The normal appearance of `d`, and its `/Im0` image's data.
+fn appearance_of(doc: &Document, d: &Dict) -> (Vec, Vec) {
+ let n = doc.resolve(sub_dict(doc, d, b"AP").get(b"N").unwrap());
+ let Object::Stream(n) = n.as_ref() else { panic!("no appearance stream") };
+ let im = sub_dict(doc, &sub_dict(doc, &n.dict, b"Resources"), b"XObject").get(b"Im0").map(|o| doc.resolve(o));
+ let pixels = match im.as_deref() {
+ Some(Object::Stream(s)) => s.decoded().unwrap(),
+ _ => Vec::new(),
+ };
+ (n.decoded().unwrap(), pixels)
+}
+
+#[test]
+fn an_image_stamp_keeps_its_appearance_through_xfdf() {
+ let mut src = pages(1);
+ let (content, pixels) = image_stamp(&mut src, "logo", "Stamp");
+ let (xml, dst) = round_trip_xfdf(&src);
+ assert!(xml.contains(""), "{xml}");
+ let d = named(&dst, "logo");
+ assert_eq!(appearance_of(&dst, &d), (content, pixels), "the stamp comes back with its own picture, not a drawn 'DRAFT'");
+ // And it survives a save.
+ let saved = Document::open(Arc::new(write_full(&dst, &SaveOptions::default()).unwrap())).unwrap();
+ let d = named(&saved, "logo");
+ assert_eq!(appearance_of(&saved, &d).1.len(), 3 * 16 * 16);
+}
+
+#[test]
+fn file_export_carries_only_stamp_appearances_and_copies_carry_every_one() {
+ let mut src = pages(1);
+ let (content, _) = image_stamp(&mut src, "sq", "Square");
+ let xml = export_xfdf(&src, true, false, "src.pdf");
+ assert!(!xml.contains(""), "XFDF 3.0 gives only stamps an appearance element");
+ let copy = export_xfdf_comments(&src, &[(0, 0)], "src.pdf");
+ assert!(copy.contains(""));
+ let mut dst = pages(1);
+ import_comments(&mut dst, ©, Some(0), Some("paste"), Some([10.0, -10.0])).unwrap();
+ let d = named(&dst, "paste-1");
+ assert_eq!(appearance_of(&dst, &d).0, content, "a pasted copy looks the same");
+ assert_eq!(f64s(&dst, d.get(b"Rect")), vec![110.0, 490.0, 310.0, 590.0]);
+}
+
+#[test]
+fn fdf_carries_only_stamp_appearances() {
+ let mut src = pages(1);
+ image_stamp(&mut src, "sq", "Square");
+ let mut ft = formatted_freetext();
+ ft.set(b"NM".to_vec(), PdfString::text("box"));
+ let ft = put(&mut src, ft);
+ let n = sub_dict(&src, &named(&src, "sq"), b"AP");
+ src.update_dict(ft, |d| d.set(b"AP".to_vec(), Object::Dict(n.clone()))).unwrap();
+ let fdf = export_fdf(&src, true, false, "src.pdf").unwrap();
+ assert!(!fdf.windows(3).any(|w| w == b"/AP"), "a text box and a square carry their formatting, not their appearance");
+ let mut dst = pages(1);
+ import(&mut dst, &fdf).unwrap();
+ let ft = named(&dst, "box");
+ assert_eq!((ft.int(b"Q"), ft.int(b"Rotate")), (Some(2), Some(90)));
+ assert_eq!(text(&dst, &ft, b"DS").as_deref(), text(&src, &formatted_freetext(), b"DS").as_deref());
+ let mut stamp = pages(1);
+ image_stamp(&mut stamp, "st", "Stamp");
+ assert!(export_fdf(&stamp, true, false, "src.pdf").unwrap().windows(3).any(|w| w == b"/AP"));
+}
+
+/// The intent (/IT) goes out under both spellings XFDF files use, and either comes back.
+#[test]
+fn the_intent_is_written_and_read_as_intent_or_it() {
+ let mut src = pages(1);
+ let mut d = annot("FreeText", "tw", [10.0, 10.0, 90.0, 30.0]);
+ d.set(b"IT".to_vec(), Object::name("FreeTextTypewriter"));
+ put(&mut src, d);
+ let xml = export_xfdf(&src, true, false, "src.pdf");
+ assert!(xml.contains(r#"intent="FreeTextTypewriter" IT="FreeTextTypewriter""#), "{xml}");
+ let only_it = r#"
+
+ /Helvetica 9 Tf font: Helvetica ,sans-serif 9.00pt;color:#FF0000
+
+ "#;
+ let mut dst = pages(1);
+ import(&mut dst, only_it.as_bytes()).unwrap();
+ let a = named(&dst, "a");
+ assert_eq!(a.name(b"IT"), Some(b"FreeTextTypewriter".as_slice()));
+ assert_eq!((a.int(b"Q"), a.int(b"Rotate"), text(&dst, &a, b"Subj").as_deref()), (Some(0), Some(0), Some("Typewriter")));
+ assert_eq!(f64s(&dst, a.get(b"Rect")), vec![71.0004, 737.255, 138.977, 747.299]);
+ assert_eq!(named(&dst, "b").name(b"IT"), Some(b"FreeTextCallout".as_slice()));
+}
+
+#[test]
+fn a_stamp_without_area_exports_no_appearance() {
+ let mut src = pages(1);
+ image_stamp(&mut src, "flat", "Stamp");
+ let r = xfdf::find_by_name(&src, "flat").unwrap();
+ src.update_dict(r, |d| d.set(b"Rect".to_vec(), nums(&[100.0, 500.0, 100.0, 600.0]))).unwrap();
+ assert!(!export_xfdf(&src, true, false, "src.pdf").contains(""));
+}
+
+/// The appearance encoding other tools write (the stamps attached to PDFBOX-4437 and
+/// PDFBOX-4478 hold this shape): data written `filtered`/`ascii` under a dictionary that still
+/// names its filter, and `raw`/`hex`.
+#[test]
+fn an_appearance_written_by_another_tool_is_imported() {
+ let ap = r#"
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+3020302031302031302072650A66
+
+
+
+
+
+
+q
+/Fm0 Do
+0 0 1 rg 0 0 100 50 re f
+Q
+
+
+ "#;
+ let b64 = base64::engine::general_purpose::STANDARD.encode(ap);
+ let xml = format!(
+ r#"{b64} "#
+ );
+ let mut dst = pages(1);
+ let report = import(&mut dst, xml.as_bytes()).unwrap();
+ assert!(report.skipped.is_empty(), "{:?}", report.skipped);
+ let d = named(&dst, "s");
+ let n = dst.resolve(sub_dict(&dst, &d, b"AP").get(b"N").unwrap());
+ let Object::Stream(n) = n.as_ref() else { panic!("no appearance stream") };
+ assert!(!n.dict.contains(b"Filter"), "filtered data is already decoded");
+ assert_eq!(n.decoded().unwrap(), b"q\n/Fm0 Do\n0 0 1 rg 0 0 100 50 re f\nQ\n");
+ let fm = sub_dict(&dst, &sub_dict(&dst, &n.dict, b"Resources"), b"XObject").get(b"Fm0").map(|o| dst.resolve(o)).unwrap();
+ let Object::Stream(fm) = fm.as_ref() else { panic!("no form") };
+ assert_eq!(fm.decoded().unwrap(), b"0 0 10 10 re\nf");
+ assert_eq!(fm.dict.get(b"Interpolate"), Some(&Object::Bool(true)));
+}
+
+/// XFDF with one comment of type `sub` whose `` text is `inner`.
+fn appearance_xfdf(inner: &str, sub: &str) -> String {
+ format!(
+ r##"<{sub} page="0" rect="10,10,110,60" name="x" color="#FF0000">{inner} {sub}> "##
+ )
+}
+
+fn b64(s: &str) -> String {
+ base64::engine::general_purpose::STANDARD.encode(s)
+}
+
+#[test]
+fn unreadable_appearances_are_skipped_recorded_and_drawn_again() {
+ let deep = format!(
+ r#"{} {}00 "#,
+ r#""#.repeat(70),
+ " ".repeat(70)
+ );
+ for (why, inner) in [
+ ("not base 64", "@@@not base64@@@".to_string()),
+ ("not XML", b64(" ")),
+ ("no normal appearance", b64(r#" "#)),
+ ("a stream without data", b64(r#" "#)),
+ ("odd hexadecimal", b64(r#"ABC "#)),
+ ("an unknown element", b64(r#"q Q "#)),
+ ("an unknown encoding", b64(r#"q Q "#)),
+ ("a bad number", b64(r#"q Q "#)),
+ ("a DTD", b64(r#"]>&a; "#)),
+ ("too deep", b64(&deep)),
+ (
+ "states with none selected",
+ b64(r#"q Q "#),
+ ),
+ ] {
+ let mut dst = pages(1);
+ let report = import(&mut dst, appearance_xfdf(&inner, "square").as_bytes()).unwrap_or_else(|e| panic!("{why}: {e}"));
+ assert_eq!(report.comments, 1, "{why}: the comment itself is imported");
+ assert_eq!(report.skipped.len(), 1, "{why}: {:?}", report.skipped);
+ assert!(report.skipped[0].starts_with("x: "), "{why}: {:?}", report.skipped);
+ // PdfCraft draws the square from its own entries instead.
+ let d = named(&dst, "x");
+ let n = sub_dict(&dst, &d, b"AP").get(b"N").map(|o| dst.resolve(o));
+ assert!(matches!(n.as_deref(), Some(Object::Stream(_))), "{why}: drawn again");
+ }
+}
+
+#[test]
+fn an_oversized_appearance_is_refused_before_it_is_decoded() {
+ let mut budget = 1000;
+ let inner = b64(&format!(r#"{} "#, "q ".repeat(2000)));
+ assert!(appearance::decode(&inner, &mut budget).is_err());
+ assert_eq!(budget, 1000, "nothing was charged for a refused appearance");
+ let mut budget = appearance::MAX_IMPORT_APPEARANCE_BYTES;
+ let big = "A".repeat(appearance::MAX_APPEARANCE_BYTES / 3 * 4 + 8);
+ let err = appearance::decode(&big, &mut budget).unwrap_err();
+ assert!(err.contains("larger than"), "{err}");
+}
+
+#[test]
+fn many_appearances_share_one_import_budget() {
+ let mut budget = 100;
+ let one = b64(r#"0 0 m 1 1 l S "#);
+ let mut read = 0;
+ while appearance::decode(&one, &mut budget).is_ok() {
+ read += 1;
+ assert!(read < 10);
+ }
+ assert!(read >= 1 && budget < 100);
+}
+
+#[test]
+fn an_imported_redaction_mark_is_always_drawn_by_pdfcraft() {
+ let inner = b64(
+ r#"%nothing "#,
+ );
+ let mut dst = pages(1);
+ import(&mut dst, appearance_xfdf(&inner, "redact").as_bytes()).unwrap();
+ let d = named(&dst, "x");
+ let n = dst.resolve(sub_dict(&dst, &d, b"AP").get(b"N").unwrap());
+ let Object::Stream(n) = n.as_ref() else { panic!("no appearance") };
+ assert_ne!(n.decoded().unwrap(), b"%nothing", "the file's appearance could hide what the mark removes");
+}
+
+#[test]
+fn appearance_cycles_and_strings_survive_export() {
+ let mut src = pages(1);
+ image_stamp(&mut src, "c", "Stamp");
+ let d = named(&src, "c");
+ let n = sub_dict(&src, &d, b"AP").get(b"N").and_then(Object::as_ref).unwrap();
+ // The form's resources name the form itself, and hold a binary string.
+ let Object::Stream(mut form) = (*src.get(n)).clone() else { panic!("no form") };
+ let mut xo = Dict::new();
+ xo.set(b"Self".to_vec(), Object::Ref(n));
+ let mut res = sub_dict(&src, &form.dict, b"Resources");
+ res.set(b"Pattern".to_vec(), Object::Dict(xo));
+ res.set(b"Bin".to_vec(), Object::String(PdfString::literal(vec![0u8, 1, 0xFE, 0xFF])));
+ form.dict.set(b"Resources".to_vec(), Object::Dict(res));
+ src.set(n, Object::Stream(form));
+ let (xml, dst) = round_trip_xfdf(&src);
+ assert!(xml.contains(""));
+ let d = named(&dst, "c");
+ let n = dst.resolve(sub_dict(&dst, &d, b"AP").get(b"N").unwrap());
+ let Object::Stream(n) = n.as_ref() else { panic!("no form") };
+ let res = sub_dict(&dst, &n.dict, b"Resources");
+ assert_eq!(res.get(b"Bin"), Some(&Object::String(PdfString::literal(vec![0u8, 1, 0xFE, 0xFF]))));
+ // The reference back to the form ends there (as null, so the entry is left out).
+ assert!(sub_dict(&dst, &res, b"Pattern").is_empty());
+}
+
+#[test]
+fn an_appearance_that_names_its_page_does_not_carry_the_page_along() {
+ let mut src = pages(1);
+ image_stamp(&mut src, "pg", "Stamp");
+ let d = named(&src, "pg");
+ let n = sub_dict(&src, &d, b"AP").get(b"N").and_then(Object::as_ref).unwrap();
+ let page = page_ref(&src, 0);
+ let Object::Stream(mut form) = (*src.get(n)).clone() else { panic!("no form") };
+ form.dict.set(b"PieceInfo".to_vec(), Object::Ref(page));
+ src.set(n, Object::Stream(form));
+ let xml = export_xfdf(&src, true, false, "src.pdf");
+ let b64: String = xml.split("").nth(1).unwrap().split(" ").next().unwrap().split_whitespace().collect();
+ let inner = String::from_utf8(base64::engine::general_purpose::STANDARD.decode(b64).unwrap()).unwrap();
+ assert!(inner.contains(r#" "#), "{inner}");
+ assert!(!inner.contains("Kids") && !inner.contains("MediaBox"));
+}
+
+#[test]
+fn fdf_carries_appearances_with_their_resources() {
+ let mut src = pages(1);
+ let (content, pixels) = image_stamp(&mut src, "logo", "Stamp");
+ put(&mut src, formatted_freetext());
+ let fdf = export_fdf(&src, true, false, "src.pdf").unwrap();
+ assert!(fdf.windows(4).any(|w| w == b"/AP "), "the FDF holds the appearance");
+ let mut dst = pages(1);
+ import(&mut dst, &fdf).unwrap();
+ let d = named(&dst, "logo");
+ assert_eq!(appearance_of(&dst, &d), (content, pixels));
+ // Formatting already travelled in FDF and still does.
+ let ft = named(&dst, "ft");
+ assert_eq!((ft.int(b"Q"), ft.int(b"Rotate")), (Some(2), Some(90)));
+ assert_eq!(text(&dst, &ft, b"RC").as_deref(), Some(RICH));
+ let saved = write_full(&dst, &SaveOptions::default()).unwrap();
+ assert!(Document::open(Arc::new(saved)).is_ok());
+}
+
+/// A shading's function sits a dozen levels below the comment (appearance, form, resources,
+/// pattern, shading, function, functions, …); an FDF import nulled everything past 16 levels, so
+/// a gradient stamp lost its colours.
+#[test]
+fn deeply_nested_appearance_resources_survive_fdf_and_xfdf() {
+ let mut src = pages(1);
+ image_stamp(&mut src, "deep", "Stamp");
+ let d = named(&src, "deep");
+ let n = sub_dict(&src, &d, b"AP").get(b"N").and_then(Object::as_ref).unwrap();
+ let Object::Stream(mut form) = (*src.get(n)).clone() else { panic!("no form") };
+ let mut inner = Object::Array(vec![Object::Real(0.25), Object::Real(0.5), Object::Real(0.75)]);
+ for _ in 0..20 {
+ let mut level = Dict::new();
+ level.set(b"Next".to_vec(), inner);
+ inner = Object::Dict(level);
+ }
+ let mut res = sub_dict(&src, &form.dict, b"Resources");
+ res.set(b"Pattern".to_vec(), inner);
+ form.dict.set(b"Resources".to_vec(), Object::Dict(res));
+ src.set(n, Object::Stream(form));
+ let innermost = |doc: &Document| {
+ let d = named(doc, "deep");
+ let n = doc.resolve(sub_dict(doc, &d, b"AP").get(b"N").unwrap());
+ let Object::Stream(n) = n.as_ref() else { panic!("no form") };
+ let mut at = sub_dict(doc, &n.dict, b"Resources").get(b"Pattern").cloned().unwrap();
+ for _ in 0..20 {
+ at = at.as_dict().and_then(|d| d.get(b"Next")).cloned().unwrap_or(Object::Null);
+ }
+ f64s(doc, Some(&at))
+ };
+ let mut dst = pages(1);
+ import(&mut dst, &export_fdf(&src, true, false, "src.pdf").unwrap()).unwrap();
+ assert_eq!(innermost(&dst), vec![0.25, 0.5, 0.75], "FDF");
+ let (_, dst) = round_trip_xfdf(&src);
+ assert_eq!(innermost(&dst), vec![0.25, 0.5, 0.75], "XFDF");
+}
+
+#[test]
+fn fdf_comments_off_the_document_copy_no_streams_in() {
+ let mut src = pages(3);
+ // A stamp on the third page, imported into a one-page document: nothing to place it on.
+ image_stamp(&mut src, "far", "Stamp");
+ let r = xfdf::find_by_name(&src, "far").unwrap();
+ let p2 = page_ref(&src, 2);
+ let p0 = page_ref(&src, 0);
+ src.update_dict(p0, |p| {
+ p.remove(b"Annots");
+ })
+ .unwrap();
+ src.update_dict(p2, |p| p.set(b"Annots".to_vec(), Object::Array(vec![Object::Ref(r)]))).unwrap();
+ let fdf = export_fdf(&src, true, false, "src.pdf").unwrap();
+ let mut dst = pages(1);
+ let before = dst.add(Object::Null);
+ assert!(import(&mut dst, &fdf).is_err(), "nothing in the file is for this document");
+ let after = dst.add(Object::Null);
+ assert_eq!(after.num, before.num + 1, "the stamp's appearance and image were not copied in");
+}
+
+proptest! {
+ #![proptest_config(ProptestConfig { cases: 64, ..ProptestConfig::default() })]
+
+ /// Whatever formatting a free text and a line comment carry comes back the same.
+ #[test]
+ fn formatting_round_trips(
+ q in 0i64..3,
+ rotate in prop::sample::select(vec![0i64, 90, 180, 270]),
+ width in 0.0f64..20.0,
+ dashes in prop::collection::vec(0.5f64..30.0, 1..6),
+ fringe in prop::collection::vec(0.0f64..50.0, 4),
+ ll in -100.0f64..100.0,
+ lle in 0.0f64..50.0,
+ llo in 0.0f64..50.0,
+ ds in "[a-zA-Z0-9:;.# ]{0,40}",
+ ) {
+ // XFDF writes numbers to four decimals.
+ let r = |v: f64| (v * 10_000.0).round() / 10_000.0;
+ let mut src = pages(1);
+ let mut ft = formatted_freetext();
+ ft.set(b"Q".to_vec(), Object::Int(q));
+ ft.set(b"Rotate".to_vec(), Object::Int(rotate));
+ ft.set(b"RD".to_vec(), nums(&fringe));
+ ft.set(b"DS".to_vec(), PdfString::text(&ds));
+ let mut bs = Dict::new();
+ bs.set(b"W".to_vec(), Object::Real(width));
+ bs.set(b"S".to_vec(), Object::name("D"));
+ bs.set(b"D".to_vec(), nums(&dashes));
+ ft.set(b"BS".to_vec(), Object::Dict(bs));
+ put(&mut src, ft);
+ let mut ln = formatted_line();
+ ln.set(b"LL".to_vec(), Object::Real(ll));
+ ln.set(b"LLE".to_vec(), Object::Real(lle));
+ ln.set(b"LLO".to_vec(), Object::Real(llo));
+ put(&mut src, ln);
+ let (_, dst) = round_trip_xfdf(&src);
+ let ft = named(&dst, "ft");
+ prop_assert_eq!(ft.int(b"Q"), Some(q));
+ prop_assert_eq!(ft.int(b"Rotate"), Some(rotate));
+ prop_assert_eq!(f64s(&dst, ft.get(b"RD")), fringe.iter().map(|v| r(*v)).collect::>());
+ prop_assert_eq!(text(&dst, &ft, b"DS"), Some(ds.clone()));
+ let bs = sub_dict(&dst, &ft, b"BS");
+ prop_assert_eq!(bs.get(b"W").and_then(Object::as_f64), Some(r(width)));
+ prop_assert_eq!(f64s(&dst, bs.get(b"D")), dashes.iter().map(|v| r(*v)).collect::>());
+ let ln = named(&dst, "ln");
+ prop_assert_eq!(ln.get(b"LL").and_then(Object::as_f64), Some(r(ll)));
+ prop_assert_eq!(ln.get(b"LLE").and_then(Object::as_f64), Some(r(lle)));
+ prop_assert_eq!(ln.get(b"LLO").and_then(Object::as_f64), Some(r(llo)));
+ }
+
+ /// Any appearance dictionary of numbers, names, strings and nested data comes back the same.
+ #[test]
+ fn appearance_values_round_trip(
+ ints in prop::collection::vec(any::(), 0..8),
+ reals in prop::collection::vec(-1.0e6f64..1.0e6, 0..8),
+ names in prop::collection::vec("[A-Za-z#/ ]{1,12}", 0..5),
+ strings in prop::collection::vec(prop::collection::vec(any::(), 0..20), 0..5),
+ data in prop::collection::vec(any::(), 0..300),
+ ) {
+ let mut src = pages(1);
+ let mut extra = Dict::new();
+ extra.set(b"Ints".to_vec(), Object::Array(ints.iter().map(|i| Object::Int(*i)).collect()));
+ extra.set(b"Reals".to_vec(), Object::Array(reals.iter().map(|v| Object::Real(*v)).collect()));
+ extra.set(b"Names".to_vec(), Object::Array(names.iter().map(|n| Object::Name(n.as_bytes().to_vec())).collect()));
+ extra.set(b"Strings".to_vec(), Object::Array(strings.iter().map(|s| Object::String(PdfString::literal(s.clone()))).collect()));
+ let mut form = Dict::new();
+ form.set(b"Subtype".to_vec(), Object::name("Form"));
+ form.set(b"BBox".to_vec(), nums(&[0.0, 0.0, 10.0, 10.0]));
+ form.set(b"Extra".to_vec(), Object::Dict(extra.clone()));
+ let n = src.add(Object::Stream(Stream { dict: form, raw: data.clone().into() }));
+ let mut ap = Dict::new();
+ ap.set(b"N".to_vec(), Object::Ref(n));
+ let mut d = annot("Stamp", "p", [0.0, 0.0, 10.0, 10.0]);
+ d.set(b"AP".to_vec(), Object::Dict(ap));
+ put(&mut src, d);
+ let (_, dst) = round_trip_xfdf(&src);
+ let d = named(&dst, "p");
+ let n = dst.resolve(sub_dict(&dst, &d, b"AP").get(b"N").unwrap());
+ let Object::Stream(n) = n.as_ref() else { panic!("no appearance") };
+ prop_assert_eq!(n.raw.as_ref(), data.as_slice());
+ prop_assert_eq!(sub_dict(&dst, &n.dict, b"Extra"), extra);
+ }
+}
+
+/// A stamp on page 0 whose normal appearance is one form stream holding `content`.
+fn content_stamp(doc: &mut Document, nm: &str, content: Vec) -> ObjRef {
+ let mut form = Dict::new();
+ form.set(b"Type".to_vec(), Object::name("XObject"));
+ form.set(b"Subtype".to_vec(), Object::name("Form"));
+ form.set(b"BBox".to_vec(), nums(&[0.0, 0.0, 100.0, 50.0]));
+ let n = doc.add(Object::Stream(Stream { dict: form, raw: content.into() }));
+ let mut ap = Dict::new();
+ ap.set(b"N".to_vec(), Object::Ref(n));
+ let mut d = annot("Stamp", nm, [100.0, 500.0, 200.0, 550.0]);
+ d.set(b"AP".to_vec(), Object::Dict(ap));
+ put(doc, d);
+ n
+}
+
+/// The `` XML export wrote for the first comment of `xml`.
+fn exported_appearance(xml: &str) -> String {
+ let b64: String = xml.split("").nth(1).unwrap().split(" ").next().unwrap().split_whitespace().collect();
+ String::from_utf8(base64::engine::general_purpose::STANDARD.decode(b64).unwrap()).unwrap()
+}
+
+/// The write-time checks leave out the closing tags and the hexadecimal line breaks: an appearance
+/// just under the limit there came out over it, and import then refused what export wrote.
+#[test]
+fn an_exported_appearance_always_fits_what_import_reads() {
+ let mut src = pages(1);
+ content_stamp(&mut src, "big", vec![0u8; (appearance::MAX_APPEARANCE_BYTES / 2) - 4096]);
+ let d = named(&src, "big");
+ if let Some(text) = appearance::encode(&src, &d, &mut appearance::MAX_IMPORT_APPEARANCE_BYTES.clone()) {
+ let mut budget = appearance::MAX_IMPORT_APPEARANCE_BYTES;
+ appearance::decode(&text, &mut budget).expect("what export writes, import reads");
+ }
+ // Just under the limit once the line breaks are counted (one per 80 hexadecimal digits): it
+ // is written, and read back.
+ let mut src = pages(1);
+ content_stamp(&mut src, "near", vec![0u8; appearance::MAX_APPEARANCE_BYTES / 2 * 80 / 81 - 4096]);
+ let d = named(&src, "near");
+ let text = appearance::encode(&src, &d, &mut appearance::MAX_IMPORT_APPEARANCE_BYTES.clone()).expect("under the limit");
+ let mut budget = appearance::MAX_IMPORT_APPEARANCE_BYTES;
+ appearance::decode(&text, &mut budget).expect("what export writes, import reads");
+}
+
+/// A page whose `/Type` is a reference is still the source page: written in place it would carry
+/// the page's contents into a file meant to hold one comment.
+#[test]
+fn a_page_with_an_indirect_type_stays_out_of_an_exported_appearance() {
+ let mut src = pages(1);
+ let n = content_stamp(&mut src, "pg", b"q Q".to_vec());
+ let page = page_ref(&src, 0);
+ let page_type = src.add(Object::name("Page"));
+ src.update_dict(page, |p| p.set(b"Type".to_vec(), Object::Ref(page_type))).unwrap();
+ let Object::Stream(mut form) = (*src.get(n)).clone() else { panic!("no form") };
+ form.dict.set(b"PieceInfo".to_vec(), Object::Ref(page));
+ src.set(n, Object::Stream(form));
+ let inner = exported_appearance(&export_xfdf(&src, true, false, "src.pdf"));
+ assert!(inner.contains(r#" "#), "{inner}");
+ assert!(!inner.contains("MediaBox"), "{inner}");
+}
+
+/// XML reads a carriage return as a line feed, so data holding one goes out as hexadecimal.
+#[test]
+fn stream_data_with_carriage_returns_comes_back_byte_for_byte() {
+ let mut src = pages(1);
+ let data = b"q\r/Im0\rDo\r\nQ\r".to_vec();
+ content_stamp(&mut src, "cr", data.clone());
+ let (_, dst) = round_trip_xfdf(&src);
+ let d = named(&dst, "cr");
+ let n = dst.resolve(sub_dict(&dst, &d, b"AP").get(b"N").unwrap());
+ let Object::Stream(n) = n.as_ref() else { panic!("no appearance") };
+ assert_eq!(n.raw.as_ref(), data.as_slice());
+}
+
+/// XFDF has no appearance state: the stream `/AS` selects is what goes out.
+#[test]
+fn the_selected_appearance_state_is_what_xfdf_carries() {
+ let mut src = pages(1);
+ let on = content_stamp(&mut src, "st", b"0 0 1 rg 0 0 100 50 re f".to_vec());
+ let off = src.add(Object::Stream(Stream { dict: Dict::new(), raw: b"%off".to_vec().into() }));
+ let mut states = Dict::new();
+ states.set(b"On".to_vec(), Object::Ref(on));
+ states.set(b"Off".to_vec(), Object::Ref(off));
+ let mut ap = Dict::new();
+ ap.set(b"N".to_vec(), Object::Dict(states.clone()));
+ ap.set(b"D".to_vec(), Object::Dict(states));
+ let r = xfdf::find_by_name(&src, "st").unwrap();
+ src.update_dict(r, |d| {
+ d.set(b"AP".to_vec(), Object::Dict(ap.clone()));
+ d.set(b"AS".to_vec(), Object::name("On"));
+ })
+ .unwrap();
+ let (_, dst) = round_trip_xfdf(&src);
+ let d = named(&dst, "st");
+ let ap = sub_dict(&dst, &d, b"AP");
+ for key in [b"N".as_slice(), b"D"] {
+ let s = dst.resolve(ap.get(key).unwrap());
+ let Object::Stream(s) = s.as_ref() else { panic!("{key:?} is not the selected stream: {s:?}") };
+ assert_eq!(s.raw.as_ref(), b"0 0 1 rg 0 0 100 50 re f");
+ }
+ // A state no stream answers to has nothing to draw: no appearance goes out.
+ src.update_dict(r, |d| d.set(b"AS".to_vec(), Object::name("Gone"))).unwrap();
+ assert!(!export_xfdf(&src, true, false, "src.pdf").contains(""));
+}
+
+/// Forms that draw forms: FDF export writes the chain however long, and import copied only the
+/// first dozen and nulled the rest without a word. A chain sixty forms deep comes back whole; one
+/// deeper than import follows is refused rather than imported in part.
+#[test]
+fn a_chain_of_forms_comes_back_whole_from_fdf_or_is_refused() {
+ let chain = |forms: usize| {
+ let mut src = pages(1);
+ put(&mut src, annot("Text", "first", [10.0, 10.0, 30.0, 30.0]));
+ let mut inner = src.add(Object::Stream(Stream { dict: Dict::new(), raw: b"%innermost".to_vec().into() }));
+ for _ in 0..forms {
+ let mut xo = Dict::new();
+ xo.set(b"Fm".to_vec(), Object::Ref(inner));
+ let mut res = Dict::new();
+ res.set(b"XObject".to_vec(), Object::Dict(xo));
+ let mut form = Dict::new();
+ form.set(b"Subtype".to_vec(), Object::name("Form"));
+ form.set(b"Resources".to_vec(), Object::Dict(res));
+ inner = src.add(Object::Stream(Stream { dict: form, raw: b"/Fm Do".to_vec().into() }));
+ }
+ let mut ap = Dict::new();
+ ap.set(b"N".to_vec(), Object::Ref(inner));
+ let mut d = annot("Stamp", "chain", [100.0, 500.0, 200.0, 550.0]);
+ d.set(b"AP".to_vec(), Object::Dict(ap));
+ put(&mut src, d);
+ export_fdf(&src, true, false, "src.pdf").unwrap()
+ };
+ let mut dst = pages(1);
+ import(&mut dst, &chain(60)).unwrap();
+ let d = named(&dst, "chain");
+ let mut at = dst.resolve(sub_dict(&dst, &d, b"AP").get(b"N").unwrap());
+ for level in 0..60 {
+ let Object::Stream(s) = at.as_ref() else { panic!("level {level}: {at:?}") };
+ let fm = sub_dict(&dst, &sub_dict(&dst, &s.dict, b"Resources"), b"XObject").get(b"Fm").cloned().unwrap_or(Object::Null);
+ at = dst.resolve(&fm);
+ }
+ let Object::Stream(innermost) = at.as_ref() else { panic!("the innermost form was lost: {at:?}") };
+ assert_eq!(innermost.raw.as_ref(), b"%innermost");
+ let mut dst = pages(1);
+ let before = dst.add(Object::Null);
+ let err = import(&mut dst, &chain(80)).unwrap_err();
+ assert!(err.to_string().contains("nest more than"), "{err}");
+ // All or nothing: the note before the stamp, and the forms copied so far, are not left behind.
+ assert_eq!(dst.add(Object::Null).num, before.num + 1);
+ assert!(xfdf::find_by_name(&dst, "first").is_none());
+}
+
+/// A `/P` an FDF comment holds points into the FDF; it is replaced, and nothing it reaches is
+/// copied into the document.
+#[test]
+fn an_fdf_comments_page_link_copies_nothing_in() {
+ let fdf = |p: &str| {
+ format!(
+ "%FDF-1.2\n1 0 obj\n<< /FDF << /Annots [2 0 R] >> >>\nendobj\n2 0 obj\n<< /Type /Annot /Subtype /Text /Rect [10 10 30 30] /NM (t) /Page 0{p} >>\nendobj\n3 0 obj\n<< /Type /Page /Junk 4 0 R >>\nendobj\n4 0 obj\n<< /Length 5 >>\nstream\nhello\nendstream\nendobj\ntrailer\n<< /Root 1 0 R >>\n%%EOF\n"
+ )
+ .into_bytes()
+ };
+ let added = |bytes: &[u8]| {
+ let mut dst = pages(1);
+ let before = dst.add(Object::Null);
+ import(&mut dst, bytes).unwrap();
+ let p = named(&dst, "t").reference(b"P");
+ assert_eq!(p, Some(page_ref(&dst, 0)));
+ dst.add(Object::Null).num - before.num
+ };
+ assert_eq!(added(&fdf(" /P 3 0 R")), added(&fdf("")), "the FDF's page and its stream were not copied in");
+}
+
+/// Two line breaks in a row leave a blank line in the comment's plain text.
+#[test]
+fn consecutive_rich_text_line_breaks_are_kept() {
+ let xml = r#"
+one two
three
four
+ "#;
+ let mut dst = pages(1);
+ import(&mut dst, xml.as_bytes()).unwrap();
+ assert_eq!(text(&dst, &named(&dst, "b"), b"Contents").as_deref(), Some("one\r\rtwo\r\rthree\rfour"));
+}
+
+/// Rich text that is not XML, on a comment with no plain text, comes back as rich text, not as
+/// the comment's text (a line would otherwise show the markup as its caption).
+#[test]
+fn rich_text_alone_that_is_not_xml_comes_back_as_rich_text() {
+ let mut src = pages(1);
+ let mut d = annot("Line", "ln", [10.0, 10.0, 90.0, 30.0]);
+ d.set(b"L".to_vec(), nums(&[10.0, 20.0, 90.0, 20.0]));
+ d.set(b"RC".to_vec(), PdfString::text("unclosed"));
+ put(&mut src, d);
+ let (_, dst) = round_trip_xfdf(&src);
+ let d = named(&dst, "ln");
+ assert_eq!(text(&dst, &d, b"RC").as_deref(), Some("
unclosed"));
+ assert_ne!(text(&dst, &d, b"Contents").as_deref(), Some("
unclosed"));
+}
+
+/// A prefix the rich text inherits from the XFDF around it is declared on it, so the rich text
+/// is XML of its own and goes out again as markup.
+#[test]
+fn rich_text_keeps_the_namespaces_it_inherits() {
+ let xml = r#"
+hi hi
+ "#;
+ let mut dst = pages(1);
+ import(&mut dst, xml.as_bytes()).unwrap();
+ let rc = text(&dst, &named(&dst, "ns"), b"RC").unwrap();
+ assert!(common::parse_form_xml(&rc).is_ok(), "{rc}");
+ let out = export_xfdf(&dst, true, false, "dst.pdf");
+ assert!(
+ out.contains(r#"%nothing
"#,
+ );
+ for extra in [r#" style="cloudy""#, r#" overlay-text="日本語""#] {
+ let xml = appearance_xfdf(&inner, "redact").replace(r#"name="x""#, &format!(r#"name="x"{extra}"#));
+ let mut dst = pages(1);
+ let before = dst.add(Object::Null);
+ import(&mut dst, xml.as_bytes()).unwrap();
+ let d = named(&dst, "x");
+ let n = dst.resolve(sub_dict(&dst, &d, b"AP").get(b"N").unwrap());
+ let Object::Stream(n) = n.as_ref() else { panic!("{extra}: no appearance") };
+ let drawn = n.decoded().unwrap();
+ assert_ne!(drawn, b"%nothing", "{extra}");
+ assert!(String::from_utf8_lossy(&drawn).contains("h S"), "{extra}: the outline is stroked: {}", String::from_utf8_lossy(&drawn));
+ assert!(!d.contains(b"BE"), "{extra}");
+ // The file's appearance was not read in at all.
+ for num in before.num..dst.add(Object::Null).num {
+ if let Object::Stream(s) = dst.get(ObjRef::new(num, 0)).as_ref() {
+ assert_ne!(s.raw.as_ref(), b"%nothing", "{extra}");
+ }
+ }
+ }
+}
+
+/// Appearances share one budget over the whole import: past it, the rest are skipped.
+#[test]
+fn the_import_budget_is_shared_by_every_comment() {
+ let one = b64(r#"0 0 m 1 1 l S "#);
+ let size = base64::engine::general_purpose::STANDARD.decode(&one).unwrap().len();
+ let stamps: String = ["a", "b", "c"]
+ .iter()
+ .map(|nm| format!(r#"{one} "#))
+ .collect();
+ let xml = format!(r#"{stamps} "#);
+ let mut dst = pages(1);
+ let report = xfdf::import_xfdf_with(&mut dst, &xml, None, None, None, size * 5 / 2, false).unwrap();
+ assert_eq!(report.comments, 3);
+ assert_eq!(report.skipped.len(), 1, "{:?}", report.skipped);
+ assert!(report.skipped[0].starts_with("c: "), "{:?}", report.skipped);
+}
+
+/// A dash array of any length export writes comes back (65 numbers were written and dropped).
+#[test]
+fn a_long_dash_array_comes_back() {
+ let mut src = pages(1);
+ let dashes: Vec = (1..=65).map(f64::from).collect();
+ let mut bs = Dict::new();
+ bs.set(b"W".to_vec(), Object::Real(1.0));
+ bs.set(b"S".to_vec(), Object::name("D"));
+ bs.set(b"D".to_vec(), nums(&dashes));
+ let mut d = annot("Square", "sq", [10.0, 10.0, 90.0, 60.0]);
+ d.set(b"BS".to_vec(), Object::Dict(bs));
+ put(&mut src, d);
+ let (_, dst) = round_trip_xfdf(&src);
+ assert_eq!(f64s(&dst, sub_dict(&dst, &named(&dst, "sq"), b"BS").get(b"D")), dashes);
+}
+
+/// Export stops writing appearances where import would stop reading them, so every appearance
+/// written comes back.
+#[test]
+fn export_writes_no_more_appearance_than_import_reads() {
+ let mut src = pages(1);
+ content_stamp(&mut src, "a", b"0 0 m 1 1 l S".to_vec());
+ let d = named(&src, "a");
+ let mut probe = usize::MAX;
+ let one = appearance::encode(&src, &d, &mut probe).unwrap();
+ let size = usize::MAX - probe;
+ let mut budget = size * 3 / 2;
+ assert_eq!(appearance::encode(&src, &d, &mut budget), Some(one));
+ assert_eq!(appearance::encode(&src, &d, &mut budget), None, "past what import reads");
+}
+
+/// The export loop shares one budget over all of its comments: of five stamps whose appearances
+/// together are past what import reads, the fifth goes out without one, and import reads every
+/// appearance that was written.
+#[test]
+fn the_export_loop_writes_no_more_appearance_than_import_reads() {
+ let mut src = pages(1);
+ // About 14 MiB of XML each (hexadecimal): four fit in 64 MiB, five do not.
+ let form = content_stamp(&mut src, "s1", vec![0u8; 7 << 20]);
+ for nm in ["s2", "s3", "s4", "s5"] {
+ let mut ap = Dict::new();
+ ap.set(b"N".to_vec(), Object::Ref(form));
+ let mut d = annot("Stamp", nm, [100.0, 500.0, 200.0, 550.0]);
+ d.set(b"AP".to_vec(), Object::Dict(ap));
+ put(&mut src, d);
+ }
+ let xml = export_xfdf(&src, true, false, "src.pdf");
+ assert_eq!(xml.matches("").count(), 4);
+ let mut dst = pages(1);
+ let report = xfdf::import_xfdf(&mut dst, &xml).unwrap();
+ assert_eq!(report.comments, 5);
+ assert!(report.skipped.is_empty(), "{:?}", report.skipped);
+}
+
+/// Printable data is written as it is, so a budget it fits as text takes it (the size check
+/// counted it as hexadecimal, twice as long, and left the appearance out).
+#[test]
+fn printable_appearance_data_that_fits_the_budget_as_text_is_written() {
+ let mut src = pages(1);
+ // Printable as XFDF 3.0 counts it: no spaces.
+ content_stamp(&mut src, "a", "q\nQ\n".repeat(500).into_bytes());
+ let d = named(&src, "a");
+ let mut probe = usize::MAX;
+ let one = appearance::encode(&src, &d, &mut probe).unwrap();
+ let mut budget = usize::MAX - probe;
+ assert!(budget < 3000, "written as text, not hexadecimal: {budget}");
+ assert_eq!(appearance::encode(&src, &d, &mut budget), Some(one), "fits exactly");
+ assert_eq!(budget, 0);
+}
+
+/// A copied redaction mark goes without its appearance (import draws the mark itself and never
+/// reads one), so it leaves the shared budget to the comments whose appearances are read.
+#[test]
+fn a_copied_redaction_mark_spends_no_appearance_budget() {
+ let mut src = pages(1);
+ let form = content_stamp(&mut src, "st", b"0 0 m 1 1 l S".to_vec());
+ let mut ap = Dict::new();
+ ap.set(b"N".to_vec(), Object::Ref(form));
+ let mut rd = annot("Redact", "rd", [300.0, 10.0, 400.0, 30.0]);
+ rd.set(b"AP".to_vec(), Object::Dict(ap));
+ put(&mut src, rd);
+ let copy = export_xfdf_comments(&src, &[(0, 0), (0, 1)], "src.pdf");
+ assert_eq!(copy.matches("").count(), 1, "{copy}");
+ let redact = copy.split("").next().unwrap();
+ assert!(!redact.contains(""), "{copy}");
+}
+
+/// A page an FDF stamp's appearance reaches (its /Type a reference here) is not copied in with
+/// its contents.
+#[test]
+fn an_fdf_appearance_that_reaches_a_page_copies_no_page_in() {
+ let fdf = b"%FDF-1.2\n1 0 obj\n<< /FDF << /Annots [2 0 R] >> >>\nendobj\n\
+2 0 obj\n<< /Type /Annot /Subtype /Stamp /Rect [10 10 60 60] /NM (s) /Page 0 /AP << /N 3 0 R >> >>\nendobj\n\
+3 0 obj\n<< /Subtype /Form /BBox [0 0 1 1] /PieceInfo 4 0 R /Length 3 >>\nstream\nq Q\nendstream\nendobj\n\
+4 0 obj\n<< /Type 6 0 R /Contents 5 0 R >>\nendobj\n\
+5 0 obj\n<< /Length 11 >>\nstream\npagecontent\nendstream\nendobj\n\
+6 0 obj\n/Page\nendobj\ntrailer\n<< /Root 1 0 R >>\n%%EOF\n";
+ let mut dst = pages(1);
+ let before = dst.add(Object::Null);
+ import(&mut dst, fdf).unwrap();
+ for num in before.num..dst.add(Object::Null).num {
+ if let Object::Stream(s) = dst.get(ObjRef::new(num, 0)).as_ref() {
+ assert_ne!(s.raw.as_ref(), b"pagecontent", "the page's contents were copied in");
+ }
+ }
+ let n = dst.resolve(sub_dict(&dst, &named(&dst, "s"), b"AP").get(b"N").unwrap());
+ let Object::Stream(n) = n.as_ref() else { panic!("no appearance") };
+ assert!(matches!(n.dict.get(b"PieceInfo"), None | Some(Object::Null)), "{:?}", n.dict.get(b"PieceInfo"));
+}
+
+/// Rich text keeps the default (XHTML) namespace it inherits from ``, and a
+/// prefix it redeclares with spaces around `=` is not declared twice.
+#[test]
+fn rich_text_keeps_an_inherited_default_namespace() {
+ let xml = r#"
+hi hi
+hi hi
+ "#;
+ let mut dst = pages(1);
+ import(&mut dst, xml.as_bytes()).unwrap();
+ let rc = text(&dst, &named(&dst, "d"), b"RC").unwrap();
+ let parsed = common::parse_form_xml(&rc).unwrap();
+ assert_eq!(parsed.root_element().tag_name().namespace(), Some("http://www.w3.org/1999/xhtml"), "{rc}");
+ let rc = text(&dst, &named(&dst, "w"), b"RC").unwrap();
+ assert!(common::parse_form_xml(&rc).is_ok(), "{rc}");
+ assert!(!rc.contains(r#"xmlns:a="urn:a""#), "{rc}");
+}
+
+/// A declaration written inside another attribute's value declares nothing, so the prefix the
+/// rich text inherits is still declared on it; and a prefixed root keeps the default (XHTML)
+/// namespace its unprefixed descendants inherit. A `>` in an attribute value is not the end of
+/// the start tag.
+#[test]
+fn rich_text_namespaces_come_from_attributes_and_the_scope() {
+ let xml = r#"
+hi hi
+hi hi
+hi hi
+ "#;
+ let mut dst = pages(1);
+ import(&mut dst, xml.as_bytes()).unwrap();
+ let rc = text(&dst, &named(&dst, "v"), b"RC").unwrap();
+ let parsed = common::parse_form_xml(&rc).unwrap_or_else(|e| panic!("{e}: {rc}"));
+ assert!(parsed.root_element().attributes().any(|a| a.namespace() == Some("urn:b")), "{rc}");
+ let rc = text(&dst, &named(&dst, "g"), b"RC").unwrap();
+ assert!(common::parse_form_xml(&rc).is_ok(), "a `>` in a value does not end the start tag: {rc}");
+ let rc = text(&dst, &named(&dst, "p"), b"RC").unwrap();
+ let parsed = common::parse_form_xml(&rc).unwrap();
+ let p = parsed.descendants().find(|n| n.has_tag_name("p")).unwrap();
+ assert_eq!(p.tag_name().namespace(), Some("http://www.w3.org/1999/xhtml"), "{rc}");
+}
+
+/// A redaction mark whose /Rect has no area shows its quads all the same: the /Rect grows to hold
+/// them.
+#[test]
+fn a_redaction_marks_rect_holds_its_quads() {
+ let xml = r#" "#;
+ let mut dst = pages(1);
+ import(&mut dst, xml.as_bytes()).unwrap();
+ assert_eq!(f64s(&dst, named(&dst, "r").get(b"Rect")), vec![10.0, 20.0, 90.0, 50.0]);
+}
diff --git a/crates/xfdf/src/xfdf.rs b/crates/xfdf/src/xfdf.rs
index e2137a98f0..c5ec3d642d 100644
--- a/crates/xfdf/src/xfdf.rs
+++ b/crates/xfdf/src/xfdf.rs
@@ -1,6 +1,6 @@
use super::common::{
FLAGS, MAX_DEPTH, SUBTYPES, arr, check_form_xml_depth, csv, esc, hex, n, nums_of, parse_form_xml, parse_hex, quad_has_area, rect_strict, text_of,
- walk_xfdf,
+ walk_xfdf, xml_nesting_depth,
};
use super::*;
@@ -99,31 +99,259 @@ fn read_own_keys(node: roxmltree::Node, d: &mut Dict) {
}
}
-/// The name of every annotation, for `inreplyto`: its /NM, or, for one in `only` without one
-/// (other tools leave /NM out), a name new to the document for this export, so a reply copied
-/// with it still finds it.
+/// Rich text deeper than this is written as text rather than as markup, so the XFDF it goes into
+/// stays well inside the nesting the reader accepts (`MAX_XML_DEPTH`).
+const MAX_RICH_DEPTH: usize = 512;
+
+/// Rich text (`/RC`) as `` holds it: its root element alone (no XML
+/// declaration), when the text is well-formed XML; `None` otherwise.
+fn rich_text_element(rc: &str) -> Option<&str> {
+ let t = rc.trim_start_matches('\u{feff}');
+ if xml_nesting_depth(t) > MAX_RICH_DEPTH {
+ return None;
+ }
+ let parsed = parse_form_xml(t).ok()?;
+ t.get(parsed.root_element().range())
+}
+
+/// The formatting attributes of a comment: XFDF 3.0 "Border style attributes" (`width`, `style`,
+/// `dashes`), "Border effect attributes" (`style="cloudy"`, `intensity`), and the free text
+/// (`rotation`, `justification`), stamp (`rotation`), circle/square/caret (`fringe`), line
+/// (`leaderLength`, `leaderExtend`, `leader-offset`, `caption`, `caption-style`,
+/// `caption-offset-h`/`-v`), caret (`symbol`) and redaction (`overlay-text`,
+/// `overlay-text-repeat`, `justification`) attributes.
+fn format_attrs(doc: &Document, d: &Dict, sub: &[u8], attrs: &mut String) {
+ let num = |k: &[u8]| d.get(k).and_then(|o| doc.resolve(o).as_f64()).filter(|v| v.is_finite());
+ let name = |k: &[u8]| d.get(k).and_then(|o| doc.resolve(o).as_name().map(<[u8]>::to_vec));
+ let list = |v: &[f64]| v.iter().map(|x| n(*x)).collect::>().join(",");
+ // The border: /BS, or (without one) the older /Border array [h v width dashes].
+ let (width, style, dashes) = match d.get(b"BS").map(|b| doc.resolve(b)).and_then(|b| b.as_dict().cloned()) {
+ Some(bs) => (
+ bs.get(b"W").and_then(|w| doc.resolve(w).as_f64()),
+ bs.get(b"S").and_then(|s| doc.resolve(s).as_name().map(<[u8]>::to_vec)),
+ nums_of(doc, bs.get(b"D")),
+ ),
+ None => {
+ let border = d.get(b"Border").map(|b| doc.resolve(b)).and_then(|b| b.as_array().cloned()).unwrap_or_default();
+ let dash = border.get(3).map(|x| nums_of(doc, Some(x))).unwrap_or_default();
+ (border.get(2).and_then(|w| doc.resolve(w).as_f64()), (!dash.is_empty()).then(|| b"D".to_vec()), dash)
+ }
+ };
+ if let Some(w) = width.filter(|w| w.is_finite()) {
+ let _ = write!(attrs, " width=\"{}\"", n(w));
+ }
+ // One `style` attribute names both: a cloudy border effect (/BE /S /C) takes it.
+ let cloudy = d.get(b"BE").map(|o| doc.resolve(o)).and_then(|o| o.as_dict().cloned()).filter(|b| b.name(b"S") == Some(b"C".as_slice()));
+ if let Some(be) = cloudy {
+ attrs.push_str(" style=\"cloudy\"");
+ if let Some(i) = be.get(b"I").and_then(|i| doc.resolve(i).as_f64()).filter(|i| i.is_finite()) {
+ let _ = write!(attrs, " intensity=\"{}\"", n(i));
+ }
+ } else if let Some(s) = match style.as_deref() {
+ Some(b"D") => Some("dash"),
+ Some(b"B") => Some("bevelled"),
+ Some(b"I") => Some("inset"),
+ Some(b"U") => Some("underline"),
+ _ => None,
+ } {
+ let _ = write!(attrs, " style=\"{s}\"");
+ }
+ // The dash array (/D) whatever the style, as `dashes` maps it; only `style="dash"` draws it.
+ if !dashes.is_empty() && dashes.iter().all(|v| v.is_finite()) {
+ let _ = write!(attrs, " dashes=\"{}\"", list(&dashes));
+ }
+ if let Some(r) = d.get(b"Rotate").and_then(|o| doc.resolve(o).as_int()) {
+ let _ = write!(attrs, " rotation=\"{r}\"");
+ }
+ if let Some(q) = d.get(b"Q").and_then(|o| doc.resolve(o).as_int()) {
+ // Free text names its justification; a redaction mark gives the number (XFDF 3.0).
+ match (sub, q) {
+ (b"FreeText", 0) => attrs.push_str(" justification=\"left\""),
+ (b"FreeText", 1) => attrs.push_str(" justification=\"centered\""),
+ (b"FreeText", 2) => attrs.push_str(" justification=\"right\""),
+ (b"FreeText", _) => {}
+ (_, q) => {
+ let _ = write!(attrs, " justification=\"{q}\"");
+ }
+ }
+ }
+ let rd = nums_of(doc, d.get(b"RD"));
+ if rd.len() == 4 && rd.iter().all(|v| v.is_finite()) {
+ let _ = write!(attrs, " fringe=\"{}\"", list(&rd));
+ }
+ if let Some(ll) = num(b"LL") {
+ let _ = write!(attrs, " leaderLength=\"{}\"", n(ll));
+ }
+ if let Some(lle) = num(b"LLE") {
+ let _ = write!(attrs, " leaderExtend=\"{}\"", n(lle));
+ }
+ if let Some(llo) = num(b"LLO") {
+ let _ = write!(attrs, " leader-offset=\"{}\"", n(llo));
+ }
+ if let Some(Object::Bool(cap)) = d.get(b"Cap").map(|o| doc.resolve(o)).as_deref() {
+ let _ = write!(attrs, " caption=\"{}\"", if *cap { "yes" } else { "no" });
+ }
+ if let Some(cp) = name(b"CP") {
+ let _ = write!(attrs, " caption-style=\"{}\"", esc(&String::from_utf8_lossy(&cp)));
+ }
+ if let [h, v] = nums_of(doc, d.get(b"CO")).as_slice()
+ && h.is_finite()
+ && v.is_finite()
+ {
+ let _ = write!(attrs, " caption-offset-h=\"{}\" caption-offset-v=\"{}\"", n(*h), n(*v));
+ }
+ match name(b"Sy").as_deref() {
+ Some(b"P") => attrs.push_str(" symbol=\"paragraph\""),
+ Some(b"None") => attrs.push_str(" symbol=\"none\""),
+ _ => {}
+ }
+ if let Some(t) = text_of(doc, d, b"OverlayText") {
+ let _ = write!(attrs, " overlay-text=\"{}\"", esc(&t));
+ }
+ if let Some(Object::Bool(repeat)) = d.get(b"Repeat").map(|o| doc.resolve(o)).as_deref() {
+ let _ = write!(attrs, " overlay-text-repeat=\"{repeat}\"");
+ }
+}
+
+/// The formatting attributes of an XFDF comment element back as dictionary entries (see
+/// [`format_attrs`]). Values that are not numbers, or out of range, are left out.
+fn read_format(node: roxmltree::Node, d: &mut Dict) {
+ let num = |a: &str| node.attribute(a).and_then(|v| v.trim().parse::().ok()).filter(|v| v.is_finite());
+ let style = node.attribute("style").map(str::trim);
+ let dashes = node.attribute("dashes").map(csv).filter(|v| !v.is_empty() && v.iter().all(|x| *x >= 0.0) && v.iter().any(|x| *x > 0.0));
+ let bs_style = match style {
+ Some("dash") => Some("D"),
+ Some("bevelled" | "beveled") => Some("B"),
+ Some("inset") => Some("I"),
+ Some("underline") => Some("U"),
+ Some("solid") => Some("S"),
+ _ => None,
+ };
+ let width = num("width");
+ if width.is_some() || bs_style.is_some() || dashes.is_some() {
+ let mut bs = Dict::new();
+ // XFDF 3.0: the width is 1 and the style solid unless given.
+ bs.set(b"W".to_vec(), Object::Real(width.unwrap_or(1.0).max(0.0)));
+ bs.set(b"S".to_vec(), Object::name(bs_style.unwrap_or("S")));
+ if let Some(dv) = &dashes {
+ bs.set(b"D".to_vec(), arr(dv));
+ }
+ d.set(b"BS".to_vec(), Object::Dict(bs));
+ }
+ if style == Some("cloudy") {
+ let mut be = Dict::new();
+ be.set(b"S".to_vec(), Object::name("C"));
+ let intensity = num("intensity").unwrap_or(1.0);
+ be.set(b"I".to_vec(), Object::Real(intensity.clamp(0.0, 2.0)));
+ d.set(b"BE".to_vec(), Object::Dict(be));
+ }
+ if let Some(r) = node.attribute("rotation").and_then(|r| r.trim().parse::().ok()) {
+ d.set(b"Rotate".to_vec(), Object::Int(i64::from(r)));
+ }
+ let q = match node.attribute("justification").map(str::trim) {
+ Some("left" | "0") => Some(0),
+ Some("centered" | "center" | "1") => Some(1),
+ Some("right" | "2") => Some(2),
+ _ => None,
+ };
+ if let Some(q) = q {
+ d.set(b"Q".to_vec(), Object::Int(q));
+ }
+ if let Some(rd) = node.attribute("fringe").map(csv).filter(|r| r.len() == 4) {
+ d.set(b"RD".to_vec(), arr(&rd));
+ }
+ if let Some(ll) = num("leaderLength") {
+ d.set(b"LL".to_vec(), Object::Real(ll));
+ }
+ if let Some(lle) = num("leaderExtend").filter(|v| *v >= 0.0) {
+ d.set(b"LLE".to_vec(), Object::Real(lle));
+ }
+ if let Some(llo) = num("leader-offset").filter(|v| *v >= 0.0) {
+ d.set(b"LLO".to_vec(), Object::Real(llo));
+ }
+ match node.attribute("caption").map(str::trim) {
+ Some("yes" | "true") => d.set(b"Cap".to_vec(), Object::Bool(true)),
+ Some("no" | "false") => d.set(b"Cap".to_vec(), Object::Bool(false)),
+ _ => {}
+ }
+ if let Some(cp) = node.attribute("caption-style").map(str::trim).filter(|c| matches!(*c, "Inline" | "Top")) {
+ d.set(b"CP".to_vec(), Object::name(cp));
+ }
+ let (h, v) = (num("caption-offset-h"), num("caption-offset-v"));
+ if h.is_some() || v.is_some() {
+ d.set(b"CO".to_vec(), arr(&[h.unwrap_or(0.0), v.unwrap_or(0.0)]));
+ }
+ match node.attribute("symbol").map(str::trim) {
+ Some("paragraph" | "P") => d.set(b"Sy".to_vec(), Object::name("P")),
+ Some("none" | "None") => d.set(b"Sy".to_vec(), Object::name("None")),
+ _ => {}
+ }
+ if let Some(t) = node.attribute("overlay-text") {
+ d.set(b"OverlayText".to_vec(), PdfString::text(t));
+ }
+ match node.attribute("overlay-text-repeat").map(str::trim) {
+ Some("true" | "yes") => d.set(b"Repeat".to_vec(), Object::Bool(true)),
+ Some("false" | "no") => d.set(b"Repeat".to_vec(), Object::Bool(false)),
+ _ => {}
+ }
+}
+
+/// A `` element's plain text, a line per paragraph: what `/Contents` gets
+/// when the element comes without ``.
+fn rich_plain(node: roxmltree::Node) -> String {
+ let mut out = String::new();
+ for n in node.descendants() {
+ // A line break is a line of its own, so two in a row leave a blank line; a paragraph
+ // starts on a new line.
+ if n.is_element() && n.tag_name().name() == "br" {
+ out.push('\r');
+ } else if n.is_element() && matches!(n.tag_name().name(), "p" | "div" | "li") {
+ if !out.is_empty() && !out.ends_with('\r') {
+ out.push('\r');
+ }
+ } else if let Some(t) = n.text().filter(|_| n.is_text()) {
+ // Indentation between elements is not text.
+ if !(t.trim().is_empty() && t.contains('\n')) {
+ out.push_str(&t.replace("\r\n", "\r").replace('\n', "\r"));
+ }
+ }
+ }
+ out.trim_end_matches('\r').to_string()
+}
+
+/// The name of every annotation, for `inreplyto`: its /NM, or, for one without one (other tools
+/// leave /NM out) that is in `only` or that another annotation replies to or is grouped under
+/// (`/IRT`, ISO 32000-2 §12.5.6.2; a Replace Text pair is such a group), a name new to the
+/// document for this export, so the link survives the round trip. Made-up names are never written
+/// into the PDF.
fn annotation_names(doc: &Document, pages: &[pdfcraft_model::Page], only: Option<&HashSet<(usize, usize)>>) -> HashMap {
let mut names: HashMap = HashMap::new();
let mut unnamed: Vec<(usize, usize, ObjRef)> = Vec::new();
+ let mut targets: HashSet = HashSet::new();
// Every name in use, those of annotations written straight into the page array too, so a
// given name is new.
let mut taken: HashSet = HashSet::new();
for (pi, p) in pages.iter().enumerate() {
for (ai, a) in p.dict.get(b"Annots").map(|a| doc.resolve(a)).and_then(|a| a.as_array().cloned()).unwrap_or_default().into_iter().enumerate() {
- let nm = doc.resolve(&a).as_dict().and_then(|d| text_of(doc, d, b"NM"));
+ let d = doc.resolve(&a).as_dict().cloned();
+ if let Some(t) = d.as_ref().and_then(|d| d.get(b"IRT")).and_then(Object::as_ref) {
+ targets.insert(t);
+ }
+ let nm = d.as_ref().and_then(|d| text_of(doc, d, b"NM")).filter(|nm| !nm.is_empty());
if let Some(nm) = &nm {
taken.insert(nm.clone());
}
+ // Only an indirect annotation can be an `/IRT` target, so only it is keyed here.
let Some(r) = a.as_ref() else { continue };
match nm {
Some(nm) => {
names.insert(r, nm);
}
- None if only.is_some_and(|only| only.contains(&(pi, ai))) => unnamed.push((pi, ai, r)),
- None => {}
+ None => unnamed.push((pi, ai, r)),
}
}
}
+ unnamed.retain(|(pi, ai, r)| only.is_some_and(|only| only.contains(&(*pi, *ai))) || targets.contains(r));
for (pi, ai, r) in unnamed {
let mut name = format!("pdfcraft-{pi}-{ai}");
while taken.contains(&name) {
@@ -135,15 +363,42 @@ fn annotation_names(doc: &Document, pages: &[pdfcraft_model::Page], only: Option
names
}
-/// The elements inside a comment's XFDF element: its text, default appearance, ink, vertices
-/// and pop-up (on page `pi`).
-fn xfdf_annot_children(doc: &Document, out: &mut String, d: &Dict, pi: usize) {
- if let Some(c) = text_of(doc, d, b"Contents") {
- let _ = write!(out, "{} ", esc(&c));
+/// The elements inside a comment's XFDF element: its text (plain and rich), default appearance
+/// and style, ink, vertices, appearance (with `ap`) and pop-up (on page `pi`).
+fn xfdf_annot_children(doc: &Document, out: &mut String, d: &Dict, pi: usize, ap: Option<&mut usize>) {
+ let rc = text_of(doc, d, b"RC");
+ match text_of(doc, d, b"Contents") {
+ Some(c) => {
+ let _ = write!(out, "{} ", esc(&c));
+ }
+ // Rich text written as text (below) is read back as rich text only beside ``;
+ // alone it would become the comment's plain text.
+ None if rc.as_deref().is_some_and(|rc| rich_text_element(rc).is_none()) => out.push_str(" "),
+ None => {}
+ }
+ if let Some(rc) = rc {
+ match rich_text_element(&rc) {
+ // Rich text is an XML (XHTML) document (ISO 32000-2 Table 172, RC): its element goes in as markup.
+ Some(markup) => {
+ let _ = write!(out, "{markup} ");
+ }
+ // Text that is not well-formed XML goes in as text, so nothing is lost.
+ None => {
+ let _ = write!(out, "{} ", esc(&rc));
+ }
+ }
}
if let Some(da) = text_of(doc, d, b"DA") {
let _ = write!(out, "{} ", esc(&da));
}
+ if let Some(ds) = text_of(doc, d, b"DS") {
+ let _ = write!(out, "{} ", esc(&ds));
+ }
+ if let Some(budget) = ap
+ && let Some(b64) = super::appearance::encode(doc, d, budget)
+ {
+ let _ = write!(out, "{b64} ");
+ }
let ink = d.get(b"InkList").map(|o| doc.resolve(o)).and_then(|o| o.as_array().cloned()).unwrap_or_default();
if !ink.is_empty() {
out.push_str("");
@@ -180,9 +435,11 @@ fn xfdf_annot_children(doc: &Document, out: &mut String, d: &Dict, pi: usize) {
/// `own`: write each comment's PdfCraft keys too (see [`own_keys`]), for a copy and paste.
fn xfdf_annots(doc: &Document, out: &mut String, only: Option<&HashSet<(usize, usize)>>, own: bool) {
let pages = pdfcraft_model::pages(doc);
- // NM of every annotation, for inreplyto. A selected annotation without one (other tools
- // leave /NM out) gets a name for this export, so a reply copied with it still finds it.
+ // NM of every annotation, for inreplyto. A selected or replied-to annotation without one
+ // (other tools leave /NM out) gets a name for this export, so its replies still find it.
let names = annotation_names(doc, &pages, only);
+ // What the import reads of appearances, over all of the comments.
+ let mut appearance_budget = super::appearance::MAX_IMPORT_APPEARANCE_BYTES;
for (pi, p) in pages.iter().enumerate() {
for (ai, a) in p.dict.get(b"Annots").map(|a| doc.resolve(a)).and_then(|a| a.as_array().cloned()).unwrap_or_default().into_iter().enumerate() {
if only.is_some_and(|only| !only.contains(&(pi, ai))) {
@@ -203,8 +460,8 @@ fn xfdf_annots(doc: &Document, out: &mut String, only: Option<&HashSet<(usize, u
n(rect[1].max(rect[3]))
);
}
- // The name: /NM, or the one given above for this export.
- if let Some(nm) = text_of(doc, &d, b"NM").or_else(|| a.as_ref().and_then(|r| names.get(&r).cloned())) {
+ // Its `/NM`, or the name given above for this export.
+ if let Some(nm) = a.as_ref().and_then(|r| names.get(&r)).cloned().or_else(|| text_of(doc, &d, b"NM")) {
let _ = write!(attrs, " name=\"{}\"", esc(&nm));
}
for (key, attr) in [
@@ -233,9 +490,7 @@ fn xfdf_annots(doc: &Document, out: &mut String, only: Option<&HashSet<(usize, u
if let Some(o) = d.get(b"CA").and_then(|o| doc.resolve(o).as_f64()) {
let _ = write!(attrs, " opacity=\"{}\"", n(o));
}
- if let Some(w) = d.get(b"BS").and_then(|b| doc.resolve(b).as_dict().and_then(|b| b.get(b"W").and_then(Object::as_f64))) {
- let _ = write!(attrs, " width=\"{}\"", n(w));
- }
+ format_attrs(doc, &d, sub, &mut attrs);
let quads = nums_of(doc, d.get(b"QuadPoints"));
if !quads.is_empty() {
let _ = write!(attrs, " coords=\"{}\"", quads.iter().map(|v| n(*v)).collect::>().join(","));
@@ -254,26 +509,14 @@ fn xfdf_annots(doc: &Document, out: &mut String, only: Option<&HashSet<(usize, u
let cl = nums_of(doc, d.get(b"CL"));
if cl.len() == 4 || cl.len() == 6 {
let _ = write!(attrs, " callout=\"{}\"", cl.iter().map(|v| n(*v)).collect::>().join(","));
- let rd = nums_of(doc, d.get(b"RD"));
- if rd.len() == 4 {
- let _ = write!(attrs, " fringe=\"{}\"", rd.iter().map(|v| n(*v)).collect::>().join(","));
- }
if let Some(le) = d.get(b"LE").map(|o| doc.resolve(o)).and_then(|o| o.as_name().map(|x| String::from_utf8_lossy(x).into_owned())) {
let _ = write!(attrs, " head=\"{}\"", esc(&le));
}
}
// What the comment is meant as (/IT): typewriter text, a callout, a cloud, an arrow.
+ // Written under both spellings XFDF files use for it, `intent` and `IT`.
if let Some(it) = d.get(b"IT").map(|o| doc.resolve(o)).and_then(|o| o.as_name().map(|x| String::from_utf8_lossy(x).into_owned())) {
- let _ = write!(attrs, " intent=\"{}\"", esc(&it));
- }
- // A cloudy border (/BE /S /C) and how far its arcs bulge.
- if let Some(be) =
- d.get(b"BE").map(|o| doc.resolve(o)).and_then(|o| o.as_dict().cloned()).filter(|b| b.name(b"S") == Some(b"C".as_slice()))
- {
- attrs.push_str(" style=\"cloudy\"");
- if let Some(i) = be.get(b"I").and_then(Object::as_f64) {
- let _ = write!(attrs, " intensity=\"{}\"", n(i));
- }
+ let _ = write!(attrs, " intent=\"{0}\" IT=\"{0}\"", esc(&it));
}
if let Some(irt) = d.get(b"IRT").and_then(Object::as_ref).and_then(|r| names.get(&r)) {
let _ = write!(attrs, " inreplyto=\"{}\"", esc(irt));
@@ -282,7 +525,13 @@ fn xfdf_annots(doc: &Document, out: &mut String, only: Option<&HashSet<(usize, u
let _ = write!(attrs, " pdfcraft:keys=\"{}\"", esc(&keys));
}
let _ = write!(out, "<{tag}{attrs}>");
- xfdf_annot_children(doc, out, &d, pi);
+ // XFDF 3.0 carries a stamp's appearance, and none for a rect with no area; a copy and
+ // paste (`own`) carries every comment's, so the copy looks the same, except a
+ // redaction mark's, which import never reads (PdfCraft draws the mark) and which would
+ // only use up the budget the others share.
+ let has_area = rect.len() == 4 && rect[0] != rect[2] && rect[1] != rect[3];
+ let carried = has_area && sub != b"Redact" && (own || sub == b"Stamp");
+ xfdf_annot_children(doc, out, &d, pi, carried.then_some(&mut appearance_budget));
let _ = writeln!(out, "{tag}>");
}
}
@@ -659,12 +908,7 @@ fn annot_from_xml(node: roxmltree::Node, subtype: &str, page_ref: ObjRef) -> Opt
if let Some(o) = node.attribute("opacity").and_then(|o| o.parse::().ok()) {
d.set(b"CA".to_vec(), Object::Real(o.clamp(0.0, 1.0)));
}
- if let Some(w) = node.attribute("width").and_then(|w| w.parse::().ok()) {
- let mut bs = Dict::new();
- bs.set(b"W".to_vec(), Object::Real(w.max(0.0)));
- bs.set(b"S".to_vec(), Object::name("S"));
- d.set(b"BS".to_vec(), Object::Dict(bs));
- }
+ read_format(node, &mut d);
if let Some(q) = node.attribute("coords") {
d.set(b"QuadPoints".to_vec(), arr(&csv(q)));
}
@@ -680,22 +924,14 @@ fn annot_from_xml(node: roxmltree::Node, subtype: &str, page_ref: ObjRef) -> Opt
Object::Array(vec![Object::name(node.attribute("head").unwrap_or("None")), Object::name(node.attribute("tail").unwrap_or("None"))]),
);
}
- if let Some(it) = node.attribute("intent").filter(|it| !it.is_empty()) {
+ // The intent (/IT), spelt `intent` or `IT`.
+ let intent = node.attribute("intent").filter(|it| !it.is_empty()).or_else(|| node.attribute("IT").filter(|it| !it.is_empty()));
+ if let Some(it) = intent {
d.set(b"IT".to_vec(), Object::name(it));
}
- if node.attribute("style") == Some("cloudy") {
- let mut be = Dict::new();
- be.set(b"S".to_vec(), Object::name("C"));
- let intensity = node.attribute("intensity").and_then(|i| i.parse::().ok()).filter(|i| i.is_finite()).unwrap_or(1.0);
- be.set(b"I".to_vec(), Object::Real(intensity.clamp(0.0, 2.0)));
- d.set(b"BE".to_vec(), Object::Dict(be));
- }
if let Some(cl) = node.attribute("callout").map(csv).filter(|c| c.len() == 4 || c.len() == 6) {
d.set(b"CL".to_vec(), arr(&cl));
- if let Some(rd) = node.attribute("fringe").map(csv).filter(|r| r.len() == 4) {
- d.set(b"RD".to_vec(), arr(&rd));
- }
- d.set(b"IT".to_vec(), Object::name(node.attribute("intent").unwrap_or("FreeTextCallout")));
+ d.set(b"IT".to_vec(), Object::name(intent.unwrap_or("FreeTextCallout")));
// A callout's /LE is one name, not the head/tail pair of a line.
match node.attribute("head") {
Some(h) => d.set(b"LE".to_vec(), Object::name(h)),
@@ -712,6 +948,9 @@ fn annot_from_xml(node: roxmltree::Node, subtype: &str, page_ref: ObjRef) -> Opt
"defaultappearance" => {
d.set(b"DA".to_vec(), PdfString::literal(child.text().unwrap_or("").as_bytes().to_vec()));
}
+ "defaultstyle" => {
+ d.set(b"DS".to_vec(), PdfString::text(&child.children().filter(|c| c.is_text()).filter_map(|c| c.text()).collect::()));
+ }
"inklist" => {
let list: Vec = child
.children()
@@ -731,10 +970,120 @@ fn annot_from_xml(node: roxmltree::Node, subtype: &str, page_ref: ObjRef) -> Opt
_ => {}
}
}
+ if let Some(rich) = node.children().find(|c| c.has_tag_name("contents-richtext")) {
+ read_rich_text(rich, node.children().any(|c| c.has_tag_name("contents")), &mut d);
+ }
read_own_keys(node, &mut d);
Some(d)
}
+/// `` back as `/RC` (XFDF 3.0 "The contents and contents-richtext elements in
+/// annotations"): its markup, as written in the file, after an XML declaration. Plain text in it is the comment's text
+/// (`/Contents`) when the element comes alone; beside `` it is kept as `/RC` (rich text
+/// PdfCraft exported as text because it was not well-formed XML). Markup without ``
+/// gives `/Contents` its plain text too, so the comment's text shows where rich text is not read.
+fn read_rich_text(rich: roxmltree::Node, has_contents: bool, d: &mut Dict) {
+ let elements: Vec = rich.children().filter(|c| c.is_element()).collect();
+ let (Some(first), Some(last)) = (elements.first(), elements.last()) else {
+ let text: String = rich.children().filter(|c| c.is_text()).filter_map(|c| c.text()).collect();
+ if has_contents {
+ d.set(b"RC".to_vec(), PdfString::text(&text));
+ } else {
+ d.set(b"Contents".to_vec(), PdfString::text(&text.replace("\r\n", "\r").replace('\n', "\r")));
+ }
+ return;
+ };
+ let source = rich.document().input_text();
+ let Some(markup) = source.get(first.range().start..last.range().end) else { return };
+ let markup = match elements.as_slice() {
+ [_] => standalone(rich, markup),
+ _ => markup.to_string(),
+ };
+ // Rich text is an XML document of its own; export left its declaration out.
+ d.set(b"RC".to_vec(), PdfString::text(&format!("{markup}")));
+ if !has_contents {
+ d.set(b"Contents".to_vec(), PdfString::text(&rich_plain(rich)));
+ }
+}
+
+/// Whether start tag `tag` (from `<` up to its closing `>`) declares attribute `name` (white
+/// space may come before the `=`). Attribute values are skipped: `title=" xmlns:b='x'"` declares
+/// nothing.
+fn declares(tag: &str, name: &str) -> bool {
+ let mut quote = None;
+ let mut after_space = false;
+ for (i, c) in tag.char_indices() {
+ if let Some(q) = quote {
+ if c == q {
+ quote = None;
+ }
+ continue;
+ }
+ if c == '"' || c == '\'' {
+ quote = Some(c);
+ } else if after_space && tag.get(i..).and_then(|rest| rest.strip_prefix(name)).is_some_and(|a| a.trim_start().starts_with('=')) {
+ return true;
+ }
+ after_space = c.is_whitespace();
+ }
+ false
+}
+
+/// Where the start tag at the beginning of `markup` ends: its first `>` outside an attribute
+/// value (the end of `markup` when there is none).
+fn start_tag_end(markup: &str) -> usize {
+ let mut quote = None;
+ for (i, c) in markup.char_indices() {
+ match quote {
+ Some(q) if c == q => quote = None,
+ Some(_) => {}
+ None if c == '"' || c == '\'' => quote = Some(c),
+ None if c == '>' => return i,
+ None => {}
+ }
+ }
+ markup.len()
+}
+
+/// The one element `markup` (cut out of `rich`, a ``) as an XML
+/// document of its own: the namespaces it inherits from the XFDF around it are declared on it,
+/// the default one (XHTML declared on ``, say; not XFDF's own, which a
+/// standalone document has no use for) and the prefixes it uses. Unchanged when nothing is
+/// inherited, or when the declarations would not make it parse.
+fn standalone(rich: roxmltree::Node, markup: &str) -> String {
+ // The start tag's name ends at white space, `/` or `>`.
+ let Some(name_end) = markup.get(1..).and_then(|t| t.find(|c: char| c.is_whitespace() || c == '/' || c == '>')).map(|i| i + 1) else {
+ return markup.to_string();
+ };
+ let start_tag = markup.get(..start_tag_end(markup)).unwrap_or(markup);
+ let mut declared = String::new();
+ // The default namespace in scope where the element sits: its own when it has no prefix, and
+ // its unprefixed descendants' when it has one.
+ if let Some(uri) = rich.namespaces().find(|ns| ns.name().is_none()).map(|ns| ns.uri())
+ && !uri.is_empty()
+ && uri != XFDF_NS
+ && !declares(start_tag, "xmlns")
+ {
+ let _ = write!(declared, " xmlns=\"{}\"", esc(uri));
+ }
+ for ns in rich.namespaces() {
+ let Some(prefix) = ns.name() else { continue };
+ if prefix == "xml" || !markup.contains(&format!("{prefix}:")) || declares(start_tag, &format!("xmlns:{prefix}")) {
+ continue;
+ }
+ let _ = write!(declared, " xmlns:{prefix}=\"{}\"", esc(ns.uri()));
+ }
+ if declared.is_empty() {
+ return markup.to_string();
+ }
+ let (Some(head), Some(tail)) = (markup.get(..name_end), markup.get(name_end..)) else { return markup.to_string() };
+ let fixed = format!("{head}{declared}{tail}");
+ if parse_form_xml(&fixed).is_ok() { fixed } else { markup.to_string() }
+}
+
+/// XFDF's own namespace (ISO 19444-1).
+const XFDF_NS: &str = "http://ns.adobe.com/xfdf/";
+
/// Put an annotation dictionary on a page, replacing one with the same `/NM`. Returns its
/// reference.
/// `/F` bits an imported file may not set on a redaction mark: Invisible, Hidden, NoView — so a
@@ -764,6 +1113,11 @@ pub(crate) fn place(doc: &mut Document, page_ref: ObjRef, mut d: Dict) -> Result
// without usable /QuadPoints removes its /Rect, which the outline is then drawn from.
d.remove(b"CA");
d.remove(b"ca");
+ // The outline is PdfCraft's own (an appearance the file carries could hide the mark), and
+ // a redaction has no border effect (ISO 32000-2 Table 195 lists none; §12.5.4 gives
+ // /BE to squares, circles, polygons and free text), which the outline could not draw.
+ d.remove(b"AP");
+ d.remove(b"BE");
let quads_drawable = d.get(b"QuadPoints").and_then(Object::as_array).is_some_and(|q| {
let v: Vec = q.iter().filter_map(Object::as_f64).filter(|v| v.is_finite()).collect();
let (quads, rest) = v.as_chunks::<8>();
@@ -783,7 +1137,32 @@ pub(crate) fn place(doc: &mut Document, page_ref: ObjRef, mut d: Dict) -> Result
}
}
}
+ // The outline is drawn inside /Rect: it is grown to hold every quad, so the whole area
+ // the mark removes shows (a /Rect with no area would show none of it).
+ let quads: Vec =
+ d.get(b"QuadPoints").and_then(Object::as_array).map(|q| q.iter().filter_map(Object::as_f64).collect()).unwrap_or_default();
+ if !quads.is_empty() {
+ let rect = rect_strict(doc, d.get(b"Rect"));
+ let start = rect.map(|[x0, y0, x1, y1]| [x0.min(x1), y0.min(y1), x0.max(x1), y0.max(y1)]);
+ let bounds = quads
+ .as_chunks::<2>()
+ .0
+ .iter()
+ .fold(start, |b, [x, y]| Some(b.map_or([*x, *y, *x, *y], |[l, bo, r, t]| [l.min(*x), bo.min(*y), r.max(*x), t.max(*y)])));
+ if let Some(b) = bounds
+ && Some(b) != rect
+ {
+ d.set(b"Rect".to_vec(), arr(&b));
+ }
+ }
}
+ // An appearance the file carries is how the comment looked where it came from, and is kept
+ // (XFDF 3.0 "stamp": it takes precedence over the icon). A redaction mark is always drawn by
+ // PdfCraft, so what it marks for removal is shown.
+ let redact = d.name(b"Subtype") == Some(b"Redact".as_slice());
+ // A redaction mark with an area removes something when applied.
+ let marks = redact && d.contains(b"QuadPoints");
+ let keep_appearance = !redact && super::appearance::has_appearance(doc, &d);
let nm = d.get(b"NM").and_then(|n| n.as_string().map(|s| s.to_text()));
let annots: Vec = doc
.get(page_ref)
@@ -827,8 +1206,17 @@ pub(crate) fn place(doc: &mut Document, page_ref: ObjRef, mut d: Dict) -> Result
}
None => doc.add(Object::Dict(d)),
};
- // Our own appearance where we can draw one; others keep none (viewers draw a default).
- let _ = pdfcraft_annot::set_appearance(doc, r);
+ // Otherwise our own appearance where we can draw one; others keep none (viewers draw a default).
+ if !keep_appearance {
+ let drawn = pdfcraft_annot::set_appearance(doc, r);
+ // A redaction mark that removes something but shows nothing is refused: applying it
+ // would remove content the reviewer never saw marked.
+ if let Err(why) = drawn
+ && marks
+ {
+ return Err(DataError::Malformed(format!("a redaction mark could not be drawn, so what it removes would not show ({why})")));
+ }
+ }
kept.push(Object::Ref(r));
doc.update_dict(page_ref, |p| p.set(b"Annots".to_vec(), Object::Array(kept)))?;
Ok(r)
@@ -864,19 +1252,35 @@ pub fn import_comments(
fresh: Option<&str>,
offset: Option<[f64; 2]>,
) -> Result {
- import_xfdf_with(doc, text, page, fresh, offset.filter(|o| o.iter().all(|v| v.is_finite())))
+ // Into a copy, kept only when the whole import succeeds.
+ let mut work = doc.clone();
+ let report = import_xfdf_with(
+ &mut work,
+ text,
+ page,
+ fresh,
+ offset.filter(|o| o.iter().all(|v| v.is_finite())),
+ super::appearance::MAX_IMPORT_APPEARANCE_BYTES,
+ true,
+ )?;
+ *doc = work;
+ Ok(report)
}
pub(crate) fn import_xfdf(doc: &mut Document, text: &str) -> Result {
- import_xfdf_with(doc, text, None, None, None)
+ import_xfdf_with(doc, text, None, None, None, super::appearance::MAX_IMPORT_APPEARANCE_BYTES, false)
}
-fn import_xfdf_with(
+/// The import, with `appearance_budget` decoded bytes of appearance for all of its comments;
+/// `comments_only` leaves the file's field values out (comments placed as copies).
+pub(crate) fn import_xfdf_with(
doc: &mut Document,
text: &str,
target_page: Option,
fresh: Option<&str>,
offset: Option<[f64; 2]>,
+ mut appearance_budget: usize,
+ comments_only: bool,
) -> Result {
check_form_xml_depth(text)?;
let xml = parse_form_xml(text).map_err(|e| DataError::Malformed(e.to_string()))?;
@@ -912,6 +1316,18 @@ fn import_xfdf_with(
let own_page = node.attribute("page").and_then(|p| p.parse::().ok());
let Some(page) = target_page.or(own_page).and_then(|p| pages.get(p).copied()) else { continue };
let Some(mut d) = annot_from_xml(node, subtype, page) else { continue };
+ // The appearance the file carries (XFDF 3.0 "appearance"), when it can be read.
+ // A redaction mark is always drawn by PdfCraft (see `place`): its appearance is not read.
+ if let Some(ap) = node.children().find(|c| c.has_tag_name("appearance")).filter(|_| *subtype != "Redact") {
+ let text: String = ap.children().filter(|c| c.is_text()).filter_map(|c| c.text()).collect();
+ match super::appearance::decode(&text, &mut appearance_budget) {
+ Ok(tree) => {
+ let ap = super::appearance::materialize(doc, tree);
+ d.set(b"AP".to_vec(), ap);
+ }
+ Err(why) => report.skipped.push(format!("{}: {why}", node.attribute("name").unwrap_or(&tag))),
+ }
+ }
let assigned = fresh.map(|prefix| format!("{prefix}-{}", n + 1));
if let Some(name) = &assigned {
// A copy under a name of its own (one even where the original had none).
@@ -956,7 +1372,7 @@ fn import_xfdf_with(
}
}
// Comments placed as copies: the file's field values are not part of the paste.
- if fresh.is_some() || target_page.is_some() || offset.is_some() {
+ if comments_only {
return Ok(report);
}
// Fields.
diff --git a/docs/contributors.md b/docs/contributors.md
index fa7e988611..b24d1cd053 100644
--- a/docs/contributors.md
+++ b/docs/contributors.md
@@ -8,7 +8,8 @@ the AI models named in `Co-Authored-By` trailers.
- Two files, both **compiled into the binary** by the UI crate's `build.rs` (nothing is read from
disk or the network at run time; the web build has them too):
- [`contributors/contributors.json`](../contributors/contributors.json): commit stats per GitHub
- username.
+ username. Release builds regenerate it for the release commit
+ (`.github/workflows/release.yml`, `credits` job); the copy in the repository is not updated.
- [`contributors/people.toml`](../contributors/people.toml): the names people chose for
themselves. **Each contributor adds only their own entry**, in their own PR.
- Each contributor gets one line: GitHub username (always), display name (opt-in, or their synced
diff --git a/docs/editing-existing-text.md b/docs/editing-existing-text.md
index 426058f7b7..f1007be05b 100644
--- a/docs/editing-existing-text.md
+++ b/docs/editing-existing-text.md
@@ -1,5 +1,29 @@
# Editing existing text and source subsets
+In **Edit text and images**, text drawn inside a Form XObject (grouped artwork) is edited
+with one click: clicking its text prepares that page in an undoable **Prepare grouped text**
+step and opens the paragraph clicked for typing. Nothing is prepared while pages are only
+shown or scrolled. A drag still moves the selected group as a whole; a click on grouped
+artwork that preparation wouldn't open (a logo, a refused group) selects it as before, and
+changes nothing. To select a text group for moving, right-click it. While a paragraph is open
+or another edit is waiting, the click selects the group instead, as before; the next click
+prepares it. The group's original operators, clip, placement and resources become page
+content; shared forms on other pages stay unchanged. Ungroup (the artwork's right-click menu)
+draws one placement in place with the same code. Headless callers use `text_prepare`, then
+list `text_paragraphs` and call `text_edit`.
+This edits existing glyph operators; it adds neither a cover rectangle nor an Add Text box.
+Preparation refuses knockout/blended groups, groups that blend in a colour space other than
+the page group's (DeviceRGB on a page that names none), forms whose default
+colour spaces differ from the page's, tagged forms, forms drawn inside text objects or
+unfinished paths, groups whose nested content can't be checked and unreadable content. Forms
+that draw only images or vector artwork are left grouped. Decoding is capped at 16 MiB, 64
+placements and eight expansion levels per page; text grouped deeper is reported. Unsupported
+groups remain intact: `text_prepare` lists each with its reason, and the repair log records
+them when the page is prepared. A narrowly fingerprinted legacy THSarabunPSK exporter map can
+also be repaired in copied page fonts, only when every glyph the subset kept advances as its
+assumed Thai character does; `text_prepare` repairs it also for text that was never grouped,
+and the repair log records both preparation and map recovery.
+
Click a text region in **Edit a PDF → Edit text and images**. One editor contains its
source rows and mixed styles. Embedded TrueType and OpenType/CFF faces are used in memory;
source font programs, colour, size and baseline anchors stay intact. A textless preview
@@ -44,6 +68,44 @@ this works only when that build input actually contains the full face. This chan
add a font binary or change the release font pin. Fonts shared by releases belong in
`storytold/craft-fonts` under the repository's asset rules.
+**Keep source fonts** retains the existing Thai family, weight and point size. For legacy
+THSarabunPSK subsets, PdfCraft reconstructs an editor-only Unicode cmap from the PDF's
+Unicode and CID-to-glyph maps. HarfRust uses the retained Thai positional glyphs, and the
+saved text refers to the original PDF font resources. Several subsets of the same exact
+face can supply Thai and punctuation glyphs, including a Thai run whose clusters are split
+across subsets, and a subset whose glyph for a character is empty is skipped; Regular and
+Bold stay separate. Source font
+programs are never modified or replaced. Text settings, including character/word spacing,
+horizontal scale, rise, color and paint mode, remain in the PDF text state.
+
+A source subset that lacks a needed contextual glyph produces an error asking for the
+complete original face or an explicit replacement. Cross-family replacement requires an
+explicit choice. The document-font menu offers **Noto Sans Thai**: pass its `text_fonts`
+resource (normally `builtin:thai`) as `text_edit.font_resource` or a range's `font_resource`. This replacement
+requires the optional craft-fonts Thai input and currently uses Regular. A matching Noto
+subset can still be completed by that same bundled family when it is Regular and upright; a
+subset its name or descriptor marks bold or italic needs an explicit replacement.
+
+The bundled variable Thai face is written as bounded Type 3 glyph outlines, with shaped
+vowel/tone positions and logical Unicode text, rather than embedded as a static font.
+Saved paragraphs can be reopened and edited again without installing a font. Modern Thai
+shaping of vowels and tone marks uses the source's GPOS mark positioning (a `mark` or `mkmk` feature in the script and language system the shaper
+selects for Thai, not just a GPOS table); GSUB substitution is optional, as specified by
+[the OpenType Thai model](https://learn.microsoft.com/en-us/typography/script-development/thai).
+Verified legacy Thai PUA fonts use positional substitutions instead of requiring GPOS; their
+alternates are used only when each kept one has a mark's zero advance (or, for the two
+consonant forms, an advance) and, where the PDF's own map names its character, the character
+that alternate stands for. A THSarabunPSK program with its own Thai mark
+positioning, such as a complete face loaded with Load font, is shaped by that layout instead,
+still in its own codes. One without it takes the legacy path only when every Thai glyph it keeps
+is where the legacy glyph order puts it, and is otherwise shaped as an ordinary source font. A
+subset needs only the glyphs its new text uses. When no subset can show the new text in its
+existing codes, a complete program of the same face and style (one added with Load font, CFF
+included) shapes the whole span with its own layout, Latin rows too, rather than the edit being
+refused; a Regular program never completes text the source marks bold or italic.
+Mixed contextual style runs and dictionary word segmentation remain limited. No font binary
+or release pin changes are needed.
+
When mixed-style text needs outline fallback, characters using the same actual fallback face
share Type 3 fonts, with at most 240 distinct glyphs per font. Adjacent characters with the same
font and source style are written as one run. Latin characters that the source font can encode
@@ -60,6 +122,13 @@ sign before an amount: the line-start and line-end rules of JIS X 4051, as in Un
breaking (UAX #14). Latin words inside such text are not split. Korean and Thai still break only
at spaces.
+Text pasted from a browser or a word processor often carries an invisible break instead of a
+newline. Every Unicode row break starts a new row: U+2028 LINE SEPARATOR, U+2029 PARAGRAPH
+SEPARATOR, U+0085 NEXT LINE, the vertical tab, the form feed and the information separators
+(U+001C to U+001E), alongside the carriage return and the newline. These move the text down a
+row rather than being looked up in a font, so a paste no longer fails because no face has an
+outline for them. Other white space is still written as one space.
+
Select text within the editor before changing size, colour, font, underline or spacing to
format that selection. Automation supports up to 1024 disjoint UTF-8 byte ranges with the
same properties; invalid or overlapping ranges fail atomically. Untouched source formatting
@@ -89,8 +158,16 @@ On a scanned page, recognised text (Scan & OCR) is an invisible layer over the p
text groups it into phrases: words joined by a word space, with a table cell, a tab stop and each
scanned line kept apart. Applying an edit draws the new text visibly in the scan's ink colour (or
the one chosen) and first covers the old words with the paper colour sampled around them. Each
-word keeps its position and width, and a longer phrase grows rightwards rather than wrapping. The
-cover is one flat colour, and the text uses the layer's Helvetica, not the scanned typeface.
+word keeps its position and width, and a longer phrase grows rightwards rather than wrapping.
+OCR sizes each word from its own box, so a phrase's words can come out several points apart: the
+editor and the rewrite set the whole phrase in one size, the median of its words' sizes.
+A text edit covers and redraws only the words it changes: the rest of the line stays the scan, and
+a deleted word leaves its gap, because the words after it are pixels. A replacement a little too
+wide is squeezed across to fit its place (by up to a quarter); wider than that it takes over the
+word it would run into, and new words with nothing to replace take a neighbour.
+The whole phrase is redrawn for a change of formatting or a new line, and for a layer whose words
+would move without the ones before them. While the phrase is open, the editor still shows all of
+it in the layer's Helvetica. The cover is one flat colour, and the text uses the layer's Helvetica, not the scanned typeface.
This applies to any invisible text (rendering mode 3), not just a PdfCraft OCR layer: editing
invisible text, such as another OCR tool's layer, makes the rewritten paragraph visible over a
painted cover in the sampled paper colour. Edit text also groups invisible text differently: its lines never
diff --git a/docs/editing-images.md b/docs/editing-images.md
index 4ebafd115f..16a78f711a 100644
--- a/docs/editing-images.md
+++ b/docs/editing-images.md
@@ -18,9 +18,10 @@ content, resources, clipping box, and transparency settings remain intact. Movin
deleting one use of a shared figure does not alter its other placements or pages.
**Replace Image** and **Save Image As** apply only to raster Image XObjects; these menu
-items are disabled for grouped Form artwork. The tool does not ungroup Forms, edit their
-individual internal elements, select arbitrary ungrouped vector paths, or edit inline
-images (`BI`/`ID`/`EI`). A Form's bounding box may include whitespace.
+items are disabled for grouped Form artwork. **Ungroup** (right-click) draws one placement's
+content in place so its text and pictures can be edited; while grouped, the tool does not edit
+a Form's individual internal elements. It does not select arbitrary ungrouped vector paths or
+edit inline images (`BI`/`ID`/`EI`). A Form's bounding box may include whitespace.
For automation, `page_images` lists both kinds with `kind: "image"` or `kind: "form"`.
Forms have `pixels: [0, 0]`, since they have no single bitmap resolution. Use the returned
diff --git a/docs/editing-multiple-objects.md b/docs/editing-multiple-objects.md
index 7881be6a7c..3cf4a6b167 100644
--- a/docs/editing-multiple-objects.md
+++ b/docs/editing-multiple-objects.md
@@ -13,6 +13,30 @@ In **Edit a PDF → Edit text & images**, select several items on the same page:
- Modifier-clicks prefer added items and text over background artwork, so labels remain selectable.
- Clear the selection or double-click an item to return to ordinary text editing and image resizing.
Finish or discard a text draft before starting a multi-selection.
+- **⌘A / Ctrl+A** selects every item on the current page (paragraphs, artwork and added items),
+ as Acrobat's Edit PDF does, instead of the page's text. Inside a paragraph or text box open for
+ typing it still selects that text.
+
+## Copy, cut and paste
+
+With items selected together, **⌘C / Ctrl+C** (Edit ▸ Copy) copies them and **⌘X / Ctrl+X**
+(Edit ▸ Cut) copies them, then deletes them as one undo step. **⌘V / Ctrl+V** (Edit ▸ Paste) pastes
+them onto the current page of any open document, also after the original changed or closed, as
+one undo step, and selects what it pasted. Onto the page they came from they land 18 points down
+and to the right, as Acrobat offsets a paste onto the same page; elsewhere where they were; each
+further paste onto a page steps another 18 points; a copy that would land off the page is centred.
+
+A paste draws the same: it copies the items' content operators with the graphics state they were
+drawn in (transformation, clip, colours, transparency, text state) and every resource they use
+(fonts, images and Form artwork, ExtGStates, colour spaces, patterns, shadings), merged into the
+target page's resources under names that don't clash, as Ungroup merges them. Within a document the
+same font and image objects are drawn again. Into another document they are copied with what they
+refer to, each once whatever the cycles, sharing objects it already holds; a paste whose resources
+take more than 20,000 objects or 256 MB is refused with that reason. Pasted items are ordinary page
+content: an added text box comes as page text, untagged and in no layer. The system clipboard gets
+the copied text (or, without text, the first picture) for other applications; a newer copy there,
+here or in another application, wins ⌘V. Text drawn as a clipping path before the selection is
+refused, as is artwork without resources of its own that names one, where a paste would change it.
The supported items are the existing paragraph boxes, raster Image XObjects, whole Form artwork,
and text/images added by PdfCraft. A Form remains one item, including its nested artwork and
@@ -75,6 +99,17 @@ session. For a CLI script, include `doc_open` in that script before the move:
]
```
+`{"all": true}` instead of `objects` takes every item on the page, as ⌘A does. `object_copy` takes
+the same references (with `cut: true` it deletes them afterwards, one undo step) and `object_paste
+{doc, page}` pastes them, into the same or another open document, as the app does:
+
+```json
+[
+ {"tool":"object_copy","args":{"doc":1,"page":1,"all":true}},
+ {"tool":"object_paste","args":{"doc":2,"page":3}}
+]
+```
+
Use the actual generation and references from your document, rather than assuming these example
values. `offset` is in displayed points: positive x moves right, positive y moves down. The optional
generation guard rejects a changed document before interpreting references. Re-list after any edit,
@@ -82,6 +117,9 @@ undo, redo, or save; there is no claim that an index persists across generations
`pdfcraft-cli run --script steps.json --root DIR` or call these tools through the opt-in MCP server.
Regression coverage: `crates/edit/src/tests.rs` (glyph bytes, neighbours, split streams, shared Forms,
-rotated/cropped/UserUnit pages and refusal), `crates/engine/src/tests.rs` (permissions, history,
-rendering and save/reopen), `crates/automation/tests/it/automation.rs` (generation guards and hostile
-references), and `crates/ui-egui/tests/it/object_selection.rs` (real-shell selection and gestures).
+rotated/cropped/UserUnit pages and refusal), `crates/edit/src/objects/clip_tests.rs` (copies that
+render the same pixels, renamed resources, hostile content), `crates/engine/src/tests.rs` and
+`crates/engine/src/object_clip_tests.rs` (permissions, history, rendering, save/reopen, pastes into
+another document, cycles and the size limit), `crates/automation/tests/it/automation.rs` (generation
+guards, hostile references, copy/cut/paste tools), and `crates/ui-egui/tests/it/object_selection.rs`
+(real-shell selection, gestures, ⌘A and the clipboard keys).
diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md
index cc3e231979..288b7ca0cf 100644
--- a/docs/file-format-parity.md
+++ b/docs/file-format-parity.md
@@ -80,7 +80,7 @@ features total).
| Target | Acrobat | PdfCraft | Fidelity | Tests and evidence |
|---|---|---|---|---|
-| Word (`.docx`) | yes, layout-preserving | flowing paragraphs and borderless inferred tables; positioned text/artwork only for pages with rotated text or text overlapping an image/watermark, with per-page sizes | **basic** (#773 synthetic invoice regression covered; exact fonts, vector rules and general layout fidelity remain incomplete) | `create.export-docx` partial |
+| Word (`.docx`) | yes, layout-preserving | flowing paragraphs and inferred tables (bordered only along the grid lines the page draws); positioned text/artwork only for pages with rotated text or text overlapping an image/watermark, with per-page sizes | **basic** (#773 synthetic invoice regression covered; exact fonts, vector rules and general layout fidelity remain incomplete) | `create.export-docx` partial |
| Word 97–2003 (`.doc`) | yes | no | none | |
| Excel (`.xlsx`), XML Spreadsheet 2003 | yes | no | none | `create.export-xlsx` planned |
| PowerPoint (`.pptx`) | yes | slides per page: title from largest text, body text, images, tables (no slide overflow reflow / normAutofit; first page sets presentation dimensions) | basic | `create.export-pptx` partial |
diff --git a/docs/hardware-parity.md b/docs/hardware-parity.md
index da2b8d92b1..455c7bcd78 100644
--- a/docs/hardware-parity.md
+++ b/docs/hardware-parity.md
@@ -1,6 +1,6 @@
# Hardware and platform parity
-> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-11 · **Change:** minor (web printing through the browser's print dialog; earlier: shared craft-print spooler with passing Windows CI; Windows printers row and 1:1 touchpad scrolling, #756, #759) · **Target:** Adobe Acrobat Pro (Acrobat DC, continuous track 26.002.21931, macOS)
+> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-12 · **Change:** minor (web OCR shipped: Web Workers with SIMD, checked in a browser; earlier: web printing through the browser's print dialog; earlier: shared craft-print spooler with passing Windows CI; Windows printers row and 1:1 touchpad scrolling, #756, #759) · **Target:** Adobe Acrobat Pro (Acrobat DC, continuous track 26.002.21931, macOS)
Each hardware feature Acrobat Pro uses, per platform, ours against Acrobat's. Acrobat runs on macOS
and Windows (plus a limited web viewer/editor in Document Cloud); PdfCraft runs on macOS, Windows,
@@ -34,12 +34,14 @@ printing are counted in their feature areas). **Platforms ≈ 70% ready, 15–30
| Windows (x64, x86, ARM64) | yes (x64, ARM64) | yes | signed installers | — |
| Linux | no | yes | AppImage, deb, rpm, Flatpak, tarball | Chinese faces in Flatpak (#689) |
| FreeBSD | no | yes | package | — |
-| Web | Acrobat online (cloud) | yes (WASM, offline in the browser) | static site | OCR, crash recovery, PKCS #12 signing, hosted deployment |
+| Web | Acrobat online (cloud) | yes (WASM, offline in the browser) | static site | OCR as fast as native (Web Workers with SIMD read a page about 17× slower), crash recovery, PKCS #12 signing, hosted deployment |
## Revision history
| Date | Change | Summary |
|---|---|---|
+| 2026-10-12 | minor | Web OCR (`ocr.ocr-web`) shipped after a browser check |
+| 2026-10-12 | minor | Web platform row: OCR downloads its models on first use and reads in Web Workers with SIMD (`ocr.ocr-web`, partial); what's left is speed |
| 2026-10-11 | minor | Web printers row: printing through the browser's print dialog (gap 4 closed); Web platform row no longer lists printing |
| 2026-10-10 | major | Created from the code, `vendor/README.md`, `.github/workflows/release.yml`, the print crate's README and user issues |
| 2026-10-10 | minor | Windows printing shipped (#756): the Windows row's gap is closed; the web row keeps "printing" |
diff --git a/docs/localization-parity.md b/docs/localization-parity.md
index 1944575ce3..4e30fcdf0a 100644
--- a/docs/localization-parity.md
+++ b/docs/localization-parity.md
@@ -1,24 +1,32 @@
# Localization parity
-> **Last reviewed:** 2026-11-03 · **Last updated:** 2026-11-03 · **Change:** minor (Turkish: 2,867 entries, 0 missing in `cargo xtask i18n-report` on 2026-11-03; AI-assisted)
-> **Last reviewed:** 2026-10-25 · **Last updated:** 2026-10-25 · **Change:** minor (Persian (`fa`, 2,785 entries) added right-to-left like Arabic and Kurdish; Arabic current state corrected: catalogs stay logical, RTL labels take an explicit direction and stock chrome mirrors; native/browser RTL input, IME and complex workflows remain unqualified. Native release Hans face via LXGW WenKai Lite; release-pinned craft-fonts still has no Telugu face. Current union 2,798 keys. Scores and estimates unchanged) · **Target:** Adobe Acrobat Pro (Acrobat DC, continuous track 26.002.21931, macOS)
+> **Last reviewed:** 2026-11-03 · **Last updated:** 2026-11-03 · **Change:** minor (every catalog restated from `cargo xtask i18n-report` on `main` at `14ae839a`: 2,897 strings in the report's denominator; Hindi, Indonesian, Korean, Thai, Lao and Central Kurdish listed with their catalogs. Scores and estimates unchanged) · **Target:** Adobe Acrobat Pro (Acrobat DC, continuous track 26.002.21931, macOS)
Per-language status of PdfCraft's interface against Acrobat Pro's. How translations work and how to
add a language: [localization.md](localization.md). Summary in [ROADMAP.md](../ROADMAP.md).
## How this was measured
-- **Strings translated** is measured: the catalogs in `crates/ui-egui/src/i18n/.tsv` (since moved to craft-i18n's `locales//`), counted
- as distinct `(context, English)` keys with a non-empty translation. The denominator is the union of
- keys across all catalogs, counting language-specific context rows such as `theme`/`Appearance`.
- **That union is a moving target**: every change that adds a string widens it, so a count is only
- comparable with others measured on the same date, and a catalog that reached 100% falls behind
- without losing a single translation. Every figure here therefore carries its date. The current
- union is **2,798** keys as of 2026-10-25, against the **2,143-key snapshot** of 2026-10-10; earlier
- revisions quote the union of their own date (see the revision history), not this one. The
- twelve-language percentage table below still quotes the 2026-10-10 snapshot for every language
- except Spanish, Vietnamese, Lithuanian and Brazilian Portuguese, which are measured against the current union. English is
+- **Strings translated** is measured with `cargo xtask i18n-report`, which CI also runs: the
+ English strings in its denominator, less the ones a catalog has no translation for. The
+ denominator is the UI source's literals, the command, All tools and engine wordings, and every
+ key of every bundled catalog, which brings in the contextual, plural and dynamically looked-up
+ strings the scan can't see. On `main` at `14ae839a` (2026-11-03) that is **2,897** strings, and
+ every count and percentage in the tables below is of that number. A key only some catalogs have
+ counts as missing in the others; a contextual one (such as `theme`/`Appearance`) is met by a
+ plain translation of the same English, but a `@plural` one only by its own plural forms. The
+ denominator still grows whenever the interface gains a string, so a catalog that was complete
+ falls behind without losing a translation, and every figure here carries its date. English is
built in.
+- **Catalogs:** the figures above were taken from the in-repo catalogs
+ (`crates/ui-egui/src/i18n/.tsv`), which have since moved to craft-i18n's `locales//`.
+ The report reads the catalogs the build embeds, so measuring again needs `CRAFT_I18N_DIR` set to a
+ craft-i18n checkout at the commit in `craft-i18n.rev`; without it the report says it was
+ skipped.
+- **Before 2026-11-03** this page counted distinct `(context, English)` keys against the union of
+ keys across all catalogs: 2,143 keys on 2026-10-10, 2,798 on 2026-10-25, and 2,895 on
+ `14ae839a`. That union also grew whenever one catalog added a key no other had, so it moved every
+ row at once. Earlier revisions in the history quote it, at the size of their own date.
- **Not counted:** error details from the engine and the operating system, which are shown in
English inside a translated frame; there is no translated user documentation or help yet (Acrobat
ships localized help).
@@ -32,64 +40,71 @@ add a language: [localization.md](localization.md). Summary in [ROADMAP.md](../R
## The twelve key languages
-| Language | Code | UI strings translated | Dialogs / tooltips / help | Script support | Native review | Status | Acrobat ships it | To `full` (h) |
+| Language | Code | UI strings translated (of 2,897, 2026-11-03) | Dialogs / tooltips / help | Script support | Native review | Status | Acrobat ships it | To `full` (h) |
|---|---|---|---|---|---|---|---|---|
| English | `en` | built in (100%) | all; README and docs | Latin | yes | **full** | yes | 0 |
-| Simplified Chinese | `zh-hans` | 2,088 (97.4%) | dialogs and tooltips through `tl!`; no help | CJK text and IME work; native craft-fonts builds embed the **LXGW WenKai Lite** Hans face, while the web build has no Hans face beyond BIZ UDPGothic, and missing-glyph reports (#826, #688, #728, #758; Flatpak #689) predate the native face | no | partial | yes | 6–12 |
-| Spanish | `es` | 2,798 (100% of current key union) | dialogs and tooltips; no help | Latin | no | partial | yes | 2–4 |
-| Hindi | `hi` | 0 | none | Devanagari not tested (egui shapes Telugu conjuncts, so shaping is likely workable); the pinned craft-fonts manifest has Noto Sans Devanagari Regular; rendering remains unqualified | no | none | no | 10–18 |
-| Arabic | `ar` | 2,143 (100%) | dialogs and tooltips; no help | Logical-order catalog; egui 0.37's epaint reorders with UAX #9, Arabic, Kurdish and Persian labels use an explicit right-to-left paragraph direction, and stock chrome is mirrored. Native/browser RTL input and IME, and complex bidirectional workflows, are not yet qualified (`localization.md` §Arabic) | no | partial | yes (Middle East edition) | 25–45 |
-| French | `fr` | 2,128 (99.3%) | dialogs and tooltips; no help | Latin | no | partial | yes | 1–2 |
-| Portuguese (Brazil) | `pt-br` | 2,798 (100% of current union) | dialogs and tooltips; no help | Latin | community (#288) | partial | yes | 1–2 |
-| Indonesian | `id` | 0 | none | Latin | no | none | no | 3–5 |
-| Japanese | `ja` | 2,123 (99.1%) | dialogs and tooltips; no help | BIZ UDPGothic from craft-fonts; IME patched on macOS, Windows, X11, Wayland; vertical text renders but can't be edited | no | partial | yes | 4–8 |
-| German | `de` | 2,128 (99.3%) | dialogs and tooltips; no help | Latin | community, in progress (#828: terminology, clipping) | partial | yes | 2–4 |
-| Korean | `ko` | 0 | none | Hangul IME patched (Microsoft and Apple Korean, `vendor/README.md` winit 3, 6, 9, 10); no Hangul UI face in craft-fonts | no | none | yes | 6–10 |
-| Vietnamese | `vi` | 2,798 (100% of current key union) | dialogs and tooltips; no help | Latin with stacked diacritics; bundled Inter covers them (fonts test) | community | partial | no | 2–4 |
+| Simplified Chinese | `zh-hans` | 2,560 (88.4%) | dialogs and tooltips through `tl!`; no help | CJK text and IME work; native craft-fonts builds embed the **LXGW WenKai Lite** Hans face, while the web build has no Hans face beyond BIZ UDPGothic, and missing-glyph reports (#826, #688, #728, #758; Flatpak #689) predate the native face | no | partial | yes | 6–12 |
+| Spanish | `es` | 2,851 (98.4%) | dialogs and tooltips; no help | Latin | no | partial | yes | 2–4 |
+| Hindi | `hi` | 2,825 (97.5%) | dialogs and tooltips; no help | Devanagari not tested (egui shapes Telugu conjuncts, so shaping is likely workable); the pinned craft-fonts manifest has Noto Sans Devanagari Regular; rendering remains unqualified | no | partial | no | 10–18 |
+| Arabic | `ar` | 2,836 (97.9%) | dialogs and tooltips; no help | Logical-order catalog; egui 0.37's epaint reorders with UAX #9, Arabic, Kurdish and Persian labels use an explicit right-to-left paragraph direction, and stock chrome is mirrored. Native/browser RTL input and IME, and complex bidirectional workflows, are not yet qualified (`localization.md` §Arabic) | no | partial | yes (Middle East edition) | 25–45 |
+| French | `fr` | 2,851 (98.4%) | dialogs and tooltips; no help | Latin | no | partial | yes | 1–2 |
+| Portuguese (Brazil) | `pt-br` | 2,851 (98.4%) | dialogs and tooltips; no help | Latin | community (#288) | partial | yes | 1–2 |
+| Indonesian | `id` | 2,825 (97.5%) | dialogs and tooltips; no help | Latin | no | partial | no | 3–5 |
+| Japanese | `ja` | 2,597 (89.6%) | dialogs and tooltips; no help | BIZ UDPGothic from craft-fonts; IME patched on macOS, Windows, X11, Wayland; vertical text renders but can't be edited | no | partial | yes | 4–8 |
+| German | `de` | 2,600 (89.7%) | dialogs and tooltips; no help | Latin | community, in progress (#828: terminology, clipping) | partial | yes | 2–4 |
+| Korean | `ko` | 2,825 (97.5%) | dialogs and tooltips; no help | Hangul IME patched (Microsoft and Apple Korean, `vendor/README.md` winit 3, 6, 9, 10); no Hangul UI face in craft-fonts | no | partial | yes | 6–10 |
+| Vietnamese | `vi` | 2,851 (98.4%) | dialogs and tooltips; no help | Latin with stacked diacritics; bundled Inter covers them (fonts test) | community | partial | no | 2–4 |
-**Localization dimension ≈ 68%**: the mean over the twelve, counting a catalog's percentage but only
-60% for Chinese and Arabic until their script problems are fixed, and 0 for Hindi, Indonesian and
-Korean (still missing). Vietnamese moved from 0% to 100% in that mean (59% → 68%). **≈ 55–110 h**
+**Localization dimension ≈ 68%** (scored 2026-10-13, before the counts above): the mean over the
+twelve, counting a catalog's percentage of the 2,143-key snapshot but only 60% for Chinese and
+Arabic until their script problems are fixed, and 0 for Hindi, Indonesian and Korean, which had no
+catalog yet. Vietnamese moved from 0% to 100% in that mean (59% → 68%). Hindi, Indonesian and
+Korean now have catalogs, so the score understates them. It is not re-scored here, because that
+decides how their script caveats count (Devanagari rendering unqualified, no Hangul UI face). **≈ 55–110 h**
to bring all twelve to `full`, of which ≈ 35–60 h is engineering (remaining RTL qualification, a web Hans face, bidi text)
and the rest catalogs and fixes; native-speaker review needs humans.
No language is `full` except English: every catalog leaves engine error details in English, and
-none has translated help. The **To `full`** hours of Vietnamese and Spanish are therefore residual
-help/docs polish (catalog and script work are already done), not missing UI strings.
+none has translated help. The **To `full`** hours of Vietnamese and Spanish are therefore mostly
+help/docs polish: their script work is done, and each catalog lacks 46 strings on 2026-11-03.
## Other shipped languages
-| Language | Code | UI strings translated | Status | Acrobat ships it |
+| Language | Code | UI strings translated (of 2,897, 2026-11-03) | Status | Acrobat ships it |
|---|---|---|---|---|
-| Traditional Chinese | `zh-hant` | 2,016 (94.1%) | partial (same Hans/Hant face caveat) | yes |
-| Russian | `ru` | 2,043 (95.3%) | partial | yes |
-| Bulgarian | `bg` | 2,094 (97.7%) | partial | no |
-| Czech | `cs` | 2,794 entries (all but four keys of the current union; the engine's sentences, weekdays and certificate fields) | partial | yes |
-| Telugu | `te` | 2,058 (96.0%) | partial (the release-pinned craft-fonts has no Telugu face yet) | no |
-| Hungarian | `hu` | 2,126 (99.2%) | partial | yes |
-| Ukrainian | `uk` | 2,142 (100%) | partial | yes |
-| Italian | `it` | 2,736 entries (all but 62 keys of the current union) | partial | yes |
-| Kazakh | `kk` | 2,539 entries | partial | no |
-| Polish | `pl` | 2,611 entries | partial | yes |
-| Slovenian | `sl` | 2,536 entries | partial | no |
-| Greek | `el` | 2,545 entries | partial | no |
-| Turkish | `tr` | 2,867 entries (0 missing in `cargo xtask i18n-report`, 2026-11-03) | partial; AI-assisted, judgement calls reviewed by a native speaker, full proofreading pending | yes |
-| Lithuanian | `lt` | 2,798 (100% of current key union) | partial; community native-speaker review ([#1401](https://github.com/storytold/pdfcraft/pull/1401)) | no |
-| Finnish | `fi` | 2,798 entries (every current key) | partial; AI-assisted, native proofreading pending | yes |
-| Albanian | `sq` | 2,524 entries | partial; not yet reviewed by a native speaker | no |
-| Catalan | `ca` | 2,798 entries | partial: no translated help, engine error details in English; native-speaker review by the contributor | no |
-| Romanian | `ro` | 2,798 entries (every current key) | partial; AI-assisted, not yet reviewed line by line by a native speaker | no |
-| Norwegian Bokmål | `nb` | 2,707 entries | partial; native-speaker terminology review by the contributor ([#1836](https://github.com/storytold/pdfcraft/pull/1836)), not yet line by line | yes |
-| Persian | `fa` | 2,785 entries (all but 13 keys of the current 2,798-key union) | partial; AI-assisted, not yet reviewed line by line by a native speaker | no |
+| Traditional Chinese | `zh-hant` | 2,559 (88.3%) | partial (same Hans/Hant face caveat) | yes |
+| Russian | `ru` | 2,515 (86.8%) | partial | yes |
+| Bulgarian | `bg` | 2,564 (88.5%) | partial | no |
+| Czech | `cs` | 2,847 (98.3%) | partial | yes |
+| Telugu | `te` | 2,513 (86.7%) | partial (the release-pinned craft-fonts has no Telugu face yet) | no |
+| Hungarian | `hu` | 2,599 (89.7%) | partial | yes |
+| Ukrainian | `uk` | 2,600 (89.7%) | partial | yes |
+| Italian | `it` | 2,790 (96.3%) | partial | yes |
+| Kazakh | `kk` | 2,609 (90.1%) | partial | no |
+| Polish | `pl` | 2,681 (92.5%) | partial | yes |
+| Slovenian | `sl` | 2,618 (90.4%) | partial | no |
+| Greek | `el` | 2,615 (90.3%) | partial | no |
+| Turkish | `tr` | 2,895 (99.9%) | partial; AI-assisted, judgement calls reviewed by a native speaker, full proofreading pending | yes |
+| Lithuanian | `lt` | 2,851 (98.4%) | partial; community native-speaker review ([#1401](https://github.com/storytold/pdfcraft/pull/1401)) | no |
+| Finnish | `fi` | 2,849 (98.3%) | partial; AI-assisted, native proofreading pending | yes |
+| Albanian | `sq` | 2,604 (89.9%) | partial; not yet reviewed by a native speaker | no |
+| Catalan | `ca` | 2,849 (98.3%) | partial: no translated help, engine error details in English; native-speaker review by the contributor | no |
+| Romanian | `ro` | 2,849 (98.3%) | partial; AI-assisted, not yet reviewed line by line by a native speaker | no |
+| Norwegian Bokmål | `nb` | 2,758 (95.2%) | partial; native-speaker terminology review by the contributor ([#1836](https://github.com/storytold/pdfcraft/pull/1836)), not yet line by line | yes |
+| Persian | `fa` | 2,801 (96.7%) | partial; AI-assisted, not yet reviewed line by line by a native speaker | no |
+| Central Kurdish (Sorani) | `ckb` | 2,754 (95.1%) | partial; right-to-left like Arabic | no |
+| Thai | `th` | 2,751 (95.0%) | partial | no |
+| Lao | `lo` | 2,504 (86.4%) | partial | no |
-**20 other languages** ship (34 catalogs plus English = **35** interface languages in Preferences).
-The entry counts without percentages are as of 2026-10-25; they are not percentages of the older 2,143-key snapshot above. Their presence does not imply a detailed linguistic or runtime review.
+**23 other languages** ship (34 catalogs plus English = **35** interface languages in Preferences).
+Their presence does not imply a detailed linguistic or runtime review.
Acrobat languages PdfCraft lacks: Danish, Dutch, Swedish, Hebrew. Vietnamese is shipped here but not by Acrobat.
## Revision history
| Date | Change | Summary |
|---|---|---|
+| 2026-11-03 | minor | Every catalog restated from `cargo xtask i18n-report` on `14ae839a` (of the 2,897 strings in the report's denominator), replacing the catalog-union measure, which had reached 2,895 keys and left rows "100%" that were 44 short (#5805). Hindi, Indonesian and Korean restated from 0 to their catalogs, and Thai, Lao and Central Kurdish added to the table. The ≈ 68% score is not re-scored |
| 2026-10-25 | minor | Arabic current state corrected: catalogs stay logical, Arabic/Kurdish labels take an explicit RTL direction, and stock chrome mirrors; native/browser RTL input, IME and complex workflows remain unqualified. Native Simplified Chinese uses LXGW WenKai Lite; the web build still has no Hans face and the release-pinned craft-fonts still has no Telugu face. Scores and estimates unchanged |
| 2026-10-25 | minor | Added Persian (`fa`, 2,785 entries, all but 13 of the current 2,798-key union); right-to-left like Arabic and Kurdish, with logical entries reordered by egui 0.37's epaint; AI-assisted, not yet native-reviewed |
| 2026-10-21 | minor | Brazilian Portuguese (`pt-br`) now covers all 2,674 distinct keys in the current catalog union; no help or engine/OS error-detail localization; twelve-language mean still rounds to ≈ 68% |
diff --git a/docs/localization.md b/docs/localization.md
index 96822877a3..a7860fa1c0 100644
--- a/docs/localization.md
+++ b/docs/localization.md
@@ -1,6 +1,6 @@
# Interface language
-Choose **Menu > Edit > Preferences…** (Command-comma on macOS, Ctrl-comma elsewhere) **> Interface language** and select **Auto**, **English**, **日本語**, **简体中文**, **繁體中文**, **Čeština**, **Português (Brasil)**, **Deutsch**, **Español**, **Français**, **Русский**, **Қазақша**, **Български**, **తెలుగు**, **Magyar**, **Українська**, **Italiano**, **العربية**, **کوردیی ناوەندی**, **فارسی**, **Polski**, **Slovenščina**, **Ελληνικά**, **Türkçe**, **Lietuvių**, **Tiếng Việt**, **Suomi**, **Shqip**, **Català**, **Română** or **Norsk bokmål**. The change applies immediately and persists between launches. Command ids, document contents and file names are unchanged.
+Choose **Menu > Edit > Preferences…** (Command-comma on macOS, Ctrl-comma elsewhere) **> Interface language** and select **Auto**, **English**, **日本語**, **简体中文**, **繁體中文**, **Čeština**, **Português (Brasil)**, **Deutsch**, **Español**, **Français**, **Русский**, **Қазақша**, **Български**, **తెలుగు**, **Magyar**, **Українська**, **Italiano**, **العربية**, **کوردیی ناوەندی**, **فارسی**, **Polski**, **Slovenščina**, **Ελληνικά**, **Türkçe**, **Lietuvių**, **Tiếng Việt**, **Suomi**, **Shqip**, **Català**, **Română** or **Norsk bokmål**. The change applies immediately and persists between launches. Command ids, document contents and file names are unchanged. The status caption PdfCraft draws into a named-layer signature appearance ("Signature valid" and its siblings) follows it too, on screen, in exports and in print; it is never saved. It is drawn in Helvetica, or shaped in embedded Inter, or shaped in a craft-fonts face for Arabic, Japanese, Telugu, Thai and Devanagari when the build has one (drawn as outlines), and otherwise in English, as Chinese always is; saving never writes it.
Displayed keyboard shortcuts use the same active interface language. For example, German shows `Strg+K` and `Strg+Umschalt+S` in the toolbar, menus, command palette, tooltips and Keyboard shortcuts dialog; macOS keeps its modifier symbols (`⌘`, `⇧`, `⌃`). Key names have their own `key` catalog context, so the Delete key can read `Entf` while the command remains `Löschen`. A missing key-name entry falls back to the English key name. Actual bindings and machine-facing command ids remain stable.
diff --git a/docs/releasing.md b/docs/releasing.md
index 72206e16f1..eaeb4a63f1 100644
--- a/docs/releasing.md
+++ b/docs/releasing.md
@@ -128,8 +128,14 @@ neither the MSI nor the portable zip needs the Visual C++ redistributable.
this.
- `installer-ui.wxs` supplies native welcome, maintenance, progress, files-in-use and outcome
dialogs. Full UI confirms success with Finish; failures and cancellations have distinct messages.
- The welcome dialog has a "Create a desktop shortcut" checkbox and an "Edit with PdfCraft"
- right-click menu checkbox, both ticked by default. `/qn` and `/qb` stay unattended and create
+ The welcome dialog has an "Install to" row (a `PathEdit`, and Browse… into `BrowseFolder`, a
+ native folder browser: drive list, folder list, Up, New folder, typed path; #1139), a "Create a
+ desktop shortcut" checkbox and an "Edit with PdfCraft" right-click menu checkbox, both ticked by
+ default. Install sets the folder (`SetTargetPath`) before the dialog closes. `INSTALLFOLDER` is
+ secure, so the choice reaches the elevated install, and `INSTALLFOLDER=` works on the
+ command line. The row starts on the folder `install-policy.wxi` chose for the scope picked on the
+ first page (the recorded folder on an update), and an update installs into the recorded folder
+ unless the command line gives one (`INSTALLATION.md`). `/qn` and `/qb` stay unattended and create
both unless `INSTALLDESKTOPSHORTCUT=0` or `INSTALLPDFCONTEXTMENU=0` is passed;
`INSTALLIMAGECONTEXTMENU=0` (no checkbox) leaves out the image menu. An update (the launcher runs
`msiexec /passive` with no properties) keeps the desktop shortcut only if `PdfCraft.lnk` is still
diff --git a/docs/roadmap.md b/docs/roadmap.md
index 736d53bb7a..f870a91a2c 100644
--- a/docs/roadmap.md
+++ b/docs/roadmap.md
@@ -1,11 +1,15 @@
# PdfCraft roadmap: milestones and what's next
+> **Last reviewed:** 2026-11-07 | **Last updated:** 2026-11-07 | **Change:** patch (M7 #2964 / #3185: grouped source text and Thai font/style preservation, with reported deep or unsafe groups and a per-glyph check of the Thai map repair; estimates unchanged)
+
> **Last reviewed:** 2026-10-28 | **Last updated:** 2026-10-28 | **Change:** minor (M10, #4119 partial: Enhance scanned file cleans scanned pages in place: background removal, edge shadow removal, despeckle; estimates unchanged)
> **Last reviewed:** 2026-11-03 | **Last updated:** 2026-11-03 | **Change:** patch (M5 #5850 review: indirect typewriter intent and composer edits preserve outer whitespace; movement regression commits by outside click; estimates unchanged)
> **Last reviewed:** 2026-11-03 | **Last updated:** 2026-11-03 | **Change:** patch (M5 #5850: Enter adds Fill & Sign line breaks; outside clicks commit, Escape cancels, and saved multiline appearances retain their text and height; estimates unchanged)
> **2026-11-03, M7 / #5835 review:** active image crops retain secondary clicks over overlapping images; crop controls share measured layout with hit detection. Rotation, handle and page-edge regressions added; focused tests, scoped Clippy, formatting, layering and asset checks passed locally. Estimates unchanged.
+> **Last reviewed:** 2026-10-31 | **Last updated:** 2026-10-31 | **Change:** minor (M3/M4, #5330: Crop pages is directly available in the document quick toolbar; estimates unchanged)
+
> **Last reviewed:** 2026-11-01 | **Last updated:** 2026-11-01 | **Change:** patch (M7 #5657: header/footer, watermark and background operations commit all selected pages together; later-page errors preserve marks, content, shared/inherited resources and pending edits; estimates unchanged)
@@ -216,7 +220,7 @@ total matches the parity estimate.
| M2 | Model, render, text | 200–350 | 15% | 130–230 | hayro bootstrap renderer (vendored patches); inspector predictor scratch is bounded by available input, and JPX sample rescaling handles 1–32 bits safely. Text extraction reaches word-F1 0.98 against pdftotext. Short same-line redraws split before placement rather than interleaving. Missing: model crate, fonts, DisplayList, renderer independent of hayro. Inspector page-label traversal and output are resource-bounded, with physical-number fallback warnings. Packed TIFF-predictor RGB rows retain later rows in decoding and rendering. Page marks, added content and print output retain small page-unit transform coefficients when serialized. Forms without Resources use page Properties for ActualText and layer visibility; own dictionaries stop fallback. Oversized missing inline-image samples, including header and terminator overhead, no longer pin the content window (#3107 / PR #3438); normal large streamed images retain deterministic sample boundaries. Radial luminosity fades have synthetic coverage for the existing #2132 mask guard, including per-pixel references, antialiased clips, previews, scales and tiles; no additional production fix was needed. Dotted TOC leaders no longer inflate letter tracking or hide word spaces (#3086); phrase search and selection are covered. Short tracked ellipses retain their gap samples and remain searchable. Missing spacing glyphs in non-embedded Japanese CID substitutes render blank without changing PDF advances or Unicode (#3601). The desktop viewer can use installed CJK fonts, including Windows GBK Song/Hei/Kai/FangSong and subset-prefixed Founder names; Combine thumbnails and accessibility figure previews use the same display-only fallback, without changing export or print font policy (#234, continuation of #1567, review #4172). Print previews exclude installed faces and isolate their font cache; GBK regressions cover view/print switching for inline and pooled whole-page/tile rendering. Installed-font helpers and their regression contracts have function documentation. GBK regression rasters match explicit-Unicode references with independently selected installed faces; wrong-glyph and wrong-family negative controls fail. Integration with main fa5f9f8c retains viewer fallback across the split engine session modules, renderer tests and Combine thumbnail workers. |
| M2 | Model, render, text | 200–350 | 15% | 130–230 | hayro bootstrap renderer (vendored patches); inspector predictor scratch is bounded by available input, and JPX sample rescaling handles 1–32 bits safely. Text extraction reaches word-F1 0.98 against pdftotext. Short same-line redraws split before placement rather than interleaving. Missing: model crate, fonts, DisplayList, renderer independent of hayro. Inspector page-label traversal and output are resource-bounded, with physical-number fallback warnings. Packed TIFF-predictor RGB rows retain later rows in decoding and rendering. The renderer keeps its one-point crop-size floor in physical points after UserUnit scaling, with regression coverage for crop origins, rotations and f32 reciprocal rounding. Existing unit policy and nearly-zero fallback are retained. |
| M2 | Model, render, text | 200–350 | 15% | 130–230 | hayro bootstrap renderer (vendored patches); inspector predictor scratch is bounded by available input, and JPX sample rescaling handles 1–32 bits safely. Text extraction reaches word-F1 0.98 against pdftotext. Short same-line redraws split before placement rather than interleaving. Missing: model crate, fonts, DisplayList, renderer independent of hayro. Inspector page-label traversal and output are resource-bounded, with physical-number fallback warnings |
-| M3 | Viewer app (native + web) | 80–150 | 90% | 10–20 | Acrobat-style shell, find, select, panels, tiles, web build, UI control channel for agents (opt-in). #3808: the Pages inspector offers a 50–150% thumbnail slider and buttons, also available through `ui.set`. Missing: 60 fps test on a 500-page document, snapshot tests of every panel Done since: fit visible, document title in the window; Linux middle-button scrolling; shared three-state theme preferences in the toolbar, View menu and control channel; numeric Linux portal events and idle wakeups completing #881, with native appearance inheritance retained (#446); late browser startup downloads preserve the current document and Save target (#171). Selected-text Copy in Edit and the canvas context menu is covered by focused regressions and native clipboard checks (#1225); document copy restrictions apply to the floating action too. #1364 candidate: absolute local GoToR links ask before target access; headless callers explicitly opt in. Native-opening candidate: chosen tools survive preparation and password retries; startup intake waits for pending preparation. Page-label navigation displays logical labels, retains the current page on unchanged submission and refreshes focused same-document replacements; clean file-watcher reload preserves the chosen scrolling mode, preventing a Single Page reader from jumping to page 1 during replacement. Synthetic control regressions cover these behaviors. #3149: page-list changes discard render demand based on old geometry; actual raster dimensions are checked against the GPU limit before upload. Synthetic crash and continued-rendering regressions cover the replacement path. Save-prompt shortcuts yield to dialogs above them; stacked link-consent UI regression covers Escape and Return. Comment hover follows individual marked lines and original annotation paint order (#3541/#3620), independently of spatial inspection sorting; synthetic rotation, differing-upper-edge overlap and unchanged-document regressions. Optional page gaps join page edges without cropping PDF margins; current-document toggle, persisted default and UI control options are covered by viewer tests. Gap changes in Organize Pages preserve document scroll position, and both comparison panes follow menu and control choices. Repeated window resizes by an edge and moves by the tab strip on GNOME/Wayland work without a click in between. Optional --two-paged applies noncontinuous two-page layout to explicitly opened CLI files without changing defaults; explicit --layout wins. |
+| M3 | Viewer app (native + web) | 80–150 | 90% | 10–20 | Acrobat-style shell, find, select, panels, tiles, web build, UI control channel for agents (opt-in). #3808: the Pages inspector offers a 50–150% thumbnail slider and buttons, also available through `ui.set`. Missing: 60 fps test on a 500-page document, snapshot tests of every panel Done since: fit visible, document title in the window; Linux middle-button scrolling; shared three-state theme preferences in the toolbar, View menu and control channel; numeric Linux portal events and idle wakeups completing #881, with native appearance inheritance retained (#446); late browser startup downloads preserve the current document and Save target (#171). Selected-text Copy in Edit and the canvas context menu is covered by focused regressions and native clipboard checks (#1225); document copy restrictions apply to the floating action too. #1364 candidate: absolute local GoToR links ask before target access; headless callers explicitly opt in. Native-opening candidate: chosen tools survive preparation and password retries; startup intake waits for pending preparation. Page-label navigation displays logical labels, retains the current page on unchanged submission and refreshes focused same-document replacements; clean file-watcher reload preserves the chosen scrolling mode, preventing a Single Page reader from jumping to page 1 during replacement. Synthetic control regressions cover these behaviors. #3149: page-list changes discard render demand based on old geometry; actual raster dimensions are checked against the GPU limit before upload. Synthetic crash and continued-rendering regressions cover the replacement path. Save-prompt shortcuts yield to dialogs above them; stacked link-consent UI regression covers Escape and Return. Comment hover follows individual marked lines and original annotation paint order (#3541/#3620), independently of spatial inspection sorting; synthetic rotation, differing-upper-edge overlap and unchanged-document regressions. Optional page gaps join page edges without cropping PDF margins; current-document toggle, persisted default and UI control options are covered by viewer tests. Gap changes in Organize Pages preserve document scroll position, and both comparison panes follow menu and control choices. Repeated window resizes by an edge and moves by the tab strip on GNOME/Wayland work without a click in between. Optional --two-paged applies noncontinuous two-page layout to explicitly opened CLI files without changing defaults; explicit --layout wins. Crop pages is directly available in the quick toolbar (#5330). |
| M3 | Viewer app (native + web) | 80–150 | 90% | 10–20 | Acrobat-style shell, find, select, panels, tiles, web build, UI control channel for agents (opt-in). Missing: 60 fps test on a 500-page document, snapshot tests of every panel Done since: fit visible, document title in the window; Linux middle-button scrolling; shared three-state theme preferences in the toolbar, View menu and control channel; numeric Linux portal events and idle wakeups completing #881, with native appearance inheritance retained (#446); late browser startup downloads preserve the current document and Save target (#171). Selected-text Copy in Edit and the canvas context menu is covered by focused regressions and native clipboard checks (#1225); document copy restrictions apply to the floating action too. #1364 candidate: absolute local GoToR links ask before target access; headless callers explicitly opt in. Native-opening candidate: chosen tools survive preparation and password retries; startup intake waits for pending preparation. Page-label navigation displays logical labels, retains the current page on unchanged submission and refreshes focused same-document replacements; clean file-watcher reload preserves the chosen scrolling mode, preventing a Single Page reader from jumping to page 1 during replacement. Synthetic control regressions cover these behaviors. Wrapped revision buttons stay above Binding in Document Properties (#2739); a synthetic UI test checks layout and saved revision content. |
| M3 | Viewer app (native + web) | 80–150 | 90% | 10–20 | Acrobat-style shell, find, select, panels, tiles, web build, UI control channel for agents (opt-in). Missing: 60 fps test on a 500-page document, snapshot tests of every panel Done since: fit visible, document title in the window; Linux middle-button scrolling; shared three-state theme preferences in the toolbar, View menu and control channel; numeric Linux portal events and idle wakeups completing #881, with native appearance inheritance retained (#446); late browser startup downloads preserve the current document and Save target (#171). #1364 candidate: absolute local GoToR links ask before target access; headless callers explicitly opt in. Native-opening candidate: chosen tools survive preparation and password retries; startup intake waits for pending preparation. Later native-open replies stay queued while a modal or picker owns the foreground; regressions cover recipient ownership, completion/cancellation and one-shot wakes. |
| M3 | Viewer app (native + web) | 80–150 | 90% | 10–20 | Acrobat-style shell, find, select, panels, tiles, web build, UI control channel for agents (opt-in). Missing: 60 fps test on a 500-page document, snapshot tests of every panel Done since: fit visible, document title in the window; Linux middle-button scrolling; shared three-state theme preferences in the toolbar, View menu and control channel; numeric Linux portal events and idle wakeups completing #881, with native appearance inheritance retained (#446); late browser startup downloads preserve the current document and Save target (#171). #1364 candidate: absolute local GoToR links ask before target access; headless callers explicitly opt in. Native-opening candidate: chosen tools survive preparation and password retries; startup intake waits for pending preparation. #1980: exact quit modifiers preserve Ctrl+Alt+Q email input; Ctrl+Q/Cmd+Q asks before discarding unsaved documents. |
@@ -239,15 +243,15 @@ total matches the parity estimate.
| M6 | Forms + JavaScript | 160–320 | 50% | 40–75 | Done: filling all field types with regenerated appearances; Prepare a form (every field type, multi-select/shared properties, move/resize/delete, Field Properties General/Appearance/Position/Options/Format/Validate/Calculate); Acrobat's AF format/keystroke/validate/calculate functions and simplified field notation run natively in Acrobat's event order; tab order; push-button actions; flatten; agent tools. Form data exchange (FDF, XFDF, XML, CSV, text) done; XFDF values retain text across XML comments and processing instructions. Plain AcroForm XML imports retain all direct text around comments and processing instructions, including CDATA and character references. Done since: JavaScript engine (boa, sandboxed) running custom keystroke/validate/calculate/format and button scripts, document JavaScripts, console. Missing: Actions tab, wider object model (annotations, layers, dialogs), XFA Done since: Multi-select choice fields write ascending `/I` option indices while preserving `/V` selection order; synthetic forms/engine regressions cover reverse selection and save/reopen. CSV export preserves carriage returns in names and values. |
| M6 | Forms + JavaScript | 160–320 | 50% | 40–75 | Done: filling all field types with regenerated appearances; Prepare a form (every field type, multi-select/shared properties, move/resize/delete, Field Properties General/Appearance/Position/Options/Format/Validate/Calculate); Acrobat's AF format/keystroke/validate/calculate functions and simplified field notation run natively in Acrobat's event order; tab order; push-button actions; flatten; agent tools. Form data exchange (FDF, XFDF, XML, CSV, text) done; XFDF values retain text across XML comments and processing instructions. XML/XFDF exports preserve tabs and line breaks in names and comment metadata. Refreshed against upstream `99941daa` (2026-10-15). Done since: JavaScript engine (boa, sandboxed) running custom keystroke/validate/calculate/format and button scripts, document JavaScripts, console. Missing: Actions tab, wider object model (annotations, layers, dialogs), XFA Done since: Multi-select choice fields write ascending `/I` option indices while preserving `/V` selection order; synthetic forms/engine regressions cover reverse selection and save/reopen. CSV export preserves carriage returns in names and values. |
| M6 | Forms + JavaScript | 160–320 | 50% | 40–75 | Done: filling all field types with regenerated appearances; Prepare a form (every field type, multi-select/shared properties, move/resize/delete, Field Properties General/Appearance/Position/Options/Format/Validate/Calculate); Acrobat's AF format/keystroke/validate/calculate functions and simplified field notation run natively in Acrobat's event order; tab order; push-button actions; flatten; agent tools. Form data exchange (FDF, XFDF, XML, CSV, text) done; XFDF values retain text across XML comments and processing instructions. XML/XFDF exports preserve tabs and line breaks in names and comment metadata. Plain AcroForm XML imports retain all direct text around comments and processing instructions, including CDATA and character references. CSV export and spreadsheet merging quote tabs, and import distinguishes quoted tabs from TSV delimiters without changing field identities. Done since: JavaScript engine (boa, sandboxed) running custom keystroke/validate/calculate/format and button scripts, document JavaScripts, console. Missing: Actions tab, wider object model (annotations, layers, dialogs), XFA Done since: Multi-select choice fields write ascending `/I` option indices while preserving `/V` selection order; synthetic forms/engine regressions cover reverse selection and save/reopen. CSV export preserves carriage returns in names and values. |
-| M7 | Content editing (text, images, header/footer, watermark) | 250–500 | 20% | 100–180 | Done: header & footer, watermarks, backgrounds, Bates; added text and images that stay editable (move, resize, format, rotate, flip, crop, replace); links (Link tool, Link Properties, create from URLs, remove all). Done since: Edit text preserves Arabic/Hebrew `/ActualText` typing order, with font-independent regressions; single-glyph RTL ligature spans (including lam-alef) join their surrounding word. Done since (#1116): editable text regions grouped across compatible words and subset fonts, one rich-text editor over a background with the source text removed, embedded sfnt faces reused as editor faces, and visible (clipped) bounds for cropped-image selection and resize. Exclusive crops now resize across nested states and content streams, with shared clips fixed. Done since: #594 ordinary paragraph drags preserve overlapping source text; UI/engine regressions, native save/reopen, independent-reader checks and full CI passed in the Linux test environment. #1200 candidate: local GoToR links open in desktop tabs and through root-confined automation; appearance-only edits preserve existing actions. Named destinations remain unapplied and `/NewWindow` is a tab hint. Done since: #3187: Added-image automation normalizes extreme signed rotation angles before combining them with the current orientation; integer bounds, history, pixels, save/reopen and MCP have regressions. Done since: #2592: Styled fallback fonts batch up to 240 glyphs per actual face and retain source styles. Budget refusal and distinct same-BaseFont descriptor weights have mutation-checked regressions; coverage and complex mixed runs remain limited. Done since: #5657 page-mark operations are atomic across selected pages, including shared/inherited resources and existing unsaved edits. Missing: editing existing text and images in place (the longest pole), image/PDF watermarks PR #2155 candidate: editor-owned crops preserve original clips through group moves; Arrange preserves added-item stream ownership and refuses unsafe scope/state/tag extraction; image handles and flips follow page orientation; general transforms and Unicode script toggles have headless tools. Clipboard, mixed-size formatting, Home pins and reloadable installed-font discovery have review regressions. Latest follow-up uses explicit image-paste events, refreshes the mixed-size display, and documents script normalization with Undo. Further review covers inherited Form text and mask chronology, scoped transform composition, affine resize/rotation pivots, paste/selection ownership, no-op scripts and page-menu permissions. Done since: #5835 a right-click on an image in crop mode keeps the crop and opens no menu, also over overlapping and rotated images. |
+| M7 | Content editing (text, images, header/footer, watermark) | 250–500 | 20% | 100–180 | Done: header & footer, watermarks, backgrounds, Bates; added text and images that stay editable (move, resize, format, rotate, flip, crop, replace); links (Link tool, Link Properties, create from URLs, remove all). Done since: Edit text preserves Arabic/Hebrew `/ActualText` typing order, with font-independent regressions; single-glyph RTL ligature spans (including lam-alef) join their surrounding word. Done since (#1116): editable text regions grouped across compatible words and subset fonts, one rich-text editor over a background with the source text removed, embedded sfnt faces reused as editor faces, and visible (clipped) bounds for cropped-image selection and resize. Exclusive crops now resize across nested states and content streams, with shared clips fixed. Done since: #594 ordinary paragraph drags preserve overlapping source text; UI/engine regressions, native save/reopen, independent-reader checks and full CI passed in the Linux test environment. #1200 candidate: local GoToR links open in desktop tabs and through root-confined automation; appearance-only edits preserve existing actions. Named destinations remain unapplied and `/NewWindow` is a tab hint. Done since: #3187: Added-image automation normalizes extreme signed rotation angles before combining them with the current orientation; integer bounds, history, pixels, save/reopen and MCP have regressions. Done since: #2592: Styled fallback fonts batch up to 240 glyphs per actual face and retain source styles. Budget refusal and distinct same-BaseFont descriptor weights have mutation-checked regressions; coverage and complex mixed runs remain limited. Done since: #5657 page-mark operations are atomic across selected pages, including shared/inherited resources and existing unsaved edits. Missing: editing existing text and images in place (the longest pole), image/PDF watermarks PR #2155 candidate: editor-owned crops preserve original clips through group moves; Arrange preserves added-item stream ownership and refuses unsafe scope/state/tag extraction; image handles and flips follow page orientation; general transforms and Unicode script toggles have headless tools. Clipboard, mixed-size formatting, Home pins and reloadable installed-font discovery have review regressions. Latest follow-up uses explicit image-paste events, refreshes the mixed-size display, and documents script normalization with Undo. Further review covers inherited Form text and mask chronology, scoped transform composition, affine resize/rotation pivots, paste/selection ownership, no-op scripts and page-menu permissions. Done since: #5835 a right-click on an image in crop mode keeps the crop and opens no menu, also over overlapping and rotated images. Thai editing (#2964, #3185): supported Form text is editable; legacy Thai retains source fonts and text settings. Cross-family replacement is explicit; unsafe groups and mixed contextual styles remain partial. |
| M7 | Content editing (text, images, header/footer, watermark) | 250–500 | 20% | 100–180 | Done: header & footer, watermarks, backgrounds, Bates; added text and images that stay editable (move, resize, format, rotate, flip, crop, replace); links (Link tool, Link Properties, create from URLs, remove all). Done since: Edit text preserves Arabic/Hebrew `/ActualText` typing order, with font-independent regressions. Done since (#1116): editable text regions grouped across compatible words and subset fonts, one rich-text editor over a background with the source text removed, embedded sfnt faces reused as editor faces, and visible (clipped) bounds for cropped-image selection and resize. Exclusive crops now resize across nested states and content streams, with shared clips fixed. Done since: #594 ordinary paragraph drags preserve overlapping source text; UI/engine regressions, native save/reopen, independent-reader checks and full CI passed in the Linux test environment. #1200 candidate: local GoToR links open in desktop tabs and through root-confined automation; appearance-only edits preserve existing actions. Named destinations remain unapplied and `/NewWindow` is a tab hint. #1316: replacing a line or paragraph keeps a neighbouring line whose glyph box overlaps when the baselines differ; a second copy on the same baseline is still replaced. Missing: editing existing text and images in place (the longest pole), image/PDF watermarks |
| M7 | Content editing (text, images, header/footer, watermark) | 250–500 | 20% | 100–180 | Done: header & footer, watermarks, backgrounds, Bates; added text and images that stay editable (move, resize, format, rotate, flip, crop, replace); links (Link tool, Link Properties, create from URLs, remove all). #3212: Headers, Bates numbers, watermarks and added text stay visible after unfinished marked content, without revealing hidden content. Tracked editable text distinguishes repeated glyph spacing from word gaps, with synthetic paragraph/object regressions. Missing: editing existing text and images in place (the longest pole), watermark print/screen visibility and repeat |
| M6 | Forms + JavaScript | 160–320 | 50% | 40–75 | Done: filling all field types with regenerated appearances; Prepare a form (every field type, multi-select/shared properties, move/resize/delete, Field Properties General/Appearance/Position/Options/Format/Validate/Calculate); Acrobat's AF format/keystroke/validate/calculate functions and simplified field notation run natively in Acrobat's event order; tab order; push-button actions; flatten; agent tools. Form data exchange (FDF, XFDF, XML, CSV, text) done; XFDF values retain text across XML comments and processing instructions. Done since: JavaScript engine (boa, sandboxed) running custom keystroke/validate/calculate/format and button scripts, document JavaScripts, console. Missing: Actions tab, wider object model (annotations, layers, dialogs), XFA Done since: Existing simple field-font encodings and Differences are respected when generating appearances; an unencodable value uses a separate Helvetica appearance font without changing the source font. Synthetic reopen regressions cover punctuation, subset fallback and multiline text. Exact font metrics/layout and broader Unicode fallback remain incomplete. |
| M6 | Forms + JavaScript | 160–320 | 50% | 40–75 | Done: filling all field types with regenerated appearances; Prepare a form (every field type, multi-select/shared properties, move/resize/delete, Field Properties General/Appearance/Position/Options/Format/Validate/Calculate); Acrobat's AF format/keystroke/validate/calculate functions and simplified field notation run natively in Acrobat's event order; tab order; push-button actions; flatten; agent tools. Form data exchange (FDF, XFDF, XML, CSV, text) done; XFDF values retain text across XML comments and processing instructions. Done since: JavaScript engine (boa, sandboxed) running custom keystroke/validate/calculate/format and button scripts, document JavaScripts, console. Missing: Actions tab, wider object model (annotations, layers, dialogs), XFA Done since: Tab and Shift-Tab wrapping to the same field or another widget of that field refresh the newly opened editor from the accepted value before Save. Synthetic UI regressions cover both directions, same-frame Save, validation refusal and undo/redo. Renaming a field renames it in the calculations that read it (field lists, notation, literal `getField` names), in one undo step, and says how many changed. Prepare a form ▸ Calculation order, a page of its own: each calculated field's formula and value, what is wrong (fields that calculate too early, loops, fields missing from `/CO`) and Fix order, Up/Down, Alt+↑/↓ and drag, and on the page each field's step and arrows to and from the field in focus (`form_calculation_order` headlessly). |
| M7 | Content editing (text, images, header/footer, watermark) | 250–500 | 20% | 100–180 | Done: header & footer, watermarks, backgrounds, Bates; added text and images that stay editable (move, resize, format, rotate, flip, crop, replace); links (Link tool, Link Properties, create from URLs, remove all). Missing: editing existing text and images in place (the longest pole), image/PDF watermarks |
| M8 | Security + redaction | 100–180 | 68% | 15–30 | Done: opening protected documents, permissions, Protect Using Password, Remove security; redaction (mark text/areas/pages, Search & Redact with patterns, apply removing glyphs, image pixels, vectors, XObject content, annotations and fields, verification, full rewrite on save); Remove hidden information and Sanitize. Done since: redaction codes (U.S. FOIA and Privacy Act sets as overlay text, in Redaction properties and `redact_mark`). Redaction cleans indirect and form structure references, preserving surviving form tags. Redaction retires inherited resource dictionaries, so a parent `/Pages` can't keep a removed XObject reachable; unredacted pages are left untouched. Image redaction removes alternate images and unsupported masks only on affected images. Changed marked-content spans lose replacement descriptions; untouched spans keep theirs. Hidden-text cleanup retires unused named descriptions across inherited/shared page and form resources (64 focused tests and scoped Rust 1.96 Clippy/wasm checks pass; publication CI pending). Retained text/image-bearing or unreadable tiling-pattern cells now make Apply refuse atomically after a bounded check of rewritten resources; fully removed cells still apply, and cross-page retention is checked. The redaction audit counts a filled cover that hides half of any one word of a long line (#2662), applied or not. Phone-pattern redaction also matches labelled Italian geographic numbers with `+39` and a slash after the area code (#3205 follow-up); unlabelled international slash numbers remain unsupported. Missing: certificate security, custom redaction code sets and pattern locales, DCT re-encoding |
-| M9 | Signatures (PAdES, validation) | 160–280 | 60% | 40–70 | Done: new `sign` crate (DER, X.509, CMS, PKCS #12 on RustCrypto; aws-lc-rs for RSA private keys); PAdES B-B signing (visible, invisible, existing fields, certification with DocMDP); validation with trust store and changes-after-signing classification; self-signed digital IDs; Signatures panel, message bar, sign dialogs; agent tools. Checked with pdfsig and OpenSSL. Done since: macOS Keychain and Windows Current User Personal store signing (software-backed CNG keys), certificate viewer, signed documents protected from rewrites, page validation overlays separate from original signature artwork (baked Not Verified captions remain; #79 open), snapshot tabs that reuse instead of multiplying. Missing: timestamps (B-T), LTV (DSS, OCSP, CRL), FieldMDP, smart cards, PKCS #11 |
-| M10 | OCR, create, export, print | 200–350 | 33% | 120–215 | Done: create from blank/text/PNG/JPEG/TIFF (multi-page)/GIF/BMP; export PNG/JPEG/TIFF and text; Print (Acrobat's sizing, n-up, booklet, poster, comments & forms, preview, the CUPS and Windows spoolers, print-ready PDF). Done since: embedded/72/custom DPI choices for image imports; export all images; OCR (searchable image for pages, ranges and multiple files); single-sided cut-and-stack imposition with cut marks, through Print and doc_print; architectural/ANSI/large ISO sheet presets, Match page at 100% and PDF-scale preview (#599 follow-up); Create PDF from multiple files (PDFs, images and text, edited as pages in the grid); OCR can also read pictures on pages that have text, without adding that text twice (#1028). Model staging fetches SHA-256-verified ONNX detection/recognition files after the upstream RTEN URL brownout; runtime discovery prefers complete ONNX pairs per directory, then complete legacy RTEN pairs, without mixing formats or changing directory precedence. Done since: Word invoice export uses borderless inferred tables, floating positioned text/artwork only where text overlaps an image or is rotated, and per-page sizes, covered by synthetic invoice automation regressions (#773); printing on the web through the browser's print dialog, sheets drawn by PdfCraft (gap 4). Lossless image export applies per-component Decode, including Indexed mapping (#1201 partial). Existing 16-bit precision and color-management limits remain. #3532 partial: vector printing retains existing appearances with absent Subtype through a print-owned Form copy; source artwork stays unchanged. #3120: Office export reads form XObjects 50 levels deep, as the renderer does, and up to 50 000 a page; pages past that are listed in `truncated_pages`. Word table cells use the grid columns they span, including cells after a merged cell. Done since: text in a table slot covered by another cell's span remains as paragraph text in Word, HTML, RTF and PowerPoint. Missing: OCR languages beyond Latin, editable-text OCR output, full Office layout fidelity/import. Done since: dotted-leader contents entries stay in separate complete paragraphs (#1757) #2156 candidate: last selected print paper persists across sessions; other print preferences unchanged. Image export applies soft-mask Decode opacity intervals before resizing, including indirect entries and inverted ranges. Vector printing gives annotation appearances unoccupied XObject names so existing page artwork survives. Done since: Enhance scanned file cleans scanned pages in place (background removal, edge shadow removal, despeckle; the OCR text layer and comments stay; #4119 partial). |
+| M9 | Signatures (PAdES, validation) | 160–280 | 60% | 40–70 | Done: new `sign` crate (DER, X.509, CMS, PKCS #12 on RustCrypto; aws-lc-rs for RSA private keys); PAdES B-B signing (visible, invisible, existing fields, certification with DocMDP); validation with trust store and changes-after-signing classification; self-signed digital IDs; Signatures panel, message bar, sign dialogs; agent tools. Checked with pdfsig and OpenSSL. Done since: macOS Keychain and Windows Current User Personal store signing (software-backed CNG keys), certificate viewer, signed documents protected from rewrites, page validation overlays separate from original signature artwork, placed in the widget's bottom-right corner as it lies on the page, at a quarter of its shorter side and 48 screen points at most, so they annotate the artwork from a corner instead of covering the middle of it and turn with the page and the view (a field falling under 32 screen points, as a page does when zoomed out to fit, keeps its outline), snapshot tabs that reuse instead of multiplying, named-layer signature appearances redrawn for their real state (#79; display, the CLI's render, exports and printing, never saves; captions in the interface language, Chinese in English; the badge stays). Missing: timestamps (B-T), LTV (DSS, OCSP, CRL), FieldMDP, smart cards, PKCS #11 |
+| M10 | OCR, create, export, print | 200–350 | 33% | 120–215 | Done: create from blank/text/PNG/JPEG/TIFF (multi-page)/GIF/BMP; export PNG/JPEG/TIFF and text; Print (Acrobat's sizing, n-up, booklet, poster, comments & forms, preview, the CUPS and Windows spoolers, print-ready PDF). Done since: embedded/72/custom DPI choices for image imports; export all images; OCR (searchable image for pages, ranges and multiple files); single-sided cut-and-stack imposition with cut marks, through Print and doc_print; architectural/ANSI/large ISO sheet presets, Match page at 100% and PDF-scale preview (#599 follow-up); Create PDF from multiple files (PDFs, images and text, edited as pages in the grid); OCR can also read pictures on pages that have text, without adding that text twice (#1028). Model staging fetches SHA-256-verified ONNX detection/recognition files after the upstream RTEN URL brownout; runtime discovery prefers complete ONNX pairs per directory, then complete legacy RTEN pairs, without mixing formats or changing directory precedence. Done since: Word invoice export uses borderless inferred tables, floating positioned text/artwork only where text overlaps an image or is rotated, and per-page sizes, covered by synthetic invoice automation regressions (#773); printing on the web through the browser's print dialog, sheets drawn by PdfCraft (gap 4). Lossless image export applies per-component Decode, including Indexed mapping (#1201 partial). Existing 16-bit precision and color-management limits remain. #3532 partial: vector printing retains existing appearances with absent Subtype through a print-owned Form copy; source artwork stays unchanged. #3120: Office export reads form XObjects 50 levels deep, as the renderer does, and up to 50 000 a page; pages past that are listed in `truncated_pages`. Word table cells use the grid columns they span, including cells after a merged cell. Done since: text in a table slot covered by another cell's span remains as paragraph text in Word, HTML, RTF and PowerPoint. Web OCR downloads its models on first use and reads in Web Workers with SIMD (`ocr.ocr-web`, shipped). Missing: OCR languages beyond Latin, web OCR near native speed, editable-text OCR output, full Office layout fidelity/import. Done since: dotted-leader contents entries stay in separate complete paragraphs (#1757) #2156 candidate: last selected print paper persists across sessions; other print preferences unchanged. Image export applies soft-mask Decode opacity intervals before resizing, including indirect entries and inverted ranges. Vector printing gives annotation appearances unoccupied XObject names so existing page artwork survives. Done since: Enhance scanned file cleans scanned pages in place (background removal, edge shadow removal, despeckle; the OCR text layer and comments stay; #4119 partial). |
| M11 | Optimize, preflight, PDF/A/X/UA, print production | 200–350 | 18% | 80–140 | Done: new `optimize` crate: Reduce File Size and the PDF Optimizer (images measured where drawn, bicubic downsampling, JPEG/ZIP recompression only when smaller, discard objects and user data, Flate clean-up, resource merging, object streams). Target-version compatibility is partial: newer content is not detected or converted. Content stream boundaries preserve comments, split operands and graphics state when image fragments merge. Image downsampling includes page-local `/UserUnit` scaling when measuring physical resolution. Done since: reject invalid image and soft-mask dimensions with checked sizing (#2178); black-and-white images stored losslessly as CCITT Group 4 when smaller, averaged down to 300 ppi above 450 (halftones aside), Group 3 stored again as Group 4, and black-and-white RGB and indexed images that use only palette entries 0 and 1 packed to one bit. Missing: fonts and transparency panels, space audit, preflight, PDF/A/X/UA |
| M12 | Accessibility, compare, measure, search, XFA | 200–380 | 30% | 90–160 | Done: new `a11y` crate with the Accessibility Checker (all 32 rules, report, Fix/Skip/Explain, options dialog and results panel, agent tools). Locatable figure, annotation and form findings highlight their page bounds. Character encoding accepts Identity-H/V with Adobe CJK collections and predefined CJK CMaps independently (#3673); per-glyph validation and embedded-font extraction remain separate. Done since: 2D distance, perimeter and area measurements with persistent viewport calibration, snapping, live information and CSV export; a bounded, text-only auto-tag proposal tool for one page. Marking a figure decorative rewrites only that stream (#1324). An XFA radio item whose value contains a space is written back unchanged (#1319). Done since: #2569: Growable multiline XFA text reflows after edits, with undo/redo, save/reopen and print coverage; oversized fields still become read-only page text. Structured-data synchronization warnings retain accepted whitespace without relayout from stale data. Done since: #2572: Every repeated page-master button resolves its own field to the shared XFA click script, including print buttons. Done since: #2570: Dynamic XFA rich-text fields carry exData/maxLength into AcroForm MaxLen for reported and enforced Unicode character limits, retained after save/reopen. Done since: #2589: Active XFA skips PDF-container fallback scripts while retaining requested messages and saved scripts; ordinary/static/unlaid-out documents and explicit console/field calls keep their existing behavior. Missing: writing proposed tags and parent tree, field autotag, visual Tags/Order/Content panels, Reading Order tool, compare, geospatial/3D measurement, search index, XFA Reading colours: pending page backgrounds follow the configured colour (#2059). |
| M13 | Automation (MCP, Action Wizard, CLI) + AI providers | 60–120 | 45% | 25–45 | Done: MCP resources (document info, text, page images); headless tool table (123 tools incl. signing, optimizing, initial view, links, stamps, data exchange, comment review, forms authoring and scripts, redaction, sanitize, print, add content), opt-in MCP server over stdio, CLI `run`/`tools` (closed stdout pipes exit cleanly), UI control channel with drag. Missing: Action Wizard, AI providers Done since: CLI run and MCP reject missing, empty, repeated and option-valued --root arguments before any tool/script execution or MCP initialization. A single-hyphen directory name remains valid; synthetic CLI regressions preserve a would-be overwritten file. `text_find` also caps the per-page match ranges it materializes at the remaining result limit plus one continuation match. CLI robustness scans visit each directory once through overlapping roots and symlink aliases. |
@@ -296,6 +300,8 @@ M2 (renderer), M7 (content editing), M10 (OCR and Office), M11 (Preflight and st
## Revision history
+**2026-10-31 · minor:** M3/M4 #5330: direct quick-toolbar Crop pages action reuses command permissions and the existing crop tool. Estimates unchanged.
+
**2026-10-26 · patch:** M2/PR #4172: reconcile current main and preserve upstream Japanese serif/weight selection alongside the installed CJK viewer and preview fallback. Estimates unchanged.
**2026-10-25 · minor:** M14 localization current state: Arabic catalogs stay logical, Arabic/Kurdish labels take an explicit RTL direction, and stock chrome mirrors; native/browser RTL input, IME and complex workflows remain unqualified. Native Simplified Chinese uses LXGW WenKai Lite; the web build has no Hans face. Estimates unchanged.
@@ -312,10 +318,14 @@ Estimates unchanged.
| Date | Change | Summary |
|---|---|---|
+| 2026-11-07 | patch | M10 `ocr.ocr-web` ported onto #977's engines and preprocessing: the page prepares each page, a Web Worker runs ocrs, the downloaded models join the engine cache. Estimates unchanged. |
+| 2026-11-05 | patch | M7 #2964 / #3185: grouped text and Thai source-font preservation; limitations and estimates unchanged. |
| 2026-11-03 | minor | M11: Optimize's JBIG2 images share a symbol dictionary (`/JBIG2Globals`), up to 16 at a time and when smaller (`pdfcraft_filters::encode_jbig2_shared`): 41–46% smaller on rendered text in proportional fonts, 10% in Courier |
| 2026-11-03 | patch | M5 #5850 review: indirect typewriter intent and composer edits preserve outer whitespace; movement regression commits by outside click; estimates unchanged. |
| 2026-11-03 | patch | M5 #5850: Enter adds Fill & Sign line breaks; outside clicks commit, Escape cancels, and saved multiline appearances retain their text and height; estimates unchanged. |
| 2026-11-02 | patch | M10 #5743: macOS print jobs carry the job name and owner some vendors' filters need; not yet checked on a physical printer |
+| 2026-11-02 | patch | M3 #5708: pages shorter than the window sit in its middle, on a whole physical pixel |
+| 2026-11-02 | patch | M3 #5716: a snapshot keeps its resolution when zoomed out; a choice of resolution remains |
| 2026-11-02 | patch | M14 #5737, #5460: Preferences turns off the update check at start, on by default |
| 2026-11-01 | patch | M7 #5657: header/footer, watermark and background operations commit all selected pages together; later-page errors preserve marks, content, shared/inherited resources and pending edits; estimates unchanged. |
| 2026-10-31 | patch | #1577: reconcile optional page shadows with current viewer/organizer and settings modules; CI validation pending. |
@@ -333,6 +343,7 @@ Estimates unchanged.
| 2026-10-29 | minor | M7 #2517: widening a paragraph rejoins a wrap with the spaces that wrap consumed, including a typed run and none for a Chinese or Japanese word split, after an incremental save and a full rewrite. Estimates unchanged. |
| 2026-10-29 | minor | M2: non-interpolated images drawn below their resolution are area-averaged to whole device pixels instead of nearest-neighbour (scanned text kept one sample in N per axis); page-scan-size images are smoothed when enlarged. Estimates unchanged. |
| 2026-10-27 | minor | M10: OCR stages SHA-256-verified ONNX models after the upstream RTEN URL brownout; discovery prefers a complete ONNX pair per directory, falls back to a complete RTEN pair, and never mixes formats or directories; language/web limits and estimates unchanged. |
+| 2026-10-20 | minor | M9 #79 review, M2, M8: /ActualText that marks no glyph extracts where it paints, as far as it is visible; redaction strips /ActualText around paint it clips; named-layer recognition needs the layer form to draw n1 and n3. Estimates unchanged. |
| 2026-10-24 | minor | M3, #3970 follow-up: the button release given back after a window move or resize goes before the pointer leaving, so hover doesn't stick. Estimates unchanged. |
| 2026-10-23 | minor | M8, #3205 follow-up: phone-pattern redaction includes the +39 country code on labelled Italian geographic numbers with a slash; dates, protocol identifiers and whole-run guards remain. Estimates unchanged. |
| 2026-10-23 | minor | M10: Word table cells use the grid columns they span, including cells after a merged cell; synthetic export regression and CLI reproduction. Estimates unchanged. |
@@ -364,6 +375,8 @@ Estimates unchanged.
| 2026-10-18 | minor | M1, #1143: a live reference may match the xref generation or a same-number header at its indexed offset; neither-match and free slots remain null. Bounded repair diagnostics and synthetic cache, free-slot, edit and classic/packed save regressions; estimates unchanged. |
| 2026-10-18 | minor | M5, PR #1971: nested source `/Page` and `/Pages` dictionaries export as null without traversing page content or the page tree. Synthetic saved/reopened three-page regression retains unrelated metadata and aliases. FDF import semantics, copied-graph limits and estimates unchanged. |
| 2026-10-15 | minor | M5: budget retained FDF entries before cloning; discovery keeps lazy array owners and annotation positions, with alias/cache-eviction stress fixtures. Limits cover the copied graph; source parsing/page discovery retain existing COS/parser limits, with no total source-memory bound. FDF import semantics and estimates unchanged. |
+| 2026-10-16 | minor | M9 #79: named-layer signature appearances show the signature's real state in the display copy, exports and both print modes, never in saves; captions follow the interface language. Estimates unchanged. |
+| 2026-10-16 | minor | M9: the page validation overlay moves to the widget's bottom-right corner as it lies on the page and stops growing past 48 screen points, so it annotates the signer's artwork from a corner instead of covering the middle of it; a field under 32 screen points keeps its outline. Estimates unchanged. |
| 2026-10-15 | minor | M7: Edit text caret height follows its row, with a kittest regression; estimates unchanged |
| 2026-10-19 | minor | M3 #3360: retain each document’s scroll position when switching Read and the docking workspace at fixed zoom. Estimates unchanged. |
| 2026-10-18 | minor | M4, PR #1919 review: repeated page indices apply each rotation to the latest page-local value, preserving indirect/inherited angles. Synthetic adjacent/interleaved duplicates retain siblings and page contents through incremental and full saves. Estimates unchanged. |
@@ -379,6 +392,8 @@ Estimates unchanged.
| 2026-10-15 | minor | M6: CSV export and spreadsheet merging quote tabs, and import distinguishes quoted tabs from TSV delimiters without changing field identities. Estimates unchanged. |
| 2026-10-13 | minor | M4: rotation queries and edits resolve indirect page-tree values; inherited, negative and large rotations verified through both saves. Estimates unchanged. |
| 2026-10-14 | minor | M12: pending page backgrounds respect reading colours (#2059); estimates unchanged. |
+| 2026-10-12 | minor | M10 `ocr.ocr-web` shipped: Web Worker OCR checked by hand in a browser. Estimates unchanged. |
+| 2026-10-12 | minor | M10 `ocr.ocr-web` (partial): the web build downloads the OCR models on first use (the web zip ships them) and reads pages in Web Workers built with SIMD. Estimates unchanged. |
| 2026-10-12 | minor | M6: valid AcroForm XML element names with original PDF field names preserved; saved-PDF collision and Unicode regressions. Estimates unchanged. |
| 2026-10-12 | minor | M6: preserve carriage returns in exported CSV field names and values; saved-PDF round-trip coverage. Estimates unchanged. |
| 2026-10-12 | minor | M7 local candidate: text drafts grow and save their width; single visual rows grow across style boundaries; both text tools retype added items and Add Text edits source text. Added-item textless previews are read-only and covered by UI/tool regressions. Estimates unchanged. |
diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md
index 44364aee66..2ed8365a73 100644
--- a/docs/target-app-parity.md
+++ b/docs/target-app-parity.md
@@ -191,7 +191,7 @@ features total and are shown for orientation; the others add to it.
| Localization | ≈ 68% over the 12 key languages | 5% | 35–60 | additional | 22 catalogs + English (23 interface languages); native craft-fonts builds embed a Simplified Chinese face (LXGW WenKai Lite) but the web build has none; Arabic labels stay logical with explicit RTL direction and mirrored stock chrome, while native/browser/IME workflows are unqualified; no Hindi, Indonesian, Korean | [localization-parity.md](localization-parity.md) |
| Performance | ≈ 40% | 6% | 25–45 | additional | 500-page smooth scrolling and large-file memory work (#307) done; no performance budgets (`misc.performance-budgets`), no lazy loading of GB files; blurry text at 1080p/1440p (#730) | [gaps.md](gaps.md) |
| Stability | ≈ 50% | 8% | 45–80 | additional | Never-crash rules and nightly fuzzing; 245 open issues on 2026-10-10, many of them `fix(...)` reports of wrong results in shipped features (the #799–#821 batch is fixed) | [gaps.md](gaps.md) |
-| Platforms | ≈ 70% | 5% | 15–30 | additional | macOS (signed, notarized), Windows x64/x86/ARM64 (signed), Linux (AppImage, deb, rpm, Flatpak), FreeBSD, web (WASM). Acrobat has no Linux, FreeBSD or full web editor; we lack web OCR and web recovery | [hardware-parity.md](hardware-parity.md) |
+| Platforms | ≈ 70% | 5% | 15–30 | additional | macOS (signed, notarized), Windows x64/x86/ARM64 (signed), Linux (AppImage, deb, rpm, Flatpak), FreeBSD, web (WASM). Acrobat has no Linux, FreeBSD or full web editor; web OCR reads in Web Workers but is far slower than native, and we lack web recovery | [hardware-parity.md](hardware-parity.md) |
| Ecosystem and plug-ins | ≈ 30% | 1% | 10–20 | within features | No plug-in SDK or folder-level JavaScript; Action Wizard partial. Agent automation (CLI, MCP, UI control channel) has no Acrobat equivalent | [gaps.md](gaps.md) |
| AI features | ≈ 0% (in scope) | 1% | 20–40 | within features | Acrobat's AI Assistant is cloud-only (out of scope). Local, opt-in provider interface (`misc.ai-provider`) not started | [gaps.md](gaps.md) |
| **Total (weighted sum)** | **≈ 50%** | 100% | **≈ 780–1,400** | | | |
@@ -303,6 +303,8 @@ licensed OCR or AI model.
| 2026-10-26 | minor | `optimize.mono-compression` became partial (CCITT Group 4), counted on the table's own measurement: K Optimize and standards 15 shipped and 11 partial of 58 (35.3%), no longer listing CCITT as missing; breadth 57.0% unweighted (423 + 75 of 808), mainstream 63.3% (292 + 45 of 497). Estimates unchanged. |
| 2026-10-25 | minor | Localization current state: Arabic catalogs stay logical, Arabic/Kurdish labels take an explicit RTL direction, and stock chrome mirrors; native/browser RTL input, IME and complex workflows remain unqualified. Native Simplified Chinese uses LXGW WenKai Lite; the web build has no Hans face. Scores and estimates unchanged. |
| 2026-10-20 | minor | M12 #3673: the Character encoding rule accepts Identity-H/V fonts with Adobe CJK collections, or a predefined non-Identity CMap, while rejecting unknown names and foreign registries. Synthetic checker and read-only automation regressions passed after failing before the fix; per-glyph mapping validation and embedded-font extraction remain separate. Breadth, readiness and hours unchanged. |
+| 2026-10-12 | minor | Web OCR (`ocr.ocr-web`) shipped after a browser check; scores not re-judged |
+| 2026-10-12 | minor | Web OCR (`ocr.ocr-web`, partial): the web zip serves the models, Recognize Text downloads them on first use, and pages are read in Web Workers built with SIMD. Platforms text updated; scores not re-judged |
| 2026-10-12 | minor | Exclusive image crops resize with their pixels across nested states, intervening operators and content streams; shared clips remain fixed. Synthetic engine/tool regressions and private image save/reopen checks; estimates unchanged. |
| 2026-10-11 | minor | Web printing shipped (gap 4): Hardware, Platforms and L Print text updated. Text only: scores, readiness and hours not re-judged |
| 2026-10-11 | minor | Contributor fork: document-font selection and subset completion, CFF, style ranges, contextual/bidi save/reopen and all-page Chinese keyboard acceptance; curve/hole hit testing (shared clips stay fixed, as on main). Scope remains bounded; percentages unchanged |
diff --git a/docs/windows-printing.md b/docs/windows-printing.md
new file mode 100644
index 0000000000..e96566fc3d
--- /dev/null
+++ b/docs/windows-printing.md
@@ -0,0 +1,25 @@
+# Windows print jobs rejected before submission
+
+A report on PdfCraft 0.19.0 described the preview closing without output while Edge printed the same PDF. On the investigated Windows machine, the HUAWEI CV81Z driver accepted the PrintTicket (paper, grayscale, duplex and collation), and its capabilities XML parsed successfully.
+
+The native submission test failed before queueing: `StorageFile::GetFileFromPathAsync` returned `0x80070005` for the temporary PDF. Ordinary desktop file access could read it. This isolates one reproducible failure; it does not establish the cause of every report of an empty print queue.
+
+The winprint loader uses `CreateRandomAccessStreamOnFile` with read-only access, then calls `PdfDocument::LoadFromStreamAsync`. The stream is backed by the job file and reads on demand. There is no whole-job `InMemoryRandomAccessStream` copy, `DataWriter`, transfer loop or per-chunk `StoreAsync().join()`. The path is made absolute and embedded NUL characters are rejected before calling the native API. The temporary file remains alive throughout rendering and submission through craft-print's existing lifetime management. PDF decoding and rendering can still allocate memory; the change removes the loader's full-file copy, not all printing memory use.
+
+Upstream loader: https://github.com/storytold/winprint.rs/pull/15 (`51934db3`). Dependency follow-up: https://github.com/storytold/craft-libs/pull/636 (`7ee35a9f`, includes merged #605). PdfCraft updates only its normal `craft-print` dependency. There is no global patch or personal-fork source. The loader revision descends from `64e7afd4`, preserving the multi-threaded Direct2D factory fix for #5006. Upstream reviews are still required before release.
+
+The public `craft_print::rgb` GDI transport remains pinned to main's `64e7afd4` revision. It is independent of the internal PDF-loader pin `51934db3`: retaining the public source identity avoids incompatible Rust types when a downstream application also uses that GDI revision directly. PdfCraft resolves one GDI package at that stable revision.
+
+## Evidence
+
+- Original Windows loader: synthetic A4 submission failed at PDF loading with `0x80070005`. The earlier memory-stream prototype submitted the same HUAWEI job; physical output was not independently confirmed.
+- Final file-backed loader: five focused tests pass, covering a hidden PDF, read-only stream behavior, reading the final byte of a 256 MiB file, a missing file, and a path containing NUL.
+- The hidden-file test was observed failing with the original StorageFile loader. The read-only test was observed failing with the earlier in-memory implementation and passing with the final loader.
+- Isolated craft-print suite with the final loader and multi-threaded Direct2D source: 63 passed, 3 hardware tests ignored. These diagnostic tests are not a full build of the final dependency graph; the disabled PDFium downloader build dependencies were omitted locally.
+- The file-backed loader at `b334ebbb` was subsequently submitted natively to the HUAWEI CV81Z; the reporter confirmed physical output of the synthetic A4 page. This used an isolated diagnostic workspace and writable TEMP directory, not the packaged UI. See https://github.com/storytold/winprint.rs/pull/15#issuecomment-6704470691.
+- The current loader pin `51934db3` also includes the review repairs: standard-library NUL validation, GetPage(0) before document/file cleanup, RAII temporary-file cleanup, and the explicit WinRT feature. In a complete Windows checkout with normal build dependencies, five loader tests and 14 Print Schema tests passed; injected failures left no temporary files behind.
+- Full final-graph build/quality gates must be rerun for the updated pins. Packaged-UI and wider printer/duplex qualification remain unverified; single-page output does not establish those.
+
+When reporting a different failure, include the PdfCraft version, printer/driver name, displayed error and whether a job appears in the Windows queue. Saving the print-ready PDF and printing it in another viewer remains a workaround until the fix ships.
+
+The loader pin also includes a bounded 30-second wait in the large-file native stream regression test. Production `PdfDocument::LoadFromStreamAsync` still has no dedicated timeout; the terminal print-completion timeout does not cover document loading. Current dependency-graph CI must pass before merging; earlier-head results do not qualify this update.
diff --git a/docs/word-count.md b/docs/word-count.md
index 4b3d02cba4..a211236075 100644
--- a/docs/word-count.md
+++ b/docs/word-count.md
@@ -25,8 +25,9 @@ Explicit Table/Code/Figure marked content still works there. Cyclic and oversize
graphs are bounded and reported as incomplete.
PDF `/ActualText` replacements are respected. If one replacement spans both included and
-excluded glyphs, there is no reliable mapping of its words to the selected content: counting
-fails with an explanation instead of silently returning the wrong total. Disable exclusions to
+excluded glyphs (or, with no glyphs, included and excluded outlines or pictures), there is no
+reliable mapping of its words to the selected content: counting fails with an explanation
+instead of silently returning the wrong total. Disable exclusions to
count that page. Unreadable pages likewise fail the operation, without a misleading partial total.
Images alone contain no extractable words. Run Scan & OCR first when counting scanned pages.
diff --git a/licenses/ICU4X-LICENSE.txt b/licenses/ICU4X-LICENSE.txt
new file mode 100644
index 0000000000..c9be6012c5
--- /dev/null
+++ b/licenses/ICU4X-LICENSE.txt
@@ -0,0 +1,46 @@
+UNICODE LICENSE V3
+
+COPYRIGHT AND PERMISSION NOTICE
+
+Copyright © 2020-2024 Unicode, Inc.
+
+NOTICE TO USER: Carefully read the following legal agreement. BY
+DOWNLOADING, INSTALLING, COPYING OR OTHERWISE USING DATA FILES, AND/OR
+SOFTWARE, YOU UNEQUIVOCALLY ACCEPT, AND AGREE TO BE BOUND BY, ALL OF THE
+TERMS AND CONDITIONS OF THIS AGREEMENT. IF YOU DO NOT AGREE, DO NOT
+DOWNLOAD, INSTALL, COPY, DISTRIBUTE OR USE THE DATA FILES OR SOFTWARE.
+
+Permission is hereby granted, free of charge, to any person obtaining a
+copy of data files and any associated documentation (the "Data Files") or
+software and any associated documentation (the "Software") to deal in the
+Data Files or Software without restriction, including without limitation
+the rights to use, copy, modify, merge, publish, distribute, and/or sell
+copies of the Data Files or Software, and to permit persons to whom the
+Data Files or Software are furnished to do so, provided that either (a)
+this copyright and permission notice appear with all copies of the Data
+Files or Software, or (b) this copyright and permission notice appear in
+associated Documentation.
+
+THE DATA FILES AND SOFTWARE ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
+KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF
+THIRD PARTY RIGHTS.
+
+IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS NOTICE
+BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES,
+OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
+WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
+ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THE DATA
+FILES OR SOFTWARE.
+
+Except as contained in this notice, the name of a copyright holder shall
+not be used in advertising or otherwise to promote the sale, use or other
+dealings in these Data Files or Software without prior written
+authorization of the copyright holder.
+
+SPDX-License-Identifier: Unicode-3.0
+
+—
+
+Portions of ICU4X may have been adapted from ICU4C and/or ICU4J.
+ICU 1.8.1 to ICU 57.1 © 1995-2016 International Business Machines Corporation and others.
diff --git a/packaging/macos/Info.plist.in b/packaging/macos/Info.plist.in
index cfc7d2d08e..f38f186c82 100644
--- a/packaging/macos/Info.plist.in
+++ b/packaging/macos/Info.plist.in
@@ -6,6 +6,46 @@
CFBundleDevelopmentRegion
en
+
+ CFBundleLocalizations
+
+ en
+ ja
+ zh-Hans
+ zh-Hant
+ cs
+ pt-BR
+ de
+ es
+ fr
+ ru
+ kk
+ bg
+ te
+ hu
+ uk
+ it
+ ar
+ ckb
+ fa
+ pl
+ sl
+ el
+ tr
+ lt
+ id
+ vi
+ fi
+ sq
+ th
+ ca
+ ro
+ lo
+ hi
+ ko
+ nb
+
CFBundleDisplayName
PdfCraft
CFBundleName
diff --git a/packaging/web/README.md b/packaging/web/README.md
index 3149dc75d5..f5a51b4259 100644
--- a/packaging/web/README.md
+++ b/packaging/web/README.md
@@ -8,7 +8,9 @@ static site in `pdfcraft-web-/`:
| `index.html` | The page. It loads everything through relative URLs. |
| `pdfcraft-web-.js` | wasm-bindgen glue (generated, ES module) |
| `pdfcraft-web-_bg.wasm` | The app, about 13 MB, or 5 MB with compression |
+| `pdfcraft-ocr-worker-.js`, `_bg.wasm`, `_loader.js` | The text recognition worker (about 3 MB), started only when OCR runs |
| `_headers`, `.htaccess` | Sample header rules for Netlify/Cloudflare Pages and Apache |
+| `models/` | The text recognition (OCR) models, about 12 MB, with their licences (CC-BY-SA-4.0) |
There is no server-side code. Upload the folder's contents anywhere that serves static files.
@@ -55,6 +57,26 @@ location /pdfcraft/ {
Local test: `python3 -m http.server 8765` inside the folder, then open http://localhost:8765/.
+## Text recognition (OCR)
+
+Scan & OCR ▸ Recognize Text downloads `models/text-detection.onnx` and
+`models/text-recognition.onnx`, relative to the page, the first time it is opened in a visit.
+Keep `models/` beside `index.html`. The app loads only the files whose SHA-256 matches
+`ATTRIBUTION.toml`, so a wrong file fails like a missing one. Their file names carry no content
+hash, so the app asks the server before using a cached copy (`no-cache`): the server must answer
+that check correctly (an ETag, or a `Last-Modified` that changes whenever the file does). Without
+the models, everything else works and the Recognize Text dialog says the download failed.
+
+Pages are read in Web Workers (`pdfcraft-ocr-worker-_loader.js`, a module worker), so the
+app keeps responding, and two pages are read at once on a machine with three or more cores. Each
+worker needs about 600 MB while it reads; idle workers close after a minute. The workers need no
+special headers, but a `Content-Security-Policy` must allow them (`worker-src 'self'`, or
+`script-src 'self'`). Where they can't start, the app reads the pages itself, a page at a time,
+and doesn't respond while each page is read.
+
+From a source build, `trunk build --release` doesn't fetch the models. Add them with
+`cargo xtask models dist/web/models` (after the build, which replaces `dist/web`).
+
## Embedding in a page (iframe)
```html
@@ -136,6 +158,18 @@ The messages and both transports are the shared contract of [`craft-web-host`](h
- **Files from the host are untrusted input.** An opened file goes through the same reading as one picked with File ▸ Open or dropped on the window, with the same format limits; before it is copied into the app's memory, its size is checked against the host open limit (512 MiB) and a larger file is refused, and a name is cut to 255 characters.
- **The event and message names are the interface.** `pdfcraft:ready`, `pdfcraft:open`, `pdfcraft:save`, `pdfcraft:dirty` and `pdfcraft:failed`, and the fields they carry (the same as the `?host=parent` messages), stay stable; changing one is a breaking change.
+### Driving it from the page (`window.pdfcraft`)
+
+`?control` on the page's URL puts `window.pdfcraft` on the page, from [`craft-web-api`](https://github.com/storytold/craft-libs/tree/main/crates/web-api) (storytold/craft-libs#413), the same shape in every Craft app (`index.html?control`, which can be combined with other flags). It is opt-in because the control channel keeps the accessibility tree of every frame. The browser already exposes PdfCraft's canvas (`id="pdfcraft"`) as `window.pdfcraft`, so the functions are added to that element. `pdfcraft.request(method, params)` calls any method of the UI control channel the desktop app serves with `--control` (`ui.state`, `ui.inspect`, `ui.click`, `ui.key`, `ui.set`…; `ui.open` needs a file system, so on the web it answers with an error and a file is dropped on the page instead), and `execute(command, params)` (`ui.command`: a registry command id), `commands()` (`ui.commands`), `docInspect(params)` (`ui.state`), `uiInspect(params)` (`ui.inspect`) and `screenshot(params)` are shortcuts for the common ones. Each returns a Promise that resolves with the method's result and rejects with an `Error`; a call the app does not answer within 30 seconds rejects, and the app may still reach it later and run it (or reject it), as it does for a desktop client that timed out, so a timed-out call is not guaranteed to have been skipped. The API is installed after `pdfcraft:ready` is posted, and `window.pdfcraft` is the canvas element before that, so wait for a function rather than for the name: `await new Promise(r => { const t = setInterval(() => typeof pdfcraft.request === "function" && (clearInterval(t), r()), 50); })`.
+
+```js
+const state = await pdfcraft.docInspect(); // open documents, page, zoom, panels, dialog
+await pdfcraft.request("ui.set", { key: "show_page_edge_shadows", value: "false" });
+const { data } = await pdfcraft.screenshot(); // the window as PNG (base64)
+```
+
+Opening a PDF, handing a saved or exported file to the page, the file name and the unsaved flag stay with the host messages above.
+
## Renderer selection and fallback flags
PdfCraft renders with wgpu. It uses **WebGPU** when the browser has it and falls back to
@@ -150,3 +184,7 @@ PdfCraft renders with wgpu. It uses **WebGPU** when the browser has it and falls
For example: `