Skip to content

Open-source Android PDF and document toolkit with PDF tools, Office viewing, XLSX editing, scanning, and image editing. Built with Kotlin and Jetpack Compose.

chore: merge upstream PdfCraft v0.14.0 (engine 0.14.0)

Josh75565b1592f6
diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md
index cf0c69c..e7d2dd5 100644
--- a/ATTRIBUTION.md
+++ b/ATTRIBUTION.md
@@ -2,39 +2,39 @@
<!-- Generated from ATTRIBUTION.toml by `cargo xtask assets --write`. Do not edit by hand. -->
-Every asset PdfCraft includes, bundles or uses to build its published material, with its author, source and licence. The policy is in [AGENTS.md](AGENTS.md) §1. The machine-readable list, with SHA-256 hashes, is [ATTRIBUTION.toml](ATTRIBUTION.toml). Licence texts are kept beside the assets and summarised in [NOTICE](NOTICE).
+Every asset PdfCraft includes, bundles or uses to build its published material, with its author, source and licence. The policy is in [AGENTS.md](AGENTS.md) §1. The machine-readable list, with the SHA-256 of every asset but the translation catalogs, is [ATTRIBUTION.toml](ATTRIBUTION.toml). Licence texts are kept beside the assets and summarised in [NOTICE](NOTICE).
## In this repository (322)
| Asset | Title | Author | Licence | Source | Used for |
|---|---|---|---|---|---|
-| `crates/ui-egui/src/i18n/el.tsv` | Greek interface translation catalog | Camthalion77 and contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft English UI labels; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed | Greek UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
-| `crates/ui-egui/src/i18n/zh-hans.tsv` | Simplified Chinese interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed | Simplified Chinese UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
-| `crates/ui-egui/src/i18n/zh-hant.tsv` | Traditional Chinese (Taiwan) interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed | Traditional Chinese UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
-| `crates/ui-egui/src/i18n/cs.tsv` | Czech interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 signature-check and standard-identification wordings are contributor-original AI-assisted translations from English, not separately native-reviewed | Czech UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
-| `crates/ui-egui/src/i18n/pt-br.tsv` | Brazilian Portuguese interface translation catalog | André Cardoso (andrecards), PdfCraft contributors | MIT OR Apache-2.0 | Clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources: the ~1,826-entry gist posted in issue #288 (https://gist.github.com/andrecards/ac388c25fba17312ce83207f8b7b467e), completed and reviewed by PdfCraft contributors; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 text-field-table limit messages are contributor-original AI-assisted translations from English, not separately native-reviewed | Brazilian Portuguese UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
-| `crates/ui-egui/src/i18n/es.tsv` | Spanish interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; the 2026-10-20 coverage additions are AI-assisted and not separately native-reviewed; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 signature-check wordings are contributor-original AI-assisted translations from English, not separately native-reviewed | Spanish UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
-| `crates/ui-egui/src/i18n/fr.tsv` | French interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed | French UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
-| `crates/ui-egui/src/i18n/de.tsv` | German interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed | German UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
-| `crates/ui-egui/src/i18n/lo.tsv` | Lao interface translation catalog | @bounkirdni-2025 | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft English UI labels, no proprietary localisation resources; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed | Lao UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
-| `crates/ui-egui/src/i18n/te.tsv` | Telugu interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed | Telugu UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
-| `crates/ui-egui/src/i18n/it.tsv` | Italian interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed | Italian UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
-| `crates/ui-egui/src/i18n/pl.tsv` | Polish interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 signature-check wordings are contributor-original AI-assisted translations from English, not separately native-reviewed | Polish UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
-| `crates/ui-egui/src/i18n/ru.tsv` | Russian interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed | Russian UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
-| `crates/ui-egui/src/i18n/hu.tsv` | Hungarian interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed | Hungarian UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
-| `crates/ui-egui/src/i18n/bg.tsv` | Bulgarian interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed | Bulgarian UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
-| `crates/ui-egui/src/i18n/kk.tsv` | Kazakh interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of the English UI labels into Kazakh, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed | Kazakh UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
-| `crates/ui-egui/src/i18n/ja.tsv` | Japanese interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed | Japanese UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
-| `crates/ui-egui/src/i18n/uk.tsv` | Ukrainian interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed | Ukrainian UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
-| `crates/ui-egui/src/i18n/ar.tsv` | Arabic interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed | Arabic UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
-| `crates/ui-egui/src/i18n/ckb.tsv` | Central Kurdish (Sorani) interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed | Central Kurdish UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
-| `crates/ui-egui/src/i18n/tr.tsv` | Turkish interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed | Turkish UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
-| `crates/ui-egui/src/i18n/lt.tsv` | Lithuanian interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels and user-facing messages; original catalog reviewed by a native Lithuanian-speaking contributor; 2026-10-15 coverage additions are AI-assisted and not separately native-reviewed; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed | Lithuanian UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
-| `crates/ui-egui/src/i18n/hi.tsv` | Hindi interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 text-field-table labels are contributor-original AI-assisted translations from English, not separately native-reviewed | Hindi UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
-| `crates/ui-egui/src/i18n/id.tsv` | Indonesian interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 text-field-table labels are contributor-original AI-assisted translations from English, not separately native-reviewed | Indonesian UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
-| `crates/ui-egui/src/i18n/ko.tsv` | Korean interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 text-field-table labels are contributor-original AI-assisted translations from English, not separately native-reviewed | Korean UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
-| `crates/ui-egui/src/i18n/ro.tsv` | Romanian interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels and user-facing messages; AI-assisted and not yet reviewed line by line by a native Romanian speaker; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 text-field-table labels are contributor-original AI-assisted translations from English, not separately native-reviewed | Romanian UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
-| `crates/ui-egui/src/i18n/fi.tsv` | Finnish interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: AI-assisted (Claude Code) clean-room translations of PdfCraft's English UI labels and user-facing messages; not yet proofread by a native Finnish speaker; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 text-field-table labels are contributor-original AI-assisted translations from English, not separately native-reviewed | Finnish UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
+| `crates/ui-egui/src/i18n/el.tsv` | Greek interface translation catalog | Camthalion77 and contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft English UI labels; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed | Greek UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
+| `crates/ui-egui/src/i18n/zh-hans.tsv` | Simplified Chinese interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed | Simplified Chinese UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
+| `crates/ui-egui/src/i18n/zh-hant.tsv` | Traditional Chinese (Taiwan) interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed | Traditional Chinese UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
+| `crates/ui-egui/src/i18n/cs.tsv` | Czech interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 signature-check and standard-identification wordings are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed | Czech UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
+| `crates/ui-egui/src/i18n/pt-br.tsv` | Brazilian Portuguese interface translation catalog | André Cardoso (andrecards), PdfCraft contributors | MIT OR Apache-2.0 | Clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources: the ~1,826-entry gist posted in issue #288 (https://gist.github.com/andrecards/ac388c25fba17312ce83207f8b7b467e), completed and reviewed by PdfCraft contributors; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 text-field-table limit messages are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed | Brazilian Portuguese UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
+| `crates/ui-egui/src/i18n/es.tsv` | Spanish interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; the 2026-10-20 coverage additions are AI-assisted and not separately native-reviewed; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 signature-check wordings are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed | Spanish UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
+| `crates/ui-egui/src/i18n/fr.tsv` | French interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed | French UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
+| `crates/ui-egui/src/i18n/de.tsv` | German interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed | German UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
+| `crates/ui-egui/src/i18n/lo.tsv` | Lao interface translation catalog | @bounkirdni-2025 | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft English UI labels, no proprietary localisation resources; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed | Lao UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
+| `crates/ui-egui/src/i18n/te.tsv` | Telugu interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed | Telugu UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
+| `crates/ui-egui/src/i18n/it.tsv` | Italian interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed | Italian UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
+| `crates/ui-egui/src/i18n/pl.tsv` | Polish interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 signature-check wordings are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed | Polish UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
+| `crates/ui-egui/src/i18n/ru.tsv` | Russian interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed | Russian UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
+| `crates/ui-egui/src/i18n/hu.tsv` | Hungarian interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed | Hungarian UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
+| `crates/ui-egui/src/i18n/bg.tsv` | Bulgarian interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed | Bulgarian UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
+| `crates/ui-egui/src/i18n/kk.tsv` | Kazakh interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of the English UI labels into Kazakh, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed | Kazakh UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
+| `crates/ui-egui/src/i18n/ja.tsv` | Japanese interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed | Japanese UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
+| `crates/ui-egui/src/i18n/uk.tsv` | Ukrainian interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed | Ukrainian UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
+| `crates/ui-egui/src/i18n/ar.tsv` | Arabic interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed | Arabic UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
+| `crates/ui-egui/src/i18n/ckb.tsv` | Central Kurdish (Sorani) interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed | Central Kurdish UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
+| `crates/ui-egui/src/i18n/tr.tsv` | Turkish interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed | Turkish UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
+| `crates/ui-egui/src/i18n/lt.tsv` | Lithuanian interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels and user-facing messages; original catalog reviewed by a native Lithuanian-speaking contributor; 2026-10-15 coverage additions are AI-assisted and not separately native-reviewed; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed | Lithuanian UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
+| `crates/ui-egui/src/i18n/hi.tsv` | Hindi interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 text-field-table labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed | Hindi UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
+| `crates/ui-egui/src/i18n/id.tsv` | Indonesian interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 text-field-table labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed | Indonesian UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
+| `crates/ui-egui/src/i18n/ko.tsv` | Korean interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 text-field-table labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed | Korean UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
+| `crates/ui-egui/src/i18n/ro.tsv` | Romanian interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels and user-facing messages; AI-assisted and not yet reviewed line by line by a native Romanian speaker; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 text-field-table labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed | Romanian UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
+| `crates/ui-egui/src/i18n/fi.tsv` | Finnish interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: AI-assisted (Claude Code) clean-room translations of PdfCraft's English UI labels and user-facing messages; not yet proofread by a native Finnish speaker; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 text-field-table labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 calculation-order, text-format, print, thumbnail, layer, comment-reshape and signature labels (previously English placeholders) are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed | Finnish UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
| `assets/icons/accessibility.svg` | Lucide icon "accessibility" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/accessibility.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/align-left.svg` | Lucide icon "align-left" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/align-left.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/align-center.svg` | Lucide icon "align-center" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/align-center.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
@@ -319,17 +319,17 @@ Every asset PdfCraft includes, bundles or uses to build its published material,
| `packaging/macos/dmg/background.tiff` | PdfCraft macOS DMG window background (rendered) | @XusBadia | MIT OR Apache-2.0 | Rendered from packaging/macos/dmg/background.svg by packaging/macos/dmg/generate.py | 1x + 2x HiDPI 16-colour palette TIFF copied into the macOS DMG by packaging/macos/package.sh; includes the app icon and the free LittleCMS built-in sRGB profile |
| `crates/sign/tests/data/x509-rsa-sha1.pdf` | One-page PDF with a legacy adbe.x509.rsa_sha1 signature by the RSA test key | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: hand-written PDF objects; signature made with `openssl dgst -sha1 -sign` over its byte ranges (see crates/sign/tests/data/README.md) | Signature validation tests (crates/sign/tests/it/pdf.rs): the legacy adbe.x509.rsa_sha1 format |
| `assets/icons/monitor.svg` | Lucide icon "monitor" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/monitor.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
-| `crates/ui-egui/src/i18n/vi.tsv` | Vietnamese interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels; PhotoCraft and VectorCraft Vietnamese catalogs used only as translation memory when English source and semantic context matched; original catalog reviewed by a native Vietnamese-speaking contributor; 2026-10-15 coverage additions are AI-assisted and not separately native-reviewed; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 signature-check wordings are contributor-original AI-assisted translations from English, not separately native-reviewed | Vietnamese UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
-| `crates/ui-egui/src/i18n/sl.tsv` | Slovene interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed | Slovene UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
+| `crates/ui-egui/src/i18n/vi.tsv` | Vietnamese interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels; PhotoCraft and VectorCraft Vietnamese catalogs used only as translation memory when English source and semantic context matched; original catalog reviewed by a native Vietnamese-speaking contributor; 2026-10-15 coverage additions are AI-assisted and not separately native-reviewed; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 signature-check wordings are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed | Vietnamese UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
+| `crates/ui-egui/src/i18n/sl.tsv` | Slovene interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed | Slovene UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
| `vendor/vello_common/assets/probe.png` | vello_common probe reference image (rendered from probe.rgba) | Linebender vello contributors | MIT OR Apache-2.0 | vello_common 0.0.8 (crates.io), vendored in vendor/vello_common; regenerated by its vello_sparse_tests regenerate_probe_reference binary | Reference picture of the vendored vello_common probe module, for people only; the build reads probe.rgba, not this file |
-| `crates/ui-egui/src/i18n/nb.tsv` | Norwegian Bokmål interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed | Norwegian Bokmål UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
+| `crates/ui-egui/src/i18n/nb.tsv` | Norwegian Bokmål interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed | Norwegian Bokmål UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
| `assets/icons/superscript.svg` | Lucide icon "superscript" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/superscript.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/subscript.svg` | Lucide icon "subscript" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/subscript.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/pilcrow.svg` | Lucide icon "pilcrow" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/pilcrow.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/move-horizontal.svg` | Lucide icon "move-horizontal" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | 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 |
-| `crates/ui-egui/src/i18n/sq.tsv` | Albanian interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 signature-appearance labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 text-field-table labels are contributor-original AI-assisted translations from English, not separately native-reviewed | Albanian UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
-| `crates/ui-egui/src/i18n/th.tsv` | Thai interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed | Thai UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
-| `crates/ui-egui/src/i18n/ca.tsv` | Catalan interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, written from their meaning; no proprietary localisation resources; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 text-field-table labels are contributor-original AI-assisted translations from English, not separately native-reviewed | Catalan UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
+| `crates/ui-egui/src/i18n/sq.tsv` | Albanian interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 signature-appearance labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 text-field-table labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed | Albanian UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
+| `crates/ui-egui/src/i18n/th.tsv` | Thai interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed | Thai UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
+| `crates/ui-egui/src/i18n/ca.tsv` | Catalan interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, written from their meaning; no proprietary localisation resources; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 text-field-table labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed | Catalan UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
## Compiled in through dependencies (5)
@@ -376,4 +376,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-fonts` | `CRAFT_FONTS_DIR` | Japanese fonts: BIZ UDPGothic (Regular, Bold), Shippori Mincho, BIZ UDMincho; Arabic font: Noto Sans Arabic | The BIZ UDGothic and BIZ UDMincho Project Authors (Morisawa Inc.), The Shippori Mincho Project Authors (FONTDASU), The Noto Project Authors (Noto Sans Arabic) | OFL-1.1 | https://github.com/storytold/craft-fonts (pinned by commit in .github/workflows/release.yml) | 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); Arabic interface text, file names and document titles (Noto Sans Arabic); the web build embeds only BIZ UDPGothic Regular and Noto Sans Arabic. The checkout also holds Noto Sans CJK SC, which crates/fonts/build.rs never embeds (AGENTS.md §1.1) |
+| `craft-fonts` | `CRAFT_FONTS_DIR` | Japanese fonts: BIZ UDPGothic (Regular, Bold), Shippori Mincho, BIZ UDMincho; Arabic font: Noto Sans Arabic | The BIZ UDGothic and BIZ UDMincho Project Authors (Morisawa Inc.), The Shippori Mincho Project Authors (FONTDASU), The Noto Project Authors (Noto Sans Arabic) | OFL-1.1 | https://github.com/storytold/craft-fonts (pinned by commit in .github/workflows/release.yml) | 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); Arabic interface text, file names and document titles (Noto Sans Arabic); the web build embeds only BIZ UDPGothic Regular and Noto Sans Arabic. The checkout also holds Noto Sans CJK SC, which crates/fonts/build.rs leaves out for size |
diff --git a/ATTRIBUTION.toml b/ATTRIBUTION.toml
index 4a7f41a..d9fb5e3 100644
--- a/ATTRIBUTION.toml
+++ b/ATTRIBUTION.toml
@@ -2,17 +2,18 @@
path = "crates/ui-egui/src/i18n/el.tsv"
title = "Greek interface translation catalog"
author = "Camthalion77 and contributors"
-source = "Contributor-original: clean-room translations of PdfCraft English UI labels; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed"
+source = "Contributor-original: clean-room translations of PdfCraft English UI labels; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed"
licence = "MIT OR Apache-2.0"
licence_file = "LICENSE-MIT"
kind = "translation"
usage = "Greek UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs"
-sha256 = "b3fdc3260e5c4ed0a2111e4d2f8f9cacfb7fc2b613ad6a2cbb18f7976347c461"
# ATTRIBUTION.toml: one entry per asset (AGENTS.md §1). The source of truth for provenance and licences.
# ATTRIBUTION.md is generated from this file: `cargo xtask assets --write`. Checked by `cargo xtask assets` (part of `xtask ci`).
#
# [[asset]] a file in this repository (committed or vendored); `sha256` must match the file.
+# Translation catalogs (kind = "translation", crates/ui-egui/src/i18n/*.tsv) are project files
+# under the project licence and carry no `sha256`: git history records their provenance.
# [[bundled]] a file compiled into PdfCraft by a Cargo dependency (its crate version must match Cargo.lock).
# [[fetched]] downloaded at build time by xtask (never committed), pinned by `sha256`.
# [[build_input]] an optional build input outside this repository (e.g. craft-fonts via CRAFT_FONTS_DIR);
@@ -25,286 +26,260 @@ sha256 = "b3fdc3260e5c4ed0a2111e4d2f8f9cacfb7fc2b613ad6a2cbb18f7976347c461"
path = "crates/ui-egui/src/i18n/zh-hans.tsv"
title = "Simplified Chinese interface translation catalog"
author = "PdfCraft contributors"
-source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed"
+source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed"
licence = "MIT OR Apache-2.0"
licence_file = "LICENSE-MIT"
kind = "translation"
usage = "Simplified Chinese UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs"
-sha256 = "a996f1c6845ea03e369aa1f119a42d24c20c88c3ef3fa2cf77b06cc06171c25a"
[[asset]]
path = "crates/ui-egui/src/i18n/zh-hant.tsv"
title = "Traditional Chinese (Taiwan) interface translation catalog"
author = "PdfCraft contributors"
-source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed"
+source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed"
licence = "MIT OR Apache-2.0"
licence_file = "LICENSE-MIT"
kind = "translation"
usage = "Traditional Chinese UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs"
-sha256 = "1fb5c191c82afb712c5589fad87eee87e6e07b144aded71b02c052ed5d438842"
[[asset]]
path = "crates/ui-egui/src/i18n/cs.tsv"
title = "Czech interface translation catalog"
author = "PdfCraft contributors"
-source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 signature-check and standard-identification wordings are contributor-original AI-assisted translations from English, not separately native-reviewed"
+source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 signature-check and standard-identification wordings are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed"
licence = "MIT OR Apache-2.0"
licence_file = "LICENSE-MIT"
kind = "translation"
usage = "Czech UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs"
-sha256 = "aebf9e50c9cd769ded01e0b27c9258439bef4fbc2b823cedf20255411ee12528"
[[asset]]
path = "crates/ui-egui/src/i18n/pt-br.tsv"
title = "Brazilian Portuguese interface translation catalog"
author = "André Cardoso (andrecards), PdfCraft contributors"
-source = "Clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources: the ~1,826-entry gist posted in issue #288 (https://gist.github.com/andrecards/ac388c25fba17312ce83207f8b7b467e), completed and reviewed by PdfCraft contributors; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 text-field-table limit messages are contributor-original AI-assisted translations from English, not separately native-reviewed"
+source = "Clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources: the ~1,826-entry gist posted in issue #288 (https://gist.github.com/andrecards/ac388c25fba17312ce83207f8b7b467e), completed and reviewed by PdfCraft contributors; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 text-field-table limit messages are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed"
licence = "MIT OR Apache-2.0"
licence_file = "LICENSE-MIT"
kind = "translation"
usage = "Brazilian Portuguese UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs"
-sha256 = "dd8ad09be123d6ea83b8bc1b25b95e84eef45c5f6666c688b0fa7288b5bdcb07"
[[asset]]
path = "crates/ui-egui/src/i18n/es.tsv"
title = "Spanish interface translation catalog"
author = "PdfCraft contributors"
-source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; the 2026-10-20 coverage additions are AI-assisted and not separately native-reviewed; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 signature-check wordings are contributor-original AI-assisted translations from English, not separately native-reviewed"
+source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; the 2026-10-20 coverage additions are AI-assisted and not separately native-reviewed; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 signature-check wordings are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed"
licence = "MIT OR Apache-2.0"
licence_file = "LICENSE-MIT"
kind = "translation"
usage = "Spanish UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs"
-sha256 = "38fc9e7d5c043713afb727b4abc2fd0b945e3c7f88bbc094b918f8320538d58a"
[[asset]]
path = "crates/ui-egui/src/i18n/fr.tsv"
title = "French interface translation catalog"
author = "PdfCraft contributors"
-source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed"
+source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed"
licence = "MIT OR Apache-2.0"
licence_file = "LICENSE-MIT"
kind = "translation"
usage = "French UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs"
-sha256 = "074685e399c51ffae685c33c1be4280268e292b03ef7a301f495cf6a82cd3fd4"
[[asset]]
path = "crates/ui-egui/src/i18n/de.tsv"
title = "German interface translation catalog"
author = "PdfCraft contributors"
-source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed"
+source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed"
licence = "MIT OR Apache-2.0"
licence_file = "LICENSE-MIT"
kind = "translation"
usage = "German UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs"
-sha256 = "accf6b414da37f76520f17932c7d6de335f321cf731db9eea1e80e6de9865f6b"
[[asset]]
path = "crates/ui-egui/src/i18n/lo.tsv"
title = "Lao interface translation catalog"
author = "@bounkirdni-2025"
-source = "Contributor-original: clean-room translations of PdfCraft English UI labels, no proprietary localisation resources; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed"
+source = "Contributor-original: clean-room translations of PdfCraft English UI labels, no proprietary localisation resources; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed"
licence = "MIT OR Apache-2.0"
licence_file = "LICENSE-MIT"
kind = "translation"
usage = "Lao UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs"
-sha256 = "f4046e28a8f506f258610449fe99dadfe57ffc496b6602da1fd160756acd00fc"
[[asset]]
path = "crates/ui-egui/src/i18n/te.tsv"
title = "Telugu interface translation catalog"
author = "PdfCraft contributors"
-source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed"
+source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed"
licence = "MIT OR Apache-2.0"
licence_file = "LICENSE-MIT"
kind = "translation"
usage = "Telugu UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs"
-sha256 = "830a9420e5813ec859d5b29e6a555e410d36047281b510919a8576b33f71aadf"
[[asset]]
path = "crates/ui-egui/src/i18n/it.tsv"
title = "Italian interface translation catalog"
author = "PdfCraft contributors"
-source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed"
+source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed"
licence = "MIT OR Apache-2.0"
licence_file = "LICENSE-MIT"
kind = "translation"
usage = "Italian UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs"
-sha256 = "303833b5f9a14c4b3b9f54df372ffc34fe29f8edd7ee18249790cd1b012001b0"
[[asset]]
path = "crates/ui-egui/src/i18n/pl.tsv"
title = "Polish interface translation catalog"
author = "PdfCraft contributors"
-source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 signature-check wordings are contributor-original AI-assisted translations from English, not separately native-reviewed"
+source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 signature-check wordings are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed"
licence = "MIT OR Apache-2.0"
licence_file = "LICENSE-MIT"
kind = "translation"
usage = "Polish UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs"
-sha256 = "529766aa99c74ce92d0535718f5348405a6ef7d18bd150485d0589baa27f77ea"
[[asset]]
path = "crates/ui-egui/src/i18n/ru.tsv"
title = "Russian interface translation catalog"
author = "PdfCraft contributors"
-source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed"
+source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed"
licence = "MIT OR Apache-2.0"
licence_file = "LICENSE-MIT"
kind = "translation"
usage = "Russian UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs"
-sha256 = "a3a55c0dc4da9320635ffe868d12d3d76656543cc64b6be87871d64a99fe3f30"
[[asset]]
path = "crates/ui-egui/src/i18n/hu.tsv"
title = "Hungarian interface translation catalog"
author = "PdfCraft contributors"
-source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed"
+source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed"
licence = "MIT OR Apache-2.0"
licence_file = "LICENSE-MIT"
kind = "translation"
usage = "Hungarian UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs"
-sha256 = "50e2421bae024beed216b5457e008f63eb0cae23e4b55fe8d1e807501cbc131c"
[[asset]]
path = "crates/ui-egui/src/i18n/bg.tsv"
title = "Bulgarian interface translation catalog"
author = "PdfCraft contributors"
-source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed"
+source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed"
licence = "MIT OR Apache-2.0"
licence_file = "LICENSE-MIT"
kind = "translation"
usage = "Bulgarian UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs"
-sha256 = "6681f3fe153a38f50aaf3de96109a812a1077fa17e11c558d580202a58f22943"
[[asset]]
path = "crates/ui-egui/src/i18n/kk.tsv"
title = "Kazakh interface translation catalog"
author = "PdfCraft contributors"
-source = "Contributor-original: clean-room translations of the English UI labels into Kazakh, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed"
+source = "Contributor-original: clean-room translations of the English UI labels into Kazakh, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed"
licence = "MIT OR Apache-2.0"
licence_file = "LICENSE-MIT"
kind = "translation"
usage = "Kazakh UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs"
-sha256 = "4e5e84b8164585bb1ea39cee79f34cee1c79798d2b917ae7304466c10a304adb"
[[asset]]
path = "crates/ui-egui/src/i18n/ja.tsv"
title = "Japanese interface translation catalog"
author = "PdfCraft contributors"
-source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed"
+source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed"
licence = "MIT OR Apache-2.0"
licence_file = "LICENSE-MIT"
kind = "translation"
usage = "Japanese UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs"
-sha256 = "7f967829b937ebb66aa9f042045afffe16c4639c2b9141b5c5d0a96dabbb9653"
[[asset]]
path = "crates/ui-egui/src/i18n/uk.tsv"
title = "Ukrainian interface translation catalog"
author = "PdfCraft contributors"
-source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed"
+source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed"
licence = "MIT OR Apache-2.0"
licence_file = "LICENSE-MIT"
kind = "translation"
usage = "Ukrainian UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs"
-sha256 = "bb2bb7a0d9b0776a71af78489d62b948705610bf7b5b3a34f876e80c69e3e8ea"
[[asset]]
path = "crates/ui-egui/src/i18n/ar.tsv"
title = "Arabic interface translation catalog"
author = "PdfCraft contributors"
-source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed"
+source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed"
licence = "MIT OR Apache-2.0"
licence_file = "LICENSE-MIT"
kind = "translation"
usage = "Arabic UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs"
-sha256 = "122b104f3d5b26d470fc52845d1266eb45b5cd5ef24747b341fdad39c120be72"
[[asset]]
path = "crates/ui-egui/src/i18n/ckb.tsv"
title = "Central Kurdish (Sorani) interface translation catalog"
author = "PdfCraft contributors"
-source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed"
+source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed"
licence = "MIT OR Apache-2.0"
licence_file = "LICENSE-MIT"
kind = "translation"
usage = "Central Kurdish UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs"
-sha256 = "e491d5f67adb9f70ea4e23e4a2e1b063ebaaf54548325e3e16c514d0e0b71d81"
[[asset]]
path = "crates/ui-egui/src/i18n/tr.tsv"
title = "Turkish interface translation catalog"
author = "PdfCraft contributors"
-source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed"
+source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed"
licence = "MIT OR Apache-2.0"
licence_file = "LICENSE-MIT"
kind = "translation"
usage = "Turkish UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs"
-sha256 = "8c02888bc94d2844ec0d4ca4aa69c776ecaa52fa3a8f2a3d0c7be9636b0aafef"
[[asset]]
path = "crates/ui-egui/src/i18n/lt.tsv"
title = "Lithuanian interface translation catalog"
author = "PdfCraft contributors"
-source = "Contributor-original: clean-room translations of PdfCraft's English UI labels and user-facing messages; original catalog reviewed by a native Lithuanian-speaking contributor; 2026-10-15 coverage additions are AI-assisted and not separately native-reviewed; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed"
+source = "Contributor-original: clean-room translations of PdfCraft's English UI labels and user-facing messages; original catalog reviewed by a native Lithuanian-speaking contributor; 2026-10-15 coverage additions are AI-assisted and not separately native-reviewed; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed"
licence = "MIT OR Apache-2.0"
licence_file = "LICENSE-MIT"
kind = "translation"
usage = "Lithuanian UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs"
-sha256 = "b387f130b8a7bd5b27d69764dbc59cee6813a09901725c0a189aab891eb6fcaf"
[[asset]]
path = "crates/ui-egui/src/i18n/hi.tsv"
title = "Hindi interface translation catalog"
author = "PdfCraft contributors"
-source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 text-field-table labels are contributor-original AI-assisted translations from English, not separately native-reviewed"
+source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 text-field-table labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed"
licence = "MIT OR Apache-2.0"
licence_file = "LICENSE-MIT"
kind = "translation"
usage = "Hindi UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs"
-sha256 = "c98204fcd53c76e01a7fbdb3c88c16bec07989e39c4155029988226bda9b4434"
[[asset]]
path = "crates/ui-egui/src/i18n/id.tsv"
title = "Indonesian interface translation catalog"
author = "PdfCraft contributors"
-source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 text-field-table labels are contributor-original AI-assisted translations from English, not separately native-reviewed"
+source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 text-field-table labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed"
licence = "MIT OR Apache-2.0"
licence_file = "LICENSE-MIT"
kind = "translation"
usage = "Indonesian UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs"
-sha256 = "e9a560ca03eb2bf6eba3308ddef0a578b661536eae3ddb1fde4cb0ad4f4c3174"
[[asset]]
path = "crates/ui-egui/src/i18n/ko.tsv"
title = "Korean interface translation catalog"
author = "PdfCraft contributors"
-source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 text-field-table labels are contributor-original AI-assisted translations from English, not separately native-reviewed"
+source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 text-field-table labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed"
licence = "MIT OR Apache-2.0"
licence_file = "LICENSE-MIT"
kind = "translation"
usage = "Korean UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs"
-sha256 = "8b2e8525956d47f311b50ff717a5f49f6189bc22bee606bb22c7968a59a9ff3b"
[[asset]]
path = "crates/ui-egui/src/i18n/ro.tsv"
title = "Romanian interface translation catalog"
author = "PdfCraft contributors"
-source = "Contributor-original: clean-room translations of PdfCraft's English UI labels and user-facing messages; AI-assisted and not yet reviewed line by line by a native Romanian speaker; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 text-field-table labels are contributor-original AI-assisted translations from English, not separately native-reviewed"
+source = "Contributor-original: clean-room translations of PdfCraft's English UI labels and user-facing messages; AI-assisted and not yet reviewed line by line by a native Romanian speaker; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 text-field-table labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed"
licence = "MIT OR Apache-2.0"
licence_file = "LICENSE-MIT"
kind = "translation"
usage = "Romanian UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs"
-sha256 = "b2b633ff657c22787f515dfa03a32ebd16bf59be7411eaa207df127ba9e1aea0"
[[asset]]
path = "crates/ui-egui/src/i18n/fi.tsv"
title = "Finnish interface translation catalog"
author = "PdfCraft contributors"
-source = "Contributor-original: AI-assisted (Claude Code) clean-room translations of PdfCraft's English UI labels and user-facing messages; not yet proofread by a native Finnish speaker; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 text-field-table labels are contributor-original AI-assisted translations from English, not separately native-reviewed"
+source = "Contributor-original: AI-assisted (Claude Code) clean-room translations of PdfCraft's English UI labels and user-facing messages; not yet proofread by a native Finnish speaker; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 text-field-table labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 calculation-order, text-format, print, thumbnail, layer, comment-reshape and signature labels (previously English placeholders) are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed"
licence = "MIT OR Apache-2.0"
licence_file = "LICENSE-MIT"
kind = "translation"
usage = "Finnish UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs"
-sha256 = "4c8700775b6c0b936383b11d3d2de8cce8f5d2fc0f5b35294357a38884aee6f1"
[[asset]]
path = "assets/icons/accessibility.svg"
@@ -3767,7 +3742,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); Arabic interface text, file names and document titles (Noto Sans Arabic); the web build embeds only BIZ UDPGothic Regular and Noto Sans Arabic. The checkout also holds Noto Sans CJK SC, which crates/fonts/build.rs never embeds (AGENTS.md §1.1)"
+usage = "Japanese fallback in the interface (BIZ UDPGothic first) and Japanese glyphs in edited PDF text (Shippori Mincho); Arabic interface text, file names and document titles (Noto Sans Arabic); the web build embeds only BIZ UDPGothic Regular and Noto Sans Arabic. The checkout also holds Noto Sans CJK SC, which crates/fonts/build.rs leaves out for size"
[[asset]]
path = "crates/sign/tests/data/x509-rsa-sha1.pdf"
@@ -3795,23 +3770,21 @@ sha256 = "d1a443233345724859de8e4fb48968ba91e885e12ddbd710701548bd91b39428"
path = "crates/ui-egui/src/i18n/vi.tsv"
title = "Vietnamese interface translation catalog"
author = "PdfCraft contributors"
-source = "Contributor-original: clean-room translations of PdfCraft's English UI labels; PhotoCraft and VectorCraft Vietnamese catalogs used only as translation memory when English source and semantic context matched; original catalog reviewed by a native Vietnamese-speaking contributor; 2026-10-15 coverage additions are AI-assisted and not separately native-reviewed; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 signature-check wordings are contributor-original AI-assisted translations from English, not separately native-reviewed"
+source = "Contributor-original: clean-room translations of PdfCraft's English UI labels; PhotoCraft and VectorCraft Vietnamese catalogs used only as translation memory when English source and semantic context matched; original catalog reviewed by a native Vietnamese-speaking contributor; 2026-10-15 coverage additions are AI-assisted and not separately native-reviewed; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 signature-check wordings are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed"
licence = "MIT OR Apache-2.0"
licence_file = "LICENSE-MIT"
kind = "translation"
usage = "Vietnamese UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs"
-sha256 = "7749a3461130726bc2c537f60c931f7f18f62c368a65087fb46f526232ae06da"
[[asset]]
path = "crates/ui-egui/src/i18n/sl.tsv"
title = "Slovene interface translation catalog"
author = "PdfCraft contributors"
-source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed"
+source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed"
licence = "MIT OR Apache-2.0"
licence_file = "LICENSE-MIT"
kind = "translation"
usage = "Slovene UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs"
-sha256 = "15e8b7983355ce4a1d2fa557b4398d4ca1b2e5da7b8b12cff935eed28a6f8902"
[[asset]]
@@ -3829,12 +3802,11 @@ sha256 = "78c59a0cfd2c829909d77006f94e34dac1ae5d1f90e7f10f72e84de541fef697"
path = "crates/ui-egui/src/i18n/nb.tsv"
title = "Norwegian Bokmål interface translation catalog"
author = "PdfCraft contributors"
-source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed"
+source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed"
licence = "MIT OR Apache-2.0"
licence_file = "LICENSE-MIT"
kind = "translation"
usage = "Norwegian Bokmål UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs"
-sha256 = "93955bf3542601b295747acda4e31b3b45b9d05278f2b3ca7f6f2ea7342261ec"
[[asset]]
path = "assets/icons/superscript.svg"
@@ -3884,31 +3856,28 @@ sha256 = "864ab2f19254e6ac7240bc6a98323197332e8f714d4d3f94831f41309e5ef2f7"
path = "crates/ui-egui/src/i18n/sq.tsv"
title = "Albanian interface translation catalog"
author = "PdfCraft contributors"
-source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 signature-appearance labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 text-field-table labels are contributor-original AI-assisted translations from English, not separately native-reviewed"
+source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 signature-appearance labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 text-field-table labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed"
licence = "MIT OR Apache-2.0"
licence_file = "LICENSE-MIT"
kind = "translation"
usage = "Albanian UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs"
-sha256 = "2c83cc1807ccd1f01e4f264aa639aa8070ce241f2ea3a8f9bebb11ec0de79070"
[[asset]]
path = "crates/ui-egui/src/i18n/th.tsv"
title = "Thai interface translation catalog"
author = "PdfCraft contributors"
-source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed"
+source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed"
licence = "MIT OR Apache-2.0"
licence_file = "LICENSE-MIT"
kind = "translation"
usage = "Thai UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs"
-sha256 = "d4c9b1ded657cc245cdd82f345866246eb5278f032bc3afe67100241763c9e53"
[[asset]]
path = "crates/ui-egui/src/i18n/ca.tsv"
title = "Catalan interface translation catalog"
author = "PdfCraft contributors"
-source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, written from their meaning; no proprietary localisation resources; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 text-field-table labels are contributor-original AI-assisted translations from English, not separately native-reviewed"
+source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, written from their meaning; no proprietary localisation resources; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 text-field-table labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed"
licence = "MIT OR Apache-2.0"
licence_file = "LICENSE-MIT"
kind = "translation"
usage = "Catalan UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs"
-sha256 = "92adb9b4b2daa7169be2017376caec3fec21ffe922761f23502ec0afb932e854"
diff --git a/Cargo.lock b/Cargo.lock
index f933a7d..cb874fc 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -998,9 +998,9 @@ checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5"
[[package]]
name = "crypto-bigint"
-version = "0.7.5"
+version = "0.7.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "1a52aa3fcda4e6302a9f48734f234d35d4721b96f8fe07d073f07ce9df4f0271"
+checksum = "6bb08299a6046833a879ace115697f12fd2bd6c8d3e93c909ffc9e0738e7cae0"
dependencies = [
"cpubits",
"ctutils",
@@ -1046,9 +1046,9 @@ dependencies = [
[[package]]
name = "ctutils"
-version = "0.4.2"
+version = "0.4.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "7d5515a3834141de9eafb9717ad39eea8247b5674e6066c404e8c4b365d2a29e"
+checksum = "38d28fb6aa7dd680b3ffd1a3e64e115c177bdba63c0ae7f9cd48129ff05c4fa0"
dependencies = [
"cmov",
"subtle",
@@ -1876,8 +1876,6 @@ dependencies = [
[[package]]
name = "hayro-postscript"
version = "0.1.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "885c5ef0654933139a9b9546fc2c69e18d37f38aa2520f079092b1be18f1fcaa"
[[package]]
name = "hayro-syntax"
@@ -2694,7 +2692,7 @@ dependencies = [
[[package]]
name = "pdfcraft-a11y"
-version = "0.13.0"
+version = "0.14.0"
dependencies = [
"pdfcraft-content",
"pdfcraft-cos",
@@ -2706,7 +2704,7 @@ dependencies = [
[[package]]
name = "pdfcraft-android"
-version = "0.13.0"
+version = "0.14.0"
dependencies = [
"android_logger",
"log",
@@ -2720,14 +2718,14 @@ dependencies = [
[[package]]
name = "pdfcraft-android-bindgen"
-version = "0.13.0"
+version = "0.14.0"
dependencies = [
"uniffi",
]
[[package]]
name = "pdfcraft-annot"
-version = "0.13.0"
+version = "0.14.0"
dependencies = [
"hayro-syntax",
"pdfcraft-cos",
@@ -2738,7 +2736,7 @@ dependencies = [
[[package]]
name = "pdfcraft-audit"
-version = "0.13.0"
+version = "0.14.0"
dependencies = [
"pdfcraft-content",
"pdfcraft-cos",
@@ -2749,7 +2747,7 @@ dependencies = [
[[package]]
name = "pdfcraft-automation"
-version = "0.13.0"
+version = "0.14.0"
dependencies = [
"base64 0.22.1",
"flate2",
@@ -2771,11 +2769,11 @@ dependencies = [
[[package]]
name = "pdfcraft-compare"
-version = "0.13.0"
+version = "0.14.0"
[[package]]
name = "pdfcraft-content"
-version = "0.13.0"
+version = "0.14.0"
dependencies = [
"hayro-syntax",
"pdfcraft-cos",
@@ -2783,7 +2781,7 @@ dependencies = [
[[package]]
name = "pdfcraft-cos"
-version = "0.13.0"
+version = "0.14.0"
dependencies = [
"chrono",
"hayro-syntax",
@@ -2798,7 +2796,7 @@ dependencies = [
[[package]]
name = "pdfcraft-create"
-version = "0.13.0"
+version = "0.14.0"
dependencies = [
"encoding_rs",
"flate2",
@@ -2817,7 +2815,7 @@ dependencies = [
[[package]]
name = "pdfcraft-crypt"
-version = "0.13.0"
+version = "0.14.0"
dependencies = [
"aes",
"md-5",
@@ -2829,7 +2827,7 @@ dependencies = [
[[package]]
name = "pdfcraft-edit"
-version = "0.13.0"
+version = "0.14.0"
dependencies = [
"hayro-syntax",
"kurbo",
@@ -2844,7 +2842,7 @@ dependencies = [
[[package]]
name = "pdfcraft-engine"
-version = "0.13.0"
+version = "0.14.0"
dependencies = [
"chrono",
"craft-docpath",
@@ -2885,14 +2883,14 @@ dependencies = [
[[package]]
name = "pdfcraft-export"
-version = "0.13.0"
+version = "0.14.0"
dependencies = [
"flate2",
]
[[package]]
name = "pdfcraft-filters"
-version = "0.13.0"
+version = "0.14.0"
dependencies = [
"flate2",
"proptest",
@@ -2902,7 +2900,7 @@ dependencies = [
[[package]]
name = "pdfcraft-fonts"
-version = "0.13.0"
+version = "0.14.0"
dependencies = [
"harfrust",
"pdfcraft-cos",
@@ -2912,7 +2910,7 @@ dependencies = [
[[package]]
name = "pdfcraft-forms"
-version = "0.13.0"
+version = "0.14.0"
dependencies = [
"hayro-syntax",
"pdfcraft-content",
@@ -2925,11 +2923,11 @@ dependencies = [
[[package]]
name = "pdfcraft-geom"
-version = "0.13.0"
+version = "0.14.0"
[[package]]
name = "pdfcraft-js"
-version = "0.13.0"
+version = "0.14.0"
dependencies = [
"boa_engine",
"chrono",
@@ -2937,7 +2935,7 @@ dependencies = [
[[package]]
name = "pdfcraft-measure"
-version = "0.13.0"
+version = "0.14.0"
dependencies = [
"pdfcraft-annot",
"pdfcraft-content",
@@ -2950,14 +2948,14 @@ dependencies = [
[[package]]
name = "pdfcraft-model"
-version = "0.13.0"
+version = "0.14.0"
dependencies = [
"pdfcraft-cos",
]
[[package]]
name = "pdfcraft-ocr"
-version = "0.13.0"
+version = "0.14.0"
dependencies = [
"ocrs",
"pdfcraft-fonts",
@@ -2967,24 +2965,26 @@ dependencies = [
[[package]]
name = "pdfcraft-optimize"
-version = "0.13.0"
+version = "0.14.0"
dependencies = [
"image",
"pdfcraft-annot",
"pdfcraft-content",
"pdfcraft-cos",
+ "pdfcraft-filters",
"pdfcraft-model",
"pdfcraft-render",
"thiserror",
+ "zune-jpeg",
]
[[package]]
name = "pdfcraft-oracle"
-version = "0.13.0"
+version = "0.14.0"
[[package]]
name = "pdfcraft-organize"
-version = "0.13.0"
+version = "0.14.0"
dependencies = [
"hayro-syntax",
"pdfcraft-content",
@@ -2995,7 +2995,7 @@ dependencies = [
[[package]]
name = "pdfcraft-platform"
-version = "0.13.0"
+version = "0.14.0"
dependencies = [
"async-channel",
"futures-lite",
@@ -3005,7 +3005,7 @@ dependencies = [
[[package]]
name = "pdfcraft-preflight"
-version = "0.13.0"
+version = "0.14.0"
dependencies = [
"flate2",
"pdfcraft-content",
@@ -3016,7 +3016,7 @@ dependencies = [
[[package]]
name = "pdfcraft-print"
-version = "0.13.0"
+version = "0.14.0"
dependencies = [
"craft-print",
"pdfcraft-content",
@@ -3028,7 +3028,7 @@ dependencies = [
[[package]]
name = "pdfcraft-redact"
-version = "0.13.0"
+version = "0.14.0"
dependencies = [
"pdfcraft-annot",
"pdfcraft-content",
@@ -3044,7 +3044,7 @@ dependencies = [
[[package]]
name = "pdfcraft-render"
-version = "0.13.0"
+version = "0.14.0"
dependencies = [
"bytemuck",
"flate2",
@@ -3063,7 +3063,7 @@ dependencies = [
[[package]]
name = "pdfcraft-sign"
-version = "0.13.0"
+version = "0.14.0"
dependencies = [
"aes",
"aws-lc-rs",
@@ -3085,6 +3085,7 @@ dependencies = [
"pdfcraft-annot",
"pdfcraft-cos",
"pdfcraft-fonts",
+ "pdfcraft-model",
"rc2",
"ripemd",
"rsa",
@@ -3098,11 +3099,11 @@ dependencies = [
[[package]]
name = "pdfcraft-testkit"
-version = "0.13.0"
+version = "0.14.0"
[[package]]
name = "pdfcraft-xfa"
-version = "0.13.0"
+version = "0.14.0"
dependencies = [
"base64 0.22.1",
"image",
@@ -3116,7 +3117,7 @@ dependencies = [
[[package]]
name = "pdfcraft-xfdf"
-version = "0.13.0"
+version = "0.14.0"
dependencies = [
"pdfcraft-annot",
"pdfcraft-cos",
diff --git a/Cargo.toml b/Cargo.toml
index 9858a48..80601cc 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -4,7 +4,7 @@ members = ["crates/a11y", "crates/annot", "crates/audit", "crates/automation", "
exclude = ["vendor"]
[workspace.package]
-version = "0.13.0"
+version = "0.14.0"
edition = "2024"
license = "MIT OR Apache-2.0"
rust-version = "1.95"
@@ -20,39 +20,39 @@ craft-print = { git = "https://github.com/storytold/craft-libs", version = "0.1.
# 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 = "82a24b006eefa036b43c09a67fb9a3fbd17ffe63" }
# internal
-pdfcraft-geom = { path = "crates/geom", version = "0.13.0" }
-pdfcraft-filters = { path = "crates/filters", version = "0.13.0" }
-pdfcraft-cos = { path = "crates/cos", version = "0.13.0" }
-pdfcraft-crypt = { path = "crates/crypt", version = "0.13.0" }
-pdfcraft-organize = { path = "crates/organize", version = "0.13.0" }
-pdfcraft-measure = { path = "crates/measure", version = "0.13.0" }
-pdfcraft-annot = { path = "crates/annot", version = "0.13.0" }
-pdfcraft-audit = { path = "crates/audit", version = "0.13.0" }
-pdfcraft-fonts = { path = "crates/fonts", version = "0.13.0" }
-pdfcraft-model = { path = "crates/model", version = "0.13.0" }
-pdfcraft-content = { path = "crates/content", version = "0.13.0" }
-pdfcraft-redact = { path = "crates/redact", version = "0.13.0" }
-pdfcraft-print = { path = "crates/print", version = "0.13.0" }
-pdfcraft-xfdf = { path = "crates/xfdf", version = "0.13.0" }
-pdfcraft-sign = { path = "crates/sign", version = "0.13.0" }
-pdfcraft-optimize = { path = "crates/optimize", version = "0.13.0" }
-pdfcraft-a11y = { path = "crates/a11y", version = "0.13.0" }
-pdfcraft-oracle = { path = "crates/oracle", version = "0.13.0" }
-pdfcraft-testkit = { path = "crates/testkit", version = "0.13.0" }
-pdfcraft-ocr = { path = "crates/ocr", version = "0.13.0" }
-pdfcraft-js = { path = "crates/js", version = "0.13.0" }
-pdfcraft-compare = { path = "crates/compare", version = "0.13.0" }
-pdfcraft-preflight = { path = "crates/preflight", version = "0.13.0" }
-pdfcraft-export = { path = "crates/export", version = "0.13.0" }
-pdfcraft-edit = { path = "crates/edit", version = "0.13.0" }
-pdfcraft-create = { path = "crates/create", version = "0.13.0" }
-pdfcraft-forms = { path = "crates/forms", version = "0.13.0" }
-pdfcraft-xfa = { path = "crates/xfa", version = "0.13.0" }
-pdfcraft-render = { path = "crates/render", version = "0.13.0" }
-pdfcraft-engine = { path = "crates/engine", version = "0.13.0" }
-pdfcraft-platform = { path = "crates/platform", version = "0.13.0" }
-pdfcraft-ui-egui = { path = "crates/ui-egui", version = "0.13.0" }
-pdfcraft-automation = { path = "crates/automation", version = "0.13.0", default-features = false }
+pdfcraft-geom = { path = "crates/geom", version = "0.14.0" }
+pdfcraft-filters = { path = "crates/filters", version = "0.14.0" }
+pdfcraft-cos = { path = "crates/cos", version = "0.14.0" }
+pdfcraft-crypt = { path = "crates/crypt", version = "0.14.0" }
+pdfcraft-organize = { path = "crates/organize", version = "0.14.0" }
+pdfcraft-measure = { path = "crates/measure", version = "0.14.0" }
+pdfcraft-annot = { path = "crates/annot", version = "0.14.0" }
+pdfcraft-audit = { path = "crates/audit", version = "0.14.0" }
+pdfcraft-fonts = { path = "crates/fonts", version = "0.14.0" }
+pdfcraft-model = { path = "crates/model", version = "0.14.0" }
+pdfcraft-content = { path = "crates/content", version = "0.14.0" }
+pdfcraft-redact = { path = "crates/redact", version = "0.14.0" }
+pdfcraft-print = { path = "crates/print", version = "0.14.0" }
+pdfcraft-xfdf = { path = "crates/xfdf", version = "0.14.0" }
+pdfcraft-sign = { path = "crates/sign", version = "0.14.0" }
+pdfcraft-optimize = { path = "crates/optimize", version = "0.14.0" }
+pdfcraft-a11y = { path = "crates/a11y", version = "0.14.0" }
+pdfcraft-oracle = { path = "crates/oracle", version = "0.14.0" }
+pdfcraft-testkit = { path = "crates/testkit", version = "0.14.0" }
+pdfcraft-ocr = { path = "crates/ocr", version = "0.14.0" }
+pdfcraft-js = { path = "crates/js", version = "0.14.0" }
+pdfcraft-compare = { path = "crates/compare", version = "0.14.0" }
+pdfcraft-preflight = { path = "crates/preflight", version = "0.14.0" }
+pdfcraft-export = { path = "crates/export", version = "0.14.0" }
+pdfcraft-edit = { path = "crates/edit", version = "0.14.0" }
+pdfcraft-create = { path = "crates/create", version = "0.14.0" }
+pdfcraft-forms = { path = "crates/forms", version = "0.14.0" }
+pdfcraft-xfa = { path = "crates/xfa", version = "0.14.0" }
+pdfcraft-render = { path = "crates/render", version = "0.14.0" }
+pdfcraft-engine = { path = "crates/engine", version = "0.14.0" }
+pdfcraft-platform = { path = "crates/platform", version = "0.14.0" }
+pdfcraft-ui-egui = { path = "crates/ui-egui", version = "0.14.0" }
+pdfcraft-automation = { path = "crates/automation", version = "0.14.0", default-features = false }
# pdf
hayro = "0.7.1"
@@ -88,20 +88,20 @@ dbg_macro = "warn"
todo = "warn"
# `"*"` matches every non-workspace package: crates.io dependencies and the
-# vendored crates under `vendor/` (excluded from the workspace). Our own crates
-# keep full debug info. Dependencies keep only line tables, so backtraces still
-# show file and line, but debug info for the whole dependency graph stays out of
-# every test binary (each UI test binary had a 500-600 MB PDB on Windows, #454).
+# vendored crates under `vendor/` (excluded from the workspace). Dependencies
+# carry no debug info and our own crates only line tables: backtraces and
+# panics still show file and line, while test binaries and the target dir stay
+# small (each UI test binary had a 500-600 MB PDB on Windows, #454).
[profile.dev.package."*"]
opt-level = 2
-debug = "line-tables-only"
+debug = false
[profile.dev]
opt-level = 1
+debug = "line-tables-only"
[profile.low-disk]
inherits = "dev"
-debug = "line-tables-only"
incremental = false
[profile.release]
@@ -114,6 +114,7 @@ hayro-interpret = { path = "vendor/hayro-interpret" }
hayro = { path = "vendor/hayro" }
hayro-syntax = { path = "vendor/hayro-syntax" }
hayro-cmap = { path = "vendor/hayro-cmap" }
+hayro-postscript = { path = "vendor/hayro-postscript" }
hayro-jbig2 = { path = "vendor/hayro-jbig2" }
lopdf = { path = "vendor/lopdf" }
vello_cpu = { path = "vendor/vello_cpu" }
diff --git a/assets/demo/showcase.html b/assets/demo/showcase.html
index 22e0619..b26f245 100644
--- a/assets/demo/showcase.html
+++ b/assets/demo/showcase.html
@@ -14,27 +14,27 @@
(highlight, sticky note, stamp, ...), so annotation geometry follows the layout.
-->
<style>
-@font-face { font-family: "PC Mono"; src: url("{{ASSETS}}/fonts/JetBrainsMono-Regular.ttf"); }
-@font-face { font-family: "PC Inter"; src: url("{{FONTS}}/Inter[opsz,wght].ttf"); font-weight: 100 900; }
-@font-face { font-family: "PC Inter"; src: url("{{FONTS}}/Inter-Italic[opsz,wght].ttf"); font-weight: 100 900; font-style: italic; }
-@font-face { font-family: "PC Garamond"; src: url("{{FONTS}}/EBGaramond[wght].ttf"); font-weight: 400 800; }
-@font-face { font-family: "PC Garamond"; src: url("{{FONTS}}/EBGaramond-Italic[wght].ttf"); font-weight: 400 800; font-style: italic; }
-@font-face { font-family: "PC Playfair"; src: url("{{FONTS}}/PlayfairDisplay[wght].ttf"); font-weight: 400 900; }
-@font-face { font-family: "PC Playfair"; src: url("{{FONTS}}/PlayfairDisplay-Italic[wght].ttf"); font-weight: 400 900; font-style: italic; }
-@font-face { font-family: "PC Vibes"; src: url("{{FONTS}}/GreatVibes-Regular.ttf"); }
-@font-face { font-family: "PC Math"; src: url("{{FONTS}}/STIXTwoMath-Regular.ttf"); }
-@font-face { font-family: "PC Amiri"; src: url("{{FONTS}}/Amiri-Regular.ttf"); }
-@font-face { font-family: "PC Hebrew"; src: url("{{FONTS}}/NotoSansHebrew[wdth,wght].ttf"); font-weight: 100 900; }
-@font-face { font-family: "PC Devanagari"; src: url("{{FONTS}}/NotoSansDevanagari[wdth,wght].ttf"); font-weight: 100 900; }
-@font-face { font-family: "PC Thai"; src: url("{{FONTS}}/NotoSansThai[wdth,wght].ttf"); font-weight: 100 900; }
-@font-face { font-family: "PC Armenian"; src: url("{{FONTS}}/NotoSansArmenian[wdth,wght].ttf"); font-weight: 100 900; }
-@font-face { font-family: "PC Georgian"; src: url("{{FONTS}}/NotoSansGeorgian[wdth,wght].ttf"); font-weight: 100 900; }
-@font-face { font-family: "PC Tamil"; src: url("{{FONTS}}/NotoSansTamil[wdth,wght].ttf"); font-weight: 100 900; }
-@font-face { font-family: "PC Charis"; src: url("{{FONTS}}/CharisSIL-Regular.ttf"); }
-@font-face { font-family: "PC XiaoWei"; src: url("{{FONTS}}/ZCOOLXiaoWei-Regular.ttf"); }
-@font-face { font-family: "PC Mincho"; src: url("{{FONTS}}/ShipporiMincho-Regular.ttf"); }
-@font-face { font-family: "PC Gowun"; src: url("{{FONTS}}/GowunBatang-Regular.ttf"); }
-@font-face { font-family: "PC Emoji"; src: url("{{FONTS}}/NotoColorEmoji-Regular.ttf"); }
+@font-face { font-display: block; font-family: "PC Mono"; src: url("{{ASSETS}}/fonts/JetBrainsMono-Regular.ttf"); }
+@font-face { font-display: block; font-family: "PC Inter"; src: url("{{FONTS}}/Inter[opsz,wght].ttf"); font-weight: 100 900; }
+@font-face { font-display: block; font-family: "PC Inter"; src: url("{{FONTS}}/Inter-Italic[opsz,wght].ttf"); font-weight: 100 900; font-style: italic; }
+@font-face { font-display: block; font-family: "PC Garamond"; src: url("{{FONTS}}/EBGaramond[wght].ttf"); font-weight: 400 800; }
+@font-face { font-display: block; font-family: "PC Garamond"; src: url("{{FONTS}}/EBGaramond-Italic[wght].ttf"); font-weight: 400 800; font-style: italic; }
+@font-face { font-display: block; font-family: "PC Playfair"; src: url("{{FONTS}}/PlayfairDisplay[wght].ttf"); font-weight: 400 900; }
+@font-face { font-display: block; font-family: "PC Playfair"; src: url("{{FONTS}}/PlayfairDisplay-Italic[wght].ttf"); font-weight: 400 900; font-style: italic; }
+@font-face { font-display: block; font-family: "PC Vibes"; src: url("{{FONTS}}/GreatVibes-Regular.ttf"); }
+@font-face { font-display: block; font-family: "PC Math"; src: url("{{FONTS}}/STIXTwoMath-Regular.ttf"); }
+@font-face { font-display: block; font-family: "PC Amiri"; src: url("{{FONTS}}/Amiri-Regular.ttf"); }
+@font-face { font-display: block; font-family: "PC Hebrew"; src: url("{{FONTS}}/NotoSansHebrew[wdth,wght].ttf"); font-weight: 100 900; }
+@font-face { font-display: block; font-family: "PC Devanagari"; src: url("{{FONTS}}/NotoSansDevanagari[wdth,wght].ttf"); font-weight: 100 900; }
+@font-face { font-display: block; font-family: "PC Thai"; src: url("{{FONTS}}/NotoSansThai[wdth,wght].ttf"); font-weight: 100 900; }
+@font-face { font-display: block; font-family: "PC Armenian"; src: url("{{FONTS}}/NotoSansArmenian[wdth,wght].ttf"); font-weight: 100 900; }
+@font-face { font-display: block; font-family: "PC Georgian"; src: url("{{FONTS}}/NotoSansGeorgian[wdth,wght].ttf"); font-weight: 100 900; }
+@font-face { font-display: block; font-family: "PC Tamil"; src: url("{{FONTS}}/NotoSansTamil[wdth,wght].ttf"); font-weight: 100 900; }
+@font-face { font-display: block; font-family: "PC Charis"; src: url("{{FONTS}}/CharisSIL-Regular.ttf"); }
+@font-face { font-display: block; font-family: "PC XiaoWei"; src: url("{{FONTS}}/ZCOOLXiaoWei-Regular.ttf"); }
+@font-face { font-display: block; font-family: "PC Mincho"; src: url("{{FONTS}}/ShipporiMincho-Regular.ttf"); }
+@font-face { font-display: block; font-family: "PC Gowun"; src: url("{{FONTS}}/GowunBatang-Regular.ttf"); }
+@font-face { font-display: block; font-family: "PC Emoji"; src: url("{{FONTS}}/NotoColorEmoji-Regular.ttf"); }
@page { size: Letter; margin: 0; }
@@ -598,11 +598,11 @@ a.box { position: absolute; display: block; color: transparent; font-size: 1pt;
<p class="dek">Nine small plates, each exercising one piece of the PDF imaging model.</p>
<div class="gfx">
<figure>
- <svg viewBox="0 0 160 120"><defs><linearGradient id="lg1" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="#2a6fdb"/><stop offset="0.5" stop-color="#1a9e8f"/><stop offset="1" stop-color="#e9a100"/></linearGradient></defs><rect width="160" height="120" rx="6" fill="url(#lg1)"/></svg>
+ <svg role="img" aria-label="Axial shading: three-stop linear gradient" viewBox="0 0 160 120"><defs><linearGradient id="lg1" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="#2a6fdb"/><stop offset="0.5" stop-color="#1a9e8f"/><stop offset="1" stop-color="#e9a100"/></linearGradient></defs><rect width="160" height="120" rx="6" fill="url(#lg1)"/></svg>
<figcaption class="caption"><b>Axial shading</b> &middot; three-stop linear gradient</figcaption>
</figure>
<figure>
- <svg viewBox="0 0 160 120"><defs><radialGradient id="rg1" cx="0.35" cy="0.35" r="0.75"><stop offset="0" stop-color="#fff5d6"/><stop offset="0.35" stop-color="#e9a100"/><stop offset="0.75" stop-color="#e4572e"/><stop offset="1" stop-color="#16213b"/></radialGradient></defs><rect width="160" height="120" rx="6" fill="#16213b"/><circle cx="80" cy="60" r="52" fill="url(#rg1)"/></svg>
+ <svg role="img" aria-label="Radial shading: off-centre focal point" viewBox="0 0 160 120"><defs><radialGradient id="rg1" cx="0.35" cy="0.35" r="0.75"><stop offset="0" stop-color="#fff5d6"/><stop offset="0.35" stop-color="#e9a100"/><stop offset="0.75" stop-color="#e4572e"/><stop offset="1" stop-color="#16213b"/></radialGradient></defs><rect width="160" height="120" rx="6" fill="#16213b"/><circle cx="80" cy="60" r="52" fill="url(#rg1)"/></svg>
<figcaption class="caption"><b>Radial shading</b> &middot; off-centre focal point</figcaption>
</figure>
<figure>
@@ -614,31 +614,31 @@ a.box { position: absolute; display: block; color: transparent; font-size: 1pt;
<figcaption class="caption"><b>Screen</b> &middot; additive light, /BM /Screen</figcaption>
</figure>
<figure>
- <svg viewBox="0 0 160 120"><defs><clipPath id="cp1"><text x="80" y="88" text-anchor="middle" font-family="PC Playfair, serif" font-size="70" font-weight="bold">Clip</text></clipPath><linearGradient id="lg2" x1="0" x2="0" y1="0" y2="1"><stop offset="0" stop-color="#e4572e"/><stop offset="1" stop-color="#b83b5e"/></linearGradient></defs><rect width="160" height="120" rx="6" fill="#f1ece2"/><g clip-path="url(#cp1)"><rect width="160" height="120" fill="url(#lg2)"/><g stroke="#f2c14e" stroke-width="3">
+ <svg role="img" aria-label="Clipping path: glyph outlines as a clip" viewBox="0 0 160 120"><defs><clipPath id="cp1"><text x="80" y="88" text-anchor="middle" font-family="PC Playfair, serif" font-size="70" font-weight="bold">Clip</text></clipPath><linearGradient id="lg2" x1="0" x2="0" y1="0" y2="1"><stop offset="0" stop-color="#e4572e"/><stop offset="1" stop-color="#b83b5e"/></linearGradient></defs><rect width="160" height="120" rx="6" fill="#f1ece2"/><g clip-path="url(#cp1)"><rect width="160" height="120" fill="url(#lg2)"/><g stroke="#f2c14e" stroke-width="3">
<line x1="0" y1="10" x2="160" y2="130"/><line x1="0" y1="40" x2="160" y2="160"/><line x1="0" y1="-20" x2="160" y2="100"/><line x1="0" y1="-50" x2="160" y2="70"/></g></g></svg>
<figcaption class="caption"><b>Clipping path</b> &middot; glyph outlines as a clip</figcaption>
</figure>
<figure>
- <svg viewBox="0 0 160 120"><defs><linearGradient id="fade" x1="0" x2="1"><stop offset="0" stop-color="#fff"/><stop offset="1" stop-color="#fff" stop-opacity="0"/></linearGradient><mask id="m1"><rect width="160" height="120" fill="url(#fade)"/></mask></defs><rect width="160" height="120" rx="6" fill="#f1ece2"/><g mask="url(#m1)"><rect x="12" y="14" width="136" height="92" rx="8" fill="#2a6fdb"/><circle cx="60" cy="60" r="26" fill="#f2c14e"/><circle cx="104" cy="60" r="26" fill="#e4572e"/></g></svg>
+ <svg role="img" aria-label="Soft mask: luminosity gradient fades artwork" viewBox="0 0 160 120"><defs><linearGradient id="fade" x1="0" x2="1"><stop offset="0" stop-color="#fff"/><stop offset="1" stop-color="#fff" stop-opacity="0"/></linearGradient><mask id="m1"><rect width="160" height="120" fill="url(#fade)"/></mask></defs><rect width="160" height="120" rx="6" fill="#f1ece2"/><g mask="url(#m1)"><rect x="12" y="14" width="136" height="92" rx="8" fill="#2a6fdb"/><circle cx="60" cy="60" r="26" fill="#f2c14e"/><circle cx="104" cy="60" r="26" fill="#e4572e"/></g></svg>
<figcaption class="caption"><b>Soft mask</b> &middot; luminosity gradient fades artwork</figcaption>
</figure>
<figure>
- <svg viewBox="0 0 160 120"><rect width="160" height="120" rx="6" fill="#fffdf8" stroke="#e2dccf"/><g fill="none" stroke="#16213b" stroke-width="2.5"><path d="M16 26 H144" stroke-dasharray="12 6"/><path d="M16 46 H144" stroke-dasharray="2 6" stroke-linecap="round"/><path d="M16 66 H144" stroke-dasharray="18 5 3 5" stroke="#e4572e"/><path d="M16 96 Q 50 70 80 96 T 144 96" stroke="#1a9e8f" stroke-width="5" stroke-linejoin="round" stroke-dasharray="1 9" stroke-linecap="round"/></g></svg>
+ <svg role="img" aria-label="Dash patterns: caps, joins and phase" viewBox="0 0 160 120"><rect width="160" height="120" rx="6" fill="#fffdf8" stroke="#e2dccf"/><g fill="none" stroke="#16213b" stroke-width="2.5"><path d="M16 26 H144" stroke-dasharray="12 6"/><path d="M16 46 H144" stroke-dasharray="2 6" stroke-linecap="round"/><path d="M16 66 H144" stroke-dasharray="18 5 3 5" stroke="#e4572e"/><path d="M16 96 Q 50 70 80 96 T 144 96" stroke="#1a9e8f" stroke-width="5" stroke-linejoin="round" stroke-dasharray="1 9" stroke-linecap="round"/></g></svg>
<figcaption class="caption"><b>Dash patterns</b> &middot; caps, joins and phase</figcaption>
</figure>
<figure>
- <svg viewBox="0 0 160 120"><defs><pattern id="checks" width="16" height="16" patternUnits="userSpaceOnUse"><rect width="16" height="16" fill="#f1ece2"/><rect width="8" height="8" fill="#16213b"/><rect x="8" y="8" width="8" height="8" fill="#16213b"/></pattern><pattern id="hatch" width="8" height="8" patternUnits="userSpaceOnUse" patternTransform="rotate(45)"><rect width="8" height="8" fill="#fbeccc"/><line x1="0" y1="0" x2="0" y2="8" stroke="#e9a100" stroke-width="3"/></pattern></defs><rect width="160" height="120" rx="6" fill="url(#checks)"/><circle cx="80" cy="60" r="40" fill="url(#hatch)" stroke="#16213b" stroke-width="2"/></svg>
+ <svg role="img" aria-label="Tiling patterns: checks and rotated hatch" viewBox="0 0 160 120"><defs><pattern id="checks" width="16" height="16" patternUnits="userSpaceOnUse"><rect width="16" height="16" fill="#f1ece2"/><rect width="8" height="8" fill="#16213b"/><rect x="8" y="8" width="8" height="8" fill="#16213b"/></pattern><pattern id="hatch" width="8" height="8" patternUnits="userSpaceOnUse" patternTransform="rotate(45)"><rect width="8" height="8" fill="#fbeccc"/><line x1="0" y1="0" x2="0" y2="8" stroke="#e9a100" stroke-width="3"/></pattern></defs><rect width="160" height="120" rx="6" fill="url(#checks)"/><circle cx="80" cy="60" r="40" fill="url(#hatch)" stroke="#16213b" stroke-width="2"/></svg>
<figcaption class="caption"><b>Tiling patterns</b> &middot; checks and rotated hatch</figcaption>
</figure>
<figure>
- <svg viewBox="0 0 160 120"><rect width="160" height="120" rx="6" fill="#16213b"/><g transform="translate(80 60)"><g fill="none" stroke-width="1.2">
+ <svg role="img" aria-label="Fill rules: even-odd pentagram at 45% opacity" viewBox="0 0 160 120"><rect width="160" height="120" rx="6" fill="#16213b"/><g transform="translate(80 60)"><g fill="none" stroke-width="1.2">
<path id="star" d="M0 -46 L13 -14 L46 -14 L19 6 L29 40 L0 20 L-29 40 L-19 6 L-46 -14 L-13 -14 Z" stroke="#f2c14e" fill="#f2c14e" fill-opacity="0.25" fill-rule="evenodd"/>
<path d="M0 -46 L27 37 L-44 -14 L44 -14 L-27 37 Z" stroke="#e4572e" fill="#e4572e" fill-opacity="0.45" fill-rule="evenodd"/></g></g></svg>
<figcaption class="caption"><b>Fill rules</b> &middot; even-odd pentagram, 45% opacity</figcaption>
</figure>
</div>
<div class="rule"></div>
- <svg viewBox="0 0 520 110" style="width:100%;height:auto;display:block">
+ <svg role="img" aria-label="Blend spectrum: multiplied gradient bands" viewBox="0 0 520 110" style="width:100%;height:auto;display:block">
<defs><linearGradient id="spec" x1="0" x2="1"><stop offset="0" stop-color="#16213b"/><stop offset="0.25" stop-color="#2a6fdb"/><stop offset="0.5" stop-color="#1a9e8f"/><stop offset="0.75" stop-color="#e9a100"/><stop offset="1" stop-color="#e4572e"/></linearGradient></defs>
<g style="mix-blend-mode:multiply">
<path d="M0 80 C 80 10, 160 110, 260 50 S 440 20, 520 70 L520 110 L0 110Z" fill="url(#spec)" opacity="0.85"/>
@@ -789,16 +789,16 @@ a.box { position: absolute; display: block; color: transparent; font-size: 1pt;
</div>
<div class="canvas">
<span class="lab" style="left:10pt;top:8pt">Review canvas</span>
- <a class="box" style="left:12pt;top:26pt;width:152pt;height:40pt" href="https://mark.pdfcraft.invalid/freetext/1">.</a>
- <a class="box" style="left:196pt;top:22pt;width:20pt;height:20pt" href="https://mark.pdfcraft.invalid/note/1">.</a>
- <a class="box" style="left:196pt;top:60pt;width:18pt;height:22pt" href="https://mark.pdfcraft.invalid/attach/1">.</a>
- <a class="box" style="left:16pt;top:88pt;width:90pt;height:60pt" href="https://mark.pdfcraft.invalid/square/1">.</a>
- <a class="box" style="left:120pt;top:92pt;width:90pt;height:60pt" href="https://mark.pdfcraft.invalid/circle/1">.</a>
- <a class="box" style="left:16pt;top:170pt;width:94pt;height:80pt" href="https://mark.pdfcraft.invalid/polygon/1">.</a>
- <a class="box" style="left:120pt;top:170pt;width:96pt;height:80pt" href="https://mark.pdfcraft.invalid/polyline/1">.</a>
- <a class="box" style="left:16pt;top:268pt;width:196pt;height:40pt" href="https://mark.pdfcraft.invalid/line/1">.</a>
- <a class="box" style="left:16pt;top:322pt;width:196pt;height:50pt" href="https://mark.pdfcraft.invalid/ink/1">.</a>
- <a class="box" style="left:30pt;top:388pt;width:170pt;height:56pt" href="https://mark.pdfcraft.invalid/stamp/1">.</a>
+ <a class="box" style="left:12pt;top:26pt;width:152pt;height:40pt" href="https://mark.pdfcraft.invalid/freetext/1">freetext</a>
+ <a class="box" style="left:196pt;top:22pt;width:20pt;height:20pt" href="https://mark.pdfcraft.invalid/note/1">note</a>
+ <a class="box" style="left:196pt;top:60pt;width:18pt;height:22pt" href="https://mark.pdfcraft.invalid/attach/1">attach</a>
+ <a class="box" style="left:16pt;top:88pt;width:90pt;height:60pt" href="https://mark.pdfcraft.invalid/square/1">square</a>
+ <a class="box" style="left:120pt;top:92pt;width:90pt;height:60pt" href="https://mark.pdfcraft.invalid/circle/1">circle</a>
+ <a class="box" style="left:16pt;top:170pt;width:94pt;height:80pt" href="https://mark.pdfcraft.invalid/polygon/1">polygon</a>
+ <a class="box" style="left:120pt;top:170pt;width:96pt;height:80pt" href="https://mark.pdfcraft.invalid/polyline/1">polyline</a>
+ <a class="box" style="left:16pt;top:268pt;width:196pt;height:40pt" href="https://mark.pdfcraft.invalid/line/1">line</a>
+ <a class="box" style="left:16pt;top:322pt;width:196pt;height:50pt" href="https://mark.pdfcraft.invalid/ink/1">ink</a>
+ <a class="box" style="left:30pt;top:388pt;width:170pt;height:56pt" href="https://mark.pdfcraft.invalid/stamp/1">stamp</a>
</div>
</div>
<div class="folio"><span>Review &amp; Markup</span><b>9</b></div>
diff --git a/crates/a11y/src/alt.rs b/crates/a11y/src/alt.rs
index 87cfce5..720b8a6 100644
--- a/crates/a11y/src/alt.rs
+++ b/crates/a11y/src/alt.rs
@@ -211,6 +211,25 @@ fn close(marks: &mut Vec<Mark>, matching: &mut usize, out: &mut HashMap<i64, [f6
draw(marks, b);
}
+/// The page-space box a `Do` operator paints: a form's transformed `/BBox`, or the unit square for an image.
+/// `None` when the operand is not a resolvable XObject or the form's box is malformed.
+fn xobject_bbox(doc: &Document, xobjects: &Dict, op: &pdfcraft_content::Op, top: &Matrix) -> Option<[f64; 4]> {
+ let r = op.name(0).and_then(|n| xobjects.get(n)).and_then(Object::as_ref)?;
+ Some(match &*doc.get(r) {
+ Object::Stream(s) if s.dict.name(b"Subtype") == Some(b"Form") => {
+ let bb: Vec<f64> =
+ s.dict.get(b"BBox").and_then(|b| b.as_array().map(|a| a.iter().filter_map(Object::as_f64).collect())).unwrap_or_default();
+ let m = Matrix::from_operands(s.dict.get(b"Matrix").and_then(|m| m.as_array()).map(Vec::as_slice).unwrap_or(&[]))
+ .unwrap_or(Matrix([1.0, 0.0, 0.0, 1.0, 0.0, 0.0]));
+ match bb[..] {
+ [a, b, c, d] => m.then(top).bbox([a, b, c, d]),
+ _ => return None,
+ }
+ }
+ _ => top.bbox([0.0, 0.0, 1.0, 1.0]),
+ })
+}
+
/// Where each of the marked content `ids` is drawn on a page (images, forms and paths), in one pass
/// over the page. What a sequence draws counts for every sequence of `ids` around it too.
pub(crate) fn content_bboxes(doc: &Document, page: &Dict, ids: &HashSet<i64>) -> HashMap<i64, [f64; 4]> {
@@ -274,20 +293,7 @@ pub(crate) fn content_bboxes(doc: &Document, page: &Dict, ids: &HashSet<i64>) ->
path.clear();
}
b"Do" if inside => {
- let Some(r) = op.name(0).and_then(|n| xobjects.get(n)).and_then(Object::as_ref) else { continue };
- let unit = match &*doc.get(r) {
- Object::Stream(s) if s.dict.name(b"Subtype") == Some(b"Form") => {
- let bb: Vec<f64> =
- s.dict.get(b"BBox").and_then(|b| b.as_array().map(|a| a.iter().filter_map(Object::as_f64).collect())).unwrap_or_default();
- let m = Matrix::from_operands(s.dict.get(b"Matrix").and_then(|m| m.as_array()).map(Vec::as_slice).unwrap_or(&[]))
- .unwrap_or(Matrix([1.0, 0.0, 0.0, 1.0, 0.0, 0.0]));
- match bb[..] {
- [a, b, c, d] => m.then(&top).bbox([a, b, c, d]),
- _ => continue,
- }
- }
- _ => top.bbox([0.0, 0.0, 1.0, 1.0]),
- };
+ let Some(unit) = xobject_bbox(doc, &xobjects, &op, &top) else { continue };
draw(&mut marks, unit);
}
b"BI" if inside => draw(&mut marks, top.bbox([0.0, 0.0, 1.0, 1.0])),
diff --git a/crates/a11y/src/autotag.rs b/crates/a11y/src/autotag.rs
index 4462025..9b65f69 100644
--- a/crates/a11y/src/autotag.rs
+++ b/crates/a11y/src/autotag.rs
@@ -132,6 +132,38 @@ fn harmless_inside(op: &[u8]) -> bool {
)
}
+/// The `(BT, ET)` operator index pairs of each text object that shows text, or why the page cannot be tagged.
+fn text_spans(ops: &[Op], index: usize) -> Result<Vec<(usize, usize)>, AutoTagError> {
+ let mut start = None;
+ let mut has_text = false;
+ let mut spans = Vec::new();
+ for (at, op) in ops.iter().enumerate() {
+ match op.op.as_slice() {
+ b"BT" if start.is_none() => {
+ start = Some(at);
+ has_text = false;
+ }
+ b"ET" => {
+ let Some(first) = start.take() else { return Err(unsupported(index, "unmatched ET operator")) };
+ if has_text {
+ spans.push((first, at));
+ if spans.len() > MAX_TEXT_OBJECTS {
+ return Err(unsupported(index, "too many text objects (maximum 4096)"));
+ }
+ }
+ }
+ b"Tj" | b"TJ" | b"'" | b"\"" if start.is_some() => has_text = true,
+ name if start.is_some() && harmless_inside(name) => {}
+ name if start.is_none() && harmless_outside(name) => {}
+ _ => return Err(unsupported(index, format!("unsupported or painted operator {}", String::from_utf8_lossy(&op.op)))),
+ }
+ }
+ if start.is_some() {
+ return Err(unsupported(index, "unterminated BT text object"));
+ }
+ Ok(spans)
+}
+
fn plan(doc: &Document) -> Result<Vec<Plan>, AutoTagError> {
let root = doc.root().ok_or(AutoTagError::NoCatalog)?;
let catalog = doc.get(root);
@@ -163,33 +195,7 @@ fn plan(doc: &Document) -> Result<Vec<Plan>, AutoTagError> {
if parsed.skipped > 0 || parsed.ops.len() > MAX_OPERATORS {
return Err(unsupported(index, "content has malformed or too many operators"));
}
- let mut start = None;
- let mut has_text = false;
- let mut spans = Vec::new();
- for (at, op) in parsed.ops.iter().enumerate() {
- match op.op.as_slice() {
- b"BT" if start.is_none() => {
- start = Some(at);
- has_text = false;
- }
- b"ET" => {
- let Some(first) = start.take() else { return Err(unsupported(index, "unmatched ET operator")) };
- if has_text {
- spans.push((first, at));
- if spans.len() > MAX_TEXT_OBJECTS {
- return Err(unsupported(index, "too many text objects (maximum 4096)"));
- }
- }
- }
- b"Tj" | b"TJ" | b"'" | b"\"" if start.is_some() => has_text = true,
- name if start.is_some() && harmless_inside(name) => {}
- name if start.is_none() && harmless_outside(name) => {}
- _ => return Err(unsupported(index, format!("unsupported or painted operator {}", String::from_utf8_lossy(&op.op)))),
- }
- }
- if start.is_some() {
- return Err(unsupported(index, "unterminated BT text object"));
- }
+ let spans = text_spans(&parsed.ops, index)?;
total = total.saturating_add(spans.len());
out.push(Plan { page: page.obj, ops: parsed.ops, spans });
}
diff --git a/crates/a11y/src/content.rs b/crates/a11y/src/content.rs
index fd5f0d3..d548c57 100644
--- a/crates/a11y/src/content.rs
+++ b/crates/a11y/src/content.rs
@@ -53,6 +53,15 @@ struct Walk<'a> {
budget: DecodeBudget,
}
+fn bdc_marks(doc: &Document, op: &pdfcraft_content::Op, props: &Dict) -> bool {
+ op.name(0) == Some(b"Artifact")
+ || match op.operands.get(1) {
+ Some(Object::Dict(d)) => d.contains(b"MCID"),
+ Some(Object::Name(n)) => props.get(n).map(|x| doc.resolve(x)).and_then(|x| x.as_dict().map(|d| d.contains(b"MCID"))).unwrap_or(false),
+ _ => false,
+ }
+}
+
impl Walk<'_> {
fn sub(&self, res: &Dict, key: &[u8]) -> Dict {
res.get(key).map(|x| self.doc.resolve(x)).and_then(|x| x.as_dict().cloned()).unwrap_or_default()
@@ -68,17 +77,7 @@ impl Walk<'_> {
let inside = covered || stack.last().copied().unwrap_or(false);
match op.op.as_slice() {
b"BMC" => stack.push(inside || op.name(0) == Some(b"Artifact")),
- b"BDC" => {
- let marks = op.name(0) == Some(b"Artifact")
- || match op.operands.get(1) {
- Some(Object::Dict(d)) => d.contains(b"MCID"),
- Some(Object::Name(n)) => {
- props.get(n).map(|x| self.doc.resolve(x)).and_then(|x| x.as_dict().map(|d| d.contains(b"MCID"))).unwrap_or(false)
- }
- _ => false,
- };
- stack.push(inside || marks);
- }
+ b"BDC" => stack.push(inside || bdc_marks(self.doc, &op, &props)),
b"EMC" => {
stack.pop();
}
diff --git a/crates/a11y/src/tags.rs b/crates/a11y/src/tags.rs
index 565f662..ba9d639 100644
--- a/crates/a11y/src/tags.rs
+++ b/crates/a11y/src/tags.rs
@@ -1,6 +1,6 @@
//! Properties of reachable indirect structure elements.
-use pdfcraft_cos::{CosError, Document, ObjRef, Object, PdfString};
+use pdfcraft_cos::{CosError, Dict, Document, ObjRef, Object, PdfString};
use crate::alt;
@@ -17,6 +17,10 @@ pub struct TagInfo {
pub actual_text: Option<String>,
pub alt: Option<String>,
pub language: Option<String>,
+ /// A table's `Summary` attribute.
+ pub summary: Option<String>,
+ /// A header cell's `Scope` attribute (`Row`, `Column` or `Both`).
+ pub scope: Option<String>,
/// Zero-based page when `/Pg` is known.
pub page: Option<usize>,
}
@@ -36,6 +40,10 @@ pub enum TagProperty {
ActualText,
AlternateText,
Language,
+ /// A table's `Summary`: a Table attribute (an attribute object with `/O /Table` in `/A`).
+ Summary,
+ /// A header cell's `Scope` (a Table attribute): `Row`, `Column` or `Both`.
+ Scope,
}
/// Where to place a structure tag relative to one of its direct siblings.
@@ -53,6 +61,8 @@ impl TagProperty {
"actual_text" => Some(Self::ActualText),
"alternate_text" => Some(Self::AlternateText),
"language" => Some(Self::Language),
+ "summary" => Some(Self::Summary),
+ "scope" => Some(Self::Scope),
_ => None,
}
}
@@ -64,6 +74,17 @@ impl TagProperty {
Self::ActualText => b"ActualText",
Self::AlternateText => b"Alt",
Self::Language => b"Lang",
+ Self::Summary => b"Summary",
+ Self::Scope => b"Scope",
+ }
+ }
+
+ /// The standard structure type a Table attribute belongs to; `None` for the tag's own entries.
+ fn table_attribute_of(self) -> Option<&'static str> {
+ match self {
+ Self::Summary => Some("Table"),
+ Self::Scope => Some("TH"),
+ _ => None,
}
}
}
@@ -82,6 +103,10 @@ pub enum TagError {
AmbiguousChildren,
#[error("the tag is already at the requested position")]
AlreadyThere,
+ #[error("{0} applies only to {1} tags")]
+ WrongTagType(&'static str, &'static str),
+ #[error("a scope must be Row, Column or Both")]
+ InvalidScope,
#[error(transparent)]
Cos(#[from] CosError),
}
@@ -142,6 +167,8 @@ pub fn tags(doc: &Document) -> Vec<TagInfo> {
actual_text: text(doc, &e.dict, b"ActualText"),
alt: text(doc, &e.dict, b"Alt"),
language: text(doc, &e.dict, b"Lang"),
+ summary: table_attribute(doc, &e.dict, b"Summary").and_then(|o| o.as_string().map(PdfString::to_text)),
+ scope: table_attribute(doc, &e.dict, b"Scope").and_then(|o| o.as_name().map(|n| String::from_utf8_lossy(n).into_owned())),
page: e.page.and_then(|p| page_index.get(&p).copied()),
})
})
@@ -200,11 +227,97 @@ fn direct_marks(doc: &Document, item: &Object, page: Option<ObjRef>, out: &mut V
}
}
-/// Change one property of a reachable tag; `None` removes a text property.
+/// The attribute objects of a tag's `/A` entry (one object, or an array of them each optionally
+/// followed by its revision number), as written: each entry and its revision number.
+fn attribute_entries(doc: &Document, d: &Dict) -> (Vec<(Object, Option<Object>)>, bool) {
+ let Some(a) = d.get(b"A") else { return (Vec::new(), false) };
+ // An indirect array is read as its items.
+ let resolved = doc.resolve(a);
+ let Object::Array(items) = &*resolved else { return (vec![(a.clone(), None)], false) };
+ let mut out: Vec<(Object, Option<Object>)> = Vec::new();
+ for item in items {
+ match (item, out.last_mut()) {
+ (Object::Int(_), Some((_, revision @ None))) => *revision = Some(item.clone()),
+ _ => out.push((item.clone(), None)),
+ }
+ }
+ (out, true)
+}
+
+/// Whether attribute object `o` (resolved) is a Table attribute object.
+fn is_table_attributes(o: &Object) -> bool {
+ o.as_dict().is_some_and(|d| d.name(b"O") == Some(b"Table"))
+}
+
+/// The value of `key` in the first Table attribute object of tag `d` that has it.
+fn table_attribute(doc: &Document, d: &Dict, key: &[u8]) -> Option<Object> {
+ attribute_entries(doc, d).0.iter().map(|(o, _)| doc.resolve(o)).filter(|o| is_table_attributes(o)).find_map(|o| o.as_dict()?.get(key).cloned())
+}
+
+/// Set `key` in the Table attribute object of `object`'s `/A` entry that holds it (else the first
+/// one, else a new one), or with `None` remove it from every Table attribute object that holds it.
+/// An edited object is written into the tag's own `/A`, so an attribute object other tags share
+/// keeps its value for them; one left with nothing but its owner goes, and so does an `/A` left
+/// empty.
+fn set_table_attribute(doc: &mut Document, object: ObjRef, key: &[u8], value: Option<Object>) -> Result<(), TagError> {
+ let dict = doc.get(object).as_dict().cloned().ok_or(TagError::NotATag(object))?;
+ let (entries, array) = attribute_entries(doc, &dict);
+ // Each entry with its Table attributes (resolved), when it is a Table attribute object.
+ let mut entries: Vec<(Object, Option<Object>, Option<Dict>)> = entries
+ .into_iter()
+ .map(|(o, r)| {
+ let table = Some(doc.resolve(&o)).filter(|a| is_table_attributes(a)).and_then(|a| a.as_dict().cloned());
+ (o, r, table)
+ })
+ .collect();
+ let holding = |e: &(Object, Option<Object>, Option<Dict>)| e.2.as_ref().is_some_and(|d| d.contains(key));
+ match value {
+ Some(v) => match entries.iter().position(holding).or_else(|| entries.iter().position(|e| e.2.is_some())) {
+ Some(i) => {
+ if let Some((o, _, Some(attributes))) = entries.get_mut(i) {
+ attributes.set(key.to_vec(), v);
+ *o = Object::Dict(attributes.clone());
+ }
+ }
+ None => {
+ let mut attributes = Dict::new();
+ attributes.set(b"O".to_vec(), Object::name("Table"));
+ attributes.set(key.to_vec(), v);
+ entries.push((Object::Dict(attributes), None, None));
+ }
+ },
+ None => {
+ if !entries.iter().any(holding) {
+ // Nothing to clear.
+ return Ok(());
+ }
+ for (o, _, table) in &mut entries {
+ if let Some(attributes) = table.as_mut().filter(|a| a.contains(key)) {
+ attributes.remove(key);
+ *o = Object::Dict(attributes.clone());
+ }
+ }
+ entries.retain(|(_, _, table)| !table.as_ref().is_some_and(|a| a.iter().all(|(k, _)| k.as_slice() == b"O")));
+ }
+ }
+ let entries: Vec<(Object, Option<Object>)> = entries.into_iter().map(|(o, r, _)| (o, r)).collect();
+ doc.update_dict(object, |d| match entries.as_slice() {
+ [] => {
+ d.remove(b"A");
+ }
+ [(only, None)] if !array => d.set(b"A".to_vec(), only.clone()),
+ _ => d.set(b"A".to_vec(), Object::Array(entries.into_iter().flat_map(|(o, r)| std::iter::once(o).chain(r)).collect())),
+ })?;
+ Ok(())
+}
+
+/// Change one property of a reachable tag; `None` removes a text property. A table's summary and
+/// a header cell's scope are Table attributes ([`TagProperty::Summary`], [`TagProperty::Scope`]),
+/// set only on tags of that type after the role map.
pub fn set_tag_property(doc: &mut Document, object: ObjRef, property: TagProperty, value: Option<&str>) -> Result<(), TagError> {
- if !alt::elements(doc).iter().any(|e| e.object == object) {
+ let Some(element) = alt::elements(doc).into_iter().find(|e| e.object == object) else {
return Err(TagError::NotATag(object));
- }
+ };
// ActualText may intentionally contain leading or trailing whitespace; preserve it.
let value = value.filter(|s| !s.is_empty());
if value.is_some_and(|s| s.len() > 65_536) {
@@ -215,6 +328,26 @@ pub fn set_tag_property(doc: &mut Document, object: ObjRef, property: TagPropert
{
return Err(TagError::InvalidType);
}
+ if let Some(owner) = property.table_attribute_of() {
+ let role_map =
+ alt::tree_root(doc).and_then(|r| r.get(b"RoleMap").map(|o| doc.resolve(o))).and_then(|o| o.as_dict().cloned()).unwrap_or_default();
+ let ty = element.dict.name(b"S").map(|s| alt::standard(doc, &role_map, s)).unwrap_or_default();
+ if ty != owner.as_bytes() {
+ let name = if property == TagProperty::Summary { "summary" } else { "scope" };
+ return Err(TagError::WrongTagType(name, owner));
+ }
+ let value = match value {
+ Some(s) if property == TagProperty::Scope => {
+ if !matches!(s, "Row" | "Column" | "Both") {
+ return Err(TagError::InvalidScope);
+ }
+ Some(Object::name(s))
+ }
+ Some(s) => Some(Object::String(PdfString::text(s))),
+ None => None,
+ };
+ return set_table_attribute(doc, object, property.key(), value);
+ }
doc.update_dict(object, |d| match value {
Some(s) if property == TagProperty::Type => d.set(property.key().to_vec(), Object::name(s)),
Some(s) => d.set(property.key().to_vec(), Object::String(PdfString::text(s))),
diff --git a/crates/a11y/src/tests.rs b/crates/a11y/src/tests.rs
index 399aded..a6dcdba 100644
--- a/crates/a11y/src/tests.rs
+++ b/crates/a11y/src/tests.rs
@@ -367,6 +367,103 @@ fn reachable_tag_properties_round_trip_and_reject_unrelated_objects() {
assert!(matches!(set_tag_property(&mut doc, pdfcraft_cos::ObjRef::new(4, 1), TagProperty::Title, Some("No")), Err(TagError::NotATag(_))));
}
+/// A table (object 4) with a header cell (6) and a data cell (7); `th` is the header cell's
+/// dictionary and `extra` more objects from 8 on, of which the Document element (3) lists `kids`
+/// after the table. The role map maps /MyTable to /Table.
+fn table_doc(th: &str, extra: &[&str], kids: &str) -> Document {
+ let mut objs = vec![
+ "<< /Type /Catalog /StructTreeRoot 2 0 R >>".to_string(),
+ "<< /Type /StructTreeRoot /K 3 0 R /RoleMap << /MyTable /Table >> >>".to_string(),
+ format!("<< /S /Document /K [4 0 R {kids}] >>"),
+ "<< /S /Table /K [5 0 R] >>".to_string(),
+ "<< /S /TR /K [6 0 R 7 0 R] >>".to_string(),
+ th.to_string(),
+ "<< /S /TD >>".to_string(),
+ ];
+ objs.extend(extra.iter().map(ToString::to_string));
+ pdf(&objs, "")
+}
+
+/// The attribute objects of tag `r`'s /A entry as written (one object or an array).
+fn attributes(doc: &Document, r: pdfcraft_cos::ObjRef) -> Option<pdfcraft_cos::Object> {
+ doc.get(r).as_dict()?.get(b"A").cloned()
+}
+
+#[test]
+fn a_table_summary_is_a_table_attribute() {
+ let mut doc = table_doc("<< /S /TH >>", &["<< /S /MyTable >>"], "8 0 R");
+ let (table, th) = (pdfcraft_cos::ObjRef::new(4, 0), pdfcraft_cos::ObjRef::new(6, 0));
+ set_tag_property(&mut doc, table, TagProperty::Summary, Some("Opening hours by day")).unwrap();
+ let a = attributes(&doc, table).unwrap();
+ let a = a.as_dict().unwrap();
+ assert_eq!(a.name(b"O"), Some(&b"Table"[..]));
+ assert_eq!(
+ a.get(b"Summary").and_then(pdfcraft_cos::Object::as_string).map(pdfcraft_cos::PdfString::to_text).as_deref(),
+ Some("Opening hours by day")
+ );
+ assert_eq!(tags(&doc).iter().find(|t| t.object == table).unwrap().summary.as_deref(), Some("Opening hours by day"));
+ // Only a table takes one (after the role map: /MyTable is a table).
+ assert!(matches!(set_tag_property(&mut doc, th, TagProperty::Summary, Some("No")), Err(TagError::WrongTagType(..))));
+ set_tag_property(&mut doc, pdfcraft_cos::ObjRef::new(8, 0), TagProperty::Summary, Some("Mapped")).unwrap();
+ // Cleared, the attribute object has nothing left and goes.
+ set_tag_property(&mut doc, table, TagProperty::Summary, None).unwrap();
+ assert_eq!(attributes(&doc, table), None);
+}
+
+#[test]
+fn a_header_cell_scope_keeps_its_other_attributes() {
+ // The cell's /A holds a layout attribute object, then a table one with a revision number.
+ let mut doc = table_doc("<< /S /TH /A [ << /O /Layout /Placement /Block >> << /O /Table /ColSpan 2 >> 1 ] >>", &[], "");
+ let th = pdfcraft_cos::ObjRef::new(6, 0);
+ set_tag_property(&mut doc, th, TagProperty::Scope, Some("Column")).unwrap();
+ let Some(pdfcraft_cos::Object::Array(items)) = attributes(&doc, th) else { panic!("{:?}", attributes(&doc, th)) };
+ assert_eq!(items.len(), 3, "{items:?}");
+ assert_eq!(items[0].as_dict().and_then(|d| d.name(b"O")), Some(&b"Layout"[..]));
+ let table = items[1].as_dict().unwrap();
+ assert_eq!((table.int(b"ColSpan"), table.name(b"Scope")), (Some(2), Some(&b"Column"[..])));
+ assert_eq!(items[2].as_int(), Some(1), "the revision number stays with its object");
+ assert_eq!(tags(&doc).iter().find(|t| t.object == th).unwrap().scope.as_deref(), Some("Column"));
+ // Cleared, the span stays.
+ set_tag_property(&mut doc, th, TagProperty::Scope, None).unwrap();
+ let Some(pdfcraft_cos::Object::Array(items)) = attributes(&doc, th) else { panic!() };
+ assert_eq!(items[1].as_dict().map(|d| (d.int(b"ColSpan"), d.contains(b"Scope"))), Some((Some(2), false)));
+ // A scope is Row, Column or Both, and only header cells have one.
+ for bad in ["row", "Sideways", " Both"] {
+ assert!(matches!(set_tag_property(&mut doc, th, TagProperty::Scope, Some(bad)), Err(TagError::InvalidScope)), "{bad}");
+ }
+ assert!(matches!(set_tag_property(&mut doc, pdfcraft_cos::ObjRef::new(7, 0), TagProperty::Scope, Some("Row")), Err(TagError::WrongTagType(..))));
+}
+
+/// With two Table attribute objects, the one holding the value is the one set and cleared
+/// (#4130 review): a value in the second isn't left behind or shadowed.
+#[test]
+fn the_table_attribute_object_holding_a_value_is_the_one_edited() {
+ let mut doc = table_doc("<< /S /TH /A [ << /O /Table /ColSpan 2 >> << /O /Table /Scope /Row >> ] >>", &[], "");
+ let th = pdfcraft_cos::ObjRef::new(6, 0);
+ let scopes = |doc: &Document| -> Vec<Option<Vec<u8>>> {
+ let Some(pdfcraft_cos::Object::Array(items)) = attributes(doc, th) else { return vec![] };
+ items.iter().map(|i| i.as_dict().and_then(|d| d.name(b"Scope")).map(<[u8]>::to_vec)).collect()
+ };
+ set_tag_property(&mut doc, th, TagProperty::Scope, Some("Column")).unwrap();
+ assert_eq!(scopes(&doc), [None, Some(b"Column".to_vec())]);
+ assert_eq!(tags(&doc).iter().find(|t| t.object == th).unwrap().scope.as_deref(), Some("Column"));
+ set_tag_property(&mut doc, th, TagProperty::Scope, None).unwrap();
+ assert_eq!(scopes(&doc), [None], "the second object had only the scope: {:?}", attributes(&doc, th));
+ assert_eq!(tags(&doc).iter().find(|t| t.object == th).unwrap().scope, None);
+}
+
+#[test]
+fn a_shared_attribute_object_is_not_changed_for_other_tags() {
+ // Both cells point at attribute object 8.
+ let mut doc = table_doc("<< /S /TH /A 8 0 R >>", &["<< /O /Table /Scope /Row >>"], "");
+ doc.update_dict(pdfcraft_cos::ObjRef::new(7, 0), |d| d.set(b"A".to_vec(), pdfcraft_cos::Object::Ref(pdfcraft_cos::ObjRef::new(8, 0)))).unwrap();
+ set_tag_property(&mut doc, pdfcraft_cos::ObjRef::new(6, 0), TagProperty::Scope, Some("Both")).unwrap();
+ assert_eq!(doc.get(pdfcraft_cos::ObjRef::new(8, 0)).as_dict().and_then(|d| d.name(b"Scope")), Some(&b"Row"[..]));
+ let a = attributes(&doc, pdfcraft_cos::ObjRef::new(6, 0)).unwrap();
+ assert_eq!(a.as_dict().and_then(|d| d.name(b"Scope")), Some(&b"Both"[..]), "the cell's own copy: {a:?}");
+ assert_eq!(attributes(&doc, pdfcraft_cos::ObjRef::new(7, 0)), Some(pdfcraft_cos::Object::Ref(pdfcraft_cos::ObjRef::new(8, 0))));
+}
+
#[test]
fn tag_hierarchy_keeps_indirect_parent_through_inline_tags() {
let doc = structure_doc(&["<< /S /Document /K 4 0 R >>".into(), "<< /S /Sect /K << /S /Div /K 5 0 R >> >>".into(), "<< /S /Figure >>".into()]);
diff --git a/crates/annot/README.md b/crates/annot/README.md
index 36bd237..f6321df 100644
--- a/crates/annot/README.md
+++ b/crates/annot/README.md
@@ -9,12 +9,14 @@ Comments (annotations), ISO 32000-2 §12.5. Layer L3, depends on `pdfcraft-cos`,
line and arrow (`Line` with `/LE`), freehand drawing (`Ink`) and text box (`FreeText`).
- **Appearance streams** (`appearance::build`) generated from the annotation dictionary, so new
and restyled comments look the same in every viewer. Highlights multiply (`/BM /Multiply`).
+ A line's leader lines (`/LL`, `/LLE`, `/LLO`) and caption (`/Cap`, `/CP`, `/CO`) are drawn as
+ ISO 32000-2 Table 178 places them, the caption in black Helvetica 10.
Note icons are PdfCraft's own drawings. Text boxes use standard Helvetica (WinAnsi), with
line breaking by approximate Helvetica proportions (no font program is bundled); a text box,
callout or Fill & Sign text with letters WinAnsi can't hold but the bundled Inter can (Turkish,
Polish, Greek, Cyrillic, …) is drawn as Inter's outlines and measured by Inter
(`appearance::text_measure`). Text neither can draw (in a text box, callout, Fill & Sign text,
- measurement label or dynamic stamp's by-line;
+ line caption, measurement label or dynamic stamp's by-line;
`appearance::undrawable_text`) is kept as typed and drawn as `?`, and the comment is marked with
the first such character (`pdfcraft_fonts::UNDRAWN_MARK`) so the engine reports the edit and
flattening refuses to make it permanent. Two refusals (`AnnotError::Undrawable`): a redaction
@@ -54,6 +56,11 @@ deterministic; the engine supplies them.
signature) and PdfCraft's rubber stamps counterrotate their appearance on rotated pages, so
the picture or label reads upright as the page is displayed. Restyling a picture stamp keeps
that appearance matrix. The rotation is the page's `/Rotate` at placement.
+- Sticky notes and file attachments are not counterrotated: they carry the NoRotate flag and
+ their icon is drawn in an unturned 20 × 20 box. A viewer keeps them upright on a turned page,
+ about the upper-left corner of `/Rect` (ISO 32000-2 §12.5.3). PdfCraft's renderer does so
+ (vendored hayro-interpret patch 37), and `Summary::no_rotate` tells the UI where the icon is
+ drawn.
## Not yet
diff --git a/crates/annot/src/appearance.rs b/crates/annot/src/appearance.rs
index e3fca9b..f4a81d8 100644
--- a/crates/annot/src/appearance.rs
+++ b/crates/annot/src/appearance.rs
@@ -188,23 +188,42 @@ fn interior_color(d: &Dict, fallback: Option<Rgb>) -> Option<Rgb> {
color(d, b"IC").flatten().or(fallback)
}
+/// The border width (ISO 32000-2 §12.5.4): `/BS /W` when there is a border style dictionary, which
+/// makes `/Border` ignored (Table 166), else the third element of `/Border [hr vr w [dash]]`, read
+/// whether or not the optional fourth element, a dash array, follows. 1 when neither says, and
+/// when the number given is negative or not finite.
pub(crate) fn border_width(d: &Dict) -> f64 {
- if let Some(w) = d.get(b"BS").and_then(|b| b.as_dict()).and_then(|b| b.get(b"W")).and_then(|w| w.as_f64()) {
- return w.max(0.0);
- }
- match nums(d, b"Border") {
- Some(b) if b.len() >= 3 => b[2].max(0.0),
- _ => 1.0,
- }
+ let width = match d.get(b"BS").and_then(Object::as_dict) {
+ Some(bs) => bs.get(b"W").and_then(Object::as_f64),
+ None => d.get(b"Border").and_then(Object::as_array).and_then(|b| b.get(2)).and_then(Object::as_f64),
+ };
+ width.filter(|w| w.is_finite() && *w >= 0.0).unwrap_or(1.0)
+}
+
+/// Elements a dash array may have before it is drawn solid instead: the lengths are written into
+/// the appearance as they are, so a file can't make it arbitrarily large.
+const MAX_DASH: usize = 64;
+
+/// A dash array (§8.4.3.6) as drawn: every element finite and non-negative, not all zero (that
+/// pattern is invalid) and at most [`MAX_DASH`] long. `None` for anything else, which is drawn solid.
+fn dash_array(o: &Object) -> Option<Vec<f64>> {
+ let a = o.as_array().filter(|a| !a.is_empty() && a.len() <= MAX_DASH)?;
+ let v: Vec<f64> = a.iter().map(Object::as_f64).collect::<Option<_>>()?;
+ (v.iter().all(|x| x.is_finite() && *x >= 0.0) && v.iter().any(|x| *x > 0.0)).then_some(v)
}
-/// Dash pattern operator for a dashed border, if any.
+/// Dash pattern operator for a dashed border, if any: `/BS /S /D` with its `/D` (default `[3]`,
+/// Table 168), or, without `/BS`, the dash array that may follow the width in `/Border` (Table 166).
fn dash(d: &Dict) -> String {
- let Some(bs) = d.get(b"BS").and_then(|b| b.as_dict()) else { return String::new() };
- if bs.name(b"S") != Some(b"D") {
- return String::new();
- }
- let arr = nums(bs, b"D").filter(|a| !a.is_empty() && a.iter().all(|x| *x >= 0.0)).unwrap_or_else(|| vec![3.0]);
+ let arr = match d.get(b"BS").and_then(Object::as_dict) {
+ Some(bs) if bs.name(b"S") != Some(b"D") => return String::new(),
+ Some(bs) => match bs.get(b"D") {
+ None => Some(vec![3.0]),
+ Some(o) => dash_array(o),
+ },
+ None => d.get(b"Border").and_then(Object::as_array).and_then(|b| b.get(3)).and_then(dash_array),
+ };
+ let Some(arr) = arr else { return String::new() };
format!("[{}] 0 d\n", arr.iter().map(|x| n(*x)).collect::<Vec<_>>().join(" "))
}
@@ -292,12 +311,13 @@ fn text_turn(d: &Dict) -> i64 {
/// The first text [`build`] would draw in the standard fonts (Helvetica, WinAnsiEncoding) that
/// they can't, which would come out as `?`: what it is (for the message) and the character. The
/// text of a text box, callout or Fill & Sign text (drawn in Inter when Inter has every such
-/// character), a measurement's label, a dynamic stamp's "By …" line, and a redaction mark's overlay
-/// text (drawn when it is applied). `None` when all of it can be drawn.
+/// character), a line's caption, a measurement's label, a dynamic stamp's "By …" line, and a
+/// redaction mark's overlay text (drawn when it is applied). `None` when all of it can be drawn.
pub fn undrawable_text(d: &Dict) -> Option<(&'static str, char)> {
let text = |key: &[u8]| d.get(key).and_then(Object::as_string).map(PdfString::to_text);
let (what, text) = match d.name(b"Subtype")? {
b"FreeText" => return text(b"Contents").and_then(|t| first_undrawable_inter(&t)).map(|c| ("the comment's text", c)),
+ b"Line" if !d.contains(b"PCMeasureValue") => ("the line's caption", line_caption(d)?),
b"Line" | b"PolyLine" | b"Polygon" => ("the measurement label", text(b"PCMeasureValue")?),
b"Stamp" if matches!(d.get(b"PCStamp"), Some(Object::Bool(true))) => ("the stamp's \"By\" line", text(b"PCByLine")?),
// Drawn in Helvetica when the redaction is applied: refused when it is marked.
@@ -307,6 +327,55 @@ pub fn undrawable_text(d: &Dict) -> Option<(&'static str, char)> {
Some((what, first_undrawable(&text)?))
}
+/// `/Font` resources naming `/Helv`: standard Helvetica with WinAnsiEncoding.
+fn helvetica_resource() -> Object {
+ let mut font = Dict::new();
+ font.set(b"Type".to_vec(), Object::name("Font"));
+ font.set(b"Subtype".to_vec(), Object::name("Type1"));
+ font.set(b"BaseFont".to_vec(), Object::name("Helvetica"));
+ font.set(b"Encoding".to_vec(), Object::name("WinAnsiEncoding"));
+ let mut fonts = Dict::new();
+ fonts.set(b"Helv".to_vec(), Object::Dict(font));
+ Object::Dict(fonts)
+}
+
+/// Where a caret and its paragraph symbol go within `rect`: the box the caret is drawn in, and for
+/// `/Sy /P` the symbol's baseline origin and font size (ISO 32000-2 Table 183).
+///
+/// The caret lies within `/Rect` less `/RD` (left, top, right, bottom), when `/RD` is four finite,
+/// non-negative numbers that leave a box; otherwise within `/Rect`. The ¶ sits to the right of the
+/// caret, its height a little over half the caret's, in the room `/RD` leaves on the right; when
+/// that is too narrow, the caret gives up to half its width and the symbol shrinks to what is left,
+/// so both stay inside `/Rect` (the form's `/BBox`).
+fn caret_layout(d: &Dict, rect: [f64; 4]) -> ([f64; 4], Option<(f64, f64, f64)>) {
+ let rd = nums(d, b"RD").filter(|r| r.len() == 4 && r.iter().all(|x| x.is_finite() && *x >= 0.0));
+ let mut caret = match rd {
+ Some(rd) => [rect[0] + rd[0], rect[1] + rd[3], rect[2] - rd[2], rect[3] - rd[1]],
+ None => rect,
+ };
+ if !(caret[2] > caret[0] && caret[3] > caret[1]) {
+ caret = rect;
+ }
+ if d.name(b"Sy") != Some(b"P") {
+ return (caret, None);
+ }
+ let size = (caret[3] - caret[1]) * 0.6;
+ let (gap, glyph) = (size * 0.1, text_width("\u{b6}", size));
+ let need = gap + glyph;
+ let room = rect[2] - caret[2];
+ if room < need {
+ caret[2] -= (need - room).min((caret[2] - caret[0]) * 0.5);
+ }
+ let room = rect[2] - caret[2];
+ let scale = if need > room { room / need } else { 1.0 };
+ let size = size * scale;
+ if !(size.is_finite() && size > 0.0) {
+ return (caret, None);
+ }
+ // The pilcrow descends about a sixth of the size below its baseline.
+ (caret, Some((caret[2] + gap * scale, caret[1] + size * 0.18, size)))
+}
+
/// Draw the normal appearance of an annotation, or `None` if this subtype/variant isn't supported.
/// Text the standard fonts can't draw comes out as `?`: [`undrawable_text`] says which, and
/// [`crate::set_appearance`] marks the annotation with it (`pdfcraft_fonts::UNDRAWN_MARK`).
@@ -329,6 +398,8 @@ pub fn build(d: &Dict) -> Option<Stream> {
let w = border_width(d);
let mut res = Dict::new();
let mut c = String::new();
+ // Content after `c` that isn't UTF-8 (WinAnsi text).
+ let mut tail: Vec<u8> = Vec::new();
let markup = matches!(subtype.as_slice(), b"Highlight" | b"Underline" | b"StrikeOut" | b"Squiggly");
if let Some(gs) = ext_gstate(opacity, subtype == b"Highlight") {
res.set(b"ExtGState".to_vec(), Object::Dict(gs));
@@ -458,13 +529,29 @@ pub fn build(d: &Dict) -> Option<Stream> {
return None;
}
let fill = interior_color(d, Some(col)).unwrap_or(col);
+ let layout = line_layout(d, [(l[0], l[1]), (l[2], l[3])], w);
+ let [p, q] = layout.line;
c.push_str(&format!("{}{}{} w 1 J 1 j\n{}", rg_stroke(col), rg(fill), n(w), dash(d)));
- c.push_str(&format!("{} {} m {} {} l S\n[] 0 d\n", n(l[0]), n(l[1]), n(l[2]), n(l[3])));
- for (end, (tip, from)) in ends.iter().zip([((l[0], l[1]), (l[2], l[3])), ((l[2], l[3]), (l[0], l[1]))]) {
+ for [s, e] in layout.leaders.iter().chain(&layout.strokes).chain(&layout.tick) {
+ c.push_str(&format!("{} {} m {} {} l S\n", n(s.0), n(s.1), n(e.0), n(e.1)));
+ }
+ c.push_str("[] 0 d\n");
+ for (end, (tip, from)) in ends.iter().zip([(p, q), (q, p)]) {
if !line_end(&mut c, end, tip, from, w) {
return None;
}
}
+ if let Some((text, m)) = layout.caption {
+ // The caption is black, in the standard font the measurement label uses.
+ tail.extend(
+ format!("q 0 g BT /Helv {} Tf {} {} {} {} {} {} Tm ", n(CAPTION_SIZE), n(m[0]), n(m[1]), n(m[2]), n(m[3]), n(m[4]), n(m[5]))
+ .bytes(),
+ );
+ // WinAnsi bytes go into the stream as-is, not through UTF-8.
+ tail.extend(literal(&win_ansi(&text)));
+ tail.extend_from_slice(b" Tj ET Q\n");
+ res.set(b"Font".to_vec(), helvetica_resource());
+ }
}
b"Polygon" | b"PolyLine" => {
let v = nums(d, b"Vertices").filter(|v| v.len() >= 4 && v.len() % 2 == 0 && v.iter().all(|x| x.is_finite()))?;
@@ -525,7 +612,8 @@ pub fn build(d: &Dict) -> Option<Stream> {
b"Caret" => {
// A filled caret: two curved flanks meeting at the top centre.
let col = stroke.unwrap_or([0.0, 0.47, 0.84]);
- let [x0, y0, x1, y1] = rect;
+ let (caret, pilcrow) = caret_layout(d, rect);
+ let [x0, y0, x1, y1] = caret;
let (cx, h) = ((x0 + x1) / 2.0, y1 - y0);
c.push_str(&format!(
"{}{} {} m {} {} {} {} {} {} c {} {} {} {} {} {} c h f\n",
@@ -545,11 +633,22 @@ pub fn build(d: &Dict) -> Option<Stream> {
n(x1),
n(y0)
));
+ if let Some((x, y, size)) = pilcrow {
+ // `/Sy /P`: a new paragraph symbol beside the caret (Table 183), in its colour.
+ // 0xB6 is the pilcrow in WinAnsiEncoding.
+ let mut out = c.into_bytes();
+ out.extend(format!("BT /Helv {} Tf {} {} Td (", n(size), n(x), n(y)).bytes());
+ out.push(0xB6);
+ out.extend_from_slice(b") Tj ET\n");
+ res.set(b"Font".to_vec(), helvetica_resource());
+ return Some(form(rect, &out, res));
+ }
}
b"Ink" => {
let col = stroke?;
let list = d.get(b"InkList")?.as_array()?;
- c.push_str(&format!("{}{} w 1 J 1 j\n", rg_stroke(col), n(w)));
+ // `/BS` gives an ink stroke its width and dash pattern (Table 182).
+ c.push_str(&format!("{}{} w 1 J 1 j\n{}", rg_stroke(col), n(w), dash(d)));
for s in list {
let pts: Vec<f64> = s.as_array()?.iter().map(|o| o.as_f64()).collect::<Option<_>>()?;
let pts: Vec<(f64, f64)> = pts.as_chunks::<2>().0.iter().map(|p| (p[0], p[1])).collect();
@@ -683,7 +782,8 @@ pub fn build(d: &Dict) -> Option<Stream> {
}
let kind = crate::StampKind::from_name(other)?;
let by = d.get(b"PCByLine").and_then(|o| o.as_string()).map(PdfString::to_text);
- return Some(turned(stamp(kind, draw, stroke.unwrap_or(kind.color()), by.as_deref(), opacity, res)));
+ let sign_here = kind.group() == crate::StampGroup::SignHere;
+ return Some(turned(stamp(kind.label(), sign_here, draw, stroke.unwrap_or(kind.color()), by.as_deref(), opacity, res)));
}
}
if turn != 0 {
@@ -799,14 +899,7 @@ pub fn build(d: &Dict) -> Option<Stream> {
return Some(form(full, &out, res));
}
out.extend_from_slice(b"ET\n");
- let mut font = Dict::new();
- font.set(b"Type".to_vec(), Object::name("Font"));
- font.set(b"Subtype".to_vec(), Object::name("Type1"));
- font.set(b"BaseFont".to_vec(), Object::name("Helvetica"));
- font.set(b"Encoding".to_vec(), Object::name("WinAnsiEncoding"));
- let mut fonts = Dict::new();
- fonts.set(b"Helv".to_vec(), Object::Dict(font));
- res.set(b"Font".to_vec(), Object::Dict(fonts));
+ res.set(b"Font".to_vec(), helvetica_resource());
let mut stream = form(full, &out, res);
if let Some(m) = matrix {
stream.dict.set(b"Matrix".to_vec(), Object::Array(m.iter().copied().map(Object::Real).collect()));
@@ -818,6 +911,7 @@ pub fn build(d: &Dict) -> Option<Stream> {
// PdfCraft measurement captions are kept separate from the comment's free-form text.
// A restyle regenerates the path and its value together.
let mut out = c.into_bytes();
+ out.extend(tail);
if let Some(value) = d.get(b"PCMeasureValue").and_then(Object::as_string) {
let value = value.to_text();
if value.chars().count() <= 256 && matches!(subtype.as_slice(), b"Line" | b"PolyLine" | b"Polygon") {
@@ -829,22 +923,285 @@ pub fn build(d: &Dict) -> Option<Stream> {
// WinAnsi bytes (e.g. 0xB2 for "²") go into the stream as-is, not through UTF-8.
out.extend(literal(&win_ansi(&value)));
out.extend_from_slice(b" Tj ET\n");
- let mut font = Dict::new();
- font.set(b"Type".to_vec(), Object::name("Font"));
- font.set(b"Subtype".to_vec(), Object::name("Type1"));
- font.set(b"BaseFont".to_vec(), Object::name("Helvetica"));
- font.set(b"Encoding".to_vec(), Object::name("WinAnsiEncoding"));
- let mut fonts = Dict::new();
- fonts.set(b"Helv".to_vec(), Object::Dict(font));
- res.set(b"Font".to_vec(), Object::Dict(fonts));
+ res.set(b"Font".to_vec(), helvetica_resource());
}
}
Some(form(rect, &out, res))
}
+/// The label and colour of a standard rubber stamp name (ISO 32000-2 Table 184), for a stamp
+/// another program wrote without an appearance. Names are matched byte for byte, as PDF names
+/// are compared (§7.3.5). Eight are stamps of PdfCraft's palette; the other six take a label of
+/// their own and the palette's colour for their meaning.
+fn standard_stamp(name: &[u8]) -> Option<(&'static str, Rgb)> {
+ use crate::StampKind::*;
+ let palette = [Approved, NotApproved, NotForPublicRelease, Confidential, Final, ForComment, Draft, ForPublicRelease];
+ if let Some(kind) = palette.into_iter().find(|k| k.name().as_bytes() == name) {
+ return Some((kind.label(), kind.color()));
+ }
+ let (label, like) = match name {
+ b"Experimental" => ("EXPERIMENTAL", Draft),
+ b"AsIs" => ("AS IS", Draft),
+ b"Expired" => ("EXPIRED", NotApproved),
+ b"Sold" => ("SOLD", Approved),
+ b"Departmental" => ("DEPARTMENTAL", Draft),
+ b"TopSecret" => ("TOP SECRET", Confidential),
+ _ => return None,
+ };
+ Some((label, like.color()))
+}
+
+/// The neutral grey of a stamp whose name has no drawing.
+const PLACEHOLDER_GREY: Rgb = [0.45, 0.45, 0.45];
+
+/// The display appearance of a rubber stamp another program wrote without one: the stamp its
+/// `/Name` names (Draft when there is none, Table 184's default) in its `/C` colour or the
+/// stamp's own, or for any other name a thin grey frame with both diagonals, so the stamp stays
+/// visible and can be selected. The frame is grey whatever the `/C`: it stands in for a stamp
+/// that cannot be drawn, so it takes none of that stamp's colour. The name is never drawn as text.
+///
+/// For display only ([`crate::with_missing_appearances`]): [`build`] declines these stamps, so
+/// edits (restyling, flattening) never write this drawing into the file. `None` for any other
+/// annotation, one of PdfCraft's own stamps, a dictionary with an `/AP` (a stamp's own artwork is
+/// never replaced; the display copy passes the dictionary without an `/AP` that has no normal
+/// appearance), or a `/Rect` that isn't finite or is under a point wide or high.
+pub(crate) fn display_stamp(d: &Dict) -> Option<Stream> {
+ let own = matches!(d.get(b"PCStamp"), Some(Object::Bool(true))) || d.contains(b"PCPicture") || d.contains(b"PCOutline");
+ if d.name(b"Subtype") != Some(b"Stamp") || own || d.contains(b"AP") {
+ return None;
+ }
+ let rect = nums(d, b"Rect")?;
+ let [a, b, c, e] = rect.as_slice() else { return None };
+ let rect = [a.min(*c), b.min(*e), a.max(*c), b.max(*e)];
+ if !rect.iter().all(|v| v.is_finite()) || rect[2] - rect[0] < 1.0 || rect[3] - rect[1] < 1.0 {
+ return None;
+ }
+ let opacity = d.get(b"CA").and_then(|o| o.as_f64()).unwrap_or(1.0).clamp(0.0, 1.0);
+ // A malformed `/C` falls back to the stamp's own colour rather than hiding the stamp.
+ let stroke = color(d, b"C").flatten();
+ let mut res = Dict::new();
+ if let Some(gs) = ext_gstate(opacity, false) {
+ res.set(b"ExtGState".to_vec(), Object::Dict(gs));
+ }
+ // A stamp whose intent (`/IT`, PDF 2.0) is an image or a snapshot has no `/Name` to default.
+ let stamp_intent = d.name(b"IT").is_none_or(|it| it == b"Stamp");
+ let name = d.name(b"Name").or(stamp_intent.then_some(b"Draft".as_slice()));
+ if let Some((label, col)) = name.and_then(standard_stamp) {
+ return Some(stamp(label, false, rect, stroke.unwrap_or(col), None, opacity, res));
+ }
+ let [x0, y0, x1, y1] = rect;
+ let (a0, b0, a1, b1) = (x0 + 0.5, y0 + 0.5, x1 - 0.5, y1 - 0.5);
+ let mut c = String::new();
+ if opacity < 1.0 {
+ c.push_str("/GS0 gs\n");
+ }
+ c.push_str(&format!(
+ "{}1 w\n{} {} {} {} re\n{} {} m {} {} l\n{} {} m {} {} l\nS\n",
+ // Grey whatever the `/C`: the placeholder is not the stamp, so it takes none of its colour.
+ rg_stroke(PLACEHOLDER_GREY),
+ n(a0),
+ n(b0),
+ n(a1 - a0),
+ n(b1 - b0),
+ n(a0),
+ n(b0),
+ n(a1),
+ n(b1),
+ n(a0),
+ n(b1),
+ n(a1),
+ n(b0)
+ ));
+ Some(form(rect, c.as_bytes(), res))
+}
+
+/// Size of a line's caption, as of a measurement's label.
+const CAPTION_SIZE: f64 = 10.0;
+
+/// Characters of a line's caption drawn at most, as for a measurement's label.
+const MAX_CAPTION_CHARS: usize = 256;
+
+/// Leader lengths and caption offsets (Table 178) are held within this many points (200 inches,
+/// the largest page side ISO 32000-2 Annex C allows), so an absurd value can't overflow.
+const MAX_LINE_EXTENT: f64 = 14_400.0;
+
+/// A Table 178 length or offset: finite and within [`MAX_LINE_EXTENT`], 0 when absent or not one.
+fn line_length(v: Option<f64>) -> f64 {
+ v.filter(|v| v.is_finite()).map_or(0.0, |v| v.clamp(-MAX_LINE_EXTENT, MAX_LINE_EXTENT))
+}
+
+/// The caption a Line with `/Cap true` shows (ISO 32000-2 Table 178): its `/Contents`, else the
+/// plain text of its `/RC`, on one line and cut to [`MAX_CAPTION_CHARS`]. `None` without a
+/// caption, and for PdfCraft's own measurements, whose label (`/PCMeasureValue`) is the caption.
+fn line_caption(d: &Dict) -> Option<String> {
+ if !matches!(d.get(b"Cap"), Some(Object::Bool(true))) || d.contains(b"PCMeasureValue") {
+ return None;
+ }
+ let text = |key: &[u8]| d.get(key).and_then(Object::as_string).map(PdfString::to_text);
+ let raw = text(b"Contents").filter(|t| !t.trim().is_empty()).or_else(|| text(b"RC").map(|rc| rich_plain(&rc)))?;
+ let words: Vec<&str> = raw.split_whitespace().collect();
+ let caption: String = words.join(" ").chars().filter(|c| !c.is_control()).take(MAX_CAPTION_CHARS).collect();
+ (!caption.is_empty()).then_some(caption)
+}
+
+/// The text of rich text (§12.7.4.3, XHTML): its markup dropped, the five XML entities and
+/// numeric character references read, block ends read as spaces.
+fn rich_plain(rc: &str) -> String {
+ let mut out = String::new();
+ let mut tag: Option<String> = None;
+ // Rich text past this is not caption material; it bounds the work.
+ for ch in rc.chars().take(MAX_CAPTION_CHARS * 64) {
+ match (&mut tag, ch) {
+ (None, '<') => tag = Some(String::new()),
+ (Some(name), '>') => {
+ let name =
+ name.trim_start_matches('/').split(|c: char| c.is_whitespace() || c == '/').next().unwrap_or_default().to_ascii_lowercase();
+ if matches!(name.as_str(), "p" | "br" | "div" | "li") {
+ out.push(' ');
+ }
+ tag = None;
+ }
+ (Some(name), c) => {
+ if name.len() < 16 {
+ name.push(c);
+ }
+ }
+ (None, c) => out.push(c),
+ }
+ }
+ let mut text = String::new();
+ let mut rest = out.as_str();
+ while let Some(at) = rest.find('&') {
+ text.push_str(rest.get(..at).unwrap_or_default());
+ let after = rest.get(at + 1..).unwrap_or_default();
+ let entity = after.find(';').filter(|&end| end <= 10).and_then(|end| Some((after.get(..end)?, end)));
+ let decoded = entity.and_then(|(name, end)| {
+ let c = match name {
+ "amp" => '&',
+ "lt" => '<',
+ "gt" => '>',
+ "quot" => '"',
+ "apos" => '\'',
+ _ => {
+ let num = name.strip_prefix('#')?;
+ let code = match num.strip_prefix(['x', 'X']) {
+ Some(hex) => u32::from_str_radix(hex, 16).ok()?,
+ None => num.parse().ok()?,
+ };
+ char::from_u32(code)?
+ }
+ };
+ Some((c, end))
+ });
+ match decoded {
+ Some((c, end)) => {
+ text.push(c);
+ rest = after.get(end + 1..).unwrap_or_default();
+ }
+ None => {
+ text.push('&');
+ rest = after;
+ }
+ }
+ }
+ text.push_str(rest);
+ text
+}
+
+/// Where a Line annotation's parts go (ISO 32000-2 §12.5.6.7, Table 178).
+#[derive(Debug, Default)]
+struct LineLayout {
+ /// The line itself, start to end: `/L`, or `/L` moved out by its leader lines.
+ line: [(f64, f64); 2],
+ /// Strokes along the line: the whole line, or the two pieces either side of an inline caption.
+ strokes: Vec<[(f64, f64); 2]>,
+ /// The leader lines, from `/L` (past the `/LLO` gap) to the line and on by `/LLE`.
+ leaders: Vec<[(f64, f64); 2]>,
+ /// A short stroke from the line to a caption `/CO` moved off it.
+ tick: Option<[(f64, f64); 2]>,
+ /// The caption and its text matrix.
+ caption: Option<(String, [f64; 6])>,
+}
+
+/// Lay out a Line annotation from `/L` = `[a b]`, line width `w`, and its leader and caption
+/// entries.
+///
+/// Leader lines: a positive `/LL` puts the line on the left of travel from `a` to `b` (above `/L`
+/// for a line drawn left to right), so the leader lines, followed from the line to `/L`, turn
+/// clockwise from the direction of travel; a negative one puts it on the right. The line sits
+/// `|LL| + LLO` from `/L`. `/LLE` and `/LLO` are non-negative: a negative one counts as 0.
+///
+/// Caption (`/Cap true`): centred on the line's midpoint and turned with it so it reads left to
+/// right (bottom to top for a vertical line). `/CP /Inline` (the default) centres it on the line,
+/// which is broken around it; `/Top` sets it on top of the unbroken line. `/CO [h v]` moves it `h`
+/// along the line and `v` across it (positive: up in reading direction); a caption moved off an
+/// inline line gets a tick from the line to it.
+///
+/// A zero-length or overflowing `/L` has no direction: it gets neither leader lines nor caption.
+/// Every point is finite; if anything derived from the entries is not, they are left out.
+fn line_layout(d: &Dict, [a, b]: [(f64, f64); 2], w: f64) -> LineLayout {
+ let plain = LineLayout { line: [a, b], strokes: vec![[a, b]], ..LineLayout::default() };
+ let (dx, dy) = (b.0 - a.0, b.1 - a.1);
+ let len = dx.hypot(dy);
+ if !len.is_finite() || len <= 0.0 {
+ return plain;
+ }
+ let (ux, uy) = (dx / len, dy / len);
+ let mut out = LineLayout { line: [a, b], ..LineLayout::default() };
+ let ll = line_length(d.get(b"LL").and_then(Object::as_f64));
+ if ll != 0.0 {
+ // The unit normal from `/L` towards the line: left of travel for a positive /LL.
+ let s = ll.signum();
+ let (nx, ny) = (-uy * s, ux * s);
+ let llo = line_length(d.get(b"LLO").and_then(Object::as_f64)).max(0.0);
+ let lle = line_length(d.get(b"LLE").and_then(Object::as_f64)).max(0.0);
+ let at = |p: (f64, f64), k: f64| (p.0 + nx * k, p.1 + ny * k);
+ let off = ll.abs() + llo;
+ out.line = [at(a, off), at(b, off)];
+ out.leaders = vec![[at(a, llo), at(a, off + lle)], [at(b, llo), at(b, off + lle)]];
+ }
+ let [p, _] = out.line;
+ let along = |t: f64| (p.0 + ux * t, p.1 + uy * t);
+ let mut gap = None;
+ if let Some(text) = line_caption(d) {
+ let size = CAPTION_SIZE;
+ let width = text_width(&text, size);
+ // Reading direction, and "up" across it.
+ let (tx, ty) = if ux < 0.0 || (ux == 0.0 && uy < 0.0) { (-ux, -uy) } else { (ux, uy) };
+ let (vx, vy) = (-ty, tx);
+ let co = nums(d, b"CO").filter(|c| c.len() == 2).unwrap_or_default();
+ let h = line_length(co.first().copied());
+ let v = line_length(co.get(1).copied());
+ let top = d.name(b"CP") == Some(b"Top");
+ // The caption's centre, as a distance along the line from `p`.
+ let centre = len / 2.0 + h * (tx * ux + ty * uy);
+ let mid = along(centre);
+ // Baseline across the line: on top of it, or with the text centred on it.
+ let base = if top { w.max(0.0) / 2.0 + 2.0 + v } else { v - size * 0.35 };
+ let origin = (mid.0 - tx * width / 2.0 + vx * base, mid.1 - ty * width / 2.0 + vy * base);
+ out.caption = Some((text, [tx, ty, -ty, tx, origin.0, origin.1]));
+ if !top && v.abs() < size / 2.0 {
+ let half = width / 2.0 + 2.0;
+ gap = Some(((centre - half).clamp(0.0, len), (centre + half).clamp(0.0, len)));
+ } else if !top {
+ let reach = v - v.signum() * size * 0.4;
+ out.tick = Some([mid, (mid.0 + vx * reach, mid.1 + vy * reach)]);
+ }
+ }
+ out.strokes = match gap {
+ Some((g0, g1)) => [(0.0, g0), (g1, len)].into_iter().filter(|(s, e)| e > s).map(|(s, e)| [along(s), along(e)]).collect(),
+ None => vec![out.line],
+ };
+ let finite = |q: &(f64, f64)| q.0.is_finite() && q.1.is_finite();
+ let all_finite =
+ out.line.iter().chain(out.strokes.iter().flatten()).chain(out.leaders.iter().flatten()).chain(out.tick.iter().flatten()).all(finite)
+ && out.caption.as_ref().is_none_or(|(_, m)| m.iter().all(|x| x.is_finite()));
+ if all_finite { out } else { plain }
+}
+
/// A rubber stamp: a rounded frame (a pointed tag for sign-here stamps) with the label in bold
/// capitals, and the dynamic stamps' "By … at …" line.
-fn stamp(kind: crate::StampKind, rect: [f64; 4], col: Rgb, by: Option<&str>, opacity: f64, mut res: Dict) -> Stream {
+fn stamp(label: &str, sign_here: bool, rect: [f64; 4], col: Rgb, by: Option<&str>, opacity: f64, mut res: Dict) -> Stream {
let [x0, y0, x1, y1] = rect;
let h = y1 - y0;
let mut c = String::new();
@@ -853,7 +1210,7 @@ fn stamp(kind: crate::StampKind, rect: [f64; 4], col: Rgb, by: Option<&str>, opa
}
let lw = (h * 0.07).clamp(1.0, 3.0);
let inset = lw / 2.0 + 0.5;
- if kind.group() == crate::StampGroup::SignHere {
+ if sign_here {
// A tag pointing left, filled, with white text.
let tip = h * 0.45;
c.push_str(&format!(
@@ -919,16 +1276,15 @@ fn stamp(kind: crate::StampKind, rect: [f64; 4], col: Rgb, by: Option<&str>, opa
n(b0)
));
}
- let label = kind.label();
let (title_h, by_h) = if by.is_some() { (h * 0.5, h * 0.22) } else { (h * 0.52, 0.0) };
- let text_area = if kind.group() == crate::StampGroup::SignHere { (x0 + h * 0.45, x1 - lw * 2.0) } else { (x0 + lw * 2.0, x1 - lw * 2.0) };
+ let text_area = if sign_here { (x0 + h * 0.45, x1 - lw * 2.0) } else { (x0 + lw * 2.0, x1 - lw * 2.0) };
let mut size = title_h;
let tw = text_width(label, size) * 1.12;
if tw > text_area.1 - text_area.0 - 4.0 {
size *= (text_area.1 - text_area.0 - 4.0) / tw;
}
let tw = text_width(label, size) * 1.12;
- let text_col = if kind.group() == crate::StampGroup::SignHere { [1.0, 1.0, 1.0] } else { col };
+ let text_col = if sign_here { [1.0, 1.0, 1.0] } else { col };
let ty = if by.is_some() { y0 + h * 0.48 } else { y0 + (h - size * 0.72) / 2.0 };
let mut out = c.into_bytes();
out.extend(
@@ -1010,14 +1366,107 @@ fn sound_icon(col: Rgb) -> String {
s
}
+/// A closed circle path (four Bézier quarters) centred on (`x`, `y`).
+fn circle_path(x: f64, y: f64, r: f64) -> String {
+ let k = r * 0.5523;
+ let p = |v: f64| n(v);
+ format!(
+ "{} {} m {} {} {} {} {} {} c {} {} {} {} {} {} c {} {} {} {} {} {} c {} {} {} {} {} {} c h\n",
+ p(x + r),
+ p(y),
+ p(x + r),
+ p(y + k),
+ p(x + k),
+ p(y + r),
+ p(x),
+ p(y + r),
+ p(x - k),
+ p(y + r),
+ p(x - r),
+ p(y + k),
+ p(x - r),
+ p(y),
+ p(x - r),
+ p(y - k),
+ p(x - k),
+ p(y - r),
+ p(x),
+ p(y - r),
+ p(x + k),
+ p(y - r),
+ p(x + r),
+ p(y - k),
+ p(x + r),
+ p(y)
+ )
+}
+
+/// A note's icon in a 20 × 20 box: filled in `col`, outlined in dark grey. Each name of
+/// [`crate::NoteIcon`] has its own shape, so the icon a note names is the one it shows (ISO
+/// 32000-2 §12.5.6.4, Table 175); a name PdfCraft doesn't know draws as `Note`.
fn note_icon(name: &str, col: Rgb) -> String {
let mut s = format!("{}0.25 0.25 0.25 RG 0.8 w 1 j 1 J\n", rg(col));
- if name == "Comment" {
- s.push_str("3 18.5 m 17 18.5 l 18.5 18.5 18.5 17 18.5 17 c 18.5 8 l 18.5 6.5 17 6.5 17 6.5 c 9.5 6.5 l 5 2 l 5.5 6.5 l 3 6.5 l 1.5 6.5 1.5 8 1.5 8 c 1.5 17 l 1.5 18.5 3 18.5 3 18.5 c h B\n");
- s.push_str("4.5 15 m 15.5 15 l 4.5 12.5 m 15.5 12.5 l 4.5 10 m 11.5 10 l S\n");
- } else {
- s.push_str("3 19 m 13 19 l 17 15 l 17 1 l 3 1 l h B\n13 19 m 13 15 l 17 15 l S\n");
- s.push_str("5.5 12 m 14.5 12 l 5.5 9 m 14.5 9 l 5.5 6 m 11.5 6 l S\n");
+ match name {
+ "Comment" => {
+ s.push_str("3 18.5 m 17 18.5 l 18.5 18.5 18.5 17 18.5 17 c 18.5 8 l 18.5 6.5 17 6.5 17 6.5 c 9.5 6.5 l 5 2 l 5.5 6.5 l 3 6.5 l 1.5 6.5 1.5 8 1.5 8 c 1.5 17 l 1.5 18.5 3 18.5 3 18.5 c h B\n");
+ s.push_str("4.5 15 m 15.5 15 l 4.5 12.5 m 15.5 12.5 l 4.5 10 m 11.5 10 l S\n");
+ }
+ // A key lying flat: a round bow with a hole, a shaft and two bits.
+ "Key" => {
+ s.push_str(&circle_path(5.5, 10.0, 4.5));
+ s.push_str(&circle_path(5.0, 10.0, 1.5));
+ s.push_str(
+ "9.5 11.2 m 18.5 11.2 l 18.5 8.8 l 17 8.8 l 17 6 l 15 6 l 15 8.8 l 13.5 8.8 l 13.5 6.8 l 11.5 6.8 l 11.5 8.8 l 9.5 8.8 l h B*\n",
+ );
+ }
+ // A disc with a question mark.
+ "Help" => {
+ s.push_str(&circle_path(10.0, 10.0, 8.5));
+ s.push_str("B\n1.6 w 7 12.8 m 7 15.6 13 15.6 13 12.8 c 13 10.6 10 10.8 10 8.2 c S\n10 5 m 10 5.1 l S\n");
+ }
+ // An insertion caret.
+ "Insert" => s.push_str("1.5 3 m 10 18 l 18.5 3 l 14.5 3 l 10 11 l 5.5 3 l h B\n"),
+ // A caret over a bar: a new paragraph goes here.
+ "NewParagraph" => s.push_str("3.5 9 m 10 18.5 l 16.5 9 l h B\n3 2 14 4 re B\n"),
+ // A pilcrow: a filled bowl and two stems.
+ "Paragraph" => {
+ s.push_str("11 18.5 m 7 18.5 4 16.3 4 13.2 c 4 10.1 7 8 11 8 c h B\n");
+ s.push_str("11 18.5 m 16 18.5 l 16 1.5 l 14 1.5 l 14 16.5 l 13 16.5 l 13 1.5 l 11 1.5 l h B\n");
+ }
+ // A tick.
+ "Check" => s.push_str("1.5 10.5 m 4.5 13.5 l 8 9.5 l 16 18.5 l 18.5 15.5 l 8 3.5 l h B\n"),
+ // A ring.
+ "Circle" => {
+ s.push_str(&circle_path(10.0, 10.0, 8.5));
+ s.push_str(&circle_path(10.0, 10.0, 5.0));
+ s.push_str("B*\n");
+ }
+ // A thick X.
+ "Cross" => s.push_str("4 1.5 m 10 7.5 l 16 1.5 l 18.5 4 l 12.5 10 l 18.5 16 l 16 18.5 l 10 12.5 l 4 18.5 l 1.5 16 l 7.5 10 l 1.5 4 l h B\n"),
+ // A ring with sighting lines through it.
+ "CrossHairs" => {
+ s.push_str(&circle_path(10.0, 10.0, 7.0));
+ s.push_str(&circle_path(10.0, 10.0, 4.5));
+ s.push_str("B*\n1.2 w 10 0.5 m 10 19.5 l 0.5 10 m 19.5 10 l S\n");
+ }
+ // A five-pointed star.
+ "Star" => {
+ let points: Vec<String> = (0..10)
+ .map(|i| {
+ let r = if i % 2 == 0 { 9.5 } else { 3.9 };
+ let a = std::f64::consts::FRAC_PI_2 + f64::from(i) * std::f64::consts::PI / 5.0;
+ format!("{} {}", n(10.0 + r * a.cos()), n(9.5 + r * a.sin()))
+ })
+ .collect();
+ s.push_str(&format!("{} m {} l h B\n", points[0], points[1..].join(" l ")));
+ }
+ // Block arrows.
+ "RightArrow" => s.push_str("1.5 7 m 11 7 l 11 2.5 l 18.5 10 l 11 17.5 l 11 13 l 1.5 13 l h B\n"),
+ "UpArrow" => s.push_str("7 1.5 m 7 11 l 2.5 11 l 10 18.5 l 17.5 11 l 13 11 l 13 1.5 l h B\n"),
+ _ => {
+ s.push_str("3 19 m 13 19 l 17 15 l 17 1 l 3 1 l h B\n13 19 m 13 15 l 17 15 l S\n");
+ s.push_str("5.5 12 m 14.5 12 l 5.5 9 m 14.5 9 l 5.5 6 m 11.5 6 l S\n");
+ }
}
s
}
diff --git a/crates/annot/src/lib.rs b/crates/annot/src/lib.rs
index 42e437b..d9b0a5f 100644
--- a/crates/annot/src/lib.rs
+++ b/crates/annot/src/lib.rs
@@ -14,6 +14,8 @@
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
+use std::collections::{HashMap, HashSet};
+
use pdfcraft_cos::{Dict, Document, ObjRef, Object, PdfString, Stream};
pub mod appearance;
@@ -66,7 +68,9 @@ impl Markup {
}
}
-/// The standard text-annotation icon names (§12.5.6.4, Table 175).
+/// Text-annotation icon names (`/Name`). The first seven are the standard names ISO 32000-2
+/// §12.5.6.4, Table 175 asks every viewer to draw; the rest are further names in common use, which
+/// the same table allows ("Additional names may be supported as well").
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum NoteIcon {
#[default]
@@ -77,6 +81,13 @@ pub enum NoteIcon {
Key,
NewParagraph,
Paragraph,
+ Check,
+ Circle,
+ Cross,
+ CrossHairs,
+ Star,
+ RightArrow,
+ UpArrow,
}
impl NoteIcon {
@@ -89,11 +100,36 @@ impl NoteIcon {
NoteIcon::Key => "Key",
NoteIcon::NewParagraph => "NewParagraph",
NoteIcon::Paragraph => "Paragraph",
- }
- }
+ NoteIcon::Check => "Check",
+ NoteIcon::Circle => "Circle",
+ NoteIcon::Cross => "Cross",
+ NoteIcon::CrossHairs => "CrossHairs",
+ NoteIcon::Star => "Star",
+ NoteIcon::RightArrow => "RightArrow",
+ NoteIcon::UpArrow => "UpArrow",
+ }
+ }
+
+ /// Every icon, the standard names first.
+ pub const ALL: [NoteIcon; 14] = [
+ Self::Comment,
+ Self::Note,
+ Self::Help,
+ Self::Insert,
+ Self::Key,
+ Self::NewParagraph,
+ Self::Paragraph,
+ Self::Check,
+ Self::Circle,
+ Self::Cross,
+ Self::CrossHairs,
+ Self::Star,
+ Self::RightArrow,
+ Self::UpArrow,
+ ];
pub fn from_name(n: &str) -> Option<Self> {
- [Self::Comment, Self::Note, Self::Help, Self::Insert, Self::Key, Self::NewParagraph, Self::Paragraph].into_iter().find(|i| i.name() == n)
+ Self::ALL.into_iter().find(|i| i.name() == n)
}
}
@@ -750,8 +786,9 @@ thread_local! {
static ANNOTS_ENTRIES_COPIED: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
-/// Replace a page's `/Annots`, writing into the shared array object when it is indirect.
-fn set_annots(doc: &mut Document, page: ObjRef, list: Vec<Object>) -> Result<(), AnnotError> {
+/// Replace a page's `/Annots`, writing into the shared array object when it is indirect. An empty
+/// list removes a direct `/Annots`.
+pub fn set_annots(doc: &mut Document, page: ObjRef, list: Vec<Object>) -> Result<(), pdfcraft_cos::CosError> {
let existing = doc.get(page).as_dict().and_then(|d| d.reference(b"Annots"));
match existing {
Some(r) if doc.get(r).as_array().is_some() => doc.set(r, Object::Array(list)),
@@ -818,6 +855,17 @@ fn annotation_flags(doc: &Document, d: &Dict) -> i64 {
d.get(b"F").and_then(|f| doc.resolve(f).as_int()).unwrap_or(0)
}
+/// Whether the renderer keeps the annotation upright on a turned page: the NoRotate flag, with
+/// `/F` read as the renderer reads it (a real truncated, a value that isn't a `u32` no flags).
+fn drawn_upright(doc: &Document, d: &Dict) -> bool {
+ let f = match d.get(b"F").map(|f| doc.resolve(f)).as_deref() {
+ Some(Object::Int(i)) => *i,
+ Some(Object::Real(r)) => *r as i64,
+ _ => 0,
+ };
+ u32::try_from(f).is_ok_and(|f| i64::from(f) & FLAG_NO_ROTATE != 0)
+}
+
/// Whether any page has a Fill & Sign annotation that flatten would bake in (not hidden).
pub fn has_visible_fill_sign(doc: &Document) -> bool {
let Ok(pages) = page_refs(doc) else { return false };
@@ -986,7 +1034,7 @@ fn rect_for(shape: &Shape, style: &Style) -> Result<[f64; 4], AnnotError> {
grow(bounds([*from, *to].into_iter()).unwrap_or_default(), pad + 1.0)
}
Shape::Ink { strokes } | Shape::Signature { strokes } => {
- if strokes.iter().all(|s| s.is_empty()) || !strokes.iter().flatten().all(|p| finite(p)) {
+ if strokes.iter().all(Vec::is_empty) || !strokes.iter().flatten().all(|p| finite(p)) {
return Err(bad("drawing (no points)"));
}
// Strokes of three or more points are drawn as curves, which stay within their
@@ -1198,7 +1246,7 @@ pub fn add_annotation(doc: &mut Document, new: &NewAnnotation, meta: &Meta) -> R
d.set(b"PCOutline".to_vec(), Object::Array(list));
}
Shape::CustomStamp { name, picture, image, size, .. } => {
- let clean: String = name.chars().filter(|c| c.is_ascii_alphanumeric()).collect();
+ let clean: String = name.chars().filter(char::is_ascii_alphanumeric).collect();
d.set(b"Name".to_vec(), Object::name(&format!("PCCustom{clean}")));
d.set(b"PCPicture".to_vec(), Object::Ref(*picture));
d.set(b"PCPictureImage".to_vec(), Object::Bool(*image));
@@ -1582,7 +1630,14 @@ pub fn with_missing_appearances_cached(doc: &Document, cache: &mut AppearanceCac
apply_appearance(copy.get_or_insert_with(|| doc.clone()), r, &d, stream).ok();
continue;
}
- let Some(stream) = build_appearance(doc, &d) else { continue };
+ // Another program's stamp gets a drawing for display only (ISO 32000-2 Table 184). Its
+ // `/AP`, if any, has no `/N` to keep here.
+ let other_stamp = || {
+ let mut bare = d.clone();
+ bare.remove(b"AP");
+ appearance::display_stamp(&bare)
+ };
+ let Some(stream) = build_appearance(doc, &d).or_else(other_stamp) else { continue };
cache.insert(r, &stream);
// Fails only when `r` isn't a dictionary, which the build just ruled out.
apply_appearance(copy.get_or_insert_with(|| doc.clone()), r, &d, stream).ok();
@@ -1643,36 +1698,52 @@ pub fn delete_annotation(doc: &mut Document, page: usize, index: usize) -> Resul
if let Some(r) = target.as_ref() {
unlocked(doc, r)?;
}
- let mut doomed: Vec<ObjRef> = target.as_ref().into_iter().collect();
- // Replies (`/IRT`) and pop-ups (`/Parent`) of anything doomed, to a fixpoint.
- loop {
- let before = doomed.len();
- for e in &list {
- let Some(r) = e.as_ref() else { continue };
- if doomed.contains(&r) {
- continue;
- }
- let obj = doc.get(r);
- let Some(d) = obj.as_dict() else { continue };
- let points_at = |k: &[u8]| d.reference(k).is_some_and(|t| doomed.contains(&t));
- if points_at(b"IRT") || points_at(b"Parent") {
- doomed.push(r);
- }
- }
- for r in doomed.clone() {
- if let Some(pop) = doc.get(r).as_dict().and_then(|d| d.reference(b"Popup"))
- && !doomed.contains(&pop)
- {
- doomed.push(pop);
- }
+ // An inline comment has no reference to collect; the pop-up it names still goes.
+ let seed = target.as_ref().or_else(|| target.as_dict().and_then(|d| d.reference(b"Popup")));
+ let doomed = with_replies_and_popups(doc, &list, seed);
+ let kept: Vec<Object> = list.into_iter().enumerate().filter(|(i, e)| *i != index && !goes_with(e, &doomed)).map(|(_, e)| e).collect();
+ Ok(set_annots(doc, p, kept)?)
+}
+
+/// Whether the `/Annots` entry `entry` goes with `going` (from [`with_replies_and_popups`]): it is
+/// one of them, or it is written inline (a file can, though the standard asks for references) and
+/// replies to (`/IRT`) or pops up for (`/Parent`) one of them. An inline entry has no reference
+/// for the walk to collect, so it is matched here.
+pub fn goes_with(entry: &Object, going: &HashSet<ObjRef>) -> bool {
+ match entry.as_ref() {
+ Some(r) => going.contains(&r),
+ None => entry.as_dict().is_some_and(|d| [d.reference(b"IRT"), d.reference(b"Parent")].into_iter().flatten().any(|r| going.contains(&r))),
+ }
+}
+
+/// `doomed` and what goes with it, as Acrobat deletes a comment: the entries of `list` (one or
+/// more pages' `/Annots`) that reply to (`/IRT`) or pop up for (`/Parent`) anything going, their
+/// own replies, and the pop-ups going annotations name (`/Popup`). An inline reply has no
+/// reference to collect, but the pop-up it names is. Each annotation is visited once, so a long or
+/// cyclic chain costs no more than its length. Filter a list with [`goes_with`], which also
+/// matches inline entries.
+pub fn with_replies_and_popups(doc: &Document, list: &[Object], doomed: impl IntoIterator<Item = ObjRef>) -> HashSet<ObjRef> {
+ let mut hanging: HashMap<ObjRef, Vec<ObjRef>> = HashMap::new();
+ for e in list {
+ let obj = doc.resolve(e);
+ let Some(d) = obj.as_dict() else { continue };
+ // What goes with the annotation this entry hangs off: the entry, or for an inline one the
+ // pop-up it names.
+ let Some(goes) = e.as_ref().or_else(|| d.reference(b"Popup")) else { continue };
+ for on in [d.reference(b"IRT"), d.reference(b"Parent")].into_iter().flatten() {
+ hanging.entry(on).or_default().push(goes);
}
- if doomed.len() == before {
- break;
+ }
+ let mut going = HashSet::new();
+ let mut todo: Vec<ObjRef> = doomed.into_iter().collect();
+ while let Some(r) = todo.pop() {
+ if !going.insert(r) {
+ continue;
}
+ todo.extend(hanging.get(&r).into_iter().flatten());
+ todo.extend(doc.get(r).as_dict().and_then(|d| d.reference(b"Popup")));
}
- let kept: Vec<Object> =
- list.into_iter().enumerate().filter(|(i, e)| *i != index && !e.as_ref().is_some_and(|r| doomed.contains(&r))).map(|(_, e)| e).collect();
- set_annots(doc, p, kept)
+ going
}
/// Change a comment's text. Text boxes are redrawn to show it, and their rectangle follows the
@@ -2252,6 +2323,10 @@ pub struct Summary {
pub modified: Option<String>,
pub name: Option<String>,
pub in_reply_to: Option<String>,
+ /// The page and `/Annots` position `/IRT` points at, by reference (`/NM` need not be unique).
+ pub parent: Option<(usize, usize)>,
+ /// `/RT /Group`: grouped with the `/IRT` annotation (Replace Text's caret), not a reply to it.
+ pub grouped: bool,
pub rect: [f32; 4],
pub color: Option<[f32; 3]>,
pub state: Option<String>,
@@ -2264,6 +2339,8 @@ pub struct Summary {
pub opacity: f32,
/// The line width in points: `/BS /W`, else the third number of `/Border`.
pub width: Option<f32>,
+ /// The NoRotate flag (`/F` bit 5), as `pdfcraft_render::Annotation::no_rotate`.
+ pub no_rotate: bool,
/// A line's two ends (`/L`), or the corners of connected lines, a polygon or a cloud
/// (`/Vertices`), in user space; empty for other comments.
pub points: Vec<[f32; 2]>,
@@ -2287,13 +2364,35 @@ pub fn is_comment_subtype(subtype: &str) -> bool {
!matches!(subtype, "Link" | "Widget" | "Popup" | "Screen" | "Movie" | "RichMedia" | "3D" | "PrinterMark" | "TrapNet" | "Watermark")
}
+/// Where a reference to a reference (`5 0 obj 6 0 R endobj`) ends, as `pdfcraft_render::inspect`
+/// follows it, within a few steps (a cycle stops there).
+fn final_ref(doc: &Document, mut r: ObjRef) -> ObjRef {
+ for _ in 0..8 {
+ match &*doc.get(r) {
+ Object::Ref(next) => r = *next,
+ _ => break,
+ }
+ }
+ r
+}
+
/// Every comment (see [`is_comment_subtype`]), ordered by page and then top edge.
pub fn summaries(doc: &Document) -> Vec<Summary> {
let mut out = Vec::new();
let Ok(pages) = page_refs(doc) else { return out };
- for (page, p) in pages.iter().enumerate() {
- for (index, entry) in annots(doc, *p).iter().enumerate() {
- let obj = doc.resolve(entry);
+ let lists: Vec<Vec<Object>> = pages.iter().map(|p| annots(doc, *p)).collect();
+ // Where each annotation is first listed, so a reply's `/IRT` finds its parent by reference.
+ let mut slots: std::collections::HashMap<ObjRef, (usize, usize)> = std::collections::HashMap::new();
+ for (page, list) in lists.iter().enumerate() {
+ for (index, entry) in list.iter().enumerate() {
+ if let Some(r) = entry.as_ref() {
+ slots.entry(final_ref(doc, r)).or_insert((page, index));
+ }
+ }
+ }
+ for (page, list) in lists.iter().enumerate() {
+ for (index, entry) in list.iter().enumerate() {
+ let obj = entry.as_ref().map_or_else(|| doc.resolve(entry), |r| doc.get(final_ref(doc, r)));
let Some(d) = obj.as_dict() else { continue };
let Some(subtype) = d.name(b"Subtype").map(|s| String::from_utf8_lossy(s).into_owned()) else { continue };
if !is_comment_subtype(&subtype) {
@@ -2327,7 +2426,9 @@ pub fn summaries(doc: &Document) -> Vec<Summary> {
"PolyLine" | "Polygon" => nums(b"Vertices").as_chunks::<2>().0.to_vec(),
_ => Vec::new(),
};
- let in_reply_to = d.get(b"IRT").map(|o| doc.resolve(o)).and_then(|o| o.as_dict().cloned()).and_then(|p| text_value(doc, &p, b"NM"));
+ let irt = d.get(b"IRT").map(|o| o.as_ref().map_or_else(|| doc.resolve(o), |r| doc.get(final_ref(doc, r))));
+ let in_reply_to = irt.and_then(|o| o.as_dict().cloned()).and_then(|p| text_value(doc, &p, b"NM"));
+ let parent = d.get(b"IRT").and_then(Object::as_ref).and_then(|r| slots.get(&final_ref(doc, r)).copied());
// keep in step with `pdfcraft_render::inspect`
let opacity = d.get(b"CA").and_then(|o| doc.resolve(o).as_f64()).filter(|v| v.is_finite()).map_or(1.0, |v| v.clamp(0.0, 1.0) as f32);
let width = d
@@ -2348,6 +2449,8 @@ pub fn summaries(doc: &Document) -> Vec<Summary> {
modified: text_value(doc, d, b"M"),
name: text_value(doc, d, b"NM"),
in_reply_to,
+ parent,
+ grouped: d.name(b"RT") == Some(b"Group"),
rect,
color,
state: text_value(doc, d, b"State"),
@@ -2357,6 +2460,7 @@ pub fn summaries(doc: &Document) -> Vec<Summary> {
fill_sign: is_fill_sign(doc, d),
opacity,
width,
+ no_rotate: drawn_upright(doc, d),
points,
});
}
diff --git a/crates/annot/src/links.rs b/crates/annot/src/links.rs
index 53c31d8..7cf4328 100644
--- a/crates/annot/src/links.rs
+++ b/crates/annot/src/links.rs
@@ -320,7 +320,7 @@ pub fn delete(doc: &mut Document, page: usize, index: usize) -> Result<(), Annot
let (p, _) = link_at(doc, page, index)?;
let mut list = annots(doc, p);
list.remove(index);
- set_annots(doc, p, list)
+ Ok(set_annots(doc, p, list)?)
}
/// Remove every link on `pages` (all when `None`). Returns how many went.
diff --git a/crates/annot/src/tests.rs b/crates/annot/src/tests.rs
index a7fd303..19d60fa 100644
--- a/crates/annot/src/tests.rs
+++ b/crates/annot/src/tests.rs
@@ -229,6 +229,47 @@ fn delete_takes_popup_and_reply_chain() {
assert_eq!(delete_annotation(&mut doc, 0, 9), Err(AnnotError::NoSuchAnnotation { page: 0, index: 9 }));
}
+/// A reply or pop-up written inline in `/Annots` (a file can, though the standard asks for
+/// references) goes with the comment it points at, and so does a pop-up an inline reply or an
+/// inline comment names. An unrelated inline comment stays until it is deleted itself.
+#[test]
+fn delete_takes_inline_replies_and_popups() {
+ let mut doc = fixture();
+ let mut popup = |note: &str| {
+ let mut d = Dict::new();
+ d.set(b"Type".to_vec(), Object::name("Annot"));
+ d.set(b"Subtype".to_vec(), Object::name("Popup"));
+ d.set(b"Contents".to_vec(), PdfString::text(note));
+ doc.add(Object::Dict(d))
+ };
+ let (reply_popup, square_popup) = (popup("of the reply"), popup("of the square"));
+ let inline = |subtype: &str, links: &[(&[u8], ObjRef)]| {
+ let mut d = Dict::new();
+ d.set(b"Type".to_vec(), Object::name("Annot"));
+ d.set(b"Subtype".to_vec(), Object::name(subtype));
+ links.iter().for_each(|(key, r)| d.set(key.to_vec(), Object::Ref(*r)));
+ Object::Dict(d)
+ };
+ let stamp = ObjRef::new(6, 0);
+ let entries = vec![
+ Object::Ref(stamp),
+ inline("Text", &[(b"IRT", stamp), (b"Popup", reply_popup)]),
+ Object::Ref(reply_popup),
+ inline("Popup", &[(b"Parent", stamp)]),
+ inline("Square", &[(b"Popup", square_popup)]),
+ Object::Ref(square_popup),
+ ];
+ doc.set(ObjRef::new(5, 0), Object::Array(entries));
+ let subtypes = |doc: &Document| -> Vec<String> {
+ list(doc, 1).iter().map(|d| String::from_utf8_lossy(d.name(b"Subtype").unwrap()).into_owned() + ":" + &text(d, b"Contents")).collect()
+ };
+ delete_annotation(&mut doc, 1, 0).unwrap();
+ let mut doc = reopen(&doc);
+ assert_eq!(subtypes(&doc), ["Square:", "Popup:of the square"]);
+ delete_annotation(&mut doc, 1, 0).unwrap();
+ assert!(subtypes(&reopen(&doc)).is_empty(), "the inline comment's pop-up went with it");
+}
+
#[test]
fn deleting_the_last_comment_removes_annots() {
let mut doc = fixture();
@@ -1014,6 +1055,89 @@ fn a_note_without_an_appearance_is_shown_at_icon_size() {
assert_eq!(rects(&doc), original, "the source document is unchanged");
}
+/// The fourteen rubber stamp names viewers draw without an appearance (ISO 32000-2 Table 184).
+const TABLE_184_STAMPS: [(&str, &str); 14] = [
+ ("Approved", "APPROVED"),
+ ("Experimental", "EXPERIMENTAL"),
+ ("NotApproved", "NOT APPROVED"),
+ ("AsIs", "AS IS"),
+ ("Expired", "EXPIRED"),
+ ("NotForPublicRelease", "NOT FOR PUBLIC RELEASE"),
+ ("Confidential", "CONFIDENTIAL"),
+ ("Final", "FINAL"),
+ ("Sold", "SOLD"),
+ ("Departmental", "DEPARTMENTAL"),
+ ("ForComment", "FOR COMMENT"),
+ ("TopSecret", "TOP SECRET"),
+ ("Draft", "DRAFT"),
+ ("ForPublicRelease", "FOR PUBLIC RELEASE"),
+];
+
+fn stamp_dict(extra: &str) -> Dict {
+ let doc = document_of(&[
+ b"<< /Type /Catalog /Pages 2 0 R >>",
+ b"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 612 792] >>",
+ b"<< /Type /Page /Parent 2 0 R /Annots [4 0 R] >>",
+ format!("<< /Type /Annot /Subtype /Stamp /Rect [20 40 140 100] {extra} >>").as_bytes(),
+ ]);
+ list(&doc, 0).remove(0)
+}
+
+fn drawn(d: &Dict) -> String {
+ String::from_utf8_lossy(&appearance::display_stamp(d).expect("a stamp is drawn").decoded().unwrap()).into_owned()
+}
+
+/// A stamp another program wrote without an appearance draws the stamp its `/Name` names, Draft
+/// when it has none, and a frame with both diagonals for any other name, never the name itself.
+#[test]
+fn a_stamp_without_an_appearance_draws_the_stamp_it_names() {
+ for (name, label) in TABLE_184_STAMPS {
+ let content = drawn(&stamp_dict(&format!("/Name /{name}")));
+ assert!(content.contains(&format!("({label}) Tj")), "{name}: {content}");
+ }
+ assert!(drawn(&stamp_dict("")).contains("(DRAFT) Tj"), "Table 184's default");
+ assert!(drawn(&stamp_dict("/IT /Stamp")).contains("(DRAFT) Tj"), "a stamp intent keeps the default");
+ // Any other name, a name in another case (names are compared byte for byte, §7.3.5), and an
+ // image stamp (`/IT`, which has no `/Name` to default): the frame and its diagonals.
+ for extra in ["/Name /MyCustomStamp", "/Name /draft", "/Name /APPROVED", "/IT /StampImage", "/Name /PCVoid"] {
+ let content = drawn(&stamp_dict(extra));
+ assert!(!content.contains("Tj") && content.contains(" re\n") && content.matches(" l\n").count() == 2, "{extra}: {content}");
+ }
+ // `/C` colours the stamp, as it does PdfCraft's own.
+ assert!(drawn(&stamp_dict("/Name /Final /C [1 0 1]")).contains("1 0 1 RG"));
+ // The placeholder stays grey whatever the `/C`: it is not the stamp, so it takes none of its colour.
+ let placeholder = drawn(&stamp_dict("/Name /MyCustomStamp /C [1 0 0]"));
+ assert!(placeholder.contains("0.45 0.45 0.45 RG") && !placeholder.contains("1 0 0 RG"), "{placeholder}");
+ // A stamp's own artwork is never replaced, and the drawing is for display only: edits
+ // (restyling, flattening) still find nothing they may write.
+ assert!(appearance::display_stamp(&stamp_dict("/Name /Draft /AP << /N 9 0 R >>")).is_none());
+ assert!(appearance::build(&stamp_dict("/Name /Draft")).is_none());
+ assert!(appearance::display_stamp(&stamp_dict("/Name /Draft /PCStamp true")).is_none(), "PdfCraft's own stamps are drawn by `build`");
+ assert!(appearance::display_stamp(&stamp_dict("/Name /Draft /Rect [5 5 5 50]")).is_none(), "no width");
+}
+
+/// The display copy draws a stamp that has no normal appearance, and keeps one that has.
+#[test]
+fn the_display_copy_draws_stamps_without_a_normal_appearance_only() {
+ let doc = document_of(&[
+ b"<< /Type /Catalog /Pages 2 0 R >>",
+ b"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 612 792] >>",
+ b"<< /Type /Page /Parent 2 0 R /Annots [4 0 R 5 0 R 6 0 R 7 0 R] >>",
+ b"<< /Type /Annot /Subtype /Stamp /Rect [20 40 140 100] /Name /TopSecret >>",
+ b"<< /Type /Annot /Subtype /Stamp /Rect [20 140 140 200] /Name /Draft /AP << /N 8 0 R >> >>",
+ b"<< /Type /Annot /Subtype /Stamp /Rect [20 240 140 300] /Name /Sold /AP << /D 8 0 R >> >>",
+ b"<< /Type /Annot /Subtype /Stamp /Rect [20 340 140 400] /Name /Unheard >>",
+ b"<< /Type /XObject /Subtype /Form /BBox [0 0 10 10] /Length 8 >>\nstream\n1 0 0 rg\nendstream",
+ ]);
+ let display = with_missing_appearances(&doc).expect("three stamps need an appearance");
+ let shown = list(&display, 0);
+ assert!(ap_content(&display, &shown[0]).contains("(TOP SECRET) Tj"));
+ assert_eq!(shown[1].get(b"AP"), list(&doc, 0)[1].get(b"AP"), "an existing appearance is kept");
+ assert!(ap_content(&display, &shown[2]).contains("(SOLD) Tj"), "an /AP without /N has nothing to keep");
+ assert!(!ap_content(&display, &shown[3]).contains("Tj"), "an unknown name gets the placeholder");
+ assert!(list(&doc, 0)[0].get(b"AP").is_none(), "the document itself is untouched");
+}
+
#[test]
fn every_line_ending_is_drawn() {
let filled = [LineEnding::Square, LineEnding::Circle, LineEnding::Diamond, LineEnding::ClosedArrow, LineEnding::RClosedArrow];
@@ -1351,9 +1475,9 @@ fn cached_appearances_are_reused_while_annotations_are_unchanged() {
.expect("strips");
let mut cache = AppearanceCache::default();
let first = with_missing_appearances_cached(&doc, &mut cache).expect("builds");
- assert_eq!((cache.builds(), cache.hits()), (1, 0), "only the note needs an appearance");
+ assert_eq!((cache.builds(), cache.hits()), (2, 0), "the note and the file's stamp need an appearance");
let second = with_missing_appearances_cached(&doc, &mut cache).expect("reuses");
- assert_eq!((cache.builds(), cache.hits()), (1, 1), "nothing is redrawn");
+ assert_eq!((cache.builds(), cache.hits()), (2, 2), "nothing is redrawn");
let [a, b] = [&first, &second].map(|copy| ap_content(copy, &list(copy, 0)[idx]));
assert!(!a.is_empty());
assert_eq!(a, b, "the reused appearance is byte-identical");
@@ -1673,3 +1797,392 @@ fn cloud_outline_has_a_bump_budget() {
let bumps = appearance::cloud_path(&pts, 1.0).lines().filter(|l| l.ends_with(" c")).count();
assert!((pts.len()..=appearance::MAX_CLOUD_BUMPS + 2 * pts.len()).contains(&bumps), "{bumps} bumps");
}
+
+/// A note's drawn icon (its built appearance's content) for `/Name` (none when `None`) and `/C`.
+fn note_drawing(name: Option<&str>, color: [f64; 3]) -> Vec<u8> {
+ let mut d = Dict::new();
+ d.set(b"Subtype".to_vec(), Object::name("Text"));
+ d.set(b"Rect".to_vec(), Object::Array([0.0, 0.0, 20.0, 20.0].map(Object::Real).to_vec()));
+ d.set(b"C".to_vec(), Object::Array(color.map(Object::Real).to_vec()));
+ if let Some(n) = name {
+ d.set(b"Name".to_vec(), Object::name(n));
+ }
+ crate::appearance::build(&d).expect("a note is drawn").decoded().unwrap()
+}
+
+/// ISO 32000-2 §12.5.6.4, Table 175: a viewer shall provide icons for the seven standard names,
+/// and may support more. Each of the fourteen names PdfCraft offers draws a shape of its own, so
+/// a note shows the icon it names; a name it doesn't know, and a note without one, draw `Note`
+/// (the table's default).
+#[test]
+fn every_note_icon_draws_its_own_shape() {
+ let yellow = [1.0, 0.82, 0.0];
+ let drawn: Vec<Vec<u8>> = NoteIcon::ALL.iter().map(|i| note_drawing(Some(i.name()), yellow)).collect();
+ for (i, a) in drawn.iter().enumerate() {
+ for (j, b) in drawn.iter().enumerate().skip(i + 1) {
+ assert_ne!(a, b, "{} and {} look alike", NoteIcon::ALL[i].name(), NoteIcon::ALL[j].name());
+ }
+ }
+ let note = note_drawing(Some("Note"), yellow);
+ assert_eq!(note_drawing(Some("Sparkle"), yellow), note, "an unknown name");
+ assert_eq!(note_drawing(None, yellow), note, "no name");
+ for icon in NoteIcon::ALL {
+ assert_eq!(NoteIcon::from_name(icon.name()), Some(icon));
+ }
+}
+
+/// A note named with one of the further icons reads as that icon, and a colour change redraws it
+/// as itself, not as a page.
+#[test]
+fn a_star_note_keeps_its_star_when_recoloured() {
+ let mut doc = document_of(&[
+ b"<< /Type /Catalog /Pages 2 0 R >>",
+ b"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 600 600] >>",
+ b"<< /Type /Page /Parent 2 0 R /Annots [4 0 R] >>",
+ b"<< /Type /Annot /Subtype /Text /Rect [100 100 120 120] /Name /Star /C [1 0.82 0] /F 4 >>",
+ ]);
+ assert_eq!(props(&doc, 0, 0).and_then(|p| p.icon), Some(NoteIcon::Star));
+ set_style(&mut doc, 0, 0, Some([0.0, 0.0, 1.0]), None, None, None, &meta("")).unwrap();
+ let doc = reopen(&doc);
+ let d = &list(&doc, 0)[0];
+ assert_eq!(d.name(b"Name"), Some(&b"Star"[..]));
+ let n = d.get(b"AP").unwrap().as_dict().unwrap().reference(b"N").unwrap();
+ let Object::Stream(s) = &*doc.get(n) else { panic!() };
+ assert_eq!(s.decoded().unwrap(), note_drawing(Some("Star"), [0.0, 0.0, 1.0]));
+}
+
+/// The built appearance's content for an annotation dictionary written in PDF syntax.
+fn content_of(src: &str) -> String {
+ let doc = document_of(&[src.as_bytes()]);
+ let d = doc.get(ObjRef::new(1, 0)).as_dict().cloned().expect("a dictionary");
+ let stream = appearance::build(&d).expect("drawn");
+ String::from_utf8_lossy(&stream.decoded().unwrap()).into_owned()
+}
+
+/// ISO 32000-2 Table 166: `/Border [hr vr w [dash]]`; the optional fourth element, a dash array,
+/// used to hide the width (drawn 1 pt solid instead of 3 pt dashed).
+#[test]
+fn legacy_border_width_and_dash_are_drawn() {
+ let square = |border: &str| content_of(&format!("<< /Subtype /Square /Rect [0 0 100 100] /C [1 0 0] {border} >>"));
+ let c = square("/Border [0 0 3 [6 3]]");
+ assert!(c.contains("3 w") && c.contains("[6 3] 0 d"), "{c}");
+ assert!(c.contains("1.5 1.5 97 97 re"), "the stroke is inset by half its width: {c}");
+ let c = square("/Border [0 0 3]");
+ assert!(c.contains("3 w") && !c.contains(" d\n"), "no dash array: solid: {c}");
+ // `/BS` overrides `/Border` (Table 166), for the width and the dashes alike.
+ let c = square("/Border [0 0 3 [6 3]] /BS << /W 2 >>");
+ assert!(c.contains("2 w") && !c.contains(" d\n"), "{c}");
+ let c = square("/Border [0 0 3 [6 3]] /BS << /W 2 /S /D /D [4 1] >>");
+ assert!(c.contains("2 w") && c.contains("[4 1] 0 d"), "{c}");
+ // A /BS without /W means its default width 1, not the ignored /Border's.
+ let c = square("/Border [0 0 3] /BS << /S /S >>");
+ assert!(c.contains("1 w") && !c.contains("3 w"), "{c}");
+ // A FreeText border and a line take the legacy dash array too.
+ let c = content_of("<< /Subtype /FreeText /Rect [0 0 100 40] /Contents (x) /Border [0 0 2 [5 2]] >>");
+ assert!(c.contains("2 w") && c.contains("[5 2] 0 d"), "{c}");
+ let c = content_of("<< /Subtype /Line /Rect [0 0 100 100] /L [10 10 90 90] /C [0 0 1] /Border [0 0 2 [5 2]] >>");
+ assert!(c.contains("[5 2] 0 d"), "{c}");
+}
+
+/// Dash arrays that can't be drawn (§8.4.3.6: all zeros is invalid; negative or non-numeric
+/// lengths, and absurdly long arrays) draw solid, without a panic. A non-finite or negative
+/// width falls back to 1.
+#[test]
+fn bad_dash_arrays_draw_solid() {
+ let square = |border: &str| content_of(&format!("<< /Subtype /Square /Rect [0 0 100 100] /C [1 0 0] {border} >>"));
+ let long = format!("[{}]", vec!["1"; 65].join(" "));
+ for bad in ["[0 0]", "[-3 2]", "[]", "[(a) 2]", "5", long.as_str()] {
+ let c = square(&format!("/Border [0 0 3 {bad}]"));
+ assert!(c.contains("3 w") && !c.contains(" d\n"), "{bad}: {c}");
+ let c = square(&format!("/BS << /W 3 /S /D /D {bad} >>"));
+ assert!(c.contains("3 w") && !c.contains(" d\n"), "{bad}: {c}");
+ }
+ assert!(square(&format!("/Border [0 0 3 [{}]]", vec!["1"; 64].join(" "))).contains(" 0 d\n"), "64 elements are drawn");
+ // `/S /D` without `/D` uses the default `[3]` (Table 168).
+ assert!(square("/BS << /W 3 /S /D >>").contains("[3] 0 d"));
+ let mut d = Dict::new();
+ d.set(b"Subtype".to_vec(), Object::name("Square"));
+ d.set(b"Rect".to_vec(), Object::Array([0.0, 0.0, 100.0, 100.0].map(Object::Real).to_vec()));
+ d.set(b"C".to_vec(), Object::Array([1.0, 0.0, 0.0].map(Object::Real).to_vec()));
+ for w in [f64::NAN, f64::INFINITY, -2.0] {
+ let dash = Object::Array([f64::NAN, 2.0].map(Object::Real).to_vec());
+ d.set(b"Border".to_vec(), Object::Array(vec![Object::Int(0), Object::Int(0), Object::Real(w), dash]));
+ let c = String::from_utf8_lossy(&appearance::build(&d).unwrap().decoded().unwrap()).into_owned();
+ assert!(c.contains("1 w") && !c.contains(" d\n") && !c.contains("NaN") && !c.contains("inf"), "{w}: {c}");
+ }
+}
+
+/// Table 182: an ink annotation's `/BS` gives the width and dash pattern its paths are drawn with.
+#[test]
+fn ink_draws_its_border_style_dashes() {
+ let ink = |style: &str| content_of(&format!("<< /Subtype /Ink /Rect [0 0 100 100] /C [1 0 0] /InkList [[5 5 50 95 95 5]] {style} >>"));
+ let c = ink("/BS << /W 3 /S /D /D [6 3] >>");
+ assert!(c.contains("3 w 1 J 1 j\n[6 3] 0 d"), "{c}");
+ assert!(!ink("/BS << /W 3 >>").contains(" d\n"));
+ assert!(ink("/Border [0 0 2 [4 4]]").contains("[4 4] 0 d"));
+}
+
+/// Table 183: `/Sy /P` associates a new paragraph symbol (¶) with the caret. It is drawn to the
+/// caret's right in the caret's colour, inside `/Rect`; `/Sy /None` (the default) draws none.
+#[test]
+fn a_caret_with_a_paragraph_symbol_draws_the_pilcrow() {
+ let caret = |extra: &str| {
+ let doc = document_of(&[format!("<< /Subtype /Caret /Rect [30 30 60 60] /C [0.9 0.1 0.1] {extra} >>").as_bytes()]);
+ let d = doc.get(ObjRef::new(1, 0)).as_dict().cloned().unwrap();
+ let s = appearance::build(&d).unwrap();
+ (s.decoded().unwrap(), s.dict.get(b"Resources").and_then(Object::as_dict).is_some_and(|r| r.contains(b"Font")))
+ };
+ let has_pilcrow = |c: &[u8]| c.windows(5).any(|w| w == b"(\xb6) T");
+ let (c, font) = caret("/Sy /P");
+ assert!(has_pilcrow(&c) && font, "{}", String::from_utf8_lossy(&c));
+ let text = String::from_utf8_lossy(&c).into_owned();
+ assert!(text.starts_with("0.9 0.1 0.1 rg"), "{text}");
+ // The caret gives up room on the right for the symbol, which stays within /Rect.
+ let td: Vec<f64> = text.split("Tf ").nth(1).unwrap().split_whitespace().take(2).map(|v| v.parse().unwrap()).collect();
+ let size: f64 = text.split("/Helv ").nth(1).unwrap().split_whitespace().next().unwrap().parse().unwrap();
+ assert!(td[0] > 45.0 && td[0] + appearance::text_width("\u{b6}", size) <= 60.0 + 1e-6 && td[1] >= 30.0, "{text}");
+ assert!(!text.contains("60 30 c h f"), "the caret no longer reaches the right edge: {text}");
+ for none in ["/Sy /None", ""] {
+ let (c, font) = caret(none);
+ assert!(!has_pilcrow(&c) && !font, "{none}");
+ assert!(String::from_utf8_lossy(&c).contains("60 30 c h f"), "{none}: the caret fills /Rect as before");
+ }
+ // With /RD leaving room on the right, the caret keeps its box and the symbol fits beside it.
+ let (c, _) = caret("/Sy /P /RD [0 0 15 0]");
+ let text = String::from_utf8_lossy(&c).into_owned();
+ assert!(text.contains("45 30 c h f") && has_pilcrow(&c), "{text}");
+ // Malformed /RD and a degenerate /Rect don't panic.
+ for rd in ["/RD [40 0 40 0]", "/RD [-1 0 0 0]", "/RD [1 2]", "/RD (x)"] {
+ assert!(has_pilcrow(&caret(&format!("/Sy /P {rd}")).0), "{rd}");
+ }
+ let doc = document_of(&[b"<< /Subtype /Caret /Rect [30 30 30 30] /Sy /P >>"]);
+ let d = doc.get(ObjRef::new(1, 0)).as_dict().cloned().unwrap();
+ assert!(appearance::build(&d).is_some());
+}
+
+// ── Line annotations: leader lines and captions (ISO 32000-2 §12.5.6.7, Table 178) ──────────
+
+/// A red Line from `l` with a 1 pt border, a generous `/Rect`, and `extra` entries.
+fn table_178_line(l: [f64; 4], extra: &[(&str, Object)]) -> Dict {
+ let mut d = Dict::new();
+ d.set(b"Subtype".to_vec(), Object::name("Line"));
+ d.set(b"Rect".to_vec(), Object::Array([0.0, 0.0, 600.0, 800.0].map(Object::Real).to_vec()));
+ d.set(b"C".to_vec(), Object::Array([1.0, 0.0, 0.0].map(Object::Real).to_vec()));
+ d.set(b"L".to_vec(), Object::Array(l.map(Object::Real).to_vec()));
+ for (k, v) in extra {
+ d.set(k.as_bytes().to_vec(), v.clone());
+ }
+ d
+}
+
+/// The built appearance's content.
+fn line_drawing(d: &Dict) -> String {
+ let s = crate::appearance::build(d).expect("the line is drawn");
+ String::from_utf8_lossy(&s.decoded().unwrap()).into_owned()
+}
+
+/// Every straight two-point stroke (`x0 y0 m x1 y1 l S`) in a drawing.
+fn segments(content: &str) -> Vec<[f64; 4]> {
+ content
+ .lines()
+ .filter_map(|line| {
+ let t: Vec<&str> = line.split_whitespace().collect();
+ if t.len() != 7 || t[2] != "m" || t[5] != "l" || t[6] != "S" {
+ return None;
+ }
+ let v: Vec<f64> = [t[0], t[1], t[3], t[4]].iter().map(|x| x.parse().unwrap()).collect();
+ Some([v[0], v[1], v[2], v[3]])
+ })
+ .collect()
+}
+
+/// The caption's text matrix (`a b c d e f Tm`), if any.
+fn caption_matrix(content: &str) -> Option<[f64; 6]> {
+ let at = content.find(" Tm")?;
+ let before: Vec<f64> = content[..at].split_whitespace().rev().take(6).map(|x| x.parse().unwrap()).collect();
+ Some([before[5], before[4], before[3], before[2], before[1], before[0]])
+}
+
+fn has(segs: &[[f64; 4]], want: [f64; 4]) -> bool {
+ segs.iter().any(|s| s.iter().zip(want).all(|(a, b)| (a - b).abs() < 0.01))
+}
+
+#[test]
+fn a_positive_leader_length_puts_the_line_above_a_left_to_right_line_and_a_negative_one_below() {
+ let up = segments(&line_drawing(&table_178_line([72.0, 620.0, 272.0, 620.0], &[("LL", Object::Real(20.0))])));
+ assert!(has(&up, [72.0, 640.0, 272.0, 640.0]), "the line is 20 above /L: {up:?}");
+ assert!(has(&up, [72.0, 620.0, 72.0, 640.0]) && has(&up, [272.0, 620.0, 272.0, 640.0]), "leader lines from /L up to it: {up:?}");
+ assert!(!has(&up, [72.0, 620.0, 272.0, 620.0]), "nothing along /L itself: {up:?}");
+
+ let down = segments(&line_drawing(&table_178_line([72.0, 540.0, 272.0, 540.0], &[("LL", Object::Real(-20.0)), ("LLE", Object::Real(10.0))])));
+ assert!(has(&down, [72.0, 520.0, 272.0, 520.0]), "the line is 20 below /L: {down:?}");
+ assert!(has(&down, [72.0, 540.0, 72.0, 510.0]) && has(&down, [272.0, 540.0, 272.0, 510.0]), "leaders run 10 past it: {down:?}");
+}
+
+#[test]
+fn a_leader_offset_leaves_a_gap_and_the_endings_sit_on_the_line_itself() {
+ let d = table_178_line(
+ [72.0, 460.0, 272.0, 460.0],
+ &[("LL", Object::Real(20.0)), ("LLO", Object::Real(10.0)), ("LE", Object::Array(vec![Object::name("OpenArrow"), Object::name("OpenArrow")]))],
+ );
+ let content = line_drawing(&d);
+ let segs = segments(&content);
+ assert!(has(&segs, [72.0, 490.0, 272.0, 490.0]), "the line sits |LL| + LLO above /L: {segs:?}");
+ assert!(has(&segs, [72.0, 470.0, 72.0, 490.0]) && has(&segs, [272.0, 470.0, 272.0, 490.0]), "leaders start LLO from /L: {segs:?}");
+ // The open arrows' tips (`tip l`) are at the ends of the line, not of /L.
+ assert!(content.contains(" 72 490 l ") && content.contains(" 272 490 l "), "arrows at the moved line: {content}");
+ assert!(!content.contains(" 72 460 l "), "no arrow on /L: {content}");
+}
+
+#[test]
+fn an_inline_caption_breaks_the_line_around_its_text() {
+ let d =
+ table_178_line([72.0, 380.0, 272.0, 380.0], &[("Cap", Object::Bool(true)), ("Contents", Object::String(PdfString::text("Inline 50 mm")))]);
+ let content = line_drawing(&d);
+ assert!(content.contains("(Inline 50 mm) Tj"), "the caption is drawn: {content}");
+ assert!(content.contains("/Helv 10 Tf"), "in Helvetica 10: {content}");
+ let m = caption_matrix(&content).expect("text matrix");
+ let width = crate::appearance::text_width("Inline 50 mm", 10.0);
+ assert!((m[4] - (172.0 - width / 2.0)).abs() < 0.01 && m[5] < 380.0 && m[5] > 380.0 - 10.0, "centred on the line: {m:?}");
+ let segs = segments(&content);
+ assert_eq!(segs.len(), 2, "two pieces: {segs:?}");
+ assert!(segs.iter().all(|s| s[2] <= 172.0 - width / 2.0 || s[0] >= 172.0 + width / 2.0), "no stroke under the text: {segs:?}");
+ assert!(has(&segs, [72.0, 380.0, 172.0 - width / 2.0 - 2.0, 380.0]), "the left piece starts at the line's start: {segs:?}");
+}
+
+#[test]
+fn a_top_caption_sits_above_the_unbroken_line() {
+ let d = table_178_line(
+ [72.0, 300.0, 272.0, 300.0],
+ &[("Cap", Object::Bool(true)), ("CP", Object::name("Top")), ("Contents", Object::String(PdfString::text("Top 50 mm")))],
+ );
+ let content = line_drawing(&d);
+ let m = caption_matrix(&content).expect("text matrix");
+ assert!(m[5] > 300.0 && m[5] < 305.0, "baseline just above the line: {m:?}");
+ assert_eq!(segments(&content), vec![[72.0, 300.0, 272.0, 300.0]], "the line is whole");
+}
+
+#[test]
+fn a_caption_offset_moves_it_along_and_off_the_line_with_a_tick() {
+ let co = |h: f64, v: f64| Object::Array(vec![Object::Real(h), Object::Real(v)]);
+ let text = ("Contents", Object::String(PdfString::text("Offset 15")));
+ let base = caption_matrix(&line_drawing(&table_178_line([330.0, 700.0, 530.0, 700.0], &[("Cap", Object::Bool(true)), text.clone()]))).unwrap();
+ let content = line_drawing(&table_178_line([330.0, 700.0, 530.0, 700.0], &[("Cap", Object::Bool(true)), ("CO", co(0.0, 15.0)), text.clone()]));
+ let up = caption_matrix(&content).unwrap();
+ assert!((up[5] - base[5] - 15.0).abs() < 0.01 && (up[4] - base[4]).abs() < 0.01, "15 up: {base:?} → {up:?}");
+ let segs = segments(&content);
+ assert!(has(&segs, [330.0, 700.0, 530.0, 700.0]), "a caption off the line leaves it whole: {segs:?}");
+ assert!(segs.iter().any(|s| s[0] == 430.0 && s[2] == 430.0 && s[1] == 700.0 && s[3] > 705.0), "a tick from the midpoint up: {segs:?}");
+ let along =
+ caption_matrix(&line_drawing(&table_178_line([330.0, 700.0, 530.0, 700.0], &[("Cap", Object::Bool(true)), ("CO", co(-30.0, 0.0)), text])))
+ .unwrap();
+ assert!((along[4] - base[4] + 30.0).abs() < 0.01 && (along[5] - base[5]).abs() < 0.01, "30 left: {base:?} → {along:?}");
+}
+
+#[test]
+fn without_cap_true_no_caption_is_drawn() {
+ for cap in [None, Some(Object::Bool(false)), Some(Object::Int(1))] {
+ let mut extra = vec![("Contents", Object::String(PdfString::text("Hidden caption")))];
+ if let Some(c) = cap.clone() {
+ extra.push(("Cap", c));
+ }
+ let d = table_178_line([330.0, 620.0, 530.0, 620.0], &extra);
+ let content = line_drawing(&d);
+ assert!(!content.contains("Tj"), "{cap:?}: {content}");
+ assert_eq!(segments(&content), vec![[330.0, 620.0, 530.0, 620.0]]);
+ assert!(crate::appearance::undrawable_text(&d).is_none());
+ }
+}
+
+#[test]
+fn a_diagonal_lines_leaders_are_perpendicular_and_its_caption_turns_with_it() {
+ let d = table_178_line(
+ [330.0, 460.0, 530.0, 560.0],
+ &[
+ ("LL", Object::Real(20.0)),
+ ("LLE", Object::Real(10.0)),
+ ("Cap", Object::Bool(true)),
+ ("Contents", Object::String(PdfString::text("Diagonal"))),
+ ],
+ );
+ let content = line_drawing(&d);
+ let segs = segments(&content);
+ let (ux, uy) = (200.0 / 100f64.hypot(200.0), 100.0 / 100f64.hypot(200.0));
+ let leaders: Vec<&[f64; 4]> = segs.iter().filter(|s| (s[2] - s[0]) * ux + (s[3] - s[1]) * uy < 1e-2).collect();
+ assert_eq!(leaders.len(), 2, "two leader lines across the line: {segs:?}");
+ for l in leaders {
+ let (dx, dy) = (l[2] - l[0], l[3] - l[1]);
+ assert!((dx.hypot(dy) - 30.0).abs() < 0.01, "|LL| + LLE long: {l:?}");
+ assert!(dx < 0.0 && dy > 0.0, "up and to the left (left of travel): {l:?}");
+ }
+ let m = caption_matrix(&content).expect("caption");
+ assert!((m[0] - ux).abs() < 1e-3 && (m[1] - uy).abs() < 1e-3, "the text runs along the line: {m:?}");
+ // Drawn right to left, it still reads left to right.
+ let back = caption_matrix(&line_drawing(&table_178_line(
+ [530.0, 560.0, 330.0, 460.0],
+ &[("Cap", Object::Bool(true)), ("Contents", Object::String(PdfString::text("x")))],
+ )))
+ .unwrap();
+ assert!(back[0] > 0.0, "{back:?}");
+}
+
+#[test]
+fn a_caption_from_rich_text_and_one_the_font_cant_draw() {
+ let rc = "<?xml version=\"1.0\"?><body xmlns=\"http://www.w3.org/1999/xhtml\"><p>Dim &amp; <b>5</b>0&#x20;mm &lt;x&gt;</p></body>";
+ let d = table_178_line([0.0, 0.0, 100.0, 0.0], &[("Cap", Object::Bool(true)), ("RC", Object::String(PdfString::text(rc)))]);
+ let s = crate::appearance::build(&d).unwrap().decoded().unwrap();
+ assert!(s.windows(17).any(|w| w == b"(Dim & 50 mm <x>)"), "{}", String::from_utf8_lossy(&s));
+ let cjk = table_178_line([0.0, 0.0, 100.0, 0.0], &[("Cap", Object::Bool(true)), ("Contents", Object::String(PdfString::text("長さ")))]);
+ assert_eq!(crate::appearance::undrawable_text(&cjk), Some(("the line's caption", '長')));
+ // A PdfCraft measurement's label is its caption: the comment text isn't drawn a second time.
+ let mut measured = cjk.clone();
+ measured.set(b"PCMeasureValue".to_vec(), Object::String(PdfString::text("5 mm")));
+ assert_eq!(crate::appearance::undrawable_text(&measured), None);
+ let content = line_drawing(&measured);
+ assert_eq!(content.matches(" Tj").count(), 1, "{content}");
+}
+
+#[test]
+fn degenerate_and_absurd_leader_and_caption_values_do_not_panic() {
+ let cap = ("Cap", Object::Bool(true));
+ let text = ("Contents", Object::String(PdfString::text(&"w".repeat(10_000))));
+ // A zero-length line has no direction: no leader lines, no caption, no NaN.
+ let point =
+ line_drawing(&table_178_line([50.0, 50.0, 50.0, 50.0], &[("LL", Object::Real(20.0)), ("LLE", Object::Real(5.0)), cap.clone(), text.clone()]));
+ assert!(!point.contains("NaN") && !point.contains("inf") && !point.contains("Tj"), "{point}");
+ assert_eq!(segments(&point).len(), 1);
+ for bad in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, 1e300, -1e300, f64::MAX] {
+ let d = table_178_line(
+ [0.0, 0.0, 100.0, 0.0],
+ &[
+ ("LL", Object::Real(bad)),
+ ("LLE", Object::Real(bad)),
+ ("LLO", Object::Real(bad)),
+ ("CO", Object::Array(vec![Object::Real(bad), Object::Real(bad)])),
+ cap.clone(),
+ text.clone(),
+ ],
+ );
+ let content = line_drawing(&d);
+ assert!(!content.contains("NaN") && !content.contains("inf"), "{bad}: {content}");
+ for s in segments(&content) {
+ assert!(s.iter().all(|x| x.abs() <= 50_000.0), "{bad}: {s:?}");
+ }
+ }
+ // Negative LLE and LLO count as 0.
+ let neg = segments(&line_drawing(&table_178_line(
+ [0.0, 0.0, 100.0, 0.0],
+ &[("LL", Object::Real(10.0)), ("LLE", Object::Real(-5.0)), ("LLO", Object::Real(-5.0))],
+ )));
+ assert!(has(&neg, [0.0, 0.0, 0.0, 10.0]) && has(&neg, [0.0, 10.0, 100.0, 10.0]), "{neg:?}");
+ // Huge endpoints whose midpoint would overflow fall back to the plain line.
+ let huge = line_drawing(&table_178_line([f64::MAX, f64::MAX, f64::MAX / 2.0, f64::MAX], &[("LL", Object::Real(20.0)), cap, text]));
+ assert!(!huge.contains("NaN") && !huge.contains("inf"), "{huge}");
+ // The caption is cut to 256 characters.
+ let long = line_drawing(&table_178_line(
+ [0.0, 0.0, 100.0, 0.0],
+ &[("Cap", Object::Bool(true)), ("Contents", Object::String(PdfString::text(&"w".repeat(10_000))))],
+ ));
+ assert!(long.contains(&format!("({}) Tj", "w".repeat(256))), "cut to 256");
+ assert!(!long.contains(&"w".repeat(257)));
+}
diff --git a/crates/audit/src/lib.rs b/crates/audit/src/lib.rs
index f1f1350..f2bcf63 100644
--- a/crates/audit/src/lib.rs
+++ b/crates/audit/src/lib.rs
@@ -138,16 +138,25 @@ struct Budget {
}
impl Budget {
- /// Resets the comparison count for a page with these `lines`.
+ /// Resets the comparison count for a page with these `lines`. A line costs its word boxes
+ /// or its runs, whichever are more (at least one): a cover check walks the boxes, and the
+ /// covered text walks the runs, which can draw no words at all (`( ) Tj`).
fn start_page(&mut self, lines: &[TextLine]) {
self.comparisons = 0;
- self.page_cost = lines.iter().fold(0, |n, line| n.saturating_add(line.ink.len().max(1)));
+ self.page_cost = lines.iter().fold(0, |n, line| n.saturating_add(line.ink.len().max(line.runs().count()).max(1)));
}
- /// The text of the `lines` that `hides`, joined with single spaces, or `None` when they show
- /// no text. Without `copying` the text is empty and never assembled: one long line under many
- /// covers would otherwise be copied once per cover, outside both bounds.
- fn hidden_text(&mut self, lines: &[TextLine], copying: bool, hides: impl Fn(&TextLine) -> bool) -> Result<Option<String>, AuditError> {
+ /// The text `cover` hides in the `lines` that `hides` ([`covered_words`]), joined with single
+ /// spaces, or `None` when they show no text. Without `copying` the text is empty and never
+ /// assembled: one long line under many covers would otherwise be copied once per cover,
+ /// outside both bounds.
+ fn hidden_text(
+ &mut self,
+ lines: &[TextLine],
+ copying: bool,
+ cover: &[f64; 4],
+ hides: impl Fn(&TextLine) -> bool,
+ ) -> Result<Option<String>, AuditError> {
self.comparisons = self.comparisons.saturating_add(self.page_cost);
if self.comparisons > self.limits.comparisons {
return Err(AuditError::TooManyComparisons);
@@ -160,7 +169,7 @@ impl Budget {
if !covered.is_empty() {
covered.push(' ');
}
- covered.push_str(line.text.trim());
+ covered_words(cover, line, &mut covered);
}
Ok((!covered.trim().is_empty()).then_some(covered))
}
@@ -188,14 +197,17 @@ fn audit(doc: &Document, limits: Limits) -> Result<Vec<AuditFinding>, AuditError
budget.start_page(&lines);
// 1. Opaque filled rectangles over extractable text.
for r in cover::filled_rects(doc, &page.dict)? {
- if let Some(covered) = budget.hidden_text(&lines, copying, |line| is_cover(&r, line))? {
+ if let Some(covered) = budget.hidden_text(&lines, copying, &r.rect, |line| is_cover(&r, line))? {
let covered_text = budget.report_text(covered, copying)?;
out.push(AuditFinding { page: n, kind: FindingKind::CoveredText, rect: r.rect, covered_text });
}
}
// 2. Annotation covers over extractable text.
for annot in annots(doc, &page.dict)? {
- if let Some(covered) = budget.hidden_text(&lines, copying, |line| match &annot {
+ let cover = match &annot {
+ AnnotationCover::Redact(rect) | AnnotationCover::Square { rect, .. } => *rect,
+ };
+ if let Some(covered) = budget.hidden_text(&lines, copying, &cover, |line| match &annot {
AnnotationCover::Redact(rect) => covers(rect, line),
AnnotationCover::Square { rect, rgb } => covers(rect, line) && contrast(line.color, *rgb) < COVER_CONTRAST,
})? {
@@ -250,6 +262,34 @@ fn covers(cover: &[f64; 4], line: &TextLine) -> bool {
inked || (boxed && (line.ink.is_empty() || word_intersects()))
}
+/// Appends the text of `line` that `cover` lies on to `out`: the runs whose words it overlaps
+/// (#4164), so the words of the line painted beside the cover, which stay visible, are not
+/// reported as hidden. Neighbouring runs are joined as the line joins them, so a word split
+/// across runs stays one word; runs with others left out between them are spaced. The whole
+/// line when its runs can't say: a single run, a line whose text was reordered for reading, or
+/// a cover that overlaps the line's box but none of its words.
+fn covered_words(cover: &[f64; 4], line: &TextLine, out: &mut String) {
+ let overlaps = |w: &[f64; 4]| area(&[cover[0].max(w[0]), cover[1].max(w[1]), cover[2].min(w[2]), cover[3].min(w[3])]) > 0.0;
+ let mut words = String::new();
+ let mut last = None;
+ for (i, (text, ink, spaced)) in line.runs().enumerate() {
+ if text.trim().is_empty() || !ink.iter().any(overlaps) {
+ continue;
+ }
+ let apart = last.is_some_and(|l: usize| l.saturating_add(1) != i || spaced);
+ if apart && !words.ends_with(char::is_whitespace) && !text.starts_with(char::is_whitespace) {
+ words.push(' ');
+ }
+ words.push_str(text);
+ last = Some(i);
+ }
+ if line.runs().nth(1).is_none() || last.is_none() {
+ out.push_str(line.text.trim());
+ } else {
+ out.push_str(words.trim());
+ }
+}
+
/// The area of a rectangle, 0 when it is empty or inverted.
fn area(r: &[f64; 4]) -> f64 {
(r[2] - r[0]).max(0.0) * (r[3] - r[1]).max(0.0)
diff --git a/crates/audit/src/tests.rs b/crates/audit/src/tests.rs
index 3aca406..e5fb9ab 100644
--- a/crates/audit/src/tests.rs
+++ b/crates/audit/src/tests.rs
@@ -645,6 +645,33 @@ fn later_text_on_the_line_does_not_clear_an_earlier_cover() {
assert!(findings[0].covered_text.contains("SECRET"), "{findings:?}");
}
+/// #4164: a cover over part of a line reports the words under it, not the words of the same
+/// line painted beside it, which stay visible.
+#[test]
+fn covered_text_leaves_out_the_words_beside_the_cover() {
+ let covered = |content: &[u8]| {
+ let findings = audit_redactions(&open(one_page(content, ""))).expect("audit must run");
+ findings.into_iter().map(|f| f.covered_text).collect::<Vec<_>>()
+ };
+ assert_eq!(covered(b"0 g\nBT /F1 24 Tf 100 700 Td (SECRET) Tj ET\n98 688 94 32 re f\nBT /F1 24 Tf 200 700 Td (tail) Tj ET\n"), ["SECRET"]);
+ // A word shown in two runs with nothing between them stays one word (review on #4198).
+ assert_eq!(covered(b"0 g\nBT /F1 24 Tf 100 700 Td (SE) Tj (CRET) Tj ET\n98 688 94 32 re f\nBT /F1 24 Tf 200 700 Td (tail) Tj ET\n"), ["SECRET"]);
+
+ // The same for an unapplied redaction mark over the first run only. A mark over both runs
+ // reports both, with the space the line has between them (`tail` is set apart here).
+ for (rect, expected) in [("[98 688 192 720]", "SECRET"), ("[98 688 310 720]", "SECRET tail")] {
+ let mut b = Builder::new();
+ b.add("<< /Type /Catalog /Pages 2 0 R >>");
+ b.add("<< /Type /Pages /Kids [3 0 R] /Count 1 >>");
+ b.add("<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents 4 0 R /Resources << /Font << /F1 5 0 R >> >> /Annots [6 0 R] >>");
+ b.add_stream(b"BT /F1 24 Tf 100 700 Td (SECRET) Tj ET\nBT /F1 24 Tf 250 700 Td (tail) Tj ET\n");
+ b.add(FONT);
+ b.add(&format!("<< /Type /Annot /Subtype /Redact /Rect {rect} >>"));
+ let findings = audit_redactions(&open(b.build())).expect("audit must run");
+ assert_eq!(findings.iter().map(|f| (f.kind.clone(), f.covered_text.as_str())).collect::<Vec<_>>(), [(FindingKind::UnappliedMark, expected)]);
+ }
+}
+
/// Many covers over the same long line repeat its text in every finding: a small file must not
/// expand into an unbounded report. Past the budget the audit fails rather than truncate.
#[test]
@@ -677,6 +704,28 @@ fn cover_and_line_comparisons_are_bounded() {
assert!(crate::audit(&doc, limits).expect("within the budget").is_empty());
}
+/// A run that draws no word still costs a comparison: the covered text walks every run of a
+/// covered line, so a word followed by many `( ) Tj` must not be checked for free (review on
+/// #4198).
+#[test]
+fn runs_without_words_count_against_the_comparison_bound() {
+ let mut content = b"BT /F1 24 Tf 100 700 Td (SECRET) Tj".to_vec();
+ content.extend_from_slice(&b" ( ) Tj".repeat(50));
+ content.extend_from_slice(
+ b" ET
+0 g
+98 688 94 32 re f
+",
+ );
+ let doc = open(one_page(&content, ""));
+ let lines = pdfcraft_edit::glyph_text_lines(&doc, &pdfcraft_model::pages(&doc)[0]).expect("text");
+ assert_eq!(lines.iter().map(|l| (l.ink.len(), l.runs().count())).collect::<Vec<_>>(), [(1, 51)]);
+ let limits = crate::Limits { comparisons: 50, covered_text: usize::MAX };
+ assert!(matches!(crate::audit(&doc, limits), Err(crate::AuditError::TooManyComparisons)));
+ let limits = crate::Limits { comparisons: 51, covered_text: usize::MAX };
+ assert_eq!(crate::audit(&doc, limits).expect("within the budget").len(), 1);
+}
+
/// Covered text is document text: a document whose permissions withhold copying reports where
/// its covers are but not what they hide, unless it was opened with the owner password.
#[test]
@@ -714,14 +763,15 @@ fn copy_restricted_documents_withhold_covered_text() {
/// per cover, a volume neither the comparison nor the output bound charges.
#[test]
fn withheld_covered_text_is_not_assembled() {
+ const PAGE: [f64; 4] = [0.0, 0.0, 612.0, 792.0];
let doc = open(one_page(b"BT /F1 24 Tf 100 700 Td (SECRET DATA 123) Tj ET\n", ""));
let lines = pdfcraft_edit::text_lines(&doc, 0).expect("text");
let mut budget = crate::Budget { limits: crate::Limits::DEFAULT, comparisons: 0, page_cost: 0, covered_text: 0 };
budget.start_page(&lines);
- let withheld = budget.hidden_text(&lines, false, |_| true).expect("within the budget");
+ let withheld = budget.hidden_text(&lines, false, &PAGE, |_| true).expect("within the budget");
assert_eq!(withheld.map(|t| t.capacity()), Some(0), "a finding, with no text built for it");
- assert_eq!(budget.hidden_text(&lines, false, |_| false).expect("within the budget"), None);
- let copied = budget.hidden_text(&lines, true, |_| true).expect("within the budget");
+ assert_eq!(budget.hidden_text(&lines, false, &PAGE, |_| false).expect("within the budget"), None);
+ let copied = budget.hidden_text(&lines, true, &PAGE, |_| true).expect("within the budget");
assert_eq!(copied.as_deref(), Some("SECRET DATA 123"));
}
diff --git a/crates/automation/README.md b/crates/automation/README.md
index 7eb8ca1..cdaaa13 100644
--- a/crates/automation/README.md
+++ b/crates/automation/README.md
@@ -33,7 +33,7 @@ its undo/redo history.
- For proportional image signature resizing, use the embedded image layer's width/height ratio rather than a previously stretched annotation rectangle. The GUI preserves this ratio at corners with the opposite corner anchored; edge midpoint handles change only their own axis. `comment_edit` accepts the resulting rectangle.
- `doc_close` refuses to drop unsaved changes unless `discard_changes: true`. `doc_save` writes atomically, incrementally in place, and in full for a new path. Atomic output writes call `sync_all` on the staging file before replacing the destination. A write or sync error leaves the destination intact, removes staging and leaves the document dirty for retry. A filesystem that does not support syncing returns an error; there is no unsynced fallback. This flushes file contents, but does not guarantee persistence of the parent-directory rename across power loss.
- With a root set, every read and write path must resolve inside it (symlinks and `..` included). Relative paths resolve inside the root, and `..` is resolved by name before the check. Every path outside the root gets the same refusal (`<path> is outside the allowed directory <root>`), whether or not it exists, so a confined agent can't probe the rest of the disk; on Windows another network share or device path (`\\host\share`, `\\?\UNC\…`, `\\.\…`) is refused without being contacted. "Not found" and other filesystem errors are reported only for paths inside the root. Tools that write several files into a folder name them after the document or input file, with separators, colons and control characters replaced by `_`, so a name can't lead them out of the folder. The root itself must be a folder.
-- `Automation::with_automation_roots` holds a read folder and a write folder (`pdfcraft-cli mcp --automation-read-root DIR --automation-write-root DIR`, see [docs/mcp.md](../../docs/mcp.md)). Reads must lie inside the read root and writes inside the write root, links followed. A root left out grants none of its access. Refusals read `automation path rejected: outside the read root <root>: <path>`. It applies on top of `with_root`.
+- `Automation::with_automation_roots` holds a read folder and a write folder (`pdfcraft-cli mcp --automation-read-root DIR --automation-write-root DIR`, see [docs/mcp.md](../../docs/mcp.md)). Reads must lie inside the read root and writes inside the write root, links followed. A root left out grants none of its access. Refusals read `automation path rejected: outside the read root <root>: <path>`. As with a root set, on Windows a path on another network share or device path is refused with that refusal without being contacted (#4003). It applies on top of `with_root`.
## Text search and cache limits
diff --git a/crates/automation/src/a11y.rs b/crates/automation/src/a11y.rs
index 88598c2..5afe99f 100644
--- a/crates/automation/src/a11y.rs
+++ b/crates/automation/src/a11y.rs
@@ -504,7 +504,7 @@ impl Automation {
"object": t.object.num, "generation": t.object.generation, "type": t.kind,
"parent": t.parent.map(|p| json!({ "object": p.num, "generation": p.generation })), "depth": t.depth,
"title": t.title, "actual_text": t.actual_text, "alternate_text": t.alt,
- "language": t.language, "page": t.page.map(|p| p + 1),
+ "language": t.language, "summary": t.summary, "scope": t.scope, "page": t.page.map(|p| p + 1),
})
})
.collect();
@@ -575,6 +575,8 @@ impl Automation {
}
impl Automation {
+ /// Recognition settings from the arguments: `dpi` (clamped to 72–600), `language` (refused
+ /// unless the models read it) and `skip_text_pages`, each left at its default when absent.
pub(crate) fn ocr_settings(&self, a: &Args) -> Result<pdfcraft_engine::ocr::OcrSettings> {
let mut settings = pdfcraft_engine::ocr::OcrSettings::default();
if let Some(d) = a.opt_num("dpi")? {
@@ -592,6 +594,9 @@ impl Automation {
Ok(settings)
}
+ /// Recognizes text in each of `paths` and writes the result under the same file name in
+ /// `folder`, reporting per file its output, word count and skipped pages, or its error. A
+ /// path outside the root refuses the whole call before any work starts.
pub(crate) fn ocr_recognize_files(&mut self, a: &Args) -> Result<Value> {
let settings = self.ocr_settings(a)?;
let folder = self.resolve(a.str("folder")?, true)?;
@@ -601,15 +606,26 @@ impl Automation {
for p in &paths {
self.resolve_for(p, crate::file_access::Access::Read, true)?;
}
+ // Two inputs that would write the same output file overwrite each other while both report
+ // success, so the whole batch is refused here: before the folder is created, anything is
+ // read, or the OCR engines load.
+ let targets: Vec<std::path::PathBuf> = paths.iter().map(|p| child(&folder, &input_file_name(p))).collect();
+ let shared = shared_file_names(&targets);
+ if !shared.is_empty() {
+ return Err(ToolError::InvalidArgs(format!(
+ "more than one input would write to the same output file, so each would replace the one before it. Colliding file names: {}. Give each input a different file name, or run them in separate batches with different folders.",
+ shared.join(", ")
+ )));
+ }
std::fs::create_dir_all(&folder).map_err(|e| failed(e.to_string()))?;
let ocr = pdfcraft_engine::ocr::engine().map_err(failed)?;
let mut out = Vec::new();
for p in paths {
- let name = std::path::Path::new(p).file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| "document.pdf".into());
+ let name = input_file_name(p);
let result =
- self.resolve(p, false).map_err(|e| e.to_string()).and_then(|src| std::fs::read(&src).map_err(|e| e.to_string())).and_then(|bytes| {
- pdfcraft_engine::ocr::recognize_file(&name, std::sync::Arc::new(bytes), None, settings.clone(), &ocr, |_, _| true)
- });
+ self.resolve(p, false).map_err(|e| e.to_string()).and_then(|src| crate::read_input_bytes(&src).map_err(|e| e.to_string())).and_then(
+ |bytes| pdfcraft_engine::ocr::recognize_file(&name, std::sync::Arc::new(bytes), None, settings.clone(), &ocr, |_, _| true),
+ );
out.push(match result {
Ok(r) => {
let target = child(&folder, &name);
@@ -623,6 +639,8 @@ impl Automation {
Ok(json!({ "files": out }))
}
+ /// Recognizes text on the open document's `pages` (every page when absent) and adds it,
+ /// reporting the total word count and, per page, why it was skipped or what it found.
pub(crate) fn ocr_recognize(&mut self, a: &Args) -> Result<Value> {
let settings = self.ocr_settings(a)?;
let pages = if a.opt_ints("pages")?.is_some() { self.pages(a, "pages")? } else { Vec::new() };
@@ -642,6 +660,8 @@ impl Automation {
Ok(json!({ "words": found.iter().map(|p| p.words.len()).sum::<usize>(), "pages": list }))
}
+ /// Whether text recognition's models are installed, the directories searched for them (in
+ /// order), and the languages it reads, each as a code and a name.
pub(crate) fn ocr_status(&self) -> Result<Value> {
use pdfcraft_engine::ocr;
let dirs: Vec<String> = ocr::Models::search_dirs().iter().map(|d| d.to_string_lossy().into_owned()).collect();
@@ -650,6 +670,39 @@ impl Automation {
}
}
+/// The file name an input is written under: its own file name, or `document.pdf` when it has none.
+fn input_file_name(path: &str) -> String {
+ std::path::Path::new(path).file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| "document.pdf".into())
+}
+
+/// The output file names that two or more of `targets` share, each spelling listed once, in input
+/// order. Names are compared without regard to case on Windows and macOS and exactly elsewhere; on
+/// Windows a trailing dot or space is not part of the name (`scan.pdf.` is `scan.pdf`). Unicode
+/// normalization forms (NFC and NFD spellings of one name) are not compared, so such inputs are
+/// not caught. The folder is the same for every target, so only the names are compared.
+fn shared_file_names(targets: &[std::path::PathBuf]) -> Vec<String> {
+ let mut groups: std::collections::BTreeMap<String, (usize, Vec<String>)> = std::collections::BTreeMap::new();
+ for target in targets {
+ let name = target.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
+ let key = if cfg!(windows) {
+ name.trim_end_matches(['.', ' ']).to_lowercase()
+ } else if cfg!(target_os = "macos") {
+ // Case only; NFC and NFD spellings of one name stay distinct here (a known limit).
+ name.to_lowercase()
+ } else {
+ name.clone()
+ };
+ let (count, spellings) = groups.entry(key).or_insert_with(|| (0, Vec::new()));
+ *count += 1;
+ if !spellings.contains(&name) {
+ spellings.push(name);
+ }
+ }
+ groups.into_values().filter(|(count, _)| *count > 1).flat_map(|(_, spellings)| spellings).collect()
+}
+
+/// A script's request to the viewer as the JSON that running a script reports; a side panel
+/// goes by its fixed id.
pub(crate) fn request_json(r: &pdfcraft_engine::js::Request) -> Value {
use pdfcraft_engine::js::Request as R;
match r {
@@ -661,6 +714,7 @@ pub(crate) fn request_json(r: &pdfcraft_engine::js::Request) -> Value {
R::Focus(f) => json!({ "focus": f }),
R::Beep => json!({ "beep": true }),
R::SaveAs => json!({ "save_as": true }),
+ R::ShowPanel(p) => json!({ "panel": p.id() }),
}
}
@@ -669,7 +723,9 @@ impl Automation {
let id = self.doc(a)?.id;
let o = self.session.run_javascript(id, a.str("script")?, a.opt_str("field")?).map_err(failed)?;
let reqs: Vec<Value> = o.requests.iter().map(request_json).collect();
- Ok(json!({ "alerts": o.alerts, "console": o.console, "requests": reqs, "error": o.error, "result": o.result }))
+ Ok(
+ json!({ "alerts": o.alerts, "console": o.console, "requests": reqs, "error": o.error, "document_errors": o.doc_errors, "result": o.result }),
+ )
}
pub(crate) fn js_document_scripts(&self, a: &Args) -> Result<Value> {
@@ -700,7 +756,7 @@ impl Automation {
let mut files = Vec::new();
for p in a.strs("paths")? {
let path = self.resolve(p, false)?;
- files.push((p.to_string(), std::fs::read(&path).map_err(|e| failed(format!("{p}: {e}")))?));
+ files.push((p.to_string(), crate::read_input_bytes(&path).map_err(|e| failed(format!("{p}: {e}")))?));
}
let csv = pdfcraft_engine::merge_data_files(&files).map_err(failed)?;
let target = self.resolve(a.str("path")?, true)?;
@@ -845,7 +901,7 @@ impl Automation {
let result = self
.resolve(p, false)
.map_err(|e| e.to_string())
- .and_then(|src| std::fs::read(&src).map_err(|e| e.to_string()))
+ .and_then(|src| crate::read_input_bytes(&src).map_err(|e| e.to_string()))
.and_then(|bytes| run_on(&action, &name, std::sync::Arc::new(bytes), |_, _| {}));
out.push(match result {
Ok(r) => {
@@ -1042,3 +1098,21 @@ mod review_html_tests {
assert!(!html.contains("<script>"));
}
}
+
+#[cfg(test)]
+mod shared_output_name_tests {
+ use super::*;
+
+ #[test]
+ fn shared_output_names_follow_the_default_filesystem() {
+ let targets = |names: &[&str]| -> Vec<std::path::PathBuf> { names.iter().map(|n| std::path::Path::new("out").join(n)).collect() };
+ // A spelling that repeats is one shared name, listed once.
+ assert_eq!(shared_file_names(&targets(&["a.pdf", "b.pdf", "a.pdf"])), vec!["a.pdf".to_string()]);
+ assert!(shared_file_names(&targets(&["a.pdf", "b.pdf"])).is_empty());
+ // Case is ignored on Windows and macOS only; a trailing dot is ignored on Windows only.
+ let case = shared_file_names(&targets(&["scan.pdf", "Scan.PDF"]));
+ let dot = shared_file_names(&targets(&["scan.pdf", "scan.pdf."]));
+ assert_eq!(case.len(), if cfg!(any(windows, target_os = "macos")) { 2 } else { 0 }, "{case:?}");
+ assert_eq!(dot.len(), if cfg!(windows) { 2 } else { 0 }, "{dot:?}");
+ }
+}
diff --git a/crates/automation/src/batch.rs b/crates/automation/src/batch.rs
index 9931083..47cf714 100644
--- a/crates/automation/src/batch.rs
+++ b/crates/automation/src/batch.rs
@@ -58,7 +58,7 @@ impl<'a> Recipe<'a> {
}
fn accepts(&self, path: &Path) -> bool {
- let extension = path.extension().and_then(|s| s.to_str()).unwrap_or("").to_ascii_lowercase();
+ let extension = path.extension().and_then(std::ffi::OsStr::to_str).unwrap_or("").to_ascii_lowercase();
extension == "pdf" || (self.steps.contains(&"convert") && pdfcraft_engine::CONVERTIBLE.contains(&extension.as_str()))
}
@@ -70,7 +70,7 @@ impl<'a> Recipe<'a> {
if input.len() as u64 > MAX_INPUT {
return Err(failed("input exceeds 512 MiB"));
}
- let name = path.file_name().and_then(|n| n.to_str()).ok_or_else(|| failed("input name is not UTF-8"))?;
+ let name = path.file_name().and_then(std::ffi::OsStr::to_str).ok_or_else(|| failed("input name is not UTF-8"))?;
let mut bytes = Arc::new(input);
let mut log = Vec::new();
for step in &self.steps {
diff --git a/crates/automation/src/comments.rs b/crates/automation/src/comments.rs
index cff14a6..4270df8 100644
--- a/crates/automation/src/comments.rs
+++ b/crates/automation/src/comments.rs
@@ -3,9 +3,9 @@
//! Geometry follows the automation convention: points from the top-left of the displayed page,
//! y down. It is converted to PDF user space (crop box, `/Rotate`) here.
-use pdfcraft_engine::{
- Edit, LineEnding, Markup, NOTE_SIZE, NewAnnotation, NoteIcon, ReviewState, Rgb, Shape, StampGroup, StampKind, Style, SummarySort,
-};
+use std::collections::HashMap;
+
+use pdfcraft_engine::{Edit, LineEnding, Markup, NewAnnotation, NoteIcon, ReviewState, Rgb, Shape, StampGroup, StampKind, Style, SummarySort};
use pdfcraft_render::{Annotation, PageInfo};
use serde_json::{Value, json};
@@ -13,6 +13,8 @@ use crate::{Args, Automation, Content, DEFAULT_DPI, MAX_DPI, Result, ToolError,
/// Author used when a tool call names none.
pub(crate) const DEFAULT_AUTHOR: &str = "PdfCraft";
+/// The largest side of a stamp's box, in points: the largest page PDF allows (ISO 32000-2 Annex C).
+const MAX_STAMP_SIDE: f64 = 14_400.0;
pub(crate) fn parse_color(s: &str) -> Result<Rgb> {
let named = match s.to_ascii_lowercase().as_str() {
@@ -79,13 +81,11 @@ fn rect_to_user(p: &PageInfo, r: [f64; 4]) -> [f64; 4] {
}
/// The engine's `at` for a note or attachment icon whose top-left corner *as displayed* is the
-/// view point (x, y): the top-left (`[x0, y1]`) of the icon's square in user space. Converting
-/// the point alone is only right on unrotated pages — under `/Rotate` that corner of the
-/// displayed square is another corner of the user-space one, and the icon lands one icon-width
-/// away from where it was asked for.
+/// view point (x, y): the upper-left corner (`[x0, y1]`) of its `/Rect`. Notes and attachments
+/// are NoRotate, so on a turned page the icon is drawn upright with its top-left at that corner
+/// (ISO 32000-2 §12.5.3), and `comment_list` reports that square (`Annotation::shown_rect`).
fn icon_anchor(p: &PageInfo, x: f64, y: f64) -> [f64; 2] {
- let r = rect_to_user(p, [x, y, x + NOTE_SIZE, y + NOTE_SIZE]);
- [r[0], r[3]]
+ to_user(p, x, y)
}
/// A user-space rectangle as the displayed-page rectangle every tool reports and accepts:
@@ -154,8 +154,13 @@ impl Automation {
fn comment_target(&self, a: &Args) -> Result<(usize, usize)> {
let all = self.comments(a)?;
if let Some(id) = a.opt_str("id")? {
- let c =
- all.iter().find(|c| c.name.as_deref() == Some(id)).ok_or_else(|| failed(format!("no comment with id {id:?} (see comment_list)")))?;
+ // `/NM` need not be unique (PyMuPDF names the first comment on every page `fitz-A0`):
+ // the first match could be another page's comment, so a shared id is refused.
+ let mut named = all.iter().filter(|c| c.name.as_deref() == Some(id));
+ let c = named.next().ok_or_else(|| failed(format!("no comment with id {id:?} (see comment_list)")))?;
+ if named.next().is_some() {
+ return Err(failed(format!("several comments have the id {id:?}: pass page and index instead (see comment_list)")));
+ }
return Ok((c.page, c.index));
}
let (Some(page), Some(index)) = (a.opt_int("page")?, a.opt_int("index")?) else {
@@ -181,8 +186,7 @@ impl Automation {
"author": c.author,
"contents": c.contents,
"modified": c.modified,
- // Unchanged on a page the viewer could not read (#2660), as `doc_info` reports it.
- "rect": crate::view_rect(&doc.info, c.page, c.rect),
+ "rect": crate::view_rect(&doc.info, c.page, c.shown_rect(doc.info.pages.get(c.page).map_or(0, |p| p.rotation))),
"color": c.color.map(hex),
});
// A line's ends, or the corners of connected lines, a polygon or a cloud, as
@@ -196,33 +200,44 @@ impl Automation {
}
v
};
+ // Every reply under the comment its thread starts from, at any depth, in document order:
+ // a reply to a reply keeps its `/IRT` on the direct parent, so following one level would
+ // drop it. Parents are found by reference, as `/NM` need not be unique. A status or
+ // checkmark belongs to the annotation its `/IRT` names (ISO 32000-2 §12.5.6.2), as in the
+ // Comments panel: one set on a reply is not the comment's.
+ let tops = pdfcraft_render::thread_tops(&all);
+ let mut threads: HashMap<(usize, usize), Vec<&Annotation>> = HashMap::new();
+ for r in &all {
+ let Some(&top) = tops.get(&(r.page, r.index)) else { continue };
+ let key = match r.parent {
+ Some(parent) if r.state.is_some() => parent,
+ _ => top,
+ };
+ threads.entry(key).or_default().push(r);
+ }
+ // An annotation's review status and checkmark: the latest of each set on it.
+ let states = |c: &Annotation, v: &mut Value| {
+ let set = threads.get(&(c.page, c.index)).map(Vec::as_slice).unwrap_or(&[]);
+ v["status"] = json!(set.iter().rev().filter(|r| !r.is_mark()).find_map(|r| r.state.clone()));
+ v["marked"] = json!(set.iter().rev().find(|r| r.is_mark()).is_some_and(|r| r.state.as_deref() == Some("Marked")));
+ };
let roots: Vec<Value> = all
.iter()
- .filter(|c| c.in_reply_to.is_none() && only.is_none_or(|p| c.page == p))
+ .filter(|c| c.is_comment() && only.is_none_or(|p| c.page == p))
.map(|c| {
let mut v = view(c);
- // Every reply under this comment, at any depth, in document order. A reply to a
- // reply keeps its `/IRT` on the direct parent, so following one level would drop it.
- let descends_from = |r: &Annotation, root: &str| -> bool {
- let mut parent = r.in_reply_to.as_deref();
- for _ in 0..64 {
- let Some(nm) = parent else { return false };
- if nm == root {
- return true;
- }
- parent = all.iter().find(|x| x.name.as_deref() == Some(nm)).and_then(|x| x.in_reply_to.as_deref());
- }
- false
- };
- let thread: Vec<&Annotation> = match c.name.as_deref() {
- Some(nm) => all.iter().filter(|r| r.in_reply_to.is_some() && descends_from(r, nm)).collect(),
- None => Vec::new(),
- };
- let status = thread.iter().rev().filter(|r| !r.is_mark()).find_map(|r| r.state.clone());
- v["status"] = json!(status);
- v["marked"] = json!(thread.iter().rev().find(|r| r.is_mark()).is_some_and(|r| r.state.as_deref() == Some("Marked")));
+ states(c, &mut v);
v["locked"] = json!(c.locked);
- v["replies"] = thread.iter().filter(|r| r.state.is_none()).map(|r| view(r)).collect();
+ let thread = threads.get(&(c.page, c.index)).map(Vec::as_slice).unwrap_or(&[]);
+ v["replies"] = thread
+ .iter()
+ .filter(|r| r.state.is_none())
+ .map(|r| {
+ let mut reply = view(r);
+ states(r, &mut reply);
+ reply
+ })
+ .collect();
v
})
.collect();
@@ -385,7 +400,7 @@ impl Automation {
"attachment" => {
let [x, y] = a.need::<2>("at", "an attachment (its icon's top-left)")?;
let path = self.resolve(a.str("path")?, false)?;
- let data = std::fs::read(&path).map_err(|e| failed(format!("{}: {e}", path.display())))?;
+ let data = crate::read_input(&path)?;
let file = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
let icon = match a.opt_str("icon")? {
Some(n) => pdfcraft_engine::AttachIcon::from_name(n)
@@ -646,7 +661,12 @@ impl Automation {
edits.push(Edit::FontSizeAnnotation { page, index, size });
}
if let Some(r) = a.nums::<4>("rect")? {
- edits.push(Edit::ResizeAnnotation { page, index, rect: rect_to_user(&info, r) });
+ // The rectangle as comment_list reports it: where the comment is drawn.
+ let doc = self.doc(a)?;
+ let rect = rect_to_user(&info, r);
+ let rect =
+ doc.info.annotations.iter().find(|c| c.page == page && c.index == index).map_or(rect, |c| c.rect_for_shown(rect, info.rotation));
+ edits.push(Edit::ResizeAnnotation { page, index, rect });
}
if let Some([dx, dy]) = a.nums::<2>("move")? {
let (o, d) = (to_user(&info, 0.0, 0.0), to_user(&info, dx, dy));
@@ -682,19 +702,34 @@ impl Automation {
impl Automation {
/// A custom stamp: a picture file (PDF page or image) centred at `at`, at its natural size
- /// (at most 200 pt) or `width` points wide.
+ /// (at most 200 pt), or fitted inside `rect`, keeping its shape and centred (#4077).
pub(crate) fn stamp_custom(&mut self, a: &Args) -> Result<Value> {
let page = self.page(a)?;
let info = self.doc(a)?.info.pages[page].clone();
+ let rect = match (a.nums::<4>("rect")?, a.get("at")) {
+ (Some(_), Some(_)) => return Err(ToolError::InvalidArgs("pass at (a point) or rect (a box), not both".into())),
+ (Some(r), None) => {
+ let (w, h) = ((r[2] - r[0]).abs(), (r[3] - r[1]).abs());
+ if !((1.0..=MAX_STAMP_SIDE).contains(&w) && (1.0..=MAX_STAMP_SIDE).contains(&h)) {
+ return Err(ToolError::InvalidArgs(format!(
+ "rect must be [x0, y0, x1, y1] with each side at least 1 pt and at most {MAX_STAMP_SIDE} pt"
+ )));
+ }
+ rect_to_user(&info, r)
+ }
+ (None, _) => {
+ let [x, y] = a.need::<2>("at", "a stamp (its centre, or pass rect)")?;
+ let [ux, uy] = to_user(&info, x, y);
+ [ux, uy, ux, uy]
+ }
+ };
let path = self.resolve(a.str("path")?, false)?;
- let bytes = std::fs::read(&path).map_err(|e| failed(format!("{}: {e}", path.display())))?;
+ let bytes = crate::read_input(&path)?;
let file = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
let name = a.opt_str("name")?.map(str::to_owned).unwrap_or_else(|| file.rsplit_once('.').map_or(file.clone(), |(s, _)| s.to_owned()));
- let [x, y] = a.need::<2>("at", "a stamp (its centre)")?;
- let [ux, uy] = to_user(&info, x, y);
let edit = Edit::AddCustomStamp {
page,
- rect: [ux, uy, ux, uy],
+ rect,
name,
file: pdfcraft_engine::MarkFile {
name: file,
diff --git a/crates/automation/src/content.rs b/crates/automation/src/content.rs
index 8926a13..d0b0b69 100644
--- a/crates/automation/src/content.rs
+++ b/crates/automation/src/content.rs
@@ -2,7 +2,7 @@
//! move/resize/retype/restyle it, delete it. Geometry is in points from the top-left of the
//! displayed page (y down), like every other tool.
-use pdfcraft_engine::{AddedContent, AddedText, Edit, FontFamily, TextAlign};
+use pdfcraft_engine::{ADDED_CHAR_SPACING_LIMIT, AddedContent, AddedText, Edit, FontFamily, TextAlign};
use serde_json::{Value, json};
use crate::comments::parse_color;
@@ -61,6 +61,12 @@ fn style(a: &Args, t: &mut AddedText) -> Result<()> {
other => return Err(bad(format!("unknown align {other:?}"))),
};
}
+ if let Some(c) = a.opt_num("char_spacing")? {
+ if !(-ADDED_CHAR_SPACING_LIMIT..=ADDED_CHAR_SPACING_LIMIT).contains(&c) {
+ return Err(bad(format!("char_spacing must be between -{ADDED_CHAR_SPACING_LIMIT} and {ADDED_CHAR_SPACING_LIMIT} points")));
+ }
+ t.char_spacing = c;
+ }
Ok(())
}
@@ -85,6 +91,7 @@ impl Automation {
v["size"] = json!(t.size);
v["bold"] = json!(t.bold);
v["italic"] = json!(t.italic);
+ v["char_spacing"] = json!(t.char_spacing);
}
AddedContent::Image(_) => v["type"] = json!("image"),
}
@@ -118,7 +125,7 @@ impl Automation {
let page = self.page(a)?;
let ph = self.doc(a)?.info.pages[page].height as f64;
let path = self.resolve(a.str("path")?, false)?;
- let bytes = std::fs::read(&path).map_err(|e| failed(format!("{}: {e}", path.display())))?;
+ let bytes = crate::read_input(&path)?;
let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
let rect = rect_arg(a, "rect")?.map(|r| to_display(r, ph));
let mut out = self.apply(a, Edit::AddImage { page, rect, name, bytes: std::sync::Arc::new(bytes) })?;
@@ -164,8 +171,8 @@ impl Automation {
if a.get("text").is_some() {
return Err(bad("images have no text"));
}
- if ["font", "size", "bold", "italic", "color", "align"].iter().any(|k| a.get(k).is_some()) {
- return Err(bad("font, size, bold, italic, color and align apply to text"));
+ if ["font", "size", "bold", "italic", "color", "align", "char_spacing"].iter().any(|k| a.get(k).is_some()) {
+ return Err(bad("font, size, bold, italic, color, align and char_spacing apply to text"));
}
if let Some(deg) = a.opt_int("rotate")? {
if deg.rem_euclid(90) != 0 {
@@ -188,7 +195,7 @@ impl Automation {
}
if let Some(p) = a.opt_str("image")? {
let path = self.resolve(p, false)?;
- let bytes = std::fs::read(&path).map_err(|e| failed(format!("{}: {e}", path.display())))?;
+ let bytes = crate::read_input(&path)?;
let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
// Box and transforms first, then the new picture.
self.apply(a, Edit::UpdateContent { page, index, content: content.clone() })?;
@@ -203,6 +210,63 @@ impl Automation {
let (page, index, _, _) = self.item(a)?;
self.apply(a, Edit::DeleteContent { page, index })
}
+
+ /// Edit ▸ Copy, then Paste: an added item onto `to_page` of `to_doc` (its own page and
+ /// document by default), as it is, at `at` (its top-left) or where it was, stepped down and to
+ /// the right past copies of it already on that page.
+ pub(crate) fn content_copy(&mut self, a: &Args) -> Result<Value> {
+ let (page, index, content, _) = self.item(a)?;
+ let source = self.doc(a)?;
+ source.check_copying()?;
+ let from = source.id;
+ let file = match &content {
+ AddedContent::Text(_) => None,
+ AddedContent::Image(_) => {
+ let (ext, bytes) = source.added_image_file(page, index).map_err(failed)?;
+ Some((format!("Pasted image.{ext}"), std::sync::Arc::new(bytes)))
+ }
+ };
+ let to_doc = match a.opt_int("to_doc")? {
+ Some(d) => {
+ let d = u64::try_from(d).map_err(|_| bad("to_doc must be positive"))?;
+ self.session.get(pdfcraft_engine::DocId(d)).ok_or_else(|| failed(format!("no open document with id {d} (see doc_list)")))?.id
+ }
+ None => from,
+ };
+ let doc = self.session.get(to_doc).ok_or_else(|| failed("the document is no longer open"))?;
+ let n = doc.info.pages.len();
+ let to_page = match a.opt_int("to_page")? {
+ Some(p) => usize::try_from(p)
+ .ok()
+ .and_then(|p| p.checked_sub(1))
+ .filter(|p| *p < n)
+ .ok_or_else(|| bad(format!("to_page {p} is out of range: the document has {n} pages")))?,
+ None if page < n => page,
+ None => return Err(bad(format!("page {} is out of range in the target: it has {n} pages; pass to_page", page + 1))),
+ };
+ let info = doc.info.pages.get(to_page).ok_or_else(|| bad("the page no longer exists"))?;
+ let (pw, ph) = (f64::from(info.width), f64::from(info.height));
+ let at = match a.get("at") {
+ Some(v) => {
+ let p: Option<Vec<f64>> = v.as_array().and_then(|x| x.iter().map(Value::as_f64).collect());
+ let [x, y]: [f64; 2] = p.and_then(|p| p.try_into().ok()).ok_or_else(|| bad("at must be [x, y]"))?;
+ Some([x, ph - y])
+ }
+ None => None,
+ };
+ let on_page = || doc.added().iter().filter(|x| x.page == to_page);
+ let rect = match at {
+ Some(at) => pdfcraft_engine::added_paste_rect(content.rect(), [pw, ph], 0, Some(at)),
+ None => pdfcraft_engine::added_paste_place(on_page().map(|x| &x.content), &content, [pw, ph]),
+ };
+ let before = on_page().count();
+ let target = json!({ "doc": to_doc.0 });
+ let mut out = self.apply(&Args(&target), Edit::PasteContent { page: to_page, content: content.with_rect(rect), file })?;
+ out["page"] = json!(to_page + 1);
+ out["index"] = json!(before + 1);
+ out["rect"] = json!(to_view(rect, ph).map(|x| (x * 100.0).round() / 100.0));
+ Ok(out)
+ }
}
impl Automation {
diff --git a/crates/automation/src/file_access.rs b/crates/automation/src/file_access.rs
index 55b1066..1556e3c 100644
--- a/crates/automation/src/file_access.rs
+++ b/crates/automation/src/file_access.rs
@@ -9,6 +9,9 @@
//! links are followed: for a file that doesn't exist yet, the links of its nearest existing
//! folder, the rest of the path being plain names (`..` below a missing folder is refused, and so
//! is a link that leads nowhere).
+//! - A path on another network share or in a device namespace (`\\host\share`, `\\.\pipe\x`)
+//! than the root's is refused by name, before anything is resolved: resolving it would contact
+//! the host.
//! - The result must lie inside the root, compared by whole components (`/work2` isn't inside
//! `/work`), without regard to case on Windows.
//! - Read and write access are separate: a root given alone grants only its own kind of access.
@@ -97,7 +100,10 @@ impl AutomationRoots {
Access::Write => Err(format!("automation filesystem access is not granted: write authority is absent: {shown}")),
};
};
- if inside(&resolve(shown, target)?, folder) {
+ let absolute = absolute(shown, target)?;
+ // Another network share or a device is refused by name, as `--root` refuses it: even
+ // resolving the path would contact the host (#4003).
+ if !foreign_share(&absolute, folder) && inside(&resolve(shown, &absolute)?, folder) {
return Ok(());
}
let root = root_shown.display();
@@ -123,9 +129,8 @@ fn plain(path: PathBuf) -> PathBuf {
}
}
-/// `path` made absolute with its links followed; for a path that doesn't exist (yet), its nearest
-/// existing folder's links followed and the rest appended.
-fn resolve(shown: &str, path: &Path) -> Result<PathBuf, String> {
+/// `path` made absolute against the working directory, by name: nothing on disk is read.
+fn absolute(shown: &str, path: &Path) -> Result<PathBuf, String> {
if path.as_os_str().is_empty() {
return Err("automation path rejected: path is empty".into());
}
@@ -133,10 +138,15 @@ fn resolve(shown: &str, path: &Path) -> Result<PathBuf, String> {
if cfg!(windows) && path.components().any(|c| matches!(c, Component::Normal(n) if is_device_name(&n.to_string_lossy()))) {
return Err(format!("automation path rejected: reserved device names are not allowed: {shown}"));
}
- let absolute = std::path::absolute(path).map_err(|e| format!("automation path rejected: cannot resolve {shown}: {e}"))?;
+ std::path::absolute(path).map_err(|e| format!("automation path rejected: cannot resolve {shown}: {e}"))
+}
+
+/// `absolute` with its links followed; for a path that doesn't exist (yet), its nearest existing
+/// folder's links followed and the rest appended.
+fn resolve(shown: &str, absolute: &Path) -> Result<PathBuf, String> {
// The names below the nearest existing folder, last first.
let mut missing: Vec<OsString> = vec![];
- let mut at = absolute.as_path();
+ let mut at = absolute;
loop {
match std::fs::canonicalize(at) {
Ok(mut found) => {
@@ -189,6 +199,24 @@ fn same_component(a: Component, b: Component) -> bool {
}
}
+/// Whether `path` names another network share or device namespace than `root` (Windows
+/// `\\host\share`, `\\?\UNC\…`, `\\.\…`, `\\?\…`). Those are refused by name: even checking
+/// that one exists would contact the host. Drive letters are left to the normal check.
+pub(crate) fn foreign_share(path: &Path, root: &Path) -> bool {
+ use std::path::Prefix;
+ fn share(p: &Path) -> Option<String> {
+ let Some(Component::Prefix(prefix)) = p.components().next() else { return None };
+ let (kind, a, b) = match prefix.kind() {
+ Prefix::Disk(_) | Prefix::VerbatimDisk(_) => return None,
+ Prefix::UNC(host, share) | Prefix::VerbatimUNC(host, share) => ("unc", host, share),
+ Prefix::DeviceNS(name) => ("device", name, std::ffi::OsStr::new("")),
+ Prefix::Verbatim(name) => ("verbatim", name, std::ffi::OsStr::new("")),
+ };
+ Some(format!("{kind}\\{}\\{}", a.to_string_lossy(), b.to_string_lossy()).to_lowercase())
+ }
+ share(path).is_some_and(|s| share(root).as_ref() != Some(&s))
+}
+
/// A Windows device name (`CON`, `NUL`, `COM1`… also with an extension), which names no file.
fn is_device_name(component: &str) -> bool {
let stem = component.split('.').next().unwrap_or(component).trim_end_matches(' ').to_ascii_uppercase();
@@ -233,6 +261,27 @@ mod tests {
let _ = std::fs::remove_dir_all(base);
}
+ /// #4003: another share or a device namespace is refused by name, with the same words as any
+ /// other path outside the root, before anything is resolved (which would contact the host).
+ #[cfg(windows)]
+ #[test]
+ fn other_shares_and_devices_are_refused_before_they_are_resolved() {
+ let (base, roots) = folders("shares");
+ for p in [
+ r"\\.\pipe\pdfcraft-4003.pdf",
+ r"\\?\GLOBALROOT\Device\Null",
+ r"\\pdfcraft-no-such-host.invalid\share\a.pdf",
+ "//pdfcraft-no-such-host.invalid/share/a.pdf",
+ r"\\?\UNC\pdfcraft-no-such-host.invalid\share\a.pdf",
+ ] {
+ let e = roots.check(p, Access::Read).unwrap_err();
+ assert!(e.starts_with("automation path rejected: outside the read root"), "{p}: {e}");
+ let e = roots.check(p, Access::Write).unwrap_err();
+ assert!(e.starts_with("automation path rejected: outside the write root"), "{p}: {e}");
+ }
+ let _ = std::fs::remove_dir_all(base);
+ }
+
#[test]
fn a_sibling_with_the_same_prefix_is_outside() {
let (base, roots) = folders("prefix");
@@ -345,7 +394,8 @@ mod tests {
// Helpers that are only called with a resolved path. `doc_batch` (batch.rs) resolves its
// inputs and out_dir, walks only inside them (skipping links) and resolves every
// discovered file again before `process` reads it or `publish` writes it.
- const RESOLVED_BY_CALLER: &[&str] = &["write_atomic", "write_atomic_with", "read_review_sidecar", "process", "linked", "walk", "publish"];
+ const RESOLVED_BY_CALLER: &[&str] =
+ &["write_atomic", "write_atomic_with", "read_input", "read_input_bytes", "read_review_sidecar", "process", "linked", "walk", "publish"];
let dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("src");
let mut offenders = vec![];
for entry in std::fs::read_dir(&dir).unwrap() {
@@ -365,7 +415,8 @@ mod tests {
|| !(trimmed.contains("std::fs")
|| trimmed.contains("File::open")
|| trimmed.contains("File::create")
- || trimmed.contains("OpenOptions"))
+ || trimmed.contains("OpenOptions")
+ || trimmed.contains("read_input"))
{
continue;
}
diff --git a/crates/automation/src/forms.rs b/crates/automation/src/forms.rs
index 26e7b9d..71fbc67 100644
--- a/crates/automation/src/forms.rs
+++ b/crates/automation/src/forms.rs
@@ -288,6 +288,23 @@ impl Automation {
let edit = if edits.len() == 1 { edits.remove(0) } else { Edit::Batch { label: "Fill in form".into(), edits } };
let mut out = self.apply(a, edit)?;
out["filled"] = json!(values.len());
+ // A value the box cuts off at a fixed font size is saved whole but shows only in part:
+ // said, not silent (#4018).
+ let doc = self.doc(a)?;
+ let cut: Vec<Value> = values
+ .keys()
+ .filter_map(|name| doc.field_overflow(name).map(|(page, o)| (name, page, o)))
+ .map(|(name, page, o)| {
+ let page = page.map(|p| format!(" (page {})", p.saturating_add(1))).unwrap_or_default();
+ json!(format!("form field {name:?}{page}: {o}, so the box shows only part of it (the whole value is saved)"))
+ })
+ .collect();
+ if !cut.is_empty() {
+ match out.get_mut("warnings").and_then(Value::as_array_mut) {
+ Some(w) => w.extend(cut),
+ None => out["warnings"] = Value::Array(cut),
+ }
+ }
Ok(out)
}
@@ -684,7 +701,7 @@ impl Automation {
pub(crate) fn doc_import_data(&mut self, a: &Args) -> Result<Value> {
let path = self.resolve(a.str("path")?, false)?;
- let bytes = std::fs::read(&path).map_err(|e| failed(format!("{}: {e}", path.display())))?;
+ let bytes = crate::read_input(&path)?;
let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
let before = (self.doc(a)?.info.annotations.len(), self.doc(a)?.form.iter().filter(|f| !f.value.is_empty()).count());
let mut out = self.apply(a, Edit::ImportData { name, bytes: std::sync::Arc::new(bytes) })?;
diff --git a/crates/automation/src/lib.rs b/crates/automation/src/lib.rs
index 765adf0..83de1d7 100644
--- a/crates/automation/src/lib.rs
+++ b/crates/automation/src/lib.rs
@@ -106,6 +106,7 @@ const MAX_BOOKMARK_POSITION: f64 = 1_000_000.0;
const FIND_FIRST_BATCH: usize = 8;
const FIND_MAX_BATCH: usize = 128;
+use file_access::foreign_share;
use text_cache::TextCache;
type PageTexts = Vec<(usize, std::result::Result<Arc<PageText>, String>)>;
@@ -394,6 +395,36 @@ impl Automation {
let (path, page) = (a.path("path")?, self.page(&a)?);
self.apply(&a, Edit::SetBookmarkPage { path, page })?
}
+ "bookmark_set_style" => {
+ let path = a.path("path")?;
+ // Left out keeps the colour; [0, 0, 0] is the default black.
+ let color = match a.get("color") {
+ None => None,
+ Some(v) => {
+ let rgb: Option<Vec<f64>> = v.as_array().and_then(|c| c.iter().map(Value::as_f64).collect());
+ match rgb.as_deref() {
+ Some(&[r, g, b]) if [r, g, b].iter().all(|c| (0.0..=1.0).contains(c)) => Some([r, g, b]),
+ _ => return Err(ToolError::InvalidArgs("color must be [r, g, b], each from 0 to 1".into())),
+ }
+ }
+ };
+ let (bold, italic) = (a.opt_bool("bold")?, a.opt_bool("italic")?);
+ if color.is_none() && bold.is_none() && italic.is_none() {
+ return Err(ToolError::InvalidArgs("give color, bold or italic".into()));
+ }
+ let mut edits = Vec::new();
+ if let Some(color) = color {
+ edits.push(Edit::SetBookmarkColor { path: path.clone(), color: Some(color) });
+ }
+ if bold.is_some() || italic.is_some() {
+ edits.push(Edit::SetBookmarkStyle { path, bold, italic });
+ }
+ // A colour and a style given together are one step to undo, applied all or nothing.
+ match edits.len() {
+ 1 => self.apply(&a, edits.remove(0))?,
+ _ => self.apply(&a, Edit::Batch { label: "Style".into(), edits })?,
+ }
+ }
"bookmark_from_structure" => {
let mut out = self.apply(&a, Edit::BookmarksFromStructure)?;
let listing = self.bookmark_listing(&a)?;
@@ -405,7 +436,7 @@ impl Automation {
"page_replace" => {
let pages = self.pages(&a, "pages")?;
let path = self.resolve(a.str("path")?, false)?;
- let bytes = Arc::new(std::fs::read(&path).map_err(|e| failed(format!("{}: {e}", path.display())))?);
+ let bytes = Arc::new(read_input(&path)?);
let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
let src_pages = match a.opt_ints("from_pages")? {
Some(p) => one_based(&p)?,
@@ -554,7 +585,7 @@ impl Automation {
"delete" => ImageEdit::Delete,
"replace" => {
let path = self.resolve(a.str("path")?, false)?;
- let bytes = std::fs::read(&path).map_err(|e| failed(format!("{}: {e}", path.display())))?;
+ let bytes = read_input(&path)?;
ImageEdit::Replace {
name: path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(),
bytes: Arc::new(bytes),
@@ -789,7 +820,7 @@ impl Automation {
"form_fill" => self.form_fill(&a)?,
"form_set_image" => {
let path = self.resolve(a.str("path")?, false)?;
- let bytes = std::fs::read(&path).map_err(|e| failed(format!("{}: {e}", path.display())))?;
+ let bytes = read_input(&path)?;
self.apply(&a, Edit::SetFieldImage { name: a.str("field")?.to_owned(), image: Arc::new(bytes) })?
}
"form_reset" => self.form_reset(&a)?,
@@ -821,7 +852,27 @@ impl Automation {
"page_add_image" => self.page_add_image(&a)?,
"content_update" => self.content_update(&a)?,
"content_delete" => self.content_delete(&a)?,
+ "content_copy" => self.content_copy(&a)?,
"doc_print" => self.doc_print(&a)?,
+ "attachment_add" => {
+ let path = self.resolve(a.str("path")?, false)?;
+ let bytes = read_input(&path)?;
+ let name = match a.opt_str("name")? {
+ Some(n) => n.to_string(),
+ None => path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(),
+ };
+ let mime = pdfcraft_engine::mime_for_name(&name).map(str::to_string);
+ let description = a.opt_str("description")?.map(str::to_string);
+ // Only the document-level keys: an annotation attachment of the same name is not the new one.
+ let before = document_attachment_keys(self.doc(&a)?);
+ let out = self.apply(&a, Edit::AddAttachment { name, bytes, description, mime })?;
+ let key = document_attachment_keys(self.doc(&a)?).into_iter().find(|n| !before.contains(n)).unwrap_or_default();
+ json!({ "name": key, "document": out })
+ }
+ "attachment_delete" => {
+ let edit = Edit::DeleteAttachment { key: a.str("name")?.into() };
+ self.apply(&a, edit)?
+ }
"doc_remove_hidden" => self.doc_remove_hidden(&a)?,
"doc_audit_redactions" => self.doc_audit_redactions(&a)?,
"fill_sign_add" => self.fill_sign_add(&a)?,
@@ -1023,7 +1074,7 @@ impl Automation {
fn doc_open(&mut self, a: &Args) -> Result<Value> {
let path = self.resolve(a.str("path")?, false)?;
- let bytes = std::fs::read(&path).map_err(|e| failed(format!("{}: {e}", path.display())))?;
+ let bytes = read_input(&path)?;
let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
let id = self.session.open(name, Some(path.to_string_lossy().into_owned()), Arc::new(bytes), a.opt_str("password")?).map_err(failed)?;
let doc = self.session.get(id).ok_or_else(|| failed("the document vanished"))?;
@@ -1201,7 +1252,7 @@ impl Automation {
}
fn doc_optimize(&mut self, a: &Args) -> Result<Value> {
- use pdfcraft_engine::optimize::{Compression, ImageSettings, Preset};
+ use pdfcraft_engine::optimize::{Compatibility, Compression, ImageSettings, Preset};
let id = self.doc(a)?.id;
let before = self.doc(a)?.bytes.len();
let path = self.resolve(a.str("path")?, true)?;
@@ -1209,6 +1260,10 @@ impl Automation {
None => Preset::Standard.settings(),
Some(p) => Preset::from_name(p).ok_or_else(|| ToolError::InvalidArgs(format!("unknown preset {p:?} (standard, mobile)")))?.settings(),
};
+ if let Some(c) = a.opt_str("compatibility")? {
+ settings.compatibility = Compatibility::from_name(c)
+ .ok_or_else(|| ToolError::InvalidArgs(format!("unknown compatibility {c:?} (retain, 1.4, 1.5, 1.6, 1.7, 2.0)")))?;
+ }
let images = |key: &str, base: ImageSettings| -> Result<ImageSettings> {
let Some(v) = a.get(key) else { return Ok(base) };
let mut s = base;
@@ -1242,6 +1297,8 @@ impl Automation {
("discard_tags", &mut settings.discard_tags),
("discard_print_settings", &mut settings.discard_print_settings),
("flate_unencoded", &mut settings.flate_unencoded),
+ ("object_streams", &mut settings.object_streams),
+ ("lzw_to_flate", &mut settings.lzw_to_flate),
("remove_invalid_links", &mut settings.remove_invalid_links),
("remove_unreferenced_dests", &mut settings.remove_unreferenced_dests),
] {
@@ -1264,9 +1321,26 @@ impl Automation {
};
let (bytes, r) = self.session.optimized_bytes(id, &settings, &discard).map_err(failed)?;
write_atomic(&path, &bytes)?;
+ fn valid_version(v: &[u8]) -> Option<&str> {
+ if matches!(v, [b'1'..=b'9', b'.', b'0'..=b'9']) { std::str::from_utf8(v).ok() } else { None }
+ }
+ let catalog_version = (settings.compatibility == Compatibility::Retain)
+ .then(|| {
+ let pw = self.doc(a).ok().and_then(|d| d.password.as_deref());
+ let doc = pdfcraft_cos::Document::open_with_password(bytes.clone(), pw).ok()?;
+ let root = doc.root()?;
+ doc.get(root).as_dict()?.name(b"Version").and_then(valid_version).map(str::to_owned)
+ })
+ .flatten();
+ let header_version = bytes.strip_prefix(b"%PDF-").and_then(|b| b.get(..3)).and_then(valid_version);
+ // Viewers read the later of the two (object streams raise the header past a lower catalog
+ // entry). Both are "d.d", so text order is version order.
+ let pdf_version = catalog_version.as_deref().into_iter().chain(header_version).max();
let o = &r.optimize;
Ok(json!({
"path": path.to_string_lossy(),
+ "pdf_version": pdf_version,
+ "object_streams": settings.effective_object_streams(),
"bytes_before": before,
"bytes_after": bytes.len(),
"merged_images": o.merged_images,
@@ -1280,6 +1354,7 @@ impl Automation {
"alternate_images": o.alternate_images,
"tags_removed": o.tags_removed,
"streams_compressed": o.streams_compressed,
+ "lzw_streams": o.lzw_streams,
"invalid_links": o.invalid_links,
"invalid_bookmarks": o.invalid_bookmarks,
"unreferenced_dests": o.unreferenced_dests,
@@ -1293,7 +1368,7 @@ impl Automation {
fn mark_file(&self, a: &Args) -> Result<Option<pdfcraft_engine::MarkFile>> {
let Some(p) = a.opt_str("file")? else { return Ok(None) };
let path = self.resolve(p, false)?;
- let bytes = std::fs::read(&path).map_err(|e| failed(format!("{}: {e}", path.display())))?;
+ let bytes = read_input(&path)?;
let page = a.opt_int("file_page")?.unwrap_or(1).max(1) as usize - 1;
Ok(Some(pdfcraft_engine::MarkFile {
name: path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(),
@@ -1476,7 +1551,7 @@ impl Automation {
let mut images = Vec::new();
for p in a.strs("paths")? {
let path = self.resolve(p, false)?;
- let bytes = std::fs::read(&path).map_err(|e| failed(format!("{}: {e}", path.display())))?;
+ let bytes = read_input(&path)?;
images.push((path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(), bytes));
}
let name = if images.len() == 1 {
@@ -1491,7 +1566,7 @@ impl Automation {
(Some(t), _) => ("Text".to_string(), t.to_string()),
(None, Some(p)) => {
let path = self.resolve(p, false)?;
- let t = std::fs::read(&path).map_err(|e| failed(format!("{}: {e}", path.display())))?;
+ let t = read_input(&path)?;
(path.file_stem().map(|s| s.to_string_lossy().into_owned()).unwrap_or_default(), pdfcraft_engine::decode_text(&t))
}
(None, None) => return Err(ToolError::InvalidArgs("text needs `text` or `path`".into())),
@@ -1687,7 +1762,7 @@ impl Automation {
fn insert_file(&mut self, a: &Args) -> Result<Value> {
let at = self.position(a, "at")?;
let path = self.resolve(a.str("path")?, false)?;
- let bytes = std::fs::read(&path).map_err(|e| failed(format!("{}: {e}", path.display())))?;
+ let bytes = read_input(&path)?;
let pages = a.opt_ints("pages")?.map(|p| one_based(&p)).transpose()?;
let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
self.apply(a, Edit::InsertPagesFrom { name, bytes: Arc::new(bytes), pages, at, field_conflicts: pdfcraft_organize::FieldConflicts::Rename })
@@ -1730,7 +1805,7 @@ impl Automation {
// Each file is read, converted and copied in turn, so a long list holds one file at a time.
let sources = paths.into_iter().zip(ranges).map(|(p, range)| -> std::result::Result<pdfcraft_engine::CombineSource, ToolError> {
let path = self.resolve(p, false)?;
- let bytes = std::fs::read(&path).map_err(|e| failed(format!("{}: {e}", path.display())))?;
+ let bytes = read_input(&path)?;
let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
let (_, pdf) = self.session.convert_to_pdf(&name, &Arc::new(bytes)).map_err(failed)?;
let title = path.file_stem().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
@@ -1747,7 +1822,7 @@ impl Automation {
let mut out = Vec::new();
for &p in paths {
let converted = self.resolve(p, false).map_err(|e| e.to_string()).and_then(|src| {
- let bytes = std::fs::read(&src).map_err(|e| format!("{}: {e}", src.display()))?;
+ let bytes = read_input_bytes(&src).map_err(|e| format!("{}: {e}", src.display()))?;
let name = src.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
let stem = src.file_stem().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| "document".into());
let (kind, pdf) = self.session.convert_to_pdf(&name, &Arc::new(bytes)).map_err(|e| e.to_string())?;
@@ -1851,7 +1926,7 @@ impl Automation {
if let Some(g) = group {
firsts.push((g, path.clone(), sources.len()));
}
- let bytes = Arc::new(std::fs::read(&path).map_err(|e| failed(format!("{}: {e}", path.display())))?);
+ let bytes = Arc::new(read_input(&path)?);
// Images and text files are made into PDFs first (#569), as in the Combine files tab.
let file_name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
self.session.as_pdf(&file_name, &bytes).map_err(failed)?
@@ -2344,24 +2419,6 @@ fn lexical(path: &Path) -> Option<PathBuf> {
Some(parts.iter().collect())
}
-/// Whether `path` names another network share or device namespace than `root` (Windows
-/// `\\host\share`, `\\?\UNC\…`, `\\.\…`, `\\?\…`). Those are refused by name: even checking
-/// that one exists would contact the host. Drive letters are left to the normal check.
-fn foreign_share(path: &Path, root: &Path) -> bool {
- use std::path::{Component, Prefix};
- fn share(p: &Path) -> Option<String> {
- let Some(Component::Prefix(prefix)) = p.components().next() else { return None };
- let (kind, a, b) = match prefix.kind() {
- Prefix::Disk(_) | Prefix::VerbatimDisk(_) => return None,
- Prefix::UNC(host, share) | Prefix::VerbatimUNC(host, share) => ("unc", host, share),
- Prefix::DeviceNS(name) => ("device", name, std::ffi::OsStr::new("")),
- Prefix::Verbatim(name) => ("verbatim", name, std::ffi::OsStr::new("")),
- };
- Some(format!("{kind}\\{}\\{}", a.to_string_lossy(), b.to_string_lossy()).to_lowercase())
- }
- share(path).is_some_and(|s| share(root).as_ref() != Some(&s))
-}
-
// ---- JSON helpers ----------------------------------------------------------------------------
fn parse_style_ranges(value: Option<&Value>) -> Result<Vec<pdfcraft_engine::RangeStyle>> {
@@ -2478,6 +2535,18 @@ impl Args<'_> {
}
}
+/// The name-tree keys of a document's own attachments, leaving out the files attached to pages as comments.
+fn document_attachment_keys(doc: &Document) -> Vec<String> {
+ doc.info
+ .attachments
+ .iter()
+ .filter_map(|x| match &x.source {
+ pdfcraft_render::AttachmentSource::Document { key } => Some(key.clone()),
+ pdfcraft_render::AttachmentSource::Annotation { .. } => None,
+ })
+ .collect()
+}
+
/// Bookmark rows in listing order as JSON: a row holds the rows that follow it on the page at the
/// next level down in `children`, and paths and pages are 1-based.
fn nest_rows(rows: &[pdfcraft_engine::BookmarkRow], pages: &[pdfcraft_render::PageInfo]) -> Vec<Value> {
@@ -2491,6 +2560,16 @@ fn nest_rows(rows: &[pdfcraft_engine::BookmarkRow], pages: &[pdfcraft_render::Pa
}
let path: Vec<usize> = row.path.iter().map(|p| p.saturating_add(1)).collect();
let mut fields = json!({ "path": path, "title": row.title, "page": row.page.map(|p| p.saturating_add(1)), "open": row.open });
+ // Only what differs from the defaults (black, regular), as the PDF itself stores it.
+ if let Some(color) = row.color {
+ fields["color"] = json!(color);
+ }
+ if row.bold {
+ fields["bold"] = json!(true);
+ }
+ if row.italic {
+ fields["italic"] = json!(true);
+ }
if let Some(destination) = row.page.and_then(|p| pages.get(p)).and_then(|p| destination(&row.view, p)) {
fields["destination"] = destination;
}
@@ -2602,6 +2681,9 @@ fn info(d: &Document) -> Value {
"creator": i.creator, "producer": i.producer,
"tagged": i.tagged,
"has_javascript": i.has_javascript,
+ // Where the document opens (/OpenAction, named destinations resolved): 1-based page and
+ // destination, null without one.
+ "open_destination": i.open_dest.as_ref().map(|(p, view)| json!({ "page": page1(*p), "destination": i.pages.get(*p).and_then(|pg| destination(view, pg)) })),
// XFA forms: "static" (the PDF's own fields work; the XFA data is ignored) or "dynamic"
// (laid out from the template by PdfCraft, see xfa_layout; placeholder pages when that failed).
"xfa": i.xfa.map(|x| match x { pdfcraft_render::Xfa::Static => "static", pdfcraft_render::Xfa::Dynamic => "dynamic" }),
@@ -2622,7 +2704,8 @@ fn info(d: &Document) -> Value {
// geometry-taking tools (#129).
"annotations": i.annotations.iter().map(|a| json!({
"page": page1(a.page), "type": a.subtype, "author": a.author, "contents": a.contents,
- "modified": a.modified, "name": a.name, "in_reply_to": a.in_reply_to, "rect": view_rect(i, a.page, a.rect),
+ "modified": a.modified, "name": a.name, "in_reply_to": a.in_reply_to,
+ "rect": view_rect(i, a.page, a.shown_rect(i.pages.get(a.page).map_or(0, |p| p.rotation))),
})).collect::<Vec<_>>(),
"fields": i.fields.iter().map(|f| json!({
"name": f.name, "kind": format!("{:?}", f.kind), "value": f.value, "page": f.page.map(page1),
@@ -2644,7 +2727,8 @@ fn info(d: &Document) -> Value {
})).collect::<Vec<_>>(),
"preserve_rb": preserve_rb,
}),
- pdfcraft_render::LinkTarget::RemoteGoTo { file, destination, new_window } => json!({
+ pdfcraft_render::LinkTarget::RemoteGoTo { launch, file, destination, new_window } => json!({
+ "action": if *launch { "Launch" } else { "GoToR" },
"remote_document": file,
"destination": match destination {
pdfcraft_render::RemoteDestination::Default => json!({ "kind": "default" }),
@@ -2705,7 +2789,7 @@ fn extract_parallel(bytes: &Arc<Vec<u8>>, password: Option<Arc<str>>, pages: &[u
}
};
let config = RenderConfig { password, ..Default::default() };
- let workers = if cfg!(target_arch = "wasm32") { 1 } else { std::thread::available_parallelism().map_or(1, |n| n.get()).min(8) };
+ let workers = if cfg!(target_arch = "wasm32") { 1 } else { std::thread::available_parallelism().map_or(1, std::num::NonZeroUsize::get).min(8) };
// Small jobs aren't worth a second parse of the document.
if workers == 1 || pages.len() < 8 {
let mut r = PageRenderer::new(bytes.clone(), config);
@@ -2753,6 +2837,28 @@ fn unused(dir: &Path, stem: &str) -> PathBuf {
(2..10_000u32).map(|n| child(dir, &format!("{stem} ({n}).pdf"))).find(|p| !p.exists()).unwrap_or(first)
}
+/// Largest input file a tool reads into memory (512 MiB, matching `doc_batch`).
+pub(crate) const MAX_INPUT: u64 = 512 * 1024 * 1024;
+
+/// Read a resolved input file of at most [`MAX_INPUT`] bytes without buffering past the cap.
+pub(crate) fn read_input_bytes(path: &Path) -> std::io::Result<Vec<u8>> {
+ use std::io::Read as _;
+ let file = std::fs::File::open(path)?;
+ if file.metadata().is_ok_and(|m| m.is_file() && m.len() > MAX_INPUT) {
+ return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "input exceeds 512 MiB"));
+ }
+ let mut bytes = Vec::new();
+ file.take(MAX_INPUT + 1).read_to_end(&mut bytes)?;
+ if bytes.len() as u64 > MAX_INPUT {
+ return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "input exceeds 512 MiB"));
+ }
+ Ok(bytes)
+}
+
+pub(crate) fn read_input(path: &Path) -> Result<Vec<u8>> {
+ read_input_bytes(path).map_err(|e| failed(format!("{}: {e}", path.display())))
+}
+
/// Write and sync a temporary file in the same directory, then rename over the target.
/// This flushes staged contents; it does not promise parent-directory durability after a
/// power loss. Filesystems that refuse sync cause the save to fail before publication.
@@ -3310,4 +3416,36 @@ mod tests {
assert!(a.session.get(id).is_none());
}
}
+
+ #[test]
+ fn tool_file_reads_refuse_inputs_exceeding_512_mib() {
+ let dir = staging_dir("capped-read");
+ let huge = dir.join("huge.bin");
+ let file = std::fs::File::create(&huge).unwrap();
+ file.set_len(MAX_INPUT + 1).unwrap();
+ drop(file);
+ let huge_str = huge.to_string_lossy().into_owned();
+
+ let mut a = Automation::new();
+ let id = a.session.open("a.pdf", None, Arc::new(numbered_pages(2)), None).unwrap().0;
+ for (tool, args) in [
+ ("doc_open", json!({ "path": huge_str })),
+ ("page_insert_file", json!({ "doc": id, "at": 1, "path": huge_str })),
+ ("page_replace", json!({ "doc": id, "pages": [1], "path": huge_str })),
+ ("page_add_image", json!({ "doc": id, "page": 1, "path": huge_str })),
+ ("doc_import_data", json!({ "doc": id, "path": huge_str })),
+ ("doc_create", json!({ "from": "text", "path": huge_str })),
+ ("doc_create", json!({ "from": "images", "paths": [huge_str] })),
+ ("doc_combine", json!({ "paths": [huge_str, huge_str] })),
+ ("form_merge_data", json!({ "paths": [huge_str], "path": dir.join("out.csv").to_string_lossy() })),
+ ("comment_add", json!({ "doc": id, "page": 1, "type": "attachment", "at": [72.0, 72.0], "path": huge_str })),
+ ("stamp_custom", json!({ "doc": id, "page": 1, "at": [72.0, 72.0], "path": huge_str })),
+ ("sign_trust", json!({ "paths": [huge_str] })),
+ ("attachment_add", json!({ "doc": id, "path": huge_str })),
+ ] {
+ let err = a.call(tool, &args).unwrap_err().to_string();
+ assert!(err.contains("input exceeds 512 MiB"), "{tool}: {err}");
+ }
+ let _ = std::fs::remove_dir_all(&dir);
+ }
}
diff --git a/crates/automation/src/links.rs b/crates/automation/src/links.rs
index 8058d56..41fda9b 100644
--- a/crates/automation/src/links.rs
+++ b/crates/automation/src/links.rs
@@ -117,7 +117,7 @@ impl Automation {
.iter()
.find(|link| link.page == page && link.index == index)
.ok_or_else(|| failed(format!("page {page_number} has no link {index_number} (see link_list)")))?;
- let LinkTarget::RemoteGoTo { file, destination, new_window } = &link.target else {
+ let LinkTarget::RemoteGoTo { file, destination, new_window, .. } = &link.target else {
return Err(bad("the selected link is not a supported local PDF GoToR link"));
};
(source.path.clone(), file.clone(), destination.clone(), *new_window)
diff --git a/crates/automation/src/mcp.rs b/crates/automation/src/mcp.rs
index f5fda5b..84cc21b 100644
--- a/crates/automation/src/mcp.rs
+++ b/crates/automation/src/mcp.rs
@@ -25,6 +25,10 @@ const PARSE_ERROR: i64 = -32700;
const INVALID_REQUEST: i64 = -32600;
const METHOD_NOT_FOUND: i64 = -32601;
const INVALID_PARAMS: i64 = -32602;
+const INTERNAL_ERROR: i64 = -32603;
+
+/// Longest JSON-RPC request line [`McpServer::serve`] buffers into memory (16 MiB).
+pub const MAX_LINE_BYTES: usize = 16 * 1024 * 1024;
const INSTRUCTIONS: &str = "PdfCraft edits PDFs. Open a file with doc_open to get a document id, then inspect \
(doc_info, text_extract, text_find, page_render) or edit it (page_*, doc_set_info). Edits are undoable \
@@ -83,18 +87,36 @@ impl McpServer {
}
/// Serve until `input` reaches end of file.
- pub fn serve(&mut self, input: impl BufRead, mut output: impl Write) -> std::io::Result<()> {
- for line in input.lines() {
- let line = line?;
- if line.trim().is_empty() {
- continue;
+ pub fn serve(&mut self, mut input: impl BufRead, mut output: impl Write) -> std::io::Result<()> {
+ let mut buf = Vec::new();
+ loop {
+ match read_line_limited(&mut input, &mut buf, MAX_LINE_BYTES)? {
+ LineRead::End => return Ok(()),
+ LineRead::TooLong => {
+ drain_line(&mut input)?;
+ buf.clear();
+ buf.shrink_to(64 * 1024);
+ let reply = error(Value::Null, INVALID_REQUEST, &format!("request line exceeds {MAX_LINE_BYTES} bytes"));
+ writeln!(output, "{reply}")?;
+ output.flush()?;
+ continue;
+ }
+ LineRead::Line => {}
}
- if let Some(reply) = self.handle_line(&line) {
+ let reply = match std::str::from_utf8(&buf) {
+ Ok(line) if line.trim().is_empty() => None,
+ Ok(line) => self.handle_line(line),
+ Err(e) => Some(error(Value::Null, PARSE_ERROR, &format!("parse error: {e}")).to_string()),
+ };
+ if buf.capacity() > 64 * 1024 {
+ buf.clear();
+ buf.shrink_to(64 * 1024);
+ }
+ if let Some(reply) = reply {
writeln!(output, "{reply}")?;
output.flush()?;
}
}
- Ok(())
}
/// Handle one JSON-RPC message; returns the serialized reply, if one is due.
@@ -116,7 +138,7 @@ impl McpServer {
};
let params = obj.get("params").cloned().unwrap_or(Value::Null);
let id = id?; // notifications/initialized, notifications/cancelled, …: nothing to answer
- let result = if method == "tools/call" { guarded_tool(|| self.dispatch(method, &params)) } else { self.dispatch(method, &params) };
+ let result = guarded_dispatch(method, || self.dispatch(method, &params));
Some(match result {
Ok(result) => json!({ "jsonrpc": "2.0", "id": id, "result": result }),
Err((code, message)) => error(id, code, &message),
@@ -323,11 +345,67 @@ fn unwrap_tool_call(args: &Value) -> Result<(String, Value), String> {
Ok((name.to_owned(), inner))
}
+/// What [`read_line_limited`] found.
+#[derive(Debug, PartialEq, Eq)]
+enum LineRead {
+ /// A line, now in the buffer (newline and a trailing `\r` stripped).
+ Line,
+ /// End of stream.
+ End,
+ /// The line is longer than the limit; at most `max + 1` bytes of it were read.
+ TooLong,
+}
+
+/// Read one `\n`-terminated line of at most `max` bytes into `buf`.
+fn read_line_limited(reader: &mut impl BufRead, buf: &mut Vec<u8>, max: usize) -> std::io::Result<LineRead> {
+ use std::io::Read as _;
+ buf.clear();
+ // `take` bounds what is buffered for one line: never more than `max + 1` bytes.
+ let limit = u64::try_from(max).unwrap_or(u64::MAX).saturating_add(1);
+ if reader.take(limit).read_until(b'\n', buf)? == 0 {
+ return Ok(LineRead::End);
+ }
+ if buf.last() == Some(&b'\n') {
+ buf.pop();
+ if buf.last() == Some(&b'\r') {
+ buf.pop();
+ }
+ return Ok(LineRead::Line);
+ }
+ // No newline: either the limit was passed, or this is a last line before end of stream.
+ Ok(if buf.len() > max { LineRead::TooLong } else { LineRead::Line })
+}
+
+/// Discard the rest of an overlong line up to `\n` or end of stream without buffering it.
+fn drain_line(reader: &mut impl BufRead) -> std::io::Result<()> {
+ loop {
+ let chunk = reader.fill_buf()?;
+ if chunk.is_empty() {
+ return Ok(());
+ }
+ if let Some(pos) = chunk.iter().position(|&b| b == b'\n') {
+ reader.consume(pos + 1);
+ return Ok(());
+ }
+ let len = chunk.len();
+ reader.consume(len);
+ }
+}
+
/// Last-resort boundary shared by every tools/call route, including compact dispatch.
fn guarded_tool(f: impl FnOnce() -> Result<Value, (i64, String)>) -> Result<Value, (i64, String)> {
pdfcraft_engine::guard(f).unwrap_or_else(|message| Ok(tool_error(&format!("internal error: {message}"))))
}
+/// Last-resort boundary for every JSON-RPC method: tool calls report panics in the tool result
+/// (`isError: true`), while resource and protocol methods report a JSON-RPC internal error.
+fn guarded_dispatch(method: &str, f: impl FnOnce() -> Result<Value, (i64, String)>) -> Result<Value, (i64, String)> {
+ if method == "tools/call" {
+ return guarded_tool(f);
+ }
+ pdfcraft_engine::guard(f).unwrap_or_else(|message| Err((INTERNAL_ERROR, format!("internal error: {message}"))))
+}
+
fn tool_content(name: &str, content: Vec<Content>) -> Value {
let failed = matches!(name, "command_batch" | "doc_batch")
&& content.iter().any(|c| match c {
@@ -509,7 +587,12 @@ fn call_result(content: Vec<Content>) -> Value {
#[cfg(test)]
mod tests {
- use super::{Resource, first_sentence, parse_uri};
+ use std::io::{BufReader, Read as _};
+
+ use serde_json::{Value, json};
+
+ use super::{McpServer, Resource, first_sentence, parse_uri};
+ use crate::Automation;
#[test]
fn conventions_panic_is_a_tool_error() {
@@ -520,6 +603,59 @@ mod tests {
assert_eq!(next["ok"], true);
}
+ #[test]
+ fn guarded_dispatch_catches_resource_and_protocol_panics() {
+ for method in ["resources/read", "resources/list", "resources/templates/list", "initialize"] {
+ let (code, msg) = super::guarded_dispatch(method, || panic!("synthetic {method} failure")).unwrap_err();
+ assert_eq!(code, -32603, "{method}");
+ assert!(msg.contains(&format!("synthetic {method} failure")), "{msg}");
+ }
+ let ok = super::guarded_dispatch("resources/list", || Ok(json!({"resources": []}))).unwrap();
+ assert_eq!(ok["resources"], json!([]));
+ }
+
+ #[test]
+ fn read_line_limited_and_drain_line_respect_boundaries() {
+ use super::{LineRead, drain_line, read_line_limited};
+ let mut buf = Vec::new();
+ let mut input: &[u8] = b"aaaaaaaaaa\nbb\r\ncc";
+ assert_eq!(read_line_limited(&mut input, &mut buf, 10).unwrap(), LineRead::Line);
+ assert_eq!(buf, b"aaaaaaaaaa", "a line exactly at the limit is accepted");
+ assert_eq!(read_line_limited(&mut input, &mut buf, 10).unwrap(), LineRead::Line);
+ assert_eq!(buf, b"bb", "CRLF is stripped");
+ assert_eq!(read_line_limited(&mut input, &mut buf, 10).unwrap(), LineRead::Line);
+ assert_eq!(buf, b"cc", "a last line without a newline is still read");
+ assert_eq!(read_line_limited(&mut input, &mut buf, 10).unwrap(), LineRead::End);
+
+ let mut overlong: &[u8] = b"0123456789abcdef\nafter\n";
+ assert_eq!(read_line_limited(&mut overlong, &mut buf, 10).unwrap(), LineRead::TooLong);
+ assert_eq!(buf.len(), 11, "at most max + 1 bytes are buffered");
+ drain_line(&mut overlong).unwrap();
+ assert_eq!(read_line_limited(&mut overlong, &mut buf, 10).unwrap(), LineRead::Line);
+ assert_eq!(buf, b"after", "the next line after an overlong line is read cleanly");
+ }
+
+ #[test]
+ fn serve_answers_non_utf8_and_overlong_lines_and_keeps_serving() {
+ let init = json!({
+ "jsonrpc": "2.0",
+ "id": 1,
+ "method": "initialize",
+ "params": { "protocolVersion": "2025-06-18", "capabilities": {}, "clientInfo": { "name": "test", "version": "0" } }
+ })
+ .to_string();
+ let tail = format!("\n{init}\n");
+ let stream = (&b"\xff\n"[..]).chain(std::io::repeat(b'a').take(64 * 1024 * 1024)).chain(tail.as_bytes());
+ let mut out = Vec::new();
+ McpServer::new(Automation::new()).serve(BufReader::new(stream), &mut out).unwrap();
+ let replies: Vec<Value> = String::from_utf8(out).unwrap().lines().map(|l| serde_json::from_str(l).unwrap()).collect();
+ assert_eq!(replies.len(), 3, "{replies:?}");
+ assert_eq!(replies[0]["error"]["code"], -32700);
+ assert_eq!(replies[1]["error"]["code"], -32600);
+ assert_eq!(replies[2]["id"], 1);
+ assert_eq!(replies[2]["result"]["serverInfo"]["name"], "pdfcraft");
+ }
+
#[test]
fn first_sentence_skips_abbreviations() {
assert_eq!(first_sentence("Rotate pages. Undoable."), "Rotate pages.");
diff --git a/crates/automation/src/printing.rs b/crates/automation/src/printing.rs
index 39cd457..9a1c1a6 100644
--- a/crates/automation/src/printing.rs
+++ b/crates/automation/src/printing.rs
@@ -22,11 +22,72 @@ fn duplex(value: &str, cut_stack: bool) -> Result<Option<spool::Duplex>> {
})
}
+/// [`duplex`] for a job laid out as `layout`: the name is checked either way, and a booklet
+/// decides two-sided itself (#2707), as the Print dialog does (`print::booklet_duplex`).
+fn job_duplex(value: &str, layout: &Layout) -> Result<Option<spool::Duplex>> {
+ let chosen = duplex(value, matches!(layout, Layout::Multiple { order: PageOrder::CutStack, .. }))?;
+ Ok(match layout {
+ Layout::Booklet { subset, .. } => Some(print::booklet_duplex(*subset)),
+ _ => chosen,
+ })
+}
+
+/// An invalid-arguments error saying `m`.
fn bad(m: impl Into<String>) -> ToolError {
ToolError::InvalidArgs(m.into())
}
+/// `doc_print`'s `paper`, by its name or a short form ("Letter", "ARCH D"), as its `PAPERS`
+/// index and size; US Letter when none is given.
+fn paper_named(name: Option<&str>) -> Result<(usize, (f64, f64))> {
+ let mut papers = PAPERS.iter().enumerate();
+ let found = match name {
+ None => papers.next(),
+ Some(p) => papers.find(|(_, (n, _))| {
+ n.eq_ignore_ascii_case(p)
+ || n.replace("US ", "").eq_ignore_ascii_case(p)
+ || n.split(" (").next().is_some_and(|name| name.eq_ignore_ascii_case(p))
+ }),
+ };
+ found.map(|(index, (_, size))| (index, *size)).ok_or_else(|| {
+ bad(format!(
+ "unknown paper {:?}; choose one of {}",
+ name.unwrap_or_default(),
+ PAPERS.iter().map(|(name, _)| *name).collect::<Vec<_>>().join(", ")
+ ))
+ })
+}
+
+/// The spooler job for `doc_print` to `printer`. It feeds the paper the PDF was laid out on
+/// (`PAPERS[paper]`, as `media` after the driver's `options`) rather than the queue's default
+/// paper, which a job naming none got (A4 under Letter sheets on the queue in #3752).
+fn spool_job(a: &Args, printer: &str, title: String, duplex: Option<spool::Duplex>, paper: usize) -> Result<spool::Job> {
+ let options = match a.get("options") {
+ None => Vec::new(),
+ Some(Value::Object(m)) => m
+ .iter()
+ .map(|(k, v)| match v.as_str() {
+ Some(v) => Ok((k.clone(), v.to_string())),
+ None => Err(bad(format!("options.{k} must be a string (a choice from printer_options)"))),
+ })
+ .collect::<Result<Vec<_>>>()?,
+ Some(_) => return Err(bad("options must be an object of option keys and choices from printer_options")),
+ };
+ Ok(spool::Job {
+ printer: if printer == "default" { None } else { Some(printer.to_string()) },
+ copies: a.opt_int("copies")?.unwrap_or(1).clamp(1, 999) as u32,
+ collate: a.opt_bool("collate")?.unwrap_or(true),
+ duplex,
+ scaling: spool::Scaling::Exact,
+ grayscale: a.opt_bool("grayscale")?.unwrap_or(false),
+ title,
+ options: options.into_iter().chain(print::media_option(paper)).collect(),
+ })
+}
+
impl Automation {
+ /// `printers`: the system's printers, the default marked, and each one's two-sided support
+ /// where the spooler reports it.
pub(crate) fn printers(&self) -> Result<Value> {
let list: Vec<Value> = spool::printers()
.into_iter()
@@ -53,6 +114,8 @@ impl Automation {
Ok(json!({ "printer": printer, "count": list.len(), "options": list }))
}
+ /// `doc_print`: lay the document out with the Print dialog's options, then save the
+ /// print-ready PDF to `path` or send it to `printer` with the chosen paper.
pub(crate) fn doc_print(&mut self, a: &Args) -> Result<Value> {
let doc = self.doc(a)?;
let (id, count) = (doc.id, doc.info.pages.len());
@@ -108,7 +171,7 @@ impl Automation {
},
l => return Err(bad(format!("unknown layout {l:?}"))),
};
- let duplex = duplex(a.opt_str("duplex")?.unwrap_or("off"), matches!(layout, Layout::Multiple { order: PageOrder::CutStack, .. }))?;
+ let duplex = job_duplex(a.opt_str("duplex")?.unwrap_or("off"), &layout)?;
if a.opt_str("order")? == Some("cut-stack") && !matches!(layout, Layout::Multiple { .. }) {
return Err(bad("cut-stack order needs layout multiple"));
}
@@ -125,20 +188,7 @@ impl Automation {
"form-fields-only" => Content::FormFieldsOnly,
c => return Err(bad(format!("unknown comments_forms {c:?}"))),
};
- let paper = match a.opt_str("paper")? {
- None => PAPERS[0].1,
- Some(p) => PAPERS
- .iter()
- .find(|(n, _)| {
- n.eq_ignore_ascii_case(p)
- || n.replace("US ", "").eq_ignore_ascii_case(p)
- || n.split(" (").next().is_some_and(|name| name.eq_ignore_ascii_case(p))
- })
- .map(|x| x.1)
- .ok_or_else(|| {
- bad(format!("unknown paper {p:?}; choose one of {}", PAPERS.iter().map(|(name, _)| *name).collect::<Vec<_>>().join(", ")))
- })?,
- };
+ let (paper_index, paper) = paper_named(a.opt_str("paper")?)?;
// Print as image (Acrobat's Advanced Print Setup): pictures at `dpi`, grey when
// `grayscale` is also asked for.
let raster = if a.opt_bool("as_image")?.unwrap_or(false) {
@@ -162,27 +212,7 @@ impl Automation {
out["path"] = json!(path.to_string_lossy());
}
(None, Some(printer)) => {
- let name = self.doc(a)?.name.clone();
- let job = spool::Job {
- printer: if printer == "default" { None } else { Some(printer.to_string()) },
- copies: a.opt_int("copies")?.unwrap_or(1).clamp(1, 999) as u32,
- collate: a.opt_bool("collate")?.unwrap_or(true),
- duplex,
- scaling: spool::Scaling::Exact,
- grayscale: a.opt_bool("grayscale")?.unwrap_or(false),
- title: name,
- options: match a.get("options") {
- None => Vec::new(),
- Some(Value::Object(m)) => m
- .iter()
- .map(|(k, v)| match v.as_str() {
- Some(v) => Ok((k.clone(), v.to_string())),
- None => Err(bad(format!("options.{k} must be a string (a choice from printer_options)"))),
- })
- .collect::<Result<Vec<_>>>()?,
- Some(_) => return Err(bad("options must be an object of option keys and choices from printer_options")),
- },
- };
+ let job = spool_job(a, printer, self.doc(a)?.name.clone(), duplex, paper_index)?;
out["job"] = json!(spool::submit(&bytes, &job).map_err(|e| failed(e.to_string()))?);
}
_ => return Err(bad("pass either path (save the print-ready PDF) or printer (a name from printers, or \"default\")")),
@@ -195,6 +225,19 @@ impl Automation {
mod tests {
use super::*;
+ /// #2707: a booklet sets two-sided itself whatever `duplex` asks; a bad name is still an error.
+ #[test]
+ fn a_booklet_decides_two_sided_itself() {
+ let booklet = |subset| Layout::Booklet { subset, binding: Binding::Left };
+ for asked in ["printer", "off", "long-edge", "short-edge"] {
+ assert_eq!(job_duplex(asked, &booklet(BookletSubset::BothSides)).ok(), Some(Some(spool::Duplex::ShortEdge)), "{asked}");
+ assert_eq!(job_duplex(asked, &booklet(BookletSubset::FrontOnly)).ok(), Some(Some(spool::Duplex::Off)), "{asked}");
+ assert_eq!(job_duplex(asked, &booklet(BookletSubset::BackOnly)).ok(), Some(Some(spool::Duplex::Off)), "{asked}");
+ }
+ assert!(job_duplex("sideways", &booklet(BookletSubset::BothSides)).is_err());
+ assert_eq!(job_duplex("long-edge", &Layout::Size(SizeMode::Fit)).ok(), Some(Some(spool::Duplex::LongEdge)), "other layouts keep it");
+ }
+
/// `printer` leaves two-sided to the printer's own default (#2422); cut and stack still asks
/// for single-sided sheets, and refuses an explicit edge.
#[test]
@@ -207,4 +250,30 @@ mod tests {
assert!(duplex("long-edge", true).is_err());
assert!(duplex("sideways", false).is_err());
}
+
+ /// #3752: `doc_print` to a printer sent no paper, so the queue's default paper stood in for
+ /// the one the sheets were laid out on (A4 under Letter sheets on the report's queue).
+ #[test]
+ fn printing_to_a_printer_feeds_the_laid_out_paper() {
+ let job = |args: Value, paper_name: Option<&str>| {
+ let (index, _) = paper_named(paper_name).unwrap();
+ spool_job(&Args(&args), "Office", "a.pdf".into(), None, index).unwrap()
+ };
+ let media = |m: &str| ("media".to_string(), m.to_string());
+ // US Letter when no paper is asked for, after the driver's own options.
+ let letter = job(json!({ "options": { "InputSlot": "Tray3" } }), None);
+ assert_eq!(letter.options, [("InputSlot".to_string(), "Tray3".to_string()), media("Letter")]);
+ assert_eq!((letter.printer.as_deref(), letter.title.as_str()), (Some("Office"), "a.pdf"));
+ // Every paper, by its full name, goes out as its own media name.
+ for (i, (name, size)) in PAPERS.iter().enumerate() {
+ assert_eq!(paper_named(Some(name)).ok(), Some((i, *size)), "{name}");
+ assert_eq!(job(json!({}), Some(name)).options, print::media_option(i).into_iter().collect::<Vec<_>>(), "{name}");
+ }
+ // Short forms find the same paper.
+ assert_eq!(job(json!({}), Some("letter")).options, [media("Letter")]);
+ assert_eq!(job(json!({}), Some("ARCH D")).options, [media("na_arch-d_24x36in")]);
+ assert!(matches!(paper_named(Some("Quarto")), Err(ToolError::InvalidArgs(m)) if m.contains("US Letter")));
+ assert_eq!(spool_job(&Args(&json!({})), "default", String::new(), None, 0).ok().map(|j| j.printer), Some(None));
+ assert!(spool_job(&Args(&json!({ "options": { "InputSlot": 3 } })), "Office", String::new(), None, 0).is_err());
+ }
}
diff --git a/crates/automation/src/signing.rs b/crates/automation/src/signing.rs
index c7a043c..743a36f 100644
--- a/crates/automation/src/signing.rs
+++ b/crates/automation/src/signing.rs
@@ -189,7 +189,7 @@ impl Automation {
return Err(failed(format!("windows:{r}: Windows certificate store identities are only available on Windows")));
}
let path = self.resolve(a.str("id")?, false)?;
- let bytes = std::fs::read(&path).map_err(|e| failed(format!("{}: {e}", path.display())))?;
+ let bytes = crate::read_input(&path)?;
sign::pkcs12::open(&bytes, a.opt_str("password")?.unwrap_or("")).map_err(|e| match e {
sign::SignError::WrongPassword => bad("the digital ID password is incorrect"),
e => failed(e),
@@ -320,7 +320,7 @@ impl Automation {
};
for p in paths {
let path = self.resolve(&p, false)?;
- let bytes = std::fs::read(&path).map_err(|e| failed(format!("{}: {e}", path.display())))?;
+ let bytes = crate::read_input(&path)?;
let lower = p.to_ascii_lowercase();
let found = if lower.ends_with(".p12") || lower.ends_with(".pfx") {
let id = sign::pkcs12::open(&bytes, a.opt_str("password")?.unwrap_or("")).map_err(failed)?;
diff --git a/crates/automation/src/tools.rs b/crates/automation/src/tools.rs
index 8232975..95abc54 100644
--- a/crates/automation/src/tools.rs
+++ b/crates/automation/src/tools.rs
@@ -60,7 +60,10 @@ fn color() -> Value {
fn comment_ref(mut extra: Value) -> Value {
if let Some(props) = extra.as_object_mut() {
props.insert("doc".into(), doc());
- props.insert("id".into(), json!({ "type": "string", "description": "The comment's id (from comment_list)." }));
+ props.insert(
+ "id".into(),
+ json!({ "type": "string", "description": "The comment's id (from comment_list). An id several comments share is refused: pass page and index." }),
+ );
props.insert("page".into(), json!({ "type": "integer", "minimum": 1, "description": "With `index`, instead of `id`." }));
props.insert(
"index".into(),
@@ -129,11 +132,17 @@ pub fn tools() -> Vec<ToolDef> {
"dpi": {"type":"number","minimum":72,"maximum":600},
"language": {"type":"string"}, "skip_text_pages": {"type":"boolean"}
}), &["paths","out_dir","steps"])),
+ t("attachment_add", "Attach a file", "Attach the file at path to the document (document level, the Attachments panel; not a paper-clip comment on a page). name defaults to the file's name; the attachment's key, unique in the document, is returned. Undoable.")
+ .cmd("edit.attach")
+ .with(schema(json!({"doc": doc(), "path": {"type": "string"}, "name": {"type": "string"}, "description": {"type": "string"}}), &["doc", "path"])),
+ t("attachment_delete", "Delete an attachment", "Remove the document-level attachment with this name (as doc_info lists it). Undoable.")
+ .destructive()
+ .with(schema(json!({"doc": doc(), "name": {"type": "string"}}), &["doc", "name"])),
t("doc_open", "Open a PDF", "Open a PDF file and return its document id, page count and whether it can be edited.")
.cmd("file.open")
.with(schema(json!({ "path": { "type": "string" }, "password": { "type": "string", "description": "User or owner password for encrypted files." } }), &["path"])),
t("doc_list", "List open documents", "List the open documents with their ids, page counts and unsaved state.").ro().with(schema(json!({}), &[])),
- t("doc_info", "Inspect a document", "Metadata, page sizes and labels, bookmarks, annotations, form fields, links, layers, page transitions and display times, attachments, fonts, security and repair notes.")
+ t("doc_info", "Inspect a document", "Metadata, page sizes and labels, bookmarks, annotations, form fields, links, layers, page transitions and display times, the destination it opens at, attachments, fonts, security and repair notes.")
.ro()
.cmd("file.properties")
.with(schema(json!({ "doc": doc() }), &["doc"])),
@@ -281,7 +290,7 @@ pub fn tools() -> Vec<ToolDef> {
t(
"bookmark_list",
"List bookmarks",
- "The bookmarks in outline order, one page at a time: each with its path (1-based, as the other bookmark tools take it), title, target page and open state, and its children on the same page. next is the offset of the following page, or null at the end. Bookmarks nested deeper than 33 levels are not listed.",
+ "The bookmarks in outline order, one page at a time: each with its path (1-based, as the other bookmark tools take it), title, target page and open state, its colour ([r, g, b], 0-1) and bold or italic style when it has them, and its children on the same page. next is the offset of the following page, or null at the end. Bookmarks nested deeper than 33 levels are not listed.",
)
.ro()
.with(schema(
@@ -320,6 +329,21 @@ pub fn tools() -> Vec<ToolDef> {
)),
t("bookmark_set_page", "Set a bookmark's page", "Point a bookmark at another page. Undoable.")
.with(schema(json!({ "doc": doc(), "path": path("The bookmark"), "page": { "type": "integer", "minimum": 1 } }), &["doc", "path", "page"])),
+ t(
+ "bookmark_set_style",
+ "Set a bookmark's style and colour",
+ "Colour a bookmark's title and make it bold or italic (ISO 32000-2 §12.3.3: /C and /F), as bookmark_list reports them. Give any of color ([r, g, b], each 0-1; [0, 0, 0] is the default black), bold and italic; what is left out stays as it is. Undoable.",
+ )
+ .with(schema(
+ json!({
+ "doc": doc(),
+ "path": path("The bookmark"),
+ "color": { "type": "array", "items": { "type": "number", "minimum": 0, "maximum": 1 }, "minItems": 3, "maxItems": 3 },
+ "bold": { "type": "boolean" },
+ "italic": { "type": "boolean" }
+ }),
+ &["doc", "path"],
+ )),
t(
"bookmark_from_structure",
"New bookmarks from structure",
@@ -352,7 +376,7 @@ pub fn tools() -> Vec<ToolDef> {
t(
"form_add_field",
"Prepare form: add a field",
- "Add a form field on a page. type: text, date, checkbox, radio, combo, list, button, image (a picture placeholder; fill it with form_set_image), signature. rect in points from the top-left of the displayed page [x0, y0, x1, y1]. name defaults to Acrobat's next free name (Text1, Check Box1, Group1, Dropdown1, List Box1, Button1, Image1, Signature1, Date1). Radio buttons join the radio group named by group (a new group otherwise) with the export value export. Returns the field's name. Undoable.",
+ "Add a form field on a page. type: text, date, checkbox, radio, combo, list, button, image (a picture placeholder; fill it with form_set_image), signature. rect in points from the top-left of the displayed page [x0, y0, x1, y1]. name defaults to Acrobat's next free name (Text1, Check Box1, Group1, Dropdown1, List Box1, Button1, Image1, Signature1, Date1); a dotted name such as MASTER.first makes the field first under the parent field MASTER. Radio buttons join the radio group named by group (a new group otherwise) with the export value export. Returns the field's name. Undoable.",
)
.with(schema(
json!({
@@ -392,7 +416,7 @@ pub fn tools() -> Vec<ToolDef> {
}),
&["doc", "page", "rect", "rows"],
)),
- t("stamp_custom", "Add a custom stamp", "Stamp a picture: a PDF page (file_page, default 1) or an image file, centred at at [x, y] (points from the top-left of the displayed page) at its natural size, at most 200 pt. name labels it (default: the file name). Undoable.")
+ t("stamp_custom", "Add a custom stamp", "Stamp a picture: a PDF page (file_page, default 1, kept as vector content in a form XObject) or an image file. Either centred at at [x, y] (points from the top-left of the displayed page) at its natural size, at most 200 pt, or fitted inside rect [x0, y0, x1, y1] (the same coordinates; each side 1–14400 pt), scaled to keep its shape and centred in the box. Like at, rect is not clipped to the page. Pass at or rect, not both. name labels it (default: the file name). Undoable.")
.cmd("comment.stamp")
.with(schema(
json!({
@@ -400,18 +424,19 @@ pub fn tools() -> Vec<ToolDef> {
"page": { "type": "integer", "minimum": 1 },
"path": { "type": "string" },
"at": { "type": "array", "items": { "type": "number" }, "minItems": 2, "maxItems": 2 },
+ "rect": { "type": "array", "items": { "type": "number" }, "minItems": 4, "maxItems": 4 },
"file_page": { "type": "integer", "minimum": 1 },
"name": { "type": "string" },
"author": { "type": "string" },
}),
- &["doc", "page", "path", "at"],
+ &["doc", "page", "path"],
)),
t("form_set_image", "Set an image field's picture", "Show an image file (PNG, JPEG, TIFF, GIF or BMP) in an image field or button, scaled to fit and centred (what clicking an image field does). On an XFA form the picture is kept in its data too (base64, as Designer saves it) and the form shows it from there. Undoable.")
.with(schema(json!({ "doc": doc(), "field": { "type": "string" }, "path": { "type": "string" } }), &["doc", "field", "path"])),
t(
"form_set_props",
"Field properties",
- "Change field properties: give field for one field, or fields for a list of unique field names (1–1000). A bulk change is atomic and one Undo step; an invalid or locked field leaves every field unchanged. Only the given properties change, and partial appearance changes preserve each field's other colours and font. name (rename), rect (position), rotation and caption require a single field. A rename also renames the field in the calculations that read it (calculate field lists and notation, and getField calls naming it in a string literal; names built at run time are not rewritten), in the same Undo step, and formulas_updated lists the fields whose calculation changed. caption changes one push-button normal label (widget: 1-based index, default 1); an empty string clears it. Other widgets and icon-only layouts are preserved. General and Options: tooltip, read_only, required, multiline, max_length (0 = no limit), options (combo/list items), font_size (0 = auto), format, validate, calculate (Acrobat's native AF rules). Options: align (left, center, right), default (Reset form's value; check boxes/radio buttons use their on state, \"\" for off), flags { scroll, rich_text, password, file_select, spell_check, comb (needs max_length), sort, editable, multi_select, commit_immediately }, check_style (check boxes/radio buttons: check, circle, cross, diamond, square, star). rotation is 0, 90, 180 or 270 degrees counterclockwise and swaps width/height when the axis changes. Undoable.",
+ "Change field properties: give field for one field, or fields for a list of unique field names (1–1000). A bulk change is atomic and one Undo step; an invalid or locked field leaves every field unchanged. Only the given properties change, and partial appearance changes preserve each field's other colours and font. name (rename: a dotted name such as MASTER.first is the full name and moves the field under those parent fields; a plain name renames it within its parent), rect (position), rotation and caption require a single field. A rename also renames the field in the calculations that read it (calculate field lists and notation, and getField calls naming it in a string literal; names built at run time are not rewritten), in the same Undo step, and formulas_updated lists the fields whose calculation changed. caption changes one push-button normal label (widget: 1-based index, default 1); an empty string clears it. Other widgets and icon-only layouts are preserved. General and Options: tooltip, read_only, required, multiline, max_length (0 = no limit), options (combo/list items), font_size (0 = auto), format, validate, calculate (Acrobat's native AF rules). Options: align (left, center, right), default (Reset form's value; check boxes/radio buttons use their on state, \"\" for off), flags { scroll, rich_text, password, file_select, spell_check, comb (needs max_length), sort, editable, multi_select, commit_immediately }, check_style (check boxes/radio buttons: check, circle, cross, diamond, square, star). rotation is 0, 90, 180 or 270 degrees counterclockwise and swaps width/height when the axis changes. Undoable.",
)
.with(schema(
json!({
@@ -530,7 +555,7 @@ pub fn tools() -> Vec<ToolDef> {
t(
"doc_print",
"Print",
- "Print with Acrobat's Print dialog options, or save the print-ready PDF. pages: a range such as \"1-3, 6, 9-\" (page labels allowed; default all); subset odd/even; reverse. layout: fit (default), actual, shrink, custom (scale %), multiple (per_sheet 2/4/6/9/16, order, border, auto_rotate; cut-stack order arranges single-sided sheets for cutting into piles and stacking left to right, top to bottom, keeping sheet order within each pile; duplex must be off), booklet (booklet_subset both/front/back, binding left/right), poster (scale %, overlap pt, cut_marks). orientation auto/portrait/landscape; comments_forms document / document-and-markups (default) / document-and-stamps / form-fields-only; paper Letter/Legal/Tabloid, ARCH A/B/C/D/E1/E, ANSI C/D/E, A0/A1/A2/A3/A4/A5/A6, or US #10 Envelope (short names or full preset labels); use layout actual for 100% in the print-ready PDF; printer drivers may still substitute paper or scale. Then path (save) or printer (a name or \"default\") with copies, collate, duplex off/long-edge/short-edge, grayscale, and options (driver options from printer_options, CUPS).",
+ "Print with Acrobat's Print dialog options, or save the print-ready PDF. pages: a range such as \"1-3, 6, 9-\" (page labels allowed; default all); subset odd/even (by page number, as Acrobat counts them: pages 2, 7-10 with even prints 2, 8 and 10, not every second page of the range); reverse. layout: fit (default), actual, shrink, custom (scale %), multiple (per_sheet 2/4/6/9/16, order, border, auto_rotate; cut-stack order arranges single-sided sheets for cutting into piles and stacking left to right, top to bottom, keeping sheet order within each pile; duplex must be off), booklet (booklet_subset both/front/back, binding left/right; a booklet sets two-sided itself, as Acrobat does: both flips on the short edge, front or back prints one-sided), poster (scale %, overlap pt, cut_marks). orientation auto/portrait/landscape; comments_forms document / document-and-markups (default) / document-and-stamps / form-fields-only; paper Letter/Legal/Tabloid, ARCH A/B/C/D/E1/E, ANSI C/D/E, A0/A1/A2/A3/A4/A5/A6, or US #10 Envelope (short names or full preset labels); use layout actual for 100% in the print-ready PDF; printer drivers may still substitute paper or scale. Then path (save) or printer (a name or \"default\") with copies, collate, duplex off/long-edge/short-edge, grayscale, and options (driver options from printer_options, CUPS).",
)
.with(schema(
json!({
@@ -569,7 +594,7 @@ pub fn tools() -> Vec<ToolDef> {
t(
"page_add_text",
"Add text to a page",
- "Add text as page content (not a comment). Place it with at [x, y] (top-left, points from the top-left of the displayed page) and width (wrap width, default 200), or rect. Newlines start new lines; long lines wrap. Style: font helvetica/times/courier, size, bold, italic, color (#RRGGBB or a name), align left/center/right. Text must be Western European (WinAnsi) characters, or Arabic, Hebrew or Thai when the build has their craft-fonts faces (drawn right to left where the text is); others are refused. It stays editable with content_update. Undoable.",
+ "Add text as page content (not a comment). Place it with at [x, y] (top-left, points from the top-left of the displayed page) and width (wrap width, default 200), or rect. Newlines start new lines; long lines wrap. Style: font helvetica/times/courier, size, bold, italic, color (#RRGGBB or a name), align left/center/right, char_spacing (points after each character). Text must be Western European (WinAnsi) characters, or Arabic, Hebrew or Thai when the build has their craft-fonts faces (drawn right to left where the text is); others are refused. It stays editable with content_update. Undoable.",
)
.cmd("edit.text")
.with(schema(
@@ -581,6 +606,7 @@ pub fn tools() -> Vec<ToolDef> {
"font": { "type": "string", "enum": ["helvetica", "times", "courier"] }, "size": { "type": "number", "minimum": 1, "maximum": 500 },
"bold": { "type": "boolean" }, "italic": { "type": "boolean" }, "color": { "type": "string" },
"align": { "type": "string", "enum": ["left", "center", "right", "justify"] },
+ "char_spacing": { "type": "number", "minimum": -500, "maximum": 500, "description": "Points after each character." },
}),
&["doc", "page", "text"],
)),
@@ -594,7 +620,7 @@ pub fn tools() -> Vec<ToolDef> {
json!({ "doc": doc(), "page": { "type": "integer", "minimum": 1 }, "path": { "type": "string" }, "rect": { "type": "array", "items": { "type": "number" }, "minItems": 4, "maxItems": 4 } }),
&["doc", "page", "path"],
)),
- t("content_update", "Edit added content", "Move/resize (rect), retype (text) or restyle (font, size, bold, italic, color, align) an added item (page, index from content_list). Images: rotate (degrees, multiple of 90, counter-clockwise), flip_h / flip_v (toggle), crop [left, bottom, right, top] as fractions trimmed, image (a file that replaces the picture). Undoable.")
+ t("content_update", "Edit added content", "Move/resize (rect), retype (text) or restyle (font, size, bold, italic, color, align, char_spacing in points) an added item (page, index from content_list). Images: rotate (degrees, multiple of 90, counter-clockwise), flip_h / flip_v (toggle), crop [left, bottom, right, top] as fractions trimmed, image (a file that replaces the picture). Undoable.")
.with(schema(
json!({
"doc": doc(), "page": { "type": "integer", "minimum": 1 }, "index": { "type": "integer", "minimum": 1 },
@@ -602,12 +628,27 @@ pub fn tools() -> Vec<ToolDef> {
"font": { "type": "string", "enum": ["helvetica", "times", "courier"] }, "size": { "type": "number", "minimum": 1, "maximum": 500 },
"bold": { "type": "boolean" }, "italic": { "type": "boolean" }, "color": { "type": "string" },
"align": { "type": "string", "enum": ["left", "center", "right", "justify"] },
+ "char_spacing": { "type": "number", "minimum": -500, "maximum": 500, "description": "Points after each character." },
"rotate": { "type": "integer" }, "flip_h": { "type": "boolean" }, "flip_v": { "type": "boolean" },
"crop": { "type": "array", "items": { "type": "number", "minimum": 0, "maximum": 0.49 }, "minItems": 4, "maxItems": 4 },
"image": { "type": "string", "description": "Replace the picture with this file." },
}),
&["doc", "page", "index"],
)),
+ t(
+ "content_copy",
+ "Copy and paste added content",
+ "Copy an added item (page, index from content_list) and paste it, as Edit ▸ Copy and Paste do: onto to_page of to_doc (by default its own page and document) as it is: a text box's text, font, size, colour, alignment and box; an image's picture, box, turns, flips and crop (within its document the same image object is drawn again; into another one the picture goes as its JPEG or JPEG 2000 file, or else a PNG, without a colour profile and with CMYK colours turned to RGB). It goes at at [x, y] (its top-left, points from the top-left of the page), else where it was, 18 points down and to the right past each copy of it already there; kept on the page. Refused when the source document doesn't allow copying. Returns the new item's page, index and rect. Undoable in the target document.",
+ )
+ .with(schema(
+ json!({
+ "doc": doc(), "page": { "type": "integer", "minimum": 1 }, "index": { "type": "integer", "minimum": 1 },
+ "to_doc": { "type": "integer", "minimum": 1, "description": "The document to paste into (default doc)." },
+ "to_page": { "type": "integer", "minimum": 1, "description": "The page to paste onto (default page)." },
+ "at": { "type": "array", "items": { "type": "number" }, "minItems": 2, "maxItems": 2 },
+ }),
+ &["doc", "page", "index"],
+ )),
t("content_delete", "Delete added content", "Delete an added item (page, index from content_list). Undoable.")
.destructive()
.with(schema(json!({ "doc": doc(), "page": { "type": "integer", "minimum": 1 }, "index": { "type": "integer", "minimum": 1 } }), &["doc", "page", "index"])),
@@ -665,7 +706,7 @@ pub fn tools() -> Vec<ToolDef> {
.ro().cmd("measure.snap").with(schema(json!({"doc":doc(),"page":{"type":"integer","minimum":1},"at":point(),"tolerance":{"type":"number","minimum":0,"maximum":10000},"endpoints":{"type":"boolean"},"midpoints":{"type":"boolean"},"intersections":{"type":"boolean"},"paths":{"type":"boolean"}}), &["doc","page","at"])),
t("measure_export", "Export measurements as CSV", "Atomically write saved measurement values, labels, authors and scale ratios as spreadsheet-safe CSV. Returns how many unsupported measurements were left out.")
.cmd("measure.export").with(schema(json!({"doc":doc(),"out":path_arg()}), &["doc","out"])),
- t("comment_list", "List comments", "Every comment (annotation other than links, form widgets and pop-ups) with its page, index, id, type, author, text, date, rectangle, colour, review status and replies.")
+ t("comment_list", "List comments", "Every comment (annotation other than links, form widgets and pop-ups) with its page, index, id, type, author, text, date, rectangle, colour, review status, checkmark and replies (each with its own status and checkmark).")
.ro()
.with(schema(json!({ "doc": doc(), "page": { "type": "integer", "minimum": 1, "description": "Only this page." } }), &["doc"])),
t(
@@ -696,7 +737,7 @@ pub fn tools() -> Vec<ToolDef> {
"stamp": { "type": "string" },
"dynamic": { "type": "boolean" },
"strokes": { "type": "array", "items": { "type": "array", "items": point() } },
- "icon": { "type": "string", "description": "note: Comment, Note, Help, Insert, Key, NewParagraph, Paragraph; attachment: PushPin, Paperclip, Graph, Tag." },
+ "icon": { "type": "string", "description": "note: Comment, Note, Help, Insert, Key, NewParagraph, Paragraph (the standard names), Check, Circle, Cross, CrossHairs, Star, RightArrow, UpArrow; attachment: PushPin, Paperclip, Graph, Tag." },
"color": color(),
"fill": color(),
"opacity": { "type": "number", "minimum": 0, "maximum": 1 },
@@ -1056,7 +1097,7 @@ pub fn tools() -> Vec<ToolDef> {
t("accessibility_set_alt", "Set alternate text", "Set a figure's alternate text (alt; empty or omitted clears it), or mark it decorative (decorative: true: its content becomes an artifact and the figure leaves the tags). figure is a number from accessibility_figures. Returns the figures. Undoable.")
.cmd("a11y.alt_text")
.with(schema(json!({ "doc": doc(), "figure": { "type": "integer", "minimum": 1 }, "alt": { "type": "string" }, "decorative": { "type": "boolean" } }), &["doc", "figure"])),
- t("accessibility_tags", "List structure tags", "List reachable indirect structure tags in document order with PDF object number, generation, nearest indirect parent, depth, page, type, title, actual text, alternate text and language, one page at a time: count is how many tags match, next the offset of the following page (null at the end). types, pages and max_depth keep only some tags. Inline tag dictionaries have no stable object reference and are not listed.")
+ t("accessibility_tags", "List structure tags", "List reachable indirect structure tags in document order with PDF object number, generation, nearest indirect parent, depth, page, type, title, actual text, alternate text, language, a table's summary and a header cell's scope, one page at a time: count is how many tags match, next the offset of the following page (null at the end). types, pages and max_depth keep only some tags. Inline tag dictionaries have no stable object reference and are not listed.")
.ro()
.cmd("a11y.tags")
.with(schema(
@@ -1074,11 +1115,11 @@ pub fn tools() -> Vec<ToolDef> {
.ro()
.cmd("a11y.tags")
.with(schema(json!({ "doc": doc(), "object": { "type": "integer", "minimum": 1 }, "generation": { "type": "integer", "minimum": 0, "maximum": 65535 } }), &["doc", "object", "generation"])),
- t("accessibility_set_tag_property", "Edit tag property", "Set or clear one property of a reachable indirect structure tag. Use object and generation from accessibility_tags. Properties: type, title, actual_text, alternate_text, language. Empty or omitted value clears text properties; type requires a nonempty PDF name. Undoable.")
+ t("accessibility_set_tag_property", "Edit tag property", "Set or clear one property of a reachable indirect structure tag. Use object and generation from accessibility_tags. Properties: type, title, actual_text, alternate_text, language, summary (Table tags: the table's Summary attribute), scope (TH tags: Row, Column or Both). Summary and scope are written in the tag's Table attribute object (/A, /O /Table); the role map decides a tag's type. Empty or omitted value clears text properties, summary and scope; type requires a nonempty PDF name. Undoable.")
.with(schema(json!({
"doc": doc(), "object": { "type": "integer", "minimum": 1 },
"generation": { "type": "integer", "minimum": 0, "maximum": 65535 },
- "property": { "type": "string", "enum": ["type", "title", "actual_text", "alternate_text", "language"] },
+ "property": { "type": "string", "enum": ["type", "title", "actual_text", "alternate_text", "language", "summary", "scope"] },
"value": { "type": "string" },
}), &["doc", "object", "generation", "property"])),
t("accessibility_mark_tag_artifact", "Mark tag content as artifact", "Mark a reachable leaf structure tag's direct marked content as an artifact and remove the tag from the reading structure. Use object and generation from accessibility_tags. Tags with child structure elements, no direct marked content, or content not found on its page are rejected. Undoable.")
@@ -1097,7 +1138,7 @@ pub fn tools() -> Vec<ToolDef> {
t("form_merge_data", "Merge data files into spreadsheet", "Collect the field values of form data files (FDF, XFDF) or filled-in PDF forms into one CSV file at path: a column per field name, a row per file. Returns the row and column counts.")
.cmd("form.merge_data")
.with(schema(json!({ "paths": { "type": "array", "items": { "type": "string" }, "minItems": 1 }, "path": { "type": "string" } }), &["paths", "path"])),
- t("js_run", "Run JavaScript", "Run Acrobat JavaScript in the document, as the JavaScript console does (or as push button `field`'s Mouse Up script when field is given; on a laid-out XFA form, `field` runs that button's XFA click script instead, JavaScript or FormCalc, which can add and remove rows and show or hide subforms). The form object model is available: this/getField, event, app, util, console, display, color, and the document-level scripts. Field changes and resetForm are applied as one undoable step; returns the script's alerts, console output, requests (print, page, url, submit) and error.")
+ t("js_run", "Run JavaScript", "Run Acrobat JavaScript in the document, as the JavaScript console does (or as push button `field`'s Mouse Up script when field is given; on a laid-out XFA form, `field` runs that button's XFA click script instead, JavaScript or FormCalc, which can add and remove rows and show or hide subforms). The form object model is available: this/getField, event, app, util, console, display, color, and the document-level scripts (except the PDF container scripts when XFA layout is active; they remain available through js_document_scripts). Field changes and resetForm are applied as one undoable step; returns the script's alerts, console output, requests (print, page, url, submit), error, and the errors of document-level scripts that failed (the rest still ran).")
.cmd("tools.js_console")
.with(schema(
json!({ "doc": doc(), "script": { "type": "string" }, "field": { "type": "string", "description": "Run as this button's Mouse Up event." } }),
@@ -1187,7 +1228,7 @@ pub fn tools() -> Vec<ToolDef> {
}),
&["doc"],
)),
- t("ocr_recognize_files", "Recognize text in multiple files", "Scan & OCR ▸ Recognize text ▸ In multiple files: read every page of each PDF in paths and write the searchable result into folder under the same name (pages that already have text are left alone unless skip_text_pages is false, as in ocr_recognize). Returns, per file, the output path, word count and skipped pages, or the error.")
+ t("ocr_recognize_files", "Recognize text in multiple files", "Scan & OCR ▸ Recognize text ▸ In multiple files: read every page of each PDF in paths and write the searchable result into folder under the same name (pages that already have text are left alone unless skip_text_pages is false, as in ocr_recognize). Two inputs that would write the same output file are refused before anything is read or written. Returns, per file, the output path, word count and skipped pages, or the error.")
.cmd("ocr.recognize_batch")
.with(schema(
json!({
@@ -1362,13 +1403,14 @@ pub fn tools() -> Vec<ToolDef> {
.with(schema(json!({ "doc": doc() }), &["doc"])),
t("doc_open_revision", "Open a revision", "Open saved revision `revision` (1 = the oldest) of a document as a new, unsaved document, to see the file as it was then.")
.with(schema(json!({ "doc": doc(), "revision": { "type": "integer", "minimum": 1 } }), &["doc", "revision"])),
- t("doc_optimize", "Optimize PDF", "Write an optimized copy to `path` (Acrobat's PDF Optimizer). preset: standard (default; Reduce File Size's choices) or mobile (images to 96 ppi above 144, JPEG high quality); the options below change it. merge_fragments (default true) first puts a page picture drawn as many stacked image strips (as some PDF printers write it) back together into one image, so it can be resampled (merged_images, fragments_merged). color / gray: { downsample, ppi, above_ppi, compression: jpeg|zip|retain, quality 1–100 } (defaults: downsample to 150 ppi above 225, JPEG 60). Images are measured where pages draw them and replaced only when smaller. discard_*: thumbnails (default true), alternate_images (true), tags, print_settings; flate_unencoded (true); remove_invalid_links and remove_unreferenced_dests (true); images and forms the pages list but never draw are always dropped (unused_xobjects). discard: Remove Hidden Information categories (metadata, attachments, comments, form-fields, hidden-text, hidden-layers, bookmarks, links-actions-scripts, private-data). Signed documents are refused. The open document is unchanged.")
+ t("doc_optimize", "Optimize PDF", "Write an optimized copy to `path` (Acrobat's PDF Optimizer). preset: standard (default; Reduce File Size's choices) or mobile (images to 96 ppi above 144, JPEG high quality); the options below change it. compatibility: retain (default; keeps the document's version, or 1.5 when object streams are written), 1.4, 1.5, 1.6, 1.7 or 2.0. merge_fragments (default true) first puts a page picture drawn as many stacked image strips (as some PDF printers write it) back together into one image, so it can be resampled (merged_images, fragments_merged). color / gray: { downsample, ppi, above_ppi, compression: jpeg|zip|retain, quality 1–100 } (defaults: downsample to 150 ppi above 225, JPEG 60). Images are measured where pages draw them and replaced only when smaller. discard_*: thumbnails (default true), alternate_images (true), tags, print_settings; flate_unencoded (true); object_streams (default true; always off for 1.4); lzw_to_flate (true) decodes LZW streams and stores them with Flate instead, leaving any it cannot decode unchanged (lzw_streams counts the streams converted); remove_invalid_links and remove_unreferenced_dests (true); images and forms the pages list but never draw are always dropped (unused_xobjects). discard: Remove Hidden Information categories (metadata, attachments, comments, form-fields, hidden-text, hidden-layers, bookmarks, links-actions-scripts, private-data). Signed documents are refused. The open document is unchanged.")
.cmd("optimize.advanced")
.with(schema(
json!({
"doc": doc(),
"path": { "type": "string" },
"preset": { "type": "string", "enum": ["standard", "mobile"] },
+ "compatibility": { "type": "string", "enum": ["retain", "1.4", "1.5", "1.6", "1.7", "2.0"] },
"merge_fragments": { "type": "boolean" },
"color": { "type": "object" },
"gray": { "type": "object" },
@@ -1377,6 +1419,8 @@ pub fn tools() -> Vec<ToolDef> {
"discard_tags": { "type": "boolean" },
"discard_print_settings": { "type": "boolean" },
"flate_unencoded": { "type": "boolean" },
+ "object_streams": { "type": "boolean" },
+ "lzw_to_flate": { "type": "boolean" },
"remove_invalid_links": { "type": "boolean" },
"remove_unreferenced_dests": { "type": "boolean" },
"discard": { "type": "array", "items": { "type": "string" } },
diff --git a/crates/automation/tests/it/attachment_key.rs b/crates/automation/tests/it/attachment_key.rs
new file mode 100644
index 0000000..25b0d6c
--- /dev/null
+++ b/crates/automation/tests/it/attachment_key.rs
@@ -0,0 +1,34 @@
+//! `attachment_add` reports the name-tree key of the file it added, even when a file attached to
+//! a page as a comment already has the same name.
+
+use pdfcraft_automation::{Automation, Content};
+use pdfcraft_engine::{AttachIcon, Edit, NewAnnotation, Session, Shape, Style};
+use serde_json::{Value, json};
+
+fn tool(a: &mut Automation, name: &str, args: Value) -> Value {
+ match a.call(name, &args).unwrap().remove(0) {
+ Content::Json(value) => value,
+ other => panic!("expected JSON: {other:?}"),
+ }
+}
+
+#[test]
+fn attachment_add_reports_its_own_key_when_a_page_comment_has_the_same_file_name() {
+ let dir = tempfile::tempdir().unwrap();
+ let mut session = Session::new();
+ let bytes = session.create_blank(300.0, 400.0, 1).unwrap();
+ let id = session.open("a.pdf", None, bytes, None).unwrap();
+ let shape = Shape::Attachment { at: [20.0, 300.0], icon: AttachIcon::Paperclip, file: "notes.txt".into(), data: b"on the page".to_vec() };
+ session
+ .apply(id, Edit::AddAnnotation(NewAnnotation { page: 0, shape, style: Style::default(), contents: String::new(), author: "Ada".into() }))
+ .unwrap();
+ std::fs::write(dir.path().join("a.pdf"), session.save_bytes(id).unwrap().as_slice()).unwrap();
+ std::fs::write(dir.path().join("notes.txt"), b"for the document").unwrap();
+
+ let mut auto = Automation::new().with_root(dir.path()).unwrap();
+ let doc = tool(&mut auto, "doc_open", json!({ "path": "a.pdf" }))["doc"].as_u64().unwrap();
+ let added = tool(&mut auto, "attachment_add", json!({ "doc": doc, "path": "notes.txt" }));
+ assert_eq!(added["name"], "notes.txt", "{added}");
+ let again = tool(&mut auto, "attachment_add", json!({ "doc": doc, "path": "notes.txt" }));
+ assert_eq!(again["name"], "notes.txt (2)", "{again}");
+}
diff --git a/crates/automation/tests/it/automation.rs b/crates/automation/tests/it/automation.rs
index dd85a59..3bcdabb 100644
--- a/crates/automation/tests/it/automation.rs
+++ b/crates/automation/tests/it/automation.rs
@@ -213,6 +213,49 @@ fn doc_info_lists_page_transitions_and_display_times() {
);
}
+/// `doc_info` says where the document opens: the `/OpenAction` destination, a named one
+/// resolved (ISO 32000-2 §12.3.2.4), as a 1-based page and a destination in view coordinates.
+#[test]
+fn doc_info_reports_the_open_destination() {
+ let dir = workdir("open-destination");
+ let write = |name: &str, catalog: &str| {
+ let objects: Vec<String> = vec![
+ format!("<< /Type /Catalog /Pages 2 0 R {catalog} >>"),
+ "<< /Type /Pages /Kids [3 0 R 4 0 R] /Count 2 /MediaBox [0 0 612 792] >>".into(),
+ "<< /Type /Page /Parent 2 0 R >>".into(),
+ "<< /Type /Page /Parent 2 0 R >>".into(),
+ ];
+ let mut bytes = b"%PDF-1.7\n".to_vec();
+ let mut offsets = Vec::new();
+ for (i, object) in objects.iter().enumerate() {
+ offsets.push(bytes.len());
+ bytes.extend_from_slice(format!("{} 0 obj\n{object}\nendobj\n", i + 1).as_bytes());
+ }
+ let xref = bytes.len();
+ bytes.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objects.len() + 1).as_bytes());
+ for o in offsets {
+ bytes.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes());
+ }
+ bytes.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objects.len() + 1).as_bytes());
+ std::fs::write(dir.join(name), bytes).unwrap();
+ };
+ write("named.pdf", "/OpenAction << /S /GoTo /D /there >> /Dests << /there [4 0 R /XYZ 100 500 2] >>");
+ write("script.pdf", "/OpenAction << /S /JavaScript /JS (1) >>");
+ let mut a = auto(&dir);
+ let doc = ok(&mut a, "doc_open", json!({ "path": "named.pdf" }))["doc"].as_u64().unwrap();
+ let open = ok(&mut a, "doc_info", json!({ "doc": doc }))["open_destination"].clone();
+ assert_eq!(open["page"], 2, "{open}");
+ // y 500 is 292 points below the top of the 792-point page.
+ assert_eq!(
+ (open["destination"]["fit"].as_str(), open["destination"]["left"].as_f64(), open["destination"]["top"].as_f64()),
+ (Some("XYZ"), Some(100.0), Some(292.0)),
+ "{open}"
+ );
+ assert_eq!(open["destination"]["zoom"].as_f64(), Some(2.0));
+ let doc = ok(&mut a, "doc_open", json!({ "path": "script.pdf" }))["doc"].as_u64().unwrap();
+ assert!(ok(&mut a, "doc_info", json!({ "doc": doc }))["open_destination"].is_null());
+}
+
/// Page transitions through the tools: set on chosen pages, written to the file as `/Trans` and
/// `/Dur`, removed again, bad values refused, and one undo step. (Read through `pdfcraft_cos`,
/// so this does not lean on `doc_info` listing them.)
@@ -2078,6 +2121,83 @@ fn nested_replies_stay_in_the_listing() {
assert!(replies.contains(&"DIRECT_REPLY") && replies.contains(&"NESTED_REPLY"), "the nested reply is listed: {replies:?}");
}
+/// Replies thread by their `/IRT` reference, not `/NM`: PyMuPDF names the first comment on every
+/// page `fitz-A0`. A shared id is refused rather than taken to mean page 1's comment.
+#[test]
+fn replies_thread_by_reference_when_ids_repeat_across_pages() {
+ let dir = workdir("repeated-ids");
+ // Contributor-original PDF, shaped like PyMuPDF output.
+ std::fs::write(
+ dir.join("fitz.pdf"),
+ b"%PDF-1.7
+1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj
+2 0 obj << /Type /Pages /Kids [3 0 R 4 0 R] /Count 2 >> endobj
+3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 300 200] /Annots [5 0 R] >> endobj
+4 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 300 200] /Annots [6 0 R 7 0 R] >> endobj
+5 0 obj << /Type /Annot /Subtype /Text /Rect [20 140 40 160] /NM (fitz-A0) /T (Alpha) /Contents (COVER) >> endobj
+6 0 obj << /Type /Annot /Subtype /Text /Rect [20 140 40 160] /NM (fitz-A0) /T (Beta) /Contents (SECOND) >> endobj
+7 0 obj << /Type /Annot /Subtype /Text /Rect [20 100 40 120] /NM (fitz-A1) /IRT 6 0 R /T (Gamma) /Contents (ANSWER) >> endobj
+trailer << /Root 1 0 R >>
+%%EOF",
+ )
+ .unwrap();
+ let mut a = auto(&dir);
+ let doc = ok(&mut a, "doc_open", json!({ "path": "fitz.pdf" }))["doc"].as_u64().unwrap();
+ let replies = |a: &mut Automation| -> Vec<(String, Vec<String>)> {
+ let list = ok(a, "comment_list", json!({ "doc": doc }));
+ list["comments"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .map(|c| {
+ let mut texts: Vec<String> =
+ c["replies"].as_array().unwrap().iter().filter_map(|r| r["contents"].as_str().map(String::from)).collect();
+ texts.sort();
+ (c["contents"].as_str().unwrap().to_string(), texts)
+ })
+ .collect()
+ };
+ assert_eq!(replies(&mut a), [("COVER".into(), vec![]), ("SECOND".into(), vec!["ANSWER".to_string()])]);
+ let refused = err(&mut a, "comment_reply", json!({ "doc": doc, "id": "fitz-A0", "text": "LATER" }));
+ assert!(refused.to_string().contains("several comments"), "{refused}");
+ ok(&mut a, "comment_reply", json!({ "doc": doc, "page": 2, "index": 1, "text": "LATER" }));
+ assert_eq!(replies(&mut a), [("COVER".into(), vec![]), ("SECOND".into(), vec!["ANSWER".to_string(), "LATER".to_string()])]);
+}
+
+/// A status or checkmark belongs to the annotation its `/IRT` names: one set on a reply is not
+/// its comment's, as the Comments panel shows it, and is reported on the reply. One whose
+/// annotation can't be found is not a comment of its own.
+#[test]
+fn a_checkmark_on_a_reply_is_not_its_comments() {
+ let dir = workdir("reply-checkmark");
+ // Contributor-original PDF: a comment, a reply, a checkmark and a status on the reply, and a
+ // status whose annotation (object 9) doesn't exist.
+ std::fs::write(
+ dir.join("checked.pdf"),
+ b"%PDF-1.7
+1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj
+2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj
+3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 300 200] /Annots [4 0 R 5 0 R 6 0 R 7 0 R 8 0 R] >> endobj
+4 0 obj << /Type /Annot /Subtype /Text /Rect [100 100 120 120] /T (Alpha) /Contents (COMMENT) >> endobj
+5 0 obj << /Type /Annot /Subtype /Text /Rect [100 60 120 80] /IRT 4 0 R /T (Beta) /Contents (REPLY) >> endobj
+6 0 obj << /Type /Annot /Subtype /Text /Rect [100 60 120 80] /IRT 5 0 R /T (Beta) /StateModel /Marked /State /Marked >> endobj
+7 0 obj << /Type /Annot /Subtype /Text /Rect [100 60 120 80] /IRT 5 0 R /T (Beta) /StateModel /Review /State /Accepted >> endobj
+8 0 obj << /Type /Annot /Subtype /Text /Rect [200 20 220 40] /F 30 /IRT 9 0 R /T (Gamma) /StateModel /Review /State /Rejected >> endobj
+trailer << /Root 1 0 R >>
+%%EOF",
+ )
+ .unwrap();
+ let mut a = auto(&dir);
+ let doc = ok(&mut a, "doc_open", json!({ "path": "checked.pdf" }))["doc"].as_u64().unwrap();
+ let list = ok(&mut a, "comment_list", json!({ "doc": doc }));
+ assert_eq!(list["count"], 1, "{list}");
+ let c = &list["comments"][0];
+ assert_eq!((&c["marked"], &c["status"]), (&json!(false), &Value::Null), "{c}");
+ assert_eq!(c["replies"].as_array().map(Vec::len), Some(1), "the reply, not its states: {c}");
+ let reply = &c["replies"][0];
+ assert_eq!((&reply["marked"], &reply["status"]), (&json!(true), &json!("Accepted")), "{reply}");
+}
+
#[test]
fn protecting_through_tools() {
let dir = workdir("protect");
@@ -2331,6 +2451,51 @@ fn forms_through_tools() {
assert_ne!(v, "Filled by an agent");
}
+/// A PDF of the given objects (numbered from 1).
+fn pdf_of(objs: &[&str]) -> Vec<u8> {
+ let mut out = b"%PDF-1.7\n".to_vec();
+ let mut offsets = Vec::new();
+ for (i, o) in objs.iter().enumerate() {
+ offsets.push(out.len());
+ out.extend_from_slice(format!("{} 0 obj\n{o}\nendobj\n", i + 1).as_bytes());
+ }
+ let xref = out.len();
+ out.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objs.len() + 1).as_bytes());
+ for o in offsets {
+ out.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes());
+ }
+ out.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objs.len() + 1).as_bytes());
+ out
+}
+
+/// #4018: `form_fill` warns about a value its box cuts off at the field's fixed font size (the
+/// value is saved whole), and not about one that fits.
+#[test]
+fn form_fill_warns_when_a_value_does_not_fit() {
+ let objs = [
+ "<< /Type /Catalog /Pages 2 0 R /AcroForm 4 0 R >>",
+ "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 400 300] >>",
+ "<< /Type /Page /Parent 2 0 R /Annots [5 0 R 6 0 R] >>",
+ "<< /Fields [5 0 R 6 0 R] /DA (/Helv 12 Tf 0 g) /DR << /Font << /Helv 7 0 R >> >> >>",
+ "<< /Type /Annot /Subtype /Widget /FT /Tx /T (narrow) /Rect [10 250 150 268] /P 3 0 R >>",
+ "<< /Type /Annot /Subtype /Widget /FT /Tx /T (wide) /Rect [10 200 310 218] /P 3 0 R >>",
+ "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>",
+ ];
+ let dir = workdir("form-overflow");
+ std::fs::write(dir.join("form.pdf"), pdf_of(&objs)).unwrap();
+ let mut a = auto(&dir);
+ let doc = ok(&mut a, "doc_open", json!({ "path": "form.pdf" }))["doc"].as_u64().unwrap();
+ let long = "Doe, Jane (represented by John Doe)";
+ let r = ok(&mut a, "form_fill", json!({ "doc": doc, "values": { "narrow": long, "wide": long } }));
+ let warnings: Vec<&str> = r["warnings"].as_array().map(|w| w.iter().filter_map(Value::as_str).collect()).unwrap_or_default();
+ assert_eq!(warnings.len(), 1, "{r}");
+ assert!(warnings[0].starts_with("form field \"narrow\" (page 1): the value does not fit"), "{}", warnings[0]);
+ let after = ok(&mut a, "form_fields", json!({ "doc": doc }));
+ assert_eq!(after["fields"][0]["value"], long, "saved whole");
+ let r = ok(&mut a, "form_fill", json!({ "doc": doc, "values": { "narrow": "Ada" } }));
+ assert!(r.get("warnings").is_none(), "{r}");
+}
+
/// A form whose fields are only page widgets (the `/Fields` list is empty) still lists, fills and
/// resets through the tools, and the leniency shows up as a repair note.
#[test]
@@ -2346,19 +2511,7 @@ fn orphan_form_fields_through_tools() {
"<< /Type /Annot /Subtype /Widget /FT /Tx /T (beta) /Rect [10 150 90 170] /P 3 0 R >>", // 6
"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>", // 7
];
- let mut out = b"%PDF-1.7\n".to_vec();
- let mut offsets = Vec::new();
- for (i, o) in objs.iter().enumerate() {
- offsets.push(out.len());
- out.extend_from_slice(format!("{} 0 obj\n{o}\nendobj\n", i + 1).as_bytes());
- }
- let xref = out.len();
- out.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objs.len() + 1).as_bytes());
- for o in offsets {
- out.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes());
- }
- out.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objs.len() + 1).as_bytes());
- out
+ pdf_of(&objs)
}
let dir = workdir("orphan-forms");
std::fs::write(dir.join("orphan.pdf"), orphan_form()).unwrap();
@@ -2730,6 +2883,66 @@ trailer << /Root 1 0 R >>
assert!(matches!(a.call("accessibility_set_alt", &json!({ "doc": fd, "figure": 6, "alt": "x" })), Err(ToolError::Failed(_))));
}
+/// A table's summary and a header cell's scope are set through `accessibility_set_tag_property`
+/// (#4103, #4104): the summary clears the table-summary finding, both are listed with the tags,
+/// undone, and saved.
+#[test]
+fn table_summary_and_header_scope_through_automation() {
+ let dir = workdir("a11y-table");
+ let content = "/TH << /MCID 0 >> BDC 10 150 40 20 re f EMC /TD << /MCID 1 >> BDC 60 150 40 20 re f EMC";
+ let pdf = format!(
+ "%PDF-1.7
+1 0 obj << /Type /Catalog /Pages 2 0 R /MarkInfo << /Marked true >> /StructTreeRoot 5 0 R >> endobj
+2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj
+3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Contents 4 0 R /StructParents 0 >> endobj
+4 0 obj << /Length {} >> stream
+{content}
+endstream endobj
+5 0 obj << /Type /StructTreeRoot /K 6 0 R /ParentTree 11 0 R >> endobj
+6 0 obj << /S /Document /P 5 0 R /K [7 0 R] >> endobj
+7 0 obj << /S /Table /P 6 0 R /K [8 0 R] >> endobj
+8 0 obj << /S /TR /P 7 0 R /K [9 0 R 10 0 R] >> endobj
+9 0 obj << /S /TH /P 8 0 R /Pg 3 0 R /K 0 >> endobj
+10 0 obj << /S /TD /P 8 0 R /Pg 3 0 R /K 1 >> endobj
+11 0 obj << /Nums [0 [9 0 R 10 0 R]] >> endobj
+trailer << /Root 1 0 R >>
+%%EOF",
+ content.len()
+ );
+ std::fs::write(dir.join("table.pdf"), pdf).unwrap();
+ let mut a = auto(&dir);
+ let fd = ok(&mut a, "doc_open", json!({ "path": "table.pdf" }))["doc"].as_u64().unwrap();
+ let summary_status = |a: &mut Automation| {
+ let r = ok(a, "accessibility_check", json!({ "doc": fd, "rules": ["table-summary"] }));
+ r["results"].as_array().unwrap().iter().find(|x| x["rule"] == "table-summary").unwrap()["status"].as_str().unwrap().to_owned()
+ };
+ assert_eq!(summary_status(&mut a), "failed");
+ let args =
+ |object: u32, property: &str, value: &str| json!({ "doc": fd, "object": object, "generation": 0, "property": property, "value": value });
+ let tags = ok(&mut a, "accessibility_set_tag_property", args(7, "summary", "Opening hours by day"));
+ let tag = |tags: &Value, object: u64| tags["tags"].as_array().unwrap().iter().find(|t| t["object"] == object).unwrap().clone();
+ assert_eq!(tag(&tags, 7)["summary"], "Opening hours by day");
+ assert_eq!(summary_status(&mut a), "passed");
+ let tags = ok(&mut a, "accessibility_set_tag_property", args(9, "scope", "Column"));
+ assert_eq!(tag(&tags, 9)["scope"], "Column");
+ // A scope is Row, Column or Both; only a table has a summary and only a header cell a scope.
+ for (object, property, value) in [(9, "scope", "column"), (10, "scope", "Row"), (9, "summary", "No")] {
+ assert!(
+ matches!(err(&mut a, "accessibility_set_tag_property", args(object, property, value)), ToolError::Failed(_)),
+ "{property} {value} on {object}"
+ );
+ }
+ assert_eq!(ok(&mut a, "edit_undo", json!({ "doc": fd }))["undone"], "Change tag properties");
+ assert_eq!(tag(&ok(&mut a, "accessibility_tags", json!({ "doc": fd })), 9)["scope"], Value::Null);
+ ok(&mut a, "edit_redo", json!({ "doc": fd }));
+ ok(&mut a, "doc_save", json!({ "doc": fd, "path": "tagged-table.pdf" }));
+ let saved = pdfcraft_cos::Document::open(std::sync::Arc::new(std::fs::read(dir.join("tagged-table.pdf")).unwrap())).unwrap();
+ // Saving renumbers the objects: the tags are found by type.
+ let saved = pdfcraft_engine::a11y::tags(&saved);
+ assert_eq!(saved.iter().find(|t| t.kind == "Table").and_then(|t| t.summary.as_deref()), Some("Opening hours by day"));
+ assert_eq!(saved.iter().find(|t| t.kind == "TH").and_then(|t| t.scope.as_deref()), Some("Column"));
+}
+
#[test]
fn marking_a_leaf_tag_as_an_artifact_through_automation_is_undoable_and_saved() {
let dir = workdir("a11y-artifact");
@@ -2980,6 +3193,43 @@ fn text_in_a_page_form_is_edited_through_tools() {
assert_eq!((saved[0]["text"].as_str(), saved[1]["text"].as_str()), (Some("Edited in place"), Some("Second line")));
}
+#[test]
+fn styled_cyrillic_fallback_is_batched_through_tools_and_reopen() {
+ if pdfcraft_fonts::document_japanese_font().is_none() {
+ eprintln!("skipping: built without craft-fonts");
+ return;
+ }
+ let dir = workdir("styled-fallback");
+ std::fs::write(
+ dir.join("mixed.pdf"),
+ helvetica_page(
+ "BT /F1 12 Tf 14.4 TL 72 700 Td (The quick brown fox jumps over the lazy dog) Tj T* (and keeps running through the long field.) Tj ET",
+ ),
+ )
+ .unwrap();
+ let mut a = auto(&dir);
+ let doc = ok(&mut a, "doc_open", json!({"path": "mixed.pdf"}))["doc"].as_u64().unwrap();
+ let replacement = "The quick brown fox jumps over the lazy dog шалом\nand keeps running through the long field.";
+ ok(&mut a, "text_edit", json!({"doc":doc,"page":1,"paragraph":1,"text":replacement,"width":520}));
+ ok(&mut a, "doc_save", json!({"doc":doc,"path":"saved.pdf"}));
+ let saved = pdfcraft_cos::Document::open(std::sync::Arc::new(std::fs::read(dir.join("saved.pdf")).unwrap())).unwrap();
+ let page = pdfcraft_model::pages(&saved).swap_remove(0);
+ let resources = saved.dict(page.dict.get(b"Resources").unwrap()).unwrap();
+ let fonts = saved.dict(resources.get(b"Font").unwrap()).unwrap();
+ let fallback_count = fonts.iter().filter(|(name, _)| name.starts_with(b"PCJp")).count();
+ assert_eq!(fallback_count, 1, "one shared fallback font for the new word");
+ ok(&mut a, "edit_undo", json!({"doc":doc}));
+ assert!(!page_text(&mut a, doc)[0].contains("шалом"));
+ ok(&mut a, "edit_redo", json!({"doc":doc}));
+ assert!(page_text(&mut a, doc)[0].contains("шалом"));
+ let reopened = ok(&mut a, "doc_open", json!({"path":"saved.pdf"}))["doc"].as_u64().unwrap();
+ let lines = ok(&mut a, "text_lines", json!({"doc":reopened,"page":1}));
+ let runs = lines["lines"].as_array().unwrap();
+ assert!(runs.iter().any(|l| l["text"].as_str().is_some_and(|t| t.starts_with("The quick")) && l["font"] == "Helvetica"), "{lines}");
+ assert_eq!(runs.iter().filter(|l| l["text"] == "шалом").count(), 1, "{lines}");
+ assert!(page_text(&mut a, reopened)[0].contains("шалом"));
+}
+
/// #2593: a paragraph whose own font cannot show a character is written from PdfCraft's fallback
/// faces. The Cyrillic the craft-fonts faces lack (Uzbek қ ғ ҳ, Kazakh ә ө ү ұ һ) comes from the
/// bundled Inter face, so the edit is not refused even without `CRAFT_FONTS_DIR`, and the words
@@ -4044,6 +4294,28 @@ fn redacting_through_tools() {
assert!(matches!(a.call("redact_mark", &json!({ "doc": doc })), Err(ToolError::InvalidArgs(_))));
}
+#[test]
+/// Mark, apply and save remove the complete international number while retaining labels and controls.
+fn redacting_italian_international_slash_numbers_through_tools() {
+ let dir = workdir("redact-italian-international-slash");
+ std::fs::write(dir.join("phones.txt"), "A tel. +39 0426/123456\nB tel. 0426/123456\nC protocol 2024/123456\nD on 01/10/2026").unwrap();
+ let mut a = auto(&dir);
+ let doc = ok(&mut a, "doc_create", json!({ "from": "text", "path": "phones.txt" }))["doc"].as_u64().unwrap();
+ let marked = ok(&mut a, "redact_mark", json!({ "doc": doc, "pattern": "phone" }));
+ assert_eq!(marked["marked"], 2, "both complete phone numbers need marks");
+ assert!(page_text(&mut a, doc)[0].contains("+39 0426/123456"), "marks alone remove nothing");
+ assert_eq!(ok(&mut a, "redact_apply", json!({ "doc": doc }))["applied"], 2);
+ ok(&mut a, "doc_save", json!({ "doc": doc, "path": "redacted.pdf" }));
+ let reopened = ok(&mut a, "doc_open", json!({ "path": "redacted.pdf" }))["doc"].as_u64().unwrap();
+ let text = &page_text(&mut a, reopened)[0];
+ assert!(!text.contains("+39") && !text.contains("0426"), "{text}");
+ for label in ["A tel.", "B tel."] {
+ assert!(text.lines().any(|line| line.trim() == label), "only the surrounding label remains: {text}");
+ }
+ assert!(text.contains("protocol 2024/123456") && text.contains("on 01/10/2026"), "unrelated digit runs remain: {text}");
+ std::fs::remove_dir_all(dir).unwrap();
+}
+
/// One page with the text "Secret 1234" and a Redact annotation that has neither a usable
/// QuadPoints array nor a Rect, so there is no area to redact.
fn redact_pdf_with_unreadable_mark() -> Vec<u8> {
@@ -4373,6 +4645,91 @@ fn adding_content_through_tools() {
assert!(matches!(a.call("content_delete", &json!({ "doc": doc, "page": 1, "index": 5 })), Err(ToolError::Failed(_))));
}
+/// Edit ▸ Copy and Paste headlessly (#2636): an added text box or image, as it is, onto its own
+/// page beside it, onto a point, and into another document.
+#[test]
+fn copying_added_content_through_tools() {
+ let dir = workdir("content-copy");
+ let mut png = Vec::new();
+ {
+ let mut enc = png::Encoder::new(&mut png, 40, 20);
+ enc.set_color(png::ColorType::Rgb);
+ enc.write_header().unwrap().write_image_data(&[90u8; 2400]).unwrap();
+ }
+ std::fs::write(dir.join("logo.png"), png).unwrap();
+ let mut a = auto(&dir);
+ let doc = ok(&mut a, "doc_open", json!({ "path": "a.pdf" }))["doc"].as_u64().unwrap();
+ let other = ok(&mut a, "doc_open", json!({ "path": "b.pdf" }))["doc"].as_u64().unwrap();
+ ok(
+ &mut a,
+ "page_add_text",
+ json!({ "doc": doc, "page": 1, "text": "Approved", "at": [20, 20], "width": 100, "size": 18, "bold": true, "font": "times", "color": "red", "align": "center" }),
+ );
+ ok(&mut a, "page_add_image", json!({ "doc": doc, "page": 1, "path": "logo.png", "rect": [100, 200, 180, 240] }));
+ ok(&mut a, "content_update", json!({ "doc": doc, "page": 1, "index": 2, "rotate": 90, "flip_h": true }));
+ let original = ok(&mut a, "content_list", json!({ "doc": doc }))["items"].clone();
+ // Beside itself on its own page: 18 points down and to the right, with the style content_list
+ // shows (the engine test checks colour, alignment and the image transforms).
+ let r = ok(&mut a, "content_copy", json!({ "doc": doc, "page": 1, "index": 1 }));
+ assert_eq!((r["page"].as_u64(), r["index"].as_u64()), (Some(1), Some(3)));
+ let items = ok(&mut a, "content_list", json!({ "doc": doc }))["items"].clone();
+ let (from, to) = (&original[0], &items[2]);
+ for key in ["type", "text", "font", "size", "bold", "italic"] {
+ assert_eq!(from[key], to[key], "{key}");
+ }
+ let shifted: Vec<f64> = from["rect"].as_array().unwrap().iter().map(|v| v.as_f64().unwrap() + 18.0).collect();
+ assert_eq!(to["rect"], json!(shifted));
+ assert_eq!(r["rect"], to["rect"]);
+ // An image onto another page at a point, and into another document where it was.
+ let r = ok(&mut a, "content_copy", json!({ "doc": doc, "page": 1, "index": 2, "to_page": 2, "at": [10, 30] }));
+ assert_eq!((r["page"].as_u64(), r["index"].as_u64()), (Some(2), Some(1)));
+ assert_eq!(r["rect"][0].as_f64().zip(r["rect"][1].as_f64()), Some((10.0, 30.0)), "its top-left at the point");
+ let r = ok(&mut a, "content_copy", json!({ "doc": doc, "page": 1, "index": 2, "to_doc": other }));
+ assert_eq!(r["rect"], original[1]["rect"], "in the same place");
+ let theirs = ok(&mut a, "content_list", json!({ "doc": other }));
+ assert_eq!((theirs["count"].as_u64(), theirs["items"][0]["type"].as_str()), (Some(1), Some("image")));
+ // Copied there again: it steps past the first copy, whose picture that document stores itself.
+ let r = ok(&mut a, "content_copy", json!({ "doc": doc, "page": 1, "index": 2, "to_doc": other }));
+ let stepped: Vec<f64> = original[1]["rect"].as_array().unwrap().iter().map(|v| v.as_f64().unwrap() + 18.0).collect();
+ assert_eq!(r["rect"], json!(stepped), "beside the first copy, not on it");
+ // Each paste is one undo step in the document it went into.
+ ok(&mut a, "edit_undo", json!({ "doc": other }));
+ ok(&mut a, "edit_undo", json!({ "doc": other }));
+ assert_eq!(ok(&mut a, "content_list", json!({ "doc": other }))["count"], 0);
+ assert_eq!(ok(&mut a, "content_list", json!({ "doc": doc }))["count"], 4);
+ // Out of range: a readable failure.
+ assert!(matches!(a.call("content_copy", &json!({ "doc": doc, "page": 1, "index": 9 })), Err(ToolError::Failed(_))));
+ assert!(matches!(a.call("content_copy", &json!({ "doc": doc, "page": 1, "index": 1, "to_page": 9 })), Err(ToolError::InvalidArgs(_))));
+ assert!(matches!(a.call("content_copy", &json!({ "doc": doc, "page": 1, "index": 1, "to_doc": 999 })), Err(ToolError::Failed(_))));
+ for at in [json!([1]), json!([10, "x", 30]), json!("10, 30")] {
+ assert!(matches!(a.call("content_copy", &json!({ "doc": doc, "page": 1, "index": 1, "at": at })), Err(ToolError::InvalidArgs(_))), "{at}");
+ }
+ // A second copy onto its own page steps past the first.
+ let r = ok(&mut a, "content_copy", json!({ "doc": doc, "page": 1, "index": 1 }));
+ let twice: Vec<f64> = from["rect"].as_array().unwrap().iter().map(|v| v.as_f64().unwrap() + 36.0).collect();
+ assert_eq!(r["rect"], json!(twice));
+
+ // A document that doesn't allow copying keeps its content in, even with changes allowed.
+ let mut cos = pdfcraft_cos::Document::open(std::sync::Arc::new(fixture(1))).unwrap();
+ cos.set_encryption(&pdfcraft_cos::NewEncryption {
+ algorithm: pdfcraft_cos::Algorithm::Aes256,
+ user_password: "",
+ owner_password: "owner",
+ permissions: -1 ^ 0b1_0000,
+ encrypt_metadata: true,
+ seed: [3; 32],
+ })
+ .unwrap();
+ std::fs::write(dir.join("no-copy.pdf"), pdfcraft_cos::write_full(&cos, &Default::default()).unwrap()).unwrap();
+ let locked = ok(&mut a, "doc_open", json!({ "path": "no-copy.pdf" }))["doc"].as_u64().unwrap();
+ ok(&mut a, "page_add_text", json!({ "doc": locked, "page": 1, "text": "Secret", "at": [20, 20], "width": 100 }));
+ for to in [locked, other] {
+ let refused = a.call("content_copy", &json!({ "doc": locked, "page": 1, "index": 1, "to_doc": to }));
+ assert!(matches!(&refused, Err(ToolError::Failed(m)) if m.contains("copying")), "{refused:?}");
+ }
+ assert_eq!(ok(&mut a, "content_list", json!({ "doc": locked }))["count"], 1);
+}
+
/// An out-of-range `index` (including `i64::MIN`, which overflowed `index - 1`) is a readable
/// failure for `content_update` and `content_delete`, not a panic.
#[test]
@@ -4391,6 +4748,24 @@ fn content_index_out_of_range_is_an_error_not_a_panic() {
assert_eq!(ok(&mut a, "content_list", json!({ "doc": doc }))["count"], 1);
}
+/// Character spacing on added text (#4245): set when adding or restyling, listed back, and refused
+/// out of range or on images.
+#[test]
+fn added_text_takes_character_spacing() {
+ let dir = workdir("content-char-spacing");
+ let mut a = auto(&dir);
+ let doc = ok(&mut a, "doc_open", json!({ "path": "a.pdf" }))["doc"].as_u64().unwrap();
+ ok(&mut a, "page_add_text", json!({ "doc": doc, "page": 1, "text": "Spaced", "at": [20, 20], "char_spacing": 2 }));
+ assert_eq!(ok(&mut a, "content_list", json!({ "doc": doc }))["items"][0]["char_spacing"], 2.0);
+ ok(&mut a, "content_update", json!({ "doc": doc, "page": 1, "index": 1, "char_spacing": -0.5 }));
+ assert_eq!(ok(&mut a, "content_list", json!({ "doc": doc }))["items"][0]["char_spacing"], -0.5);
+ for bad in [json!(1000), json!(-1000), json!("wide")] {
+ let args = json!({ "doc": doc, "page": 1, "index": 1, "char_spacing": bad });
+ assert!(matches!(a.call("content_update", &args), Err(ToolError::InvalidArgs(_))), "{bad}");
+ }
+ assert_eq!(ok(&mut a, "content_list", json!({ "doc": doc }))["items"][0]["char_spacing"], -0.5);
+}
+
fn added_rotation_image(dir: &Path) {
let mut png = Vec::new();
let mut enc = png::Encoder::new(&mut png, 2, 1);
@@ -4829,6 +5204,64 @@ fn stamps_through_tools() {
assert!(matches!(a.call("stamp_custom", &json!({ "doc": doc, "page": 1, "path": "nope.png", "at": [1, 1] })), Err(ToolError::Failed(_))));
}
+/// #4077: a PDF page placed at a given width (a text column, 483 pt) through `rect`, fitted
+/// inside it keeping its shape and centred, and still vector (its text is text).
+#[test]
+fn custom_stamps_fit_a_pdf_page_inside_a_rect() {
+ let dir = workdir("stamp_rect");
+ let mut a = auto(&dir);
+ let doc = ok(&mut a, "doc_create", json!({ "from": "blank", "width": 595, "height": 842 }))["doc"].as_u64().unwrap();
+ let rect_of = |a: &mut Automation, i: usize| -> Vec<f64> {
+ let list = ok(a, "comment_list", json!({ "doc": doc }));
+ list["comments"][i]["rect"].as_array().unwrap().iter().map(|v| v.as_f64().unwrap()).collect()
+ };
+ // Without rect, the page keeps its natural size, at most 200 pt: 200 × 300 is 133⅓ × 200.
+ ok(&mut a, "stamp_custom", json!({ "doc": doc, "page": 1, "path": "b.pdf", "file_page": 2, "at": [100, 150] }));
+ let natural = rect_of(&mut a, 0);
+ assert!((natural[2] - natural[0] - 400.0 / 3.0).abs() < 0.01 && (natural[3] - natural[1] - 200.0).abs() < 0.01, "{natural:?}");
+ // 483 × 750: the width limits the 200 × 300 page to 483 × 724.5, centred top to bottom.
+ ok(&mut a, "stamp_custom", json!({ "doc": doc, "page": 1, "path": "b.pdf", "file_page": 2, "rect": [56, 50, 539, 800] }));
+ assert_eq!(rect_of(&mut a, 1), [56.0, 62.75, 539.0, 787.25]);
+ assert!(page_text(&mut a, doc)[0].contains("Page 2"), "the stamped page's text is still text");
+ assert_eq!(ok(&mut a, "edit_undo", json!({ "doc": doc }))["undone"], "Add stamp");
+ assert_eq!(ok(&mut a, "comment_list", json!({ "doc": doc }))["count"], 1);
+
+ for (args, why) in [
+ (json!({ "rect": [10, 10, 10, 50] }), "zero width"),
+ (json!({ "rect": [10, 10, 50, 10] }), "zero height"),
+ (json!({ "rect": [0, 0, 1e-10, 100] }), "thinner than a point"),
+ (json!({ "rect": [0, 0, 20000, 100] }), "wider than a PDF page can be"),
+ (json!({ "rect": [0, 0, 100, f64::NAN] }), "not a number"),
+ (json!({ "rect": [0, 0, 100] }), "three numbers"),
+ (json!({ "rect": [0, 0, 100, 100], "at": [10, 10] }), "both a box and a point"),
+ (json!({}), "neither a box nor a point"),
+ ] {
+ let mut call = json!({ "doc": doc, "page": 1, "path": "b.pdf" });
+ call.as_object_mut().unwrap().extend(args.as_object().unwrap().clone());
+ assert!(matches!(a.call("stamp_custom", &call), Err(ToolError::InvalidArgs(_))), "{why}");
+ }
+ let past_the_end = json!({ "doc": doc, "page": 1, "path": "b.pdf", "file_page": 9, "rect": [0, 0, 100, 100] });
+ assert!(matches!(a.call("stamp_custom", &past_the_end), Err(ToolError::Failed(_))));
+ assert_eq!(ok(&mut a, "comment_list", json!({ "doc": doc }))["count"], 1, "a refused stamp adds nothing");
+
+ // On a quarter-turned page the picture is fitted as displayed: an 80 × 40 picture in a
+ // 100 × 100 box is 100 × 50 on screen, centred.
+ let mut png_bytes = Vec::new();
+ {
+ let mut encoder = png::Encoder::new(&mut png_bytes, 80, 40);
+ encoder.set_color(png::ColorType::Rgb);
+ encoder.set_depth(png::BitDepth::Eight);
+ encoder.write_header().unwrap().write_image_data(&[200; 80 * 40 * 3]).unwrap();
+ }
+ std::fs::write(dir.join("wide.png"), png_bytes).unwrap();
+ let turned = ok(&mut a, "doc_open", json!({ "path": "a.pdf" }))["doc"].as_u64().unwrap();
+ ok(&mut a, "page_rotate", json!({ "doc": turned, "pages": [1], "degrees": 90 }));
+ ok(&mut a, "stamp_custom", json!({ "doc": turned, "page": 1, "path": "wide.png", "rect": [50, 60, 150, 160] }));
+ let list = ok(&mut a, "comment_list", json!({ "doc": turned }));
+ let rect: Vec<f64> = list["comments"][0]["rect"].as_array().unwrap().iter().map(|v| v.as_f64().unwrap()).collect();
+ assert_eq!(rect, [50.0, 85.0, 150.0, 135.0]);
+}
+
#[test]
fn bookmark_split_with_equal_titles_keeps_every_part() {
let dir = workdir("organize_dup_titles");
@@ -4938,6 +5371,33 @@ fn links_through_tools() {
assert!(matches!(a.call("link_add", &json!({ "doc": doc, "page": 1, "rect": [0, 0, 50, 20] })), Err(ToolError::InvalidArgs(_))));
}
+/// #4168: a Launch action whose file is a PDF (here with Windows `\` separators, relative to the
+/// source as a remote link is) opens that PDF in PdfCraft through link_open, within the root; one
+/// naming a program is listed but never followed.
+#[test]
+fn a_launch_link_to_a_pdf_opens_it_like_a_remote_link() {
+ let (_base, root) = sandbox("launch-pdf");
+ std::fs::create_dir_all(root.join("ts")).unwrap();
+ std::fs::create_dir_all(root.join("se")).unwrap();
+ std::fs::write(root.join("se/se_B2.pdf"), fixture(2)).unwrap();
+ // The helper writes a GoToR; the action is renamed (the parser rebuilds the shifted offsets).
+ let launch = |file: &str| String::from_utf8(remote_link_pdf(file, None)).unwrap().replace("/S /GoToR", "/S /Launch").into_bytes();
+ std::fs::write(root.join("ts/TS_304.pdf"), launch(r"..\se\se_B2.pdf")).unwrap();
+ std::fs::write(root.join("ts/program.pdf"), launch("tool.exe")).unwrap();
+ let mut a = auto(&root);
+ let source = ok(&mut a, "doc_open", json!({ "path": "ts/TS_304.pdf" }))["doc"].as_u64().unwrap();
+ let info = ok(&mut a, "doc_info", json!({ "doc": source }));
+ let link = &info["links"][0]["target"];
+ assert_eq!((link["action"].as_str(), link["remote_document"].as_str()), (Some("Launch"), Some("../se/se_B2.pdf")), "{info}");
+ let opened = ok(&mut a, "link_open", json!({ "doc": source, "page": 1, "index": 1 }));
+ assert_eq!(opened["path"].as_str().map(|p| p.replace('\\', "/")).as_deref(), Some("se/se_B2.pdf"), "{opened}");
+ assert_eq!(opened["document"]["pages"], 2);
+ let program = ok(&mut a, "doc_open", json!({ "path": "ts/program.pdf" }))["doc"].as_u64().unwrap();
+ let before = a.session().docs().len();
+ assert!(matches!(err(&mut a, "link_open", json!({ "doc": program, "page": 1, "index": 1 })), ToolError::InvalidArgs(_) | ToolError::Failed(_)));
+ assert_eq!(a.session().docs().len(), before, "nothing was opened or launched");
+}
+
#[test]
fn local_gotor_link_open_refuses_directories_devices_and_non_pdf_targets() {
let (_base, root) = sandbox("gotor-not-a-file");
@@ -5760,6 +6220,28 @@ fn optimizing_through_tools() {
assert!(reduced["bytes_after"].as_u64().unwrap() < reduced["bytes_before"].as_u64().unwrap());
assert_eq!(reduced["written"], true);
assert_eq!(std::fs::metadata(dir.join("reduced.pdf")).unwrap().len(), reduced["bytes_after"].as_u64().unwrap());
+
+ // Target PDF 1.4 (disables object streams) and PDF 2.0 (with object_streams toggled off).
+ let v14 = ok(&mut a, "doc_optimize", json!({ "doc": doc, "path": "v14.pdf", "compatibility": "1.4" }));
+ assert_eq!((v14["pdf_version"].as_str(), v14["object_streams"].as_bool()), (Some("1.4"), Some(false)), "{v14}");
+ let v14_bytes = std::fs::read(dir.join("v14.pdf")).unwrap();
+ assert!(v14_bytes.starts_with(b"%PDF-1.4\n") && !v14_bytes.windows(7).any(|w| w == b"/ObjStm"));
+
+ let v20 = ok(&mut a, "doc_optimize", json!({ "doc": doc, "path": "v20.pdf", "compatibility": "2.0", "object_streams": false }));
+ assert_eq!((v20["pdf_version"].as_str(), v20["object_streams"].as_bool()), (Some("2.0"), Some(false)), "{v20}");
+ assert!(std::fs::read(dir.join("v20.pdf")).unwrap().starts_with(b"%PDF-2.0\n"));
+
+ // In retain mode, a catalog /Version override is reported as the effective PDF version.
+ let mut cos14 = pdfcraft_cos::Document::open(std::sync::Arc::new(v14_bytes)).unwrap();
+ let root = cos14.root().unwrap();
+ cos14.update_dict(root, |c| c.set(b"Version".to_vec(), pdfcraft_cos::Object::name("1.6"))).unwrap();
+ let cat16 = pdfcraft_cos::write_full(&cos14, &pdfcraft_cos::SaveOptions { object_streams: false, ..Default::default() }).unwrap();
+ std::fs::write(dir.join("cat16.pdf"), &cat16).unwrap();
+ let cat_doc = ok(&mut a, "doc_open", json!({ "path": "cat16.pdf" }))["doc"].as_u64().unwrap();
+ let retained = ok(&mut a, "doc_optimize", json!({ "doc": cat_doc, "path": "retained.pdf", "compatibility": "retain", "object_streams": false }));
+ assert_eq!(retained["pdf_version"].as_str(), Some("1.6"), "{retained}");
+
+ assert!(matches!(a.call("doc_optimize", &json!({ "doc": doc, "path": "x.pdf", "compatibility": "1.3" })), Err(ToolError::InvalidArgs(_))));
assert!(matches!(
a.call("doc_optimize", &json!({ "doc": doc, "path": "x.pdf", "color": { "compression": "gif" } })),
Err(ToolError::InvalidArgs(_))
@@ -5767,6 +6249,76 @@ fn optimizing_through_tools() {
assert!(matches!(a.call("doc_optimize", &json!({ "doc": doc, "path": "x.pdf", "discard": ["everything"] })), Err(ToolError::InvalidArgs(_))));
}
+/// #3227 review: retaining the version, a catalog `/Version` below the 1.5 an object stream
+/// needs is not what viewers read: the header is raised, and the later of the two is reported.
+#[test]
+fn retained_pdf_version_reports_the_header_raised_for_object_streams() {
+ let dir = workdir("optimize-retain-version");
+ let mut a = auto(&dir);
+ let blank = ok(&mut a, "doc_create", json!({ "from": "blank", "width": 300, "height": 400 }))["doc"].as_u64().unwrap();
+ ok(&mut a, "doc_optimize", json!({ "doc": blank, "path": "v14.pdf", "compatibility": "1.4" }));
+ let mut cos = pdfcraft_cos::Document::open(std::sync::Arc::new(std::fs::read(dir.join("v14.pdf")).unwrap())).unwrap();
+ let root = cos.root().unwrap();
+ cos.update_dict(root, |c| c.set(b"Version".to_vec(), pdfcraft_cos::Object::name("1.4"))).unwrap();
+ let bytes = pdfcraft_cos::write_full(&cos, &pdfcraft_cos::SaveOptions { object_streams: false, ..Default::default() }).unwrap();
+ std::fs::write(dir.join("cat14.pdf"), &bytes).unwrap();
+ let doc = ok(&mut a, "doc_open", json!({ "path": "cat14.pdf" }))["doc"].as_u64().unwrap();
+ let r = ok(&mut a, "doc_optimize", json!({ "doc": doc, "path": "out.pdf", "compatibility": "retain", "object_streams": true }));
+ let out = std::fs::read(dir.join("out.pdf")).unwrap();
+ assert!(out.starts_with(b"%PDF-1.5\n") && out.windows(7).any(|w| w == b"/ObjStm"), "{r}");
+ assert_eq!(r["pdf_version"].as_str(), Some("1.5"), "{r}");
+}
+
+/// `data` as LZW with one 9-bit literal code per byte (clear-table first, EOD last): valid for
+/// fewer than 250 bytes, before the code width grows.
+fn lzw_literals(data: &[u8]) -> Vec<u8> {
+ let codes: Vec<u16> = std::iter::once(256).chain(data.iter().map(|&b| u16::from(b))).chain([257]).collect();
+ let bits: Vec<bool> = codes.iter().flat_map(|c| (0..9).rev().map(move |i| c >> i & 1 == 1)).collect();
+ bits.chunks(8).map(|byte| byte.iter().enumerate().fold(0u8, |acc, (i, &b)| acc | (u8::from(b) << (7 - i)))).collect()
+}
+
+#[test]
+fn lzw_streams_are_stored_with_flate_through_tools() {
+ use pdfcraft_cos::{Dict, Document, Object, SaveOptions, Stream, write_full};
+ let dir = workdir("optimize-lzw");
+ let ops = b"0.2 0.4 0.8 rg 72 72 200 100 re f 0 0 1 RG 72 300 m 400 500 l S".to_vec();
+ let mut doc = Document::new_empty();
+ let pages = doc.get(doc.root().unwrap()).as_dict().unwrap().reference(b"Pages").unwrap();
+ let lzw = Stream::from_raw(Dict::from_iter([(b"Filter".to_vec(), Object::name("LZWDecode"))]), lzw_literals(&ops));
+ assert_eq!(lzw.decoded_strict().unwrap(), ops);
+ let content = doc.add(Object::Stream(lzw));
+ let page = doc.add(Object::Dict(Dict::from_iter([
+ (b"Type".to_vec(), Object::name("Page")),
+ (b"Parent".to_vec(), Object::Ref(pages)),
+ (b"MediaBox".to_vec(), Object::Array(vec![0.into(), 0.into(), 612.into(), 792.into()])),
+ (b"Contents".to_vec(), Object::Ref(content)),
+ ])));
+ doc.update_dict(pages, |d| {
+ d.set(b"Kids".to_vec(), Object::Array(vec![Object::Ref(page)]));
+ d.set(b"Count".to_vec(), Object::Int(1));
+ })
+ .unwrap();
+ std::fs::write(dir.join("lzw.pdf"), write_full(&doc, &SaveOptions::default()).unwrap()).unwrap();
+ let mut a = auto(&dir);
+ let doc = ok(&mut a, "doc_open", json!({ "path": "lzw.pdf" }))["doc"].as_u64().unwrap();
+ let filters = |name: &str| {
+ let saved = pdfcraft_cos::Document::open(std::sync::Arc::new(std::fs::read(dir.join(name)).unwrap())).unwrap();
+ let catalog = saved.get(saved.root().unwrap()).as_dict().cloned().unwrap();
+ let pages = saved.get(catalog.reference(b"Pages").unwrap()).as_dict().cloned().unwrap();
+ let page = saved.get(pages.get(b"Kids").and_then(|k| k.as_array()?.first()?.as_ref()).unwrap()).as_dict().cloned().unwrap();
+ match &*saved.get(page.reference(b"Contents").unwrap()) {
+ Object::Stream(s) => (s.dict.get(b"Filter").cloned(), s.decoded_strict().unwrap()),
+ _ => panic!("the page content is not a stream"),
+ }
+ };
+ let r = ok(&mut a, "doc_optimize", json!({ "doc": doc, "path": "flate.pdf" }));
+ assert_eq!(r["lzw_streams"].as_u64(), Some(1), "{r}");
+ assert_eq!(filters("flate.pdf"), (Some(Object::name("FlateDecode")), ops.clone()));
+ let off = ok(&mut a, "doc_optimize", json!({ "doc": doc, "path": "kept.pdf", "lzw_to_flate": false }));
+ assert_eq!(off["lzw_streams"].as_u64(), Some(0), "{off}");
+ assert_eq!(filters("kept.pdf"), (Some(Object::name("LZWDecode")), ops));
+}
+
/// A one-page PDF whose page picture is drawn as `rows` grey images one pixel row high, 600 px
/// wide on a 72 pt square (600 ppi), as some PDF printers write it.
fn printed_in_strips(rows: usize) -> Vec<u8> {
@@ -5989,6 +6541,60 @@ fn ocr_recognize_files_writes_searchable_copies() {
assert!(found.to_string().contains("\"page\""), "{found}");
}
+/// Two inputs that share a file name (from different folders) would both write `out/scan.pdf`:
+/// the second output replaces the first while both results report success. The batch is refused
+/// up front, naming the file, before the folder is created, anything is read or the OCR engines
+/// load, so the outcome is the same with or without the models installed.
+#[test]
+fn ocr_recognize_files_refuses_inputs_that_share_a_file_name() {
+ let dir = workdir("ocr-files-same-name");
+ let mut a = auto(&dir);
+ let doc = ok(&mut a, "doc_open", json!({ "path": "a.pdf" }))["doc"].as_u64().unwrap();
+ ok(&mut a, "doc_save", json!({ "doc": doc, "path": "one/scan.pdf" }));
+ ok(&mut a, "doc_save", json!({ "doc": doc, "path": "two/scan.pdf" }));
+ let r = a.call("ocr_recognize_files", &json!({ "paths": ["one/scan.pdf", "two/scan.pdf"], "folder": "out" }));
+ assert!(matches!(&r, Err(ToolError::InvalidArgs(m)) if m.contains("scan.pdf")), "{r:?}");
+ assert!(!dir.join("out").exists(), "nothing was started: the output folder was not created");
+}
+
+/// File names are compared without regard to case on Windows and macOS (`scan.pdf` and `Scan.PDF`
+/// are one file there), and exactly elsewhere, where they are two files and the batch is not
+/// refused.
+#[test]
+fn ocr_recognize_files_compares_names_the_way_the_filesystem_does() {
+ let dir = workdir("ocr-files-case");
+ let mut a = auto(&dir);
+ let doc = ok(&mut a, "doc_open", json!({ "path": "a.pdf" }))["doc"].as_u64().unwrap();
+ ok(&mut a, "doc_save", json!({ "doc": doc, "path": "one/scan.pdf" }));
+ ok(&mut a, "doc_save", json!({ "doc": doc, "path": "two/Scan.PDF" }));
+ let r = a.call("ocr_recognize_files", &json!({ "paths": ["one/scan.pdf", "two/Scan.PDF"], "folder": "out" }));
+ if cfg!(any(windows, target_os = "macos")) {
+ assert!(matches!(&r, Err(ToolError::InvalidArgs(m)) if m.contains("Scan.PDF")), "{r:?}");
+ assert!(!dir.join("out").exists(), "nothing was started: the output folder was not created");
+ } else {
+ assert!(!matches!(&r, Err(ToolError::InvalidArgs(_))), "{r:?}");
+ }
+}
+
+/// Inputs with distinct names are not refused, and the batch writes one searchable copy per input
+/// under its own name. Without the models it stops at the models error, as it did before.
+#[test]
+fn ocr_recognize_files_with_distinct_names_runs_as_before() {
+ let dir = workdir("ocr-files-distinct");
+ let mut a = auto(&dir);
+ let doc = ok(&mut a, "doc_open", json!({ "path": "a.pdf" }))["doc"].as_u64().unwrap();
+ ok(&mut a, "doc_save", json!({ "doc": doc, "path": "one/scan.pdf" }));
+ ok(&mut a, "doc_save", json!({ "doc": doc, "path": "two/other.pdf" }));
+ if ok(&mut a, "ocr_status", json!({}))["available"] == true {
+ let r = ok(&mut a, "ocr_recognize_files", json!({ "paths": ["one/scan.pdf", "two/other.pdf"], "folder": "out" }));
+ assert!(r["files"][0]["error"].is_null() && r["files"][1]["error"].is_null(), "{r}");
+ assert!(dir.join("out/scan.pdf").is_file() && dir.join("out/other.pdf").is_file(), "{r}");
+ } else {
+ let r = a.call("ocr_recognize_files", &json!({ "paths": ["one/scan.pdf", "two/other.pdf"], "folder": "out" }));
+ assert!(matches!(&r, Err(ToolError::Failed(m)) if m.contains("not installed")), "{r:?}");
+ }
+}
+
#[test]
fn javascript_through_tools() {
let dir = workdir("js");
@@ -6032,6 +6638,12 @@ fn javascript_through_tools() {
assert_eq!(total["value"], "3750");
let r = ok(&mut a, "js_run", json!({ "doc": doc, "script": "nope()" }));
assert!(r["error"].as_str().unwrap().contains("nope"));
+ assert_eq!(r["document_errors"], json!([]));
+ // A document script that throws (#3940) is reported, and the others and the script still run.
+ ok(&mut a, "js_set_document_script", json!({ "doc": doc, "name": "zz", "script": "getField('Total').buttonSetIcon(null);" }));
+ let r = ok(&mut a, "js_run", json!({ "doc": doc, "script": "money(5)" }));
+ assert_eq!((r["error"].clone(), r["result"].clone()), (json!(null), json!("EUR 5,00")));
+ assert!(r["document_errors"][0].as_str().unwrap().starts_with("document script 2: TypeError"), "{r}");
assert_eq!(ok(&mut a, "js_enabled", json!({ "enabled": false }))["enabled"], false);
assert!(a.call("js_run", &json!({ "doc": doc, "script": "1" })).is_err());
}
@@ -6567,6 +7179,33 @@ fn xfa_rich_text_max_length_is_reported_and_enforced_through_tools() {
assert_eq!(family["value"], "éàöüñ");
}
+/// A link in a dynamic XFA form's rich text is a link on the laid-out page, as link_list reports
+/// it, and stays one after a save and a fresh open.
+#[test]
+fn links_in_xfa_rich_text_are_listed_through_tools() {
+ let dir = workdir("xfa-links");
+ let xdp = r##"<?xml version="1.0" encoding="UTF-8"?>
+<xdp:xdp xmlns:xdp="http://ns.adobe.com/xdp/"><template xmlns="http://www.xfa.org/schema/xfa-template/3.3/"><subform name="form" layout="tb">
+ <pageSet><pageArea name="page"><contentArea x="0.5in" y="0.5in" w="7.5in" h="10in"/><medium short="8.5in" long="11in"/></pageArea></pageSet>
+ <draw name="help" w="6in"><font typeface="Arial" size="10pt"/><value><exData contentType="text/html"><body xmlns="http://www.w3.org/1999/xhtml"><p>Questions? Email <a href="mailto:[email protected]">[email protected]</a>.</p></body></exData></value></draw>
+ <field name="name" w="3in" h="0.3in"><ui><textEdit/></ui></field>
+</subform></template></xdp:xdp>"##;
+ std::fs::write(dir.join("links.pdf"), pdfcraft_xfa::fixtures::shell(xdp)).unwrap();
+ let mut a = auto(&dir);
+ let doc = ok(&mut a, "doc_open", json!({ "path": "links.pdf" }))["doc"].as_u64().unwrap();
+ let urls = |a: &mut Automation, doc: u64| -> Vec<String> {
+ let listed = ok(a, "link_list", json!({ "doc": doc }));
+ let links = listed["links"].as_array().cloned().unwrap_or_default();
+ links.iter().filter_map(|l| l["url"].as_str().map(str::to_string)).collect()
+ };
+ assert_eq!(urls(&mut a, doc), ["mailto:[email protected]"]);
+ ok(&mut a, "form_fill", json!({ "doc": doc, "values": { "name": "Ada" } }));
+ ok(&mut a, "doc_save", json!({ "doc": doc, "path": "saved.pdf" }));
+ ok(&mut a, "doc_close", json!({ "doc": doc }));
+ let doc = ok(&mut a, "doc_open", json!({ "path": "saved.pdf" }))["doc"].as_u64().unwrap();
+ assert_eq!(urls(&mut a, doc), ["mailto:[email protected]"], "one link after a save and a fresh open, not two");
+}
+
#[test]
fn dynamic_xfa_forms_open_render_fill_and_save_through_tools() {
let dir = workdir("xfa");
@@ -6634,7 +7273,9 @@ fn cut_stack_printing_through_tools() {
&mut a,
"doc_print",
json!({
- "doc": doc, "pages": "2-10", "subset": "odd", "reverse": true,
+ // Even pages by page number (#3984): 2, 4, 6, 8 and 10 (counting places in the range,
+ // "even" would have been 3, 5, 7 and 9).
+ "doc": doc, "pages": "2-10", "subset": "even", "reverse": true,
"layout": "multiple", "order": "cut-stack", "per_sheet": 2, "auto_rotate": false,
"orientation": "landscape", "path": "range.pdf"
}),
@@ -6898,6 +7539,35 @@ fn xfa_scripts_run_for_buttons_and_field_changes_through_tools() {
assert_eq!(r["alerts"], json!(["Hello 4"]));
}
+#[test]
+fn active_xfa_skips_container_fallback_scripts_after_save_and_reopen() {
+ let dir = workdir("xfa-container-scripts");
+ std::fs::write(dir.join("form.pdf"), pdfcraft_xfa::fixtures::shell(&pdfcraft_xfa::fixtures::scripted_template())).unwrap();
+ let mut a = auto(&dir);
+ let doc = ok(&mut a, "doc_open", json!({"path": "form.pdf"}))["doc"].as_u64().unwrap();
+ let fallback = "app.alert('This PDF form requires a newer version of Adobe Acrobat');";
+ ok(&mut a, "js_set_document_script", json!({"doc":doc,"name":"viewerFallback","script":fallback}));
+ let out = ok(&mut a, "js_run", json!({"doc":doc,"script":"app.alert('Console message');"}));
+ assert!(out["error"].is_null(), "{out}");
+ assert_eq!(out["alerts"], json!(["Console message"]));
+ ok(&mut a, "doc_save", json!({"doc":doc,"path":"saved.pdf"}));
+ ok(&mut a, "doc_close", json!({"doc":doc}));
+ let doc = ok(&mut a, "doc_open", json!({"path":"saved.pdf"}))["doc"].as_u64().unwrap();
+ assert_eq!(ok(&mut a, "js_document_scripts", json!({"doc":doc}))["scripts"], json!([{"name":"viewerFallback","script":fallback}]));
+ let out = ok(&mut a, "js_run", json!({"doc":doc,"script":""}));
+ assert!(out["error"].is_null(), "{out}");
+ assert_eq!(out["alerts"], json!([]));
+ let out = ok(&mut a, "js_run", json!({"doc":doc,"script":"","field":"hello"}));
+ assert!(out["error"].is_null(), "{out}");
+ assert_eq!(out["alerts"], json!(["Hello 2"]));
+ ok(&mut a, "xfa_to_static", json!({"doc":doc}));
+ let out = ok(&mut a, "js_run", json!({"doc":doc,"script":""}));
+ assert_eq!(out["alerts"].as_array().unwrap().len(), 1);
+ ok(&mut a, "edit_undo", json!({"doc":doc}));
+ assert_eq!(ok(&mut a, "js_run", json!({"doc":doc,"script":""}))["alerts"], json!([]));
+ let _ = std::fs::remove_dir_all(dir);
+}
+
#[test]
fn doc_info_says_when_a_runaway_script_turned_the_forms_scripts_off() {
let dir = workdir("xfa-scripts-off");
@@ -8053,6 +8723,46 @@ fn a_root_less_write_output_is_atomic_too() {
let _ = std::fs::remove_dir_all(&dir);
}
+#[test]
+fn attaching_and_deleting_files_through_the_tools() {
+ let dir = workdir("attach");
+ std::fs::write(dir.join("notes.txt"), b"keep this with the PDF").unwrap();
+ let mut a = auto(&dir);
+ let doc = ok(&mut a, "doc_open", json!({ "path": "a.pdf" }))["doc"].as_u64().unwrap();
+ assert!(ok(&mut a, "doc_info", json!({ "doc": doc }))["attachments"].as_array().unwrap().is_empty());
+ // A text file and a PDF, the PDF under a name of its own; the second notes.txt is kept apart.
+ let r = ok(&mut a, "attachment_add", json!({ "doc": doc, "path": "notes.txt", "description": "Meeting notes" }));
+ assert_eq!(r["name"], "notes.txt");
+ let r = ok(&mut a, "attachment_add", json!({ "doc": doc, "path": "b.pdf", "name": "annex.pdf" }));
+ assert_eq!(r["name"], "annex.pdf");
+ let r = ok(&mut a, "attachment_add", json!({ "doc": doc, "path": "notes.txt" }));
+ assert_eq!(r["name"], "notes.txt (2)");
+ let listed = ok(&mut a, "doc_info", json!({ "doc": doc }))["attachments"].clone();
+ let names: Vec<&str> = listed.as_array().unwrap().iter().map(|x| x["name"].as_str().unwrap()).collect();
+ assert_eq!(names, ["annex.pdf", "notes.txt", "notes.txt (2)"]);
+ assert_eq!(listed[1]["description"], "Meeting notes");
+ assert_eq!(listed[1]["size"], 22);
+ // Saved and reopened, the attachment is there with its bytes.
+ ok(&mut a, "doc_save", json!({ "doc": doc, "path": "with-notes.pdf" }));
+ let saved = std::fs::read(dir.join("with-notes.pdf")).unwrap();
+ let info = pdfcraft_render::inspect(std::sync::Arc::new(saved.clone()), None).unwrap();
+ let att = info.attachments.iter().find(|x| x.name == "notes.txt").expect("notes.txt is in the file");
+ assert_eq!(pdfcraft_render::attachment_data(&saved, None, att).unwrap(), b"keep this with the PDF");
+ // Deleting one leaves the others; a name that is not there is refused; undo brings it back.
+ ok(&mut a, "attachment_delete", json!({ "doc": doc, "name": "notes.txt" }));
+ let names: Vec<String> = ok(&mut a, "doc_info", json!({ "doc": doc }))["attachments"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .map(|x| x["name"].as_str().unwrap().to_string())
+ .collect();
+ assert_eq!(names, ["annex.pdf", "notes.txt (2)"]);
+ assert!(a.call("attachment_delete", &json!({ "doc": doc, "name": "notes.txt" })).is_err());
+ ok(&mut a, "edit_undo", json!({ "doc": doc }));
+ assert_eq!(ok(&mut a, "doc_info", json!({ "doc": doc }))["attachments"].as_array().unwrap().len(), 3);
+ assert!(a.call("attachment_add", &json!({ "doc": doc, "path": "missing.txt" })).is_err(), "a file that is not there is refused");
+}
+
#[test]
fn fdf_nested_comment_values_survive_export_import_and_save_through_tools() {
use pdfcraft_cos::{Dict, Document, Object, PdfString, SaveOptions, write_full};
@@ -8409,3 +9119,162 @@ fn comments_are_reshaped_through_the_tool() {
assert!(a.call("comment_edit", &json!({ "doc": doc, "page": 1, "index": 1, "points": [[1, 2]] })).is_err(), "a line has two ends");
assert!(matches!(a.call("comment_edit", &json!({ "doc": doc, "page": 1, "index": 1, "points": "no" })), Err(ToolError::InvalidArgs(_))));
}
+
+/// #3193: bookmark_list reports a bookmark's colour and style (ISO 32000-2 §12.3.3, Tables 151
+/// and 152), only where they differ from black and regular. The list is read from the opened file
+/// and, once the document has been edited, from the edited one; both read them alike.
+/// bookmark_set_style changes them, and they survive a save.
+#[test]
+fn bookmark_list_reports_colour_and_style() {
+ let dir = workdir("bookmark-style");
+ let objects: Vec<&[u8]> = vec![
+ b"<< /Type /Catalog /Pages 2 0 R /Outlines 4 0 R >>",
+ b"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 200 300] >>",
+ b"<< /Type /Page /Parent 2 0 R >>",
+ b"<< /Type /Outlines /First 5 0 R /Last 7 0 R /Count 3 >>",
+ b"<< /Title (Plain) /Parent 4 0 R /Next 6 0 R /Dest [3 0 R /Fit] >>",
+ b"<< /Title (Red bold) /Parent 4 0 R /Prev 5 0 R /Next 7 0 R /Dest [3 0 R /Fit] /C [1 0 0] /F 2 >>",
+ b"<< /Title (Blue italic) /Parent 4 0 R /Prev 6 0 R /Dest [3 0 R /Fit] /C [0 0 1] /F 1 >>",
+ ];
+ let mut bytes = b"%PDF-1.7\n".to_vec();
+ let mut offsets = Vec::new();
+ for (i, object) in objects.iter().enumerate() {
+ offsets.push(bytes.len());
+ bytes.extend_from_slice(format!("{} 0 obj\n", i + 1).as_bytes());
+ bytes.extend_from_slice(object);
+ bytes.extend_from_slice(b"\nendobj\n");
+ }
+ let xref = bytes.len();
+ bytes.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objects.len() + 1).as_bytes());
+ for o in offsets {
+ bytes.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes());
+ }
+ bytes.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objects.len() + 1).as_bytes());
+ std::fs::write(dir.join("styled.pdf"), bytes).unwrap();
+ let mut a = auto(&dir);
+ let doc = ok(&mut a, "doc_open", json!({ "path": "styled.pdf" }))["doc"].as_u64().unwrap();
+ let style = |list: &Value| -> Vec<(Value, Value, Value)> {
+ list.as_array().unwrap().iter().map(|b| (b["color"].clone(), b["bold"].clone(), b["italic"].clone())).collect()
+ };
+ let expected = vec![
+ (Value::Null, Value::Null, Value::Null),
+ (json!([1.0, 0.0, 0.0]), json!(true), Value::Null),
+ (json!([0.0, 0.0, 1.0]), Value::Null, json!(true)),
+ ];
+ let opened = ok(&mut a, "bookmark_list", json!({ "doc": doc }))["bookmarks"].clone();
+ assert_eq!(style(&opened), expected, "as opened: {opened}");
+ ok(&mut a, "bookmark_rename", json!({ "doc": doc, "path": [1], "title": "Still plain" }));
+ let edited = ok(&mut a, "bookmark_list", json!({ "doc": doc }))["bookmarks"].clone();
+ assert_eq!(style(&edited), expected, "after an edit: {edited}");
+
+ // bookmark_set_style changes only what it is given.
+ ok(&mut a, "bookmark_set_style", json!({ "doc": doc, "path": [1], "color": [0, 0.5, 0], "italic": true }));
+ ok(&mut a, "bookmark_set_style", json!({ "doc": doc, "path": [2], "bold": false }));
+ ok(&mut a, "bookmark_set_style", json!({ "doc": doc, "path": [3], "color": [0, 0, 0] }));
+ let set = ok(&mut a, "bookmark_list", json!({ "doc": doc }))["bookmarks"].clone();
+ assert_eq!(
+ style(&set),
+ vec![
+ (json!([0.0, 0.5, 0.0]), Value::Null, json!(true)),
+ (json!([1.0, 0.0, 0.0]), Value::Null, Value::Null),
+ (Value::Null, Value::Null, json!(true))
+ ],
+ "{set}"
+ );
+ // A colour and a style in one call are one undo step.
+ ok(&mut a, "bookmark_set_style", json!({ "doc": doc, "path": [2], "color": [0, 0, 0], "bold": true, "italic": true }));
+ let both = ok(&mut a, "bookmark_list", json!({ "doc": doc }))["bookmarks"].clone();
+ assert_eq!(style(&both)[1], (Value::Null, json!(true), json!(true)), "{both}");
+ ok(&mut a, "edit_undo", json!({ "doc": doc }));
+ let undone = ok(&mut a, "bookmark_list", json!({ "doc": doc }))["bookmarks"].clone();
+ assert_eq!(style(&undone), style(&set), "one undo takes back both: {undone}");
+ for bad in [
+ json!({ "doc": doc, "path": [1] }),
+ json!({ "doc": doc, "path": [1], "color": [2, 0, 0] }),
+ json!({ "doc": doc, "path": [1], "color": [1, 0] }),
+ ] {
+ assert!(matches!(a.call("bookmark_set_style", &bad), Err(ToolError::InvalidArgs(_))), "{bad}");
+ }
+ ok(&mut a, "doc_save", json!({ "doc": doc, "path": "restyled.pdf" }));
+ let mut b = auto(&dir);
+ let re = ok(&mut b, "doc_open", json!({ "path": "restyled.pdf" }))["doc"].as_u64().unwrap();
+ assert_eq!(style(&ok(&mut b, "bookmark_list", json!({ "doc": re }))["bookmarks"]), style(&set), "saved");
+}
+
+/// An editable combo box (ISO 32000-2 Table 233, Edit) takes a value that isn't one of its
+/// options, and its page appearance shows it, before and after a save; one without Edit takes
+/// only its options.
+#[test]
+fn form_fill_takes_free_text_only_in_an_editable_combo_box() {
+ let dir = workdir("editable-combo");
+ let mut a = auto(&dir);
+ let doc = ok(&mut a, "doc_open", json!({ "path": "a.pdf" }))["doc"].as_u64().unwrap();
+ let combo = |name: &str, top: f64, editable: bool| json!({ "doc": doc, "page": 1, "type": "combo", "rect": [20, top, 200, top + 22.0], "name": name, "options": ["Apple", "Banana"], "editable": editable });
+ ok(&mut a, "form_add_field", combo("fruit", 20.0, true));
+ ok(&mut a, "form_add_field", combo("veg", 60.0, false));
+ ok(&mut a, "form_fill", json!({ "doc": doc, "values": { "fruit": "Cherry" } }));
+ assert!(page_text(&mut a, doc)[0].contains("Cherry"), "the typed value is drawn");
+ let refused = err(&mut a, "form_fill", json!({ "doc": doc, "values": { "veg": "Cherry" } }));
+ assert!(matches!(&refused, ToolError::Failed(m) | ToolError::InvalidArgs(m) if m.contains("no option")), "{refused:?}");
+ // A choice from the list still works in both.
+ ok(&mut a, "form_fill", json!({ "doc": doc, "values": { "veg": "Banana" } }));
+ ok(&mut a, "doc_save", json!({ "doc": doc, "path": "filled.pdf" }));
+ let saved = ok(&mut a, "doc_open", json!({ "path": "filled.pdf" }))["doc"].as_u64().unwrap();
+ let fields = ok(&mut a, "form_fields", json!({ "doc": saved }));
+ let value = |name: &str| fields["fields"].as_array().unwrap().iter().find(|f| f["name"] == name).map(|f| f["value"].clone());
+ assert_eq!(value("fruit"), Some(json!("Cherry")), "{fields}");
+ assert_eq!(value("veg"), Some(json!("Banana")), "{fields}");
+ let text = page_text(&mut a, saved);
+ assert!(text[0].contains("Cherry") && text[0].contains("Banana"), "{text:?}");
+ let _ = std::fs::remove_dir_all(&dir);
+}
+
+/// `page_render`'s pixels show a rubber stamp written without an appearance as the stamp its
+/// `/Name` names (ISO 32000-2 Table 184), and one with an unknown name as a grey placeholder.
+#[test]
+fn page_render_draws_stamps_without_an_appearance() {
+ let dir = workdir("stamps-without-appearance");
+ let objects: Vec<&[u8]> = vec![
+ b"<< /Type /Catalog /Pages 2 0 R >>",
+ b"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 300 100] >>",
+ b"<< /Type /Page /Parent 2 0 R /Annots [4 0 R 5 0 R] >>",
+ b"<< /Type /Annot /Subtype /Stamp /Rect [10 20 130 80] /Name /Approved >>",
+ b"<< /Type /Annot /Subtype /Stamp /Rect [170 20 290 80] /Name /MyCustomStamp >>",
+ ];
+ let mut bytes = b"%PDF-1.7\n".to_vec();
+ let mut offsets = Vec::new();
+ for (i, object) in objects.iter().enumerate() {
+ offsets.push(bytes.len());
+ bytes.extend_from_slice(format!("{} 0 obj\n", i + 1).as_bytes());
+ bytes.extend_from_slice(object);
+ bytes.extend_from_slice(b"\nendobj\n");
+ }
+ let xref = bytes.len();
+ bytes.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objects.len() + 1).as_bytes());
+ for o in offsets {
+ bytes.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes());
+ }
+ bytes.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objects.len() + 1).as_bytes());
+ std::fs::write(dir.join("stamps.pdf"), bytes).unwrap();
+ let mut a = auto(&dir);
+ let doc = ok(&mut a, "doc_open", json!({ "path": "stamps.pdf" }))["doc"].as_u64().unwrap();
+ let (width, _, pixels) = a.render_pixels(doc, 1, 1.0).unwrap();
+ let pixels = pixels.as_ref();
+ // Ink in columns `x0..x1` of rows 20..80, which are the stamps' rows whether counted from the top or the bottom.
+ let ink = |x0: u32, x1: u32| -> Vec<[u8; 3]> {
+ (20..80u32)
+ .flat_map(|y| (x0..x1).map(move |x| (y, x)))
+ .map(|(y, x)| {
+ let i = ((y * width + x) * 4) as usize;
+ [pixels[i], pixels[i + 1], pixels[i + 2]]
+ })
+ .filter(|p| p.iter().any(|v| *v < 200))
+ .collect()
+ };
+ let approved = ink(10, 130);
+ let green = approved.iter().filter(|p| p[1] > p[0] && p[1] > p[2]).count();
+ assert!(green > 300 && green * 10 > approved.len() * 9, "Approved is drawn green: {green} of {}", approved.len());
+ let custom = ink(170, 290);
+ let grey = custom.iter().filter(|p| p[0].abs_diff(p[1]) < 24 && p[1].abs_diff(p[2]) < 24).count();
+ assert!(grey > 100 && grey == custom.len(), "an unknown name is a grey placeholder: {grey} of {}", custom.len());
+}
diff --git a/crates/automation/tests/it/automation_roots.rs b/crates/automation/tests/it/automation_roots.rs
index 94958ea..a96870c 100644
--- a/crates/automation/tests/it/automation_roots.rs
+++ b/crates/automation/tests/it/automation_roots.rs
@@ -152,6 +152,7 @@ fn tools_that_read_a_path_are_held_to_the_read_root() {
("doc_create_multiple", json!({"paths": [secret], "mode": "combine", "out": out})),
("doc_create", json!({"from": "images", "paths": [pic]})),
("stamp_custom", json!({"doc": 1, "page": 1, "path": secret, "at": [10, 10]})),
+ ("stamp_custom", json!({"doc": 1, "page": 1, "path": secret, "rect": [10, 10, 493, 300]})),
("page_add_image", json!({"doc": 1, "page": 1, "path": pic})),
("image_edit", json!({"doc": 1, "page": 1, "image": 1, "action": "replace", "path": pic})),
("comment_add", json!({"doc": 1, "page": 1, "type": "attachment", "at": [10, 10], "path": secret})),
@@ -351,6 +352,19 @@ fn links_out_of_a_root_are_refused() {
assert_eq!(names(&base.join("outside")), ["pic.png", "secret.pdf"]);
}
+/// #4003: without `--root`, another network share or a device is refused by name through the
+/// tools too, with the same words as any other path outside a root.
+#[cfg(windows)]
+#[test]
+fn other_shares_and_devices_are_refused_by_name() {
+ let (mut server, base) = confined("shares", true, true);
+ ok(&mut server, "doc_open", json!({"path": s(&base.join("in/a.pdf"))}));
+ for p in [r"\\.\pipe\pdfcraft-4003.pdf", r"\\pdfcraft-no-such-host.invalid\share\a.pdf", "//pdfcraft-no-such-host.invalid/share/a.pdf"] {
+ refused(&mut server, "doc_open", json!({"path": p}), "outside the read root");
+ refused(&mut server, "doc_save", json!({"doc": 1, "path": p}), "outside the write root");
+ }
+}
+
#[test]
fn without_roots_nothing_is_confined() {
let base = folders("none");
diff --git a/crates/automation/tests/it/hostile_args.rs b/crates/automation/tests/it/hostile_args.rs
index d393e37..c017ff7 100644
--- a/crates/automation/tests/it/hostile_args.rs
+++ b/crates/automation/tests/it/hostile_args.rs
@@ -190,6 +190,54 @@ fn guarded(a: &mut Automation, tool: &str, args: &Value) -> std::result::Result<
}
}
+/// A new one-page blank document, by id.
+fn blank_doc(a: &mut Automation) -> u64 {
+ let created = a.call("doc_create", &json!({ "from": "blank", "pages": 1 })).expect("create a blank document");
+ created
+ .into_iter()
+ .find_map(|c| match c {
+ pdfcraft_automation::Content::Json(v) => v["doc"].as_u64(),
+ pdfcraft_automation::Content::Png { .. } => None,
+ })
+ .expect("the new document has an id")
+}
+
+/// Delete everything inside `dir`, so one tool never sees files an earlier tool wrote: a digital ID
+/// that `sign_id_create` wrote to the `in.pdf` placeholder would stop every later `sign_document`
+/// call at its decrypt, before the argument under test.
+///
+/// The entries are reached through the canonical path, as the tools reach them: on Windows that
+/// is a `\\?\` path, whose names are taken literally. Through the plain path a file the tools
+/// named `" "` would lose its trailing space and name `dir` itself, which would then be deleted.
+fn empty_dir(dir: &Path) {
+ let dir = dir.canonicalize().expect("the root exists");
+ for entry in std::fs::read_dir(&dir).expect("read the root") {
+ let entry = entry.unwrap_or_else(|e| panic!("list {}: {e}", dir.display()));
+ let path = entry.path();
+ let is_dir = entry.file_type().unwrap_or_else(|e| panic!("file type of {}: {e}", path.display())).is_dir();
+ let removed = if is_dir { std::fs::remove_dir_all(&path) } else { std::fs::remove_file(&path) };
+ removed.unwrap_or_else(|e| panic!("remove {} before the next tool: {e}", path.display()));
+ }
+}
+
+/// Real values for the arguments a tool checks before the others, so a hostile value reaches the
+/// argument it is meant for instead of failing on a placeholder. `sign_document` checks its
+/// digital ID first and its document second: this ID opens with its password, and each call gets
+/// a fresh document (which the caller closes), since a successful call signs it. The ID is a test
+/// key with a low key derivation count, so the hundreds of calls that open it stay fast.
+fn fixture(a: &mut Automation, root: &Path, tool: &str) -> serde_json::Map<String, Value> {
+ match tool {
+ "sign_document" => {
+ let id = Path::new(env!("CARGO_MANIFEST_DIR")).join("../sign/tests/data/ec-p256.p12");
+ std::fs::copy(&id, root.join("id.p12")).expect("copy the test digital ID");
+ let doc = blank_doc(a);
+ let args = json!({ "doc": doc, "id": "id.p12", "password": "test", "out": "signed.pdf" });
+ args.as_object().cloned().unwrap_or_default()
+ }
+ _ => serde_json::Map::new(),
+ }
+}
+
#[test]
fn no_tool_panics_on_hostile_arguments() {
let root = tmp("args");
@@ -199,6 +247,7 @@ fn no_tool_panics_on_hostile_arguments() {
let mut calls = 0usize;
for def in tools() {
+ empty_dir(&root);
// The whole arguments object, not just its properties.
for bad in [json!(null), json!([]), json!("string"), json!(7), json!(true), json!({})] {
calls += 1;
@@ -210,13 +259,24 @@ fn no_tool_panics_on_hostile_arguments() {
for prop in &props {
for value in &values {
let mut obj = plausible(&def);
+ let fixed = fixture(&mut a, &root, def.name);
+ let fixture_doc = fixed.get("doc").cloned();
+ obj.extend(fixed);
obj.insert(prop.clone(), value.clone());
calls += 1;
if let Err(e) = guarded(&mut a, def.name, &Value::Object(obj)) {
failures.push(e);
}
+ // Later tools pass placeholder document ids, which must not find this one open.
+ if let Some(doc) = fixture_doc {
+ a.call("doc_close", &json!({ "doc": doc, "discard_changes": true })).expect("close the fixture's document");
+ }
}
}
+ // A signed file shows the fixture got calls past the ID and document checks.
+ if def.name == "sign_document" {
+ assert!(root.join("signed.pdf").is_file(), "no sign_document call signed: the hostile values stop at the ID or document");
+ }
}
eprintln!("hostile arguments: {calls} calls over {} tools, {} panics", tools().len(), failures.len());
@@ -256,14 +316,7 @@ fn no_tool_escapes_the_root() {
let mut a = Automation::new().with_root(&root).expect("root");
// A real document, so tools reach their path arguments instead of failing on `doc` first.
- let created = a.call("doc_create", &json!({ "from": "blank", "pages": 1 })).expect("create a blank document");
- let doc = created
- .into_iter()
- .find_map(|c| match c {
- pdfcraft_automation::Content::Json(v) => v["doc"].as_u64(),
- pdfcraft_automation::Content::Png { .. } => None,
- })
- .expect("the new document has an id");
+ let doc = blank_doc(&mut a);
let mut leaked = Vec::new();
let mut tried = 0usize;
diff --git a/crates/automation/tests/it/main.rs b/crates/automation/tests/it/main.rs
index 8bb3c77..d94aa9f 100644
--- a/crates/automation/tests/it/main.rs
+++ b/crates/automation/tests/it/main.rs
@@ -1,5 +1,6 @@
//! The crate's integration tests, linked into one test binary.
+mod attachment_key;
mod automation;
mod automation_roots;
mod batch;
diff --git a/crates/content/src/lib.rs b/crates/content/src/lib.rs
index bb478d1..c52916d 100644
--- a/crates/content/src/lib.rs
+++ b/crates/content/src/lib.rs
@@ -52,6 +52,12 @@ impl Op {
pub fn name(&self, i: usize) -> Option<&[u8]> {
self.operands.get(i).and_then(Object::as_name)
}
+
+ /// The last operand as a name: the one `Do` and the other one-operand operators act on, since
+ /// the renderer takes operands from the end and ignores any surplus before them.
+ pub fn last_name(&self) -> Option<&[u8]> {
+ self.operands.last().and_then(Object::as_name)
+ }
}
/// A parsed stream.
diff --git a/crates/cos/src/document.rs b/crates/cos/src/document.rs
index 550534a..1319577 100644
--- a/crates/cos/src/document.rs
+++ b/crates/cos/src/document.rs
@@ -938,6 +938,11 @@ impl Document {
&self.version
}
+ /// Set the PDF header version (`"1.4"`, `"1.7"`, `"2.0"`, …) written by a full save.
+ pub fn set_version(&mut self, version: impl Into<String>) {
+ self.version = version.into();
+ }
+
pub fn trailer(&self) -> &Dict {
&self.trailer
}
@@ -1384,6 +1389,17 @@ impl Document {
self.overlay.insert(r.num, Slot::Freed(r.generation.saturating_add(1)));
}
+ /// Free what was added since the file was read and nothing refers to any more: the objects
+ /// [`SaveOptions::drop_unlinked`](crate::SaveOptions::drop_unlinked) leaves out of an
+ /// incremental save, freed as it writes them (the generation stays). For a writer about to
+ /// add an object that nothing refers to either, which that option would leave out too.
+ pub fn free_unlinked_additions(&mut self) {
+ for num in crate::writer::unlinked_additions(self) {
+ let generation = self.generation(num);
+ self.overlay.insert(num, Slot::Freed(generation));
+ }
+ }
+
/// Record `current`'s object graph as unsaved edits of this document.
///
/// Used when the working snapshot was restored from an earlier revision and the next
diff --git a/crates/cos/src/security.rs b/crates/cos/src/security.rs
index 12d08b8..22c85c7 100644
--- a/crates/cos/src/security.rs
+++ b/crates/cos/src/security.rs
@@ -178,7 +178,10 @@ fn walk(o: &Object, strings: &dyn Fn(&PdfString) -> PdfString, h: &SecurityHandl
Object::Stream(s) => {
let mut dict: Dict = s.dict.iter().map(|(k, v)| (k.clone(), walk(v, strings, h, num, generation, pass))).collect();
let ty = s.dict.name(b"Type");
- if ty == Some(b"XRef") || (ty == Some(b"Metadata") && !h.encrypts_metadata()) {
+ // Cross-reference streams are never encrypted (§7.5.8), but only reading may trust the
+ // label: a stream a producer calls /XRef stays plaintext if writing believes it, and the
+ // writer builds its own cross-reference streams outside this transform.
+ if (decrypt && ty == Some(b"XRef")) || (ty == Some(b"Metadata") && !h.encrypts_metadata()) {
return Object::Stream(Stream { dict, raw: s.raw.clone() });
}
let mut named = named_crypt_filter(&s.dict);
diff --git a/crates/cos/src/writer.rs b/crates/cos/src/writer.rs
index b151399..627f716 100644
--- a/crates/cos/src/writer.rs
+++ b/crates/cos/src/writer.rs
@@ -2,17 +2,20 @@
//!
//! * `write_incremental` appends the edited objects, a cross-reference section in the same style
//! as the file's last one (table or stream) and a trailer with `/Prev`. The original bytes are
-//! never modified, which keeps digital signatures over earlier revisions valid.
+//! never modified, which keeps digital signatures over earlier revisions valid. With
+//! `SaveOptions::drop_unlinked`, objects added since the file was read that nothing refers to
+//! any more are left out (written as free).
//! * `write_full` writes only objects reachable from the trailer, renumbered densely, with a
//! cross-reference table or stream — the "Save As" / garbage-collecting path. Unknown trailer
//! entries are copied, including objects reachable only from them.
use std::borrow::Cow;
-use std::collections::{BTreeMap, HashMap, VecDeque};
+use std::collections::{BTreeMap, HashMap, HashSet, VecDeque};
use std::io::Write;
+use std::sync::Arc;
use crate::CosError;
-use crate::document::{Document, ObjectReader};
+use crate::document::{Document, ObjectReader, XrefEntry};
use crate::object::{Dict, ObjRef, Object, PdfString, Stream};
/// Serialize one object. Deterministic: same object → same bytes.
@@ -156,11 +159,18 @@ pub struct SaveOptions {
/// Full saves: pack non-stream objects into compressed object streams with a cross-reference
/// stream (PDF 1.5+, §7.5.7–7.5.8). Off writes a classic table that any reader accepts.
pub object_streams: bool,
+ /// Incremental saves: leave out what was added since the file was read and nothing refers to
+ /// any more, such as a comment added and deleted again or a redaction mark added and cleared
+ /// (written as free). Off by default, because a writer may add an object only it finds again
+ /// by scanning, as a standalone document timestamp is; such a writer frees the leftovers
+ /// before adding it, with [`Document::free_unlinked_additions`]. Full saves always leave
+ /// these out.
+ pub drop_unlinked: bool,
}
impl Default for SaveOptions {
fn default() -> Self {
- Self { mod_date: None, id_seed: 0x5052_494E_5443_5241, object_streams: true }
+ Self { mod_date: None, id_seed: 0x5052_494E_5443_5241, object_streams: true, drop_unlinked: false }
}
}
@@ -209,8 +219,14 @@ pub fn write_incremental(doc: &Document, opts: &SaveOptions) -> Result<Vec<u8>,
let base = (original.len() + usize::from(newline)).saturating_sub(shift) as u64;
let mut out = Vec::new();
let mut offsets: BTreeMap<u32, (u64, u16, bool)> = BTreeMap::new(); // num → (offset, gen, in use)
+ let unlinked = if opts.drop_unlinked { unlinked_additions(&doc) } else { HashSet::new() };
for (num, generation, obj) in doc.overlay_entries() {
match obj {
+ // Written as free, so `/Size` still covers every number this document handed out. The
+ // generation stays: the number was never in use, and an undo can bring it back as is.
+ Some(_) if unlinked.contains(&num) => {
+ offsets.insert(num, (0, generation, false));
+ }
Some(o) => {
offsets.insert(num, (base + out.len() as u64, generation, true));
write_indirect(num, generation, &prepared(&doc, num, num, generation, &o), &mut out);
@@ -387,7 +403,7 @@ pub fn write_full(doc: &Document, opts: &SaveOptions) -> Result<Vec<u8>, CosErro
/// Object `r` read again for writing. The traversal read it once and only kept its number, so
/// a second read that fails, finds nothing or finds a different kind of object must fail the
/// save rather than write `null` in its place.
-fn reread(reader: &mut ObjectReader, r: ObjRef, is_stream: bool) -> Result<std::sync::Arc<Object>, CosError> {
+fn reread(reader: &mut ObjectReader, r: ObjRef, is_stream: bool) -> Result<Arc<Object>, CosError> {
let o = reader.try_get(r)?;
if matches!(*o, Object::Null) || matches!(*o, Object::Stream(_)) != is_stream {
return Err(CosError::Syntax { offset: 0, detail: format!("object {} read differently while saving; nothing was written", r.num) });
@@ -439,6 +455,37 @@ fn output_number(index: usize) -> Result<u32, CosError> {
u32::try_from(index).ok().and_then(|n| n.checked_add(1)).ok_or_else(|| CosError::Syntax { offset: 0, detail: "too many objects to save".into() })
}
+/// Objects added since the file was read (their numbers are not in use in it) that nothing an
+/// incremental update writes refers to: what one edit added and a later one unlinked, such as a
+/// deleted comment or a cleared redaction mark. The file never held them, so leaving them out
+/// loses nothing, while writing them would keep what the user removed. Only the update is walked:
+/// from the trailer and the file's changed objects through additions. An unchanged object of the
+/// file is not followed: a reference it holds to such a number already reads as null in the file
+/// (a damaged file's dangling reference), and it still does.
+pub(crate) fn unlinked_additions(doc: &Document) -> HashSet<u32> {
+ let added = |num: u32| matches!(doc.xref_entry(num), None | Some(XrefEntry::Free { .. }));
+ let mut pending: HashMap<u32, Arc<Object>> =
+ doc.overlay_entries().filter_map(|(num, _, o)| Some((num, o?))).filter(|(num, _)| added(*num)).collect();
+ if pending.is_empty() {
+ return HashSet::new();
+ }
+ let mut stack: Vec<ObjRef> = Vec::new();
+ doc.trailer().iter().for_each(|(_, v)| collect_refs(v, &mut |r| stack.push(r)));
+ for (num, _, o) in doc.overlay_entries() {
+ if let Some(o) = o
+ && !added(num)
+ {
+ collect_refs(&o, &mut |r| stack.push(r));
+ }
+ }
+ while let Some(r) = stack.pop() {
+ if let Some(o) = pending.remove(&r.num) {
+ collect_refs(&o, &mut |r| stack.push(r));
+ }
+ }
+ pending.into_keys().collect()
+}
+
fn collect_refs(o: &Object, f: &mut impl FnMut(ObjRef)) {
match o {
Object::Ref(r) => f(*r),
diff --git a/crates/cos/tests/it/encryption.rs b/crates/cos/tests/it/encryption.rs
index 2c6aad2..2ee33af 100644
--- a/crates/cos/tests/it/encryption.rs
+++ b/crates/cos/tests/it/encryption.rs
@@ -477,3 +477,20 @@ fn removing_an_inline_encrypt_dictionary_leaves_an_unencrypted_file() {
assert!(hayro_syntax::Pdf::new(plain).is_ok(), "{alg:?}");
}
}
+
+/// A content stream that calls itself `/Type /XRef` is still encrypted: only reading trusts the label.
+#[test]
+fn a_stream_labelled_xref_is_encrypted_when_saved() {
+ let mut doc = Document::open(Arc::new(fixture_with(" /Type /XRef"))).unwrap();
+ doc.set_encryption(&NewEncryption {
+ algorithm: Algorithm::Aes256,
+ user_password: "u",
+ owner_password: "o",
+ permissions: -4,
+ encrypt_metadata: true,
+ seed: [9; 32],
+ })
+ .unwrap();
+ let bytes = write_full(&doc, &SaveOptions { object_streams: false, ..SaveOptions::default() }).unwrap();
+ assert!(!bytes.windows(SECRET.len()).any(|w| w == SECRET.as_bytes()), "the labelled stream was written in the clear");
+}
diff --git a/crates/cos/tests/it/writer.rs b/crates/cos/tests/it/writer.rs
index 0818402..194de97 100644
--- a/crates/cos/tests/it/writer.rs
+++ b/crates/cos/tests/it/writer.rs
@@ -228,6 +228,63 @@ fn incremental_save_keeps_a_trailer_only_edit() {
assert_qpdf_clean(&saved);
}
+/// What one edit added and a later one unlinked (a deleted comment, a cleared redaction mark) is
+/// not written: the file never held it, and writing it would keep what was removed. Additions the
+/// update still refers to, from the trailer or a changed object and through other additions, are.
+#[test]
+fn incremental_save_leaves_out_additions_nothing_refers_to() {
+ let mut doc = Document::open(Arc::new(classic_table())).unwrap();
+ let text = |s: &str| Object::String(pdfcraft_cos::PdfString::literal(s.as_bytes().to_vec()));
+ let dict = |entries: &[(&str, Object)]| {
+ let mut d = Dict::new();
+ entries.iter().for_each(|(k, v)| d.set(k.as_bytes().to_vec(), v.clone()));
+ Object::Dict(d)
+ };
+ let page_obj = ObjRef::new(3, 0);
+ let leaf = doc.add(text("kept leaf"));
+ let kept = doc.add(dict(&[("Leaf", Object::Ref(leaf))]));
+ doc.update_dict(page_obj, |d| d.set(b"PieceInfo".to_vec(), Object::Ref(kept))).unwrap();
+ let by_trailer = doc.add(text("kept by the trailer"));
+ doc.trailer_mut().set(b"Custom".to_vec(), Object::Ref(by_trailer));
+ // Linked from the page and unlinked again, as clearing a mark does.
+ let dropped_leaf = doc.add(text("dropped leaf"));
+ let dropped = doc.add(dict(&[("Leaf", Object::Ref(dropped_leaf))]));
+ doc.update_dict(page_obj, |d| d.set(b"Annots".to_vec(), Object::Array(vec![Object::Ref(dropped)]))).unwrap();
+ doc.update_dict(page_obj, |d| {
+ d.remove(b"Annots");
+ })
+ .unwrap();
+ // Unlinked additions that refer to each other.
+ let first = doc.add(Object::Null);
+ let second = doc.add(dict(&[("Next", Object::Ref(first)), ("Note", text("dropped cycle"))]));
+ doc.set(first, dict(&[("Next", Object::Ref(second))]));
+
+ // Off by default: a writer may add what only it finds again, by scanning.
+ let kept_all = write_incremental(&doc, &SaveOptions::default()).unwrap();
+ assert!(kept_all.windows(12).any(|w| w == b"dropped leaf"));
+ let saved = write_incremental(&doc, &SaveOptions { drop_unlinked: true, ..SaveOptions::default() }).unwrap();
+ let holds = |s: &str| saved.windows(s.len()).any(|w| w == s.as_bytes());
+ assert!(holds("kept leaf") && holds("kept by the trailer"));
+ assert!(!holds("dropped leaf") && !holds("dropped cycle"), "unlinked additions are written");
+ let back = Document::open(Arc::new(saved.clone())).unwrap();
+ assert!(back.repair_log().is_empty(), "{:?}", back.repair_log());
+ assert_eq!(back.get(leaf).as_string().map(|s| s.bytes.as_slice()), Some(b"kept leaf".as_slice()));
+ for gone in [dropped, dropped_leaf, first, second] {
+ assert_eq!(*back.get(gone), Object::Null);
+ }
+ assert!(!page(&back).contains(b"Annots"));
+ assert_qpdf_clean(&saved);
+
+ // Freed beforehand, they are written the same way without the option, and what is added
+ // after that, nothing referring to it either (a document timestamp), is kept.
+ let mut freed = doc.clone();
+ freed.free_unlinked_additions();
+ assert_eq!(write_incremental(&freed, &SaveOptions::default()).unwrap(), saved, "the same objects, freed the same way");
+ freed.add(text("added after"));
+ let stamped = write_incremental(&freed, &SaveOptions::default()).unwrap();
+ assert!(stamped.windows(11).any(|w| w == b"added after") && !stamped.windows(12).any(|w| w == b"dropped leaf"));
+}
+
#[test]
fn qpdf_accepts_object_stream_output() {
let qpdf = pdfcraft_oracle::or_skip!(pdfcraft_oracle::qpdf());
diff --git a/crates/create/README.md b/crates/create/README.md
index 888a6a2..1ccc328 100644
--- a/crates/create/README.md
+++ b/crates/create/README.md
@@ -57,5 +57,7 @@ Every function returns a `pdfcraft_cos::Document`; the caller writes it.
Image export and Save Image As apply each lossless image's Decode pair before converting its color components.
Indexed Decode values select palette entries after rounding and clipping. Color-key masks compare the original samples.
Missing, null or malformed Decode arrays keep the default mapping.
-The existing 16-bit path still uses each sample's high byte. JPEG and mask Decode handling remain limited.
+Soft-mask Decode intervals map samples to opacity before the mask is resized, including reversed ranges and indirect entries.
+The existing 16-bit path still uses each sample's high byte.
+JPEG image Decode handling remains limited.
ICC transforms and calibrated color conversion remain outside this export path.
diff --git a/crates/create/src/extract.rs b/crates/create/src/extract.rs
index 115876d..7828952 100644
--- a/crates/create/src/extract.rs
+++ b/crates/create/src/extract.rs
@@ -465,7 +465,7 @@ fn stencil_mask(doc: &Document, s: &Stream, w: usize, h: usize) -> Option<Vec<u8
Some(gray_plane(doc, m, w, h)?.into_iter().map(|v| 255 - v).collect())
}
-/// A one-component mask image as 8-bit values (its `/Decode` inversion applied), scaled to
+/// A one-component mask image as 8-bit values (its `/Decode` interval applied), scaled to
/// `w` × `h`. `None` when it can't be decoded (JPEG 2000, JBIG2 and CCITT masks).
fn gray_plane(doc: &Document, m: &Stream, w: usize, h: usize) -> Option<Vec<u8>> {
let (mw, mh) = size(m.dict.int(b"Width")?, m.dict.int(b"Height")?)?;
@@ -491,14 +491,11 @@ fn gray_plane(doc: &Document, m: &Stream, w: usize, h: usize) -> Option<Vec<u8>>
unpack(&m.decoded().ok()?, mw, mh, 1, bpc)?.into_iter().map(|v| (v as u32 * 255 / max) as u8).collect()
}
};
- let invert = m
- .dict
- .get(b"Decode")
- .map(|d| doc.resolve(d))
- .and_then(|d| d.as_array().map(|a| a.first().and_then(Object::as_f64) > a.get(1).and_then(Object::as_f64)))
- .unwrap_or(false);
- if invert {
- px.iter_mut().for_each(|v| *v = 255 - *v);
+ if let Some([lo, hi]) = decode(doc, m, 1).and_then(|pairs| pairs.first().copied()) {
+ for value in &mut px {
+ let t = f64::from(*value) / 255.0;
+ *value = (((1.0 - t) * lo + t * hi).clamp(0.0, 1.0) * 255.0).round() as u8;
+ }
}
if (mw, mh) == (w, h) {
return Some(px);
diff --git a/crates/create/src/lib.rs b/crates/create/src/lib.rs
index a12550a..163c5bd 100644
--- a/crates/create/src/lib.rs
+++ b/crates/create/src/lib.rs
@@ -274,7 +274,7 @@ fn jpeg(name: &str, bytes: &[u8]) -> Result<Embedded, CreateError> {
0xEE if seg.starts_with(b"Adobe") => adobe = true,
// APP2 ICC profile, possibly split over several chunks.
0xE2 => {
- if let Some(([seq, count], data)) = seg.strip_prefix(b"ICC_PROFILE\0").and_then(|r| r.split_first_chunk::<2>()) {
+ if let Some(([seq, count], data)) = seg.strip_prefix(b"ICC_PROFILE\0").and_then(<[u8]>::split_first_chunk::<2>) {
icc_chunks.push((*seq, *count, data));
}
}
diff --git a/crates/create/src/tests.rs b/crates/create/src/tests.rs
index fb2b69b..fe47f8c 100644
--- a/crates/create/src/tests.rs
+++ b/crates/create/src/tests.rs
@@ -684,6 +684,74 @@ fn jpeg_images_with_a_soft_mask_export_as_png_with_alpha() {
assert_eq!((out.images[0].extension, &out.images[0].data), ("jpg", &real_jpeg()));
}
+#[test]
+/// Both image export paths apply mask intervals independently of the image's component Decode.
+fn soft_mask_decode_ranges_become_exported_alpha() {
+ for indirect in [false, true] {
+ for (range, expected) in [
+ ([0.25, 0.75], [64, 128, 191]),
+ ([0.75, 0.25], [191, 127, 64]),
+ ([1.0, 0.0], [255, 127, 0]),
+ ([-1.0, 2.0], [0, 129, 255]),
+ ([0.5, 0.5], [128, 128, 128]),
+ ] {
+ let mut doc = from_images(&[("flat.png".into(), png_bytes(false))]).unwrap();
+ with_image(&mut doc, |doc| {
+ let endpoints = range.into_iter().map(|v| {
+ let value = Object::Real(v);
+ if indirect { Object::Ref(doc.add(value)) } else { value }
+ });
+ let decode = Object::Array(endpoints.collect());
+ let decode = if indirect { Object::Ref(doc.add(decode)) } else { decode };
+ let mut mask = image_dict(3, 1, "DeviceGray", 8);
+ mask.set(b"Decode".to_vec(), decode);
+ let mask = doc.add(Object::Stream(Stream::from_raw(mask, vec![0, 128, 255])));
+ let mut image = image_dict(3, 1, "DeviceRGB", 8);
+ image.set(b"SMask".to_vec(), Object::Ref(mask));
+ image.set(b"Decode".to_vec(), decode_array(&[1.0, 0.0, 0.0, 1.0, 0.0, 1.0]));
+ Stream::from_raw(image, [0, 64, 255].repeat(3))
+ });
+ let doc = reopen(&doc);
+ let out = extract_images(&doc, &[0], 0);
+ assert!(out.skipped.is_empty(), "{:?}", out.skipped);
+ assert_eq!(out.images.len(), 1);
+ let pixels = exported_png_pixels(&out.images[0].data);
+ assert_eq!(alphas(&pixels), expected, "Decode {range:?}, indirect={indirect}");
+ assert!(pixels.as_chunks::<4>().0.iter().all(|p| p[..3] == [255, 64, 255]), "image component Decode stays independent");
+ let (ext, bytes) = image_file(&doc, out.images[0].object).unwrap();
+ assert_eq!(ext, "png");
+ assert_eq!(exported_png_pixels(&bytes), pixels, "Save Image As and Export all images agree");
+ }
+ }
+}
+
+#[test]
+/// Packed and JPEG samples map to opacity before resizing to their image's dimensions.
+fn soft_mask_decode_maps_packed_and_jpeg_masks_before_resizing() {
+ for jpeg in [false, true] {
+ let mut doc = from_images(&[("flat.png".into(), png_bytes(false))]).unwrap();
+ with_image(&mut doc, |doc| {
+ let mask = if jpeg {
+ let mut mask = image_dict(4, 2, "DeviceGray", 8);
+ mask.set(b"Filter".to_vec(), Object::name("DCTDecode"));
+ mask.set(b"Decode".to_vec(), decode_array(&[0.25, 0.25]));
+ Stream::from_raw(mask, real_jpeg())
+ } else {
+ let mut mask = image_dict(2, 1, "DeviceGray", 1);
+ mask.set(b"Decode".to_vec(), decode_array(&[-1.0, 2.0]));
+ Stream::from_raw(mask, vec![0b0100_0000])
+ };
+ let mask = doc.add(Object::Stream(mask));
+ let mut image = image_dict(4, 2, "DeviceRGB", 8);
+ image.set(b"SMask".to_vec(), Object::Ref(mask));
+ Stream::from_raw(image, vec![10; 24])
+ });
+ // Clipping before resizing differs from resizing first, then clipping to [0, 255].
+ let expected = if jpeg { vec![64; 8] } else { vec![0, 64, 191, 255, 0, 64, 191, 255] };
+ assert_eq!(alphas(&exported_rgba(&reopen(&doc)).1), expected, "jpeg={jpeg}");
+ }
+}
+
#[test]
fn soft_masks_of_another_size_and_stencil_and_colour_key_masks_become_alpha() {
// A 2×1 soft mask on a 4×2 image is scaled to the image's size.
diff --git a/crates/edit/src/added.rs b/crates/edit/src/added.rs
index 5d9dd3b..072179f 100644
--- a/crates/edit/src/added.rs
+++ b/crates/edit/src/added.rs
@@ -21,6 +21,9 @@ use crate::{EditError, MarkKind, check, contents, matrix_number, n, page_list, p
const TAG: &str = "Added";
+/// The most character spacing an added text takes either way, in points: as far as the font size goes.
+pub const CHAR_SPACING_LIMIT: f64 = 500.0;
+
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum Family {
#[default]
@@ -117,6 +120,8 @@ pub struct AddedText {
pub size: f64,
pub color: [f64; 3],
pub align: Align,
+ /// Extra space after every character, in points: the PDF's character spacing (`Tc`).
+ pub char_spacing: f64,
}
impl Default for AddedText {
@@ -130,6 +135,7 @@ impl Default for AddedText {
size: 12.0,
color: [0.0; 3],
align: Align::Left,
+ char_spacing: 0.0,
}
}
}
@@ -193,7 +199,9 @@ impl Content {
fn scaled(self, factor: f64) -> Content {
match self {
_ if factor == 1.0 => self,
- Content::Text(t) => Content::Text(AddedText { rect: t.rect.map(|v| v * factor), size: t.size * factor, ..t }),
+ Content::Text(t) => {
+ Content::Text(AddedText { rect: t.rect.map(|v| v * factor), size: t.size * factor, char_spacing: t.char_spacing * factor, ..t })
+ }
Content::Image(i) => Content::Image(AddedImage { rect: i.rect.map(|v| v * factor), ..i }),
}
}
@@ -231,6 +239,12 @@ fn norm(r: [f64; 4]) -> [f64; 4] {
[r[0].min(r[2]), r[1].min(r[3]), r[0].max(r[2]), r[1].max(r[3])]
}
+/// The advance of `s` in the item's standard font: its glyphs' widths and the character spacing
+/// after each of them, as `Tc` moves the pen (ISO 32000-2 §9.3.2).
+fn latin_width(t: &AddedText, s: &str) -> f64 {
+ t.family.width(s, t.size, t.bold, t.italic) + t.char_spacing * s.chars().count() as f64
+}
+
/// The lines of a text item after wrapping to its box width.
pub fn lines(t: &AddedText) -> Vec<String> {
wrapped(t).into_iter().map(|(line, _)| line).collect()
@@ -268,7 +282,7 @@ fn wrapped(t: &AddedText) -> Vec<(String, bool)> {
// sum of its words' and shaping stays linear in the paragraph's length. The space is the
// paragraph's; a space between Latin words is drawn in the item's font, a few hundredths
// of an em apart.
- let measure = |s: &str| if shaped { shaped_width(t, s, rtl) } else { t.family.width(s, t.size, t.bold, t.italic) };
+ let measure = |s: &str| if shaped { shaped_width(t, s, rtl) } else { latin_width(t, s) };
let space = measure(" ");
let (mut line, mut line_w) = (String::new(), 0.0);
for word in para.split(' ') {
@@ -295,10 +309,10 @@ fn thai_lines(t: &AddedText, para: &str, width: f64) -> Result<Vec<String>, Edit
let mut atoms = Vec::new();
for piece in pieces {
match piece {
- Piece::Shaped(clusters) => atoms.extend(clusters.into_iter().map(|c| (c.text, c.advance * t.size))),
+ Piece::Shaped(clusters) => atoms.extend(clusters.into_iter().map(|c| (c.text, c.advance * t.size + t.char_spacing))),
Piece::Latin(s) => atoms.extend(s.chars().map(|c| {
let text = c.to_string();
- let w = t.family.width(&text, t.size, t.bold, t.italic);
+ let w = latin_width(t, &text);
(text, w)
})),
}
@@ -489,8 +503,9 @@ fn shaped_layout(t: &AddedText, line: &str, rtl: bool) -> Result<(Vec<Piece>, f6
let width = pieces
.iter()
.map(|p| match p {
- Piece::Latin(s) => t.family.width(s, t.size, t.bold, t.italic),
- Piece::Shaped(clusters) => clusters.iter().map(|c| c.advance).sum::<f64>() * t.size,
+ Piece::Latin(s) => latin_width(t, s),
+ // Each cluster is shown on its own, so the spacing follows each once.
+ Piece::Shaped(clusters) => clusters.iter().map(|c| c.advance * t.size + t.char_spacing).sum::<f64>(),
})
.sum();
Ok((pieces, width))
@@ -499,7 +514,7 @@ fn shaped_layout(t: &AddedText, line: &str, rtl: bool) -> Result<(Vec<Piece>, f6
/// The width of `s` in a shaped-text item; the item's font's estimate if it can't be shaped (drawing
/// then reports why).
fn shaped_width(t: &AddedText, s: &str, rtl: bool) -> f64 {
- shaped_layout(t, s, rtl).map(|(_, w)| w).unwrap_or_else(|_| t.family.width(s, t.size, t.bold, t.italic))
+ shaped_layout(t, s, rtl).map(|(_, w)| w).unwrap_or_else(|_| latin_width(t, s))
}
fn arabic_error(e: GlyphError, text: &str) -> EditError {
@@ -546,6 +561,61 @@ pub fn text_rect(t: &AddedText) -> [f64; 4] {
[r[0], r[3] - h, r[2], r[3]]
}
+/// How far each paste onto a page already holding the copy is offset, down and to the right, so a
+/// copy doesn't hide what it was copied from (points).
+pub const PASTE_STEP: f64 = 18.0;
+
+/// Where a pasted item of box `rect` goes on a page of `size` (display space): with its top-left
+/// corner at `at`, else where it was, `steps` paste steps ([`PASTE_STEP`]) down and to the right.
+/// It is kept on the page; one larger than the page keeps its left and top edges on it. A page
+/// or point that isn't a number leaves the box where it was.
+pub fn paste_rect(rect: [f64; 4], size: [f64; 2], steps: u32, at: Option<[f64; 2]>) -> [f64; 4] {
+ let [x0, y0, x1, y1] = norm(rect);
+ let (w, h) = (x1 - x0, y1 - y0);
+ let (left, top) = match at {
+ Some([x, y]) => (x, y),
+ None => {
+ let d = PASTE_STEP * f64::from(steps);
+ (x0 + d, y1 - d)
+ }
+ };
+ if !size.iter().chain(&[left, top, w, h]).all(|v| v.is_finite()) {
+ return rect;
+ }
+ let left = left.min(size[0] - w).max(0.0);
+ let top = top.max(h).min(size[1]);
+ [left, top - h, left + w, top]
+}
+
+/// Most paste steps [`paste_place`] tries before giving up on finding a free place.
+const MAX_PASTE_STEPS: u32 = 64;
+
+/// Where Edit ▸ Paste puts `content` on a page of `size` already holding `items` (display space):
+/// where it was, or as many paste steps down and to the right as it takes not to land exactly on
+/// a copy of it (the original it was copied from, or an earlier paste).
+pub fn paste_place<'a>(items: impl IntoIterator<Item = &'a Content>, content: &Content, size: [f64; 2]) -> [f64; 4] {
+ let same = copy_key(content);
+ let copies: Vec<[f64; 4]> = items.into_iter().filter(|i| copy_key(i) == same).map(Content::rect).collect();
+ let taken = |rect: [f64; 4]| copies.iter().any(|c| c.iter().zip(rect).all(|(a, b)| (a - b).abs() < 0.5));
+ let mut rect = paste_rect(content.rect(), size, 0, None);
+ for steps in 1..=MAX_PASTE_STEPS {
+ if !taken(rect) {
+ break;
+ }
+ rect = paste_rect(content.rect(), size, steps, None);
+ }
+ rect
+}
+
+/// What makes two items copies of each other for [`paste_place`]: all but the box, and for an
+/// image all but the object holding its picture, which a paste into another document stores anew.
+fn copy_key(c: &Content) -> Content {
+ match c.with_rect([0.0; 4]) {
+ Content::Image(img) => Content::Image(AddedImage { image: ObjRef::new(0, 0), ..img }),
+ text => text,
+ }
+}
+
/// The widest explicit line before wrapping, measured with the PDF writing fonts.
pub fn text_width(t: &AddedText) -> f64 {
t.text.split('\n').map(|line| shaped_width(t, line, unicode_bidi::get_base_direction(line) == unicode_bidi::Direction::Rtl)).fold(0.0, f64::max)
@@ -634,6 +704,9 @@ fn draw_laid_shaped(
}
let [cr, cg, cb] = t.color.map(|v| v.clamp(0.0, 1.0));
out.extend(format!("BT {} {} {} rg\n", n(cr), n(cg), n(cb)).bytes());
+ if t.char_spacing != 0.0 {
+ out.extend(format!("{} Tc\n", n(t.char_spacing)).bytes());
+ }
for (i, (line, rtl, pieces, w)) in laid.iter().enumerate() {
// Shaped glyphs are painted in visual order. Keep the original line's typing order
// explicitly, including marks, ligatures, digits and mixed-script punctuation.
@@ -659,7 +732,7 @@ fn draw_laid_shaped(
out.extend(literal(&win_ansi(s)));
out.extend_from_slice(b" Tj\n");
current = Some(latin.as_str());
- pen += t.family.width(s, t.size, t.bold, t.italic) + tw * s.matches(' ').count() as f64;
+ pen += latin_width(t, s) + tw * s.matches(' ').count() as f64;
}
Piece::Shaped(clusters) => {
for c in clusters {
@@ -674,7 +747,7 @@ fn draw_laid_shaped(
out.extend(format!("1 0 0 1 {} {} Tm ", n(pen), n(y)).bytes());
out.extend(literal(&[code]));
out.extend_from_slice(b" Tj\n");
- pen += c.advance * t.size + if c.text == " " { tw } else { 0.0 };
+ pen += c.advance * t.size + t.char_spacing + if c.text == " " { tw } else { 0.0 };
}
}
}
@@ -830,9 +903,12 @@ fn draw(doc: &mut Document, c: &Content, view: [f64; 6], taken: &Dict, existing:
let r = text_rect(t);
let [cr, cg, cb] = t.color.map(|v| v.clamp(0.0, 1.0));
out.extend(format!("BT /{name} {} Tf {} {} {} rg\n", n(t.size), n(cr), n(cg), n(cb)).bytes());
+ if t.char_spacing != 0.0 {
+ out.extend(format!("{} Tc\n", n(t.char_spacing)).bytes());
+ }
let all = lines(t);
for (i, line) in all.iter().enumerate() {
- let w = t.family.width(line, t.size, t.bold, t.italic);
+ let w = latin_width(t, line);
let x = match t.align {
Align::Left | Align::Justify => r[0],
Align::Center => r[0] + ((r[2] - r[0]) - w) / 2.0,
@@ -903,6 +979,9 @@ fn params(c: &Content) -> Dict {
}),
);
d.set(b"Rect".to_vec(), arr(&text_rect(t)));
+ if t.char_spacing != 0.0 {
+ d.set(b"CharSpacing".to_vec(), Object::Real(t.char_spacing));
+ }
}
Content::Image(i) => {
d.set(b"Kind".to_vec(), Object::name("Image"));
@@ -946,6 +1025,8 @@ fn parse(doc: &Document, d: &Dict) -> Option<Content> {
Some(3) => Align::Justify,
_ => Align::Left,
},
+ // Items written before character spacing have none.
+ char_spacing: d.get(b"CharSpacing").and_then(Object::as_f64).filter(|v| v.is_finite()).unwrap_or(0.0),
}))
}
b"Image" => {
@@ -1046,6 +1127,11 @@ fn validate(c: &Content) -> Result<(), EditError> {
if !(t.size.is_finite() && (1.0..=500.0).contains(&t.size)) {
return Err(EditError::Invalid("the font size must be between 1 and 500 points".into()));
}
+ if !(t.char_spacing.is_finite() && (-CHAR_SPACING_LIMIT..=CHAR_SPACING_LIMIT).contains(&t.char_spacing)) {
+ return Err(EditError::Invalid(format!(
+ "the character spacing must be between -{CHAR_SPACING_LIMIT} and {CHAR_SPACING_LIMIT} points"
+ )));
+ }
if (r[2] - r[0]).abs() < 1.0 {
return Err(EditError::Invalid("the text box is too narrow".into()));
}
diff --git a/crates/edit/src/flatten.rs b/crates/edit/src/flatten.rs
index 8aa1b0e..6e08cde 100644
--- a/crates/edit/src/flatten.rs
+++ b/crates/edit/src/flatten.rs
@@ -37,6 +37,28 @@ fn appearance(doc: &Document, d: &Dict) -> Option<ObjRef> {
}
}
+/// Whether a widget's field has a value: its `/V`, or the nearest one inherited through `/Parent`
+/// (ISO 32000-2 §12.7.4.1). An empty string or array is no value. Past the depth limit the answer
+/// is yes: a value that wasn't checked must not be removed.
+fn has_value(doc: &Document, widget: &Dict) -> bool {
+ let mut d = widget.clone();
+ let mut seen = HashSet::new();
+ for _ in 0..64 {
+ if let Some(v) = d.get(b"V") {
+ return match &*doc.resolve(v) {
+ Object::Null => false,
+ Object::String(s) => !s.to_text().is_empty(),
+ Object::Array(a) => !a.is_empty(),
+ _ => true,
+ };
+ }
+ let Some(parent) = d.reference(b"Parent").filter(|p| seen.insert(*p)) else { return false };
+ let Some(next) = doc.get(parent).as_dict().cloned() else { return false };
+ d = next;
+ }
+ true
+}
+
/// Algorithm 8.1: the matrix that maps the form's bounding box onto the annotation rectangle.
fn placement(doc: &Document, form: &Dict, rect: [f64; 4]) -> Option<[f64; 6]> {
let bbox = nums(doc, form.get(b"BBox")).filter(|b| b.len() == 4)?;
@@ -220,13 +242,14 @@ fn flatten_in(doc: &mut Document, pages: &[usize], which: Which) -> Result<usize
// left on the page. A widget stays when it has no appearance to draw at all (none
// stored, or none for its selected state): removing it would lose the field's value
// with nothing in its place (#1794). One whose appearance draws nothing (an empty
- // stream) shows nothing anywhere, so flattening still removes it.
+ // stream) shows nothing anywhere, so flattening still removes it, and so does one whose
+ // field has no value: there is nothing to lose (#4017).
if !drew {
- let no_appearance = appearance(doc, d).is_none();
- if no_appearance && let Some(r) = entry.as_ref() {
+ let keep = appearance(doc, d).is_none() && (!widget || has_value(doc, d));
+ if keep && let Some(r) = entry.as_ref() {
undrawn.insert(r);
}
- if !widget || no_appearance {
+ if !widget || keep {
continue;
}
}
diff --git a/crates/edit/src/tests.rs b/crates/edit/src/tests.rs
index cf2344d..5afd017 100644
--- a/crates/edit/src/tests.rs
+++ b/crates/edit/src/tests.rs
@@ -611,6 +611,55 @@ fn flattening_keeps_a_valued_widget_it_cannot_draw() {
assert_eq!(value(6), Some(Object::name("Yes")));
}
+/// #4017: a widget with no appearance whose field has no value (none, or an empty string) has
+/// nothing to lose, so flattening removes it instead of leaving a fillable field behind. One whose
+/// value it inherits from its parent field still stays (#1794).
+#[test]
+fn flattening_removes_an_empty_widget_it_cannot_draw() {
+ let page = stream("", " ");
+ let mut doc = build(&[
+ "<< /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [5 0 R 6 0 R 7 0 R 8 0 R] >> >>",
+ "<< /Type /Pages /Kids [3 0 R] /Count 1 >>",
+ "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Resources << >> /Contents 4 0 R /Annots [5 0 R 6 0 R 7 0 R 9 0 R] >>",
+ &page,
+ "<< /Type /Annot /Subtype /Widget /FT /Tx /T (no_value) /Rect [10 10 150 40] /F 4 >>",
+ "<< /Type /Annot /Subtype /Widget /FT /Tx /T (empty) /V () /Rect [10 50 150 80] /F 4 >>",
+ "<< /Type /Annot /Subtype /Widget /FT /Tx /T (drawn) /Rect [10 90 150 120] /F 4 /AP << /N 10 0 R >> >>",
+ "<< /FT /Tx /T (parent) /V (Ada) /Kids [9 0 R] >>",
+ "<< /Type /Annot /Subtype /Widget /Parent 8 0 R /Rect [10 130 150 160] /F 4 >>",
+ "<< /Type /XObject /Subtype /Form /BBox [0 0 140 30] /Length 0 >>\nstream\n\nendstream",
+ ]);
+ assert_eq!(flatten(&mut doc, &[0], false, true).unwrap(), 1, "only the field with an appearance is drawn");
+ let doc = reopen(&doc);
+ let refs = |o: &Object| -> Vec<u32> { doc.resolve(o).as_array().unwrap().iter().filter_map(|f| f.as_ref()).map(|r| r.num).collect() };
+ let p = &pdfcraft_model::pages(&doc)[0];
+ assert_eq!(refs(p.dict.get(b"Annots").unwrap()), [9], "only the widget with an inherited value stays on the page");
+ let root = doc.root().unwrap();
+ let af = doc.resolve(doc.get(root).as_dict().unwrap().get(b"AcroForm").unwrap());
+ assert_eq!(refs(af.as_dict().unwrap().get(b"Fields").unwrap()), [8], "and its field in the form");
+}
+
+/// #4017: when the walk up the parent fields reaches its limit before finding a value, the widget
+/// stays: an unverified value must not be removed. Here `/V` sits on the 64th ancestor.
+#[test]
+fn flattening_keeps_a_widget_whose_value_is_past_the_parent_limit() {
+ let page = stream("", " ");
+ let mut objs: Vec<String> = vec![
+ "<< /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [69 0 R] >> >>".into(),
+ "<< /Type /Pages /Kids [3 0 R] /Count 1 >>".into(),
+ "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Resources << >> /Contents 4 0 R /Annots [5 0 R] >>".into(),
+ page,
+ "<< /Type /Annot /Subtype /Widget /Parent 6 0 R /Rect [10 10 150 40] /F 4 >>".into(),
+ ];
+ objs.extend((6..69).map(|n| format!("<< /Parent {} 0 R /Kids [{} 0 R] >>", n + 1, n - 1)));
+ objs.push("<< /FT /Tx /T (deep) /V (Ada) /Kids [68 0 R] >>".into());
+ let mut doc = build(&objs.iter().map(String::as_str).collect::<Vec<_>>());
+ flatten(&mut doc, &[0], false, true).unwrap();
+ let doc = reopen(&doc);
+ let annots = pdfcraft_model::pages(&doc)[0].dict.get(b"Annots").map(|a| doc.resolve(a).as_array().map_or(0, Vec::len));
+ assert_eq!(annots, Some(1), "the widget stays");
+}
+
/// #1794: a reply this builder cannot draw stays on the page even when the comment it replies to
/// is flattened; the comment's pop-up still goes with it.
#[test]
@@ -934,6 +983,52 @@ fn added_text_and_images_are_page_content_that_stays_editable() {
assert!(marks_present(&doc).is_empty());
}
+/// Edit ▸ Paste (#2636): where a pasted item lands.
+#[test]
+fn a_paste_lands_where_the_copy_was_offset_per_paste_and_stays_on_the_page() {
+ use crate::added::{PASTE_STEP, paste_rect};
+ let page = [300.0, 400.0];
+ let rect = [40.0, 300.0, 140.0, 320.0];
+ assert_eq!(paste_rect(rect, page, 0, None), rect, "in place");
+ let d = 2.0 * PASTE_STEP;
+ assert_eq!(paste_rect(rect, page, 2, None), [40.0 + d, 300.0 - d, 140.0 + d, 320.0 - d], "two steps down and right");
+ assert_eq!(paste_rect(rect, page, 1, Some([10.0, 50.0])), [10.0, 30.0, 110.0, 50.0], "its top-left corner at the point");
+ assert_eq!(paste_rect(rect, page, 0, Some([290.0, 5.0])), [200.0, 0.0, 300.0, 20.0], "pulled back onto the page");
+ assert_eq!(paste_rect([0.0, 0.0, 500.0, 600.0], page, 0, Some([10.0, 10.0])), [0.0, -200.0, 500.0, 400.0], "too large: left and top on the page");
+ assert_eq!(paste_rect([140.0, 320.0, 40.0, 300.0], page, 0, None), rect, "a reversed box is normalized");
+ assert_eq!(paste_rect(rect, [f64::NAN, 400.0], 1, None), rect, "a page without a size leaves the box alone");
+ assert_eq!(paste_rect(rect, page, 1, Some([f64::INFINITY, 5.0])), rect, "so does a point that isn't a number");
+ assert_eq!(paste_rect(rect, page, u32::MAX, None), [200.0, 0.0, 300.0, 20.0], "many pastes stop at the page's corner");
+}
+
+/// A paste steps on past exact copies of the item (its original, earlier pastes), and only those.
+#[test]
+fn a_paste_steps_past_copies_of_itself_only() {
+ use crate::added::{PASTE_STEP, paste_place};
+ let page = [300.0, 400.0];
+ let text = |rect, t: &str| Content::Text(AddedText { rect, text: t.into(), ..AddedText::default() });
+ let item = text([40.0, 300.0, 140.0, 314.4], "Note");
+ let step = |n: f64| [40.0 + n * PASTE_STEP, 300.0 - n * PASTE_STEP, 140.0 + n * PASTE_STEP, 314.4 - n * PASTE_STEP];
+ assert_eq!(paste_place([], &item, page), step(0.0), "an empty page: where it was");
+ assert_eq!(paste_place([&item], &item, page), step(1.0), "beside its original");
+ let first = item.with_rect(step(1.0));
+ assert_eq!(paste_place([&item, &first], &item, page), step(2.0), "beside the last copy");
+ assert_eq!(paste_place([&first], &item, page), step(0.0), "its place is free again (the original was cut)");
+ let other = text(step(0.0), "Other text");
+ assert_eq!(paste_place([&other], &item, page), step(0.0), "a different item in the way doesn't count");
+ // A page full of copies at its corner: the search ends.
+ let corner = item.with_rect([200.0, 0.0, 300.0, 14.4]);
+ let stuck = paste_place([&corner], &item.with_rect([200.0, 0.0, 300.0, 14.4]), page);
+ assert_eq!(stuck, [200.0, 0.0, 300.0, 14.4]);
+ // An image pasted into another document draws its picture from an object of that document:
+ // still a copy, so the next paste steps past it.
+ let image = Content::Image(AddedImage { crop: [0.1, 0.0, 0.0, 0.0], ..AddedImage::new(step(0.0), pdfcraft_cos::ObjRef::new(7, 0)) });
+ let pasted = Content::Image(AddedImage { crop: [0.1, 0.0, 0.0, 0.0], ..AddedImage::new(step(0.0), pdfcraft_cos::ObjRef::new(42, 0)) });
+ assert_eq!(paste_place([&pasted], &image, page), step(1.0), "a copy whose picture is stored anew");
+ let turned = Content::Image(AddedImage { rotation: 1, ..AddedImage::new(step(0.0), pdfcraft_cos::ObjRef::new(7, 0)) });
+ assert_eq!(paste_place([&turned], &image, page), step(0.0), "the same picture turned or cropped otherwise isn't a copy");
+}
+
#[test]
fn added_arabic_text_is_shaped_in_display_order_and_stays_searchable() {
let mut doc = fixture();
@@ -1632,6 +1727,214 @@ fn japanese_replacement_over_240_unique_glyphs_is_split_across_fallback_fonts()
assert_eq!(glyphs, 300);
}
+#[test]
+fn styled_paragraph_batches_cyrillic_without_changing_source_fonts() {
+ if without_craft_fonts("styled_paragraph_batches_cyrillic_without_changing_source_fonts") {
+ return;
+ }
+ let mut doc = text_page(
+ "BT /F1 12 Tf 14.4 TL 1 0 0 1 72 700 Tm (The quick brown fox jumps over the lazy dog) Tj T* (and keeps running through the long field.) Tj ET",
+ );
+ let replacement = "The quick brown fox jumps over the lazy dog шалом\nand keeps running through the long field.";
+ text::rewrite_block(&mut doc, 0, 0, Some(replacement), &text::BlockStyle { width: Some(520.0), ..Default::default() }).unwrap();
+ let doc = reopen(&doc);
+ assert_eq!(fallback_fonts(&doc).len(), 1, "the five letters must share one font");
+ let lines = text::text_lines(&doc, 0).unwrap();
+ assert!(lines.iter().any(|l| l.base_font == "Helvetica" && l.text.starts_with("The quick brown fox")), "{lines:?}");
+ let fallback: Vec<_> = lines.iter().filter(|l| l.font.starts_with("PCJp")).collect();
+ assert_eq!(fallback.len(), 1, "one word must be one text run: {fallback:?}");
+ assert_eq!(fallback[0].text, "шалом");
+ assert_eq!(lines.iter().map(|l| l.text.as_str()).collect::<String>().replace(' ', ""), replacement.replace([' ', '\n'], ""));
+}
+
+#[test]
+fn styled_paragraph_over_240_fallback_glyphs_splits_and_refuses_atomically() {
+ let replacement = format!("{}\nLatin", covered_japanese_chars(300));
+ let mut doc = text_page("BT /F1 12 Tf 14.4 TL 72 700 Td (Original) Tj T* (Latin) Tj ET");
+ let original = write_incremental(&doc, &SaveOptions::default()).unwrap();
+ if without_craft_fonts("styled_paragraph_over_240_fallback_glyphs_splits_and_refuses_atomically") {
+ assert!(text::replace_block(&mut doc, 0, 0, &replacement).is_err());
+ assert_eq!(write_incremental(&doc, &SaveOptions::default()).unwrap(), original);
+ return;
+ }
+ text::rewrite_block(&mut doc, 0, 0, Some(&replacement), &text::BlockStyle { width: Some(14000.0), ..Default::default() }).unwrap();
+ let reopened = reopen(&doc);
+ let fonts = fallback_fonts(&reopened);
+ assert_eq!(fonts.len(), 2, "300 glyphs need two fonts, not an error at glyph 241");
+ let counts: Vec<_> = fonts.iter().map(|(_, f)| reopened.dict(f.get(b"CharProcs").unwrap()).unwrap().len()).collect();
+ assert_eq!(counts.iter().sum::<usize>(), 300);
+ assert!(counts.iter().all(|n| *n <= 240));
+ assert_eq!(text::text_lines(&reopened, 0).unwrap().iter().map(|l| l.text.as_str()).collect::<String>(), replacement.replace('\n', ""));
+ let before = write_incremental(&doc, &SaveOptions::default()).unwrap();
+ let snapshot = doc.clone();
+ let err = text::replace_block(&mut doc, 0, 0, &format!("{replacement}\u{10ffff}")).unwrap_err();
+ assert!(err.to_string().contains("U+10FFFF"), "{err}");
+ assert_eq!(write_incremental(&doc, &SaveOptions::default()).unwrap(), before);
+ assert_eq!(write_incremental(&snapshot, &SaveOptions::default()).unwrap(), before);
+}
+
+#[test]
+fn styled_fallback_batches_keep_face_choices_and_range_styles() {
+ if without_craft_fonts("styled_fallback_batches_keep_face_choices_and_range_styles") {
+ return;
+ }
+ if !pdfcraft_fonts::CRAFT_FONTS.iter().any(|f| f.family == "BIZ UDPGothic" && f.style == "Bold") {
+ eprintln!("skipping: no bold Gothic face");
+ return;
+ }
+ let mut doc = text_page("BT /F1 12 Tf 72 700 Td (Original) Tj ET");
+ let range = |range, family, bold| text::RangeStyle {
+ range,
+ family: Some((family, bold, false)),
+ resource: None,
+ size: None,
+ color: None,
+ underline: None,
+ char_spacing: None,
+ scale: None,
+ };
+ let style = text::BlockStyle {
+ width: Some(520.0),
+ ranges: vec![
+ range(3..6, added::Family::Times, false),
+ range(6..9, added::Family::Helvetica, true),
+ range(9..11, added::Family::Times, false),
+ ],
+ ..Default::default()
+ };
+ let original = write_incremental(&doc, &SaveOptions::default()).unwrap();
+ let err = text::rewrite_block(&mut doc, 0, 0, Some("見見見ш見ш\nLatin\u{10ffff}"), &style).unwrap_err();
+ assert!(err.to_string().contains("U+10FFFF"), "{err}");
+ assert_eq!(write_incremental(&doc, &SaveOptions::default()).unwrap(), original, "all faces must validate before writing fallback objects");
+ text::rewrite_block(&mut doc, 0, 0, Some("見見見ш見ш\nLatin"), &style).unwrap();
+ let doc = reopen(&doc);
+ let fonts = fallback_fonts(&doc);
+ let mut summary: Vec<_> = fonts
+ .iter()
+ .map(|(_, f)| {
+ let face = pdfcraft_fonts::pdf::Metrics::from_dict(&doc, f).base_font;
+ let count = doc.dict(f.get(b"CharProcs").unwrap()).unwrap().len();
+ (face, count)
+ })
+ .collect();
+ summary.sort();
+ assert_eq!(
+ summary,
+ [
+ ("BIZUDMincho-Regular".into(), 1),
+ ("BIZUDPGothic-Bold".into(), 1),
+ ("BIZUDPGothic-Regular".into(), 2),
+ ("ShipporiMincho-Regular".into(), 1)
+ ]
+ );
+ assert_eq!(text::text_lines(&doc, 0).unwrap().iter().map(|l| l.text.as_str()).collect::<String>(), "見見見ш見шLatin");
+}
+
+#[test]
+fn styled_fallback_budget_is_enforced_before_objects_are_written() {
+ let glyphs = covered_japanese_chars(65);
+ let mut doc = text_page("BT /F1 12 Tf 72 700 Td (Original) Tj ET");
+ let original = write_incremental(&doc, &SaveOptions::default()).unwrap();
+ let snapshot = doc.clone();
+ let style = text::BlockStyle { width: Some(14000.0), ..Default::default() };
+ let over_budget = format!("{glyphs}\nLatin");
+ let err = text::rewrite_block_with_limit(&mut doc, 0, 0, Some(&over_budget), &style, 1).unwrap_err().to_string();
+ assert_eq!(write_incremental(&doc, &SaveOptions::default()).unwrap(), original, "refusal must add no objects");
+ assert_eq!(write_incremental(&snapshot, &SaveOptions::default()).unwrap(), original);
+ if without_craft_fonts("styled_fallback_budget_is_enforced_before_objects_are_written") {
+ assert!(err.contains("CRAFT_FONTS_DIR"), "{err}");
+ return;
+ }
+ assert!(err.contains("more than 64 fallback glyphs"), "{err}");
+ // One glyph per font gives a small, real budget of 64 distinct glyphs. At the
+ // boundary a repeated glyph is free: this is not a limit on text length.
+ let at_budget: String = glyphs.chars().take(64).chain(glyphs.chars().take(1)).collect();
+ text::rewrite_block_with_limit(&mut doc, 0, 0, Some(&format!("{at_budget}\nLatin")), &style, 1).unwrap();
+ let doc = reopen(&doc);
+ assert_eq!(fallback_fonts(&doc).len(), 64);
+ assert_eq!(text::text_lines(&doc, 0).unwrap().iter().map(|l| l.text.as_str()).collect::<String>(), format!("{at_budget}Latin"));
+}
+
+#[test]
+fn styled_fallback_same_base_font_and_character_keep_both_weights() {
+ if without_craft_fonts("styled_fallback_same_base_font_and_character_keep_both_weights") {
+ return;
+ }
+ if !pdfcraft_fonts::CRAFT_FONTS.iter().any(|f| f.family == "BIZ UDPGothic" && f.style == "Bold") {
+ eprintln!("skipping: no bold Gothic face");
+ return;
+ }
+ let mut doc = text_page("BT /F1 12 Tf 72 700 Td (alpha ) Tj /F2 12 Tf (beta ) Tj ET");
+ let source = doc.get(pdfcraft_cos::ObjRef::new(5, 0)).as_dict().unwrap().clone();
+ for (object, weight) in [(5, 400), (6, 700)] {
+ let mut font = source.clone();
+ // The same BaseFont can have different descriptor weights. Changing a
+ // RangeStyle family would also rename BaseFont and miss this cache key.
+ font.set(b"BaseFont".to_vec(), Object::name("NeutralFace"));
+ let mut descriptor = Dict::new();
+ descriptor.set(b"FontName".to_vec(), Object::name("NeutralFace"));
+ descriptor.set(b"FontWeight".to_vec(), Object::Int(weight));
+ font.set(b"FontDescriptor".to_vec(), Object::Dict(descriptor));
+ doc.set(pdfcraft_cos::ObjRef::new(object, 0), Object::Dict(font));
+ }
+ let lines = text::text_lines(&doc, 0).unwrap();
+ assert_eq!(lines.len(), 2);
+ assert_eq!(lines[0].base_font, lines[1].base_font);
+ assert_eq!((lines[0].bold, lines[1].bold), (false, true));
+ // Unchanged words anchor each inserted copy of the same letter in its own source style.
+ let block = text::text_blocks(&doc, 0).unwrap().remove(0);
+ let mut inherited = Vec::new();
+ for (range, source) in block.edited_spans("alpha ш beta ш") {
+ for _ in "alpha ш beta ш".get(range).unwrap().chars().filter(|ch| *ch == 'ш') {
+ inherited.push(lines[source].bold);
+ }
+ }
+ assert_eq!(inherited, [false, true], "the fixture must exercise both weights of the same BaseFont");
+ text::replace_block(&mut doc, 0, 0, "alpha ш beta ш").unwrap();
+ let doc = reopen(&doc);
+ let fonts = fallback_fonts(&doc);
+ let mut names: Vec<_> = fonts.iter().map(|(_, f)| pdfcraft_fonts::pdf::Metrics::from_dict(&doc, f).base_font).collect();
+ names.sort();
+ assert_eq!(names, ["BIZUDPGothic-Bold", "BIZUDPGothic-Regular"]);
+ let outlines: Vec<_> = fonts
+ .iter()
+ .map(|(_, f)| {
+ let procs = doc.dict(f.get(b"CharProcs").unwrap()).unwrap();
+ assert_eq!(procs.len(), 1, "each weight needs just the shared letter");
+ stream_bytes(&doc, procs.iter().next().unwrap().1).unwrap()
+ })
+ .collect();
+ assert_ne!(outlines[0], outlines[1], "weight must change the outline, not only the descriptor");
+ let lines = text::text_lines(&doc, 0).unwrap();
+ assert_eq!(lines.iter().map(|l| l.text.as_str()).collect::<String>(), "alpha ш beta ш");
+}
+
+#[test]
+fn styled_fallback_shards_keep_text_advances_and_alignment() {
+ if without_craft_fonts("styled_fallback_shards_keep_text_advances_and_alignment") {
+ return;
+ }
+ let source = "BT /F1 12 Tf 0.5 Tc 5 Tw 80 Tz 14.4 TL 72 700 Td (Original row) Tj T* (Second row) Tj ET";
+ let style =
+ text::BlockStyle { width: Some(520.0), align: Some(added::Align::Center), char_spacing: Some(0.7), scale: Some(80.0), ..Default::default() };
+ let mut whole = text_page(source);
+ let mut split = text_page(source);
+ let replacement = "Latin шалом ш\nSecond row";
+ text::rewrite_block_with_limit(&mut whole, 0, 0, Some(replacement), &style, 240).unwrap();
+ text::rewrite_block_with_limit(&mut split, 0, 0, Some(replacement), &style, 2).unwrap();
+ let (whole, split) = (reopen(&whole), reopen(&split));
+ assert_eq!(fallback_fonts(&whole).len(), 1);
+ assert_eq!(fallback_fonts(&split).len(), 3);
+ let (one, many) = (text::text_lines(&whole, 0).unwrap(), text::text_lines(&split, 0).unwrap());
+ assert_eq!(one.len(), many.len(), "{one:?} vs {many:?}");
+ for (a, b) in one.iter().zip(&many) {
+ assert_eq!(a.text, b.text);
+ for (a, b) in a.rect.iter().zip(b.rect) {
+ assert!((a - b).abs() < 0.002, "sharding must preserve alignment and advances: {a} vs {b}");
+ }
+ }
+}
+
/// A replacement whose last glyph no face draws (in a later font) changes nothing: neither the
/// document nor a snapshot taken before the edit, which is what undo restores.
#[test]
@@ -2401,6 +2704,44 @@ fn missing_glyphs_substitute_helvetica_and_impossible_text_is_refused() {
assert!(text::replace_line(&mut doc, 0, 5, "x").is_err(), "no such line");
}
+/// #4280: two paragraphs in subsets without Ç or Ã, one regular and one bold. Each edit that adds
+/// an accent sets the paragraph in a standard font of its own weight. Editing the bold one must
+/// not turn the regular one, set in its stand-in earlier, bold too, and the editor's frame for the
+/// bold one must not reach the regular one.
+#[test]
+fn a_bold_stand_in_font_leaves_an_earlier_regular_one_alone() {
+ let widths = vec!["600"; 26].join(" ");
+ let font = |base: &str| {
+ format!("<< /Type /Font /Subtype /Type1 /BaseFont /{base} /FirstChar 65 /LastChar 90 /Widths [{widths}] /Encoding /WinAnsiEncoding >>")
+ };
+ let (regular, bold) = (font("ABCDEF+Garamond"), font("ABCDEF+Garamond-Bold"));
+ let content = stream("", "BT /F1 12 Tf 72 700 Td (ACAO) Tj ET BT /F2 12 Tf 300 400 Td (TENSAO) Tj ET");
+ let mut doc = build(&[
+ "<< /Type /Catalog /Pages 2 0 R >>",
+ "<< /Type /Pages /Kids [3 0 R] /Count 1 >>",
+ "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 600 800] /Contents 4 0 R /Resources << /Font << /F1 5 0 R /F2 6 0 R >> >> >>",
+ &content,
+ &regular,
+ &bold,
+ ]);
+ let block = |doc: &Document, text: &str| text::text_blocks(doc, 0).unwrap().iter().position(|b| b.text == text).unwrap();
+ let acao = block(&doc, "ACAO");
+ assert_eq!(text::replace_block(&mut doc, 0, acao, "AÇÃO").unwrap().substituted.as_deref(), Some("Times-Roman"));
+ let first = text::text_lines(&doc, 0).unwrap().into_iter().find(|l| l.text == "AÇÃO").unwrap();
+
+ let tensao = block(&doc, "TENSAO");
+ let layout = text::text_edit_layout(&doc, 0, tensao, "TENSÃO", &text::BlockStyle::default()).unwrap();
+ let draft = layout.draft_rect.unwrap();
+ assert!(draft[3] < first.rect[1] || draft[1] > first.rect[3], "the frame {draft:?} reaches the regular paragraph at {:?}", first.rect);
+ assert_eq!(text::replace_block(&mut doc, 0, tensao, "TENSÃO").unwrap().substituted.as_deref(), Some("Times-Bold"));
+
+ let doc = reopen(&doc);
+ let lines = text::text_lines(&doc, 0).unwrap();
+ let font_of = |text: &str| lines.iter().find(|l| l.text == text).map(|l| l.base_font.clone());
+ assert_eq!(font_of("AÇÃO").as_deref(), Some("Times-Roman"), "{lines:?}");
+ assert_eq!(font_of("TENSÃO").as_deref(), Some("Times-Bold"), "{lines:?}");
+}
+
#[test]
fn paragraphs_are_found_and_rewrapped() {
let mut doc = text_page(
@@ -6997,6 +7338,24 @@ fn reading_keeps_dotted_leader_entries_whole_and_in_order() {
);
}
+/// Text set larger than the widest page PDF allows (14 400 pt) panicked when its paragraph was given
+/// a width: the width is clamped between the font size and 14 400 pt, and `f64::clamp` panics when
+/// its minimum is the larger. The width is now capped at 14 400 pt whatever the font size: from the
+/// file (`Tf`, or a small `Tf` scaled up by `Tm`) or asked for (the automation tools pass it through).
+#[test]
+fn width_on_a_paragraph_set_larger_than_a_page_is_capped_not_a_panic() {
+ let wide = text::BlockStyle { width: Some(200.0), ..Default::default() };
+ let huge = text::BlockStyle { size: Some(20_000.0), width: Some(200.0), ..Default::default() };
+ for (content, style) in [
+ ("BT /F2 20000 Tf 72 700 Td (ab) Tj ET", &wide),
+ ("BT /F2 1 Tf 20000 0 0 20000 72 700 Tm (ab) Tj ET", &wide),
+ ("BT /F2 12 Tf 72 700 Td (ab) Tj ET", &huge),
+ ] {
+ let mut doc = text_page(content);
+ text::rewrite_block(&mut doc, 0, 0, None, style).unwrap();
+ }
+}
+
#[test]
fn added_text_is_wrapped_once_per_write() {
let mut doc = fixture();
@@ -7008,6 +7367,35 @@ fn added_text_is_wrapped_once_per_write() {
assert!(calls <= 4, "the text was wrapped {calls} times for 40 lines");
}
+/// Character spacing on added text (#4245) is the PDF's `Tc`, kept in `/PCAdded` so the item
+/// reopens with it; an item written without it reads 0.
+#[test]
+fn added_text_character_spacing_is_drawn_and_reopens() {
+ let mut doc = fixture();
+ let plain = AddedText { rect: [72.0, 600.0, 400.0, 700.0], text: "Approved".into(), size: 10.0, ..AddedText::default() };
+ add_content(&mut doc, 0, &Content::Text(plain.clone())).unwrap();
+ add_content(&mut doc, 0, &Content::Text(AddedText { char_spacing: 2.5, ..plain })).unwrap();
+ let doc = reopen(&doc);
+ let spacings: Vec<f64> = list_added(&doc).iter().map(|a| if let Content::Text(t) = &a.content { t.char_spacing } else { f64::NAN }).collect();
+ assert_eq!(spacings, [0.0, 2.5]);
+ let page = streams(&doc, 0);
+ let tc: Vec<bool> = page.iter().filter(|s| s.contains("(Approved) Tj")).map(|s| s.contains("2.5 Tc")).collect();
+ assert_eq!(tc, [false, true], "{page:?}");
+}
+
+/// Spacing widens every measure the layout takes: the widest line and wrapping.
+#[test]
+fn added_text_character_spacing_widens_its_layout() {
+ let plain = AddedText { rect: [0.0, 0.0, 1000.0, 100.0], text: "Approved".into(), size: 10.0, ..AddedText::default() };
+ let spaced = AddedText { char_spacing: 3.0, ..plain.clone() };
+ // After each of the 8 letters, like `Tc`.
+ assert!((added::text_width(&spaced) - added::text_width(&plain) - 24.0).abs() < 1e-9);
+ let w = added::text_width(&plain);
+ let narrow = |t: &AddedText| AddedText { text: "Approved Approved".into(), rect: [0.0, 0.0, 2.0 * w + 5.0, 100.0], ..t.clone() };
+ assert_eq!(added::lines(&narrow(&plain)).len(), 1);
+ assert_eq!(added::lines(&narrow(&spaced)).len(), 2, "the spaced words no longer fit one line");
+}
+
/// A field tree whose every node lists its child twice is pruned in work linear in its nodes, not
/// in its paths, and a node listing itself is visited once.
#[test]
@@ -7212,3 +7600,419 @@ fn a_flatten_refused_on_a_later_page_changes_nothing() {
assert!(matches!(flatten(&mut doc, &[0, 1], true, false), Err(EditError::Invalid(_))));
assert_eq!((*doc.get(first)).clone(), before, "the first page keeps its comment and content");
}
+
+/// How each glyph-showing operator on page 0 is painted, read the way a renderer reads the page:
+/// its text, `Tr`, stroke colour operators, line width (from `w` or an ExtGState's `/LW`) and
+/// the ExtGStates selected before it, following `q`/`Q`.
+#[derive(Clone, Debug, PartialEq)]
+struct Painted {
+ text: String,
+ render_mode: i64,
+ stroke: Vec<String>,
+ line_width: f64,
+ gs: Vec<String>,
+}
+
+fn painted_shows(doc: &Document) -> Vec<Painted> {
+ let (_, ops) = joined_ops(doc);
+ let p = &pdfcraft_model::pages(doc)[0];
+ let res = doc.resolve(p.dict.get(b"Resources").unwrap());
+ let ext = res.as_dict().unwrap().get(b"ExtGState").map(|g| doc.resolve(g).as_dict().cloned().unwrap()).unwrap_or_default();
+ let mut state = Painted { text: String::new(), render_mode: 0, stroke: Vec::new(), line_width: 1.0, gs: Vec::new() };
+ let mut stack = Vec::new();
+ let mut out = Vec::new();
+ let show = |op: &pdfcraft_content::Op| String::from_utf8_lossy(&pdfcraft_content::serialize_ops(std::slice::from_ref(op))).trim().to_string();
+ for op in ops {
+ match op.op.as_slice() {
+ b"q" => stack.push(state.clone()),
+ b"Q" => state = stack.pop().unwrap(),
+ b"Tr" => state.render_mode = op.operands[0].as_int().unwrap(),
+ b"G" | b"RG" | b"K" | b"CS" => state.stroke = vec![show(&op)],
+ b"SC" | b"SCN" => state.stroke.push(show(&op)),
+ b"w" => state.line_width = op.num(0).unwrap(),
+ b"gs" => {
+ let name = op.name(0).unwrap();
+ state.gs.push(String::from_utf8_lossy(name).into_owned());
+ let lw = ext.get(name).and_then(|g| doc.resolve(g).as_dict().and_then(|g| g.get(b"LW")).and_then(|w| w.as_f64()));
+ state.line_width = lw.unwrap_or(state.line_width);
+ }
+ b"Tj" => {
+ let Some(Object::String(s)) = op.operands.last() else { continue };
+ if !s.bytes.is_empty() {
+ out.push(Painted { text: String::from_utf8_lossy(&s.bytes).into_owned(), ..state.clone() });
+ }
+ }
+ _ => {}
+ }
+ }
+ out
+}
+
+/// A page with Helvetica as /F1, /GS1, an ExtGState that paints at 20 % opacity, /GS2, one that
+/// sets the line width to 4, /GS3, another at 20 % opacity, and /GS4, at 20 % opacity and dashed.
+fn faint_page(content: &str) -> Document {
+ build(&[
+ "<< /Type /Catalog /Pages 2 0 R >>",
+ "<< /Type /Pages /Kids [3 0 R] /Count 1 >>",
+ "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 600 800] /Contents 4 0 R /Resources << /Font << /F1 5 0 R >> /ExtGState << /GS1 6 0 R /GS2 7 0 R /GS3 8 0 R /GS4 9 0 R >> >> >>",
+ &format!("<< /Length {} >>\nstream\n{content}\nendstream", content.len()),
+ "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>",
+ "<< /Type /ExtGState /ca 0.2 >>",
+ "<< /Type /ExtGState /LW 4 >>",
+ "<< /Type /ExtGState /ca 0.2 >>",
+ "<< /Type /ExtGState /ca 0.2 /D [[6 3] 0] >>",
+ ])
+}
+
+/// Rewriting a paragraph drew it before its text object, restating only the font, spacing and
+/// fill: a `1 Tr 1 0 0 RG 2 w` set inside `BT` was lost, and red outline text came back filled
+/// black, even with the text unchanged (#3508). Set before `BT` (the control), it already worked.
+#[test]
+fn a_rewritten_paragraph_keeps_the_rendering_mode_stroke_and_width_set_inside_its_text_object() {
+ let outline = |text: &str| Painted { text: text.into(), render_mode: 1, stroke: vec!["1 0 0 RG".into()], line_width: 2.0, gs: Vec::new() };
+ for content in ["BT /F1 72 Tf 1 Tr 1 0 0 RG 2 w 40 400 Td (OUTLINE) Tj ET\n", "1 Tr 1 0 0 RG 2 w BT /F1 72 Tf 40 400 Td (OUTLINE) Tj ET\n"] {
+ assert_eq!(painted_shows(&text_page(content)), [outline("OUTLINE")], "the fixture: {content}");
+ for new in ["OUTLINE", "OUTLINED"] {
+ let mut doc = text_page(content);
+ text::rewrite_block(&mut doc, 0, 0, Some(new), &BlockStyle::default()).unwrap();
+ let doc = reopen(&doc);
+ assert_eq!(painted_shows(&doc), [outline(new)], "{content} -> {new}: {}", streams(&doc, 0).join("\n"));
+ }
+ }
+}
+
+/// The same for transparency: `/GS1 gs` (`/ca 0.2`) inside `BT` was not in force for the
+/// rewritten paragraph, so 20 % blue text came back opaque (#3509).
+#[test]
+fn a_rewritten_paragraph_keeps_the_extgstate_selected_inside_its_text_object() {
+ for content in ["BT /GS1 gs /F1 72 Tf 0 0 1 rg 40 400 Td (FAINT) Tj ET\n", "/GS1 gs BT /F1 72 Tf 0 0 1 rg 40 400 Td (FAINT) Tj ET\n"] {
+ for new in ["FAINT", "FAINTER"] {
+ let mut doc = faint_page(content);
+ text::rewrite_block(&mut doc, 0, 0, Some(new), &BlockStyle::default()).unwrap();
+ let doc = reopen(&doc);
+ let shows = painted_shows(&doc);
+ assert_eq!(shows.len(), 1, "{content} -> {new}: {shows:?}");
+ assert_eq!(
+ (shows[0].text.as_str(), shows[0].gs.as_slice()),
+ (new, ["GS1".to_string()].as_slice()),
+ "{content} -> {new}: {}",
+ streams(&doc, 0).join("\n")
+ );
+ }
+ }
+}
+
+/// A paragraph of differently coloured runs goes through the styled rewrite, which draws each
+/// run in its own text object: each keeps the state its source set inside `BT`.
+#[test]
+fn a_styled_rewrite_keeps_the_paint_state_set_inside_the_text_object() {
+ let content = "BT /GS1 gs 1 Tr 1 0 0 RG 2 w /F1 72 Tf 40 400 Td (FAI) Tj 0 0 1 rg (NT) Tj ET\n";
+ let mut doc = faint_page(content);
+ assert_eq!(text::text_blocks(&doc, 0).unwrap()[0].rows[0].len(), 2, "two runs on one row");
+ text::rewrite_block(&mut doc, 0, 0, Some("FAINTS"), &BlockStyle::default()).unwrap();
+ let doc = reopen(&doc);
+ let shows = painted_shows(&doc);
+ let joined = streams(&doc, 0).join("\n");
+ assert_eq!(shows.iter().map(|s| s.text.as_str()).collect::<String>(), "FAINTS", "{joined}");
+ for s in &shows {
+ assert_eq!((s.render_mode, s.stroke.as_slice(), s.line_width), (1, ["1 0 0 RG".to_string()].as_slice(), 2.0), "{s:?}: {joined}");
+ assert_eq!(s.gs, ["GS1"], "{s:?}: {joined}");
+ }
+}
+
+/// A `gs` has no inverse, so one run's ExtGState stayed in force for the runs the styled rewrite
+/// drew after it. Two ExtGStates at the same opacity paint the same (see `Paint`), so their runs
+/// share a paragraph, but either may set what that doesn't compare (a dash, a line cap): each run
+/// is drawn with only the ones its source selected.
+#[test]
+fn a_styled_rewrite_does_not_carry_one_runs_extgstate_into_the_next() {
+ // "FAI" ends at 40 + 72 * (0.611 + 0.667 + 0.278) = 152.032; "NT" is blue, so another run.
+ let content = "q BT /GS3 gs /F1 72 Tf 40 400 Td (FAI) Tj ET Q BT /GS1 gs /F1 72 Tf 0 0 1 rg 152.032 400 Td (NT) Tj ET
+";
+ for new in ["FAINT", "FAINTS"] {
+ let mut doc = faint_page(content);
+ assert_eq!(text::text_blocks(&doc, 0).unwrap()[0].rows[0].len(), 2, "two runs on one row");
+ text::rewrite_block(&mut doc, 0, 0, Some(new), &BlockStyle::default()).unwrap();
+ let doc = reopen(&doc);
+ let shows = painted_shows(&doc);
+ let joined = streams(&doc, 0).join(
+ "
+",
+ );
+ assert_eq!(shows.iter().map(|s| s.text.as_str()).collect::<String>(), new, "{joined}");
+ let gs: Vec<_> = shows.iter().map(|s| (s.text.as_str(), s.gs.as_slice())).collect();
+ assert_eq!(gs.first(), Some(&("FAI", ["GS3".to_string()].as_slice())), "{gs:?}: {joined}");
+ assert!(gs.iter().skip(1).all(|(_, gs)| *gs == ["GS1"]), "{gs:?}: {joined}");
+ }
+}
+
+/// An ExtGState's `/LW` sets the line width as `w` does: `2 w /GS2 gs` (`/LW 4`) outlines at 4,
+/// and the rewrite replayed `/GS2 gs` and then `2 w`. `/GS2 gs 1 w` outlines at 1, and the
+/// rewrite replayed only `/GS2 gs`, since 1 is the initial width.
+#[test]
+fn a_rewritten_paragraph_keeps_the_line_width_an_extgstate_set() {
+ for (content, width) in [
+ ("BT /F1 72 Tf 1 Tr 2 w /GS2 gs 40 400 Td (OUTLINE) Tj ET\n", 4.0),
+ ("BT /F1 72 Tf 1 Tr /GS2 gs 2 w 40 400 Td (OUTLINE) Tj ET\n", 2.0),
+ ("BT /F1 72 Tf 1 Tr /GS2 gs 1 w 40 400 Td (OUTLINE) Tj ET\n", 1.0),
+ ] {
+ assert_eq!(painted_shows(&faint_page(content))[0].line_width, width, "the fixture: {content}");
+ for new in ["OUTLINE", "OUTLINED"] {
+ let mut doc = faint_page(content);
+ text::rewrite_block(&mut doc, 0, 0, Some(new), &BlockStyle::default()).unwrap();
+ let doc = reopen(&doc);
+ let shows = painted_shows(&doc);
+ assert_eq!(
+ shows.iter().map(|s| (s.text.as_str(), s.render_mode, s.line_width)).collect::<Vec<_>>(),
+ [(new, 1, width)],
+ "{content} -> {new}: {}",
+ streams(&doc, 0).join("\n")
+ );
+ }
+ }
+}
+
+/// A line is rewritten in the state of its first run, so outline text partway through a text
+/// object came back filled: "FAI" filled and "NT" a red outline came back all filled. The change
+/// of `Tr` now starts a run. (A `gs` partway already starts a paragraph; see `Paint`.)
+#[test]
+fn a_rendering_mode_partway_through_a_line_starts_a_run_of_its_own() {
+ let content = "BT /F1 72 Tf 40 400 Td (FAI) Tj 1 Tr 1 0 0 RG 2 w (NT) Tj ET
+";
+ for new in ["FAINT", "FAINTS"] {
+ let mut doc = faint_page(content);
+ assert_eq!(text::text_blocks(&doc, 0).unwrap()[0].rows[0].len(), 2, "two runs on one row");
+ text::rewrite_block(&mut doc, 0, 0, Some(new), &BlockStyle::default()).unwrap();
+ let doc = reopen(&doc);
+ let shows = painted_shows(&doc);
+ let joined = streams(&doc, 0).join(
+ "
+",
+ );
+ assert_eq!(shows.iter().map(|s| s.text.as_str()).collect::<String>(), new, "{joined}");
+ let modes: Vec<_> = shows.iter().map(|s| (s.text.as_str(), s.render_mode, s.stroke.as_slice(), s.line_width)).collect();
+ assert_eq!(modes.first().map(|m| (m.0, m.1)), Some(("FAI", 0)), "{modes:?}: {joined}");
+ let outline = ["1 0 0 RG".to_string()];
+ assert!(modes.iter().skip(1).all(|m| (m.1, m.2, m.3) == (1, outline.as_slice(), 2.0)), "{modes:?}: {joined}");
+ }
+}
+
+/// Two ExtGStates at the same opacity paint text the same (see `Paint`), but one of them dashes
+/// its outline: a dashed outline after a solid one in the same text object joined its line and
+/// came back solid, drawn with the first run's selections. A different dash now starts a run.
+#[test]
+fn a_dash_partway_through_an_outlined_line_starts_a_run_of_its_own() {
+ let content = "BT /GS3 gs /F1 72 Tf 1 Tr 1 0 0 RG 2 w 40 400 Td (FAI) Tj /GS4 gs (NT) Tj ET
+";
+ for new in ["FAINT", "FAINTS"] {
+ let mut doc = faint_page(content);
+ assert_eq!(text::text_blocks(&doc, 0).unwrap()[0].rows[0].len(), 2, "two runs on one row");
+ text::rewrite_block(&mut doc, 0, 0, Some(new), &BlockStyle::default()).unwrap();
+ let doc = reopen(&doc);
+ let shows = painted_shows(&doc);
+ let joined = streams(&doc, 0).join(
+ "
+",
+ );
+ assert_eq!(shows.iter().map(|s| s.text.as_str()).collect::<String>(), new, "{joined}");
+ let gs: Vec<_> = shows.iter().map(|s| (s.text.as_str(), s.gs.as_slice())).collect();
+ assert_eq!(gs.first(), Some(&("FAI", ["GS3".to_string()].as_slice())), "{gs:?}: {joined}");
+ assert!(gs.iter().skip(1).all(|(_, gs)| gs.last().is_some_and(|g| g == "GS4")), "{gs:?}: {joined}");
+ }
+}
+
+/// The dash and cap are compared as the operators set them too: `d` or `J` partway through an
+/// outlined line starts a run, and a malformed one (too long, not numbers, out of range) is ignored.
+#[test]
+fn a_dash_or_cap_operator_partway_through_an_outlined_line_starts_a_run() {
+ let long = format!("[{}] 0 d", "1 ".repeat(40));
+ for (change, runs) in [("[6 3] 0 d", 2), ("1 J", 2), (long.as_str(), 1), ("[(a) 3] 0 d", 1), ("[6 3] /x d", 1), ("7 J", 1), ("J", 1)] {
+ let content = format!("BT /F1 72 Tf 1 Tr 1 0 0 RG 2 w 40 400 Td (FAI) Tj {change} (NT) Tj ET\n");
+ let mut doc = faint_page(&content);
+ assert_eq!(text::text_blocks(&doc, 0).unwrap()[0].rows[0].len(), runs, "{change}");
+ text::rewrite_block(&mut doc, 0, 0, Some("FAINTS"), &BlockStyle::default()).unwrap();
+ let shows = painted_shows(&reopen(&doc));
+ assert_eq!(shows.iter().map(|s| s.text.as_str()).collect::<String>(), "FAINTS", "{change}");
+ }
+}
+
+/// #4199, #3797: every space typed into a paragraph is saved, not folded into one.
+#[test]
+fn an_edited_paragraph_keeps_every_space_typed() {
+ for typed in ["Hello world", "Hello world end", " indented and trailing "] {
+ let mut doc = text_page("BT /F1 12 Tf 72 700 Td (Hello world) Tj ET");
+ assert_eq!(text::replace_block(&mut doc, 0, 0, typed).unwrap().substituted, None);
+ let doc = reopen(&doc);
+ let content = String::from_utf8_lossy(&page_content_bytes(&doc, 0)).into_owned();
+ assert!(content.contains(&format!("({typed}) Tj")), "{typed:?}: {content}");
+ assert_eq!(text::text_lines(&doc, 0).unwrap()[0].text, typed);
+ }
+}
+
+/// Spaces after a row's last word are kept but take no part in its alignment: a justified row
+/// still reaches the margin, and a centred or right-aligned one sits where it would without them.
+#[test]
+fn spaces_after_a_rows_last_word_do_not_move_its_alignment() {
+ let shown = |text: &str, align: added::Align| {
+ let mut doc = text_page("BT /F1 12 Tf 72 700 Td (Hello world) Tj ET");
+ let style =
+ text::BlockStyle { family: Some((added::Family::Helvetica, false, false)), align: Some(align), width: Some(300.0), ..Default::default() };
+ text::rewrite_block(&mut doc, 0, 0, Some(text), &style).unwrap();
+ String::from_utf8_lossy(&page_content_bytes(&doc, 0)).into_owned()
+ };
+ for (plain, trailing, align) in [
+ ("aaa bbb ccc\nddd eee", "aaa bbb ccc \nddd eee", added::Align::Justify),
+ ("Title", "Title ", added::Align::Center),
+ ("Title", "Title ", added::Align::Right),
+ ] {
+ let first = trailing.split('\n').next().unwrap();
+ let expected = shown(plain, align);
+ let actual = shown(trailing, align).replace(&format!("({first})"), &format!("({})", first.trim_end()));
+ assert_eq!(actual, expected, "{trailing:?} {align:?}");
+ }
+}
+
+/// A justified row runs from the paragraph's left edge to the margin. Word spacing reaches only
+/// the spaces between its words: the spaces before its first word and after its last are left
+/// out of a stretched row (as before #4199), so the reopened rows stay inside the paragraph and
+/// can be edited again in place.
+#[test]
+fn a_justified_row_keeps_its_indent_and_ends_at_the_margin() {
+ let style = text::BlockStyle {
+ family: Some((added::Family::Helvetica, false, false)),
+ align: Some(added::Align::Justify),
+ width: Some(300.0),
+ ..Default::default()
+ };
+ for typed in [" Pack my box with five dozen jugs\nof liquor", " Pack my box with five dozen jugs \nof liquor"] {
+ let mut doc = text_page("BT /F1 12 Tf 72 700 Td (Hello world) Tj ET");
+ text::rewrite_block(&mut doc, 0, 0, Some(typed), &style).unwrap();
+ let mut doc = reopen(&doc);
+ let lines = text::text_lines(&doc, 0).unwrap();
+ let first = lines.iter().find(|l| l.text.contains("Pack")).unwrap();
+ assert_eq!(first.text, "Pack my box with five dozen jugs", "{typed:?}");
+ assert!((first.rect[0] - 72.0).abs() < 0.5, "{typed:?}: {:?}", first.rect);
+ assert!(lines.iter().all(|l| l.rect[0] >= 72.0 - 0.5 && l.rect[2] <= 372.5), "{typed:?}: {lines:?}");
+ let blocks = text::text_blocks(&doc, 0).unwrap();
+ assert_eq!(blocks.len(), 1, "{typed:?}: {blocks:?}");
+ text::replace_block(&mut doc, 0, 0, "Edited again").unwrap();
+ let again = text::text_lines(&reopen(&doc), 0).unwrap();
+ assert!(again.iter().all(|l| l.rect[0] >= 0.0 && l.rect[2] <= 600.0), "{typed:?}: {again:?}");
+ }
+}
+
+/// A justified paragraph whose first row was typed with an indent is edited again through the
+/// styled path (a draft with a line break): its rows keep their scaling and stay one paragraph
+/// inside its width.
+#[test]
+fn a_justified_paragraph_with_an_indent_edits_again_at_its_own_scale() {
+ let style = text::BlockStyle {
+ family: Some((added::Family::Helvetica, false, false)),
+ align: Some(added::Align::Justify),
+ width: Some(300.0),
+ ..Default::default()
+ };
+ let mut doc = text_page("BT /F1 12 Tf 72 700 Td (Hello world) Tj ET");
+ text::rewrite_block(&mut doc, 0, 0, Some(" aaa bbb ccc \nddd"), &style).unwrap();
+ let mut doc = reopen(&doc);
+ let draft = text::text_blocks(&doc, 0).unwrap()[0].editor_text.replacen("ccc", "cc", 1);
+ assert!(draft.contains('\n'), "{draft:?}");
+ text::replace_block(&mut doc, 0, 0, &draft).unwrap();
+ let content = String::from_utf8_lossy(&page_content_bytes(&doc, 0)).into_owned();
+ let scales: Vec<&str> = content.lines().filter(|l| l.ends_with(" Tz")).collect();
+ assert!(scales.iter().all(|l| *l == "100 Tz"), "{scales:?}: {content}");
+ let doc = reopen(&doc);
+ let blocks = text::text_blocks(&doc, 0).unwrap();
+ assert_eq!(blocks.len(), 1, "{blocks:?}");
+ let lines = text::text_lines(&doc, 0).unwrap();
+ assert!(lines.iter().all(|l| l.rect[0] >= 72.0 - 0.5 && l.rect[2] <= 372.5), "{lines:?}");
+}
+
+/// A paragraph drawn at `0 Tz` has no width to justify into: nothing is divided by it. The
+/// writer writes a number that isn't finite as 0, so the test looks for the word spacing and
+/// the move a division by zero would add, rather than for `NaN`.
+#[test]
+fn justifying_text_at_zero_horizontal_scaling_divides_by_nothing() {
+ let mut doc = text_page("BT /F1 12 Tf 0 Tz 72 700 Td (Hello world) Tj ET");
+ let style = text::BlockStyle { family: Some((added::Family::Helvetica, false, false)), align: Some(added::Align::Justify), ..Default::default() };
+ text::rewrite_block(&mut doc, 0, 0, Some(" aaa bbb\nccc"), &style).unwrap();
+ let content = String::from_utf8_lossy(&page_content_bytes(&doc, 0)).into_owned();
+ let block = content.split("ET").next().unwrap();
+ assert_eq!(block.matches(" Tw").count(), 1, "only the paragraph's own 0 Tw: {content}");
+ let first_row = block.split(" Tm").nth(1).and_then(|rest| rest.split(" Tj").next()).unwrap();
+ assert!(!first_row.contains(" Td"), "no move before the first row: {content}");
+}
+
+/// The preview's box is the box of the rows Apply writes, measured to their last glyphs.
+#[test]
+fn a_drafts_box_is_the_box_apply_draws() {
+ let doc = text_page("BT /F1 12 Tf 14 TL 72 700 Td [(First) -2000 (row here )] TJ T* (Second row ) Tj ET");
+ let source = text::text_blocks(&doc, 0).unwrap().swap_remove(0);
+ let draft = source.editor_text.replacen("Second", "Third", 1);
+ let layout = text::text_edit_layout(&doc, 0, 0, &draft, &text::BlockStyle::default()).unwrap();
+ let mut applied = doc.clone();
+ text::replace_block(&mut applied, 0, 0, &draft).unwrap();
+ let boxed = text::text_lines(&applied, 0)
+ .unwrap()
+ .into_iter()
+ .map(|l| {
+ let end = l.ink.iter().map(|r| r[2]).fold(f64::NEG_INFINITY, f64::max);
+ [l.rect[0], l.rect[1], if end.is_finite() { end.min(l.rect[2]) } else { l.rect[2] }, l.rect[3]]
+ })
+ .reduce(|a, r| [a[0].min(r[0]), a[1].min(r[1]), a[2].max(r[2]), a[3].max(r[3])]);
+ let (d, b) = (layout.draft_rect.unwrap(), boxed.unwrap());
+ assert!(d.iter().zip(b).all(|(x, y)| (x - y).abs() < 0.01), "{draft:?}: preview {d:?}, applied {b:?}");
+}
+
+/// The draft's box is measured to its last glyph, not over the spaces typed after it.
+#[test]
+fn a_drafts_box_leaves_out_spaces_after_the_last_word() {
+ let doc = text_page("BT /F1 12 Tf 72 700 Td (Hello world) Tj ET");
+ let layout = |text: &str| text::text_edit_layout(&doc, 0, 0, text, &text::BlockStyle::default()).unwrap().draft_rect;
+ assert_eq!(layout("Hello there "), layout("Hello there"));
+}
+
+/// A lone carriage return (an old Mac line ending) breaks the row, as `\n` and `\r\n` do.
+#[test]
+fn a_lone_carriage_return_breaks_an_edited_paragraph() {
+ let mut doc = text_page("BT /F1 12 Tf 72 700 Td (Hello world) Tj ET");
+ text::replace_block(&mut doc, 0, 0, "one\rtwo").unwrap();
+ let lines: Vec<String> = text::text_lines(&reopen(&doc), 0).unwrap().into_iter().map(|l| l.text).collect();
+ assert_eq!(lines, ["one", "two"]);
+}
+
+/// On the styled rewrite path too, `\r\n` is one row break and a lone `\r` another, and no
+/// carriage return reaches the page: with no other formatting, and with a part set in red.
+#[test]
+fn carriage_returns_break_rows_on_the_styled_path() {
+ let draft = "one\r\ntwo\rthree";
+ let red = text::RangeStyle {
+ range: 0..3,
+ family: None,
+ resource: None,
+ size: None,
+ color: Some([1.0, 0.0, 0.0]),
+ underline: None,
+ char_spacing: None,
+ scale: None,
+ };
+ for style in [text::BlockStyle::default(), text::BlockStyle { ranges: vec![red], ..Default::default() }] {
+ let mut doc = text_page("BT /F1 12 Tf 72 700 Td (Hello world) Tj ET");
+ text::rewrite_block(&mut doc, 0, 0, Some(draft), &style).unwrap();
+ let doc = reopen(&doc);
+ let content = page_content_bytes(&doc, 0);
+ assert!(!content.contains(&b'\r') && !content.windows(2).any(|w| w == b"\\r"), "{}", String::from_utf8_lossy(&content));
+ let lines: Vec<String> = text::text_lines(&doc, 0).unwrap().into_iter().map(|l| l.text).collect();
+ assert_eq!(lines, ["one", "two", "three"], "{style:?}");
+ }
+}
+
+/// A subset with no space glyph shows each space as a positioning gap one space wide, so a run
+/// of spaces still takes a run's width (#4199).
+#[test]
+fn a_run_of_spaces_in_a_subset_without_a_space_glyph_keeps_its_width() {
+ let mut doc = text_page("BT /F2 12 Tf 72 700 Td (ab) Tj /F1 12 Tf ( ) Tj /F2 12 Tf (ba) Tj ET");
+ assert_eq!(text::replace_block(&mut doc, 0, 0, "ab ba ab").unwrap().substituted, None);
+ let content = String::from_utf8_lossy(&page_content_bytes(&reopen(&doc), 0)).into_owned();
+ assert_eq!(content.matches("[-330] TJ").count(), 5, "{content}");
+}
diff --git a/crates/edit/src/text.rs b/crates/edit/src/text.rs
index a08cb23..71dd4b6 100644
--- a/crates/edit/src/text.rs
+++ b/crates/edit/src/text.rs
@@ -87,6 +87,10 @@ pub struct TextLine {
/// Why the line can't be edited: its font's writing mode (its CMap's `WMode`) couldn't be read,
/// so which way its glyphs advance is unknown. The line is listed as horizontal text.
unreadable_mode: Option<String>,
+ /// The runs the line joins, in content order: each one's text, the end of its words in
+ /// `ink`, and whether joining put a space before it. Empty when the line's text was put
+ /// into another order (see [`TextLine::runs`]).
+ runs: Vec<(String, usize, bool)>,
}
impl TextLine {
@@ -214,7 +218,17 @@ fn layout_draft(
*count -= 1;
continue;
}
- rect = Some(rect.map_or(line.rect, |r| [r[0].min(line.rect[0]), r[1].min(line.rect[1]), r[2].max(line.rect[2]), r[3].max(line.rect[3])]));
+ // Spaces typed after a row's last word are drawn but show nothing, so an upright row is
+ // measured to the end of its last word: they don't make a draft overflow (#4199).
+ let mut r = line.rect;
+ if line.upright() && !line.ink.is_empty() {
+ if crate::bidi::rtl_base(&line.text) {
+ r[0] = r[0].max(line.ink.iter().map(|i| i[0]).fold(f64::INFINITY, f64::min));
+ } else {
+ r[2] = r[2].min(line.ink.iter().map(|i| i[2]).fold(f64::NEG_INFINITY, f64::max));
+ }
+ }
+ rect = Some(rect.map_or(r, |a| [a[0].min(r[0]), a[1].min(r[1]), a[2].max(r[2]), a[3].max(r[3])]));
}
let overflow = rect
.is_some_and(|r| r[0] < source.rect[0] - 0.5 || r[1] < source.rect[1] - 0.5 || r[2] > source.rect[2] + 0.5 || r[3] > source.rect[3] + 0.5);
@@ -233,6 +247,14 @@ struct TextState {
fill: Vec<Op>,
/// The text rendering mode (`Tr`); 3 is invisible text, as in an OCR layer over a scan.
render_mode: i64,
+ /// The stroke colour operators, the line width and the ExtGStates selected (see [`Ts`]):
+ /// graphics state the text was painted with that [`TextState::ops`] doesn't restate.
+ stroke: Vec<Op>,
+ line_width: Option<f64>,
+ ext_gstate: Vec<Vec<u8>>,
+ /// The dash pattern and line cap in force (see [`Ts`]): compared, not restated.
+ dash: Dash,
+ line_cap: i64,
}
impl TextState {
@@ -246,7 +268,51 @@ impl TextState {
rise: ts.rise,
fill: ts.fill.clone(),
render_mode: ts.render_mode,
+ stroke: ts.stroke.clone(),
+ line_width: ts.line_width,
+ ext_gstate: ts.ext_gstate.clone(),
+ dash: ts.dash.clone(),
+ line_cap: ts.line_cap,
+ }
+ }
+
+ /// Operators that change how text is painted from `current` (the state where they run) to
+ /// this one: the ExtGStates, stroke colour, line width and a visible rendering mode. A
+ /// rewritten paragraph is drawn before its text object, so whatever that object set before
+ /// its first show (`/GS1 gs`, `1 Tr 1 0 0 RG 2 w` inside `BT`, #3508/#3509) must be stated
+ /// again. Empty when nothing differs.
+ ///
+ /// Only fill, stroke and fill-then-stroke (`Tr` 0–2) are restated: invisible text is revealed
+ /// by [`reveal_ops`] and clipping text is refused, so neither is ever drawn this way.
+ ///
+ /// A `gs` has no inverse, so a selection `current` has and this state doesn't stays in force:
+ /// run these inside a `q`/`Q` that starts from `current`, one per state drawn.
+ fn paint_ops(&self, current: &TextState) -> Vec<Op> {
+ let n = pdfcraft_content::num;
+ let mut v = Vec::new();
+ // The selections both share stay in force; the ones after them are selected again in order.
+ let shared = self.ext_gstate.iter().zip(&current.ext_gstate).take_while(|(a, b)| a == b).count();
+ for name in self.ext_gstate.iter().skip(shared) {
+ v.push(Op::new("gs", vec![Object::Name(name.clone())]));
+ }
+ // A reselected ExtGState may set `/LW`, so the width (already the effective one) follows it.
+ let reselected = !v.is_empty();
+ if self.stroke != current.stroke {
+ if self.stroke.is_empty() {
+ // The initial stroke colour: black in DeviceGray.
+ v.push(Op::new("G", vec![n(0.0)]));
+ } else {
+ v.extend(self.stroke.iter().cloned());
+ }
+ }
+ let width = self.line_width.unwrap_or(1.0);
+ if reselected || width != current.line_width.unwrap_or(1.0) {
+ v.push(Op::new("w", vec![n(width)]));
+ }
+ if (0..=2).contains(&self.render_mode) && self.render_mode != current.render_mode {
+ v.push(Op::new("Tr", vec![Object::Int(self.render_mode)]));
}
+ v
}
/// Operators that set this state (inside a text object).
@@ -557,6 +623,20 @@ impl TextLine {
(self.stream, self.ops.iter().min().copied().unwrap_or(0))
}
+ /// The runs of text the line joins, in content order: each run's text as its glyphs show it,
+ /// the boxes of its words (a part of `ink`), and whether joining put a space between it and
+ /// the run before (`text` has one there; runs closer together join with none, so one word
+ /// can span runs). None when the line's text was reordered for reading (right-to-left or
+ /// visual-order Indic text): then only the line's text as a whole says what it reads.
+ pub fn runs(&self) -> impl Iterator<Item = (&str, &[[f64; 4]], bool)> {
+ let mut start = 0;
+ self.runs.iter().map(move |(text, end, spaced)| {
+ let ink = self.ink.get(start..*end).unwrap_or_default();
+ start = *end;
+ (text.as_str(), ink, *spaced)
+ })
+ }
+
fn rotation(&self) -> f64 {
let m = Matrix(self.origin.tm).then(&Matrix(self.origin.ctm)).0;
m[1].atan2(m[0]).to_degrees()
@@ -634,6 +714,50 @@ struct Ts {
/// Why the font's writing mode couldn't be read (a broken or cyclic CMap). Its text is then
/// listed as horizontal, but the lines in it are refused for editing.
unreadable: Option<Rc<str>>,
+ /// The operators that set the current stroke colour (`G`, `RG`, `K`, or `CS` + `SC`/`SCN`).
+ stroke: Vec<Op>,
+ /// The line width a `w` or an ExtGState's `/LW` set (`None`: the initial 1.0).
+ line_width: Option<f64>,
+ /// The ExtGState resources selected with `gs`, oldest first (see [`select_gs`]).
+ ext_gstate: Vec<Vec<u8>>,
+ /// The dash pattern a `d` or an ExtGState's `/D` set (initially solid: `[] 0`).
+ dash: Dash,
+ /// The line cap a `J` or an ExtGState's `/LC` set (initially 0, butt).
+ line_cap: i64,
+}
+
+/// A dash pattern (ISO 32000-2 §8.4.3.6): the dash array and the phase.
+type Dash = (Vec<f64>, f64);
+
+/// The most dash array entries a pattern keeps; a longer one is ignored, as is a malformed one.
+const MAX_DASH: usize = 32;
+
+/// The dash pattern `array phase`, as `d` takes it and an ExtGState's `/D` holds it.
+fn dash_pattern(doc: &Document, array: Option<&Object>, phase: Option<&Object>) -> Option<Dash> {
+ let array = doc.resolve(array?);
+ let items = array.as_array().filter(|a| a.len() <= MAX_DASH)?;
+ let finite = |o: &Object| doc.resolve(o).as_f64().filter(|v| v.is_finite());
+ Some((items.iter().map(finite).collect::<Option<Vec<_>>>()?, finite(phase?)?))
+}
+
+/// A line cap style, as `J` takes it and an ExtGState's `/LC` holds it: 0, 1 or 2.
+fn line_cap(doc: &Document, cap: Option<&Object>) -> Option<i64> {
+ doc.resolve(cap?).as_int().filter(|c| (0..=2).contains(c))
+}
+
+/// The most `gs` selections a state remembers. Repeating a selection moves it to the end, so
+/// this bounds the distinct ExtGStates in force, not the operators a hostile stream repeats.
+const MAX_GS: usize = 32;
+
+/// Record `gs /name` in `list`. A `gs` sets every parameter its dictionary names to an absolute
+/// value, so a later selection of the same dictionary overrides the earlier one completely: the
+/// earlier entry goes, which keeps replaying the list equivalent to replaying the stream.
+fn select_gs(list: &mut Vec<Vec<u8>>, name: &[u8]) {
+ list.retain(|n| n != name);
+ if list.len() >= MAX_GS {
+ list.remove(0);
+ }
+ list.push(name.to_vec());
}
/// The page's content streams as listed, each with its decoded data (empty when it doesn't
@@ -1055,6 +1179,11 @@ impl Carry {
gs: Gs::default(),
vertical: None,
unreadable: None,
+ stroke: Vec::new(),
+ line_width: None,
+ ext_gstate: Vec::new(),
+ dash: (Vec::new(), 0.0),
+ line_cap: 0,
};
Carry { ts, stack: Vec::new(), marked: Vec::new(), layers: Vec::new(), text_left: MAX_PAGE_TEXT }
}
@@ -1169,6 +1298,14 @@ fn interpret(
ts.fill.retain(|o| o.is("cs"));
ts.fill.push(op.clone());
}
+ b"G" | b"RG" | b"K" | b"CS" => ts.stroke = vec![op.clone()],
+ b"SC" | b"SCN" => {
+ ts.stroke.retain(|o| o.is("CS"));
+ ts.stroke.push(op.clone());
+ }
+ b"w" => ts.line_width = op.num(0).filter(|w| w.is_finite()).or(ts.line_width),
+ b"d" => ts.dash = dash_pattern(doc, op.operands.first(), op.operands.get(1)).unwrap_or_else(|| ts.dash.clone()),
+ b"J" => ts.line_cap = line_cap(doc, op.operands.first()).unwrap_or(ts.line_cap),
b"Tf" => {
ts.size = op.num(1).unwrap_or(ts.size);
if let Some(name) = op.name(0) {
@@ -1196,9 +1333,21 @@ fn interpret(
b"Ts" => ts.rise = op.num(0).unwrap_or(0.0),
b"Tr" => ts.render_mode = op.operands.first().and_then(Object::as_int).unwrap_or(-1),
b"gs" => {
+ if let Some(name) = op.name(0) {
+ select_gs(&mut ts.ext_gstate, name);
+ }
let params = op.name(0).and_then(|name| states.get(name)).map(|p| doc.resolve(p));
if let Some(params) = params.as_deref().and_then(Object::as_dict) {
ts.gs.apply(doc, params);
+ // `/LW` sets the line width as `w` does (ISO 32000-2 §8.4.5).
+ let lw = params.get(b"LW").and_then(|w| doc.resolve(w).as_f64()).filter(|w| w.is_finite());
+ ts.line_width = lw.or(ts.line_width);
+ let dash = params.get(b"D").map(|d| doc.resolve(d));
+ let dash = dash.as_deref().and_then(Object::as_array);
+ if let Some(d) = dash.and_then(|d| dash_pattern(doc, d.first(), d.get(1))) {
+ ts.dash = d;
+ }
+ ts.line_cap = line_cap(doc, params.get(b"LC")).unwrap_or(ts.line_cap);
}
}
b"Do" => {
@@ -1488,7 +1637,11 @@ fn text_lines_in(doc: &Document, p: &pdfcraft_model::Page, actual_text: bool) ->
&& (s.text.trim().is_empty() || lines.last().is_some_and(|l| same_font(l, &s.font, &s.base_font, s.face.as_deref())))
&& (s.text.trim().is_empty()
|| lines.last().is_some_and(|l| {
- (s.size - l.size).abs() < 0.01 && s.bold == l.bold && s.italic == l.italic && fill_color(&s.state.fill) == l.color
+ (s.size - l.size).abs() < 0.01
+ && s.bold == l.bold
+ && s.italic == l.italic
+ && fill_color(&s.state.fill) == l.color
+ && same_paint(l, &s.state)
}))
&& near
// An OCR layer is one text object over the whole scan: its words continue a line
@@ -1497,13 +1650,15 @@ fn text_lines_in(doc: &Document, p: &pdfcraft_model::Page, actual_text: bool) ->
});
if joins && let Some(l) = lines.last_mut() {
let gap = last.map_or(0.0, |(_, pen)| pen.continues(&s, 0.0).1);
- if gap - s.tracking > l.size * s.state.scale.abs() * 0.2 && !l.text.ends_with(' ') && !s.text.starts_with(' ') {
+ let spaced = gap - s.tracking > l.size * s.state.scale.abs() * 0.2 && !l.text.ends_with(' ') && !s.text.starts_with(' ');
+ if spaced {
l.text.push(' ');
}
l.text.push_str(&s.text);
l.rect = [l.rect[0].min(s.rect[0]), l.rect[1].min(s.rect[1]), l.rect[2].max(s.rect[2]), l.rect[3].max(s.rect[3])];
l.frame = union(l.frame, s.frame);
l.ink.extend(s.ink.iter().copied());
+ l.runs.push((s.text.clone(), l.ink.len(), spaced));
l.ops.push(s.op);
l.ops.extend(s.extra_ops.iter().copied());
l.decodable &= s.decodable;
@@ -1536,6 +1691,7 @@ fn text_lines_in(doc: &Document, p: &pdfcraft_model::Page, actual_text: bool) ->
actual_text: s.actual_text,
clips: s.state.render_mode >= 4,
unreadable_mode: s.state.unreadable.as_deref().map(str::to_owned),
+ runs: vec![(s.text.clone(), s.ink.len(), false)],
ops: std::iter::once(s.op).chain(s.extra_ops.iter().copied()).collect(),
origin: Origin {
tm: s.tm.0,
@@ -1555,10 +1711,15 @@ fn text_lines_in(doc: &Document, p: &pdfcraft_model::Page, actual_text: bool) ->
// Content streams draw right-to-left lines in visual order; the editor works in typing order.
for l in lines.iter_mut().filter(|l| !l.logical_order) {
// A visual-order Indic font draws pre-base vowel signs before their consonant.
+ let shown = l.text.clone();
if l.visual_order && !l.actual_text {
l.text = crate::indic::to_logical(&l.text);
}
l.text = crate::bidi::to_logical(&l.text);
+ // The runs hold the text in drawing order, which no longer reads as the line does.
+ if l.text != shown {
+ l.runs.clear();
+ }
}
// A colour set through a colour space (Chrome writes ICC-based sRGB) reads as itself.
let colour_spaces = res.get(b"ColorSpace").map(|c| doc.resolve(c)).and_then(|c| c.as_dict().cloned()).unwrap_or_default();
@@ -1601,19 +1762,25 @@ fn add_shown(lines: &mut Vec<TextLine>, last: &mut Option<Pen>, s: Shown, stream
&& (s.text.trim().is_empty() || lines.last().is_some_and(|l| same_font(l, &s.font, &s.base_font, s.face.as_deref())))
&& (s.text.trim().is_empty()
|| lines.last().is_some_and(|l| {
- (s.size - l.size).abs() < 0.01 && s.bold == l.bold && s.italic == l.italic && fill_color(&s.state.fill) == l.color
+ (s.size - l.size).abs() < 0.01
+ && s.bold == l.bold
+ && s.italic == l.italic
+ && fill_color(&s.state.fill) == l.color
+ && same_paint(l, &s.state)
}))
&& pen.continues(&s, if bt == s.bt { 3.0 } else { 1.5 }).0
});
if joins && let Some(l) = lines.last_mut() {
let gap = last.map_or(0.0, |pen| pen.continues(&s, 0.0).1);
- if gap - s.tracking > l.size * s.state.scale.abs() * 0.2 && !l.text.ends_with(' ') && !s.text.starts_with(' ') {
+ let spaced = gap - s.tracking > l.size * s.state.scale.abs() * 0.2 && !l.text.ends_with(' ') && !s.text.starts_with(' ');
+ if spaced {
l.text.push(' ');
}
l.text.push_str(&s.text);
l.rect = [l.rect[0].min(s.rect[0]), l.rect[1].min(s.rect[1]), l.rect[2].max(s.rect[2]), l.rect[3].max(s.rect[3])];
l.frame = union(l.frame, s.frame);
l.ink.extend(s.ink.iter().copied());
+ l.runs.push((s.text.clone(), l.ink.len(), spaced));
l.ops.push(s.op);
l.ops.extend(s.extra_ops.iter().copied());
l.decodable &= s.decodable;
@@ -1645,6 +1812,7 @@ fn add_shown(lines: &mut Vec<TextLine>, last: &mut Option<Pen>, s: Shown, stream
actual_text: s.actual_text,
clips: s.state.render_mode >= 4,
unreadable_mode: s.state.unreadable.as_deref().map(str::to_owned),
+ runs: vec![(s.text.clone(), s.ink.len(), false)],
ops: std::iter::once(s.op).chain(s.extra_ops.iter().copied()).collect(),
origin: Origin {
tm: s.tm.0,
@@ -1830,7 +1998,11 @@ fn reading_lines(doc: &Document, page: usize) -> Result<(Vec<TextLine>, bool), E
let mut lines = reading::lines_of(std::mem::take(&mut w.runs), &w.gradients);
// A visual-order Indic font draws pre-base vowel signs before their consonant.
for l in lines.iter_mut().filter(|l| l.visual_order && !l.actual_text) {
+ let shown = l.text.clone();
l.text = crate::indic::to_logical(&l.text);
+ if l.text != shown {
+ l.runs.clear();
+ }
}
lines.retain(|l| !l.text.trim().is_empty());
Ok((lines, w.budget.truncated))
@@ -1966,6 +2138,24 @@ fn same_font(line: &TextLine, font: &[u8], base_font: &str, face: Option<&str>)
line.font.as_bytes() == font || same_base_font(&line.base_font, base_font) || (line.face.is_some() && line.face.as_deref() == face)
}
+/// Whether a run painted with `ts` continues `line` as it is painted: a line is rewritten in the
+/// state of its first run, so a `Tr`, stroke colour or line width that changes partway starts
+/// another run (see [`TextState::paint_ops`]; the `gs` parameters are compared as [`Paint`]).
+/// The stroke colour, width, dash and cap only count for text that is stroked, so a rule drawn
+/// between two words doesn't split their line. They are compared as values, wherever they were
+/// set: two ExtGStates with the same settings under other names still continue a line.
+///
+/// Only the visible modes (`Tr` 0–2) that `paint_ops` restates are compared: a line that goes on
+/// as invisible or clipping text stays one line, which the clipping refusal reads whole (#3447).
+fn same_paint(line: &TextLine, ts: &Ts) -> bool {
+ let a = &line.origin.state;
+ let visible = |m: i64| (0..=2).contains(&m);
+ let same_mode = a.render_mode == ts.render_mode || !visible(a.render_mode) || !visible(ts.render_mode);
+ let stroked = matches!((a.render_mode, ts.render_mode), (1 | 2, 1 | 2));
+ let outline = a.stroke == ts.stroke && a.line_width == ts.line_width && a.dash == ts.dash && a.line_cap == ts.line_cap;
+ same_mode && (!stroked || outline)
+}
+
/// Whether two `/BaseFont` names name the same font: a subset's six-letter tag and `+` prefix do
/// not change the font (ISO 32000-2 §9.6.4), so `ABCDEF+Arial` and `GHIJKL+Arial` are one font.
/// A name that is missing, or only a tag (`ABCDEF+`), names no font and matches nothing.
@@ -1994,8 +2184,6 @@ fn source_family(base_font: &str) -> crate::added::Family {
}
}
-const SUBSTITUTE_NAME: &str = "PCEdHelv";
-const SUBSTITUTE: &[u8] = SUBSTITUTE_NAME.as_bytes();
const MAX_TYPE3_GLYPHS: usize = 240;
/// The generated fonts for one replacement: one per run of at most `max_glyphs` unique characters,
@@ -2213,6 +2401,19 @@ fn type3_font(
.map_err(|_| EditError::Invalid("replacement text has too many unique characters".into()))?;
glyphs.push(Type3Glyph { code, ch, path, width });
}
+ Ok(write_type3_glyphs(doc, fonts_res, face, hebrew, glyphs, per_font))
+}
+
+/// Write already validated outlines; callers can prepare every face before adding any objects.
+fn write_type3_glyphs(
+ doc: &mut Document,
+ fonts_res: &mut Dict,
+ face: &CraftFont,
+ hebrew: bool,
+ glyphs: Vec<Type3Glyph>,
+ per_font: usize,
+) -> Type3Fallback {
+ let per_font = per_font.clamp(1, MAX_TYPE3_GLYPHS);
let mut codes = HashMap::with_capacity(glyphs.len());
let mut widths = Vec::with_capacity(glyphs.len());
let mut names = Vec::new();
@@ -2228,7 +2429,7 @@ fn type3_font(
}
names.push(add_type3_font(doc, fonts_res, face, hebrew, group));
}
- Ok(Type3Fallback { family: face.family, names, widths, codes })
+ Type3Fallback { family: face.family, names, widths, codes }
}
/// Adds one generated font whose codes 1 to `glyphs.len()` show `glyphs`, and returns its resource
@@ -2723,20 +2924,28 @@ fn paragraph_separator(c: char) -> bool {
/// Greedy word wrapping to `width` with `advance` giving a string's width. Each `\n` starts a
/// new line. A row may also end inside a word of Chinese or Japanese text ([`crate::linebreak`]);
-/// those pieces join without a space.
+/// those pieces join without a space. Every white-space character is written as one space, so
+/// a run of spaces typed between, before or after words stays (#4199); only the spaces where a
+/// row wraps are dropped.
fn wrap(text: &str, width: f64, advance: impl Fn(&str) -> f64) -> Vec<String> {
let mut out = Vec::new();
for row in text.split('\n') {
let mut line = String::new();
let start = out.len();
- for word in row.split(paragraph_separator).filter(|word| !word.is_empty()) {
+ // The separators read since the last word: each one boundary between `split` pieces.
+ let mut gap = 0usize;
+ for (k, word) in row.split(paragraph_separator).enumerate() {
+ if k > 0 {
+ gap = gap.saturating_add(1);
+ }
+ if word.is_empty() {
+ continue;
+ }
+ let spaces = " ".repeat(std::mem::take(&mut gap));
for (i, piece) in crate::linebreak::pieces(word).into_iter().enumerate() {
- let candidate = match (line.is_empty(), i) {
- (true, _) => piece.to_string(),
- (false, 0) => format!("{line} {piece}"),
- (false, _) => format!("{line}{piece}"),
- };
- if !line.is_empty() && advance(&candidate) > width {
+ let candidate = if i == 0 { format!("{line}{spaces}{piece}") } else { format!("{line}{piece}") };
+ // A row holding only the spaces that indent it doesn't wrap before its first word.
+ if line.chars().any(|c| c != ' ') && advance(&candidate) > width {
out.push(std::mem::take(&mut line));
line = piece.to_string();
} else {
@@ -2744,6 +2953,7 @@ fn wrap(text: &str, width: f64, advance: impl Fn(&str) -> f64) -> Vec<String> {
}
}
}
+ line.push_str(&" ".repeat(gap));
if !line.is_empty() || out.len() == start {
out.push(line);
}
@@ -2865,7 +3075,8 @@ fn rewrite_block_from(
&& (!style.ranges.is_empty()
|| style.resource.is_some()
|| (text.is_some_and(|draft| {
- draft.contains('\n')
+ // A row break, `\n` or a carriage return, takes the path that keeps untouched rows.
+ draft.contains(['\n', '\r'])
|| pdfcraft_fonts::source_shaping::required(draft)
|| !pdfcraft_fonts::embedding::matching_faces(&b.base_font).is_empty()
}) || registered_face
@@ -2875,18 +3086,24 @@ fn rewrite_block_from(
&& style.family.is_none()
&& style.bold.is_none())
{
- return rewrite_styled_block(doc, page, &b, &lines, text, style);
+ return rewrite_styled_block(doc, page, &b, &lines, text, style, max_glyphs);
}
let streams = content_streams(doc, &p.dict)?;
let pieces = Pieces::join(&streams.iter().map(|(_, d)| d.as_slice()).collect::<Vec<_>>());
let ops = pieces.parse().ops;
- // Explicit line breaks stay (#1443); within a line, runs of white space become one space.
- let text = text
+ // Explicit line breaks stay (#1443), and so does each typed U+0020 space: a run of them is
+ // not folded into one (#4199, #3797). `\r\n` and a lone `\r` are breaks too; other white
+ // space is written as one space.
+ let text: String = text
.unwrap_or(&b.text)
- .split('\n')
- .map(|row| row.split(paragraph_separator).filter(|word| !word.is_empty()).collect::<Vec<_>>().join(" "))
- .collect::<Vec<_>>()
- .join("\n");
+ .replace("\r\n", "\n")
+ .chars()
+ .map(|c| match c {
+ '\r' => '\n',
+ c if c != '\n' && paragraph_separator(c) => ' ',
+ c => c,
+ })
+ .collect();
// The characters to show, for choosing fonts: the breaks are moves, not glyphs.
let flat = text.replace('\n', " ");
let o = &first.origin;
@@ -2940,8 +3157,9 @@ fn rewrite_block_from(
// A paragraph keeps its width (or takes the one asked for); a single line grows to the right
// (to the left when right-to-left), up to the page's margin.
let width = match style.width {
- // Capped at the largest page PDF allows (14 400 pt).
- Some(w) if w.is_finite() => w.clamp(size * k, 14_400.0),
+ // Capped at the largest page PDF allows (14 400 pt), even for text set larger than that
+ // (`clamp` panics when its minimum is the larger, or NaN).
+ Some(w) if w.is_finite() => w.clamp((size * k).min(14_400.0), 14_400.0),
Some(_) => return Err(EditError::Invalid("the paragraph's width must be a number".into())),
// Turned text: the page's margins are along another axis. A single line grows (below).
None if !upright => (frame[2] - frame[0]).max(size * k),
@@ -3042,7 +3260,9 @@ fn rewrite_block_from(
f.set(b"Subtype".to_vec(), Object::name("Type1"));
f.set(b"BaseFont".to_vec(), Object::name(base));
f.set(b"Encoding".to_vec(), Object::name("WinAnsiEncoding"));
- let name = if style.family.is_none() { String::from_utf8_lossy(SUBSTITUTE).into_owned() } else { format!("PCEd{}", base.replace('-', "")) };
+ // Named after its face, as the line and region rewrites name theirs: one name for every
+ // stand-in would repoint the paragraphs set in an earlier one at this face (#4280).
+ let name = format!("PCEd{}", base.replace('-', ""));
fonts_res.set(name.clone().into_bytes(), Object::Dict(f));
if style.family.is_none() {
substituted = Some(base.to_string());
@@ -3067,6 +3287,21 @@ fn rewrite_block_from(
None => size * 1.2,
};
let n = pdfcraft_content::num;
+ // The paragraph's operators go, and so does another drawing on the same baseline (a fake-bold
+ // second copy, an invisible text layer): the new text is all that may show.
+ let drop = dropped;
+ // Text shown earlier in the same text object stays first: the paragraph then goes where its
+ // last row was, after any backgrounds between the rows, or between two halves of the text object.
+ let start = last.ops.first().copied().unwrap_or(emit.bt_op);
+ let split = ops
+ .get(emit.bt_op..start)
+ .unwrap_or_default()
+ .iter()
+ .enumerate()
+ .any(|(i, op)| matches!(op.op.as_slice(), b"Tj" | b"TJ" | b"'" | b"\"") && !drop.contains(&(emit.bt_op + i)));
+ // What the text after the paragraph expects, and what is in force where the paragraph is
+ // drawn: the state at its BT (or where it was split).
+ let after = if split { &emit.state } else { &emit.bt_state };
// In its own graphics state, so a new colour (or anything else) stops at the paragraph.
let mut block_ops = vec![Op::new("q", vec![])];
block_ops.extend(reveal_ops(&b, &lines, style, emit.ctm)?);
@@ -3074,6 +3309,8 @@ fn rewrite_block_from(
if let Some((ax, ay)) = movement {
block_ops.push(Op::new("cm", vec![n(1.0), n(0.0), n(0.0), n(1.0), n(ax), n(ay)]));
}
+ // Painted as the paragraph was, including what its text object set before the first show.
+ block_ops.extend(o_state.paint_ops(after));
block_ops.push(Op::new("BT", vec![]));
let mut state = o_state.clone();
state.word_spacing = 0.0;
@@ -3086,12 +3323,13 @@ fn rewrite_block_from(
block_ops.extend(state.ops());
block_ops.push(Op::new("Tm", tm.iter().map(|v| n(*v)).collect()));
// Alignment: each line's offset from the left edge, in text space.
- let offset = |line: &str| -> f64 {
- let free = (width - advance(line)).max(0.0) / k;
+ // `visible` is the width the line is aligned on (see the loop below).
+ let offset = |visible: f64| -> f64 {
+ let free = (width - visible).max(0.0) / k;
match align {
Some(crate::added::Align::Center) => free / 2.0,
// A right-to-left line anchored at its right edge may start left of the old box.
- Some(crate::added::Align::Right) if anchored_right => (right_edge - advance(line)) / k,
+ Some(crate::added::Align::Right) if anchored_right => (right_edge - visible) / k,
Some(crate::added::Align::Right) => free,
// A justified right-to-left paragraph ends its last line at the right edge.
Some(crate::added::Align::Justify) if rtl => free,
@@ -3111,11 +3349,29 @@ fn rewrite_block_from(
let mut tw_set = 0.0;
let mut underlines: Vec<(f64, f64, f64)> = Vec::new(); // (x0, x1, y) in text space
for (i, line) in wrapped.iter().enumerate() {
- let spaces = line.matches(' ').count();
- let tw =
- if justify && i + 1 < wrapped.len() && spaces > 0 { (width - advance(line)).max(0.0) / k / o_state.scale / spaces as f64 } else { 0.0 };
- // A stretched line fills the width from the left edge.
- let dx = if tw > 0.0 { 0.0 } else { offset(line) };
+ // A stretched (justified) line shows only its words, as before #4199: word spacing would
+ // reach the spaces before its first word and after its last, so they are left out, and
+ // the line fills the width from the left edge. Nothing to stretch over, or a paragraph
+ // drawn at `0 Tz`, isn't justified.
+ let body = line.trim_matches(' ');
+ let interior = body.matches(' ').count();
+ let tw = if justify && i + 1 < wrapped.len() && interior > 0 && o_state.scale.abs() > 1e-6 {
+ Some((width - advance(body)).max(0.0) / k / o_state.scale / interior as f64).filter(|tw| tw.is_finite())
+ } else {
+ None
+ }
+ .unwrap_or(0.0);
+ // Other lines show every space typed. A left-to-right one is aligned on its width up to
+ // its last word; a right-to-left one on its whole width, since the spaces typed after its
+ // last word are drawn on its left and the ones before its first on its right.
+ let (shown, visible) = if tw > 0.0 {
+ (body, advance(body))
+ } else if crate::bidi::rtl_base(line) {
+ (line.as_str(), advance(line))
+ } else {
+ (line.as_str(), advance(line.trim_end_matches(' ')))
+ };
+ let dx = if tw > 0.0 { 0.0 } else { offset(visible) };
if i > 0 || dx != 0.0 {
block_ops.push(Op::new("Td", vec![n(dx - x), n(if i > 0 { -lead } else { 0.0 })]));
}
@@ -3127,7 +3383,7 @@ fn rewrite_block_from(
tw_set = tw;
}
// Each wrapped line in typing order; drawn left to right (right-to-left runs reversed).
- let visual = crate::bidi::to_visual(line);
+ let visual = crate::bidi::to_visual(shown);
// Stretched without word spacing: shown up to and including each space, then moved on.
let pieces = if stretch > 0.0 { visual.split_inclusive(' ').collect() } else { vec![visual.as_str()] };
for piece in pieces {
@@ -3148,7 +3404,8 @@ fn rewrite_block_from(
}
}
let tw = tw + stretch;
- let w = (advance(line) + tw * spaces as f64 * o_state.scale * k) / k;
+ // Underlined to the line's last word, over its stretched gaps.
+ let w = (visible + tw * interior as f64 * o_state.scale * k) / k;
underlines.push((dx, dx + w, -(i as f64) * lead - size * 0.12));
}
block_ops.push(Op::new("ET", vec![]));
@@ -3178,21 +3435,6 @@ fn rewrite_block_from(
block_ops.push(Op::new("Q", vec![]));
}
block_ops.push(Op::new("Q", vec![]));
- // The paragraph's operators go, and so does another drawing on the same baseline (a fake-bold
- // second copy, an invisible text layer): the new text is all that may show.
- let mut drop = coincident_ops(&lines, &members);
- drop.extend(members.iter().flat_map(|l| l.ops.iter().copied()));
- // Text shown earlier in the same text object stays first: the paragraph then goes where its
- // last row was, after any backgrounds between the rows, or between two halves of the text object.
- let start = last.ops.first().copied().unwrap_or(emit.bt_op);
- let split = ops
- .get(emit.bt_op..start)
- .unwrap_or_default()
- .iter()
- .enumerate()
- .any(|(i, op)| matches!(op.op.as_slice(), b"Tj" | b"TJ" | b"'" | b"\"") && !drop.contains(&(emit.bt_op + i)));
- // What the text after the paragraph expects: the state at its BT (or where it was split).
- let after = if split { &emit.state } else { &emit.bt_state };
block_ops.extend(after.ops().into_iter().filter(|op| !op.is("Tf") || after.font.is_some()));
if split {
block_ops.insert(0, Op::new("ET", vec![]));
@@ -3519,7 +3761,23 @@ mod tests {
assert_eq!(wrap("A  B C", 4.0, width), ["A  B", "C"]);
assert_eq!(wrap("A\u{a0}B C", 3.0, width), ["A B", "C"]);
assert_eq!(wrap("A\u{2028}B C", 3.0, width), ["A B", "C"]);
- assert_eq!(wrap(" \tA B\r\nC ", 3.0, width), ["A B", "C"]);
+ }
+
+ /// #4199: a run of spaces stays a run, before, between and after words; the spaces where a
+ /// row wraps go, and each other white-space character is one space.
+ #[test]
+ fn paragraph_wrapping_keeps_every_space_typed() {
+ let width = |s: &str| s.chars().count() as f64;
+ assert_eq!(wrap("a b c", 20.0, width), ["a b c"]);
+ assert_eq!(wrap(" a b ", 20.0, width), [" a b "]);
+ assert_eq!(wrap("a\t\tb", 20.0, width), ["a b"]);
+ assert_eq!(wrap("aa bb cc", 6.0, width), ["aa bb", "cc"]);
+ // An indent alone on a row doesn't wrap before its first word.
+ assert_eq!(wrap(" abc", 3.0, width), [" abc"]);
+ // The rewrite turns `\r\n` and `\r` into `\n` before wrapping.
+ assert_eq!(wrap(" \tA B\nC ", 3.0, width), [" A", "B", "C "]);
+ assert_eq!(wrap(" ", 3.0, width), [" "]);
+ assert_eq!(wrap("", 3.0, width), [""]);
}
#[test]
diff --git a/crates/edit/src/text_regions.rs b/crates/edit/src/text_regions.rs
index 082b2cb..007fa33 100644
--- a/crates/edit/src/text_regions.rs
+++ b/crates/edit/src/text_regions.rs
@@ -2,6 +2,18 @@
use super::*;
+// The draft is capped at 4 MiB; also bound the outline data prepared across all fallback faces.
+// A glyph budget worth 64 full batches (15,360 glyphs with the production batch size).
+// Lowering the internal batch size for tests lowers the budget by the same ratio.
+const MAX_STYLED_FALLBACK_BATCHES: usize = 64;
+
+struct FallbackGroup {
+ face: &'static CraftFont,
+ seen: std::collections::HashSet<char>,
+ glyphs: Vec<Type3Glyph>,
+ positions: Vec<usize>,
+}
+
fn same_plane(a: &TextLine, b: &TextLine) -> bool {
let at = Matrix(a.origin.tm).then(&Matrix(a.origin.ctm));
let bt = Matrix(b.origin.tm).then(&Matrix(b.origin.ctm));
@@ -166,8 +178,8 @@ fn opens_with_marker(text: &str) -> bool {
if !first.is_ascii_digit() && !first.is_ascii_alphabetic() {
return false;
}
- let digits = text.chars().take_while(|c| c.is_ascii_digit()).count();
- let letters = text.chars().take_while(|c| c.is_ascii_alphabetic()).count();
+ let digits = text.chars().take_while(char::is_ascii_digit).count();
+ let letters = text.chars().take_while(char::is_ascii_alphabetic).count();
// Both runs are ASCII characters, so their length in characters is their length in bytes:
// the slice below starts on a character boundary.
let rest = if digits > 0 {
@@ -178,7 +190,7 @@ fn opens_with_marker(text: &str) -> bool {
return false;
};
let mut after = rest.chars();
- matches!(after.next(), Some('.' | ')')) && after.next().is_none_or(|c| c.is_whitespace())
+ matches!(after.next(), Some('.' | ')')) && after.next().is_none_or(char::is_whitespace)
}
/// A row that opens with a list marker opens its own item: joining it to the row above is what
@@ -429,6 +441,7 @@ pub(super) fn rewrite_styled_block(
lines: &[TextLine],
text: Option<&str>,
style: &BlockStyle,
+ max_glyphs: usize,
) -> Result<LineEdit, EditError> {
let first = block.lines.first().and_then(|i| lines.get(*i)).ok_or_else(|| EditError::Invalid("the paragraph has no source runs".into()))?;
let draft = match text {
@@ -577,16 +590,29 @@ pub(super) fn rewrite_styled_block(
// Each tuple is a character, its source style and an encodable resource name.
let mut chars = Vec::new();
let mut substituted = None;
- let mut fallback_names: std::collections::BTreeMap<(String, char), String> = std::collections::BTreeMap::new();
+ let mut fallback_groups: Vec<FallbackGroup> = Vec::new();
+ let mut fallback_names: std::collections::BTreeMap<(String, bool, char), usize> = std::collections::BTreeMap::new();
+ let mut fallback_glyphs = 0_usize;
+ let per_font = max_glyphs.clamp(1, MAX_TYPE3_GLYPHS);
+ let fallback_budget = per_font.saturating_mul(MAX_STYLED_FALLBACK_BATCHES);
let mut full_faces: HashMap<String, String> = HashMap::new();
let mut programs: HashMap<String, Option<std::sync::Arc<Vec<u8>>>> = HashMap::new();
for (range, index) in styled_spans {
let source = lines.get(index).unwrap_or(first);
- for ch in draft.get(range).unwrap_or_default().chars() {
+ let start = range.start;
+ for (offset, ch) in draft.get(range).unwrap_or_default().char_indices() {
if ch == '\n' {
chars.push((ch, index, source.font.clone()));
continue;
}
+ // A carriage return breaks the row too. Before `\n` the pair is one break, so the
+ // CR stays a `\r` the rows skip. Either way it keeps its place among the draft's
+ // characters, which rows are counted in.
+ if ch == '\r' {
+ let crlf = start.checked_add(offset).and_then(|at| draft.get(at.saturating_add(1)..)).is_some_and(|rest| rest.starts_with('\n'));
+ chars.push((if crlf { '\r' } else { '\n' }, index, source.font.clone()));
+ continue;
+ }
let s = ch.to_string();
let name = if let Some(resource) = overrides.get(&index).and_then(|r| r.resource.as_ref()).or(style.resource.as_ref()) {
if !metrics.get(resource).is_some_and(|m| source_encodes(m, &s)) {
@@ -649,24 +675,40 @@ pub(super) fn rewrite_styled_block(
} else {
let family = source_family(&source.base_font);
if needs_type3(&s) {
- let key = (source.base_font.rsplit('+').next().unwrap_or(&source.base_font).to_owned(), ch);
- if let Some(name) = fallback_names.get(&key) {
- chars.push((ch, index, name.clone()));
- continue;
- }
- if fallback_names.len() >= MAX_TYPE3_GLYPHS {
- return Err(EditError::Invalid("the replacement has too many fallback glyphs".into()));
+ let key = (source.base_font.clone(), source.bold, ch);
+ let group_index = if let Some(index) = fallback_names.get(&key) {
+ *index
+ } else {
+ // Keep the old per-character face choice: a serif Japanese character
+ // and a Cyrillic character may need different faces even in one style.
+ // Hebrew uses the separate RTL path before reaching this writer.
+ let (faces, _) = type3_faces(&s, family, source.bold)?;
+ let face =
+ fallback_face(&faces, &[ch], |face, ch| japanese_glyph_from(face, ch).is_ok()).ok_or_else(|| no_fallback_font(&s))?;
+ let index = fallback_groups.iter().position(|group| std::ptr::eq(group.face, face)).unwrap_or_else(|| {
+ let index = fallback_groups.len();
+ fallback_groups.push(FallbackGroup { face, seen: Default::default(), glyphs: Vec::new(), positions: Vec::new() });
+ index
+ });
+ fallback_names.insert(key, index);
+ index
+ };
+ let group = fallback_groups.get_mut(group_index).ok_or_else(|| EditError::Invalid("the fallback face is missing".into()))?;
+ if group.seen.insert(ch) {
+ if fallback_glyphs >= fallback_budget {
+ return Err(EditError::Invalid(format!(
+ "the replacement needs more than {fallback_budget} fallback glyphs; edit a smaller paragraph or load a complete font"
+ )));
+ }
+ let (path, width) = type3_glyph(group.face, ch)?.ok_or_else(|| no_glyph_for(group.face, ch))?;
+ let code = u8::try_from((group.glyphs.len() % per_font).saturating_add(1))
+ .map_err(|_| EditError::Invalid("replacement text has too many unique characters".into()))?;
+ group.glyphs.push(Type3Glyph { code, ch, path, width });
+ fallback_glyphs = fallback_glyphs.saturating_add(1);
}
- let fallback = type3_font(doc, &mut fonts, &s, family, source.bold, MAX_TYPE3_GLYPHS)?;
- let name = fallback.names.first().cloned().ok_or_else(no_japanese_font)?;
- let dict = fonts
- .get(name.as_bytes())
- .and_then(|f| doc.resolve(f).as_dict().cloned())
- .ok_or_else(|| EditError::Invalid("the fallback font could not be loaded".into()))?;
- metrics.insert(name.clone(), Metrics::from_dict(doc, &dict));
- substituted = Some(fallback.family.to_string());
- fallback_names.insert(key, name.clone());
- name
+ group.positions.push(chars.len());
+ // Filled from the prepared font/code map before measuring or drawing.
+ String::new()
} else {
let base = family.base_font(source.bold, source.italic);
let name = format!("PCEd{}", base.replace('-', ""));
@@ -684,6 +726,24 @@ pub(super) fn rewrite_styled_block(
chars.push((ch, index, name));
}
}
+ // All fallback outlines have now succeeded. Batch by actual face, preserving source
+ // style indices; the existing writer then coalesces adjacent equal-font/style characters.
+ for group in fallback_groups {
+ let fallback = write_type3_glyphs(doc, &mut fonts, group.face, false, group.glyphs, per_font);
+ for name in &fallback.names {
+ let font = fonts
+ .get(name.as_bytes())
+ .and_then(|f| doc.dict(f))
+ .ok_or_else(|| EditError::Invalid("the fallback font could not be loaded".into()))?;
+ metrics.insert(name.clone(), Metrics::from_dict(doc, &font));
+ }
+ for position in group.positions {
+ let item = chars.get_mut(position).ok_or_else(|| EditError::Invalid("the fallback character is missing".into()))?;
+ let (font, _) = fallback.codes.get(&item.0).ok_or_else(|| EditError::Invalid("the fallback glyph is missing".into()))?;
+ item.2 = fallback.names.get(*font).cloned().ok_or_else(|| EditError::Invalid("the fallback font is missing".into()))?;
+ }
+ substituted = Some(fallback.family.to_owned());
+ }
let size_of = |source: &TextLine, index: usize| {
overrides.get(&index).and_then(|r| r.size).or(style.size).unwrap_or(source.size).max(0.1) / source.origin.k.max(1e-6)
};
@@ -815,6 +875,11 @@ pub(super) fn rewrite_styled_block(
let mut at = 0;
while at < chars.len() {
let Some(item) = chars.get(at) else { break };
+ // The CR of a CRLF: the `\n` after it breaks the row.
+ if item.0 == '\r' {
+ at += 1;
+ continue;
+ }
if item.0 == '\n' {
row_ranges.push(row_start..row_start + row.len());
rows.push(std::mem::take(&mut row));
@@ -880,6 +945,17 @@ pub(super) fn rewrite_styled_block(
}
};
let o = &lead.origin;
+ let mut drop = coincident_ops(lines, &members);
+ drop.extend(members.iter().flat_map(|l| l.ops.iter().copied()));
+ let start = lead.ops.first().copied().unwrap_or(o.bt_op);
+ let split = ops
+ .get(o.bt_op..start)
+ .unwrap_or_default()
+ .iter()
+ .enumerate()
+ .any(|(i, op)| matches!(op.op.as_slice(), b"Tj" | b"TJ" | b"'" | b"\"") && !drop.contains(&(o.bt_op + i)));
+ // What is in force where the rewrite is drawn, and what the text after it expects.
+ let after = if split { &o.state } else { &o.bt_state };
for (row, _) in rows.iter().zip(&kept).filter(|(_, k)| !**k) {
let text: String = row.iter().map(|v| v.0).collect();
if pdfcraft_fonts::source_shaping::required(&text) && row.first().is_some_and(|first| row.iter().any(|v| v.1 != first.1 || v.2 != first.2)) {
@@ -990,6 +1066,11 @@ pub(super) fn rewrite_styled_block(
tm[4] += ax;
tm[5] += ay;
let mut segment_width = segment_advances.get(&(row_index, pos)).copied().unwrap_or(0.0);
+ // Each run in its own graphics state, restating what its source set inside its text
+ // object (`gs`, stroke, line width, `Tr`; #3508/#3509) from the state the rewrite is
+ // drawn in: a `gs` has no inverse, so one run's ExtGState would stay for the next.
+ block_ops.push(Op::new("q", vec![]));
+ block_ops.extend(state.paint_ops(after));
if let Some((_, shaped, _)) = shaped_runs.get(&(row_index, pos)) {
let resource = glyph_resources.get(&(row_index, pos)).ok_or_else(|| EditError::Invalid("shaped font is missing".into()))?;
let mut properties = Dict::new();
@@ -1076,6 +1157,7 @@ pub(super) fn rewrite_styled_block(
block_ops.push(Op::new("l", vec![n(x1), n(y1)]));
block_ops.push(Op::new("S", vec![]));
}
+ block_ops.push(Op::new("Q", vec![]));
x += segment_width;
pos = end;
}
@@ -1086,16 +1168,6 @@ pub(super) fn rewrite_styled_block(
};
}
block_ops.push(Op::new("Q", vec![]));
- let mut drop = coincident_ops(lines, &members);
- drop.extend(members.iter().flat_map(|l| l.ops.iter().copied()));
- let start = lead.ops.first().copied().unwrap_or(o.bt_op);
- let split = ops
- .get(o.bt_op..start)
- .unwrap_or_default()
- .iter()
- .enumerate()
- .any(|(i, op)| matches!(op.op.as_slice(), b"Tj" | b"TJ" | b"'" | b"\"") && !drop.contains(&(o.bt_op + i)));
- let after = if split { &o.state } else { &o.bt_state };
block_ops.extend(after.ops());
if split {
block_ops.insert(0, Op::new("ET", vec![]));
diff --git a/crates/engine/README.md b/crates/engine/README.md
index 4bf80e3..86492bc 100644
--- a/crates/engine/README.md
+++ b/crates/engine/README.md
@@ -16,6 +16,14 @@ Two frontends exist on top of it today: `pdfcraft-ui-egui` (desktop and web) and
`pdfcraft-automation` (headless tools, the CLI and MCP). Anything one can do, the other must be
able to do — see AGENTS.md §3.
+When dynamic XFA layout is active, `JsRunner` does not initialize Acrobat JavaScript with
+scripts from the PDF container's `/Names /JavaScript` tree. Those scripts belong to the
+fallback PDF view and can otherwise show a misleading viewer-compatibility warning.
+They remain in the document and in `Document::document_scripts`. Requested console scripts,
+field actions and XFA events can still show messages; ordinary PDFs, static XFA and shells
+without an active layout keep their document scripts. Converting XFA to a static form and
+undoing that conversion switches the context with the document state.
+
## The editing model
Each open document holds a `pdfcraft_cos::Document`: the object graph plus a copy-on-write overlay.
diff --git a/crates/engine/src/camera_edges.rs b/crates/engine/src/camera_edges.rs
index 05dc180..e5a18ba 100644
--- a/crates/engine/src/camera_edges.rs
+++ b/crates/engine/src/camera_edges.rs
@@ -350,13 +350,42 @@ fn refine(q: [Point; 4], edges: &[Option<Edge>], w: usize, h: usize) -> Option<[
order_quad(refined)
}
+/// A candidate quad's score (its area times the square of its sides' mean support), or `None` when it
+/// strays off the image, is too small, or has a side without enough edge support.
+fn quad_score(q: &[Point; 4], edges: &[Option<Edge>], w: usize, h: usize) -> Option<f64> {
+ let (fw, fh) = (w as f64, h as f64);
+ let (mx, my) = (MARGIN * fw, MARGIN * fh);
+ if q.iter().any(|p| p[0] < -mx || p[1] < -my || p[0] > fw + mx || p[1] > fh + my) {
+ return None;
+ }
+ let area = (0..4)
+ .map(|k| {
+ let (p, n) = (q[k], q[(k + 1) % 4]);
+ p[0] * n[1] - n[0] * p[1]
+ })
+ .sum::<f64>()
+ .abs()
+ / 2.0;
+ if area < MIN_AREA * fw * fh {
+ return None;
+ }
+ let sides: Vec<f64> = (0..4).map(|k| support(q[k], q[(k + 1) % 4], edges, w, h)).collect();
+ if sides.iter().any(|&s| s < MIN_SUPPORT) {
+ return None;
+ }
+ // Large, and with every side on its edge: a slightly larger quad with a side
+ // off the sheet loses to the sheet itself.
+ let mean = sides.iter().sum::<f64>() / 4.0;
+ Some(area * mean * mean)
+}
+
/// The convex quadrilateral of two near-horizontal and two near-vertical lines whose four sides
/// all lie on edges, scored by its area times the square of its sides' mean support.
fn best_quad(lines: &[Line], edges: &[Option<Edge>], w: usize, h: usize) -> Option<[Point; 4]> {
- let horizontal: Vec<&Line> = lines.iter().filter(|l| is_flat(l)).collect();
- let vertical: Vec<&Line> = lines.iter().filter(|l| !is_flat(l)).collect();
- let (fw, fh) = (w as f64, h as f64);
- let (mx, my) = (MARGIN * fw, MARGIN * fh);
+ // A normal within 45° of vertical makes a near-horizontal line.
+ let flat = |l: &&Line| (l.theta.to_degrees() - 90.0).abs() <= 45.0;
+ let horizontal: Vec<&Line> = lines.iter().filter(flat).collect();
+ let vertical: Vec<&Line> = lines.iter().filter(|l| !flat(l)).collect();
let mut best: Option<(f64, [Point; 4])> = None;
for (i, &h1) in horizontal.iter().enumerate() {
for &h2 in horizontal.iter().skip(i + 1) {
@@ -365,28 +394,7 @@ fn best_quad(lines: &[Line], edges: &[Option<Edge>], w: usize, h: usize) -> Opti
let corners = [intersect(*h1, *v1), intersect(*h1, *v2), intersect(*h2, *v2), intersect(*h2, *v1)];
let [Some(a), Some(b), Some(c), Some(d)] = corners else { continue };
let Some(q) = order_quad([a, b, c, d]) else { continue };
- if q.iter().any(|p| p[0] < -mx || p[1] < -my || p[0] > fw + mx || p[1] > fh + my) {
- continue;
- }
- let area = (0..4)
- .map(|k| {
- let (p, n) = (q[k], q[(k + 1) % 4]);
- p[0] * n[1] - n[0] * p[1]
- })
- .sum::<f64>()
- .abs()
- / 2.0;
- if area < MIN_AREA * fw * fh {
- continue;
- }
- let sides: Vec<f64> = (0..4).map(|k| support(q[k], q[(k + 1) % 4], edges, w, h)).collect();
- if sides.iter().any(|&s| s < MIN_SUPPORT) {
- continue;
- }
- // Large, and with every side on its edge: a slightly larger quad with a side
- // off the sheet loses to the sheet itself.
- let mean = sides.iter().sum::<f64>() / 4.0;
- let score = area * mean * mean;
+ let Some(score) = quad_score(&q, edges, w, h) else { continue };
if best.is_none_or(|(b, _)| score > b) {
best = Some((score, q));
}
diff --git a/crates/engine/src/catalog.rs b/crates/engine/src/catalog.rs
index efa99c0..0ac0f26 100644
--- a/crates/engine/src/catalog.rs
+++ b/crates/engine/src/catalog.rs
@@ -147,7 +147,7 @@ pub static TOOL_GROUPS: &[ToolGroup] = &[
item("Link", "link-2", "edit.link", Ready),
item("Bates numbering", "hash", "edit.bates", Ready),
menu_item("Background", "palette", &["edit.background", "edit.background.update", "edit.background.remove"]),
- item("Attach file", "paperclip", "edit.attach", Planned("M12")),
+ item("Attach file", "paperclip", "edit.attach", Ready),
],
},
],
@@ -550,6 +550,23 @@ pub fn group(id: &str) -> Option<&'static ToolGroup> {
TOOL_GROUPS.iter().find(|g| g.id == id)
}
+/// A heading of the expanded All tools view, as Acrobat files its tools under "Create & Edit",
+/// "Forms & Signatures" and so on. Every group belongs to exactly one category.
+#[derive(Clone, Copy, Debug)]
+pub struct ToolCategory {
+ pub label: &'static str,
+ /// [`ToolGroup::id`]s, in display order.
+ pub groups: &'static [&'static str],
+}
+
+pub static TOOL_CATEGORIES: &[ToolCategory] = &[
+ ToolCategory { label: "Create & Edit", groups: &["create", "edit", "export", "combine", "organize", "scan", "compress"] },
+ ToolCategory { label: "Review & Compare", groups: &["comment", "stamp", "compare", "measure"] },
+ ToolCategory { label: "Forms & Signatures", groups: &["fill_sign", "form", "certificate"] },
+ ToolCategory { label: "Protect & Standardize", groups: &["protect", "redact", "accessibility", "standards", "print_production"] },
+ ToolCategory { label: "Customize & Automate", groups: &["actions", "javascript", "search_index", "ai"] },
+];
+
#[cfg(test)]
mod tests {
use super::*;
@@ -564,6 +581,18 @@ mod tests {
}
}
+ #[test]
+ fn every_group_is_in_exactly_one_category() {
+ let mut seen = HashSet::new();
+ for c in TOOL_CATEGORIES {
+ for id in c.groups {
+ assert!(group(id).is_some(), "{} lists unknown group {id}", c.label);
+ assert!(seen.insert(*id), "{id} is in two categories");
+ }
+ }
+ assert_eq!(seen.len(), TOOL_GROUPS.len(), "a group is in no category");
+ }
+
#[test]
fn commands_are_namespaced() {
for g in TOOL_GROUPS {
@@ -596,6 +625,19 @@ mod tests {
assert!(menus >= 3);
}
+ // Regression test for #2028: Edit text & images sat under "Add content", though it changes
+ // what is already on the page; it belongs first under "Modify page".
+ #[test]
+ fn edit_text_and_images_is_the_first_item_under_modify_page() {
+ let edit = group("edit").expect("the Edit a PDF tool");
+ let section_of = |command: &str| edit.sections.iter().find(|s| s.items.iter().any(|i| i.command == command)).map(|s| s.title);
+ assert_eq!(section_of("edit.edit_text"), Some("Modify page"), "Edit text & images is a Modify page tool");
+ let modify = edit.sections.iter().find(|s| s.title == "Modify page").expect("a Modify page section");
+ assert_eq!(modify.items.first().map(|i| i.command), Some("edit.edit_text"), "and the first one, so it is not below the fold");
+ let add = edit.sections.iter().find(|s| s.title == "Add content").expect("an Add content section");
+ assert!(add.items.iter().all(|i| i.command != "edit.edit_text"), "it adds nothing, so it is not listed under Add content");
+ }
+
#[test]
fn every_update_and_remove_command_is_reachable_from_a_tool_entry() {
let reachable: HashSet<&str> =
diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs
index 2c1dc2c..204eeee 100644
--- a/crates/engine/src/commands.rs
+++ b/crates/engine/src/commands.rs
@@ -282,6 +282,7 @@ pub const COMMANDS: &[CommandSpec] = &[
c("edit.text", "Add text", None, None, Modification, "type"),
c("edit.edit_text", "Edit text & images", None, None, Modification, "text-cursor-input"),
c("edit.link", "Add or edit links", None, None, Modification, "link-2"),
+ c("edit.attach", "Attach a file…", EDIT, None, Modification, "paperclip"),
c("edit.links_from_urls", "Create links from URLs", None, None, Modification, "link-2"),
c("edit.remove_links", "Remove all links", None, None, Modification, "trash-2"),
c("edit.bates", "Add Bates numbering…", None, None, Modification, "hash"),
diff --git a/crates/engine/src/copy_image.rs b/crates/engine/src/copy_image.rs
index 642c84e..b377903 100644
--- a/crates/engine/src/copy_image.rs
+++ b/crates/engine/src/copy_image.rs
@@ -59,6 +59,57 @@ impl Document {
let rgba = image::DynamicImage::from_decoder(decoder).map_err(|e| e.to_string())?.into_rgba8();
Ok((rgba.width(), rgba.height(), rgba.into_raw()))
}
+
+ /// Edit ▸ Copy of an added image (`index` among `page`'s added items): its picture as a file
+ /// (extension, bytes), a JPEG or JPEG 2000 file as stored, otherwise a lossless PNG, for
+ /// [`Edit::PasteContent`](crate::Edit::PasteContent). Refused when the document doesn't allow
+ /// copying.
+ pub fn added_image_file(&self, page: usize, index: usize) -> Result<(&'static str, Vec<u8>), String> {
+ self.check_copying().map_err(|e| e.to_string())?;
+ let editor = self.editor.as_ref().ok_or("the document can't be read")?;
+ let item = self.added().iter().filter(|a| a.page == page).nth(index);
+ let Some(pdfcraft_edit::Content::Image(img)) = item.map(|a| &a.content) else {
+ return Err(format!("item {} on page {} is not an added image", index + 1, page + 1));
+ };
+ picture_file(&editor.cos, img.image)
+ }
+}
+
+/// An added image's picture as a file: [`pdfcraft_create::image_file`], except that a JPEG 2000
+/// picture, which Add Image stores as the file it was given, is that file.
+fn picture_file(cos: &Cos, image: ObjRef) -> Result<(&'static str, Vec<u8>), String> {
+ match &*cos.get(image) {
+ Object::Stream(s) if s.dict.name(b"Subtype") == Some(b"Image") && s.dict.name(b"Filter") == Some(b"JPXDecode") => Ok(("jp2", s.raw.to_vec())),
+ _ => pdfcraft_create::image_file(cos, image),
+ }
+}
+
+/// Whether image object `image` in `cos` is the picture `file` (as [`picture_file`] writes it).
+/// The sizes are compared first, so an unrelated image is not re-encoded to find out.
+pub(crate) fn is_picture(cos: &Cos, image: ObjRef, file: &[u8]) -> bool {
+ let size = |s: &pdfcraft_cos::Stream| Some((u32::try_from(s.dict.int(b"Width")?).ok()?, u32::try_from(s.dict.int(b"Height")?).ok()?));
+ // The object at that number now, not one of an earlier generation of it.
+ if cos.generation(image.num) != image.generation {
+ return false;
+ }
+ let stored = match &*cos.get(image) {
+ // A JPEG 2000 picture is stored as its file.
+ Object::Stream(s) if s.dict.name(b"Subtype") == Some(b"Image") && s.dict.name(b"Filter") == Some(b"JPXDecode") => return s.raw[..] == *file,
+ Object::Stream(s) if s.dict.name(b"Subtype") == Some(b"Image") => size(s),
+ _ => return false,
+ };
+ let given = image::ImageReader::new(std::io::Cursor::new(file)).with_guessed_format().ok().and_then(|r| r.into_dimensions().ok());
+ stored.is_some() && stored == given && picture_file(cos, image).is_ok_and(|(_, data)| data == file)
+}
+
+/// The image object an added image in `cos` already draws picture `file` from, if any: where a
+/// second paste from another document finds the first one's.
+pub(crate) fn added_picture(cos: &Cos, file: &[u8]) -> Option<ObjRef> {
+ let mut seen = std::collections::HashSet::new();
+ pdfcraft_edit::list_added(cos).into_iter().find_map(|a| match a.content {
+ pdfcraft_edit::Content::Image(img) if seen.insert(img.image) && is_picture(cos, img.image, file) => Some(img.image),
+ _ => None,
+ })
}
/// The largest raster image Form `form` draws through its resources (nested Forms included).
diff --git a/crates/engine/src/js.rs b/crates/engine/src/js.rs
index c80537f..7f94971 100644
--- a/crates/engine/src/js.rs
+++ b/crates/engine/src/js.rs
@@ -7,7 +7,7 @@
//! off, scripts don't run and AF calls keep working natively.
use pdfcraft_forms::{Field, FieldChange, FieldEvent, FieldKind, FieldProps, ScriptResult, Scripts};
-pub use pdfcraft_js::{Limits, Outcome, Request};
+pub use pdfcraft_js::{Limits, Outcome, Panel, Request};
use crate::{DocId, Edit, EditError, Session};
@@ -19,25 +19,63 @@ pub struct JsOutput {
pub requests: Vec<Request>,
/// Script errors (as Acrobat's console shows them).
pub errors: Vec<String>,
+ /// Which of `errors` are document scripts' (#3940), told apart by where they came from and
+ /// not by their text, which a field script's error can share: each is reported once, however
+ /// often the document scripts run again.
+ pub doc_errors: Vec<String>,
}
impl JsOutput {
+ /// Whether scripts produced nothing: no alerts, console lines, requests or errors.
pub fn is_empty(&self) -> bool {
self.alerts.is_empty() && self.console.is_empty() && self.requests.is_empty() && self.errors.is_empty()
}
+ /// Adds what a field's own script produced: its alerts, console lines, errors and requests,
+ /// except a request to show a side panel or open Save As, which is noted on the console
+ /// and dropped.
fn absorb(&mut self, o: &Outcome) {
self.alerts.extend(o.alerts.iter().cloned());
self.console.extend(o.console.iter().cloned());
- self.requests.extend(o.requests.iter().cloned());
+ // A field's own scripts (keystroke, format, validate, calculate) run unasked: only a
+ // button's may show or hide a side panel, or open Save As.
+ for r in &o.requests {
+ match r {
+ Request::ShowPanel(_) => self.console.push("A field script asked to show a side panel; only a button may show a side panel".into()),
+ Request::SaveAs => {
+ self.console.push("A field script asked to save the document as a new file; only a button may open Save As".into())
+ }
+ r => self.requests.push(r.clone()),
+ }
+ }
self.errors.extend(o.error.iter().cloned());
+ // The document scripts run before every field script, so a failing one would repeat
+ // once per calculation; it is reported once.
+ for e in &o.doc_errors {
+ if !self.doc_errors.contains(e) {
+ self.doc_errors.push(e.clone());
+ self.errors.push(e.clone());
+ }
+ }
}
pub(crate) fn append(&mut self, other: JsOutput) {
self.alerts.extend(other.alerts);
self.console.extend(other.console);
self.requests.extend(other.requests);
- self.errors.extend(other.errors);
+ // As in `absorb`: a document script's error, already reported, is not repeated; a field
+ // script's errors are each their own, even one worded like a document script's.
+ let mut docs = other.doc_errors;
+ for e in other.errors {
+ if let Some(k) = docs.iter().position(|d| *d == e) {
+ docs.swap_remove(k);
+ if self.doc_errors.contains(&e) {
+ continue;
+ }
+ self.doc_errors.push(e.clone());
+ }
+ self.errors.push(e);
+ }
}
}
@@ -129,15 +167,19 @@ pub struct JsRunner {
}
impl JsRunner {
+ /// A runner for `cos`: what scripts read about the document (pages, info, whether it is
+ /// an XFA form) and its document-level scripts, read once.
pub fn new(cos: &pdfcraft_cos::Document, file_name: &str) -> JsRunner {
- let doc = pdfcraft_js::DocInfo { file_name: file_name.to_string(), num_pages: pdfcraft_model::pages(cos).len(), page: 0, info: info(cos) };
- JsRunner {
- doc,
- doc_scripts: pdfcraft_forms::document_scripts(cos),
- output: JsOutput::default(),
- cos: cos.clone(),
- displays: std::collections::HashMap::new(),
- }
+ let xfa = pdfcraft_xfa::xfa_shape(cos).is_some();
+ let doc =
+ pdfcraft_js::DocInfo { file_name: file_name.to_string(), num_pages: pdfcraft_model::pages(cos).len(), page: 0, info: info(cos), xfa };
+ // Once XFA owns the form, the PDF container's scripts belong to its fallback view.
+ // Keep them in the file and in Document JavaScripts, but do not initialize an
+ // AcroForm context with them: a viewer-compatibility alert would be misleading.
+ // Packets alone are not enough: static XFA and an unlaid-out shell keep their scripts.
+ let xfa_active = xfa && pdfcraft_xfa::existing_layout(cos).is_some();
+ let doc_scripts = if xfa_active { Vec::new() } else { pdfcraft_forms::document_scripts(cos) };
+ JsRunner { doc, doc_scripts, output: JsOutput::default(), cos: cos.clone(), displays: std::collections::HashMap::new() }
}
}
@@ -192,6 +234,11 @@ impl crate::Document {
self.editor.as_ref().and_then(|e| pdfcraft_forms::field_actions(&e.cos, name).ok()).unwrap_or_default()
}
+ /// Field Properties ▸ Actions: how many actions are chained after each trigger's first one.
+ pub fn field_action_chains(&self, name: &str) -> Vec<(pdfcraft_forms::Trigger, usize)> {
+ self.editor.as_ref().and_then(|e| pdfcraft_forms::field_action_chains(&e.cos, name).ok()).unwrap_or_default()
+ }
+
/// Document JavaScripts (name, source), in name order.
pub fn document_scripts(&self) -> Vec<(String, String)> {
self.editor.as_ref().map(|e| document_scripts(&e.cos)).unwrap_or_default()
@@ -440,6 +487,32 @@ mod review_tests {
assert!(read <= 4 * n, "{read} characters read for {n} glyphs");
}
+ /// Review on #3985: merging two outputs reports a failing document script once, as one run
+ /// does, while each field script error stays: told apart by where an error came from, so a
+ /// field script that throws a document script's very words is still reported.
+ #[test]
+ fn merged_output_reports_a_document_script_error_once() {
+ let doc = "document script 2: TypeError: not a callable function";
+ let field = "ReferenceError: x is not defined";
+ let run = |error: &str| {
+ let mut out = JsOutput::default();
+ out.absorb(&Outcome { error: Some(error.into()), doc_errors: vec![doc.into()], ..Outcome::default() });
+ out
+ };
+ let mut out = run(field);
+ out.append(run(field));
+ assert_eq!(out.errors, [field, doc, field]);
+ // CodeRabbit on #3985: a field script that throws the document script's text.
+ out.append(run(doc));
+ assert_eq!(out.errors, [field, doc, field, doc]);
+ let alone = run(doc);
+ assert_eq!(alone.errors, [doc, doc], "the field's error and the document script's");
+ let count = |o: &JsOutput| o.errors.iter().filter(|e| *e == doc).count();
+ let mut merged = run(field);
+ merged.append(alone);
+ assert_eq!(count(&merged), 2, "the field's copy stays; the document script's is listed once");
+ }
+
#[test]
fn duplicate_field_names_diff_against_first_original() {
let first = pdfcraft_js::FieldState::new("duplicate", pdfcraft_js::FieldType::Text, vec!["first".into()]);
diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs
index 768c4d7..b339459 100644
--- a/crates/engine/src/lib.rs
+++ b/crates/engine/src/lib.rs
@@ -46,16 +46,20 @@ pub use signature_scan::{PhotoRect, ScanError, SignaturePhoto, Turn};
pub use stamp_preview::StampPreview;
pub use text_preview::TextEditPreview;
-pub use pdfcraft_organize::{BoxSpec, FieldConflicts, PageBox, SplitBy, Transition, TransitionSpec, split_ranges};
+pub use pdfcraft_organize::{BoxSpec, FieldConflicts, PageBox, SplitBy, Transition, TransitionSpec, mime_for_name, split_ranges};
/// One file produced by a split: (1-based first page, last page, PDF bytes).
pub use pdfcraft_organize::LabelStyle;
pub use pdfcraft_organize::Standard;
+pub use pdfcraft_organize::check_custom_key;
pub use pdfcraft_organize::view::{InitialView, Layout as InitialLayout, Magnification, Navigation};
pub use pdfcraft_cos::Algorithm;
pub use pdfcraft_create::{CONVERTIBLE, CreateError, ImageResolution, OfficeKind, SourceKind, decode_text, office_kind, source_kind};
-pub use pdfcraft_edit::added::{text_rect as added_text_rect, text_width as added_text_width};
+pub use pdfcraft_edit::added::{
+ CHAR_SPACING_LIMIT as ADDED_CHAR_SPACING_LIMIT, paste_place as added_paste_place, paste_rect as added_paste_rect, text_rect as added_text_rect,
+ text_width as added_text_width,
+};
pub use pdfcraft_edit::{
Added, AddedImage, AddedText, Align as TextAlign, Background, Content as AddedContent, Family as FontFamily, HeaderFooter, MarkKind, Watermark,
};
@@ -276,6 +280,8 @@ fn uses_scripts(edit: &Edit) -> bool {
fn scope_of(edit: &Edit) -> Scope {
match edit {
Edit::SetInfo { .. } => Scope::Metadata,
+ // The Attachments list is read from the whole document.
+ Edit::AddAttachment { .. } | Edit::DeleteAttachment { .. } => Scope::Full,
// A file attachment also changes the Attachments list.
Edit::AddAnnotation(a) if matches!(a.shape, Shape::Attachment { .. }) => Scope::Full,
Edit::AddMeasurement(_)
@@ -309,6 +315,7 @@ fn scope_of(edit: &Edit) -> Scope {
| Edit::UpdateContent { .. }
| Edit::DeleteContent { .. }
| Edit::ReplaceImage { .. }
+ | Edit::PasteContent { .. }
| Edit::AddHeaderFooter { .. }
| Edit::AddWatermark { .. }
| Edit::AddBackground { .. }
@@ -787,6 +794,17 @@ impl Document {
self.editable() && self.permissions().is_none_or(|p| p.modify())
}
+ /// How widget `widget` of text field `name` lays its value out, for asking whether a typed
+ /// value fits it ([`form_appearance::TextBox::fits`]): a field that doesn't scroll takes no
+ /// more than fits. `None` without such a field or widget, or when the document can't be
+ /// edited.
+ pub fn field_text_box(&self, name: &str, widget: usize) -> Option<form_appearance::TextBox> {
+ let cos = &self.editor.as_ref()?.cos;
+ let f = self.form.iter().find(|f| f.name == name)?;
+ let w = f.widgets.get(widget)?;
+ Some(form_appearance::text_box(cos, f, w))
+ }
+
/// Filling in form fields is allowed (Table 22, bits 6 and 9).
pub fn allows_form_filling(&self) -> bool {
self.editable() && self.permissions().is_none_or(|p| p.fill_forms())
@@ -847,6 +865,14 @@ impl Document {
matches!(f.kind, FormFieldKind::CheckBox | FormFieldKind::Radio).then(|| pdfcraft_forms::check_style(&e.cos, f))
}
+ /// Whether text field `name`'s value is cut off by its box at the field's font size (#4018):
+ /// the page (0-based) of the first widget that cuts it, and how.
+ pub fn field_overflow(&self, name: &str) -> Option<(Option<usize>, pdfcraft_forms::appearance::Overflow)> {
+ let e = self.editor.as_ref()?;
+ let f = self.form.iter().find(|f| f.name == name)?;
+ f.widgets.iter().find_map(|w| pdfcraft_forms::appearance::value_overflow(&e.cos, f, w).map(|o| (w.page, o)))
+ }
+
/// Remove Hidden Information: what each category would remove.
pub fn hidden_info(&self) -> Vec<(Hidden, usize)> {
self.editor.as_ref().map(|e| pdfcraft_redact::sanitize::scan(&e.cos)).unwrap_or_default()
@@ -870,6 +896,11 @@ impl Document {
self.editor.as_ref().and_then(|e| pdfcraft_organize::info(&e.cos, key))
}
+ /// Whether the document information has an entry `key`, of any type, listed or not.
+ pub fn has_info(&self, key: &str) -> bool {
+ self.editor.as_ref().is_some_and(|e| pdfcraft_organize::has_info(&e.cos, key))
+ }
+
/// The custom document properties as they are now (name, text), Document Properties ▸ Custom.
pub fn custom_info(&self) -> Vec<(String, String)> {
self.editor.as_ref().map(|e| pdfcraft_organize::custom_info(&e.cos)).unwrap_or_default()
@@ -946,6 +977,20 @@ fn same_pages(a: &[pdfcraft_render::PageInfo], b: &[pdfcraft_render::PageInfo])
&& a.iter().zip(b).all(|(x, y)| (x.width - y.width).abs() < 0.01 && (x.height - y.height).abs() < 0.01 && x.rotation == y.rotation)
}
+/// Each document-information field of `info` with its value in `cos` (`/Info`, else XMP), read
+/// the way the full inspection reads them: NULs and spaces trimmed, empty is none.
+fn info_fields<'a>(info: &'a mut DocInfo, cos: &pdfcraft_cos::Document) -> [(&'a mut Option<String>, Option<String>); 6] {
+ let read = |key| pdfcraft_organize::info(cos, key).map(|v| v.trim_matches('\0').trim().to_string()).filter(|v| !v.is_empty());
+ [
+ (&mut info.title, read("Title")),
+ (&mut info.author, read("Author")),
+ (&mut info.subject, read("Subject")),
+ (&mut info.keywords, read("Keywords")),
+ (&mut info.creator, read("Creator")),
+ (&mut info.producer, read("Producer")),
+ ]
+}
+
/// The copy PDFCraft displays when opening `bytes`: with appearances drawn, in memory only, for
/// comments that have none and form fields the file leaves to the viewer. Render paths outside the app, such as the CLI, use this so their page
/// images agree with the app and independent viewers. It never changes the source document, and an
@@ -1050,7 +1095,7 @@ fn shown_under_redactions(
}
fn render_threads() -> usize {
- std::thread::available_parallelism().map(|n| n.get()).unwrap_or(4).clamp(2, 8) - 1
+ std::thread::available_parallelism().map(std::num::NonZeroUsize::get).unwrap_or(4).clamp(2, 8) - 1
}
/// Write `layers`' visibility into the default optional-content configuration of `cos` (a copy
@@ -1129,6 +1174,10 @@ pub struct BookmarkRow {
pub page: Option<usize>,
/// Where on that page it goes ([`pdfcraft_render::DestView::Top`] when it doesn't say).
pub view: pdfcraft_render::DestView,
+ /// The title's colour (`/C`), `None` for the default black, and its style (`/F`).
+ pub color: Option<[f32; 3]>,
+ pub italic: bool,
+ pub bold: bool,
}
/// One page of the bookmark list, in outline order.
@@ -1156,7 +1205,16 @@ fn outline_rows(items: &[pdfcraft_render::OutlineItem]) -> Vec<BookmarkRow> {
top.1 += 1;
}
let path: Vec<usize> = levels.iter().map(|(_, listed)| listed.saturating_sub(1)).collect();
- rows.push(BookmarkRow { path, title: item.title.clone(), open: item.open, page: item.page, view: item.view });
+ rows.push(BookmarkRow {
+ path,
+ title: item.title.clone(),
+ open: item.open,
+ page: item.page,
+ view: item.view,
+ color: item.color,
+ italic: item.italic,
+ bold: item.bold,
+ });
if !item.children.is_empty() {
levels.push((&item.children, 0));
}
@@ -1298,7 +1356,7 @@ impl Protection {
(Some(a), Some(b)) if a == b => return bad("the open password and the permissions password must be different"),
_ => {}
}
- if [&self.open_password, &self.permissions_password].into_iter().flatten().any(|p| p.is_empty()) {
+ if [&self.open_password, &self.permissions_password].into_iter().flatten().any(String::is_empty) {
return bad("passwords can't be empty");
}
if self.algorithm != pdfcraft_cos::Algorithm::Aes256
@@ -1416,6 +1474,17 @@ pub enum Edit {
path: Vec<usize>,
page: usize,
},
+ /// Colour a bookmark's title (`/C`); `None` or black is the default black.
+ SetBookmarkColor {
+ path: Vec<usize>,
+ color: Option<[f64; 3]>,
+ },
+ /// Make a bookmark's title bold or italic or not (`/F`); `None` keeps that one.
+ SetBookmarkStyle {
+ path: Vec<usize>,
+ bold: Option<bool>,
+ italic: Option<bool>,
+ },
/// Bookmarks for the tagged headings (H, H1–H6), nested by level under a new first
/// "Untitled" bookmark (New Bookmarks from Structure).
BookmarksFromStructure,
@@ -1440,6 +1509,8 @@ pub enum Edit {
AddAnnotation(NewAnnotation),
/// A custom stamp from a picture file (a PDF page or an image) on `page`. A zero-size
/// `rect` is a point: the stamp is centred there at its natural size (at most 200 pt).
+ /// Any other `rect` is a box: the picture is scaled to fit inside it, keeping its shape,
+ /// and centred in it (#4077).
AddCustomStamp {
page: usize,
rect: [f64; 4],
@@ -1589,6 +1660,18 @@ pub enum Edit {
},
/// Document Properties ▸ Initial View (and the language and binding).
SetInitialView(Box<InitialView>),
+ /// Edit ▸ Attach a file: a document-level attachment (`/Names /EmbeddedFiles`) under
+ /// `name`, made unique; `mime` is the embedded file's `/Subtype` when known.
+ AddAttachment {
+ name: String,
+ bytes: Vec<u8>,
+ description: Option<String>,
+ mime: Option<String>,
+ },
+ /// Remove the document-level attachment whose name-tree key is `key`.
+ DeleteAttachment {
+ key: String,
+ },
/// Build a tagged structure tree for an untagged, text-only document.
AutoTagText,
/// Add alternate text: set (or clear, with `None`) a figure's alternate text. `figure` is
@@ -1756,6 +1839,16 @@ pub enum Edit {
name: String,
bytes: Arc<Vec<u8>>,
},
+ /// Edit ▸ Paste: an added item copied in this document or another, as it was: text with its
+ /// style, an image in its box (display space) with its turns, flips and crop. An image's
+ /// picture is `file` (from [`Document::added_image_file`]): the copied image object is reused
+ /// while it is still that picture in this document, else one an added image here already draws
+ /// it from, else the file is embedded.
+ PasteContent {
+ page: usize,
+ content: AddedContent,
+ file: Option<(String, Arc<Vec<u8>>)>,
+ },
/// Apply redaction marks (all, or those on `pages`): remove what they cover for good.
ApplyRedactions {
pages: Option<Vec<usize>>,
@@ -1912,11 +2005,15 @@ pub const EDIT_LABELS: &[&str] = &[
"Insert pages from {name}",
"Insert pages from {name} — 1 field renamed",
"Insert pages from {name} — fields renamed",
+ "Attach {name}",
+ "Delete attachment {key}",
"Add bookmark",
"Rename bookmark",
"Delete bookmark",
"Move bookmark",
"Set bookmark destination",
+ "Colour",
+ "Style",
"New bookmarks from structure",
"Number pages",
"Measure distance",
@@ -2006,6 +2103,7 @@ pub const EDIT_LABELS: &[&str] = &[
"Add image",
"Edit content",
"Delete content",
+ "Paste",
"Apply redactions",
"Remove redaction marks",
"Remove hidden information",
@@ -2029,7 +2127,7 @@ pub const EDIT_LABELS: &[&str] = &[
/// [`EDIT_LABELS`] and so translates the same way. A batch built in the interface itself arrives
/// already worded in the interface's language.
pub const BATCH_LABELS: &[&str] =
- &["Set document title", "Mark differences", "Detect form fields", "Run JavaScript", "Recognize text", field_table::LABEL];
+ &["Set document title", "Mark differences", "Detect form fields", "Run JavaScript", "Recognize text", field_table::LABEL, "Style"];
impl Edit {
/// Label for the Edit menu and history ("Undo Rotate pages").
@@ -2060,6 +2158,9 @@ impl Edit {
Edit::DeleteBookmark { .. } => Label::of("Delete bookmark"),
Edit::MoveBookmark { .. } => Label::of("Move bookmark"),
Edit::SetBookmarkPage { .. } => Label::of("Set bookmark destination"),
+ // The bookmark Style and Colour menus' own names, already said in every language.
+ Edit::SetBookmarkColor { .. } => Label::of("Colour"),
+ Edit::SetBookmarkStyle { .. } => Label::of("Style"),
Edit::BookmarksFromStructure => Label::of("New bookmarks from structure"),
Edit::NumberPages { .. } => Label::of("Number pages"),
// What was measured is part of the wording too, for the same reason.
@@ -2104,6 +2205,8 @@ impl Edit {
Edit::SetTabOrder { .. } | Edit::MoveInTabOrder { .. } => Label::of("Set tab order"),
Edit::SetCalculationOrder { .. } => Label::of("Set calculation order"),
Edit::SetInitialView(_) => Label::of("Change initial view"),
+ Edit::AddAttachment { name, .. } => Label::with("Attach {name}", name.as_str()),
+ Edit::DeleteAttachment { key } => Label::with("Delete attachment {key}", key.as_str()),
Edit::AutoTagText => Label::of("Automatically tag text"),
Edit::SetAltText { .. } => Label::of("Set alternate text"),
Edit::AutoTagFormFields => Label::of("Tag form fields"),
@@ -2145,6 +2248,7 @@ impl Edit {
Edit::UpdateContent { .. } => Label::of("Edit content"),
Edit::DeleteContent { .. } => Label::of("Delete content"),
Edit::ReplaceImage { .. } => Label::of("Replace image"),
+ Edit::PasteContent { .. } => Label::of("Paste"),
Edit::ApplyRedactions { .. } => Label::of("Apply redactions"),
Edit::ClearRedactions => Label::of("Remove redaction marks"),
Edit::RemoveHidden { .. } => Label::of("Remove hidden information"),
@@ -2228,6 +2332,8 @@ fn check_permission(edit: &Edit, p: &pdfcraft_cos::Permissions) -> Result<(), Ed
| Edit::DeleteBookmark { .. }
| Edit::MoveBookmark { .. }
| Edit::SetBookmarkPage { .. }
+ | Edit::SetBookmarkColor { .. }
+ | Edit::SetBookmarkStyle { .. }
| Edit::BookmarksFromStructure
| Edit::NumberPages { .. } => {
if p.assemble() {
@@ -2275,6 +2381,15 @@ fn check_permission(edit: &Edit, p: &pdfcraft_cos::Permissions) -> Result<(), Ed
Err(EditError::NotPermitted("changing security"))
}
}
+ // Converting to PDF/A takes the encryption off (PDF/A forbids it), so on an encrypted
+ // document it is a change of security (#3921).
+ Edit::ConvertPdfA { .. } => {
+ if unrestricted(p) {
+ Ok(())
+ } else {
+ Err(EditError::NotPermitted("removing the encryption, which PDF/A forbids"))
+ }
+ }
Edit::SetInfo { .. }
| Edit::AddHeaderFooter { .. }
| Edit::AddWatermark { .. }
@@ -2288,6 +2403,7 @@ fn check_permission(edit: &Edit, p: &pdfcraft_cos::Permissions) -> Result<(), Ed
| Edit::MoveObjects { .. }
| Edit::DeleteContent { .. }
| Edit::ReplaceImage { .. }
+ | Edit::PasteContent { .. }
| Edit::ClearRedactions
| Edit::RemoveHidden { .. }
| Edit::ImportData { .. }
@@ -2305,6 +2421,8 @@ fn check_permission(edit: &Edit, p: &pdfcraft_cos::Permissions) -> Result<(), Ed
| Edit::MoveInTabOrder { .. }
| Edit::SetCalculationOrder { .. }
| Edit::SetInitialView(_)
+ | Edit::AddAttachment { .. }
+ | Edit::DeleteAttachment { .. }
| Edit::AutoTagText
| Edit::SetAltText { .. }
| Edit::AutoTagFormFields
@@ -2315,7 +2433,6 @@ fn check_permission(edit: &Edit, p: &pdfcraft_cos::Permissions) -> Result<(), Ed
| Edit::AddOcrText { .. }
| Edit::SetDocumentScript { .. }
| Edit::SetFieldScript { .. }
- | Edit::ConvertPdfA { .. }
| Edit::RemoveStandardId { .. }
| Edit::EditTextLine { .. }
| Edit::EditTextBlock { .. }
@@ -2465,6 +2582,8 @@ fn run_edit(doc: &mut pdfcraft_cos::Document, edit: &Edit, cx: &mut EditCtx) ->
pdfcraft_organize::move_bookmark(doc, from, to_parent, *index)?;
}
Edit::SetBookmarkPage { path, page } => pdfcraft_organize::set_bookmark_page(doc, path, *page)?,
+ Edit::SetBookmarkColor { path, color } => pdfcraft_organize::set_bookmark_color(doc, path, *color)?,
+ Edit::SetBookmarkStyle { path, bold, italic } => pdfcraft_organize::set_bookmark_style(doc, path, *bold, *italic)?,
Edit::BookmarksFromStructure => {
let entries: Vec<_> = pdfcraft_a11y::headings(doc)
.into_iter()
@@ -2485,12 +2604,14 @@ fn run_edit(doc: &mut pdfcraft_cos::Document, edit: &Edit, cx: &mut EditCtx) ->
let (sw, sh) = (src.size.0.max(1.0), src.size.1.max(1.0));
let natural = rect[2] == rect[0] && rect[3] == rect[1];
let rotation = pdfcraft_organize::page_rotation(doc, *page)?;
+ // The picture as displayed: a quarter turn swaps its sides in user space.
+ let (dw, dh) = if matches!(rotation, 90 | 270) { (sh, sw) } else { (sw, sh) };
let rect = if natural {
let k = (200.0 / sw.max(sh)).min(1.0);
- let (w, h) = if matches!(rotation, 90 | 270) { (sh * k, sw * k) } else { (sw * k, sh * k) };
+ let (w, h) = (dw * k, dh * k);
[rect[0] - w / 2.0, rect[1] - h / 2.0, rect[0] + w / 2.0, rect[1] + h / 2.0]
} else {
- *rect
+ fit_picture(*rect, dw, dh)
};
let shape = Shape::CustomStamp { rect, name: name.clone(), picture: src.xobject, image: src.image, size: (sw, sh) };
let style = pdfcraft_annot::Style::default_for(&shape);
@@ -2509,6 +2630,10 @@ fn run_edit(doc: &mut pdfcraft_cos::Document, edit: &Edit, cx: &mut EditCtx) ->
Edit::EraseInk { page, index, path, radius } => {
pdfcraft_annot::erase_ink(doc, *page, *index, path, *radius, &cx.meta())?;
}
+ Edit::AddAttachment { name, bytes, description, mime } => {
+ pdfcraft_organize::add_attachment(doc, name, bytes, description.as_deref(), mime.as_deref(), cx.date.as_deref())?;
+ }
+ Edit::DeleteAttachment { key } => pdfcraft_organize::delete_attachment(doc, key)?,
Edit::ReplaceText { page, quads, text, author, strike, caret } => {
// One `/NM` each: the caret replies to the strikeout, and XFDF names that reply by
// the strikeout's `/NM` (#2666).
@@ -2530,10 +2655,23 @@ fn run_edit(doc: &mut pdfcraft_cos::Document, edit: &Edit, cx: &mut EditCtx) ->
Edit::SetAnnotationInfo { page, index, author, subject, icon } => {
pdfcraft_annot::set_info(doc, *page, *index, author.as_deref(), subject.as_deref(), *icon, &cx.meta())?;
}
- Edit::SetFieldValue { name, value } => match cx.js.as_mut() {
- Some(js) => pdfcraft_forms::set_value_with(doc, name, value, js)?,
- None => pdfcraft_forms::set_value(doc, name, value)?,
- },
+ Edit::SetFieldValue { name, value } => {
+ let mut set = |doc: &mut pdfcraft_cos::Document, value: &FieldValue| match cx.js.as_mut() {
+ Some(js) => pdfcraft_forms::set_value_with(doc, name, value, js),
+ None => pdfcraft_forms::set_value(doc, name, value),
+ };
+ match set(doc, value) {
+ Ok(()) => {}
+ // A date the field's format doesn't read may be typed by another of an XFA date
+ // field's patterns: it is kept in the first. Only a format refusal is tried
+ // again: it comes before any of the field's scripts run, so they run once.
+ Err(refused @ pdfcraft_forms::FormError::Format(_)) => match xfa::typed_date(doc, cx.xfa.as_deref(), name, value) {
+ Some(typed) => set(doc, &typed)?,
+ None => return Err(refused.into()),
+ },
+ Err(refused) => return Err(refused.into()),
+ }
+ }
Edit::ApplyScriptChanges { changes } => match cx.js.as_mut() {
Some(js) => pdfcraft_forms::apply_script_changes(doc, changes, js)?,
None => pdfcraft_forms::apply_script_changes(doc, changes, &mut pdfcraft_forms::NoScripts)?,
@@ -2740,6 +2878,28 @@ fn run_edit(doc: &mut pdfcraft_cos::Document, edit: &Edit, cx: &mut EditCtx) ->
let (image, _) = embed_image(doc, name, bytes)?;
pdfcraft_edit::update_content(doc, *page, *index, &AddedContent::Image(pdfcraft_edit::AddedImage { image, ..old }))?;
}
+ Edit::PasteContent { page, content, file } => {
+ let content = match content {
+ AddedContent::Text(_) => content.clone(),
+ AddedContent::Image(img) => {
+ let Some((name, bytes)) = file else {
+ return Err(EditError::Edit(pdfcraft_edit::EditError::Invalid("a pasted image needs its picture".into())));
+ };
+ // The same picture in this document (copied here, pasted here before, or an
+ // identical file): drawn again from the one image object rather than stored twice.
+ let image = if copy_image::is_picture(doc, img.image, bytes) {
+ img.image
+ } else {
+ match copy_image::added_picture(doc, bytes) {
+ Some(image) => image,
+ None => embed_image(doc, name, bytes)?.0,
+ }
+ };
+ AddedContent::Image(pdfcraft_edit::AddedImage { image, ..img.clone() })
+ }
+ };
+ pdfcraft_edit::add_content(doc, *page, &content)?;
+ }
Edit::ApplyRedactions { pages } => {
cx.redaction_overlays = pdfcraft_redact::apply(doc, pages.as_deref())?.overlays;
}
@@ -2846,7 +3006,7 @@ fn run_edit(doc: &mut pdfcraft_cos::Document, edit: &Edit, cx: &mut EditCtx) ->
/// The comment list, read from the object graph (as `inspect` lists comments).
fn comment_list(doc: &pdfcraft_cos::Document) -> Vec<pdfcraft_render::Annotation> {
- pdfcraft_annot::summaries(doc)
+ let mut list: Vec<pdfcraft_render::Annotation> = pdfcraft_annot::summaries(doc)
.into_iter()
.map(|s| pdfcraft_render::Annotation {
page: s.page,
@@ -2857,6 +3017,8 @@ fn comment_list(doc: &pdfcraft_cos::Document) -> Vec<pdfcraft_render::Annotation
modified_raw: s.modified,
name: s.name,
in_reply_to: s.in_reply_to,
+ parent: s.parent,
+ grouped: s.grouped,
rect: s.rect,
color: s.color,
index: s.index,
@@ -2867,9 +3029,12 @@ fn comment_list(doc: &pdfcraft_cos::Document) -> Vec<pdfcraft_render::Annotation
fill_sign: s.fill_sign,
opacity: s.opacity,
width: s.width,
+ no_rotate: s.no_rotate,
points: s.points,
})
- .collect()
+ .collect();
+ pdfcraft_render::link_replies(&mut list);
+ list
}
/// Seconds to add to UTC for local time (0 where unknown).
@@ -2909,6 +3074,27 @@ fn renderer_password(bytes: &[u8]) -> String {
}
}
+/// The document as it may be written to a file (#3926, #3944): a copy without the values of text
+/// fields with the Password flag (or XFA `<passwordEdit/>` fields in the datasets), or `cos`
+/// itself when it holds none. ISO 32000-2 §12.7.5.3, Table 231 (a note to the Password flag):
+/// "it is imperative that PDF processors never store the value of the text field in the PDF file
+/// if this flag is set". The open document keeps them in memory.
+fn writable(cos: &pdfcraft_cos::Document) -> Result<std::borrow::Cow<'_, pdfcraft_cos::Document>, EditError> {
+ let has_form_pw = pdfcraft_forms::has_password_values(cos);
+ let has_xfa_pw = pdfcraft_xfa::has_password_values(cos);
+ if !has_form_pw && !has_xfa_pw {
+ return Ok(std::borrow::Cow::Borrowed(cos));
+ }
+ let mut copy = cos.clone();
+ if has_form_pw {
+ pdfcraft_forms::clear_password_values(&mut copy).map_err(|e| EditError::Write(e.to_string()))?;
+ }
+ if has_xfa_pw {
+ pdfcraft_xfa::clear_password_values(&mut copy).map_err(|e| EditError::Write(e.to_string()))?;
+ }
+ Ok(std::borrow::Cow::Owned(copy))
+}
+
/// The last-resort guard (AGENTS.md §4): run `f`, turning a panic that escapes it into an error
/// message, so one bad file or edit can't take the app and its other documents down. It is a
/// safety net for bugs, not a substitute for returning errors.
@@ -3670,7 +3856,7 @@ impl Session {
name: String,
path: Option<String>,
bytes: Arc<Vec<u8>>,
- info: DocInfo,
+ mut info: DocInfo,
cos: Result<Result<pdfcraft_cos::Document, pdfcraft_cos::CosError>, Box<dyn std::any::Any + Send>>,
render_password: Option<String>,
password: Option<&str>,
@@ -3702,6 +3888,15 @@ impl Session {
};
let sig_cache = Arc::new(pdfcraft_sign::DigestCache::default());
let signatures = editor.as_ref().map(|e| signatures_of(&e.cos, &bytes, trust, &sig_cache)).unwrap_or_default();
+ // The inspection reads only `/Info`; a file stating its title or author only in XMP still
+ // shows them (#2373).
+ if let Some(e) = &editor {
+ for (field, value) in info_fields(&mut info, &e.cos) {
+ if field.is_none() {
+ *field = value;
+ }
+ }
+ }
let display = display_bytes(editor.as_mut(), &bytes);
let renderer = RenderPool::new(display.clone(), render_threads(), config.clone());
let (form, adopted) = editor
@@ -4067,15 +4262,9 @@ impl Session {
editor.cos.bytes().clone()
};
if scope == Scope::Metadata {
- // Read the way the full inspection reads them (NULs and spaces trimmed, empty is
- // none), so editing one entry doesn't change how the others display.
- let info = |key| pdfcraft_organize::info(&editor.cos, key).map(|v| v.trim_matches('\0').trim().to_string()).filter(|v| !v.is_empty());
- doc.info.title = info("Title");
- doc.info.author = info("Author");
- doc.info.subject = info("Subject");
- doc.info.keywords = info("Keywords");
- doc.info.creator = info("Creator");
- doc.info.producer = info("Producer");
+ for (field, value) in info_fields(&mut doc.info, &editor.cos) {
+ *field = value;
+ }
doc.info.custom = pdfcraft_organize::custom_info(&editor.cos);
doc.info.file_size = bytes.len();
#[cfg(test)]
@@ -4136,10 +4325,22 @@ impl Session {
/// Which derived lists a content-only edit can change: added content (`None`, from
/// undo/redo, re-reads both: always correct, rarely paid).
fn content_refresh_lists(edit: Option<&Edit>) -> (bool, bool) {
+ if let Some(Edit::Batch { edits, .. }) = edit {
+ // A batch of content edits (from a script, say) changes what its parts change.
+ return edits.iter().fold((false, false), |(added, marks), part| {
+ let (a, m) = Self::content_refresh_lists(Some(part));
+ (added || a, marks || m)
+ });
+ }
let touches_added = edit.is_none_or(|e| {
matches!(
e,
- Edit::AddText { .. } | Edit::AddImage { .. } | Edit::UpdateContent { .. } | Edit::DeleteContent { .. } | Edit::ReplaceImage { .. }
+ Edit::AddText { .. }
+ | Edit::AddImage { .. }
+ | Edit::UpdateContent { .. }
+ | Edit::DeleteContent { .. }
+ | Edit::ReplaceImage { .. }
+ | Edit::PasteContent { .. }
) || matches!(e, Edit::MoveObjects { objects, .. } if objects.iter().any(|o| o.kind == ObjectKind::Added))
});
let touches_marks = edit.is_none_or(|e| {
@@ -4236,6 +4437,13 @@ impl Session {
}
}
note_warnings(&mut info.warnings, &doc.xfa_warnings);
+ // As in `build_document`: the inspection reads only `/Info`, so fields stated only in XMP
+ // are filled in again after every full refresh.
+ for (field, value) in info_fields(&mut info, &editor.cos) {
+ if field.is_none() {
+ *field = value;
+ }
+ }
doc.info = info;
doc.fonts_stale = false;
let mut form = pdfcraft_forms::fields(&editor.cos);
@@ -4269,17 +4477,19 @@ impl Session {
if !editor.cos.is_modified() && on_saved && (!editor.cos.reconstructed() || doc.is_signed()) {
return Ok(editor.saved.clone());
}
- let opts = SaveOptions { mod_date: self.now().map(pdfcraft_cos::pdf_date), ..SaveOptions::default() };
+ // What the user removed again before saving (a cleared redaction mark) stays out of the file.
+ let opts = SaveOptions { mod_date: self.now().map(pdfcraft_cos::pdf_date), drop_unlinked: true, ..SaveOptions::default() };
// A restored snapshot can be based on an earlier revision. Append to the last saved
// file so that revision stays in the chain. A full rewrite (redaction, new encryption,
// a reconstructed file) still writes the current graph on its own.
let rewrite = editor.cos.full_save_required() || editor.cos.encryption_changed() || editor.cos.revisions().is_empty();
+ let cos = writable(&editor.cos)?;
guard(|| {
if on_saved || rewrite {
- write_incremental(&editor.cos, &opts)
+ write_incremental(&cos, &opts)
} else {
let mut base = pdfcraft_cos::Document::open_with_password(editor.saved.clone(), editor.saved_keys.reopen.as_deref())?;
- base.overlay_changes_from(&editor.cos)?;
+ base.overlay_changes_from(&cos)?;
write_incremental(&base, &opts)
}
})
@@ -4296,7 +4506,8 @@ impl Session {
}
let editor = doc.editor.as_ref().ok_or_else(|| EditError::ReadOnly(doc.read_only_reason.clone().unwrap_or_default()))?;
let opts = SaveOptions { mod_date: self.now().map(pdfcraft_cos::pdf_date), ..SaveOptions::default() };
- guard(|| write_full(&editor.cos, &opts)).map_err(EditError::Write)?.map(Arc::new).map_err(|e| EditError::Write(e.to_string()))
+ let cos = writable(&editor.cos)?;
+ guard(|| write_full(&cos, &opts)).map_err(EditError::Write)?.map(Arc::new).map_err(|e| EditError::Write(e.to_string()))
}
/// Check that `bytes`, from [`Self::save_bytes`] or [`Self::save_full_bytes`], reopen as this
@@ -4317,8 +4528,15 @@ impl Session {
// An encrypted file needs the password it is protected with now (the owner
// password when known, so saving never downgrades this session's rights).
let keys = editor.keys.clone();
+ // The saved file carries no Password-field values (#3943, #3944); the open document keeps them.
+ let typed = pdfcraft_forms::password_values(&editor.cos);
editor.cos =
pdfcraft_cos::Document::open_with_password(bytes.clone(), keys.reopen.as_deref()).map_err(|e| EditError::Reopen(e.to_string()))?;
+ pdfcraft_forms::restore_password_values(&mut editor.cos, &typed).map_err(|e| EditError::Reopen(e.to_string()))?;
+ if !typed.is_empty() && doc.info.xfa.is_some() {
+ let mut datasets = None;
+ let _ = xfa_sync_datasets(&mut editor.cos, doc.xfa_template.as_deref(), &mut datasets);
+ }
editor.saved = bytes;
editor.saved_keys = keys;
editor.unsaved_file = false;
@@ -4664,7 +4882,7 @@ impl Session {
pub fn combine_field_conflicts(&self, sources: &[CombineSource], passwords: &[Option<&str>]) -> Vec<Vec<(String, String)>> {
let docs: Vec<Option<pdfcraft_cos::Document>> =
sources.iter().enumerate().map(|(i, (n, b, _))| open_source_with(n, b, passwords.get(i).copied().flatten()).ok()).collect();
- let refs: Vec<&pdfcraft_cos::Document> = docs.iter().filter_map(|d| d.as_ref()).collect();
+ let refs: Vec<&pdfcraft_cos::Document> = docs.iter().filter_map(Option::as_ref).collect();
let mut opened = pdfcraft_organize::combine_field_conflicts(&refs).into_iter();
// One preview per source, in step with it: a file that cannot be opened has none.
docs.iter().map(|d| if d.is_some() { opened.next().unwrap_or_default() } else { Default::default() }).collect()
@@ -4863,7 +5081,7 @@ impl Session {
let numbers: Vec<Option<f32>> = numbers.iter().map(|n| n.map(|n| n as f32)).collect();
pdfcraft_render::DestView::from_operands(Some(&kind), &numbers)
});
- BookmarkRow { path: b.path, title: b.title, open: b.open, page: b.page, view }
+ BookmarkRow { path: b.path, title: b.title, open: b.open, page: b.page, view, color: b.color, italic: b.italic, bold: b.bold }
})
.collect();
return Some(BookmarkPage { rows, next: page.next, truncated: false });
@@ -4917,9 +5135,12 @@ impl Session {
}
/// [`Self::write_new`] without the check, for bytes nobody writes: measuring a part's size.
+ /// Like a save, a new file never carries a typed Password-field value (#3926): Extract and
+ /// Split copy the fields of the pages they take.
fn write_unchecked(&self, doc: &pdfcraft_cos::Document) -> Result<Arc<Vec<u8>>, EditError> {
let opts = SaveOptions { mod_date: self.now().map(pdfcraft_cos::pdf_date), ..SaveOptions::default() };
- write_full(doc, &opts).map(Arc::new).map_err(|e| EditError::Write(e.to_string()))
+ let doc = writable(doc)?;
+ write_full(&doc, &opts).map(Arc::new).map_err(|e| EditError::Write(e.to_string()))
}
/// Whether a changed document still needs a recovery snapshot. This does not consume it.
@@ -4933,12 +5154,24 @@ impl Session {
let mut out = Vec::new();
for d in &mut self.docs {
if d.dirty && d.generation != d.snapshot_generation {
+ // The working bytes hold typed Password-field values (#3926, #3944): a recovery file
+ // is written from a copy without them, and none is written if that copy fails.
+ let bytes =
+ match d.editor.as_ref().filter(|e| pdfcraft_forms::has_password_values(&e.cos) || pdfcraft_xfa::has_password_values(&e.cos)) {
+ Some(e) => match writable(&e.cos)
+ .and_then(|c| write_incremental(&c, &SaveOptions::default()).map_err(|e| EditError::Write(e.to_string())))
+ {
+ Ok(b) => Arc::new(b),
+ Err(_) => continue,
+ },
+ None => d.bytes.clone(),
+ };
d.snapshot_generation = d.generation;
out.push(RecoverySnapshot {
doc: d.id,
name: d.name.clone(),
path: d.path.clone(),
- bytes: d.bytes.clone(),
+ bytes,
encrypted: d.info.encrypted || d.editor.as_ref().is_some_and(|e| e.cos.security().is_some()),
});
}
@@ -5092,7 +5325,9 @@ impl Session {
if opts.date.is_empty() {
opts.date = self.signing_date();
}
- Ok(Arc::new(pdfcraft_sign::sign(&editor.cos, id, &opts)?))
+ // A typed Password-field value is not signed into the file (#3926), as it isn't saved.
+ let cos = writable(&editor.cos)?;
+ Ok(Arc::new(pdfcraft_sign::sign(&cos, id, &opts)?))
}
/// [`Session::sign`], embedding an RFC 3161 signature timestamp (PAdES B-T) produced by
@@ -5109,7 +5344,8 @@ impl Session {
if opts.date.is_empty() {
opts.date = self.signing_date();
}
- let signed = Arc::new(pdfcraft_sign::sign_with_timestamp(&editor.cos, id, &opts, tsa)?);
+ let cos = writable(&editor.cos)?;
+ let signed = Arc::new(pdfcraft_sign::sign_with_timestamp(&cos, id, &opts, tsa)?);
// Checked like a save before anyone writes it (#2166).
self.check_save(doc, &signed)?;
Ok(signed)
@@ -5121,7 +5357,8 @@ impl Session {
let d = self.get(doc).ok_or(EditError::NoDocument)?;
let editor = d.editor.as_ref().ok_or_else(|| EditError::ReadOnly(d.read_only_reason.clone().unwrap_or_default()))?;
let date = if date.is_empty() { self.signing_date() } else { date };
- let stamped = Arc::new(pdfcraft_sign::timestamp_document(&editor.cos, tsa, &date)?);
+ let cos = writable(&editor.cos)?;
+ let stamped = Arc::new(pdfcraft_sign::timestamp_document(&cos, tsa, &date)?);
self.check_save(doc, &stamped)?;
Ok(stamped)
}
@@ -5131,7 +5368,8 @@ impl Session {
pub fn embed_ltv(&self, doc: DocId, evidence: &pdfcraft_sign::dss::Evidence) -> Result<Arc<Vec<u8>>, EditError> {
let d = self.get(doc).ok_or(EditError::NoDocument)?;
let editor = d.editor.as_ref().ok_or_else(|| EditError::ReadOnly(d.read_only_reason.clone().unwrap_or_default()))?;
- let embedded = Arc::new(pdfcraft_sign::dss::embed(&editor.cos, evidence)?);
+ let cos = writable(&editor.cos)?;
+ let embedded = Arc::new(pdfcraft_sign::dss::embed(&cos, evidence)?);
self.check_save(doc, &embedded)?;
Ok(embedded)
}
@@ -5189,6 +5427,29 @@ fn embed_image(
pdfcraft_create::image_xobject(doc, name, bytes)
}
+/// The largest box of `w`:`h` shape inside `rect`, centred in it: a stamp's picture keeps its
+/// shape in a box of any other shape. A box that is already that shape (to within rounding) is
+/// kept exactly, so callers that size it themselves get their box back. An empty or non-finite
+/// box, or a picture with no size, is returned as it is, for the annotation's own check to refuse.
+fn fit_picture(rect: [f64; 4], w: f64, h: f64) -> [f64; 4] {
+ if !rect.iter().all(|v| v.is_finite()) {
+ return rect;
+ }
+ let rect = [rect[0].min(rect[2]), rect[1].min(rect[3]), rect[0].max(rect[2]), rect[1].max(rect[3])];
+ let (bw, bh) = (rect[2] - rect[0], rect[3] - rect[1]);
+ let usable = |v: f64| v.is_finite() && v > 0.0;
+ if !(usable(bw) && usable(bh) && usable(w) && usable(h)) {
+ return rect;
+ }
+ let k = (bw / w).min(bh / h);
+ let (fw, fh) = (w * k, h * k);
+ if (fw - bw).abs() <= bw * 1e-9 && (fh - bh).abs() <= bh * 1e-9 {
+ return rect;
+ }
+ let (cx, cy) = (rect[0] + bw / 2.0, rect[1] + bh / 2.0);
+ [cx - fw / 2.0, cy - fh / 2.0, cx + fw / 2.0, cy + fh / 2.0]
+}
+
/// Bring a mark's picture into `doc`: a PDF page as a form XObject, or an image.
fn mark_source(doc: &mut pdfcraft_cos::Document, f: &MarkFile) -> Result<pdfcraft_edit::MarkSource, EditError> {
let head = &f.bytes[..f.bytes.len().min(1024)];
@@ -5276,24 +5537,30 @@ pub fn comment_kind(a: &pdfcraft_render::Annotation) -> &str {
/// pop-ups; the number is the comment's position on its page.
pub fn comment_summary(name: &str, all: &[pdfcraft_render::Annotation], sort: SummarySort) -> String {
use std::fmt::Write;
- let top: Vec<&pdfcraft_render::Annotation> = all.iter().filter(|a| a.in_reply_to.is_none() && a.state.is_none()).collect();
+ let top: Vec<&pdfcraft_render::Annotation> = all.iter().filter(|a| a.is_comment()).collect();
+ // Each reply under the annotation its `/IRT` points at, in document order, gathered once.
+ type Children<'a> = std::collections::HashMap<(usize, usize), Vec<&'a pdfcraft_render::Annotation>>;
+ let mut children = Children::new();
+ for r in all.iter().filter(|r| r.state.is_none()) {
+ if let Some(parent) = r.parent {
+ children.entry(parent).or_default().push(r);
+ }
+ }
// Write a comment's replies, indenting each level. A reply to a reply keeps its `/IRT` on the
// direct parent, so following one level would leave the deeper replies out of the summary.
- fn write_replies(out: &mut String, all: &[pdfcraft_render::Annotation], parent: &str, depth: usize) {
+ fn write_replies(out: &mut String, children: &Children<'_>, parent: &pdfcraft_render::Annotation, depth: usize) {
use std::fmt::Write;
if depth > 64 {
return;
}
- for r in all.iter().filter(|r| r.state.is_none() && r.in_reply_to.as_deref() == Some(parent)) {
+ for r in children.get(&(parent.page, parent.index)).into_iter().flatten() {
let indent = " ".repeat(depth + 1);
let _ =
writeln!(out, "{indent}Author: {} Subject: Reply Date: {}", r.author.as_deref().unwrap_or(""), r.modified.as_deref().unwrap_or(""));
for line in r.contents.as_deref().unwrap_or("").lines() {
let _ = writeln!(out, "{indent}{line}");
}
- if let Some(nm) = r.name.as_deref() {
- write_replies(out, all, nm, depth + 1);
- }
+ write_replies(out, children, r, depth + 1);
}
}
let mut numbered: Vec<(usize, &pdfcraft_render::Annotation)> = Vec::new();
@@ -5332,9 +5599,7 @@ pub fn comment_summary(name: &str, all: &[pdfcraft_render::Annotation], sort: Su
if let Some(c) = a.contents.as_deref().filter(|c| !c.is_empty()) {
let _ = writeln!(out, "{c}");
}
- if let Some(nm) = a.name.as_deref() {
- write_replies(&mut out, all, nm, 0);
- }
+ write_replies(&mut out, &children, a, 0);
out.push('\n');
}
out
diff --git a/crates/engine/src/links.rs b/crates/engine/src/links.rs
index 4902d72..9b1c497 100644
--- a/crates/engine/src/links.rs
+++ b/crates/engine/src/links.rs
@@ -176,7 +176,7 @@ pub fn remote_document_path_is_absolute(raw: &str) -> bool {
/// Resolve a PDF remote-Go-To file specification to a local path without opening it.
/// Relative paths are based on the source document, which should be an absolute path; an
/// in-memory source has no fallback to CWD. URLs (including `file:`), network and device paths are
-/// refused ([`craft_docpath::resolve`]).
+/// refused ([`craft_docpath::resolve_absolute`]).
pub fn resolve_remote_document_path(source: Option<&Path>, raw: &str) -> Result<PathBuf, RemoteDocumentPathError> {
if raw.is_empty() || raw.trim().is_empty() {
return Err(RemoteDocumentPathError::Empty);
@@ -197,12 +197,14 @@ pub fn resolve_remote_document_path(source: Option<&Path>, raw: &str) -> Result<
return Err(RemoteDocumentPathError::NotLocal(craft_docpath::Refused::Url));
}
}
- let path = craft_docpath::resolve(raw, source).map_err(RemoteDocumentPathError::NotLocal)?;
- // A relative result would be read against the working directory.
- if !path.is_absolute() {
- return Err(RemoteDocumentPathError::MissingSourcePath);
- }
- Ok(path)
+ craft_docpath::resolve_absolute(raw, source).map_err(|r| match r {
+ // A path that resolves but not to an absolute one needed a source with an absolute path. With
+ // such a source, it is a path this platform cannot open (`C:\x.pdf` on Unix).
+ craft_docpath::Refused::Invalid if !source.is_some_and(Path::is_absolute) && craft_docpath::resolve(raw, source).is_ok() => {
+ RemoteDocumentPathError::MissingSourcePath
+ }
+ r => RemoteDocumentPathError::NotLocal(r),
+ })
}
/// Largest linked PDF a GoToR link may open (1 GiB, the largest size the large-file work measures).
@@ -512,6 +514,8 @@ mod tests {
assert_eq!(resolve(Some(source), "/manual/target.pdf").as_deref(), Ok(Path::new("/manual/target.pdf")));
assert_eq!(resolve(None, "target.pdf"), Err(E::MissingSourcePath));
assert_eq!(resolve(Some(Path::new("source.pdf")), "target.pdf"), Err(E::MissingSourcePath), "a relative source is not used");
+ #[cfg(unix)]
+ assert_eq!(resolve(Some(source), "C:\\x.pdf"), Err(E::NotLocal(craft_docpath::Refused::Invalid)), "a Windows path on Unix needs no source");
assert_eq!(resolve(Some(source), ""), Err(E::Empty));
assert_eq!(resolve(Some(source), " "), Err(E::Empty));
for url in
@@ -520,6 +524,8 @@ mod tests {
assert!(matches!(resolve(Some(source), url), Err(E::NotLocal(_))), "{url}");
}
assert_eq!(resolve(Some(source), "folder/hidden\u{200B}.pdf"), Err(E::Hidden));
+ #[cfg(windows)]
+ assert_eq!(resolve(Some(source), "folder/a:b.pdf"), Err(E::NotLocal(craft_docpath::Refused::Invalid)));
assert_eq!(resolve(Some(source), &"a".repeat(super::MAX_REMOTE_DOCUMENT_PATH_BYTES + 1)), Err(E::TooLong));
}
diff --git a/crates/engine/src/ocr.rs b/crates/engine/src/ocr.rs
index dcd4142..6b9869c 100644
--- a/crates/engine/src/ocr.rs
+++ b/crates/engine/src/ocr.rs
@@ -24,6 +24,11 @@ pub struct OcrSettings {
/// text" and skips them). When `false`, such pages are read too (a picture on a page that
/// also has text, #1028) and only the words that aren't already there are added.
pub skip_text_pages: bool,
+ /// What counts as the page's text when `skip_text_pages` is on: only its own (page content
+ /// and form fields). Comments and text boxes are left out, and are not drawn into the picture
+ /// that is read, so a scan with a few comments on it is still a scan. `false`: everything
+ /// the page shows.
+ pub native_text_only: bool,
}
/// A recognised word whose box is at least this much covered by the page's own text is that
@@ -51,7 +56,7 @@ fn covered(word: [f32; 4], text: &[[f32; 4]]) -> f32 {
impl Default for OcrSettings {
fn default() -> Self {
- OcrSettings { dpi: 300.0, language: "en".into(), skip_text_pages: true }
+ OcrSettings { dpi: 300.0, language: "en".into(), skip_text_pages: true, native_text_only: false }
}
}
@@ -75,7 +80,7 @@ impl OcrPage {
/// The recogniser, loaded once (it takes a moment) and shared.
pub fn engine() -> Result<Arc<Ocr>, String> {
static OCR: Mutex<Option<Arc<Ocr>>> = Mutex::new(None);
- let mut slot = OCR.lock().unwrap_or_else(|e| e.into_inner());
+ let mut slot = OCR.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
if let Some(o) = slot.as_ref() {
return Ok(o.clone());
}
@@ -105,7 +110,8 @@ impl OcrJob {
/// Read the pages. `progress(done, total)` is called before each page; returning `false`
/// stops (the pages read so far are returned).
pub fn run(self, ocr: &Ocr, mut progress: impl FnMut(usize, usize) -> bool) -> Vec<OcrPage> {
- let config = RenderConfig { password: self.password.as_deref().map(Arc::from), ..Default::default() };
+ let config =
+ RenderConfig { password: self.password.as_deref().map(Arc::from), hide_comments: self.settings.native_text_only, ..Default::default() };
let mut r = PageRenderer::new(self.bytes.clone(), config);
let mut out = Vec::new();
let total = self.pages.len();
diff --git a/crates/engine/src/optimizer.rs b/crates/engine/src/optimizer.rs
index ee8c957..42af737 100644
--- a/crates/engine/src/optimizer.rs
+++ b/crates/engine/src/optimizer.rs
@@ -68,7 +68,11 @@ impl Session {
cos: editor.cos.clone(),
settings: settings.clone(),
discard: discard.to_vec(),
- opts: SaveOptions { mod_date: self.now().map(pdfcraft_cos::pdf_date), ..SaveOptions::default() },
+ opts: SaveOptions {
+ mod_date: self.now().map(pdfcraft_cos::pdf_date),
+ object_streams: settings.effective_object_streams(),
+ ..SaveOptions::default()
+ },
})
}
}
@@ -83,6 +87,9 @@ impl OptimizeJob {
fn work(self, progress: &mut dyn FnMut(OptimizeStage) -> bool) -> Result<Optimized, EditError> {
let OptimizeJob { mut cos, settings, discard, opts } = self;
+ // Like every file written, without the values of Password-flag fields (#3926, #3944).
+ pdfcraft_forms::clear_password_values(&mut cos).map_err(|e| EditError::Write(e.to_string()))?;
+ pdfcraft_xfa::clear_password_values(&mut cos).map_err(|e| EditError::Write(e.to_string()))?;
let mut step = |stage| if progress(stage) { Ok(()) } else { Err(EditError::Cancelled) };
step(OptimizeStage::Discarding)?;
let discarded = if discard.is_empty() { Vec::new() } else { pdfcraft_redact::sanitize::remove_hidden(&mut cos, &discard)? };
diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs
index 7e1a8ec..ee9dc47 100644
--- a/crates/engine/src/tests.rs
+++ b/crates/engine/src/tests.rs
@@ -196,6 +196,47 @@ fn rubber_stamps_point_left_as_displayed_on_rotated_pages() {
}
}
+/// #2583, #1869: a sticky note placed on a turned page is drawn upright, with its top-left as
+/// displayed where it was placed (the corner its `/Rect` keeps, as the NoRotate flag it is saved
+/// with asks), exactly as on an unturned page, including after save. The comment list's
+/// `shown_rect`, which the UI hit-tests, is that square.
+#[test]
+fn sticky_notes_stay_upright_where_they_are_placed_on_rotated_pages() {
+ // The displayed 20 × 20 pt square whose top-left is (100, 40), in device pixels at scale 2.
+ let crop = |rendered: &pdfcraft_render::RenderedPage| -> Vec<[u8; 4]> {
+ (80..120).flat_map(|y| (200..240).map(move |x| (x, y))).map(|(x, y)| stamp_pixel(rendered, x, y)).collect()
+ };
+ let mut upright = None;
+ for degrees in [0, 90, 180, 270] {
+ let (mut session, id) = rotated_blank(degrees);
+ let info = session.get(id).unwrap().info.pages[0].clone();
+ let [x, y] = info.view_to_user(100.0, 40.0);
+ let shape = Shape::Note { at: [f64::from(x), f64::from(y)], icon: NoteIcon::Comment };
+ let style = Style::default_for(&shape);
+ session.apply(id, Edit::AddAnnotation(NewAnnotation { page: 0, style, shape, contents: "Turned".into(), author: "Test".into() })).unwrap();
+ let mut check = |session: &Session, id: DocId| {
+ let doc = session.get(id).unwrap();
+ let info = &doc.info.pages[0];
+ let note = &doc.info.annotations[0];
+ assert!(note.no_rotate, "rotation {degrees}: notes are saved NoRotate");
+ let shown = note.shown_rect(info.rotation);
+ let (a, b) = (info.user_to_view(shown[0], shown[1]), info.user_to_view(shown[2], shown[3]));
+ let shown = [a[0].min(b[0]), a[1].min(b[1]), a[0].max(b[0]), a[1].max(b[1])];
+ assert!(shown.iter().zip([100.0, 40.0, 120.0, 60.0]).all(|(v, w)| (v - w).abs() < 0.01), "rotation {degrees}: shown at {shown:?}");
+ let icon = crop(&render_page(session, id));
+ let reference = upright.get_or_insert_with(|| icon.clone());
+ assert!(reference.iter().filter(|c| c.iter().any(|v| *v < 200)).count() > 100, "the note's icon is drawn");
+ let off = icon.iter().zip(reference.iter()).filter(|(a, b)| a.iter().zip(b.iter()).any(|(a, b)| a.abs_diff(*b) > 48)).count();
+ assert!(off <= 8, "rotation {degrees}: {off} of the icon's {} pixels differ from the unturned page's", icon.len());
+ };
+ check(&session, id);
+ let saved = session.save_bytes(id).unwrap();
+ let mut reopened = Session::new().with_clock(|| 1_700_000_000);
+ let again = reopened.open("drawing.pdf", None, saved, None).unwrap();
+ check(&reopened, again);
+ }
+}
+
/// #2392: Fill & Sign marks are drawn as displayed on every page rotation, including after save:
/// a checkmark's long stroke rises to the right, and a line runs across.
#[test]
@@ -373,6 +414,31 @@ fn explicit_image_stamps_keep_displayed_orientation_on_rotated_pages() {
}
}
+/// A visible digital signature reads upright as the page is displayed on every page rotation:
+/// its picture, alone in the box, shows its quadrants where they are in the image.
+#[test]
+fn visible_signatures_keep_displayed_orientation_on_rotated_pages() {
+ let p12 = std::fs::read(concat!(env!("CARGO_MANIFEST_DIR"), "/../sign/tests/data/ec-p256.p12")).unwrap();
+ let digital_id = sign::pkcs12::open(&p12, "test").unwrap();
+ let picture = image::load_from_memory(&quadrant_png()).unwrap().to_rgba8();
+ let graphic = sign::Graphic::Image { width: picture.width(), height: picture.height(), rgba: Arc::new(picture.into_raw()) };
+ let bare = sign::Appearance { name: false, date: false, reason: false, location: false, distinguished_name: false, labels: false };
+ for degrees in [0, 90, 180, 270] {
+ // After the test certificate's start date (2026-10-02).
+ let mut session = Session::new().with_clock(|| 1_800_000_000);
+ let blank = session.create_blank(200.0, 300.0, 1).unwrap();
+ let id = session.open_new("contract.pdf", blank).unwrap();
+ session.apply(id, Edit::RotatePages { pages: vec![0], degrees }).unwrap();
+ let info = session.get(id).unwrap().info.pages[0].clone();
+ // The picture's proportions (2:1) as displayed, centred at (100, 100).
+ let rect = displayed_rect(&info, 100.0, 100.0, 80.0, 40.0);
+ let opts = SignOptions { page: 0, rect: Some(rect), graphic: Some(graphic.clone()), appearance: bare.clone(), ..SignOptions::default() };
+ let signed = session.sign(id, &digital_id, opts).unwrap();
+ let reopened = session.open("signed.pdf", None, signed, None).unwrap();
+ assert_upright_quadrants(&session, reopened, degrees);
+ }
+}
+
/// #1398: a PDF page used as a stamp stays upright, at its natural size and in an explicit box.
#[test]
fn pdf_page_stamps_keep_displayed_orientation_on_rotated_pages() {
@@ -405,6 +471,48 @@ fn pdf_page_stamps_keep_displayed_orientation_on_rotated_pages() {
}
}
+/// #4077: a PDF page stamped into a box of another shape is fitted inside it, keeping its shape
+/// and centred, and stays vector: a form XObject, not a picture of it.
+#[test]
+fn pdf_page_stamps_fit_inside_an_explicit_box() {
+ let bytes = Arc::new(half_red_page());
+ let mut session = Session::new().with_clock(|| 1_700_000_000);
+ let blank = session.create_blank(595.0, 842.0, 1).unwrap();
+ let id = session.open_new("text.pdf", blank).unwrap();
+ // 483 pt wide (a text column) and 300 pt tall: the 80 × 40 page is 483 × 241.5, centred.
+ let stamp = |rect| Edit::AddCustomStamp {
+ page: 0,
+ rect,
+ name: "Diagram".into(),
+ file: MarkFile { name: "diagram.pdf".into(), bytes: bytes.clone(), page: 0 },
+ author: "Test".into(),
+ };
+ session.apply(id, stamp([56.0, 400.0, 539.0, 700.0])).unwrap();
+ assert_eq!(session.get(id).unwrap().info.annotations[0].rect, [56.0, 429.25, 539.0, 670.75]);
+ // A box too tall and narrow: the width limits it, and it is centred vertically.
+ session.apply(id, stamp([100.0, 100.0, 140.0, 300.0])).unwrap();
+ assert_eq!(session.get(id).unwrap().info.annotations[1].rect, [100.0, 190.0, 140.0, 210.0]);
+
+ let doc = pdfcraft_cos::Document::open(session.save_bytes(id).unwrap()).unwrap();
+ let page = &pdfcraft_model::pages(&doc)[0];
+ let annots = doc.resolve(page.dict.get(b"Annots").unwrap());
+ let first = annots.as_array().unwrap()[0].as_ref().unwrap();
+ let annot = doc.get(first);
+ let annot = annot.as_dict().unwrap();
+ let pdfcraft_cos::Object::Stream(picture) = doc.get(annot.reference(b"PCPicture").unwrap()).as_ref().clone() else {
+ panic!("the picture is a stream")
+ };
+ assert_eq!(picture.dict.name(b"Subtype"), Some(&b"Form"[..]), "the page is kept as a form XObject");
+ let ap = doc.resolve(annot.get(b"AP").unwrap());
+ let pdfcraft_cos::Object::Stream(normal) = doc.get(ap.as_dict().unwrap().reference(b"N").unwrap()).as_ref().clone() else {
+ panic!("an appearance stream")
+ };
+ let bbox: Vec<f64> = normal.dict.get(b"BBox").unwrap().as_array().unwrap().iter().filter_map(pdfcraft_cos::Object::as_f64).collect();
+ assert_eq!(bbox, [56.0, 429.25, 539.0, 670.75]);
+ let content = String::from_utf8(normal.decoded().unwrap().to_vec()).unwrap();
+ assert!(content.contains("/Pic Do") && !content.contains("BI"), "{content}");
+}
+
fn page_texts(s: &Session, id: DocId) -> Vec<String> {
let doc = s.get(id).unwrap();
let config = pdfcraft_render::RenderConfig { password: doc.password.as_deref().map(Arc::from), ..Default::default() };
@@ -425,6 +533,38 @@ impl RenderRequestFor {
}
}
+/// A file with its title and author only in XMP shows them in the document information and in
+/// Document Properties ▸ Description (#2373).
+#[test]
+fn document_information_stated_only_in_xmp_is_shown() {
+ let mut cos = pdfcraft_cos::Document::open(Arc::new(fixture(1))).unwrap();
+ let xmp = "<x:xmpmeta xmlns:x=\"adobe:ns:meta/\"><rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\">\
+ <rdf:Description rdf:about=\"\" xmlns:dc=\"http://purl.org/dc/elements/1.1/\">\
+ <dc:title><rdf:Alt><rdf:li xml:lang=\"x-default\">Quarterly report</rdf:li></rdf:Alt></dc:title>\
+ <dc:creator><rdf:Seq><rdf:li>Ada</rdf:li></rdf:Seq></dc:creator></rdf:Description></rdf:RDF></x:xmpmeta>";
+ let mut dict = pdfcraft_cos::Dict::new();
+ dict.set(b"Type".to_vec(), pdfcraft_cos::Object::name("Metadata"));
+ dict.set(b"Subtype".to_vec(), pdfcraft_cos::Object::name("XML"));
+ let m = cos.add(pdfcraft_cos::Object::Stream(pdfcraft_cos::Stream::from_raw(dict, xmp.as_bytes().to_vec())));
+ let root = cos.root().unwrap();
+ cos.update_dict(root, |c| c.set(b"Metadata".to_vec(), pdfcraft_cos::Object::Ref(m))).unwrap();
+ let bytes = pdfcraft_cos::write_full(&cos, &pdfcraft_cos::SaveOptions::default()).unwrap();
+ let mut s = Session::new();
+ let id = s.open("xmp.pdf", None, Arc::new(bytes), None).unwrap();
+ let doc = s.get(id).unwrap();
+ assert_eq!((doc.info.title.as_deref(), doc.info.author.as_deref(), doc.info.subject.as_deref()), (Some("Quarterly report"), Some("Ada"), None));
+ assert_eq!(doc.info_value("Title").as_deref(), Some("Quarterly report"));
+ assert_eq!(doc.info_value("Author").as_deref(), Some("Ada"));
+
+ // A full refresh (any structural edit, undo, redo) reads /Info again and must not lose them.
+ s.apply(id, Edit::RotatePages { pages: vec![0], degrees: 90 }).unwrap();
+ let doc = s.get(id).unwrap();
+ assert_eq!((doc.info.title.as_deref(), doc.info.author.as_deref()), (Some("Quarterly report"), Some("Ada")), "after an edit");
+ s.undo(id).unwrap();
+ let doc = s.get(id).unwrap();
+ assert_eq!((doc.info.title.as_deref(), doc.info.author.as_deref()), (Some("Quarterly report"), Some("Ada")), "after undo");
+}
+
#[test]
fn edits_update_view_data_and_mark_dirty() {
let (mut s, id) = session_with(3);
@@ -1911,6 +2051,34 @@ fn permissions_password_restricts_others_but_not_this_session() {
assert!(s2.get(id3).unwrap().allows_security_change());
}
+/// Converting to PDF/A takes the encryption off (PDF/A forbids it), so on an encrypted document
+/// it needs the same rights as removing security, not just the right to make changes (#3921).
+#[test]
+fn convert_to_pdfa_needs_the_owners_rights_on_an_encrypted_document() {
+ let pdfa = || Edit::ConvertPdfA { level: pdfcraft_preflight::Level::A2b };
+ let refused = Err(EditError::NotPermitted("removing the encryption, which PDF/A forbids"));
+ // Changes allowed; printing (bit 3) and copying (bit 5) withheld.
+ let bytes = protected("pw", "owner", !((1 << 2) | (1 << 4)));
+ let mut s = Session::new();
+ let id = s.open("x.pdf", None, bytes.clone(), Some("pw")).unwrap();
+ assert!(s.get(id).unwrap().allows_modification());
+ assert_eq!(s.apply(id, pdfa()), refused);
+ // Nor inside a batch.
+ let batch = Edit::Batch { label: "x".into(), edits: vec![Edit::RotatePages { pages: vec![0], degrees: 90 }, pdfa()] };
+ assert_eq!(s.apply(id, batch), refused);
+ // Nothing was applied: no undo step, and saving gives back the encrypted original.
+ assert!(s.get(id).unwrap().can_undo().is_none());
+ assert_eq!(s.save_bytes(id).unwrap().as_slice(), bytes.as_slice());
+ // The owner's password allows it, and the result is no longer encrypted.
+ let id2 = s.open("x.pdf", None, bytes, Some("owner")).unwrap();
+ s.apply(id2, pdfa()).unwrap();
+ let saved = s.save_bytes(id2).unwrap();
+ assert!(pdfcraft_cos::Document::open(saved).unwrap().trailer().get(b"Encrypt").is_none());
+ // An unencrypted document needs nothing more.
+ let (mut s, id) = session_with(1);
+ s.apply(id, pdfa()).unwrap();
+}
+
#[test]
fn combine_source_check_says_why_a_file_cannot_be_combined() {
let (mut s, id) = session_with(1);
@@ -2048,6 +2216,173 @@ fn form_fixture() -> Vec<u8> {
out
}
+/// Whether `needle` appears in `bytes`, or in any stream of the PDF they hold once decoded (so
+/// compressed object streams are searched too), as literal or hex string bytes.
+fn appears_in_pdf(bytes: &Arc<Vec<u8>>, needle: &str) -> bool {
+ let hex: String = needle.bytes().map(|b| format!("{b:02x}")).collect();
+ let forms = [needle.as_bytes().to_vec(), hex.clone().into_bytes(), hex.to_uppercase().into_bytes()];
+ let found = |hay: &[u8]| forms.iter().any(|f| hay.windows(f.len()).any(|w| w == f.as_slice()));
+ if found(bytes) {
+ return true;
+ }
+ let doc = pdfcraft_cos::Document::open(bytes.clone()).unwrap();
+ doc.object_numbers().into_iter().any(|num| match &*doc.get(pdfcraft_cos::ObjRef { num, generation: 0 }) {
+ pdfcraft_cos::Object::Stream(st) => st.decoded().is_ok_and(|d| found(&d)),
+ _ => false,
+ })
+}
+
+/// #3926: a value typed into a text field with the Password flag stays in the open document but
+/// is written to no file: Save, a full rewrite, Reduce File Size, a recovery snapshot, or a new
+/// file made from its pages (Extract, Split, Combine). ISO
+/// 32000-2 §12.7.5.3, Table 231, note to the Password flag: PDF processors should never store
+/// the value in the PDF file.
+#[test]
+fn password_field_values_are_kept_in_memory_but_written_to_no_file() {
+ let fixture = String::from_utf8(form_fixture()).unwrap().replace("/T (name)", "/T (name) /Ff 8192");
+ // Offsets shift by the inserted text; the parser rebuilds the cross-reference table.
+ let mut s = Session::new().with_clock(|| 1_700_000_000);
+ let id = s.open("form.pdf", None, Arc::new(fixture.into_bytes()), None).unwrap();
+ s.apply(id, Edit::SetFieldValue { name: "name".into(), value: FieldValue::Text("hunter2".into()) }).unwrap();
+ let field = s.get(id).unwrap().form.iter().find(|f| f.name == "name").cloned().unwrap();
+ assert!(field.has(pdfcraft_forms::flags::PASSWORD));
+ assert_eq!(field.value, vec!["hunter2".to_string()], "the open document keeps the value");
+ assert!(appears_in_pdf(&s.get(id).unwrap().bytes, "hunter2"), "the working bytes do hold it (the test can see it)");
+
+ let saved = s.save_bytes(id).unwrap();
+ assert!(!appears_in_pdf(&saved, "hunter2"), "Save");
+ // As Acrobat saves it (#3943 review): no default value, so an empty field whose appearance
+ // no longer shows how long the typed password was.
+ assert!(!appears_in_pdf(&saved, "*******"), "the typed length is not kept in the appearance");
+ assert!(!appears_in_pdf(&s.save_full_bytes(id).unwrap(), "hunter2"), "a full rewrite");
+ assert!(!appears_in_pdf(&s.reduced_bytes(id).unwrap().0, "hunter2"), "Reduce File Size");
+ let snaps = s.autosave_snapshots();
+ assert_eq!(snaps.len(), 1);
+ assert!(!appears_in_pdf(&snaps[0].bytes, "hunter2"), "the recovery snapshot");
+ // New files built from its pages too (#3943 review): Extract copies the fields of the pages it
+ // takes, and Split writes each part the same way.
+ let extracted = s.extract(id, &[0]).unwrap();
+ assert!(!appears_in_pdf(&extracted, "hunter2"), "Extract Pages");
+ assert!(!appears_in_pdf(&extracted, "*******"), "nor on the extracted page");
+ for (_, _, part) in s.split_by_size(id, 1).unwrap() {
+ assert!(!appears_in_pdf(&part, "hunter2"), "Split");
+ }
+ assert!(!appears_in_pdf(&s.combine(&[("form.pdf".into(), s.get(id).unwrap().bytes.clone())]).unwrap(), "hunter2"), "Combine");
+ // Reopened, the field is empty, as in any reader.
+ let mut t = Session::new();
+ let reopened = t.open("saved.pdf", None, saved, None).unwrap();
+ assert!(t.get(reopened).unwrap().form.iter().find(|f| f.name == "name").unwrap().value.iter().all(|v| v.is_empty()));
+}
+
+/// #3943 review: recording a save rebases editing on the saved file, which carries no Password
+/// value; the typed value stays in the open document all the same, and a later save still omits it.
+#[test]
+fn a_typed_password_value_survives_save_and_mark_saved() {
+ let fixture = String::from_utf8(form_fixture()).unwrap().replace("/T (name)", "/T (name) /Ff 8192");
+ let mut s = Session::new().with_clock(|| 1_700_000_000);
+ let id = s.open("form.pdf", None, Arc::new(fixture.into_bytes()), None).unwrap();
+ s.apply(id, Edit::SetFieldValue { name: "name".into(), value: FieldValue::Text("hunter2".into()) }).unwrap();
+ let saved = s.save_bytes(id).unwrap();
+ s.mark_saved(id, saved, Some("saved.pdf".into())).unwrap();
+ let value = |s: &Session| s.get(id).unwrap().form.iter().find(|f| f.name == "name").unwrap().value.clone();
+ assert_eq!(value(&s), ["hunter2"], "the open document keeps the value after Save");
+ assert!(!s.get(id).unwrap().dirty, "restoring it is not an unsaved change");
+ assert!(!appears_in_pdf(&s.save_bytes(id).unwrap(), "hunter2"), "the next save still omits it");
+}
+
+/// #3926 / #3943 review: signing writes the signed file from the same copy a save does, so a
+/// typed Password-field value is not signed into the file either.
+#[test]
+fn a_signed_file_carries_no_password_field_value() {
+ let p12 = std::fs::read(concat!(env!("CARGO_MANIFEST_DIR"), "/../sign/tests/data/ec-p256.p12")).unwrap();
+ let digital_id = sign::pkcs12::open(&p12, "test").unwrap();
+ let fixture = String::from_utf8(form_fixture()).unwrap().replace("/T (name)", "/T (name) /Ff 8192");
+ // After the test certificate's start date (2026-10-02).
+ let mut s = Session::new().with_clock(|| 1_800_000_000);
+ let id = s.open("form.pdf", None, Arc::new(fixture.into_bytes()), None).unwrap();
+ s.apply(id, Edit::SetFieldValue { name: "name".into(), value: FieldValue::Text("hunter2".into()) }).unwrap();
+ assert!(appears_in_pdf(&s.get(id).unwrap().bytes, "hunter2"), "the working bytes hold it");
+ let signed = s.sign(id, &digital_id, SignOptions { rect: None, ..SignOptions::default() }).unwrap();
+ assert!(!appears_in_pdf(&signed, "hunter2"), "the signed file");
+ assert!(!appears_in_pdf(&signed, "*******"), "nor the typed length");
+}
+
+/// #3944: a value typed into an XFA `<passwordEdit/>` field stays in the open document (both the
+/// widget and the live XFA datasets, even across multiple edits and across Save + `mark_saved`),
+/// but is written to no file — neither on the widget nor in the XFA datasets stream.
+#[test]
+fn xfa_password_field_values_are_not_saved_in_datasets_or_widgets() {
+ let xfa_pdf = pdfcraft_xfa::fixtures::shell(&pdfcraft_xfa::fixtures::fields_template(""));
+ let mut s = Session::new().with_clock(|| 1_700_000_000);
+ let id = s.open("xfa.pdf", None, Arc::new(xfa_pdf), None).unwrap();
+ let pin_name = s.get(id).unwrap().form.iter().find(|f| f.name.contains("pin")).unwrap().name.clone();
+
+ // Edit the password twice so an earlier edit's datasets stream could not linger in the overlay.
+ s.apply(id, Edit::SetFieldValue { name: pin_name.clone(), value: FieldValue::Text("secret1".into()) }).unwrap();
+ s.apply(id, Edit::SetFieldValue { name: pin_name.clone(), value: FieldValue::Text("hunter2".into()) }).unwrap();
+
+ let field = s.get(id).unwrap().form.iter().find(|f| f.name == pin_name).cloned().unwrap();
+ assert!(field.has(pdfcraft_forms::flags::PASSWORD));
+ assert_eq!(field.value, vec!["hunter2".to_string()], "the open document keeps the value");
+ assert!(appears_in_pdf(&s.get(id).unwrap().bytes, "hunter2"), "the working bytes hold the live datasets");
+ assert!(!appears_in_pdf(&s.get(id).unwrap().bytes, "secret1"), "the first edit's datasets stream was replaced in place");
+
+ let saved = s.save_bytes(id).unwrap();
+ for leak in ["hunter2", "secret1", "*******"] {
+ assert!(!appears_in_pdf(&saved, leak), "Save leaked {leak}");
+ assert!(!appears_in_pdf(&s.save_full_bytes(id).unwrap(), leak), "save_full_bytes leaked {leak}");
+ assert!(!appears_in_pdf(&s.reduced_bytes(id).unwrap().0, leak), "reduced_bytes leaked {leak}");
+ }
+ let snaps = s.autosave_snapshots();
+ assert_eq!(snaps.len(), 1);
+ for leak in ["hunter2", "secret1", "*******"] {
+ assert!(!appears_in_pdf(&snaps[0].bytes, leak), "autosave snapshot leaked {leak}");
+ }
+
+ // Reopening the saved file in a new session leaves the password field empty (it does not
+ // repopulate from the XFA datasets on open).
+ let mut t = Session::new();
+ let reopened = t.open("saved.pdf", None, saved.clone(), None).unwrap();
+ assert!(
+ t.get(reopened).unwrap().form.iter().find(|f| f.name == pin_name).unwrap().value.iter().all(|v| v.is_empty()),
+ "reopened XFA form must have an empty password field"
+ );
+
+ // Recording the save keeps the typed password in the open document (and its live datasets),
+ // while a subsequent save still omits it.
+ s.mark_saved(id, saved, Some("saved.pdf".into())).unwrap();
+ assert_eq!(s.get(id).unwrap().form.iter().find(|f| f.name == pin_name).unwrap().value, ["hunter2"]);
+ assert!(!s.get(id).unwrap().dirty);
+ for leak in ["hunter2", "secret1", "*******"] {
+ assert!(!appears_in_pdf(&s.save_bytes(id).unwrap(), leak), "save after mark_saved leaked {leak}");
+ }
+
+ // Undo past `mark_saved` and edit again: the datasets stream in the restored overlay is
+ // overwritten in place rather than left behind.
+ s.undo(id).unwrap();
+ s.apply(id, Edit::SetFieldValue { name: pin_name.clone(), value: FieldValue::Text("secret3".into()) }).unwrap();
+ let saved_after_undo = s.save_bytes(id).unwrap();
+ for leak in ["hunter2", "secret1", "secret3", "*******"] {
+ assert!(!appears_in_pdf(&saved_after_undo, leak), "save after undo leaked {leak}");
+ }
+
+ // A relayout (`rerender`) after typing a password frees the replaced generated widget and its
+ // masked appearance stream so neither remains in the overlay when saving.
+ let relayout_xml = pdfcraft_xfa::fixtures::fields_template("").replace(
+ r#"<subform name="page1" layout="tb">"#,
+ r#"<subform name="page1" layout="tb"><field name="grow" w="2in"><ui><textEdit multiLine="1"/></ui></field>"#,
+ );
+ let id2 = s.open("relayout.pdf", None, Arc::new(pdfcraft_xfa::fixtures::shell(&relayout_xml)), None).unwrap();
+ let pin2 = s.get(id2).unwrap().form.iter().find(|f| f.name.contains("pin")).unwrap().name.clone();
+ let grow2 = s.get(id2).unwrap().form.iter().find(|f| f.name.contains("grow")).unwrap().name.clone();
+ s.apply(id2, Edit::SetFieldValue { name: pin2, value: FieldValue::Text("s3cr3t!".into()) }).unwrap();
+ s.apply(id2, Edit::SetFieldValue { name: grow2, value: FieldValue::Text("line1\nline2\nline3\nline4\nline5".into()) }).unwrap();
+ let saved_relayout = s.save_bytes(id2).unwrap();
+ for leak in ["s3cr3t!", "*******"] {
+ assert!(!appears_in_pdf(&saved_relayout, leak), "save after relayout leaked {leak}");
+ }
+}
+
/// A value its field's font can't draw is kept, and the edit that drew it reports it in
/// `edit_notices` (the interface shows it, tools return it): not a later unrelated edit, not a
/// failed one, and not a value that can be drawn. The form (an inline AcroForm here) asks other
@@ -2418,6 +2753,84 @@ fn redaction_marks_apply_for_good_and_undo() {
assert!(matches!(s.apply(id, Edit::ApplyRedactions { pages: None }), Err(EditError::Redact(_))));
}
+/// What [`mark_with_reply`] writes that must not reach a file once the mark is removed.
+const MARK_TRACES: [&str; 5] = ["/Redact", "MARKED OVERLAY", "Mark Author", "REPLY TO THE MARK", "Replier"];
+
+/// A redaction mark on page 1 (the first annotation there) and a reply to it.
+fn mark_with_reply(s: &mut Session, id: DocId) {
+ let shape = Shape::Redact {
+ quads: vec![pdfcraft_annot::rect_quad([80.0, 140.0, 100.0, 180.0])],
+ overlay: "MARKED OVERLAY".into(),
+ look: Default::default(),
+ };
+ let mark = Edit::AddAnnotation(NewAnnotation {
+ page: 0,
+ style: Style::default_for(&shape),
+ shape,
+ contents: String::new(),
+ author: "Mark Author".into(),
+ });
+ s.apply(id, mark).unwrap();
+ let reply = Edit::ReplyToAnnotation { page: 0, index: 0, text: "REPLY TO THE MARK".into(), author: "Replier".into() };
+ s.apply(id, reply).unwrap();
+}
+
+/// Marks removed before they are applied, all at once or one by one, are not saved, nor are
+/// replies to them: the file would otherwise record where they were, their overlay text and who
+/// made them, and the page is left as it was.
+#[test]
+fn removed_redaction_marks_are_not_saved() {
+ for clear in [true, false] {
+ let (mut s, id) = session_with(1);
+ mark_with_reply(&mut s, id);
+ let removal = if clear { Edit::ClearRedactions } else { Edit::DeleteAnnotation { page: 0, index: 0 } };
+ s.apply(id, removal).unwrap();
+ assert_eq!(s.get(id).unwrap().redaction_marks(), 0);
+ let saved = s.save_bytes(id).unwrap();
+ for trace in MARK_TRACES {
+ assert!(!saved.windows(trace.len()).any(|w| w == trace.as_bytes()), "clear: {clear}, {trace:?}");
+ }
+ let mut reopened = Session::new();
+ let back = reopened.open("saved.pdf", None, saved.clone(), None).unwrap();
+ assert_eq!(page_texts(&reopened, back), ["Page 1"]);
+ let page = pdfcraft_model::pages(&reopened.get(back).unwrap().editor.as_ref().unwrap().cos).swap_remove(0);
+ assert!(!page.dict.contains(b"Annots"), "clear: {clear}");
+
+ // Undo past that save brings the mark back, under the number the saved file left free.
+ s.mark_saved(id, saved, None).unwrap();
+ s.undo(id).unwrap();
+ let again = s.save_bytes(id).unwrap();
+ let mut reopened = Session::new();
+ let back = reopened.open("again.pdf", None, again.clone(), None).unwrap();
+ let d = reopened.get(back).unwrap();
+ assert!(d.info.warnings.is_empty() && d.editor.as_ref().unwrap().cos.repair_log().is_empty(), "{:?}", d.info.warnings);
+ assert_eq!(d.redaction_marks(), 1, "clear: {clear}");
+ let marks = pdfcraft_redact::marks(&d.editor.as_ref().unwrap().cos);
+ assert_eq!(marks.first().map(|m| m.overlay.as_str()), Some("MARKED OVERLAY"));
+ }
+}
+
+/// Removed marks are not in a signed file either, nor in one with revocation evidence embedded:
+/// no later save could take them out of those.
+#[test]
+fn removed_redaction_marks_are_not_signed() {
+ let p12 = std::fs::read(concat!(env!("CARGO_MANIFEST_DIR"), "/../sign/tests/data/ec-p256.p12")).unwrap();
+ let digital_id = sign::pkcs12::open(&p12, "test").unwrap();
+ // After the test certificate's start date (2026-10-02).
+ let mut s = Session::new().with_clock(|| 1_800_000_000);
+ let id = s.open("fixture.pdf", None, Arc::new(fixture(1)), None).unwrap();
+ mark_with_reply(&mut s, id);
+ s.apply(id, Edit::ClearRedactions).unwrap();
+ let signed = s.sign(id, &digital_id, SignOptions { rect: None, ..SignOptions::default() }).unwrap();
+ let evidence = sign::dss::Evidence { certs: vec![digital_id.certificate.raw.clone()], ocsps: Vec::new(), crls: Vec::new() };
+ let ltv = s.embed_ltv(id, &evidence).unwrap();
+ for (what, out) in [("signed", signed), ("LTV", ltv)] {
+ for trace in MARK_TRACES {
+ assert!(!out.windows(trace.len()).any(|w| w == trace.as_bytes()), "{what}: {trace:?}");
+ }
+ }
+}
+
#[test]
fn oversized_redaction_overlay_preserves_the_document_and_undo() {
let (mut s, id) = session_with(1);
@@ -3083,6 +3496,143 @@ fn added_text_and_images_render_and_stay_editable() {
assert_eq!(s.get(id).unwrap().added().len(), 2);
}
+/// Edit ▸ Copy and Paste of added content (#2636): a text box comes back with all its style, an
+/// image with its picture and transforms, in the same document and in another.
+#[test]
+fn pasted_added_content_keeps_its_style_and_picture() {
+ let (mut s, id) = session_with(2);
+ let text = AddedText {
+ rect: [20.0, 250.0, 180.0, 264.4],
+ text: "Styled note".into(),
+ family: FontFamily::Times,
+ bold: true,
+ italic: true,
+ size: 12.0,
+ color: [0.8, 0.1, 0.2],
+ align: TextAlign::Center,
+ char_spacing: 0.0,
+ };
+ s.apply(id, Edit::AddText { page: 0, text: text.clone() }).unwrap();
+ let copied = s.get(id).unwrap().added()[0].content.clone();
+ let moved = copied.with_rect([40.0, 100.0, 200.0, 114.4]);
+ s.apply(id, Edit::PasteContent { page: 1, content: moved.clone(), file: None }).unwrap();
+ let doc = s.get(id).unwrap();
+ assert_eq!(doc.can_undo(), Some("Paste"));
+ assert_eq!(doc.added()[1].page, 1);
+ assert_eq!(doc.added()[1].content, moved, "every part of the style, in the new box");
+
+ // An image, turned, flipped and cropped.
+ let mut png = Vec::new();
+ {
+ let mut enc = png::Encoder::new(&mut png, 20, 10);
+ enc.set_color(png::ColorType::Rgb);
+ let px: Vec<u8> = (0..200).flat_map(|i| [(i % 256) as u8, 40, 200]).collect();
+ enc.write_header().unwrap().write_image_data(&px).unwrap();
+ }
+ s.apply(id, Edit::AddImage { page: 0, rect: Some([50.0, 100.0, 150.0, 150.0]), name: "p.png".into(), bytes: Arc::new(png) }).unwrap();
+ let AddedContent::Image(mut img) = s.get(id).unwrap().added()[1].content.clone() else { panic!("the image is the page's second item") };
+ (img.rotation, img.flip_h, img.crop) = (1, true, [0.1, 0.0, 0.2, 0.05]);
+ s.apply(id, Edit::UpdateContent { page: 0, index: 1, content: AddedContent::Image(img.clone()) }).unwrap();
+ let (ext, file) = s.get(id).unwrap().added_image_file(0, 1).unwrap();
+ assert_eq!(ext, "png");
+ let file = Some(("Pasted image.png".to_string(), Arc::new(file)));
+ assert!(s.get(id).unwrap().added_image_file(0, 0).is_err(), "the first item is text");
+ let pasted = AddedImage { rect: [60.0, 90.0, 160.0, 140.0], ..img.clone() };
+ s.apply(id, Edit::PasteContent { page: 0, content: AddedContent::Image(pasted.clone()), file: file.clone() }).unwrap();
+ let AddedContent::Image(got) = s.get(id).unwrap().added()[2].content.clone() else { panic!("an image was pasted") };
+ assert_eq!(got, pasted, "the same picture object, box, turn, flip and crop");
+
+ // Into another document: the picture comes along as a file of its own.
+ let other = s.open("other.pdf", None, Arc::new(fixture(1)), None).unwrap();
+ s.apply(other, Edit::PasteContent { page: 0, content: AddedContent::Image(pasted.clone()), file: file.clone() }).unwrap();
+ s.apply(other, Edit::PasteContent { page: 0, content: copied.clone(), file: None }).unwrap();
+ let d = s.get(other).unwrap();
+ let AddedContent::Image(theirs) = &d.added()[0].content else { panic!("an image was pasted") };
+ assert_eq!(AddedImage { image: img.image, ..theirs.clone() }, pasted, "the same box and transforms");
+ assert_eq!(d.added_image_file(0, 0).unwrap().1, file.as_ref().unwrap().1.as_slice(), "the same picture");
+ assert_eq!(d.added()[1].content, copied);
+ // Pasted there again, it draws the first paste's picture object rather than storing a third.
+ let first = theirs.image;
+ s.apply(other, Edit::PasteContent { page: 0, content: AddedContent::Image(pasted.clone()), file: file.clone() }).unwrap();
+ let AddedContent::Image(again) = s.get(other).unwrap().added()[2].content.clone() else { panic!("an image was pasted") };
+ assert_eq!(again.image, first, "one picture object for both pastes");
+ // The object holds another picture of the same size (another document's numbering, an undone
+ // add): the file is embedded instead of drawing the wrong picture.
+ let mut other_png = Vec::new();
+ {
+ let mut enc = png::Encoder::new(&mut other_png, 20, 10);
+ enc.set_color(png::ColorType::Rgb);
+ enc.write_header().unwrap().write_image_data(&[7u8; 600]).unwrap();
+ }
+ let other_file = Some(("other.png".to_string(), Arc::new(other_png)));
+ s.apply(id, Edit::PasteContent { page: 0, content: AddedContent::Image(pasted.clone()), file: other_file }).unwrap();
+ let AddedContent::Image(fresh) = s.get(id).unwrap().added()[3].content.clone() else { panic!("an image was pasted") };
+ assert_ne!(fresh.image, img.image, "a picture object of its own");
+ assert_ne!(s.get(id).unwrap().added_image_file(0, 3).unwrap().1, file.as_ref().unwrap().1.as_slice());
+ assert!(matches!(
+ s.apply(id, Edit::PasteContent { page: 0, content: AddedContent::Image(pasted), file: None }),
+ Err(EditError::Edit(pdfcraft_edit::EditError::Invalid(_)))
+ ));
+ // Four items on page 1 and the pasted text on page 2.
+ assert_eq!(s.get(id).unwrap().added().len(), 5, "refused pastes add nothing");
+ s.undo(id).unwrap();
+ assert_eq!(s.get(id).unwrap().added().len(), 4, "a paste is one undo step");
+}
+
+/// An added JPEG 2000 picture is copied as the file it was added from: pasted into its own
+/// document it draws the same object, and into another one it is embedded once.
+#[test]
+fn an_added_jpeg_2000_image_is_copied_as_its_file() {
+ // A JP2 file (30 × 20, three components) with a stub codestream, as Add Image takes it.
+ let bx = |ty: &[u8], payload: &[u8]| [((payload.len() + 8) as u32).to_be_bytes().as_slice(), ty, payload].concat();
+ let ihdr = [20u32.to_be_bytes().as_slice(), &30u32.to_be_bytes(), &[0, 3, 7, 7, 0, 0]].concat();
+ let signature = [0, 0, 0, 0x0C, b'j', b'P', b' ', b' ', 0x0D, 0x0A, 0x87, 0x0A];
+ let file = [signature.as_slice(), &bx(b"ftyp", b"jp2 \0\0\0\0jp2 "), &bx(b"jp2h", &bx(b"ihdr", &ihdr)), &bx(b"jp2c", &[0xFF, 0x4F, 0xFF, 0x51])]
+ .concat();
+ let (mut s, id) = session_with(1);
+ s.apply(id, Edit::AddImage { page: 0, rect: Some([50.0, 100.0, 110.0, 140.0]), name: "photo.jp2".into(), bytes: Arc::new(file.clone()) })
+ .unwrap();
+ let (ext, copied) = s.get(id).unwrap().added_image_file(0, 0).unwrap();
+ assert_eq!((ext, &copied), ("jp2", &file), "the file as it was added");
+ let AddedContent::Image(img) = s.get(id).unwrap().added()[0].content.clone() else { panic!("an image was added") };
+ let copied = Arc::new(copied);
+ let file = Some(("Pasted image.jp2".to_string(), copied.clone()));
+ let pasted = AddedContent::Image(AddedImage { rect: [70.0, 80.0, 130.0, 120.0], ..img.clone() });
+ s.apply(id, Edit::PasteContent { page: 0, content: pasted.clone(), file: file.clone() }).unwrap();
+ assert!(matches!(&s.get(id).unwrap().added()[1].content, AddedContent::Image(i) if i.image == img.image), "the same picture object");
+ let other = s.open("other.pdf", None, Arc::new(fixture(1)), None).unwrap();
+ for _ in 0..2 {
+ s.apply(other, Edit::PasteContent { page: 0, content: pasted.clone(), file: file.clone() }).unwrap();
+ }
+ let d = s.get(other).unwrap();
+ let images: Vec<_> = d
+ .added()
+ .iter()
+ .filter_map(|a| match &a.content {
+ AddedContent::Image(i) => Some(i.image),
+ _ => None,
+ })
+ .collect();
+ assert_eq!(images.len(), 2);
+ assert_eq!(images[0], images[1], "embedded once");
+ assert_eq!(d.added_image_file(0, 0).unwrap().1, copied.as_slice());
+}
+
+#[test]
+fn a_batch_of_content_edits_refreshes_the_added_content_and_marks() {
+ let (mut s, id) = session_with(1);
+ let text = |t: &str, y: f64| AddedText { rect: [20.0, y, 180.0, y + 14.4], text: t.into(), ..AddedText::default() };
+ let edits = vec![Edit::AddText { page: 0, text: text("One", 200.0) }, Edit::AddText { page: 0, text: text("Two", 150.0) }];
+ s.apply(id, Edit::Batch { label: "Script".into(), edits }).unwrap();
+ assert_eq!(s.get(id).unwrap().added().len(), 2);
+ s.apply(id, Edit::Batch { label: "Script".into(), edits: vec![Edit::DeleteContent { page: 0, index: 0 }] }).unwrap();
+ assert_eq!(s.get(id).unwrap().added().len(), 1);
+ let watermark =
+ Edit::AddWatermark { pages: vec![0], settings: Watermark { text: "Draft".into(), ..Watermark::default() }, file: None, replace: false };
+ s.apply(id, Edit::Batch { label: "Script".into(), edits: vec![watermark] }).unwrap();
+ assert_eq!(s.get(id).unwrap().marks().len(), 1);
+}
+
#[test]
fn added_images_rotate_flip_and_crop_as_drawn() {
// A 20×10 image: left half red, right half blue.
@@ -3347,6 +3897,78 @@ fn comments_lock_take_checkmarks_hide_and_summarize() {
assert_eq!(comment_summary("x", &[], SummarySort::Page), "Summary of Comments on x\n\nThis document has no comments.\n");
}
+/// Replies thread by their `/IRT` reference, not `/NM`: PyMuPDF names the first comment on every
+/// page `fitz-A0`, which used to file every reply under page 1's comment. An `/IRT` to the
+/// annotation itself, or to a link (never listed as a comment), leaves it a comment of its own. Both readers (inspect on open, and the
+/// comment list the engine refreshes after an edit) must agree.
+#[test]
+fn replies_thread_by_reference_when_names_repeat_across_pages() {
+ let pdf = b"%PDF-1.7
+1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj
+2 0 obj << /Type /Pages /Kids [3 0 R 4 0 R] /Count 2 >> endobj
+3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 300 200] /Annots [5 0 R 8 0 R 9 0 R 10 0 R] >> endobj
+4 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 300 200] /Annots [6 0 R 7 0 R] >> endobj
+5 0 obj << /Type /Annot /Subtype /Text /Rect [20 140 40 160] /NM (fitz-A0) /T (Alpha) /Contents (COVER) >> endobj
+6 0 obj << /Type /Annot /Subtype /Text /Rect [20 140 40 160] /NM (fitz-A0) /T (Beta) /Contents (SECOND) >> endobj
+7 0 obj << /Type /Annot /Subtype /Text /Rect [20 100 40 120] /NM (fitz-A1) /IRT 6 0 R /T (Gamma) /Contents (ANSWER) >> endobj
+8 0 obj << /Type /Annot /Subtype /Text /Rect [20 100 40 120] /NM (fitz-A1) /IRT 8 0 R /T (Delta) /Contents (SELF) >> endobj
+9 0 obj << /Type /Annot /Subtype /Link /Rect [200 20 260 40] /Border [0 0 0] /Dest [3 0 R /Fit] >> endobj
+10 0 obj << /Type /Annot /Subtype /Text /Rect [20 60 40 80] /NM (fitz-A2) /IRT 9 0 R /T (Echo) /Contents (LINKED) >> endobj
+trailer << /Root 1 0 R >>
+%%EOF";
+ let mut s = Session::new().with_clock(|| 1_700_000_000);
+ let id = s.open("fitz.pdf", None, Arc::new(pdf.to_vec()), None).expect("opens");
+ let check = |s: &Session, replies: usize| {
+ let all = &s.get(id).unwrap().info.annotations;
+ let answer = all.iter().find(|a| a.contents.as_deref() == Some("ANSWER")).unwrap();
+ assert_eq!(answer.parent, Some((1, 0)), "{answer:?}");
+ let looped = all.iter().find(|a| a.contents.as_deref() == Some("SELF")).unwrap();
+ assert!(!looped.is_reply(), "{looped:?}");
+ let linked = all.iter().find(|a| a.contents.as_deref() == Some("LINKED")).unwrap();
+ assert!(!linked.is_reply(), "{linked:?}");
+ let text = comment_summary("fitz.pdf", all, SummarySort::Page);
+ let (cover, second) = text.split_once("SECOND").unwrap();
+ assert!(!cover.contains("ANSWER"), "page 1's comment has no replies: {text}");
+ assert!(cover.contains("Number: 2 Author: Delta"), "the self-reply is a comment of its own: {text}");
+ assert!(cover.contains("Number: 3 Author: Echo"), "so is the reply to a link: {text}");
+ assert_eq!(second.matches(" Author:").count(), replies, "{text}");
+ };
+ check(&s, 1);
+ s.apply(id, Edit::ReplyToAnnotation { page: 1, index: 0, text: "LATER".into(), author: "Delta".into() }).unwrap();
+ check(&s, 2);
+}
+
+/// A comment listed through a reference chain (`/Annots [5 0 R]`, `5 0 obj 6 0 R`) keeps its
+/// replies after an edit, whether their `/IRT` names the comment or the chain, as on open.
+#[test]
+fn replies_thread_through_a_reference_chain_after_an_edit() {
+ let pdf = b"%PDF-1.7
+1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj
+2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj
+3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 300 200] /Annots [5 0 R 7 0 R 8 0 R 9 0 R] >> endobj
+5 0 obj 6 0 R endobj
+6 0 obj << /Type /Annot /Subtype /Text /Rect [20 140 40 160] /NM (one) /Contents (CHAINED) >> endobj
+7 0 obj << /Type /Annot /Subtype /Text /Rect [20 120 40 130] /IRT 6 0 R /Contents (TO THE COMMENT) >> endobj
+8 0 obj << /Type /Annot /Subtype /Text /Rect [20 100 40 110] /IRT 5 0 R /Contents (THROUGH THE CHAIN) >> endobj
+9 0 obj << /Type /Annot /Subtype /Text /Rect [20 60 40 80] /NM (two) /Contents (PLAIN) >> endobj
+trailer << /Root 1 0 R >>
+%%EOF";
+ let mut s = Session::new().with_clock(|| 1_700_000_000);
+ let id = s.open("chain.pdf", None, Arc::new(pdf.to_vec()), None).expect("opens");
+ let check = |s: &Session| {
+ let all = &s.get(id).unwrap().info.annotations;
+ let comment = all.iter().find(|a| a.contents.as_deref() == Some("CHAINED")).expect("listed");
+ assert_eq!((comment.page, comment.index, comment.is_reply()), (0, 0, false), "{all:?}");
+ for reply in ["TO THE COMMENT", "THROUGH THE CHAIN"] {
+ let a = all.iter().find(|a| a.contents.as_deref() == Some(reply)).expect("listed");
+ assert_eq!((a.parent, a.in_reply_to.as_deref()), (Some((0, 0)), Some("one")), "{reply}: {all:?}");
+ }
+ };
+ check(&s);
+ s.apply(id, Edit::ReplyToAnnotation { page: 0, index: 3, text: "LATER".into(), author: "Delta".into() }).unwrap();
+ check(&s);
+}
+
/// #820: the generated summary includes replies to replies, indented one level deeper.
#[test]
fn comment_summary_includes_replies_to_replies() {
@@ -4035,9 +4657,70 @@ fn recognize_text_reads_a_picture_on_a_page_that_has_text() {
assert_eq!((count(&s, "invoice"), count(&s, "brown")), (1, 1));
}
+/// Edit reads a scan that only has comments on it, not a page with real text and a picture
+/// (`native_text_only`): a text box over the picture is not the page's text, page content is.
+#[test]
+fn native_text_only_ignores_comments_but_not_page_text() {
+ if !ocr::available() {
+ eprintln!("skipped: OCR models not installed");
+ return;
+ }
+ let mut s = Session::new().with_clock(|| 1_700_000_000);
+ let text = s.create_from_text("t", "The quick brown fox jumps over the lazy dog.").unwrap();
+ let id = s.open("text.pdf", None, text, None).unwrap();
+ let png = export::Exporter::new(s.get(id).unwrap()).png(0, 150.0).unwrap();
+ let scan = s.create_from_images(&[("scan.png".into(), png)]).unwrap();
+ let comment_only = |s: &mut Session| {
+ let id = s.open("scan.pdf", None, scan.clone(), None).unwrap();
+ let (w, h) = {
+ let p = &s.get(id).unwrap().info.pages[0];
+ (p.width as f64, p.height as f64)
+ };
+ let shape = pdfcraft_annot::Shape::TextBox { rect: [w * 0.1, h * 0.75, w * 0.9, h * 0.85], font_size: 18.0 };
+ s.apply(
+ id,
+ Edit::AddAnnotation(NewAnnotation {
+ page: 0,
+ style: pdfcraft_annot::Style::default_for(&shape),
+ shape,
+ contents: "Invoice reference 4711".into(),
+ author: "Test".into(),
+ }),
+ )
+ .unwrap();
+ id
+ };
+ let native = ocr::OcrSettings { native_text_only: true, ..Default::default() };
+
+ // A comment over the picture: the default run counts it as text and skips the page, the
+ // native-text run reads the picture.
+ let id = comment_only(&mut s);
+ let skipped = s.recognize_text(id, &[], ocr::OcrSettings::default()).unwrap();
+ assert!(skipped[0].skipped.is_some(), "a comment is text for the default run");
+ let found = s.recognize_text(id, &[], native.clone()).unwrap();
+ assert_eq!(found[0].skipped, None, "{:?}", found[0]);
+ assert!(found[0].text().to_lowercase().contains("brown"), "{:?}", found[0]);
+
+ // Page content over the picture is the page's own text: skipped, whatever the setting.
+ let id = comment_only(&mut s);
+ let (w, h) = {
+ let p = &s.get(id).unwrap().info.pages[0];
+ (p.width as f64, p.height as f64)
+ };
+ let note = AddedText { rect: [w * 0.1, h * 0.6, w * 0.9, h * 0.7], text: "Page text".into(), size: 18.0, ..Default::default() };
+ s.apply(id, Edit::AddText { page: 0, text: note }).unwrap();
+ let skipped = s.recognize_text(id, &[], native).unwrap();
+ assert!(skipped[0].skipped.is_some(), "{:?}", skipped[0]);
+}
+
/// A form whose scripts are custom JavaScript: total = price × qty (calculate, through a
/// document-level function), shown with a custom format; qty is validated; a button script.
fn scripted_form() -> Vec<u8> {
+ scripted_form_with("function times\\(a, b\\) { console.println('times'); return a * b; }")
+}
+
+/// [`scripted_form`] with `helpers` (PDF string syntax) as its document-level script.
+fn scripted_form_with(helpers: &str) -> Vec<u8> {
let text = |name: &str, y: u32, aa: &str| {
format!("<< /Type /Annot /Subtype /Widget /FT /Tx /T ({name}) /Rect [20 {y} 180 {}] /P 3 0 R /F 4 {aa} >>", y + 20)
};
@@ -4051,7 +4734,7 @@ fn scripted_form() -> Vec<u8> {
"<< /Type /Annot /Subtype /Widget /FT /Btn /Ff 65536 /T (go) /Rect [20 150 80 170] /P 3 0 R /F 4 >>".to_string(),
"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>".to_string(),
"<< >>".to_string(),
- "<< /S /JavaScript /JS (function times\\(a, b\\) { console.println('times'); return a * b; }) >>".to_string(),
+ format!("<< /S /JavaScript /JS ({helpers}) >>"),
];
let mut out = b"%PDF-1.7\n".to_vec();
let mut offsets = Vec::new();
@@ -4099,6 +4782,113 @@ fn form_javascript_validates_calculates_and_formats() {
assert!(s.run_javascript(id, "1", None).is_err());
}
+/// XFA forms check `xfa_installed` and `xfa_version` in a document script that runs before
+/// each of their scripts, and alert when either is missing.
+#[test]
+fn scripts_in_an_xfa_form_see_the_xfa_plugin_installed() {
+ let check = "typeof xfa_installed + ' ' + typeof xfa_version + ' ' + xfa_version";
+ let mut s = Session::new().with_clock(|| 1_700_000_000);
+ let xfa = s.open("form.pdf", None, Arc::new(pdfcraft_xfa::fixtures::shell(&pdfcraft_xfa::fixtures::template(3))), None).unwrap();
+ let o = s.run_javascript(xfa, check, None).unwrap();
+ assert_eq!((o.error, o.result.as_deref()), (None, Some("boolean number 3.5")));
+ let plain = s.open("order.pdf", None, Arc::new(scripted_form()), None).unwrap();
+ let o = s.run_javascript(plain, check, None).unwrap();
+ assert_eq!((o.error, o.result.as_deref()), (None, Some("undefined number 3.5")));
+}
+
+/// #3940: a document-level script that defines the helper and then calls a method PdfCraft lacks
+/// (an Acrobat form copying a button icon at open) left every calculated field blank. The
+/// helper stays defined, the form calculates, and the error is reported once.
+#[test]
+fn a_document_script_that_throws_still_lets_the_form_calculate() {
+ let helpers =
+ "function times\\(a, b\\) { return a * b; } this.getField\\('go'\\).buttonSetIcon\\(this.getField\\('go'\\).buttonGetIcon\\(\\)\\);";
+ let mut s = Session::new().with_clock(|| 1_700_000_000);
+ let id = s.open("order.pdf", None, Arc::new(scripted_form_with(helpers)), None).unwrap();
+ let _ = s.take_js_output(id);
+ s.apply(id, Edit::SetFieldValue { name: "qty".into(), value: FieldValue::Text("4".into()) }).unwrap();
+ let total = s.get(id).unwrap().form.iter().find(|f| f.name == "total").unwrap().value.clone();
+ assert_eq!(total, ["10"], "calculated through the helper the failing script defined");
+ let out = s.take_js_output(id);
+ assert_eq!(out.errors.len(), 1, "reported once, not once per script: {out:?}");
+ assert!(out.errors[0].starts_with("document script 1: TypeError"), "{out:?}");
+ // The console runs too, and says which document script failed.
+ let o = s.run_javascript(id, "times(2, 3)", None).unwrap();
+ assert_eq!((o.error, o.result.as_deref(), o.doc_errors.len()), (None, Some("6"), 1));
+}
+
+#[test]
+fn active_xfa_does_not_run_pdf_container_scripts_but_keeps_requested_alerts() {
+ let template = pdfcraft_xfa::fixtures::scripted_template().replace(
+ r#"xfa.host.messageBox("Hello " + qty.rawValue);"#,
+ r#"xfa.host.messageBox("Hello " + qty.rawValue); xfa.host.print(1, "0", "0", 0, 0, 0, 0, 0);"#,
+ );
+ let mut cos = pdfcraft_cos::Document::open(Arc::new(pdfcraft_xfa::fixtures::shell(&template))).unwrap();
+ let fallback = "app.alert('This PDF form requires a newer version of Adobe Acrobat');";
+ pdfcraft_forms::set_document_script(&mut cos, "viewerFallback", Some(fallback)).unwrap();
+ let bytes = Arc::new(pdfcraft_cos::write_full(&cos, &Default::default()).unwrap());
+ let mut s = Session::new();
+ let id = s.open("xfa.pdf", None, bytes, None).unwrap();
+ assert!(s.get(id).unwrap().xfa.is_some());
+ assert!(s.take_js_output(id).alerts.is_empty());
+ let out = s.run_javascript(id, "app.alert('Console message');", None).unwrap();
+ assert!(out.error.is_none(), "{out:?}");
+ assert_eq!(out.alerts, ["Console message"]);
+ assert_eq!(s.get(id).unwrap().document_scripts(), [("viewerFallback".into(), fallback.into())]);
+ let out = s.run_javascript(id, "", Some("hello")).unwrap();
+ assert!(out.error.is_none(), "{out:?}");
+ assert_eq!(out.alerts, ["Hello 2"]);
+ assert_eq!(out.requests, [js::Request::Print]);
+ // The same context rule applies to format/validate/calculate through JsRunner.
+ s.apply(id, Edit::SetFieldScript { name: "qty".into(), event: "validate".into(), script: Some("app.alert('Field message');".into()) }).unwrap();
+ s.take_js_output(id);
+ s.apply(id, Edit::SetFieldValue { name: "qty".into(), value: FieldValue::Text("3".into()) }).unwrap();
+ assert_eq!(s.take_js_output(id).alerts, ["Field message"]);
+ // Saved XFA keeps its container scripts for inspection, but does not execute them.
+ let saved = s.get(id).unwrap().bytes.clone();
+ let reopened = s.open("saved.pdf", None, saved, None).unwrap();
+ assert!(s.run_javascript(reopened, "", None).unwrap().alerts.is_empty());
+ // Making the form static restores the ordinary PDF context; undo restores XFA's.
+ s.apply(id, Edit::XfaToStatic).unwrap();
+ assert_eq!(s.run_javascript(id, "", None).unwrap().alerts.len(), 1);
+ s.undo(id).unwrap();
+ assert!(s.run_javascript(id, "", None).unwrap().alerts.is_empty());
+}
+
+#[test]
+fn active_xfa_without_template_scripts_does_not_initialize_pdf_fallback_scripts() {
+ let template = r#"<template xmlns="http://www.xfa.org/schema/xfa-template/3.3/">
+<subform name="form" layout="tb"><pageSet><pageArea name="page">
+<contentArea x="36pt" y="36pt" w="540pt" h="720pt"/><medium short="612pt" long="792pt"/>
+</pageArea></pageSet><field name="text" w="200pt" h="30pt"><ui><textEdit/></ui></field></subform></template>"#;
+ let mut s = Session::new();
+ let id = s.open("no-scripts.pdf", None, Arc::new(pdfcraft_xfa::fixtures::shell(template)), None).unwrap();
+ assert!(s.get(id).unwrap().xfa.is_some());
+ assert!(s.get(id).unwrap().xfa_template.is_none());
+ s.apply(id, Edit::SetDocumentScript { name: "fallback".into(), script: Some("throw new Error('PDF fallback ran');".into()) }).unwrap();
+ let out = s.run_javascript(id, "app.alert('Console message');", None).unwrap();
+ assert!(out.error.is_none(), "{out:?}");
+ assert_eq!(out.alerts, ["Console message"]);
+}
+
+#[test]
+fn inactive_xfa_and_ordinary_pdfs_keep_document_helpers_and_alerts() {
+ for bytes in [
+ fixture(1),
+ pdfcraft_xfa::fixtures::static_shell("<form1><page1><name>Test</name></page1></form1>"),
+ pdfcraft_xfa::fixtures::shell(&pdfcraft_xfa::fixtures::scripted_template()),
+ ] {
+ let mut cos = pdfcraft_cos::Document::open(Arc::new(bytes)).unwrap();
+ pdfcraft_forms::set_document_script(&mut cos, "helper", Some("function twice(n) { return n * 2; } app.alert('PDF message');")).unwrap();
+ // The raw dynamic shell has not been laid out: XFA's presence alone is not enough.
+ let runner = js::JsRunner::new(&cos, "control.pdf");
+ let out = pdfcraft_js::run("twice(3)", &pdfcraft_js::Event::doc("Console"), &runner.doc, &[], &runner.doc_scripts, Default::default());
+ assert!(out.error.is_none(), "{out:?}");
+ assert_eq!(out.result.as_deref(), Some("6"));
+ assert_eq!(out.alerts, ["PDF message"]);
+ }
+}
+
#[test]
fn edit_history_does_not_replay_field_script_side_effects() {
let mut s = Session::new().with_clock(|| 1_700_000_000);
@@ -4613,6 +5403,80 @@ fn measurement_edits_are_transactional_and_honour_annotation_permissions() {
);
}
+/// A laid-out XFA field that doesn't scroll (`hScrollPolicy="off"`) opens as a text field with
+/// DoNotScroll, and its text box says what fits it: what the editor takes no more than.
+#[test]
+fn an_xfa_field_that_doesnt_scroll_opens_with_do_not_scroll_and_a_text_box() {
+ let xdp = r##"<?xml version="1.0" encoding="UTF-8"?>
+<xdp:xdp xmlns:xdp="http://ns.adobe.com/xdp/"><template xmlns="http://www.xfa.org/schema/xfa-template/3.3/"><subform name="form" layout="tb">
+<field name="code" w="1in" h="0.3in"><ui><textEdit hScrollPolicy="off"/></ui><font typeface="Arial" size="10pt"/></field>
+<field name="note" w="1in" h="0.3in"><ui><textEdit/></ui><font typeface="Arial" size="10pt"/></field>
+</subform></template></xdp:xdp>"##;
+ let mut s = Session::new();
+ let id = s.open("form.pdf", None, Arc::new(pdfcraft_xfa::fixtures::shell(xdp)), None).expect("opens");
+ let doc = s.get(id).unwrap();
+ let field = |end: &str| doc.form.iter().find(|f| f.name.ends_with(end)).unwrap_or_else(|| panic!("no field {end}"));
+ assert!(field("code").has(field_flags::DO_NOT_SCROLL) && !field("note").has(field_flags::DO_NOT_SCROLL));
+ let tb = doc.field_text_box(&field("code").name, 0).expect("a text box");
+ assert!(tb.fits("A1B2") && !tb.fits(&"W".repeat(40)), "a 1-inch field at 10 pt");
+ assert!(doc.field_text_box("no such field", 0).is_none() && doc.field_text_box(&field("code").name, 5).is_none());
+}
+
+/// A round XFA check button opens drawn round: the appearance its laid-out widget gets draws a
+/// circle, the on state with its mark in it, while a square one keeps its box.
+#[test]
+fn round_xfa_check_buttons_open_drawn_round() {
+ let xdp = r##"<?xml version="1.0" encoding="UTF-8"?>
+<xdp:xdp xmlns:xdp="http://ns.adobe.com/xdp/"><template xmlns="http://www.xfa.org/schema/xfa-template/3.3/"><subform name="form" layout="tb">
+<field name="round" w="1in" h="0.3in"><ui><checkButton shape="round"/></ui><items><integer>1</integer><integer>0</integer></items></field>
+<field name="square" w="1in" h="0.3in"><ui><checkButton/></ui><items><integer>1</integer><integer>0</integer></items></field>
+</subform></template></xdp:xdp>"##;
+ let mut s = Session::new();
+ let id = s.open("form.pdf", None, Arc::new(pdfcraft_xfa::fixtures::shell(xdp)), None).expect("opens");
+ let cos = s.get(id).unwrap().editor.as_ref().unwrap().cos.clone();
+ let all = pdfcraft_forms::fields(&cos);
+ // The decoded appearance of `name`'s widget in `state`.
+ let drawn = |name: &str, state: &[u8]| {
+ let w = all.iter().find(|f| f.name.ends_with(name)).unwrap_or_else(|| panic!("no field {name}")).widgets[0].obj;
+ let wd = cos.get(w).as_dict().cloned().unwrap();
+ let n = cos.resolve(wd.get(b"AP").unwrap().as_dict().unwrap().get(b"N").unwrap());
+ let r = n.as_dict().unwrap().reference(state).unwrap_or_else(|| panic!("{name} has no {} state", String::from_utf8_lossy(state)));
+ let pdfcraft_cos::Object::Stream(st) = &*cos.get(r) else { panic!("a stream") };
+ String::from_utf8_lossy(&st.decoded().unwrap()).into_owned()
+ };
+ for state in [&b"Off"[..], b"1"] {
+ let round = drawn("round", state);
+ assert!(round.contains(" c S") && !round.contains(" re S"), "the round one's border is a circle: {round}");
+ assert!(drawn("square", state).contains(" re S"), "the square one keeps its box");
+ }
+}
+
+#[test]
+fn a_dynamic_xfa_form_is_saved_without_the_usage_rights_its_layout_voided() {
+ let xdp = pdfcraft_xfa::fixtures::template(3);
+ let original = Arc::new(pdfcraft_xfa::fixtures::usage_rights_shell(&xdp, "", false));
+ let mut s = Session::new().with_clock(|| 1_700_000_000);
+ let id = s.open("form.pdf", None, original.clone(), None).expect("opens");
+ let doc = s.get(id).unwrap();
+ let warnings = &doc.xfa.as_ref().expect("laid out from the template").warnings;
+ assert!(warnings.iter().any(|w| w.contains("usage rights")), "the user is told: {warnings:?}");
+ assert!(!doc.dirty, "laying out is still not an edit");
+ s.apply(id, Edit::SetFieldValue { name: "familyName".into(), value: FieldValue::Text("Singh".into()) }).unwrap();
+ let incremental = s.save_bytes(id).unwrap();
+ assert!(incremental.starts_with(&original[..]), "still an incremental save");
+ // Saved either way, the file no longer carries them, and keeps what was filled in.
+ for saved in [incremental, s.save_full_bytes(id).unwrap()] {
+ let cos = pdfcraft_cos::Document::open(saved.clone()).unwrap();
+ let catalog = cos.get(cos.root().unwrap()).as_dict().cloned().unwrap();
+ assert!(!catalog.contains(b"Perms"), "{catalog:?}");
+ let again = s.open("saved.pdf", None, saved, None).unwrap();
+ let d2 = s.get(again).unwrap();
+ assert_eq!(d2.form.iter().find(|f| f.name == "familyName").unwrap().value, vec!["Singh".to_string()]);
+ let warnings = &d2.xfa.as_ref().expect("the layout is remembered").warnings;
+ assert!(!warnings.iter().any(|w| w.contains("usage rights")), "nothing left to say: {warnings:?}");
+ }
+}
+
#[test]
fn dynamic_xfa_forms_are_laid_out_on_open_filled_and_saved_incrementally() {
let original = Arc::new(pdfcraft_xfa::fixtures::shell(&pdfcraft_xfa::fixtures::template(3)));
@@ -5822,6 +6686,149 @@ fn comments_without_appearances_are_drawn_but_not_saved() {
}
}
+/// ISO 32000-2 Table 178: with `/LL`, `/L` gives the ends of the leader lines, and the line itself
+/// is drawn `/LL` from it (above, for a positive `/LL` on a line drawn left to right). The page
+/// view shows the line there, with its leaders down to `/L`, and nothing along `/L` itself.
+#[test]
+fn a_line_without_an_appearance_is_drawn_at_its_leader_length() {
+ let objs: Vec<&[u8]> = vec![
+ b"<< /Type /Catalog /Pages 2 0 R >>",
+ b"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 200 300] >>",
+ b"<< /Type /Page /Parent 2 0 R /Annots [4 0 R] >>",
+ b"<< /Type /Annot /Subtype /Line /Rect [0 0 200 300] /L [40 100 160 100] /LL 30 /C [1 0 0] /BS << /W 4 >> >>",
+ ];
+ let mut bytes = b"%PDF-1.7\n".to_vec();
+ let mut offsets = Vec::new();
+ for (i, o) in objs.iter().enumerate() {
+ offsets.push(bytes.len());
+ bytes.extend_from_slice(format!("{} 0 obj\n", i + 1).as_bytes());
+ bytes.extend_from_slice(o);
+ bytes.extend_from_slice(b"\nendobj\n");
+ }
+ let xref = bytes.len();
+ bytes.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objs.len() + 1).as_bytes());
+ for o in offsets {
+ bytes.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes());
+ }
+ bytes.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objs.len() + 1).as_bytes());
+ let mut s = Session::new().with_clock(|| 1_700_000_000);
+ let id = s.open("line.pdf", None, Arc::new(bytes), None).expect("opens");
+ let p = shown(&s, id, 0);
+ let px = |x: u32, y: u32| p.rgba[((y * p.width + x) * 4) as usize..][..4].to_vec();
+ // y down: /L is row 200, the line itself row 170.
+ assert_eq!(px(100, 170), vec![255, 0, 0, 255], "the line, 30 above /L");
+ assert_eq!(px(40, 185), vec![255, 0, 0, 255], "the leader line at the start");
+ assert_eq!(px(160, 185), vec![255, 0, 0, 255], "the leader line at the end");
+ assert_eq!(px(100, 200), vec![255, 255, 255, 255], "nothing along /L");
+}
+
+/// A stamp's `/Rect` and the colour family expected inside it.
+type StampRect = ([f64; 4], char);
+
+/// Rubber stamps without an appearance (ISO 32000-2 Table 184): the fourteen standard names, one
+/// without `/Name`, one custom name, and last a Draft stamp with artwork of its own (magenta).
+/// Each sits in a 120 × 60 `/Rect` on a 612 × 792 page; the name and the expected colour family
+/// (`'r'`, `'g'`, `'b'`, or `'n'` for the neutral placeholder) of each, in page order.
+fn stamps_without_appearances() -> (Arc<Vec<u8>>, Vec<StampRect>) {
+ let stamps: [(Option<&str>, char); 16] = [
+ (Some("Approved"), 'g'),
+ (Some("Experimental"), 'b'),
+ (Some("NotApproved"), 'r'),
+ (Some("AsIs"), 'b'),
+ (Some("Expired"), 'r'),
+ (Some("NotForPublicRelease"), 'r'),
+ (Some("Confidential"), 'r'),
+ (Some("Final"), 'g'),
+ (Some("Sold"), 'g'),
+ (Some("Departmental"), 'b'),
+ (Some("ForComment"), 'b'),
+ (Some("TopSecret"), 'r'),
+ (Some("Draft"), 'b'),
+ (Some("ForPublicRelease"), 'b'),
+ (None, 'b'),
+ (Some("MyCustomStamp"), 'n'),
+ ];
+ let mut objs: Vec<String> =
+ vec!["<< /Type /Catalog /Pages 2 0 R >>".into(), "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 612 792] >>".into(), String::new()];
+ let mut expected = Vec::new();
+ for (i, (name, family)) in stamps.iter().enumerate() {
+ let (x, y) = (30 + (i % 4) * 145, 660 - (i / 4) * 150);
+ let rect = [x as f64, y as f64, x as f64 + 120.0, y as f64 + 60.0];
+ let name = name.map(|n| format!("/Name /{n}")).unwrap_or_default();
+ objs.push(format!("<< /Type /Annot /Subtype /Stamp /Rect [{} {} {} {}] {name} /F 4 >>", rect[0], rect[1], rect[2], rect[3]));
+ expected.push((rect, *family));
+ }
+ let own = objs.len() + 2;
+ objs.push(format!("<< /Type /Annot /Subtype /Stamp /Rect [30 60 150 120] /Name /Draft /F 4 /AP << /N {own} 0 R >> >>"));
+ expected.push(([30.0, 60.0, 150.0, 120.0], 'm'));
+ objs.push("<< /Type /XObject /Subtype /Form /BBox [0 0 10 10] /Length 23 >>\nstream\n1 0 1 rg 0 0 10 10 re f\nendstream".into());
+ let annots: Vec<String> = (4..own).map(|n| format!("{n} 0 R")).collect();
+ objs[2] = format!("<< /Type /Page /Parent 2 0 R /Annots [{}] >>", annots.join(" "));
+ let mut bytes = b"%PDF-1.7\n".to_vec();
+ let mut offsets = Vec::new();
+ for (i, o) in objs.iter().enumerate() {
+ offsets.push(bytes.len());
+ bytes.extend_from_slice(format!("{} 0 obj\n{o}\nendobj\n", i + 1).as_bytes());
+ }
+ let xref = bytes.len();
+ bytes.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objs.len() + 1).as_bytes());
+ for o in offsets {
+ bytes.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes());
+ }
+ bytes.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objs.len() + 1).as_bytes());
+ (Arc::new(bytes), expected)
+}
+
+/// The colour family of an RGBA pixel that isn't white: `'r'`, `'g'` or `'b'` for the dominant
+/// channel, `'n'` for a grey, `'m'` for magenta.
+fn colour_family(p: &[u8]) -> Option<char> {
+ let (r, g, b) = (i32::from(p[0]), i32::from(p[1]), i32::from(p[2]));
+ if r.min(g).min(b) > 200 {
+ return None;
+ }
+ Some(if (r - g).abs() < 24 && (g - b).abs() < 24 {
+ 'n'
+ } else if r > 200 && b > 200 && g < 80 {
+ 'm'
+ } else if r > g && r > b {
+ 'r'
+ } else if g > r && g > b {
+ 'g'
+ } else {
+ 'b'
+ })
+}
+
+/// Rubber stamps without an appearance are drawn from their `/Name` (ISO 32000-2 Table 184), in
+/// the colour of the stamp they name; an unknown name gets a grey placeholder; a stamp's own
+/// artwork is drawn as it is. Display only: Save writes the file without new appearances.
+#[test]
+fn stamps_without_appearances_draw_the_stamp_they_name() {
+ let (original, expected) = stamps_without_appearances();
+ let mut s = Session::new();
+ let id = s.open("stamps.pdf", None, original.clone(), None).expect("opens");
+ let p = shown(&s, id, 0);
+ for (i, (rect, family)) in expected.iter().enumerate() {
+ let mut counts = std::collections::HashMap::new();
+ for y in (792.0 - rect[3]) as u32..(792.0 - rect[1]) as u32 {
+ for x in rect[0] as u32..rect[2] as u32 {
+ let px = &p.rgba[((y * p.width + x) * 4) as usize..][..4];
+ if let Some(f) = colour_family(px) {
+ *counts.entry(f).or_insert(0) += 1;
+ }
+ }
+ }
+ let total: u32 = counts.values().sum();
+ let main = counts.iter().max_by_key(|(_, n)| **n).map(|(f, _)| *f);
+ assert!(total > 300, "stamp {i} draws ink inside its /Rect: {counts:?}");
+ assert_eq!(main, Some(*family), "stamp {i} is drawn in its colour: {counts:?}");
+ }
+ let saved = pdfcraft_cos::Document::open(s.save_bytes(id).unwrap()).unwrap();
+ for n in 4..20 {
+ assert!(saved.get(pdfcraft_cos::ObjRef::new(n, 0)).as_dict().is_some_and(|d| !d.contains(b"AP")), "{n} is saved without /AP");
+ }
+}
+
/// A page with a FreeText comment that has no `/AP` stream: the smallest case behind #2371.
fn free_text_without_appearance() -> Arc<Vec<u8>> {
let objs: Vec<&[u8]> = vec![
@@ -6307,6 +7314,7 @@ fn content_edit_keeps_pages_annotations_fields_and_links() {
size: 12.0,
color: [0.0, 0.0, 0.0],
align: TextAlign::Left,
+ char_spacing: 0.0,
};
session.apply(id, Edit::AddText { page: 1, text }).unwrap();
let after = session.get(id).unwrap();
@@ -6346,6 +7354,7 @@ fn content_refresh_lists_match_the_storages_an_edit_touches() {
size: 12.0,
color: [0.0, 0.0, 0.0],
align: TextAlign::Left,
+ char_spacing: 0.0,
},
},
Edit::MoveObjects { page: 0, objects: vec![target(crate::ObjectKind::Added)], offset: [1.0, 0.0] },
@@ -6883,6 +7892,18 @@ fn text_blocks_stay_cached_after_an_edit_and_follow_undo_and_redo() {
assert!(Arc::ptr_eq(&redone, &blocks(&session)));
}
+/// #4199, #3797: the spaces typed into a paragraph are all there after saving and reopening.
+#[test]
+fn edited_text_keeps_every_space_typed_through_save_and_reopen() {
+ let (mut s, id) = session_with(1);
+ let typed = " A b c";
+ s.apply(id, Edit::EditTextBlock { page: 0, block: 0, text: typed.into(), style: pdfcraft_edit::BlockStyle::default() }).unwrap();
+ let saved = s.save_bytes(id).unwrap();
+ let reopened = s.open("saved.pdf", None, saved, None).unwrap();
+ let blocks = s.get(reopened).unwrap().editor.as_ref().unwrap().text_blocks(0).unwrap();
+ assert_eq!(blocks[0].editor_text, typed);
+}
+
/// A new document, or one restored from recovery, has never been written where it belongs: undo
/// back to the bytes it was opened from must not make it clean, or closing it would discard the
/// whole document without asking. Saving makes it clean; Revert of a saved one too.
@@ -7346,6 +8367,100 @@ fn exporting_office_keeps_dotted_leader_entries_as_paragraphs() {
assert!(positions.windows(2).all(|pair| pair[0] < pair[1]), "reading order: {html}");
}
+/// A date typed in another of an XFA date field's edit patterns is kept in its first: yymmdd and
+/// yyyymd are rewritten as yyyymmdd, a date none of them reads is refused, and the data holds the date.
+#[test]
+fn a_date_typed_by_another_of_an_xfa_fields_edit_patterns_is_kept_in_its_first() {
+ let mut s = Session::new();
+ let id = s
+ .open("dates.pdf", None, Arc::new(pdfcraft_xfa::fixtures::shell(&pdfcraft_xfa::fixtures::date_alternatives_template())), None)
+ .expect("opens");
+ let value = |s: &Session| s.get(id).unwrap().form.iter().find(|f| f.name == "leave").unwrap().value.clone();
+ s.apply(id, Edit::SetFieldValue { name: "leave".into(), value: FieldValue::Text("261018".into()) }).expect("yymmdd is one of its patterns");
+ assert_eq!(value(&s), ["20261018"]);
+ s.apply(id, Edit::SetFieldValue { name: "leave".into(), value: FieldValue::Text("2026118".into()) }).expect("so is yyyymd");
+ assert_eq!(value(&s), ["20261108"]);
+ let refused = s.apply(id, Edit::SetFieldValue { name: "leave".into(), value: FieldValue::Text("2618".into()) });
+ assert!(refused.is_err_and(|e| e.to_string().contains("yyyymmdd")), "none of its patterns reads it");
+ assert_eq!(value(&s), ["20261108"]);
+ // The data holds the date.
+ let cos = pdfcraft_cos::Document::open(s.save_bytes(id).unwrap()).unwrap();
+ let data = pdfcraft_xfa::parse_datasets(&pdfcraft_xfa::read_packets(&cos).unwrap().unwrap().xdp).expect("a datasets packet");
+ assert_eq!(data.text_at(&pdfcraft_xfa::som_to_path("form[0].leave[0]")), Some("2026-11-08"));
+}
+
+/// A date the field's own scripts refuse is not tried again in another of an XFA date field's
+/// patterns: only a date its format refuses is, which happens before any script runs, so the
+/// scripts run once. This validate script counts its runs in `name` and accepts on its second.
+#[test]
+fn a_date_its_validate_script_refuses_is_not_tried_again() {
+ let mut s = Session::new();
+ let id = s
+ .open("dates.pdf", None, Arc::new(pdfcraft_xfa::fixtures::shell(&pdfcraft_xfa::fixtures::date_alternatives_template())), None)
+ .expect("opens");
+ let script = Some("var n = Number(getField('name').value || 0) + 1; getField('name').value = String(n); event.rc = n >= 2;".to_string());
+ s.apply(id, Edit::SetFieldScript { name: "leave".into(), event: "validate".into(), script }).unwrap();
+ let value = |s: &Session, n: &str| s.get(id).unwrap().form.iter().find(|f| f.name == n).unwrap().value.clone();
+ // Its format reads 18OCT26, and so does its DDMMMYY pattern.
+ let refused = s.apply(id, Edit::SetFieldValue { name: "leave".into(), value: FieldValue::Text("18OCT26".into()) });
+ assert!(refused.is_err(), "the validate script refused it, once");
+ assert!(value(&s, "name").is_empty(), "nothing the refused run changed is kept: {:?}", value(&s, "name"));
+}
+
+/// An XFA button's click script may show the attachments panel; a text field's exit script
+/// asking the same is noted on the console and ignored.
+#[test]
+fn an_xfa_button_may_show_a_side_panel_and_other_events_may_not() {
+ let xdp = r##"<?xml version="1.0" encoding="UTF-8"?>
+<xdp:xdp xmlns:xdp="http://ns.adobe.com/xdp/">
+<template xmlns="http://www.xfa.org/schema/xfa-template/3.3/">
+<subform name="form" layout="tb">
+ <pageSet><pageArea name="front"><contentArea x="0.5in" y="0.5in" w="7.5in" h="10in"/><medium short="8.5in" long="11in"/></pageArea></pageSet>
+ <field name="files" w="2in" h="0.3in"><ui><button/></ui><caption><value><text>Attachments</text></value></caption>
+ <event activity="click"><script contentType="application/x-javascript">app.execMenuItem("ShowHideFileAttachment");</script></event></field>
+ <field name="note" w="2in" h="0.3in"><ui><textEdit/></ui>
+ <event activity="exit"><script contentType="application/x-javascript">app.execMenuItem("ShowHideFileAttachment");</script></event></field>
+</subform>
+</template>
+</xdp:xdp>
+"##;
+ let mut s = Session::new();
+ let id = s.open("files.pdf", None, Arc::new(pdfcraft_xfa::fixtures::shell(xdp)), None).expect("opens");
+ s.take_js_output(id);
+ s.apply(id, Edit::XfaEvent { som: "form[0].files[0]".into(), activity: "click".into() }).unwrap();
+ let out = s.take_js_output(id);
+ assert_eq!(out.requests, [pdfcraft_js::Request::ShowPanel(pdfcraft_js::Panel::Attachments)], "{out:?}");
+ s.apply(id, Edit::SetFieldValue { name: "note".into(), value: FieldValue::Text("x".into()) }).unwrap();
+ let out = s.take_js_output(id);
+ assert!(out.requests.is_empty(), "only a click shows a panel: {out:?}");
+ assert!(out.console.iter().any(|c| c.contains("show a side panel")), "{:?}", out.console);
+}
+
+/// A validate script that asks for Save As and a side panel gets neither, with a console note
+/// for each; a button's script may still open Save As.
+#[test]
+fn a_fields_own_script_may_not_save_as_or_show_a_panel() {
+ let mut s = Session::new().with_clock(|| 1_700_000_000);
+ let id = s.open("order.pdf", None, Arc::new(scripted_form()), None).unwrap();
+ s.apply(
+ id,
+ Edit::SetFieldScript {
+ name: "qty".into(),
+ event: "validate".into(),
+ script: Some("app.execMenuItem('SaveAs'); app.execMenuItem('ShowHideFileAttachment');".into()),
+ },
+ )
+ .unwrap();
+ s.take_js_output(id);
+ s.apply(id, Edit::SetFieldValue { name: "qty".into(), value: FieldValue::Text("4".into()) }).unwrap();
+ let out = s.take_js_output(id);
+ assert!(out.requests.is_empty(), "a validate script runs unasked: {out:?}");
+ assert_eq!(out.console.iter().filter(|c| c.contains("only a button may")).count(), 2, "{:?}", out.console);
+ // A button's script may.
+ let o = s.run_javascript(id, "app.execMenuItem('SaveAs');", Some("go")).unwrap();
+ assert_eq!(o.requests, [js::Request::SaveAs]);
+}
+
/// A page whose forms go past the reading limit and whose picture goes past the image budget is
/// listed once among the truncated pages.
#[test]
@@ -7391,3 +8506,109 @@ fn a_page_truncated_for_forms_and_pictures_is_listed_once() {
assert!(pages[0].images.is_empty(), "the picture is past the budget");
assert_eq!(truncated, [0]);
}
+
+/// ISO 32000-2 Table 192, 12.7.5.2.3 and Table 228 (Comb): a check box, a push button, a comb
+/// field the file leaves to the viewer. The page as displayed and printed as an image shows the
+/// check box's caption symbol in its text colour, the button's grey face and the comb's cells in
+/// the border colour, and saving writes the file as it was.
+#[test]
+fn buttons_and_combs_left_to_the_viewer_are_displayed() {
+ let pdf = b"%PDF-1.7\n\
+ 1 0 obj << /Type /Catalog /Pages 2 0 R /AcroForm 4 0 R >> endobj\n\
+ 2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj\n\
+ 3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 400 200] /Annots [6 0 R 7 0 R 8 0 R] >> endobj\n\
+ 4 0 obj << /Fields [6 0 R 7 0 R 8 0 R] /DA (/Helv 0 Tf 0 g) /DR << /Font << /Helv 5 0 R >> >> >> endobj\n\
+ 5 0 obj << /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >> endobj\n\
+ 6 0 obj << /Type /Annot /Subtype /Widget /FT /Btn /T (k) /V /Yes /AS /Yes /DA (/ZaDb 0 Tf 1 0 0 rg) /MK << /CA (8) /BC [0 0 0] >> /Rect [20 150 60 190] /F 4 /P 3 0 R >> endobj\n\
+ 7 0 obj << /Type /Annot /Subtype /Widget /FT /Btn /Ff 65536 /T (o) /DA (/Helv 12 Tf 0 g) /MK << /CA (Press) /BG [0.8 0.8 0.8] /BC [0 0 0] >> /BS << /W 2 /S /B >> /Rect [100 150 220 190] /F 4 /P 3 0 R >> endobj\n\
+ 8 0 obj << /Type /Annot /Subtype /Widget /FT /Tx /Ff 16777216 /MaxLen 4 /T (d) /V (AB) /DA (/Helv 12 Tf 0 g) /MK << /BC [0 0 1] >> /Rect [20 80 220 110] /F 4 /P 3 0 R >> endobj\n\
+ trailer << /Root 1 0 R >>\n%%EOF"
+ .to_vec();
+ let render = |bytes: Arc<Vec<u8>>| {
+ let mut r = pdfcraft_render::PageRenderer::new(bytes, pdfcraft_render::RenderConfig::default());
+ r.render(pdfcraft_render::RenderRequest { page: 0, scale: 1.0, ..Default::default() })
+ };
+ // Pixels of the page (drawn at scale 1, 400 x 200) in user-space box x0..x1, y0..y1 that `keep`.
+ let count = |page: &pdfcraft_render::RenderedPage, (x0, y0, x1, y1): (u32, u32, u32, u32), keep: &dyn Fn(&[u8; 4]) -> bool| {
+ let (px, _) = page.rgba.as_chunks::<4>();
+ (200 - y1..200 - y0)
+ .flat_map(|y| (x0..x1).map(move |x| (x, y)))
+ .filter(|&(x, y)| px.get((y * page.width + x) as usize).is_some_and(keep))
+ .count()
+ };
+ let red = |p: &[u8; 4]| p[0] > 200 && p[1] < 80 && p[2] < 80;
+ let grey = |p: &[u8; 4]| (180..=230).contains(&p[0]) && p[0] == p[1] && p[1] == p[2];
+ // Bluish: a 1 pt line on a pixel edge is half blue on each side.
+ let blue = |p: &[u8; 4]| p[2] > 200 && p[0] < 180 && p[1] < 180 && p[0] + 40 < p[2];
+ let mut s = Session::new();
+ let id = s.open("form.pdf", None, Arc::new(pdf), None).unwrap();
+ let shown = render(s.get(id).unwrap().display.clone());
+ assert!(count(&shown, (24, 154, 56, 186), &red) > 60, "the check box's red cross");
+ assert!(count(&shown, (104, 154, 216, 186), &grey) > 1000, "the push button's grey face");
+ // The comb's three inner lines at x = 70, 120 and 170, between its cells.
+ for x in [70, 120, 170] {
+ assert!(count(&shown, (x - 1, 84, x + 1, 106), &blue) >= 20, "a cell line at {x}");
+ }
+ assert_eq!(count(&shown, (95, 84, 97, 106), &blue), 0, "no line inside a cell");
+ // Print as Image: the page as a picture, at 72 dpi so it is the size of the page here.
+ let raster = pdfcraft_print::Raster { dpi: 72.0, grayscale: false };
+ let pictures = crate::print_raster::rasterize(s.get(id).unwrap(), &[0], &raster, pdfcraft_print::Content::Document).unwrap();
+ let printed = render(Arc::new(pictures));
+ assert!(count(&printed, (24, 154, 56, 186), &red) > 60, "the check box prints");
+ assert!(count(&printed, (104, 154, 216, 186), &grey) > 1000, "and the push button");
+ // The file is saved as it was: no widget has an appearance.
+ let saved = pdfcraft_cos::Document::open(s.save_bytes(id).unwrap()).unwrap();
+ for f in pdfcraft_forms::fields(&saved) {
+ assert!(saved.get(f.widgets[0].obj).as_dict().is_some_and(|d| !d.contains(b"AP")), "{} has no appearance", f.name);
+ }
+}
+
+/// ISO 32000-2 Tables 166 and 183, drawn on the page: a square without an appearance whose
+/// `/Border [0 0 3 [6 3]]` names its width before a dash array is stroked 3 pt wide and dashed
+/// (it was 1 pt and solid), and a caret with `/Sy /P` shows a ¶ to its right.
+#[test]
+fn legacy_border_dashes_and_the_caret_paragraph_symbol_are_drawn() {
+ let original = Arc::new(pdf_with_annots(&[
+ b"<< /Type /Annot /Subtype /Square /Rect [20 180 120 280] /Border [0 0 3 [6 3]] /C [1 0 0] >>",
+ b"<< /Type /Annot /Subtype /Caret /Rect [20 20 80 80] /Sy /P /C [0 0 1] >>",
+ ]));
+ let mut s = Session::new().with_clock(|| 1_700_000_000);
+ let id = s.open("noap.pdf", None, original, None).expect("opens");
+ let p = shown(&s, id, 0);
+ let px = |x: u32, y: u32| p.rgba[((y * p.width + x) * 4) as usize..][..4].to_vec();
+ // y down: the bottom edge's stroke is centred 1.5 pt inside /Rect, on row 118.
+ let row: Vec<Vec<u8>> = (24..116).map(|x| px(x, 118)).collect();
+ let red = row.iter().filter(|c| c[0] > 200 && c[1] < 80).count();
+ let white = row.iter().filter(|c| c[1] > 200).count();
+ assert!(red > 40 && white > 15, "3 pt and dashed: {red} red, {white} white");
+ // The ¶ sits in the right part of the caret's /Rect, where the caret no longer reaches.
+ let blue = (250..270).flat_map(|y| (68..80).map(move |x| (x, y))).filter(|&(x, y)| {
+ let c = px(x, y);
+ c[2] > 150 && c[0] < 100
+ });
+ assert!(blue.count() > 20, "the pilcrow is drawn beside the caret");
+}
+
+/// A one-page 200 × 300 document whose page lists `annots` (objects 4, 5, …).
+fn pdf_with_annots(annots: &[&[u8]]) -> Vec<u8> {
+ let list: String = (0..annots.len()).map(|i| format!("{} 0 R ", i + 4)).collect();
+ let page = format!("<< /Type /Page /Parent 2 0 R /Annots [{list}] >>");
+ let mut objs: Vec<&[u8]> =
+ vec![b"<< /Type /Catalog /Pages 2 0 R >>", b"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 200 300] >>", page.as_bytes()];
+ objs.extend_from_slice(annots);
+ let mut bytes = b"%PDF-1.7\n".to_vec();
+ let mut offsets = Vec::new();
+ for (i, o) in objs.iter().enumerate() {
+ offsets.push(bytes.len());
+ bytes.extend_from_slice(format!("{} 0 obj\n", i + 1).as_bytes());
+ bytes.extend_from_slice(o);
+ bytes.extend_from_slice(b"\nendobj\n");
+ }
+ let xref = bytes.len();
+ bytes.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objs.len() + 1).as_bytes());
+ for o in offsets {
+ bytes.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes());
+ }
+ bytes.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objs.len() + 1).as_bytes());
+ bytes
+}
diff --git a/crates/engine/src/text_fonts.rs b/crates/engine/src/text_fonts.rs
index f4945f7..859bc1a 100644
--- a/crates/engine/src/text_fonts.rs
+++ b/crates/engine/src/text_fonts.rs
@@ -74,5 +74,5 @@ pub fn discover(roots: &[PathBuf]) -> Vec<FontFile> {
files
}
fn font_extension(path: &Path) -> bool {
- path.extension().and_then(|e| e.to_str()).is_some_and(|e| e.eq_ignore_ascii_case("ttf") || e.eq_ignore_ascii_case("otf"))
+ path.extension().and_then(std::ffi::OsStr::to_str).is_some_and(|e| e.eq_ignore_ascii_case("ttf") || e.eq_ignore_ascii_case("otf"))
}
diff --git a/crates/engine/src/word_count.rs b/crates/engine/src/word_count.rs
index bd31c27..feeb0a0 100644
--- a/crates/engine/src/word_count.rs
+++ b/crates/engine/src/word_count.rs
@@ -110,6 +110,16 @@ fn standard_role(doc: &pdfcraft_cos::Document, map: &Dict, role: &[u8]) -> Vec<u
role
}
+/// Whether the page's resources hold a Form XObject, whose MCIDs are a separate namespace.
+fn page_has_form_xobject(doc: &pdfcraft_cos::Document, page: &pdfcraft_cos::Dict) -> bool {
+ let resources = page.get(b"Resources").map(|o| doc.resolve(o));
+ let objects = resources.as_ref().and_then(|o| o.as_dict()).and_then(|d| d.get(b"XObject")).map(|o| doc.resolve(o));
+ objects
+ .as_ref()
+ .and_then(|o| o.as_dict())
+ .is_some_and(|d| d.iter().any(|(_, value)| matches!(&*doc.resolve(value), Object::Stream(s) if s.dict.name(b"Subtype") == Some(b"Form"))))
+}
+
type Exclusions = HashMap<usize, HashSet<i32>>;
/// Resolve page-local MCIDs through the structure hierarchy, including inherited roles and
@@ -179,11 +189,7 @@ fn exclusions(source: &ExportSource, options: Options) -> Result<(Exclusions, bo
if !out.contains_key(&index) {
continue;
}
- let resources = page.dict.get(b"Resources").map(|o| doc.resolve(o));
- let objects = resources.as_ref().and_then(|o| o.as_dict()).and_then(|d| d.get(b"XObject")).map(|o| doc.resolve(o));
- let has_form = objects.as_ref().and_then(|o| o.as_dict()).is_some_and(|d| {
- d.iter().any(|(_, value)| matches!(&*doc.resolve(value), Object::Stream(s) if s.dict.name(b"Subtype") == Some(b"Form")))
- });
+ let has_form = page_has_form_xobject(&doc, &page.dict);
if has_form {
out.remove(&index);
unclassified = true;
diff --git a/crates/engine/src/xfa.rs b/crates/engine/src/xfa.rs
index 6ce7654..2f98efd 100644
--- a/crates/engine/src/xfa.rs
+++ b/crates/engine/src/xfa.rs
@@ -53,6 +53,7 @@ fn click_only(e: &XfaEffect) -> Option<&'static str> {
XfaEffect::Print => Some("print"),
XfaEffect::SaveAs => Some("save"),
XfaEffect::LaunchUrl(_) => Some("open a link"),
+ XfaEffect::ShowPanel(_) => Some("show a side panel"),
XfaEffect::SetFocus(_) => Some("move the focus"),
_ => None,
}
@@ -532,7 +533,7 @@ impl<'a, 'b> Runner<'a, 'b> {
} else {
Some(by_som.iter().filter(|(som, _)| names.iter().any(|n| som_matches(som, n))).map(|(_, f)| f.clone()).collect())
};
- if listed.as_ref().is_some_and(|l| l.is_empty()) {
+ if listed.as_ref().is_some_and(Vec::is_empty) {
return Ok(());
}
pdfcraft_forms::reset(self.doc, listed.as_deref()).map_err(|e| e.to_string())?;
@@ -628,6 +629,7 @@ impl<'a, 'b> Runner<'a, 'b> {
XfaEffect::Print => self.run.out.requests.push(Request::Print),
XfaEffect::SaveAs => self.run.out.requests.push(Request::SaveAs),
XfaEffect::LaunchUrl(u) => self.run.out.requests.push(Request::LaunchUrl(u.clone())),
+ XfaEffect::ShowPanel(p) => self.run.out.requests.push(Request::ShowPanel(*p)),
XfaEffect::SetFocus(som) => {
if let Some(name) = self.by_som().get(som).cloned() {
self.run.out.requests.push(Request::Focus(name));
@@ -858,6 +860,28 @@ pub(crate) fn on_data_replaced(doc: &mut pdfcraft_cos::Document, tpl: &Template,
r.finish().map(|_| ())
}
+/// A text value typed into the laid-out XFA date field `name` by another of its edit picture's
+/// patterns, written in the first ([`pdfcraft_xfa::typed_date`]); `None` for anything else.
+/// `tpl` is the template the scripts use, when they run; otherwise it is read from `doc`.
+pub(crate) fn typed_date(
+ doc: &pdfcraft_cos::Document,
+ tpl: Option<&Template>,
+ name: &str,
+ value: &pdfcraft_forms::FieldValue,
+) -> Option<pdfcraft_forms::FieldValue> {
+ let pdfcraft_forms::FieldValue::Text(text) = value else { return None };
+ let som = pdfcraft_xfa::fields_by_som(doc).into_iter().find_map(|(som, n)| (n == name).then_some(som))?;
+ let read;
+ let tpl = match tpl {
+ Some(t) => t,
+ None => {
+ read = pdfcraft_xfa::template_of(doc).ok()?;
+ &read
+ }
+ };
+ pdfcraft_xfa::typed_date(tpl, &som, text).map(pdfcraft_forms::FieldValue::Text)
+}
+
/// A button's click script (or any event, by SOM path and activity), then calculations.
pub(crate) fn on_event(doc: &mut pdfcraft_cos::Document, tpl: &Template, som: &str, activity: &str, run: &mut XfaRun) -> Result<(), String> {
let mut r = Runner::new(doc, tpl, run, EVENT_BUDGET_MS);
diff --git a/crates/export/src/lib.rs b/crates/export/src/lib.rs
index 37644df..48ab783 100644
--- a/crates/export/src/lib.rs
+++ b/crates/export/src/lib.rs
@@ -264,7 +264,7 @@ pub(crate) fn tables(blocks: &[Block]) -> (Vec<Table>, Vec<bool>) {
used.sort_unstable();
used.dedup();
let mut edges: Vec<f64> = used.iter().filter_map(|&i| col_of.get(i).copied().flatten()).filter_map(|ci| cols.get(ci)).map(|c| c.0).collect();
- edges.sort_by(|a, b| a.total_cmp(b));
+ edges.sort_by(f64::total_cmp);
edges.dedup_by(|a, b| (*a - *b).abs() <= COL_TOL);
let ncols = edges.len();
let ok = (ncols >= 3 || (ncols == 2 && run.len() >= 3)) && ncols <= MAX_COLS;
@@ -274,7 +274,7 @@ pub(crate) fn tables(blocks: &[Block]) -> (Vec<Table>, Vec<bool>) {
}
let right = used.iter().map(|&i| blocks[i].rect[2]).fold(f64::MIN, f64::max) + COL_TOL;
let mut rows_out = Vec::new();
- let mut slots: Vec<Option<Cell>> = vec![None; ncols];
+ let mut slots: Vec<Option<(Cell, Vec<usize>)>> = vec![None; ncols];
let mut row_tops = Vec::with_capacity(run.len());
for row in run.drain(..) {
row_tops.push(row.iter().filter_map(|(_, bi)| blocks.get(*bi)).map(|b| b.rect[3]).fold(f64::MIN, f64::max));
@@ -294,20 +294,28 @@ pub(crate) fn tables(blocks: &[Block]) -> (Vec<Table>, Vec<bool>) {
span,
font: b.font.clone(),
};
- match &mut slots[slot] {
- Some(c) => {
+ match slots.get_mut(slot) {
+ Some(Some((c, sources))) => {
c.text.push(' ');
c.text.push_str(&cell.text);
+ sources.push(bi);
}
- None => slots[slot] = Some(cell),
+ Some(empty @ None) => *empty = Some((cell, vec![bi])),
+ None => continue,
}
- consumed[bi] = true;
}
let mut materialized = Vec::with_capacity(ncols);
let mut column = 0;
while column < ncols {
- match slots[column].take() {
- Some(mut cell) => {
+ match slots.get_mut(column).and_then(Option::take) {
+ Some((mut cell, sources)) => {
+ // A spanning cell can skip later slots. Only consume source blocks
+ // when their text is emitted, leaving covered text in paragraph flow.
+ for bi in sources {
+ if let Some(taken) = consumed.get_mut(bi) {
+ *taken = true;
+ }
+ }
cell.span = cell.span.min(ncols - column).max(1);
column += cell.span;
materialized.push(cell);
@@ -349,7 +357,7 @@ pub(crate) fn tables(blocks: &[Block]) -> (Vec<Table>, Vec<bool>) {
let run_edges = |run: &[Vec<(usize, usize)>]| -> Vec<f64> {
let mut es: Vec<f64> =
run.iter().flatten().filter_map(|(_, i)| col_of.get(*i).copied().flatten()).filter_map(|ci| cols.get(ci)).map(|c| c.0).collect();
- es.sort_by(|a, b| a.total_cmp(b));
+ es.sort_by(f64::total_cmp);
es.dedup_by(|a, b| (*a - *b).abs() <= COL_TOL);
es
};
@@ -553,17 +561,18 @@ fn docx_table(t: &Table) -> String {
s.push_str("</w:tblGrid>");
for row in &t.rows {
s.push_str("<w:tr>");
+ let mut column = 0usize;
for c in row {
let span = if c.span > 1 { format!("<w:gridSpan w:val=\"{}\"/>", c.span) } else { String::new() };
- let w: i64 = widths.iter().take(c.span.min(widths.len())).sum();
+ let w: i64 = widths.iter().skip(column).take(c.span).sum();
s.push_str(&format!(
"<w:tc><w:tcPr><w:tcW w:w=\"{w}\" w:type=\"dxa\"/>{span}</w:tcPr><w:p>{}</w:p></w:tc>",
run_xml(&c.text, c.size, c.bold, c.italic, c.color)
));
+ column = column.saturating_add(c.span);
}
// Pad the grid so every row covers all columns (Word rejects short rows).
- let used: usize = row.iter().map(|c| c.span).sum();
- for _ in used..t.cols.len() {
+ for _ in column..t.cols.len() {
s.push_str("<w:tc><w:tcPr><w:tcW w:w=\"0\" w:type=\"auto\"/></w:tcPr><w:p/></w:tc>");
}
s.push_str("</w:tr>");
@@ -1096,6 +1105,28 @@ mod tests {
assert!(xml.contains("<w:insideH w:val=\"nil\"/>"));
}
+ #[test]
+ fn word_table_cell_widths_follow_the_columns_they_span() {
+ let cell = |text: &str, span| Cell { text: text.into(), size: 11.0, bold: false, italic: false, color: [0.0; 3], span, font: String::new() };
+ let table = Table {
+ rect: [0.0, 0.0, 300.0, 100.0],
+ cols: vec![0.0, 50.0, 150.0],
+ rows: vec![
+ vec![cell("First", 1), cell("Second", 1), cell("Third", 1)],
+ vec![cell("First", 1), cell("Last two", 2)],
+ vec![cell("First two", 2), cell("Third", 1)],
+ vec![cell("All", 3)],
+ vec![cell("First", 1)],
+ ],
+ row_tops: vec![100.0, 80.0, 60.0, 40.0, 20.0],
+ };
+ let xml = docx_table(&table);
+ assert!(xml.contains("<w:gridCol w:w=\"1000\"/><w:gridCol w:w=\"2000\"/><w:gridCol w:w=\"3000\"/>"), "{xml}");
+ let widths: Vec<Vec<&str>> =
+ xml.split("<w:tr>").skip(1).map(|row| row.split("<w:tcW w:w=\"").skip(1).map(|cell| cell.split('"').next().unwrap()).collect()).collect();
+ assert_eq!(widths, vec![vec!["1000", "2000", "3000"], vec!["1000", "5000"], vec!["3000", "3000"], vec!["6000"], vec!["1000", "0", "0"]]);
+ }
+
#[test]
fn word_keeps_a_page_with_a_clear_image_and_big_title_in_flow() {
// page() has a picture between paragraphs and a 24 pt title over 11 pt body text, but
@@ -1845,6 +1876,40 @@ mod tests {
assert_eq!(h.matches("https://example.org/event").count(), 3, "{h}");
}
+ /// A continuation can drift into a grid column covered by the preceding cell's span.
+ /// It must remain available as paragraph text if that slot never becomes an output cell.
+ #[test]
+ fn table_spans_do_not_consume_text_they_do_not_emit() {
+ let mut blocks = vec![
+ Block { size: 12.0, ..block("ABCDEFGHIJK", 72.1, 697.0, 151.3, 710.8) },
+ Block { size: 12.0, color: [0.0, 0.0, 1.0], ..block("LOST", 150.4, 697.0, 179.2, 710.8) },
+ Block { size: 12.0, ..block("R0", 250.0, 697.0, 264.4, 710.8) },
+ ];
+ for row in 1..=4 {
+ let y = 697.0 - f64::from(row) * 50.0;
+ for (text, left, right) in [(format!("L{row}"), 72.1, 86.5), (format!("M{row}"), 146.4, 160.8), (format!("R{row}"), 250.0, 264.4)] {
+ blocks.push(Block { size: 12.0, ..block(&text, left, y, right, y + 13.8) });
+ }
+ }
+ let p = Page { width: 612.0, height: 792.0, blocks, ..Page::default() };
+ let (tables, consumed) = tables(&p.blocks);
+ assert_eq!(tables.len(), 1);
+ assert_eq!(tables[0].rows[0][0].span, 2);
+ assert!(!consumed[1], "a covered slot did not emit its text");
+ assert!(consumed.iter().enumerate().all(|(index, used)| index == 1 || *used));
+ let outputs = [
+ html(std::slice::from_ref(&p), "Continuations"),
+ part(&docx(std::slice::from_ref(&p), "Continuations"), "word/document.xml"),
+ rtf(std::slice::from_ref(&p)),
+ part(&pptx(std::slice::from_ref(&p), "Continuations"), "ppt/slides/slide1.xml"),
+ ];
+ for output in outputs {
+ for b in &p.blocks {
+ assert_eq!(output.matches(&b.text).count(), 1, "{} must survive exactly once", b.text);
+ }
+ }
+ }
+
/// #2806: a superscript right after a number ("1" "st") continues its cell; the prize table
/// around it stays a table.
#[test]
@@ -1860,6 +1925,10 @@ mod tests {
let h = html(std::slice::from_ref(&p), "Prizes");
assert!(h.contains("<table>"), "the prize table was lost: {h}");
assert!(h.contains("30,000") && h.contains("15,000"), "{h}");
+ let (tables, consumed) = tables(&p.blocks);
+ assert!(consumed.iter().all(|used| *used), "ordinary table continuations stay in their cells");
+ let cells: Vec<&str> = tables.iter().flat_map(|t| &t.rows).flatten().map(|c| c.text.as_str()).collect();
+ assert!(["st", "nd", "rd", "th"].iter().all(|suffix| cells.contains(suffix)));
}
#[test]
diff --git a/crates/fonts/build.rs b/crates/fonts/build.rs
index 397f6fc..bc87a16 100644
--- a/crates/fonts/build.rs
+++ b/crates/fonts/build.rs
@@ -7,6 +7,9 @@
use std::fmt::Write as _;
use std::path::PathBuf;
+#[path = "src/cjk_scripts.rs"]
+mod cjk_scripts;
+
fn main() {
println!("cargo::rerun-if-env-changed=CRAFT_FONTS_DIR");
println!("cargo::rerun-if-env-changed=CRAFT_FONTS_REQUIRED");
@@ -27,10 +30,6 @@ fn main() {
}
}
-/// Family-name prefixes of the faces AGENTS.md §1.1 forbids: Adobe's Source families and Noto
-/// CJK, which is Source Han under another name. The test in `src/craft.rs` has the same list.
-const BARRED_FAMILIES: [&str; 5] = ["Source Han", "Source Serif", "Source Sans", "Noto Sans CJK", "Noto Serif CJK"];
-
/// One `CraftFont { .. }` initialiser per manifest line.
fn craft_fonts(dir: &std::path::Path) -> Result<String, String> {
let manifest = dir.join("fonts/manifest.txt");
@@ -43,10 +42,13 @@ fn craft_fonts(dir: &std::path::Path) -> Result<String, String> {
let [family, style, file, scripts, ..] = f.as_slice() else {
return Err(format!("malformed manifest line: {line}"));
};
- // AGENTS.md §1.1 bars Adobe's type designs whatever their licence, so a checkout that
- // carries one (craft-fonts has Noto Sans CJK, which is Source Han) never embeds it.
- if BARRED_FAMILIES.iter().any(|barred| family.starts_with(barred)) {
- println!("cargo::warning=craft-fonts: not embedding {family} {style} (AGENTS.md §1.1)");
+ // Whole CJK faces aren't embedded for size; interface CJK comes from cut faces once the app
+ // moves to craft-fonts-build (storytold/craft-libs#213).
+ let cjk = scripts.split(',').any(cjk_scripts::is_cjk_script);
+ if cjk
+ && !cjk_scripts::WHOLE_CJK_FAMILIES.contains(family)
+ && std::fs::metadata(dir.join(file)).is_ok_and(|m| m.len() > cjk_scripts::MAX_OTHER_CJK_BYTES)
+ {
continue;
}
// Arabic interface faces are small, so the web build keeps them too.
diff --git a/crates/fonts/src/cjk_scripts.rs b/crates/fonts/src/cjk_scripts.rs
new file mode 100644
index 0000000..16a863c
--- /dev/null
+++ b/crates/fonts/src/cjk_scripts.rs
@@ -0,0 +1,19 @@
+//! The rule `build.rs` follows for CJK faces: which manifest script tags are CJK, which families
+//! are embedded whole, and the size cap for the others. The build script includes this file with
+//! `#[path]` and the crate's tests use it as a module, so the two can't drift.
+
+/// The CJK families embedded whole: the Japanese faces documents and the renderer use.
+pub const WHOLE_CJK_FAMILIES: [&str; 3] = ["Shippori Mincho", "BIZ UDPGothic", "BIZ UDMincho"];
+
+/// Any other CJK face over this size is left out.
+pub const MAX_OTHER_CJK_BYTES: u64 = 4 << 20;
+
+/// ISO 15924 codes of the Han, Japanese and Korean scripts, Hangul on its own included.
+const CJK_SCRIPTS: [&str; 6] = ["Hani", "Hans", "Hant", "Jpan", "Kore", "Hang"];
+
+/// Whether a craft-fonts manifest script tag is CJK. A tag can carry a region after the code
+/// (craft-fonts tags Noto Sans HK UI `Hant-HK`), so only the part before `-` is compared.
+pub fn is_cjk_script(tag: &str) -> bool {
+ let code = tag.trim().split('-').next().unwrap_or_default();
+ CJK_SCRIPTS.contains(&code)
+}
diff --git a/crates/fonts/src/craft.rs b/crates/fonts/src/craft.rs
index e6103a5..e778a42 100644
--- a/crates/fonts/src/craft.rs
+++ b/crates/fonts/src/craft.rs
@@ -297,20 +297,6 @@ mod tests {
assert_eq!(ui_arabic_fonts().len(), CRAFT_FONTS.iter().filter(|f| f.covers("Arab")).count());
}
- /// Family-name prefixes `build.rs` never embeds (its own `BARRED_FAMILIES`): Adobe's type
- /// designs, which includes Noto CJK (Source Han under another name).
- const BARRED_FAMILIES: [&str; 5] = ["Source Han", "Source Serif", "Source Sans", "Noto Sans CJK", "Noto Serif CJK"];
-
- /// Whatever the craft-fonts checkout holds, no Adobe type design is embedded (AGENTS.md §1.1).
- #[test]
- fn barred_families_are_never_embedded() {
- for face in CRAFT_FONTS {
- assert!(!BARRED_FAMILIES.iter().any(|barred| face.family.starts_with(barred)), "{} is embedded", face.name());
- }
- assert!(BARRED_FAMILIES.iter().any(|barred| "Noto Sans CJK SC".starts_with(barred)));
- assert!(!BARRED_FAMILIES.iter().any(|barred| "Noto Sans Arabic".starts_with(barred)));
- }
-
#[test]
fn hebrew_document_faces_follow_the_weight() {
static HEBR_LATN: &[&str] = &["Hebr", "Latn"];
@@ -328,6 +314,26 @@ mod tests {
assert_eq!(document_hebrew_font(false).is_some(), CRAFT_FONTS.iter().any(|f| f.covers("Hebr")));
}
+ /// `build.rs` embeds the Japanese CJK faces whole and any other CJK face only up to
+ /// `MAX_OTHER_CJK_BYTES`, so a checkout with a large Chinese or Korean face (craft-fonts has the
+ /// 16.4 MB Noto Sans CJK SC) leaves it out. The four Japanese faces of the pinned craft-fonts
+ /// are 24.1 MB.
+ #[test]
+ fn cjk_faces_follow_the_size_rule() {
+ use crate::cjk_scripts::{MAX_OTHER_CJK_BYTES, WHOLE_CJK_FAMILIES, is_cjk_script};
+ // A tag can carry a region after the code: craft-fonts tags Noto Sans HK UI `Hant-HK`.
+ assert!(["Hant-HK", "Hans", "Jpan", "Hang"].iter().all(|s| is_cjk_script(s)));
+ assert!(!["Latn", "Arab", "Hebr"].iter().any(|s| is_cjk_script(s)));
+ let cjk = CRAFT_FONTS.iter().filter(|f| f.scripts.iter().any(|s| is_cjk_script(s)));
+ let (whole, other): (Vec<_>, Vec<_>) = cjk.partition(|f| WHOLE_CJK_FAMILIES.contains(&f.family));
+ for face in &other {
+ let len = face.bytes.len();
+ assert!(u64::try_from(len).is_ok_and(|n| n <= MAX_OTHER_CJK_BYTES), "{} is embedded at {len} bytes", face.name());
+ }
+ let bytes: usize = whole.iter().map(|f| f.bytes.len()).sum();
+ assert!(bytes < 25_000_000, "{bytes} bytes of Japanese faces");
+ }
+
/// The bundled Inter faces carry the Latin, Greek and Cyrillic letters the craft-fonts faces
/// lack: Uzbek қ ғ ҳ, Kazakh ә ө ү ұ һ, Ukrainian ї є ґ, Greek. This one runs with or without
/// CRAFT_FONTS_DIR (#2593).
diff --git a/crates/fonts/src/fallback.rs b/crates/fonts/src/fallback.rs
index 64069a3..d309c6b 100644
--- a/crates/fonts/src/fallback.rs
+++ b/crates/fonts/src/fallback.rs
@@ -156,8 +156,7 @@ impl Substitution {
fn script_for(ordering: &str) -> Option<&'static str> {
match ordering {
"Japan1" => Some("Jpan"),
- // Registered orderings we have no openly licensed face for. AGENTS.md 1.1 rules out
- // Source Han and Noto CJK (Source Han rebranded), which is why these have none.
+ // Registered orderings the chain maps to no craft-fonts face.
"GB1" | "CNS1" | "Korea1" | "KR" => Some(""),
_ => None,
}
diff --git a/crates/fonts/src/lib.rs b/crates/fonts/src/lib.rs
index c923e05..7a1643b 100644
--- a/crates/fonts/src/lib.rs
+++ b/crates/fonts/src/lib.rs
@@ -7,6 +7,8 @@
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
+#[cfg(test)]
+mod cjk_scripts;
mod craft;
pub mod embedding;
mod encodings;
diff --git a/crates/fonts/src/std14.rs b/crates/fonts/src/std14.rs
index aae6575..13bb5b7 100644
--- a/crates/fonts/src/std14.rs
+++ b/crates/fonts/src/std14.rs
@@ -59,7 +59,7 @@ impl Std14 {
/// report that called it a standard-14 name would be telling the reader something untrue.
pub fn recognise(base: &str) -> Option<(Self, Match)> {
let base = base.rsplit('+').next().unwrap_or(base);
- let flat: String = base.chars().filter(|c| c.is_ascii_alphanumeric()).map(|c| c.to_ascii_lowercase()).collect();
+ let flat: String = base.chars().filter(char::is_ascii_alphanumeric).map(|c| c.to_ascii_lowercase()).collect();
let has = |w: &str| flat.contains(w);
let (bold, italic) = (has("bold"), has("italic") || has("oblique"));
// Two bools index a four-element array, so the subscript is provably 0..=3.
diff --git a/crates/forms/README.md b/crates/forms/README.md
index fde9287..664a8d7 100644
--- a/crates/forms/README.md
+++ b/crates/forms/README.md
@@ -39,8 +39,9 @@ let cells: Vec<table::Cell> = grid.cells_for(names)?; // "Table1_1", "Table
- Inheritable attributes (`/FT`, `/Ff`, `/V`, `/DV`, `/DA`, `/Q`, `/MaxLen`) are resolved down the
field tree; the form's `/DA` and `/Q` are the last fallback.
-- Text and choice fields get new appearance streams (`/Tx BMC … EMC`): auto-size (`0 Tf`), comb,
- multiline wrapping, password masking, quadding, `/MK` background and border, list-box selection.
+- Text and choice fields get new appearance streams (`/Tx BMC … EMC`): auto-size (`0 Tf`), comb
+ (cells parted in the border colour), multiline wrapping, password masking, quadding, `/MK`
+ background and border, list-box selection.
The `/DA` font is used when `/DR` has it as a simple font or a composite font with a predefined
Unicode CMap; otherwise Helvetica (WinAnsi), or, for a value WinAnsi can't hold but the bundled
Inter can (Turkish, Polish, Greek, Cyrillic, …), Inter's outlines with no font at all. A value or
@@ -57,7 +58,9 @@ let cells: Vec<table::Cell> = grid.cells_for(names)?; // "Table1_1", "Table
drawn from their values, as typing them would draw them; the engine shows and prints that copy
and saves the file as it was (#3470). `with_field_appearances_cached` keeps each widget's
drawing while the objects it was drawn from are the same (`FieldAppearanceCache`), so typing in
- one field redraws that field, not the form.
+ one field redraws that field, not the form. Check boxes and radio buttons with no appearance for
+ their state are drawn from `/MK` (border, background, and when on the `/MK /CA` ZapfDingbats
+ symbol in the `/DA` colour), and push buttons with none from `/MK`, `/BS` and their caption.
- Check boxes and radio buttons switch `/V` and each widget's `/AS`. Widgets with no appearances
get PdfCraft's own (a drawn check mark or dot; no symbol font needed).
- Imported `/MaxLen 0` is treated as unlimited (also clearing an inherited limit), while the
diff --git a/crates/forms/src/actions.rs b/crates/forms/src/actions.rs
index cdc89e5..f58bd10 100644
--- a/crates/forms/src/actions.rs
+++ b/crates/forms/src/actions.rs
@@ -159,6 +159,60 @@ pub fn field_actions(doc: &Document, name: &str) -> Result<Vec<(Trigger, FieldAc
Ok(out)
}
+/// Most chained actions [`field_action_chains`] walks per trigger.
+const MAX_CHAIN: usize = 1000;
+
+/// How many actions follow `action` through `/Next` (a dictionary or an array of them, each with
+/// its own `/Next`), counting each object once.
+fn chained(doc: &Document, action: &Object) -> usize {
+ let mut seen = std::collections::HashSet::new();
+ if let Object::Ref(r) = action {
+ seen.insert(*r);
+ }
+ let mut stack: Vec<Object> = doc.resolve(action).as_dict().and_then(|d| d.get(b"Next").cloned()).into_iter().collect();
+ let mut count = 0;
+ while let Some(o) = stack.pop() {
+ if count >= MAX_CHAIN {
+ break;
+ }
+ if let Object::Ref(r) = &o
+ && !seen.insert(*r)
+ {
+ continue;
+ }
+ match &*doc.resolve(&o) {
+ Object::Array(items) => stack.extend(items.iter().cloned()),
+ Object::Dict(d) => {
+ count += 1;
+ stack.extend(d.get(b"Next").cloned());
+ }
+ _ => {}
+ }
+ }
+ count
+}
+
+/// For each trigger of field `name` (its first widget) whose action has others chained after it,
+/// how many there are.
+pub fn field_action_chains(doc: &Document, name: &str) -> Result<Vec<(Trigger, usize)>, FormError> {
+ let all = fields(doc);
+ let f = all.iter().find(|f| f.name == name).ok_or_else(|| FormError::NoSuchField(name.into()))?;
+ let Some(w) = f.widgets.first() else { return Ok(Vec::new()) };
+ let wd = doc.get(w.obj).as_dict().cloned().unwrap_or_default();
+ let aa = wd.get(b"AA").map(|a| doc.resolve(a)).and_then(|a| a.as_dict().cloned()).unwrap_or_default();
+ Ok(Trigger::ALL
+ .into_iter()
+ .filter_map(|t| {
+ let o = match t.key() {
+ None => wd.get(b"A").cloned().or_else(|| aa.get(b"U").cloned()),
+ Some(k) => aa.get(k).cloned(),
+ }?;
+ let n = chained(doc, &o);
+ (n > 0).then_some((t, n))
+ })
+ .collect())
+}
+
fn write(doc: &mut Document, a: &FieldAction, pages: &[pdfcraft_cos::ObjRef]) -> Result<Option<Object>, FormError> {
let mut d = Dict::new();
d.set(b"Type".to_vec(), Object::name("Action"));
@@ -207,11 +261,13 @@ fn write(doc: &mut Document, a: &FieldAction, pages: &[pdfcraft_cos::ObjRef]) ->
}
/// Replace field `name`'s actions (on every widget) with `actions`; triggers not listed lose
-/// theirs. `Other` actions are left as they are.
+/// theirs. `Other` actions, and actions that read the same as before, are left as they are (with
+/// their chain and the keys this module doesn't read); a replaced action keeps its chain.
pub fn set_field_actions(doc: &mut Document, name: &str, actions: &[(Trigger, FieldAction)]) -> Result<(), FormError> {
let all = fields(doc);
let f = all.iter().find(|f| f.name == name).ok_or_else(|| FormError::NoSuchField(name.into()))?.clone();
let pages = crate::page_refs(doc);
+ let mut scripts = crate::script_budget();
for w in &f.widgets {
let wd = doc.get(w.obj).as_dict().cloned().unwrap_or_default();
let mut aa = wd.get(b"AA").map(|a| doc.resolve(a)).and_then(|a| a.as_dict().cloned()).unwrap_or_default();
@@ -221,10 +277,23 @@ pub fn set_field_actions(doc: &mut Document, name: &str, actions: &[(Trigger, Fi
if matches!(new, Some(FieldAction::Other(_))) {
continue;
}
+ let old = match t.key() {
+ None => wd.get(b"A").cloned().or_else(|| aa.get(b"U").cloned()),
+ Some(k) => aa.get(k).cloned(),
+ };
+ let old_action = old.as_ref().and_then(|o| read(doc, o, &pages, &mut scripts));
+ if new.is_some() && new == old_action.as_ref() {
+ continue;
+ }
+ // The list shows a trigger's first action: replacing it keeps the ones chained after it.
+ let next = new.and(old).and_then(|o| doc.resolve(&o).as_dict().and_then(|d| d.get(b"Next").cloned()));
let obj = match new {
Some(a) => write(doc, a, &pages)?,
None => None,
};
+ if let (Some(Object::Ref(r)), Some(next)) = (&obj, next) {
+ doc.update_dict(*r, |d| d.set(b"Next".to_vec(), next))?;
+ }
match t.key() {
None => {
a_entry = obj;
diff --git a/crates/forms/src/af.rs b/crates/forms/src/af.rs
index 39e3b8a..7b706e9 100644
--- a/crates/forms/src/af.rs
+++ b/crates/forms/src/af.rs
@@ -379,10 +379,12 @@ pub fn parse_validate(js: &str) -> Option<Validate> {
}
pub fn parse_calculate(js: &str) -> Option<Calculate> {
- // Simplified field notation: Acrobat keeps the expression in a comment.
- if let (Some(a), Some(b)) = (js.find("BVCALC"), js.find("EVCALC")) {
- let expr = js.get(a + 6..b)?.trim().to_string();
- return Some(Calculate::Notation(expr));
+ // Simplified field notation: Acrobat keeps the expression in a comment. A script is read for
+ // its comments only when it spells the marker.
+ if js.contains("BVCALC")
+ && let Some(range) = notation_range(js, &js_tokens(js).1)
+ {
+ return Some(Calculate::Notation(js.get(range)?.trim().to_string()));
}
let args = call(js, "AFSimple_Calculate")?;
let op = match args.first().and_then(Arg::string)?.as_str() {
@@ -479,21 +481,41 @@ enum Js {
Other,
}
+/// A [`Js`] token with its byte range in the script.
+type Token = (Range<usize>, Js);
+
/// Words after which `/` starts a regular expression instead of dividing.
const BEFORE_REGEX: [&str; 13] = ["return", "typeof", "case", "do", "else", "in", "of", "new", "delete", "void", "throw", "instanceof", "yield"];
-/// JavaScript's tokens with their byte ranges, comments left out: enough of the language to tell
-/// code from strings, comments and regular expressions. The tokens stop where a string, comment
-/// or template literal never ends.
-fn js_tokens(js: &str) -> Vec<(Range<usize>, Js)> {
+/// Words whose condition, in parentheses, comes before a statement, so a `/` after it starts a
+/// regular expression. The `while` that ends a `do` loop counts too: the loop ends at its `)`, so
+/// a `/` after it starts the next statement, and can't divide.
+const BEFORE_CONDITION: [&str; 4] = ["if", "while", "for", "with"];
+
+/// Whether a line ends at `s[j]`: JavaScript ends one at `\n`, `\r`, U+2028 and U+2029.
+fn line_ends_at(s: &[u8], j: usize) -> bool {
+ matches!(s.get(j..), Some([b'\n' | b'\r', ..] | [0xE2, 0x80, 0xA8 | 0xA9, ..]))
+}
+
+/// JavaScript's tokens with their byte ranges, and apart from them the text of each comment
+/// (inside its `//`, or its `/*` and `*/`): enough of the language to tell code from strings,
+/// comments and regular expressions. The tokens stop where a string, comment or template literal
+/// never ends; a comment that never ends runs to the end of the script.
+fn js_tokens(js: &str) -> (Vec<Token>, Vec<Range<usize>>) {
let s = js.as_bytes();
- // Bytes past ASCII are parts of identifiers, so a range never ends inside a character.
- let word = |b: u8| b.is_ascii_alphanumeric() || b == b'_' || b == b'$' || !b.is_ascii();
- let mut out: Vec<(Range<usize>, Js)> = Vec::new();
+ // Whether `s[j]` is part of a word. Bytes past ASCII are parts of identifiers, except
+ // U+2028 and U+2029, which end a line: a range never ends inside a character.
+ let word = |j: usize| s.get(j).is_some_and(|&b| b.is_ascii_alphanumeric() || b == b'_' || b == b'$' || !b.is_ascii()) && !line_ends_at(s, j);
+ let mut out: Vec<Token> = Vec::new();
+ let mut comments = Vec::new();
let mut i = 0;
// Where a regular expression that never ended stopped being read: every `/` before it
// divides, so a line of them is read once, not once for each.
let mut divides_until = 0;
+ // For each `(` still open, whether it opened the condition of `if`, `while`, `for` or
+ // `with`; and whether the last token is the `)` that closed one.
+ let mut conditions: Vec<bool> = Vec::new();
+ let mut after_condition = false;
'scan: while let Some(&c) = s.get(i) {
let start = i;
let token = match c {
@@ -501,16 +523,27 @@ fn js_tokens(js: &str) -> Vec<(Range<usize>, Js)> {
i += 1;
continue;
}
+ // U+2028 or U+2029 between tokens ends a line, and is skipped whole: read a byte at a
+ // time, the rest of it would be read from inside the character.
+ 0xE2 if line_ends_at(s, i) => {
+ i += 3;
+ continue;
+ }
b'/' if s.get(i + 1) == Some(&b'/') => {
- i = s.iter().skip(i).position(|b| *b == b'\n').map_or(s.len(), |n| i + n);
+ i = (i + 2..s.len()).find(|&j| line_ends_at(s, j)).unwrap_or(s.len());
+ comments.push(start + 2..i);
continue;
}
b'/' if s.get(i + 1) == Some(&b'*') => match js.get(i + 2..).and_then(|rest| rest.find("*/")) {
Some(n) => {
+ comments.push(i + 2..i + 2 + n);
i += n + 4;
continue;
}
- None => break 'scan,
+ None => {
+ comments.push(i + 2..s.len());
+ break 'scan;
+ }
},
b'"' | b'\'' => {
let mut p = Parser { s, i, depth: 0 };
@@ -531,13 +564,14 @@ fn js_tokens(js: &str) -> Vec<(Range<usize>, Js)> {
i = j + 1;
Js::Other
}
- b'/' if i >= divides_until && regex_may_follow(js, &out) => {
+ b'/' if i >= divides_until && regex_may_follow(js, &out, after_condition) => {
// A regular expression ends at a `/` outside a class; a line break first means it
// was a division after all.
let (mut j, mut class) = (i + 1, false);
let end = loop {
match s.get(j) {
- None | Some(b'\n') => break None,
+ None => break None,
+ Some(_) if line_ends_at(s, j) => break None,
Some(b'\\') => j += 2,
Some(b'/') if !class => break Some(j),
Some(b) => {
@@ -553,7 +587,7 @@ fn js_tokens(js: &str) -> Vec<(Range<usize>, Js)> {
match end {
Some(e) => {
i = e + 1;
- while s.get(i).is_some_and(|b| word(*b)) {
+ while word(i) {
i += 1;
}
Js::Other
@@ -566,13 +600,13 @@ fn js_tokens(js: &str) -> Vec<(Range<usize>, Js)> {
}
}
_ if c.is_ascii_digit() => {
- while s.get(i).is_some_and(|b| word(*b) || *b == b'.') {
+ while word(i) || s.get(i) == Some(&b'.') {
i += 1;
}
Js::Other
}
- _ if word(c) => {
- while s.get(i).is_some_and(|b| word(*b)) {
+ _ if word(i) => {
+ while word(i) {
i += 1;
}
Js::Ident
@@ -582,22 +616,52 @@ fn js_tokens(js: &str) -> Vec<(Range<usize>, Js)> {
Js::Punct(char::from(c))
}
};
+ after_condition = match token {
+ Js::Punct('(') => {
+ conditions.push(opens_condition(js, &out));
+ false
+ }
+ Js::Punct(')') => conditions.pop().unwrap_or(false),
+ _ => false,
+ };
out.push((start..i, token));
}
- out
+ (out, comments)
}
/// Whether a `/` after `tokens` starts a regular expression: after an operator, an opening
-/// bracket or a keyword such as `return`, not after a value.
-fn regex_may_follow(js: &str, tokens: &[(Range<usize>, Js)]) -> bool {
+/// bracket, a keyword such as `return` or the condition of `if`, `while`, `for` or `with`, not
+/// after a value. `after_condition` says the last token is the `)` that ends such a condition.
+fn regex_may_follow(js: &str, tokens: &[Token], after_condition: bool) -> bool {
match tokens.last() {
None => true,
Some((range, Js::Ident)) => js.get(range.clone()).is_some_and(|w| BEFORE_REGEX.contains(&w)),
- Some((_, Js::Punct(c))) => !matches!(c, ')' | ']' | '}'),
+ Some((_, Js::Punct(')'))) => after_condition,
+ Some((_, Js::Punct(c))) => !matches!(c, ']' | '}'),
Some((_, Js::Str(_) | Js::Other)) => false,
}
}
+/// Whether a `(` after `tokens` opens the condition of `if`, `while`, `for` or `with`, and not
+/// the arguments of a method that has one of those names (`o.if(x)`).
+fn opens_condition(js: &str, tokens: &[Token]) -> bool {
+ let mut back = tokens.iter().rev();
+ let Some((range, Js::Ident)) = back.next() else { return false };
+ js.get(range.clone()).is_some_and(|w| BEFORE_CONDITION.contains(&w)) && !matches!(back.next(), Some((_, Js::Punct('.'))))
+}
+
+/// Where a Calculate script keeps its simplified field notation: between `BVCALC` and the
+/// `EVCALC` after it, in the first of `comments` that holds both, as Acrobat writes it
+/// (`/** BVCALC a + b EVCALC **/`). A string or code that spells the markers is not the notation.
+fn notation_range(js: &str, comments: &[Range<usize>]) -> Option<Range<usize>> {
+ comments.iter().find_map(|comment| {
+ let text = js.get(comment.clone())?;
+ let a = text.find("BVCALC")? + 6;
+ let b = a + text.get(a..)?.find("EVCALC")?;
+ Some(comment.start + a..comment.start + b)
+ })
+}
+
/// A place where a Calculate script names a field.
#[derive(Clone, Debug, PartialEq)]
enum Site {
@@ -635,22 +699,22 @@ impl Site {
}
}
-/// Where a Calculate script names fields, in order: the simplified field notation between
-/// `BVCALC` and `EVCALC` (where [`parse_calculate`] reads it), the field list of
+/// Where a Calculate script names fields, in order: the simplified field notation in its comment
+/// (see [`notation_range`]; [`parse_calculate`] reads it there too), the field list of
/// `AFSimple_Calculate`, and every `getField` whose whole argument is one string literal.
/// A name built at run time (`getField("row" + i)`) is not a site.
fn calculation_sites(js: &str) -> Vec<(Range<usize>, Site)> {
let mut sites = Vec::new();
- if let (Some(a), Some(b)) = (js.find("BVCALC"), js.find("EVCALC"))
- && let Some(expr) = js.get(a + 6..b)
+ let (tokens, comments) = js_tokens(js);
+ if let Some(at) = notation_range(js, &comments)
+ && let Some(expr) = js.get(at.clone())
{
for (range, token) in notation_tokens(expr) {
if let Notation::Name(name) = token {
- sites.push((a + 6 + range.start..a + 6 + range.end, Site::Notation(name)));
+ sites.push((at.start + range.start..at.start + range.end, Site::Notation(name)));
}
}
}
- let tokens = js_tokens(js);
let ident = |k: usize, word: &str| tokens.get(k).is_some_and(|(range, t)| *t == Js::Ident && js.get(range.clone()) == Some(word));
let punct = |k: usize, c: char| tokens.get(k).is_some_and(|(_, t)| *t == Js::Punct(c));
let string = |k: usize| match tokens.get(k) {
@@ -1522,6 +1586,67 @@ mod tests {
}
}
+ /// The notation is read only from a comment, where Acrobat writes it: a string or code that
+ /// spells the markers is left alone, by the Calculate tab and by a rename.
+ #[test]
+ fn notation_is_read_only_from_a_comment() {
+ let string = "var s = \"BVCALC a EVCALC\"; event.value = getField(\"b\").value;";
+ assert_eq!(parse_calculate(string), None);
+ assert_eq!(rename_in_calculation(string, "a", "qty"), None);
+ // A comment after such a string holds the notation.
+ let both = "var s = 'BVCALC x EVCALC'; /** BVCALC a + 1 EVCALC **/ event.value = 1;";
+ assert_eq!(parse_calculate(both), Some(Calculate::Notation("a + 1".into())));
+ assert_eq!(rename_in_calculation(both, "x", "y"), None);
+ assert_eq!(rename_in_calculation(both, "a", "qty"), Some(both.replace("a + 1", "qty + 1")));
+ // A line comment is a comment too, and an unfinished one still holds it.
+ assert_eq!(parse_calculate("// BVCALC a EVCALC\nevent.value = 1;"), Some(Calculate::Notation("a".into())));
+ assert_eq!(parse_calculate("/** BVCALC a EVCALC"), Some(Calculate::Notation("a".into())));
+ }
+
+ /// A line comment ends at any of JavaScript's line terminators, not only `\n`, so with `\r` line
+ /// endings the code after one is still code; and a `/` read as starting a regular expression
+ /// divides after all when the line ends first.
+ #[test]
+ fn a_line_comment_ends_at_any_line_terminator() {
+ for end in ["\n", "\r", "\r\n", "\u{2028}", "\u{2029}"] {
+ let string = format!("// header{end}var s = \"BVCALC a EVCALC\"; event.value = getField(\"b\").value;");
+ assert_eq!(parse_calculate(&string), None, "{end:?}");
+ assert_eq!(rename_in_calculation(&string, "a", "qty"), None, "{end:?}");
+ let script = format!("// note{end}getField(\"a\").value;");
+ assert_eq!(rename_in_calculation(&script, "a", "qty"), Some(script.replace("\"a\"", "\"qty\"")), "{end:?}");
+ let divides = format!("var n = i++ / 2;{end}event.value = getField(\"a\").value / 4;");
+ assert_eq!(rename_in_calculation(&divides, "a", "qty"), Some(divides.replace("\"a\"", "\"qty\"")), "{end:?}");
+ }
+ }
+
+ /// U+2028 and U+2029 end a word, a number or a regular expression's flags, though as bytes
+ /// past ASCII they could be part of one, so a `getField` right after one is still a call.
+ #[test]
+ fn a_token_ends_at_a_line_separator() {
+ for end in ["\u{2028}", "\u{2029}"] {
+ let scripts = ["x", "1", "/r/g"].map(|token| format!("var t = {token}{end}getField(\"a\").value;"));
+ let renamed = scripts.clone().map(|js| rename_in_calculation(&js, "a", "qty"));
+ assert_eq!(renamed, scripts.map(|js| Some(js.replace("\"a\"", "\"qty\""))), "{end:?}");
+ }
+ }
+
+ /// A `/` after the condition of `if`, `while`, `for` or `with` starts a regular expression,
+ /// as after an operator; after a call's parentheses it still divides.
+ #[test]
+ fn a_regex_after_a_condition_is_not_read_as_code() {
+ let renamed = |js: &str| rename_in_calculation(js, "a", "qty");
+ assert_eq!(renamed("if (flag) /getField(\"a\")/.test(x); event.value = 1;"), None);
+ // A quote inside it doesn't start a string that hides the rest of the script.
+ let quote = "while (i--) /\"/.test(s); event.value = getField(\"a\").value;";
+ assert_eq!(renamed(quote), Some(quote.replace("\"a\"", "\"qty\"")));
+ // The same after the `while` that ends a `do` loop.
+ let after_do = "do i++; while (i < n) /\"/.test(s); event.value = getField(\"a\").value;";
+ assert_eq!(renamed(after_do), Some(after_do.replace("\"a\"", "\"qty\"")));
+ // After a call, or a method that happens to be called `if`, the `/` divides.
+ let divides = "event.value = Math.abs(getField(\"b\").value) / 2 + getField(\"a\").value / 3 + o.if(x) / 4 + getField(\"a\").value / 5;";
+ assert_eq!(renamed(divides), Some(divides.replace("\"a\"", "\"qty\"")));
+ }
+
/// Scripts are read in one pass: a line of unfinished regular expressions, or calls nested in
/// one another's field lists, don't make a rename read the rest of the script again for each.
#[test]
diff --git a/crates/forms/src/appearance.rs b/crates/forms/src/appearance.rs
index 3fcb190..5b6a3d0 100644
--- a/crates/forms/src/appearance.rs
+++ b/crates/forms/src/appearance.rs
@@ -72,6 +72,134 @@ pub fn auto_text_size_by(width: f64, height: f64, multiline: bool, line_width: i
if tw.is_finite() && tw > width { (size * width / tw).max(4.0) } else { size }
}
+/// How a text field's widget lays its value out in [`field_appearance_drawn`], for asking
+/// whether a value fits it ([`TextBox::fits`]): what a field that doesn't scroll (`DoNotScroll`,
+/// ISO 32000-2 Table 228) still takes. Built from the same pieces the appearance uses: the `/DA`
+/// font from the form's `/DR` (Helvetica where that font can't show the text), the room inside
+/// the border and the 2 pt padding, the `/DA` size (or the automatic size), and wrapping for a
+/// multi-line field; the two must change together.
+#[derive(Clone, Debug, PartialEq)]
+pub struct TextBox {
+ /// The `/DA` font from `/DR`, when it is one the appearance can draw with.
+ font: Option<FontText>,
+ /// Width and height inside the border and padding.
+ inner_w: f64,
+ inner_h: f64,
+ /// The `/DA` size; `None` for an automatic (`0 Tf`) size, which shrinks to fit.
+ size: Option<f64>,
+ multiline: bool,
+ password: bool,
+ /// A comb field: its cells, not its width, bound it (`/MaxLen`).
+ comb: bool,
+}
+
+/// The [`TextBox`] widget `w` of text field `f` lays its value out in.
+pub fn text_box(doc: &Document, f: &Field, w: &Widget) -> TextBox {
+ let wobj = doc.get(w.obj);
+ let wd = wobj.as_dict().cloned().unwrap_or_default();
+ let (page_w, page_h) = ((w.rect[2] - w.rect[0]).max(1.0), (w.rect[3] - w.rect[1]).max(1.0));
+ let place = placement(mk_rotation(doc, &wd), page_w, page_h);
+ let da = parse_da(wd.get(b"DA").and_then(|o| doc.resolve(o).as_string().map(|s| s.to_text())).as_deref().unwrap_or(&f.da));
+ let pad = 2.0 + border_width(doc, &wd);
+ let multiline = f.has(flags::MULTILINE);
+ TextBox {
+ font: dr_font(doc, &da.font).map(|(_, enc)| enc),
+ inner_w: (place.layout_w - 2.0 * pad).max(1.0),
+ inner_h: place.layout_h - 2.0 * pad,
+ size: (da.size > 0.0 && da.size.is_finite()).then_some(da.size),
+ multiline,
+ password: f.has(flags::PASSWORD),
+ comb: f.has(flags::COMB) && !multiline && !f.has(flags::PASSWORD) && f.max_len.is_some_and(|m| m > 0),
+ }
+}
+
+impl TextBox {
+ /// Whether `text` fits: on one line within the width, or, multi-line, wrapped within the
+ /// height, as the appearance draws it. An automatic size shrinks before text stops fitting,
+ /// so such a field is full only when the text no longer fits at its smallest size (4 pt). A
+ /// comb field always fits (its `/MaxLen` bounds it).
+ pub fn fits(&self, text: &str) -> bool {
+ if self.comb || text.is_empty() {
+ return true;
+ }
+ let shown: String = if self.password { "*".repeat(text.chars().count()) } else { text.to_string() };
+ // The font the appearance would choose for this text.
+ let can_show = |enc: &FontText| if self.multiline { shown.split(['\n', '\r']).all(|l| enc.can_encode(l)) } else { enc.can_encode(&shown) };
+ let font = self.font.as_ref().filter(|enc| can_show(enc)).unwrap_or(&FontText::WinAnsi);
+ let width_of = |t: &str, size: f64| font.width(t, size);
+ // The smallest an automatic size goes ([`auto_text_size_by`]).
+ let size = self.size.unwrap_or(4.0);
+ if self.multiline {
+ // As the appearance draws it: the first baseline is 0.85 em below the padded top and
+ // a line is drawn while its descent (0.207 em) stays inside the border, so the
+ // padding below the last line is not needed: `inner_h` plus 2 pt.
+ // Long words break by character, so a line is wider than the box only when it is a
+ // single character wider than the box, which the appearance still cuts at the sides.
+ let lines = wrap_with(&shown, size, self.inner_w, width_of);
+ let above = lines.len().saturating_sub(1) as f64;
+ above * size * 1.15 + 1.057 * size <= self.inner_h + 2.0 + 0.01 && lines.iter().all(|l| width_of(l, size) <= self.inner_w + 0.01)
+ } else {
+ // A line break in a single-line value is drawn as a space.
+ let line: String = shown.chars().map(|c| if matches!(c, '\n' | '\r') { ' ' } else { c }).collect();
+ width_of(&line, size) <= self.inner_w + 1e-6
+ }
+ }
+
+ /// An edit from `before` to `after` as a field that doesn't scroll takes it: all of it when
+ /// `after` fits, and otherwise as much of the text it inserted (typed or pasted) as still
+ /// fits, keeping what it removed removed. Returns the text and where the caret goes (in
+ /// characters, after what was kept of the insertion).
+ pub fn fitted_edit(&self, before: &str, after: &str) -> (String, usize) {
+ let (b, a): (Vec<char>, Vec<char>) = (before.chars().collect(), after.chars().collect());
+ // The edit replaced b[p..b.len() - q] with a[p..a.len() - q].
+ let p = b.iter().zip(&a).take_while(|(x, y)| x == y).count();
+ let most = b.len().min(a.len()).saturating_sub(p);
+ let q = b.iter().rev().zip(a.iter().rev()).take(most).take_while(|(x, y)| x == y).count();
+ // q <= a.len() - p, so these are in range; `get` keeps it so if that ever changes.
+ let end = a.len().saturating_sub(q);
+ let (prefix, inserted, suffix) = (a.get(..p).unwrap_or_default(), a.get(p..end).unwrap_or_default(), a.get(end..).unwrap_or_default());
+ let with = |k: usize| prefix.iter().chain(inserted.get(..k).unwrap_or_default()).chain(suffix).collect::<String>();
+ if self.fits(after) {
+ return (after.to_string(), p + inserted.len());
+ }
+ // The longest of the insertion's first `from..=to` characters that fits, halving: in one
+ // font a longer text is never narrower. `None` when even `from` doesn't fit.
+ let longest = |from: usize, to: usize| -> Option<usize> {
+ if from > to || !self.fits(&with(from)) {
+ return None;
+ }
+ let (mut lo, mut hi) = (from, to);
+ while lo < hi {
+ let mid = lo + (hi - lo).div_ceil(2);
+ if self.fits(&with(mid)) { lo = mid } else { hi = mid - 1 }
+ }
+ Some(lo)
+ };
+ // The font can change once, from the form's own to Helvetica, at the first inserted
+ // character the form's font can't show: each side of that point is searched on its own.
+ let n = inserted.len();
+ let kept = match self.font_switch(prefix, inserted, suffix) {
+ Some(t) => longest(0, t.saturating_sub(1)).into_iter().chain(longest(t, n)).max(),
+ None => longest(0, n),
+ }
+ .unwrap_or(0);
+ (with(kept), p + kept)
+ }
+
+ /// Where an insertion changes the font [`Self::fits`] measures in: how much of `inserted`
+ /// (between `prefix` and `suffix`) first includes a character the form's own font can't show,
+ /// when everything around it can be shown in that font. `None` when the font never changes.
+ fn font_switch(&self, prefix: &[char], inserted: &[char], suffix: &[char]) -> Option<usize> {
+ let enc = self.font.as_ref().filter(|_| !self.password)?;
+ // As `fits` decides: a multi-line value is checked line by line, its breaks aside.
+ let shows = |c: &char| (self.multiline && matches!(c, '\n' | '\r')) || enc.can_encode(&c.to_string());
+ if !prefix.iter().chain(suffix).all(shows) {
+ return None;
+ }
+ inserted.iter().position(|c| !shows(c)).map(|i| i + 1)
+ }
+}
+
/// `/MK /R` as a quadrant, or 0 when it is missing or not a multiple of 90.
pub(crate) fn mk_rotation(doc: &Document, wd: &Dict) -> i64 {
let Some(raw) = wd.get(b"MK") else { return 0 };
@@ -285,10 +413,14 @@ fn stroke_op(fill: &str) -> String {
}
}
-/// Background and border from `/MK` and `/BS`; returns (content, border width).
+/// Background and border from `/MK` and `/BS`; returns (content, border width). A round XFA
+/// check button's ([`is_round`]) are a circle inside the widget instead of its rectangle.
fn frame(doc: &Document, wd: &Dict, w: f64, h: f64) -> (String, f64) {
let mk = wd.get(b"MK").map(|m| doc.resolve(m)).and_then(|m| m.as_dict().cloned());
let mut c = String::new();
+ if is_round(doc, wd) {
+ return round_frame(doc, wd, mk.as_ref(), w, h);
+ }
if let Some(bg) = color_array(doc, mk.as_ref(), b"BG") {
c.push_str(&format!("{bg}\n0 0 {} {} re f\n", n(w), n(h)));
}
@@ -354,12 +486,89 @@ fn frame(doc: &Document, wd: &Dict, w: f64, h: f64) -> (String, f64) {
(c, 0.0)
}
+/// Whether `wd` is a check box or radio button PdfCraft laid out for a round XFA check button
+/// (`/PCXfaRound true`, written by the XFA layout).
+fn is_round(doc: &Document, wd: &Dict) -> bool {
+ matches!(wd.get(b"PCXfaRound").map(|o| doc.resolve(o)).as_deref(), Some(Object::Bool(true)))
+}
+
+/// [`frame`] for a round check button: the `/MK /BG` background as a disc and the `/MK /BC`
+/// border as a circle, both centred in the `w` × `h` box and as wide as its shorter side. A
+/// dashed border stays dashed and an underline stays an underline; any other style is drawn
+/// solid, and a border as wide as the circle fills it. Returns the border width.
+fn round_frame(doc: &Document, wd: &Dict, mk: Option<&Dict>, w: f64, h: f64) -> (String, f64) {
+ let mut c = String::new();
+ let (cx, cy, r) = (w / 2.0, h / 2.0, w.min(h).max(0.0) / 2.0);
+ if let Some(bg) = color_array(doc, mk, b"BG") {
+ c.push_str(&format!("{bg}\n{}f\n", circle_path(cx, cy, r)));
+ }
+ let bs = wd.get(b"BS").map(|b| doc.resolve(b)).and_then(|b| b.as_dict().cloned());
+ let bw = bs.as_ref().and_then(|b| b.get(b"W")).and_then(|x| doc.resolve(x).as_f64()).unwrap_or(1.0).max(0.0);
+ let style = bs.as_ref().and_then(|b| b.name(b"S").map(<[u8]>::to_vec)).unwrap_or_default();
+ match color_array(doc, mk, b"BC") {
+ // An underline stays one: only the bottom edge, as for any widget.
+ Some(bc) if bw > 0.0 && style == b"U" => {
+ c.push_str(&format!("{}\n{} w\n0 {} m {} {} l S\n", stroke_op(&bc), n(bw), n(bw / 2.0), n(w), n(bw / 2.0)));
+ (c, bw)
+ }
+ // A border as wide as the circle fills it: a disc in the border's colour.
+ Some(bc) if bw > 0.0 && bw >= 2.0 * r => {
+ c.push_str(&format!("{bc}\n{}f\n", circle_path(cx, cy, r)));
+ (c, 2.0 * r)
+ }
+ Some(bc) if bw > 0.0 => {
+ let dashed = style == b"D";
+ // The stroke is centred on the path: inset by half its width, it stays inside.
+ let path = circle_path(cx, cy, r - bw / 2.0);
+ c.push_str(&format!("{}\n{} w\n{}{path}S\n[] 0 d\n", stroke_op(&bc), n(bw), if dashed { "[3] 0 d\n" } else { "" }));
+ (c, bw)
+ }
+ _ => (c, 0.0),
+ }
+}
+
+/// A closed circle of radius `r` around (`cx`, `cy`) as four Bézier arcs, ending with a space
+/// so a paint operator can follow.
+fn circle_path(cx: f64, cy: f64, r: f64) -> String {
+ // The control-point distance for a quarter circle.
+ let k = 0.5523 * r;
+ format!(
+ "{} {} m {} {} {} {} {} {} c {} {} {} {} {} {} c {} {} {} {} {} {} c {} {} {} {} {} {} c ",
+ n(cx + r),
+ n(cy),
+ n(cx + r),
+ n(cy + k),
+ n(cx + k),
+ n(cy + r),
+ n(cx),
+ n(cy + r),
+ n(cx - k),
+ n(cy + r),
+ n(cx - r),
+ n(cy + k),
+ n(cx - r),
+ n(cy),
+ n(cx - r),
+ n(cy - k),
+ n(cx - k),
+ n(cy - r),
+ n(cx),
+ n(cy - r),
+ n(cx + k),
+ n(cy - r),
+ n(cx + r),
+ n(cy - k),
+ n(cx + r),
+ n(cy)
+ )
+}
+
/// The width [`frame`] insets the content by: the `/BS` border width when the widget has a
/// border colour, doubled for beveled and inset borders, and 0 without a border.
fn border_width(doc: &Document, wd: &Dict) -> f64 {
let mk = wd.get(b"MK").map(|m| doc.resolve(m)).and_then(|m| m.as_dict().cloned());
let bs = wd.get(b"BS").map(|b| doc.resolve(b)).and_then(|b| b.as_dict().cloned());
- let bw = bs.as_ref().and_then(|b| b.get(b"W")).and_then(|x| doc.resolve(x).as_f64()).unwrap_or(1.0).max(0.0);
+ let bw = line_width(doc, wd);
if color_array(doc, mk.as_ref(), b"BC").is_none() || bw <= 0.0 {
return 0.0;
}
@@ -367,6 +576,37 @@ fn border_width(doc: &Document, wd: &Dict) -> f64 {
if style == b"B" || style == b"I" { 2.0 * bw } else { bw }
}
+/// The widget's border line width, `/BS /W` (default 1, Table 168), as [`frame`] strokes it.
+fn line_width(doc: &Document, wd: &Dict) -> f64 {
+ let bs = wd.get(b"BS").map(|b| doc.resolve(b)).and_then(|b| b.as_dict().cloned());
+ // `f64::max` turns NaN into 0, as it does a negative width.
+ bs.as_ref().and_then(|b| b.get(b"W")).and_then(|x| doc.resolve(x).as_f64()).unwrap_or(1.0).max(0.0)
+}
+
+/// Comb fields stop drawing their cells past this many; they would be a solid block anyway.
+const MAX_COMB_DIVIDERS: usize = 500;
+
+/// The lines between the `cells` positions of a comb field `w` × `h` (ISO 32000-2 Table 228,
+/// Comb: the field is divided into `MaxLen` equally spaced positions), in the border's colour and
+/// width, inside the border. None without a border, or past [`MAX_COMB_DIVIDERS`] cells.
+fn comb_dividers(doc: &Document, wd: &Dict, w: f64, h: f64, cells: usize) -> String {
+ let mk = wd.get(b"MK").map(|m| doc.resolve(m)).and_then(|m| m.as_dict().cloned());
+ let inset = border_width(doc, wd);
+ let lw = line_width(doc, wd);
+ let Some(bc) = color_array(doc, mk.as_ref(), b"BC") else { return String::new() };
+ if !(inset > 0.0 && inset.is_finite() && lw > 0.0 && lw.is_finite()) || !(2..=MAX_COMB_DIVIDERS).contains(&cells) {
+ return String::new();
+ }
+ let cell = w / cells as f64;
+ let mut c = format!("{}\n{} w\n", stroke_op(&bc), n(lw));
+ for i in 1..cells {
+ let x = cell * i as f64;
+ c.push_str(&format!("{} {} m {} {} l\n", n(x), n(inset), n(x), n(h - inset)));
+ }
+ c.push_str("S\n");
+ c
+}
+
/// Where a list box draws its options: one row per option from the top, starting with option
/// `top` (`/TI`, §12.7.4.4). The appearance PdfCraft writes and the viewer's in-place list share
/// it, so a click picks the option drawn under the pointer (#1524).
@@ -457,6 +697,45 @@ pub fn field_appearance_as(doc: &Document, f: &Field, w: &Widget, values: &[Stri
/// hold it: the form's font is a simple (WinAnsi) font, Helvetica stands in for one PdfCraft can't
/// write with (an embedded subset, `Identity-H`), or a UCS-2 CMap meets a character beyond U+FFFF.
pub fn field_appearance_drawn(doc: &Document, f: &Field, w: &Widget, values: &[String], format: bool) -> (Stream, Option<char>) {
+ let (stream, unencodable, _) = field_appearance_fit(doc, f, w, values, format);
+ (stream, unencodable)
+}
+
+/// A text value that its box cuts off at the field's font size (#4018).
+#[derive(Clone, Debug, PartialEq)]
+pub enum Overflow {
+ /// One line `width` points wide, with `room` for it, at `size` points.
+ Wide { width: f64, room: f64, size: f64 },
+ /// `lines` wrapped lines, of which the box shows `room`, at `size` points.
+ Tall { lines: usize, room: usize, size: f64 },
+ /// One line `height` points high (ascent to descent), with `room` for it, at `size` points.
+ High { height: f64, room: f64, size: f64 },
+}
+
+impl std::fmt::Display for Overflow {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ match self {
+ Self::Wide { width, room, size } => {
+ write!(f, "the value does not fit: {} pt wide at {} pt, room for {} pt", fmt(*width), fmt(*size), fmt(*room))
+ }
+ Self::Tall { lines, room, size } => write!(f, "the value does not fit: {lines} lines at {} pt, room for {room}", fmt(*size)),
+ Self::High { height, room, size } => {
+ write!(f, "the value does not fit: {} pt high at {} pt, room for {} pt", fmt(*height), fmt(*size), fmt(*room))
+ }
+ }
+ }
+}
+
+/// Whether the text field's value, drawn in widget `w`, is cut off by its box.
+pub fn value_overflow(doc: &Document, f: &Field, w: &Widget) -> Option<Overflow> {
+ if f.kind != FieldKind::Text {
+ return None;
+ }
+ field_appearance_fit(doc, f, w, &f.value, true).2
+}
+
+/// [`field_appearance_drawn`], and whether the text drawn is cut off by the box.
+fn field_appearance_fit(doc: &Document, f: &Field, w: &Widget, values: &[String], format: bool) -> (Stream, Option<char>, Option<Overflow>) {
// The Format event: what is shown, not what is stored.
let formatted: Vec<String>;
let values = if format
@@ -536,6 +815,7 @@ pub fn field_appearance_drawn(doc: &Document, f: &Field, w: &Widget, values: &[S
}
};
let mut size = da.size;
+ let mut overflow = None;
match f.kind {
FieldKind::List => {
// Every option, one per line from the top (from `/TI`); selected ones highlighted.
@@ -562,13 +842,25 @@ pub fn field_appearance_drawn(doc: &Document, f: &Field, w: &Widget, values: &[S
size = auto_text_size(&text, inner_w, height - 2.0 * pad, true, width_of);
}
let mut y = height - pad - size * 0.85;
- for line in wrap_with(&text, size, inner_w, width_of) {
+ let lines = wrap_with(&text, size, inner_w, width_of);
+ // The lines whose descent stays inside the border; the rest are cut off.
+ let mut room = 0;
+ for line in &lines {
if y < -size {
break;
}
- show(&mut body, x_for(&line, size), y, &line, size);
+ if y - 0.207 * size >= bw - 0.01 {
+ room += 1;
+ }
+ show(&mut body, x_for(line, size), y, line, size);
y -= size * 1.15;
}
+ if room < lines.len() {
+ overflow = Some(Overflow::Tall { lines: lines.len(), room, size });
+ } else if let Some(tw) = lines.iter().map(|l| width_of(l, size)).filter(|tw| *tw > inner_w + 0.01).reduce(f64::max) {
+ // A character wider than the box is a line of its own, still cut at the sides.
+ overflow = Some(Overflow::Wide { width: tw, room: inner_w, size });
+ }
} else {
if size == 0.0 {
// Comb cells hold one character each, so only the height limits them.
@@ -580,14 +872,24 @@ pub fn field_appearance_drawn(doc: &Document, f: &Field, w: &Widget, values: &[S
}
// Centre Helvetica's ascent (0.718) and descent (0.207) vertically.
let y = (height - 0.925 * size) / 2.0 + 0.207 * size;
+ // The clip box is inside the border; a line taller than it is cut at the top and bottom.
+ let room_h = height - 2.0 * bw;
+ if 0.925 * size > room_h + 0.01 {
+ overflow = Some(Overflow::High { height: 0.925 * size, room: room_h, size });
+ }
if comb {
let cells = f.max_len.unwrap_or(1).max(1);
let cell = width / cells as f64;
+ c.push_str(&comb_dividers(doc, &wd, width, height, cells));
for (i, ch) in text.chars().take(cells).enumerate() {
let s = ch.to_string();
show(&mut body, cell * i as f64 + (cell - width_of(&s, size)) / 2.0, y, &s, size);
}
} else {
+ let tw = width_of(&text.replace(['\n', '\r'], " "), size);
+ if overflow.is_none() && tw > inner_w + 0.01 {
+ overflow = Some(Overflow::Wide { width: tw, room: inner_w, size });
+ }
show(&mut body, x_for(&text, size), y, &text, size);
}
}
@@ -617,13 +919,17 @@ pub fn field_appearance_drawn(doc: &Document, f: &Field, w: &Widget, values: &[S
d.set(b"Subtype".to_vec(), Object::name("Form"));
set_form_box(&mut d, place);
d.set(b"Resources".to_vec(), Object::Dict(res));
- (Stream::flate(d, &content), unencodable)
+ // Nothing drawn is nothing cut, however small the box.
+ let overflow = overflow.filter(|_| !text.is_empty());
+ (Stream::flate(d, &content), unencodable, overflow)
}
/// On/Off appearances for a check box or radio button that has none (a check mark or a dot,
/// drawn as paths, so no symbol font is needed).
+/// The mark is drawn in the colour of the widget's `/DA`, else of `f_da` (the field's): the
+/// Appearance tab's Text Color (#4261).
/// The streams are added to `doc` as indirect objects (streams can't be direct objects).
-pub fn check_box_states(doc: &mut Document, w: &Widget, kind: FieldKind, on_name: &str) -> Dict {
+pub fn check_box_states(doc: &mut Document, w: &Widget, kind: FieldKind, on_name: &str, f_da: &str) -> Dict {
let wobj = doc.get(w.obj);
let wd = wobj.as_dict().cloned().unwrap_or_default();
let (page_w, page_h) = ((w.rect[2] - w.rect[0]).max(1.0), (w.rect[3] - w.rect[1]).max(1.0));
@@ -631,6 +937,7 @@ pub fn check_box_states(doc: &mut Document, w: &Widget, kind: FieldKind, on_name
let (width, height) = (place.layout_w, place.layout_h);
let (frame_c, _) = frame(doc, &wd, width, height);
let style = crate::author::CheckStyle::of_widget(doc, &wd, kind);
+ let da = parse_da(wd.get(b"DA").and_then(|o| doc.resolve(o).as_string().map(|s| s.to_text())).as_deref().unwrap_or(f_da));
let mut form = |content: String| -> Object {
let mut d = Dict::new();
d.set(b"Type".to_vec(), Object::name("XObject"));
@@ -639,7 +946,7 @@ pub fn check_box_states(doc: &mut Document, w: &Widget, kind: FieldKind, on_name
Object::Ref(doc.add(Object::Stream(Stream::flate(d, content.as_bytes()))))
};
let s = width.min(height);
- let mark = check_mark(style, width / 2.0, height / 2.0, s);
+ let mark = check_mark(style, width / 2.0, height / 2.0, s, &da.color);
let mut nd = Dict::new();
nd.set(crate::name_bytes(on_name), form(format!("{frame_c}{mark}")));
nd.set(b"Off".to_vec(), form(frame_c));
@@ -649,12 +956,13 @@ pub fn check_box_states(doc: &mut Document, w: &Widget, kind: FieldKind, on_name
}
/// The on-state mark for `style` (#94), centred on (`cx`, `cy`) in a box whose smaller side is
-/// `s`, drawn in black.
-fn check_mark(style: crate::author::CheckStyle, cx: f64, cy: f64, s: f64) -> String {
+/// `s`, drawn in the fill colour operation `color` (`0 g`, `0 0 1 rg`).
+fn check_mark(style: crate::author::CheckStyle, cx: f64, cy: f64, s: f64, color: &str) -> String {
use crate::author::CheckStyle;
+ let (fill, stroke) = (color, stroke_op(color));
// A filled polygon through `pts`.
let polygon = |pts: &[(f64, f64)]| {
- let mut c = String::from("0 g\n");
+ let mut c = format!("{fill}\n");
for (i, (x, y)) in pts.iter().enumerate() {
c.push_str(&format!("{} {} {} ", n(*x), n(*y), if i == 0 { "m" } else { "l" }));
}
@@ -664,7 +972,7 @@ fn check_mark(style: crate::author::CheckStyle, cx: f64, cy: f64, s: f64) -> Str
let line = n((s * 0.1).max(1.0));
match style {
CheckStyle::Check => format!(
- "0 G\n{line} w 1 J 1 j\n{} {} m {} {} l {} {} l S\n",
+ "{stroke}\n{line} w 1 J 1 j\n{} {} m {} {} l {} {} l S\n",
n(cx - s * 0.28),
n(cy),
n(cx - s * 0.08),
@@ -675,7 +983,7 @@ fn check_mark(style: crate::author::CheckStyle, cx: f64, cy: f64, s: f64) -> Str
CheckStyle::Cross => {
let d = s * 0.25;
format!(
- "0 G\n{line} w 1 J\n{} {} m {} {} l S\n{} {} m {} {} l S\n",
+ "{stroke}\n{line} w 1 J\n{} {} m {} {} l S\n{} {} m {} {} l S\n",
n(cx - d),
n(cy - d),
n(cx + d),
@@ -688,7 +996,7 @@ fn check_mark(style: crate::author::CheckStyle, cx: f64, cy: f64, s: f64) -> Str
}
CheckStyle::Square => {
let d = s * 0.22;
- format!("0 g\n{} {} {} {} re f\n", n(cx - d), n(cy - d), n(2.0 * d), n(2.0 * d))
+ format!("{fill}\n{} {} {} {} re f\n", n(cx - d), n(cy - d), n(2.0 * d), n(2.0 * d))
}
CheckStyle::Diamond => {
let d = s * 0.3;
@@ -710,7 +1018,7 @@ fn check_mark(style: crate::author::CheckStyle, cx: f64, cy: f64, s: f64) -> Str
let r = s * 0.25;
let k = 0.5523 * r;
format!(
- "0 g\n{} {} m {} {} {} {} {} {} c {} {} {} {} {} {} c {} {} {} {} {} {} c {} {} {} {} {} {} c f\n",
+ "{fill}\n{} {} m {} {} {} {} {} {} c {} {} {} {} {} {} c {} {} {} {} {} {} c {} {} {} {} {} {} c f\n",
n(cx + r),
n(cy),
n(cx + r),
@@ -742,6 +1050,94 @@ fn check_mark(style: crate::author::CheckStyle, cx: f64, cy: f64, s: f64) -> Str
}
}
+/// How a check box or radio button widget `w` of field `f` looks in state on (`on`) or Off when
+/// the file has no appearance for that state: its `/MK` background and border ([`frame`]), and
+/// when on, its caption `/MK /CA` (ISO 32000-2 Table 192: the normal caption, which check boxes
+/// and radio buttons may use too) as a ZapfDingbats character, as in the check box example of
+/// 12.7.5.2.3: `4` (a check mark) by default, `l` (a dot) for a radio button. The character is
+/// drawn in the `/DA` colour, at the `/DA` size or, for an automatic size (`0 Tf`), filling most
+/// of the box. ZapfDingbats is one of the standard 14 fonts, so no font program is needed.
+pub(crate) fn button_state_shown(doc: &Document, f: &Field, w: &Widget, on: bool) -> Stream {
+ let wobj = doc.get(w.obj);
+ let wd = wobj.as_dict().cloned().unwrap_or_default();
+ let (page_w, page_h) = ((w.rect[2] - w.rect[0]).max(1.0), (w.rect[3] - w.rect[1]).max(1.0));
+ let place = placement(mk_rotation(doc, &wd), page_w, page_h);
+ let (width, height) = (place.layout_w, place.layout_h);
+ let (frame_c, bw) = frame(doc, &wd, width, height);
+ let mut content = frame_c.into_bytes();
+ let mut res = Dict::new();
+ if on {
+ let mk = wd.get(b"MK").map(|m| doc.resolve(m)).and_then(|m| m.as_dict().cloned());
+ let caption = mk.as_ref().and_then(|mk| mk.get(b"CA")).and_then(|o| doc.resolve(o).as_string().map(|s| s.to_text()));
+ let dingbats = pdfcraft_fonts::Std14::ZapfDingbats;
+ // The caption's first character as a ZapfDingbats code, when the font has a glyph there.
+ let code = caption
+ .and_then(|s| s.chars().next())
+ .and_then(|ch| u8::try_from(u32::from(ch)).ok())
+ .filter(|&code| dingbats.width(code) > 0.0)
+ .unwrap_or(if f.kind == FieldKind::Radio { b'l' } else { b'4' });
+ let da = parse_da(wd.get(b"DA").and_then(|o| doc.resolve(o).as_string().map(|s| s.to_text())).as_deref().unwrap_or(&f.da));
+ // The glyph's advance and (about) its height, in ems.
+ let (advance, tall) = (dingbats.width(code) / 1000.0, 0.75);
+ let room = |side: f64| (side - 2.0 * bw - 2.0).max(1.0);
+ // An automatic size leaves a margin of a tenth of the room on each side.
+ let size = if da.size > 0.0 { da.size } else { (0.8 * room(width) / advance.max(0.1)).min(0.8 * room(height) / tall).clamp(1.0, 300.0) };
+ let (x, y) = ((width - advance * size) / 2.0, (height - tall * size) / 2.0 + 0.05 * size);
+ content.extend(format!("q\nBT\n/ZaDb {} Tf\n{}\n{} {} Td\n", n(size), da.color, n(x), n(y)).bytes());
+ content.extend(literal(&[code]));
+ content.extend_from_slice(b" Tj\nET\nQ\n");
+ let mut font = Dict::new();
+ font.set(b"Type".to_vec(), Object::name("Font"));
+ font.set(b"Subtype".to_vec(), Object::name("Type1"));
+ font.set(b"BaseFont".to_vec(), Object::name("ZapfDingbats"));
+ let mut fonts = Dict::new();
+ fonts.set(b"ZaDb".to_vec(), Object::Dict(font));
+ res.set(b"Font".to_vec(), Object::Dict(fonts));
+ }
+ let mut d = Dict::new();
+ d.set(b"Type".to_vec(), Object::name("XObject"));
+ d.set(b"Subtype".to_vec(), Object::name("Form"));
+ set_form_box(&mut d, place);
+ d.set(b"Resources".to_vec(), Object::Dict(res));
+ Stream::flate(d, &content)
+}
+
+/// How a push button widget `w` of field `f` with no normal appearance looks: its `/MK`
+/// background and border, in the `/BS` width and style ([`frame`]: Table 168, `B` beveled, `I`
+/// inset), with its caption `/MK /CA` (Table 192) centred in the `/DA` font, size and colour.
+/// A button with an icon (`/MK /I`) is drawn as PdfCraft draws its own buttons, icon included.
+pub(crate) fn push_button_shown(doc: &Document, f: &Field, w: &Widget) -> Stream {
+ let wobj = doc.get(w.obj);
+ let wd = wobj.as_dict().cloned().unwrap_or_default();
+ let mk = wd.get(b"MK").map(|m| doc.resolve(m)).and_then(|m| m.as_dict().cloned()).unwrap_or_default();
+ if mk.contains(b"I") {
+ return crate::author::button_appearance(doc, w, &f.da).0;
+ }
+ let (page_w, page_h) = ((w.rect[2] - w.rect[0]).max(1.0), (w.rect[3] - w.rect[1]).max(1.0));
+ let place = placement(mk_rotation(doc, &wd), page_w, page_h);
+ let (width, height) = (place.layout_w, place.layout_h);
+ let (frame_c, _) = frame(doc, &wd, width, height);
+ let mut content = frame_c.into_bytes();
+ let caption = mk.get(b"CA").and_then(|o| doc.resolve(o).as_string().map(|s| s.to_text())).unwrap_or_default();
+ let mut fonts = Dict::new();
+ if !caption.is_empty() && mk.get(b"TP").and_then(|t| doc.resolve(t).as_int()) != Some(1) {
+ let da = wd.get(b"DA").and_then(|o| doc.resolve(o).as_string().map(|s| s.to_text()));
+ // The automatic size PdfCraft's own buttons use.
+ let auto = ((height - 4.0) * 0.6).clamp(4.0, 14.0);
+ let (ops, name, font, _) = button_caption(doc, da.as_deref().unwrap_or(&f.da), &caption, width, height, auto);
+ content.extend(ops);
+ fonts.set(name.into_bytes(), font);
+ }
+ let mut res = Dict::new();
+ res.set(b"Font".to_vec(), Object::Dict(fonts));
+ let mut d = Dict::new();
+ d.set(b"Type".to_vec(), Object::name("XObject"));
+ d.set(b"Subtype".to_vec(), Object::name("Form"));
+ set_form_box(&mut d, place);
+ d.set(b"Resources".to_vec(), Object::Dict(res));
+ Stream::flate(d, &content)
+}
+
#[cfg(test)]
mod tests {
use super::*;
diff --git a/crates/forms/src/author.rs b/crates/forms/src/author.rs
index 544d0a7..873ef3d 100644
--- a/crates/forms/src/author.rs
+++ b/crates/forms/src/author.rs
@@ -134,10 +134,9 @@ pub(crate) fn ensure_form(doc: &mut Document) -> Result<ObjRef, FormError> {
if !af.contains(b"DA") {
af.set(b"DA".to_vec(), PdfString::literal(b"/Helv 0 Tf 0 g".to_vec()));
}
- let mut dr = af.get(b"DR").map(|o| doc.resolve(o)).and_then(|o| o.as_dict().cloned()).unwrap_or_default();
- let mut fonts = dr.get(b"Font").map(|o| doc.resolve(o)).and_then(|o| o.as_dict().cloned()).unwrap_or_default();
+ let (dr, mut fonts) = form_fonts(doc, &af);
+ let mut added = inline_fonts_as_objects(doc, &mut fonts);
// Acrobat's resource names for the standard fonts its Appearance tab offers.
- let mut added = false;
for (name, base) in [("Helv", "Helvetica"), ("TiRo", "Times-Roman"), ("Cour", "Courier")] {
if fonts.contains(name.as_bytes()) {
continue;
@@ -147,17 +146,105 @@ pub(crate) fn ensure_form(doc: &mut Document) -> Result<ObjRef, FormError> {
f.set(b"Subtype".to_vec(), Object::name("Type1"));
f.set(b"BaseFont".to_vec(), Object::name(base));
f.set(b"Encoding".to_vec(), Object::name("WinAnsiEncoding"));
- fonts.set(name.as_bytes().to_vec(), Object::Dict(f));
+ let r = doc.add(Object::Dict(f));
+ fonts.set(name.as_bytes().to_vec(), Object::Ref(r));
added = true;
}
if added {
- dr.set(b"Font".to_vec(), Object::Dict(fonts));
- af.set(b"DR".to_vec(), Object::Dict(dr));
+ store_form_fonts(doc, &mut af, dr, fonts);
}
doc.set(r, Object::Dict(af));
Ok(r)
}
+/// The form dictionary's `/DR` and its `/Font` dictionary, resolved (empty where missing).
+fn form_fonts(doc: &Document, af: &Dict) -> (Dict, Dict) {
+ let dr = af.get(b"DR").map(|o| doc.resolve(o)).and_then(|o| o.as_dict().cloned()).unwrap_or_default();
+ let fonts = dr.get(b"Font").map(|o| doc.resolve(o)).and_then(|o| o.as_dict().cloned()).unwrap_or_default();
+ (dr, fonts)
+}
+
+/// Each /DR font its own object: Acrobat, redrawing a text field after it is typed in, shows
+/// nothing when the font is a dictionary written inline in /DR (#3441). Fonts written inline
+/// (by an earlier save, or another writer) become objects saying the same; a font that is an
+/// object already, or an entry that isn't a dictionary, is left alone. Whether any changed.
+fn inline_fonts_as_objects(doc: &mut Document, fonts: &mut Dict) -> bool {
+ let inline: Vec<(Vec<u8>, Dict)> = fonts.iter().filter_map(|(k, v)| Some((k.clone(), v.as_dict()?.clone()))).collect();
+ let changed = !inline.is_empty();
+ for (name, font) in inline {
+ let r = doc.add(Object::Dict(font));
+ fonts.set(name, Object::Ref(r));
+ }
+ changed
+}
+
+/// Write `fonts` back as the `/DR /Font` of the form dictionary `af`. An indirect `/DR` or
+/// `/Font` stays the object it is.
+fn store_form_fonts(doc: &mut Document, af: &mut Dict, mut dr: Dict, fonts: Dict) {
+ match dr.get(b"Font").and_then(Object::as_ref) {
+ Some(fr) => doc.set(fr, Object::Dict(fonts)),
+ None => dr.set(b"Font".to_vec(), Object::Dict(fonts)),
+ }
+ match af.get(b"DR").and_then(Object::as_ref) {
+ Some(dr_ref) => doc.set(dr_ref, Object::Dict(dr)),
+ None => af.set(b"DR".to_vec(), Object::Dict(dr)),
+ }
+}
+
+/// Filling a field: the form's inline `/DR` fonts become objects (see
+/// [`inline_fonts_as_objects`]), so a form an earlier version of PdfCraft made works in Acrobat
+/// once it has been filled here too (#3441). Only the font storage changes; nothing is added.
+/// Not in a form a signature covers: there the file stays as the signer saw it, apart from the
+/// value itself.
+pub(crate) fn form_fonts_as_objects(doc: &mut Document, all: &[crate::Field]) -> Result<(), FormError> {
+ let signed = all.iter().any(|f| f.kind == crate::FieldKind::Signature && holds_value(doc, f.obj));
+ if signed {
+ return Ok(());
+ }
+ let Some(root) = doc.root() else { return Ok(()) };
+ let Some(entry) = doc.get(root).as_dict().and_then(|c| c.get(b"AcroForm").cloned()) else { return Ok(()) };
+ match entry {
+ Object::Ref(r) => {
+ let Some(mut af) = doc.get(r).as_dict().cloned() else { return Ok(()) };
+ let (dr, mut fonts) = form_fonts(doc, &af);
+ if inline_fonts_as_objects(doc, &mut fonts) {
+ store_form_fonts(doc, &mut af, dr, fonts);
+ doc.set(r, Object::Dict(af));
+ }
+ }
+ // A form dictionary written directly in the catalog (the catalog's /AcroForm need not be
+ // an indirect reference) is written back there.
+ Object::Dict(mut af) => {
+ let (dr, mut fonts) = form_fonts(doc, &af);
+ if inline_fonts_as_objects(doc, &mut fonts) {
+ store_form_fonts(doc, &mut af, dr, fonts);
+ doc.update_dict(root, |c| c.set(b"AcroForm".to_vec(), Object::Dict(af)))?;
+ }
+ }
+ _ => {}
+ }
+ Ok(())
+}
+
+/// Whether the field `r`, or the nearest ancestor that has one, holds a `/V` (the entry is
+/// inheritable, ISO 32000-2 §12.7.4). The `/Parent` chain is followed at most 64 deep, as deep
+/// as the field walk goes, so a cyclic chain ends.
+fn holds_value(doc: &Document, r: ObjRef) -> bool {
+ let mut at = r;
+ for _ in 0..=64 {
+ let obj = doc.get(at);
+ let Some(d) = obj.as_dict() else { return false };
+ if d.contains(b"V") {
+ return true;
+ }
+ match d.reference(b"Parent") {
+ Some(p) => at = p,
+ None => return false,
+ }
+ }
+ false
+}
+
/// The Appearance tab: borders, colours and text.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Look {
@@ -486,14 +573,228 @@ fn add_to_fields(doc: &mut Document, af: ObjRef, field: ObjRef) -> Result<(), Fo
Ok(())
}
-/// The first free "<base>N" name.
-fn free_name(existing: &[Field], base: &str) -> String {
+/// The most parts a dotted field name may have ("a.b.c" has three).
+const MAX_NAME_PARTS: usize = 32;
+
+/// The field attributes a field inherits from its parents (ISO 32000-2 §12.7.4.1).
+const INHERITED_KEYS: [&[u8]; 7] = [b"FT", b"Ff", b"V", b"DV", b"DA", b"Q", b"MaxLen"];
+
+/// The parts of a full field name: `a.b` is the field `b` under the parent field `a`, since a
+/// field's own (partial) name can't contain a period (ISO 32000-2 §12.7.4.2) (#2696).
+fn name_parts(name: &str) -> Result<Vec<&str>, FormError> {
+ let parts: Vec<&str> = name.split('.').take(MAX_NAME_PARTS.saturating_add(1)).collect();
+ if parts.len() > MAX_NAME_PARTS {
+ return invalid(format!("field names can have at most {MAX_NAME_PARTS} parts"));
+ }
+ if parts.iter().any(|p| p.trim().is_empty()) {
+ return invalid("field names can't be empty, or have an empty part between periods");
+ }
+ Ok(parts)
+}
+
+/// Why the full name `name` can't be used beside the field named `other`, if it can't: the
+/// same name, or one inside the other (a field that has a value can't also hold fields).
+fn clash(name: &str, other: &str) -> Option<String> {
+ if name == other {
+ return Some(format!("a field named {name:?} already exists"));
+ }
+ let inside = |a: &str, b: &str| a.strip_prefix(b).is_some_and(|rest| rest.starts_with('.'));
+ (inside(name, other) || inside(other, name)).then(|| format!("{name:?} can't be used beside the field {other:?}"))
+}
+
+/// The array `key` of `holder` (`/Fields` of the form, `/Kids` of a field).
+fn list_of(doc: &Document, holder: ObjRef, key: &[u8]) -> Vec<Object> {
+ let d = doc.get(holder).as_dict().cloned().unwrap_or_default();
+ d.get(key).map(|o| doc.resolve(o)).and_then(|o| o.as_array().cloned()).unwrap_or_default()
+}
+
+/// Add `field` to `parent`'s `/Kids`, or to the form's `/Fields` at the top.
+fn link(doc: &mut Document, af: ObjRef, parent: Option<ObjRef>, field: ObjRef) -> Result<(), FormError> {
+ let Some(p) = parent else { return add_to_fields(doc, af, field) };
+ let mut kids = list_of(doc, p, b"Kids");
+ kids.push(Object::Ref(field));
+ doc.update_dict(p, |d| d.set(b"Kids".to_vec(), Object::Array(kids)))?;
+ Ok(())
+}
+
+/// The node named `name` (its own `/T`) directly under `parent`, or at the top of the form.
+fn child_named(doc: &Document, af: ObjRef, parent: Option<ObjRef>, name: &str) -> Option<ObjRef> {
+ let list = match parent {
+ Some(p) => list_of(doc, p, b"Kids"),
+ None => list_of(doc, af, b"Fields"),
+ };
+ list.iter()
+ .filter_map(|o| o.as_ref())
+ .find(|r| doc.get(*r).as_dict().and_then(|d| d.get(b"T").cloned()).and_then(|t| crate::text_of(&doc.resolve(&t))).as_deref() == Some(name))
+}
+
+/// The values a parent field passes to the fields under it that can't be turned off by giving
+/// the field a neutral one of its own, as `/Ff` and `/Q` can.
+const PASSED_VALUES: [&[u8]; 3] = [b"V", b"DV", b"MaxLen"];
+
+/// Whether `field` may go in the field tree under the full name `parts`, changing nothing. The
+/// field list holds only terminal fields, so a parent left empty by a move isn't in it: a node
+/// of the same name there is found here.
+/// `inherited` is what the field will hold as its own before it moves (see [`inherited`]).
+fn check_place(doc: &Document, af: ObjRef, field: ObjRef, parts: &[&str], inherited: &Dict) -> Result<(), FormError> {
+ let Some((own, parents)) = parts.split_last() else { return invalid("field names can't be empty") };
+ let mut owned = doc.get(field).as_dict().cloned().unwrap_or_default();
+ for (k, v) in inherited.iter() {
+ owned.set(k.to_vec(), v.clone());
+ }
+ let mut at: Option<ObjRef> = None;
+ let mut whole_path = true;
+ for part in parents {
+ let Some(r) = child_named(doc, af, at, part) else {
+ whole_path = false;
+ break;
+ };
+ // A value, reset value or length limit held by a parent would pass to this field.
+ let held = doc.get(r).as_dict().is_some_and(|d| PASSED_VALUES.iter().any(|k| d.contains(k) && !owned.contains(k)));
+ if held {
+ return invalid(format!("{part:?} holds a value for the fields under it, so {:?} can't be put there", parts.join(".")));
+ }
+ at = Some(r);
+ }
+ // A field being moved is still in the tree here, but under another full name (a move to its
+ // own name changes nothing and doesn't get here), so a node found is another.
+ if whole_path && child_named(doc, af, at, own).is_some() {
+ return invalid(format!("a field named {:?} already exists", parts.join(".")));
+ }
+ Ok(())
+}
+
+/// Put `field` in the field tree under the full name `parts`: its own `/T` is the last part,
+/// and the parts before it name parent fields, reused where the tree has them and made where
+/// not (Acrobat makes `a.b` a field `b` under a field `a`).
+fn attach(doc: &mut Document, af: ObjRef, field: ObjRef, parts: &[&str]) -> Result<(), FormError> {
+ let Some((own, parents)) = parts.split_last() else { return invalid("field names can't be empty") };
+ check_place(doc, af, field, parts, &Dict::new())?;
+ let mut parent: Option<ObjRef> = None;
+ let mut inherits = false;
+ for part in parents {
+ let next = match child_named(doc, af, parent, part) {
+ Some(r) => {
+ inherits |= doc.get(r).as_dict().is_some_and(|d| d.contains(b"Ff") || d.contains(b"Q"));
+ r
+ }
+ None => {
+ let mut d = Dict::new();
+ d.set(b"T".to_vec(), PdfString::text(part));
+ d.set(b"Kids".to_vec(), Object::Array(Vec::new()));
+ if let Some(p) = parent {
+ d.set(b"Parent".to_vec(), Object::Ref(p));
+ }
+ let r = doc.add(Object::Dict(d));
+ link(doc, af, parent, r)?;
+ r
+ }
+ };
+ parent = Some(next);
+ }
+ doc.update_dict(field, |d| {
+ d.set(b"T".to_vec(), PdfString::text(own));
+ match parent {
+ Some(p) => d.set(b"Parent".to_vec(), Object::Ref(p)),
+ None => {
+ d.remove(b"Parent");
+ }
+ }
+ // An existing parent's flags and alignment would otherwise pass to this field.
+ if inherits {
+ for k in [&b"Ff"[..], b"Q"] {
+ if !d.contains(k) {
+ d.set(k.to_vec(), Object::Int(0));
+ }
+ }
+ }
+ })?;
+ link(doc, af, parent, field)
+}
+
+/// What `field` inherits from its parents and doesn't hold itself, changing nothing.
+fn inherited(doc: &Document, field: ObjRef) -> Dict {
+ let own = doc.get(field).as_dict().cloned().unwrap_or_default();
+ let mut add = Dict::new();
+ let mut seen = std::collections::HashSet::new();
+ let mut parent = own.reference(b"Parent");
+ while let Some(p) = parent {
+ if seen.len() > 64 || !seen.insert(p) {
+ break;
+ }
+ let Some(d) = doc.get(p).as_dict().cloned() else { break };
+ for k in INHERITED_KEYS {
+ if let Some(v) = d.get(k).filter(|_| !own.contains(k) && !add.contains(k)) {
+ add.set(k.to_vec(), v.clone());
+ }
+ }
+ parent = d.reference(b"Parent");
+ }
+ add
+}
+
+/// Copy onto `field` what it inherits (`add`, from [`inherited`]), so it keeps it when it moves.
+fn own_inherited(doc: &mut Document, field: ObjRef, add: &Dict) -> Result<(), FormError> {
+ if add.iter().next().is_some() {
+ doc.update_dict(field, |d| {
+ for (k, v) in add.iter() {
+ d.set(k.to_vec(), v.clone());
+ }
+ })?;
+ }
+ Ok(())
+}
+
+/// Take `field` out of the field tree: from its parent's `/Kids`, or from `/Fields`.
+fn detach(doc: &mut Document, field: ObjRef) -> Result<(), FormError> {
+ let parent = doc.get(field).as_dict().and_then(|d| d.reference(b"Parent"));
+ let remove_from = |doc: &mut Document, holder: ObjRef, key: &[u8]| -> Result<(), FormError> {
+ let mut d = doc.get(holder).as_dict().cloned().unwrap_or_default();
+ let list = d.get(key).map(|o| doc.resolve(o)).and_then(|o| o.as_array().cloned()).unwrap_or_default();
+ let kept: Vec<Object> = list.into_iter().filter(|o| o.as_ref() != Some(field)).collect();
+ d.set(key.to_vec(), Object::Array(kept));
+ doc.set(holder, Object::Dict(d));
+ Ok(())
+ };
+ match parent {
+ Some(p) => remove_from(doc, p, b"Kids")?,
+ None => {
+ let root = doc.root().ok_or(FormError::NoForm)?;
+ match doc.get(root).as_dict().and_then(|d| d.get(b"AcroForm").cloned()) {
+ Some(Object::Ref(af)) => remove_from(doc, af, b"Fields")?,
+ // A form dictionary held directly in the catalog.
+ Some(Object::Dict(mut af)) => {
+ let list = af.get(b"Fields").map(|o| doc.resolve(o)).and_then(|o| o.as_array().cloned()).unwrap_or_default();
+ let kept: Vec<Object> = list.into_iter().filter(|o| o.as_ref() != Some(field)).collect();
+ af.set(b"Fields".to_vec(), Object::Array(kept));
+ doc.update_dict(root, |d| d.set(b"AcroForm".to_vec(), Object::Dict(af)))?;
+ }
+ _ => {}
+ }
+ }
+ }
+ Ok(())
+}
+
+/// The first free "<base>N" name: not a field's, and not held by a node at the top of the field
+/// tree (`held`), such as a parent field left empty by a move, which isn't in `existing`.
+fn free_name(existing: &[Field], held: &[String], base: &str) -> String {
(1..=u64::MAX)
.map(|n| format!("{base}{n}"))
- .find(|c| !existing.iter().any(|f| f.name == *c || f.name.starts_with(&format!("{c}."))))
+ .find(|c| !held.contains(c) && !existing.iter().any(|f| f.name == *c || f.name.starts_with(&format!("{c}."))))
.unwrap_or_else(|| base.to_string())
}
+/// The own names (`/T`) of the nodes in the form's `/Fields`, changing nothing.
+fn top_names(doc: &Document) -> Vec<String> {
+ let Some(root) = doc.root() else { return Vec::new() };
+ let Some(af) = doc.get(root).as_dict().and_then(|d| d.get(b"AcroForm").map(|o| doc.resolve(o))).and_then(|o| o.as_dict().cloned()) else {
+ return Vec::new();
+ };
+ let list = af.get(b"Fields").map(|o| doc.resolve(o)).and_then(|o| o.as_array().cloned()).unwrap_or_default();
+ list.iter().filter_map(|o| doc.resolve(o).as_dict().and_then(|d| d.get(b"T").cloned())).filter_map(|t| crate::text_of(&doc.resolve(&t))).collect()
+}
+
fn widget_dict(page: ObjRef, rect: [f64; 4]) -> Dict {
let mut d = Dict::new();
d.set(b"Type".to_vec(), Object::name("Annot"));
@@ -527,20 +828,18 @@ pub fn add_field(doc: &mut Document, page: usize, rect: [f64; 4], kind: &NewFiel
_ => name,
};
let name = match name.map(str::trim) {
- Some(n) if !n.is_empty() => {
- if n.contains('.') {
- return invalid("field names can't contain a period");
- }
- n.to_string()
- }
- _ => free_name(&existing, kind.base_name()),
+ Some(n) if !n.is_empty() => n.to_string(),
+ _ => free_name(&existing, &top_names(doc), kind.base_name()),
};
+ let parts = name_parts(&name)?;
let radio_group = match kind {
NewField::Radio { group, .. } => existing.iter().find(|f| f.kind == FieldKind::Radio && Some(&f.name) == group.as_ref()).cloned(),
_ => None,
};
- if radio_group.is_none() && existing.iter().any(|f| f.name == name) {
- return invalid(format!("a field named {name:?} already exists"));
+ if radio_group.is_none()
+ && let Some(why) = existing.iter().find_map(|f| clash(&name, &f.name))
+ {
+ return invalid(why);
}
let af = ensure_form(doc)?;
let mut w = widget_dict(page_ref, rect);
@@ -637,12 +936,11 @@ pub fn add_field(doc: &mut Document, page: usize, rect: [f64; 4], kind: &NewFiel
let mut g = Dict::new();
g.set(b"FT".to_vec(), Object::name("Btn"));
g.set(b"Ff".to_vec(), Object::Int((flags::RADIO | flags::NO_TOGGLE_TO_OFF) as i64));
- g.set(b"T".to_vec(), PdfString::text(&field_name));
g.set(b"V".to_vec(), Object::name("Off"));
g.set(b"DA".to_vec(), PdfString::literal(b"/ZaDb 0 Tf 0 g".to_vec()));
g.set(b"Kids".to_vec(), Object::Array(Vec::new()));
let g = doc.add(Object::Dict(g));
- add_to_fields(doc, af, g)?;
+ attach(doc, af, g, &parts)?;
g
}
};
@@ -666,13 +964,10 @@ pub fn add_field(doc: &mut Document, page: usize, rect: [f64; 4], kind: &NewFiel
caption: None,
list: None,
};
- let ap = appearance::check_box_states(doc, &w, FieldKind::Radio, export);
+ let ap = appearance::check_box_states(doc, &w, FieldKind::Radio, export, "/ZaDb 0 Tf 0 g");
doc.update_dict(widget, |d| d.set(b"AP".to_vec(), Object::Dict(ap)))?;
}
- _ => {
- doc.update_dict(widget, |d| d.set(b"T".to_vec(), PdfString::text(&name)))?;
- add_to_fields(doc, af, widget)?;
- }
+ _ => attach(doc, af, widget, &parts)?,
}
add_to_page(doc, page_ref, widget)?;
redraw_field(doc, &field_name)?;
@@ -709,7 +1004,7 @@ fn redraw_widgets(doc: &mut Document, name: &str, only: Option<usize>) -> Result
}
FieldKind::CheckBox | FieldKind::Radio => {
let on = w.on_state.clone().unwrap_or_else(|| "Yes".into());
- appearance::check_box_states(doc, w, f.kind, &on)
+ appearance::check_box_states(doc, w, f.kind, &on, &f.da)
}
FieldKind::PushButton => {
let (s, m) = button_appearance(doc, w, &f.da);
@@ -775,7 +1070,7 @@ fn form_stream(place: crate::appearance::Placement, content: Vec<u8>, resources:
/// color its `/DA` asks for (the widget's, else `field_da`, the field's own or inherited one).
/// Also returns the first caption character the font can't draw (drawn as `?`), for the caller to
/// mark and report.
-fn button_appearance(doc: &Document, w: &Widget, field_da: &str) -> (Stream, Option<char>) {
+pub(crate) fn button_appearance(doc: &Document, w: &Widget, field_da: &str) -> (Stream, Option<char>) {
let (mut c, place) = frame_only(doc, w);
let (width, height) = (place.layout_w, place.layout_h);
let wobj = doc.get(w.obj);
@@ -919,18 +1214,52 @@ pub fn set_props(doc: &mut Document, name: &str, props: &FieldProps) -> Result<S
}
let mut new_name = name.to_string();
if let Some(n) = props.name.as_deref().map(str::trim).filter(|n| *n != f.name) {
- if n.is_empty() || n.contains('.') {
- return invalid("field names can't be empty or contain a period");
- }
- // Rename the terminal part (the field's own /T). The parents' part stays, so the name that
- // must be free is the full one: `MASTER.a` renamed to `b` takes `MASTER.b` (ISO 32000-2
- // §12.7.4.2). The field itself is no clash when it keeps its own name.
- let prefix = f.name.rsplit_once('.').map(|(p, _)| format!("{p}.")).unwrap_or_default();
- new_name = format!("{prefix}{n}");
- if all.iter().any(|x| x.obj != f.obj && x.name == new_name) {
- return invalid(format!("a field named {new_name:?} already exists"));
- }
- doc.update_dict(f.obj, |d| d.set(b"T".to_vec(), PdfString::text(n)))?;
+ // A full name under the same parents only renames the field's own part (the editor
+ // shows nested fields by their full name): it isn't moved, so it keeps its place and
+ // goes on inheriting from its parents.
+ let n = match (n.rsplit_once('.'), f.name.rsplit_once('.')) {
+ (Some((parents, own)), Some((current, _))) if parents == current => own,
+ _ => n,
+ };
+ if n.contains('.') {
+ // A full name: the field moves under the parent fields it names (#2696).
+ let parts = name_parts(n)?;
+ if let Some(why) = all.iter().filter(|x| x.obj != f.obj).find_map(|x| clash(n, &x.name)) {
+ return invalid(why);
+ }
+ let af = ensure_form(doc)?;
+ // Checked before anything changes, so a refused move leaves the field as it was.
+ let add = inherited(doc, f.obj);
+ check_place(doc, af, f.obj, &parts, &add)?;
+ // From here a failure (a write that `check_place` couldn't foresee) would leave the
+ // field half moved in `doc`. The engine runs every edit on a copy of the document and
+ // keeps it only when the edit succeeds (`Session::apply`), so the open document never
+ // sees that.
+ own_inherited(doc, f.obj, &add)?;
+ detach(doc, f.obj)?;
+ attach(doc, af, f.obj, &parts)?;
+ new_name = n.to_string();
+ } else {
+ if n.is_empty() {
+ return invalid("field names can't be empty");
+ }
+ // Rename the terminal part (the field's own /T). The parents' part stays, so the name
+ // that must be free is the full one: `MASTER.a` renamed to `b` takes `MASTER.b` (ISO
+ // 32000-2 §12.7.4.2). The field itself is no clash when it keeps its own name.
+ let prefix = f.name.rsplit_once('.').map(|(p, _)| format!("{p}.")).unwrap_or_default();
+ new_name = format!("{prefix}{n}");
+ if let Some(why) = all.iter().filter(|x| x.obj != f.obj).find_map(|x| clash(&new_name, &x.name)) {
+ return invalid(why);
+ }
+ // A node of that name beside it that isn't a terminal field, such as a parent
+ // field left empty by a move.
+ let af = ensure_form(doc)?;
+ let parent = doc.get(f.obj).as_dict().and_then(|d| d.reference(b"Parent"));
+ if child_named(doc, af, parent, n).is_some_and(|r| r != f.obj) {
+ return invalid(format!("a field named {new_name:?} already exists"));
+ }
+ doc.update_dict(f.obj, |d| d.set(b"T".to_vec(), PdfString::text(n)))?;
+ }
// Calculations read the field by its new name, unless another field keeps the old one.
if all.iter().filter(|x| x.name == f.name).count() == 1 {
rename_in_calculations(doc, &all, &f.name, &new_name)?;
@@ -980,7 +1309,7 @@ pub fn set_props(doc: &mut Document, name: &str, props: &FieldProps) -> Result<S
{
return invalid("alignment is 0 (left), 1 (centre) or 2 (right)");
}
- if props.options.as_ref().is_some_and(|o| o.is_empty()) && matches!(f.kind, FieldKind::Combo | FieldKind::List) {
+ if props.options.as_ref().is_some_and(Vec::is_empty) && matches!(f.kind, FieldKind::Combo | FieldKind::List) {
return invalid("a list needs at least one option");
}
if props.check_style.is_some() && !matches!(f.kind, FieldKind::CheckBox | FieldKind::Radio) {
@@ -1239,8 +1568,17 @@ fn rename_in_calculations(doc: &mut Document, all: &[Field], old: &str, new: &st
/// Delete a field: its widgets leave their pages and the field leaves the form.
pub fn delete_field(doc: &mut Document, name: &str) -> Result<(), FormError> {
- let all = fields(doc);
- let f = all.iter().find(|f| f.name == name).ok_or_else(|| FormError::NoSuchField(name.into()))?.clone();
+ let f = fields(doc).into_iter().find(|f| f.name == name).ok_or_else(|| FormError::NoSuchField(name.into()))?;
+ delete_found_field(doc, f)
+}
+
+/// [`delete_field`] for the field object `obj`, when separate fields share one name.
+pub fn delete_field_object(doc: &mut Document, obj: ObjRef) -> Result<(), FormError> {
+ let f = fields(doc).into_iter().find(|f| f.obj == obj).ok_or_else(|| FormError::NoSuchField(format!("{obj:?}")))?;
+ delete_found_field(doc, f)
+}
+
+fn delete_found_field(doc: &mut Document, f: Field) -> Result<(), FormError> {
let widgets: std::collections::HashSet<ObjRef> = f.widgets.iter().map(|w| w.obj).collect();
for p in page_refs(doc) {
let Some(a) = doc.get(p).as_dict().and_then(|d| d.get(b"Annots").cloned()) else { continue };
@@ -1253,33 +1591,7 @@ pub fn delete_field(doc: &mut Document, name: &str) -> Result<(), FormError> {
}
}
}
- // Out of the field tree: from its parent's /Kids, or from /Fields.
- let parent = doc.get(f.obj).as_dict().and_then(|d| d.reference(b"Parent"));
- let remove_from = |doc: &mut Document, holder: ObjRef, key: &[u8]| -> Result<(), FormError> {
- let mut d = doc.get(holder).as_dict().cloned().unwrap_or_default();
- let list = d.get(key).map(|o| doc.resolve(o)).and_then(|o| o.as_array().cloned()).unwrap_or_default();
- let kept: Vec<Object> = list.into_iter().filter(|o| o.as_ref() != Some(f.obj)).collect();
- d.set(key.to_vec(), Object::Array(kept));
- doc.set(holder, Object::Dict(d));
- Ok(())
- };
- match parent {
- Some(p) => remove_from(doc, p, b"Kids")?,
- None => {
- let root = doc.root().ok_or(FormError::NoForm)?;
- match doc.get(root).as_dict().and_then(|d| d.get(b"AcroForm").cloned()) {
- Some(Object::Ref(af)) => remove_from(doc, af, b"Fields")?,
- // A form dictionary held directly in the catalog.
- Some(Object::Dict(mut af)) => {
- let list = af.get(b"Fields").map(|o| doc.resolve(o)).and_then(|o| o.as_array().cloned()).unwrap_or_default();
- let kept: Vec<Object> = list.into_iter().filter(|o| o.as_ref() != Some(f.obj)).collect();
- af.set(b"Fields".to_vec(), Object::Array(kept));
- doc.update_dict(root, |d| d.set(b"AcroForm".to_vec(), Object::Dict(af)))?;
- }
- _ => {}
- }
- }
- }
+ detach(doc, f.obj)?;
// Out of the calculation order too: a `/CO` entry would keep the field, its value and its
// widgets reachable for a full save.
drop_from_calculation_order(doc, |r| r == f.obj || widgets.contains(&r))
diff --git a/crates/forms/src/calc_order.rs b/crates/forms/src/calc_order.rs
index 428c172..4e7f030 100644
--- a/crates/forms/src/calc_order.rs
+++ b/crates/forms/src/calc_order.rs
@@ -243,13 +243,7 @@ fn components(links: &[Vec<usize>]) -> Vec<usize> {
continue;
}
if low[v] == index[v] {
- while let Some(w) = stack.pop() {
- on_stack[w] = false;
- component[w] = count;
- if w == v {
- break;
- }
- }
+ pop_component(&mut stack, &mut on_stack, &mut component, v, count);
count += 1;
}
if let Some(&(parent, _)) = work.last() {
@@ -260,6 +254,16 @@ fn components(links: &[Vec<usize>]) -> Vec<usize> {
component
}
+fn pop_component(stack: &mut Vec<usize>, on_stack: &mut [bool], component: &mut [usize], v: usize, count: usize) {
+ while let Some(w) = stack.pop() {
+ on_stack[w] = false;
+ component[w] = count;
+ if w == v {
+ break;
+ }
+ }
+}
+
/// Fix order: every node after the nodes it reads in other components, the earliest ready node
/// first, so an order that is already right stays as it is and otherwise only what must move
/// moves. Reads within a component (a loop) are left out: no order satisfies them.
diff --git a/crates/forms/src/detect.rs b/crates/forms/src/detect.rs
index 8c980c0..386671f 100644
--- a/crates/forms/src/detect.rs
+++ b/crates/forms/src/detect.rs
@@ -307,7 +307,7 @@ fn label_for(words: &[Word], rect: [f64; 4], right_of: bool) -> String {
.iter()
.filter(|w| w.rect[1] >= rect[3] - 1.0 && w.rect[1] - rect[3] < 24.0 && w.rect[0] < rect[2] && w.rect[2] > rect[0] - 4.0)
.collect();
- let Some(line) = above.iter().map(|w| mid(w.rect)).min_by(|a, b| a.total_cmp(b)) else { return String::new() };
+ let Some(line) = above.iter().map(|w| mid(w.rect)).min_by(f64::total_cmp) else { return String::new() };
let mut on: Vec<&&Word> = above.iter().filter(|w| (mid(w.rect) - line).abs() < 3.0).collect();
on.sort_by(|a, b| a.rect[0].total_cmp(&b.rect[0]));
clean(&on.iter().map(|w| w.text.as_str()).collect::<Vec<_>>().join(" "))
diff --git a/crates/forms/src/lib.rs b/crates/forms/src/lib.rs
index 82c1c8e..2354d69 100644
--- a/crates/forms/src/lib.rs
+++ b/crates/forms/src/lib.rs
@@ -24,10 +24,10 @@ mod calc_order;
pub mod detect;
mod scripting;
pub mod table;
-pub use actions::{FieldAction, Trigger, field_actions, set_field_actions};
+pub use actions::{FieldAction, Trigger, field_action_chains, field_actions, set_field_actions};
pub use author::{
- BorderStyle, CheckStyle, FieldFont, FieldProps, Look, LookPatch, MIN_FIELD_SIDE, NewField, add_field, check_style, delete_field, duplicate_field,
- look, redraw_field, set_button_icon, set_props,
+ BorderStyle, CheckStyle, FieldFont, FieldProps, Look, LookPatch, MIN_FIELD_SIDE, NewField, add_field, check_style, delete_field,
+ delete_field_object, duplicate_field, look, redraw_field, set_button_icon, set_props,
};
pub use calc_order::{CalculatedField, CalculationIssue, CalculationOrder, calculation_order, set_calculation_order};
pub use scripting::{
@@ -48,6 +48,10 @@ pub enum FormError {
ReadOnly(String),
#[error("{0}")]
Invalid(String),
+ /// The value doesn't fit the field's format (its keystroke check refused it), which is
+ /// checked before any of the field's scripts run.
+ #[error("{0}")]
+ Format(String),
#[error("{0}")]
Cos(#[from] pdfcraft_cos::CosError),
}
@@ -932,6 +936,7 @@ pub fn set_value_with(doc: &mut Document, name: &str, value: &FieldValue, script
return Err(FormError::ReadOnly(name.into()));
}
write_value(doc, f, value, scripts)?;
+ author::form_fonts_as_objects(doc, &all)?;
// Fields with the same fully qualified name are one field (§12.7.3.1). Writers that repeat a
// name as separate field dictionaries, instead of widgets under one parent, get the value
// the first one took after its scripts, without running them again.
@@ -1049,7 +1054,7 @@ fn write_value(doc: &mut Document, f: &Field, value: &FieldValue, scripts: &mut
return invalid(format!("{:?} takes at most {max} characters", f.name));
}
// Keystroke (on commit) and Validate, as Acrobat runs them before accepting a value.
- let t = &af::keystroke(&f.actions.format, &f.name, t).map_err(FormError::Invalid)?;
+ let t = &af::keystroke(&f.actions.format, &f.name, t).map_err(FormError::Format)?;
af::validate(&f.actions.validate, t).map_err(FormError::Invalid)?;
let t = &scripting::accept(doc, f, t, scripts)?;
doc.update_dict(f.obj, |d| {
@@ -1191,7 +1196,7 @@ fn set_states(doc: &mut Document, f: &Field, on: Option<&str>) -> Result<(), For
let has_ap = doc.get(w.obj).as_dict().and_then(|d| d.get(b"AP").cloned()).is_some();
if !has_ap {
let on_name = w.on_state.clone().unwrap_or_else(|| on.unwrap_or("Yes").to_string());
- let ap = appearance::check_box_states(doc, w, f.kind, &on_name);
+ let ap = appearance::check_box_states(doc, w, f.kind, &on_name, &f.da);
doc.update_dict(w.obj, |d| d.set(b"AP".to_vec(), Object::Dict(ap)))?;
}
doc.update_dict(w.obj, |d| d.set(b"AS".to_vec(), name_obj(state)))?;
@@ -1248,6 +1253,7 @@ fn redraw(doc: &mut Document, f: &Field, values: &[String], scripts: &mut dyn Sc
[one] if matches!(f.kind, FieldKind::Text | FieldKind::Combo) => scripting::formatted(doc, f, one, scripts),
_ => None,
};
+ let in_place = f.kind == FieldKind::Text && f.has(flags::PASSWORD);
let mut undrawn = false;
for w in &f.widgets {
let (stream, missing) = match &shown {
@@ -1255,7 +1261,23 @@ fn redraw(doc: &mut Document, f: &Field, values: &[String], scripts: &mut dyn Sc
None => appearance::field_appearance_drawn(doc, f, w, values, true),
};
undrawn |= missing.is_some();
- let ap = doc.add(Object::Stream(stream));
+ let existing_ap = in_place
+ .then(|| {
+ doc.get(w.obj)
+ .as_dict()
+ .and_then(|d| d.get(b"AP").map(|a| doc.resolve(a)))
+ .and_then(|a| a.as_dict().and_then(|a| a.get(b"N").cloned()))
+ .and_then(|n| n.as_ref())
+ .filter(|r| doc.is_edited(r.num) && matches!(&*doc.get(*r), Object::Stream(_)))
+ })
+ .flatten();
+ let ap = match existing_ap {
+ Some(r) => {
+ doc.set(r, Object::Stream(stream));
+ r
+ }
+ None => doc.add(Object::Stream(stream)),
+ };
let mut fresh = Dict::new();
fresh.set(b"N".to_vec(), Object::Ref(ap));
let apd = merged_appearance(doc, w.obj, &fresh);
@@ -1293,16 +1315,158 @@ pub(crate) fn ask_viewers_to_redraw(doc: &mut Document) -> Result<(), FormError>
Ok(())
}
+/// Text fields with the Password flag (inherited or their own) whose value (`/V`, inherited or
+/// their own) is not empty and not their default value (`/DV`, which the form's author wrote and
+/// a save restores), or one of whose separate widgets carries a `/V`.
+fn password_fields(doc: &Document) -> Vec<Field> {
+ if !has_password_flag(doc) {
+ return Vec::new();
+ }
+ let on_widget = |f: &Field| f.widgets.iter().any(|w| w.obj != f.obj && doc.get(w.obj).as_dict().is_some_and(|d| d.get(b"V").is_some()));
+ let typed = |f: &Field| f.value.iter().any(|v| !v.is_empty()) && f.value.first() != f.default.first();
+ fields(doc).into_iter().filter(|f| f.kind == FieldKind::Text && f.has(flags::PASSWORD) && (typed(f) || on_widget(f))).collect()
+}
+
+/// Whether any field dictionary sets the Password flag (#3943 review). A field that inherits the
+/// flag has an ancestor that sets it, so that ancestor is found instead; a kid clearing the flag
+/// again only makes the answer cautious. It reads only `/Ff`, `/Kids` and `/Parent`, so a save
+/// or recovery snapshot of a form without such a field doesn't build every [`Field`]. Like
+/// [`fields`], it looks at the form's field tree and at the widgets on the pages, which may be
+/// missing from `/Fields`. Each dictionary is visited once and at most 64 levels deep.
+fn has_password_flag(doc: &Document) -> bool {
+ let sets_it = |r: ObjRef| doc.get(r).as_dict().and_then(|d| field_flags(doc, d)).is_some_and(|ff| ff & flags::PASSWORD != 0);
+ let top = acroform(doc).and_then(|af| af.get(b"Fields").map(|o| doc.resolve(o)).and_then(|o| o.as_array().cloned())).unwrap_or_default();
+ let mut stack: Vec<(Object, usize)> = top.into_iter().map(|o| (o, 0)).collect();
+ let mut seen = std::collections::HashSet::new();
+ while let Some((o, depth)) = stack.pop() {
+ let Object::Ref(r) = o else { continue };
+ if depth > 64 || !seen.insert(r) {
+ continue;
+ }
+ if sets_it(r) {
+ return true;
+ }
+ let kids = doc.get(r).as_dict().and_then(|d| d.get(b"Kids").map(|k| doc.resolve(k)).and_then(|k| k.as_array().cloned())).unwrap_or_default();
+ stack.extend(kids.into_iter().map(|k| (k, depth + 1)));
+ }
+ // Widgets on the pages, and the fields above them.
+ page_refs(doc).into_iter().any(|p| {
+ let annots =
+ doc.get(p).as_dict().and_then(|d| d.get(b"Annots").map(|a| doc.resolve(a)).and_then(|a| a.as_array().cloned())).unwrap_or_default();
+ annots.iter().filter_map(Object::as_ref).filter(|r| !seen.contains(r)).any(|r| field_chain(doc, r).into_iter().any(sets_it))
+ })
+}
+
+/// Whether any text field with the Password flag holds a value in `doc`.
+pub fn has_password_values(doc: &Document) -> bool {
+ !password_fields(doc).is_empty()
+}
+
+/// The typed values of the text fields with the Password flag, as (name, text) pairs, for
+/// [`restore_password_values`] after the document was rebased on a file written without them.
+pub fn password_values(doc: &Document) -> Vec<(String, String)> {
+ password_fields(doc).into_iter().filter_map(|f| f.value.first().map(|v| (f.name.clone(), v.clone()))).collect()
+}
+
+/// Put values from [`password_values`] back into the open document, in memory only. A field
+/// that is gone or read-only keeps what it has.
+pub fn restore_password_values(doc: &mut Document, values: &[(String, String)]) -> Result<(), FormError> {
+ for (name, v) in values {
+ match set_value(doc, name, &FieldValue::Text(v.clone())) {
+ Ok(()) | Err(FormError::NoSuchField(_) | FormError::ReadOnly(_)) => {}
+ Err(e) => return Err(e),
+ }
+ }
+ Ok(())
+}
+
+/// `r` and its field ancestors (`/Parent`), nearest first, at most 64 deep and without repeats.
+fn field_chain(doc: &Document, r: ObjRef) -> Vec<ObjRef> {
+ let mut chain = vec![r];
+ let mut cur = r;
+ while chain.len() < 64 {
+ let Some(Object::Ref(parent)) = doc.get(cur).as_dict().and_then(|d| d.get(b"Parent").cloned()) else { break };
+ if chain.contains(&parent) {
+ break;
+ }
+ chain.push(parent);
+ cur = parent;
+ }
+ chain
+}
+
+/// Remove the values of the text fields with the Password flag, for a copy of the document about
+/// to be written to a file (#3926). ISO 32000-2 §12.7.5.3, Table 231, Password flag, note: "it is
+/// imperative that PDF processors never store the value of the text field in the PDF file if
+/// this flag is set". As Acrobat saves such a field (#3943 review, black-box test): a field with
+/// a default value (`/DV`, which the form's author wrote) gets it back as its value, one without
+/// is left empty, and its appearance is drawn again from that value, so the masking characters
+/// no longer show how long the typed password was. `/DV` and the field's scripts stay.
+///
+/// A value can sit on the field, on one of its widgets, or on an ancestor it inherits from
+/// (`/V` is inheritable). Each is removed; an ancestor's only when every field inheriting from it
+/// is such a password field. Where an ancestor's value is shared with other fields and stays, the
+/// password field gets an empty value of its own so it no longer inherits it. Returns how many
+/// fields were cleared.
+pub fn clear_password_values(doc: &mut Document) -> Result<usize, FormError> {
+ let targets = password_fields(doc);
+ if targets.is_empty() {
+ return Ok(0);
+ }
+ let is_password = |f: &Field| f.kind == FieldKind::Text && f.has(flags::PASSWORD);
+ // Each field's ancestors, found once: only values change below, never `/Parent` (#3943
+ // review: walking them again for every ancestor of every target was quadratic).
+ let chains: Vec<(bool, Vec<ObjRef>)> = fields(doc).iter().map(|g| (is_password(g), field_chain(doc, g.obj))).collect();
+ for f in &targets {
+ let chain = field_chain(doc, f.obj);
+ for w in &f.widgets {
+ if w.obj != f.obj {
+ doc.update_dict(w.obj, |d| {
+ d.remove(b"V");
+ })?;
+ }
+ }
+ doc.update_dict(f.obj, |d| {
+ d.remove(b"V");
+ })?;
+ let mut shared_value_kept = false;
+ for a in chain.iter().skip(1) {
+ if doc.get(*a).as_dict().is_none_or(|d| d.get(b"V").is_none()) {
+ continue;
+ }
+ let exclusive = chains.iter().filter(|(_, chain)| chain.contains(a)).all(|(password, _)| *password);
+ if exclusive {
+ doc.update_dict(*a, |d| {
+ d.remove(b"V");
+ })?;
+ } else {
+ shared_value_kept = true;
+ }
+ }
+ let restored: Vec<String> = f.default.first().cloned().into_iter().collect();
+ match restored.first() {
+ Some(dv) => doc.update_dict(f.obj, |d| d.set(b"V".to_vec(), PdfString::text(dv)))?,
+ None if shared_value_kept => doc.update_dict(f.obj, |d| d.set(b"V".to_vec(), PdfString::text("")))?,
+ None => {}
+ }
+ redraw(doc, f, &restored, &mut NoScripts)?;
+ }
+ Ok(targets.len())
+}
+
/// Whether the form asks viewers to draw its fields' appearances themselves (`/NeedAppearances`).
pub fn need_appearances(doc: &Document) -> bool {
acroform(doc).is_some_and(|af| matches!(af.get(b"NeedAppearances").map(|o| doc.resolve(o)).as_deref(), Some(Object::Bool(true))))
}
-/// A copy of `doc` in which text and choice fields are drawn from their values, for displaying
-/// the document (`None` when no widget needs it): every such widget when the form sets
-/// `/NeedAppearances` (ISO 32000-2 Table 224: the writer left the appearances to the viewer),
-/// and otherwise each widget without a normal appearance (`/AP /N`). Drawn as typing the value
-/// would draw it (#3470). `doc` is not changed: saving writes the file as it was.
+/// A copy of `doc` in which form fields are drawn the way the file leaves to the viewer, for
+/// displaying the document (`None` when no widget needs it). Text and choice fields are drawn from
+/// their values: every one when the form sets `/NeedAppearances` (ISO 32000-2 Table 224: the
+/// writer left the appearances to the viewer), and otherwise each widget without a normal
+/// appearance (`/AP /N`), as typing the value would draw it (#3470). Check boxes and radio buttons
+/// with no normal appearance for their state (`/AS`) are drawn from their `/MK` background, border
+/// and caption, and push buttons with none from their `/MK` and `/BS` (Table 192). `doc` is not
+/// changed: saving writes the file as it was.
pub fn with_field_appearances(doc: &Document) -> Option<Document> {
with_field_appearances_cached(doc, &mut FieldAppearanceCache::default())
}
@@ -1312,18 +1476,45 @@ pub fn with_field_appearances(doc: &Document) -> Option<Document> {
pub fn with_field_appearances_cached(doc: &Document, cache: &mut FieldAppearanceCache) -> Option<Document> {
let all = need_appearances(doc);
let mut copy: Option<Document> = None;
- for f in fields(doc).iter().filter(|f| matches!(f.kind, FieldKind::Text | FieldKind::Combo | FieldKind::List)) {
+ for f in fields(doc) {
for w in &f.widgets {
let widget = doc.get(w.obj);
- let drawn = widget.as_dict().and_then(|d| d.get(b"AP")).is_some_and(|ap| doc.resolve(ap).as_dict().is_some_and(|ap| ap.contains(b"N")));
- if drawn && !all {
+ let normal = widget
+ .as_dict()
+ .and_then(|d| d.get(b"AP"))
+ .and_then(|ap| doc.resolve(ap).as_dict().and_then(|ap| ap.get(b"N").map(|n| doc.resolve(n))));
+ // A check box or radio button shows the appearance of its state (12.7.5.2.3): `/AS`,
+ // else a check box's value, else Off. An Off state may go without one (it shows
+ // nothing); an on state needs one.
+ let state = match f.kind {
+ FieldKind::CheckBox | FieldKind::Radio => {
+ let value = f.value.first().filter(|v| f.kind == FieldKind::CheckBox && !v.is_empty() && v.as_str() != "Off");
+ Some(w.state.clone().or_else(|| value.cloned()).unwrap_or_else(|| "Off".into()))
+ }
+ _ => None,
+ };
+ let missing = match f.kind {
+ FieldKind::Text | FieldKind::Combo | FieldKind::List => normal.is_none() || all,
+ FieldKind::PushButton => normal.is_none(),
+ FieldKind::CheckBox | FieldKind::Radio => match (normal.as_deref(), state.as_deref()) {
+ (None, _) => true,
+ (Some(Object::Dict(states)), Some(s)) => s != "Off" && !states.contains(&name_bytes(s)),
+ _ => false,
+ },
+ FieldKind::Signature => false,
+ };
+ if !missing {
continue;
}
let inputs = appearance_inputs(doc, w);
let stream = match cache.get(w.obj, &inputs) {
Some(stream) => stream,
None => {
- let (stream, _) = appearance::field_appearance_drawn(doc, f, w, &f.value, true);
+ let stream = match f.kind {
+ FieldKind::CheckBox | FieldKind::Radio => appearance::button_state_shown(doc, &f, w, state.as_deref() != Some("Off")),
+ FieldKind::PushButton => appearance::push_button_shown(doc, &f, w),
+ _ => appearance::field_appearance_drawn(doc, &f, w, &f.value, true).0,
+ };
cache.insert(w.obj, inputs, &stream);
stream
}
@@ -1331,10 +1522,25 @@ pub fn with_field_appearances_cached(doc: &Document, cache: &mut FieldAppearance
let target = copy.get_or_insert_with(|| doc.clone());
let ap = target.add(Object::Stream(stream));
let mut fresh = Dict::new();
- fresh.set(b"N".to_vec(), Object::Ref(ap));
+ match &state {
+ // The drawn look under its state's name, and that state as the widget's own.
+ Some(s) => {
+ let mut states = Dict::new();
+ states.set(name_bytes(s), Object::Ref(ap));
+ fresh.set(b"N".to_vec(), Object::Dict(states));
+ }
+ None => fresh.set(b"N".to_vec(), Object::Ref(ap)),
+ }
let apd = merged_appearance(target, w.obj, &fresh);
// Fails only when the widget isn't a dictionary; that widget then keeps its own look.
- target.update_dict(w.obj, |d| d.set(b"AP".to_vec(), Object::Dict(apd))).ok();
+ target
+ .update_dict(w.obj, |d| {
+ d.set(b"AP".to_vec(), Object::Dict(apd));
+ if let Some(s) = &state {
+ d.set(b"AS".to_vec(), Object::Name(name_bytes(s)));
+ }
+ })
+ .ok();
}
}
copy
diff --git a/crates/forms/src/table.rs b/crates/forms/src/table.rs
index 23ad18c..ae56505 100644
--- a/crates/forms/src/table.rs
+++ b/crates/forms/src/table.rs
@@ -269,23 +269,28 @@ pub fn cell_name(pattern: &str, row: usize, column: usize, seq: usize) -> String
if numbered {
return out;
}
+ substitute_isolated_n(&out, &row_number)
+}
+
+fn substitute_isolated_n(out: &str, row_number: &str) -> String {
if out == "N" || out == "n" {
- return row_number;
+ return row_number.to_string();
}
let chars: Vec<char> = out.chars().collect();
let mut named = String::with_capacity(out.len() + row_number.len());
+ let mut numbered = false;
for (i, &ch) in chars.iter().enumerate() {
let after_separator = i.checked_sub(1).and_then(|p| chars.get(p)).is_some_and(|c| SEPARATORS.contains(c));
let before_separator = chars.get(i + 1).is_none_or(|c| SEPARATORS.contains(c));
if matches!(ch, 'N' | 'n') && after_separator && before_separator {
- named.push_str(&row_number);
+ named.push_str(row_number);
numbered = true;
} else {
named.push(ch);
}
}
if !numbered {
- named.push_str(&row_number);
+ named.push_str(row_number);
}
named
}
diff --git a/crates/forms/src/tests.rs b/crates/forms/src/tests.rs
index bb32679..3f93e6f 100644
--- a/crates/forms/src/tests.rs
+++ b/crates/forms/src/tests.rs
@@ -387,6 +387,229 @@ fn opt_export_values_select_button_states() {
assert!(err.to_string().contains("options: Post, Pick-up"), "{err}");
}
+/// What fits a text field is measured as its appearance draws it: in the field's own font (its
+/// `/DR` font, Helvetica where that can't show the text), inside the border and padding, at its
+/// size, wrapped for multi-line, at the smallest automatic size, as asterisks for a password,
+/// and without a limit for a comb field.
+#[test]
+fn a_text_field_says_what_fits_it_as_its_appearance_draws_it() {
+ // Each widget is 100 x 20 pt (multi-line: 100 x 40 pt) with no border: 96 pt inside the 2 pt
+ // padding (36 pt high for the multi-line one).
+ let tx = |name: &str, da: &str, ff: u32, extra: &str, top: i32, h: i32| {
+ format!("<< /Type /Annot /Subtype /Widget /FT /Tx /T ({name}) /DA ({da}) /Ff {ff}{extra} /Rect [50 {} 150 {top}] /P 3 0 R >>", top - h)
+ };
+ let objs: Vec<String> = vec![
+ "<< /Type /Catalog /Pages 2 0 R /AcroForm 4 0 R >>".into(),
+ "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 600 800] >>".into(),
+ "<< /Type /Page /Parent 2 0 R /Annots [7 0 R 8 0 R 9 0 R 10 0 R 11 0 R 12 0 R] >>".into(),
+ "<< /Fields [7 0 R 8 0 R 9 0 R 10 0 R 11 0 R 12 0 R] /DA (/Helv 0 Tf 0 g) /DR << /Font << /Helv 5 0 R /Cour 6 0 R >> >> >>".into(),
+ "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>".into(),
+ "<< /Type /Font /Subtype /Type1 /BaseFont /Courier /Encoding /WinAnsiEncoding >>".into(),
+ tx("one", "/Helv 12 Tf 0 g", 0, "", 780, 20),
+ tx("auto", "/Helv 0 Tf 0 g", 0, "", 750, 20),
+ tx("many", "/Helv 12 Tf 0 g", flags::MULTILINE, "", 720, 40),
+ tx("cour", "/Cour 12 Tf 0 g", 0, "", 670, 20),
+ tx("pin", "/Helv 12 Tf 0 g", flags::PASSWORD, "", 640, 20),
+ tx("comb", "/Helv 12 Tf 0 g", flags::COMB, " /MaxLen 5", 610, 20),
+ ];
+ let doc = document(&objs);
+ let all = fields(&doc);
+ let tb = |name: &str| {
+ let f = field(&all, name);
+ appearance::text_box(&doc, f, &f.widgets[0])
+ };
+ let helv = |s: &str, size: f64| pdfcraft_fonts::helvetica_width(s, size);
+ // Single line at 12 pt: as wide as the 96 pt inside, and no wider.
+ let fits_12: String = std::iter::repeat_n('W', (96.0 / helv("W", 12.0)) as usize).collect();
+ assert!(tb("one").fits(&fits_12) && !tb("one").fits(&format!("{fits_12}W")), "{}", fits_12.len());
+ // An automatic size shrinks first: full only when 4 pt no longer fits.
+ let fits_4: String = std::iter::repeat_n('W', (96.0 / helv("W", 4.0)) as usize).collect();
+ assert!(!tb("one").fits(&fits_4) && tb("auto").fits(&fits_4) && !tb("auto").fits(&format!("{fits_4}W")));
+ // Multi-line: lines of 12 x 1.15 pt each in 36 pt, so two lines fit and three don't.
+ assert!(tb("many").fits("one\ntwo") && !tb("many").fits("one\ntwo\nthree"));
+ let two_lines_of_words = "word ".repeat(((96.0 / helv("word ", 12.0)) as usize) * 2);
+ assert!(tb("many").fits(two_lines_of_words.trim_end()) && !tb("many").fits(&format!("{two_lines_of_words}word")));
+ // The field's own font: narrow i's that Helvetica fits are too wide in Courier (600/1000 em).
+ let i_s: String = std::iter::repeat_n('i', 14).collect();
+ assert!(tb("one").fits(&i_s) && !tb("cour").fits(&i_s), "Courier is 0.6 em a character: {}", 14.0 * 0.6 * 12.0);
+ // A password is drawn, so measured, as asterisks.
+ let thirty_i: String = std::iter::repeat_n('i', 30).collect();
+ assert!(tb("one").fits(&thirty_i) && !tb("pin").fits(&thirty_i), "{} pt of asterisks", helv(&"*".repeat(30), 12.0));
+ // A comb field's cells bound it, not its width.
+ assert!(tb("comb").fits(&"W".repeat(50)));
+}
+
+/// #4339 review: a multi-line field is full when its appearance stops drawing lines (a line is
+/// drawn while its descent stays inside the border), not when `lines x size x 1.15` outgrows the
+/// padded height: a 16 pt field at 12 pt draws one line.
+#[test]
+fn a_short_multiline_field_takes_the_one_line_it_draws() {
+ let tx = |name: &str, extra: &str, h: i32| {
+ format!(
+ "<< /Type /Annot /Subtype /Widget /FT /Tx /T ({name}) /DA (/Helv 12 Tf 0 g) /Ff {}{extra} /Rect [50 {} 150 700] /P 3 0 R >>",
+ flags::MULTILINE,
+ 700 - h
+ )
+ };
+ let objs: Vec<String> = vec![
+ "<< /Type /Catalog /Pages 2 0 R /AcroForm 4 0 R >>".into(),
+ "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 600 800] >>".into(),
+ "<< /Type /Page /Parent 2 0 R /Annots [6 0 R 7 0 R] >>".into(),
+ "<< /Fields [6 0 R 7 0 R] /DA (/Helv 12 Tf 0 g) /DR << /Font << /Helv 5 0 R >> >> >>".into(),
+ "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>".into(),
+ tx("plain", "", 16),
+ tx("boxed", " /MK << /BC [0] >>", 16),
+ ];
+ let doc = document(&objs);
+ let all = fields(&doc);
+ let tb = |name: &str| {
+ let f = field(&all, name);
+ appearance::text_box(&doc, f, &f.widgets[0])
+ };
+ assert!(tb("plain").fits("one line") && !tb("plain").fits("one\ntwo"));
+ // A 1 pt border takes 1 pt from each side: the line's descent then falls outside it.
+ assert!(!tb("boxed").fits("one line"));
+}
+
+/// A multi-line field narrower than one glyph: wrapping can't break inside a character, so the
+/// appearance cuts that character at the sides (`Overflow::Wide`), and `fits` must say so too.
+#[test]
+fn a_multiline_field_rejects_a_glyph_wider_than_the_field() {
+ // 12 x 40 pt with no border: 8 pt inside the 2 pt padding. At 12 pt Helvetica a W is 11.3 pt
+ // wide and an i 2.7 pt.
+ let objs: Vec<String> = vec![
+ "<< /Type /Catalog /Pages 2 0 R /AcroForm 4 0 R >>".into(),
+ "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 600 800] >>".into(),
+ "<< /Type /Page /Parent 2 0 R /Annots [6 0 R] >>".into(),
+ "<< /Fields [6 0 R] /DA (/Helv 12 Tf 0 g) /DR << /Font << /Helv 5 0 R >> >> >>".into(),
+ "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>".into(),
+ format!(
+ "<< /Type /Annot /Subtype /Widget /FT /Tx /T (thin) /V (W) /DA (/Helv 12 Tf 0 g) /Ff {} /Rect [50 660 62 700] /P 3 0 R >>",
+ flags::MULTILINE
+ ),
+ ];
+ let doc = document(&objs);
+ let all = fields(&doc);
+ let f = field(&all, "thin");
+ let tb = appearance::text_box(&doc, f, &f.widgets[0]);
+ assert!(tb.fits("i") && tb.fits("i\ni"));
+ assert!(matches!(appearance::value_overflow(&doc, f, &f.widgets[0]), Some(appearance::Overflow::Wide { .. })));
+ assert!(!tb.fits("W") && !tb.fits("iW"));
+}
+
+/// An edit to a field that doesn't scroll keeps as much of what it inserted as fits, wherever the
+/// caret was, and always keeps a deletion.
+#[test]
+fn an_edit_to_a_full_field_keeps_what_fits() {
+ let objs: Vec<String> = vec![
+ "<< /Type /Catalog /Pages 2 0 R /AcroForm 4 0 R >>".into(),
+ "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 600 800] >>".into(),
+ "<< /Type /Page /Parent 2 0 R /Annots [5 0 R] >>".into(),
+ "<< /Fields [5 0 R] /DA (/Helv 12 Tf 0 g) >>".into(),
+ "<< /Type /Annot /Subtype /Widget /FT /Tx /T (one) /DA (/Helv 12 Tf 0 g) /Rect [50 760 150 780] /P 3 0 R >>".into(),
+ ];
+ let doc = document(&objs);
+ let all = fields(&doc);
+ let f = field(&all, "one");
+ let tb = appearance::text_box(&doc, f, &f.widgets[0]);
+ // Typing in the middle of "Short": the X's go in until the field is full, the end stays.
+ let typed = format!("Sh{}ort", "X".repeat(40));
+ let (kept, caret) = tb.fitted_edit("Short", &typed);
+ let xs = kept.chars().filter(|c| *c == 'X').count();
+ assert!(kept.starts_with("ShX") && kept.ends_with("Xort") && xs < 40, "{kept}");
+ assert!(tb.fits(&kept) && !tb.fits(&format!("Sh{}ort", "X".repeat(xs + 1))), "as many as fit: {xs}");
+ assert_eq!(caret, 2 + xs, "the caret after the last X kept");
+ // What fits is kept whole.
+ assert_eq!(tb.fitted_edit("Short", "Shorter"), ("Shorter".to_string(), 7));
+ // A deletion is kept even from text that already overflows (set by a script, say).
+ let long = "W".repeat(20);
+ assert!(!tb.fits(&long));
+ assert_eq!(tb.fitted_edit(&long, &"W".repeat(19)), ("W".repeat(19), 19));
+ // Replacing a selection with too much keeps the removal and what fits of the replacement.
+ let (kept, _) = tb.fitted_edit("Short", &format!("S{}t", "W".repeat(30)));
+ assert!(kept.starts_with("SW") && kept.ends_with('t') && tb.fits(&kept), "{kept}");
+}
+
+/// When the field's own font can't show a character of a paste, the text from there on is drawn
+/// in Helvetica, which can be narrower: the longest part that fits may come after that point, and
+/// is still the one kept.
+#[test]
+fn an_edit_keeps_the_longest_part_that_fits_across_a_change_of_font() {
+ // A subset font holding only A, 1 em wide: 12 pt an A at 12 pt, against Helvetica's 8 pt.
+ let objs: Vec<String> = vec![
+ "<< /Type /Catalog /Pages 2 0 R /AcroForm 4 0 R >>".into(),
+ "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 600 800] >>".into(),
+ "<< /Type /Page /Parent 2 0 R /Annots [6 0 R] >>".into(),
+ "<< /Fields [6 0 R] /DA (/Wide 12 Tf 0 g) /DR << /Font << /Wide 5 0 R >> >> >>".into(),
+ "<< /Type /Font /Subtype /Type1 /BaseFont /ABCDEF+Wide /FirstChar 65 /LastChar 65 /Widths [1000] /Encoding /WinAnsiEncoding >>".into(),
+ "<< /Type /Annot /Subtype /Widget /FT /Tx /T (one) /DA (/Wide 12 Tf 0 g) /Rect [50 760 150 780] /P 3 0 R >>".into(),
+ ];
+ let doc = document(&objs);
+ let all = fields(&doc);
+ let f = field(&all, "one");
+ let tb = appearance::text_box(&doc, f, &f.widgets[0]);
+ // 96 pt inside: 8 A's in the subset font, or 11 characters (8.004 pt each) once a B brings
+ // Helvetica in.
+ assert!(tb.fits(&"A".repeat(8)) && !tb.fits(&"A".repeat(9)));
+ let pasted = format!("{}B{}", "A".repeat(10), "A".repeat(30));
+ let (kept, caret) = tb.fitted_edit("", &pasted);
+ assert_eq!(kept, format!("{}B", "A".repeat(10)), "the 11 characters that fit in Helvetica, not the 8 before the B");
+ assert!(!tb.fits(&format!("{}BA", "A".repeat(10))), "and no more");
+ assert_eq!(caret, 11);
+}
+
+/// A check box laid out for a round XFA check button (`/PCXfaRound true`) draws its background
+/// and border as a circle inside the widget, inset by half the border so the stroke stays in,
+/// or a disc when the border is as wide as the circle (an underline stays one); one without the
+/// key keeps its rectangle.
+#[test]
+fn a_round_xfa_check_button_draws_a_round_background_and_border() {
+ let widget = |name: &str, extra: &str| {
+ format!(
+ "<< /Type /Annot /Subtype /Widget /FT /Btn /T ({name}) /Rect [50 700 70 720] /P 3 0 R /MK << /BG [0.8 0.85 1] /BC [1 0 0] >> /BS << /W 1 /S /S >>{extra} >>"
+ )
+ };
+ let objs: Vec<String> = vec![
+ "<< /Type /Catalog /Pages 2 0 R /AcroForm 4 0 R >>".into(),
+ "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 600 800] >>".into(),
+ "<< /Type /Page /Parent 2 0 R /Annots [5 0 R 6 0 R 7 0 R 8 0 R 9 0 R] >>".into(),
+ "<< /Fields [5 0 R 6 0 R 7 0 R 8 0 R 9 0 R] >>".into(),
+ widget("round", " /PCXfaRound true"),
+ widget("square", ""),
+ widget("dashed", " /PCXfaRound true /BS << /W 2 /S /D >>").replace("/BS << /W 1 /S /S >>", ""),
+ widget("thick", " /PCXfaRound true /BS << /W 30 /S /S >>").replace("/BS << /W 1 /S /S >>", ""),
+ widget("underlined", " /PCXfaRound true /BS << /W 1 /S /U >>").replace("/BS << /W 1 /S /S >>", ""),
+ ];
+ let mut doc = document(&objs);
+ for name in ["round", "square", "dashed", "thick", "underlined"] {
+ redraw_field(&mut doc, name).unwrap();
+ }
+ // The Off state: only the frame.
+ let off = |name: &str| {
+ let all = fields(&doc);
+ let w = field(&all, name).widgets[0].obj;
+ let wd = doc.get(w).as_dict().cloned().unwrap();
+ let n = doc.resolve(wd.get(b"AP").unwrap().as_dict().unwrap().get(b"N").unwrap());
+ let r = n.as_dict().unwrap().reference(b"Off").expect("an Off appearance");
+ let Object::Stream(s) = &*doc.get(r) else { panic!("Off is a stream") };
+ String::from_utf8_lossy(&s.decoded().unwrap()).into_owned()
+ };
+ let round = off("round");
+ assert!(!round.contains(" re "), "no rectangle: {round}");
+ assert!(round.contains("0.8 0.85 1 rg\n20 10 m"), "the background is a disc as wide as the box: {round}");
+ assert!(round.contains("1 0 0 RG\n1 w\n19.5 10 m") && round.contains(" c S"), "the border is a circle inset by half its width: {round}");
+ let square = off("square");
+ assert!(square.contains("0 0 20 20 re f") && square.contains("re S"), "a square box keeps its rectangle: {square}");
+ let dashed = off("dashed");
+ assert!(dashed.contains("[3] 0 d\n19 10 m"), "a dashed round border stays dashed: {dashed}");
+ // A border wider than the 20pt circle fills it: a disc in the border's colour, no stroke.
+ let thick = off("thick");
+ assert!(thick.contains("1 0 0 rg\n20 10 m") && !thick.contains(" S\n"), "a border as wide as the circle is a disc: {thick}");
+ // An underline stays the bottom edge, under a round background.
+ let underlined = off("underlined");
+ assert!(underlined.contains("1 0 0 RG\n1 w\n0 0.5 m 20 0.5 l S"), "an underline stays an underline: {underlined}");
+}
+
/// Issue #1323: a text field without a format keeps a whitespace-only value as typed; only an
/// empty value clears it.
#[test]
@@ -1307,7 +1530,7 @@ fn formats_validation_and_calculations_run_like_acrobat() {
// Keystroke and validation errors use Acrobat's messages and change nothing.
assert_eq!(
set_value(&mut doc, "Qty", &FieldValue::Text("lots".into())),
- Err(FormError::Invalid("The value entered does not match the format of the field [ Qty ]".into()))
+ Err(FormError::Format("The value entered does not match the format of the field [ Qty ]".into()))
);
assert_eq!(
set_value(&mut doc, "Qty", &FieldValue::Text("120".into())),
@@ -1326,6 +1549,30 @@ fn formats_validation_and_calculations_run_like_acrobat() {
assert_eq!(field(&fields(&doc), "Price").actions.format, Format::None);
}
+/// A Calculate script that spells the notation's markers in a string, not in a comment, is kept
+/// as a script and runs: the form used to calculate the string's notation instead.
+#[test]
+fn a_script_that_spells_the_markers_in_a_string_runs_as_a_script() {
+ struct Ran;
+ impl Scripts for Ran {
+ fn run(&mut self, _event: FieldEvent, _script: &str, _target: &Field, _value: &str, _fields: &[Field]) -> ScriptResult {
+ ScriptResult { rc: true, value: "ran".into(), changes: Vec::new(), message: None }
+ }
+ }
+ let mut doc = one_page();
+ let text = NewField::Text { multiline: false };
+ add_field(&mut doc, 0, [50.0, 700.0, 250.0, 720.0], &text, Some("a")).unwrap();
+ add_field(&mut doc, 0, [50.0, 660.0, 250.0, 680.0], &text, Some("total")).unwrap();
+ let js = "var note = \"BVCALC a EVCALC\"; event.value = 7;";
+ set_field_script(&mut doc, "total", "calculate", Some(js)).unwrap();
+ set_value(&mut doc, "a", &FieldValue::Text("5".into())).unwrap();
+ let all = fields(&doc);
+ let total = &field(&all, "total").actions;
+ assert_eq!((&total.calculate, total.scripts.calculate.as_deref()), (&af::Calculate::None, Some(js)));
+ recalculate_with(&mut doc, &mut Ran).unwrap();
+ assert_eq!(field(&fields(&doc), "total").value, ["ran"]);
+}
+
/// Renaming a field renames it in the calculations that read it: a sum dropped it, notation
/// read it as 0 and a script read a field that no longer existed.
#[test]
@@ -1358,6 +1605,32 @@ fn renaming_a_field_renames_it_in_the_calculations_that_read_it() {
assert_eq!((field(&all, "sum").value.clone(), field(&all, "product").value.clone()), (vec!["12".to_string()], vec!["20".to_string()]));
}
+/// A dotted name moves the field under new parent fields (#2696), and the calculations that read
+/// it follow it to its full new name, as they follow a plain rename.
+#[test]
+fn a_dotted_rename_moves_the_field_and_its_calculations_follow() {
+ use crate::af::{CalcOp, Calculate};
+ let mut doc = one_page();
+ let text = NewField::Text { multiline: false };
+ for (i, name) in ["a", "b", "sum", "script"].into_iter().enumerate() {
+ let y = 700.0 - 40.0 * i as f64;
+ add_field(&mut doc, 0, [50.0, y, 250.0, y + 20.0], &text, Some(name)).unwrap();
+ }
+ let calculate =
+ FieldProps { calculate: Some(Calculate::Simple { op: CalcOp::Sum, fields: vec!["a".into(), "b".into()] }), ..FieldProps::default() };
+ set_props(&mut doc, "sum", &calculate).unwrap();
+ set_field_script(&mut doc, "script", "calculate", Some("event.value = getField(\"a\").value;")).unwrap();
+ set_props(&mut doc, "a", &FieldProps { name: Some("Group.a".into()), ..FieldProps::default() }).unwrap();
+ let mut doc = reopen(&doc);
+ let all = fields(&doc);
+ assert!(all.iter().any(|f| f.name == "Group.a") && all.iter().all(|f| f.name != "a"));
+ assert_eq!(field(&all, "sum").actions.calculate, Calculate::Simple { op: CalcOp::Sum, fields: vec!["Group.a".into(), "b".into()] });
+ assert_eq!(field(&all, "script").actions.scripts.calculate.as_deref(), Some("event.value = getField(\"Group.a\").value;"));
+ set_value(&mut doc, "Group.a", &FieldValue::Text("10".into())).unwrap();
+ set_value(&mut doc, "b", &FieldValue::Text("2".into())).unwrap();
+ assert_eq!(field(&fields(&doc), "sum").value, ["12"]);
+}
+
/// The rename reaches a script stored as a stream, an indirect action and the only widget's
/// actions; it leaves a script that isn't UTF-8 as it is, and a name another field still has.
#[test]
@@ -1739,6 +2012,49 @@ fn check_box_styles_change_the_mark() {
);
}
+#[test]
+fn check_mark_takes_the_fields_text_colour() {
+ // #4261: Appearance ▸ Text Color is written to /DA; the mark of a check box or radio button
+ // is drawn in it (Acrobat does the same), black when the /DA has no colour.
+ let mut doc = one_page();
+ let check = add_field(&mut doc, 0, [50.0, 700.0, 70.0, 720.0], &NewField::CheckBox, None).unwrap();
+ let radio = add_field(&mut doc, 0, [50.0, 600.0, 70.0, 620.0], &NewField::Radio { group: None, export: "A".into() }, None).unwrap();
+ let on_ap = |doc: &Document, name: &str| {
+ let all = fields(doc);
+ let w = &field(&all, name).widgets[0];
+ let on = w.on_state.clone().unwrap();
+ let n = doc
+ .get(w.obj)
+ .as_dict()
+ .unwrap()
+ .get(b"AP")
+ .unwrap()
+ .as_dict()
+ .unwrap()
+ .get(b"N")
+ .unwrap()
+ .as_dict()
+ .unwrap()
+ .reference(on.as_bytes())
+ .unwrap();
+ let Object::Stream(s) = &*doc.get(n) else { panic!() };
+ String::from_utf8_lossy(&s.decoded().unwrap()).into_owned()
+ };
+ assert!(on_ap(&doc, &check).contains("0 G"), "black by default");
+ let blue = FieldProps { appearance: Some(LookPatch { text: Some([0.0, 0.0, 1.0]), ..Default::default() }), ..Default::default() };
+ for name in [&check, &radio] {
+ set_props(&mut doc, name, &blue).unwrap();
+ let ap = on_ap(&reopen(&doc), name);
+ // The check strokes, the radio's default circle fills.
+ let op = if name == &check { "0 0 1 RG" } else { "0 0 1 rg" };
+ assert!(ap.contains(op), "{name}: the mark is blue: {ap}");
+ assert!(!ap.contains("0 G\n") && !ap.contains("0 g\n"), "{name}: no black left: {ap}");
+ }
+ // A style change redraws too, and keeps the colour.
+ set_props(&mut doc, &check, &FieldProps { check_style: Some(CheckStyle::Square), ..FieldProps::default() }).unwrap();
+ assert!(on_ap(&doc, &check).contains("0 0 1 rg"), "a square is blue as well");
+}
+
#[test]
fn ordering_tabs_manually() {
let mut doc = one_page();
@@ -1920,6 +2236,80 @@ fn field_actions_round_trip_on_every_trigger() {
assert_eq!(fields(&doc).iter().find(|f| f.name == "go").unwrap().button, Some(af::ButtonAction::Named("Print".into())));
}
+#[test]
+fn editing_one_script_keeps_the_other_actions_and_the_chain() {
+ let mut doc = fixture();
+ let go = field(&fields(&doc), "go").obj;
+ let action = |doc: &mut Document, entries: Vec<(&[u8], Object)>| {
+ let mut a = Dict::new();
+ for (k, v) in entries {
+ a.set(k.to_vec(), v);
+ }
+ doc.add(Object::Dict(a))
+ };
+ let next = action(&mut doc, vec![(b"S", Object::name("URI")), (b"URI", Object::String(PdfString::literal(b"https://example.org".to_vec())))]);
+ let up = action(
+ &mut doc,
+ vec![(b"S", Object::name("JavaScript")), (b"JS", Object::String(PdfString::text("app.alert(1);"))), (b"Next", Object::Ref(next))],
+ );
+ let blur = action(
+ &mut doc,
+ vec![(b"S", Object::name("JavaScript")), (b"JS", Object::String(PdfString::text("this.dirty = true;"))), (b"Foo", Object::Int(7))],
+ );
+ let mut aa = Dict::new();
+ aa.set(b"Bl".to_vec(), Object::Ref(blur));
+ doc.update_dict(go, |d| {
+ d.set(b"A".to_vec(), Object::Ref(up));
+ d.set(b"AA".to_vec(), Object::Dict(aa));
+ })
+ .unwrap();
+ let mut acts = field_actions(&doc, "go").unwrap();
+ assert_eq!(acts[0], (Trigger::MouseUp, FieldAction::JavaScript("app.alert(1);".into())));
+ acts[0].1 = FieldAction::JavaScript("app.alert(2);".into());
+ set_field_actions(&mut doc, "go", &acts).unwrap();
+ let w = doc.get(go).as_dict().cloned().unwrap();
+ // The action that did not change is the same object, with its keys this crate doesn't read.
+ let aa = w.get(b"AA").unwrap().as_dict().unwrap().clone();
+ assert_eq!(aa.get(b"Bl"), Some(&Object::Ref(blur)));
+ // The edited script keeps the actions chained after it.
+ let a = doc.resolve(w.get(b"A").unwrap()).as_dict().cloned().unwrap();
+ assert_eq!(a.get(b"Next"), Some(&Object::Ref(next)));
+ assert_eq!(field_actions(&doc, "go").unwrap()[0], (Trigger::MouseUp, FieldAction::JavaScript("app.alert(2);".into())));
+}
+
+#[test]
+fn replacing_a_chained_action_with_another_type_keeps_the_chain() {
+ let mut doc = fixture();
+ let go = field(&fields(&doc), "go").obj;
+ let s = |t: &str| Object::String(PdfString::text(t));
+ let mut named = Dict::new();
+ named.set(b"S".to_vec(), Object::name("Named"));
+ named.set(b"N".to_vec(), Object::name("NextPage"));
+ let named = doc.add(Object::Dict(named));
+ // A chain as an array: a link, then a menu item that points back at the link (a loop).
+ let mut uri = Dict::new();
+ uri.set(b"S".to_vec(), Object::name("URI"));
+ uri.set(b"URI".to_vec(), s("https://example.org"));
+ let uri = doc.add(Object::Dict(uri));
+ doc.update_dict(named, |d| d.set(b"Next".to_vec(), Object::Ref(uri))).unwrap();
+ let chain = Object::Array(vec![Object::Ref(uri), Object::Ref(named)]);
+ let mut up = Dict::new();
+ up.set(b"S".to_vec(), Object::name("JavaScript"));
+ up.set(b"JS".to_vec(), s("app.alert(1);"));
+ up.set(b"Next".to_vec(), chain.clone());
+ doc.update_dict(go, |d| d.set(b"A".to_vec(), Object::Dict(up))).unwrap();
+ assert_eq!(field_action_chains(&doc, "go").unwrap(), [(Trigger::MouseUp, 2)]);
+ set_field_actions(&mut doc, "go", &[(Trigger::MouseUp, FieldAction::Uri("https://example.com".into()))]).unwrap();
+ let w = doc.get(go).as_dict().cloned().unwrap();
+ let a = doc.resolve(w.get(b"A").unwrap()).as_dict().cloned().unwrap();
+ assert_eq!(a.get(b"Next"), Some(&chain));
+ assert_eq!(field_actions(&doc, "go").unwrap(), [(Trigger::MouseUp, FieldAction::Uri("https://example.com".into()))]);
+ assert_eq!(field_action_chains(&doc, "go").unwrap(), [(Trigger::MouseUp, 2)]);
+ // Deleting the trigger's action deletes its chain with it.
+ set_field_actions(&mut doc, "go", &[]).unwrap();
+ assert_eq!(field_action_chains(&doc, "go").unwrap(), []);
+}
+
#[test]
fn push_buttons_read_hide_actions() {
let mut doc = fixture();
@@ -3110,3 +3500,899 @@ fn a_skipped_field_leaves_its_widget_to_the_next() {
let widgets: Vec<(&str, usize)> = all.iter().map(|f| (f.name.as_str(), f.widgets.len())).collect();
assert_eq!(widgets, [("b", 1)]);
}
+
+/// #2696: a dotted name is a full name. `MASTER.first` is a field `first` under a parent field
+/// `MASTER` (a partial name can't contain a period, ISO 32000-2 §12.7.4.2); a second `MASTER.`
+/// name joins that parent; renaming to a dotted name moves the field, keeping what it inherited;
+/// and a name that would make one field both hold a value and hold fields is refused.
+#[test]
+fn dotted_field_names_are_made_with_parent_fields() {
+ let mut doc = fixture();
+ let top = |doc: &Document| {
+ let root = doc.root().unwrap();
+ let af = doc.get(root).as_dict().and_then(|d| d.reference(b"AcroForm")).unwrap();
+ doc.get(af).as_dict().and_then(|d| d.get(b"Fields").and_then(|o| o.as_array().map(|a| a.len()))).unwrap()
+ };
+ let own_name = |doc: &Document, f: &Field| doc.get(f.obj).as_dict().and_then(|d| d.get(b"T").and_then(text_of));
+ let parent_of = |doc: &Document, f: &Field| doc.get(f.obj).as_dict().and_then(|d| d.reference(b"Parent")).unwrap();
+ let text = NewField::Text { multiline: false };
+ let before = top(&doc);
+ assert_eq!(add_field(&mut doc, 0, [50.0, 300.0, 200.0, 320.0], &text, Some("MASTER.account_firstname")).unwrap(), "MASTER.account_firstname");
+ add_field(&mut doc, 0, [50.0, 260.0, 200.0, 280.0], &text, Some("MASTER.street1")).unwrap();
+ assert_eq!(top(&doc), before + 1, "one parent field at the top");
+ let saved = reopen(&doc);
+ let all = fields(&saved);
+ let (a, b) = (field(&all, "MASTER.account_firstname"), field(&all, "MASTER.street1"));
+ assert_eq!(own_name(&saved, b).as_deref(), Some("street1"), "the field's own name has no period");
+ let master = parent_of(&saved, a);
+ assert_eq!(parent_of(&saved, b), master, "both under one MASTER");
+ assert_eq!(saved.get(master).as_dict().and_then(|d| d.get(b"T").and_then(text_of)).as_deref(), Some("MASTER"));
+
+ // Renaming to a dotted name moves the field: zip joins the existing address parent.
+ assert_eq!(set_props(&mut doc, "zip", &FieldProps { name: Some("address.zip".into()), ..FieldProps::default() }).unwrap(), "address.zip");
+ assert_eq!(top(&doc), before, "zip left the top");
+ let all = fields(&doc);
+ let (zip, city) = (field(&all, "address.zip"), field(&all, "address.city"));
+ assert_eq!(parent_of(&doc, zip), parent_of(&doc, city));
+ assert_eq!(zip.max_len, Some(5), "its own settings move with it");
+
+ // What a moved field inherited stays; what a new field would inherit from a parent it
+ // joins doesn't apply to it.
+ let address = parent_of(&doc, city);
+ doc.update_dict(address, |d| {
+ d.set(b"Ff".to_vec(), Object::Int(flags::READ_ONLY as i64));
+ d.set(b"V".to_vec(), Object::String(PdfString::literal(b"Springfield".to_vec())));
+ })
+ .unwrap();
+ let city = field(&fields(&doc), "address.city").clone();
+ assert!(city.read_only() && city.value == ["Springfield"]);
+ set_props(&mut doc, "address.city", &FieldProps { name: Some("billing.city".into()), ..FieldProps::default() }).unwrap();
+ let moved = field(&fields(&doc), "billing.city").clone();
+ assert!(moved.read_only() && moved.value == ["Springfield"], "the moved field keeps what it inherited");
+ // A parent's value, reset value or length limit would pass to a new field under it (review
+ // on #2957), and a field can't turn them off: such a parent takes no new field.
+ let street = |doc: &mut Document| add_field(doc, 0, [300.0, 300.0, 450.0, 320.0], &text, Some("address.street"));
+ for (key, value) in [
+ (&b"V"[..], Object::String(PdfString::literal(b"x".to_vec()))),
+ (b"DV", Object::String(PdfString::literal(b"x".to_vec()))),
+ (b"MaxLen", Object::Int(3)),
+ ] {
+ doc.update_dict(address, |d| {
+ for k in [&b"V"[..], b"DV", b"MaxLen"] {
+ d.remove(k);
+ }
+ d.set(key.to_vec(), value);
+ })
+ .unwrap();
+ let mut copy = doc.clone();
+ assert!(street(&mut copy).is_err(), "address holds /{}", String::from_utf8_lossy(key));
+ }
+ doc.update_dict(address, |d| {
+ d.remove(b"MaxLen");
+ })
+ .unwrap();
+ street(&mut doc).unwrap();
+ let new = field(&fields(&doc), "address.street").clone();
+ assert!(!new.read_only(), "a new field doesn't take its parent's flags");
+ assert!(new.value.iter().all(|v| v.is_empty()) && new.max_len.is_none(), "nor a value or length limit: {:?} {:?}", new.value, new.max_len);
+
+ // A parent left empty by a move isn't a terminal field, but its name is still taken.
+ add_field(&mut doc, 0, [300.0, 340.0, 450.0, 360.0], &text, Some("box.only")).unwrap();
+ set_props(&mut doc, "box.only", &FieldProps { name: Some("elsewhere.only".into()), ..FieldProps::default() }).unwrap();
+ assert!(fields(&doc).iter().all(|f| !f.name.starts_with("box")), "box holds no field now");
+ let mut copy = doc.clone();
+ assert!(add_field(&mut copy, 0, [300.0, 380.0, 450.0, 400.0], &text, Some("box")).is_err(), "a new field named box");
+ let mut copy = doc.clone();
+ assert!(set_props(&mut copy, "name", &FieldProps { name: Some("box".into()), ..FieldProps::default() }).is_err(), "a rename to box");
+ // Under it, the name is free: the empty parent takes a field again.
+ add_field(&mut doc, 0, [300.0, 380.0, 450.0, 400.0], &text, Some("box.again")).unwrap();
+ // Only a whole path that exists can be taken: under box.sub, made new, "again" is free.
+ add_field(&mut doc, 0, [300.0, 420.0, 450.0, 440.0], &text, Some("box.sub.again")).unwrap();
+ // A field holding its own value may join a parent holding one; and the parents a new path
+ // makes are new, even where an existing field has the name of a later part.
+ doc.update_dict(address, |d| d.set(b"V".to_vec(), Object::String(PdfString::literal(b"x".to_vec())))).unwrap();
+ set_props(&mut doc, "billing.city", &FieldProps { name: Some("address.city".into()), ..FieldProps::default() }).unwrap();
+ assert_eq!(field(&fields(&doc), "address.city").value, ["Springfield"]);
+ add_field(&mut doc, 0, [300.0, 460.0, 450.0, 480.0], &text, Some("nope.address.x")).unwrap();
+ // Renaming the last part: to its own name is no change; to an empty parent's name beside it
+ // is taken.
+ assert_eq!(set_props(&mut doc, "address.city", &FieldProps { name: Some("city".into()), ..FieldProps::default() }).unwrap(), "address.city");
+ doc.update_dict(address, |d| {
+ d.remove(b"V");
+ })
+ .unwrap();
+ add_field(&mut doc, 0, [300.0, 500.0, 450.0, 520.0], &text, Some("address.grp.x")).unwrap();
+ set_props(&mut doc, "address.grp.x", &FieldProps { name: Some("elsewhere.x".into()), ..FieldProps::default() }).unwrap();
+ assert!(
+ set_props(&mut doc.clone(), "address.city", &FieldProps { name: Some("grp".into()), ..FieldProps::default() }).is_err(),
+ "address.grp is taken"
+ );
+ // A move the destination refuses leaves the field where it was (review on #2957): it was
+ // taken out of the tree before the destination was checked, and stayed out.
+ doc.update_dict(address, |d| d.set(b"MaxLen".to_vec(), Object::Int(3))).unwrap();
+ let at_top = top(&doc);
+ assert!(set_props(&mut doc, "name", &FieldProps { name: Some("address.name".into()), ..FieldProps::default() }).is_err());
+ assert_eq!(top(&doc), at_top, "name is still in the form's /Fields");
+ // Nor is what it inherits copied onto it first (review on #2957): src.f inherits /V from src.
+ add_field(&mut doc, 0, [300.0, 540.0, 450.0, 560.0], &text, Some("src.f")).unwrap();
+ let f = field(&fields(&doc), "src.f").obj;
+ let src = doc.get(f).as_dict().and_then(|d| d.reference(b"Parent")).unwrap();
+ doc.update_dict(src, |d| d.set(b"V".to_vec(), Object::String(PdfString::literal(b"inh".to_vec())))).unwrap();
+ assert!(set_props(&mut doc, "src.f", &FieldProps { name: Some("address.f".into()), ..FieldProps::default() }).is_err());
+ assert!(!doc.get(f).as_dict().unwrap().contains(b"V"), "src.f still only inherits its value");
+ // What it inherits counts as its own where it goes: with /V on address and no /MaxLen,
+ // src.f moves, keeping its value.
+ doc.update_dict(address, |d| {
+ d.remove(b"MaxLen");
+ d.set(b"V".to_vec(), Object::String(PdfString::literal(b"x".to_vec())));
+ })
+ .unwrap();
+ set_props(&mut doc, "src.f", &FieldProps { name: Some("address.f".into()), ..FieldProps::default() }).unwrap();
+ assert_eq!(field(&fields(&doc), "address.f").value, ["inh"]);
+ doc.update_dict(address, |d| {
+ d.remove(b"V");
+ })
+ .unwrap();
+ doc.update_dict(address, |d| {
+ d.remove(b"MaxLen");
+ })
+ .unwrap();
+
+ for bad in ["MASTER", "MASTER.street1.x", "MASTER..x", ".x", "x.", "MASTER. "] {
+ assert!(add_field(&mut doc, 0, [300.0, 200.0, 450.0, 220.0], &text, Some(bad)).is_err(), "{bad:?}");
+ assert!(set_props(&mut doc, "name", &FieldProps { name: Some(bad.into()), ..FieldProps::default() }).is_err(), "{bad:?}");
+ }
+ let deep = vec!["p"; 33].join(".");
+ assert!(add_field(&mut doc, 0, [300.0, 200.0, 450.0, 220.0], &text, Some(&deep)).is_err(), "too deep");
+ assert!(set_props(&mut doc, "name", &FieldProps { name: Some("MASTER.street1".into()), ..FieldProps::default() }).is_err(), "taken");
+}
+
+/// Review on #2957: a parent left empty by a move keeps its name from the next default name
+/// (`Text1` after `Text1.x` moved away); and a full name that keeps the parents is a plain
+/// rename, so the field stays in its place among its parent's /Kids and keeps inheriting.
+#[test]
+fn empty_parents_and_same_parent_renames() {
+ let mut doc = fixture();
+ let text = NewField::Text { multiline: false };
+ let auto = |doc: &mut Document, y: f64| add_field(doc, 0, [50.0, y, 200.0, y + 20.0], &text, None);
+ let mut copy = doc.clone();
+ let first = auto(&mut copy, 100.0).unwrap();
+ add_field(&mut doc, 0, [50.0, 140.0, 200.0, 160.0], &text, Some(&format!("{first}.x"))).unwrap();
+ set_props(&mut doc, &format!("{first}.x"), &FieldProps { name: Some("other.x".into()), ..FieldProps::default() }).unwrap();
+ assert!(fields(&doc).iter().all(|f| !f.name.starts_with(&first)), "{first} is an empty parent now");
+ let next = auto(&mut doc, 100.0).expect("a default name the empty parent doesn't hold");
+ assert_ne!(next, first);
+
+ let all = fields(&doc);
+ let city = field(&all, "address.city").obj;
+ let address = doc.get(city).as_dict().and_then(|d| d.reference(b"Parent")).unwrap();
+ doc.update_dict(address, |d| d.set(b"V".to_vec(), Object::String(PdfString::literal(b"Springfield".to_vec())))).unwrap();
+ let kids = |doc: &Document| doc.get(address).as_dict().and_then(|d| d.get(b"Kids").and_then(|o| o.as_array().cloned())).unwrap();
+ let before = kids(&doc);
+ assert_eq!(
+ set_props(&mut doc, "address.city", &FieldProps { name: Some("address.town".into()), ..FieldProps::default() }).unwrap(),
+ "address.town"
+ );
+ assert_eq!(kids(&doc), before, "same place among the kids");
+ assert!(!doc.get(city).as_dict().unwrap().contains(b"V"), "still inherits its value rather than owning a copy");
+ assert_eq!(field(&fields(&doc), "address.town").value, ["Springfield"]);
+}
+
+/// Review on #2957: spaces in a typed name. The ends of the whole name are dropped, as Acrobat
+/// does when a field is renamed; a space beside a period stays in the part it belongs to (`a. b`
+/// is `b` with a leading space under `a`), as Acrobat keeps it and as ISO 32000-2 §12.7.4.2
+/// allows: only a period is barred from a partial name.
+#[test]
+fn a_typed_name_loses_its_ends_but_keeps_spaces_beside_periods() {
+ let mut doc = fixture();
+ let own_name = |doc: &Document, full: &str| {
+ let all = fields(doc);
+ doc.get(field(&all, full).obj).as_dict().and_then(|d| d.get(b"T").and_then(text_of))
+ };
+ let text = NewField::Text { multiline: false };
+ assert_eq!(add_field(&mut doc, 0, [50.0, 300.0, 200.0, 320.0], &text, Some(" plain ")).unwrap(), "plain");
+ assert_eq!(add_field(&mut doc, 0, [50.0, 260.0, 200.0, 280.0], &text, Some("a. b")).unwrap(), "a. b");
+ assert_eq!(add_field(&mut doc, 0, [50.0, 220.0, 200.0, 240.0], &text, Some("c .d")).unwrap(), "c .d");
+ assert_eq!(set_props(&mut doc, "zip", &FieldProps { name: Some(" e. f ".into()), ..FieldProps::default() }).unwrap(), "e. f");
+ let saved = reopen(&doc);
+ assert_eq!(own_name(&saved, "plain").as_deref(), Some("plain"));
+ assert_eq!(own_name(&saved, "a. b").as_deref(), Some(" b"));
+ assert_eq!(own_name(&saved, "c .d").as_deref(), Some("d"));
+ assert_eq!(own_name(&saved, "e. f").as_deref(), Some(" f"));
+ let parent = |full: &str| {
+ let all = fields(&saved);
+ let p = saved.get(field(&all, full).obj).as_dict().and_then(|d| d.reference(b"Parent")).unwrap();
+ saved.get(p).as_dict().and_then(|d| d.get(b"T").and_then(text_of))
+ };
+ assert_eq!(parent("c .d").as_deref(), Some("c "), "the space before the period is the parent's");
+ assert_eq!(parent("e. f").as_deref(), Some("e"));
+ // A part that is only spaces is still empty.
+ assert!(add_field(&mut doc, 0, [300.0, 300.0, 450.0, 320.0], &text, Some("g. .h")).is_err());
+}
+
+/// The form's `/DR /Font` entries, resolved through an indirect `/DR` or `/Font`.
+fn dr_fonts(doc: &Document) -> Dict {
+ let af = acroform(doc).unwrap();
+ let dr = doc.resolve(af.get(b"DR").unwrap());
+ doc.resolve(dr.as_dict().unwrap().get(b"Font").unwrap()).as_dict().cloned().unwrap()
+}
+
+/// #3441: Acrobat shows nothing in a text field it redraws after typing when the field's `/DR`
+/// font is a dictionary written inline. A form PdfCraft makes holds each font as its own object.
+#[test]
+fn a_new_form_holds_its_fonts_as_objects() {
+ let mut doc = document(&[
+ "<< /Type /Catalog /Pages 2 0 R >>".into(),
+ "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 600 800] >>".into(),
+ "<< /Type /Page /Parent 2 0 R >>".into(),
+ ]);
+ add_field(&mut doc, 0, [40.0, 600.0, 300.0, 630.0], &NewField::Text { multiline: false }, Some("name")).unwrap();
+ let doc = reopen(&doc);
+ let fonts = dr_fonts(&doc);
+ for (name, base) in [("Helv", "Helvetica"), ("TiRo", "Times-Roman"), ("Cour", "Courier")] {
+ let r = fonts.reference(name.as_bytes()).unwrap_or_else(|| panic!("{name} is an object: {fonts:?}"));
+ assert_eq!(doc.get(r).as_dict().and_then(|f| f.name(b"BaseFont")), Some(base.as_bytes()));
+ }
+}
+
+/// #3441: a form saved earlier with inline `/DR` fonts gets them as objects once a field is
+/// added, saying the same; an indirect `/Font` dictionary stays the object it was.
+#[test]
+fn inline_form_fonts_become_objects_and_an_indirect_font_dictionary_stays_one() {
+ for indirect in [false, true] {
+ let font = "/Helv << /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >> /Mine << /Type /Font /Subtype /Type1 /BaseFont /Symbol >>";
+ let (fonts_entry, extra) =
+ if indirect { ("6 0 R".to_string(), vec![format!("<< {font} >>")]) } else { (format!("<< {font} >>"), Vec::new()) };
+ let mut objs: Vec<String> = vec![
+ "<< /Type /Catalog /Pages 2 0 R /AcroForm 4 0 R >>".into(),
+ "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 600 800] >>".into(),
+ "<< /Type /Page /Parent 2 0 R >>".into(),
+ format!("<< /Fields [] /DA (/Helv 0 Tf 0 g) /DR << /Font {fonts_entry} >> >>"),
+ "null".into(),
+ ];
+ objs.extend(extra);
+ let mut doc = document(&objs);
+ add_field(&mut doc, 0, [40.0, 600.0, 300.0, 630.0], &NewField::Text { multiline: false }, Some("name")).unwrap();
+ let doc = reopen(&doc);
+ let fonts = dr_fonts(&doc);
+ for (name, base) in [("Helv", "Helvetica"), ("Mine", "Symbol"), ("TiRo", "Times-Roman")] {
+ let r = fonts.reference(name.as_bytes()).unwrap_or_else(|| panic!("{name} is an object (indirect {indirect}): {fonts:?}"));
+ assert_eq!(doc.get(r).as_dict().and_then(|f| f.name(b"BaseFont")), Some(base.as_bytes()), "{name} says the same");
+ }
+ let dr = doc.resolve(acroform(&doc).unwrap().get(b"DR").unwrap());
+ assert_eq!(dr.as_dict().unwrap().reference(b"Font").is_some(), indirect, "the /Font dictionary keeps its form");
+ }
+}
+
+/// #3441: an indirect `/DR` stays the object it is, and a form whose three standard fonts are
+/// all already there (inline) still gets them as objects, though none is added.
+#[test]
+fn an_indirect_resource_dictionary_and_a_complete_inline_set_are_handled() {
+ let inline = "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>";
+ let all = format!(
+ "/Helv {inline} /TiRo << /Type /Font /Subtype /Type1 /BaseFont /Times-Roman >> /Cour << /Type /Font /Subtype /Type1 /BaseFont /Courier >>"
+ );
+ for indirect_dr in [false, true] {
+ let dr = if indirect_dr { "5 0 R".to_string() } else { format!("<< /Font << {all} >> >>") };
+ let doc = document(&[
+ "<< /Type /Catalog /Pages 2 0 R /AcroForm 4 0 R >>".into(),
+ "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 600 800] >>".into(),
+ "<< /Type /Page /Parent 2 0 R >>".into(),
+ format!("<< /Fields [] /DA (/Helv 0 Tf 0 g) /DR {dr} >>"),
+ format!("<< /Font << {all} >> >>"),
+ ]);
+ let mut doc = doc;
+ add_field(&mut doc, 0, [40.0, 600.0, 300.0, 630.0], &NewField::Text { multiline: false }, Some("name")).unwrap();
+ let doc = reopen(&doc);
+ let fonts = dr_fonts(&doc);
+ for name in ["Helv", "TiRo", "Cour"] {
+ assert!(fonts.reference(name.as_bytes()).is_some(), "{name} is an object (indirect /DR {indirect_dr}): {fonts:?}");
+ }
+ assert_eq!(acroform(&doc).unwrap().reference(b"DR").is_some(), indirect_dr, "/DR keeps its form");
+ }
+}
+
+/// #3441: fonts the form already has are its own, not replaced by the standard ones: an inline
+/// `/Helv` that is Arial becomes an object that is still Arial, a `/TiRo` object stays that
+/// object, and a form needing no change leaves its `/DR` object unwritten. The fonts PdfCraft
+/// adds use WinAnsi, as Acrobat's do.
+#[test]
+fn existing_form_fonts_are_kept_and_an_unchanged_resource_dictionary_is_not_rewritten() {
+ let mut doc = document(&[
+ "<< /Type /Catalog /Pages 2 0 R /AcroForm 4 0 R >>".into(),
+ "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 600 800] >>".into(),
+ "<< /Type /Page /Parent 2 0 R >>".into(),
+ "<< /Fields [] /DA (/Helv 0 Tf 0 g) /DR << /Font << /Helv << /Type /Font /Subtype /Type1 /BaseFont /Arial >> /TiRo 5 0 R >> >> >>".into(),
+ "<< /Type /Font /Subtype /Type1 /BaseFont /Times-Bold >>".into(),
+ ]);
+ add_field(&mut doc, 0, [40.0, 600.0, 300.0, 630.0], &NewField::Text { multiline: false }, Some("name")).unwrap();
+ let doc = reopen(&doc);
+ let fonts = dr_fonts(&doc);
+ let font = |name: &str| doc.get(fonts.reference(name.as_bytes()).unwrap()).as_dict().cloned().unwrap();
+ assert_eq!(font("Helv").name(b"BaseFont"), Some(&b"Arial"[..]), "the form's own Helv");
+ assert_eq!(fonts.reference(b"TiRo"), Some(pdfcraft_cos::ObjRef::new(5, 0)), "the same object");
+ assert_eq!(font("Cour").name(b"Encoding"), Some(&b"WinAnsiEncoding"[..]));
+
+ // Every font an object already, /DR an object: adding a field leaves /DR as it was.
+ let mut doc = document(&[
+ "<< /Type /Catalog /Pages 2 0 R /AcroForm 4 0 R >>".into(),
+ "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 600 800] >>".into(),
+ "<< /Type /Page /Parent 2 0 R >>".into(),
+ "<< /Fields [] /DA (/Helv 0 Tf 0 g) /DR 5 0 R >>".into(),
+ "<< /Font << /Helv 6 0 R /TiRo 6 0 R /Cour 6 0 R >> >>".into(),
+ "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>".into(),
+ ]);
+ add_field(&mut doc, 0, [40.0, 600.0, 300.0, 630.0], &NewField::Text { multiline: false }, Some("name")).unwrap();
+ assert!(!doc.modified_objects().contains(&5), "/DR unchanged: {:?}", doc.modified_objects());
+}
+
+/// #3441, exhaustively: every way a form's `/DR` may hold its fonts. `/DR` missing, inline or an
+/// object; its `/Font` missing, inline, an object or not a dictionary; `/Helv` missing, inline,
+/// an object, a reference to nothing, `null` or a number; and a font of the form's own, inline or
+/// an object. After a field is added, whatever the shape:
+/// - no font is a dictionary written inline;
+/// - a font that was an object is the same object, and one that was inline says the same as an
+/// object;
+/// - a `/DR` or `/Font` that was an object (and a dictionary) still is one;
+/// - an entry that is not a dictionary (`null`, a number, a reference to nothing) is left alone;
+/// - Helv, TiRo and Cour are there.
+#[test]
+fn every_shape_of_form_fonts_ends_as_objects() {
+ let font = |base: &str| format!("<< /Type /Font /Subtype /Type1 /BaseFont /{base} >>");
+ let mut cases = 0;
+ for dr_shape in ["missing", "inline", "object"] {
+ for font_shape in ["missing", "inline", "object", "number"] {
+ for helv in ["missing", "inline", "object", "dangling", "null", "number"] {
+ for mine in ["missing", "inline", "object"] {
+ if dr_shape == "missing" && (font_shape != "missing" || helv != "missing" || mine != "missing") {
+ continue;
+ }
+ if matches!(font_shape, "missing" | "number") && (helv != "missing" || mine != "missing") {
+ continue;
+ }
+ cases += 1;
+ let what = format!("/DR {dr_shape}, /Font {font_shape}, /Helv {helv}, /Mine {mine}");
+ let mut entries = String::new();
+ match helv {
+ "inline" => entries += &format!("/Helv {} ", font("Arial")),
+ "object" => entries += "/Helv 7 0 R ",
+ "dangling" => entries += "/Helv 99 0 R ",
+ "null" => entries += "/Helv null ",
+ "number" => entries += "/Helv 3 ",
+ _ => {}
+ }
+ match mine {
+ "inline" => entries += &format!("/Mine {} ", font("Symbol")),
+ "object" => entries += "/Mine 8 0 R ",
+ _ => {}
+ }
+ let fonts_value = match font_shape {
+ "inline" => format!("<< {entries}>>"),
+ "object" => "6 0 R".into(),
+ "number" => "7".into(),
+ _ => String::new(),
+ };
+ let dr_dict = if fonts_value.is_empty() { "<< >>".to_string() } else { format!("<< /Font {fonts_value} >>") };
+ let dr_value = match dr_shape {
+ "inline" => dr_dict.clone(),
+ "object" => "5 0 R".into(),
+ _ => String::new(),
+ };
+ let af = if dr_value.is_empty() { "<< /Fields [] >>".to_string() } else { format!("<< /Fields [] /DR {dr_value} >>") };
+ let mut doc = document(&[
+ "<< /Type /Catalog /Pages 2 0 R /AcroForm 4 0 R >>".into(),
+ "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 600 800] >>".into(),
+ "<< /Type /Page /Parent 2 0 R >>".into(),
+ af,
+ if dr_shape == "object" { dr_dict } else { "null".into() },
+ if font_shape == "object" { format!("<< {entries}>>") } else { "null".into() },
+ font("Helvetica-Oblique"),
+ font("ZapfDingbats"),
+ ]);
+ add_field(&mut doc, 0, [40.0, 600.0, 300.0, 630.0], &NewField::Text { multiline: false }, Some("name"))
+ .unwrap_or_else(|e| panic!("{what}: {e}"));
+ let doc = reopen(&doc);
+ let af = acroform(&doc).unwrap();
+ let dr = doc.resolve(af.get(b"DR").unwrap_or_else(|| panic!("{what}: no /DR")));
+ let fonts = dr_fonts(&doc);
+ for (name, value) in fonts.iter() {
+ assert!(value.as_dict().is_none(), "{what}: {} is inline", String::from_utf8_lossy(name));
+ }
+ for name in ["Helv", "TiRo", "Cour"] {
+ assert!(fonts.contains(name.as_bytes()), "{what}: no {name}");
+ }
+ let base =
+ |name: &[u8]| fonts.reference(name).and_then(|r| doc.get(r).as_dict().and_then(|f| f.name(b"BaseFont").map(<[u8]>::to_vec)));
+ match helv {
+ "inline" => assert_eq!(base(b"Helv").as_deref(), Some(&b"Arial"[..]), "{what}"),
+ "object" => assert_eq!(fonts.reference(b"Helv"), Some(pdfcraft_cos::ObjRef::new(7, 0)), "{what}"),
+ "dangling" => assert_eq!(fonts.reference(b"Helv"), Some(pdfcraft_cos::ObjRef::new(99, 0)), "{what}"),
+ "null" => assert_eq!(fonts.get(b"Helv"), Some(&Object::Null), "{what}"),
+ "number" => assert_eq!(fonts.get(b"Helv"), Some(&Object::Int(3)), "{what}"),
+ _ => assert_eq!(base(b"Helv").as_deref(), Some(&b"Helvetica"[..]), "{what}"),
+ }
+ match mine {
+ "inline" => assert_eq!(base(b"Mine").as_deref(), Some(&b"Symbol"[..]), "{what}"),
+ "object" => assert_eq!(fonts.reference(b"Mine"), Some(pdfcraft_cos::ObjRef::new(8, 0)), "{what}"),
+ _ => assert!(!fonts.contains(b"Mine"), "{what}"),
+ }
+ if dr_shape == "object" {
+ assert_eq!(af.reference(b"DR"), Some(pdfcraft_cos::ObjRef::new(5, 0)), "{what}: /DR stays its object");
+ }
+ if font_shape == "object" {
+ assert_eq!(dr.as_dict().unwrap().reference(b"Font"), Some(pdfcraft_cos::ObjRef::new(6, 0)), "{what}: /Font stays its object");
+ }
+ }
+ }
+ }
+ }
+ assert_eq!(cases, 1 + 2 * (2 + 2 * 6 * 3), "every shape was tried");
+}
+
+/// #3441 (review follow-up): filling a field converts the form's inline `/DR` fonts, so a form
+/// an earlier PdfCraft made works in Acrobat once it has been filled here. Nothing is added. A
+/// form a signature covers keeps `/DR` as the signer saw it, and a form whose fonts are objects
+/// already leaves its `/DR` object unwritten.
+#[test]
+fn filling_a_field_makes_inline_form_fonts_objects_unless_the_form_is_signed() {
+ let inline = "/Helv << /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>";
+ let form = |signed: bool, dr: &str| {
+ let sig = if signed { "<< /Type /Annot /Subtype /Widget /FT /Sig /T (sig) /V 7 0 R /Rect [0 0 0 0] /P 3 0 R >>" } else { "null" };
+ let fields = if signed { "[5 0 R 6 0 R]" } else { "[5 0 R]" };
+ document(&[
+ "<< /Type /Catalog /Pages 2 0 R /AcroForm 4 0 R >>".into(),
+ "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 600 800] >>".into(),
+ "<< /Type /Page /Parent 2 0 R /Annots [5 0 R] >>".into(),
+ format!("<< /Fields {fields} /DA (/Helv 0 Tf 0 g) /DR {dr} >>"),
+ "<< /Type /Annot /Subtype /Widget /FT /Tx /T (name) /DA (/Helv 12 Tf 0 g) /Rect [50 700 300 720] /P 3 0 R >>".into(),
+ sig.into(),
+ "<< /Type /Sig /Filter /Adobe.PPKLite /Contents <00> >>".into(),
+ "<< /Font << /Helv 9 0 R >> >>".into(),
+ "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>".into(),
+ ])
+ };
+ let mut doc = form(false, &format!("<< /Font << {inline} >> >>"));
+ set_value(&mut doc, "name", &FieldValue::Text("Ada".into())).unwrap();
+ let doc = reopen(&doc);
+ let fonts = dr_fonts(&doc);
+ assert!(fonts.reference(b"Helv").is_some(), "Helv became an object: {fonts:?}");
+ assert_eq!(fonts.len(), 1, "nothing added: {fonts:?}");
+ assert_eq!(field(&fields(&doc), "name").value, ["Ada"]);
+
+ let mut doc = form(true, &format!("<< /Font << {inline} >> >>"));
+ set_value(&mut doc, "name", &FieldValue::Text("Ada".into())).unwrap();
+ let doc = reopen(&doc);
+ assert!(dr_fonts(&doc).get(b"Helv").is_some_and(|h| h.as_dict().is_some()), "a signed form keeps /DR as it was");
+
+ // An empty signature field signs nothing: the form is converted as an unsigned one.
+ let mut doc = form(true, &format!("<< /Font << {inline} >> >>"));
+ doc.update_dict(pdfcraft_cos::ObjRef::new(6, 0), |d| {
+ d.remove(b"V");
+ })
+ .unwrap();
+ set_value(&mut doc, "name", &FieldValue::Text("Ada".into())).unwrap();
+ assert!(dr_fonts(&reopen(&doc)).reference(b"Helv").is_some(), "an unsigned signature field doesn't hold /DR back");
+
+ let mut doc = form(false, "8 0 R");
+ set_value(&mut doc, "name", &FieldValue::Text("Ada".into())).unwrap();
+ assert!(!doc.modified_objects().contains(&8), "/DR unchanged: {:?}", doc.modified_objects());
+}
+
+/// #3441 (review follow-up): a signature value held by a parent field signs its kid too (`/V` is
+/// inheritable, ISO 32000-2 Table 226), so the form still counts as signed and keeps its `/DR`.
+#[test]
+fn a_signature_value_on_a_parent_field_keeps_the_form_fonts_as_signed() {
+ let mut doc = document(&[
+ "<< /Type /Catalog /Pages 2 0 R /AcroForm 4 0 R >>".into(),
+ "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 600 800] >>".into(),
+ "<< /Type /Page /Parent 2 0 R /Annots [5 0 R 8 0 R] >>".into(),
+ "<< /Fields [5 0 R 6 0 R] /DA (/Helv 0 Tf 0 g) /DR << /Font << /Helv << /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >> >> >> >>".into(),
+ "<< /Type /Annot /Subtype /Widget /FT /Tx /T (name) /DA (/Helv 12 Tf 0 g) /Rect [50 700 300 720] /P 3 0 R >>".into(),
+ "<< /FT /Sig /T (sig) /V 7 0 R /Kids [8 0 R] >>".into(),
+ "<< /Type /Sig /Filter /Adobe.PPKLite /Contents <00> >>".into(),
+ "<< /Type /Annot /Subtype /Widget /T (s1) /Parent 6 0 R /Rect [0 0 0 0] /P 3 0 R >>".into(),
+ ]);
+ let kid = pdfcraft_cos::ObjRef::new(8, 0);
+ assert!(fields(&doc).iter().any(|f| f.obj == kid && f.kind == FieldKind::Signature), "the kid is the signature field");
+ set_value(&mut doc, "name", &FieldValue::Text("Ada".into())).unwrap();
+ let doc = reopen(&doc);
+ assert!(dr_fonts(&doc).get(b"Helv").is_some_and(|h| h.as_dict().is_some()), "an inherited signature value keeps /DR as it was");
+ assert_eq!(field(&fields(&doc), "name").value, ["Ada"]);
+}
+
+/// #3441 (review follow-up): a catalog that holds `/AcroForm` as a direct dictionary gets its
+/// inline `/DR` fonts converted too when a field is filled.
+#[test]
+fn filling_a_field_converts_inline_fonts_of_a_direct_form_dictionary() {
+ let mut doc = document(&[
+ "<< /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [4 0 R] /DA (/Helv 0 Tf 0 g) /DR << /Font << /Helv << /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >> >> >> >> >>".into(),
+ "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 600 800] >>".into(),
+ "<< /Type /Page /Parent 2 0 R /Annots [4 0 R] >>".into(),
+ "<< /Type /Annot /Subtype /Widget /FT /Tx /T (name) /DA (/Helv 12 Tf 0 g) /Rect [50 700 300 720] /P 3 0 R >>".into(),
+ ]);
+ set_value(&mut doc, "name", &FieldValue::Text("Ada".into())).unwrap();
+ let doc = reopen(&doc);
+ let fonts = dr_fonts(&doc);
+ assert!(fonts.reference(b"Helv").is_some(), "Helv became an object: {fonts:?}");
+ assert_eq!(fonts.len(), 1, "nothing added: {fonts:?}");
+ assert_eq!(field(&fields(&doc), "name").value, ["Ada"]);
+}
+
+/// #3926 / #3943 review: a password value can be inherited from an ancestor field or sit on a
+/// separate widget. Clearing removes both; an ancestor's value shared with a non-password field
+/// stays for that field, and the password field gets an empty value of its own instead.
+#[test]
+fn inherited_and_widget_password_values_are_cleared() {
+ let objs: Vec<String> = vec![
+ "<< /Type /Catalog /Pages 2 0 R /AcroForm 4 0 R >>".into(), // 1
+ "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 600 800] >>".into(), // 2
+ "<< /Type /Page /Parent 2 0 R /Annots [6 0 R 7 0 R 9 0 R 11 0 R] >>".into(), // 3
+ "<< /Fields [5 0 R 8 0 R 10 0 R] /DA (/Helv 0 Tf 0 g) >>".into(), // 4
+ "<< /T (acct) /FT /Tx /Ff 8192 /V (secret1) /Kids [6 0 R] >>".into(), // 5 flag and value inherited
+ "<< /Type /Annot /Subtype /Widget /T (pin) /Parent 5 0 R /Rect [50 700 150 720] /P 3 0 R >>".into(), // 6
+ "<< /Type /Annot /Subtype /Widget /Parent 8 0 R /V (secret3) /Rect [50 650 150 670] /P 3 0 R >>".into(), // 7 value on the widget
+ "<< /FT /Tx /T (code) /Ff 8192 /Kids [7 0 R] >>".into(), // 8
+ "<< /Type /Annot /Subtype /Widget /FT /Tx /T (pw) /Ff 8192 /Parent 10 0 R /Rect [50 600 150 620] /P 3 0 R >>".into(), // 9
+ "<< /T (grp) /V (shared2) /Kids [9 0 R 11 0 R] >>".into(), // 10 shared with a plain field
+ "<< /Type /Annot /Subtype /Widget /FT /Tx /T (plain) /Parent 10 0 R /Rect [50 550 150 570] /P 3 0 R >>".into(), // 11
+ ];
+ let mut doc = document(&objs);
+ assert!(has_password_values(&doc));
+ let value = |doc: &Document, n: &str| fields(doc).into_iter().find(|f| f.name == n).map(|f| f.value).unwrap_or_default();
+ assert_eq!(value(&doc, "acct.pin"), ["secret1"], "inherited before");
+ assert_eq!(clear_password_values(&mut doc).unwrap(), 3);
+ assert!(!has_password_values(&doc));
+ for n in ["acct.pin", "code", "grp.pw"] {
+ assert!(value(&doc, n).iter().all(|v| v.is_empty()), "{n} cleared");
+ }
+ assert_eq!(value(&doc, "grp.plain"), ["shared2"], "the shared value stays for the plain field");
+ let has_v = |doc: &Document, n: u32| doc.get(pdfcraft_cos::ObjRef { num: n, generation: 0 }).as_dict().is_some_and(|d| d.get(b"V").is_some());
+ assert!(!has_v(&doc, 5), "an ancestor only password fields inherit from loses its value");
+ assert!(!has_v(&doc, 7), "a widget's value is removed");
+ assert!(has_v(&doc, 10), "a shared ancestor keeps its value");
+}
+
+/// #3943 review: a cleared password field saves as Acrobat saves it (black-box test). One with a
+/// default value gets it back, and its appearance shows as many masking characters as the
+/// default has, not as the typed password had; one without is left empty and draws none. The
+/// default value and the scripts stay, and a field already at its default needs no clearing.
+#[test]
+fn a_cleared_password_field_returns_to_its_default_value() {
+ let objs: Vec<String> = vec![
+ "<< /Type /Catalog /Pages 2 0 R /AcroForm 4 0 R >>".into(), // 1
+ "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 600 800] >>".into(), // 2
+ "<< /Type /Page /Parent 2 0 R /Annots [6 0 R 7 0 R 8 0 R] >>".into(), // 3
+ "<< /Fields [6 0 R 7 0 R 8 0 R] /DA (/Helv 12 Tf 0 g) /DR << /Font << /Helv 5 0 R >> >> >>".into(), // 4
+ "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>".into(), // 5
+ "<< /Type /Annot /Subtype /Widget /FT /Tx /T (pw) /Ff 8192 /DV (DEF-1) /V (NEWPASS-77777) /AA << /K << /S /JavaScript /JS (1;) >> >> /Rect [50 700 250 720] /P 3 0 R >>".into(), // 6
+ "<< /Type /Annot /Subtype /Widget /FT /Tx /T (pw3) /Ff 8192 /V (PW3-TYPED-9) /Rect [50 650 250 670] /P 3 0 R >>".into(), // 7
+ "<< /Type /Annot /Subtype /Widget /FT /Tx /T (blank) /Ff 8192 /V [()] /Rect [50 600 250 620] /P 3 0 R >>".into(), // 8 holds nothing (an empty string in an array)
+ ];
+ let mut doc = document(&objs);
+ assert_eq!(clear_password_values(&mut doc).unwrap(), 2);
+ let all = fields(&doc);
+ let (pw, pw3) = (field(&all, "pw"), field(&all, "pw3"));
+ assert_eq!(pw.value, ["DEF-1"], "back to its default");
+ assert_eq!(pw.default, ["DEF-1"], "the default stays");
+ assert!(pw.actions.scripts.keystroke.is_some(), "the scripts stay");
+ assert!(pw3.value.iter().all(|v| v.is_empty()), "no default: empty");
+ let shown = ap(&doc, &pw.widgets[0]);
+ assert!(shown.contains("(*****)") && !shown.contains("NEWPASS") && !shown.contains("******"), "{shown}");
+ let shown3 = ap(&doc, &pw3.widgets[0]);
+ assert!(!shown3.contains('*') && !shown3.contains("PW3"), "{shown3}");
+ assert!(!has_password_values(&doc), "a field at its default holds no typed password");
+ assert_eq!(clear_password_values(&mut doc).unwrap(), 0);
+}
+
+/// #3943 review: the quick check that skips forms without a Password field still sees one whose
+/// widget is only on the page, not listed in `/Fields`; one that inherits the flag from a parent
+/// that is not listed either; and one deeper in the field tree whose widget is on no page. Each
+/// is alone in its own document, so each path of the check is needed.
+#[test]
+fn a_password_field_missing_from_the_field_list_is_still_cleared() {
+ let form = |fields: &str, annots: &str, rest: &[&str]| {
+ let mut objs: Vec<String> = vec![
+ "<< /Type /Catalog /Pages 2 0 R /AcroForm 4 0 R >>".into(),
+ "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 600 800] >>".into(),
+ format!("<< /Type /Page /Parent 2 0 R /Annots [{annots}] >>"),
+ format!("<< /Fields [{fields}] /DA (/Helv 0 Tf 0 g) >>"),
+ ];
+ objs.extend(rest.iter().map(|o| o.to_string()));
+ document(&objs)
+ };
+ let page_only =
+ form("", "5 0 R", &["<< /Type /Annot /Subtype /Widget /FT /Tx /T (pin) /Ff 8192 /V (secret5) /Rect [50 700 150 720] /P 3 0 R >>"]);
+ let inherited = form(
+ "",
+ "5 0 R",
+ &[
+ "<< /Type /Annot /Subtype /Widget /T (kid) /Parent 6 0 R /Rect [50 650 150 670] /P 3 0 R >>",
+ "<< /FT /Tx /T (acct) /Ff 8192 /V (secret6) /Kids [5 0 R] >>",
+ ],
+ );
+ let off_page = form(
+ "5 0 R",
+ "",
+ &[
+ "<< /T (grp) /Kids [6 0 R] >>",
+ "<< /Type /Annot /Subtype /Widget /FT /Tx /T (hidden) /Ff 8192 /V (secret7) /Parent 5 0 R /Rect [0 0 0 0] >>",
+ ],
+ );
+ for (what, mut doc) in [("page only", page_only), ("inherited", inherited), ("on no page", off_page)] {
+ assert!(has_password_values(&doc), "{what}");
+ assert_eq!(clear_password_values(&mut doc).unwrap(), 1, "{what}");
+ assert!(fields(&doc).iter().all(|f| f.value.iter().all(|v| v.is_empty())), "{what}: {:?}", fields(&doc));
+ }
+}
+
+/// A password field nested beyond depth 32 (e.g. depth 35) is recognized by `has_password_flag`
+/// and `has_password_values`, matching the field tree walk limit of 64.
+#[test]
+fn a_password_field_nested_beyond_depth_32_is_recognized() {
+ let target_depth = 35;
+ let leaf_obj_num = 5 + target_depth;
+ let mut objs: Vec<String> = vec![
+ "<< /Type /Catalog /Pages 2 0 R /AcroForm 4 0 R >>".into(),
+ "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 600 800] >>".into(),
+ "<< /Type /Page /Parent 2 0 R >>".into(),
+ "<< /Fields [5 0 R] /DA (/Helv 0 Tf 0 g) >>".into(),
+ ];
+ for d in 0..target_depth {
+ let obj_num = 5 + d;
+ let next_obj_num = obj_num + 1;
+ let parent_entry = if d == 0 { String::new() } else { format!(" /Parent {} 0 R", obj_num - 1) };
+ objs.push(format!("<< /T (node{d}) /Kids [{next_obj_num} 0 R]{parent_entry} >>"));
+ }
+ objs.push(format!(
+ "<< /Type /Annot /Subtype /Widget /FT /Tx /T (pass) /Ff 8192 /V (secret35) /Parent {} 0 R /Rect [50 600 150 620] /P 3 0 R >>",
+ leaf_obj_num - 1
+ ));
+ let mut doc = document(&objs);
+ assert!(has_password_flag(&doc));
+ assert!(has_password_values(&doc));
+ assert_eq!(clear_password_values(&mut doc).unwrap(), 1);
+ assert!(!has_password_values(&doc));
+}
+
+/// A password field whose widget is reachable through a page's Annots and whose inherited Password
+/// flag is deeper than 32 levels is recognized by `has_password_flag`.
+#[test]
+fn a_page_widget_inheriting_password_flag_beyond_depth_32_is_recognized() {
+ let target_depth = 35;
+ let leaf_obj_num = 5 + target_depth;
+ let mut objs: Vec<String> = vec![
+ "<< /Type /Catalog /Pages 2 0 R /AcroForm 4 0 R >>".into(),
+ "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 600 800] >>".into(),
+ format!("<< /Type /Page /Parent 2 0 R /Annots [{leaf_obj_num} 0 R] >>"),
+ "<< /Fields [5 0 R] /DA (/Helv 0 Tf 0 g) >>".into(),
+ ];
+ for d in 0..target_depth {
+ let obj_num = 5 + d;
+ let next_obj_num = obj_num + 1;
+ let parent_entry = if d == 0 { String::new() } else { format!(" /Parent {} 0 R", obj_num - 1) };
+ let ff_entry = if d == 0 { " /Ff 8192" } else { "" };
+ objs.push(format!("<< /T (node{d}){ff_entry} /Kids [{next_obj_num} 0 R]{parent_entry} >>"));
+ }
+ objs.push(format!(
+ "<< /Type /Annot /Subtype /Widget /FT /Tx /T (pass) /V (secret_chain) /Parent {} 0 R /Rect [50 600 150 620] /P 3 0 R >>",
+ leaf_obj_num - 1
+ ));
+ let mut doc = document(&objs);
+ assert!(has_password_flag(&doc));
+ assert!(has_password_values(&doc));
+ assert_eq!(clear_password_values(&mut doc).unwrap(), 1);
+ assert!(!has_password_values(&doc));
+}
+
+/// #4018: a value that doesn't fit its box at the field's font size is reported (it is drawn cut
+/// at the box). An auto-sized field shrinks to fit, and a short or empty value fits.
+#[test]
+fn a_value_wider_or_taller_than_its_box_is_reported() {
+ let long = "Doe, Jane (represented by John Doe)";
+ let field = |name: &str, rect: &str, extra: &str, value: &str| {
+ format!("<< /Type /Annot /Subtype /Widget /FT /Tx /T ({name}) /V ({value}) /Rect [{rect}] /P 3 0 R {extra} >>")
+ };
+ let doc = document(&[
+ "<< /Type /Catalog /Pages 2 0 R /AcroForm 4 0 R >>".into(),
+ "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 600 800] >>".into(),
+ "<< /Type /Page /Parent 2 0 R /Annots [6 0 R 7 0 R 8 0 R 9 0 R 10 0 R] >>".into(),
+ "<< /Fields [6 0 R 7 0 R 8 0 R 9 0 R 10 0 R] /DA (/Helv 12 Tf 0 g) /DR << /Font << /Helv 5 0 R >> >> >>".into(),
+ "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>".into(),
+ field("single", "50 700 190 718", "", long),
+ field("multi", "50 650 190 668", "/Ff 4096", long),
+ field("auto", "50 600 190 618", "/DA (/Helv 0 Tf 0 g)", long),
+ field("wide", "50 550 350 568", "", long),
+ field("short", "50 500 190 518", "/Ff 4096", "Ada"),
+ ]);
+ let overflow = |name: &str| {
+ let f = fields(&doc).into_iter().find(|f| f.name == name).unwrap();
+ appearance::value_overflow(&doc, &f, &f.widgets[0])
+ };
+ match overflow("single") {
+ Some(appearance::Overflow::Wide { width, room, size }) => {
+ assert_eq!(size, 12.0);
+ assert!((width - 201.4).abs() < 1.0 && room < 140.0, "{width} in {room}");
+ }
+ other => panic!("single: {other:?}"),
+ }
+ assert_eq!(overflow("multi"), Some(appearance::Overflow::Tall { lines: 2, room: 1, size: 12.0 }));
+ assert_eq!(overflow("auto"), None, "auto size shrinks to fit");
+ assert_eq!(overflow("wide"), None);
+ assert_eq!(overflow("short"), None);
+}
+
+/// #4018: a single line taller than its box is cut at the top and bottom, and a character wider
+/// than a multiline box is a line of its own that is still cut at the sides; both are reported.
+/// An empty value draws nothing, so nothing is cut however small the box.
+#[test]
+fn a_line_taller_than_its_box_or_a_character_wider_than_it_is_reported() {
+ let field = |name: &str, rect: &str, extra: &str, value: &str| {
+ format!("<< /Type /Annot /Subtype /Widget /FT /Tx /T ({name}) /V ({value}) /Rect [{rect}] /P 3 0 R {extra} >>")
+ };
+ let doc = document(&[
+ "<< /Type /Catalog /Pages 2 0 R /AcroForm 4 0 R >>".into(),
+ "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 600 800] >>".into(),
+ "<< /Type /Page /Parent 2 0 R /Annots [6 0 R 7 0 R 8 0 R 9 0 R 10 0 R 11 0 R] >>".into(),
+ "<< /Fields [6 0 R 7 0 R 8 0 R 9 0 R 10 0 R 11 0 R] /DA (/Helv 12 Tf 0 g) /DR << /Font << /Helv 5 0 R >> >> >>".into(),
+ "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>".into(),
+ field("low", "50 700 190 708", "", "Ada"),
+ field("comb", "50 650 190 658", "/Ff 16777216 /MaxLen 5", "Ada"),
+ field("narrow", "50 500 56 560", "/Ff 4096", "WW"),
+ field("roomy", "50 400 190 418", "", "Ada"),
+ field("empty", "50 350 190 358", "", ""),
+ field("empty-multi", "50 300 190 304", "/Ff 4096", ""),
+ ]);
+ let overflow = |name: &str| {
+ let f = fields(&doc).into_iter().find(|f| f.name == name).unwrap();
+ appearance::value_overflow(&doc, &f, &f.widgets[0])
+ };
+ for name in ["low", "comb"] {
+ match overflow(name) {
+ Some(o @ appearance::Overflow::High { height, room, size }) => {
+ assert_eq!(size, 12.0);
+ assert!((height - 11.1).abs() < 0.01 && room <= 8.0, "{name}: {height} in {room}");
+ assert!(o.to_string().starts_with("the value does not fit: 11.1 pt high at 12 pt"), "{o}");
+ }
+ other => panic!("{name}: {other:?}"),
+ }
+ }
+ match overflow("narrow") {
+ Some(appearance::Overflow::Wide { width, room, size }) => {
+ assert_eq!(size, 12.0);
+ assert!(width > room && (width - 11.32).abs() < 0.1, "{width} in {room}");
+ }
+ other => panic!("narrow: {other:?}"),
+ }
+ assert_eq!(overflow("roomy"), None);
+ assert_eq!(overflow("empty"), None);
+ assert_eq!(overflow("empty-multi"), None);
+}
+
+/// Check boxes, radio buttons and push buttons whose file gives them no appearance, a comb field,
+/// a combo box and a list box, for the display copy.
+fn left_buttons() -> Document {
+ let widget = |n: &str, rest: &str| format!("<< /Type /Annot /Subtype /Widget /T ({n}) /F 4 /P 3 0 R {rest} >>");
+ document(&[
+ "<< /Type /Catalog /Pages 2 0 R /AcroForm 4 0 R >>".into(),
+ "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 600 800] >>".into(),
+ "<< /Type /Page /Parent 2 0 R /Annots [6 0 R 7 0 R 8 0 R 9 0 R 10 0 R 11 0 R 12 0 R 13 0 R 14 0 R 15 0 R 16 0 R 17 0 R 18 0 R] >>".into(),
+ "<< /Fields [6 0 R 7 0 R 8 0 R 9 0 R 10 0 R 11 0 R 12 0 R 13 0 R 14 0 R 15 0 R 16 0 R 17 0 R 18 0 R] /DA (/Helv 0 Tf 0 g) /DR << /Font << /Helv 5 0 R >> >> >>".into(),
+ "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>".into(),
+ widget("i", "/FT /Btn /V /Yes /AS /Yes /DA (/ZaDb 0 Tf 0 g) /MK << /CA (4) /BC [0 0 0] >> /Rect [50 700 74 724]"), // 6
+ widget("j", "/FT /Btn /V /Yes /AS /Yes /DA (/ZaDb 0 Tf 0 0 1 rg) /MK << /CA (l) /BC [0 0 0] >> /Rect [100 700 124 724]"),
+ widget("k", "/FT /Btn /V /Yes /AS /Yes /DA (/ZaDb 0 Tf 1 0 0 rg) /MK << /CA (8) /BC [0 0 0] >> /Rect [150 700 174 724]"),
+ widget("l", "/FT /Btn /V /Yes /AS /Yes /DA (/ZaDb 9 Tf 0 g) /MK << /CA (H) /BC [0 0 0] /BG [1 1 0] >> /Rect [200 700 224 724]"),
+ widget("off", "/FT /Btn /V /Off /AS /Off /DA (/ZaDb 0 Tf 0 g) /MK << /CA (4) /BC [0 0 0] >> /Rect [250 700 274 724]"), // 10
+ widget("radio", "/FT /Btn /Ff 32768 /V /A /AS /A /DA (/ZaDb 0 Tf 0 g) /MK << /BC [0 0 0] >> /Rect [300 700 324 724]"),
+ widget(
+ "o",
+ "/FT /Btn /Ff 65536 /DA (/Helv 12 Tf 0 g) /MK << /CA (Press me) /BG [0.8 0.8 0.8] /BC [0 0 0] >> /BS << /W 2 /S /B >> /Rect [50 600 170 624]",
+ ),
+ widget("own", "/FT /Btn /V /Yes /AS /Yes /MK << /CA (4) /BC [0 0 0] >> /Rect [350 700 374 724] /AP << /N << /Yes 19 0 R /Off 19 0 R >> >>"),
+ widget("half", "/FT /Btn /V /Yes /AS /Yes /DA (/ZaDb 0 Tf 0 g) /MK << /CA (8) >> /Rect [400 700 424 724] /AP << /N << /Off 19 0 R >> >>"),
+ widget("bad", "/FT /Btn /V /Yes /AS /Yes /DA (/ZaDb nan Tf 1 x rg) /MK << /CA 42 /BC [(no) /Name] /BG 7 >> /BS << /W -3 >> /Rect [450 700 474 724]"), // 15
+ widget("d", "/FT /Tx /Ff 16777216 /MaxLen 6 /V (ABC123) /DA (/Helv 12 Tf 0 g) /MK << /BC [0 0 1] >> /Rect [50 500 170 524]"),
+ widget("m", "/FT /Ch /Ff 131072 /Opt [(Apple) (Banana)] /V (Banana) /Q 2 /DA (/Helv 12 Tf 0 g) /MK << /BC [0 0 0] >> /Rect [50 400 170 424]"),
+ widget("n", "/FT /Ch /Opt [(One) (Two)] /V (Two) /DA (/Helv 11 Tf 0 g) /MK << /BC [0 0 0] >> /Rect [200 400 320 460]"),
+ "<< /Length 4 >>\nstream\nq\nQ\nendstream".into(), // 19
+ ])
+}
+
+/// The appearance stream of widget `w` in `state` (a check box's `/AP /N /<state>`).
+fn state_ap(doc: &Document, w: &Widget, state: &str) -> String {
+ let wd = doc.get(w.obj).as_dict().cloned().unwrap();
+ let ap = doc.resolve(wd.get(b"AP").unwrap()).as_dict().cloned().unwrap();
+ let n = doc.resolve(ap.get(b"N").unwrap()).as_dict().cloned().unwrap();
+ let r = n.reference(state.as_bytes()).expect("the state's appearance");
+ let Object::Stream(s) = &*doc.get(r) else { panic!("a stream") };
+ String::from_utf8_lossy(&s.decoded().unwrap()).into_owned()
+}
+
+/// The decoded appearance PdfCraft would save for text or choice field `name` of `doc`.
+fn saved_look(doc: &Document, name: &str) -> String {
+ let all = fields(doc);
+ let f = field(&all, name);
+ String::from_utf8_lossy(&appearance::field_appearance(doc, f, &f.widgets[0], &f.value).decoded().unwrap()).into_owned()
+}
+
+/// ISO 32000-2 Table 192 and 12.7.5.2.3: a check box with no appearance shows its `/MK /BC`
+/// border and, when on, its caption `/MK /CA` as a ZapfDingbats character in the `/DA` colour,
+/// sized to the box when the `/DA` size is 0.
+#[test]
+fn check_boxes_without_an_appearance_show_their_caption_symbol() {
+ let doc = left_buttons();
+ let copy = with_field_appearances(&doc).expect("buttons to draw");
+ let all = fields(&copy);
+ for (name, symbol, colour) in [("i", "(4) Tj", "0 g"), ("j", "(l) Tj", "0 0 1 rg"), ("k", "(8) Tj", "1 0 0 rg"), ("l", "(H) Tj", "0 g")] {
+ let shown = state_ap(&copy, &field(&all, name).widgets[0], "Yes");
+ assert!(shown.contains(symbol), "{name}: {shown}");
+ assert!(shown.contains(&format!("{colour}\n")), "{name} in its colour: {shown}");
+ assert!(shown.contains("0 0 0 RG\n1 w\n0.5 0.5 23 23 re S"), "{name} has its border: {shown}");
+ }
+ // A /DA size is kept; the automatic one fills the box inside the border.
+ let l = state_ap(&copy, &field(&all, "l").widgets[0], "Yes");
+ assert!(l.contains("/ZaDb 9 Tf") && l.contains("1 1 0 rg\n0 0 24 24 re f"), "{l}");
+ let i = state_ap(&copy, &field(&all, "i").widgets[0], "Yes");
+ let size: f64 = i.split("/ZaDb ").nth(1).and_then(|s| s.split(' ').next()).and_then(|s| s.parse().ok()).unwrap();
+ assert!((18.0..=26.0).contains(&size), "{size}");
+ let w = copy.get(field(&all, "i").widgets[0].obj);
+ let ap = copy.resolve(w.as_dict().unwrap().get(b"AP").unwrap());
+ let n = copy.resolve(ap.as_dict().unwrap().get(b"N").unwrap());
+ let Object::Stream(s) = &*copy.get(n.as_dict().unwrap().reference(b"Yes").unwrap()) else { panic!() };
+ let font = s.dict.get(b"Resources").and_then(|r| r.as_dict()).and_then(|r| r.get(b"Font")).and_then(|f| f.as_dict()).and_then(|f| f.get(b"ZaDb"));
+ assert_eq!(font.and_then(|f| f.as_dict()).and_then(|f| f.name(b"BaseFont")), Some(&b"ZapfDingbats"[..]), "a standard-14 font, no program");
+}
+
+/// An Off check box shows only its border, a radio button without a caption a dot (`l`), a box
+/// whose file has only an Off look gets an on look, and one with its own look keeps it.
+#[test]
+fn button_states_without_an_appearance() {
+ let doc = left_buttons();
+ let copy = with_field_appearances(&doc).expect("buttons to draw");
+ let all = fields(&copy);
+ let off = state_ap(&copy, &field(&all, "off").widgets[0], "Off");
+ assert!(off.contains("re S") && !off.contains("Tj"), "{off}");
+ assert!(state_ap(&copy, &field(&all, "radio").widgets[0], "A").contains("(l) Tj"));
+ assert!(state_ap(&copy, &field(&all, "half").widgets[0], "Yes").contains("(8) Tj"));
+ let own = |d: &Document| d.get(field(&fields(d), "own").widgets[0].obj).as_dict().and_then(|w| w.get(b"AP").cloned());
+ assert_eq!(own(&copy), own(&doc), "a check box with its own look keeps it");
+ // Nonsense in /MK, /DA and /BS: the default symbol, no border, and no panic.
+ let bad = state_ap(&copy, &field(&all, "bad").widgets[0], "Yes");
+ assert!(bad.contains("(4) Tj") && !bad.contains("re S"), "{bad}");
+ // The document itself is untouched.
+ assert!(doc.get(field(&fields(&doc), "i").widgets[0].obj).as_dict().is_some_and(|w| !w.contains(b"AP")));
+}
+
+/// Table 192 and Table 168: a push button with no appearance shows its `/MK /BG` background, its
+/// beveled `/MK /BC` border in the `/BS` width, and its caption `/MK /CA` centred.
+#[test]
+fn push_buttons_without_an_appearance_show_their_caption_and_frame() {
+ let copy = with_field_appearances(&left_buttons()).expect("buttons to draw");
+ let shown = ap(&copy, &field(&fields(&copy), "o").widgets[0]);
+ for part in ["0.8 0.8 0.8 rg\n0 0 120 24 re f", "0 0 0 RG\n2 w\n1 1 118 22 re S", "1 g\n", "0.5 g\n", "(Press me) Tj", "/Helv 12.00 Tf"] {
+ assert!(shown.contains(part), "{part}: {shown}");
+ }
+}
+
+/// ISO 32000-2 Table 228, Comb: the field is divided into MaxLen equally spaced positions, and a
+/// bordered comb field shows them: MaxLen - 1 lines in the border colour, in its saved look too.
+#[test]
+fn comb_fields_show_their_cells() {
+ let mut doc = left_buttons();
+ let shown = saved_look(&doc, "d");
+ let lines: Vec<&str> = shown.lines().filter(|l| l.ends_with(" l") && l.contains(" 1 m ")).collect();
+ assert_eq!(lines, ["20 1 m 20 23 l", "40 1 m 40 23 l", "60 1 m 60 23 l", "80 1 m 80 23 l", "100 1 m 100 23 l"], "{shown}");
+ assert!(shown.contains("0 0 1 RG\n1 w\n20 1 m"), "in the border colour: {shown}");
+ // Past the cap no lines, and a huge MaxLen is no trouble; without a border, none either.
+ let r = field(&fields(&doc), "d").widgets[0].obj;
+ doc.update_dict(r, |w| w.set(b"MaxLen".to_vec(), Object::Int(1 << 40))).unwrap();
+ let huge = saved_look(&doc, "d");
+ assert!(!huge.contains(" 1 m ") && huge.contains("(A) Tj"), "{huge}");
+ doc.update_dict(r, |w| {
+ w.set(b"MaxLen".to_vec(), Object::Int(6));
+ w.remove(b"MK");
+ })
+ .unwrap();
+ let plain = saved_look(&doc, "d");
+ assert!(!plain.contains(" m ") && plain.contains("(A) Tj"), "{plain}");
+}
diff --git a/crates/js/src/formcalc.rs b/crates/js/src/formcalc.rs
index 4ff77b7..7b0d0e8 100644
--- a/crates/js/src/formcalc.rs
+++ b/crates/js/src/formcalc.rs
@@ -123,7 +123,7 @@ fn lex(src: &str) -> Result<Vec<Token>, String> {
}
out.push(Token { tok: Tok::Str(s), line });
}
- c if c.is_ascii_digit() || (c == '.' && chars.get(i + 1).is_some_and(|d| d.is_ascii_digit())) => {
+ c if c.is_ascii_digit() || (c == '.' && chars.get(i + 1).is_some_and(char::is_ascii_digit)) => {
let start = i;
while i < chars.len() && (chars[i].is_ascii_digit() || (chars[i] == '.' && chars.get(i + 1) != Some(&'.'))) {
i += 1;
@@ -716,6 +716,8 @@ fn num_text(n: f64) -> String {
fn fixed(v: f64, decimals: usize) -> String {
let k = 10f64.powi(decimals.min(20) as i32);
let scaled = (v * k).round() / k;
+ // A small negative value rounds to -0.0, which would print as "-0".
+ let scaled = if scaled == 0.0 { 0.0 } else { scaled };
format!("{:.decimals$}", if scaled.is_finite() { scaled } else { v })
}
@@ -758,7 +760,7 @@ fn parse_num(s: &str) -> Option<f64> {
}
fn is_numeric_text(s: &str) -> bool {
- s.trim().parse::<f64>().is_ok_and(|v| v.is_finite())
+ s.trim().parse::<f64>().is_ok_and(f64::is_finite)
}
// ── the evaluator ───────────────────────────────────────────────────────────────────────────
@@ -1946,7 +1948,7 @@ fn parse_date(text: &str, picture: &str) -> Option<(i64, u32, u32)> {
}
/// Number of days in month `m` (1-12) of year `y`, leap years included.
-fn days_in(y: i64, m: u32) -> u32 {
+pub(crate) fn days_in(y: i64, m: u32) -> u32 {
// The length of the month from chrono (the first of the next month, less the first of this
// one). An invalid month keeps the old 31-day default.
// Month lengths repeat every 400 years, so the year within its cycle is enough (and always
@@ -2323,10 +2325,11 @@ impl Interp<'_> {
}
text = if frac.is_empty() { g } else { format!("{g}.{frac}") };
}
+ let nonzero = text.chars().any(|c| ('1'..='9').contains(&c));
if pic.contains('$') {
text = format!("${text}");
}
- if num < 0.0 {
+ if num < 0.0 && nonzero {
text = format!("-{text}");
}
Val::Str(text)
@@ -2520,10 +2523,10 @@ impl Interp<'_> {
let v = parse_num(&s).unwrap_or(0.0);
let unit: String = s.trim().chars().skip_while(|c| c.is_ascii_digit() || *c == '.' || *c == '-' || *c == '+').collect();
let per_in = |u: &str| match u.trim().to_ascii_lowercase().as_str() {
- "mm" => 25.4,
- "cm" => 2.54,
- "pt" => 72.0,
- "pc" => 6.0,
+ "mm" | "millimeter" | "millimeters" => 25.4,
+ "cm" | "centimeter" | "centimeters" => 2.54,
+ "pt" | "point" | "points" => 72.0,
+ "pc" | "pica" => 6.0,
_ => 1.0,
};
let target = if to.trim().is_empty() { unit.clone() } else { to };
@@ -2627,6 +2630,14 @@ pub fn run_formcalc_within(script: &str, event: &XfaEvent, doc: &XfaDoc, root: X
mod tests {
use super::*;
+ #[test]
+ fn fixed_does_not_print_negative_zero() {
+ assert_eq!(fixed(-0.4, 0), "0");
+ assert_eq!(fixed(-0.004, 2), "0.00");
+ assert_eq!(fixed(-0.0, 0), "0");
+ assert_eq!(fixed(-1.5, 0), "-2");
+ }
+
#[test]
fn dates_round_trip_through_formcalc_day_numbers() {
assert_eq!(days_from_civil(1900, 1, 1), 1);
diff --git a/crates/js/src/lib.rs b/crates/js/src/lib.rs
index 255a841..434b674 100644
--- a/crates/js/src/lib.rs
+++ b/crates/js/src/lib.rs
@@ -13,8 +13,8 @@
//! `required`, `display`, `hidden`, `numItems`, `getItemAt`, `currentValueIndices`,
//! `isBoxChecked`, `checkThisBox`, `exportValues`, `charLimit`, `textColor`, `fillColor`,
//! `setFocus`.
-//! - `app` (`alert`, `beep`, `response`, `launchURL`, `viewerType`, `viewerVersion`,
-//! `platform`, `setTimeOut`), `util` (`printf`, `printd`, `printx`), `console` (`println`,
+//! - `app` (`alert`, `beep`, `response`, `launchURL`, `execMenuItem`, `viewerType`, `viewerVersion`,
+//! `platform`, `setTimeOut`), `util` (`printf`, `printd`, `printx`, `scand`), `console` (`println`,
//! `show`, `clear`), `display` and `color`.
//!
//! The engine is a sandbox: no file, network or timer access exists, and loops and recursion
@@ -28,7 +28,7 @@ use std::collections::BTreeSet;
use std::sync::Arc;
use boa_engine::context::HostHooks;
-use boa_engine::object::builtins::{JsArray, JsFunction};
+use boa_engine::object::builtins::{JsArray, JsDate, JsFunction};
use boa_engine::object::{FunctionObjectBuilder, ObjectInitializer};
use boa_engine::property::Attribute;
use boa_engine::realm::Realm;
@@ -144,6 +144,8 @@ pub struct DocInfo {
pub page: usize,
/// Document information (`this.info.title` etc.): lower-case key, value.
pub info: Vec<(String, String)>,
+ /// The document has an XFA form, so scripts see `xfa_installed`.
+ pub xfa: bool,
}
/// Something a script asked the viewer to do.
@@ -162,6 +164,36 @@ pub enum Request {
Beep,
/// `app.execMenuItem("SaveAs")` (XFA forms' Save buttons).
SaveAs,
+ /// `app.execMenuItem("ShowHide…")`: show the side panel, or hide it when it is showing.
+ ShowPanel(Panel),
+}
+
+/// A side panel a script can show or hide (`app.execMenuItem("ShowHideFileAttachment")`, …).
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum Panel {
+ /// The document's bookmarks (outline).
+ Bookmarks,
+ /// Page thumbnails.
+ Pages,
+ /// The files attached to the document.
+ Attachments,
+ /// The document's signatures and their validity.
+ Signatures,
+ /// The document's layers (optional content).
+ Layers,
+}
+
+impl Panel {
+ /// The panel's name in automation output, fixed whatever the variant is called.
+ pub fn id(self) -> &'static str {
+ match self {
+ Panel::Bookmarks => "bookmarks",
+ Panel::Pages => "pages",
+ Panel::Attachments => "attachments",
+ Panel::Signatures => "signatures",
+ Panel::Layers => "layers",
+ }
+ }
}
/// What running a script did.
@@ -179,6 +211,9 @@ pub struct Outcome {
pub requests: Vec<Request>,
/// The script's error (syntax error, exception, or a limit reached), if it failed.
pub error: Option<String>,
+ /// Errors in the document-level scripts that ran first. Each is a script of its own: one
+ /// that throws stops where it failed, and the others and the script itself still run (#3940).
+ pub doc_errors: Vec<String>,
/// The script's completion value (what the console prints), unless undefined.
pub result: Option<String>,
}
@@ -624,6 +659,8 @@ fn message(v: &JsValue, key: &str, ctx: &mut Context) -> JsResult<String> {
}
}
+/// `app.alert(cMsg)`: records the message, given as a string or as an object with `cMsg`, and
+/// returns 1 (the OK button).
fn alert(_: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> {
let m = message(&arg(args, 0), "cMsg", ctx)?;
host(ctx)?.borrow_mut().alert(m);
@@ -631,17 +668,49 @@ fn alert(_: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValue>
Ok(JsValue::from(1))
}
+/// `app.beep()`: queues a request to beep.
fn beep(_: &JsValue, _: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> {
host(ctx)?.borrow_mut().request(Request::Beep);
Ok(JsValue::undefined())
}
+/// `app.launchURL(cURL)`: queues a request to open the URL, given as a string or as an object
+/// with `cURL`.
fn launch_url(_: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> {
let u = message(&arg(args, 0), "cURL", ctx)?;
host(ctx)?.borrow_mut().request(Request::LaunchUrl(u));
Ok(JsValue::undefined())
}
+/// What `app.execMenuItem(name)` asks for, for the menu items forms use: the side panels, Print
+/// and Save As. Other items do nothing.
+pub(crate) fn menu_item(name: &str) -> Option<Request> {
+ Some(match name {
+ "ShowHideFileAttachment" => Request::ShowPanel(Panel::Attachments),
+ "ShowHideBookmarks" => Request::ShowPanel(Panel::Bookmarks),
+ "ShowHideThumbnails" => Request::ShowPanel(Panel::Pages),
+ "ShowHideSignatures" => Request::ShowPanel(Panel::Signatures),
+ "ShowHideOptCont" => Request::ShowPanel(Panel::Layers),
+ "Print" => Request::Print,
+ // Save opens Save As too, as it always has for XFA forms' buttons: a click on a form
+ // never overwrites the file unasked.
+ "SaveAs" | "Save" => Request::SaveAs,
+ _ => return None,
+ })
+}
+
+/// `app.execMenuItem(name)`: queues the request [`menu_item`] gives for the name (Save opens
+/// Save As too); an unknown name does nothing.
+fn exec_menu_item(_: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> {
+ let item = text(&arg(args, 0), ctx)?;
+ if let Some(r) = menu_item(&item) {
+ host(ctx)?.borrow_mut().request(r);
+ }
+ Ok(JsValue::undefined())
+}
+
+/// `app.response(…)`: always `null`, the answer for a canceled dialog, since no one is there to
+/// type one.
fn response(_: &JsValue, _: &[JsValue], _: &mut Context) -> JsResult<JsValue> {
// No one to answer: as if the dialog was cancelled.
Ok(JsValue::null())
@@ -883,6 +952,324 @@ fn printd(_: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValue>
Ok(s(&out))
}
+/// A field of a `util.scand` format.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+enum DateUnit {
+ /// `yyyy`: four digits.
+ Year,
+ /// `yy`: two digits, read as 1950–2049.
+ ShortYear,
+ Month,
+ /// `mmm`, `mmmm`: a month's name or its three-letter abbreviation.
+ MonthName,
+ Day,
+ /// `ddd`, `dddd`: a weekday's name, read and not checked.
+ Weekday,
+ Hour,
+ /// `h`, `hh`: 0–12, with `tt` for the afternoon.
+ Hour12,
+ Minute,
+ Second,
+ /// `t`, `tt`: am or pm.
+ AmPm,
+}
+
+impl DateUnit {
+ /// A year, month or day: a format needs one of these for `util.scand` to read anything.
+ fn is_date(self) -> bool {
+ matches!(self, Self::Year | Self::ShortYear | Self::Month | Self::MonthName | Self::Day)
+ }
+
+ /// Read from a run of digits, not from letters.
+ fn is_numeric(self) -> bool {
+ !matches!(self, Self::MonthName | Self::Weekday | Self::AmPm)
+ }
+}
+
+/// A piece of a `util.scand` format.
+#[derive(Debug, PartialEq, Eq)]
+enum ScanPart {
+ /// A field, the digits it takes when typed together with the next one (`width`), and whether
+ /// the next one follows it with nothing between them in the format (`joined`).
+ Field { unit: DateUnit, width: usize, joined: bool },
+ /// Letters the format writes as they are, which the text must have there.
+ Word(String),
+}
+
+/// The fields and literal words of a `util.scand` format, in order. A numeric field is marked
+/// `joined` when another numeric field follows it directly; anything but letters and digits
+/// outside a field is left out.
+fn scan_parts(fmt: &str) -> Vec<ScanPart> {
+ let chars: Vec<char> = fmt.chars().collect();
+ let mut parts: Vec<ScanPart> = Vec::new();
+ // The last part is a field written right before this point, or letters still being collected.
+ let (mut after_field, mut in_word) = (false, false);
+ let mut i = 0;
+ while let Some(&c) = chars.get(i) {
+ // Counted for field letters only, so a long run of anything else is read once.
+ let run = if "ymdHhMst".contains(c) { chars.get(i..).unwrap_or_default().iter().take_while(|x| **x == c).count() } else { 1 };
+ let field = match (c, run) {
+ ('y', 4..) => Some((DateUnit::Year, 4)),
+ ('y', _) => Some((DateUnit::ShortYear, 2)),
+ ('m', 3..) => Some((DateUnit::MonthName, 0)),
+ ('m', n) => Some((DateUnit::Month, n)),
+ ('d', 3..) => Some((DateUnit::Weekday, 0)),
+ ('d', n) => Some((DateUnit::Day, n)),
+ ('H', n) => Some((DateUnit::Hour, n.min(2))),
+ ('h', n) => Some((DateUnit::Hour12, n.min(2))),
+ ('M', n) => Some((DateUnit::Minute, n.min(2))),
+ ('s', n) => Some((DateUnit::Second, n.min(2))),
+ ('t', _) => Some((DateUnit::AmPm, 0)),
+ _ => None,
+ };
+ if let Some((unit, width)) = field {
+ if after_field
+ && unit.is_numeric()
+ && let Some(ScanPart::Field { unit: last, joined, .. }) = parts.last_mut()
+ && last.is_numeric()
+ {
+ *joined = true;
+ }
+ parts.push(ScanPart::Field { unit, width, joined: false });
+ (after_field, in_word) = (true, false);
+ i += run;
+ continue;
+ }
+ // `\` writes the next character as it is.
+ let (literal, step) = if c == '\\' { (chars.get(i + 1).copied(), 2) } else { (Some(c), 1) };
+ i += step;
+ after_field = false;
+ match literal {
+ Some(l) if l.is_alphanumeric() => match parts.last_mut() {
+ Some(ScanPart::Word(w)) if in_word => w.push(l),
+ _ => {
+ parts.push(ScanPart::Word(l.to_string()));
+ in_word = true;
+ }
+ },
+ _ => in_word = false,
+ }
+ }
+ parts
+}
+
+/// A run of digits or of letters in the text `util.scand` reads.
+enum ScanToken<'a> {
+ Digits(&'a str),
+ Letters(&'a str),
+}
+
+/// The text's runs of digits and of letters, in order; anything else only separates them, and
+/// may not begin or end the text. `None` when it does.
+fn scan_tokens(text: &str) -> Option<Vec<ScanToken<'_>>> {
+ // Some(true) for a digit, Some(false) for a letter, None for a separator.
+ let kind = |c: char| (c.is_ascii_digit() || c.is_alphabetic()).then_some(c.is_ascii_digit());
+ kind(text.chars().next()?)?;
+ kind(text.chars().next_back()?)?;
+ let mut out = Vec::new();
+ let mut start: Option<(usize, bool)> = None;
+ for (at, c) in text.char_indices().chain(std::iter::once((text.len(), ' '))) {
+ let k = kind(c);
+ if let Some((from, digits)) = start
+ && k != Some(digits)
+ {
+ let piece = text.get(from..at)?;
+ out.push(if digits { ScanToken::Digits(piece) } else { ScanToken::Letters(piece) });
+ start = None;
+ }
+ if let Some(digits) = k
+ && start.is_none()
+ {
+ start = Some((at, digits));
+ }
+ }
+ Some(out)
+}
+
+/// What `util.scand` reads.
+#[derive(Debug, PartialEq, Eq)]
+enum Scanned {
+ /// The text is empty: today, at noon.
+ Today,
+ /// A date and time: year, month (1–12), day, hours, minutes, seconds.
+ At(i32, u32, u32, u32, u32, u32),
+}
+
+/// The fields `util.scand` has read so far.
+#[derive(Default)]
+struct ScanValues {
+ y: Option<i32>,
+ mo: Option<u32>,
+ d: Option<u32>,
+ h: Option<u32>,
+ mi: Option<u32>,
+ sec: Option<u32>,
+ pm: Option<bool>,
+ /// The hour was read from `h` or `hh`.
+ twelve: bool,
+}
+
+impl ScanValues {
+ /// Records `v` as the value of `unit`: a `yy` year as 1950–2049, and an `h` or `hh` hour
+ /// marked as 12-hour. Month names, weekdays and am/pm are not read here.
+ fn set(&mut self, unit: DateUnit, v: u32) {
+ match unit {
+ DateUnit::Year => self.y = i32::try_from(v).ok(),
+ DateUnit::ShortYear => self.y = i32::try_from(v).ok().map(|v| if v < 50 { 2000 + v } else { 1900 + v }),
+ DateUnit::Month => self.mo = Some(v),
+ DateUnit::Day => self.d = Some(v),
+ DateUnit::Hour => self.h = Some(v),
+ DateUnit::Hour12 => {
+ self.h = Some(v);
+ self.twelve = true;
+ }
+ DateUnit::Minute => self.mi = Some(v),
+ DateUnit::Second => self.sec = Some(v),
+ DateUnit::MonthName | DateUnit::Weekday | DateUnit::AmPm => {}
+ }
+ }
+}
+
+/// Reads `text` by a `util.scand` format, as another viewer was observed to (black-box):
+///
+/// - Fields may be separated by anything but digits and letters, whether or not the format
+/// separates them, but nothing may come before the first or after the last.
+/// - Digits typed together fill the format's fields written together with exactly as many
+/// digits as each has letters (`yyyymd`: 4, 1 and 1). A run of digits for one field alone may
+/// have one or two, except a four-digit year.
+/// - `yy` is 1950–2049; month names may be written in full or as three letters, in any case.
+/// - Impossible dates are refused, but a month or day of 0 is read as 1.
+/// - A format with no year, month or day reads nothing; an empty text is today, at noon.
+///
+/// Not observed: a year left out is `this_year`, and a month or day left out is 1.
+fn scan_date(fmt: &str, text: &str, this_year: i32) -> Option<Scanned> {
+ let parts = scan_parts(fmt);
+ if !parts.iter().any(|p| matches!(p, ScanPart::Field { unit, .. } if unit.is_date())) {
+ return None;
+ }
+ if text.is_empty() {
+ return Some(Scanned::Today);
+ }
+ let tokens = scan_tokens(text)?;
+ let mut v = ScanValues::default();
+ let (mut p, mut t) = (0, 0);
+ while let Some(part) = parts.get(p) {
+ let token = tokens.get(t)?;
+ t += 1;
+ match (part, token) {
+ (ScanPart::Word(w), ScanToken::Letters(l) | ScanToken::Digits(l)) => {
+ if w.to_lowercase() != l.to_lowercase() {
+ return None;
+ }
+ p += 1;
+ }
+ (ScanPart::Field { unit: DateUnit::MonthName, .. }, ScanToken::Letters(l)) => {
+ v.mo = Some(named(&MONTHS, l)?.saturating_add(1));
+ p += 1;
+ }
+ (ScanPart::Field { unit: DateUnit::Weekday, .. }, ScanToken::Letters(l)) => {
+ named(&DAYS, l)?;
+ p += 1;
+ }
+ (ScanPart::Field { unit: DateUnit::AmPm, .. }, ScanToken::Letters(l)) => {
+ v.pm = Some(match l.to_lowercase().as_str() {
+ "am" | "a" => false,
+ "pm" | "p" => true,
+ _ => return None,
+ });
+ p += 1;
+ }
+ (ScanPart::Field { unit, width, joined }, ScanToken::Digits(run)) if unit.is_numeric() => {
+ // The fields written together from here, no more than the run's digits can fill,
+ // and the fewest of them the run fills.
+ let mut group = vec![(*unit, *width)];
+ let (mut more, mut widths) = (*joined, *width);
+ while more
+ && widths < run.len()
+ && let Some(ScanPart::Field { unit, width, joined }) = parts.get(p + group.len())
+ {
+ group.push((*unit, *width));
+ widths = widths.saturating_add(*width);
+ more = *joined;
+ }
+ let mut sum = 0;
+ let fills = group.iter().position(|(_, w)| {
+ sum += w;
+ sum == run.len()
+ });
+ if let Some(last) = fills {
+ let mut at = 0;
+ for (unit, w) in group.iter().take(last + 1) {
+ v.set(*unit, run.get(at..at + w)?.parse().ok()?);
+ at += w;
+ }
+ p += last + 1;
+ } else if *unit != DateUnit::Year && run.len() <= 2 {
+ v.set(*unit, run.parse().ok()?);
+ p += 1;
+ } else {
+ return None;
+ }
+ }
+ _ => return None,
+ }
+ }
+ if t != tokens.len() {
+ return None;
+ }
+ let y = v.y.unwrap_or(this_year);
+ let mo = v.mo.unwrap_or(1).max(1);
+ let d = v.d.unwrap_or(1).max(1);
+ if mo > 12 || i64::from(d) > i64::from(formcalc::days_in(i64::from(y), mo)) {
+ return None;
+ }
+ let mut h = v.h.unwrap_or(0);
+ if v.twelve && h > 12 {
+ return None;
+ }
+ match v.pm {
+ Some(true) if h < 12 => h += 12,
+ Some(false) if h == 12 => h = 0,
+ _ => {}
+ }
+ let (mi, sec) = (v.mi.unwrap_or(0), v.sec.unwrap_or(0));
+ (h <= 23 && mi <= 59 && sec <= 59).then_some(Scanned::At(y, mo, d, h, mi, sec))
+}
+
+/// The index of the name `word` is, in full or as its first three letters, in any case.
+fn named(names: &[&str], word: &str) -> Option<u32> {
+ let word = word.to_lowercase();
+ let i = names.iter().position(|n| {
+ let n = n.to_lowercase();
+ word == n || n.get(..3) == Some(word.as_str())
+ })?;
+ u32::try_from(i).ok()
+}
+
+/// `util.scand(cFormat, cDate)`: the date `cDate` gives by a `util.printd` format, as a local
+/// `Date`, or `null` when it doesn't read as one (see [`scan_date`]). Only text is read.
+fn scand(_: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> {
+ let Some(typed) = arg(args, 1).as_string().map(|t| t.to_std_string_escaped()) else {
+ return Ok(JsValue::null());
+ };
+ let fmt = text(&arg(args, 0), ctx)?;
+ let date = JsDate::new(ctx);
+ let this_year = date.get_full_year(ctx)?.to_number(ctx)?;
+ let this_year = if this_year.is_finite() { this_year as i32 } else { 2000 };
+ match scan_date(&fmt, &typed, this_year) {
+ None => return Ok(JsValue::null()),
+ Some(Scanned::Today) => {
+ date.set_hours(&[12.into(), 0.into(), 0.into(), 0.into()], ctx)?;
+ }
+ Some(Scanned::At(y, mo, d, h, mi, sec)) => {
+ // setFullYear, not the constructor, so years 0–99 stay as they are.
+ date.set_full_year(&[y.into(), (mo.saturating_sub(1)).into(), d.into()], ctx)?;
+ date.set_hours(&[h.into(), mi.into(), sec.into(), 0.into()], ctx)?;
+ }
+ }
+ Ok(date.into())
+}
+
/// `util.printx(cFormat, cSource)`: `?` any character, `X` letter or digit, `A` letter, `9`
/// digit, `*` the rest, `\` escape, `>` / `<` / `=` upper / lower / as is.
fn printx(_: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> {
@@ -948,6 +1335,8 @@ fn printx(_: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValue>
Ok(s(&out))
}
+/// The `color` object: each named color (`transparent`, `black`, `red`, `cyan`, `gray`, …) as
+/// an array of its color space (`T`, `G`, `RGB` or `CMYK`) followed by its components.
fn color_object(ctx: &mut Context) -> JsObject {
let mut entries: Vec<(&str, Vec<JsValue>)> = vec![
("transparent", vec![s("T")]),
@@ -971,6 +1360,13 @@ fn color_object(ctx: &mut Context) -> JsObject {
o.build()
}
+/// The XFA version scripts see as `xfa_version`.
+const XFA_VERSION: f64 = 3.5;
+
+/// Defines the form object model's globals: the document's functions (`getField`, `resetForm`,
+/// `print`, `submitForm` and others) and properties (`numFields`, `pageNum`, `numPages`,
+/// `documentFileName`, `info`, the XFA version), and the `app`, `util`, `console`, `display` and
+/// `color` objects.
fn install(ctx: &mut Context) -> JsResult<()> {
let globals: [(&str, usize, NativeFunction); 9] = [
("getField", 1, NativeFunction::from_fn_ptr(get_field)),
@@ -991,9 +1387,9 @@ fn install(ctx: &mut Context) -> JsResult<()> {
let nf = function(ctx, NativeFunction::from_fn_ptr(num_fields));
let pg = function(ctx, NativeFunction::from_fn_ptr(page_num_get));
let ps = function(ctx, NativeFunction::from_fn_ptr(page_num_set));
- let (file, pages, info) = {
+ let (file, pages, info, xfa) = {
let h = host(ctx)?.borrow();
- (h.doc.file_name.clone(), h.doc.num_pages, h.doc.info.clone())
+ (h.doc.file_name.clone(), h.doc.num_pages, h.doc.info.clone(), h.doc.xfa)
};
let mut io = ObjectInitializer::new(ctx);
for (k, v) in &info {
@@ -1006,12 +1402,19 @@ fn install(ctx: &mut Context) -> JsResult<()> {
ctx.register_global_property(js_string!("numPages"), JsValue::from(pages as f64), rw)?;
ctx.register_global_property(js_string!("documentFileName"), s(&file), rw)?;
ctx.register_global_property(js_string!("info"), info, rw)?;
+ // XFA forms check both before they run: every document sees the XFA version, and only an
+ // XFA form sees `xfa_installed`.
+ ctx.register_global_property(js_string!("xfa_version"), JsValue::from(XFA_VERSION), rw)?;
+ if xfa {
+ ctx.register_global_property(js_string!("xfa_installed"), JsValue::from(true), rw)?;
+ }
let app = ObjectInitializer::new(ctx)
.function(NativeFunction::from_fn_ptr(alert), js_string!("alert"), 1)
.function(NativeFunction::from_fn_ptr(beep), js_string!("beep"), 0)
.function(NativeFunction::from_fn_ptr(response), js_string!("response"), 1)
.function(NativeFunction::from_fn_ptr(launch_url), js_string!("launchURL"), 2)
+ .function(NativeFunction::from_fn_ptr(exec_menu_item), js_string!("execMenuItem"), 1)
.function(NativeFunction::from_fn_ptr(timer), js_string!("setTimeOut"), 2)
.function(NativeFunction::from_fn_ptr(timer), js_string!("setInterval"), 2)
.function(NativeFunction::from_fn_ptr(noop), js_string!("clearTimeOut"), 1)
@@ -1028,6 +1431,7 @@ fn install(ctx: &mut Context) -> JsResult<()> {
.function(NativeFunction::from_fn_ptr(printf), js_string!("printf"), 1)
.function(NativeFunction::from_fn_ptr(printd), js_string!("printd"), 2)
.function(NativeFunction::from_fn_ptr(printx), js_string!("printx"), 2)
+ .function(NativeFunction::from_fn_ptr(scand), js_string!("scand"), 2)
.build();
ctx.register_global_property(js_string!("util"), util, rw)?;
let console = ObjectInitializer::new(ctx)
@@ -1191,16 +1595,31 @@ pub fn run(script: &str, event: &Event, doc: &DocInfo, fields: &[FieldState], do
/// script can observe uncommitted writes. Read-only calculations avoid copying the whole form.
pub fn run_shared(script: &str, event: &Event, doc: &DocInfo, fields: Arc<Vec<FieldState>>, doc_scripts: &[String], limits: Limits) -> Outcome {
let failed = |why: String| Outcome { rc: true, value: event.value.clone(), change: event.change.clone(), error: Some(why), ..Default::default() };
- if let Some(why) = std::iter::once(script).chain(doc_scripts.iter().map(String::as_str)).find_map(refuse) {
+ if let Some(why) = refuse(script) {
return failed(why);
}
+ // A document script too long or too deeply nested to run safely is skipped and reported,
+ // as one that throws is; the others and the script still run (#3940).
+ let mut skipped = Vec::new();
+ let kept: Vec<(usize, &str)> = doc_scripts
+ .iter()
+ .enumerate()
+ .filter_map(|(i, d)| match refuse(d) {
+ Some(why) => {
+ skipped.push((i, why));
+ None
+ }
+ None => Some((i, d.as_str())),
+ })
+ .collect();
+ let (kept, skipped) = (&kept, &skipped);
#[cfg(not(target_arch = "wasm32"))]
{
std::thread::scope(|scope| {
let spawned = std::thread::Builder::new()
.name("pdfcraft-js".into())
.stack_size(SCRIPT_STACK)
- .spawn_scoped(scope, || run_here(script, event, doc, fields, doc_scripts, limits));
+ .spawn_scoped(scope, || run_here(script, event, doc, fields, kept, skipped, limits));
match spawned {
Ok(thread) => thread.join().unwrap_or_else(|panic| {
// what went wrong, for the console: a panic's message is a &str or a String
@@ -1212,7 +1631,7 @@ pub fn run_shared(script: &str, event: &Event, doc: &DocInfo, fields: Arc<Vec<Fi
})
}
#[cfg(target_arch = "wasm32")]
- run_here(script, event, doc, fields, doc_scripts, limits)
+ run_here(script, event, doc, fields, kept, skipped, limits)
}
/// Host hooks that refuse to compile code from strings (`eval`, `Function` and its generator
@@ -1247,7 +1666,22 @@ impl HostHooks for CheckedCodeFromStrings {
}
}
-fn run_here(script: &str, event: &Event, doc: &DocInfo, fields: Arc<Vec<FieldState>>, doc_scripts: &[String], limits: Limits) -> Outcome {
+/// How [`Outcome::doc_errors`] names a failing document script: by its 1-based place.
+fn doc_error(index: usize, error: &dyn std::fmt::Display) -> String {
+ format!("document script {}: {error}", index.saturating_add(1))
+}
+
+/// `doc_scripts` are the document scripts to run with their places among all of them;
+/// `skipped` the ones refused before running, with the reason.
+fn run_here(
+ script: &str,
+ event: &Event,
+ doc: &DocInfo,
+ fields: Arc<Vec<FieldState>>,
+ doc_scripts: &[(usize, &str)],
+ skipped: &[(usize, String)],
+ limits: Limits,
+) -> Outcome {
let mut ctx = match Context::builder().host_hooks(std::rc::Rc::new(NoCodeFromStrings)).build() {
Ok(ctx) => ctx,
Err(e) => {
@@ -1268,12 +1702,18 @@ fn run_here(script: &str, event: &Event, doc: &DocInfo, fields: Arc<Vec<FieldSta
dropped: 0,
}));
let mut out = Outcome { rc: true, value: event.value.clone(), change: event.change.clone(), ..Default::default() };
+ let mut doc_errors: Vec<(usize, String)> = skipped.iter().map(|(i, why)| (*i, doc_error(*i, why))).collect();
let result = (|| -> JsResult<()> {
install(&mut ctx)?;
let ev = event_object(&mut ctx, event);
ctx.register_global_property(js_string!("event"), ev.clone(), Attribute::all())?;
- for d in doc_scripts {
- ctx.eval(Source::from_bytes(d))?;
+ // One document script that throws (calling a method PdfCraft lacks, say) must not keep
+ // every field script in the form from running: what it defined before the error, and
+ // the other scripts, stay available (#3940).
+ for &(i, d) in doc_scripts {
+ if let Err(e) = ctx.eval(Source::from_bytes(d)) {
+ doc_errors.push((i, doc_error(i, &e)));
+ }
}
let r = ctx.eval(Source::from_bytes(script))?;
if !r.is_undefined() {
@@ -1290,6 +1730,8 @@ fn run_here(script: &str, event: &Event, doc: &DocInfo, fields: Arc<Vec<FieldSta
if let Err(e) = result {
out.error = Some(e.to_string());
}
+ doc_errors.sort_by_key(|(i, _)| *i);
+ out.doc_errors = doc_errors.into_iter().map(|(_, e)| e).collect();
if let Some(h) = ctx.remove_data::<Shared>() {
let h = h.into_inner();
out.changed = h.changed.iter().map(|i| h.fields[*i].clone()).collect();
diff --git a/crates/js/src/tests.rs b/crates/js/src/tests.rs
index 01a4362..3d3c4ab 100644
--- a/crates/js/src/tests.rs
+++ b/crates/js/src/tests.rs
@@ -16,7 +16,7 @@ fn fields() -> Vec<FieldState> {
}
fn doc() -> DocInfo {
- DocInfo { file_name: "order.pdf".into(), num_pages: 3, page: 0, info: vec![("title".into(), "Order".into())] }
+ DocInfo { file_name: "order.pdf".into(), num_pages: 3, page: 0, info: vec![("title".into(), "Order".into())], xfa: false }
}
fn go(script: &str, event: &Event) -> Outcome {
@@ -254,6 +254,13 @@ fn kept_bytes(o: &Outcome) -> usize {
o.console.iter().chain(&o.alerts).map(String::len).sum::<usize>() + o.requests.iter().map(req).sum::<usize>()
}
+#[test]
+fn exec_menu_item_requests_are_capped_like_other_requests() {
+ let o = go("for (var i = 0; i < 12000; i++) app.execMenuItem('Print');", &Event::field("Mouse Up", "agree", ""));
+ assert_eq!(o.error, None);
+ assert_eq!(o.requests.len(), crate::xfa::MAX_EFFECTS);
+}
+
#[test]
fn console_alerts_and_requests_are_capped_in_count_and_bytes() {
let o = go(
@@ -297,6 +304,61 @@ fn document_level_functions_are_available() {
assert_eq!(o.value, "8");
}
+/// #3940: a document script that throws after defining a helper (here calling an Acrobat method
+/// PdfCraft lacks) still leaves the helper, and the later scripts, to the field script.
+#[test]
+fn a_failing_document_script_does_not_stop_the_field_script() {
+ let docs = [
+ "function double(x) { return x * 2; }\nthis.getField('qty').buttonSetIcon(null);\nvar after = 1;".to_string(),
+ "function plus(x) { return x + 1; }".to_string(),
+ "this is not javascript".to_string(),
+ ];
+ let o = run(
+ "event.value = plus(double(getField('qty').value));",
+ &Event::field("Calculate", "total", ""),
+ &doc(),
+ &fields(),
+ &docs,
+ Limits::default(),
+ );
+ assert_eq!((o.error.as_deref(), o.value.as_str()), (None, "9"));
+ assert_eq!(o.doc_errors.len(), 2, "{:?}", o.doc_errors);
+ assert!(o.doc_errors[0].starts_with("document script 1: TypeError"), "{:?}", o.doc_errors);
+ assert!(o.doc_errors[1].starts_with("document script 3: SyntaxError"), "{:?}", o.doc_errors);
+ // The failing script stopped where it failed.
+ let o = run("event.value = typeof after;", &Event::field("Calculate", "total", ""), &doc(), &fields(), &docs, Limits::default());
+ assert_eq!(o.value, "undefined");
+ // Working document scripts report nothing.
+ assert!(go("event.value = 1;", &Event::field("Calculate", "total", "")).doc_errors.is_empty());
+}
+
+/// A document script refused before running (too long, or nested too deeply to run safely) is
+/// skipped like one that throws: never run, reported in its place, the rest still run.
+#[test]
+fn a_document_script_too_big_to_run_is_skipped_and_reported() {
+ let docs = [
+ "this.getField('qty').buttonSetIcon(null);".to_string(),
+ format!("var big = 1{};", "+1".repeat(MAX_SCRIPT_BYTES / 2)),
+ "function double(x) { return x * 2; }".to_string(),
+ format!("var deep = {}1{};", "(".repeat(10_000), ")".repeat(10_000)),
+ ];
+ let o = run(
+ "event.value = double(getField('qty').value) + typeof big;",
+ &Event::field("Calculate", "total", ""),
+ &doc(),
+ &fields(),
+ &docs,
+ Limits::default(),
+ );
+ assert_eq!((o.error.as_deref(), o.value.as_str()), (None, "8undefined"));
+ let places: Vec<&str> = o.doc_errors.iter().map(|e| e.split(':').next().unwrap_or_default()).collect();
+ assert_eq!(places, ["document script 1", "document script 2", "document script 4"], "{:?}", o.doc_errors);
+ assert!(o.doc_errors[1].contains("too long") && o.doc_errors[2].contains("nested too deeply"), "{:?}", o.doc_errors);
+ // The field script's own limits still refuse it outright.
+ let o = run(&format!("1{}", "+1".repeat(MAX_SCRIPT_BYTES)), &Event::field("Calculate", "total", ""), &doc(), &fields(), &docs, Limits::default());
+ assert!(o.error.is_some_and(|e| e.contains("too long")) && o.doc_errors.is_empty());
+}
+
#[test]
fn errors_and_runaway_scripts_are_contained() {
let o = go("event.value = nosuch.thing;", &Event::field("Calculate", "total", "keep"));
@@ -336,9 +398,11 @@ fn deeply_nested_scripts_fail_instead_of_crashing() {
let o = go(s, &Event::doc("Open"));
assert!(o.error.is_some(), "{}…", &s[..20]);
}
- // A hostile document-level script is refused too, before the field script runs.
+ // A hostile document-level script is refused too: it never runs, and is reported, while
+ // the field script still does (#3940).
let o = run("event.value = 'ran';", &Event::field("Calculate", "a", ""), &doc(), &fields(), &[hostile[0].clone()], Limits::default());
- assert!(o.error.is_some());
+ assert_eq!((o.error, o.value.as_str()), (None, "ran"));
+ assert!(o.doc_errors.len() == 1 && o.doc_errors[0].contains("nested too deeply"), "{:?}", o.doc_errors);
}
#[test]
@@ -805,6 +869,14 @@ mod formcalc {
o.result.unwrap_or_default()
}
+ /// A negative value that rounds to zero under the picture prints without a minus sign.
+ #[test]
+ fn format_does_not_print_negative_zero() {
+ assert_eq!(calc(r#"Format("9.9", -0.04)"#), "0.0");
+ assert_eq!(calc(r#"Format("99", -0.2)"#), "00");
+ assert_eq!(calc(r#"Format("9.9", -1.5)"#), "-1.5");
+ }
+
/// Assigning one long value to many fields at once stops at the run's byte budget and is
/// charged per copy, and a reset list names each field once.
#[test]
@@ -990,6 +1062,9 @@ mod formcalc {
assert_eq!(calc("Round(PV(100, 0.01, 12), 2)"), "1125.51");
assert_eq!(calc(r#"UnitValue("2in", "mm")"#), "50.8");
assert_eq!(calc(r#"UnitType("2.5cm")"#), "cm");
+ assert_eq!(calc(r#"UnitValue("72points", "in")"#), "1");
+ assert_eq!(calc(r#"UnitValue("25.4millimeters", "inches")"#), "1");
+ assert_eq!(calc(r#"UnitValue("1in", "points")"#), "72");
assert_eq!(calc(r#"Encode("a b&c", "url")"#), "a%20b%26c");
assert_eq!(calc(r#"Decode("a%20b", "url")"#), "a b");
assert!(go(r#"Get("http://example.com")"#, "form1[0].page1[0].total[0]", "calculate").error.unwrap().contains("network"));
@@ -1325,6 +1400,8 @@ mod session {
use crate::xfa::*;
use crate::xfa_session::{Script, XfaSession};
+ /// A JavaScript or FormCalc script for `activity` on `target`, against the test form with
+ /// default limits and a 3 s timeout.
fn script(source: &str, formcalc: bool, target: &str, activity: &str) -> Script {
Script {
source: source.into(),
@@ -1336,6 +1413,9 @@ mod session {
}
}
+ /// JavaScript and FormCalc scripts run in turn in one session, each on the form the caller
+ /// sends: nothing an earlier script changed or defined leaks into the next, a failing script
+ /// doesn't end the session, and hundreds of scripts run on its one thread.
#[test]
fn scripts_of_one_event_run_on_one_thread_each_on_the_form_the_caller_sends() {
let mut s = XfaSession::new(XfaDoc { page_count: 3, ..Default::default() });
@@ -1375,6 +1455,8 @@ mod session {
assert!(started.elapsed() < std::time::Duration::from_secs(10), "{:?}", started.elapsed());
}
+ /// A JavaScript or FormCalc script whose engine takes longer to be ready than the script's
+ /// time limit still runs and returns its result, and the session stays alive.
#[test]
fn a_scripts_time_starts_when_its_context_is_ready() {
// The engine made slow to be ready (300 ms) under a 50 ms script limit: the script is
@@ -1395,6 +1477,9 @@ mod session {
assert_eq!(s.dead(), None);
}
+ /// An endless JavaScript loop past its 200 ms limit is abandoned within 2 s and leaves the
+ /// session dead, so nothing more runs in it; an endless FormCalc loop is abandoned or
+ /// reported as running too long.
#[test]
fn a_script_past_its_time_is_abandoned_and_the_session_is_dead_after_it() {
let mut s = XfaSession::new(XfaDoc::default());
@@ -1451,3 +1536,272 @@ fn shared_field_snapshots_isolate_writes_errors_and_script_globals() {
assert_eq!(read.value, "undefined:4:false");
assert!(read.changed.is_empty());
}
+
+mod scand {
+ use super::*;
+ use crate::xfa::{XfaDoc, XfaEvent, run_xfa};
+
+ /// Runs `util.scand(format, text)` for each case and checks the date it gives, written as
+ /// `yyyy-mm-dd HH:MM:ss`, or `null`.
+ fn assert_scand(cases: &[(&str, &str, &str)]) {
+ let list: Vec<String> = cases.iter().map(|(f, t, _)| format!("['{f}', '{t}']")).collect();
+ let script = format!(
+ "event.value = [{}].map(function (c) {{ var d = util.scand(c[0], c[1]); \
+ return d === null ? 'null' : util.printd('yyyy-mm-dd HH:MM:ss', d); }}).join('|');",
+ list.join(", ")
+ );
+ let o = go(&script, &Event::field("Calculate", "total", ""));
+ assert_eq!(o.error, None);
+ let got: Vec<&str> = o.value.split('|').collect();
+ assert_eq!(got.len(), cases.len());
+ for ((f, t, want), got) in cases.iter().zip(got) {
+ assert_eq!(got, *want, "util.scand('{f}', '{t}')");
+ }
+ }
+
+ // The cases below are another viewer's answers, observed black-box with a synthetic file.
+
+ /// Any separator may come between fields, whether the format has that one, another or none,
+ /// but a text with a space or a letter before or after the date reads nothing.
+ #[test]
+ fn scand_allows_separators_between_fields_but_nothing_before_or_after_them() {
+ assert_scand(&[
+ ("yyyymmdd", "20261018", "2026-10-18 00:00:00"),
+ ("yyyymmdd", "2026-10-18", "2026-10-18 00:00:00"),
+ ("yyyymmdd", "2026 10 18", "2026-10-18 00:00:00"),
+ ("mm/dd/yyyy", "10/18/2026", "2026-10-18 00:00:00"),
+ ("mm/dd/yyyy", "10-18-2026", "2026-10-18 00:00:00"),
+ ("yyyymmdd", " 20261018 ", "null"),
+ ("yyyymmdd", "20261018x", "null"),
+ ("yyyymmdd", "x20261018", "null"),
+ ]);
+ }
+
+ /// Digits typed together fill the joined fields with exactly as many digits as each field has
+ /// letters, so a run of any other length reads nothing.
+ #[test]
+ fn scand_splits_digits_typed_together_by_the_formats_letter_counts() {
+ assert_scand(&[
+ ("yyyymmdd", "261018", "null"),
+ ("yyyymmdd", "2026118", "null"),
+ ("yyyymmdd", "202610181", "null"),
+ ("yymmdd", "20261018", "null"),
+ ("yyyymdd", "2026118", "2026-01-18 00:00:00"),
+ ("yyyymmd", "2026118", "2026-11-08 00:00:00"),
+ ("yyyymd", "2026118", "null"),
+ ("yyyymd", "202618", "2026-01-08 00:00:00"),
+ ("yyyymd", "20261018", "null"),
+ ("yymd", "2618", "2026-01-08 00:00:00"),
+ ("yymd", "261018", "null"),
+ ]);
+ }
+
+ /// A month past 12, a day past the month's end and February 29 outside a leap year are
+ /// refused, while a month or day of 0 is read as 1.
+ #[test]
+ fn scand_refuses_impossible_dates_and_reads_a_zero_month_or_day_as_1() {
+ assert_scand(&[
+ ("yyyymmdd", "20261318", "null"),
+ ("yyyymmdd", "20260230", "null"),
+ ("yyyymmdd", "20260229", "null"),
+ ("yyyymmdd", "20240229", "2024-02-29 00:00:00"),
+ ("mm/dd/yyyy", "13/45/2026", "null"),
+ ("yyyymmdd", "20260018", "2026-01-18 00:00:00"),
+ ("yyyymmdd", "20261000", "2026-10-01 00:00:00"),
+ ]);
+ }
+
+ /// A field typed by itself may have one or two digits, but a `yyyy` year needs four; `yy` reads
+ /// as 1950–2049; month names may be full or three letters in any case; weekday names are read.
+ #[test]
+ fn scand_reads_lone_fields_two_digit_years_and_month_and_weekday_names() {
+ assert_scand(&[
+ ("mm/dd/yyyy", "1/5/2026", "2026-01-05 00:00:00"),
+ ("m/d/yyyy", "1/5/2026", "2026-01-05 00:00:00"),
+ ("m/d/yyyy", "01/05/2026", "2026-01-05 00:00:00"),
+ ("m/d/yy", "1/5/26", "2026-01-05 00:00:00"),
+ ("mm/dd/yyyy", "10/18/26", "null"),
+ ("yyyy/mm/dd", "26/10/18", "null"),
+ ("yymmdd", "261018", "2026-10-18 00:00:00"),
+ ("yymmdd", "491018", "2049-10-18 00:00:00"),
+ ("yymmdd", "501018", "1950-10-18 00:00:00"),
+ ("mmm d, yyyy", "Oct 18, 2026", "2026-10-18 00:00:00"),
+ ("mmm d, yyyy", "October 18, 2026", "2026-10-18 00:00:00"),
+ ("mmm d, yyyy", "oct 18, 2026", "2026-10-18 00:00:00"),
+ ("mmmm d, yyyy", "Oct 18, 2026", "2026-10-18 00:00:00"),
+ ("mmmm d, yyyy", "October 18, 2026", "2026-10-18 00:00:00"),
+ ("dd-mmm-yyyy", "18-Oct-2026", "2026-10-18 00:00:00"),
+ ("dddd, mmmm d, yyyy", "Sunday, October 18, 2026", "2026-10-18 00:00:00"),
+ ]);
+ }
+
+ /// A time is read along with a date, but a format with only time fields reads nothing.
+ #[test]
+ fn scand_reads_a_time_only_with_a_date() {
+ assert_scand(&[
+ ("mm/dd/yyyy HH:MM:ss", "10/18/2026 21:07:05", "2026-10-18 21:07:05"),
+ ("HH:MM", "09:07", "null"),
+ ("HH:MM", "9:07", "null"),
+ ("h:MM tt", "9:07 pm", "null"),
+ ("h:MM tt", "9:07 am", "null"),
+ ("h:MM tt", "12:07 am", "null"),
+ ("h:MM tt", "9:07pm", "null"),
+ ]);
+ }
+
+ /// An empty text reads as today at noon, and a text that is not a string (a number, or none
+ /// at all) reads nothing.
+ #[test]
+ fn scand_reads_only_text_and_an_empty_text_is_today_at_noon() {
+ let o = go(
+ "var d = util.scand('yyyymmdd', ''), n = new Date(); \
+ event.value = [d.toDateString() == n.toDateString(), d.getHours(), d.getMinutes(), d.getSeconds(), \
+ util.scand('yyyymmdd', 20261018), util.scand(), util.scand('yyyymmdd')].join('|');",
+ &Event::field("Calculate", "total", ""),
+ );
+ assert_eq!(o.error, None);
+ assert_eq!(o.value, "true|12|0|0|||");
+ }
+
+ // Not observed: the choices made where the other viewer wasn't asked.
+
+ /// A year left out is this year, `h:MM tt` reads a 12-hour time and refuses hours it cannot
+ /// have, and a letter the format writes must be typed there.
+ #[test]
+ fn scand_takes_this_year_when_none_is_given_and_reads_12_hour_times_and_written_letters() {
+ assert_scand(&[
+ ("mm/dd/yyyy h:MM tt", "10/18/2026 9:07 pm", "2026-10-18 21:07:00"),
+ ("mm/dd/yyyy h:MM tt", "10/18/2026 12:07 AM", "2026-10-18 00:07:00"),
+ ("mm/dd/yyyy h:MM tt", "10/18/2026 13:07 pm", "null"),
+ ("mm/dd/yyyy HH:MM", "10/18/2026 24:00", "null"),
+ ("yyyy-mm-ddTHH:MM", "2026-10-18T21:07", "2026-10-18 21:07:00"),
+ ("yyyy-mm-ddTHH:MM", "2026-10-18X21:07", "null"),
+ ]);
+ let o = go(
+ "var d = util.scand('mm/dd', '10/18'); event.value = [d.getFullYear() == new Date().getFullYear(), d.getMonth(), d.getDate()].join('|');",
+ &Event::field("Calculate", "total", ""),
+ );
+ assert_eq!(o.error, None);
+ assert_eq!(o.value, "true|9|18");
+ }
+
+ /// A format of 50,000 literal letters and one of 100,000 fields, with texts to match, are read
+ /// in linear time. The limit is generous so a loaded runner passes (it also covers starting
+ /// the engine and building the strings); a quadratic scan of inputs this size takes minutes.
+ #[test]
+ fn scand_reads_long_formats_and_texts_in_linear_time() {
+ // Scripts can pass anything; native code isn't bounded by the loop limit.
+ let started = std::time::Instant::now();
+ let o = go(
+ "var x = new Array(50001).join('x'), md = new Array(50001).join('md'), ones = new Array(100000).join('1 ') + '1'; \
+ event.value = [util.scand(x + 'yyyy', x + '2026') !== null, util.scand('yyyy' + md, '2026 ' + ones) !== null].join('|');",
+ &Event::field("Calculate", "total", ""),
+ );
+ assert_eq!(o.error, None);
+ assert_eq!(o.value, "true|true");
+ assert!(started.elapsed() < std::time::Duration::from_secs(10), "{:?}", started.elapsed());
+ }
+
+ /// The check an XFA form runs on leaving a date field tries six formats with `util.scand` and
+ /// writes the first that reads the text back as `yyyymmdd`, or reports an invalid date.
+ #[test]
+ fn xfa_scripts_check_typed_dates_with_util_scand() {
+ // The check a form runs when a date field is left: the first of six formats that reads
+ // the typed text, written back as yyyymmdd; or an invalid date. Results as another viewer gives them.
+ let check = |typed: &str| {
+ let script = format!(
+ "var six = ['yyyymmdd', 'yymmdd', 'yyyymdd', 'yyyymmd', 'yyyymd', 'yymd'], out = 'invalid'; \
+ for (var i = 0; i < six.length; i++) {{ var d = util.scand(six[i], '{typed}'); \
+ if (d !== null) {{ out = util.printd('yyyymmdd', d); break; }} }} out"
+ );
+ let event = XfaEvent { activity: "exit".into(), target: "form1[0].page1[0].total[0]".into(), ..Default::default() };
+ run_xfa(&script, &event, &XfaDoc::default(), &super::xfa_model::form(), Limits::default())
+ };
+ for (typed, want) in [
+ ("20261018", "20261018"),
+ ("261018", "20261018"),
+ ("2026118", "20260118"),
+ ("202618", "20260108"),
+ ("2618", "20260108"),
+ ("2026-10-18", "20261018"),
+ ("20261318", "invalid"),
+ ("20260230", "invalid"),
+ ] {
+ let o = check(typed);
+ assert_eq!(o.error, None, "{typed}: {o:?}");
+ assert_eq!(o.result.as_deref(), Some(want), "{typed}");
+ }
+ }
+}
+
+mod menu_items {
+ use super::*;
+ use crate::xfa::{XfaDoc, XfaEffect, XfaEvent, run_xfa};
+
+ /// Every side panel has a fixed id in automation output.
+ #[test]
+ fn each_panel_has_a_fixed_id_for_automation() {
+ let ids = [Panel::Bookmarks, Panel::Pages, Panel::Attachments, Panel::Signatures, Panel::Layers].map(Panel::id);
+ assert_eq!(ids, ["bookmarks", "pages", "attachments", "signatures", "layers"]);
+ }
+
+ /// Each side panel item, Print and SaveAs make their request, in order; an unknown item
+ /// makes none and is not an error.
+ #[test]
+ fn exec_menu_item_shows_side_panels_prints_and_saves() {
+ let o = go(
+ "app.execMenuItem('ShowHideFileAttachment'); app.execMenuItem('ShowHideBookmarks'); app.execMenuItem('ShowHideThumbnails'); \
+ app.execMenuItem('ShowHideSignatures'); app.execMenuItem('ShowHideOptCont'); app.execMenuItem('Print'); \
+ app.execMenuItem('SaveAs'); app.execMenuItem('NoSuchItem');",
+ &Event::field("Mouse Up", "total", ""),
+ );
+ assert_eq!(o.error, None);
+ assert_eq!(
+ o.requests,
+ [
+ Request::ShowPanel(Panel::Attachments),
+ Request::ShowPanel(Panel::Bookmarks),
+ Request::ShowPanel(Panel::Pages),
+ Request::ShowPanel(Panel::Signatures),
+ Request::ShowPanel(Panel::Layers),
+ Request::Print,
+ Request::SaveAs,
+ ]
+ );
+ }
+
+ /// `app.execMenuItem` works in XFA scripts too: a click shows the attachments panel.
+ #[test]
+ fn xfa_scripts_show_the_attachments_panel() {
+ let event = XfaEvent { activity: "click".into(), target: "form1[0].page1[0].go[0]".into(), ..Default::default() };
+ let o = run_xfa("app.execMenuItem('ShowHideFileAttachment')", &event, &XfaDoc::default(), &super::xfa_model::form(), Limits::default());
+ assert_eq!(o.error, None, "{o:?}");
+ assert!(o.effects.contains(&XfaEffect::ShowPanel(Panel::Attachments)), "{:?}", o.effects);
+ }
+}
+
+/// The check XFA forms run on opening: without both globals, or with a version below 2.8, it
+/// alerts that the viewer can't show the form.
+const XFA_CHECK: &str = "if (typeof(xfa_installed) == 'undefined' || typeof(xfa_version) == 'undefined' || xfa_version < 2.8) app.alert('old viewer'); \
+ event.value = typeof xfa_installed + ' ' + typeof xfa_version + ' ' + xfa_version;";
+
+/// An XFA form sees `xfa_installed` (true) and `xfa_version` (3.5), so the check passes.
+#[test]
+fn an_xfa_form_sees_the_xfa_plugin_installed() {
+ let xfa = DocInfo { xfa: true, ..doc() };
+ let o = run(XFA_CHECK, &Event::doc("Open"), &xfa, &fields(), &[], Limits::default());
+ assert_eq!(o.error, None);
+ assert_eq!(o.value, "boolean number 3.5");
+ assert!(o.alerts.is_empty(), "{:?}", o.alerts);
+ let o = run("event.value = String(xfa_installed);", &Event::doc("Open"), &xfa, &fields(), &[], Limits::default());
+ assert_eq!(o.value, "true");
+}
+
+/// A form without XFA sees `xfa_version` but no `xfa_installed`, so the check alerts.
+#[test]
+fn a_plain_form_sees_the_xfa_version_but_not_installed() {
+ let o = go(XFA_CHECK, &Event::doc("Open"));
+ assert_eq!(o.error, None);
+ assert_eq!(o.value, "undefined number 3.5");
+ assert_eq!(o.alerts, ["old viewer"]);
+}
diff --git a/crates/js/src/xfa.rs b/crates/js/src/xfa.rs
index 8a60e8b..42b1688 100644
--- a/crates/js/src/xfa.rs
+++ b/crates/js/src/xfa.rs
@@ -15,7 +15,7 @@ use boa_engine::object::builtins::{JsArray, JsProxy};
use boa_engine::property::Attribute;
use boa_engine::{Context, JsObject, JsResult, JsString, JsValue, NativeFunction, Source, js_string};
-use crate::{Limits, arg, as_number, error, function, platform, printd, printf, printx, refuse, s, text};
+use crate::{Limits, arg, as_number, error, function, platform, printd, printf, printx, refuse, s, scand, text};
/// What kind of template object a node is.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -115,6 +115,8 @@ pub enum XfaEffect {
MessageBox(String),
/// `xfa.host.resetData()`: the named fields, or every field when empty.
ResetData(Vec<String>),
+ /// `app.execMenuItem("ShowHide…")`: show or hide a side panel.
+ ShowPanel(crate::Panel),
Print,
SaveAs,
LaunchUrl(String),
@@ -219,7 +221,7 @@ fn payload(e: &XfaEffect) -> usize {
XfaEffect::AddInstance { som } | XfaEffect::RemoveInstance { som } => som.len(),
XfaEffect::MessageBox(s) | XfaEffect::LaunchUrl(s) | XfaEffect::SetFocus(s) => s.len(),
XfaEffect::ResetData(names) => names.iter().fold(0usize, |n, s| n.saturating_add(s.len()).saturating_add(std::mem::size_of::<String>())),
- XfaEffect::Print | XfaEffect::SaveAs | XfaEffect::Beep | XfaEffect::Recalculate | XfaEffect::Relayout => 0,
+ XfaEffect::Print | XfaEffect::SaveAs | XfaEffect::Beep | XfaEffect::Recalculate | XfaEffect::Relayout | XfaEffect::ShowPanel(_) => 0,
}
}
@@ -1131,39 +1133,50 @@ fn resolver(ctx: &mut Context, from: usize, many: bool) -> JsResult<JsValue> {
// ── xfa.host, xfa.layout, xfa.event, app, console ───────────────────────────────────────────
+/// Records effect `e` on the host, as [`XHost::push`] does.
fn effect(ctx: &mut Context, e: XfaEffect) -> JsResult<()> {
host(ctx)?.borrow_mut().push(e);
Ok(())
}
+/// `xfa.host.messageBox(message)`: records the message, cut to [`MAX_LINE`] characters, and
+/// returns 1.
fn message_box(_: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> {
let m = clip(text(&arg(args, 0), ctx)?);
effect(ctx, XfaEffect::MessageBox(m))?;
Ok(JsValue::from(1.0))
}
+/// `xfa.host.resetData(names)`: asks to reset the comma-separated fields, or every field when
+/// the list is empty.
fn reset_data(_: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> {
let list = text(&arg(args, 0), ctx)?;
effect(ctx, XfaEffect::ResetData(reset_names(&list)))?;
Ok(JsValue::undefined())
}
+/// `xfa.host.print(…)`: asks to print; its arguments are ignored.
fn print(_: &JsValue, _: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> {
effect(ctx, XfaEffect::Print)?;
Ok(JsValue::undefined())
}
+/// `xfa.host.beep()`: asks to beep.
fn beep(_: &JsValue, _: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> {
effect(ctx, XfaEffect::Beep)?;
Ok(JsValue::undefined())
}
+/// `xfa.host.gotoURL(url)`: asks to open the URL.
fn goto_url(_: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> {
let u = text(&arg(args, 0), ctx)?;
effect(ctx, XfaEffect::LaunchUrl(u))?;
Ok(JsValue::undefined())
}
+/// `xfa.host.setFocus(target)`: asks to focus the node, given as a node object or as a SOM
+/// expression resolved from the current node; an expression that names no node is passed on
+/// as written.
fn set_focus(_: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> {
let target = arg(args, 0);
let som = match target.as_object() {
@@ -1182,11 +1195,14 @@ fn set_focus(_: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsVal
Ok(JsValue::undefined())
}
+/// `app.execMenuItem(name)`: the effect for the request the shared menu table gives the name
+/// (Save opens Save As too); an unknown name does nothing.
fn exec_menu_item(_: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> {
let item = text(&arg(args, 0), ctx)?;
- match item.as_str() {
- "SaveAs" | "Save" => effect(ctx, XfaEffect::SaveAs)?,
- "Print" => effect(ctx, XfaEffect::Print)?,
+ match crate::menu_item(&item) {
+ Some(crate::Request::SaveAs) => effect(ctx, XfaEffect::SaveAs)?,
+ Some(crate::Request::Print) => effect(ctx, XfaEffect::Print)?,
+ Some(crate::Request::ShowPanel(p)) => effect(ctx, XfaEffect::ShowPanel(p))?,
_ => {}
}
Ok(JsValue::undefined())
@@ -1233,6 +1249,9 @@ fn xfa_resolve(ctx: &mut Context, many: bool) -> JsResult<JsValue> {
resolver(ctx, current, many)
}
+/// Defines the globals for one script on node `current`: `xfa` (`form`, `host`, `layout`, `event`,
+/// `resolveNode` and more), `event` as the same object as `xfa.event`, `app`, `console`, `util`,
+/// and the nodes in scope by name, with `_name` for each repeatable one's instance manager.
fn install(ctx: &mut Context, event: &XfaEvent, doc: &XfaDoc, current: usize) -> JsResult<()> {
let rw = Attribute::CONFIGURABLE;
let form = node_object(ctx, 0)?;
@@ -1343,6 +1362,7 @@ fn install(ctx: &mut Context, event: &XfaEvent, doc: &XfaDoc, current: usize) ->
.function(NativeFunction::from_fn_ptr(printf), js_string!("printf"), 1)
.function(NativeFunction::from_fn_ptr(printd), js_string!("printd"), 2)
.function(NativeFunction::from_fn_ptr(printx), js_string!("printx"), 2)
+ .function(NativeFunction::from_fn_ptr(scand), js_string!("scand"), 2)
.build();
ctx.register_global_property(js_string!("util"), util, rw)?;
// Unqualified names: the current node's children, its siblings, then each ancestor's
@@ -1416,7 +1436,7 @@ fn install(ctx: &mut Context, event: &XfaEvent, doc: &XfaDoc, current: usize) ->
"DataView",
"Intl",
];
- let mut defined: Vec<String> = RESERVED.iter().map(|s| s.to_string()).collect();
+ let mut defined: Vec<String> = RESERVED.iter().map(ToString::to_string).collect();
for scope in scopes {
let kids: Vec<(usize, String, bool)> = {
let h = host(ctx)?.borrow();
diff --git a/crates/optimize/Cargo.toml b/crates/optimize/Cargo.toml
index 184ee96..456ab4c 100644
--- a/crates/optimize/Cargo.toml
+++ b/crates/optimize/Cargo.toml
@@ -12,12 +12,15 @@ workspace = true
[dependencies]
pdfcraft-cos = { workspace = true }
+pdfcraft-filters = { workspace = true }
pdfcraft-content = { workspace = true }
pdfcraft-model = { workspace = true }
pdfcraft-annot = { workspace = true }
thiserror.workspace = true
# JPEG decoding (zune-jpeg) and encoding, and bicubic resampling; already in the tree.
image = { version = "0.25", default-features = false, features = ["jpeg"] }
+# The same JPEG decoder, used directly to read samples untransformed (/ColorTransform 0).
+zune-jpeg = "0.5"
[dev-dependencies]
pdfcraft-render = { workspace = true }
diff --git a/crates/optimize/README.md b/crates/optimize/README.md
index 3d517ee..cbe37f6 100644
--- a/crates/optimize/README.md
+++ b/crates/optimize/README.md
@@ -21,19 +21,37 @@ let report = optimize_with_progress(&mut doc, &settings, &mut |stage| keep_going
side-by-side tiles, rotated strips, masks. Content arrays use the shared space boundary
policy, so trailing comments, split operands and graphics state keep their meaning after merging.
- **Images:** the effective resolution of each image is measured where pages draw it (the CTM
- through form XObjects, up to 12 deep; the smallest over all uses). If a use can't be
+ through form XObjects, up to 12 deep; the smallest over all uses).
+ Page-local `/UserUnit` scaling is included, so large-format pages are measured in physical inches.
+ If a use can't be
measured (forms nested deeper, or drawn too many times), no image is resampled. Colour and grayscale images above a
threshold are resampled with a bicubic (Catmull-Rom) filter to a target resolution and
stored as JPEG (Acrobat's quality steps) or ZIP; soft masks are resampled with their image.
An image is replaced only if the result is smaller. Left alone: CMYK and other colour spaces,
- image masks, decode arrays, more than 8 bits, JPEG 2000, JBIG2 and CCITT.
+ image masks, decode arrays, more than 8 bits, JPEG 2000, JBIG2 and CCITT. A JPEG is read with
+ its colour transform (an Adobe marker's, else `/ColorTransform`, ISO 32000-2 §7.4.8), so one
+ stored untransformed keeps its colours; one whose marker and `/ColorTransform` disagree is left
+ alone, since readers differ on which wins.
- **Discard objects:** thumbnails, alternate images, document tags, print settings.
- **Clean up:** Flate for streams with no filter; for streams with an outer ASCII85 or ASCIIHex
layer, that layer is removed when the result is smaller (the inner filters keep their encoded
- bytes). Streams with `/DecodeParms`, images and object streams are left alone.
+ bytes; streams with `/DecodeParms`, images and object streams keep their ASCII layer. LZW-compressed
+ streams, content and images alike, are decoded and stored with Flate instead (Acrobat's "In
+ streams that use LZW encoding, use Flate instead"): a predictor carries over to Flate without
+ `EarlyChange`, filters applied before the LZW one go with it and those after it keep their
+ bytes. A stream whose LZW data doesn't decode cleanly is left as it is. Not yet: inline images.
The engine runs Remove Hidden Information (`pdfcraft-redact`) for the user-data categories,
then this, then merges identical objects and writes a full, compressed save
(`pdfcraft_engine::optimizer::OptimizeJob`, which the UI runs on a worker thread with a
-progress bar). JPEG decoding and
-encoding and resampling come from the `image` crate.
+progress bar). JPEG decoding comes from `zune-jpeg` (the decoder behind `image` and the
+renderer), JPEG encoding and resampling from the `image` crate.
+
+## Target PDF version: partial compatibility
+
+The target selects the header version, clears the catalog `/Version`, controls object
+streams (disabled for PDF 1.4), and checks encryption requirements. It does **not**
+detect or convert content newer than the target: optional content, JPEG 2000 images,
+16-bit images, OpenType fonts and PDF 2.0 features can remain. A PDF 1.4 header
+therefore does not guarantee compatibility with PDF 1.4 readers or validators.
+`optimize.compatibility-level` remains partial until content compatibility is checked.
diff --git a/crates/optimize/src/fragments.rs b/crates/optimize/src/fragments.rs
index 4fa6e21..c069de2 100644
--- a/crates/optimize/src/fragments.rs
+++ b/crates/optimize/src/fragments.rs
@@ -176,7 +176,7 @@ fn merge(doc: &Document, run: &[Fragment], n: usize) -> Option<(Vec<u8>, u32, u3
}
let obj = doc.get(f.image);
let Object::Stream(s) = &*obj else { return None };
- let px = pixels(s, n)?;
+ let px = pixels(doc, s, n)?;
let px = if (f.width, f.height) == (width, r1 - r0) { px } else { resample(&px, n, f.width, f.height, width, r1 - r0)? };
out.get_mut(r0 as usize * row..r1 as usize * row)?.copy_from_slice(px.get(..(r1 - r0) as usize * row)?);
}
diff --git a/crates/optimize/src/images.rs b/crates/optimize/src/images.rs
index 8965422..b9761b8 100644
--- a/crates/optimize/src/images.rs
+++ b/crates/optimize/src/images.rs
@@ -158,15 +158,18 @@ pub fn effective_resolutions(doc: &Document, pages: &[ObjRef]) -> HashMap<ObjRef
out: HashMap::new(),
};
for p in pages {
- let Some(d) = doc.get(*p).as_dict().cloned() else { continue };
- let Some(contents) = d.get(b"Contents") else { continue };
+ let Some(dict) = doc.get(*p).as_dict().cloned() else { continue };
+ let page = pdfcraft_model::Page { obj: *p, dict };
+ let Some(contents) = page.dict.get(b"Contents") else { continue };
let res = page_resources(doc, *p).unwrap_or_default();
walk.budget = DecodeBudget::page();
let Some(data) = content_bytes(doc, contents, &mut walk.budget) else {
walk.complete = false;
continue;
};
- walk.content(&data, &res, Matrix([1.0, 0.0, 0.0, 1.0, 0.0, 0.0]));
+ // Content coordinates are in page units; image resolution is in physical inches.
+ let unit = page.user_unit(doc);
+ walk.content(&data, &res, Matrix([unit, 0.0, 0.0, unit, 0.0, 0.0]));
}
if !walk.complete {
walk.out.values_mut().for_each(|v| *v = f64::INFINITY);
@@ -255,25 +258,21 @@ fn count_decoded(_n: u64) {
DECODED_PIXELS.with(|c| c.set(c.get().saturating_add(_n)));
}
-/// 8-bit samples of an image (`n` components), decoded.
-pub(crate) fn pixels(s: &Stream, n: usize) -> Option<Vec<u8>> {
+/// 8-bit samples of an image (`n` components), decoded. `None` for a JPEG whose colour transform
+/// readers may disagree about ([`ycc_encoded`]).
+pub(crate) fn pixels(doc: &Document, s: &Stream, n: usize) -> Option<Vec<u8>> {
let (w, h) = (u32::try_from(s.dict.int(b"Width")?).ok()?, u32::try_from(s.dict.int(b"Height")?).ok()?);
if w == 0 || h == 0 || u64::from(w) * u64::from(h) > MAX_PIXELS {
return None;
}
let bytes = usize::try_from(w).ok()?.checked_mul(usize::try_from(h).ok()?)?.checked_mul(n)?;
if is_dct(s)? {
- use image::ImageDecoder as _;
- // The JPEG's own size is what gets decoded: one other than the dictionary's is refused from
- // its header, before any pixels are.
- let decoder = image::codecs::jpeg::JpegDecoder::new(std::io::Cursor::new(&s.raw[..])).ok()?;
- if decoder.dimensions() != (w, h) {
- return None;
- }
- let img = image::DynamicImage::from_decoder(decoder).ok()?;
- count_decoded(u64::from(img.width()) * u64::from(img.height()));
- // Adobe CMYK/YCCK JPEGs aren't handled (the colour space check excludes them).
- let v = if n == 1 { img.into_luma8().into_raw() } else { img.into_rgb8().into_raw() };
+ // The colour transform matters to three components only (§7.4.8). CMYK and YCCK JPEGs
+ // never get here: the colour space check excludes them. The JPEG's own size must be the
+ // dictionary's: `jpeg_samples` refuses another from its header, before any pixels.
+ let ycc = n == 3 && ycc_encoded(doc, s)?;
+ let v = jpeg_samples(&s.raw, usize::try_from(w).ok()?, usize::try_from(h).ok()?, n, ycc)?;
+ count_decoded(u64::from(w) * u64::from(h));
(v.len() == bytes).then_some(v)
} else {
let v = s.decoded().ok()?;
@@ -281,6 +280,130 @@ pub(crate) fn pixels(s: &Stream, n: usize) -> Option<Vec<u8>> {
}
}
+/// Whether the samples of a three-component JPEG are YCbCr, to be converted to RGB (ISO 32000-2
+/// §7.4.8). An Adobe APP14 marker's transform flag says so, overriding the filter's
+/// /ColorTransform; without a marker /ColorTransform does, 1 (YCbCr) by default.
+///
+/// `None`, so the image is left as it is, when readers may disagree: the marker and
+/// /ColorTransform contradict each other (PdfCraft's renderer lets /ColorTransform 0 win where
+/// the standard lets the marker win), either holds a value other than 0 or 1, or the parameters
+/// or the JPEG's segments can't be read.
+fn ycc_encoded(doc: &Document, s: &Stream) -> Option<bool> {
+ let entry = color_transform(doc, s)?;
+ match adobe_transform(&s.raw)? {
+ Some(t @ (0 | 1)) => entry.is_none_or(|c| c == i64::from(t)).then_some(t == 1),
+ Some(_) => None,
+ None => match entry {
+ None | Some(1) => Some(true),
+ Some(0) => Some(false),
+ Some(_) => None,
+ },
+ }
+}
+
+/// The /ColorTransform of a JPEG stream's filter parameters: `Some(None)` without one. `None`
+/// if it isn't an integer, or the parameters aren't a dictionary paired with the filter as
+/// §7.4 pairs them (a dictionary for a filter name, a one-element array for a one-filter array).
+fn color_transform(doc: &Document, s: &Stream) -> Option<Option<i64>> {
+ let Some(parms) = s.dict.get(b"DecodeParms") else { return Some(None) };
+ let parms = doc.resolve(parms);
+ let parms = match (s.dict.get(b"Filter"), &*parms) {
+ (Some(Object::Array(_)), Object::Array(a)) if a.len() == 1 => doc.resolve(a.first()?),
+ (Some(Object::Name(_)), _) | (_, Object::Null) => parms.clone(),
+ _ => return None,
+ };
+ match &*parms {
+ Object::Null => Some(None),
+ Object::Dict(d) => match d.get(b"ColorTransform").map(|c| doc.resolve(c)).as_deref() {
+ None => Some(None),
+ Some(Object::Int(c)) => Some(Some(*c)),
+ Some(_) => None,
+ },
+ _ => None,
+ }
+}
+
+/// Markers and fill bytes [`adobe_transform`] reads before the first scan, at most. Encoders
+/// write a few dozen segments.
+const MAX_HEADER_STEPS: usize = 4096;
+
+/// The transform flag of a JPEG's Adobe APP14 segment (0: samples stored as they are,
+/// 1: YCbCr, 2: YCCK), the last one if there are several, as decoders read them; `Some(None)`
+/// without one. `None` if the segments before the first scan can't be read, which includes a
+/// stray byte between segments and a header of more than [`MAX_HEADER_STEPS`] steps.
+///
+/// Each step reads one marker or fill byte and jumps over its segment, so the work is bounded
+/// by the step count, not by the size of the stream. That matters: Optimize asks again for every
+/// group of fragments it tries, and the same image can be drawn many times.
+fn adobe_transform(data: &[u8]) -> Option<Option<u8>> {
+ if data.get(..2)? != [0xFF, 0xD8] {
+ return None;
+ }
+ let mut flag = None;
+ let mut i = 2usize;
+ // Reading past the end returns.
+ for _ in 0..MAX_HEADER_STEPS {
+ // Decoders skip stray bytes between segments, but a stream can hold megabytes of them
+ // and each would be a step: the header counts as unreadable and the image is left as
+ // it is.
+ if *data.get(i)? != 0xFF {
+ return None;
+ }
+ let marker = *data.get(i.checked_add(1)?)?;
+ match marker {
+ // A fill byte before the marker.
+ 0xFF => i = i.checked_add(1)?,
+ // The first scan (or the end): no header segments after it.
+ 0xDA | 0xD9 => return Some(flag),
+ // Markers without a segment: TEM, RSTn, SOI.
+ 0x01 | 0xD0..=0xD8 => i = i.checked_add(2)?,
+ _ => {
+ let len = usize::from(u16::from_be_bytes([*data.get(i.checked_add(2)?)?, *data.get(i.checked_add(3)?)?]));
+ // The length counts its own two bytes: anything shorter is malformed.
+ let end = i.checked_add(2)?.checked_add(len)?;
+ let segment = data.get(i.checked_add(4)?..end)?;
+ if marker == 0xEE
+ && let Some(rest) = segment.strip_prefix(b"Adobe")
+ {
+ // Version, flags0 and flags1 (two bytes each), then the transform flag.
+ flag = Some(*rest.get(6)?);
+ }
+ i = end;
+ }
+ }
+ }
+ None
+}
+
+/// 8-bit samples of a JPEG `w` × `h` with `n` components (grey or RGB): YCbCr converted to RGB
+/// if `ycc`, otherwise the samples as stored. `None` if the JPEG doesn't match (size or number
+/// of components), is too large, or its decoder reads the samples otherwise (for example
+/// components named R, G and B, which decoders take as stored, while `ycc` says YCbCr).
+fn jpeg_samples(data: &[u8], w: usize, h: usize, n: usize, ycc: bool) -> Option<Vec<u8>> {
+ use zune_jpeg::zune_core::{bytestream::ZCursor, colorspace::ColorSpace, options::DecoderOptions};
+ if (w.checked_mul(h)? as u64) > MAX_PIXELS {
+ return None;
+ }
+ let options = DecoderOptions::default().set_strict_mode(false).set_max_width(usize::from(u16::MAX)).set_max_height(usize::from(u16::MAX));
+ let mut dec = zune_jpeg::JpegDecoder::new_with_options(ZCursor::new(data), options);
+ dec.decode_headers().ok()?;
+ if dec.dimensions()? != (w, h) || usize::from(dec.info()?.components) != n {
+ return None;
+ }
+ let out = match (n, ycc, dec.input_colorspace()?) {
+ (1, _, ColorSpace::Luma) => ColorSpace::Luma,
+ (3, true, ColorSpace::YCbCr) => ColorSpace::RGB,
+ // As stored: no conversion either way. The decoder reports an Adobe marker's 0 as CMYK
+ // until it decodes, and then reads three such components as RGB.
+ (3, false, ColorSpace::YCbCr) => ColorSpace::YCbCr,
+ (3, false, ColorSpace::RGB | ColorSpace::CMYK) => ColorSpace::RGB,
+ _ => return None,
+ };
+ dec.set_options(options.jpeg_set_out_colorspace(out));
+ let px = dec.decode().ok()?;
+ (px.len() == w.checked_mul(h)?.checked_mul(n)?).then_some(px)
+}
+
pub(crate) fn resample(px: &[u8], n: usize, w: u32, h: u32, nw: u32, nh: u32) -> Option<Vec<u8>> {
use image::imageops::{FilterType, resize};
Some(match n {
@@ -297,11 +420,17 @@ fn jpeg(px: &[u8], n: usize, w: u32, h: u32, quality: u8) -> Option<Vec<u8>> {
Some(out)
}
-/// Whether [`pixels`] reads `s` as it is drawn: a codec it decodes and no decode array that
-/// changes anything. `None` when the colour space isn't grey or RGB.
+/// Whether [`pixels`] reads `s` as it is drawn: a codec it decodes, no decode array that
+/// changes anything, and for an RGB JPEG a colour transform readers agree on. `None` when the
+/// colour space isn't grey or RGB.
pub(crate) fn decodable(doc: &Document, s: &Stream) -> Option<bool> {
let n = components(doc, s.dict.get(b"ColorSpace")?)?;
- Some(is_dct(s).is_some() && s.dict.get(b"Decode").is_none_or(|d| is_identity_decode(doc, d, n)))
+ let dct = is_dct(s);
+ Some(
+ dct.is_some()
+ && s.dict.get(b"Decode").is_none_or(|d| is_identity_decode(doc, d, n))
+ && (n != 3 || dct == Some(false) || ycc_encoded(doc, s).is_some()),
+ )
}
/// Whether `decode` is the default decode array for `n` components ([0 1] each), which changes
@@ -313,7 +442,9 @@ fn is_identity_decode(doc: &Document, decode: &Object, n: usize) -> bool {
}
/// A new image stream from 8-bit samples: the original dictionary with the new size and filter.
-/// A decode array is dropped: only images without one, or with the default one, get here.
+/// A decode array is dropped: only images without one, or with the default one, get here. So are
+/// the filter parameters: the samples are decoded, and a JPEG written here is plain YCbCr with no
+/// Adobe marker, which is what a missing /ColorTransform means.
fn image_stream(old: &Dict, px: &[u8], n: usize, w: u32, h: u32, compression: Compression, was_dct: bool) -> Option<Stream> {
let mut d = old.clone();
for k in [&b"Filter"[..], b"DecodeParms", b"Decode", b"Length", b"DL"] {
@@ -374,7 +505,7 @@ fn process(doc: &Document, s: &Stream, ppi: f64, settings: &ImageSettings, n: us
} else {
(w, h)
};
- let px = pixels(s, n)?;
+ let px = pixels(doc, s, n)?;
let px = if (nw, nh) != (w, h) { resample(&px, n, w, h, nw, nh)? } else { px };
let new = image_stream(d, &px, n, nw, nh, settings.compression, was_dct)?;
// A soft mask must keep the image's dimensions: resample it with the image (lossless).
@@ -387,7 +518,7 @@ fn process(doc: &Document, s: &Stream, ppi: f64, settings: &ImageSettings, n: us
return None;
}
let (mw, mh) = (u32::try_from(m.dict.int(b"Width")?).ok()?, u32::try_from(m.dict.int(b"Height")?).ok()?);
- let mpx = pixels(m, 1)?;
+ let mpx = pixels(doc, m, 1)?;
let mpx = resample(&mpx, 1, mw, mh, nw, nh)?;
smask = Some((mr, image_stream(&m.dict, &mpx, 1, nw, nh, Compression::Flate, false)?));
}
@@ -460,13 +591,13 @@ mod dimension_tests {
dict.set(b"Width".to_vec(), Object::Int(width));
dict.set(b"Height".to_vec(), Object::Int(height));
let stream = Stream::from_raw(dict, vec![0; 4]);
- assert!(pixels(&stream, channels).is_none(), "{width} x {height} x {channels}");
+ assert!(pixels(&Document::new_empty(), &stream, channels).is_none(), "{width} x {height} x {channels}");
}
let mut dict = Dict::new();
dict.set(b"Width".to_vec(), Object::Int(2));
dict.set(b"Height".to_vec(), Object::Int(2));
let stream = Stream::from_raw(dict, vec![1, 2, 3, 4, 5]);
- assert_eq!(pixels(&stream, 1), Some(vec![1, 2, 3, 4]));
+ assert_eq!(pixels(&Document::new_empty(), &stream, 1), Some(vec![1, 2, 3, 4]));
}
/// A JPEG larger than its dictionary says is refused from its header, before its pixels are decoded.
@@ -481,9 +612,9 @@ mod dimension_tests {
Stream::from_raw(dict, data.clone())
};
DECODED_PIXELS.with(|c| c.set(0));
- assert!(pixels(&stream(10, 10), 1).is_none());
+ assert!(pixels(&Document::new_empty(), &stream(10, 10), 1).is_none());
assert_eq!(DECODED_PIXELS.with(|c| c.get()), 0, "pixels decoded");
- assert_eq!(pixels(&stream(1000, 1000), 1).map(|p| p.len()), Some(1000 * 1000));
+ assert_eq!(pixels(&Document::new_empty(), &stream(1000, 1000), 1).map(|p| p.len()), Some(1000 * 1000));
}
}
diff --git a/crates/optimize/src/lib.rs b/crates/optimize/src/lib.rs
index c8b9b67..9f9fcdf 100644
--- a/crates/optimize/src/lib.rs
+++ b/crates/optimize/src/lib.rs
@@ -9,12 +9,13 @@
//! threshold are resampled (bicubic) to a target resolution and recompressed as JPEG or Flate.
//! A new image replaces the old one only if it is smaller. Images PdfCraft can't decode
//! faithfully (CMYK and other colour spaces, masks, decode arrays other than the default,
-//! JPEG 2000, JBIG2, CCITT, other than 8 bits) are left alone.
+//! JPEG 2000, JBIG2, CCITT, other than 8 bits, JPEGs whose Adobe marker and `/ColorTransform`
+//! disagree) are left alone.
//! - **Discard objects:** page thumbnails, alternate images, document tags (structure tree),
//! print settings.
//! - **Clean up:** drop images and forms that pages list but never draw (such as a deleted
//! image); Flate-compress streams that have no filter; remove a redundant outer ASCII85 or
-//! ASCIIHex layer from streams that have one.
+//! ASCIIHex layer from streams that have one; store LZW-compressed streams with Flate instead.
//!
//! Metadata, attachments, comments, scripts, private data, hidden layers, bookmarks and form
//! fields are discarded by `pdfcraft-redact`'s Remove Hidden Information, which the engine
@@ -30,7 +31,8 @@ mod unused;
pub use audit::{SpaceCategory, SpaceUse, audit_space};
-use pdfcraft_cos::{Document, ObjRef, Object, Stream, serialize};
+use pdfcraft_cos::{Dict, Document, MAX_PAGE_DECODED, ObjRef, Object, Stream, serialize};
+use pdfcraft_filters::{Filter, Params};
pub use images::effective_resolutions;
@@ -38,12 +40,62 @@ pub use images::effective_resolutions;
pub enum OptimizeError {
#[error("the document has no page tree")]
NoPages,
+ #[error("the document's encryption requires PDF {required} or later (chosen: PDF {chosen})")]
+ IncompatibleEncryption { required: &'static str, chosen: &'static str },
#[error(transparent)]
Cos(#[from] pdfcraft_cos::CosError),
#[error("the optimization was cancelled")]
Cancelled,
}
+/// The target header version and object-stream policy for an optimized copy.
+///
+/// Partial compatibility only: encryption requirements are checked, but content newer than
+/// the target is neither detected nor converted. A lower header does not guarantee that
+/// older readers can read the document.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+pub enum Compatibility {
+ /// Keep the document's version (upgraded to 1.5 when object streams are written).
+ #[default]
+ Retain,
+ Pdf1_4,
+ Pdf1_5,
+ Pdf1_6,
+ Pdf1_7,
+ Pdf2_0,
+}
+
+impl Compatibility {
+ pub const ALL: [Compatibility; 6] =
+ [Compatibility::Retain, Compatibility::Pdf1_4, Compatibility::Pdf1_5, Compatibility::Pdf1_6, Compatibility::Pdf1_7, Compatibility::Pdf2_0];
+
+ /// The name tools use (`"retain"`, `"1.4"`, `"1.5"`, `"1.6"`, `"1.7"`, `"2.0"`).
+ pub fn name(self) -> &'static str {
+ match self {
+ Compatibility::Retain => "retain",
+ Compatibility::Pdf1_4 => "1.4",
+ Compatibility::Pdf1_5 => "1.5",
+ Compatibility::Pdf1_6 => "1.6",
+ Compatibility::Pdf1_7 => "1.7",
+ Compatibility::Pdf2_0 => "2.0",
+ }
+ }
+
+ pub fn from_name(name: &str) -> Option<Compatibility> {
+ let trimmed = name.trim();
+ let stripped = if trimmed.get(..4).is_some_and(|p| p.eq_ignore_ascii_case("pdf ")) { &trimmed[4..] } else { trimmed };
+ Compatibility::ALL.into_iter().find(|c| c.name().eq_ignore_ascii_case(stripped))
+ }
+
+ /// The three-character `%PDF-` header version, when a target version is chosen.
+ pub fn version(self) -> Option<&'static str> {
+ match self {
+ Compatibility::Retain => None,
+ _ => Some(self.name()),
+ }
+ }
+}
+
/// Where an optimization is, reported to [`optimize_with_progress`]'s callback.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Stage {
@@ -89,6 +141,8 @@ impl ImageSettings {
#[derive(Clone, Debug, PartialEq)]
pub struct Settings {
+ /// Target PDF version (`Retain` by default).
+ pub compatibility: Compatibility,
/// Put page pictures drawn as many stacked fragments back together first ([`fragments`]).
pub merge_fragments: bool,
pub color: ImageSettings,
@@ -100,16 +154,30 @@ pub struct Settings {
/// Flate-compress streams stored without a filter, and strip a redundant outer ASCII85 or
/// ASCIIHex layer from streams that have one.
pub flate_unencoded: bool,
+ /// Clean Up: pack non-stream objects into compressed object streams with a cross-reference
+ /// stream (PDF 1.5+, §7.5.7–7.5.8). Always off when `compatibility` is [`Compatibility::Pdf1_4`].
+ pub object_streams: bool,
+ /// Clean Up: decode LZW-compressed streams and store them with Flate instead.
+ pub lzw_to_flate: bool,
/// Clean Up: remove links (and bookmark destinations) that point nowhere.
pub remove_invalid_links: bool,
/// Clean Up: remove named destinations nothing refers to.
pub remove_unreferenced_dests: bool,
}
+impl Settings {
+ /// Whether `write_full` should pack non-stream objects into compressed object streams:
+ /// enabled when `object_streams` is set and the target version is not PDF 1.4 (§7.5.7).
+ pub fn effective_object_streams(&self) -> bool {
+ self.object_streams && self.compatibility != Compatibility::Pdf1_4
+ }
+}
+
impl Default for Settings {
/// Acrobat's Reduce File Size choices.
fn default() -> Self {
Self {
+ compatibility: Compatibility::Retain,
merge_fragments: true,
color: ImageSettings::REDUCE,
gray: ImageSettings::REDUCE,
@@ -118,6 +186,8 @@ impl Default for Settings {
discard_tags: false,
discard_print_settings: false,
flate_unencoded: true,
+ object_streams: true,
+ lzw_to_flate: true,
remove_invalid_links: true,
remove_unreferenced_dests: true,
}
@@ -178,6 +248,8 @@ pub struct Report {
pub tags_removed: bool,
pub print_settings: usize,
pub streams_compressed: usize,
+ /// Streams whose LZW compression was replaced with Flate (Clean Up).
+ pub lzw_streams: usize,
/// Links removed and bookmarks whose destination was cleared (Clean Up).
pub invalid_links: usize,
pub invalid_bookmarks: usize,
@@ -186,6 +258,20 @@ pub struct Report {
pub unused_xobjects: usize,
}
+/// The minimum PDF version required by `doc`'s active security handler, when it uses features
+/// introduced after PDF 1.4 (crypt filters in 1.5, AES-128 in 1.6, AES-256 in 1.7).
+fn required_encryption_version(doc: &Document) -> Option<&'static str> {
+ let h = doc.output_handler()?;
+ let d = h.dict();
+ if d.v >= 5 || d.crypt_filters.iter().any(|(_, m)| *m == pdfcraft_cos::CryptMethod::Aes256) {
+ Some("1.7")
+ } else if d.v == 4 {
+ if d.crypt_filters.iter().any(|(_, m)| *m == pdfcraft_cos::CryptMethod::Aes128) { Some("1.6") } else { Some("1.5") }
+ } else {
+ None
+ }
+}
+
/// Optimize `doc` in place.
pub fn optimize(doc: &mut Document, settings: &Settings) -> Result<Report, OptimizeError> {
optimize_with_progress(doc, settings, &mut |_| true)
@@ -195,6 +281,13 @@ pub fn optimize(doc: &mut Document, settings: &Settings) -> Result<Report, Optim
/// during a long one). Returning `false` stops with [`OptimizeError::Cancelled`]; `doc` is then
/// partly optimized and should be dropped.
pub fn optimize_with_progress(doc: &mut Document, settings: &Settings, progress: &mut dyn FnMut(Stage) -> bool) -> Result<Report, OptimizeError> {
+ // Lexical ordering is valid for these fixed versions with single-digit components.
+ if let Some(chosen) = settings.compatibility.version()
+ && let Some(required) = required_encryption_version(doc)
+ && chosen < required
+ {
+ return Err(OptimizeError::IncompatibleEncryption { required, chosen });
+ }
let mut report = Report::default();
let pages = pdfcraft_annot::page_refs(doc).map_err(|_| OptimizeError::NoPages)?;
if settings.merge_fragments {
@@ -230,6 +323,16 @@ pub fn optimize_with_progress(doc: &mut Document, settings: &Settings, progress:
}
}
let root = doc.root();
+ if let Some(chosen) = settings.compatibility.version() {
+ doc.set_version(chosen);
+ if let Some(root) = root
+ && doc.get(root).as_dict().is_some_and(|c| c.contains(b"Version"))
+ {
+ doc.update_dict(root, |c| {
+ c.remove(b"Version");
+ })?;
+ }
+ }
if settings.discard_tags
&& let Some(root) = root
&& doc.get(root).as_dict().is_some_and(|c| c.contains(b"StructTreeRoot"))
@@ -279,6 +382,19 @@ pub fn optimize_with_progress(doc: &mut Document, settings: &Settings, progress:
if settings.remove_unreferenced_dests {
report.unreferenced_dests = links::remove_unreferenced_dests(doc)?;
}
+ // Before the unencoded-stream pass, which would otherwise take the ASCII layer off an
+ // `[/ASCII85Decode /LZWDecode]` stream first and count it twice.
+ if settings.lzw_to_flate {
+ for num in doc.object_numbers() {
+ let r = ObjRef { num, generation: doc.generation(num) };
+ let obj = doc.get(r);
+ let Object::Stream(s) = &*obj else { continue };
+ if let Some(replacement) = lzw_to_flate(s, MAX_LZW_DECODED) {
+ doc.set(r, Object::Stream(replacement));
+ report.lzw_streams += 1;
+ }
+ }
+ }
if settings.flate_unencoded {
for num in doc.object_numbers() {
let r = ObjRef { num, generation: doc.generation(num) };
@@ -305,6 +421,101 @@ pub fn optimize_with_progress(doc: &mut Document, settings: &Settings, progress:
Ok(report)
}
+/// Largest decoded LZW stream converted, as for a page's content: the data and its check are
+/// held together, so a few hundred kilobytes of hostile LZW can't ask for gigabytes.
+const MAX_LZW_DECODED: usize = MAX_PAGE_DECODED;
+
+/// `s` with its LZW compression replaced by Flate (Acrobat's "In streams that use LZW encoding,
+/// use Flate instead"). The filters up to the last LZW one are decoded, strictly and with its
+/// predictor; the result is Flate-encoded under the same predictor, without `EarlyChange`, and
+/// the filters after it keep their encoded bytes. A stream that doesn't decode cleanly, or
+/// whose filters or parameters can't be read for certain, or that decodes past `max` bytes, is
+/// left as it is.
+fn lzw_to_flate(s: &Stream, max: usize) -> Option<Stream> {
+ // An external file's data isn't in `raw`; cross-reference and object streams are rewritten
+ // on save, so converting them would change nothing in the file.
+ if s.dict.contains(b"F") || matches!(s.dict.name(b"Type"), Some(b"XRef" | b"ObjStm")) {
+ return None;
+ }
+ let names: Vec<&[u8]> = match s.dict.get(b"Filter")? {
+ Object::Name(n) => vec![n.as_slice()],
+ Object::Array(a) => a.iter().map(Object::as_name).collect::<Option<_>>()?,
+ _ => return None,
+ };
+ // `/Crypt` was applied when the object was loaded, and dropping it would change how the
+ // stream is encrypted.
+ if names.contains(&&b"Crypt"[..]) {
+ return None;
+ }
+ let lzw = names.iter().rposition(|n| matches!(*n, b"LZWDecode" | b"LZW"))?;
+ // One entry per filter, each a dictionary or null; anything else (an indirect reference, an
+ // array of the wrong length) would be read as defaults, so the data might not decode as
+ // written.
+ let parms: Vec<Option<&Dict>> = match s.dict.get(b"DecodeParms") {
+ None | Some(Object::Null) => vec![None; names.len()],
+ Some(Object::Dict(d)) if names.len() == 1 => vec![Some(d)],
+ Some(Object::Array(a)) if a.len() == names.len() => a
+ .iter()
+ .map(|p| match p {
+ Object::Dict(d) => Some(Some(d)),
+ Object::Null => Some(None),
+ _ => None,
+ })
+ .collect::<Option<_>>()?,
+ _ => return None,
+ };
+ let chain = s.filters();
+ let stages = chain.get(..=lzw)?;
+ let (_, params) = stages.last()?;
+ // The decoded stages' parameters must be direct integers: `filters` reads anything else (a
+ // reference, 12.5, a name) as the default, and the dictionary carried over would then
+ // describe the new data differently from how it was encoded.
+ let direct = |p: &Option<&Dict>| p.is_none_or(|d| d.iter().all(|(_, v)| matches!(v, Object::Int(_))));
+ if !parms.get(..=lzw)?.iter().all(direct) {
+ return None;
+ }
+ let data = pdfcraft_filters::decode(stages, &s.raw, max).ok()?;
+ let flate = Params { early_change: 1, ..params.clone() };
+ let raw = pdfcraft_filters::encode(&Filter::Flate, &flate, &data).ok()?;
+ // The predictor's encoder must give back exactly what its decoder read (a short last row,
+ // unusual parameters), or the stream would change. The limit counts a PNG predictor's tag
+ // bytes too, at most one per row of at least one byte.
+ if pdfcraft_filters::decode(&[(Filter::Flate, flate)], &raw, data.len().saturating_mul(2).saturating_add(1)).ok()? != data {
+ return None;
+ }
+ // Without a predictor the other parameters say nothing to Flate.
+ let first = parms.get(lzw).copied().flatten().filter(|_| params.predictor > 1).map(|d| {
+ let mut d = d.clone();
+ d.remove(b"EarlyChange");
+ Object::Dict(d)
+ });
+ let rest_names = names.get(lzw + 1..)?;
+ let rest_parms = parms.get(lzw + 1..)?;
+ let mut dict = s.dict.clone();
+ dict.remove(b"Length");
+ if rest_names.is_empty() {
+ dict.set(b"Filter".to_vec(), Object::name("FlateDecode"));
+ match first {
+ Some(p) => dict.set(b"DecodeParms".to_vec(), p),
+ None => {
+ dict.remove(b"DecodeParms");
+ }
+ }
+ } else {
+ let filters = std::iter::once(Object::name("FlateDecode")).chain(rest_names.iter().map(|n| Object::Name(n.to_vec())));
+ dict.set(b"Filter".to_vec(), Object::Array(filters.collect()));
+ let parms: Vec<Object> = std::iter::once(first.unwrap_or(Object::Null))
+ .chain(rest_parms.iter().map(|p| p.map_or(Object::Null, |d| Object::Dict(d.clone()))))
+ .collect();
+ if parms.iter().all(|p| matches!(p, Object::Null)) {
+ dict.remove(b"DecodeParms");
+ } else {
+ dict.set(b"DecodeParms".to_vec(), Object::Array(parms));
+ }
+ }
+ Some(Stream::from_raw(dict, raw))
+}
+
/// `s` without its outer ASCII85 or ASCIIHex layer (`[/ASCII85Decode /FlateDecode]` becomes
/// `[/FlateDecode]`), when that is smaller. Only the outer layer is decoded: strictly, and within
/// the stored size, which ASCII text never falls below, so the inner encoded bytes stay exact.
@@ -335,3 +546,20 @@ fn stored_len(s: &Stream) -> Option<usize> {
serialize(&Object::Dict(dict), &mut out);
out.len().checked_add(s.raw.len())
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn an_lzw_stream_that_decodes_past_the_limit_is_left_as_it_is() {
+ let data = b"0 0 m 612 792 l S\n".repeat(64);
+ let raw = pdfcraft_filters::encode(&Filter::Lzw, &Params::default(), &data).unwrap();
+ let mut dict = Dict::new();
+ dict.set(b"Filter".to_vec(), Object::name("LZWDecode"));
+ let s = Stream::from_raw(dict, raw);
+ assert!(lzw_to_flate(&s, data.len() - 1).is_none());
+ let converted = lzw_to_flate(&s, data.len()).unwrap();
+ assert_eq!(converted.decoded_strict().unwrap(), data);
+ }
+}
diff --git a/crates/optimize/src/links.rs b/crates/optimize/src/links.rs
index 744881d..cbd64eb 100644
--- a/crates/optimize/src/links.rs
+++ b/crates/optimize/src/links.rs
@@ -150,11 +150,15 @@ fn referenced_names(doc: &Document) -> HashSet<Vec<u8>> {
while let Some(o) = stack.pop() {
match o {
Object::Dict(d) => {
- if let Some(n) = d.get(b"Dest").and_then(dest_name) {
+ // Resolve first: /Dest and a GoTo's /D may be an indirect reference to the name
+ // string, and an unresolved ref has no name, so the destination it uses would
+ // look unreferenced and be removed. A GoToR or GoToE /D names a destination in
+ // another document, so it does not count as a use of this one's.
+ if let Some(n) = d.get(b"Dest").and_then(|x| dest_name(doc.resolve(x).as_ref())) {
out.insert(n);
}
- if matches!(d.name(b"S"), Some(b"GoTo" | b"GoToR" | b"GoToE"))
- && let Some(n) = d.get(b"D").and_then(dest_name)
+ if d.name(b"S") == Some(b"GoTo")
+ && let Some(n) = d.get(b"D").and_then(|x| dest_name(doc.resolve(x).as_ref()))
{
out.insert(n);
}
diff --git a/crates/optimize/tests/jpeg_color_transform.rs b/crates/optimize/tests/jpeg_color_transform.rs
new file mode 100644
index 0000000..c4dfabc
--- /dev/null
+++ b/crates/optimize/tests/jpeg_color_transform.rs
@@ -0,0 +1,418 @@
+//! Optimize keeps a JPEG's colours whatever its colour transform says (#1201).
+//!
+//! A JPEG with three or four components can store its samples as they are or converted to YCbCr
+//! (YCCK). An Adobe APP14 marker in the JPEG says which; without one, the filter's
+//! `/ColorTransform` does (ISO 32000-2 §7.4.8, default 1 for three components). Each image here
+//! is drawn by PdfCraft's own renderer before and after Optimize, and the two must show the same
+//! colours, up to what a JPEG re-encode loses.
+
+use std::sync::Arc;
+
+use pdfcraft_cos::{Dict, Document, ObjRef, Object, SaveOptions, Stream, write_full};
+use pdfcraft_optimize::{OptimizeError, Settings, Stage, optimize, optimize_with_progress};
+
+/// A photo-like RGB picture: colourful gradients with a little texture, so the colour transform
+/// matters everywhere and a medium-quality JPEG is smaller than a maximum-quality one.
+fn photo(w: u32, h: u32) -> Vec<u8> {
+ let mut px = Vec::with_capacity((w * h * 3) as usize);
+ for y in 0..h {
+ for x in 0..w {
+ let t = ((x ^ y) & 7) as u8;
+ px.push((x * 255 / w) as u8 ^ t);
+ px.push((y * 255 / h) as u8);
+ px.push((255 - (x + y) * 127 / (w + h)) as u8 ^ (t << 2));
+ }
+ }
+ px
+}
+
+fn rgb_jpeg(px: &[u8], w: u32, h: u32) -> Vec<u8> {
+ let mut out = Vec::new();
+ image::codecs::jpeg::JpegEncoder::new_with_quality(&mut out, 100).encode(px, w, h, image::ExtendedColorType::Rgb8).unwrap();
+ out
+}
+
+/// The JPEG's segments before its first scan: (marker, start of the marker, end of the segment).
+fn segments(jpeg: &[u8]) -> Vec<(u8, usize, usize)> {
+ assert_eq!(&jpeg[..2], &[0xFF, 0xD8]);
+ let (mut i, mut out) = (2, Vec::new());
+ loop {
+ assert_eq!(jpeg[i], 0xFF, "a marker at {i}");
+ let marker = jpeg[i + 1];
+ let end = i + 2 + u16::from_be_bytes([jpeg[i + 2], jpeg[i + 3]]) as usize;
+ out.push((marker, i, end));
+ if marker == 0xDA {
+ return out;
+ }
+ i = end;
+ }
+}
+
+/// `jpeg` with an Adobe APP14 segment whose transform flag is `transform` (0: samples stored as
+/// they are, 1: YCbCr, 2: YCCK).
+fn with_adobe(jpeg: &[u8], transform: u8) -> Vec<u8> {
+ assert!(segments(jpeg).iter().all(|s| s.0 != 0xEE), "no Adobe segment yet");
+ let mut v = jpeg[..2].to_vec();
+ v.extend_from_slice(&[0xFF, 0xEE, 0, 14, b'A', b'd', b'o', b'b', b'e', 0, 100, 0, 0, 0, 0, transform]);
+ v.extend_from_slice(&jpeg[2..]);
+ v
+}
+
+/// `jpeg` with its three components named R, G and B (in the frame and scan headers), which
+/// JPEG decoders read as samples stored untransformed.
+fn with_rgb_ids(jpeg: &[u8]) -> Vec<u8> {
+ let mut v = jpeg.to_vec();
+ let mut ids = Vec::new();
+ for (marker, i, _) in segments(jpeg) {
+ match marker {
+ 0xC0 => {
+ assert_eq!(v[i + 9], 3);
+ for k in 0..3 {
+ ids.push(v[i + 10 + 3 * k]);
+ v[i + 10 + 3 * k] = b"RGB"[k];
+ }
+ }
+ 0xDA => {
+ for k in 0..v[i + 4] as usize {
+ let id = v[i + 5 + 2 * k];
+ v[i + 5 + 2 * k] = b"RGB"[ids.iter().position(|&x| x == id).unwrap()];
+ }
+ }
+ _ => {}
+ }
+ }
+ v
+}
+
+/// A baseline JPEG `w` × `h` (multiples of 8) with four components, every 8 × 8 block one flat
+/// colour `block(bx, by)` as stored, and an Adobe APP14 segment if `adobe` is given.
+fn four_component_jpeg(w: u16, h: u16, adobe: Option<u8>, block: impl Fn(u16, u16) -> [u8; 4]) -> Vec<u8> {
+ fn put(bits: &mut Vec<bool>, value: u32, n: u32) {
+ bits.extend((0..n).rev().map(|i| value >> i & 1 == 1));
+ }
+ let mut v = vec![0xFF, 0xD8];
+ if let Some(t) = adobe {
+ v.extend_from_slice(&[0xFF, 0xEE, 0, 14, b'A', b'd', b'o', b'b', b'e', 0, 100, 0, 0, 0, 0, t]);
+ }
+ // Every quantiser 1: a flat block's DC coefficient is 8 × (sample − 128), exactly.
+ v.extend_from_slice(&[0xFF, 0xDB, 0, 67, 0]);
+ v.extend_from_slice(&[1; 64]);
+ v.extend_from_slice(&[0xFF, 0xC0, 0, 20, 8]);
+ v.extend_from_slice(&h.to_be_bytes());
+ v.extend_from_slice(&w.to_be_bytes());
+ v.push(4);
+ for id in 1..=4 {
+ v.extend_from_slice(&[id, 0x11, 0]);
+ }
+ // DC table: categories 0 to 11 with four-bit codes equal to the category. AC table: EOB, "0".
+ v.extend_from_slice(&[0xFF, 0xC4, 0, 31, 0x00, 0, 0, 0, 12, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
+ v.extend(0..12u8);
+ v.extend_from_slice(&[0xFF, 0xC4, 0, 20, 0x10, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
+ v.extend_from_slice(&[0xFF, 0xDA, 0, 14, 4, 1, 0, 2, 0, 3, 0, 4, 0, 0, 63, 0]);
+ let mut bits = Vec::new();
+ let mut pred = [0i32; 4];
+ for by in 0..h / 8 {
+ for bx in 0..w / 8 {
+ for (c, s) in block(bx, by).into_iter().enumerate() {
+ let dc = (i32::from(s) - 128) * 8;
+ let diff = dc - pred[c];
+ pred[c] = dc;
+ let category = 32 - diff.unsigned_abs().leading_zeros();
+ put(&mut bits, category, 4);
+ put(&mut bits, if diff < 0 { (diff + (1 << category) - 1) as u32 } else { diff as u32 }, category);
+ put(&mut bits, 0, 1);
+ }
+ }
+ }
+ bits.resize(bits.len().div_ceil(8) * 8, true);
+ for byte in bits.chunks(8).map(|b| b.iter().fold(0u8, |a, &x| a << 1 | u8::from(x))) {
+ v.push(byte);
+ if byte == 0xFF {
+ v.push(0);
+ }
+ }
+ v.extend_from_slice(&[0xFF, 0xD9]);
+ v
+}
+
+/// An image XObject holding `jpeg`.
+fn jpeg_image(doc: &mut Document, w: u32, h: u32, colour_space: &str, jpeg: Vec<u8>, parms: Parms) -> ObjRef {
+ let mut d = Dict::new();
+ d.set(b"Type".to_vec(), Object::name("XObject"));
+ d.set(b"Subtype".to_vec(), Object::name("Image"));
+ d.set(b"Width".to_vec(), Object::Int(w as i64));
+ d.set(b"Height".to_vec(), Object::Int(h as i64));
+ d.set(b"BitsPerComponent".to_vec(), Object::Int(8));
+ d.set(b"ColorSpace".to_vec(), Object::name(colour_space));
+ let ct = |c: i64| {
+ let mut p = Dict::new();
+ p.set(b"ColorTransform".to_vec(), Object::Int(c));
+ Object::Dict(p)
+ };
+ match parms {
+ Parms::None => d.set(b"Filter".to_vec(), Object::name("DCTDecode")),
+ Parms::Dict(c) => {
+ d.set(b"Filter".to_vec(), Object::name("DCTDecode"));
+ d.set(b"DecodeParms".to_vec(), ct(c));
+ }
+ Parms::Array(c) => {
+ d.set(b"Filter".to_vec(), Object::Array(vec![Object::name("DCTDecode")]));
+ d.set(b"DecodeParms".to_vec(), Object::Array(vec![ct(c)]));
+ }
+ }
+ doc.add(Object::Stream(Stream::from_raw(d, jpeg)))
+}
+
+/// How an image's `/DecodeParms` gives its `/ColorTransform`.
+#[derive(Clone, Copy, Debug)]
+enum Parms {
+ None,
+ /// `/Filter /DCTDecode /DecodeParms << /ColorTransform c >>`.
+ Dict(i64),
+ /// `/Filter [/DCTDecode] /DecodeParms [<< /ColorTransform c >>]`.
+ Array(i64),
+}
+
+/// A document with one page, `w` × `h` pt, whose content is `content` drawing `images`.
+fn one_page(doc: &mut Document, w: u32, h: u32, images: &[(String, ObjRef)], content: &str) {
+ let pages = doc.root().and_then(|r| doc.get(r).as_dict().and_then(|d| d.reference(b"Pages"))).unwrap();
+ let mut x = Dict::new();
+ for (name, r) in images {
+ x.set(name.as_bytes().to_vec(), Object::Ref(*r));
+ }
+ let mut res = Dict::new();
+ res.set(b"XObject".to_vec(), Object::Dict(x));
+ let c = doc.add(Object::Stream(Stream::from_raw(Dict::new(), content.as_bytes().to_vec())));
+ let mut p = Dict::new();
+ p.set(b"Type".to_vec(), Object::name("Page"));
+ p.set(b"Parent".to_vec(), Object::Ref(pages));
+ p.set(b"MediaBox".to_vec(), Object::Array(vec![0.into(), 0.into(), (w as i64).into(), (h as i64).into()]));
+ p.set(b"Resources".to_vec(), Object::Dict(res));
+ p.set(b"Contents".to_vec(), Object::Ref(c));
+ let r = doc.add(Object::Dict(p));
+ doc.update_dict(pages, |d| {
+ d.set(b"Kids".to_vec(), Object::Array(vec![Object::Ref(r)]));
+ d.set(b"Count".to_vec(), Object::Int(1));
+ })
+ .unwrap();
+}
+
+/// A document whose one page shows `jpeg` (`w` × `h` px) at `ppi`.
+fn showing(w: u32, h: u32, ppi: u32, colour_space: &str, jpeg: Vec<u8>, parms: Parms) -> (Document, ObjRef) {
+ let mut doc = Document::new_empty();
+ let img = jpeg_image(&mut doc, w, h, colour_space, jpeg, parms);
+ let (pw, ph) = (w * 72 / ppi, h * 72 / ppi);
+ one_page(&mut doc, pw, ph, &[("Im".to_string(), img)], &format!("q {pw} 0 0 {ph} 0 0 cm /Im Do Q"));
+ (doc, img)
+}
+
+fn stream(doc: &Document, r: ObjRef) -> Stream {
+ match &*doc.get(r) {
+ Object::Stream(s) => s.clone(),
+ _ => panic!("not a stream"),
+ }
+}
+
+/// The page as PdfCraft's renderer draws it, `scale` device pixels per point: RGB rows.
+fn render(doc: &Document, scale: f32) -> (u32, u32, Vec<u8>) {
+ let bytes = write_full(doc, &SaveOptions::default()).unwrap();
+ let mut r = pdfcraft_render::PageRenderer::new(Arc::new(bytes), pdfcraft_render::RenderConfig::default());
+ let out = r.render(pdfcraft_render::RenderRequest { page: 0, scale, ..Default::default() });
+ assert!(out.error.is_none(), "{:?}", out.error);
+ (out.width, out.height, out.rgba.chunks(4).flat_map(|p| [p[0], p[1], p[2]]).collect())
+}
+
+/// The mean difference per colour component between two renders of one page, leaving out a
+/// two-pixel border (where the picture's edge is smoothed).
+fn mean_difference(a: &(u32, u32, Vec<u8>), b: &(u32, u32, Vec<u8>)) -> f64 {
+ assert_eq!((a.0, a.1), (b.0, b.1), "renders of one page size");
+ let (w, h) = (a.0 as usize, a.1 as usize);
+ let (mut sum, mut count) = (0u64, 0u64);
+ for y in 2..h - 2 {
+ for x in 2..w - 2 {
+ for c in 0..3 {
+ let i = (y * w + x) * 3 + c;
+ sum += u64::from(a.2[i].abs_diff(b.2[i]));
+ count += 1;
+ }
+ }
+ }
+ sum as f64 / count as f64
+}
+
+/// Re-encoding a JPEG at medium quality moves a component by about this much on average; a
+/// colour transform applied or dropped wrongly moves it by tens.
+const TOLERANCE: f64 = 4.0;
+
+#[derive(Clone, Copy, Debug, PartialEq)]
+enum Outcome {
+ /// Re-encoded (smaller), as a plain YCbCr JPEG with no `/DecodeParms`.
+ Reencoded,
+ /// Left exactly as it was.
+ Untouched,
+}
+
+#[test]
+fn optimize_keeps_the_colours_of_an_rgb_jpeg_whatever_its_colour_transform() {
+ use Outcome::*;
+ let (w, h) = (128, 128);
+ let plain = rgb_jpeg(&photo(w, h), w, h);
+ // What the cases rely on: one JPEG read with and without its colour transform shows very
+ // different colours, so a transform lost or added by Optimize can't hide in the tolerance.
+ let transformed = render(&showing(w, h, 72, "DeviceRGB", plain.clone(), Parms::None).0, 1.0);
+ let as_stored = render(&showing(w, h, 72, "DeviceRGB", plain.clone(), Parms::Dict(0)).0, 1.0);
+ let apart = mean_difference(&transformed, &as_stored);
+ assert!(apart > 10.0 * TOLERANCE, "the fixture tells the two readings apart: {apart:.1}");
+
+ let mut failures = Vec::new();
+ for (what, adobe, rgb_ids, parms, expect) in [
+ ("no Adobe marker, no /ColorTransform", None, false, Parms::None, Reencoded),
+ ("no Adobe marker, /ColorTransform 1", None, false, Parms::Dict(1), Reencoded),
+ ("no Adobe marker, /ColorTransform 0", None, false, Parms::Dict(0), Reencoded),
+ ("no Adobe marker, /ColorTransform 0 in a filter array", None, false, Parms::Array(0), Reencoded),
+ ("Adobe YCbCr marker", Some(1), false, Parms::None, Reencoded),
+ ("Adobe YCbCr marker, /ColorTransform 1", Some(1), false, Parms::Dict(1), Reencoded),
+ ("Adobe untransformed marker", Some(0), false, Parms::None, Reencoded),
+ ("Adobe untransformed marker, /ColorTransform 0", Some(0), false, Parms::Dict(0), Reencoded),
+ // The marker overrides /ColorTransform in the standard, but readers differ (PdfCraft's
+ // renderer lets /ColorTransform 0 win): the image is left as it is.
+ ("Adobe YCbCr marker, /ColorTransform 0", Some(1), false, Parms::Dict(0), Untouched),
+ ("Adobe untransformed marker, /ColorTransform 1", Some(0), false, Parms::Dict(1), Untouched),
+ // Components named R, G and B: JPEG decoders read them untransformed, the standard's
+ // default transforms them. Only an explicit /ColorTransform 0 settles it.
+ ("components R, G, B, no /ColorTransform", None, true, Parms::None, Untouched),
+ ("components R, G, B, /ColorTransform 0", None, true, Parms::Dict(0), Reencoded),
+ ] {
+ let mut jpeg = plain.clone();
+ if rgb_ids {
+ jpeg = with_rgb_ids(&jpeg);
+ }
+ if let Some(t) = adobe {
+ jpeg = with_adobe(&jpeg, t);
+ }
+ let (mut doc, img) = showing(w, h, 72, "DeviceRGB", jpeg, parms);
+ let original = stream(&doc, img);
+ let before = render(&doc, 1.0);
+ // Reduce File Size: an image at 72 ppi isn't resampled, only recompressed as JPEG 60.
+ let report = optimize(&mut doc, &Settings::default()).unwrap();
+ let after = render(&doc, 1.0);
+ let new = stream(&doc, img);
+ let outcome = if new == original {
+ Untouched
+ } else {
+ assert_eq!(new.dict.name(b"Filter"), Some(&b"DCTDecode"[..]), "{what}");
+ assert!(!new.dict.contains(b"DecodeParms"), "{what}: a plain JPEG has no colour transform to state");
+ assert_eq!(report.images_recompressed, 1, "{what}");
+ Reencoded
+ };
+ let difference = mean_difference(&before, &after);
+ if outcome != expect || difference > TOLERANCE {
+ failures.push(format!("{what}: {outcome:?} (expected {expect:?}), colours moved by {difference:.1}"));
+ }
+ }
+ assert!(failures.is_empty(), "\n{}", failures.join("\n"));
+}
+
+#[test]
+fn optimize_leaves_cmyk_jpegs_as_they_are_with_or_without_an_adobe_marker() {
+ // 256 px drawn at 288 ppi: Reduce File Size would resample a colour space it handles.
+ let (w, h) = (256u16, 256u16);
+ let block = |bx: u16, by: u16| [(bx * 8) as u8, (by * 8) as u8, (255 - (bx + by) * 4) as u8, ((bx ^ by) * 8) as u8];
+ for (adobe, parms) in [
+ (None, Parms::None),
+ (None, Parms::Dict(0)),
+ (None, Parms::Dict(1)),
+ (Some(0), Parms::None),
+ (Some(0), Parms::Dict(1)),
+ (Some(2), Parms::None),
+ (Some(2), Parms::Dict(0)),
+ ] {
+ let what = format!("Adobe marker {adobe:?}, {parms:?}");
+ let jpeg = four_component_jpeg(w, h, adobe, block);
+ let (mut doc, img) = showing(u32::from(w), u32::from(h), 288, "DeviceCMYK", jpeg, parms);
+ let original = doc.get(img);
+ let before = render(&doc, 4.0);
+ optimize(&mut doc, &Settings::default()).unwrap();
+ assert_eq!(doc.get(img), original, "{what}: left as it is");
+ assert!(before == render(&doc, 4.0), "{what}: the page looks the same");
+ }
+}
+
+#[test]
+fn merging_jpeg_strips_keeps_their_colour_transform() {
+ // A page picture printed as 16 JPEG strips stored untransformed (/ColorTransform 0, no
+ // Adobe marker): the merged image must show the strips' colours, not their samples converted
+ // from YCbCr.
+ let (w, h, rows) = (128u32, 128u32, 8u32);
+ let px = photo(w, h);
+ let mut doc = Document::new_empty();
+ let mut images = Vec::new();
+ let mut content = String::new();
+ for k in 0..h / rows {
+ let band = &px[(k * rows * w * 3) as usize..((k + 1) * rows * w * 3) as usize];
+ let img = jpeg_image(&mut doc, w, rows, "DeviceRGB", rgb_jpeg(band, w, rows), Parms::Dict(0));
+ images.push((format!("S{k}"), img));
+ content += &format!("q {w} 0 0 {rows} 0 {} cm /S{k} Do Q\n", h - (k + 1) * rows);
+ }
+ one_page(&mut doc, w, h, &images, &content);
+ let before = render(&doc, 1.0);
+ let report = optimize(&mut doc, &Settings::default()).unwrap();
+ assert_eq!(report.merged_images, 1, "{report:?}");
+ let difference = mean_difference(&before, &render(&doc, 1.0));
+ assert!(difference <= TOLERANCE, "colours moved by {difference:.1}");
+}
+
+/// `jpeg` with `bytes` right after its SOI marker.
+fn after_soi(jpeg: &[u8], bytes: &[u8]) -> Vec<u8> {
+ let mut v = jpeg[..2].to_vec();
+ v.extend_from_slice(bytes);
+ v.extend_from_slice(&jpeg[2..]);
+ v
+}
+
+#[test]
+fn a_jpeg_header_that_takes_more_than_a_few_steps_to_read_is_left_as_it_is() {
+ // Decoders skip stray bytes between segments and any number of fill bytes before a marker,
+ // so a stream can make a header scan walk megabytes. Optimize reads the header again for
+ // every group of fragments it tries: it stops at the first stray byte, or after a few
+ // thousand steps, and leaves such an image as it is.
+ let (w, h) = (128, 128);
+ let plain = rgb_jpeg(&photo(w, h), w, h);
+ for (what, jpeg, expect) in [
+ ("three fill bytes before the first segment", after_soi(&plain, &[0xFF; 3]), Outcome::Reencoded),
+ ("one stray byte before the first segment", after_soi(&plain, &[0]), Outcome::Untouched),
+ ("8 MB of stray bytes before the first segment", after_soi(&plain, &vec![0; 8_000_000]), Outcome::Untouched),
+ ("10,000 fill bytes before the first segment", after_soi(&plain, &[0xFF; 10_000]), Outcome::Untouched),
+ ] {
+ let (mut doc, img) = showing(w, h, 72, "DeviceRGB", jpeg, Parms::None);
+ let original = stream(&doc, img);
+ optimize(&mut doc, &Settings::default()).unwrap();
+ let outcome = if stream(&doc, img) == original { Outcome::Untouched } else { Outcome::Reencoded };
+ assert_eq!(outcome, expect, "{what}");
+ }
+}
+
+#[test]
+fn cancelling_works_from_the_first_call_with_a_jpeg_drawn_many_times() {
+ // One JPEG with 8 MB of stray bytes after SOI, drawn 64 times at the same place (the case
+ // reported on #3012). Fragment merging reads its header for each group it tries, before the
+ // first progress call. The header scan stops at the first stray byte, so that call is the
+ // first image, and cancelling there stops Optimize.
+ let (w, h) = (128, 8);
+ let jpeg = after_soi(&rgb_jpeg(&photo(w, h), w, h), &vec![0; 8_000_000]);
+ let mut doc = Document::new_empty();
+ let img = jpeg_image(&mut doc, w, h, "DeviceRGB", jpeg, Parms::None);
+ let content = format!(
+ "q {w} 0 0 {h} 0 0 cm /Im Do Q
+"
+ )
+ .repeat(64);
+ one_page(&mut doc, w, h, &[("Im".to_string(), img)], &content);
+ let mut stages = Vec::new();
+ let result = optimize_with_progress(&mut doc, &Settings::default(), &mut |stage| {
+ stages.push(stage);
+ false
+ });
+ assert!(matches!(result, Err(OptimizeError::Cancelled)), "{result:?}");
+ assert_eq!(stages, [Stage::Images { done: 0, total: 1 }]);
+}
diff --git a/crates/optimize/tests/optimize.rs b/crates/optimize/tests/optimize.rs
index 6cf53d4..3e69e27 100644
--- a/crates/optimize/tests/optimize.rs
+++ b/crates/optimize/tests/optimize.rs
@@ -3,7 +3,10 @@
use std::sync::Arc;
use pdfcraft_cos::{Dict, Document, ObjRef, Object, SaveOptions, Stream, write_full};
-use pdfcraft_optimize::{Compression, ImageSettings, Settings, SpaceCategory, audit_space, effective_resolutions, optimize};
+use pdfcraft_filters::{Filter, Params};
+use pdfcraft_optimize::{
+ Compatibility, Compression, ImageSettings, OptimizeError, Settings, SpaceCategory, audit_space, effective_resolutions, optimize,
+};
fn image(doc: &mut Document, w: u32, h: u32, n: usize, jpeg: bool, smask: Option<ObjRef>) -> ObjRef {
// A smooth gradient with a little texture (photo-like).
@@ -74,6 +77,57 @@ fn stream(doc: &Document, r: ObjRef) -> Stream {
}
}
+#[test]
+fn image_resolution_uses_the_pages_physical_unit() {
+ for (unit, scale) in [
+ (None, 1.0),
+ (Some(Object::Int(10)), 10.0),
+ (Some(Object::Real(2.5)), 2.5),
+ (Some(Object::Int(0)), 1.0),
+ (Some(Object::Int(-10)), 1.0),
+ (Some(Object::Real(0.5)), 1.0),
+ (Some(Object::name("Ten")), 1.0),
+ (Some(Object::Int(100_000)), pdfcraft_model::MAX_USER_UNIT),
+ ] {
+ for indirect in [false, true] {
+ let mut doc = Document::new_empty();
+ let img = image(&mut doc, 720, 720, 1, false, None);
+ let p = page(&mut doc, &[("Im", img)], "q 72 0 0 72 0 0 cm /Im Do Q");
+ let parent = doc.get(p).as_dict().unwrap().reference(b"Parent").unwrap();
+ // UserUnit is page-local, unlike Resources and MediaBox.
+ doc.update_dict(parent, |d| d.set(b"UserUnit".to_vec(), Object::Int(10))).unwrap();
+ if let Some(unit) = unit.clone() {
+ let unit = if indirect { Object::Ref(doc.add(unit)) } else { unit };
+ doc.update_dict(p, |d| d.set(b"UserUnit".to_vec(), unit)).unwrap();
+ }
+ let ppi = effective_resolutions(&doc, &[p])[&img];
+ assert!((ppi - 720.0 / scale).abs() < 1e-9, "unit={unit:?}, indirect={indirect}: {ppi}");
+ }
+ }
+}
+
+#[test]
+fn optimization_retains_an_image_below_threshold_on_a_scaled_page() {
+ let mut doc = Document::new_empty();
+ let img = image(&mut doc, 720, 720, 3, false, None);
+ let p = page(&mut doc, &[("Im", img)], "q 72 0 0 72 0 0 cm /Im Do Q");
+ doc.update_dict(p, |d| d.set(b"UserUnit".to_vec(), Object::Int(10))).unwrap();
+ // 720 pixels across ten inches is 72 ppi, already below the 225 ppi threshold.
+ let report = optimize(&mut doc, &Settings::default()).unwrap();
+ assert_eq!(report.images_resampled, 0, "{report:?}");
+ let image = stream(&doc, img);
+ assert_eq!((image.dict.int(b"Width"), image.dict.int(b"Height")), (Some(720), Some(720)));
+ let reopened = Document::open(Arc::new(write_full(&doc, &SaveOptions::default()).unwrap())).unwrap();
+ let dimensions: Vec<_> = reopened
+ .scan_objects()
+ .filter_map(|(_, object)| match &*object {
+ Object::Stream(s) if s.dict.name(b"Subtype") == Some(b"Image") => Some((s.dict.int(b"Width"), s.dict.int(b"Height"))),
+ _ => None,
+ })
+ .collect();
+ assert_eq!(dimensions, [(Some(720), Some(720))]);
+}
+
#[test]
fn images_are_measured_where_drawn_and_downsampled() {
let mut doc = Document::new_empty();
@@ -925,6 +979,23 @@ fn nested_forms(doc: &mut Document, img: ObjRef, levels: usize) -> ObjRef {
inner
}
+#[test]
+fn shared_forms_are_measured_in_each_pages_physical_units() {
+ for reverse in [false, true] {
+ let mut doc = Document::new_empty();
+ let img = image(&mut doc, 720, 720, 3, false, None);
+ let outer = nested_forms(&mut doc, img, 3);
+ let normal = page(&mut doc, &[("F", outer)], "q 72 0 0 72 0 0 cm /F Do Q");
+ let scaled = page(&mut doc, &[("F", outer)], "q 72 0 0 72 0 0 cm /F Do Q");
+ doc.update_dict(scaled, |d| d.set(b"UserUnit".to_vec(), Object::Int(10))).unwrap();
+ let pages = if reverse { [scaled, normal] } else { [normal, scaled] };
+ assert_eq!(effective_resolutions(&doc, &pages)[&img], 72.0, "reverse={reverse}");
+ let report = optimize(&mut doc, &Settings::default()).unwrap();
+ assert_eq!(report.images_resampled, 0, "{report:?}");
+ assert_eq!(stream(&doc, img).dict.int(b"Width"), Some(720));
+ }
+}
+
#[test]
fn a_deeply_nested_form_is_measured_at_its_largest_use() {
// 1200 px drawn 1 in wide (1200 ppi) and then 8 in wide (150 ppi): 150 ppi, so it isn't resampled.
@@ -1036,6 +1107,77 @@ fn images_are_not_resampled_when_a_page_enters_more_forms_than_allowed() {
assert_eq!(effective_resolutions(&doc, &refs)[&img], f64::INFINITY);
}
+#[test]
+fn compatibility_level_sets_version_unpacks_for_1_4_and_checks_encryption() {
+ let mut base = Document::new_empty();
+ page(&mut base, &[], "BT /F1 12 Tf 72 720 Td (Compatibility test) Tj ET");
+ let root = base.root().unwrap();
+ base.update_dict(root, |c| c.set(b"Version".to_vec(), Object::name("1.6"))).unwrap();
+
+ for (compat, expected) in [
+ (Compatibility::Pdf1_4, "1.4"),
+ (Compatibility::Pdf1_5, "1.5"),
+ (Compatibility::Pdf1_6, "1.6"),
+ (Compatibility::Pdf1_7, "1.7"),
+ (Compatibility::Pdf2_0, "2.0"),
+ ] {
+ let mut doc = base.clone();
+ let settings = Settings { compatibility: compat, ..Settings::default() };
+ optimize(&mut doc, &settings).unwrap();
+ assert_eq!(doc.version(), expected);
+ assert!(!doc.get(root).as_dict().unwrap().contains(b"Version"), "overriding catalog /Version is cleared");
+ let bytes = write_full(&doc, &SaveOptions { object_streams: settings.effective_object_streams(), ..SaveOptions::default() }).unwrap();
+ assert!(bytes.starts_with(format!("%PDF-{expected}\n").as_bytes()), "{expected}");
+ let has_objstm = bytes.windows(7).any(|w| w == b"/ObjStm");
+ assert_eq!(has_objstm, compat != Compatibility::Pdf1_4, "{compat:?}");
+ let info = pdfcraft_render::inspect(Arc::new(bytes), None).unwrap();
+ assert_eq!(info.pdf_version, expected);
+ }
+
+ // Disabling object_streams on PDF 1.7 writes a classic cross-reference table.
+ let mut doc = base.clone();
+ let settings = Settings { compatibility: Compatibility::Pdf1_7, object_streams: false, ..Settings::default() };
+ optimize(&mut doc, &settings).unwrap();
+ let bytes = write_full(&doc, &SaveOptions { object_streams: settings.effective_object_streams(), ..SaveOptions::default() }).unwrap();
+ assert!(bytes.starts_with(b"%PDF-1.7\n") && !bytes.windows(7).any(|w| w == b"/ObjStm"));
+
+ // Encryption that requires a newer PDF version than the chosen compatibility is refused.
+ let mut aes256 = base.clone();
+ aes256
+ .set_encryption(&pdfcraft_cos::NewEncryption {
+ algorithm: pdfcraft_cos::Algorithm::Aes256,
+ user_password: "u",
+ owner_password: "o",
+ permissions: -1,
+ encrypt_metadata: true,
+ seed: [1; 32],
+ })
+ .unwrap();
+ assert!(matches!(
+ optimize(&mut aes256, &Settings { compatibility: Compatibility::Pdf1_6, ..Settings::default() }),
+ Err(OptimizeError::IncompatibleEncryption { required: "1.7", chosen: "1.6" })
+ ));
+ optimize(&mut aes256, &Settings { compatibility: Compatibility::Pdf2_0, ..Settings::default() }).unwrap();
+ assert_eq!(aes256.version(), "2.0");
+
+ let mut aes128 = base;
+ aes128
+ .set_encryption(&pdfcraft_cos::NewEncryption {
+ algorithm: pdfcraft_cos::Algorithm::Aes128,
+ user_password: "u",
+ owner_password: "o",
+ permissions: -1,
+ encrypt_metadata: true,
+ seed: [1; 32],
+ })
+ .unwrap();
+ assert!(matches!(
+ optimize(&mut aes128, &Settings { compatibility: Compatibility::Pdf1_5, ..Settings::default() }),
+ Err(OptimizeError::IncompatibleEncryption { required: "1.6", chosen: "1.5" })
+ ));
+ optimize(&mut aes128, &Settings { compatibility: Compatibility::Pdf1_6, ..Settings::default() }).unwrap();
+}
+
#[test]
fn image_resolution_keeps_comments_across_content_pieces() {
for ending in ["", "\n", "\r", "\r\n"] {
@@ -1097,3 +1239,300 @@ fn a_hostile_soft_mask_leaves_its_image_unchanged() {
assert_eq!(stream(&doc, photo), before);
assert_eq!(stream(&doc, mask), hostile);
}
+
+#[test]
+fn indirectly_referenced_destination_is_kept() {
+ // A link's /Dest can be an indirect reference to the name string, not the string itself. Reduce
+ // File Size read the name only from a direct string, so it deleted a destination the link still
+ // used, silently breaking the link.
+ let mut doc = Document::new_empty();
+ let p = page(&mut doc, &[], "BT ET");
+ let s = |t: &str| Object::String(pdfcraft_cos::PdfString::literal(t.as_bytes().to_vec()));
+ // A link whose /Dest is `ref -> "target"`, and an unused destination for contrast.
+ let name_ref = Object::Ref(doc.add(s("target")));
+ let mut link = Dict::new();
+ link.set(b"Type".to_vec(), Object::name("Annot"));
+ link.set(b"Subtype".to_vec(), Object::name("Link"));
+ link.set(b"Rect".to_vec(), Object::Array(vec![0.into(), 0.into(), 10.into(), 10.into()]));
+ link.set(b"Dest".to_vec(), name_ref);
+ let link = Object::Ref(doc.add(Object::Dict(link)));
+ doc.update_dict(p, |d| d.set(b"Annots".to_vec(), Object::Array(vec![link]))).unwrap();
+ let fit = Object::Array(vec![Object::Ref(p), Object::name("Fit")]);
+ let mut tree = Dict::new();
+ tree.set(b"Names".to_vec(), Object::Array(vec![s("target"), fit.clone(), s("unused"), fit]));
+ let tree = doc.add(Object::Dict(tree));
+ let mut names = Dict::new();
+ names.set(b"Dests".to_vec(), Object::Ref(tree));
+ let root = doc.root().unwrap();
+ doc.update_dict(root, |c| c.set(b"Names".to_vec(), Object::Dict(names))).unwrap();
+ let report = optimize(&mut doc, &Settings::default()).unwrap();
+ // Only "unused" is removed; the indirectly-referenced "target" is kept.
+ assert_eq!(report.unreferenced_dests, 1);
+ let left = named_dest_keys(&doc);
+ assert!(left.contains(&b"target".to_vec()), "indirectly referenced destination was kept: {left:?}");
+ assert!(!left.contains(&b"unused".to_vec()));
+}
+
+#[test]
+fn a_destination_named_only_by_a_remote_or_embedded_go_to_is_removed() {
+ // The /D of a GoToR or GoToE action names a destination in another document. A local
+ // destination of the same name that nothing else uses is unreferenced.
+ let mut doc = Document::new_empty();
+ let p = page(&mut doc, &[], "BT ET");
+ let s = |t: &str| Object::String(pdfcraft_cos::PdfString::literal(t.as_bytes().to_vec()));
+ let link = |doc: &mut Document, action: Dict| {
+ let mut link = Dict::new();
+ link.set(b"Type".to_vec(), Object::name("Annot"));
+ link.set(b"Subtype".to_vec(), Object::name("Link"));
+ link.set(b"Rect".to_vec(), Object::Array(vec![0.into(), 0.into(), 10.into(), 10.into()]));
+ link.set(b"A".to_vec(), Object::Dict(action));
+ Object::Ref(doc.add(Object::Dict(link)))
+ };
+ let mut go_to = Dict::new();
+ go_to.set(b"S".to_vec(), Object::name("GoTo"));
+ go_to.set(b"D".to_vec(), s("local"));
+ let mut remote = Dict::new();
+ remote.set(b"S".to_vec(), Object::name("GoToR"));
+ remote.set(b"F".to_vec(), s("other.pdf"));
+ remote.set(b"D".to_vec(), s("remote"));
+ let mut target = Dict::new();
+ target.set(b"R".to_vec(), Object::name("C"));
+ target.set(b"N".to_vec(), s("attached.pdf"));
+ let mut embedded = Dict::new();
+ embedded.set(b"S".to_vec(), Object::name("GoToE"));
+ embedded.set(b"T".to_vec(), Object::Dict(target));
+ embedded.set(b"D".to_vec(), s("embedded"));
+ let links = vec![link(&mut doc, go_to), link(&mut doc, remote), link(&mut doc, embedded)];
+ doc.update_dict(p, |d| d.set(b"Annots".to_vec(), Object::Array(links))).unwrap();
+ let fit = Object::Array(vec![Object::Ref(p), Object::name("Fit")]);
+ let mut tree = Dict::new();
+ tree.set(b"Names".to_vec(), Object::Array(vec![s("embedded"), fit.clone(), s("local"), fit.clone(), s("remote"), fit]));
+ let tree = doc.add(Object::Dict(tree));
+ let mut names = Dict::new();
+ names.set(b"Dests".to_vec(), Object::Ref(tree));
+ let root = doc.root().unwrap();
+ doc.update_dict(root, |c| c.set(b"Names".to_vec(), Object::Dict(names))).unwrap();
+ let report = optimize(&mut doc, &Settings::default()).unwrap();
+ assert_eq!(report.unreferenced_dests, 2);
+ assert_eq!(named_dest_keys(&doc), vec![b"local".to_vec()]);
+}
+
+/// The keys in the catalog's /Names /Dests name tree (one level, as the optimizer writes it).
+fn named_dest_keys(doc: &Document) -> Vec<Vec<u8>> {
+ let cat = doc.get(doc.root().unwrap()).as_dict().cloned().unwrap();
+ let names = doc.resolve(cat.get(b"Names").unwrap()).as_dict().cloned().unwrap();
+ let tree = doc.resolve(names.get(b"Dests").unwrap()).as_dict().cloned().unwrap();
+ let arr = doc.resolve(tree.get(b"Names").unwrap()).as_array().cloned().unwrap();
+ arr.chunks(2).filter_map(|c| doc.resolve(&c[0]).as_string().map(|s| s.bytes.clone())).collect()
+}
+
+/// Page content long enough for LZW codes to grow past 9 bits, where `EarlyChange` matters.
+fn lzw_ops() -> Vec<u8> {
+ (0..300).flat_map(|i| format!("{} {} m {} {} l S\n", i % 97, i * 7 % 389, i * 13 % 612, i * 31 % 792).into_bytes()).collect()
+}
+
+fn lzw(data: &[u8], params: &Params) -> Vec<u8> {
+ pdfcraft_filters::encode(&Filter::Lzw, params, data).unwrap()
+}
+
+/// `params` as a `/DecodeParms` dictionary, only the entries that differ from the defaults.
+fn decode_parms(p: &Params) -> Dict {
+ let mut d = Dict::new();
+ for (k, v, default) in [
+ (&b"Predictor"[..], p.predictor, 1),
+ (b"Colors", p.colors, 1),
+ (b"BitsPerComponent", p.bits_per_component, 8),
+ (b"Columns", p.columns, 1),
+ (b"EarlyChange", p.early_change, 1),
+ ] {
+ if v != default {
+ d.set(k.to_vec(), Object::Int(v));
+ }
+ }
+ d
+}
+
+/// A 64 × 48 RGB image, LZW-encoded with `params`.
+fn lzw_image(doc: &mut Document, params: &Params) -> (ObjRef, Vec<u8>) {
+ let (w, h) = (64u32, 48u32);
+ let px: Vec<u8> = (0..w * h).flat_map(|i| [(i % w * 4) as u8, (i / w * 5) as u8, ((i % w + i / w) * 2) as u8]).collect();
+ let mut d = Dict::new();
+ d.set(b"Type".to_vec(), Object::name("XObject"));
+ d.set(b"Subtype".to_vec(), Object::name("Image"));
+ d.set(b"Width".to_vec(), Object::Int(w.into()));
+ d.set(b"Height".to_vec(), Object::Int(h.into()));
+ d.set(b"BitsPerComponent".to_vec(), Object::Int(8));
+ d.set(b"ColorSpace".to_vec(), Object::name("DeviceRGB"));
+ d.set(b"Filter".to_vec(), Object::name("LZWDecode"));
+ d.set(b"DecodeParms".to_vec(), Object::Dict(decode_parms(params)));
+ (doc.add(Object::Stream(Stream::from_raw(d, lzw(&px, params)))), px)
+}
+
+/// Settings that leave images to the clean-up: no resampling, no recompression.
+fn clean_up_only() -> Settings {
+ let keep = ImageSettings { downsample: false, compression: Compression::Retain, ..ImageSettings::REDUCE };
+ Settings { color: keep, gray: keep, ..Settings::default() }
+}
+
+#[test]
+fn lzw_streams_become_flate_and_decode_to_the_same_bytes() {
+ let ops = lzw_ops();
+ let early = Params::default();
+ let late = Params { early_change: 0, ..Params::default() };
+ let png = Params { predictor: 15, colors: 3, columns: 64, ..Params::default() };
+ let png_late = Params { early_change: 0, ..png.clone() };
+ let mut doc = Document::new_empty();
+ let content = |doc: &mut Document, p: &Params| {
+ let mut d = Dict::new();
+ d.set(b"Filter".to_vec(), Object::name("LZWDecode"));
+ if *p != Params::default() {
+ d.set(b"DecodeParms".to_vec(), Object::Dict(decode_parms(p)));
+ }
+ doc.add(Object::Stream(Stream::from_raw(d, lzw(&ops, p))))
+ };
+ let c_early = content(&mut doc, &early);
+ let c_late = content(&mut doc, &late);
+ let (img, px) = lzw_image(&mut doc, &png);
+ let (img_late, _) = lzw_image(&mut doc, &png_late);
+ page(&mut doc, &[("Im", img), ("Im2", img_late)], "q 64 0 0 48 72 600 cm /Im Do Q q 64 0 0 48 172 600 cm /Im2 Do Q");
+ let pg = pdfcraft_annot::page_refs(&doc).unwrap()[0];
+ doc.update_dict(pg, |d| {
+ d.set(b"Contents".to_vec(), Object::Array(vec![Object::Ref(c_early), Object::Ref(c_late), d.get(b"Contents").unwrap().clone()]))
+ })
+ .unwrap();
+ // Each LZW stream reads as its own data before, so a decoder ignoring EarlyChange fails here.
+ assert_eq!((stream(&doc, c_early).decoded_strict().unwrap(), stream(&doc, c_late).decoded_strict().unwrap()), (ops.clone(), ops.clone()));
+ assert!(lzw(&ops, &early) != lzw(&ops, &late), "the two code widths differ on this data");
+
+ let r = optimize(&mut doc, &clean_up_only()).unwrap();
+ assert_eq!(r.lzw_streams, 4, "{r:?}");
+ for (label, at, data) in
+ [("content", c_early, &ops), ("content, EarlyChange 0", c_late, &ops), ("image", img, &px), ("image, EarlyChange 0", img_late, &px)]
+ {
+ let after = stream(&doc, at);
+ assert_eq!(after.dict.get(b"Filter"), Some(&Object::name("FlateDecode")), "{label}");
+ assert_eq!(&after.decoded_strict().unwrap(), data, "{label}");
+ let parms = after.dict.get(b"DecodeParms").and_then(Object::as_dict);
+ assert!(parms.is_none_or(|p| !p.contains(b"EarlyChange")), "{label}: EarlyChange is LZW's alone");
+ }
+ // The image keeps its PNG predictor, now applied under Flate.
+ let parms = stream(&doc, img).dict.get(b"DecodeParms").and_then(Object::as_dict).cloned().unwrap();
+ assert_eq!((parms.int(b"Predictor"), parms.int(b"Colors"), parms.int(b"Columns")), (Some(15), Some(3), Some(64)));
+ assert!(!stream(&doc, c_late).dict.contains(b"DecodeParms"), "nothing left to say for the content stream");
+}
+
+#[test]
+fn a_page_drawn_from_lzw_streams_renders_the_same_after_conversion() {
+ let png = Params { predictor: 12, colors: 3, columns: 64, early_change: 0, ..Params::default() };
+ let mut doc = Document::new_empty();
+ let (img, _) = lzw_image(&mut doc, &png);
+ let pg = page(&mut doc, &[("Im", img)], "");
+ let ops = b"0.2 0.5 0.8 rg 36 36 300 200 re f q 256 0 0 192 72 400 cm /Im Do Q\n".repeat(4);
+ let mut d = Dict::new();
+ d.set(b"Filter".to_vec(), Object::name("LZWDecode"));
+ d.set(b"DecodeParms".to_vec(), Object::Dict(decode_parms(&Params { early_change: 0, ..Params::default() })));
+ let c = doc.add(Object::Stream(Stream::from_raw(d, lzw(&ops, &Params { early_change: 0, ..Params::default() }))));
+ doc.update_dict(pg, |p| p.set(b"Contents".to_vec(), Object::Ref(c))).unwrap();
+ let render = |doc: &Document| {
+ let bytes = write_full(doc, &SaveOptions::default()).unwrap();
+ let mut r = pdfcraft_render::PageRenderer::new(Arc::new(bytes), pdfcraft_render::RenderConfig::default());
+ let out = r.render(pdfcraft_render::RenderRequest { page: 0, scale: 1.0, ..Default::default() });
+ assert!(out.error.is_none(), "{:?}", out.error);
+ out.rgba
+ };
+ let before = render(&doc);
+ // The picture and the rectangle are drawn: the page is not blank.
+ assert!(before.chunks(4).any(|p| p[..3] != [255, 255, 255]));
+ let r = optimize(&mut doc, &clean_up_only()).unwrap();
+ assert_eq!(r.lzw_streams, 2, "{r:?}");
+ assert_eq!(stream(&doc, c).dict.name(b"Filter"), Some(&b"FlateDecode"[..]));
+ assert!(render(&doc) == before, "the page renders pixel for pixel as before");
+}
+
+#[test]
+fn lzw_inside_a_filter_chain_is_replaced_and_the_other_stages_kept() {
+ let ops = lzw_ops();
+ let inner = lzw(&ops, &Params::default());
+ // An ASCII85 layer outside the LZW goes with it; a JPEG inside it stays encoded as it was.
+ let (mut doc, c) = with_content(filtered(&["ASCII85Decode", "LZWDecode"], ascii85(&inner)));
+ let photo = image(&mut doc, 40, 30, 3, true, None);
+ let jpeg = stream(&doc, photo).raw.to_vec();
+ let mut picture = filtered(&["LZWDecode", "DCTDecode"], lzw(&jpeg, &Params::default()));
+ picture.dict.set(b"DecodeParms".to_vec(), Object::Array(vec![Object::Null, Object::Null]));
+ let pic = doc.add(Object::Stream(picture));
+ // An ASCII85 layer over LZW with a PNG predictor: the predictor's parameters move to the one
+ // Flate filter left, without EarlyChange.
+ let rows: Vec<u8> = (0..40 * 30).map(|i| (i % 40 * 3 + i / 40) as u8).collect();
+ let png = Params { predictor: 12, columns: 40, early_change: 0, ..Params::default() };
+ let mut predicted = filtered(&["ASCII85Decode", "LZWDecode"], ascii85(&lzw(&rows, &png)));
+ predicted.dict.set(b"DecodeParms".to_vec(), Object::Array(vec![Object::Null, Object::Dict(decode_parms(&png))]));
+ let pred = doc.add(Object::Stream(predicted));
+ let r = optimize(&mut doc, &clean_up_only()).unwrap();
+ assert_eq!(r.lzw_streams, 3, "{r:?}");
+ let after = stream(&doc, pred);
+ assert_eq!(after.dict.get(b"Filter"), Some(&Object::name("FlateDecode")));
+ let parms = after.dict.get(b"DecodeParms").and_then(Object::as_dict).cloned().unwrap();
+ assert_eq!((parms.int(b"Predictor"), parms.int(b"Columns"), parms.contains(b"EarlyChange")), (Some(12), Some(40), false));
+ assert_eq!(after.decoded_strict().unwrap(), rows);
+ let after = stream(&doc, c);
+ assert_eq!(after.dict.get(b"Filter"), Some(&Object::name("FlateDecode")));
+ assert_eq!(after.decoded_strict().unwrap(), ops);
+ let after = stream(&doc, pic);
+ assert_eq!(after.dict.get(b"Filter"), Some(&Object::Array(vec![Object::name("FlateDecode"), Object::name("DCTDecode")])));
+ assert!(!after.dict.contains(b"DecodeParms"), "all null: dropped");
+ let inside = pdfcraft_filters::decode(&[(Filter::Flate, Params::default())], &after.raw, 1 << 20).unwrap();
+ assert_eq!(inside, jpeg, "the JPEG bytes are kept exactly");
+}
+
+#[test]
+fn lzw_streams_that_cannot_be_read_or_are_not_asked_for_stay_unchanged() {
+ let ops = lzw_ops();
+ let good = lzw(&ops, &Params::default());
+ // 9-bit codes 511 after a literal: past the table, corrupt.
+ let corrupt = vec![0x80, 0x0F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF];
+ assert!(filtered(&["LZWDecode"], corrupt.clone()).decoded_strict().is_err());
+ let mut bad_predictor = filtered(&["LZWDecode"], good.clone());
+ let mut parms = Dict::new();
+ parms.set(b"Predictor".to_vec(), Object::Int(12));
+ parms.set(b"Columns".to_vec(), Object::Int(7));
+ bad_predictor.dict.set(b"DecodeParms".to_vec(), Object::Dict(parms));
+ let mut indirect_parms = filtered(&["LZWDecode"], good.clone());
+ indirect_parms.dict.set(b"DecodeParms".to_vec(), Object::Ref(ObjRef { num: 999, generation: 0 }));
+ // Columns the reader can't take as an integer: read as the default 1 here, so the data is
+ // predicted with one column and decodes, but a viewer resolving the value would use another.
+ let one_column = Params { predictor: 12, ..Params::default() };
+ let odd_columns = |columns: Object| {
+ let mut s = filtered(&["LZWDecode"], lzw(&ops, &one_column));
+ let mut parms = Dict::new();
+ parms.set(b"Predictor".to_vec(), Object::Int(12));
+ parms.set(b"Columns".to_vec(), columns);
+ s.dict.set(b"DecodeParms".to_vec(), Object::Dict(parms));
+ s
+ };
+ assert_eq!(odd_columns(Object::Real(12.5)).decoded_strict().unwrap(), ops, "read with one column");
+ let mut objstm = filtered(&["LZWDecode"], good.clone());
+ objstm.dict.set(b"Type".to_vec(), Object::name("ObjStm"));
+ let mut external = filtered(&["LZWDecode"], good.clone());
+ external.dict.set(b"F".to_vec(), Object::String(pdfcraft_cos::PdfString::literal(b"data.bin".to_vec())));
+ let cases = [
+ ("corrupt LZW", filtered(&["LZWDecode"], corrupt), Settings::default()),
+ ("corrupt under a PNG predictor", bad_predictor, Settings::default()),
+ ("indirect DecodeParms", indirect_parms, Settings::default()),
+ ("external file", external, Settings::default()),
+ ("object stream, rewritten on save", objstm, Settings::default()),
+ ("Columns by reference", odd_columns(Object::Ref(ObjRef { num: 9, generation: 0 })), Settings::default()),
+ ("Columns not an integer", odd_columns(Object::Real(12.5)), Settings::default()),
+ ("crypt filter", filtered(&["Crypt", "LZWDecode"], good.clone()), Settings::default()),
+ ("option off", filtered(&["LZWDecode"], good.clone()), Settings { lzw_to_flate: false, ..Settings::default() }),
+ ];
+ for (label, s, settings) in cases {
+ let (mut doc, c) = with_content(s.clone());
+ let r = optimize(&mut doc, &settings).unwrap();
+ assert_eq!(r.lzw_streams, 0, "{label}");
+ assert_eq!(stream(&doc, c), s, "{label}");
+ }
+ // The same data, readable and asked for, is converted: the cases above fail for their reason.
+ let (mut doc, c) = with_content(filtered(&["LZWDecode"], good));
+ assert_eq!(optimize(&mut doc, &Settings::default()).unwrap().lzw_streams, 1);
+ assert_eq!(stream(&doc, c).decoded_strict().unwrap(), ops);
+}
diff --git a/crates/organize/src/attachments.rs b/crates/organize/src/attachments.rs
new file mode 100644
index 0000000..b0bf222
--- /dev/null
+++ b/crates/organize/src/attachments.rs
@@ -0,0 +1,166 @@
+//! Document-level file attachments (Acrobat: Edit ▸ Attach file; the Attachments panel): the
+//! `/Names /EmbeddedFiles` name tree of file specifications, each with its embedded stream.
+//!
+//! A FileAttachment annotation (a paper clip on a page) is a comment and lives in the annot
+//! crate; this is the document level only.
+
+use pdfcraft_cos::{Dict, Document, Object, PdfString, Stream};
+
+use crate::OrganizeError;
+use crate::import::{name_tree_entries, set_attachments};
+
+/// The keys of the document-level attachments, in name-tree order.
+pub fn attachment_keys(doc: &Document) -> Vec<String> {
+ entries(doc).into_iter().map(|(k, _)| PdfString::literal(k).to_text()).collect()
+}
+
+/// Attach `bytes` to the document under `name` (a file name; any folder part is dropped). The
+/// name tree's key is the name, made unique with " (2)", " (3)"… when it is already taken, and
+/// is returned so the caller can find the attachment again. `date` is a PDF date string for the
+/// embedded file's `/ModDate`; `mime` its `/Subtype` when known.
+pub fn add_attachment(
+ doc: &mut Document,
+ name: &str,
+ bytes: &[u8],
+ description: Option<&str>,
+ mime: Option<&str>,
+ date: Option<&str>,
+) -> Result<String, OrganizeError> {
+ let name = file_name(name);
+ if name.is_empty() {
+ return Err(OrganizeError::Invalid("the attachment needs a file name".into()));
+ }
+ let mut all = entries(doc);
+ let taken: Vec<String> = all.iter().map(|(k, _)| PdfString::literal(k.clone()).to_text()).collect();
+ let mut key = name.clone();
+ let mut n = 2;
+ while taken.contains(&key) {
+ key = format!("{name} ({n})");
+ n += 1;
+ }
+
+ let mut params = Dict::new();
+ params.set(b"Size".to_vec(), Object::Int(bytes.len() as i64));
+ if let Some(d) = date {
+ params.set(b"ModDate".to_vec(), Object::String(PdfString::literal(d.as_bytes().to_vec())));
+ }
+ let mut ef = Dict::new();
+ ef.set(b"Type".to_vec(), Object::name("EmbeddedFile"));
+ if let Some(m) = mime.map(str::trim).filter(|m| !m.is_empty()) {
+ ef.set(b"Subtype".to_vec(), Object::Name(m.as_bytes().to_vec()));
+ }
+ ef.set(b"Params".to_vec(), Object::Dict(params));
+ let stream = doc.add(Object::Stream(Stream::flate(ef, bytes)));
+
+ let mut spec = Dict::new();
+ spec.set(b"Type".to_vec(), Object::name("Filespec"));
+ spec.set(b"F".to_vec(), Object::String(PdfString::text(&key)));
+ spec.set(b"UF".to_vec(), Object::String(PdfString::text(&key)));
+ if let Some(d) = description.map(str::trim).filter(|d| !d.is_empty()) {
+ spec.set(b"Desc".to_vec(), Object::String(PdfString::text(d)));
+ }
+ let mut files = Dict::new();
+ files.set(b"F".to_vec(), Object::Ref(stream));
+ files.set(b"UF".to_vec(), Object::Ref(stream));
+ spec.set(b"EF".to_vec(), Object::Dict(files));
+ let spec = doc.add(spec);
+
+ all.push((PdfString::text(&key).bytes, Object::Ref(spec)));
+ set_attachments(doc, all)?;
+ Ok(key)
+}
+
+/// Remove the document-level attachment whose name-tree key is `key`. The embedded stream is
+/// left for the writer's garbage collection, as with every other removal.
+pub fn delete_attachment(doc: &mut Document, key: &str) -> Result<(), OrganizeError> {
+ let mut all = entries(doc);
+ let before = all.len();
+ all.retain(|(k, _)| PdfString::literal(k.clone()).to_text() != key);
+ if all.len() == before {
+ return Err(OrganizeError::Invalid(format!("there is no attachment named {key}")));
+ }
+ if all.is_empty() { clear_embedded_files(doc) } else { set_attachments(doc, all) }
+}
+
+/// The `/EmbeddedFiles` entries (key, file specification), in tree order.
+fn entries(doc: &Document) -> Vec<(Vec<u8>, Object)> {
+ let Some(tree) = doc
+ .root()
+ .and_then(|r| doc.get(r).as_dict().cloned())
+ .and_then(|c| c.get(b"Names").map(|n| doc.resolve(n)))
+ .and_then(|n| n.as_dict().and_then(|d| d.get(b"EmbeddedFiles").cloned()))
+ else {
+ return Vec::new();
+ };
+ let mut out = Vec::new();
+ name_tree_entries(doc, &tree, 0, &mut std::collections::HashSet::new(), &mut out);
+ out
+}
+
+/// Drop `/EmbeddedFiles` from the catalog's `/Names` (and `/Names` itself when nothing is left).
+fn clear_embedded_files(doc: &mut Document) -> Result<(), OrganizeError> {
+ let root = doc.root().ok_or(OrganizeError::NoPageTree)?;
+ let names = doc.get(root).as_dict().and_then(|c| c.get(b"Names").cloned());
+ match names {
+ Some(Object::Ref(r)) => {
+ let mut empty = false;
+ doc.update_dict(r, |n| {
+ n.remove(b"EmbeddedFiles");
+ empty = n.is_empty();
+ })?;
+ if empty {
+ doc.update_dict(root, |c| {
+ c.remove(b"Names");
+ })?;
+ }
+ }
+ Some(Object::Dict(mut n)) => {
+ n.remove(b"EmbeddedFiles");
+ doc.update_dict(root, |c| {
+ if n.is_empty() {
+ c.remove(b"Names");
+ } else {
+ c.set(b"Names".to_vec(), Object::Dict(n));
+ }
+ })?;
+ }
+ _ => {}
+ }
+ Ok(())
+}
+
+/// The last path component of `name`, trimmed: a dragged-in path or a folder part never becomes
+/// the attachment's name.
+fn file_name(name: &str) -> String {
+ name.rsplit(['/', '\\']).next().unwrap_or(name).trim().to_string()
+}
+
+/// A media type from the file's extension, for the embedded file's `/Subtype`; `None` when it
+/// is not one of the common kinds (the attachment is still fine without it).
+pub fn mime_for_name(name: &str) -> Option<&'static str> {
+ let ext = name.rsplit_once('.').map(|(_, e)| e.to_ascii_lowercase())?;
+ Some(match ext.as_str() {
+ "pdf" => "application/pdf",
+ "txt" | "log" | "md" => "text/plain",
+ "csv" => "text/csv",
+ "htm" | "html" => "text/html",
+ "xml" => "text/xml",
+ "json" => "application/json",
+ "zip" => "application/zip",
+ "png" => "image/png",
+ "jpg" | "jpeg" => "image/jpeg",
+ "gif" => "image/gif",
+ "tif" | "tiff" => "image/tiff",
+ "svg" => "image/svg+xml",
+ "doc" => "application/msword",
+ "docx" => "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
+ "xls" => "application/vnd.ms-excel",
+ "xlsx" => "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
+ "ppt" => "application/vnd.ms-powerpoint",
+ "pptx" => "application/vnd.openxmlformats-officedocument.presentationml.presentation",
+ "rtf" => "application/rtf",
+ "eml" => "message/rfc822",
+ "msg" => "application/vnd.ms-outlook",
+ _ => return None,
+ })
+}
diff --git a/crates/organize/src/import.rs b/crates/organize/src/import.rs
index 1162a81..ef11f10 100644
--- a/crates/organize/src/import.rs
+++ b/crates/organize/src/import.rs
@@ -34,6 +34,37 @@ const SKIP_ON_ANNOT: &[&[u8]] = &[b"StructParent", b"P"];
/// objects, each shallow enough for the parser, would otherwise exhaust the stack (#1800).
const MAX_COPY_DEPTH: usize = 256;
+/// Keys that stay on the widget when a combined field/widget is split (#1810): the annotation's
+/// appearance, placement and page. Field state (name, value, flags, default appearance) moves to
+/// the new parent field, where the widgets inherit it.
+const WIDGET_KEYS: &[&[u8]] = &[
+ b"Type",
+ b"Subtype",
+ b"Rect",
+ b"P",
+ b"AP",
+ b"AS",
+ b"MK",
+ b"BS",
+ b"Border",
+ b"C",
+ b"CA",
+ b"F",
+ b"H",
+ b"R",
+ b"NM",
+ b"M",
+ b"StructParent",
+ b"StructParents",
+ b"OC",
+ b"Tabs",
+ b"A",
+ b"Contents",
+ b"BM",
+ b"Lang",
+ b"AF",
+];
+
struct Copier<'a> {
src: &'a Document,
/// Current recursion depth, bounded by [`MAX_COPY_DEPTH`].
@@ -404,27 +435,33 @@ fn import_pages_mapped(
let r = dst.add(Object::Null);
let c = copier.copy_value(dst, &resolved, Some(r))?;
dst.set(r, c);
- // `/Kids` may be an array object of its own: add to it there, so the
- // field keeps its other widgets.
- match dst.get(copied).as_dict().and_then(|f| f.get(b"Kids").cloned()) {
- Some(Object::Ref(list)) => {
- let mut kids = dst.get(list).as_array().cloned().unwrap_or_default();
- kids.push(Object::Ref(r));
- dst.set(list, Object::Array(kids));
- }
- _ => dst.update_dict(copied, |f| {
- let mut kids = f.get(b"Kids").and_then(|k| k.as_array()).cloned().unwrap_or_default();
- kids.push(Object::Ref(r));
- f.set(b"Kids".to_vec(), Object::Array(kids));
- })?,
- }
+ add_kid(dst, copied, r)?;
annot_pages.insert(r, new);
out.push(Object::Ref(r));
continue;
}
- // A widget that is its own field (no parent to hang a second widget on) stays
- // the one object, shown on both pages, so the field stays one.
+ // A widget that is its own field (no parent to hang a second widget on): on
+ // its first copy it is split into a parent field and a widget child (#1810);
+ // every later copy of the page gets one more widget child of that field, so
+ // the pages no longer share one widget whose `/P` names only the last page.
let own_field = resolved.as_dict().is_some_and(|d| d.name(b"Subtype") == Some(b"Widget") && !d.contains(b"Parent"));
+ if own_field
+ && let Some(first) = a.as_ref().and_then(|r| copier.map.get(&r).copied())
+ && let Some(parent) = dst.get(first).as_dict().and_then(|d| d.reference(b"Parent"))
+ {
+ let r = dst.add(Object::Null);
+ let c = copier.copy_value(dst, &resolved, Some(r))?;
+ let Object::Dict(d) = c else { continue };
+ let (_, mut d) = field_and_widget(dst, &d);
+ d.set(b"Parent".to_vec(), Object::Ref(parent));
+ // The new widget is not a field root of its own.
+ copier.fields.retain(|f| *f != r);
+ dst.set(r, Object::Dict(d));
+ add_kid(dst, parent, r)?;
+ annot_pages.insert(r, new);
+ out.push(Object::Ref(r));
+ continue;
+ }
let annots = if own_field { &mut copier } else { own.as_mut().unwrap_or(&mut copier) };
// Direct (inline) annotation dictionaries become indirect objects, so every
// copied annotation can be fixed up the same way.
@@ -438,6 +475,9 @@ fn import_pages_mapped(
}
_ => continue,
};
+ if own_field && copier.fields.contains(&r) {
+ split_own_field(dst, &mut copier.fields, r);
+ }
annot_pages.insert(r, new);
out.push(Object::Ref(r));
}
@@ -570,7 +610,7 @@ fn name_tree_lookup(src: &Document, node: &Object, key: &[u8], depth: u8, seen:
}
/// All (key, value) pairs of a name tree, in order, each node read once.
-fn name_tree_entries(src: &Document, node: &Object, depth: u8, seen: &mut HashSet<ObjRef>, out: &mut Vec<(Vec<u8>, Object)>) {
+pub(crate) fn name_tree_entries(src: &Document, node: &Object, depth: u8, seen: &mut HashSet<ObjRef>, out: &mut Vec<(Vec<u8>, Object)>) {
if depth > 32 || node.as_ref().is_some_and(|r| !seen.insert(r)) {
return;
}
@@ -834,6 +874,73 @@ fn qualified_optional(prefix: &str, name: &str) -> String {
if name.is_empty() { prefix.to_string() } else { qualified(prefix, name) }
}
+/// Add `kid` to `field`'s `/Kids`, in the array object itself when `/Kids` is one, so the field
+/// keeps its other widgets.
+fn add_kid(dst: &mut Document, field: ObjRef, kid: ObjRef) -> Result<(), OrganizeError> {
+ match dst.get(field).as_dict().and_then(|f| f.get(b"Kids").cloned()) {
+ Some(Object::Ref(list)) => {
+ let mut kids = dst.get(list).as_array().cloned().unwrap_or_default();
+ kids.push(Object::Ref(kid));
+ dst.set(list, Object::Array(kids));
+ }
+ _ => dst.update_dict(field, |f| {
+ let mut kids = f.get(b"Kids").and_then(|k| k.as_array()).cloned().unwrap_or_default();
+ kids.push(Object::Ref(kid));
+ f.set(b"Kids".to_vec(), Object::Array(kids));
+ })?,
+ }
+ Ok(())
+}
+
+/// PdfCraft patch (#1810): split a widget that doubles as its own field into a parent field
+/// holding the field keys (name, value, flags…) and a widget child holding the annotation keys
+/// (rectangle, appearance, page). The parent takes the widget's place among the top-level fields;
+/// later copies of the page add widget children of it, so every page has its own widget and the
+/// field stays one.
+fn split_own_field(dst: &mut Document, fields: &mut [ObjRef], widget: ObjRef) {
+ let Some(d) = dst.get(widget).as_dict().cloned() else { return };
+ let (mut field, mut child) = field_and_widget(dst, &d);
+ let parent = dst.add(Object::Null);
+ field.set(b"Kids".to_vec(), Object::Array(vec![Object::Ref(widget)]));
+ child.set(b"Parent".to_vec(), Object::Ref(parent));
+ dst.set(parent, Object::Dict(field));
+ dst.set(widget, Object::Dict(child));
+ if let Some(entry) = fields.iter_mut().find(|f| **f == widget) {
+ *entry = parent;
+ }
+}
+
+/// A combined field/widget has two additional-action namespaces (ISO 32000-1 tables 194/196).
+/// Partition them as well as the ordinary entries, including when copying a later widget.
+fn field_and_widget(doc: &Document, d: &Dict) -> (Dict, Dict) {
+ let (mut field, mut child) = (Dict::new(), Dict::new());
+ for (k, v) in d.iter() {
+ if k.as_slice() == b"AA"
+ && let Some(actions) = doc.resolve(v).as_dict().cloned()
+ {
+ let (mut field_actions, mut widget_actions) = (Dict::new(), Dict::new());
+ for (trigger, action) in actions.iter() {
+ if [b"E".as_slice(), b"X", b"D", b"U", b"Fo", b"Bl", b"PO", b"PC", b"PV", b"PI"].contains(&trigger.as_slice()) {
+ widget_actions.set(trigger.clone(), action.clone());
+ } else {
+ field_actions.set(trigger.clone(), action.clone());
+ }
+ }
+ if field_actions.iter().next().is_some() {
+ field.set(k.clone(), Object::Dict(field_actions));
+ }
+ if widget_actions.iter().next().is_some() {
+ child.set(k.clone(), Object::Dict(widget_actions));
+ }
+ } else if WIDGET_KEYS.contains(&k.as_slice()) {
+ child.set(k.clone(), v.clone());
+ } else {
+ field.set(k.clone(), v.clone());
+ }
+ }
+ (field, child)
+}
+
/// Add top-level fields to the destination's `/AcroForm /Fields` (creating the form if needed).
fn register_fields(dst: &mut Document, fields: &[ObjRef]) -> Result<(), OrganizeError> {
if fields.is_empty() {
@@ -868,12 +975,26 @@ fn register_fields(dst: &mut Document, fields: &[ObjRef]) -> Result<(), Organize
/// A new document containing copies of `pages` from `src` (Extract Pages / Split).
/// Document information (title, author…) is carried over, and so is the print standard the
-/// source declares (PDF/X: its output intents and identification, #263).
+/// source declares (PDF/X: its output intents and identification, #263), and the bookmarks that
+/// go to the copied pages.
pub fn extract_pages(src: &Document, pages: &[usize]) -> Result<Document, OrganizeError> {
let mut out = Document::new_empty();
// One source: nothing to deduplicate. Its fields keep their names (a source with two
// same-named field roots stays one field, as it was), so Extract and Split never rename.
let imported = import_pages_mapped(&mut out, src, pages, 0, FieldConflicts::Merge)?;
+ // The bookmarks of these pages come along, mapped to the copies (#4020).
+ let outline = kept_bookmarks(source_outline(src, imported.page_map));
+ if !outline.is_empty() {
+ let root = crate::outline::container(&mut out, &[])?;
+ if let Some((first, last, _)) = write_outline_level(&mut out, root, &outline)? {
+ out.update_dict(root, |d| {
+ d.set(b"First".to_vec(), Object::Ref(first));
+ d.set(b"Last".to_vec(), Object::Ref(last));
+ })?;
+ let top = crate::outline::children(&out, root);
+ crate::outline::relink_and_recount(&mut out, root, &top)?;
+ }
+ }
for key in crate::INFO_KEYS {
if let Some(v) = crate::info(src, key) {
crate::set_info(&mut out, key, &v)?;
@@ -1178,18 +1299,24 @@ fn collect_attachments(dst: &mut Document, src: &Document, out: &mut Vec<(Vec<u8
}
/// Write attachments as a flat, sorted `/EmbeddedFiles` name tree; duplicate names get " (2)"…
-fn set_attachments(dst: &mut Document, mut entries: Vec<(Vec<u8>, Object)>) -> Result<(), OrganizeError> {
+pub(crate) fn set_attachments(dst: &mut Document, mut entries: Vec<(Vec<u8>, Object)>) -> Result<(), OrganizeError> {
if entries.is_empty() {
return Ok(());
}
+ // Names are compared and numbered as text: a key written as UTF-16 (a name with an accent
+ // or Chinese letters) must not get ASCII bytes appended to it.
let mut seen = std::collections::HashSet::new();
for (k, _) in entries.iter_mut() {
- let base = k.clone();
+ let base = pdfcraft_cos::PdfString::literal(k.clone()).to_text();
+ let mut text = base.clone();
let mut n = 2;
- while !seen.insert(k.clone()) {
- *k = [base.as_slice(), format!(" ({n})").as_bytes()].concat();
+ while !seen.insert(text.clone()) {
+ text = format!("{base} ({n})");
n += 1;
}
+ if text != base {
+ *k = pdfcraft_cos::PdfString::text(&text).bytes;
+ }
}
entries.sort_by(|a, b| a.0.cmp(&b.0));
let mut names = Vec::new();
@@ -1201,6 +1328,14 @@ fn set_attachments(dst: &mut Document, mut entries: Vec<(Vec<u8>, Object)>) -> R
tree.set(b"Names".to_vec(), Object::Array(names));
let tree = dst.add(tree);
let root = dst.root().ok_or(OrganizeError::NoPageTree)?;
+ // `/Names` may be an indirect dictionary (Acrobat writes it so): update it where it is, so
+ // its other trees (/Dests, /JavaScript…) stay.
+ if let Some(Object::Ref(names)) = dst.get(root).as_dict().and_then(|c| c.get(b"Names").cloned())
+ && dst.get(names).as_dict().is_some()
+ {
+ dst.update_dict(names, |n| n.set(b"EmbeddedFiles".to_vec(), Object::Ref(tree)))?;
+ return Ok(());
+ }
dst.update_dict(root, |c| {
let mut n = match c.get(b"Names") {
Some(Object::Dict(d)) => d.clone(),
@@ -1245,6 +1380,18 @@ fn source_outline(src: &Document, pages: HashMap<ObjRef, ObjRef>) -> Vec<Outline
outline_level(&mapper, first, 0, &mut budget)
}
+/// `nodes` without the bookmarks whose page was not copied (no destination left), unless a bookmark
+/// under them stays. [`outline_level`] already bounds the depth.
+fn kept_bookmarks(nodes: Vec<OutlineNode>) -> Vec<OutlineNode> {
+ nodes
+ .into_iter()
+ .filter_map(|mut n| {
+ n.children = kept_bookmarks(n.children);
+ (n.dest.is_some() || !n.children.is_empty()).then_some(n)
+ })
+ .collect()
+}
+
/// One level of bookmarks from `first` (its siblings), each with its children. Cycle- and size-safe:
/// at most `budget` bookmarks are read in all, and nesting stops at 32 levels.
fn outline_level(m: &Copier<'_>, first: Option<ObjRef>, depth: u8, budget: &mut usize) -> Vec<OutlineNode> {
diff --git a/crates/organize/src/lib.rs b/crates/organize/src/lib.rs
index d0e088f..e24056a 100644
--- a/crates/organize/src/lib.rs
+++ b/crates/organize/src/lib.rs
@@ -13,6 +13,7 @@
use pdfcraft_cos::{Dict, Document, ObjRef, Object, PdfString, XrefEntry};
+mod attachments;
mod boxes;
mod dedupe;
mod import;
@@ -24,6 +25,7 @@ mod transition;
pub mod view;
mod xmp;
+pub use attachments::{add_attachment, attachment_keys, delete_attachment, mime_for_name};
pub use boxes::{BoxSpec, PageBox, page_boxes, set_page_box};
pub use dedupe::dedupe_resources;
pub use import::{
@@ -34,7 +36,7 @@ pub use import::{
pub use labels::{LabelRange, LabelStyle, PageLabels, number_pages, page_label_ranges, page_labels, set_page_label_ranges};
pub use outline::{
Bookmark, BookmarkPage, OutlineEntry, OutlineError, add_bookmark, add_bookmark_at, add_bookmark_tree, bookmark_page, bookmarks, delete_bookmark,
- move_bookmark, rename_bookmark, set_bookmark_open, set_bookmark_page, top_level_bookmarks,
+ move_bookmark, rename_bookmark, set_bookmark_color, set_bookmark_open, set_bookmark_page, set_bookmark_style, top_level_bookmarks,
};
pub use transition::{TRANSITION_DIRECTIONS, TRANSITION_STYLES, Transition, TransitionSpec, set_transition};
pub use view::{InitialView, displays_doc_title, initial_view, set_initial_view};
@@ -658,10 +660,21 @@ pub fn check_custom_key(name: &str) -> Result<(), OrganizeError> {
Ok(())
}
-/// Read a document-information entry as text.
+/// Read a document-information entry as text: `/Info`, else the XMP packet (Title, Author,
+/// Subject, Keywords, Creator and Producer, see `xmp`).
pub fn info(doc: &Document, key: &str) -> Option<String> {
- let info = doc.trailer().get(b"Info").map(|o| doc.resolve(o))?;
- info.as_dict()?.get(key.as_bytes()).and_then(|v| doc.resolve(v).as_string().map(|s| s.to_text()))
+ let in_info = doc
+ .trailer()
+ .get(b"Info")
+ .map(|o| doc.resolve(o))
+ .and_then(|info| info.as_dict()?.get(key.as_bytes()).and_then(|v| doc.resolve(v).as_string().map(|s| s.to_text())));
+ // Files that state it only in their XMP packet (#2373).
+ in_info.filter(|v| !v.trim_matches('\0').trim().is_empty()).or_else(|| xmp::info_value(doc, key))
+}
+
+/// Whether the document information has an entry `key`, of any type.
+pub fn has_info(doc: &Document, key: &str) -> bool {
+ doc.trailer().get(b"Info").map(|o| doc.resolve(o)).is_some_and(|info| info.as_dict().is_some_and(|d| d.get(key.as_bytes()).is_some()))
}
/// Set (or clear, with an empty value) a document-information entry.
@@ -691,12 +704,18 @@ fn set_info_entry(doc: &mut Document, key: &[u8], entry: Option<Object>) -> Resu
})?;
}
_ => {
- let Some(v) = entry else { return Ok(()) };
let mut d = match doc.trailer().get(b"Info") {
Some(Object::Dict(d)) => d.clone(),
_ => Dict::new(),
};
- d.set(key.to_vec(), v);
+ match entry {
+ Some(v) => d.set(key.to_vec(), v),
+ None => {
+ if d.remove(key).is_none() {
+ return Ok(());
+ }
+ }
+ }
let r = doc.add(d);
doc.trailer_mut().set(b"Info".to_vec(), Object::Ref(r));
}
diff --git a/crates/organize/src/outline.rs b/crates/organize/src/outline.rs
index 39e601d..cc1bbb0 100644
--- a/crates/organize/src/outline.rs
+++ b/crates/organize/src/outline.rs
@@ -41,6 +41,13 @@ pub struct Bookmark {
/// Where on that page it goes: the destination's type (`XYZ`, `Fit`, `FitH`…) and the numbers
/// after it, in PDF user space (`None` for `null` or anything that isn't a number).
pub view: Option<(Vec<u8>, Vec<Option<f64>>)>,
+ /// The title's colour (`/C`, DeviceRGB, ISO 32000-2 §12.3.3 Table 151), each component kept
+ /// within 0–1; `None` for the default black or a value that isn't three numbers. The
+ /// inspector's `OutlineItem::color` reads it the same way.
+ pub color: Option<[f32; 3]>,
+ /// The title's style (`/F`, Table 152): bit 1 italic, bit 2 bold.
+ pub italic: bool,
+ pub bold: bool,
}
/// One page of the outline listing (see [`bookmark_page`]).
@@ -61,6 +68,8 @@ pub enum OutlineError {
EmptyTitle,
#[error("a bookmark's position must be a finite number")]
BadPosition,
+ #[error("a bookmark's colour must be three numbers from 0 to 1")]
+ BadColor,
#[error("this document has no tagged headings to make bookmarks from")]
NoEntries,
#[error("{0}")]
@@ -306,7 +315,19 @@ fn describe(doc: &Document, targets: &mut Targets, obj: ObjRef, path: Vec<usize>
};
let page = dest.as_deref().and_then(|d| page_of_explicit(targets, d));
let view = dest.as_deref().filter(|_| page.is_some()).and_then(|d| view_of_explicit(doc, d));
- Bookmark { obj, path, title, open, page, view }
+ let color = item.as_dict().and_then(|d| d.get(b"C").map(|c| doc.resolve(c))).and_then(|c| title_color(doc, &c));
+ let flags = item.as_dict().and_then(|d| d.get(b"F").and_then(|f| doc.resolve(f).as_int())).unwrap_or(0);
+ Bookmark { obj, path, title, open, page, view, color, italic: flags & 1 != 0, bold: flags & 2 != 0 }
+}
+
+/// A bookmark title's `/C` as a colour: three numbers, each kept within 0–1 (ISO 32000-2
+/// §12.3.3, Table 151: "An array of three numbers in the range 0.0 to 1.0"); a number past the
+/// range, however large, is kept at its edge. Black, the default, and anything else give `None`.
+fn title_color(doc: &Document, c: &Object) -> Option<[f32; 3]> {
+ let [r, g, b] = c.as_array()?.as_slice() else { return None };
+ let channel = |v: &Object| doc.resolve(v).as_f64().map(|v| v.clamp(0.0, 1.0) as f32);
+ let rgb = [channel(r)?, channel(g)?, channel(b)?];
+ (rgb != [0.0; 3]).then_some(rgb)
}
/// Lists up to `limit` bookmarks from position `offset`, entering no level deeper than `max_depth`.
@@ -532,10 +553,7 @@ pub fn add_bookmark_at(
let at = index.min(kids.len());
kids.insert(at, item);
relink(doc, parent, &kids)?;
- // Show the new bookmark: open its parent (the root is always open).
- if !parent_path.is_empty() && doc.get(parent).as_dict().and_then(|d| d.int(b"Count")).is_none_or(|c| c <= 0) {
- put(doc, parent, b"Count", Some(Object::Int(1)))?;
- }
+ show_children(doc, parent, parent_path)?;
recount(doc)?;
let mut path = parent_path.to_vec();
path.push(at);
@@ -612,6 +630,33 @@ pub fn rename_bookmark(doc: &mut Document, path: &[usize], title: &str) -> Resul
put(doc, r, b"Title", Some(Object::String(PdfString::text(title))))
}
+/// Set the colour of a bookmark's title (`/C`, ISO 32000-2 §12.3.3, Table 151: "An array of three
+/// numbers in the range 0.0 to 1.0, representing the components in the DeviceRGB colour space").
+/// Black, the default, and `None` remove `/C`; a component outside 0–1 is refused.
+pub fn set_bookmark_color(doc: &mut Document, path: &[usize], color: Option<[f64; 3]>) -> Result<()> {
+ if color.is_some_and(|c| !c.iter().all(|v| (0.0..=1.0).contains(v))) {
+ return Err(OutlineError::BadColor);
+ }
+ let (r, _) = resolve_path(doc, path)?;
+ let value = color.filter(|c| *c != [0.0; 3]).map(|c| Object::Array(c.iter().map(|v| Object::Real(*v)).collect()));
+ put(doc, r, b"C", value)
+}
+
+/// Make a bookmark's title bold or italic or not (`/F`, ISO 32000-2 §12.3.3, Table 152: bit 1
+/// italic, bit 2 bold); `None` keeps that one as it is, and so are the other bits. When no bit is
+/// left, `/F` is removed, its default being 0.
+pub fn set_bookmark_style(doc: &mut Document, path: &[usize], bold: Option<bool>, italic: Option<bool>) -> Result<()> {
+ let (r, _) = resolve_path(doc, path)?;
+ let old = doc.get(r).as_dict().and_then(|d| d.get(b"F").and_then(|f| doc.resolve(f).as_int())).unwrap_or(0);
+ let bit = |flags: i64, mask: i64, on: Option<bool>| match on {
+ Some(true) => flags | mask,
+ Some(false) => flags & !mask,
+ None => flags,
+ };
+ let flags = bit(bit(old, 1, italic), 2, bold);
+ put(doc, r, b"F", (flags != 0).then_some(Object::Int(flags)))
+}
+
/// Point a bookmark at `page` (0-based), replacing its destination or GoTo action.
pub fn set_bookmark_page(doc: &mut Document, path: &[usize], page: usize) -> Result<()> {
let dest = destination(doc, page)?;
@@ -651,11 +696,23 @@ pub fn move_bookmark(doc: &mut Document, from: &[usize], to_parent: &[usize], in
let at = index.min(kids.len());
kids.insert(at, r);
relink(doc, parent, &kids)?;
+ if parent != old_parent {
+ show_children(doc, parent, &to_parent)?;
+ }
recount(doc)?;
to_parent.push(at);
Ok(to_parent)
}
+/// Open `parent` so a bookmark just added or moved into it shows (the root is always open).
+/// Only the sign of `/Count` matters here: [`recount`] sets its value.
+fn show_children(doc: &mut Document, parent: ObjRef, parent_path: &[usize]) -> Result<()> {
+ if !parent_path.is_empty() && doc.get(parent).as_dict().and_then(|d| d.int(b"Count")).is_none_or(|c| c <= 0) {
+ put(doc, parent, b"Count", Some(Object::Int(1)))?;
+ }
+ Ok(())
+}
+
/// Expand or collapse a bookmark that has children.
pub fn set_bookmark_open(doc: &mut Document, path: &[usize], open: bool) -> Result<()> {
let (r, _) = resolve_path(doc, path)?;
diff --git a/crates/organize/src/tests.rs b/crates/organize/src/tests.rs
index 9ce1284..1ba8861 100644
--- a/crates/organize/src/tests.rs
+++ b/crates/organize/src/tests.rs
@@ -528,6 +528,29 @@ fn custom_document_properties_are_listed_set_removed_and_their_names_checked() {
assert!(custom_info(&doc).is_empty());
}
+/// An `/Info` dictionary written directly in the trailer: a cleared entry is removed, and the
+/// other entries are kept.
+#[test]
+fn document_info_entries_are_cleared_from_an_info_dictionary_in_the_trailer() {
+ let b = build(
+ &[
+ "<< /Type /Catalog /Pages 2 0 R >>".into(),
+ "<< /Type /Pages /Kids [3 0 R] /Count 1 >>".into(),
+ "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Contents 4 0 R >>".into(),
+ body("X"),
+ ],
+ "/Root 1 0 R /Info << /Title (Report) /Project (Apollo) /Revision (7) >>",
+ );
+ let mut doc = open(b);
+ set_info(&mut doc, "Missing", "").unwrap();
+ assert!(matches!(doc.trailer().get(b"Info"), Some(Object::Dict(_))), "clearing an absent entry changes nothing");
+ set_info(&mut doc, "Project", "").unwrap();
+ set_info(&mut doc, "Title", "").unwrap();
+ let doc = save_and_reopen(&doc);
+ assert_eq!(custom_info(&doc), [("Revision".to_string(), "7".to_string())]);
+ assert_eq!(info(&doc, "Title"), None);
+}
+
/// Padding is not part of a custom value, in any mix of NULs and whitespace, a value that is only
/// padding is not listed, and such entries don't count towards the 256 listed: a real property
/// after 300 blank ones is still there.
@@ -628,6 +651,43 @@ fn document_info_edits_update_the_xmp_packet() {
assert_eq!((dict.name(b"Type"), dict.name(b"Subtype"), dict.get(b"Filter")), (Some(&b"Metadata"[..]), Some(&b"XML"[..]), None));
}
+/// A file that states its title, author and so on only in XMP (PDF 2.0 deprecates `/Info`) shows
+/// them in Document Properties (#2373); `/Info` wins where it has a value.
+#[test]
+fn document_info_falls_back_to_the_xmp_packet() {
+ let xmp = LIBREOFFICE_XMP
+ .replace(
+ "<rdf:li xml:lang=\"x-default\">Untitled 1</rdf:li>",
+ "<rdf:li xml:lang=\"de\">Bericht</rdf:li><rdf:li xml:lang=\"x-default\">Report &amp; &#x201C;notes&#8221;</rdf:li>",
+ )
+ .replace("<rdf:li>Old Author</rdf:li>", "<rdf:li>Ada</rdf:li>\n<rdf:li>Grace</rdf:li>")
+ .replace("<pdf:Producer>Writer 1.0</pdf:Producer>", "<pdf:Producer>Writer 1.0</pdf:Producer><pdf:Keywords/>");
+ let mut doc = doc_with_xmp(xmp.as_bytes());
+ // Both: /Info's own values, XMP for what /Info lacks.
+ assert_eq!(info(&doc, "Title").as_deref(), Some("Untitled 1"));
+ assert_eq!(info(&doc, "Subject").as_deref(), Some("Old subject"));
+ // XMP only.
+ doc.trailer_mut().remove(b"Info");
+ let doc = full_roundtrip(&doc);
+ assert_eq!(info(&doc, "Title").as_deref(), Some("Report & \u{201C}notes\u{201D}"));
+ assert_eq!(info(&doc, "Author").as_deref(), Some("Ada; Grace"));
+ assert_eq!(info(&doc, "Subject").as_deref(), Some("Old subject"));
+ assert_eq!(info(&doc, "Producer").as_deref(), Some("Writer 1.0"));
+ assert_eq!(info(&doc, "Keywords"), None, "an empty property is no value");
+ assert_eq!(info(&doc, "Rating"), None, "no XMP counterpart");
+ // The attribute form, and a packet that isn't UTF-8 is not read.
+ let attrs = "<x:xmpmeta xmlns:x=\"adobe:ns:meta/\"><rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\">\
+ <rdf:Description rdf:about=\"\" xmlns:pdf=\"http://ns.adobe.com/pdf/1.3/\" pdf:Keywords='a, b &amp; c'/></rdf:RDF></x:xmpmeta>";
+ let mut doc = doc_with_xmp(attrs.as_bytes());
+ doc.trailer_mut().remove(b"Info");
+ assert_eq!(info(&doc, "Keywords").as_deref(), Some("a, b & c"));
+ let mut latin1 = LIBREOFFICE_XMP.as_bytes().to_vec();
+ latin1.extend_from_slice(b"<!-- \xE9 -->");
+ let mut doc = doc_with_xmp(&latin1);
+ doc.trailer_mut().remove(b"Info");
+ assert_eq!(info(&doc, "Subject"), None);
+}
+
#[test]
fn document_info_edits_leave_files_without_usable_xmp_alone() {
// No packet: none is added.
@@ -931,9 +991,111 @@ fn links_are_rewired_to_copied_pages_or_dropped() {
assert!(!link.contains(b"Dest") && !link.contains(b"A"));
}
-/// A widget annotation that is its own form field (no `/Parent`).
-fn own_field(doc: &Document, r: ObjRef) -> bool {
- doc.get(r).as_dict().is_some_and(|d| d.name(b"Subtype") == Some(b"Widget") && !d.contains(b"Parent"))
+/// Issue #1810: a widget that is its own field was shared between both copies of a repeated
+/// page, so only the last page could identify it (its `/P`), and per-page annotation edits were
+/// impossible. Each copy must get its own widget sharing one parent field (name and value).
+#[test]
+fn repeated_page_splits_a_combined_field_widget() {
+ let out = full_roundtrip(&extract_pages(&doc_a(), &[1, 1]).unwrap());
+ let ps = pages(&out).unwrap();
+ let widget = |i: usize| -> ObjRef {
+ let list = page_dict(&out, i).get(b"Annots").map(|a| out.resolve(a).as_array().cloned().unwrap_or_default()).unwrap_or_default();
+ list.iter()
+ .filter_map(|a| a.as_ref())
+ .find(|r| out.get(*r).as_dict().is_some_and(|d| d.name(b"Subtype") == Some(b"Widget")))
+ .expect("a widget annotation")
+ };
+ let (w1, w2) = (widget(0), widget(1));
+ assert_ne!(w1, w2, "each copy of the page has its own widget");
+ for (i, w) in [(0, w1), (1, w2)] {
+ let d = out.get(w).as_dict().unwrap().clone();
+ for key in [b"T".as_slice(), b"V", b"FT"] {
+ assert!(!d.contains(key), "a widget inherits field entries: {key:?}");
+ }
+ assert_eq!(d.reference(b"P"), Some(ps[i].obj), "/P names the page holding the widget");
+ let parent = d.reference(b"Parent").expect("the widget has a parent field");
+ let f = out.get(parent).as_dict().unwrap().clone();
+ assert_eq!(f.get(b"T").and_then(|v| v.as_string()).map(|s| s.to_text()).as_deref(), Some("name"));
+ assert_eq!(f.get(b"V").and_then(|v| v.as_string()).map(|s| s.to_text()).as_deref(), Some("Ada"));
+ let kids: Vec<ObjRef> =
+ f.get(b"Kids").and_then(|k| out.resolve(k).as_array().cloned()).unwrap_or_default().iter().filter_map(|k| k.as_ref()).collect();
+ assert!(kids.contains(&w1) && kids.contains(&w2), "one field holds both widgets: {kids:?}");
+ let fields: Vec<ObjRef> = catalog(&out)
+ .get(b"AcroForm")
+ .map(|f| out.resolve(f))
+ .and_then(|f| f.as_dict().cloned())
+ .and_then(|f| f.get(b"Fields").map(|x| out.resolve(x)))
+ .and_then(|f| f.as_array().cloned())
+ .unwrap_or_default()
+ .iter()
+ .filter_map(|f| f.as_ref())
+ .collect();
+ assert_eq!(fields, [parent], "the parent is the one top-level field");
+ }
+}
+
+#[test]
+fn splitting_a_combined_widget_keeps_annotation_actions_and_field_triggers() {
+ let mut src = doc_a();
+ let page = pages(&src).unwrap()[1].obj;
+ let list = page_dict(&src, 1).get(b"Annots").and_then(|a| a.as_array()).cloned().unwrap();
+ let widget =
+ list.iter().filter_map(Object::as_ref).find(|r| src.get(*r).as_dict().is_some_and(|d| d.name(b"Subtype") == Some(b"Widget"))).unwrap();
+ let mut action = Dict::new();
+ action.set(b"S".to_vec(), Object::name("GoTo"));
+ action.set(b"D".to_vec(), Object::Array(vec![Object::Ref(page), Object::name("Fit")]));
+ let mut named = Dict::new();
+ named.set(b"S".to_vec(), Object::name("Named"));
+ named.set(b"N".to_vec(), Object::name("NextPage"));
+ let mut aa = Dict::new();
+ aa.set(b"E".to_vec(), Object::Dict(named.clone()));
+ aa.set(b"K".to_vec(), Object::Dict(named));
+ let aa = src.add(Object::Dict(aa));
+ src.update_dict(widget, |d| {
+ d.set(b"A".to_vec(), Object::Dict(action));
+ d.set(b"AA".to_vec(), Object::Ref(aa));
+ })
+ .unwrap();
+ let out = full_roundtrip(&extract_pages(&src, &[1, 1]).unwrap());
+ let ps = pages(&out).unwrap();
+ for i in 0..2 {
+ let w = annots(&out, i).into_iter().find(|d| d.name(b"Subtype") == Some(b"Widget")).unwrap();
+ let action = out.resolve(w.get(b"A").expect("the widget keeps its action"));
+ let dest = action.as_dict().unwrap().get(b"D").and_then(|a| a.as_array()).unwrap()[0].as_ref().unwrap();
+ assert!(ps.iter().any(|p| p.obj == dest), "the action targets a copied page");
+ let waa = out.resolve(w.get(b"AA").expect("widget triggers"));
+ assert!(waa.as_dict().unwrap().contains(b"E"));
+ assert!(!waa.as_dict().unwrap().contains(b"K"));
+ let parent = out.get(w.reference(b"Parent").unwrap()).as_dict().unwrap().clone();
+ assert!(!parent.contains(b"A"));
+ let faa = out.resolve(parent.get(b"AA").expect("field triggers"));
+ assert!(faa.as_dict().unwrap().contains(b"K"));
+ assert!(!faa.as_dict().unwrap().contains(b"E"));
+ }
+}
+
+#[test]
+fn splitting_a_combined_widget_keeps_its_annotation_only_keys() {
+ let mut src = doc_a();
+ let list = page_dict(&src, 1).get(b"Annots").and_then(|a| a.as_array()).cloned().unwrap();
+ let widget =
+ list.iter().filter_map(Object::as_ref).find(|r| src.get(*r).as_dict().is_some_and(|d| d.name(b"Subtype") == Some(b"Widget"))).unwrap();
+ src.update_dict(widget, |d| {
+ d.set(b"Contents".to_vec(), Object::String(PdfString::text("alt text")));
+ d.set(b"BM".to_vec(), Object::name("Multiply"));
+ d.set(b"Lang".to_vec(), Object::String(PdfString::text("en-US")));
+ d.set(b"AF".to_vec(), Object::Array(Vec::new()));
+ })
+ .unwrap();
+ let out = full_roundtrip(&extract_pages(&src, &[1, 1]).unwrap());
+ for i in 0..2 {
+ let w = annots(&out, i).into_iter().find(|d| d.name(b"Subtype") == Some(b"Widget")).unwrap();
+ let parent = out.get(w.reference(b"Parent").unwrap()).as_dict().unwrap().clone();
+ for key in [b"Contents".as_slice(), b"BM", b"Lang", b"AF"] {
+ assert!(w.contains(key), "the widget keeps {key:?}");
+ assert!(!parent.contains(key), "the parent field does not take {key:?}");
+ }
+ }
}
#[test]
@@ -949,15 +1111,11 @@ fn repeated_page_gets_independent_annotations() {
assert!(!refs[i].is_empty());
assert_eq!(refs[i].len(), refs[i + 1].len());
for (a, b) in refs[i].iter().zip(&refs[i + 1]) {
- // A widget that is its own field stays one object on both pages, so the field stays
- // one (#790); every other annotation is copied.
- if !own_field(&out, *a) {
- assert_ne!(a, b, "each copy of the page has its own annotation objects");
- }
+ assert_ne!(a, b, "each copy of the page has its own annotation objects");
}
}
for (i, list) in refs.iter().enumerate() {
- for a in list.iter().filter(|a| !own_field(&out, **a)) {
+ for a in list.iter() {
assert_eq!(out.get(*a).as_dict().unwrap().reference(b"P"), Some(ps[i].obj), "/P names the page holding the copy");
}
}
@@ -978,7 +1136,32 @@ fn form_fields_come_along_and_are_registered() {
assert_eq!(fields.len(), 1);
let field = out.resolve(&fields[0]).as_dict().cloned().unwrap();
assert_eq!(field.get(b"V").and_then(|v| v.as_string()).map(|s| s.to_text()).as_deref(), Some("Ada"));
- assert_eq!(field.reference(b"P"), Some(pages(&out).unwrap()[0].obj));
+ // The widget child, not the field, names the page (#1810).
+ let kid =
+ field.get(b"Kids").map(|k| out.resolve(k)).and_then(|k| k.as_array().cloned()).and_then(|k| k.first().and_then(|k| k.as_ref())).unwrap();
+ assert_eq!(out.get(kid).as_dict().unwrap().reference(b"P"), Some(pages(&out).unwrap()[0].obj));
+}
+
+/// #4020: Extract keeps the bookmarks that go to the pages it copies, mapped to the copies. One whose
+/// page was left out goes, unless a bookmark under it stays.
+#[test]
+fn extract_keeps_the_bookmarks_of_the_pages_it_copies() {
+ let mut src = doc_a();
+ crate::add_bookmark(&mut src, &[], 0, "One", 0).unwrap();
+ crate::add_bookmark(&mut src, &[], 1, "Two", 1).unwrap();
+ crate::add_bookmark(&mut src, &[1], 0, "Two.a", 2).unwrap();
+ crate::add_bookmark(&mut src, &[], 2, "Three", 2).unwrap();
+ let marks = |d: &Document| -> Vec<(String, usize, Option<usize>)> { bookmarks(d).into_iter().map(|b| (b.title, b.path.len(), b.page)).collect() };
+ let s = |t: &str| t.to_string();
+
+ let all = full_roundtrip(&extract_pages(&src, &[0, 1, 2]).unwrap());
+ assert_eq!(marks(&all), [(s("One"), 1, Some(0)), (s("Two"), 1, Some(1)), (s("Two.a"), 2, Some(2)), (s("Three"), 1, Some(2))]);
+
+ let last = full_roundtrip(&extract_pages(&src, &[2]).unwrap());
+ assert_eq!(marks(&last), [(s("Two"), 1, None), (s("Two.a"), 2, Some(0)), (s("Three"), 1, Some(0))], "One's page was left out");
+
+ let none = full_roundtrip(&extract_pages(&doc_a(), &[0]).unwrap());
+ assert!(!none.get(none.root().unwrap()).as_dict().unwrap().contains(b"Outlines"), "no bookmarks, no outline");
}
#[test]
@@ -1565,6 +1748,18 @@ fn bookmarks_add_rename_move_delete() {
assert_eq!(crate::move_bookmark(&mut d, &[0], &[2], 9).unwrap(), vec![1, 1]);
assert_eq!(titles(&crate::bookmarks(&d)), ["Intro", "Results[Table,Figure 1]"]);
assert_eq!(crate::move_bookmark(&mut d, &[1], &[1, 0], 0), Err(crate::OutlineError::IntoItself));
+ // Into a bookmark with no children yet (Indent): it opens, so the moved one shows.
+ assert_eq!(crate::move_bookmark(&mut d, &[1, 1], &[0], 0).unwrap(), vec![0, 0]);
+ let intro = crate::bookmarks(&d)[0].obj;
+ assert_eq!(count_of(&d, intro), Some(1));
+ // Reordering inside a closed parent leaves it closed.
+ crate::add_bookmark(&mut d, &[0], 1, "Second", 0).unwrap();
+ crate::set_bookmark_open(&mut d, &[0], false).unwrap();
+ crate::move_bookmark(&mut d, &[0, 1], &[0], 0).unwrap();
+ assert_eq!(count_of(&d, intro), Some(-2));
+ crate::delete_bookmark(&mut d, &[0, 0]).unwrap();
+ crate::move_bookmark(&mut d, &[0, 0], &[1], 9).unwrap();
+ assert_eq!(titles(&crate::bookmarks(&d)), ["Intro", "Results[Table,Figure 1]"]);
crate::delete_bookmark(&mut d, &[1, 0]).unwrap();
assert_eq!(titles(&crate::bookmarks(&d)), ["Intro", "Results[Figure 1]"]);
@@ -1692,7 +1887,7 @@ fn outline_with(items: &[&str]) -> Document {
format!("<< /Type /Outlines /First 5 0 R /Count {} >>", items.len()),
"<< /Type /Page /Parent 2 0 R >>".into(),
];
- b.extend(items.iter().map(|s| s.to_string()));
+ b.extend(items.iter().map(ToString::to_string));
open(build(&b, "/Root 1 0 R"))
}
@@ -2232,6 +2427,46 @@ fn initial_view_round_trips_and_keeps_scripts() {
assert!(crate::set_initial_view(&mut doc, &crate::InitialView { page: 9, ..Default::default() }).is_err());
}
+#[test]
+fn an_unchanged_opening_destination_keeps_its_position_and_name() {
+ use crate::view::{Magnification, Navigation};
+ let page2 = Object::Ref(pdfcraft_cos::ObjRef::new(5, 0));
+ let xyz = Object::Array(vec![page2.clone(), Object::name("XYZ"), Object::Int(100), Object::Int(500), Object::Int(2)]);
+ let mut named = pdfcraft_cos::Dict::new();
+ named.set(b"S".to_vec(), Object::name("GoTo"));
+ named.set(b"D".to_vec(), Object::name("there"));
+ let mut dests = pdfcraft_cos::Dict::new();
+ dests.set(b"there".to_vec(), Object::Array(vec![page2, Object::name("Fit")]));
+ let mut prefs = pdfcraft_cos::Dict::new();
+ prefs.set(b"NonFullScreenPageMode".to_vec(), Object::name("UseOutlines"));
+ for action in [xyz, Object::Dict(named)] {
+ let mut doc = open(fixture());
+ let root = doc.root().unwrap();
+ doc.update_dict(root, |c| {
+ c.set(b"OpenAction".to_vec(), action.clone());
+ c.set(b"Dests".to_vec(), Object::Dict(dests.clone()));
+ c.set(b"PageMode".to_vec(), Object::name("FullScreen"));
+ c.set(b"ViewerPreferences".to_vec(), Object::Dict(prefs.clone()));
+ })
+ .unwrap();
+ // Another option changes: the opening action is written back as it was, and so is the
+ // full-screen panel, which the dialog doesn't edit.
+ let v = crate::initial_view(&doc);
+ assert_eq!(v.non_full_screen, Navigation::Bookmarks);
+ crate::set_initial_view(&mut doc, &crate::InitialView { hide_toolbar: true, ..v.clone() }).unwrap();
+ let catalog = doc.get(root).as_dict().cloned().unwrap();
+ assert_eq!(catalog.get(b"OpenAction"), Some(&action));
+ let doc = save_and_reopen(&doc);
+ assert_eq!(crate::initial_view(&doc), crate::InitialView { hide_toolbar: true, ..v.clone() });
+ // A changed magnification writes a destination of its own.
+ let mut doc = doc;
+ crate::set_initial_view(&mut doc, &crate::InitialView { magnification: Magnification::FitPage, ..v }).unwrap();
+ let catalog = doc.get(root).as_dict().cloned().unwrap();
+ assert_ne!(catalog.get(b"OpenAction"), Some(&action));
+ assert_eq!(crate::initial_view(&doc).magnification, Magnification::FitPage);
+ }
+}
+
// ── Split / Extract keep only the resources the part draws (#204) ──────────────────────────────
/// A content stream with no text operators (an image draw).
@@ -2850,8 +3085,9 @@ fn import_renames_a_field_colliding_with_another_incoming_field() {
assert_eq!(form_field_names(&dst), ["Other", "Text1", "Text1-1"]);
}
-/// A page listed twice shows its widget on both copies — also when the field was renamed: both
-/// pages' widgets belong to the one renamed field, and no second Text1 appears.
+/// A page listed twice shows its widget on both copies — also when the field was renamed: each
+/// copy has its own widget, both widgets belong to the one renamed field (#1810), and no second
+/// Text1 appears.
#[test]
fn a_repeated_page_joins_the_renamed_field() {
let mut dst = doc_with_field("Text1");
@@ -2868,10 +3104,14 @@ fn a_repeated_page_joins_the_renamed_field() {
.and_then(|l| l.as_array().cloned())
.unwrap();
let renamed = fields[1].clone();
+ let mut widgets = Vec::new();
for page in [1, 2] {
let list = page_dict(&dst, page).get(b"Annots").map(|a| dst.resolve(a)).and_then(|a| a.as_array().cloned()).unwrap();
- assert!(list.contains(&renamed), "page {page}'s widget belongs to the renamed field");
+ let widget = list.iter().find_map(|a| a.as_ref()).expect("a widget on the page");
+ widgets.push(widget);
+ assert_eq!(dst.get(widget).as_dict().unwrap().reference(b"Parent"), renamed.as_ref(), "page {page}'s widget belongs to the renamed field");
}
+ assert_ne!(widgets[0], widgets[1], "each copy has its own widget");
}
/// Combining forms keeps same-named fields separate — the second file's colliding field is
@@ -3040,6 +3280,87 @@ fn a_refused_import_takes_back_what_it_added_wherever_it_is_numbered() {
assert!(run.is_ok(), "a refused import must leave the document as it was, without panicking");
}
+/// What Edit ▸ Attach file added survives Combine files (upstream's writer), names
+/// with accents included, and the combined document takes more attachments and deletions.
+#[test]
+fn attachments_added_in_the_app_survive_combine_and_more_can_be_attached() {
+ let embedded = |doc: &Document, key: &str| -> (Vec<u8>, Option<String>) {
+ let names = doc.resolve(catalog(doc).get(b"Names").unwrap()).as_dict().cloned().unwrap();
+ let tree = doc.resolve(names.get(b"EmbeddedFiles").unwrap()).as_dict().cloned().unwrap();
+ let pairs = tree.get(b"Names").and_then(|n| n.as_array()).cloned().unwrap();
+ let at = pairs.chunks(2).position(|p| p[0].as_string().unwrap().to_text() == key).unwrap_or_else(|| panic!("no attachment {key}"));
+ let spec = doc.resolve(&pairs[at * 2 + 1]).as_dict().cloned().unwrap();
+ let desc = spec.get(b"Desc").and_then(Object::as_string).map(|s| s.to_text());
+ let ef = spec.get(b"EF").and_then(Object::as_dict).unwrap().get(b"F").cloned().unwrap();
+ let Object::Stream(stream) = doc.resolve(&ef).as_ref().clone() else { panic!("the embedded file is a stream") };
+ (stream.decoded().unwrap(), desc)
+ };
+ let mut a = Document::open(Arc::new(fixture())).unwrap();
+ add_attachment(&mut a, "invoice.csv", b"a,b", Some("March"), Some("text/csv"), None).unwrap();
+ add_attachment(&mut a, "año.txt", b"uno", None, None, None).unwrap();
+ let mut b = Document::open(Arc::new(fixture())).unwrap();
+ add_attachment(&mut b, "invoice.csv", b"x,y", None, None, None).unwrap();
+ add_attachment(&mut b, "año.txt", b"dos", None, None, None).unwrap();
+ let a = save_and_reopen(&a);
+ let b = save_and_reopen(&b);
+ let mut out = full_roundtrip(&combine(&[("A", &a), ("B", &b)]).unwrap());
+ // Both files' attachments, the second copies numbered as text (not bytes glued onto UTF-16).
+ assert_eq!(attachment_keys(&out), ["invoice.csv", "invoice.csv (2)", "año.txt", "año.txt (2)"]);
+ assert_eq!(embedded(&out, "invoice.csv"), (b"a,b".to_vec(), Some("March".into())));
+ assert_eq!(embedded(&out, "invoice.csv (2)"), (b"x,y".to_vec(), None));
+ assert_eq!(embedded(&out, "año.txt (2)").0, b"dos");
+ // The combined document goes on taking attachments, and losing them, like any other.
+ assert_eq!(add_attachment(&mut out, "invoice.csv", b"z", None, None, None).unwrap(), "invoice.csv (3)");
+ delete_attachment(&mut out, "invoice.csv (2)").unwrap();
+ let out = full_roundtrip(&out);
+ assert_eq!(attachment_keys(&out), ["invoice.csv", "invoice.csv (3)", "año.txt", "año.txt (2)"]);
+ assert_eq!(embedded(&out, "invoice.csv (3)").0, b"z");
+}
+
+#[test]
+fn attachments_are_added_listed_and_deleted() {
+ let mut doc = Document::open(Arc::new(fixture())).unwrap();
+ assert!(attachment_keys(&doc).is_empty());
+ // A path loses its folder; the key is the file name.
+ let key = add_attachment(&mut doc, "/Users/eva/Desktop/invoice.csv", b"a,b\n1,2\n", Some("March"), Some("text/csv"), Some("D:20261012120000Z"))
+ .unwrap();
+ assert_eq!(key, "invoice.csv");
+ // The same name again is kept apart.
+ assert_eq!(add_attachment(&mut doc, "invoice.csv", b"x", None, None, None).unwrap(), "invoice.csv (2)");
+ assert_eq!(add_attachment(&mut doc, " ", b"x", None, None, None), Err(OrganizeError::Invalid("the attachment needs a file name".into())));
+ let doc = save_and_reopen(&doc);
+ assert_eq!(attachment_keys(&doc), ["invoice.csv", "invoice.csv (2)"]);
+ // What was written: a Filespec with the embedded stream, its size and type, and the description.
+ let root = doc.root().unwrap();
+ let names = doc.get(root).as_dict().unwrap().get(b"Names").cloned().unwrap();
+ let tree = doc.resolve(&names).as_dict().unwrap().get(b"EmbeddedFiles").cloned().unwrap();
+ let tree = doc.resolve(&tree);
+ let pairs = tree.as_dict().unwrap().get(b"Names").cloned().unwrap();
+ let pairs = doc.resolve(&pairs).as_array().cloned().unwrap();
+ assert_eq!(pairs.len(), 4);
+ let spec = doc.resolve(&pairs[1]);
+ let spec = spec.as_dict().unwrap();
+ assert_eq!(spec.get(b"Type"), Some(&Object::name("Filespec")));
+ assert_eq!(spec.get(b"UF").and_then(Object::as_string).map(PdfString::to_text).as_deref(), Some("invoice.csv"));
+ assert_eq!(spec.get(b"Desc").and_then(Object::as_string).map(PdfString::to_text).as_deref(), Some("March"));
+ let ef = spec.get(b"EF").and_then(Object::as_dict).unwrap().get(b"F").cloned().unwrap();
+ let ef = doc.resolve(&ef);
+ let Object::Stream(stream) = ef.as_ref() else { panic!("the embedded file is a stream") };
+ assert_eq!(stream.dict.get(b"Subtype"), Some(&Object::Name(b"text/csv".to_vec())));
+ let params = stream.dict.get(b"Params").and_then(Object::as_dict).unwrap();
+ assert_eq!(params.get(b"Size"), Some(&Object::Int(8)));
+ assert_eq!(stream.decoded().unwrap(), b"a,b\n1,2\n");
+ // Deleting: the one named goes, the other stays; the last one takes the tree with it.
+ let mut doc = doc;
+ delete_attachment(&mut doc, "invoice.csv").unwrap();
+ assert_eq!(attachment_keys(&doc), ["invoice.csv (2)"]);
+ assert_eq!(delete_attachment(&mut doc, "invoice.csv"), Err(OrganizeError::Invalid("there is no attachment named invoice.csv".into())));
+ delete_attachment(&mut doc, "invoice.csv (2)").unwrap();
+ let doc = save_and_reopen(&doc);
+ assert!(attachment_keys(&doc).is_empty());
+ assert!(doc.get(doc.root().unwrap()).as_dict().unwrap().get(b"Names").is_none());
+}
+
#[test]
fn rotate_repeated_indices_accumulate_from_the_current_page_value() {
for level in 0..3 {
@@ -3286,3 +3607,84 @@ fn repeated_content_references_share_one_decode_budget() {
assert!(len <= pdfcraft_cos::MAX_PAGE_DECODED + 300, "{len} bytes");
}
}
+
+/// #3193: the bookmark list reads a bookmark's colour and style as the inspector does (ISO
+/// 32000-2 §12.3.3, Tables 151 and 152): `/C` within 0–1, black and malformed values as none,
+/// `/F` bit 1 italic and bit 2 bold, through indirect values too.
+#[test]
+fn bookmarks_report_their_colour_and_style() {
+ let mut objs: Vec<String> = vec![
+ "<< /Type /Catalog /Pages 2 0 R /Outlines 4 0 R >>".into(),
+ "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 200 400] >>".into(),
+ "<< /Type /Page /Parent 2 0 R >>".into(),
+ "<< /Type /Outlines /First 5 0 R /Last 10 0 R /Count 6 >>".into(),
+ ];
+ objs.push("<< /Title (Plain) /Parent 4 0 R /Next 6 0 R /Dest [3 0 R /Fit] >>".into()); // 5
+ objs.push("<< /Title (Red bold) /Parent 4 0 R /Prev 5 0 R /Next 7 0 R /Dest [3 0 R /Fit] /C [1 0 0] /F 2 >>".into()); // 6
+ objs.push("<< /Title (Indirect) /Parent 4 0 R /Prev 6 0 R /Next 8 0 R /Dest [3 0 R /Fit] /C 11 0 R /F 12 0 R >>".into()); // 7
+ objs.push("<< /Title (Black) /Parent 4 0 R /Prev 7 0 R /Next 9 0 R /Dest [3 0 R /Fit] /C [0 0 0] /F 1 >>".into()); // 8
+ objs.push("<< /Title (Bright) /Parent 4 0 R /Prev 8 0 R /Next 10 0 R /Dest [3 0 R /Fit] /C [2 -1 0.5] >>".into()); // 9
+ objs.push("<< /Title (Short) /Parent 4 0 R /Prev 9 0 R /Dest [3 0 R /Fit] /C [1 0] /F 4 >>".into()); // 10
+ objs.push("[0 0.5 0]".into()); // 11
+ objs.push("3".into()); // 12
+ let doc = open(build(&objs, "/Root 1 0 R"));
+ let got: Vec<(String, Option<[f32; 3]>, bool, bool)> = bookmarks(&doc).into_iter().map(|b| (b.title, b.color, b.italic, b.bold)).collect();
+ assert_eq!(
+ got,
+ [
+ ("Plain".into(), None, false, false),
+ ("Red bold".into(), Some([1.0, 0.0, 0.0]), false, true),
+ ("Indirect".into(), Some([0.0, 0.5, 0.0]), true, true),
+ ("Black".into(), None, true, false),
+ ("Bright".into(), Some([1.0, 0.0, 0.5]), false, false),
+ ("Short".into(), None, false, false),
+ ]
+ );
+}
+
+/// #3193: setting a bookmark's style and colour writes what ISO 32000-2 §12.3.3 asks for: bold is
+/// `/F 2` and bold italic `/F 3` (Table 152), and neither removes `/F`, whose default is 0; a
+/// style change leaves `/C` alone and a colour change leaves `/F`; black, the default (Table 151),
+/// removes `/C`. Bits the table doesn't define are kept, and a colour outside 0–1 is refused.
+#[test]
+fn bookmark_style_and_colour_are_set_as_the_table_says() {
+ let mut objs: Vec<String> = vec![
+ "<< /Type /Catalog /Pages 2 0 R /Outlines 4 0 R >>".into(),
+ "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 200 400] >>".into(),
+ "<< /Type /Page /Parent 2 0 R >>".into(),
+ "<< /Type /Outlines /First 5 0 R /Last 6 0 R /Count 2 >>".into(),
+ ];
+ objs.push("<< /Title (Plain) /Parent 4 0 R /Next 6 0 R /Dest [3 0 R /Fit] >>".into()); // 5
+ objs.push("<< /Title (Odd bits) /Parent 4 0 R /Prev 5 0 R /Dest [3 0 R /Fit] /F 4 /C [1 0 0] >>".into()); // 6
+ let mut doc = open(build(&objs, "/Root 1 0 R"));
+ let raw = |doc: &Document, n: u32, key: &[u8]| doc.get(ObjRef { num: n, generation: 0 }).as_dict().and_then(|d| d.get(key).cloned());
+ crate::set_bookmark_style(&mut doc, &[0], Some(true), None).unwrap();
+ assert_eq!(raw(&doc, 5, b"F"), Some(Object::Int(2)), "bold");
+ crate::set_bookmark_style(&mut doc, &[0], None, Some(true)).unwrap();
+ assert_eq!(raw(&doc, 5, b"F"), Some(Object::Int(3)), "bold italic");
+ crate::set_bookmark_color(&mut doc, &[0], Some([0.0, 0.5, 0.0])).unwrap();
+ assert_eq!(raw(&doc, 5, b"C"), Some(Object::Array(vec![Object::Real(0.0), Object::Real(0.5), Object::Real(0.0)])));
+ assert_eq!(raw(&doc, 5, b"F"), Some(Object::Int(3)), "a colour change keeps the style");
+ crate::set_bookmark_style(&mut doc, &[0], Some(false), Some(false)).unwrap();
+ assert_eq!(raw(&doc, 5, b"F"), None, "regular removes /F");
+ assert!(raw(&doc, 5, b"C").is_some(), "a style change keeps the colour");
+ crate::set_bookmark_color(&mut doc, &[0], Some([0.0; 3])).unwrap();
+ assert_eq!(raw(&doc, 5, b"C"), None, "black removes /C");
+
+ crate::set_bookmark_style(&mut doc, &[1], Some(true), None).unwrap();
+ assert_eq!(raw(&doc, 6, b"F"), Some(Object::Int(6)), "bold beside a bit the table doesn't define");
+ crate::set_bookmark_style(&mut doc, &[1], Some(false), Some(false)).unwrap();
+ assert_eq!(raw(&doc, 6, b"F"), Some(Object::Int(4)), "that bit stays");
+ crate::set_bookmark_color(&mut doc, &[1], None).unwrap();
+ assert_eq!(raw(&doc, 6, b"C"), None, "no colour is black");
+ for bad in [[1.5, 0.0, 0.0], [0.0, -0.1, 0.0], [f64::NAN, 0.0, 0.0]] {
+ assert_eq!(crate::set_bookmark_color(&mut doc, &[1], Some(bad)), Err(crate::OutlineError::BadColor), "{bad:?}");
+ }
+ assert_eq!(crate::set_bookmark_style(&mut doc, &[7], Some(true), None), Err(crate::OutlineError::NoSuchBookmark(vec![7])));
+
+ crate::set_bookmark_style(&mut doc, &[0], Some(true), Some(true)).unwrap();
+ crate::set_bookmark_color(&mut doc, &[0], Some([0.0, 0.0, 1.0])).unwrap();
+ let saved = open(write_full(&doc, &SaveOptions::default()).unwrap());
+ let got: Vec<_> = bookmarks(&saved).into_iter().map(|b| (b.color, b.bold, b.italic)).collect();
+ assert_eq!(got, [(Some([0.0, 0.0, 1.0]), true, true), (None, false, false)]);
+}
diff --git a/crates/organize/src/view.rs b/crates/organize/src/view.rs
index 0f115d3..b51df1a 100644
--- a/crates/organize/src/view.rs
+++ b/crates/organize/src/view.rs
@@ -63,6 +63,10 @@ pub struct InitialView {
pub language: Option<String>,
/// Right-edge binding (`/Direction /R2L`).
pub right_to_left: bool,
+ /// The navigation panel on leaving full screen (`/ViewerPreferences /NonFullScreenPageMode`,
+ /// ISO 32000-2 Table 147), read only when `full_screen` is set. It is read, not written:
+ /// [`set_initial_view`] leaves the entry as it is.
+ pub non_full_screen: Navigation,
}
fn catalog(doc: &Document) -> Result<(pdfcraft_cos::ObjRef, Dict), OrganizeError> {
@@ -104,6 +108,15 @@ pub fn initial_view(doc: &Document) -> InitialView {
v.hide_toolbar = flag(b"HideToolbar");
v.hide_window_ui = flag(b"HideWindowUI");
v.right_to_left = name(&vp, b"Direction").as_deref() == Some(b"R2L");
+ // Table 147: meaningful only with `/PageMode /FullScreen`, and only these four values.
+ if v.full_screen {
+ v.non_full_screen = match name(&vp, b"NonFullScreenPageMode").as_deref() {
+ Some(b"UseOutlines") => Navigation::Bookmarks,
+ Some(b"UseThumbs") => Navigation::Pages,
+ Some(b"UseOC") => Navigation::Layers,
+ _ => Navigation::PageOnly,
+ };
+ }
}
// The opening destination: an explicit array, or a GoTo action's.
let dest = c.get(b"OpenAction").map(|o| doc.resolve(o)).and_then(|o| match &*o {
@@ -149,8 +162,13 @@ pub fn displays_doc_title(doc: &Document) -> bool {
}
/// Write the initial view. An opening action that isn't a plain destination (a script, say) is
-/// kept unless the page or magnification asks for a destination.
+/// kept unless the page or magnification asks for a destination, and an opening action whose page
+/// and magnification `v` leaves as [`initial_view`] reads them is kept as it is.
pub fn set_initial_view(doc: &mut Document, v: &InitialView) -> Result<(), OrganizeError> {
+ let same_destination = {
+ let now = initial_view(doc);
+ now.page == v.page && now.magnification == v.magnification
+ };
let (root, c) = catalog(doc)?;
let pages = crate::walk(doc)?;
if v.page >= pages.len() {
@@ -238,6 +256,9 @@ pub fn set_initial_view(doc: &mut Document, v: &InitialView) -> Result<(), Organ
}
}
match (&dest, open_action_is_dest) {
+ // The opening page and magnification are as read: the action stays as written, with
+ // its position or named destination (§12.3.2.4) that the view model doesn't hold.
+ _ if same_destination => {}
(Some(d), _) => c.set(b"OpenAction".to_vec(), Object::Array(d.clone())),
(None, true) => {
c.remove(b"OpenAction");
@@ -294,4 +315,40 @@ mod tests {
assert_eq!(flags(initial_view(&doc)), [false; 6]);
}
}
+
+ /// A catalog with `/PageMode page_mode` and `/ViewerPreferences << /NonFullScreenPageMode mode >>`.
+ fn with_modes(page_mode: &str, mode: Object) -> Document {
+ let mut doc = Document::new_empty();
+ let mode = doc.add(mode);
+ let mut preferences = Dict::new();
+ preferences.set(b"NonFullScreenPageMode".to_vec(), Object::Ref(mode));
+ let root = doc.root().unwrap();
+ doc.update_dict(root, |c| {
+ c.set(b"PageMode".to_vec(), Object::name(page_mode));
+ c.set(b"ViewerPreferences".to_vec(), Object::Dict(preferences));
+ })
+ .unwrap();
+ doc
+ }
+
+ #[test]
+ fn non_full_screen_page_mode_is_read_with_full_screen_only() {
+ for (mode, want) in [
+ ("UseOutlines", Navigation::Bookmarks),
+ ("UseThumbs", Navigation::Pages),
+ ("UseOC", Navigation::Layers),
+ ("UseNone", Navigation::PageOnly),
+ // Not a value Table 147 lists.
+ ("UseAttachments", Navigation::PageOnly),
+ ("FullScreen", Navigation::PageOnly),
+ ] {
+ let v = initial_view(&with_modes("FullScreen", Object::name(mode)));
+ assert!(v.full_screen);
+ assert_eq!(v.non_full_screen, want, "{mode}");
+ // Ignored unless the document opens in full screen.
+ let v = initial_view(&with_modes("UseThumbs", Object::name(mode)));
+ assert_eq!((v.navigation, v.non_full_screen), (Navigation::Pages, Navigation::PageOnly), "{mode}");
+ }
+ assert_eq!(initial_view(&with_modes("FullScreen", Object::Int(1))).non_full_screen, Navigation::PageOnly);
+ }
}
diff --git a/crates/organize/src/xmp.rs b/crates/organize/src/xmp.rs
index cc3a78c..5b6f393 100644
--- a/crates/organize/src/xmp.rs
+++ b/crates/organize/src/xmp.rs
@@ -92,6 +92,128 @@ fn edit_packet(doc: &mut Document, edit: impl FnOnce(&str) -> Option<String>) ->
Ok(true)
}
+/// The value the catalog's XMP packet gives the document information key `key`, for files that
+/// state their title, author and so on only there (`/Info` is deprecated in PDF 2.0, and some
+/// writers leave it out). A language alternative gives its `x-default` item (else the first),
+/// several authors are joined with "; ". `None` for keys XMP doesn't mirror, files without XMP,
+/// packets that can't be read safely, and empty values.
+pub(crate) fn info_value(doc: &Document, key: &str) -> Option<String> {
+ let (name, _, shape) = property(key)?;
+ let root = doc.root()?;
+ let r = doc.get(root).as_dict()?.reference(b"Metadata")?;
+ let obj = doc.get(r);
+ let Object::Stream(stream) = &*obj else { return None };
+ let xmp = String::from_utf8(stream.decoded_within(MAX_XMP).ok()?).ok()?;
+ get_property(&xmp, name, shape)
+}
+
+/// The text of the property `name` in `xmp`, element or attribute form (see [`info_value`]).
+fn get_property(xmp: &str, name: &str, shape: Shape) -> Option<String> {
+ let value = if let Some((start, end)) = element_span(xmp, name) {
+ let element = xmp.get(start..end)?;
+ let open_end = element.find('>')?;
+ // `<dc:title/>`: no value.
+ if element.get(..open_end)?.ends_with('/') {
+ return None;
+ }
+ let inner = element.get(open_end + 1..)?.strip_suffix(&format!("</{name}>"))?;
+ let items = list_items(inner);
+ if items.is_empty() {
+ // An empty `<rdf:Alt/>` or `<rdf:Seq></rdf:Seq>` has no value, not its markup.
+ text_value(inner)?
+ } else if shape == Shape::LangAlt {
+ let (_, text) = items.iter().find(|(lang, _)| lang.as_deref() == Some("x-default")).or(items.first())?;
+ text_value(text)?
+ } else {
+ items.iter().filter_map(|(_, text)| text_value(text)).filter(|t| !t.is_empty()).collect::<Vec<_>>().join("; ")
+ }
+ } else {
+ let (_, value_start, value_end, _) = attribute_span(xmp, name)?;
+ unescape(xmp.get(value_start..value_end)?.trim())
+ };
+ Some(value).filter(|v| !v.trim().is_empty())
+}
+
+/// Character data `text` as a value, unescaped; `None` when it still holds markup (a `<`, which
+/// a value escapes as `&lt;`), so a structure the reader doesn't take apart never shows as text.
+fn text_value(text: &str) -> Option<String> {
+ let text = text.trim();
+ (!text.contains('<')).then(|| unescape(text))
+}
+
+/// The `rdf:li` items of a property's content: each one's `xml:lang` (if any) and its text.
+fn list_items(inner: &str) -> Vec<(Option<String>, &str)> {
+ let mut items = Vec::new();
+ let mut rest = inner;
+ while let Some(i) = rest.find("<rdf:li") {
+ let Some(after) = rest.get(i + "<rdf:li".len()..) else { break };
+ // `<rdf:li` must end there: not `<rdf:link`.
+ if !after.starts_with(|c: char| c == '>' || c == '/' || c.is_whitespace()) {
+ rest = after;
+ continue;
+ }
+ let Some(tag_end) = after.find('>') else { break };
+ let tag = after.get(..tag_end).unwrap_or_default();
+ let lang = tag.find("xml:lang=").and_then(|at| {
+ let v = tag.get(at + "xml:lang=".len()..)?;
+ let quote = v.chars().next().filter(|c| matches!(c, '"' | '\''))?;
+ let v = v.get(1..)?;
+ Some(v.get(..v.find(quote)?)?.to_string())
+ });
+ let Some(body) = after.get(tag_end + 1..) else { break };
+ if tag.ends_with('/') {
+ items.push((lang, ""));
+ rest = body;
+ continue;
+ }
+ let Some(close) = body.find("</rdf:li>") else { break };
+ items.push((lang, body.get(..close).unwrap_or_default()));
+ rest = body.get(close..).unwrap_or_default();
+ }
+ items
+}
+
+/// XML text with its character and entity references resolved (an unknown one is kept as is).
+fn unescape(text: &str) -> String {
+ let mut out = String::with_capacity(text.len());
+ let mut rest = text;
+ while let Some(i) = rest.find('&') {
+ out.push_str(rest.get(..i).unwrap_or_default());
+ let after = rest.get(i..).unwrap_or_default();
+ let Some(semi) = after.find(';').filter(|&n| n <= 12) else {
+ out.push('&');
+ rest = after.get(1..).unwrap_or_default();
+ continue;
+ };
+ let entity = after.get(1..semi).unwrap_or_default();
+ let c = match entity {
+ "amp" => Some('&'),
+ "lt" => Some('<'),
+ "gt" => Some('>'),
+ "quot" => Some('"'),
+ "apos" => Some('\''),
+ _ => entity
+ .strip_prefix("#x")
+ .or_else(|| entity.strip_prefix("#X"))
+ .and_then(|h| u32::from_str_radix(h, 16).ok())
+ .or_else(|| entity.strip_prefix('#').and_then(|d| d.parse().ok()))
+ .and_then(char::from_u32),
+ };
+ match c {
+ Some(c) => {
+ out.push(c);
+ rest = after.get(semi + 1..).unwrap_or_default();
+ }
+ None => {
+ out.push('&');
+ rest = after.get(1..).unwrap_or_default();
+ }
+ }
+ }
+ out.push_str(rest);
+ out
+}
+
/// `xmp` with the property `name` (namespace `ns`) set to `value`, or removed when `value` is
/// empty; `None` when nothing changes or the packet has no `rdf:RDF` to add the property to.
fn set_property(xmp: &str, name: &str, ns: &str, shape: Shape, value: &str) -> Option<String> {
@@ -219,6 +341,28 @@ mod tests {
<dc:description><rdf:Alt><rdf:li xml:lang=\"x-default\">Old subject</rdf:li></rdf:Alt></dc:description>\n\
</rdf:Description>\n </rdf:RDF>\n</x:xmpmeta>\n<?xpacket end=\"w\"?>";
+ #[test]
+ fn values_are_read_back_unescaped() {
+ assert_eq!(unescape("a &amp; b &lt;c&gt; &#65;&#x42; &bogus; &#xD800; & end"), "a & b <c> AB &bogus; &#xD800; & end");
+ assert_eq!(get_property(PACKET, "dc:title", Shape::LangAlt).as_deref(), Some("Untitled 1"));
+ assert_eq!(get_property(PACKET, "dc:creator", Shape::Seq).as_deref(), Some("Old Author"));
+ assert_eq!(get_property(PACKET, "pdf:Producer", Shape::Text).as_deref(), Some("Writer 1.0"));
+ assert_eq!(get_property(PACKET, "pdf:Keywords", Shape::Text), None);
+ // No x-default: the first language; empty and self-closed items are skipped.
+ let alt = "<dc:title><rdf:Alt><rdf:li xml:lang='fr'>Rapport</rdf:li><rdf:li xml:lang='en'>Report</rdf:li></rdf:Alt></dc:title>";
+ assert_eq!(get_property(alt, "dc:title", Shape::LangAlt).as_deref(), Some("Rapport"));
+ let seq = "<dc:creator><rdf:Seq><rdf:li/><rdf:li> </rdf:li><rdf:li>Ada</rdf:li></rdf:Seq></dc:creator>";
+ assert_eq!(get_property(seq, "dc:creator", Shape::Seq).as_deref(), Some("Ada"));
+ // Unfinished markup reads as nothing rather than as a wrong value.
+ assert_eq!(get_property("<dc:title><rdf:Alt><rdf:li>Cut", "dc:title", Shape::LangAlt), None);
+ // An empty alternative or list, or an item holding markup, has no value: never the markup.
+ assert_eq!(get_property("<dc:title><rdf:Alt/></dc:title>", "dc:title", Shape::LangAlt), None);
+ assert_eq!(get_property("<dc:title><rdf:Alt></rdf:Alt></dc:title>", "dc:title", Shape::LangAlt), None);
+ assert_eq!(get_property("<dc:creator><rdf:Seq/></dc:creator>", "dc:creator", Shape::Seq), None);
+ let nested = "<dc:creator><rdf:Seq><rdf:li><rdf:Description/></rdf:li><rdf:li>Ada</rdf:li></rdf:Seq></dc:creator>";
+ assert_eq!(get_property(nested, "dc:creator", Shape::Seq).as_deref(), Some("Ada"));
+ }
+
#[test]
fn element_values_are_replaced_in_place() {
let out = set_property(PACKET, "dc:title", DC, Shape::LangAlt, "Guide & <draft>").unwrap();
diff --git a/crates/organize/tests/attachment_names_cleanup.rs b/crates/organize/tests/attachment_names_cleanup.rs
new file mode 100644
index 0000000..b24a461
--- /dev/null
+++ b/crates/organize/tests/attachment_names_cleanup.rs
@@ -0,0 +1,44 @@
+//! Deleting the last document attachment when the catalog's `/Names` is an indirect dictionary
+//! (as some producers write it) must not leave an empty `/Names` behind.
+
+use std::sync::Arc;
+
+use pdfcraft_cos::{Document, Object};
+use pdfcraft_organize::{add_attachment, attachment_keys, delete_attachment};
+
+/// One page, and a catalog whose `/Names` is the indirect (empty) dictionary 4 0 R.
+fn indirect_names_pdf() -> Vec<u8> {
+ let objs: [&[u8]; 4] = [
+ b"<< /Type /Catalog /Pages 2 0 R /Names 4 0 R >>",
+ b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>",
+ b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 100 100] >>",
+ b"<< >>",
+ ];
+ 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", i + 1).as_bytes());
+ out.extend_from_slice(o);
+ out.extend_from_slice(b"\nendobj\n");
+ }
+ let xref = out.len();
+ out.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objs.len() + 1).as_bytes());
+ for o in offsets {
+ out.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes());
+ }
+ out.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objs.len() + 1).as_bytes());
+ out
+}
+
+#[test]
+fn deleting_the_last_attachment_removes_an_indirect_empty_names_dictionary() {
+ let mut doc = Document::open(Arc::new(indirect_names_pdf())).unwrap();
+ let key = add_attachment(&mut doc, "notes.txt", b"hello", None, None, None).unwrap();
+ assert_eq!(attachment_keys(&doc), ["notes.txt"]);
+ delete_attachment(&mut doc, &key).unwrap();
+ assert!(attachment_keys(&doc).is_empty());
+ let root = doc.root().unwrap();
+ let catalog = doc.get(root).as_dict().cloned().unwrap();
+ assert!(catalog.get(b"Names").is_none(), "the catalog keeps no empty /Names: {:?}", catalog.get(b"Names").map(|n| matches!(n, Object::Ref(_))));
+}
diff --git a/crates/platform/src/staging.rs b/crates/platform/src/staging.rs
index f6a98c4..c0e8f99 100644
--- a/crates/platform/src/staging.rs
+++ b/crates/platform/src/staging.rs
@@ -145,7 +145,7 @@ pub fn write_atomically_with(
return Err(std::io::Error::new(std::io::ErrorKind::PermissionDenied, "the file is read-only; save a copy with Save As"));
}
let dir = path.parent().filter(|d| !d.as_os_str().is_empty()).unwrap_or(Path::new("."));
- let name = path.file_name().and_then(|n| n.to_str()).unwrap_or("save");
+ let name = path.file_name().and_then(std::ffi::OsStr::to_str).unwrap_or("save");
// A file that is replaced keeps its permissions (#1790) and group. Unix only: Windows is as before.
#[cfg(unix)]
let keep = std::fs::metadata(path).ok();
diff --git a/crates/preflight/src/xmp.rs b/crates/preflight/src/xmp.rs
index 0da4869..0aaab12 100644
--- a/crates/preflight/src/xmp.rs
+++ b/crates/preflight/src/xmp.rs
@@ -151,7 +151,7 @@ fn esc(s: &str) -> String {
/// A PDF date (`D:YYYYMMDDHHmmSSOHH'mm'`) as an XMP (ISO 8601) date.
pub fn iso_date(pdf: &str) -> Option<String> {
let d = pdf.trim().trim_start_matches("D:");
- let digits: String = d.chars().take_while(|c| c.is_ascii_digit()).collect();
+ let digits: String = d.chars().take_while(char::is_ascii_digit).collect();
if digits.len() < 4 {
return None;
}
@@ -161,7 +161,7 @@ pub fn iso_date(pdf: &str) -> Option<String> {
let tz = match rest.chars().next() {
Some('Z') | None => "Z".to_string(),
Some(sign @ ('+' | '-')) => {
- let t: String = rest[1..].chars().filter(|c| c.is_ascii_digit()).collect();
+ let t: String = rest[1..].chars().filter(char::is_ascii_digit).collect();
format!("{sign}{}:{}", t.get(0..2).unwrap_or("00"), t.get(2..4).unwrap_or("00"))
}
_ => "Z".to_string(),
diff --git a/crates/print/README.md b/crates/print/README.md
index ae60e1a..1379be2 100644
--- a/crates/print/README.md
+++ b/crates/print/README.md
@@ -35,6 +35,7 @@ spool::submit(&pdf, &spool::Job { printer: None, copies: 2, ..Default::default()
Each source page becomes a Form XObject (its content wrapped in q/Q, plus the printable
annotations); sheets place them with a clip. The result is a fresh, unencrypted,
garbage-collected file (callers check the print permission).
+Annotation appearances receive unused XObject names, preserving existing page resources even when they use the same naming prefix.
The GUI Print dialog remembers its last selected paper size across application sessions,
including when Print is cancelled. The preference stores a canonical name such as `A4`;
diff --git a/crates/print/src/lib.rs b/crates/print/src/lib.rs
index db65492..b731aff 100644
--- a/crates/print/src/lib.rs
+++ b/crates/print/src/lib.rs
@@ -149,6 +149,19 @@ pub enum BookletSubset {
BackOnly,
}
+/// How a booklet goes through the printer (#2707): it decides two-sided printing itself, as
+/// Acrobat does (its Print dialog hides Two-sided while Booklet is chosen; Using Acrobat X Pro,
+/// Print dialog box options: "Acrobat automatically enables duplex printing, if available, for
+/// booklet printing"). Both sides flip on the short edge, the fold of a 2-up sheet turned
+/// sideways; front side only or back side only is one pass of a manual duplex and prints
+/// single-sided.
+pub fn booklet_duplex(subset: BookletSubset) -> spool::Duplex {
+ match subset {
+ BookletSubset::BothSides => spool::Duplex::ShortEdge,
+ BookletSubset::FrontOnly | BookletSubset::BackOnly => spool::Duplex::Off,
+ }
+}
+
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum Binding {
#[default]
@@ -307,20 +320,45 @@ pub const PAPERS: [(&str, (f64, f64)); 21] = [
pub const LABEL_PAPER: usize = 19;
/// The CUPS media name for `PAPERS[index]`, so the spooler feeds the sheet the PDF was laid out
-/// on rather than the queue's default (PPD keywords; `w288h432` is the usual 4×6 label, `Env10`
-/// the US #10 envelope).
+/// on rather than the queue's default; `None` only past the end of `PAPERS`. The common sizes
+/// use their PPD keywords (`w288h432` is the usual 4×6 label, `Env10` the US #10 envelope).
+/// The rest use PWG 5101.1 names (ARCH E1 is its `wide-format` size), spelled exactly as the
+/// spec and the IANA registry have them: a driverless printer may take only the names it
+/// advertises. They carry their dimensions, so CUPS feeds the PPD size of those dimensions
+/// whatever the driver calls it (`ARCHD`, `AnsiD`) (#3752).
pub fn cups_media(index: usize) -> Option<&'static str> {
- match PAPERS.get(index)?.0 {
- "US Letter" => Some("Letter"),
- "US Legal" => Some("Legal"),
- "Tabloid" => Some("Tabloid"),
- "A3" => Some("A3"),
- "A4" => Some("A4"),
- "A5" => Some("A5"),
- "US #10 Envelope (4.125 x 9.5 in)" => Some("Env10"),
- _ if index == LABEL_PAPER => Some("w288h432"),
- _ => None,
- }
+ Some(match PAPERS.get(index)?.0 {
+ "US Letter" => "Letter",
+ "US Legal" => "Legal",
+ "Tabloid" => "Tabloid",
+ "A3" => "A3",
+ "A4" => "A4",
+ "A5" => "A5",
+ "A6" => "iso_a6_105x148mm",
+ "ARCH A (9 x 12 in)" => "na_arch-a_9x12in",
+ "ARCH B (12 x 18 in)" => "na_arch-b_12x18in",
+ "ARCH C (18 x 24 in)" => "na_arch-c_18x24in",
+ "ARCH D (24 x 36 in)" => "na_arch-d_24x36in",
+ "ARCH E1 (30 x 42 in)" => "na_wide-format_30x42in",
+ "ARCH E (36 x 48 in)" => "na_arch-e_36x48in",
+ "ANSI C (17 x 22 in)" => "na_c_17x22in",
+ "ANSI D (22 x 34 in)" => "na_d_22x34in",
+ "ANSI E (34 x 44 in)" => "na_e_34x44in",
+ "A2" => "iso_a2_420x594mm",
+ "A1" => "iso_a1_594x841mm",
+ "A0" => "iso_a0_841x1189mm",
+ "US #10 Envelope (4.125 x 9.5 in)" => "Env10",
+ _ if index == LABEL_PAPER => "w288h432",
+ // A size added to PAPERS without a name here: its tests fail, and meanwhile the queue's
+ // paper stands, as it did for every size before #1583.
+ _ => return None,
+ })
+}
+
+/// The job option that feeds `PAPERS[index]` (`media`, see [`cups_media`]), for the Print
+/// dialog's jobs and `doc_print`'s alike.
+pub fn media_option(index: usize) -> Option<(String, String)> {
+ cups_media(index).map(|m| ("media".to_string(), m.to_string()))
}
/// Whether most of page `index`'s text runs bottom-to-top as the page displays (a label laid
@@ -719,19 +757,57 @@ pub fn keep_printed(doc: &mut Document, content: Content) {
}
}
+/// The standard annotation types of ISO 32000-2 Table 171.
+const STANDARD_ANNOTATION_TYPES: [&[u8]; 28] = [
+ b"Text",
+ b"Link",
+ b"FreeText",
+ b"Line",
+ b"Square",
+ b"Circle",
+ b"Polygon",
+ b"PolyLine",
+ b"Highlight",
+ b"Underline",
+ b"Squiggly",
+ b"StrikeOut",
+ b"Caret",
+ b"Stamp",
+ b"Ink",
+ b"Popup",
+ b"FileAttachment",
+ b"Sound",
+ b"Movie",
+ b"Screen",
+ b"Widget",
+ b"PrinterMark",
+ b"TrapNet",
+ b"Watermark",
+ b"3D",
+ b"Redact",
+ b"Projection",
+ b"RichMedia",
+];
+
/// Does annotation `d` print under `content`?
fn prints(doc: &Document, d: &Dict, content: Content) -> bool {
+ const INVISIBLE: i64 = 1;
const HIDDEN: i64 = 2;
const PRINT: i64 = 4;
let flags = d.get(b"F").and_then(|f| doc.resolve(f).as_int()).unwrap_or(0);
if flags & PRINT == 0 || flags & HIDDEN != 0 {
return false;
}
- let subtype = d.name(b"Subtype").unwrap_or(b"");
+ // `/Subtype` may be an indirect reference (ISO 32000-2 §7.3.10), so resolve it first.
+ let subtype_obj = d.get(b"Subtype").map(|s| doc.resolve(s));
+ let subtype = subtype_obj.as_deref().and_then(Object::as_name).unwrap_or(b"");
match subtype {
b"Widget" => true,
b"Link" | b"Popup" => false,
b"Stamp" => content != Content::Document && content != Content::FormFieldsOnly,
+ // ISO 32000-2 Table 167: an Invisible annotation of a type that isn't standard (Table
+ // 171) is not printed even with its Print flag set.
+ _ if flags & INVISIBLE != 0 && !STANDARD_ANNOTATION_TYPES.contains(&subtype) => false,
_ => content == Content::DocumentAndMarkups,
}
}
@@ -801,7 +877,7 @@ fn page_form(
}
let annots = page.dict.get(b"Annots").and_then(|a| doc.resolve(a).as_array().cloned()).unwrap_or_default();
let mut xobjects = res.get(b"XObject").and_then(|x| doc.resolve(x).as_dict().cloned()).unwrap_or_default();
- let mut k = 0;
+ let mut k = 0usize;
for a in annots {
let Some(d) = doc.resolve(&a).as_dict().cloned() else { continue };
if !prints(doc, &d, content) {
@@ -833,8 +909,15 @@ fn page_form(
} else {
ap
};
- let name = format!("PCPrA{k}");
- k += 1;
+ // Keep the page's own XObjects, including names previous print operations generated.
+ // Check the growing map so each appearance also keeps the name just assigned to it.
+ let name = loop {
+ let name = format!("PCPrA{k}");
+ k = k.checked_add(1).ok_or_else(|| PrintError::Invalid("too many annotation appearance resources".into()))?;
+ if !xobjects.contains(name.as_bytes()) {
+ break name;
+ }
+ };
let [a0, b0, c0, d0, e0, f0] = m.0;
body.extend(format!("q {} {} {} {} {} {} cm /{name} Do Q\n", n(a0), n(b0), n(c0), n(d0), n(e0), n(f0)).bytes());
xobjects.set(name.into_bytes(), Object::Ref(ap));
diff --git a/crates/print/src/range.rs b/crates/print/src/range.rs
index 0752619..f0d8939 100644
--- a/crates/print/src/range.rs
+++ b/crates/print/src/range.rs
@@ -45,8 +45,8 @@ fn hyphenated_label_range(part: &str, count: usize, labels: &[String]) -> Option
}
/// The pages to print (0-based, in print order). `range` is `None` for all pages; it may list
-/// numbers and labels with `-` ranges (open-ended allowed: `5-`, `-3`). The subset counts the
-/// selected pages (the first selected is "odd"), as Acrobat does.
+/// numbers and labels with `-` ranges (open-ended allowed: `5-`, `-3`). The subset keeps the odd or
+/// even pages of those chosen, by page number (see [`narrow`]).
pub fn select_pages(count: usize, range: Option<&str>, labels: &[String], subset: Subset, reverse: bool) -> Result<Vec<usize>, PrintError> {
let mut pages = Vec::new();
match range.map(str::trim).filter(|r| !r.is_empty()) {
@@ -70,7 +70,7 @@ pub fn select_pages(count: usize, range: Option<&str>, labels: &[String], subset
Some(_) if labels.iter().any(|l| l == part) => pages.push(page_of(part, count, labels)?),
Some((a, b)) => {
let from = if a.trim().is_empty() { 0 } else { page_of(a, count, labels)? };
- let to = if b.trim().is_empty() { count.saturating_sub(1) } else { page_of(b, count, labels)? };
+ let to = if b.trim().is_empty() { count.checked_sub(1).ok_or(PrintError::NoPages)? } else { page_of(b, count, labels)? };
if from <= to {
pages.extend(from..=to);
} else {
@@ -95,12 +95,17 @@ pub fn select_listed(count: usize, pages: &[usize], subset: Subset, reverse: boo
narrow(pages.to_vec(), subset, reverse)
}
-/// Odd or even positions of the chosen pages, then the print order.
+/// The odd or even pages of those chosen, by page number (the first page of the document is 1,
+/// odd; `pages` are 0-based), then the print order. Acrobat counts the same way (#3984): "if you
+/// set the range to 2, 7–10 and choose Even Pages Only, only pages 2, 8, and 10 print" (Adobe
+/// Acrobat DC Help, last updated 11/28/2019, Options in the Print dialog box, p. 515; the same
+/// example in Using Adobe Acrobat 9 Pro, p. 413). Counting places in the range instead printed
+/// 7 and 9 there, and a range starting on an even page started its "even" pages on an odd one.
fn narrow(pages: Vec<usize>, subset: Subset, reverse: bool) -> Result<Vec<usize>, PrintError> {
let mut out: Vec<usize> = match subset {
Subset::All => pages,
- Subset::Odd => pages.into_iter().step_by(2).collect(),
- Subset::Even => pages.into_iter().skip(1).step_by(2).collect(),
+ Subset::Odd => pages.into_iter().filter(|p| p % 2 == 0).collect(),
+ Subset::Even => pages.into_iter().filter(|p| p % 2 == 1).collect(),
};
if reverse {
out.reverse();
@@ -110,3 +115,18 @@ fn narrow(pages: Vec<usize>, subset: Subset, reverse: bool) -> Result<Vec<usize>
}
Ok(out)
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn open_ended_range_of_empty_document_is_an_error() {
+ assert!(select_pages(0, Some("-"), &[], Subset::All, false).is_err());
+ }
+
+ #[test]
+ fn open_ended_range_covers_all_pages() {
+ assert_eq!(select_pages(5, Some("-"), &[], Subset::All, false).unwrap(), vec![0, 1, 2, 3, 4]);
+ }
+}
diff --git a/crates/print/src/tests.rs b/crates/print/src/tests.rs
index fabe19a..bc0454c 100644
--- a/crates/print/src/tests.rs
+++ b/crates/print/src/tests.rs
@@ -71,8 +71,10 @@ fn page_selection() {
assert_eq!(select_pages(1, None, &[], Subset::Even, false), Err(PrintError::NoPages));
// An explicit list (selected thumbnails): positions, never labels, in the order given.
assert_eq!(select_listed(5, &[1, 3], Subset::All, false).unwrap(), [1, 3]);
- assert_eq!(select_listed(5, &[0, 2, 4], Subset::Even, false).unwrap(), [2]);
- assert_eq!(select_listed(5, &[0, 2, 4], Subset::Odd, true).unwrap(), [4, 0]);
+ // Picked pages keep their page numbers: pages 1, 3 and 5 are all odd.
+ assert_eq!(select_listed(5, &[0, 2, 4], Subset::Even, false), Err(PrintError::NoPages));
+ assert_eq!(select_listed(5, &[0, 2, 4], Subset::Odd, true).unwrap(), [4, 2, 0]);
+ assert_eq!(select_listed(5, &[1, 2, 3], Subset::Even, false).unwrap(), [1, 3]);
assert_eq!(select_listed(5, &[1, 5], Subset::All, false), Err(PrintError::OutOfRange(6, 5)));
assert!(matches!(select_listed(0, &[usize::MAX], Subset::All, false), Err(PrintError::OutOfRange(_, 0))));
assert_eq!(select_listed(5, &[], Subset::All, false), Err(PrintError::NoPages));
@@ -672,6 +674,8 @@ fn architectural_sheets_preserve_full_scale() {
assert!(fit[0].placed[0].matrix.0[0] < 1.0, "Fit adds margins and must not masquerade as full scale");
}
+/// A sheet matches a preset either way round and rounded to whole points, but not half a point off;
+/// empty, negative, infinite, NaN and custom sizes match none.
#[test]
fn paper_matching_accepts_rounded_metric_sizes_but_not_custom_or_invalid_sizes() {
for (i, (_, (w, h))) in PAPERS.iter().enumerate() {
@@ -685,9 +689,69 @@ fn paper_matching_accepts_rounded_metric_sizes_but_not_custom_or_invalid_sizes()
}
}
+/// #3752: 13 of the 21 sizes had no media name, so their jobs went out on the queue's default
+/// paper (A4 on the report's queue) whatever the sheets were laid out on.
+#[test]
+fn every_paper_reaches_the_spooler_by_a_name_of_its_size() {
+ let ppd_keywords = ["Letter", "Legal", "Tabloid", "A3", "A4", "A5", "w288h432", "Env10"];
+ for (i, (name, (w, h))) in PAPERS.iter().enumerate() {
+ let media = cups_media(i).unwrap_or_else(|| panic!("{name} has no media name"));
+ assert_eq!(media_option(i), Some(("media".to_string(), media.to_string())));
+ let args = lp_args(&Job { options: media_option(i).into_iter().collect(), ..Job::default() });
+ assert!(args.contains(&format!("media={media}")), "{name}: lp is given it: {args:?}");
+ if ppd_keywords.contains(&media) {
+ continue;
+ }
+ // The rest are PWG 5101.1 names, which end in their dimensions: CUPS feeds the driver's
+ // size of those dimensions, so they must be the paper's.
+ let dims = media.rsplit('_').next().unwrap_or_default();
+ let (dims, points_per_unit) = match (dims.strip_suffix("mm"), dims.strip_suffix("in")) {
+ (Some(mm), _) => (mm, 72.0 / 25.4),
+ (_, Some(inches)) => (inches, 72.0),
+ _ => panic!("{name}: {media} is not a PWG name"),
+ };
+ let (pw, ph) = dims.split_once('x').unwrap_or_else(|| panic!("{name}: {media} has no dimensions"));
+ let (pw, ph) = (pw.parse::<f64>().unwrap() * points_per_unit, ph.parse::<f64>().unwrap() * points_per_unit);
+ assert!((pw - w).abs() < 0.5 && (ph - h).abs() < 0.5, "{name}: {media} is {pw:.2} x {ph:.2} pt, not {w} x {h}");
+ }
+ assert_eq!((cups_media(PAPERS.len()), media_option(PAPERS.len())), (None, None));
+ // The names themselves, spelled as PWG 5101.1 has them: a driverless printer may take only the
+ // names it advertises, so one CUPS can merely parse (ARCH A was `arch_a_9x12in`) is not enough.
+ // ARCH E1 is 5101.1's `wide-format` size: `na_arch-e1_30x42in` was asked for once and never
+ // registered.
+ let names: Vec<(&str, &str)> = PAPERS.iter().enumerate().map(|(i, (name, _))| (*name, cups_media(i).unwrap_or_default())).collect();
+ assert_eq!(
+ names,
+ [
+ ("US Letter", "Letter"),
+ ("US Legal", "Legal"),
+ ("Tabloid", "Tabloid"),
+ ("A3", "A3"),
+ ("A4", "A4"),
+ ("A5", "A5"),
+ ("A6", "iso_a6_105x148mm"),
+ ("ARCH A (9 x 12 in)", "na_arch-a_9x12in"),
+ ("ARCH B (12 x 18 in)", "na_arch-b_12x18in"),
+ ("ARCH C (18 x 24 in)", "na_arch-c_18x24in"),
+ ("ARCH D (24 x 36 in)", "na_arch-d_24x36in"),
+ ("ARCH E1 (30 x 42 in)", "na_wide-format_30x42in"),
+ ("ARCH E (36 x 48 in)", "na_arch-e_36x48in"),
+ ("ANSI C (17 x 22 in)", "na_c_17x22in"),
+ ("ANSI D (22 x 34 in)", "na_d_22x34in"),
+ ("ANSI E (34 x 44 in)", "na_e_34x44in"),
+ ("A2", "iso_a2_420x594mm"),
+ ("A1", "iso_a1_594x841mm"),
+ ("A0", "iso_a0_841x1189mm"),
+ ("4 x 6 in label (101.6 x 152.4 mm)", "w288h432"),
+ ("US #10 Envelope (4.125 x 9.5 in)", "Env10"),
+ ]
+ );
+}
+
+/// #2734: the US #10 envelope (4.125 × 9.5 in) is offered, fed by its PPD name and laid out at
+/// its own size.
#[test]
fn us_number_10_envelope_is_offered_and_fed_by_name() {
- // 4.125 × 9.5 in (#2734).
let index = matching_paper((684.0, 297.0)).unwrap();
assert_eq!(PAPERS[index].0, "US #10 Envelope (4.125 x 9.5 in)");
assert_eq!(PAPERS[index].1, (297.0, 684.0));
@@ -940,3 +1004,58 @@ fn text_direction_reads_on_past_a_refused_form() {
text_direction(&doc, content, &res, Matrix::IDENTITY, 0, &mut score, &mut DecodeBudget::new(1 << 20, 0));
assert_eq!(score, 1);
}
+
+/// #3984: odd and even are page numbers, as Acrobat counts them, not places in the range.
+#[test]
+fn odd_and_even_pages_are_page_numbers_not_places_in_the_range() {
+ let even = |range: &str| select_pages(12, Some(range), &[], Subset::Even, false).unwrap();
+ let odd = |range: &str| select_pages(12, Some(range), &[], Subset::Odd, false).unwrap();
+ // Adobe Acrobat DC Help (11/28/2019), Options in the Print dialog box, p. 515: "if you set the
+ // range to 2, 7–10 and choose Even Pages Only, only pages 2, 8, and 10 print".
+ assert_eq!(even("2, 7-10"), [1, 7, 9]);
+ // The report: 4–11 and 3–11 both print pages 4, 6, 8 and 10 as Even pages only.
+ assert_eq!(even("4-11"), [3, 5, 7, 9]);
+ assert_eq!(even("3-11"), [3, 5, 7, 9]);
+ assert_eq!(odd("4-11"), [4, 6, 8, 10]);
+ // Typed order is kept, and Reverse turns it round.
+ assert_eq!(even("10, 3, 4"), [9, 3]);
+ assert_eq!(select_pages(12, Some("10, 3, 4"), &[], Subset::Even, true).unwrap(), [3, 9]);
+ // A range with no page of the kind prints nothing.
+ assert_eq!(select_pages(12, Some("3, 5"), &[], Subset::Even, false), Err(PrintError::NoPages));
+}
+
+/// ISO 32000-2 Table 167: an Invisible annotation of a type that isn't standard does not print,
+/// even with its Print flag; Invisible means nothing for a standard type.
+#[test]
+fn invisible_annotations_of_unknown_types_do_not_print() {
+ let doc = fixture(1);
+ let annot = |subtype: Option<&str>, flags: i64| {
+ let mut d = Dict::new();
+ if let Some(s) = subtype {
+ d.set(b"Subtype".to_vec(), Object::name(s));
+ }
+ d.set(b"F".to_vec(), Object::Int(flags));
+ d
+ };
+ let all = Content::DocumentAndMarkups;
+ assert!(prints(&doc, &annot(Some("MyCustomType"), 4), all), "an unknown type prints without Invisible");
+ assert!(!prints(&doc, &annot(Some("MyCustomType"), 5), all), "Invisible + Print on an unknown type");
+ assert!(!prints(&doc, &annot(None, 5), all), "no Subtype is no standard type");
+ assert!(prints(&doc, &annot(Some("Square"), 5), all), "Invisible doesn't apply to a standard type");
+ assert!(prints(&doc, &annot(Some("Widget"), 5), Content::FormFieldsOnly), "nor to a field");
+
+ // An indirect `/Subtype` (§7.3.10) is resolved: a standard type stays standard.
+ let mut doc = doc;
+ let square = doc.add(Object::name("Square"));
+ let mut indirect = annot(None, 5);
+ indirect.set(b"Subtype".to_vec(), Object::Ref(square));
+ assert!(prints(&doc, &indirect, all), "an indirect standard Subtype");
+}
+
+/// #2707: a booklet's two-sided setting follows its subset.
+#[test]
+fn a_booklet_prints_both_sides_on_the_short_edge() {
+ assert_eq!(booklet_duplex(BookletSubset::BothSides), spool::Duplex::ShortEdge);
+ assert_eq!(booklet_duplex(BookletSubset::FrontOnly), spool::Duplex::Off);
+ assert_eq!(booklet_duplex(BookletSubset::BackOnly), spool::Duplex::Off);
+}
diff --git a/crates/print/src/tests/appearances.rs b/crates/print/src/tests/appearances.rs
index acf8ece..0d3107d 100644
--- a/crates/print/src/tests/appearances.rs
+++ b/crates/print/src/tests/appearances.rs
@@ -85,6 +85,68 @@ fn xobject(doc: &Document, owner: &Dict, name: &[u8]) -> ObjRef {
objects.as_dict().unwrap().get(name).unwrap().as_ref().unwrap()
}
+/// Printing keeps occupied page resource names and distinct annotation appearances intact,
+/// whether the page resources are direct or inherited from the page tree.
+#[test]
+fn annotation_appearances_do_not_replace_page_xobjects() {
+ for inherited in [false, true] {
+ let (mut doc, ap, widget) = widget_fixture(Some(Object::name("Form")), None);
+ let page = pdfcraft_model::pages(&doc)[0].obj;
+ let mut xobjects = Dict::new();
+ for (name, color) in [("PCPrA0", "1 0 0"), ("PCPrA1", "0 0 1"), ("PCPrA3", "1 0 0")] {
+ let dict = Dict::from_iter([
+ (b"Type".to_vec(), Object::name("XObject")),
+ (b"Subtype".to_vec(), Object::name("Form")),
+ (b"BBox".to_vec(), numbers(&[0.0, 0.0, 10.0, 10.0])),
+ ]);
+ let form = doc.add(Object::Stream(Stream::flate(dict, format!("{color} rg 0 0 10 10 re f").as_bytes())));
+ xobjects.set(name.as_bytes().to_vec(), Object::Ref(form));
+ }
+ let xobjects = doc.add(Object::Dict(xobjects));
+ let resources = doc.add(Object::Dict(Dict::from_iter([(b"XObject".to_vec(), Object::Ref(xobjects))])));
+ let contents = doc.add(Object::Stream(Stream::flate(
+ Dict::new(),
+ b"q 1 0 0 1 60 20 cm /PCPrA0 Do Q\nq 1 0 0 1 70 20 cm /PCPrA1 Do Q\nq 1 0 0 1 80 20 cm /PCPrA3 Do Q",
+ )));
+ let second_ap = doc.add(Object::Stream(Stream::flate(doc.get(ap).as_dict().unwrap().clone(), b"/Ink cs 1 1 0 scn 0 0 20 10 re f")));
+ let mut second_widget = doc.get(widget).as_dict().unwrap().clone();
+ second_widget.set(b"Rect".to_vec(), numbers(&[10.0, 50.0, 50.0, 70.0]));
+ second_widget.set(b"AP".to_vec(), Object::Dict(Dict::from_iter([(b"N".to_vec(), Object::Ref(second_ap))])));
+ let second_widget = doc.add(Object::Dict(second_widget));
+ doc.update_dict(page, |d| {
+ d.set(b"Resources".to_vec(), Object::Ref(resources));
+ d.set(b"Contents".to_vec(), Object::Ref(contents));
+ d.set(b"Annots".to_vec(), Object::Array(vec![Object::Ref(widget), Object::Ref(second_widget)]));
+ })
+ .unwrap();
+ if inherited {
+ let parent = doc.get(page).as_dict().unwrap().reference(b"Parent").unwrap();
+ doc.update_dict(parent, |d| d.set(b"Resources".to_vec(), Object::Ref(resources))).unwrap();
+ doc.update_dict(page, |d| {
+ d.remove(b"Resources");
+ })
+ .unwrap();
+ }
+ let before = saved(&doc);
+ let source = render(before.clone());
+ for (x, color) in [(65, [255, 0, 0, 255]), (75, [0, 0, 255, 255]), (85, [255, 0, 0, 255])] {
+ assert_eq!(pixel(&source, x, 75), color, "source page artwork");
+ }
+ for (y, color) in [(40, [255, 255, 0, 255]), (70, [0, 255, 0, 255])] {
+ assert_eq!(pixel(&source, 30, y), color, "source widget appearance");
+ }
+ let printed = render(impose(&doc, &print_settings(Content::Document)).unwrap());
+ for (x, color) in [(65, [255, 0, 0, 255]), (75, [0, 0, 255, 255]), (85, [255, 0, 0, 255])] {
+ assert_eq!(pixel(&printed, x, 75), color, "printed page artwork, inherited={inherited}");
+ }
+ for (y, color) in [(40, [255, 255, 0, 255]), (70, [0, 255, 0, 255])] {
+ assert_eq!(pixel(&printed, 30, y), color, "printed widget appearance, inherited={inherited}");
+ }
+ assert_eq!(printed.rgba, source.rgba, "printing must retain page artwork and both appearances, inherited={inherited}");
+ assert_eq!(saved(&doc), before, "printing must leave the source resources unchanged");
+ }
+}
+
#[test]
fn missing_subtype_appearance_survives_vector_print() {
let (control, _, _) = widget_fixture(Some(Object::name("Form")), None);
diff --git a/crates/redact/README.md b/crates/redact/README.md
index cca3d51..34c9f4f 100644
--- a/crates/redact/README.md
+++ b/crates/redact/README.md
@@ -89,6 +89,10 @@ read in full is refused, not cleaned in part. Both make the next save a full rew
`patterns` finds phone numbers, e-mail addresses, credit card numbers (Luhn-checked), US Social
Security numbers and dates for Search & Redact.
+A phone label such as `Tel.` or `Fax:` also enables Italian international geographic numbers with a slash, such as `Tel. +39 0426/123456` or `Fax: +390426/123456` (#3205 follow-up).
+The country code and national number are matched together, with the significant initial `0` and 6 to 11 national digits described in the [AGCOM numbering plan published by ITU](https://www.itu.int/dms_pub/itu-t/oth/02/02/t020200006b0001pdfe.pdf).
+This narrow case accepts at most one space after `+39` and one slash immediately after the area code; international slash numbers without a phone label, or with country codes other than +39, remain unsupported.
+Patterns are heuristic: dates, protocol identifiers and longer number runs are retained, and users still need to review the marks before applying them.
`codes` holds the redaction code sets (U.S. FOIA and U.S. Privacy Act exemptions):
`CodeSet::from_id("foia")?.overlay(&["(b)(6)"])` gives the overlay text for the picked codes.
diff --git a/crates/redact/src/interp.rs b/crates/redact/src/interp.rs
index 9851c2e..ffd59a2 100644
--- a/crates/redact/src/interp.rs
+++ b/crates/redact/src/interp.rs
@@ -26,7 +26,19 @@ use pdfcraft_cos::{CosError, DecodeBudget, Dict, Document, MAX_PAGE_FORMS, ObjRe
use crate::{RedactError, Report, image, page_streams, tags};
use pdfcraft_fonts::pdf::Metrics;
-const MAX_DEPTH: usize = 12;
+/// How deep this pass follows form XObjects. A form past it is removed rather than walked, which
+/// is the fail-safe choice for a redaction -- marked content inside a form we cannot read would
+/// otherwise survive -- but it also removes whatever else that form drew, marked or not. So the
+/// limit has to reach as deep as anything the reader can see: the renderer follows forms to 50
+/// (`MAX_NESTED_INTERPRETATION_DEPTH`) and so does Edit text's reader (`text::MAX_FORM_DEPTH`).
+/// At 12, a page with a 13-deep chain lost the text of its innermost form even with nothing in it
+/// marked (#3645); past 50 nothing is drawn by any of the three, so removing it costs nothing
+/// visible.
+pub(crate) const MAX_DEPTH: usize = 50;
+
+// A form a reader still shows must be walkable here, or a redaction removes content that is
+// visible; the build says so rather than a test, so the two limits cannot drift apart.
+const _: () = assert!(MAX_DEPTH >= pdfcraft_edit::text::MAX_FORM_DEPTH);
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Mode {
@@ -415,7 +427,7 @@ pub(crate) fn prune(xo: &mut Dict, replaced: &[Vec<u8>], content: &[Vec<u8>]) {
}
let joined = Pieces::join(content);
let ops = joined.parse().ops;
- let still_drawn = |n: &[u8]| ops.iter().any(|op| op.is("Do") && op.name(0) == Some(n));
+ let still_drawn = |n: &[u8]| ops.iter().any(|op| op.is("Do") && op.last_name() == Some(n));
for n in replaced {
if !still_drawn(n) {
xo.remove(n);
@@ -430,7 +442,7 @@ fn content_draws(doc: &Document, content: &[Vec<u8>], xo: &Dict, name: &[u8], de
let joined = Pieces::join(content);
let ops = joined.parse().ops;
for op in ops.iter().filter(|op| op.is("Do")) {
- let Some(n) = op.name(0) else { continue };
+ let Some(n) = op.last_name() else { continue };
if n == name {
return Some(true);
}
@@ -616,14 +628,7 @@ fn unlink_from_forms(doc: &mut Document, holders: &[ObjRef], doomed: &HashSet<Ob
continue;
}
let data = form.decoded()?;
- let mut pruned = false;
- for name in doomed_names {
- match content_draws(doc, std::slice::from_ref(&data), &xo, &name, 0, &mut HashSet::new()) {
- Some(true) => {}
- Some(false) => pruned |= xo.remove(&name).is_some(),
- None => return Err(CosError::Syntax { offset: 0, detail: "redaction could not fully inspect shared form resources".into() }),
- }
- }
+ let mut pruned = prune_doomed_xobjects(doc, std::slice::from_ref(&data), &mut xo, &doomed_names)?;
if pruned {
res.set(b"XObject".to_vec(), Object::Dict(xo));
}
@@ -637,6 +642,18 @@ fn unlink_from_forms(doc: &mut Document, holders: &[ObjRef], doomed: &HashSet<Ob
Ok(())
}
+fn prune_doomed_xobjects(doc: &Document, content: &[Vec<u8>], xo: &mut Dict, doomed_names: &[Vec<u8>]) -> Result<bool, CosError> {
+ let mut pruned = false;
+ for name in doomed_names {
+ match content_draws(doc, content, xo, name, 0, &mut HashSet::new()) {
+ Some(true) => {}
+ Some(false) => pruned |= xo.remove(name).is_some(),
+ None => return Err(CosError::Syntax { offset: 0, detail: "redaction could not fully inspect shared form resources".into() }),
+ }
+ }
+ Ok(pruned)
+}
+
/// The clip that hides everything inside each region: one even-odd clip per region (a big
/// rectangle with the region cut out), in the current user space. Returns `None` when the CTM
/// can't be inverted (nothing is painted then anyway).
@@ -672,7 +689,7 @@ fn resource_ops(doc: &Document, res: &Dict, content: &[Vec<u8>]) -> Result<Vec<O
while cursor < ops.len() {
let op = &ops[cursor];
if op.is("Do")
- && let Some(r) = op.name(0).and_then(|n| xobjects.get(n)).and_then(Object::as_ref)
+ && let Some(r) = op.last_name().and_then(|n| xobjects.get(n)).and_then(Object::as_ref)
&& seen.insert(r)
&& let Object::Stream(s) = &*doc.get(r)
&& s.dict.name(b"Subtype") == Some(b"Form")
@@ -717,7 +734,7 @@ fn prune_form_resources(doc: &Document, res: &mut Dict, content: &[Vec<u8>]) ->
let mut xo = res_dict(doc, res, b"XObject");
let names: Vec<Vec<u8>> = xo.iter().map(|(n, _)| n.to_vec()).collect();
for name in names {
- if !ops.iter().any(|op| op.is("Do") && op.name(0) == Some(&name)) {
+ if !ops.iter().any(|op| op.is("Do") && op.last_name() == Some(&name)) {
xo.remove(&name);
}
}
@@ -1204,7 +1221,7 @@ fn xobject(
xobjects: &mut Dict,
out: &mut Output,
) -> Option<Option<Op>> {
- let name = op.name(0)?.to_vec();
+ let name = op.last_name()?.to_vec();
let r = xobjects.get(&name)?.as_ref()?;
let obj = doc.get(r);
let Object::Stream(s) = &*obj else { return None };
@@ -1264,6 +1281,9 @@ fn xobject(
{
return None;
}
+ // Too deep: this form cannot be read, so it goes (Apply) or the page is left alone
+ // (Verify), as a form that will not decode does. The page's decode budget below is what
+ // keeps a fan-out or a cycle from costing 2^50 walks.
if scope.depth >= MAX_DEPTH {
if scope.mode == Mode::Verify {
// Sanitization removes a Form it cannot enter, so the verification scan
diff --git a/crates/redact/src/lib.rs b/crates/redact/src/lib.rs
index 00fbbbd..bdf1db8 100644
--- a/crates/redact/src/lib.rs
+++ b/crates/redact/src/lib.rs
@@ -185,7 +185,14 @@ pub(crate) fn marks_checked(doc: &Document) -> (Vec<Mark>, Vec<usize>) {
let (mut out, mut unreadable) = (Vec::new(), Vec::new());
for (pi, p) in pdfcraft_model::pages(doc).iter().enumerate() {
for a in annots_of(doc, &p.dict) {
- let Some(r) = a.as_ref() else { continue };
+ let Some(r) = a.as_ref() else {
+ // A mark written in place has no object to find, apply or remove: refuse it
+ // rather than apply the others as if it were not there.
+ if doc.resolve(&a).as_dict().is_some_and(|d| d.name(b"Subtype") == Some(b"Redact")) {
+ unreadable.push(pi);
+ }
+ continue;
+ };
let obj = doc.get(r);
let Some(d) = obj.as_dict() else { continue };
if d.name(b"Subtype") != Some(b"Redact") {
@@ -400,13 +407,14 @@ fn apply_to(doc: &mut Document, pages: Option<&[usize]>) -> Result<Report, Redac
.collect::<Result<Vec<_>, _>>()?;
report.pages = by_page.len();
localize_resources(doc, &by_page)?;
- let mut doomed_fields: Vec<String> = Vec::new();
+ let mut doomed_fields: Vec<ObjRef> = Vec::new();
// The original image and form XObjects the rewrite drops or replaces, on any page.
let mut doomed_xobjects: Vec<ObjRef> = Vec::new();
let mut retired_properties = Vec::new();
- let widget_owner: Vec<(ObjRef, String)> =
- pdfcraft_forms::fields(doc).into_iter().flat_map(|f| f.widgets.iter().map(|w| (w.obj, f.name.clone())).collect::<Vec<_>>()).collect();
+ let widget_owner: Vec<(ObjRef, ObjRef)> =
+ pdfcraft_forms::fields(doc).into_iter().flat_map(|f| f.widgets.iter().map(|w| (w.obj, f.obj)).collect::<Vec<_>>()).collect();
let listed_before = listed_annotations(doc);
+ let mut removed_everywhere: HashSet<ObjRef> = HashSet::new();
for &(pi, page_marks) in &groups {
let page = pdfcraft_model::pages(doc).swap_remove(pi);
@@ -521,10 +529,10 @@ fn apply_to(doc: &mut Document, pages: Option<&[usize]>) -> Result<Report, Redac
if rect_of(doc, d.get(b"Rect")).is_some_and(|b| rects.iter().any(|x| pdfcraft_content::overlaps(*x, b, 0.0))) {
removed.push(r);
if subtype == b"Widget" {
- if let Some((_, name)) = widget_owner.iter().find(|(w, _)| *w == r)
- && !doomed_fields.contains(name)
+ if let Some((_, field)) = widget_owner.iter().find(|(w, _)| *w == r)
+ && !doomed_fields.contains(field)
{
- doomed_fields.push(name.clone());
+ doomed_fields.push(*field);
}
} else {
report.annotations += 1;
@@ -557,6 +565,14 @@ fn apply_to(doc: &mut Document, pages: Option<&[usize]>) -> Result<Report, Redac
break;
}
}
+ removed_everywhere.extend(removed.iter().copied());
+ // Pop-ups dropped with their parent below count too: a reply on another page may answer one.
+ for a in &annots {
+ let Some(r) = a.as_ref() else { continue };
+ if doc.get(r).as_dict().and_then(|d| d.get(b"Parent")).and_then(Object::as_ref).is_some_and(|p| removed.contains(&p)) {
+ removed_everywhere.insert(r);
+ }
+ }
let kept: Vec<Object> = annots
.into_iter()
.filter(|a| {
@@ -578,10 +594,56 @@ fn apply_to(doc: &mut Document, pages: Option<&[usize]>) -> Result<Report, Redac
})?;
}
+ // 2b. Replies and pop-ups of a removed annotation can be listed on another page than their
+ // parent: their `/IRT` or `/Parent` would keep the removed comment reachable.
+ loop {
+ let mut grew = false;
+ for p in pdfcraft_model::pages(doc) {
+ let annots = annots_of(doc, &p.dict);
+ let mut kept = Vec::with_capacity(annots.len());
+ for a in &annots {
+ let Some(r) = a.as_ref() else {
+ kept.push(a.clone());
+ continue;
+ };
+ let obj = doc.get(r);
+ let Some(d) = obj.as_dict() else {
+ kept.push(a.clone());
+ continue;
+ };
+ let is_reply =
+ d.get(b"IRT").and_then(Object::as_ref).is_some_and(|x| removed_everywhere.contains(&x)) && d.name(b"Subtype") != Some(b"Widget");
+ let is_popup = d.get(b"Parent").and_then(Object::as_ref).is_some_and(|x| removed_everywhere.contains(&x));
+ if removed_everywhere.contains(&r) || is_reply || is_popup {
+ if removed_everywhere.insert(r) {
+ grew = true;
+ if is_reply {
+ report.annotations += 1;
+ }
+ }
+ } else {
+ kept.push(a.clone());
+ }
+ }
+ if kept.len() != annots.len() {
+ doc.update_dict(p.obj, |d| {
+ if kept.is_empty() {
+ d.remove(b"Annots");
+ } else {
+ d.set(b"Annots".to_vec(), Object::Array(kept));
+ }
+ })?;
+ }
+ }
+ if !grew {
+ break;
+ }
+ }
+
// 3. Form fields with a widget under a mark (all their widgets go).
- for name in &doomed_fields {
- if pdfcraft_forms::fields(doc).iter().any(|f| &f.name == name) {
- pdfcraft_forms::delete_field(doc, name)?;
+ for field in &doomed_fields {
+ if pdfcraft_forms::fields(doc).iter().any(|f| f.obj == *field) {
+ pdfcraft_forms::delete_field_object(doc, *field)?;
report.fields += 1;
}
}
@@ -637,27 +699,24 @@ fn apply_to(doc: &mut Document, pages: Option<&[usize]>) -> Result<Report, Redac
Ok(report)
}
-/// Remove redaction marks without applying them (`None` = all).
+/// Remove redaction marks without applying them (`None` = all), with their replies and pop-ups as
+/// deleting a comment does: a reply left behind would keep its mark in the file through `/IRT`.
+/// Returns how many marks went.
pub fn clear_marks(doc: &mut Document, pages: Option<&[usize]>) -> Result<usize, RedactError> {
- let all = marks(doc);
- let doomed: Vec<ObjRef> = all.iter().filter(|m| pages.is_none_or(|p| p.contains(&m.page))).map(|m| m.obj).collect();
- if doomed.is_empty() {
+ let targets: HashSet<ObjRef> = marks(doc).iter().filter(|m| pages.is_none_or(|p| p.contains(&m.page))).map(|m| m.obj).collect();
+ if targets.is_empty() {
return Err(RedactError::NothingToApply);
}
+ let listed: Vec<Object> = pdfcraft_model::pages(doc).iter().flat_map(|p| annots_of(doc, &p.dict)).collect();
+ let doomed = pdfcraft_annot::with_replies_and_popups(doc, &listed, targets.iter().copied());
for p in pdfcraft_model::pages(doc) {
let annots = annots_of(doc, &p.dict);
- let kept: Vec<Object> = annots
- .iter()
- .filter(|a| {
- let Some(r) = a.as_ref() else { return true };
- let parent = doc.get(r).as_dict().and_then(|d| d.get(b"Parent")).and_then(Object::as_ref);
- !doomed.contains(&r) && !parent.is_some_and(|p| doomed.contains(&p))
- })
- .cloned()
- .collect();
+ let kept: Vec<Object> = annots.iter().filter(|a| !pdfcraft_annot::goes_with(a, &doomed)).cloned().collect();
+ // As deleting a comment does: a page whose marks were all it had loses `/Annots` again,
+ // and an indirect array stays the one object the page points to.
if kept.len() != annots.len() {
- doc.update_dict(p.obj, |d| d.set(b"Annots".to_vec(), Object::Array(kept)))?;
+ pdfcraft_annot::set_annots(doc, p.obj, kept)?;
}
}
- Ok(doomed.len())
+ Ok(targets.len())
}
diff --git a/crates/redact/src/patterns.rs b/crates/redact/src/patterns.rs
index f707f17..59e623a 100644
--- a/crates/redact/src/patterns.rs
+++ b/crates/redact/src/patterns.rs
@@ -158,15 +158,30 @@ fn phone(s: &[char], i: usize) -> Option<usize> {
if seps == 0 && !labelled(s, i) || digit(s.get(end)) || run_continues(s, end.checked_sub(1)?, 1, &SEPS) {
return None;
}
- // Only an area code with a trunk 0 takes a slash, so "2024/123456" is no phone number; and
- // only one, right after it ("0426/123456", not "0426/12/3456" or "0426 12/3456").
let slash = run.contains(&'/');
- if run.iter().filter(|c| **c == '/').count() > 1 || slash && !run.iter().take_while(|c| **c != '/').all(char::is_ascii_digit) {
+ // Italian geographic numbers retain their initial 0 after +39. For a labelled number,
+ // apply the national slash rule after that country code and an optional separating space.
+ // AGCOM's E.164 plan gives geographic numbers 6 to 11 national digits (#3205).
+ let slash_run = if plus && slash {
+ if !labelled(s, i) || !(8..=13).contains(&n) {
+ return None;
+ }
+ let national = run.strip_prefix(&['3', '9'])?;
+ national.strip_prefix(&[' ']).unwrap_or(national)
+ } else {
+ run
+ };
+ // Only an area code beginning with 0 takes a slash, so "2024/123456" is no phone number;
+ // and only one, right after it (not "0426/12/3456" or "0426 12/3456").
+ if run.iter().filter(|c| **c == '/').count() > 1
+ || slash
+ && (slash_run.first() != Some(&'0') || !digit(slash_run.get(1)) || !slash_run.iter().take_while(|c| **c != '/').all(char::is_ascii_digit))
+ {
return None;
}
let ok = if plus {
// E.164: a `+` country code and up to 15 digits in all ("+49 2151 123456").
- !slash && (8..=15).contains(&n)
+ (8..=15).contains(&n)
} else {
// North American: 10 digits, 11 with a country code ("(555) 123-4567").
let nanp = (10..=11).contains(&n) && !slash;
@@ -346,7 +361,7 @@ fn date(s: &[char], i: usize) -> Option<usize> {
// Numeric: m/d/yy(yy), m-d-yyyy, d.m.yyyy, yyyy-mm-dd.
if let Some(a) = number(s, i, 1, 4) {
let sep = s.get(i + a).copied();
- if matches!(sep, Some('/' | '-' | '.'))
+ if matches!(sep, Some('-'..='/'))
&& let Some(b) = number(s, i + a + 1, 1, 2)
&& s.get(i + a + 1 + b).copied() == sep
&& let Some(c) = number(s, i + a + b + 2, if a == 4 { 1 } else { 2 }, if a == 4 { 2 } else { 4 })
@@ -505,6 +520,39 @@ mod tests {
);
}
+ #[test]
+ /// Labelled Italian geographic numbers match completely while dates and other digit runs stay unmarked.
+ fn labelled_italian_international_slash_numbers_match_whole() {
+ for (text, number) in [
+ ("tel. +39 0426/123456", "+39 0426/123456"),
+ ("Fax: +390426/123456", "+390426/123456"),
+ ("Telefono +39 02/12345678", "+39 02/12345678"),
+ ("tel. +39 02/1234", "+39 02/1234"),
+ ("tel. +39 0426/1234567", "+39 0426/1234567"),
+ ] {
+ assert_eq!(found(Pattern::Phone, text), [number], "{text}");
+ }
+ for text in [
+ "+39 0426/123456",
+ "tel. +39 2024/123456",
+ "tel. +39 0/123456789",
+ "tel. +39 0426/12/3456",
+ "tel. +39 0426 12/3456",
+ "tel. +39 0426/ 123456",
+ "tel. +39 02/123",
+ "tel. +39 0426/12345678",
+ "tel. +39 0426/1234567890",
+ "tel. +39 0426/123456",
+ "tel. +39-0426/123456",
+ "tel. +39 -0426/123456",
+ "tel. +40 0426/123456",
+ "protocol 2024/123456",
+ "on 01/10/2026",
+ ] {
+ assert!(found(Pattern::Phone, text).is_empty(), "{text}");
+ }
+ }
+
#[test]
fn the_tail_of_a_longer_number_is_not_a_phone_number() {
// #1884: the last groups of a French social security number, an IBAN and a SIRET used
diff --git a/crates/redact/src/sanitize.rs b/crates/redact/src/sanitize.rs
index 0b6c04f..202ece3 100644
--- a/crates/redact/src/sanitize.rs
+++ b/crates/redact/src/sanitize.rs
@@ -400,6 +400,8 @@ fn content_pass(doc: &mut Document, text: bool, layers: bool, write: bool) -> Re
_ => Dict::new(),
};
dict.remove(b"Length");
+ // The source text of an added item (Edit ▸ Add content) would keep what was removed.
+ dict.remove(b"PCAdded");
new_list[i] = Object::Ref(doc.add(Object::Stream(pdfcraft_cos::Stream::flate(dict, &bytes))));
changed = true;
}
@@ -472,7 +474,16 @@ pub fn scan(doc: &Document) -> Vec<(Hidden, usize)> {
+ owned(Hidden::Attachments)
}
Hidden::Comments => annots.iter().filter(|a| is_comment(a.name(b"Subtype").unwrap_or(b""))).count(),
- Hidden::FormFields => pdfcraft_forms::fields(doc).len(),
+ Hidden::FormFields => {
+ let n = pdfcraft_forms::fields(doc).len();
+ if n > 0 {
+ n
+ } else if cat.contains(b"AcroForm") {
+ 1
+ } else {
+ 0
+ }
+ }
Hidden::HiddenText => content_pass(&mut doc2, true, false, false).map(|(n, _)| n).unwrap_or(0),
Hidden::HiddenLayers => {
let off = hidden_layers(doc).len();
@@ -505,17 +516,11 @@ pub fn remove_hidden(doc: &mut Document, which: &[Hidden]) -> Result<Vec<(Hidden
let count = |h: Hidden| counts.iter().find(|c| c.0 == h).map_or(0, |c| c.1);
let (root, _) = catalog(doc).ok_or(RedactError::NothingToApply)?;
let mut done = Vec::new();
- // Content first (it needs the layers and the form still in place).
- let (text, layers) = (which.contains(&Hidden::HiddenText), which.contains(&Hidden::HiddenLayers));
- let retained_off_layers = if (text && count(Hidden::HiddenText) > 0) || (layers && count(Hidden::HiddenLayers) > 0) {
- content_pass(doc, text, layers, true)?.1
- } else {
- std::collections::HashSet::new()
- };
// Every annotation the pages list now: whatever is no longer listed at the end (flattened
// widgets included) leaves the structure tree too.
let listed_before = listed_annotations(doc);
- let fields = which.contains(&Hidden::FormFields) && count(Hidden::FormFields) > 0;
+ let has_acroform = doc.get(root).as_dict().is_some_and(|d| d.contains(b"AcroForm"));
+ let fields = which.contains(&Hidden::FormFields) && (count(Hidden::FormFields) > 0 || has_acroform);
if fields {
// Fields without appearances get one first, so their values stay visible.
for f in pdfcraft_forms::fields(doc) {
@@ -529,6 +534,14 @@ pub fn remove_hidden(doc: &mut Document, which: &[Hidden]) -> Result<Vec<(Hidden
d.remove(b"AcroForm");
})?;
}
+ // Content next (it needs the layers still in place). Flattened appearances are page content
+ // by now, so hidden text or layers inside them are removed with the rest.
+ let (text, layers) = (which.contains(&Hidden::HiddenText), which.contains(&Hidden::HiddenLayers));
+ let retained_off_layers = if (text && (fields || count(Hidden::HiddenText) > 0)) || (layers && (fields || count(Hidden::HiddenLayers) > 0)) {
+ content_pass(doc, text, layers, true)?.1
+ } else {
+ std::collections::HashSet::new()
+ };
// Annotations: comments, attachments, links, actions, and the widgets flattening kept (hidden
// ones, and ones with nothing to draw), which still hold their field's value and parent.
let drop_annot = |a: &Dict| -> bool {
@@ -628,9 +641,12 @@ pub fn remove_hidden(doc: &mut Document, which: &[Hidden]) -> Result<Vec<(Hidden
cat.set(b"OCProperties".to_vec(), Object::Dict(oc));
}
}
+ Hidden::FormFields => {
+ cat.remove(b"AcroForm");
+ }
_ => {}
}
- let n = count(h);
+ let n = if h == Hidden::FormFields && fields { count(h).max(1) } else { count(h) };
if n > 0 {
done.push((h, n));
}
diff --git a/crates/redact/src/tags.rs b/crates/redact/src/tags.rs
index 60c158b..961f016 100644
--- a/crates/redact/src/tags.rs
+++ b/crates/redact/src/tags.rs
@@ -108,7 +108,7 @@ pub(crate) fn touched(doc: &Document, resources: &Dict, before: &[u8], after: &[
let mut changed = HashSet::new();
let mut empty = HashSet::new();
let mut budget = MAX_COMPARED;
- let len = |ranges: &[Range<usize>]| ranges.iter().map(|r| r.len()).fold(0usize, usize::saturating_add);
+ let len = |ranges: &[Range<usize>]| ranges.iter().map(Range::len).fold(0usize, usize::saturating_add);
for (id, (old, _)) in &b.ids {
match a.ids.get(id) {
Some((new, draws)) => {
diff --git a/crates/redact/src/tests.rs b/crates/redact/src/tests.rs
index e29cd99..fa39853 100644
--- a/crates/redact/src/tests.rs
+++ b/crates/redact/src/tests.rs
@@ -289,6 +289,110 @@ fn vectors_are_removed_or_clipped_and_inline_images_go() {
assert!(c.contains("150 150 m"), "the line elsewhere stays");
}
+/// A chain of nested forms deeper than the pass can walk was removed from the page, taking
+/// whatever else it drew with it even when nothing in it was marked. The limit now reaches as
+/// deep as the renderer and Edit text read (50), so anything a reader can see can be walked;
+/// past that nothing is drawn either, so removing it costs nothing visible (#3645).
+#[test]
+fn a_deeply_nested_form_keeps_the_text_nobody_marked() {
+ /// A page that draws `HEAD` at the top, then a chain of `depth` forms whose innermost draws
+ /// `DEEP`, then `TAIL`. Only `HEAD` is marked.
+ fn page_with_chain(depth: usize) -> Document {
+ let first = 7;
+ let mut objs: Vec<Vec<u8>> = vec![
+ b"<< /Type /Catalog /Pages 2 0 R >>".to_vec(),
+ b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_vec(),
+ format!(
+ "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 300] /Contents 4 0 R /Resources << /Font << /F1 5 0 R >> /XObject << /Fm1 {first} 0 R >> >> >>"
+ )
+ .into_bytes(),
+ stream("", b"BT /F1 10 Tf 10 280 Td (HEAD) Tj ET /Fm1 Do BT /F1 10 Tf 10 10 Td (TAIL) Tj ET"),
+ FONT.replace("95 0 R", "6 0 R").into_bytes(),
+ widths(),
+ ];
+ for k in 1..=depth {
+ let res = if k < depth {
+ format!("/Resources << /Font << /F1 5 0 R >> /XObject << /Fm{} {} 0 R >> >>", k + 1, first + k)
+ } else {
+ "/Resources << /Font << /F1 5 0 R >> >>".to_string()
+ };
+ let body: Vec<u8> = if k < depth { format!("/Fm{} Do", k + 1).into_bytes() } else { b"BT /F1 10 Tf 10 150 Td (DEEP) Tj ET".to_vec() };
+ objs.push(stream(&format!("/Type /XObject /Subtype /Form /BBox [0 0 300 300] {res}"), &body));
+ }
+ pdf(objs)
+ }
+
+ // Deeper than the old limit of 12 and within the new one: the innermost text survives.
+ for depth in [1, 12, 13, 20, 50] {
+ let mut doc = page_with_chain(depth);
+ mark(&mut doc, 0, &[[5.0, 275.0, 60.0, 295.0]], "");
+ let report = apply(&mut doc, None).unwrap();
+ assert_eq!(report.forms_removed, 0, "depth {depth}: a form was removed");
+ let c = content(&doc, 0);
+ assert!(c.contains("(TAIL)"), "depth {depth}: {c}");
+ // The innermost form's text is still in the saved file.
+ let saved = write_incremental(&doc, &SaveOptions::default()).unwrap();
+ assert!(saved.windows(6).any(|w| w == b"(DEEP)"), "depth {depth}: the innermost form's text was deleted");
+ }
+
+ // Past what any reader follows, the form is still removed: the fail-safe, and nothing the
+ // renderer draws is lost because it stops at 50 too.
+ let mut doc = page_with_chain(crate::interp::MAX_DEPTH + 1);
+ mark(&mut doc, 0, &[[5.0, 275.0, 60.0, 295.0]], "");
+ assert_eq!(apply(&mut doc, None).unwrap().forms_removed, 1, "a chain past the limit is removed");
+}
+
+/// Depth alone does not bound the walk: a form that draws the next level twice, or a cycle of two
+/// forms, costs 2^depth interpretations, which at a depth limit of 50 is a hang on a file anyone
+/// can send. The pass also counts the forms it enters, and a page past that budget is treated as
+/// one it cannot read.
+#[test]
+fn a_form_that_fans_out_or_loops_is_bounded_by_the_page_budget() {
+ /// A page drawing `Fm1`, where each of `n` forms draws the next **twice** and the last draws
+ /// text: 2^n paths if nothing stops the walk. With `looping`, the last form draws the first
+ /// one again instead, so the chain has no end at all.
+ fn fan_out(n: usize, looping: bool) -> Document {
+ let first = 7;
+ let mut objs: Vec<Vec<u8>> = vec![
+ b"<< /Type /Catalog /Pages 2 0 R >>".to_vec(),
+ b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_vec(),
+ format!(
+ "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 300] /Contents 4 0 R /Resources << /Font << /F1 5 0 R >> /XObject << /Fm1 {first} 0 R >> >> >>"
+ )
+ .into_bytes(),
+ stream("", b"BT /F1 10 Tf 10 280 Td (HEAD) Tj ET /Fm1 Do"),
+ FONT.replace("95 0 R", "6 0 R").into_bytes(),
+ widths(),
+ ];
+ for k in 1..=n {
+ let (next, body) = if k < n {
+ (first + k, format!("/Fm{0} Do /Fm{0} Do", k + 1))
+ } else if looping {
+ (first, "/Fm1 Do /Fm1 Do".to_string())
+ } else {
+ (first, "BT /F1 10 Tf 10 150 Td (DEEP) Tj ET".to_string())
+ };
+ let name = if k < n { format!("/Fm{}", k + 1) } else { "/Fm1".to_string() };
+ let res = format!("/Resources << /Font << /F1 5 0 R >> /XObject << {name} {next} 0 R >> >>");
+ objs.push(stream(&format!("/Type /XObject /Subtype /Form /BBox [0 0 300 300] {res}"), body.as_bytes()));
+ }
+ pdf(objs)
+ }
+
+ for looping in [false, true] {
+ let start = std::time::Instant::now();
+ let mut doc = fan_out(crate::interp::MAX_DEPTH, looping);
+ mark(&mut doc, 0, &[[5.0, 275.0, 60.0, 295.0]], "");
+ let result = apply(&mut doc, None);
+ let took = start.elapsed();
+ // An unbounded walk would never end; the limit leaves room for a loaded test machine.
+ assert!(took < std::time::Duration::from_secs(120), "looping {looping}: the walk took {took:?}");
+ // The page's form budget stops the walk, and Apply refuses the page rather than
+ // removing forms it could not read.
+ assert!(result.is_err(), "looping {looping}: the page past its form budget is refused");
+ }
+}
+
#[test]
fn shared_form_xobjects_are_copied_not_changed() {
let form =
@@ -720,19 +824,19 @@ fn form_chain_at_max_depth_is_counted_and_removed_by_hidden_layer_sanitization()
use crate::sanitize::{Hidden, remove_hidden, scan};
const PRIVATE: &[u8] = b"PRIVATE_FORM_BEYOND_MAX_DEPTH";
- // MAX_DEPTH is 12. The final Form is encountered at that depth and is removed
- // conservatively without being entered. Verify must count that removal or sanitize
- // can skip the HiddenLayers pass entirely.
+ // The final Form is encountered at MAX_DEPTH and is removed conservatively without being
+ // entered. Verify must count that removal or sanitize can skip the HiddenLayers pass entirely.
+ let max = crate::interp::MAX_DEPTH;
let mut forms = Vec::new();
- for depth in 0..=12 {
- let content = if depth == 12 {
+ for depth in 0..=max {
+ let content = if depth == max {
b"BT /F1 10 Tf 10 100 Td (PRIVATE_FORM_BEYOND_MAX_DEPTH) Tj ET".to_vec()
} else {
format!("/F{} Do", depth + 1).into_bytes()
};
forms.push(stream("/Type /XObject /Subtype /Form /BBox [0 0 300 300]", &content));
}
- let xobjects = (0..=12).map(|depth| format!("/F{depth} {} 0 R", 7 + depth)).collect::<Vec<_>>().join(" ");
+ let xobjects = (0..=max).map(|depth| format!("/F{depth} {} 0 R", 7 + depth)).collect::<Vec<_>>().join(" ");
let mut doc = one_page(b"/F0 Do", &format!("/XObject << {xobjects} >>"), forms);
assert!(
write_full(&doc, &SaveOptions::default()).unwrap().windows(PRIVATE.len()).any(|w| w == PRIVATE),
@@ -1041,6 +1145,41 @@ fn nothing_to_apply_and_clearing_marks() {
assert!(content(&doc, 0).contains("(AB) Tj"));
}
+/// Clearing marks puts a page's annotation list back as it was: a page that had none has no
+/// `/Annots` again, replies to the marks included, and one listed through an indirect array keeps
+/// pointing at that array.
+#[test]
+fn clearing_marks_leaves_the_annotation_list_as_it_was() {
+ let mut doc = one_page(b"BT /F1 10 Tf 10 100 Td (AB) Tj ET", "", vec![]);
+ let page = pdfcraft_model::pages(&doc)[0].obj;
+ let before = doc.get(page);
+ mark(&mut doc, 0, &[[0.0, 0.0, 50.0, 50.0]], "");
+ pdfcraft_annot::add_reply(&mut doc, 0, 0, "a reply", "Tester", &Meta::default()).unwrap();
+ // And a reply written inline, as a file can.
+ let mut inline = Dict::new();
+ inline.set(b"Subtype".to_vec(), Object::name("Text"));
+ inline.set(b"IRT".to_vec(), Object::Ref(marks(&doc)[0].obj));
+ let mut listed = annots_of(&doc, doc.get(page).as_dict().unwrap());
+ listed.push(Object::Dict(inline));
+ doc.update_dict(page, |d| d.set(b"Annots".to_vec(), Object::Array(listed))).unwrap();
+ assert_eq!(clear_marks(&mut doc, None), Ok(1), "one mark");
+ assert_eq!(doc.get(page), before, "the page has no /Annots again: both replies went with their mark");
+
+ let mut doc = pdf(vec![
+ b"<< /Type /Catalog /Pages 2 0 R >>".to_vec(),
+ b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_vec(),
+ b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 300] /Annots 4 0 R >>".to_vec(),
+ b"[5 0 R]".to_vec(),
+ b"<< /Type /Annot /Subtype /Link /Rect [0 0 10 10] >>".to_vec(),
+ ]);
+ let (page, list) = (ObjRef::new(3, 0), ObjRef::new(4, 0));
+ let before = (doc.get(page), doc.get(list));
+ mark(&mut doc, 0, &[[0.0, 0.0, 50.0, 50.0]], "");
+ assert_eq!(doc.get(list).as_array().map(|a| a.len()), Some(2), "the mark is listed in the shared array");
+ clear_marks(&mut doc, None).unwrap();
+ assert_eq!((doc.get(page), doc.get(list)), before, "the page points at its array, which lists the link alone");
+}
+
#[test]
fn unreadable_content_fails_closed() {
let mut doc = one_page(b"", "", vec![]);
@@ -2569,6 +2708,27 @@ fn removing_form_fields_takes_hidden_widgets_and_their_values_out_of_the_file()
assert!(annots_of(&doc, &pdfcraft_model::pages(&doc).swap_remove(0).dict).is_empty());
}
+/// F-021: removing form fields on a document with an AcroForm dictionary (even one with no
+/// enumerable terminal fields) removes the AcroForm dictionary, processes widgets, and requires full save.
+#[test]
+fn removing_form_fields_removes_acroform_even_without_terminal_fields() {
+ use crate::sanitize::{Hidden, remove_hidden, scan};
+ let mut doc =
+ one_page(b"BT /F1 10 Tf 10 100 Td (Visible) Tj ET", "", vec![b"<< /Type /Annot /Subtype /Widget /Rect [10 200 150 220] >>".to_vec()]);
+ doc.update_dict(doc.root().unwrap(), |d| d.set(b"AcroForm".to_vec(), fields_dict(&[]))).unwrap();
+ doc.update_dict(ObjRef::new(3, 0), |d| d.set(b"Annots".to_vec(), ref_array(&[7]))).unwrap();
+ let counts = scan(&doc);
+ assert_eq!(counts.iter().find(|c| c.0 == Hidden::FormFields).map(|c| c.1), Some(1));
+ assert!(doc.get(doc.root().unwrap()).as_dict().is_some_and(|d| d.contains(b"AcroForm")));
+ assert!(!doc.full_save_required());
+
+ let done = remove_hidden(&mut doc, &[Hidden::FormFields]).unwrap();
+ assert_eq!(done, [(Hidden::FormFields, 1)]);
+ assert!(!doc.get(doc.root().unwrap()).as_dict().is_some_and(|d| d.contains(b"AcroForm")));
+ assert!(annots_of(&doc, &pdfcraft_model::pages(&doc).swap_remove(0).dict).is_empty());
+ assert!(doc.full_save_required());
+}
+
/// Removing hidden text cleans the structure tree as redaction does: the elements describing the
/// removed text lose their descriptions, and a reference into a rewritten Form points at the copy.
#[test]
@@ -2762,3 +2922,85 @@ fn a_failure_on_a_later_page_leaves_the_document_unchanged() {
assert_eq!(after, before);
assert_eq!(content(&doc, 0), text);
}
+
+#[test]
+fn a_reply_and_pop_up_on_another_page_go_with_the_removed_comment() {
+ let objs: Vec<Vec<u8>> = vec![
+ b"<< /Type /Catalog /Pages 2 0 R >>".to_vec(),
+ b"<< /Type /Pages /Kids [3 0 R 4 0 R] /Count 2 >>".to_vec(),
+ b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 300] /Contents 5 0 R /Annots [6 0 R] >>".to_vec(),
+ b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 300] /Contents 5 0 R /Annots [7 0 R 8 0 R] >>".to_vec(),
+ stream("", b"BT ET"),
+ b"<< /Type /Annot /Subtype /Text /Rect [20 20 40 40] /Contents (PARENT-NOTE) /Popup 8 0 R >>".to_vec(),
+ b"<< /Type /Annot /Subtype /Text /Rect [250 250 270 270] /IRT 6 0 R /Contents (OTHER-PAGE-REPLY) >>".to_vec(),
+ b"<< /Type /Annot /Subtype /Popup /Rect [200 150 290 190] /Parent 6 0 R >>".to_vec(),
+ ];
+ let mut doc = pdf(objs);
+ mark(&mut doc, 0, &[[10.0, 10.0, 70.0, 50.0]], "");
+ apply(&mut doc, None).unwrap();
+ let second = pdfcraft_model::pages(&doc).swap_remove(1);
+ assert!(annots_of(&doc, &second.dict).is_empty(), "the reply and the pop-up leave page 2");
+ let bytes = write_full(&doc, &SaveOptions { object_streams: false, ..SaveOptions::default() }).unwrap();
+ assert!(!bytes.windows(10).any(|w| w == b"PARENT-NOT"), "the removed comment survived the save");
+}
+
+#[test]
+fn a_redact_mark_written_in_place_is_refused() {
+ let objs: Vec<Vec<u8>> = vec![
+ b"<< /Type /Catalog /Pages 2 0 R >>".to_vec(),
+ b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_vec(),
+ b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 300] /Contents 4 0 R /Annots [<< /Type /Annot /Subtype /Redact /Rect [10 10 70 40] >>] >>"
+ .to_vec(),
+ stream("", b"BT ET"),
+ ];
+ let mut doc = pdf(objs);
+ mark(&mut doc, 0, &[[100.0, 100.0, 120.0, 120.0]], "");
+ assert!(matches!(apply(&mut doc, None), Err(RedactError::UnreadableMark(1))));
+}
+
+#[test]
+fn do_acts_on_the_operand_before_the_operator_like_the_renderer() {
+ // `/Missing /Im Do`: the renderer draws /Im, so redaction must find the image there.
+ let img = stream("/Type /XObject /Subtype /Image /Width 1 /Height 1 /ColorSpace /DeviceGray /BitsPerComponent 8", b"\x00");
+ let mut doc = one_page(b"q 100 0 0 100 10 10 cm /Missing /Im Do Q", "/XObject << /Im 7 0 R >>", vec![img]);
+ mark(&mut doc, 0, &[[0.0, 0.0, 300.0, 300.0]], "");
+ let r = apply(&mut doc, None).unwrap();
+ assert_eq!(r.images_removed, 1, "{r:?}");
+}
+
+#[test]
+fn hidden_text_removal_drops_the_source_text_of_added_content() {
+ let mut doc = one_page(b"BT /F1 12 Tf 3 Tr 20 20 Td (SECRET) Tj ET", "", vec![]);
+ let content_ref = pdfcraft_model::pages(&doc)[0].dict.get(b"Contents").and_then(Object::as_ref).unwrap();
+ doc.update_dict(content_ref, |d| {
+ d.set(b"PCAdded".to_vec(), Object::Dict(Dict::new()));
+ })
+ .unwrap();
+ sanitize::remove_hidden(&mut doc, &[sanitize::Hidden::HiddenText]).unwrap();
+ let p = &pdfcraft_model::pages(&doc)[0];
+ let (list, _) = page_streams(&doc, &p.dict, 0).unwrap();
+ assert!(list.iter().all(|o| doc.resolve(o).as_dict().is_some_and(|d| !d.contains(b"PCAdded"))));
+}
+
+#[test]
+fn a_reply_on_another_page_to_a_removed_popup_goes_too() {
+ let objs: Vec<Vec<u8>> = vec![
+ b"<< /Type /Catalog /Pages 2 0 R >>".to_vec(),
+ b"<< /Type /Pages /Kids [3 0 R 4 0 R] /Count 2 >>".to_vec(),
+ b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 300] /Contents 5 0 R /Annots [6 0 R 8 0 R] >>".to_vec(),
+ b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 300] /Contents 5 0 R /Annots [7 0 R] >>".to_vec(),
+ stream("", b"BT ET"),
+ b"<< /Type /Annot /Subtype /Text /Rect [20 20 40 40] /Contents (PARENT-NOTE) /Popup 8 0 R >>".to_vec(),
+ b"<< /Type /Annot /Subtype /Text /Rect [250 250 270 270] /IRT 8 0 R /Contents (POPUP-REPLY) >>".to_vec(),
+ b"<< /Type /Annot /Subtype /Popup /Rect [200 150 290 190] /Parent 6 0 R /Contents (POPUP-TEXT) >>".to_vec(),
+ ];
+ let mut doc = pdf(objs);
+ mark(&mut doc, 0, &[[10.0, 10.0, 70.0, 50.0]], "");
+ apply(&mut doc, None).unwrap();
+ let second = pdfcraft_model::pages(&doc).swap_remove(1);
+ assert!(annots_of(&doc, &second.dict).is_empty());
+ let bytes = write_full(&doc, &SaveOptions { object_streams: false, ..SaveOptions::default() }).unwrap();
+ for gone in [&b"POPUP-REPLY"[..], b"POPUP-TEXT", b"PARENT-NOTE"] {
+ assert!(!bytes.windows(gone.len()).any(|w| w == gone), "{} survived", String::from_utf8_lossy(gone));
+ }
+}
diff --git a/crates/redact/src/tests/surviving_references.rs b/crates/redact/src/tests/surviving_references.rs
index d3aa98a..a297ded 100644
--- a/crates/redact/src/tests/surviving_references.rs
+++ b/crates/redact/src/tests/surviving_references.rs
@@ -66,3 +66,42 @@ fn an_image_a_surviving_form_draws_is_kept() {
assert_eq!(apply(&mut doc, None).unwrap().images_removed, 1);
assert!(full_save_holds(&doc, b"IMAGESECRET"), "the image the form still draws outside the mark");
}
+
+/// The surviving form draws the image through a nested form without /Resources of its own,
+/// which draws through the outer form's: the image is kept.
+#[test]
+fn an_image_a_surviving_forms_nested_form_draws_is_kept() {
+ let mut doc = pdf(vec![
+ b"<< /Type /Catalog /Pages 2 0 R >>".to_vec(),
+ b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_vec(),
+ b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 300] /Contents 4 0 R /Resources 5 0 R >>".to_vec(),
+ stream("", b"q 100 0 0 100 0 0 cm /Im Do Q /Fm Do"),
+ b"<< /XObject << /Im 6 0 R /Fm 7 0 R /Inner 8 0 R >> >>".to_vec(),
+ stream("/Type /XObject /Subtype /Image /Width 11 /Height 1 /ColorSpace /DeviceGray /BitsPerComponent 8", b"IMAGESECRET"),
+ stream("/Type /XObject /Subtype /Form /BBox [0 0 300 300] /Resources 5 0 R", b"/Inner Do"),
+ stream("/Type /XObject /Subtype /Form /BBox [0 0 300 300]", b"q 50 0 0 50 200 200 cm /Im Do Q"),
+ ]);
+ mark(&mut doc, 0, &[[0.0, 0.0, 120.0, 120.0]], "");
+ assert_eq!(apply(&mut doc, None).unwrap().images_removed, 1);
+ assert!(full_save_holds(&doc, b"IMAGESECRET"), "the image the nested form still draws outside the mark");
+}
+
+/// Two pages share one resource dictionary, and the second draws the image only through a form
+/// without /Resources: redacting the image on the first page keeps it for the second.
+#[test]
+fn an_image_another_page_draws_through_a_form_without_resources_is_kept() {
+ let mut doc = pdf(vec![
+ b"<< /Type /Catalog /Pages 2 0 R >>".to_vec(),
+ b"<< /Type /Pages /Kids [3 0 R 4 0 R] /Count 2 >>".to_vec(),
+ b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 300] /Contents 5 0 R /Resources 7 0 R >>".to_vec(),
+ b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 300] /Contents 6 0 R /Resources 7 0 R >>".to_vec(),
+ stream("", b"q 100 0 0 100 0 0 cm /Im Do Q"),
+ stream("", b"/Inner Do"),
+ b"<< /XObject << /Im 8 0 R /Inner 9 0 R >> >>".to_vec(),
+ stream("/Type /XObject /Subtype /Image /Width 11 /Height 1 /ColorSpace /DeviceGray /BitsPerComponent 8", b"IMAGESECRET"),
+ stream("/Type /XObject /Subtype /Form /BBox [0 0 300 300]", b"q 50 0 0 50 200 200 cm /Im Do Q"),
+ ]);
+ mark(&mut doc, 0, &[[0.0, 0.0, 120.0, 120.0]], "");
+ assert_eq!(apply(&mut doc, None).unwrap().images_removed, 1);
+ assert!(full_save_holds(&doc, b"IMAGESECRET"), "the second page still draws the image through its form");
+}
diff --git a/crates/render/examples/page_timing.rs b/crates/render/examples/page_timing.rs
index f1d143a..5fc60c6 100644
--- a/crates/render/examples/page_timing.rs
+++ b/crates/render/examples/page_timing.rs
@@ -51,7 +51,7 @@ fn main() -> Result<(), Box<dyn Error>> {
};
let threads: usize = match args.get(4) {
Some(s) => s.parse::<usize>()?.max(1),
- None => std::thread::available_parallelism().map_or(4, |n| n.get()).clamp(2, 8) - 1,
+ None => std::thread::available_parallelism().map_or(4, std::num::NonZeroUsize::get).clamp(2, 8) - 1,
};
let bytes = Arc::new(std::fs::read(path)?);
diff --git a/crates/render/src/inspect.rs b/crates/render/src/inspect.rs
index 46977c4..2d083c5 100644
--- a/crates/render/src/inspect.rs
+++ b/crates/render/src/inspect.rs
@@ -6,6 +6,7 @@
//! are empty and `warnings` says why.
use std::cell::OnceCell;
+use std::collections::hash_map::Entry;
use std::collections::{BTreeMap, HashMap, HashSet};
use std::sync::Arc;
@@ -110,6 +111,10 @@ pub struct DocInfo {
pub attachments: Vec<Attachment>,
/// Pages with a presentation transition (`/Trans`) or display time (`/Dur`), in page order.
pub transitions: Vec<PageTransition>,
+ /// Where the document opens (`/OpenAction`): the (0-based page, view) of its destination,
+ /// named destinations resolved. `None` without one, for an action that goes nowhere in this
+ /// document (a script, say), or for one that doesn't resolve to a page of it.
+ pub open_dest: Option<(usize, DestView)>,
pub warnings: Vec<String>,
}
@@ -325,7 +330,10 @@ pub enum LinkTarget {
preserve_rb: bool,
},
/// A local-file remote Go-To action. The caller resolves `file` relative to the source path.
+ /// `launch` marks a Launch action that names a PDF file (see `launch_pdf`), opened the same
+ /// way: as a document in PdfCraft, never by the operating system.
RemoteGoTo {
+ launch: bool,
file: String,
destination: RemoteDestination,
new_window: Option<bool>,
@@ -398,7 +406,16 @@ pub struct OutlineItem {
/// Where on `page` the bookmark goes ([`DestView::Top`] for a bookmark without a page).
pub view: DestView,
pub children: Vec<OutlineItem>,
+ /// Whether the bookmark starts open: only a positive `/Count` says so (ISO 32000-2 §12.3.3,
+ /// Table 151). A negative one is closed, and so is a missing one, which a bookmark with
+ /// children should not have.
pub open: bool,
+ /// The title's colour (`/C`, DeviceRGB, ISO 32000-2 §12.3.3 Table 151), or `None` for the
+ /// default black or a value that isn't three numbers.
+ pub color: Option<[f32; 3]>,
+ /// The title's style (`/F`, Table 152): bit 1 italic, bit 2 bold.
+ pub italic: bool,
+ pub bold: bool,
}
#[derive(Clone, Debug)]
@@ -411,9 +428,17 @@ pub struct Annotation {
pub modified: Option<String>,
/// `/M` as the PDF has it (`D:20261011171900Z`, with its time zone), for showing it in local time.
pub modified_raw: Option<String>,
- /// `/NM` of this annotation, and of the one it replies to (`/IRT`), for threading.
+ /// `/NM` of this annotation, and of the one it replies to (`/IRT`).
pub name: Option<String>,
pub in_reply_to: Option<String>,
+ /// The page and `/Annots` position of the comment `/IRT` points at, found by object
+ /// reference. Threads follow this rather than `/NM`, which need not be unique: PyMuPDF
+ /// names the first comment on every page `fitz-A0`. `None` when `/IRT` leads to no listed
+ /// comment ([`link_replies`]).
+ pub parent: Option<(usize, usize)>,
+ /// `/RT /Group`: grouped with the annotation `/IRT` points at (Replace Text's caret with its
+ /// strikeout) rather than a reply to it.
+ pub grouped: bool,
/// Rect in PDF user space: [x0, y0, x1, y1].
pub rect: [f32; 4],
pub color: Option<[f32; 3]>,
@@ -435,6 +460,10 @@ pub struct Annotation {
/// The line width in points: `/BS /W`, else the third number of `/Border`; none when neither
/// is there.
pub width: Option<f32>,
+ /// The NoRotate flag (`/F` bit 5), set on sticky notes and attachments: on a turned page the
+ /// appearance stays upright, turned about the upper-left corner of `rect`
+ /// ([`Self::shown_rect`]).
+ pub no_rotate: bool,
/// The points that shape a line (its two ends, `/L`) or connected lines, a polygon or a
/// cloud (their corners, `/Vertices`), in user space; empty for other comments.
pub points: Vec<[f32; 2]>,
@@ -445,6 +474,124 @@ impl Annotation {
pub fn is_mark(&self) -> bool {
matches!(self.state.as_deref(), Some("Marked" | "Unmarked"))
}
+
+ /// A reply (or status reply) to another comment rather than a comment of its own.
+ pub fn is_reply(&self) -> bool {
+ self.parent.is_some()
+ }
+
+ /// A comment of its own: not a reply, and not a status or checkmark. One whose comment can't
+ /// be found (deleted from another page, or never listed) has nothing to show, so it is listed
+ /// nowhere: not as a card, on the page or in a count.
+ pub fn is_comment(&self) -> bool {
+ !self.is_reply() && self.state.is_none()
+ }
+
+ /// Whether this annotation's `/IRT` points at `other`.
+ pub fn replies_to(&self, other: &Annotation) -> bool {
+ self.parent == Some((other.page, other.index))
+ }
+
+ /// Where the comment is drawn on a page turned by `rotation` (`PageInfo::rotation`), in user
+ /// space: `rect`, or for a NoRotate comment `rect` turned upright about its upper-left corner
+ /// (see [`Self::no_rotate`]). Hit-testing, selection and anything placed beside the comment
+ /// use this, so they match the drawing.
+ pub fn shown_rect(&self, rotation: u16) -> [f32; 4] {
+ self.shown(self.rect.map(f64::from), rotation).map(|v| v as f32)
+ }
+
+ /// [`Self::shown_rect`] for this comment with its `/Rect` at `rect` (one being moved or
+ /// resized).
+ pub fn shown(&self, rect: [f64; 4], rotation: u16) -> [f64; 4] {
+ if self.no_rotate { upright_rect(rect, rotation) } else { rect }
+ }
+
+ /// The `/Rect` that shows this comment in the user-space box `shown`: the inverse of
+ /// [`Self::shown`], for a box resized as drawn.
+ pub fn rect_for_shown(&self, shown: [f64; 4], rotation: u16) -> [f64; 4] {
+ if self.no_rotate { rect_from_upright(shown, rotation) } else { shown }
+ }
+}
+
+/// The user-space box a NoRotate annotation with `/Rect` `rect` is drawn in on a page turned
+/// clockwise by `rotation` (ISO 32000-2 §12.5.3): `rect` turned as far counterclockwise about its
+/// upper-left corner `(x0, y1)`, which stays where it is on the page. As displayed, the box's
+/// top-left is that corner, the rectangle's width runs across and its height down, as on an
+/// unturned page. `rect` itself for 0 or anything that isn't a quarter turn. The vendored
+/// renderer draws the appearance there (hayro-interpret patch 37).
+fn upright_rect(rect: [f64; 4], rotation: u16) -> [f64; 4] {
+ let [x0, y0, x1, y1] = [rect[0].min(rect[2]), rect[1].min(rect[3]), rect[0].max(rect[2]), rect[1].max(rect[3])];
+ let (w, h) = (x1 - x0, y1 - y0);
+ match rotation {
+ 90 => [x0, y1, x0 + h, y1 + w],
+ 180 => [x0 - w, y1, x0, y1 + h],
+ 270 => [x0 - h, y1 - w, x0, y1],
+ _ => [x0, y0, x1, y1],
+ }
+}
+
+/// The `/Rect` whose [`upright_rect`] is `shown`: `shown` turned back about the corner that
+/// stays put.
+fn rect_from_upright(shown: [f64; 4], rotation: u16) -> [f64; 4] {
+ let [s0, s1, s2, s3] = [shown[0].min(shown[2]), shown[1].min(shown[3]), shown[0].max(shown[2]), shown[1].max(shown[3])];
+ let (sw, sh) = (s2 - s0, s3 - s1);
+ // The upper-left corner of `/Rect` and the rectangle's width and height.
+ let ((x0, y1), w, h) = match rotation {
+ 90 => ((s0, s1), sh, sw),
+ 180 => ((s2, s1), sw, sh),
+ 270 => ((s2, s3), sh, sw),
+ _ => return [s0, s1, s2, s3],
+ };
+ [x0, y1 - h, x0 + w, y1]
+}
+
+/// Settle the reply links of a document's annotations: a reply keeps its `parent` only when
+/// following the links reaches a comment of its own within 64 steps. An `/IRT` to an unlisted
+/// object, a pop-up, the annotation itself or a loop leaves it a comment of its own, so it stays
+/// in view instead of hanging off nothing. Both comment readers (inspect, and the engine's list
+/// after an edit) run this.
+///
+/// Only comments can be parents: both readers leave links, form widgets, pop-ups and other
+/// non-markup annotations out of `annotations` (`pdfcraft_annot::is_comment_subtype`), so an
+/// `/IRT` to one of those finds no parent here. Pop-ups are skipped again in case a caller's list
+/// has them.
+pub fn link_replies(annotations: &mut [Annotation]) {
+ let at: HashMap<(usize, usize), usize> =
+ annotations.iter().enumerate().filter(|(_, a)| a.subtype != "Popup").map(|(i, a)| ((a.page, a.index), i)).collect();
+ let links: Vec<Option<usize>> =
+ annotations.iter().enumerate().map(|(i, a)| a.parent.and_then(|p| at.get(&p).copied()).filter(|&j| j != i)).collect();
+ for (i, a) in annotations.iter_mut().enumerate() {
+ let mut up = links.get(i).copied().flatten();
+ let mut settled = false;
+ for _ in 0..64 {
+ let Some(j) = up else { break };
+ up = links.get(j).copied().flatten();
+ if up.is_none() {
+ settled = true;
+ break;
+ }
+ }
+ if !settled {
+ a.parent = None;
+ }
+ }
+}
+
+/// The comment each reply's thread starts from, by the reply's page and `/Annots` position: a
+/// reply to a reply files under that comment too. Expects links [`link_replies`] settled.
+pub fn thread_tops(annotations: &[Annotation]) -> HashMap<(usize, usize), (usize, usize)> {
+ let parents: HashMap<(usize, usize), (usize, usize)> = annotations.iter().filter_map(|a| Some(((a.page, a.index), a.parent?))).collect();
+ parents
+ .iter()
+ .map(|(&reply, &first)| {
+ let mut top = first;
+ for _ in 0..64 {
+ let Some(&up) = parents.get(&top) else { break };
+ top = up;
+ }
+ (reply, top)
+ })
+ .collect()
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -785,6 +932,25 @@ impl<'a> Inspector<'a> {
{
info.has_javascript = true;
}
+ info.open_dest = catalog.get(b"OpenAction").ok().and_then(|o| self.open_dest(o));
+ }
+
+ /// The destination `/OpenAction` opens at (ISO 32000-2 §7.7.2 Table 29): an explicit
+ /// destination array, a `/GoTo` action's `/D`, or (leniently, since Table 29 asks for an array
+ /// or an action) a destination name or string; a name or string is looked up as a named
+ /// destination (§12.3.2.4). Any other action (a script, a remote go-to) has none here, and
+ /// neither has a page number past the end of the document.
+ fn open_dest(&self, action: &Object) -> Option<(usize, DestView)> {
+ let dest = match self.resolve(action) {
+ Object::Dictionary(d) => {
+ if d.get(b"S").ok().and_then(|o| self.resolve(o).as_name().ok()) != Some(&b"GoTo"[..]) {
+ return None;
+ }
+ d.get(b"D").ok()?
+ }
+ other => other,
+ };
+ self.dest(dest, 0).filter(|(page, _)| *page < self.page_ids.len())
}
// ── object helpers ──────────────────────────────────────────────────────────────────────
@@ -1097,7 +1263,13 @@ impl<'a> Inspector<'a> {
}
let open = d.get(b"Count").ok().and_then(|c| c.as_i64().ok()).is_some_and(|c| c > 0);
let title = self.text(d, b"Title").unwrap_or_default();
- listed.push((depth, OutlineItem { title, page, view, children: Vec::new(), open }));
+ let color = match d.get(b"C").map(|o| self.resolve(o)) {
+ Ok(Object::Array(c)) => outline_color(c.iter().map(|v| self.resolve(v).as_float().ok())),
+ _ => None,
+ };
+ let flags = d.get(b"F").ok().and_then(|f| self.resolve(f).as_i64().ok()).unwrap_or(0);
+ let (italic, bold) = (flags & 1 != 0, flags & 2 != 0);
+ listed.push((depth, OutlineItem { title, page, view, children: Vec::new(), open, color, italic, bold }));
}
(nest_outline(listed), more)
}
@@ -1260,13 +1432,12 @@ impl<'a> Inspector<'a> {
pages.sort_unstable_by_key(|&(_, page)| page);
// An annotation, or a whole `/Annots` array, that several entries or pages list is on the
// first of them (§12.5.2 allows one page per annotation). Both are told apart by the object
- // a reference resolves to, since an indirect object may itself hold a reference.
+ // a reference resolves to, since an indirect object may itself hold a reference. Where each
+ // annotation is listed is collected before any is read, so a reply's `/IRT` finds its
+ // parent by reference even when the parent comes later.
let mut seen_arrays = HashSet::new();
- let mut seen_annotations = HashSet::new();
- let mut kept = 0usize;
- // Once the comment budget is spent, comments are no longer built, but links and attachments
- // are still listed.
- let mut comments_full = false;
+ let mut slots: HashMap<ObjectId, (usize, usize)> = HashMap::new();
+ let mut entries = Vec::new();
for (id, page) in pages {
let Ok(page_dict) = self.doc.get_dictionary(id) else { continue };
if let Ok(annots) = page_dict.get(b"Annots")
@@ -1277,121 +1448,131 @@ impl<'a> Inspector<'a> {
}
let Ok(Object::Array(annots)) = page_dict.get(b"Annots").map(|o| self.resolve(o)) else { continue };
for (index, a) in annots.iter().enumerate() {
- if let Some(r) = self.resolved_id(a)
- && !seen_annotations.insert(r)
- {
- continue;
+ if let Some(r) = self.resolved_id(a) {
+ let Entry::Vacant(slot) = slots.entry(r) else { continue };
+ slot.insert((page, index));
}
- let Some(d) = self.dict(a) else { continue };
- let Some(subtype) = self.name(d, b"Subtype") else { continue };
- if subtype == "FileAttachment"
- && let Ok(fs) = d.get(b"FS")
- {
- let fallback = |budget: &mut usize| self.budgeted_text(d, b"Contents", budget);
- info.attachments.push(self.attachment(fs, AttachmentSource::Annotation { page, index }, text_budget, fallback));
- }
- if subtype == "Link" {
- if let Some(link) = self.link(page, index, d, text_budget) {
- if matches!(&link.target, LinkTarget::Other(s) if s == "JavaScript") {
- info.has_javascript = true;
- }
- info.links.push(link);
+ entries.push((page, index, a));
+ }
+ }
+ let mut kept = 0usize;
+ // Once the comment budget is spent, comments are no longer built, but links and attachments
+ // are still listed.
+ let mut comments_full = false;
+ for (page, index, a) in entries {
+ let Some(d) = self.dict(a) else { continue };
+ let Some(subtype) = self.name(d, b"Subtype") else { continue };
+ if subtype == "FileAttachment"
+ && let Ok(fs) = d.get(b"FS")
+ {
+ let fallback = |budget: &mut usize| self.budgeted_text(d, b"Contents", budget);
+ info.attachments.push(self.attachment(fs, AttachmentSource::Annotation { page, index }, text_budget, fallback));
+ }
+ if subtype == "Link" {
+ if let Some(link) = self.link(page, index, d, text_budget) {
+ if matches!(&link.target, LinkTarget::Other(s) if s == "JavaScript") {
+ info.has_javascript = true;
}
- continue;
+ info.links.push(link);
}
- // Not comments: form widgets, pop-ups and non-markup annotations such as the
- // Screen annotation that drives a LaTeX `animate` player (keep in step with
- // `pdfcraft_annot::is_comment_subtype`).
- if matches!(subtype.as_str(), "Widget" | "Popup" | "Screen" | "Movie" | "RichMedia" | "3D" | "PrinterMark" | "TrapNet" | "Watermark")
+ continue;
+ }
+ // Not comments: form widgets, pop-ups and non-markup annotations such as the
+ // Screen annotation that drives a LaTeX `animate` player (keep in step with
+ // `pdfcraft_annot::is_comment_subtype`).
+ if matches!(subtype.as_str(), "Widget" | "Popup" | "Screen" | "Movie" | "RichMedia" | "3D" | "PrinterMark" | "TrapNet" | "Watermark") {
+ continue;
+ }
+ if comments_full {
+ continue;
+ }
+ let rect = rect4(self.resolve(d.get(b"Rect").unwrap_or(&Object::Null)));
+ let mut color = match d.get(b"C").map(|o| self.resolve(o)) {
+ Ok(Object::Array(c)) if c.len() == 3 => {
+ let f = |i: usize| c[i].as_float().unwrap_or(0.0);
+ Some([f(0), f(1), f(2)])
+ }
+ _ => None,
+ };
+ // A text box's /C is its background; its text colour is in /DA.
+ if subtype == "FreeText"
+ && let Some(da) = self.text(d, b"DA")
+ {
+ let t: Vec<&str> = da.split_whitespace().collect();
+ if let Some(i) = t.iter().position(|x| *x == "rg")
+ && i >= 3
{
- continue;
+ let f = |k: usize| t[k].parse::<f32>().unwrap_or(0.0);
+ color = Some([f(i - 3), f(i - 2), f(i - 1)]);
}
- if comments_full {
- continue;
+ }
+ let quads = match d.get(b"QuadPoints").map(|o| self.resolve(o)) {
+ Ok(Object::Array(q)) => {
+ let v: Vec<f32> = q.iter().map(|o| o.as_float().unwrap_or(0.0)).collect();
+ v.as_chunks::<8>().0.to_vec()
}
- let rect = rect4(self.resolve(d.get(b"Rect").unwrap_or(&Object::Null)));
- let mut color = match d.get(b"C").map(|o| self.resolve(o)) {
- Ok(Object::Array(c)) if c.len() == 3 => {
- let f = |i: usize| c[i].as_float().unwrap_or(0.0);
- Some([f(0), f(1), f(2)])
- }
+ _ => Vec::new(),
+ };
+ let in_reply_to = d.get(b"IRT").ok().and_then(|o| self.dict(o)).and_then(|p| self.text(p, b"NM"));
+ let parent = d.get(b"IRT").ok().and_then(|o| self.resolved_id(o)).and_then(|r| slots.get(&r).copied());
+ let fill_sign = self.is_fill_sign(d, &subtype);
+ let opacity =
+ d.get(b"CA").ok().and_then(|o| self.resolve(o).as_float().ok()).filter(|v| v.is_finite()).map_or(1.0, |v| v.clamp(0.0, 1.0));
+ let width = d
+ .get(b"BS")
+ .ok()
+ .and_then(|o| self.dict(o))
+ .and_then(|bs| bs.get(b"W").ok().and_then(|w| self.resolve(w).as_float().ok()))
+ .or_else(|| match d.get(b"Border").map(|o| self.resolve(o)) {
+ Ok(Object::Array(b)) => b.get(2).and_then(|w| w.as_float().ok()),
_ => None,
- };
- // A text box's /C is its background; its text colour is in /DA.
- if subtype == "FreeText"
- && let Some(da) = self.text(d, b"DA")
- {
- let t: Vec<&str> = da.split_whitespace().collect();
- if let Some(i) = t.iter().position(|x| *x == "rg")
- && i >= 3
- {
- let f = |k: usize| t[k].parse::<f32>().unwrap_or(0.0);
- color = Some([f(i - 3), f(i - 2), f(i - 1)]);
- }
- }
- let quads = match d.get(b"QuadPoints").map(|o| self.resolve(o)) {
- Ok(Object::Array(q)) => {
- let v: Vec<f32> = q.iter().map(|o| o.as_float().unwrap_or(0.0)).collect();
- v.as_chunks::<8>().0.to_vec()
- }
- _ => Vec::new(),
- };
- let in_reply_to = d.get(b"IRT").ok().and_then(|o| self.dict(o)).and_then(|p| self.text(p, b"NM"));
- let fill_sign = self.is_fill_sign(d, &subtype);
- let opacity =
- d.get(b"CA").ok().and_then(|o| self.resolve(o).as_float().ok()).filter(|v| v.is_finite()).map_or(1.0, |v| v.clamp(0.0, 1.0));
- let width = d
- .get(b"BS")
- .ok()
- .and_then(|o| self.dict(o))
- .and_then(|bs| bs.get(b"W").ok().and_then(|w| self.resolve(w).as_float().ok()))
- .or_else(|| match d.get(b"Border").map(|o| self.resolve(o)) {
- Ok(Object::Array(b)) => b.get(2).and_then(|w| w.as_float().ok()),
- _ => None,
- })
- .filter(|w| w.is_finite() && *w >= 0.0);
- // Keep in step with `pdfcraft_annot::summaries`.
- let key: &[u8] = if subtype == "Line" { b"L" } else { b"Vertices" };
- let points = match d.get(key).map(|o| self.resolve(o)) {
- Ok(Object::Array(v)) if matches!(subtype.as_str(), "Line" | "PolyLine" | "Polygon") => {
- let v: Vec<f32> = v.iter().map(|o| o.as_float().unwrap_or(0.0)).collect();
- let pts: Vec<[f32; 2]> = v.as_chunks::<2>().0.to_vec();
- if subtype == "Line" && pts.len() != 2 { Vec::new() } else { pts }
- }
- _ => Vec::new(),
- };
- let annotation = Annotation {
- page,
- subtype,
- author: self.text(d, b"T"),
- // Acrobat ends lines with CR, which the interface would draw as nothing (keep
- // in step with `pdfcraft_annot::summaries`).
- contents: self.text(d, b"Contents").map(|s| s.replace("\r\n", "\n").replace('\r', "\n")),
- modified: self.text(d, b"M").map(|m| pretty_date(&m)),
- modified_raw: self.text(d, b"M"),
- name: self.text(d, b"NM"),
- in_reply_to,
- rect,
- color,
- index,
- state: self.text(d, b"State"),
- quads,
- locked: d.get(b"F").ok().and_then(|f| self.resolve(f).as_i64().ok()).unwrap_or(0) & 128 != 0,
- intent: self.name(d, b"IT"),
- fill_sign,
- opacity,
- width,
- points,
- };
- kept = kept.saturating_add(retained(&annotation));
- if kept > MAX_ANNOTATION_BYTES {
- comments_full = true;
- continue;
+ })
+ .filter(|w| w.is_finite() && *w >= 0.0);
+ // Keep in step with `pdfcraft_annot::summaries`.
+ let key: &[u8] = if subtype == "Line" { b"L" } else { b"Vertices" };
+ let points = match d.get(key).map(|o| self.resolve(o)) {
+ Ok(Object::Array(v)) if matches!(subtype.as_str(), "Line" | "PolyLine" | "Polygon") => {
+ let v: Vec<f32> = v.iter().map(|o| o.as_float().unwrap_or(0.0)).collect();
+ let pts: Vec<[f32; 2]> = v.as_chunks::<2>().0.to_vec();
+ if subtype == "Line" && pts.len() != 2 { Vec::new() } else { pts }
}
- info.annotations.push(annotation);
+ _ => Vec::new(),
+ };
+ let annotation = Annotation {
+ page,
+ subtype,
+ author: self.text(d, b"T"),
+ // Acrobat ends lines with CR, which the interface would draw as nothing (keep
+ // in step with `pdfcraft_annot::summaries`).
+ contents: self.text(d, b"Contents").map(|s| s.replace("\r\n", "\n").replace('\r', "\n")),
+ modified: self.text(d, b"M").map(|m| pretty_date(&m)),
+ modified_raw: self.text(d, b"M"),
+ name: self.text(d, b"NM"),
+ in_reply_to,
+ parent,
+ grouped: self.name(d, b"RT").as_deref() == Some("Group"),
+ rect,
+ color,
+ index,
+ state: self.text(d, b"State"),
+ quads,
+ locked: d.get(b"F").ok().and_then(|f| self.resolve(f).as_i64().ok()).unwrap_or(0) & 128 != 0,
+ intent: self.name(d, b"IT"),
+ fill_sign,
+ opacity,
+ width,
+ no_rotate: d.get(b"F").is_ok_and(|f| draw_flags(self.resolve(f)) & 16 != 0),
+ points,
+ };
+ kept = kept.saturating_add(retained(&annotation));
+ if kept > MAX_ANNOTATION_BYTES {
+ comments_full = true;
+ continue;
}
+ info.annotations.push(annotation);
}
info.annotations.sort_by(|a, b| a.page.cmp(&b.page).then(b.rect[3].total_cmp(&a.rect[3])));
+ link_replies(&mut info.annotations);
}
fn link(&self, page: usize, index: usize, d: &Dictionary, text_budget: &mut usize) -> Option<Link> {
@@ -1415,6 +1596,7 @@ impl<'a> Inspector<'a> {
}
Some("SetOCGState") => self.layer_state(a),
Some("GoToR") => self.remote_go_to(a).unwrap_or_else(|| LinkTarget::Other("GoToR".into())),
+ Some("Launch") => self.launch_pdf(a).unwrap_or_else(|| LinkTarget::Other("Launch".into())),
Some(other) => LinkTarget::Other(other.to_string()),
None => return None,
}
@@ -1423,25 +1605,7 @@ impl<'a> Inspector<'a> {
}
fn remote_go_to(&self, action: &Dictionary) -> Option<LinkTarget> {
- if self.name(action, b"FS").as_deref() == Some("URL") {
- return None;
- }
- let file = match self.resolve(action.get(b"F").ok()?) {
- Object::String(bytes, _) => limited_pdf_string(bytes, MAX_REMOTE_FILE_SPEC_BYTES)?,
- Object::Dictionary(spec) => {
- if self.name(spec, b"FS").as_deref() == Some("URL") {
- return None;
- }
- spec.get(b"UF")
- .ok()
- .and_then(|o| self.pdf_text(o, MAX_REMOTE_FILE_SPEC_BYTES))
- .or_else(|| spec.get(b"F").ok().and_then(|o| self.pdf_text(o, MAX_REMOTE_FILE_SPEC_BYTES)))?
- }
- _ => return None,
- };
- if file.is_empty() {
- return None;
- }
+ let file = self.action_file(action)?;
let destination = match action.get(b"D") {
Err(_) => RemoteDestination::Default,
Ok(o) => match self.resolve(o) {
@@ -1468,11 +1632,54 @@ impl<'a> Inspector<'a> {
_ => return None,
},
};
- let new_window = match action.get(b"NewWindow").map(|o| self.resolve(o)) {
+ Some(LinkTarget::RemoteGoTo { launch: false, file, destination, new_window: self.new_window(action) })
+ }
+
+ /// The non-empty local file an action's `/F` names (a string or a file specification), shared
+ /// by GoToR and Launch. A URL file system (`/FS /URL`) names no local file.
+ fn action_file(&self, action: &Dictionary) -> Option<String> {
+ if self.name(action, b"FS").as_deref() == Some("URL") {
+ return None;
+ }
+ let file = match self.resolve(action.get(b"F").ok()?) {
+ Object::String(bytes, _) => limited_pdf_string(bytes, MAX_REMOTE_FILE_SPEC_BYTES)?,
+ Object::Dictionary(spec) => {
+ if self.name(spec, b"FS").as_deref() == Some("URL") {
+ return None;
+ }
+ spec.get(b"UF")
+ .ok()
+ .and_then(|o| self.pdf_text(o, MAX_REMOTE_FILE_SPEC_BYTES))
+ .or_else(|| spec.get(b"F").ok().and_then(|o| self.pdf_text(o, MAX_REMOTE_FILE_SPEC_BYTES)))?
+ }
+ _ => return None,
+ };
+ (!file.is_empty()).then_some(file)
+ }
+
+ fn new_window(&self, action: &Dictionary) -> Option<bool> {
+ match action.get(b"NewWindow").map(|o| self.resolve(o)) {
Ok(Object::Boolean(value)) => Some(*value),
_ => None,
- };
- Some(LinkTarget::RemoteGoTo { file, destination, new_window })
+ }
+ }
+
+ /// A Launch action (ISO 32000-2 §12.6.4.6, Table 207) whose `/F` names a `.pdf` file, read as
+ /// the remote Go-To to that file's first page that it amounts to (#4168). Launching anything
+ /// else, or with the deprecated `/Win` launch parameters (an application, an operation, its
+ /// arguments), is not followed: a document must not start programs. `\` separators, which
+ /// Windows writers put in such paths, are read as `/` (§7.11.2.1 separates components with
+ /// `/`) when the path has no `/` of its own. Launch has no `/D`, so one present (written
+ /// for GoToR, or junk) is ignored rather than checked as a destination.
+ fn launch_pdf(&self, action: &Dictionary) -> Option<LinkTarget> {
+ if action.has(b"Win") {
+ return None;
+ }
+ let file = self.action_file(action)?;
+ let new_window = self.new_window(action);
+ let file = if file.contains('/') { file } else { file.replace('\\', "/") };
+ let pdf = file.rsplit('/').next().is_some_and(|name| name.len() > 4 && name.to_ascii_lowercase().ends_with(".pdf"));
+ pdf.then_some(LinkTarget::RemoteGoTo { launch: true, file, destination: RemoteDestination::Default, new_window })
}
fn pdf_text(&self, o: &Object, max_bytes: usize) -> Option<String> {
@@ -1824,6 +2031,18 @@ fn limited_pdf_string(bytes: &[u8], max_bytes: usize) -> Option<String> {
(text.len() <= max_bytes).then_some(text)
}
+/// A bookmark title's colour from its `/C` entries, each kept within 0–1 (ISO 32000-2 §12.3.3,
+/// Table 151: "An array of three numbers in the range 0.0 to 1.0, representing the components in
+/// the DeviceRGB colour space"). Black, the default, and anything that isn't three numbers give
+/// `None`.
+pub(crate) fn outline_color(values: impl Iterator<Item = Option<f32>>) -> Option<[f32; 3]> {
+ let v: Vec<Option<f32>> = values.take(4).collect();
+ let [Some(r), Some(g), Some(b)] = v.as_slice() else { return None };
+ // A number past the range, however large, is kept at its edge.
+ let rgb = [*r, *g, *b].map(|c| c.clamp(0.0, 1.0));
+ (rgb != [0.0; 3]).then_some(rgb)
+}
+
/// Nests a pre-order list of `(depth, item)` into the outline tree.
fn nest_outline(listed: Vec<(usize, OutlineItem)>) -> Vec<OutlineItem> {
let mut roots = Vec::new();
@@ -1851,6 +2070,17 @@ fn close_outline(open: &mut Vec<(usize, OutlineItem)>, roots: &mut Vec<OutlineIt
}
}
+/// An annotation's `/F` as the renderer reads it: a real is truncated, and a value that isn't a
+/// `u32` counts as no flags.
+fn draw_flags(o: &Object) -> u32 {
+ let f = match o {
+ Object::Integer(i) => *i,
+ Object::Real(r) => *r as i64,
+ _ => 0,
+ };
+ u32::try_from(f).unwrap_or(0)
+}
+
fn rect4(o: &Object) -> [f32; 4] {
match o {
Object::Array(a) if a.len() == 4 => {
@@ -2448,6 +2678,59 @@ mod tests {
assert_eq!(p.view_rect_to_quad([0.0, 0.0, 10.0, 5.0]), [10.0, 320.0, 20.0, 320.0, 10.0, 315.0, 20.0, 315.0]);
}
+ /// #2583: a NoRotate comment is drawn upright with its top-left as displayed at the upper-left
+ /// corner of `/Rect`, its width across and its height down; a box resized as drawn maps back to
+ /// the `/Rect` that shows it. Other comments, and pages that aren't quarter-turned, keep `/Rect`.
+ #[test]
+ fn no_rotate_comments_are_shown_upright_from_their_corner_and_back() {
+ let mut note = super::Annotation {
+ page: 0,
+ subtype: "Text".into(),
+ author: None,
+ contents: None,
+ modified: None,
+ modified_raw: None,
+ name: None,
+ in_reply_to: None,
+ parent: None,
+ grouped: false,
+ rect: [40.0, 50.0, 70.0, 70.0],
+ color: None,
+ index: 0,
+ state: None,
+ quads: Vec::new(),
+ locked: false,
+ intent: None,
+ fill_sign: false,
+ opacity: 1.0,
+ width: None,
+ no_rotate: true,
+ points: Vec::new(),
+ };
+ let rect = note.rect.map(f64::from);
+ for rotation in [0u16, 90, 180, 270, 45] {
+ let (w, h) = if rotation % 180 == 90 { (140.0, 200.0) } else { (200.0, 140.0) };
+ let p = super::PageInfo { width: w, height: h, label: String::new(), crop: [0.0, 0.0, 200.0, 140.0], rotation };
+ let shown = note.shown_rect(rotation);
+ let (a, b) = (p.user_to_view(shown[0], shown[1]), p.user_to_view(shown[2], shown[3]));
+ let [cx, cy] = p.user_to_view(40.0, 70.0);
+ let want = [cx, cy, cx + 30.0, cy + 20.0];
+ let got = [a[0].min(b[0]), a[1].min(b[1]), a[0].max(b[0]), a[1].max(b[1])];
+ assert!(got.iter().zip(want).all(|(g, w)| (g - w).abs() < 1e-3), "{rotation}: shown {got:?}, want {want:?}");
+ assert_eq!(note.rect_for_shown(note.shown(rect, rotation), rotation), rect, "{rotation}");
+ // Moved by (5, -7) and resized to 50 × 10 as drawn, back to a /Rect.
+ let resized = [shown[0] as f64 + 5.0, shown[1] as f64 - 7.0, 0.0, 0.0];
+ let across = if rotation % 180 == 90 { [10.0, 50.0] } else { [50.0, 10.0] };
+ let resized = [resized[0], resized[1], resized[0] + across[0], resized[1] + across[1]];
+ let back = note.rect_for_shown(resized, rotation);
+ assert_eq!((back[2] - back[0], back[3] - back[1]), (50.0, 10.0), "{rotation}: {back:?}");
+ assert_eq!(note.shown(back, rotation), resized, "{rotation}");
+ }
+ note.no_rotate = false;
+ assert_eq!(note.shown_rect(90), note.rect);
+ assert_eq!(note.rect_for_shown([1.0, 2.0, 3.0, 4.0], 90), [1.0, 2.0, 3.0, 4.0]);
+ }
+
use super::*;
#[test]
@@ -2986,6 +3269,39 @@ trailer << /Root 1 0 R >>
}
}
+ /// A reply finds its comment where the listing keeps it: on the first page of a page-shared
+ /// `/Annots` array, whether its `/IRT` names the comment or an object holding a reference to it.
+ #[test]
+ fn a_reply_finds_its_comment_through_a_reference_chain_and_a_shared_array() {
+ let pdf = "%PDF-1.7\n1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj\n\
+ 2 0 obj << /Type /Pages /Kids [3 0 R 4 0 R] /Count 2 >> endobj\n\
+ 3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Annots 7 0 R >> endobj\n\
+ 4 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Annots 7 0 R >> endobj\n\
+ 5 0 obj 6 0 R endobj\n\
+ 6 0 obj << /Type /Annot /Subtype /Text /Rect [0 0 1 1] /Contents (comment) >> endobj\n\
+ 7 0 obj [5 0 R 8 0 R 9 0 R] endobj\n\
+ 8 0 obj << /Type /Annot /Subtype /Text /Rect [0 0 1 1] /Contents (to the comment) /IRT 6 0 R >> endobj\n\
+ 9 0 obj << /Type /Annot /Subtype /Text /Rect [0 0 1 1] /Contents (through the chain) /IRT 5 0 R >> endobj\n\
+ trailer << /Root 1 0 R >>\n%%EOF";
+ let mut doc = Document::load_mem(pdf.as_bytes()).expect("loads");
+ let mut saved = Vec::new();
+ doc.save_to(&mut saved).expect("saves");
+ let lazy = LazyStructure::new(Arc::new(saved), None).expect("opens");
+ let page = PageInfo { width: 200.0, height: 200.0, crop: [0.0, 0.0, 200.0, 200.0], rotation: 0, label: String::new() };
+ for reader in [&doc as &dyn Structure, &lazy] {
+ let mut info = DocInfo { pages: vec![page.clone(), page.clone()], ..Default::default() };
+ Inspector::new(reader).fill(&mut info);
+ let notes = &info.annotations;
+ assert_eq!(notes.len(), 3, "{notes:?}");
+ let comment = notes.iter().find(|a| a.contents.as_deref() == Some("comment")).expect("listed");
+ assert_eq!((comment.page, comment.index, comment.is_reply()), (0, 0, false));
+ for reply in ["to the comment", "through the chain"] {
+ let a = notes.iter().find(|a| a.contents.as_deref() == Some(reply)).expect("listed");
+ assert_eq!((a.page, a.parent), (0, Some((0, 0))), "{reply}");
+ }
+ }
+ }
+
/// A conversion rejected as too long, or trimmed short or to nothing, still spends the raw
/// length, so a string many entries share is converted only a few times.
#[test]
@@ -3301,6 +3617,46 @@ trailer << /Root 1 0 R >>
);
}
+ /// #4168: a Launch action naming a `.pdf` file is read as the link to that file it amounts
+ /// to, `\` separators included, and a stray `/D` (which Launch has no use for) doesn't stop
+ /// it. One naming anything else, with no file, or with `/Win` launch parameters stays an
+ /// action that isn't followed.
+ #[test]
+ fn launch_actions_that_name_a_pdf_open_it_like_a_remote_link() {
+ let pdf = "%PDF-1.7\n1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj\n\
+ 2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 300 400] >> endobj\n\
+ 3 0 obj << /Type /Page /Parent 2 0 R /Annots [30 0 R 31 0 R 32 0 R 33 0 R 34 0 R 35 0 R 36 0 R 37 0 R 38 0 R] >> endobj\n\
+ 30 0 obj << /Type /Annot /Subtype /Link /Rect [0 0 10 10] /A << /S /Launch /F (..\\\\se\\\\se_ST.pdf) >> >> endobj\n\
+ 31 0 obj << /Type /Annot /Subtype /Link /Rect [0 20 10 30] /A << /S /Launch /F << /Type /Filespec /F (chapters/Two.PDF) >> /NewWindow true >> >> endobj\n\
+ 32 0 obj << /Type /Annot /Subtype /Link /Rect [0 40 10 50] /A << /S /Launch /F (tool.exe) >> >> endobj\n\
+ 33 0 obj << /Type /Annot /Subtype /Link /Rect [0 60 10 70] /A << /S /Launch /F (a.pdf) /Win << /F (cmd.exe) /P (/c x) >> >> >> endobj\n\
+ 34 0 obj << /Type /Annot /Subtype /Link /Rect [0 80 10 90] /A << /S /Launch /Win << /F (b.pdf) >> >> >> endobj\n\
+ 35 0 obj << /Type /Annot /Subtype /Link /Rect [0 100 10 110] /A << /S /Launch /F (.pdf) >> >> endobj\n\
+ 36 0 obj << /Type /Annot /Subtype /Link /Rect [0 120 10 130] /A << /S /Launch /F (dir/a\\\\b.pdf) >> >> endobj\n\
+ 37 0 obj << /Type /Annot /Subtype /Link /Rect [0 140 10 150] /A << /S /Launch /FS /URL /F (https://example.com/x.pdf) >> >> endobj\n\
+ 38 0 obj << /Type /Annot /Subtype /Link /Rect [0 160 10 170] /A << /S /Launch /F (c.pdf) /D 0 >> >> endobj\n\
+ trailer << /Root 1 0 R >>\n%%EOF";
+ let info = inspect(Arc::new(pdf.as_bytes().to_vec()), None).expect("opens");
+ let targets: Vec<_> = info.links.iter().map(|l| l.target.clone()).collect();
+ let launch =
+ |file: &str, new_window| LinkTarget::RemoteGoTo { launch: true, file: file.into(), destination: RemoteDestination::Default, new_window };
+ let other = || LinkTarget::Other("Launch".into());
+ assert_eq!(
+ targets,
+ [
+ launch("../se/se_ST.pdf", None),
+ launch("chapters/Two.PDF", Some(true)),
+ other(),
+ other(),
+ other(),
+ other(),
+ launch("dir/a\\b.pdf", None),
+ other(),
+ launch("c.pdf", None),
+ ]
+ );
+ }
+
#[test]
fn links_read_bounded_local_remote_go_to_actions() {
use DestView::{Fit, Xyz};
@@ -3329,6 +3685,7 @@ trailer << /Root 1 0 R >>
let targets: Vec<_> = info.links.iter().map(|l| (l.index, l.target.clone())).collect();
let huge_page_target = usize::try_from(i64::MAX)
.map(|page| LinkTarget::RemoteGoTo {
+ launch: false,
file: "chapter.pdf".into(),
destination: RemoteDestination::Page { page, view: Fit },
new_window: None,
@@ -3340,6 +3697,7 @@ trailer << /Root 1 0 R >>
(
1,
LinkTarget::RemoteGoTo {
+ launch: false,
file: "chapters/remote.pdf".into(),
destination: RemoteDestination::Page { page: 2, view: Xyz { left: Some(10.0), top: Some(20.0), zoom: Some(1.5) } },
new_window: Some(true),
@@ -3348,16 +3706,33 @@ trailer << /Root 1 0 R >>
(
2,
LinkTarget::RemoteGoTo {
+ launch: false,
file: "foo.pdf".into(),
destination: RemoteDestination::Page { page: 0, view: Fit },
new_window: Some(false),
}
),
- (3, LinkTarget::RemoteGoTo { file: "remote.pdf".into(), destination: RemoteDestination::Default, new_window: None }),
- (4, LinkTarget::RemoteGoTo { file: "chapter.pdf".into(), destination: RemoteDestination::Named("chapter".into()), new_window: None }),
+ (3, LinkTarget::RemoteGoTo { launch: false, file: "remote.pdf".into(), destination: RemoteDestination::Default, new_window: None }),
+ (
+ 4,
+ LinkTarget::RemoteGoTo {
+ launch: false,
+ file: "chapter.pdf".into(),
+ destination: RemoteDestination::Named("chapter".into()),
+ new_window: None
+ }
+ ),
(5, LinkTarget::Other("GoToR".into())),
(6, LinkTarget::Other("GoToR".into())),
- (7, LinkTarget::RemoteGoTo { file: "chapter.pdf".into(), destination: RemoteDestination::Named("chapter".into()), new_window: None }),
+ (
+ 7,
+ LinkTarget::RemoteGoTo {
+ launch: false,
+ file: "chapter.pdf".into(),
+ destination: RemoteDestination::Named("chapter".into()),
+ new_window: None
+ }
+ ),
(8, LinkTarget::Other("GoToR".into())),
(9, LinkTarget::Other("GoToR".into())),
(10, huge_page_target),
@@ -3607,6 +3982,54 @@ trailer << /Root 1 0 R >>
items.iter().map(|o| if o.children.is_empty() { o.title.clone() } else { format!("{}[{}]", o.title, shape(&o.children).join(",")) }).collect()
}
+ /// #3193: a bookmark's colour and style (ISO 32000-2 §12.3.3, Tables 151 and 152). `/C` is
+ /// three numbers within 0–1 (one outside is kept at the edge); black, the default, and a `/C`
+ /// that isn't three numbers read as no colour. `/F` bit 1 is italic, bit 2 bold.
+ #[test]
+ fn outline_items_carry_their_colour_and_style() {
+ let titles = [
+ ("Plain", ""),
+ ("Red", "/C [1 0 0]"),
+ ("Italic", "/F 1"),
+ ("Bold", "/F 2"),
+ ("Both", "/C [0 0 1] /F 3"),
+ ("Black", "/C [0 0 0]"),
+ ("Bright", "/C [2 -1 0.5]"),
+ ("Short", "/C [1 0]"),
+ ("Long", "/C [1 0 0 0]"),
+ ("Named", "/C [1 /x 0]"),
+ ("Other bits", "/F 4"),
+ ];
+ let n = titles.len();
+ let items: Vec<String> = titles
+ .iter()
+ .enumerate()
+ .map(|(k, (title, extra))| {
+ let prev = if k == 0 { String::new() } else { format!(" /Prev {} 0 R", 4 + k) };
+ let next = if k + 1 == n { String::new() } else { format!(" /Next {} 0 R", 6 + k) };
+ format!("<< /Title ({title}) /Parent 4 0 R{prev}{next} /Dest [3 0 R /Fit] {extra} >>")
+ })
+ .collect();
+ let info = inspect(Arc::new(outline_file(&items)), None).expect("opens");
+ let got: Vec<(&str, Option<[f32; 3]>, bool, bool)> = info.outline.iter().map(|o| (o.title.as_str(), o.color, o.italic, o.bold)).collect();
+ assert_eq!(
+ got,
+ [
+ ("Plain", None, false, false),
+ ("Red", Some([1.0, 0.0, 0.0]), false, false),
+ ("Italic", None, true, false),
+ ("Bold", None, false, true),
+ ("Both", Some([0.0, 0.0, 1.0]), true, true),
+ ("Black", None, false, false),
+ ("Bright", Some([1.0, 0.0, 0.5]), false, false),
+ ("Short", None, false, false),
+ ("Long", None, false, false),
+ ("Named", None, false, false),
+ ("Other bits", None, false, false),
+ ]
+ );
+ }
+
#[test]
fn outline_window_keeps_the_first_bookmarks_and_says_when_more_follow() {
const COUNT: usize = OUTLINE_WINDOW + 5;
@@ -4020,3 +4443,112 @@ mod open_action_javascript_tests {
assert!(!info.has_javascript, "a /GoTo /OpenAction is not JavaScript");
}
}
+
+#[cfg(test)]
+mod open_dest_tests {
+ use std::sync::Arc;
+
+ use super::{DestView, inspect};
+
+ /// Three 612×792 pages (objects 3, 4, 5); `catalog` is added to the catalog dictionary and
+ /// `extra` become objects 6, 7, ….
+ fn pdf(catalog: &str, extra: &[String]) -> Vec<u8> {
+ let mut objs =
+ vec![format!("<< /Type /Catalog /Pages 2 0 R {catalog} >>"), "<< /Type /Pages /Kids [3 0 R 4 0 R 5 0 R] /Count 3 >>".to_string()];
+ for _ in 0..3 {
+ objs.push("<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >>".to_string());
+ }
+ objs.extend(extra.iter().cloned());
+ let mut out = b"%PDF-1.7\n".to_vec();
+ let mut offsets = Vec::new();
+ for (i, o) in objs.iter().enumerate() {
+ offsets.push(out.len());
+ out.extend_from_slice(format!("{} 0 obj\n{o}\nendobj\n", i + 1).as_bytes());
+ }
+ let xref = out.len();
+ out.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objs.len() + 1).as_bytes());
+ for o in offsets {
+ out.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes());
+ }
+ out.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objs.len() + 1).as_bytes());
+ out
+ }
+
+ fn open_dest(catalog: &str, extra: &[String]) -> Option<(usize, DestView)> {
+ inspect(Arc::new(pdf(catalog, extra)), None).expect("inspects").open_dest
+ }
+
+ const XYZ: DestView = DestView::Xyz { left: Some(100.0), top: Some(500.0), zoom: Some(2.0) };
+
+ #[test]
+ fn an_explicit_destination_opens_at_its_page_and_position() {
+ assert_eq!(open_dest("/OpenAction [5 0 R /XYZ 100 500 2]", &[]), Some((2, XYZ)));
+ assert_eq!(open_dest("/OpenAction [4 0 R /FitH 400]", &[]), Some((1, DestView::FitH { top: Some(400.0) })));
+ // Indirect, and a zoom of 0 keeps the zoom (Table 149).
+ assert_eq!(
+ open_dest("/OpenAction 6 0 R", &["[4 0 R /XYZ 0 792 0]".into()]),
+ Some((1, DestView::Xyz { left: Some(0.0), top: Some(792.0), zoom: None }))
+ );
+ }
+
+ #[test]
+ fn a_go_to_action_opens_at_its_destination_explicit_or_named() {
+ assert_eq!(open_dest("/OpenAction << /S /GoTo /D [5 0 R /XYZ 100 500 2] >>", &[]), Some((2, XYZ)));
+ // A name, through the PDF 1.1 catalog /Dests dictionary (§12.3.2.4).
+ assert_eq!(open_dest("/OpenAction << /S /GoTo /D /there >> /Dests << /there [5 0 R /XYZ 100 500 2] >>", &[]), Some((2, XYZ)));
+ // A byte string, through the /Names /Dests name tree, whose value is a dictionary with /D.
+ assert_eq!(
+ open_dest(
+ "/OpenAction << /S /GoTo /D (there) >> /Names << /Dests 6 0 R >>",
+ &["<< /Kids [7 0 R] >>".into(), "<< /Names [(here) [3 0 R /Fit] (there) << /D [5 0 R /XYZ 100 500 2] >>] >>".into()]
+ ),
+ Some((2, XYZ))
+ );
+ }
+
+ #[test]
+ fn an_open_action_given_as_a_name_or_string_is_looked_up() {
+ assert_eq!(open_dest("/OpenAction /there /Dests << /there [4 0 R /Fit] >>", &[]), Some((1, DestView::Fit)));
+ assert_eq!(
+ open_dest("/OpenAction (there) /Names << /Dests << /Names [(there) [5 0 R /FitV 30]] >> >>", &[]),
+ Some((2, DestView::FitV { left: Some(30.0) }))
+ );
+ }
+
+ #[test]
+ fn an_open_action_that_goes_nowhere_here_has_no_destination() {
+ for catalog in [
+ "",
+ "/OpenAction << /S /JavaScript /JS (app.alert(1)) >>",
+ // A remote go-to's /D is a page of another file.
+ "/OpenAction << /S /GoToR /F (other.pdf) /D [1 /Fit] >>",
+ "/OpenAction << /D [4 0 R /Fit] >>",
+ // An unknown name, and no name dictionaries at all.
+ "/OpenAction << /S /GoTo /D /missing >> /Dests << /there [4 0 R /Fit] >>",
+ "/OpenAction /missing",
+ // A page number past the end, and a page reference that is no page.
+ "/OpenAction [7 /Fit]",
+ "/OpenAction [2 0 R /Fit]",
+ "/OpenAction 42",
+ ] {
+ assert_eq!(open_dest(catalog, &[]), None, "{catalog}");
+ }
+ }
+
+ #[test]
+ fn cyclic_and_deep_named_destinations_end() {
+ // Names that refer to each other.
+ assert_eq!(open_dest("/OpenAction /a /Dests << /a /b /b /a >>", &[]), None);
+ assert_eq!(open_dest("/OpenAction /a /Dests << /a << /D /a >> >>", &[]), None);
+ // A name tree whose node is its own kid.
+ assert_eq!(open_dest("/OpenAction (x) /Names << /Dests 6 0 R >>", &["<< /Kids [6 0 R] >>".into()]), None);
+ // A name tree deeper than the depth bound: the leaf past it isn't read.
+ let depth = 40;
+ let mut nodes: Vec<String> = (0..depth).map(|i| format!("<< /Kids [{} 0 R] >>", 7 + i)).collect();
+ nodes.push("<< /Names [(x) [4 0 R /Fit]] >>".into());
+ assert_eq!(open_dest("/OpenAction (x) /Names << /Dests 6 0 R >>", &nodes), None);
+ // A shallow one is read.
+ let shallow = ["<< /Kids [7 0 R] >>".to_string(), "<< /Kids [8 0 R] >>".into(), "<< /Names [(x) [4 0 R /Fit]] >>".into()];
+ assert_eq!(open_dest("/OpenAction (x) /Names << /Dests 6 0 R >>", &shallow), Some((1, DestView::Fit)));
+ }
+}
diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs
index 699b8d6..45b0288 100644
--- a/crates/render/src/lib.rs
+++ b/crates/render/src/lib.rs
@@ -18,7 +18,8 @@ pub mod transition;
pub use inspect::{
Annotation, Attachment, AttachmentSource, DestView, DocInfo, Field, FieldKind, FontInfo, Layer, LayerOp, Link, LinkTarget, OutlineItem, PageInfo,
- PageTransition, RemoteDestination, TransitionStyle, Xfa, attachment_data, check_pages, inspect, pretty_date, sound_wav,
+ PageTransition, RemoteDestination, TransitionStyle, Xfa, attachment_data, check_pages, inspect, link_replies, pretty_date, sound_wav,
+ thread_tops,
};
pub use pixels::Pixels;
pub use raster::{
diff --git a/crates/render/src/raster.rs b/crates/render/src/raster.rs
index 2ad1e4f..5e9a9a3 100644
--- a/crates/render/src/raster.rs
+++ b/crates/render/src/raster.rs
@@ -91,8 +91,8 @@ impl RenderConfig {
/// A Japanese face from craft-fonts for a CID font of the Adobe-Japan1 collection that the PDF
/// doesn't embed (`HeiseiMin-W3`, `KozGoPro-Medium`, …). hayro's own substitutes for fonts that
/// aren't embedded are the Latin standard 14, so such text drew nothing. `None` for every other
-/// font, and when PdfCraft was built without craft-fonts. Only Japanese: the pinned craft-fonts
-/// has no other CJK faces, and its later Chinese face is Noto CJK, which AGENTS.md §1.1 rules out.
+/// font, and when PdfCraft was built without craft-fonts. Only Japanese: no other CJK face is
+/// embedded whole.
fn japanese_fallback(query: &FontQuery) -> Option<(FontData, u32)> {
let FontQuery::Fallback(f) = query else { return None };
if f.character_collection.as_ref()?.family != CidFamily::AdobeJapan1 {
@@ -223,6 +223,9 @@ pub struct RenderedPage {
pub enum RenderWarning {
/// Content was skipped after the per-page decoded-content budget was exhausted.
ContentTruncated,
+ /// A colour could not be computed (a colour space that cannot be read, or a Separation or
+ /// DeviceN tint transform that cannot be evaluated) and was painted in a fallback colour.
+ ColourFallback,
}
/// Counters for work performed by a renderer or render pool.
@@ -405,12 +408,15 @@ fn warning_settings(settings: &InterpreterSettings, warnings: Arc<Mutex<Vec<Rend
InterpreterSettings {
warning_sink: Arc::new(move |warning| {
// Nested forms, Type 3 glyphs and patterns are interpreted again and each reports the
- // exhausted budget: once per page is enough.
- if matches!(warning, InterpreterWarning::ContentTruncated) {
- let mut warnings = lock(&target);
- if !warnings.contains(&RenderWarning::ContentTruncated) {
- warnings.push(RenderWarning::ContentTruncated);
- }
+ // exhausted budget, or the colours that fell back: once per page is enough.
+ let warning = match warning {
+ InterpreterWarning::ContentTruncated => RenderWarning::ContentTruncated,
+ InterpreterWarning::ColorFallback => RenderWarning::ColourFallback,
+ InterpreterWarning::UnsupportedFont | InterpreterWarning::ImageDecodeFailure => return,
+ };
+ let mut warnings = lock(&target);
+ if !warnings.contains(&warning) {
+ warnings.push(warning);
}
}),
..settings.clone()
@@ -491,7 +497,7 @@ fn parse(bytes: &Arc<Vec<u8>>, password: Option<&str>) -> Option<Pdf> {
}
pub(crate) fn panic_message(p: &Box<dyn std::any::Any + Send>) -> String {
- p.downcast_ref::<&str>().map(|s| s.to_string()).or_else(|| p.downcast_ref::<String>().cloned()).unwrap_or_else(|| "unknown panic".into())
+ p.downcast_ref::<&str>().map(ToString::to_string).or_else(|| p.downcast_ref::<String>().cloned()).unwrap_or_else(|| "unknown panic".into())
}
/// How long one page may render before the pool gives up on it (the watchdog).
@@ -590,7 +596,7 @@ struct Shared {
}
fn lock<T>(m: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
- m.lock().unwrap_or_else(|poisoned| poisoned.into_inner())
+ m.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
}
#[cfg(not(target_arch = "wasm32"))]
@@ -669,7 +675,7 @@ impl PoolParser {
// Drop never joins a parser. A waiting worker must still notice
// its pool's disconnected wake channel while another thread is
// stuck in initialization and cannot signal this condition.
- state = self.ready.wait_timeout(state, std::time::Duration::from_millis(50)).unwrap_or_else(|p| p.into_inner()).0;
+ state = self.ready.wait_timeout(state, std::time::Duration::from_millis(50)).unwrap_or_else(std::sync::PoisonError::into_inner).0;
}
ParserState::Empty => {
*state = ParserState::Loading;
@@ -3178,6 +3184,91 @@ trailer << /Root 1 0 R >>
}
}
+ /// #2583, #1869: a sticky note carries the NoRotate flag (`/F` bit 5), so on a page with
+ /// `/Rotate` its icon stays upright as displayed, turned about the upper-left corner of its
+ /// `/Rect`, which stays where it is on the page (ISO 32000-2 §12.5.3). It was drawn turned with
+ /// the page, in `/Rect` as displayed (vendored hayro-interpret patch 37). A note without the
+ /// flag still turns with the page. `Annotation::shown_rect` is where the UI hit-tests the
+ /// note, and must be where it is drawn.
+ #[test]
+ fn no_rotate_notes_stay_upright_at_their_corner_on_rotated_pages() {
+ // A 30 × 20 appearance: red in its top-left quarter, blue elsewhere.
+ let content = "0 0 1 rg 0 0 30 20 re f 1 0 0 rg 0 10 15 10 re f";
+ for rotation in [0u16, 90, 180, 270] {
+ let objects = [
+ "<< /Type /Catalog /Pages 2 0 R >>".to_string(),
+ "<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_string(),
+ format!("<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 140] /Rotate {rotation} /Annots [4 0 R 5 0 R] >>"),
+ // NoRotate (and Print), as PdfCraft and Acrobat save notes.
+ "<< /Type /Annot /Subtype /Text /F 20 /Rect [40 50 70 70] /AP << /N 6 0 R >> >>".to_string(),
+ // The same appearance without the flag.
+ "<< /Type /Annot /Subtype /Text /F 4 /Rect [120 50 150 70] /AP << /N 6 0 R >> >>".to_string(),
+ format!("<< /Type /XObject /Subtype /Form /BBox [0 0 30 20] /Length {} >>\nstream\n{content}\nendstream", content.len()),
+ ];
+ let mut pdf = b"%PDF-1.7\n".to_vec();
+ let mut offsets = Vec::new();
+ for (i, object) in objects.iter().enumerate() {
+ offsets.push(pdf.len());
+ pdf.extend_from_slice(format!("{} 0 obj\n{object}\nendobj\n", i + 1).as_bytes());
+ }
+ let xref = pdf.len();
+ pdf.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objects.len() + 1).as_bytes());
+ for offset in offsets {
+ pdf.extend_from_slice(format!("{offset:010} 00000 n \n").as_bytes());
+ }
+ pdf.extend_from_slice(format!("trailer << /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objects.len() + 1).as_bytes());
+ let pdf = Arc::new(pdf);
+ let info = crate::inspect(pdf.clone(), None).expect("opens");
+ let page = &info.pages[0];
+ assert_eq!(page.rotation, rotation);
+ let mut r = PageRenderer::new(pdf, RenderConfig::default());
+ let p = r.render(RenderRequest { page: 0, scale: 1.0, ..Default::default() });
+ assert!(p.error.is_none(), "{:?}", p.error);
+ // Displayed-page points are device pixels at scale 1.
+ let px = |x: f32, y: f32| -> [u8; 4] {
+ let (x, y) = (x.clamp(0.0, p.width as f32 - 1.0) as u32, y.clamp(0.0, p.height as f32 - 1.0) as u32);
+ p.rgba[((y * p.width + x) * 4) as usize..][..4].try_into().unwrap()
+ };
+ let red: fn([u8; 4]) -> bool = |c| c[0] > 200 && c[1] < 60 && c[2] < 60;
+ let blue: fn([u8; 4]) -> bool = |c| c[2] > 200 && c[0] < 60 && c[1] < 60;
+ let paper: fn([u8; 4]) -> bool = |c| c.iter().all(|v| *v > 240);
+
+ // The NoRotate note: its upper-left corner (40, 70) is the top-left of an upright
+ // 30 × 20 icon as displayed, red quarter top-left.
+ let [cx, cy] = page.user_to_view(40.0, 70.0);
+ for ((dx, dy), want, what) in [
+ ((7.5, 5.0), red, "red top-left quarter"),
+ ((22.5, 5.0), blue, "blue top-right"),
+ ((7.5, 15.0), blue, "blue bottom-left"),
+ ((22.5, 15.0), blue, "blue bottom-right"),
+ ((-3.0, 10.0), paper, "paper left of the icon"),
+ ((10.0, -3.0), paper, "paper above the icon"),
+ ((33.0, 10.0), paper, "paper right of its 30 pt width"),
+ ((10.0, 23.0), paper, "paper below its 20 pt height"),
+ ] {
+ let c = px(cx + dx, cy + dy);
+ assert!(want(c), "rotation {rotation}: NoRotate note at corner + ({dx}, {dy}) is {c:?}, want {what}");
+ }
+ let note = info.annotations.iter().find(|a| a.no_rotate).expect("the NoRotate note is listed");
+ let shown = note.shown_rect(rotation);
+ let (a, b) = (page.user_to_view(shown[0], shown[1]), page.user_to_view(shown[2], shown[3]));
+ let box_ = [a[0].min(b[0]), a[1].min(b[1]), a[0].max(b[0]), a[1].max(b[1])];
+ let want = [cx, cy, cx + 30.0, cy + 20.0];
+ assert!(box_.iter().zip(want).all(|(v, w)| (v - w).abs() < 0.01), "rotation {rotation}: shown {box_:?}, drawn {want:?}");
+
+ // The note without the flag turns with the page: its red quarter stays at the
+ // user-space top-left of /Rect, at the displayed top-left only when unturned.
+ let plain = info.annotations.iter().find(|a| !a.no_rotate).expect("the plain note is listed");
+ assert_eq!(plain.shown_rect(rotation), plain.rect);
+ let [rx, ry] = page.user_to_view(127.5, 65.0);
+ let [bx, by] = page.user_to_view(142.5, 55.0);
+ assert!(red(px(rx, ry)) && blue(px(bx, by)), "rotation {rotation}: the plain note's appearance turns with the page");
+ let (a, b) = (page.user_to_view(120.0, 50.0), page.user_to_view(150.0, 70.0));
+ let corner = px(a[0].min(b[0]) + 4.0, a[1].min(b[1]) + 4.0);
+ assert_eq!(red(corner), rotation == 0, "rotation {rotation}: displayed top-left of the plain note is {corner:?}");
+ }
+ }
+
/// #1968: the highlight appearance other editors write, a transparency group whose content is
/// filled with `/BM /Multiply`, drew as an opaque block over the text. Every `/Group` form
/// got a layer of its own, so the Multiply blended with that layer's transparent backdrop
@@ -3346,6 +3437,40 @@ trailer << /Root 1 0 R >>
assert_eq!(px(&hidden, 20, 80), vec![255, 0, 0, 255], "fields stay");
}
+ /// ISO 32000-2 Table 167: Invisible hides an annotation of a type that isn't standard and
+ /// nothing else; §12.5.6.14: a popup has no appearance of its own, so its `/AP` isn't painted.
+ #[test]
+ fn invisible_unknown_annotations_and_popups_paint_nothing() {
+ let annots = [
+ "/Subtype /MyCustomType /F 0",
+ "/Subtype /MyCustomType /F 1",
+ "/Subtype /MyCustomType /F 5",
+ "/F 1",
+ "/Subtype /Square /F 1",
+ "/Subtype /Popup /F 4 /Open true",
+ ];
+ let mut pdf = String::from("%PDF-1.7\n1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj\n");
+ pdf.push_str("2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj\n");
+ let refs: Vec<String> = (0..annots.len()).map(|i| format!("{} 0 R", 10 + i)).collect();
+ pdf.push_str(&format!("3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 300 50] /Annots [{}] >> endobj\n", refs.join(" ")));
+ pdf.push_str("4 0 obj << /Type /XObject /Subtype /Form /BBox [0 0 30 30] /Length 24 >> stream\n0 1 0 rg 0 0 30 30 re f\nendstream endobj\n");
+ for (i, a) in annots.iter().enumerate() {
+ let x = 10 + 50 * i;
+ pdf.push_str(&format!("{} 0 obj << /Type /Annot {a} /Rect [{x} 10 {} 40] /AP << /N 4 0 R >> >> endobj\n", 10 + i, x + 30));
+ }
+ pdf.push_str("trailer << /Root 1 0 R >>\n%%EOF");
+ let mut r = PageRenderer::new(Arc::new(pdf.into_bytes()), RenderConfig::default());
+ let p = r.render(RenderRequest { page: 0, kind: RequestKind::Pixels, tile: None, scale: 1.0, tag: 0, ..Default::default() });
+ let px = |x: u32| p.rgba[((25 * p.width + x) * 4) as usize..][..4].to_vec();
+ let (green, white) = (vec![0, 255, 0, 255], vec![255, 255, 255, 255]);
+ assert_eq!(px(25), green, "an unknown type without Invisible is drawn");
+ assert_eq!(px(75), white, "Invisible hides an unknown type");
+ assert_eq!(px(125), white, "even with the Print flag");
+ assert_eq!(px(175), white, "no Subtype is no standard type");
+ assert_eq!(px(225), green, "Invisible means nothing for a standard type");
+ assert_eq!(px(275), white, "a popup's appearance is not painted on the page");
+ }
+
#[test]
fn hiding_notes_keeps_other_comments() {
let pdf = b"%PDF-1.7
@@ -7470,6 +7595,9 @@ endstream endobj
// ICC profiles whose stream dictionaries are the same (vendored hayro-interpret patch 48).
mod icc_profile_cache;
+ // A symbolic TrueType font draws through its (3, 0) cmap subtable first (#4156).
+ mod symbolic_truetype_cmap;
+
/// Render `pdf`'s first page at 72 dpi with no time limit beyond the test's own.
fn render_first_page(pdf: Vec<u8>) -> RenderedPage {
let mut r = PageRenderer::new(Arc::new(pdf), RenderConfig::default());
@@ -8198,13 +8326,15 @@ trailer << /Root 1 0 R >>
}
}
- /// ISO 32000-1 §9.3.6: only text rendering mode 3 has any effect on a Type 3 font (vendored
- /// hayro-interpret patch in `show_glyph`). Print-stream PDFs set `2 Tr` for Type 3 bitmap
- /// fonts, and the glyph procedure ran twice (fill, then stroke), so its anti-aliased edges
- /// doubled up and the text looked bold; under `1 Tr` an uncoloured glyph took the stroking
- /// colour, and under `7 Tr` it disappeared. Both glyph kinds have edges between pixels.
+ /// ISO 32000-2 §9.3.6: text in a Type 3 font is rendered from its glyph descriptions in every
+ /// text rendering mode but 3 and 7 (vendored hayro-interpret patches 42 and 64 in
+ /// `show_glyph`). Print-stream PDFs set `2 Tr` for Type 3 bitmap fonts, and the glyph
+ /// procedure ran twice (fill, then stroke), so its anti-aliased edges doubled up and the text
+ /// looked bold; under `1 Tr` an uncoloured glyph took the stroking colour. Modes 3 and 7
+ /// render nothing (`tests/it/type3_text_clip.rs` covers the clip). Both glyph kinds have
+ /// edges between pixels.
#[test]
- fn text_rendering_modes_other_than_invisible_draw_type3_glyphs_as_filled() {
+ fn rendering_modes_but_3_and_7_draw_type3_glyphs_as_filled() {
let render = |glyph: &str, mode: u8| {
let content = format!("BT 1 0 0 RG 6 w 0 g /F1 20 Tf {mode} Tr 10.3 10.3 Td (A) Tj ET");
let pdf = format!(
@@ -8233,16 +8363,22 @@ trailer << /Root 1 0 R >>
for glyph in ["1 0 0 0 1 1 d1 0.12 0.12 0.71 0.71 re f", "1 0 d0 0.12 0.12 0.71 0.71 re f"] {
let filled = render(glyph, 0);
assert!(filled.as_chunks::<4>().0.iter().any(|p| p[0] < 128), "{glyph}: the glyph paints");
- for mode in [1, 2, 4, 5, 6, 7] {
+ for mode in [1, 2, 4, 5, 6] {
assert!(render(glyph, mode) == filled, "{glyph}: {mode} Tr draws as 0 Tr");
}
- assert!(render(glyph, 3).as_chunks::<4>().0.iter().all(|p| p[..3] == [255, 255, 255]), "{glyph}: 3 Tr hides the glyph");
+ for mode in [3, 7] {
+ assert!(render(glyph, mode).as_chunks::<4>().0.iter().all(|p| p[..3] == [255, 255, 255]), "{glyph}: {mode} Tr hides the glyph");
+ }
}
}
// #1201: /DefaultGray, /DefaultRGB and /DefaultCMYK (vendored hayro-interpret patch 38).
mod default_colour_spaces;
+ // #4260: DeviceN colours with many inks, and tint transforms that cannot be evaluated
+ // (vendored hayro-syntax patch 28, hayro-interpret patch 55).
+ mod devicen_inks;
+
/// #3109 / #3116: clipping-only text (`7 Tr`) installs a clip for subsequent painting
/// but draws no pixels itself.
#[test]
diff --git a/crates/render/src/raster/tests/devicen_inks.rs b/crates/render/src/raster/tests/devicen_inks.rs
new file mode 100644
index 0000000..e08ce77
--- /dev/null
+++ b/crates/render/src/raster/tests/devicen_inks.rs
@@ -0,0 +1,123 @@
+//! #4260: a DeviceN colour with more inks than the content parser held operands for, and a
+//! colour whose tint transform cannot be evaluated (ISO 32000-2 §8.6.6.5).
+//!
+//! The content parser kept at most ten operands per operator (vendored hayro-syntax patch 28):
+//! the eleventh operand of a twelve-ink `scn` ended the whole content stream, so the page came
+//! out blank with no error. A tint transform that cannot be evaluated painted the alternate
+//! space's initial colour without a word (vendored hayro-interpret patch 55): it now says so.
+
+use super::{RenderWarning, rgb_at};
+use crate::{PageRenderer, RenderConfig, RenderRequest, RenderedPage, RequestKind};
+use std::sync::Arc;
+
+/// The page is 200 × 200 pt, drawn at 72 dpi.
+const SIDE: usize = 200;
+
+const GREEN: [u8; 3] = [0, 255, 0];
+const RED: [u8; 3] = [255, 0, 0];
+const BLUE: [u8; 3] = [0, 0, 255];
+const BLACK: [u8; 3] = [0, 0, 0];
+
+/// The twelve inks of the report's print dieline.
+const TWELVE_INKS: &str =
+ "[/Cyan /Magenta /Yellow /Black /PANTONE156C /PANTONE2227C /PANTONE1565C /PANTONE2975C /PANTONE7463C /Varnish /Dieline /SGKBlack]";
+
+/// The report's tint transform: all inks at 1.0 give CMYK 1 1 1 1.
+const TINT: &str = "<< /FunctionType 2 /Domain [0 1] /N 1 /C0 [0 0 0 0] /C1 [1 1 1 1] >>";
+
+/// Render the one page `content` draws with the colour space `CS1` defined as `cs1`.
+fn render(content: &str, cs1: &str) -> RenderedPage {
+ render_with(content, cs1, "")
+}
+
+/// [`render`], with `objects` (whole indirect objects from 5 0 obj on) added to the file.
+fn render_with(content: &str, cs1: &str, objects: &str) -> RenderedPage {
+ let pdf = format!(
+ "%PDF-1.7\n1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj\n\
+ 2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj\n\
+ 3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Resources << /ColorSpace << /CS1 {cs1} >> >> /Contents 4 0 R >> endobj\n\
+ 4 0 obj << /Length {} >> stream\n{content}\nendstream endobj\n\
+ {objects}trailer << /Root 1 0 R >>\n%%EOF",
+ content.len()
+ );
+ let mut renderer = PageRenderer::new(Arc::new(pdf.into_bytes()), RenderConfig::default());
+ let page = renderer.render(RenderRequest { page: 0, kind: RequestKind::Pixels, tile: None, scale: 1.0, tag: 0, preview: false });
+ assert!(page.error.is_none(), "{:?}", page.error);
+ assert_eq!((page.width, page.height), (SIDE as u32, SIDE as u32));
+ page
+}
+
+/// The colour at (`x`, `y`) in page points from the bottom left.
+fn at(page: &RenderedPage, x: usize, y: usize) -> [u8; 3] {
+ rgb_at(&page.rgba, SIDE, x, SIDE - 1 - y)
+}
+
+/// CMYK 1 1 1 1 through the renderer's CMYK profile: very dark, whatever the exact profile.
+fn is_rich_black(rgb: [u8; 3]) -> bool {
+ rgb.iter().all(|c| *c < 48)
+}
+
+/// The report's page: twelve inks, all at 1.0, fill the page black. A green square drawn
+/// afterwards shows the rest of the content is still read.
+#[test]
+fn a_twelve_ink_devicen_colour_paints() {
+ let content = "/CS1 cs 1 1 1 1 1 1 1 1 1 1 1 1 scn 0 0 200 200 re f 0 1 0 rg 0 0 20 20 re f";
+ let page = render(content, &format!("[/DeviceN {TWELVE_INKS} /DeviceCMYK {TINT}]"));
+ assert!(is_rich_black(at(&page, 100, 100)), "the twelve-ink fill paints: {:?}", at(&page, 100, 100));
+ assert_eq!(at(&page, 10, 10), GREEN, "what follows the twelve-ink colour is drawn");
+ assert!(page.warnings.is_empty(), "{:?}", page.warnings);
+}
+
+/// The control from the report: the same colour with four inks always painted.
+#[test]
+fn a_four_ink_devicen_colour_paints() {
+ let content = "/CS1 cs 1 1 1 1 scn 0 0 200 200 re f 0 1 0 rg 0 0 20 20 re f";
+ let page = render(content, &format!("[/DeviceN [/Cyan /Magenta /Yellow /Black] /DeviceCMYK {TINT}]"));
+ assert!(is_rich_black(at(&page, 100, 100)), "the four-ink fill paints: {:?}", at(&page, 100, 100));
+ assert_eq!(at(&page, 10, 10), GREEN);
+ assert!(page.warnings.is_empty(), "{:?}", page.warnings);
+}
+
+/// An operator with more operands than the parser keeps still reads the ones nearest to it,
+/// as one with a few stray operands does, and the content after it is drawn.
+#[test]
+fn an_operator_with_hundreds_of_operands_does_not_end_the_content() {
+ let strays = "0 ".repeat(300);
+ let content = format!("1 0 0 rg 0 0 200 200 re f {strays}0 1 0 rg 0 0 20 20 re f");
+ let page = render(&content, "/DeviceRGB");
+ assert_eq!(at(&page, 100, 100), RED, "the content before the stray operands is drawn");
+ assert_eq!(at(&page, 10, 10), GREEN, "the operator after them reads its own three operands");
+}
+
+/// A tint transform that fails when it runs (a calculator function that pops more than it is
+/// given) paints that one colour in the alternate space's initial colour (black in DeviceRGB)
+/// and records a warning; the paints before and after it are drawn as usual.
+#[test]
+fn a_tint_transform_that_cannot_be_evaluated_draws_the_rest_of_the_page_and_warns() {
+ let program = "{ pop pop pop }";
+ let function = format!(
+ "5 0 obj << /FunctionType 4 /Domain [0 1 0 1] /Range [0 1 0 1 0 1] /Length {} >> stream\n{program}\nendstream endobj\n",
+ program.len()
+ );
+ let content = "1 0 0 rg 0 0 100 200 re f /CS1 cs 0.5 0.5 scn 100 0 100 200 re f 0 0 1 rg 0 0 50 50 re f";
+ let page = render_with(content, "[/DeviceN [/Spot1 /Spot2] /DeviceRGB 5 0 R]", &function);
+ assert_eq!(at(&page, 75, 150), RED, "the paint before the colour is drawn");
+ assert_eq!(at(&page, 150, 150), BLACK, "the colour falls back to the alternate space's initial colour");
+ assert_eq!(at(&page, 25, 25), BLUE, "the paint after the colour is drawn");
+ assert!(page.warnings.contains(&RenderWarning::ColourFallback), "{:?}", page.warnings);
+}
+
+/// A tint transform that cannot even be read (an unknown function type) keeps the colour space,
+/// so its paints fall back the same way, with the same warning, instead of being drawn in
+/// DeviceGray from the first tint (white here).
+#[test]
+fn a_tint_transform_that_cannot_be_read_falls_back_and_warns() {
+ let cs1 = format!("[/DeviceN {TWELVE_INKS} /DeviceCMYK << /FunctionType 7 /Domain [0 1] >>]");
+ let content = "/CS1 cs 1 1 1 1 1 1 1 1 1 1 1 1 scn 0 0 200 200 re f 0 1 0 rg 0 0 20 20 re f";
+ let page = render(content, &cs1);
+ assert!(is_rich_black(at(&page, 100, 100)), "the colour falls back to CMYK black: {:?}", at(&page, 100, 100));
+ assert_eq!(at(&page, 10, 10), GREEN, "what follows is drawn");
+ assert!(page.warnings.contains(&RenderWarning::ColourFallback), "{:?}", page.warnings);
+ // Reported once per page, however many paints fell back.
+ assert_eq!(page.warnings.iter().filter(|w| **w == RenderWarning::ColourFallback).count(), 1);
+}
diff --git a/crates/render/src/raster/tests/symbolic_truetype_cmap.rs b/crates/render/src/raster/tests/symbolic_truetype_cmap.rs
new file mode 100644
index 0000000..f66aff1
--- /dev/null
+++ b/crates/render/src/raster/tests/symbolic_truetype_cmap.rs
@@ -0,0 +1,162 @@
+//! A symbolic TrueType font draws through its (3, 0) `cmap` subtable before its (1, 0) one
+//! (vendored hayro-interpret patch, #4156; ISO 32000-2 §9.6.5.4: "If the font contains a (3, 0)
+//! subtable" it is used, "Otherwise, if the font contains a (1, 0) subtable"). SAS writes AMT
+//! fonts whose (1, 0) table is wrong, so "8" drew as "p" and "+" as "V".
+//!
+//! The font is built here, in memory: three glyphs (`.notdef`, an empty one and a filled square),
+//! a (1, 0) subtable mapping `A` to the empty glyph and a (3, 0) subtable mapping it (as U+F041)
+//! to the square. No font file is involved.
+
+use super::render_first_page;
+
+fn be16(out: &mut Vec<u8>, n: u16) {
+ out.extend_from_slice(&n.to_be_bytes());
+}
+
+fn be32(out: &mut Vec<u8>, n: u32) {
+ out.extend_from_slice(&n.to_be_bytes());
+}
+
+/// A TrueType font whose (1, 0) and (3, 0) subtables disagree about the code `A`.
+fn disagreeing_font() -> Vec<u8> {
+ // Glyph 2: one contour, the square 0..1000 on both axes (glyph 0 and 1 are empty).
+ let mut square = Vec::new();
+ for n in [1i16, 0, 0, 1000, 1000] {
+ out16(&mut square, n);
+ }
+ be16(&mut square, 3); // the contour's last point
+ be16(&mut square, 0); // no instructions
+ square.extend([1u8; 4]); // four on-curve points, two-byte coordinates
+ for dx in [0i16, 1000, 0, -1000] {
+ out16(&mut square, dx);
+ }
+ for dy in [0i16, 0, 1000, 0] {
+ out16(&mut square, dy);
+ }
+ let glyf = square.clone();
+ let mut loca = Vec::new();
+ for offset in [0u16, 0, 0, (glyf.len() / 2) as u16] {
+ be16(&mut loca, offset);
+ }
+
+ let mut head = vec![0; 54];
+ head[0..4].copy_from_slice(&[0, 1, 0, 0]);
+ head[12..16].copy_from_slice(&0x5f0f_3cf5u32.to_be_bytes());
+ head[18..20].copy_from_slice(&1000u16.to_be_bytes());
+ head[40..42].copy_from_slice(&1000i16.to_be_bytes());
+ head[42..44].copy_from_slice(&1000i16.to_be_bytes());
+ let mut hhea = vec![0; 36];
+ hhea[0..4].copy_from_slice(&[0, 1, 0, 0]);
+ hhea[4..6].copy_from_slice(&1000i16.to_be_bytes());
+ hhea[34..36].copy_from_slice(&3u16.to_be_bytes());
+ let mut hmtx = Vec::new();
+ for _ in 0..3 {
+ be16(&mut hmtx, 1000);
+ be16(&mut hmtx, 0);
+ }
+ let mut maxp = vec![0, 1, 0, 0];
+ be16(&mut maxp, 3);
+ maxp.resize(32, 0);
+
+ // (1, 0), format 0: `A` → glyph 1 (empty), and `B`, which the (3, 0) table leaves out, →
+ // glyph 2.
+ let mut mac = Vec::new();
+ be16(&mut mac, 0);
+ be16(&mut mac, 262);
+ be16(&mut mac, 0);
+ let mut ids = [0u8; 256];
+ ids[usize::from(b'A')] = 1;
+ ids[usize::from(b'B')] = 2;
+ mac.extend(ids);
+ // (3, 0), format 4: U+F041 → glyph 2 (the square).
+ let mut win = Vec::new();
+ be16(&mut win, 4);
+ be16(&mut win, 32);
+ be16(&mut win, 0);
+ for n in [4u16, 4, 1, 0] {
+ be16(&mut win, n); // segCountX2, searchRange, entrySelector, rangeShift
+ }
+ for n in [0xF041u16, 0xFFFF, 0, 0xF041, 0xFFFF, 2u16.wrapping_sub(0xF041), 1, 0, 0] {
+ be16(&mut win, n); // endCode ×2, pad, startCode ×2, idDelta ×2, idRangeOffset ×2
+ }
+ let mut cmap = Vec::new();
+ be16(&mut cmap, 0);
+ be16(&mut cmap, 2);
+ for (platform, encoding, offset) in [(1u16, 0u16, 20u32), (3, 0, 20 + mac.len() as u32)] {
+ be16(&mut cmap, platform);
+ be16(&mut cmap, encoding);
+ be32(&mut cmap, offset);
+ }
+ cmap.extend(mac);
+ cmap.extend(win);
+
+ let tables = [(*b"cmap", cmap), (*b"glyf", glyf), (*b"head", head), (*b"hhea", hhea), (*b"hmtx", hmtx), (*b"loca", loca), (*b"maxp", maxp)];
+ let mut out = vec![0, 1, 0, 0];
+ be16(&mut out, tables.len() as u16);
+ for n in [64u16, 2, 48] {
+ be16(&mut out, n);
+ }
+ let mut payload = Vec::new();
+ let mut offset = 12 + 16 * tables.len();
+ for (tag, bytes) in tables {
+ out.extend(tag);
+ let mut padded = bytes.clone();
+ padded.resize(bytes.len().div_ceil(4) * 4, 0);
+ let sum = padded.as_chunks::<4>().0.iter().fold(0u32, |s, b| s.wrapping_add(u32::from_be_bytes(*b)));
+ be32(&mut out, sum);
+ be32(&mut out, offset as u32);
+ be32(&mut out, bytes.len() as u32);
+ offset += padded.len();
+ payload.extend(padded);
+ }
+ out.extend(payload);
+ out
+}
+
+fn out16(out: &mut Vec<u8>, n: i16) {
+ out.extend_from_slice(&n.to_be_bytes());
+}
+
+/// A 40 × 40 pt page that shows `text` at 30 pt from (5, 5) in the font, marked symbolic and
+/// with no `/Encoding`, as SAS writes it.
+fn page_with_symbolic_font(font: &[u8], text: &str) -> Vec<u8> {
+ let content = format!("BT /F1 30 Tf 5 5 Td ({text}) Tj ET").into_bytes();
+ let objects: Vec<Vec<u8>> = vec![
+ b"<< /Type /Catalog /Pages 2 0 R >>".to_vec(),
+ b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_vec(),
+ b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 40 40] /Resources << /Font << /F1 5 0 R >> >> /Contents 4 0 R >>".to_vec(),
+ [format!("<< /Length {} >>\nstream\n", content.len()).into_bytes(), content.clone(), b"\nendstream".to_vec()].concat(),
+ b"<< /Type /Font /Subtype /TrueType /BaseFont /AAAAAA+Sym /FirstChar 65 /LastChar 66 /Widths [1000 1000] /FontDescriptor 6 0 R >>".to_vec(),
+ b"<< /Type /FontDescriptor /FontName /AAAAAA+Sym /Flags 4 /FontBBox [0 0 1000 1000] /ItalicAngle 0 /Ascent 1000 /Descent 0 /CapHeight 1000 /StemV 80 /FontFile2 7 0 R >>".to_vec(),
+ [format!("<< /Length {} >>\nstream\n", font.len()).into_bytes(), font.to_vec(), b"\nendstream".to_vec()].concat(),
+ ];
+ let mut pdf = b"%PDF-1.7\n".to_vec();
+ let mut offsets = Vec::new();
+ for (i, object) in objects.iter().enumerate() {
+ offsets.push(pdf.len());
+ pdf.extend(format!("{} 0 obj\n", i + 1).into_bytes());
+ pdf.extend(object);
+ pdf.extend(b"\nendobj\n");
+ }
+ let xref = pdf.len();
+ pdf.extend(format!("xref\n0 {}\n0000000000 65535 f \n", objects.len() + 1).into_bytes());
+ for offset in offsets {
+ pdf.extend(format!("{offset:010} 00000 n \n").into_bytes());
+ }
+ pdf.extend(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objects.len() + 1).into_bytes());
+ pdf
+}
+
+#[test]
+fn a_symbolic_truetype_font_draws_through_its_3_0_subtable_first() {
+ let font = disagreeing_font();
+ // The square covers (5, 5)–(35, 35) in page space: row 20 from the top is inside it.
+ let square_drawn = |text: &str| {
+ let page = render_first_page(page_with_symbolic_font(&font, text));
+ let at = |x: u32, y: u32| page.rgba.get(((y * page.width + x) * 4) as usize).copied().unwrap_or(255);
+ assert_eq!(at(2, 2), 255, "nothing is drawn outside the square");
+ at(20, 20) < 128
+ };
+ assert!(square_drawn("A"), "the (3, 0) subtable's square, not the (1, 0) subtable's empty glyph");
+ assert!(square_drawn("B"), "a code the (3, 0) subtable leaves out still reads through (1, 0)");
+}
diff --git a/crates/render/src/raster/work_queue.rs b/crates/render/src/raster/work_queue.rs
index eb1d05b..ff20bbf 100644
--- a/crates/render/src/raster/work_queue.rs
+++ b/crates/render/src/raster/work_queue.rs
@@ -220,7 +220,7 @@ impl WorkQueue {
}
// The parser validity token can change independently of this queue. Bound the
// wait so failed generations are released even while the consumer is paused.
- state = self.changed.wait_timeout(state, Duration::from_millis(25)).unwrap_or_else(|p| p.into_inner()).0;
+ state = self.changed.wait_timeout(state, Duration::from_millis(25)).unwrap_or_else(std::sync::PoisonError::into_inner).0;
}
}
diff --git a/crates/render/src/text.rs b/crates/render/src/text.rs
index 11cde90..a1c2717 100644
--- a/crates/render/src/text.rs
+++ b/crates/render/src/text.rs
@@ -499,11 +499,11 @@ impl TextDevice {
return;
}
let Some(glyph) = merge(&drawn, text.clone()) else {
- self.glyphs.extend(drawn.into_iter().filter(|d| !d.2.text.chars().all(|c| c.is_control())));
+ self.glyphs.extend(drawn.into_iter().filter(|d| !d.2.text.chars().all(char::is_control)));
return;
};
- let originals = drawn.iter().filter(|d| !d.2.text.chars().all(|c| c.is_control())).map(|d| (d.2.text.clone(), d.2.rect)).collect();
- let at = if text.chars().all(|c| c.is_control()) {
+ let originals = drawn.iter().filter(|d| !d.2.text.chars().all(char::is_control)).map(|d| (d.2.text.clone(), d.2.rect)).collect();
+ let at = if text.chars().all(char::is_control) {
None
} else {
self.glyphs.push(glyph);
@@ -594,7 +594,7 @@ impl TextDevice {
let text = replacement.to_owned();
#[cfg(test)]
REDRAW_TEXT_BYTES.with(|c| c.set(c.get() + text.len()));
- if !text.chars().all(|c| c.is_control()) {
+ if !text.chars().all(char::is_control) {
match merge(run, text) {
Some(glyph) => self.glyphs.push(glyph),
None => self.glyphs.extend_from_slice(run),
@@ -640,7 +640,7 @@ impl<'a> Device<'a> for TextDevice {
return;
}
};
- if !replaced && text.chars().all(|c| c.is_control()) {
+ if !replaced && text.chars().all(char::is_control) {
return;
}
// Glyph space → view space. Glyph space uses 1000 units per em for outline glyphs; the em
@@ -1468,7 +1468,15 @@ fn union(a: &mut [f32; 4], b: &[f32; 4]) {
/// Segments on the same baseline that nearly touch are merged (text drawn out of order).
/// 2. *Blocks:* segments stacked with line-sized gaps and overlapping horizontally.
/// 3. *Block order:* repeatedly take the top-most remaining block, preferring a block to its left
-/// that overlaps it vertically (so columns read left, then right).
+/// that overlaps it vertically (so columns read left, then right). A column goes on first (#3658):
+/// the nearest block below the last one, overlapping it horizontally and at most 2.5 heights of
+/// its last line below it, comes next, unless an unread block sits above it in its own span, sits
+/// beside it on its left, or shares its first line (the first lines overlap by at least 30% of the
+/// taller one: a table or form row, which reads across, even with labels and values in different
+/// sizes or on shifted baselines).
+/// Known limit: when a paragraph in the next column starts on the same line as the continuation
+/// (text on a baseline grid), it counts as a row and the top-most rule applies, so the column
+/// order of #3658 is lost there. Telling prose from a row in that case needs more evidence.
/// 4. Within a segment glyphs run left to right; runs of right-to-left script are reversed so the
/// text comes out in logical order.
pub fn layout(glyphs: Vec<TextGlyph>) -> PageText {
@@ -1632,19 +1640,65 @@ fn arrange(glyphs: &[TextGlyph]) -> (Vec<usize>, Vec<u32>, Vec<bool>) {
// 3. Block order.
let mut remaining: Vec<usize> = (0..blocks.len()).collect();
- let mut block_order = Vec::with_capacity(blocks.len());
+ let mut block_order: Vec<usize> = Vec::with_capacity(blocks.len());
+ // A block to the left of `cb` that shares at least half the height of the shorter one: it reads first.
+ let beside_left = |cb: &[f32; 4], lb: &[f32; 4]| {
+ let v = lb[3].min(cb[3]) - lb[1].max(cb[1]);
+ lb[2] <= cb[0] + 1.0 && v > 0.5 * (lb[3] - lb[1]).min(cb[3] - cb[1])
+ };
+ // The box of a block's first line. Every block is created with one segment, so the block's own box is a fallback
+ // that is never used.
+ let first_line = |b: usize| blocks[b].0.first().and_then(|&s| segs.get(s)).map_or(blocks[b].1, |s| s.bbox);
while let Some(&top) = remaining.iter().min_by(|a, b| blocks[**a].1[1].total_cmp(&blocks[**b].1[1])) {
- let tb = blocks[top].1;
- let pick = remaining
- .iter()
- .copied()
- .filter(|c| {
- let cb = blocks[*c].1;
- let v = cb[3].min(tb[3]) - cb[1].max(tb[1]);
- cb[2] <= tb[0] + 1.0 && v > 0.5 * (cb[3] - cb[1]).min(tb[3] - tb[1])
- })
- .min_by(|a, b| blocks[*a].1[0].total_cmp(&blocks[*b].1[0]))
- .unwrap_or(top);
+ // A column goes on past a paragraph gap (#3658): the nearest block below the one just read that overlaps it
+ // horizontally comes next, if the gap above it is at most two and a half heights of the last line read (a
+ // footer, a footnote or a caption under a figure is further) and no other unread block
+ // - sits above it in its own horizontal span (the rest of a column above a full-width heading or footnote),
+ // - is beside it on its left, or
+ // - shares its first line: their first lines overlap by at least 30% of the taller one (a table or form row,
+ // which reads across, even with labels and values in different sizes or on shifted baselines; a line that
+ // only touches it, or a small superscript or footnote marker, is not a row).
+ let next_in_column = block_order.last().and_then(|&prev| {
+ let pb = blocks[prev].1;
+ // The gap is measured in the height of the block's last line, which borders it.
+ let pl = blocks[prev].0.last().and_then(|&s| segs.get(s)).map_or(pb, |s| s.bbox);
+ let tol = (pl[3] - pl[1]).max(0.1) * 0.5;
+ let c = remaining
+ .iter()
+ .copied()
+ .filter(|&c| {
+ let cb = blocks[c].1;
+ let overlap = cb[2].min(pb[2]) - cb[0].max(pb[0]);
+ let minw = (cb[2] - cb[0]).min(pb[2] - pb[0]).max(1.0);
+ cb[1] >= pb[3] - tol && overlap > minw * 0.3
+ })
+ .min_by(|a, b| blocks[*a].1[1].total_cmp(&blocks[*b].1[1]))?;
+ let cb = blocks[c].1;
+ if cb[1] - pb[3] >= tol * 5.0 {
+ return None;
+ }
+ let cl = first_line(c);
+ let blocked = remaining.iter().any(|&r| {
+ if r == c {
+ return false;
+ }
+ let rb = blocks[r].1;
+ let rl = first_line(r);
+ let shared = rl[3].min(cl[3]) - rl[1].max(cl[1]);
+ let row = shared > 0.3 * (rl[3] - rl[1]).max(cl[3] - cl[1]);
+ (rb[1] < cb[1] && rb[2].min(cb[2]) > rb[0].max(cb[0])) || beside_left(&cb, &rb) || row
+ });
+ (!blocked).then_some(c)
+ });
+ let pick = next_in_column.unwrap_or_else(|| {
+ let tb = blocks[top].1;
+ remaining
+ .iter()
+ .copied()
+ .filter(|c| beside_left(&tb, &blocks[*c].1))
+ .min_by(|a, b| blocks[*a].1[0].total_cmp(&blocks[*b].1[0]))
+ .unwrap_or(top)
+ });
remaining.retain(|r| *r != pick);
block_order.push(pick);
}
@@ -2093,6 +2147,43 @@ mod tests {
}
}
+ /// ISO 32000-2 §9.3.6: Type 3 text under `7 Tr` is not rendered (vendored hayro-interpret
+ /// patch 64), but it is still clipping text, not an invisible text layer: the filter that
+ /// drops OCR layers keeps it, as it keeps clipping text in other fonts.
+ #[test]
+ fn clipping_mode_type3_text_is_kept_by_the_ocr_filter() {
+ let font = "<< /Type /Font /Subtype /Type3 /FontBBox [0 0 1000 1000] /FontMatrix [0.001 0 0 0.001 0 0] \
+ /CharProcs << /A 6 0 R >> /Encoding << /Type /Encoding /Differences [65 /A] >> \
+ /FirstChar 65 /LastChar 65 /Widths [1000] >>";
+ let glyph = "1000 0 100 0 900 800 d1 100 0 800 800 re f";
+ let content = "BT /T3 24 Tf 7 Tr 30 200 Td (AAA) Tj ET BT /T3 12 Tf 3 Tr 30 100 Td (A) Tj ET";
+ let objects = [
+ "<< /Type /Catalog /Pages 2 0 R >>".to_string(),
+ "<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_string(),
+ "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 300] /Contents 4 0 R /Resources << /Font << /T3 5 0 R >> >> >>".to_string(),
+ format!("<< /Length {} >>\nstream\n{content}\nendstream", content.len()),
+ font.to_string(),
+ format!("<< /Length {} >>\nstream\n{glyph}\nendstream", glyph.len()),
+ ];
+ let mut bytes = b"%PDF-1.7\n".to_vec();
+ let mut offsets = Vec::new();
+ for (i, object) in objects.iter().enumerate() {
+ offsets.push(bytes.len());
+ bytes.extend_from_slice(format!("{} 0 obj\n{object}\nendobj\n", i + 1).as_bytes());
+ }
+ let xref = bytes.len();
+ bytes.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objects.len() + 1).as_bytes());
+ for offset in offsets {
+ bytes.extend_from_slice(format!("{offset:010} 00000 n \n").as_bytes());
+ }
+ bytes.extend_from_slice(format!("trailer << /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objects.len() + 1).as_bytes());
+ let pdf = Pdf::new(std::sync::Arc::new(bytes)).unwrap();
+ let all = extract_page_filtered(&pdf, 0, &InterpreterSettings::default(), TextFilter::default()).unwrap();
+ assert_eq!(all.plain_text().matches('A').count(), 4, "{:?}", all.plain_text());
+ let filtered = extract_page_filtered(&pdf, 0, &InterpreterSettings::default(), TextFilter { images: true, ..Default::default() }).unwrap();
+ assert_eq!(filtered.plain_text().trim(), "AAA", "the 7 Tr text stays, the 3 Tr layer goes");
+ }
+
/// One page per `(encoding, content)`, in Helvetica (`/F1`).
fn encoded_pages(pages: &[(lopdf::Object, &[u8])]) -> Pdf {
use lopdf::{Document, Object, Stream, dictionary};
@@ -2568,6 +2659,190 @@ mod tests {
assert_eq!(t.plain_text(), "Left1\nLeft2\nRight1\nRight2");
}
+ /// Lays out one-word lines, each `(text, x, y)`, 10 pt high: 14 pt apart is a line in a paragraph, 24 pt a
+ /// paragraph gap.
+ fn lines(at: &[(&str, f32, f32)]) -> String {
+ let mut v = Vec::new();
+ for &(s, x, y) in at {
+ word(&mut v, s, x, y, 6.0);
+ }
+ layout(v).plain_text()
+ }
+
+ #[test]
+ fn a_column_reads_on_past_a_paragraph_gap() {
+ // #3658: a heading and paragraph A at the top of the left column, a paragraph gap, then paragraph B, which
+ // goes on at the top of the right column, and paragraph C below it.
+ let two = [
+ ("Heading", 10.0, 10.0),
+ ("A1", 10.0, 30.0),
+ ("A2", 10.0, 44.0),
+ ("A3", 10.0, 58.0),
+ ("B1", 10.0, 82.0),
+ ("B2", 10.0, 96.0),
+ ("B3", 200.0, 30.0),
+ ("B4", 200.0, 44.0),
+ ("C1", 200.0, 68.0),
+ ("C2", 200.0, 82.0),
+ ];
+ assert_eq!(lines(&two), "Heading\nA1\nA2\nA3\nB1\nB2\nB3\nB4\nC1\nC2");
+ // Three columns, each with a gap at a different height.
+ let three = [
+ ("A1", 10.0, 10.0),
+ ("A2", 10.0, 24.0),
+ ("B1", 10.0, 48.0),
+ ("C1", 150.0, 10.0),
+ ("D1", 150.0, 38.0),
+ ("D2", 150.0, 52.0),
+ ("E1", 290.0, 10.0),
+ ("E2", 290.0, 24.0),
+ ("E3", 290.0, 38.0),
+ ("F1", 290.0, 62.0),
+ ];
+ assert_eq!(lines(&three), "A1\nA2\nB1\nC1\nD1\nD2\nE1\nE2\nE3\nF1");
+ }
+
+ #[test]
+ fn a_column_reads_on_past_a_line_that_only_touches_it() {
+ // The #3658 page with a right-column paragraph whose first line touches B1's by 1 pt or 0.1 pt, or whose
+ // second line carries a 6 pt footnote marker reaching up beside B2: none of them is a row with B1.
+ let page = |extra: &[(&str, f32, f32, f32)]| {
+ let mut v = Vec::new();
+ let left = [("H", 10.0, 10.0), ("A1", 10.0, 30.0), ("A2", 10.0, 44.0), ("A3", 10.0, 58.0), ("B1", 10.0, 82.0), ("B2", 10.0, 96.0)];
+ for &(s, x, y) in left.iter().chain(&[("R1", 200.0, 30.0), ("R2", 200.0, 44.0)]) {
+ word(&mut v, s, x, y, 6.0);
+ }
+ for &(s, x, y, h) in extra {
+ for (i, c) in s.chars().enumerate() {
+ let x0 = x + i as f32 * h * 0.6;
+ v.push(em_box(&c.to_string(), x0, y, x0 + h * 0.6, y + h));
+ }
+ }
+ layout(v).plain_text().replace('\n', " ")
+ };
+ assert_eq!(page(&[("S1", 200.0, 91.0, 10.0), ("S2", 200.0, 105.0, 10.0)]), "H A1 A2 A3 B1 B2 R1 R2 S1 S2", "1 pt touch");
+ assert_eq!(page(&[("S1", 200.0, 72.1, 10.0), ("S2", 200.0, 86.1, 10.0)]), "H A1 A2 A3 B1 B2 R1 R2 S1 S2", "0.1 pt touch");
+ let marker = page(&[("S1", 200.0, 68.0, 10.0), ("x", 200.0, 96.0, 10.0), ("9", 206.5, 90.0, 6.0), ("S2y", 214.0, 96.0, 10.0)]);
+ assert!(marker.starts_with("H A1 A2 A3 B1 B2 R1 R2 S1 "), "footnote marker: {marker}");
+ }
+
+ #[test]
+ fn a_full_width_line_ends_the_columns_above_it() {
+ // Two columns, a full-width heading, two more columns and a full-width footnote. The left column stops at the
+ // heading and the footnote: the right column above each one reads first.
+ let page = [
+ ("L1", 10.0, 10.0),
+ ("L2", 10.0, 24.0),
+ ("L3", 10.0, 48.0),
+ ("R1", 200.0, 10.0),
+ ("R2", 200.0, 38.0),
+ ("Fullwidthheading", 10.0, 80.0),
+ ("L4", 10.0, 110.0),
+ ("L5", 10.0, 124.0),
+ ("L6", 10.0, 148.0),
+ ("R3", 200.0, 110.0),
+ ("R4", 200.0, 138.0),
+ ("Fullwidthfootnote", 10.0, 200.0),
+ ];
+ // The two full-width lines run past the right column (x = 286 and 304) at 18 pt a letter.
+ let mut v = Vec::new();
+ for &(s, x, y) in &page {
+ word(&mut v, s, x, y, if s.len() > 2 { 18.0 } else { 6.0 });
+ }
+ assert_eq!(layout(v).plain_text(), "L1\nL2\nL3\nR1\nR2\nFullwidthheading\nL4\nL5\nL6\nR3\nR4\nFullwidthfootnote");
+ }
+
+ #[test]
+ fn table_rows_apart_still_read_across() {
+ // Rows a paragraph gap apart whose cells start level read row by row, as before #3658.
+ let rows = [("Name", 10.0, 10.0), ("Qty", 100.0, 10.0), ("Apple", 10.0, 34.0), ("12", 100.0, 34.0), ("Pear", 10.0, 58.0), ("7", 100.0, 58.0)];
+ assert_eq!(lines(&rows), "Name\nQty\nApple\n12\nPear\n7");
+ }
+
+ #[test]
+ fn form_rows_in_mixed_sizes_still_read_across() {
+ // 8 pt labels beside 12 pt values on one baseline, rows 30 pt apart: the tops differ by 4 pt, but the first
+ // lines overlap, so each row reads label then value.
+ let mut v = Vec::new();
+ let sized = |v: &mut Vec<TextGlyph>, s: &str, x: f32, base: f32, h: f32| {
+ for (i, c) in s.chars().enumerate() {
+ let x0 = x + i as f32 * h * 0.6;
+ v.push(em_box(&c.to_string(), x0, base - h, x0 + h * 0.6, base));
+ }
+ };
+ for (i, (label, value)) in [("Name", "Alice"), ("Street", "Main"), ("City", "Oslo")].into_iter().enumerate() {
+ let base = 20.0 + 30.0 * i as f32;
+ sized(&mut v, label, 10.0, base, 8.0);
+ sized(&mut v, value, 100.0, base, 12.0);
+ }
+ assert_eq!(layout(v).plain_text(), "Name\nAlice\nStreet\nMain\nCity\nOslo");
+ // Values drawn 6 pt below their labels, rows a paragraph gap apart.
+ let offset =
+ [("Name", 10.0, 10.0), ("Val1", 100.0, 16.0), ("Addr", 10.0, 40.0), ("Val2", 100.0, 46.0), ("City", 10.0, 70.0), ("Val3", 100.0, 76.0)];
+ assert_eq!(lines(&offset), "Name\nVal1\nAddr\nVal2\nCity\nVal3");
+ }
+
+ #[test]
+ fn a_column_does_not_jump_to_a_distant_footer_footnote_or_caption() {
+ // A page number far below the left column reads after the right column.
+ let footer = [
+ ("L1", 10.0, 10.0),
+ ("L2", 10.0, 24.0),
+ ("L3", 10.0, 48.0),
+ ("R1", 200.0, 10.0),
+ ("R2", 200.0, 24.0),
+ ("R3", 200.0, 48.0),
+ ("Pg7", 10.0, 400.0),
+ ];
+ assert_eq!(lines(&footer), "L1\nL2\nR1\nR2\nL3\nR3\nPg7");
+ // So does a footnote under the left column only, with the page number under the right one.
+ let footnote = [
+ ("L1", 10.0, 10.0),
+ ("L2", 10.0, 24.0),
+ ("L3", 10.0, 48.0),
+ ("R1", 200.0, 10.0),
+ ("R2", 200.0, 24.0),
+ ("R3", 200.0, 48.0),
+ ("Note", 10.0, 380.0),
+ ("Pg7", 200.0, 400.0),
+ ];
+ assert_eq!(lines(&footnote), "L1\nL2\nR1\nR2\nL3\nR3\nNote\nPg7");
+ // A caption under a full-width figure (no text from 70 to 250), as narrow as the left column, reads after both
+ // columns above the figure and before the columns below it.
+ let caption = [
+ ("L1", 10.0, 10.0),
+ ("L2", 10.0, 24.0),
+ ("L3", 10.0, 38.0),
+ ("R1", 200.0, 10.0),
+ ("R2", 200.0, 24.0),
+ ("R3", 200.0, 38.0),
+ ("Cap", 10.0, 260.0),
+ ("M1", 10.0, 290.0),
+ ("M2", 10.0, 304.0),
+ ("N1", 200.0, 290.0),
+ ("N2", 200.0, 304.0),
+ ];
+ assert_eq!(lines(&caption), "L1\nL2\nL3\nR1\nR2\nR3\nCap\nM1\nM2\nN1\nN2");
+ }
+
+ #[test]
+ fn many_column_paragraphs_order_in_bounded_time() {
+ // 2000 paragraphs in two columns, the right one offset by half a paragraph: every block is a column
+ // continuation, and choosing each one scans the remaining blocks.
+ let mut v = Vec::new();
+ for i in 0..1000u16 {
+ let y = 10.0 + 24.0 * f32::from(i);
+ word(&mut v, "L", 10.0, y, 6.0);
+ word(&mut v, "R", 200.0, y + 12.0, 6.0);
+ }
+ let start = std::time::Instant::now();
+ let text = layout(v).plain_text();
+ assert!(start.elapsed() < std::time::Duration::from_secs(5), "{:?}", start.elapsed());
+ // Compared without printing 4000 characters on failure.
+ let expected = format!("{}{}", "L\n".repeat(1000), "R\n".repeat(999) + "R");
+ assert!(text == expected, "the first R reads after {:?} lines, not 1000", text.find('R').map(|i| i / 2));
+ }
+
#[test]
fn tracked_text_keeps_letters_together() {
let mut v = Vec::new();
diff --git a/crates/render/tests/it/cid_fallback_query.rs b/crates/render/tests/it/cid_fallback_query.rs
new file mode 100644
index 0000000..12d2f6d
--- /dev/null
+++ b/crates/render/tests/it/cid_fallback_query.rs
@@ -0,0 +1,94 @@
+//! The request a font resolver gets for a CIDFont the document doesn't embed carries the style
+//! of the descendant's font descriptor (ISO 32000-2 §9.7.4.1, §9.7.6.1, §9.8). Contributor-original
+//! synthetic fixtures.
+use hayro::hayro_interpret::InterpreterSettings;
+use hayro::hayro_interpret::font::{FallbackFontQuery, FontQuery};
+use hayro::hayro_interpret::hayro_cmap::CidFamily;
+use hayro::hayro_syntax::Pdf;
+use hayro::{RenderCache, RenderSettings, render};
+use std::sync::{Arc, Mutex};
+
+/// A one-page document drawing two characters in a Type 0 font whose descendant is a
+/// non-embedded CIDFontType0 with the given entries after `/CIDSystemInfo`. The name says
+/// nothing about the style and matches no standard font.
+fn fixture(descendant_extra: &str, descriptor: Option<&str>) -> Vec<u8> {
+ let mut objects = vec![
+ "<< /Type /Catalog /Pages 2 0 R >>".to_string(),
+ "<< /Type /Pages /Kids [3 0 R] /Count 1 >>".into(),
+ "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 100] /Contents 4 0 R /Resources << /Font << /F1 5 0 R >> >> >>".into(),
+ stream("", "BT /F1 24 Tf 10 40 Td <11b30ed4> Tj ET"),
+ "<< /Type /Font /Subtype /Type0 /BaseFont /CraftCJK-W3 /Encoding /Identity-H /DescendantFonts [6 0 R] >>".into(),
+ format!(
+ "<< /Type /Font /Subtype /CIDFontType0 /BaseFont /CraftCJK-W3 \
+ /CIDSystemInfo << /Registry (Adobe) /Ordering (GB1) /Supplement 2 >> {descendant_extra} >>"
+ ),
+ ];
+ if let Some(descriptor) = descriptor {
+ objects.push(descriptor.to_string());
+ }
+ pdf(&objects)
+}
+
+/// The fallback queries the resolver received while drawing the page.
+fn fallback_queries(bytes: Vec<u8>) -> Vec<FallbackFontQuery> {
+ let seen = Arc::new(Mutex::new(Vec::new()));
+ let sink = seen.clone();
+ let settings = InterpreterSettings {
+ font_resolver: Arc::new(move |query| {
+ if let FontQuery::Fallback(f) = query {
+ sink.lock().unwrap().push(f.clone());
+ }
+ None
+ }),
+ ..InterpreterSettings::default()
+ };
+ let pdf = Pdf::new(bytes).unwrap();
+ let pages = pdf.pages();
+ let page = pages.first().unwrap();
+ let cache = RenderCache::new();
+ render(page, &cache, &settings, &RenderSettings::default());
+ seen.lock().unwrap().clone()
+}
+
+#[test]
+fn a_cid_font_fallback_request_carries_its_descendants_style() {
+ // Flags: Serif (bit 2), Nonsymbolic (bit 6), Italic (bit 7) = 2 + 32 + 64.
+ let descriptor = "<< /Type /FontDescriptor /FontName /CraftCJK-W3 /Flags 98 /FontWeight 700 \
+ /FontBBox [0 -120 1000 880] /ItalicAngle -12 /Ascent 880 /Descent -120 /CapHeight 700 /StemV 120 >>";
+ let queries = fallback_queries(fixture("/FontDescriptor 7 0 R", Some(descriptor)));
+ let query = queries.first().expect("the resolver is asked for a fallback");
+ assert_eq!(query.post_script_name.as_deref(), Some("CraftCJK-W3"));
+ assert!(query.character_collection.as_ref().is_some_and(|cc| cc.family == CidFamily::AdobeGB1), "{query:?}");
+ assert!(query.is_serif, "Serif flag of the descendant's descriptor: {query:?}");
+ assert!(query.is_italic, "Italic flag of the descendant's descriptor: {query:?}");
+ assert_eq!(query.font_weight, 700, "/FontWeight of the descendant's descriptor: {query:?}");
+}
+
+#[test]
+fn a_cid_font_without_a_descriptor_asks_for_the_default_style() {
+ let queries = fallback_queries(fixture("", None));
+ let query = queries.first().expect("the resolver is asked for a fallback");
+ assert_eq!(query.post_script_name.as_deref(), Some("CraftCJK-W3"));
+ assert!(!query.is_serif && !query.is_italic && !query.is_bold, "{query:?}");
+ assert_eq!(query.font_weight, 400);
+}
+
+fn pdf(objects: &[String]) -> Vec<u8> {
+ let mut bytes = b"%PDF-1.7\n".to_vec();
+ let mut offsets = Vec::new();
+ for (i, object) in objects.iter().enumerate() {
+ offsets.push(bytes.len());
+ bytes.extend_from_slice(format!("{} 0 obj\n{object}\nendobj\n", i + 1).as_bytes());
+ }
+ let xref = bytes.len();
+ bytes.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objects.len() + 1).as_bytes());
+ for offset in offsets {
+ bytes.extend_from_slice(format!("{offset:010} 00000 n \n").as_bytes());
+ }
+ bytes.extend_from_slice(format!("trailer << /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objects.len() + 1).as_bytes());
+ bytes
+}
+
+fn stream(dict: &str, body: &str) -> String {
+ format!("<< {dict} /Length {} >>\nstream\n{body}\nendstream", body.len())
+}
diff --git a/crates/render/tests/it/main.rs b/crates/render/tests/it/main.rs
index 944fcd0..ca9adf0 100644
--- a/crates/render/tests/it/main.rs
+++ b/crates/render/tests/it/main.rs
@@ -1,6 +1,11 @@
//! The crate's integration tests, linked into one test binary.
+mod cid_fallback_query;
mod inline_image_ei;
mod jbig2_invariants;
mod named_form_properties;
mod search;
+mod separation_all;
+mod substitute_widths;
+mod tiling_cell_placement;
+mod type3_text_clip;
diff --git a/crates/render/tests/it/separation_all.rs b/crates/render/tests/it/separation_all.rs
new file mode 100644
index 0000000..5b519e0
--- /dev/null
+++ b/crates/render/tests/it/separation_all.rs
@@ -0,0 +1,145 @@
+//! Contributor-original synthetic pages for the special colourant names of a Separation colour
+//! space (ISO 32000-2 §8.6.6.4): `/All` paints every colourant of the output device at once, so
+//! on screen a tint t is the gray 1 − t whatever the alternate space and tint transform say;
+//! `/None` paints nothing; any other name goes through its alternate space.
+use pdfcraft_render::{PageRenderer, RenderConfig, RenderRequest, RenderedPage};
+use std::sync::Arc;
+
+/// A tint transform into DeviceCMYK that gives cyan: tint t → (t, 0, 0, 0). Through it a tint
+/// draws light or full cyan, never a neutral gray, so a gray result proves it was not used.
+const CYAN: &str = "<< /FunctionType 2 /Domain [0 1] /C0 [0 0 0 0] /C1 [1 0 0 0] /N 1 >>";
+
+/// A PDF of the given objects (object 1 the catalog), with a cross-reference table. Each object
+/// is its bytes: a stream's data need not be text.
+fn pdf(objects: &[Vec<u8>]) -> Vec<u8> {
+ let mut bytes = b"%PDF-1.7\n".to_vec();
+ let mut offsets = Vec::new();
+ for (i, object) in objects.iter().enumerate() {
+ offsets.push(bytes.len());
+ bytes.extend_from_slice(format!("{} 0 obj\n", i + 1).as_bytes());
+ bytes.extend_from_slice(object);
+ bytes.extend_from_slice(b"\nendobj\n");
+ }
+ let xref = bytes.len();
+ bytes.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objects.len() + 1).as_bytes());
+ for offset in offsets {
+ bytes.extend_from_slice(format!("{offset:010} 00000 n \n").as_bytes());
+ }
+ bytes.extend_from_slice(format!("trailer << /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objects.len() + 1).as_bytes());
+ bytes
+}
+
+fn stream(dict: &str, data: &[u8]) -> Vec<u8> {
+ let mut bytes = format!("<< {dict} /Length {} >>\nstream\n", data.len()).into_bytes();
+ bytes.extend_from_slice(data);
+ bytes.extend_from_slice(b"\nendstream");
+ bytes
+}
+
+/// A 300 × 100 pt page drawing `content` with `resources`, then `extra` as objects 5 onwards.
+fn page(content: &str, resources: &str, extra: &[Vec<u8>]) -> Vec<u8> {
+ let mut objects = vec![
+ b"<< /Type /Catalog /Pages 2 0 R >>".to_vec(),
+ b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_vec(),
+ format!("<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 100] /Contents 4 0 R /Resources {resources} >>").into_bytes(),
+ stream("", content.as_bytes()),
+ ];
+ objects.extend_from_slice(extra);
+ pdf(&objects)
+}
+
+fn render(pdf: Vec<u8>) -> RenderedPage {
+ let mut renderer = PageRenderer::new(Arc::new(pdf), RenderConfig::default());
+ let out = renderer.render(RenderRequest { page: 0, scale: 1.0, ..Default::default() });
+ assert!(out.error.is_none(), "{:?}", out.error);
+ assert_eq!((out.width, out.height), (300, 100));
+ out
+}
+
+/// The RGB of the pixel at (`x`, `y`) pt from the page's top left.
+fn rgb(out: &RenderedPage, x: usize, y: usize) -> [u8; 3] {
+ let at = (y * out.width as usize + x) * 4;
+ let pixel = out.rgba.get(at..at + 3).expect("the pixel lies on the page");
+ [pixel[0], pixel[1], pixel[2]]
+}
+
+/// `got` is the neutral gray `want`, give or take one level of rounding.
+fn assert_gray(got: [u8; 3], want: u8, what: &str) {
+ assert!(got.iter().all(|c| c.abs_diff(want) <= 1), "{what}: got {got:?}, want gray {want}");
+}
+
+/// Three boxes filled with `cs` at tints 0, 0.5 and 1, left to right.
+fn three_tints(space: &str) -> RenderedPage {
+ let content = "/CS0 cs 0 scn 0 0 100 100 re f 0.5 scn 100 0 100 100 re f 1 scn 200 0 100 100 re f";
+ render(page(content, "<< /ColorSpace << /CS0 5 0 R >> >>", &[space.as_bytes().to_vec(), CYAN.as_bytes().to_vec()]))
+}
+
+#[test]
+fn separation_all_fills_paint_the_complemented_tint_as_gray() {
+ let out = three_tints("[/Separation /All /DeviceCMYK 6 0 R]");
+ assert_gray(rgb(&out, 50, 50), 255, "tint 0 paints no colourant: white");
+ assert_gray(rgb(&out, 150, 50), 128, "tint 0.5 paints half of every colourant: 50% gray");
+ assert_gray(rgb(&out, 250, 50), 0, "tint 1 paints every colourant: black");
+}
+
+#[test]
+fn separation_all_strokes_paint_the_complemented_tint_as_gray() {
+ let content = "/CS0 CS 0.25 SCN 40 w 0 50 m 300 50 l S";
+ let out =
+ render(page(content, "<< /ColorSpace << /CS0 5 0 R >> >>", &[b"[/Separation /All /DeviceCMYK 6 0 R]".to_vec(), CYAN.as_bytes().to_vec()]));
+ assert_gray(rgb(&out, 150, 50), 191, "a stroke at tint 0.25: 75% gray");
+}
+
+#[test]
+fn separation_none_paints_nothing() {
+ // A red background, so "nothing" is told apart from white.
+ let content = "1 0 0 rg 0 0 300 100 re f /CS0 cs 0 scn 0 0 100 100 re f 0.5 scn 100 0 100 100 re f 1 scn 200 0 100 100 re f";
+ let out =
+ render(page(content, "<< /ColorSpace << /CS0 5 0 R >> >>", &[b"[/Separation /None /DeviceCMYK 6 0 R]".to_vec(), CYAN.as_bytes().to_vec()]));
+ for x in [50, 150, 250] {
+ assert_eq!(rgb(&out, x, 50), [255, 0, 0], "a /None fill at x = {x} leaves the background");
+ }
+}
+
+#[test]
+fn a_named_separation_still_paints_through_its_alternate() {
+ let out = three_tints("[/Separation /Cyan /DeviceCMYK 6 0 R]");
+ let [white, half, full] = [rgb(&out, 50, 50), rgb(&out, 150, 50), rgb(&out, 250, 50)];
+ assert_gray(white, 255, "tint 0 of a named colourant");
+ for (what, colour) in [("tint 0.5", half), ("tint 1", full)] {
+ // Cyan: red well below green and blue.
+ assert!(colour[0] < colour[1] && colour[0] < colour[2] && colour[2] > 200, "{what} of /Cyan is cyan: {colour:?}");
+ }
+ assert!(full[0] < half[0], "full cyan is deeper than half: {full:?} against {half:?}");
+}
+
+#[test]
+fn a_device_n_space_naming_all_still_paints_through_its_alternate() {
+ // §8.6.6.4 gives All its meaning in a Separation space; a DeviceN space keeps its alternate.
+ let out = three_tints("[/DeviceN [/All] /DeviceCMYK 6 0 R]");
+ let half = rgb(&out, 150, 50);
+ assert!(half[0] < half[1] && half[0] < half[2], "DeviceN [/All] at 0.5 draws its tint transform's cyan: {half:?}");
+}
+
+#[test]
+fn separation_all_images_paint_each_sample_as_the_complemented_gray() {
+ // Three 8-bit samples: tints 0, 128/255 and 1.
+ let data = [0u8, 128, 255];
+ let image =
+ stream("/Type /XObject /Subtype /Image /Width 3 /Height 1 /ColorSpace [/Separation /All /DeviceCMYK 6 0 R] /BitsPerComponent 8", &data);
+ let out = render(page("q 300 0 0 100 0 0 cm /Im Do Q", "<< /XObject << /Im 5 0 R >> >>", &[image, CYAN.as_bytes().to_vec()]));
+ assert_gray(rgb(&out, 50, 50), 255, "sample 0");
+ assert_gray(rgb(&out, 150, 50), 127, "sample 128");
+ assert_gray(rgb(&out, 250, 50), 0, "sample 255");
+}
+
+#[test]
+fn separation_all_shadings_paint_the_complemented_gray() {
+ // An axial shading from tint 0 at x = 0 to tint 1 at x = 300, painted with `sh`.
+ let shading = "<< /ShadingType 2 /ColorSpace [/Separation /All /DeviceCMYK 6 0 R] /Coords [0 0 300 0] /Function << /FunctionType 2 /Domain [0 1] /C0 [0] /C1 [1] /N 1 >> /Extend [true true] >>";
+ let out = render(page("/Sh sh", "<< /Shading << /Sh 5 0 R >> >>", &[shading.as_bytes().to_vec(), CYAN.as_bytes().to_vec()]));
+ for (x, want) in [(1usize, 254u8), (150, 128), (298, 1)] {
+ let got = rgb(&out, x, 50);
+ assert!(got.iter().all(|c| c.abs_diff(want) <= 3), "shading at x = {x}: got {got:?}, want gray near {want}");
+ }
+}
diff --git a/crates/render/tests/it/substitute_widths.rs b/crates/render/tests/it/substitute_widths.rs
new file mode 100644
index 0000000..b7c4073
--- /dev/null
+++ b/crates/render/tests/it/substitute_widths.rs
@@ -0,0 +1,116 @@
+//! Contributor-original synthetic fonts: a simple font the document names but doesn't embed is
+//! drawn with a standard-font stand-in, its glyphs placed at the advances `/Widths` gives
+//! (ISO 32000-2 §9.6.2.1, Table 109) and their shapes kept.
+
+use pdfcraft_render::{PageRenderer, RenderConfig, RenderRequest};
+use std::sync::Arc;
+
+const SIZE: f64 = 80.0;
+
+fn pdf(objects: &[String]) -> Vec<u8> {
+ let mut bytes = b"%PDF-1.7\n".to_vec();
+ let mut offsets = Vec::new();
+ for (i, object) in objects.iter().enumerate() {
+ offsets.push(bytes.len());
+ bytes.extend_from_slice(format!("{} 0 obj\n{object}\nendobj\n", i + 1).as_bytes());
+ }
+ let xref = bytes.len();
+ bytes.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objects.len() + 1).as_bytes());
+ for offset in offsets {
+ bytes.extend_from_slice(format!("{offset:010} 00000 n \n").as_bytes());
+ }
+ bytes.extend_from_slice(format!("trailer << /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objects.len() + 1).as_bytes());
+ bytes
+}
+
+/// A page showing `text` at 80 pt in the font dictionary `font`, with the font descriptor
+/// `descriptor` as object 6.
+fn page(font: &str, descriptor: &str, text: &str) -> Vec<u8> {
+ let body = format!("BT /F1 {SIZE} Tf 20 30 Td ({text}) Tj ET");
+ pdf(&[
+ "<< /Type /Catalog /Pages 2 0 R >>".into(),
+ "<< /Type /Pages /Kids [3 0 R] /Count 1 >>".into(),
+ "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 400 140] /Contents 4 0 R /Resources << /Font << /F1 5 0 R >> >> >>".into(),
+ format!("<< /Length {} >>\nstream\n{body}\nendstream", body.len()),
+ font.into(),
+ descriptor.into(),
+ ])
+}
+
+/// The runs of columns holding dark pixels, as (first, last) column.
+fn ink_runs(bytes: Vec<u8>) -> Vec<(u32, u32)> {
+ let mut renderer = PageRenderer::new(Arc::new(bytes), RenderConfig::default());
+ let image = renderer.render(RenderRequest { page: 0, scale: 1.0, ..Default::default() });
+ assert!(image.error.is_none(), "{:?}", image.error);
+ let dark = |x: u32| {
+ (0..image.height).any(|y| {
+ let at = usize::try_from((y * image.width + x) * 4).unwrap_or(usize::MAX);
+ image.rgba.get(at).is_some_and(|r| *r < 128)
+ })
+ };
+ let mut runs: Vec<(u32, u32)> = Vec::new();
+ for x in 0..image.width {
+ if dark(x) {
+ match runs.last_mut() {
+ Some(run) if run.1 + 1 == x => run.1 = x,
+ _ => runs.push((x, x)),
+ }
+ }
+ }
+ runs
+}
+
+fn standard(name: &str, text: &str) -> Vec<(u32, u32)> {
+ ink_runs(page(&format!("<< /Type /Font /Subtype /Type1 /BaseFont /{name} /Encoding /WinAnsiEncoding >>"), "<< >>", text))
+}
+
+fn substituted(base_font: &str, flags: u32, weight: u32, code: u8, width: u32, text: &str) -> Vec<(u32, u32)> {
+ let font = format!(
+ "<< /Type /Font /Subtype /TrueType /BaseFont /{base_font} /Encoding /WinAnsiEncoding \
+ /FirstChar {code} /LastChar {code} /Widths [{width}] /FontDescriptor 6 0 R >>"
+ );
+ let descriptor = format!(
+ "<< /Type /FontDescriptor /FontName /{base_font} /Flags {flags} /FontBBox [-600 -200 2000 1000] \
+ /ItalicAngle 0 /Ascent 900 /Descent -200 /CapHeight 700 /StemV 140 /FontWeight {weight} >>"
+ );
+ ink_runs(page(&font, &descriptor, text))
+}
+
+/// A `/Widths` entry wider than the stand-in's glyph moves the next glyph on, and the glyph keeps
+/// its own shape: every advance of 600 stretched each glyph of `Arial,Bold` to 600 units, so the
+/// stems of `i` and `l` became solid blocks twice their width and the text read as a heavy
+/// fixed-pitch face.
+#[test]
+fn a_substitute_keeps_its_glyph_shapes_at_wider_advances() {
+ for (base_font, flags, weight, stand_in) in [
+ ("Arial,Bold", 32, 700, "Helvetica-Bold"),
+ ("Arial,Bold", 4, 700, "Helvetica-Bold"),
+ ("Arial-BoldMT", 32, 700, "Helvetica-Bold"),
+ ("ArialMT", 32, 400, "Helvetica"),
+ ] {
+ let reference = standard(stand_in, "l");
+ let [(ref_start, ref_end)] = reference[..] else { panic!("{stand_in}: one stem, {reference:?}") };
+ let runs = substituted(base_font, flags, weight, b'l', 600, "ll");
+ let [(first, first_end), (second, second_end)] = runs[..] else { panic!("{base_font}: two stems, {runs:?}") };
+ for (start, end) in [(first, first_end), (second, second_end)] {
+ assert!(
+ (end - start).abs_diff(ref_end - ref_start) <= 1,
+ "{base_font} /Flags {flags}: the stem is {stand_in}'s, not stretched: {runs:?} vs {reference:?}"
+ );
+ }
+ // 600 units at 80 pt is 48 pixels.
+ assert!((second - first).abs_diff(48) <= 1, "{base_font}: the second l is 600 units on: {runs:?}");
+ assert!(first.abs_diff(ref_start) <= 1, "{base_font}: the first l starts where {stand_in}'s does: {runs:?} vs {reference:?}");
+ }
+}
+
+/// A `/Widths` entry narrower than the stand-in's glyph still narrows the glyph to it, so
+/// neighbours don't overlap: `W` (944 units in Helvetica-Bold) at an advance of 400.
+#[test]
+fn a_substitute_still_narrows_glyphs_to_narrower_advances() {
+ let runs = substituted("Arial,Bold", 32, 700, b'W', 400, "WW");
+ let [(first, first_end), (second, _)] = runs[..] else { panic!("two separate glyphs: {runs:?}") };
+ // 400 units at 80 pt is 32 pixels.
+ assert!(first_end - first <= 33, "the W is narrowed to its advance: {runs:?}");
+ assert!((second - first).abs_diff(32) <= 1, "the second W is 400 units on: {runs:?}");
+}
diff --git a/crates/render/tests/it/tiling_cell_placement.rs b/crates/render/tests/it/tiling_cell_placement.rs
new file mode 100644
index 0000000..3a57f15
--- /dev/null
+++ b/crates/render/tests/it/tiling_cell_placement.rs
@@ -0,0 +1,191 @@
+//! Tiling pattern cells sit at whole multiples of `/XStep` and `/YStep` in pattern space
+//! (ISO 32000-2 8.7.3.1, Table 74), at any rendering scale, however far they are from the
+//! pattern's origin.
+//!
+//! Each page is filled (or stroked) with a pattern whose 20 × 20 cell holds one 6 × 6 blue square
+//! at (7, 7). At 110 dpi a step is 30.56 device pixels; every probe finds the blue square in a
+//! disc around where the pattern matrix puts it and checks that its centroid is within one
+//! device pixel of that place.
+
+use std::sync::Arc;
+
+use pdfcraft_render::{PageRenderer, RenderConfig, RenderRequest, RequestKind};
+
+/// The rendering scale for 110 dpi: a step of 20 points is 30.56 pixels, not a whole number.
+const SCALE: f64 = 110.0 / 72.0;
+/// The page is `SIDE` × `SIDE` points.
+const SIDE: f64 = 400.0;
+
+/// One page `SIDE` points square whose content `content` paints with `/P1`: the 20-point cell
+/// with its blue square, `/XStep` and `/YStep` 20, under pattern matrix `matrix`.
+fn page_pdf(content: &str, matrix: [f64; 6]) -> Vec<u8> {
+ let cell = "0 0 1 rg 7 7 6 6 re f";
+ let m = matrix.map(|v| format!("{v}")).join(" ");
+ format!(
+ "%PDF-1.7
+1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj
+2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj
+3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 {SIDE} {SIDE}] /Contents 4 0 R /Resources << /Pattern << /P1 5 0 R >> >> >> endobj
+4 0 obj << /Length {} >> stream
+{content}
+endstream endobj
+5 0 obj << /Type /Pattern /PatternType 1 /PaintType 1 /TilingType 1 /BBox [0 0 20 20] /XStep 20 /YStep 20 /Matrix [{m}] /Length {} >> stream
+{cell}
+endstream endobj
+trailer << /Root 1 0 R >>
+%%EOF",
+ content.len(),
+ cell.len()
+ )
+ .into_bytes()
+}
+
+struct Page {
+ rgba: Vec<u8>,
+ width: usize,
+ height: usize,
+}
+
+fn render(content: &str, matrix: [f64; 6]) -> Page {
+ let mut r = PageRenderer::new(Arc::new(page_pdf(content, matrix)), RenderConfig::default());
+ let page = r.render(RenderRequest { page: 0, kind: RequestKind::Pixels, tile: None, scale: SCALE as f32, tag: 0, ..Default::default() });
+ assert!(page.error.is_none(), "{:?}", page.error);
+ Page { rgba: page.rgba.to_vec(), width: page.width as usize, height: page.height as usize }
+}
+
+/// The device position of pattern-space point `(x, y)`: the pattern matrix to page space, then
+/// page space to device pixels (y down).
+fn device(matrix: [f64; 6], x: f64, y: f64) -> (f64, f64) {
+ let [a, b, c, d, e, f] = matrix;
+ let (px, py) = (a * x + c * y + e, b * x + d * y + f);
+ (px * SCALE, (SIDE - py) * SCALE)
+}
+
+/// The centroid of blue (weighted by how far each pixel is from white) in the disc of `radius`
+/// pixels around `(cx, cy)`, and the total weight. `None` when the disc leaves the page.
+fn blue_centroid(page: &Page, cx: f64, cy: f64, radius: f64) -> Option<((f64, f64), f64)> {
+ let (x0, x1) = ((cx - radius).floor(), (cx + radius).ceil());
+ let (y0, y1) = ((cy - radius).floor(), (cy + radius).ceil());
+ if x0 < 0.0 || y0 < 0.0 || x1 >= page.width as f64 || y1 >= page.height as f64 {
+ return None;
+ }
+ let (mut sum, mut sx, mut sy) = (0.0, 0.0, 0.0);
+ for j in (y0 as usize)..=(y1 as usize) {
+ for i in (x0 as usize)..=(x1 as usize) {
+ let (px, py) = (i as f64 + 0.5, j as f64 + 0.5);
+ if (px - cx).powi(2) + (py - cy).powi(2) > radius * radius {
+ continue;
+ }
+ let red = *page.rgba.get((j * page.width + i) * 4)?;
+ let w = f64::from(255 - red) / 255.0;
+ sum += w;
+ sx += w * px;
+ sy += w * py;
+ }
+ }
+ (sum > 0.0).then(|| ((sx / sum, sy / sum), sum))
+}
+
+/// Checks every cell `(k, m)` whose blue square's centre falls in the page rectangle `area`
+/// (points: x0, y0, x1, y1): its square is found where the matrix puts it, within one pixel.
+/// Returns how many cells were checked.
+fn assert_cells_in_place(page: &Page, matrix: [f64; 6], area: [f64; 4], what: &str) -> usize {
+ let [a, b, c, d, _, _] = matrix;
+ // The square is 6 × 6 at (7, 7); its centre is (10, 10) in the cell. A disc of 6 cell
+ // units around it holds the whole square (half-diagonal 4.24) and no neighbour (7 away).
+ let units = (a * a + b * b).sqrt().min((c * c + d * d).sqrt());
+ let radius = 6.0 * units * SCALE;
+ let area_px = 36.0 * units * units * SCALE * SCALE;
+ let mut checked = 0;
+ for k in -60..60 {
+ for m in -60..60 {
+ let (cx_cell, cy_cell) = (20.0 * f64::from(k) + 10.0, 20.0 * f64::from(m) + 10.0);
+ let [ea, eb, ec, ed, ee, ef] = matrix;
+ let (px, py) = (ea * cx_cell + ec * cy_cell + ee, eb * cx_cell + ed * cy_cell + ef);
+ if px < area[0] || px > area[2] || py < area[1] || py > area[3] {
+ continue;
+ }
+ let (cx, cy) = device(matrix, cx_cell, cy_cell);
+ let Some(((gx, gy), weight)) = blue_centroid(page, cx, cy, radius) else { continue };
+ assert!(weight > 0.8 * area_px, "{what}: cell ({k}, {m}) at ({cx:.1}, {cy:.1}) only partly there: {weight:.1} of {area_px:.1}");
+ assert!(
+ (gx - cx).abs() <= 1.0 && (gy - cy).abs() <= 1.0,
+ "{what}: cell ({k}, {m}) should be centred at ({cx:.2}, {cy:.2}) px, found at ({gx:.2}, {gy:.2})"
+ );
+ checked += 1;
+ }
+ }
+ checked
+}
+
+const IDENTITY: [f64; 6] = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0];
+
+/// A fill far from the pattern's origin: the cells 300 to 400 points away (15 to 19 steps) are
+/// where 15 to 19 steps put them, not 0.44 pixel further for every step.
+#[test]
+fn far_cells_of_a_fill_sit_at_whole_steps() {
+ let page = render("/Pattern cs /P1 scn 0 0 400 400 re f", IDENTITY);
+ let near = assert_cells_in_place(&page, IDENTITY, [0.0, 0.0, 100.0, 100.0], "near the origin");
+ let far = assert_cells_in_place(&page, IDENTITY, [290.0, 290.0, 400.0, 400.0], "far from the origin");
+ assert!(near >= 16 && far >= 16, "{near} near, {far} far");
+}
+
+/// The same under a pattern matrix that scales by 1.49 and turns by 30 degrees: a step is
+/// 45.5 pixels along each turned axis.
+#[test]
+fn far_cells_sit_at_whole_steps_under_a_turned_scaled_matrix() {
+ let (scale, turn) = (1.49_f64, 30_f64.to_radians());
+ let matrix = [scale * turn.cos(), scale * turn.sin(), -scale * turn.sin(), scale * turn.cos(), 3.0, 5.0];
+ let page = render("/Pattern cs /P1 scn 0 0 400 400 re f", matrix);
+ let far = assert_cells_in_place(&page, matrix, [250.0, 250.0, 390.0, 390.0], "turned and scaled");
+ assert!(far >= 6, "{far} cells checked");
+}
+
+/// A stroke painted with the pattern: the cells under a wide border far from the origin are
+/// in place on every side of it.
+#[test]
+fn far_cells_of_a_stroke_sit_at_whole_steps() {
+ let page = render("/Pattern CS /P1 SCN 40 w 200 200 180 180 re S", IDENTITY);
+ let mut checked = 0;
+ // The border is 40 points wide around the square from (200, 200) to (380, 380).
+ for band in [[180.0, 180.0, 400.0, 220.0], [180.0, 360.0, 400.0, 400.0], [180.0, 180.0, 220.0, 400.0], [360.0, 180.0, 400.0, 400.0]] {
+ checked += assert_cells_in_place(&page, IDENTITY, band, "stroke");
+ }
+ assert!(checked >= 20, "{checked} cells checked");
+ // Inside the border nothing is painted.
+ let (cx, cy) = device(IDENTITY, 290.0, 290.0);
+ let at = ((cy as usize) * page.width + cx as usize) * 4;
+ assert_eq!(page.rgba.get(at..at + 3), Some(&[255, 255, 255][..]), "inside the stroked square");
+}
+
+/// The cell pixmap's side and the scale its cell is drawn at: one step is exactly the side, the
+/// side stays within 1 and the cap whatever the step, and nothing odd reaches the cast.
+#[test]
+fn a_cell_pixmap_spans_exactly_one_step() {
+ // 110 dpi, a step of 20: 30.56 pixels, drawn at 31 / 20.
+ assert_eq!(hayro::tiling_cell_pixels(110.0 / 72.0, 20.0, 3000.0), (31, 31.0 / 20.0));
+ assert_eq!(hayro::tiling_cell_pixels(110.0 / 72.0, -20.0, 3000.0), (31, 31.0 / 20.0), "a negative step");
+ for (scale, step) in [(1.0_f32, 7.3_f32), (2.37, 0.9), (0.013, 1234.5), (3.0, 999.9), (1.0, 2.0e9)] {
+ let (side, drawn) = hayro::tiling_cell_pixels(scale, step, 3000.0);
+ assert!((1..=3000).contains(&side), "{scale} {step}: {side}");
+ let span = drawn * f64::from(step);
+ assert!((span - f64::from(side)).abs() < 1e-9 * f64::from(side), "{scale} {step}: a step spans {span}, not {side}");
+ if f64::from(scale) * f64::from(step) <= 3000.0 {
+ assert!((span - f64::from(scale) * f64::from(step)).abs() <= 0.5 + 1e-9, "{scale} {step}: drawn {drawn}");
+ }
+ }
+ // A step under half a pixel still gets one pixel (a 0 × N pixmap can't be sampled).
+ assert_eq!(hayro::tiling_cell_pixels(0.03, 10.0, 3000.0), (1, 0.1));
+ // Steps and scales that aren't finite and positive: the side is bounded, the scale kept.
+ assert_eq!(hayro::tiling_cell_pixels(2.0, f32::INFINITY, 3000.0), (3000, 2.0));
+ assert_eq!(hayro::tiling_cell_pixels(2.0, 0.0, 3000.0), (1, 2.0));
+ let (side, drawn) = hayro::tiling_cell_pixels(f32::NAN, 20.0, 3000.0);
+ assert!(side == 1 && drawn.is_nan());
+ // A cap past u16::MAX is lowered to it, and the scale follows the side the pixmap gets.
+ let (side, drawn) = hayro::tiling_cell_pixels(2.0, 1.0e6, 1.0e9);
+ assert_eq!(side, u16::MAX, "the cap is at most u16::MAX");
+ assert!((drawn * 1.0e6 - f64::from(u16::MAX)).abs() < 1e-6, "a step spans the side: {drawn}");
+ // A cap that is not a whole number, or not a number, is a whole number of pixels.
+ assert_eq!(hayro::tiling_cell_pixels(1.0, 100.0, 30.7), (30, 0.3));
+ assert_eq!(hayro::tiling_cell_pixels(1.0, 100.0, f32::NAN), (1, 0.01));
+}
diff --git a/crates/render/tests/it/type3_text_clip.rs b/crates/render/tests/it/type3_text_clip.rs
new file mode 100644
index 0000000..2cdfce5
--- /dev/null
+++ b/crates/render/tests/it/type3_text_clip.rs
@@ -0,0 +1,163 @@
+//! Contributor-original synthetic pages: text in a Type 3 font in the text rendering modes
+//! (ISO 32000-2 §9.3.6, Table 104). For a Type 3 font, modes 3 and 7 render nothing, the other
+//! modes render the glyph descriptions, and modes 4 to 7 add nothing to the clipping path
+//! (vendored hayro-interpret patch 64).
+use pdfcraft_render::{PageRenderer, RenderConfig, RenderRequest, RequestKind};
+use std::sync::Arc;
+
+/// Glyph procedures in a 1000-unit glyph space (`/FontMatrix [0.001 0 0 0.001 0 0]`), named
+/// by the letters that show them: the `/Differences` give them codes 65 (`A`) on, in order.
+const GLYPHS: &[(&str, &[u8])] = &[
+ // A: a square, x 100..900, y 0..800.
+ ("A", b"1000 0 100 0 900 800 d1 100 0 800 800 re f"),
+ // B: a triangle on the baseline with its apex at the top middle.
+ ("B", b"1000 0 0 0 1000 1000 d1 0 0 m 1000 0 l 500 1000 l f"),
+ // C: a coloured glyph (`d0`): a blue square.
+ ("C", b"1000 0 d0 0 0 1 rg 100 0 800 800 re f"),
+ // D: shows four of itself, nesting until the paint budget runs out.
+ ("D", b"1000 0 0 0 1000 1000 d1 BT /T3 1000 Tf 0 0 Td (DDDD) Tj ET"),
+];
+
+fn pdf(content: &str) -> Vec<u8> {
+ let names: String = GLYPHS.iter().map(|(n, _)| format!("/{n} ")).collect();
+ let procs: String = GLYPHS.iter().enumerate().map(|(i, (n, _))| format!("/{n} {} 0 R ", 6 + i)).collect();
+ let widths = vec!["1000"; GLYPHS.len()].join(" ");
+ let mut objects: Vec<Vec<u8>> = vec![
+ b"<< /Type /Catalog /Pages 2 0 R >>".to_vec(),
+ b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_vec(),
+ b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 100 100] /Contents 4 0 R /Resources << /Font << /T3 5 0 R /F1 << /Type /Font /Subtype /Type1 /BaseFont /Helvetica >> >> >> >>".to_vec(),
+ stream(content.as_bytes()),
+ format!(
+ "<< /Type /Font /Subtype /Type3 /FontBBox [0 0 1000 1000] /FontMatrix [0.001 0 0 0.001 0 0] \
+ /CharProcs << {procs}>> /Encoding << /Type /Encoding /Differences [65 {names}] >> \
+ /FirstChar 65 /LastChar {} /Widths [{widths}] >>",
+ 64 + GLYPHS.len()
+ )
+ .into_bytes(),
+ ];
+ objects.extend(GLYPHS.iter().map(|(_, body)| stream(body)));
+ let mut out = b"%PDF-1.7\n".to_vec();
+ let mut offsets = Vec::new();
+ for (i, object) in objects.iter().enumerate() {
+ offsets.push(out.len());
+ out.extend_from_slice(format!("{} 0 obj\n", i + 1).as_bytes());
+ out.extend_from_slice(object);
+ out.extend_from_slice(b"\nendobj\n");
+ }
+ let xref = out.len();
+ out.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objects.len() + 1).as_bytes());
+ for offset in offsets {
+ out.extend_from_slice(format!("{offset:010} 00000 n \n").as_bytes());
+ }
+ out.extend_from_slice(format!("trailer << /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objects.len() + 1).as_bytes());
+ out
+}
+
+fn stream(body: &[u8]) -> Vec<u8> {
+ let mut s = format!("<< /Length {} >>\nstream\n", body.len()).into_bytes();
+ s.extend_from_slice(body);
+ s.extend_from_slice(b"\nendstream");
+ s
+}
+
+/// A 100 x 100 pixel rendering of a 100 x 100 pt page; `at(x, y)` reads the pixel at page
+/// coordinates (y up).
+struct Page(Vec<u8>);
+
+impl Page {
+ fn render(content: &str) -> Self {
+ let mut renderer = PageRenderer::new(Arc::new(pdf(content)), RenderConfig::default());
+ let page = renderer.render(RenderRequest { page: 0, kind: RequestKind::Pixels, scale: 1.0, ..Default::default() });
+ assert!(page.error.is_none(), "{content}: {:?}", page.error);
+ assert_eq!((page.width, page.height), (100, 100), "{content}");
+ Self(page.rgba.to_vec())
+ }
+
+ fn at(&self, x: usize, y: usize) -> [u8; 3] {
+ let i = ((99 - y) * 100 + x) * 4;
+ match self.0.get(i..i + 3) {
+ Some([r, g, b]) => [*r, *g, *b],
+ _ => panic!("pixel {x},{y} is off the page"),
+ }
+ }
+
+ /// Whether any pixel is dark in every channel: a glyph painted in the default black.
+ fn has_black(&self) -> bool {
+ self.0.as_chunks::<4>().0.iter().any(|p| p[0] < 128 && p[1] < 128 && p[2] < 128)
+ }
+}
+
+const RED: [u8; 3] = [255, 0, 0];
+const BLUE: [u8; 3] = [0, 0, 255];
+const WHITE: [u8; 3] = [255, 255, 255];
+
+/// `ABA` at 20 pt from (10, 40): squares x 12..28 and 52..68 (y 40..56), and a triangle from
+/// (30, 40) and (50, 40) up to (40, 60).
+const ABA: &str = "/T3 20 Tf 10 40 Td (ABA) Tj";
+
+#[test]
+fn clip_only_type3_text_is_not_rendered_and_leaves_no_clip() {
+ // The fill stops at x 60, inside the second square: a glyph painted under `7 Tr` would show
+ // past it as a bar beside the box.
+ let page = Page::render(&format!("BT 7 Tr {ABA} ET 1 0 0 rg 0 0 60 100 re f"));
+ assert_eq!(page.at(20, 48), RED, "the fill over the first square");
+ assert_eq!(page.at(5, 5), RED, "no clip: the fill covers its whole box");
+ assert_eq!(page.at(29, 45), RED, "no clip between the glyphs either");
+ assert_eq!(page.at(33, 57), RED, "no clip beside the triangle");
+ assert_eq!(page.at(64, 48), WHITE, "the second square past the fill is not rendered");
+ assert_eq!(page.at(80, 80), WHITE, "outside the fill");
+ assert!(!page.has_black(), "7 Tr renders no glyph");
+
+ // Alone, neither shape glyphs nor a coloured glyph leave a mark.
+ for text in [ABA, "/T3 20 Tf 10 40 Td (C) Tj"] {
+ let page = Page::render(&format!("BT 7 Tr {text} ET"));
+ assert!(page.0.as_chunks::<4>().0.iter().all(|p| p[..3] == WHITE), "7 Tr {text} renders nothing");
+ }
+}
+
+#[test]
+fn invisible_type3_text_is_not_rendered() {
+ for text in [ABA, "/T3 20 Tf 10 40 Td (C) Tj"] {
+ let page = Page::render(&format!("BT 3 Tr {text} ET"));
+ assert!(page.0.as_chunks::<4>().0.iter().all(|p| p[..3] == WHITE), "3 Tr {text} renders nothing");
+ }
+}
+
+#[test]
+fn other_modes_render_type3_glyphs_filled_and_never_clip() {
+ for mode in [0, 1, 2, 4, 5, 6] {
+ let page = Page::render(&format!("BT 0 0 1 rg 1 1 0 RG 6 w {mode} Tr {ABA} ET 1 0 0 rg 0 0 60 100 re f"));
+ assert_eq!(page.at(64, 48), BLUE, "{mode} Tr: the glyph is rendered, in the fill colour");
+ assert_eq!(page.at(70, 48), WHITE, "{mode} Tr: and not stroked");
+ assert_eq!(page.at(20, 48), RED, "{mode} Tr: the later fill over the glyph");
+ assert_eq!(page.at(5, 5), RED, "{mode} Tr: the later fill is not clipped");
+ assert_eq!(page.at(29, 45), RED, "{mode} Tr: not clipped between the glyphs");
+ assert!(!page.has_black(), "{mode} Tr");
+ }
+ // A coloured glyph keeps its own colour.
+ let page = Page::render("BT 1 0 0 rg 4 Tr /T3 20 Tf 10 40 Td (C) Tj ET");
+ assert_eq!(page.at(20, 48), BLUE);
+}
+
+#[test]
+fn only_outline_glyphs_shape_a_clip_shared_with_type3_text() {
+ // `I` in Helvetica at 40 pt from (60, 10): its stem covers (65, 20). The square A from
+ // (10, 40) at 20 pt adds nothing to the clip and is not rendered.
+ let page = Page::render("BT 7 Tr /F1 40 Tf 60 10 Td (I) Tj /T3 20 Tf -50 30 Td (A) Tj ET 1 0 0 rg 0 0 100 100 re f");
+ assert_eq!(page.at(65, 20), RED, "inside the outline glyph's clip");
+ assert_eq!(page.at(20, 48), WHITE, "the Type 3 square neither clips nor paints");
+ assert_eq!(page.at(5, 5), WHITE, "outside the clip");
+ assert!(!page.has_black());
+}
+
+#[test]
+fn self_nesting_type3_text_in_a_clip_mode_stays_bounded() {
+ // Every D shows four Ds: unbounded this is 4^n procedures. The paint nesting depth and the
+ // page's paint budget stop it; the page must still render.
+ for mode in [4, 6, 7] {
+ let content = format!("BT {mode} Tr /T3 20 Tf 10 40 Td (DD) Tj ET 1 0 0 rg 0 0 100 100 re f");
+ let page = Page::render(&content);
+ assert_eq!(page.at(5, 5), RED, "{content}: no clip");
+ assert!(!page.has_black(), "{content}");
+ }
+}
diff --git a/crates/sign/Cargo.toml b/crates/sign/Cargo.toml
index d58811d..4f1f0d4 100644
--- a/crates/sign/Cargo.toml
+++ b/crates/sign/Cargo.toml
@@ -14,6 +14,7 @@ workspace = true
pdfcraft-cos = { workspace = true }
pdfcraft-annot = { workspace = true }
pdfcraft-fonts = { workspace = true }
+pdfcraft-model = { workspace = true }
thiserror.workspace = true
# ASN.1 UTCTime/GeneralizedTime conversion goes through chrono (no hand-rolled calendar code).
chrono = { workspace = true }
diff --git a/crates/sign/README.md b/crates/sign/README.md
index 72f72dd..6844b1a 100644
--- a/crates/sign/README.md
+++ b/crates/sign/README.md
@@ -22,7 +22,10 @@ for s in signatures(&doc, &bytes, &trust) { // li
An existing unsigned field or a new one (visible with Acrobat's name-and-details appearance,
or invisible); certification with DocMDP P=1/2/3. A visible signature can show a `Graphic`
where the large name would be: drawn strokes, filled outlines (a typed signature) or RGBA
- pixels (an image XObject with a soft mask), checked and size-capped first. The document is written incrementally
+ pixels (an image XObject with a soft mask), checked and size-capped first. On a page shown
+ turned (`/Rotate`, inherited or not), a new visible signature reads upright as displayed: its
+ widget gets `/MK /R` and its appearance is laid out in the displayed box and turned back by a
+ `/Matrix`; an existing field follows its own `/MK /R`. The document is written incrementally
with a zero-filled `/Contents` and fixed-width `/ByteRange`, which are then patched in
place. Encrypted documents are refused for now.
- **Timestamps (PAdES B-T):** the `timestamp` module builds and parses RFC 3161 requests,
diff --git a/crates/sign/src/cms.rs b/crates/sign/src/cms.rs
index 3568cbf..b148ea4 100644
--- a/crates/sign/src/cms.rs
+++ b/crates/sign/src/cms.rs
@@ -294,6 +294,24 @@ fn parse_signer(si: &Tlv<'_>) -> Result<SignerInfo, SignError> {
}
let (scheme, scheme_digest) = signature_algorithm(&next)?;
let signature = it.next().ok_or_else(|| bad("signature"))?.octets("signature")?.into_owned();
+ let (timestamp, timestamp_token) = parse_timestamp_token(it)?;
+ Ok(SignerInfo {
+ sid,
+ digest,
+ signed_attrs,
+ message_digest,
+ content_type,
+ signing_time,
+ signing_certificate,
+ scheme,
+ scheme_digest,
+ signature,
+ timestamp,
+ timestamp_token,
+ })
+}
+
+fn parse_timestamp_token<'a>(it: impl Iterator<Item = Tlv<'a>>) -> Result<(bool, Option<Vec<u8>>), SignError> {
let mut timestamp = false;
let mut timestamp_token = None;
for t in it {
@@ -309,20 +327,7 @@ fn parse_signer(si: &Tlv<'_>) -> Result<SignerInfo, SignError> {
}
}
}
- Ok(SignerInfo {
- sid,
- digest,
- signed_attrs,
- message_digest,
- content_type,
- signing_time,
- signing_certificate,
- scheme,
- scheme_digest,
- signature,
- timestamp,
- timestamp_token,
- })
+ Ok((timestamp, timestamp_token))
}
/// Attach an RFC 3161 `signatureTimeStampToken` unsigned attribute to a detached CMS object.
diff --git a/crates/sign/src/dss.rs b/crates/sign/src/dss.rs
index e095ec7..0d82c79 100644
--- a/crates/sign/src/dss.rs
+++ b/crates/sign/src/dss.rs
@@ -93,7 +93,9 @@ pub fn embed(doc: &Document, evidence: &Evidence) -> Result<Vec<u8>, SignError>
}
let dss_ref = doc.add(Object::Dict(dss));
doc.update_dict(root, |c| c.set(b"DSS".to_vec(), Object::Ref(dss_ref)))?;
- Ok(pdfcraft_cos::write_incremental(&doc, &SaveOptions::default())?)
+ // What the user removed again before this (a cleared redaction mark) stays out of the file,
+ // as in a save; the store and everything in it are reachable from the catalog.
+ Ok(pdfcraft_cos::write_incremental(&doc, &SaveOptions { drop_unlinked: true, ..SaveOptions::default() })?)
}
/// Store one DER blob as a `/Type /Embed` stream.
diff --git a/crates/sign/src/pdf.rs b/crates/sign/src/pdf.rs
index f48e69c..1b1002d 100644
--- a/crates/sign/src/pdf.rs
+++ b/crates/sign/src/pdf.rs
@@ -590,7 +590,10 @@ pub fn list_cached(doc: &Document, bytes: &[u8], trust: &TrustStore, cache: &Dig
.and_then(|(_, w)| nums(doc, w, b"Rect"))
.filter(|r| r.len() == 4)
.map(|r| [r[0].min(r[2]), r[1].min(r[3]), r[0].max(r[2]), r[1].max(r[3])]);
- let visible = rect.is_some_and(|r| r[2] - r[0] > 0.5 && r[3] - r[1] > 0.5);
+ // Shown when it has a box, and its widget isn't Hidden (2) or NoView (32), as the forms
+ // crate reads a widget's flags.
+ let flags = widget.and_then(|(_, w)| w.get(b"F")).and_then(|o| doc.resolve(o).as_int()).unwrap_or(0);
+ let visible = rect.is_some_and(|r| r[2] - r[0] > 0.5 && r[3] - r[1] > 0.5) && flags & (2 | 32) == 0;
let v = f.signature(doc);
let mut info = SignatureInfo {
field: f.name.clone(),
@@ -672,6 +675,17 @@ fn page_index(doc: &Document, p: ObjRef) -> Option<usize> {
pdfcraft_annot::page_refs(doc).ok()?.iter().position(|r| *r == p)
}
+/// A widget's `/MK /R` as a quarter turn (0, 90, 180 or 270); missing, malformed or not a
+/// multiple of 90 counts as 0, as `pdfcraft-forms` reads it for the fields it draws.
+fn mk_rotation(doc: &Document, widget: &Dict) -> i64 {
+ let r = widget
+ .get(b"MK")
+ .map(|mk| doc.resolve(mk))
+ .and_then(|mk| mk.as_dict().and_then(|mk| mk.get(b"R")).map(|r| doc.resolve(r)))
+ .and_then(|r| r.as_int().or_else(|| r.as_f64().filter(|v| v.is_finite() && v.abs() <= 1.0e6).map(|v| v.round() as i64)));
+ r.map(|r| r.rem_euclid(360)).filter(|q| matches!(q, 90 | 180 | 270)).unwrap_or(0)
+}
+
/// Validate one signature dictionary.
pub fn validate(doc: &Document, bytes: &[u8], trust: &TrustStore, field: &str) -> Option<SignatureInfo> {
list(doc, bytes, trust).into_iter().find(|s| s.field == field)
@@ -1346,6 +1360,11 @@ fn classify_changes(doc: &Document, old: Option<Document>, p: Option<u8>) -> Mod
// attacker-written version carries (relabelling a signed page /Type /Sig, or dropping its
// /Type and adding /ModDate, must not reclassify it away from page content).
let signed_pages: HashSet<ObjRef> = pdfcraft_annot::page_refs(&old).unwrap_or_default().into_iter().collect();
+ // The signed pages' /Annots arrays that are objects of their own. Adding an annotation updates
+ // such an array in place (the page dictionary does not change), so it is judged like a
+ // page's inline /Annots: by the annotations it gained.
+ let signed_annots: HashSet<ObjRef> =
+ signed_pages.iter().filter_map(|pg| old.get(*pg).as_dict().and_then(|d| d.get(b"Annots").and_then(Object::as_ref))).collect();
// What each signed page draws from, by the role it held when signed (#1787).
let signed_resources = signed_page_resources(&old, &signed_pages);
let old_info = old.trailer().get(b"Info").and_then(Object::as_ref);
@@ -1414,6 +1433,24 @@ fn classify_changes(doc: &Document, old: Option<Document>, p: Option<u8>) -> Mod
(Some(k), _) => k,
// The Document Security Store's own arrays and dictionaries, when they only grew.
(_, _) if dss.contains(&num) => kind::SECURITY_STORE,
+ // A signed page's indirect /Annots array, still an array: what it lost, then what it
+ // gained. Dropping a signed annotation is never hidden behind an added signature.
+ (_, Object::Array(now)) if signed_annots.contains(&r) && before.as_deref().is_some_and(|b| b.as_array().is_some()) => {
+ let was: HashSet<ObjRef> =
+ before.as_deref().and_then(Object::as_array).map(|a| a.iter().filter_map(Object::as_ref).collect()).unwrap_or_default();
+ let kept: HashSet<ObjRef> = now.iter().filter_map(Object::as_ref).collect();
+ let removed: Vec<ObjRef> = was.iter().filter(|r| !kept.contains(r)).copied().collect();
+ if removed.is_empty() {
+ let added: Vec<ObjRef> = now.iter().filter_map(Object::as_ref).filter(|r| !was.contains(r)).collect();
+ added_annots(doc, &added)
+ } else if removed.iter().any(|r| old.get(*r).as_dict().is_some_and(|d| d.name(b"Subtype") == Some(b"Widget"))) {
+ // A form field or signature widget taken off the page: no permission covers it.
+ kind::OTHER
+ } else {
+ // Deleting comments is a comment change (permitted at P 3 only).
+ kind::COMMENTS
+ }
+ }
(_, Object::Dict(d)) => {
let was = before.as_deref().and_then(Object::as_dict);
if signed_pages.contains(&r) {
@@ -1467,6 +1504,23 @@ fn classify_changes(doc: &Document, old: Option<Document>, p: Option<u8>) -> Mod
list.push(what);
}
}
+ // An object the signed revision had and this one frees is a change too, and the loop above
+ // only sees objects that still exist. File plumbing (cross-reference and object streams) is
+ // rewritten by every save and is not a change.
+ let current: HashSet<u32> = doc.object_numbers().into_iter().collect();
+ for num in old.object_numbers().into_iter().filter(|n| !current.contains(n)) {
+ let r = ObjRef { num, generation: old.generation(num) };
+ let was = old.get(r);
+ let signed_role = old_content.contains(&r) || signed_pages.contains(&r) || signed_resources.contains_key(&r);
+ // A signed page's content or resource is judged by that role, whatever /Type its stream carried.
+ if !signed_role && matches!(&*was, Object::Stream(s) if matches!(s.dict.name(b"Type"), Some(b"XRef" | b"ObjStm"))) {
+ continue;
+ }
+ let what = if signed_role { kind::PAGE_CONTENT } else { kind::OTHER };
+ if !disallowed.contains(&what) {
+ disallowed.push(what);
+ }
+ }
if disallowed.is_empty() { Modification::Allowed(allowed) } else { Modification::Disallowed(disallowed) }
}
@@ -1766,18 +1820,43 @@ fn page_change_kind(doc: &Document, old: &Document, d: &Dict, before: Option<&Di
}
}
+/// Whether the catalog `d` keeps every developer extension the signed catalog `b` declared, each
+/// with the same value: it may only declare more.
+fn extensions_kept(doc: &Document, old: &Document, d: &Dict, b: &Dict) -> bool {
+ let now = d.get(b"Extensions").map(|e| doc.resolve(e)).and_then(|e| e.as_dict().cloned());
+ let was = b.get(b"Extensions").map(|e| old.resolve(e)).and_then(|e| e.as_dict().cloned());
+ match (was, now) {
+ (None, _) => true,
+ (Some(was), Some(now)) => was.iter().all(|(k, v)| now.get(k) == Some(v)),
+ (Some(_), None) => false,
+ }
+}
+
fn change_kind(doc: &Document, old: &Document, d: &Dict, before: Option<&Dict>) -> &'static str {
let ty = d.name(b"Type");
// A later revision cannot make an existing object a signature by relabelling it: a signature
// change is only a brand-new object, or one that was already a signature object when signed.
let signature_ok = before.is_none_or(is_signature_dict);
+ // A signature widget that already held a signature is what the signature shows: moving it or
+ // swapping its appearance can hide the signed page under it. Judged by the signed revision,
+ // so relabelling the widget now does not change that.
+ if before.is_some_and(|b| {
+ b.name(b"Subtype") == Some(b"Widget") && b.name(b"FT") == Some(b"Sig") && b.get(b"V").is_some_and(|v| old.resolve(v).as_dict().is_some())
+ }) && before != Some(d)
+ {
+ return kind::PAGE_CONTENT;
+ }
match ty {
// Only a new signature value or policy: rewriting a signed one is not a signature (#1788).
Some(b"Sig" | b"DocTimeStamp" | b"SigRef" | b"TransformParams") if before.is_none() => return kind::SIGNATURE,
Some(b"Catalog") => {
- let keys: &[&[u8]] = &[b"AcroForm", b"DSS", b"Perms", b"Metadata", b"NeedsRendering"];
+ let keys: &[&[u8]] = &[b"AcroForm", b"DSS", b"Perms", b"Metadata", b"NeedsRendering", b"Extensions"];
return match before {
Some(b) if without(d, keys) != without(b, keys) => kind::STRUCTURE,
+ // Developer extensions (ISO 32000-2 §7.12) only declare what the file uses. A
+ // writer adding a /DSS also declares the ESIC extension it belongs to, so a
+ // declaration may be added, but none that was signed may change or go.
+ Some(b) if !extensions_kept(doc, old, d, b) => kind::STRUCTURE,
Some(b) => {
if d.get(b"AcroForm") != b.get(b"AcroForm") {
// Compare the forms themselves, inline or not.
@@ -2028,7 +2107,8 @@ fn sign_inner(
.field
.as_deref()
.map(|n| sig_fields(&doc).into_iter().find(|f| f.name == n).ok_or_else(|| SignError::Pdf(format!("there is no signature field {n:?}"))));
- let (widget, rect) = match existing {
+ // `turn`: how far the appearance is turned to read upright (`/MK /R`, counterclockwise).
+ let (widget, rect, turn) = match existing {
Some(f) => {
let f = f?;
if f.signature(&doc).is_some() {
@@ -2041,7 +2121,9 @@ fn sign_inner(
doc.update_dict(fr, |d| d.set(b"V".to_vec(), Object::Ref(sig)))?;
let (wr, wd) = f.widgets.first().cloned().ok_or_else(|| SignError::Pdf("the field has no widget".into()))?;
let rect = nums(&doc, &wd, b"Rect").filter(|r| r.len() == 4).map(|r| [r[0].min(r[2]), r[1].min(r[3]), r[0].max(r[2]), r[1].max(r[3])]);
- (wr.unwrap_or(fr), rect.unwrap_or([0.0; 4]))
+ // The field's own rotation, as a form author set it: an existing field is not
+ // reoriented, so one without `/MK /R` is drawn as before.
+ (wr.unwrap_or(fr), rect.unwrap_or([0.0; 4]), mk_rotation(&doc, &wd))
}
None => {
let page = *pages.get(opts.page).ok_or_else(|| SignError::Pdf(format!("page {} does not exist", opts.page + 1)))?;
@@ -2061,6 +2143,14 @@ fn sign_inner(
w.set(b"P".to_vec(), Object::Ref(page));
// Print + Locked.
w.set(b"F".to_vec(), Object::Int(4 | 128));
+ // On a page shown turned, the signature reads upright as the page is displayed: the
+ // widget is turned back by the page's rotation (ISO 32000-2 §12.5.6.19, `/MK /R`).
+ let turn = pdfcraft_model::pages(&doc).get(opts.page).map_or(0, |p| p.rotation(&doc));
+ if turn != 0 {
+ let mut mk = Dict::new();
+ mk.set(b"R".to_vec(), Object::Int(turn));
+ w.set(b"MK".to_vec(), Object::Dict(mk));
+ }
let wr = doc.add(Object::Dict(w));
// Page /Annots (indirect arrays are updated in place).
let pd = doc.get(page).as_dict().cloned().unwrap_or_default();
@@ -2096,7 +2186,7 @@ fn sign_inner(
// Inline (or new) AcroForms stay in the catalog.
None => doc.update_dict(root, |c| c.set(b"AcroForm".to_vec(), Object::Dict(af)))?,
}
- (wr, rect)
+ (wr, rect, turn)
}
};
if opts.field.is_some() {
@@ -2110,13 +2200,16 @@ fn sign_inner(
}
}
// The appearance.
- let ap = appearance(&mut doc, rect, &name, &id.certificate, opts)?;
+ let ap = appearance(&mut doc, rect, turn, &name, &id.certificate, opts)?;
let ap_ref = doc.add(Object::Stream(ap));
let mut apd = Dict::new();
apd.set(b"N".to_vec(), Object::Ref(ap_ref));
doc.update_dict(widget, |w| w.set(b"AP".to_vec(), Object::Dict(apd)))?;
- // Write with the placeholders, then patch them.
- let save = SaveOptions { mod_date: Some(opts.date.clone()), object_streams: false, ..SaveOptions::default() };
+ // Write with the placeholders, then patch them. What the user removed again before signing
+ // (a cleared redaction mark) stays out of the file, as in a save; what signing added is
+ // reachable (the signature through the field's `/V`), and the placeholders are found in the
+ // written bytes.
+ let save = SaveOptions { mod_date: Some(opts.date.clone()), object_streams: false, drop_unlinked: true, ..SaveOptions::default() };
let mut out = pdfcraft_cos::write_incremental(&doc, &save)?;
let (br_at, gap) = locate(&out, reserve)?;
let (start, end) = gap;
@@ -2165,6 +2258,10 @@ pub fn timestamp_document(doc: &Document, tsa: &dyn crate::timestamp::TimestampA
));
}
let mut doc = doc.clone();
+ // What the user removed again before this (a cleared redaction mark) stays out of the file,
+ // as in a save. Nothing refers to the timestamp either, so the leftovers go first and the
+ // save keeps everything.
+ doc.free_unlinked_additions();
let mut v = Dict::new();
v.set(b"Type".to_vec(), Object::name("DocTimeStamp"));
v.set(b"Filter".to_vec(), Object::name("Adobe.PPKLite"));
@@ -2238,9 +2335,15 @@ pub fn display_date(pdf: &str) -> String {
/// draw: signing invisibly, or leaving that part out, still works. A graphic doesn't change this:
/// the name it replaces on the left is still among the details. A label that is drawn
/// ([`AppearanceLabels`], the caller's words) must be drawable in Helvetica, and is refused otherwise.
-fn appearance(doc: &mut Document, rect: [f64; 4], name: &str, cert: &Certificate, opts: &SignOptions) -> Result<Stream, SignError> {
+///
+/// `turn` is the widget's `/MK /R` (0, 90, 180 or 270; anything else counts as 0): the layout is
+/// drawn upright in the box as turned by it, and a `/Matrix` maps that box onto `rect`.
+fn appearance(doc: &mut Document, rect: [f64; 4], turn: i64, name: &str, cert: &Certificate, opts: &SignOptions) -> Result<Stream, SignError> {
use pdfcraft_fonts::{first_undrawable, helvetica_width, inter_width, literal, undrawable_message, win_ansi, wrap, wrap_with};
- let (w, h) = ((rect[2] - rect[0]).max(0.0), (rect[3] - rect[1]).max(0.0));
+ let turn = if matches!(turn, 90 | 180 | 270) { turn } else { 0 };
+ let (rw, rh) = ((rect[2] - rect[0]).max(0.0), (rect[3] - rect[1]).max(0.0));
+ // The upright layout box: a quarter turn swaps its sides.
+ let (w, h) = if turn % 180 == 0 { (rw, rh) } else { (rh, rw) };
let a = &opts.appearance;
let dn = cert.subject.display();
let mut needs_unicode = false;
@@ -2386,6 +2489,16 @@ fn appearance(doc: &mut Document, rect: [f64; 4], name: &str, cert: &Certificate
d.set(b"Type".to_vec(), Object::name("XObject"));
d.set(b"Subtype".to_vec(), Object::name("Form"));
d.set(b"BBox".to_vec(), Object::Array([0.0, 0.0, w, h].iter().map(|x| Object::Real(*x)).collect()));
+ if turn != 0 {
+ // Viewers fit the box, transformed by `/Matrix`, to the widget's `/Rect` (ISO 32000-2
+ // §12.5.5); this one lands on `rect` exactly, turned as `/MK /R` says.
+ let mut m = pdfcraft_model::view_matrix_for(turn, [rect[0], rect[1], rect[0] + rw, rect[1] + rh]);
+ if !m.iter().all(|x| x.is_finite()) {
+ // A caller's non-finite corner: the turn alone, which viewers fit to `/Rect` the same.
+ m = pdfcraft_model::view_matrix_for(turn, [0.0; 4]);
+ }
+ d.set(b"Matrix".to_vec(), Object::Array(m.iter().map(|x| Object::Real(*x)).collect()));
+ }
let mut res = Dict::new();
res.set(b"Font".to_vec(), Object::Dict(fonts));
if let Some(im) = image {
diff --git a/crates/sign/tests/it/pdf.rs b/crates/sign/tests/it/pdf.rs
index b7de2a4..7234e78 100644
--- a/crates/sign/tests/it/pdf.rs
+++ b/crates/sign/tests/it/pdf.rs
@@ -2,7 +2,7 @@
use std::sync::Arc;
-use pdfcraft_cos::{Document, Object, PdfString, SaveOptions, write_incremental};
+use pdfcraft_cos::{Dict, Document, ObjRef, Object, PdfString, SaveOptions, write_incremental};
use pdfcraft_sign::{
Certificate, Detail, DigitalId, Modification, Name, SignError, SignOptions, Status, Time, TimestampAuthority, TrustStore, WORDINGS, der,
in_english, kind, pkcs12, signatures,
@@ -28,6 +28,11 @@ fn fixture_with(catalog: &[u8], more: &[&[u8]]) -> Vec<u8> {
b"<< /Type /Annot /Subtype /Widget /FT /Sig /T (Approval) /Rect [150 20 280 70] /P 3 0 R /F 4 >>",
];
objs.extend_from_slice(more);
+ write_pdf(&objs)
+}
+
+/// A classic-xref PDF of `objs`, numbered from 1, with object 1 as the catalog.
+fn write_pdf(objs: &[&[u8]]) -> Vec<u8> {
let mut out = b"%PDF-1.7\n".to_vec();
let mut offsets = Vec::new();
for (i, o) in objs.iter().enumerate() {
@@ -139,6 +144,71 @@ fn signing_an_existing_field_and_counter_signing() {
));
}
+/// A page whose /Annots is an object of its own: signing and commenting update that array in
+/// place, not the page. A second signature is a signature change for the first, as with an
+/// inline /Annots, and a comment is still a comment (refused under a form-fill certification).
+#[test]
+fn an_indirect_annots_array_is_judged_by_the_annotations_it_gains() {
+ let page = pdfcraft_cos::ObjRef { num: 3, generation: 0 };
+ let unsigned = edit_after(&fixture(), |doc| {
+ let annots = doc.add(Object::Array(vec![Object::Ref(pdfcraft_cos::ObjRef { num: 6, generation: 0 })]));
+ doc.update_dict(page, |p| p.set(b"Annots".to_vec(), Object::Ref(annots))).unwrap();
+ });
+ let annots_ref = |bytes: &[u8]| open(bytes).get(page).as_dict().and_then(|d| d.get(b"Annots").and_then(Object::as_ref));
+ let annots = annots_ref(&unsigned).unwrap();
+ let id = pkcs12::open(&data("rsa-aes.p12"), "test").unwrap();
+ let trust = TrustStore { certs: vec![id.certificate.clone()] };
+ let first = pdfcraft_sign::sign(&open(&unsigned), &id, &opts()).unwrap();
+ let second = pdfcraft_sign::sign(&open(&first), &id, &SignOptions { rect: Some([20.0, 160.0, 220.0, 210.0]), ..opts() }).unwrap();
+ assert_eq!(annots_ref(&second), Some(annots), "the signer kept the page's array indirect");
+ let doc = open(&second);
+ let sigs = signatures(&doc, &second, &trust);
+ let s = sigs.iter().find(|s| s.field == "Signature1").unwrap();
+ assert_eq!(s.modification, Modification::Allowed(vec![kind::SIGNATURE]), "{:?}", s.details);
+ assert_eq!(s.status, Status::Valid);
+ // A comment appended to the indirect array.
+ let comment = |doc: &mut Document| {
+ let mut d = pdfcraft_cos::Dict::new();
+ d.set(b"Type".to_vec(), Object::name("Annot"));
+ d.set(b"Subtype".to_vec(), Object::name("Text"));
+ d.set(b"Rect".to_vec(), Object::Array(vec![Object::Int(10), Object::Int(10), Object::Int(30), Object::Int(30)]));
+ let r = doc.add(Object::Dict(d));
+ let mut a = doc.get(annots).as_array().cloned().unwrap();
+ a.push(Object::Ref(r));
+ doc.set(annots, Object::Array(a));
+ };
+ let check = |bytes: &[u8]| signatures(&open(bytes), bytes, &trust).into_iter().find(|s| s.signed).unwrap();
+ let s = check(&edit_after(&first, comment));
+ assert_eq!((s.status, s.modification), (Status::Valid, Modification::Allowed(vec![kind::COMMENTS])));
+ let certified = pdfcraft_sign::sign(&open(&unsigned), &id, &SignOptions { certify: Some(2), ..opts() }).unwrap();
+ let s = check(&edit_after(&certified, comment));
+ assert_eq!((s.status, s.modification), (Status::Invalid, Modification::Disallowed(vec![kind::COMMENTS])));
+ // Under that certification, a signed comment swapped for a new signature widget is still a
+ // deleted comment, and a form field taken off the page is permitted by no level.
+ let commented = pdfcraft_sign::sign(&open(&edit_after(&unsigned, comment)), &id, &SignOptions { certify: Some(2), ..opts() }).unwrap();
+ let swap = |drop: &dyn Fn(&Document, &Object) -> bool| {
+ edit_after(&commented, |doc| {
+ let mut w = pdfcraft_cos::Dict::new();
+ w.set(b"Type".to_vec(), Object::name("Annot"));
+ w.set(b"Subtype".to_vec(), Object::name("Widget"));
+ w.set(b"FT".to_vec(), Object::name("Sig"));
+ w.set(b"T".to_vec(), PdfString::text("Later"));
+ w.set(b"Rect".to_vec(), Object::Array(vec![Object::Int(0); 4]));
+ let w = doc.add(Object::Dict(w));
+ let mut a = doc.get(annots).as_array().cloned().unwrap();
+ a.retain(|o| !drop(doc, o));
+ a.push(Object::Ref(w));
+ doc.set(annots, Object::Array(a));
+ })
+ };
+ let subtype =
+ |doc: &Document, o: &Object, t: &[u8]| o.as_ref().is_some_and(|r| doc.get(r).as_dict().is_some_and(|d| d.name(b"Subtype") == Some(t)));
+ let s = check(&swap(&|doc, o| subtype(doc, o, b"Text")));
+ assert_eq!((s.status, s.modification), (Status::Invalid, Modification::Disallowed(vec![kind::COMMENTS])));
+ let s = check(&swap(&|doc, o| subtype(doc, o, b"Widget") && o.as_ref().is_some_and(|r| r.num == 6)));
+ assert_eq!((s.status, s.modification), (Status::Invalid, Modification::Disallowed(vec![kind::OTHER])));
+}
+
/// Issue #1328: a signature field whose /V is null, directly or through a reference, is unsigned:
/// it is listed as unsigned and can be signed by name.
#[test]
@@ -163,6 +233,24 @@ fn a_field_with_a_null_value_is_unsigned_and_can_be_signed() {
}
}
+/// A signature field whose widget is hidden (annotation flag Hidden, 2) or not shown on screen
+/// (NoView, 32) is listed as not visible, whatever its rectangle, as form widgets are: a form's
+/// requestor box with flags 96 (NoView and ReadOnly) has no box on the page to show. A widget
+/// that is only printable (4) stays visible.
+#[test]
+fn a_hidden_signature_field_is_listed_as_not_visible() {
+ let field = pdfcraft_cos::ObjRef { num: 6, generation: 0 };
+ let visible_with = |flags: i64| {
+ let bytes = edit_after(&fixture(), |doc| doc.update_dict(field, |d| d.set(b"F".to_vec(), Object::Int(flags))).unwrap());
+ let listed = signatures(&open(&bytes), &bytes, &TrustStore::default());
+ listed.iter().find(|s| s.field == "Approval").map(|s| s.visible).expect("listed")
+ };
+ assert!(visible_with(4), "printable only: shown");
+ for flags in [2, 32, 96, 34] {
+ assert!(!visible_with(flags), "flags {flags}: not shown");
+ }
+}
+
/// Follow-up to #1374: a signature field whose /V is neither null nor a signature dictionary is
/// refused by name with an error saying so, instead of being overwritten or called signed.
#[test]
@@ -347,6 +435,105 @@ fn visible_signatures_show_a_drawn_typed_or_image_graphic() {
assert!(!invisible.windows(6).any(|w| w == b"/Image"));
}
+/// [`fixture`]'s page and "Approval" widget with extra entries: `page` (a `/Rotate`, say) and
+/// `widget` (an `/MK`); `pages` goes on the page tree node, where `/Rotate` is inheritable.
+fn rotated_fixture(pages: &str, page: &str, widget: &str) -> Vec<u8> {
+ let pages = format!("<< /Type /Pages /Kids [3 0 R] /Count 1 {pages} >>");
+ let page = format!(
+ "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 300] /Contents 4 0 R /Resources << /Font << /F1 5 0 R >> >> /Annots [6 0 R] {page} >>"
+ );
+ let widget = format!("<< /Type /Annot /Subtype /Widget /FT /Sig /T (Approval) /Rect [150 20 280 70] /P 3 0 R /F 4 {widget} >>");
+ write_pdf(&[
+ b"<< /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [6 0 R] >> >>",
+ pages.as_bytes(),
+ page.as_bytes(),
+ b"<< /Length 44 >>\nstream\nBT /F1 14 Tf 20 250 Td (Contract text) Tj ET\nendstream",
+ b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>",
+ widget.as_bytes(),
+ ])
+}
+
+/// The signature field `name`'s widget and its normal appearance's dictionary and content.
+fn widget_and_appearance(bytes: &[u8], name: &str) -> (pdfcraft_cos::Dict, pdfcraft_cos::Dict, String) {
+ let doc = open(bytes);
+ let catalog = doc.get(doc.root().unwrap()).as_dict().cloned().unwrap();
+ let form = doc.resolve(catalog.get(b"AcroForm").unwrap()).as_dict().cloned().unwrap();
+ let fields = doc.resolve(form.get(b"Fields").unwrap()).as_array().cloned().unwrap();
+ let widget = fields
+ .iter()
+ .filter_map(|f| doc.resolve(f).as_dict().cloned())
+ .find(|f| matches!(f.get(b"T"), Some(Object::String(s)) if s.bytes == name.as_bytes()))
+ .unwrap();
+ let ap = doc.resolve(widget.get(b"AP").unwrap()).as_dict().cloned().unwrap();
+ let Object::Stream(s) = &*doc.resolve(ap.get(b"N").unwrap()) else { panic!("no normal appearance") };
+ (widget.clone(), s.dict.clone(), String::from_utf8_lossy(&s.decoded().unwrap()).into_owned())
+}
+
+fn numbers(d: &pdfcraft_cos::Dict, key: &[u8]) -> Option<Vec<f64>> {
+ d.get(key).and_then(|o| o.as_array()).map(|a| a.iter().filter_map(|n| n.as_f64()).collect())
+}
+
+/// On a page shown turned, a visible signature reads upright as displayed: its appearance is the
+/// one an unturned page gets in the box with the displayed proportions, turned back onto the
+/// widget by `/MK /R` and the matching `/Matrix`.
+#[test]
+fn visible_signatures_read_upright_on_rotated_pages() {
+ use pdfcraft_sign::Appearance;
+ let id = pkcs12::open(&data("rsa-aes.p12"), "test").unwrap();
+ // 200 x 50 in user space: shown 50 wide and 200 tall on a page turned a quarter.
+ let rect = [20.0, 100.0, 220.0, 150.0];
+ let swapped = [20.0, 100.0, 70.0, 300.0];
+ let shown = Appearance { reason: true, location: true, ..Appearance::default() };
+ let sign = |bytes: &[u8], rect: [f64; 4]| {
+ let o = SignOptions { rect: Some(rect), graphic: Some(picture(false)), appearance: shown.clone(), ..opts() };
+ pdfcraft_sign::sign(&open(bytes), &id, &o).unwrap()
+ };
+ let upright = |rect: [f64; 4]| widget_and_appearance(&sign(&fixture(), rect), "Signature1");
+ for (pages, page, turn) in [
+ ("", "", 0),
+ ("", "/Rotate 90", 90),
+ ("", "/Rotate 180", 180),
+ ("", "/Rotate 270", 270),
+ ("", "/Rotate -90", 270),
+ // Inherited from the page tree.
+ ("/Rotate 270", "", 270),
+ // Not a quarter turn: drawn as unturned, as the page is.
+ ("", "/Rotate 45", 0),
+ ] {
+ let doc = rotated_fixture(pages, page, "");
+ let signed = sign(&doc, rect);
+ let s = signatures(&open(&signed), &signed, &TrustStore::default()).into_iter().find(|s| s.signed).unwrap();
+ assert_eq!((s.status, s.modification), (Status::Unknown, Modification::None), "{pages} {page}: {:?}", s.details);
+ let (widget, form, content) = widget_and_appearance(&signed, "Signature1");
+ let (_, expected_form, expected) = upright(if turn % 180 == 0 { rect } else { swapped });
+ assert_eq!(content, expected, "{pages} {page}: the layout is the upright box's");
+ assert_eq!(numbers(&form, b"BBox"), numbers(&expected_form, b"BBox"), "{pages} {page}");
+ let mk = widget.get(b"MK").and_then(|m| m.as_dict()).and_then(|m| m.int(b"R"));
+ let matrix = numbers(&form, b"Matrix");
+ if turn == 0 {
+ assert_eq!((mk, matrix), (None, None), "{pages} {page}: an unturned page's signature is unchanged");
+ } else {
+ assert_eq!(mk, Some(turn), "{pages} {page}");
+ assert_eq!(matrix, Some(pdfcraft_model::view_matrix_for(turn, rect).to_vec()), "{pages} {page}");
+ }
+ }
+ // An existing field keeps its own orientation: `/MK /R` turns it, whatever the page does.
+ let field = |bytes: &[u8]| {
+ let o = SignOptions { field: Some("Approval".into()), graphic: Some(picture(false)), appearance: shown.clone(), ..opts() };
+ widget_and_appearance(&pdfcraft_sign::sign(&open(bytes), &id, &o).unwrap(), "Approval")
+ };
+ let field_rect = [150.0, 20.0, 280.0, 70.0];
+ let (_, plain, plain_content) = field(&rotated_fixture("", "/Rotate 90", ""));
+ assert_eq!((numbers(&plain, b"Matrix"), numbers(&plain, b"BBox")), (None, Some(vec![0.0, 0.0, 130.0, 50.0])));
+ let (_, turned, turned_content) = field(&rotated_fixture("", "/Rotate 90", "/MK << /R 90 >>"));
+ assert_eq!(numbers(&turned, b"BBox"), Some(vec![0.0, 0.0, 50.0, 130.0]));
+ assert_eq!(numbers(&turned, b"Matrix"), Some(pdfcraft_model::view_matrix_for(90, field_rect).to_vec()));
+ assert_ne!(turned_content, plain_content);
+ // A malformed `/MK /R` counts as 0.
+ let (_, odd, _) = field(&rotated_fixture("", "", "/MK << /R (ninety) >>"));
+ assert_eq!(numbers(&odd, b"Matrix"), None);
+}
+
#[test]
fn malformed_signature_graphics_are_refused_not_drawn() {
use pdfcraft_sign::Graphic;
@@ -544,6 +731,35 @@ fn cached_discovery_still_validates_current_timestamp_bytes_ranges_and_trust() {
assert_eq!(check(&doc, &tampered, &trusted).status, Status::Invalid);
}
+#[test]
+fn ltv_writers_may_declare_the_esic_extension_but_not_change_a_signed_one() {
+ let id = pkcs12::open(&data("rsa-aes.p12"), "test").unwrap();
+ let trust = TrustStore { certs: vec![id.certificate.clone()] };
+ let check = |bytes: &[u8]| signatures(&open(bytes), bytes, &trust).into_iter().find(|s| s.signed).unwrap();
+ let ext = |base: &[u8], level: i64| {
+ let mut esic = pdfcraft_cos::Dict::new();
+ esic.set(b"BaseVersion".to_vec(), Object::name("1.7"));
+ esic.set(b"ExtensionLevel".to_vec(), Object::Int(level));
+ let mut e = pdfcraft_cos::Dict::new();
+ e.set(b"ESIC".to_vec(), Object::Dict(esic));
+ edit_after(base, |doc| {
+ let root = doc.root().unwrap();
+ doc.update_dict(root, |c| c.set(b"Extensions".to_vec(), Object::Dict(e))).unwrap();
+ })
+ };
+ // As PAdES LTV writers save it: the store and the ESIC declaration in one revision.
+ let signed = pdfcraft_sign::sign(&open(&fixture()), &id, &opts()).unwrap();
+ let evidence = pdfcraft_sign::dss::Evidence { certs: vec![id.certificate.raw.clone()], ocsps: Vec::new(), crls: Vec::new() };
+ let ltv = pdfcraft_sign::dss::embed(&open(&ext(&signed, 2)), &evidence).unwrap();
+ let s = check(&ltv);
+ assert_eq!(s.status, Status::Valid, "{:?}", s.details);
+ assert!(matches!(&s.modification, Modification::Allowed(k) if !k.contains(&kind::STRUCTURE)), "{:?}", s.modification);
+ // A declaration that was signed may not change afterwards.
+ let signed_with = pdfcraft_sign::sign(&open(&ext(&fixture(), 2)), &id, &opts()).unwrap();
+ let s = check(&ext(&signed_with, 3));
+ assert_eq!((s.status, s.modification), (Status::Invalid, Modification::Disallowed(vec![kind::STRUCTURE])));
+}
+
#[test]
fn embedding_ltv_evidence_adds_a_dss_and_keeps_signatures_valid() {
use pdfcraft_sign::dss::{self, Evidence};
@@ -599,6 +815,71 @@ fn sign_then_ltv_then_timestamp_makes_a_b_lta_file() {
assert_eq!(stamp.status, Status::Valid, "{:?}", stamp.details);
}
+/// A redaction mark and a reply to it, added to the page and removed again before signing (what
+/// clearing a mark leaves behind), are in none of the signing outputs: a signature, a timestamped
+/// one, embedded revocation evidence or a document timestamp. Nothing can take them out of a
+/// signed revision afterwards. Each output still validates.
+#[test]
+fn what_was_removed_before_signing_is_not_signed() {
+ use pdfcraft_sign::dss::{self, Evidence};
+ let id = pkcs12::open(&data("ec-p256.p12"), "test").unwrap();
+ let tsa = TestTsa { id: tsa_id(), time: Time { year: 2026, month: 10, day: 6, hour: 12, minute: 0, second: 0 } };
+ let anchor = id.chain.first().cloned().unwrap_or_else(|| id.certificate.clone());
+ let trust = TrustStore { certs: vec![anchor, tsa.id.certificate.clone()] };
+ let text = |s: &str| Object::String(PdfString::literal(s.as_bytes().to_vec()));
+ let dict = |entries: &[(&str, Object)]| {
+ let mut d = Dict::new();
+ entries.iter().for_each(|(k, v)| d.set(k.as_bytes().to_vec(), v.clone()));
+ Object::Dict(d)
+ };
+ let cleared = |bytes: &[u8]| {
+ let mut doc = open(bytes);
+ let page = ObjRef::new(3, 0);
+ let annots = doc.get(page).as_dict().and_then(|d| d.get(b"Annots").cloned()).unwrap();
+ let mark = doc.add(dict(&[
+ ("Type", Object::name("Annot")),
+ ("Subtype", Object::name("Redact")),
+ ("Rect", Object::Array([80, 140, 100, 180].map(Object::Int).to_vec())),
+ ("OverlayText", text("MARKED OVERLAY")),
+ ("T", text("Mark Author")),
+ ("P", Object::Ref(page)),
+ ]));
+ let reply = doc.add(dict(&[
+ ("Type", Object::name("Annot")),
+ ("Subtype", Object::name("Text")),
+ ("IRT", Object::Ref(mark)),
+ ("Contents", text("REPLY TO THE MARK")),
+ ("T", text("Replier")),
+ ]));
+ let mut with = annots.as_array().cloned().unwrap();
+ with.extend([Object::Ref(mark), Object::Ref(reply)]);
+ doc.update_dict(page, |d| d.set(b"Annots".to_vec(), Object::Array(with))).unwrap();
+ doc.update_dict(page, |d| d.set(b"Annots".to_vec(), annots.clone())).unwrap();
+ doc
+ };
+ let unsigned = fixture();
+ let signed = pdfcraft_sign::sign(&open(&unsigned), &id, &opts()).unwrap();
+ let evidence = Evidence { certs: vec![id.certificate.raw.clone()], ocsps: Vec::new(), crls: Vec::new() };
+ let outputs = [
+ ("sign", &unsigned, pdfcraft_sign::sign(&cleared(&unsigned), &id, &opts()).unwrap()),
+ ("sign_with_timestamp", &unsigned, pdfcraft_sign::sign_with_timestamp(&cleared(&unsigned), &id, &opts(), &tsa).unwrap()),
+ ("dss::embed", &signed, dss::embed(&cleared(&signed), &evidence).unwrap()),
+ ("timestamp_document", &unsigned, pdfcraft_sign::timestamp_document(&cleared(&unsigned), &tsa, "D:20261006120000Z").unwrap()),
+ ];
+ for (what, input, out) in outputs {
+ assert!(out.starts_with(input), "{what}: an incremental update");
+ let holds = |s: &str| out.windows(s.len()).any(|w| w == s.as_bytes());
+ for trace in ["/Redact", "MARKED OVERLAY", "Mark Author", "REPLY TO THE MARK", "Replier"] {
+ assert!(!holds(trace), "{what} wrote {trace:?}");
+ }
+ let doc = open(&out);
+ assert!(doc.repair_log().is_empty(), "{what}: {:?}", doc.repair_log());
+ let all: Vec<_> = signatures(&doc, &out, &trust).into_iter().filter(|s| s.signed).collect();
+ assert_eq!(all.iter().filter(|s| s.doc_timestamp).count(), usize::from(what == "timestamp_document"), "{what}");
+ assert!(!all.is_empty() && all.iter().all(|s| s.status == Status::Valid), "{what}: {all:?}");
+ }
+}
+
#[test]
fn an_embedded_verified_revocation_invalidates_the_signature() {
use pdfcraft_sign::dss::{self, Evidence};
@@ -665,12 +946,20 @@ trailer << /Root 1 0 R >>
}
}
+/// Held by every test that changes the user's keychain search list. Each saves the list, changes
+/// it and restores what it saved, so two at once could undo each other's temporary keychain or
+/// put back one already deleted.
+#[cfg(target_os = "macos")]
+static KEYCHAIN_SEARCH_LIST: std::sync::Mutex<()> = std::sync::Mutex::new(());
+
/// Signing with Keychain identities, in a throwaway keychain file. Ignored by default: creating
/// a keychain touches the user's keychain search list (restored afterwards).
#[cfg(target_os = "macos")]
#[test]
#[ignore = "creates a temporary macOS keychain; run with --ignored"]
fn signing_with_keychain_identities() {
+ // A test that failed while holding it leaves the list restored, so a poisoned lock is fine.
+ let _list = KEYCHAIN_SEARCH_LIST.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
use std::process::Command;
let dir = std::env::temp_dir().join(format!("pdfcraft-keychain-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
@@ -683,7 +972,7 @@ fn signing_with_keychain_identities() {
let restore = || {
let mut args = vec!["list-keychains", "-d", "user", "-s"];
args.extend(saved.iter().map(String::as_str));
- sec(&args);
+ sec(&args)
};
restore();
// Everything that can fail runs before the clean-up below.
@@ -705,9 +994,11 @@ fn signing_with_keychain_identities() {
assert_eq!(s.status, Status::Valid, "{:?}", s.details);
}
}));
+ // The list first: it is what outlives the test if deleting the keychain goes wrong.
+ let restored = restore();
sec(&["delete-keychain", k]);
- restore();
let _ = std::fs::remove_dir_all(&dir);
+ assert!(restored.status.success(), "the keychain search list wasn't restored: {}", String::from_utf8_lossy(&restored.stderr));
result.unwrap();
}
@@ -718,20 +1009,28 @@ fn signing_with_keychain_identities() {
#[test]
#[ignore = "creates a temporary macOS keychain; run with --ignored"]
fn keychain_identities_carry_their_issuers() {
+ // A test that failed while holding it leaves the list restored, so a poisoned lock is fine.
+ let _list = KEYCHAIN_SEARCH_LIST.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
use std::process::Command;
- let dir = std::env::temp_dir().join(format!("pdfcraft-keychain-chain-{}", std::process::id()));
- std::fs::create_dir_all(&dir).unwrap();
+ // The same path every run: trustd remembers which keychain file it found an issuer in, and
+ // after a run's keychain is deleted it keeps looking there, so a keychain at a new path
+ // would get an empty chain until that memory expires.
+ let dir = std::env::temp_dir().join("pdfcraft-keychain-chain");
let kc = dir.join("test.keychain-db");
let sec = |args: &[&str]| Command::new("security").args(args).output().unwrap();
+ let k = kc.to_str().unwrap();
+ // Left over by a run that was killed before its clean-up.
+ sec(&["delete-keychain", k]);
+ let _ = std::fs::remove_dir_all(&dir);
+ std::fs::create_dir_all(&dir).unwrap();
let list = String::from_utf8(sec(&["list-keychains", "-d", "user"]).stdout).unwrap();
let saved: Vec<String> = list.lines().map(|l| l.trim().trim_matches('"').to_string()).filter(|l| !l.is_empty()).collect();
- let k = kc.to_str().unwrap();
assert!(sec(&["create-keychain", "-p", "pc-test", k]).status.success());
let set_list = |extra: Option<&str>| {
let mut args = vec!["list-keychains", "-d", "user", "-s"];
args.extend(saved.iter().map(String::as_str));
args.extend(extra);
- sec(&args);
+ sec(&args)
};
// macOS finds an identity's issuers in the keychains on the search list.
set_list(Some(k));
@@ -742,15 +1041,29 @@ fn keychain_identities_carry_their_issuers() {
assert!(out.status.success(), "chain-legacy.p12: {}", String::from_utf8_lossy(&out.stderr));
let listed = pdfcraft_sign::keychain::identities(Some(&kc)).unwrap();
assert_eq!(listed.len(), 1, "{listed:?}");
- let id = pdfcraft_sign::keychain::find(&pdfcraft_sign::keychain::reference(&listed[0].certificate)).unwrap();
+ // The Security framework caches the search list in-process and learns of `security
+ // list-keychains` asynchronously, so after another Keychain test it takes a moment to look
+ // in the new keychain.
+ let reference = pdfcraft_sign::keychain::reference(&listed[0].certificate);
+ let mut found = pdfcraft_sign::keychain::find(&reference);
+ for _ in 0..50 {
+ if found.is_ok() {
+ break;
+ }
+ std::thread::sleep(std::time::Duration::from_millis(100));
+ found = pdfcraft_sign::keychain::find(&reference);
+ }
+ let id = found.unwrap();
let issuers: Vec<_> = id.chain.iter().map(|c| c.subject.common_name()).collect();
assert_eq!(issuers, [Some("PrintCraft Test Root CA")]);
let file = pkcs12::open(&data("chain.p12"), "test").unwrap();
assert_eq!(id.chain.iter().map(|c| &c.raw).collect::<Vec<_>>(), file.chain.iter().map(|c| &c.raw).collect::<Vec<_>>());
}));
+ // The list first: it is what outlives the test if deleting the keychain goes wrong.
+ let restored = set_list(None);
sec(&["delete-keychain", k]);
- set_list(None);
let _ = std::fs::remove_dir_all(&dir);
+ assert!(restored.status.success(), "the keychain search list wasn't restored: {}", String::from_utf8_lossy(&restored.stderr));
result.unwrap();
}
@@ -2576,3 +2889,45 @@ fn a_timestamp_from_a_certificate_not_issued_for_time_stamping_is_not_trusted_ti
assert_eq!(s.timestamp_time, None, "{:?}", s.details);
assert!(s.details.iter().any(|d| d.message.contains("not issued for time stamping")), "{:?}", s.details);
}
+
+/// A signed revision's objects can't be freed or its signature widget rewritten without the
+/// change being seen: the classifier used to look only at objects still present, and let a
+/// signature widget's geometry and appearance change count as a signature.
+#[test]
+fn freeing_a_signed_object_or_rewriting_the_signed_widget_is_a_page_content_change() {
+ let id = pkcs12::open(&data("rsa-aes.p12"), "test").unwrap();
+ let trust = TrustStore { certs: vec![id.certificate.clone()] };
+ let check = |bytes: &[u8]| signatures(&open(bytes), bytes, &trust).into_iter().find(|s| s.signed).unwrap();
+ let signed = pdfcraft_sign::sign(&open(&fixture()), &id, &opts()).unwrap();
+ let freed = check(&edit_after(&signed, |doc| doc.free(pdfcraft_cos::ObjRef { num: 5, generation: 0 })));
+ assert_eq!(freed.status, Status::Invalid, "{:?}", freed.modification);
+ assert!(matches!(&freed.modification, Modification::Disallowed(k) if k.contains(&kind::PAGE_CONTENT)), "{:?}", freed.modification);
+ let widget = open(&signed)
+ .object_numbers()
+ .into_iter()
+ .map(|num| pdfcraft_cos::ObjRef { num, generation: 0 })
+ .find(|r| open(&signed).get(*r).as_dict().is_some_and(|d| d.name(b"Subtype") == Some(b"Widget") && d.contains(b"V")))
+ .unwrap();
+ let moved = check(&edit_after(&signed, |doc| {
+ doc.update_dict(widget, |d| d.set(b"Rect".to_vec(), Object::Array(vec![Object::Int(0), Object::Int(0), Object::Int(300), Object::Int(300)])))
+ .unwrap();
+ }));
+ assert_eq!(moved.status, Status::Invalid, "{:?}", moved.modification);
+ assert!(matches!(&moved.modification, Modification::Disallowed(k) if k.contains(&kind::PAGE_CONTENT)), "{:?}", moved.modification);
+}
+
+/// An existing signature field whose `/V` is null is unsigned: signing it rewrites its widget,
+/// and that is a signature, not a change to what an earlier signature shows.
+#[test]
+fn signing_a_field_with_a_null_value_after_another_signature_keeps_the_first_valid() {
+ let id = pkcs12::open(&data("rsa-aes.p12"), "test").unwrap();
+ let trust = TrustStore { certs: vec![id.certificate.clone()] };
+ let first = pdfcraft_sign::sign(&open(&fixture()), &id, &opts()).unwrap();
+ let second = pdfcraft_sign::sign(&open(&first), &id, &SignOptions { field: Some("Approval".into()), ..opts() }).unwrap();
+ let all = signatures(&open(&second), &second, &trust);
+ assert!(
+ all.iter().filter(|s| s.signed).all(|s| s.status == Status::Valid),
+ "{:?}",
+ all.iter().map(|s| (&s.status, &s.modification)).collect::<Vec<_>>()
+ );
+}
diff --git a/crates/xfa/README.md b/crates/xfa/README.md
index 7616625..23a6ef0 100644
--- a/crates/xfa/README.md
+++ b/crates/xfa/README.md
@@ -70,6 +70,10 @@ be measured exponentially often in their nesting. A measurement budget backs thi
field changes, and click for buttons. Every generated copy of a page-master button resolves
its own PDF field to the shared XFA click script, so clicking an early copy works as well
as the last, including through `js_run` and after save/reopen.
+ While this XFA layout is active, the engine does not
+ initialize Acrobat JavaScript with the PDF container's document-level scripts (including
+ non-XFA-viewer warnings). They stay available for inspection and saving; explicit console
+ scripts and XFA messages still run. Static XFA keeps its document scripts.
Private keys PdfCraft writes (other viewers ignore them):
diff --git a/crates/xfa/src/data.rs b/crates/xfa/src/data.rs
index 2b80d8b..eac2f20 100644
--- a/crates/xfa/src/data.rs
+++ b/crates/xfa/src/data.rs
@@ -12,7 +12,7 @@ use std::collections::HashMap;
use pdfcraft_cos::{Dict, Document, ObjRef, Object, PdfString, Stream};
use crate::XfaError;
-use crate::model::{Field, Node, SomIndices, Template};
+use crate::model::{Field, Node, SomIndices, Template, Ui};
use crate::packets::{Encoding, encode};
const XFA_DATA_NS: &str = "http://www.xfa.org/schema/xfa-data/1.0/";
@@ -441,11 +441,8 @@ pub fn pattern_to_iso(text: &str, pattern: &str) -> Option<String> {
"yyyy" | "yy" | "mm" | "m" | "dd" | "d" => {
// Digits up to the next literal (or a fixed width).
let fixed = matches!(t.as_str(), "yyyy" | "yy" | "mm" | "dd");
- let width = if fixed {
- t.len()
- } else {
- rest.chars().take_while(|c| c.is_ascii_digit()).count().min(if t == "d" || t == "m" { 2 } else { 4 })
- };
+ let width =
+ if fixed { t.len() } else { rest.chars().take_while(char::is_ascii_digit).count().min(if t == "d" || t == "m" { 2 } else { 4 }) };
let digits: String = rest.chars().take(width).collect();
if digits.is_empty() || !digits.chars().all(|c| c.is_ascii_digit()) {
return None;
@@ -1633,11 +1630,11 @@ pub fn write_data_ops(doc: &mut Document, ops: &[DataOp], reuse: Option<ObjRef>)
}
/// Put `bytes` in the document as a datasets stream: in place of `old` when that is the stream
-/// `reuse`, else as a new object.
+/// `reuse` or already an unsaved overlay stream of `doc`, else as a new object.
fn put_stream(doc: &mut Document, old: Option<&Object>, reuse: Option<ObjRef>, bytes: &[u8]) -> ObjRef {
let stream = Object::Stream(Stream::flate(Dict::new(), bytes));
- match (old.and_then(Object::as_ref), reuse) {
- (Some(r), Some(keep)) if r == keep => {
+ match old.and_then(Object::as_ref) {
+ Some(r) if reuse == Some(r) || doc.is_edited(r.num) => {
doc.set(r, stream);
r
}
@@ -1797,3 +1794,210 @@ pub fn is_on(text: &str, on: &str) -> bool {
}
!matches!(t.to_ascii_lowercase().as_str(), "" | "0" | "off" | "false" | "no") && on.trim().is_empty()
}
+
+/// The datasets stream's object reference in `doc` (the `datasets` item in the `/XFA` array, or
+/// the single `/XFA` stream), when `doc` has one.
+fn datasets_stream_ref(doc: &Document) -> Option<ObjRef> {
+ let root = doc.root()?;
+ let catalog = doc.get(root);
+ let acro = catalog.as_dict()?.get(b"AcroForm").map(|a| doc.resolve(a))?;
+ let xfa = acro.as_dict()?.get(b"XFA")?;
+ match &*doc.resolve(xfa) {
+ Object::Array(items) => {
+ let at = (0..items.len())
+ .step_by(2)
+ .find(|&i| items.get(i).and_then(|n| n.as_string()).is_some_and(|s| s.to_text() == "datasets") && i + 1 < items.len())?;
+ items.get(at + 1)?.as_ref()
+ }
+ Object::Stream(_) => xfa.as_ref(),
+ _ => None,
+ }
+}
+
+/// The SOM path and default value of every AcroForm text field with the Password flag (bit 14,
+/// `1 << 13`) in `doc`, for static XFA forms whose password fields set the flag in the AcroForm
+/// dictionary.
+fn acro_password_fields(doc: &Document) -> Vec<(String, String)> {
+ const PASSWORD_FLAG: i64 = 1 << 13;
+ let Some(root) = doc.root() else { return Vec::new() };
+ let catalog = doc.get(root);
+ let Some(acro) = catalog.as_dict().and_then(|c| c.get(b"AcroForm")).map(|a| doc.resolve(a)) else { return Vec::new() };
+ let Some(top) = acro.as_dict().and_then(|a| a.get(b"Fields")).map(|f| doc.resolve(f)).and_then(|f| f.as_array().cloned()) else {
+ return Vec::new();
+ };
+ struct AcroWalk<'a> {
+ doc: &'a Document,
+ seen: std::collections::HashSet<ObjRef>,
+ out: Vec<(String, String)>,
+ }
+ impl AcroWalk<'_> {
+ fn walk(
+ &mut self,
+ items: &[Object],
+ parent_name: &str,
+ inherited_ft: Option<&[u8]>,
+ inherited_ff: i64,
+ inherited_dv: Option<&str>,
+ depth: usize,
+ ) {
+ if depth > 32 {
+ return;
+ }
+ for item in items {
+ let Some(r) = item.as_ref() else { continue };
+ if !self.seen.insert(r) {
+ continue;
+ }
+ let obj = self.doc.get(r);
+ let Some(d) = obj.as_dict() else { continue };
+ let ft = d.name(b"FT").or(inherited_ft);
+ let ff = d.int(b"Ff").unwrap_or(inherited_ff);
+ let dv_own = text_of(self.doc, d, b"DV");
+ let dv = dv_own.as_deref().or(inherited_dv);
+ let t = text_of(self.doc, d, b"T");
+ let full_name = match (&t, parent_name.is_empty()) {
+ (Some(seg), true) => seg.clone(),
+ (Some(seg), false) => format!("{parent_name}.{seg}"),
+ (None, _) => parent_name.to_string(),
+ };
+ let kids = d.get(b"Kids").map(|k| self.doc.resolve(k)).and_then(|k| k.as_array().cloned()).unwrap_or_default();
+ let has_named_kid = kids.iter().filter_map(Object::as_ref).any(|kr| self.doc.get(kr).as_dict().is_some_and(|kd| kd.contains(b"T")));
+ if !has_named_kid && ft == Some(b"Tx") && (ff & PASSWORD_FLAG) != 0 {
+ let som = text_of(self.doc, d, crate::pdf::SOM_KEY).unwrap_or_else(|| full_name.clone());
+ if !som.is_empty() {
+ self.out.push((som, dv.unwrap_or_default().to_string()));
+ }
+ }
+ if !kids.is_empty() {
+ self.walk(&kids, &full_name, ft, ff, dv, depth + 1);
+ }
+ }
+ }
+ }
+ let mut w = AcroWalk { doc, seen: std::collections::HashSet::new(), out: Vec::new() };
+ w.walk(&top, "", None, 0, None, 0);
+ w.out
+}
+
+/// The `Want` entries needed to restore password fields in `doc`'s datasets packet to their
+/// defaults (or empty when they have no default).
+fn password_dataset_wants(doc: &Document) -> Vec<Want> {
+ if datasets_stream_ref(doc).is_none() {
+ return Vec::new();
+ }
+ let Ok(Some(packet)) = datasets_packet(doc) else { return Vec::new() };
+ let Some(data) = parse_datasets(&packet) else { return Vec::new() };
+ with_template(doc, None, |tpl| {
+ let mut candidates: Vec<(String, DataPath, String)> = Vec::new();
+ let mut seen = std::collections::HashSet::new();
+ if let Some(t) = tpl {
+ struct Walk<'a> {
+ tpl: &'a Template,
+ data: &'a DataNode,
+ nodes: usize,
+ seen: &'a mut std::collections::HashSet<DataPath>,
+ out: &'a mut Vec<(String, DataPath, String)>,
+ }
+ impl Walk<'_> {
+ fn child_som(parent: &str, name: Option<&str>, index: usize) -> String {
+ match name {
+ Some(n) if !parent.is_empty() => format!("{parent}.{n}[{index}]"),
+ Some(n) => format!("{n}[{index}]"),
+ None => parent.to_string(),
+ }
+ }
+ fn walk(&mut self, children: &[Node], parent_som: &str, depth: usize) {
+ if depth > MAX_DEPTH || self.nodes >= crate::script::MAX_FORM_NODES {
+ return;
+ }
+ let sibs = SomIndices::of(children);
+ for (i, n) in children.iter().enumerate() {
+ if self.nodes >= crate::script::MAX_FORM_NODES {
+ break;
+ }
+ self.nodes += 1;
+ let sib = sibs.at(i);
+ match n {
+ Node::Subform(sf) => {
+ let from_data = match &sf.common.name {
+ Some(name) if sf.occur.max != Some(1) => self.data.count(&data_path(self.tpl, parent_som), name),
+ _ => 0,
+ };
+ let instances = crate::layout::instance_count(&sf.occur, from_data).max(from_data);
+ for k in 0..instances {
+ if k > 0 {
+ if self.nodes >= crate::script::MAX_FORM_NODES {
+ break;
+ }
+ self.nodes += 1;
+ }
+ let som = Self::child_som(parent_som, sf.common.name.as_deref(), sib + k);
+ self.walk(&sf.children, &som, depth + 1);
+ }
+ }
+ Node::Area(a) => {
+ let som = Self::child_som(parent_som, a.common.name.as_deref(), sib);
+ self.walk(&a.children, &som, depth + 1);
+ }
+ Node::Field(f) if f.ui == Ui::PasswordEdit => {
+ let som = Self::child_som(parent_som, f.common.name.as_deref().or(Some("field")), sib);
+ let path = data_path(self.tpl, &som);
+ if !path.is_empty() && self.seen.insert(path.clone()) {
+ let default = f.value.plain().map(|v| f.saved_value(v.trim())).unwrap_or_default();
+ self.out.push((som, path, default));
+ }
+ }
+ _ => {}
+ }
+ }
+ }
+ }
+ let root = Node::Subform(Box::new(t.root.clone()));
+ let mut w = Walk { tpl: t, data: &data, nodes: 0, seen: &mut seen, out: &mut candidates };
+ w.walk(std::slice::from_ref(&root), "", 0);
+ if let Some(ps) = &t.root.page_set {
+ for (i, area) in ps.areas.iter().enumerate() {
+ let som = area.name.clone().map(|n| format!("{n}[0]")).unwrap_or_else(|| format!("#pageArea[{i}]"));
+ w.walk(&area.items, &som, 1);
+ }
+ }
+ }
+ for (som, default) in acro_password_fields(doc) {
+ let path = path_of(tpl, &som);
+ if !path.is_empty() && seen.insert(path.clone()) {
+ candidates.push((som, path, default));
+ }
+ }
+ candidates
+ .into_iter()
+ .filter_map(|(som, path, default)| {
+ let cur = data.value_at(&path)?;
+ (!cur.is_empty() && cur != default).then_some(Want { som, path, text: default, ensure: false })
+ })
+ .collect()
+ })
+}
+
+/// Whether any XFA password field (`<passwordEdit/>` or an AcroForm text field with the Password
+/// flag) holds a value in `doc`'s datasets packet beyond its default (#3944).
+pub fn has_password_values(doc: &Document) -> bool {
+ !password_dataset_wants(doc).is_empty()
+}
+
+/// Clear typed password values from `doc`'s XFA datasets packet (restoring a template default
+/// where the field has one, else emptying the element), replacing the datasets stream in place
+/// (#3944). Returns how many password fields were cleared in the datasets.
+pub fn clear_password_values(doc: &mut Document) -> Result<usize, XfaError> {
+ let wants = password_dataset_wants(doc);
+ if wants.is_empty() {
+ return Ok(0);
+ }
+ let count = wants.len();
+ let reuse = datasets_stream_ref(doc);
+ let report = rewrite(doc, &[Op::Values(&wants)], reuse)?;
+ if !report.written || !password_dataset_wants(doc).is_empty() {
+ let reason = report.warnings.first().map_or("the XFA datasets password values could not be cleared", String::as_str);
+ return Err(XfaError::Malformed(reason.to_string()));
+ }
+ Ok(count)
+}
diff --git a/crates/xfa/src/fixtures.rs b/crates/xfa/src/fixtures.rs
index a0307a6..b76b3ef 100644
--- a/crates/xfa/src/fixtures.rs
+++ b/crates/xfa/src/fixtures.rs
@@ -505,6 +505,29 @@ pub fn fields_template(data: &str) -> String {
)
}
+/// Date fields whose edit pictures list alternatives, as forms let a date be typed several ways
+/// (`date{YYYYMMDD}|date{YYMMDD}|…`); one with a single pattern; a text field; `code`, whose
+/// only alternative is a text clause; `short`, whose first pattern has a two-digit year; and
+/// `pick`, where two later patterns read some dates and only one gives a year the first keeps.
+pub fn date_alternatives_template() -> String {
+ r##"<?xml version="1.0" encoding="UTF-8"?>
+<xdp:xdp xmlns:xdp="http://ns.adobe.com/xdp/">
+<template xmlns="http://www.xfa.org/schema/xfa-template/3.3/">
+<subform name="form" layout="tb">
+ <pageSet><pageArea name="front"><contentArea x="0.5in" y="0.5in" w="7.5in" h="10in"/><medium short="8.5in" long="11in"/></pageArea></pageSet>
+ <field name="leave" w="2in" h="0.3in"><ui><dateTimeEdit/><picture>date{YYYYMMDD}|date{DDMMMYY}|date{YYMMDD}|date{YYYYMMD}|date{YY MM DD}</picture></ui><value><date/></value></field>
+ <field name="born" w="2in" h="0.3in"><ui><dateTimeEdit/><picture>date{YYYY-MM-DD}</picture></ui><value><date/></value></field>
+ <field name="name" w="2in" h="0.3in"><ui><textEdit/></ui></field>
+ <field name="code" w="2in" h="0.3in"><ui><dateTimeEdit/><picture>date{YYYYMMDD}|text{YYMMDD}</picture></ui><value><date/></value></field>
+ <field name="short" w="2in" h="0.3in"><ui><dateTimeEdit/><picture>date{YYMMDD}|date{YYYYMMDD}</picture></ui><value><date/></value></field>
+ <field name="pick" w="2in" h="0.3in"><ui><dateTimeEdit/><picture>date{YYMMDD}|date{DDMMYYYY}|date{YYYYMMDD}</picture></ui><value><date/></value></field>
+</subform>
+</template>
+</xdp:xdp>
+"##
+ .to_string()
+}
+
/// A form of `sections` sections of `rows` rows, each row with a calculated total (half in
/// JavaScript, half in FormCalc) and a section sum over its rows: 2 × sections × rows + sections
/// calculate scripts, every one reading values the earlier ones settled.
@@ -597,6 +620,27 @@ pub fn shell(xdp: &str) -> Vec<u8> {
assemble(objs)
}
+/// [`shell`] with usage rights: the catalog's `/Perms` holds a `/UR3` signature (a stand-in
+/// dictionary, nothing verifies it), beside `others` (`/DocMDP 6 0 R`, say: object 6 is a
+/// signature dictionary too). `indirect` puts `/Perms` in an object of its own.
+pub fn usage_rights_shell(xdp: &str, others: &str, indirect: bool) -> Vec<u8> {
+ let perms = format!("<< /UR3 6 0 R {others} >>");
+ let entry = if indirect { "7 0 R".to_string() } else { perms.clone() };
+ let catalog = format!("<< /Type /Catalog /Pages 2 0 R /NeedsRendering true /AcroForm << /XFA 5 0 R /Fields [] >> /Perms {entry} >>");
+ let mut objs: Vec<Vec<u8>> = vec![
+ catalog.into_bytes(),
+ b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_vec(),
+ b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents 4 0 R >>".to_vec(),
+ b"<< /Length 44 >>\nstream\nBT /F1 12 Tf 72 700 Td (Please wait...) Tj ET\nendstream".to_vec(),
+ format!("<< /Length {} >>\nstream\n{xdp}\nendstream", xdp.len()).into_bytes(),
+ b"<< /Type /Sig /Reference [<< /Type /SigRef /TransformMethod /UR3 >>] >>".to_vec(),
+ ];
+ if indirect {
+ objs.push(perms.into_bytes());
+ }
+ assemble(objs)
+}
+
/// A dynamic form with two signature boxes of which `sign` has been signed: the file holds the
/// field a signing application leaves (named by its SOM path, its value a signature dictionary)
/// and the picture drawn in the box, a solid blue rectangle.
diff --git a/crates/xfa/src/layout.rs b/crates/xfa/src/layout.rs
index 2334216..670d437 100644
--- a/crates/xfa/src/layout.rs
+++ b/crates/xfa/src/layout.rs
@@ -14,7 +14,10 @@ use base64::Engine;
use crate::XfaError;
use crate::data::{DataNode, data_date_letters, data_path, data_to_iso, date_letters, is_on, iso_to_pattern};
-use crate::model::*;
+use crate::model::{
+ Access, Area, Border, Common, Draw, ExclGroup, Field, Font, HAlign, Layout, Margin, Node, Occur, PageArea, PageRole, Para, Placement, Presence,
+ Rect, Script, SomIndices, Stroke, Subform, Template, Ui, VAlign, Value,
+};
use crate::text::{self, Block, Face, Span};
/// Most pages a form may lay out to.
@@ -37,15 +40,52 @@ const MAX_IMAGE_BYTES: usize = 256 << 20;
/// Placeholder for the page count in text laid out before the count is known.
const PAGE_COUNT_MARK: char = '\u{E000}';
+/// How far below its baseline an underline is drawn, in the text's size: an underline is the
+/// level line pushed just before its span, this far below it (the PDF writer tells it apart from
+/// a rule by this).
+pub(crate) const UNDERLINE_DROP: f64 = 0.1;
+
#[derive(Clone, Debug, PartialEq)]
pub enum Item {
- Fill { rect: Rect, color: [f64; 3] },
- Line { from: (f64, f64), to: (f64, f64), width: f64, color: [f64; 3], dashed: bool },
+ Fill {
+ rect: Rect,
+ color: [f64; 3],
+ },
+ Line {
+ from: (f64, f64),
+ to: (f64, f64),
+ width: f64,
+ color: [f64; 3],
+ dashed: bool,
+ },
+ /// A box with rounded (or inverted) corners: its fill, and its edge drawn inside it.
+ Rounded(Box<Rounded>),
Text(Span),
- Image { rect: Rect, data: Arc<Vec<u8>>, content_type: String },
+ Image {
+ rect: Rect,
+ data: Arc<Vec<u8>>,
+ content_type: String,
+ },
Widget(Box<Widget>),
}
+/// A box with rounded corners ([`Item::Rounded`]).
+#[derive(Clone, Debug, PartialEq)]
+pub struct Rounded {
+ pub rect: Rect,
+ /// Top-left, top-right, bottom-right and bottom-left radii, each at most half the box's
+ /// shorter side.
+ pub radii: [f64; 4],
+ /// Corners whose curve goes into the box rather than around it, in the same order.
+ pub inverted: [bool; 4],
+ pub fill: Option<[f64; 3]>,
+ /// The edge: its width, colour and whether it is dashed.
+ pub edge: Option<(f64, [f64; 3], bool)>,
+ /// A page break cut the box here: that side has no edge, and its corners are square.
+ pub open_top: bool,
+ pub open_bottom: bool,
+}
+
#[derive(Clone, Debug, PartialEq)]
pub enum WidgetKind {
Text,
@@ -126,6 +166,8 @@ pub struct Widget {
pub action: Option<Action>,
/// Check boxes: the on and off values of the data; radio buttons: the on value.
pub items: Vec<String>,
+ /// A text field that doesn't scroll: it takes no more text than it shows (`DoNotScroll`).
+ pub no_scroll: bool,
}
#[derive(Clone, Debug, Default, PartialEq)]
@@ -155,6 +197,8 @@ impl Ctx {
Ctx { font: self.font.apply(&c.font), para: self.para.apply(&c.para), som: self.som.clone() }
}
+ /// [`Self::child`] for object `c`, its SOM path extended by its name and `index` among the
+ /// siblings of that name (an unnamed object adds nothing).
fn with_som(&self, c: &Common, index: usize) -> Ctx {
let mut out = self.child(c);
if let Some(n) = &c.name {
@@ -177,6 +221,33 @@ struct Measured {
size: (f64, f64),
}
+/// A point in the flow ([`Layouter::flow_mark`]): the page and content area, the height
+/// reached there, and how many items the page had then.
+#[derive(Clone, Copy, Debug)]
+struct FlowMark {
+ page: usize,
+ area: usize,
+ content: usize,
+ y: f64,
+ items: usize,
+}
+
+/// A flowed subform being laid out ([`Layouter::frames`]): where it sits across, its margins and
+/// border, its part on the content area the flow is in, and its parts on earlier ones (page
+/// index, the page's first item of the part, the part's box).
+struct Frame {
+ x: f64,
+ w: f64,
+ margin: Margin,
+ border: Option<Border>,
+ part: FlowMark,
+ parts: Vec<(usize, usize, Rect)>,
+ /// Something inside didn't fit its content area: an item cut across areas, or one placed past
+ /// the area's bottom (a table row taller than an area, an overflow leader and the row after it
+ /// that don't fit together). The border is left out ([`Layouter::finish_frame`]).
+ lost: bool,
+}
+
struct Cursor {
area: usize,
content: usize,
@@ -211,6 +282,9 @@ struct Layouter<'t> {
/// The fields and draws of the block being placed: (first item, one past the last, top,
/// bottom) on the last page. A page break keeps each whole (see `split_block`).
leaves: Vec<(usize, usize, f64, f64)>,
+ /// The flowed subforms being laid out, outermost first: a break between their children
+ /// closes their parts on one content area and opens new ones on the next.
+ frames: Vec<Frame>,
}
/// How many instances of a repeating subform to lay out: what the data holds once it holds
@@ -256,6 +330,7 @@ pub fn layout(tpl: &Template, data: Option<&DataNode>) -> Result<Form, XfaError>
measured: RefCell::new(HashMap::new()),
measures: Cell::new(0),
leaves: Vec::new(),
+ frames: Vec::new(),
};
let ctx = Ctx { font: Font::default(), para: Para::default(), som: String::new() };
l.new_page()?;
@@ -334,7 +409,7 @@ fn solid_extent(item: &Item) -> Option<(f64, f64)> {
Item::Text(s) => Some((s.baseline - s.face.size * 0.8, s.baseline + s.face.size * 0.2)),
Item::Image { rect, .. } => Some((rect.y, rect.bottom())),
Item::Widget(w) => Some((w.rect.y, w.rect.bottom())),
- Item::Fill { .. } | Item::Line { .. } => None,
+ Item::Fill { .. } | Item::Line { .. } | Item::Rounded(_) => None,
}
}
@@ -369,6 +444,23 @@ fn divide(item: Item, cut: f64) -> (Option<Item>, Option<Item>) {
(Some(Item::Line { from: lo, to: mid, width, color, dashed }), Some(Item::Line { from: mid, to: hi, width, color, dashed }))
}
}
+ Item::Rounded(r) => {
+ if r.rect.bottom() <= cut + 0.01 {
+ (Some(Item::Rounded(r)), None)
+ } else if r.rect.y >= cut - 0.01 {
+ (None, Some(Item::Rounded(r)))
+ } else {
+ // Each part keeps the corners on its side, rounded no more than its own height
+ // allows, and is open where it was cut.
+ let [tl, tr, br, bl] = r.radii;
+ let above = Rect::new(r.rect.x, r.rect.y, r.rect.w, cut - r.rect.y);
+ let below = Rect::new(r.rect.x, cut, r.rect.w, r.rect.bottom() - cut);
+ let fit = |v: f64, h: f64| v.min(h.max(0.0));
+ let upper = Rounded { rect: above, radii: [fit(tl, above.h), fit(tr, above.h), 0.0, 0.0], open_bottom: true, ..(*r).clone() };
+ let lower = Rounded { rect: below, radii: [0.0, 0.0, fit(br, below.h), fit(bl, below.h)], open_top: true, ..*r };
+ (Some(Item::Rounded(Box::new(upper))), Some(Item::Rounded(Box::new(lower))))
+ }
+ }
other => (Some(other), None),
}
}
@@ -380,6 +472,10 @@ fn moved(mut item: Item, dx: f64, dy: f64) -> Item {
rect.x += dx;
rect.y += dy;
}
+ Item::Rounded(r) => {
+ r.rect.x += dx;
+ r.rect.y += dy;
+ }
Item::Line { from, to, .. } => {
*from = (from.0 + dx, from.1 + dy);
*to = (to.0 + dx, to.1 + dy);
@@ -401,7 +497,7 @@ fn is_row(node: &Node) -> bool {
}
/// The Acrobat date pattern for an XFA picture clause such as `date{YYYY-MM-DD}`.
-fn date_pattern(picture: Option<&str>) -> String {
+pub(crate) fn date_pattern(picture: Option<&str>) -> String {
picture.and_then(date_letters).unwrap_or_else(|| "yyyy-mm-dd".into())
}
@@ -521,7 +617,7 @@ impl Layouter<'_> {
for s in b.spans {
if s.face.underline {
let w = s.face.width(&s.text);
- let y = s.baseline + s.face.size * 0.1;
+ let y = s.baseline + s.face.size * UNDERLINE_DROP;
self.push(Item::Line { from: (s.x, y), to: (s.x + w, y), width: (s.face.size * 0.06).max(0.3), color: s.face.color, dashed: false })?;
}
if !s.text.trim().is_empty() {
@@ -589,6 +685,8 @@ impl Layouter<'_> {
self.new_page()
}
+ /// The current content area, how far down it the flow is, and whether anything has been
+ /// placed in it; before the first page, an empty letter-size page from its top.
fn cursor(&self) -> (Rect, f64, bool) {
match &self.cur {
Some(c) => (c.rect, c.y, c.placed),
@@ -596,6 +694,111 @@ impl Layouter<'_> {
}
}
+ /// Where the flow is now ([`FlowMark`]); `None` before the first page.
+ fn flow_mark(&self) -> Option<FlowMark> {
+ let c = self.cur.as_ref()?;
+ Some(FlowMark { page: self.pages.len(), area: c.area, content: c.content, y: c.y, items: self.pages.last().map_or(0, |p| p.items.len()) })
+ }
+
+ /// Whether the flow is still in the content area `m` was taken in.
+ fn on_area(&self, m: &FlowMark) -> bool {
+ self.pages.len() == m.page && self.cur.as_ref().is_some_and(|c| c.area == m.area && c.content == m.content)
+ }
+
+ /// Whether page `page` (an index) got anything from item `at` on.
+ fn has_items_from(&self, page: usize, at: usize) -> bool {
+ self.pages.get(page).is_some_and(|p| p.items.len() > at)
+ }
+
+ /// Break the flowed subforms being laid out ([`Self::frames`]) across content areas, as
+ /// another viewer breaks such a section on a synthetic form: each one's part here ends after
+ /// its content and its bottom margin (the innermost first, each inside the next), the flow
+ /// moves to the next content area, and each starts a new part there after its top margin
+ /// (the outermost first). The top margins take only what the `need` points of what comes next
+ /// leave of the new area: a child that fits a fresh area but not after the margins would
+ /// otherwise run past its bottom, out of its border. `to_page` moves to a new page instead (a
+ /// child's own page break), which breaks the subforms around it the same way.
+ fn break_frames(&mut self, need: f64, to_page: bool) -> Result<(), XfaError> {
+ let (rect, mut y, _) = self.cursor();
+ let page = self.pages.len().saturating_sub(1);
+ let here: Vec<bool> = self.frames.iter().map(|f| self.on_area(&f.part)).collect();
+ let filled: Vec<bool> = self.frames.iter().map(|f| self.has_items_from(page, f.part.items)).collect();
+ for ((f, here), filled) in self.frames.iter_mut().zip(here).zip(filled).rev() {
+ y = (y + f.margin.bottom).min(rect.bottom());
+ if !here {
+ f.lost = true;
+ } else if filled && y - f.part.y >= 0.01 {
+ f.parts.push((page, f.part.items, Rect::new(f.x, f.part.y, f.w, y - f.part.y)));
+ }
+ }
+ if to_page {
+ self.new_page()?;
+ } else {
+ self.next_area()?;
+ }
+ let (rect, y, _) = self.cursor();
+ let mut room = (rect.bottom() - y - need).max(0.0);
+ for i in 0..self.frames.len() {
+ let Some(mark) = self.flow_mark() else { break };
+ let Some(f) = self.frames.get_mut(i) else { break };
+ f.part = mark;
+ // `max` before `min`: a NaN margin counts as none and leaves `room` a number.
+ let top = f.margin.top.max(0.0).min(room);
+ room = (room - top).max(0.0);
+ self.advance(top);
+ }
+ Ok(())
+ }
+
+ /// Close flowed subform `f` once its content is placed: its last part ends where the flow
+ /// is, and its border (edges and fill) is drawn round each part, closed on every side, under
+ /// that part's content. One holding something that didn't fit its content area ([`Frame::lost`])
+ /// is drawn without its border, and the layout says so.
+ fn finish_frame(&mut self, mut f: Frame) -> Result<(), XfaError> {
+ let Some(b) = f.border.take() else { return Ok(()) };
+ if b.fill().is_none() && b.visible_edges() == [false; 4] {
+ return Ok(());
+ }
+ let (area, end, _) = self.cursor();
+ // The bottom margin stays in the content area, as at a break; content that itself ran
+ // past it has already cost the section its border ([`Self::overflowed`]).
+ let end = end.min(area.bottom()).max(end - f.margin.bottom);
+ let page = self.pages.len().saturating_sub(1);
+ if !self.on_area(&f.part) {
+ f.lost = true;
+ } else if self.has_items_from(page, f.part.items) && end - f.part.y >= 0.01 {
+ f.parts.push((page, f.part.items, Rect::new(f.x, f.part.y, f.w, end - f.part.y)));
+ }
+ if f.lost {
+ self.warn_once("a bordered section holding an item that doesn't fit on its page is drawn without its border");
+ return Ok(());
+ }
+ // The last part first: a part's place on its page stays where it was found.
+ for (page, at, rect) in f.parts.into_iter().rev() {
+ self.insert_border(&b, rect, page, at)?;
+ }
+ Ok(())
+ }
+
+ /// Draw border `b` round `rect` on page `page` (an index), under what that page got from item
+ /// `at` on.
+ fn insert_border(&mut self, b: &Border, rect: Rect, page: usize, at: usize) -> Result<(), XfaError> {
+ let before = self.pages.last().map_or(0, |p| p.items.len());
+ self.draw_border(b, rect)?;
+ let drawn: Vec<Item> = match self.pages.last_mut() {
+ Some(p) => {
+ let from = before.min(p.items.len());
+ p.items.drain(from..).collect()
+ }
+ None => return Ok(()),
+ };
+ if let Some(target) = self.pages.get_mut(page) {
+ let at = at.min(target.items.len());
+ target.items.splice(at..at, drawn);
+ }
+ Ok(())
+ }
+
/// Move the cursor down (margins and spacing: the area still counts as empty).
fn advance(&mut self, dy: f64) {
if let Some(c) = &mut self.cur {
@@ -609,16 +812,36 @@ impl Layouter<'_> {
c.y += dy.max(0.0);
c.placed = true;
}
+ let (_, y, _) = self.cursor();
+ self.overflowed(y);
+ }
+
+ /// Something was placed down to `bottom`: past the content area's bottom, the flowed subforms
+ /// it is inside can't hold it in a part, and are drawn without their border.
+ fn overflowed(&mut self, bottom: f64) {
+ let (rect, _, _) = self.cursor();
+ if bottom > rect.bottom() + 0.01 {
+ for f in &mut self.frames {
+ f.lost = true;
+ }
+ }
}
- /// Make room for `h`: stay, or move to the next content area / page. Returns whether a
- /// break happened.
- fn make_room(&mut self, h: f64) -> Result<bool, XfaError> {
+ /// Make room for `h`, with `after` more drawn before it should it move (a table's overflow
+ /// leader): stay, or move to the next content area / page. Returns whether a break happened.
+ /// Something that fits a fresh area breaks the flowed subforms it is in with it
+ /// ([`Self::break_frames`]), a table's rows included; one taller than an area just moves on,
+ /// and those subforms are drawn without their border ([`Self::finish_frame`]).
+ fn make_room(&mut self, h: f64, after: f64) -> Result<bool, XfaError> {
let (rect, y, placed) = self.cursor();
if y + h <= rect.bottom() + 0.01 || !placed {
return Ok(false);
}
- self.next_area()?;
+ if h <= rect.h + 0.01 {
+ self.break_frames(h + after, false)?;
+ } else {
+ self.next_area()?;
+ }
Ok(true)
}
@@ -628,7 +851,7 @@ impl Layouter<'_> {
fn flow_block(&mut self, node: &Node, x: f64, (w, h): (f64, f64), ctx: &Ctx, depth: usize, sib: usize) -> Result<(), XfaError> {
let (rect, y, _) = self.cursor();
if y + h > rect.bottom() + 0.01 && h <= rect.h + 0.01 {
- self.make_room(h)?;
+ self.make_room(h, 0.0)?;
}
let (rect, y, _) = self.cursor();
let first = self.pages.last().map_or(0, |p| p.items.len());
@@ -747,6 +970,7 @@ impl Layouter<'_> {
c.y = (end - shift).min(c.rect.bottom()).max(c.y);
c.placed = true;
}
+ self.overflowed(end - shift);
return Ok(());
}
rest = below;
@@ -773,7 +997,7 @@ impl Layouter<'_> {
let Node::Subform(sf) = node else { return Ok(()) };
self.check_measures()?;
if sf.break_before_page && self.page_has_flow() {
- self.new_page()?;
+ self.break_frames(0.0, true)?;
}
// Data adds instances of a repeating subform (rows added in another viewer).
let instances = self.instances(node, &ctx.som);
@@ -794,6 +1018,14 @@ impl Layouter<'_> {
continue;
}
let m = sf.common.margin;
+ // Its border and fill go round what it takes from here, a part on each content area.
+ let framed = match self.flow_mark() {
+ Some(part) => {
+ self.frames.push(Frame { x, w, margin: m, border: sf.common.border.clone(), part, parts: Vec::new(), lost: false });
+ true
+ }
+ None => false,
+ };
self.advance(m.top);
let inner_x = x + m.left;
let inner_w = (w - m.horizontal()).max(1.0);
@@ -818,9 +1050,12 @@ impl Layouter<'_> {
}
}
self.advance(m.bottom);
+ if framed && let Some(frame) = self.frames.pop() {
+ self.finish_frame(frame)?;
+ }
}
if sf.break_after_page {
- self.new_page()?;
+ self.break_frames(0.0, true)?;
}
Ok(())
}
@@ -837,6 +1072,12 @@ impl Layouter<'_> {
let cols = self.columns(sf, inner_w);
let leader =
sf.overflow_leader.as_ref().and_then(|name| sf.children.iter().position(|c| c.common().name.as_deref() == Some(name) && is_row(c)));
+ // The overflow leader starts each part after the first, before the row that moved.
+ let lead = leader.and_then(|li| match sf.children.get(li) {
+ Some(Node::Subform(l)) => Some((li, l.as_ref())),
+ _ => None,
+ });
+ let lead_h = lead.map_or(0.0, |(_, l)| self.row_height(l, &cols, inner_w, ctx, depth + 1));
let sibs = SomIndices::of(&sf.children);
for (ci, child) in sf.children.iter().enumerate() {
if !child.common().presence.occupies() {
@@ -851,15 +1092,13 @@ impl Layouter<'_> {
self.warn_truncated(child, &ctx.som, instances);
for inst in 0..instances {
let h = self.row_height(row, &cols, inner_w, ctx, depth + 1);
- if self.make_room(h)?
- && let Some(li) = leader
- && li != ci
- && let Some(Node::Subform(l)) = sf.children.get(li)
+ let led = lead.filter(|(li, _)| *li != ci);
+ if self.make_room(h, led.map_or(0.0, |_| lead_h))?
+ && let Some((li, l)) = led
{
- let lh = self.row_height(l, &cols, inner_w, ctx, depth + 1);
let (_, y, _) = self.cursor();
- self.draw_row(l, &cols, Rect::new(x, y, inner_w, lh), ctx, depth + 1, sibs.at(li))?;
- self.place(lh);
+ self.draw_row(l, &cols, Rect::new(x, y, inner_w, lead_h), ctx, depth + 1, sibs.at(li))?;
+ self.place(lead_h);
}
let (_, y, _) = self.cursor();
self.draw_row(row, &cols, Rect::new(x, y, inner_w, h), ctx, depth + 1, csib + inst)?;
@@ -1089,6 +1328,10 @@ impl Layouter<'_> {
if cap.value.is_empty() && cap.reserve.is_none() {
return None;
}
+ // A check box has no text for an inline caption to run with: it is not shown.
+ if f.ui == Ui::CheckButton && cap.placement == Placement::Inline {
+ return None;
+ }
let placement = if cap.placement == Placement::Inline { Placement::Left } else { cap.placement };
let font = ctx.font.apply(&cap.font);
let para = ctx.para.apply(&cap.para);
@@ -1129,13 +1372,18 @@ impl Layouter<'_> {
};
match self.caption_reserve(f, inner_w, ctx) {
Some((Placement::Top | Placement::Bottom, r)) => ui + r,
- Some((_, r)) => {
+ Some((placement, r)) => {
+ // A check box's caption without a reserve is drawn in all the box leaves.
+ let w = match auto_check_reserve(f, placement, inner_w, None) {
+ Some(auto) => auto,
+ None => inner_w - r,
+ };
let cap = f.caption.as_ref().map(|c| {
let rich = match &c.value {
Value::Rich(r) => r.clone(),
other => text::plain(&other.plain().unwrap_or_default()),
};
- text::measure_height(&rich, (inner_w - r).max(1.0), &ctx.para.apply(&c.para), &Face::of(&ctx.font.apply(&c.font)), &|id, max| {
+ text::measure_height(&rich, w.max(1.0), &ctx.para.apply(&c.para), &Face::of(&ctx.font.apply(&c.font)), &|id, max| {
self.embed(id, max)
})
});
@@ -1403,11 +1651,35 @@ impl Layouter<'_> {
}
}
+ /// Draw border `b` around `rect`: its fill, then each shown edge as a line inside the box, or
+ /// the whole box as one rounded shape when its corners are rounded.
fn draw_border(&mut self, b: &Border, rect: Rect) -> Result<(), XfaError> {
+ let vis = b.visible_edges();
+ // Rounded corners: the box is one shape, filled and edged along its curves, when its
+ // edges are all alike (all shown and the same, or all hidden). Edges that differ keep
+ // square corners.
+ let radii = b.radii(rect.w, rect.h);
+ let alike = b.edges.iter().all(|e| *e == b.edges[0]);
+ if radii.iter().any(|r| *r > 0.0) && (vis == [true; 4] && alike || vis == [false; 4]) {
+ let e = b.edges[0];
+ let edge = vis[0].then(|| {
+ let color = if e.stroke == Stroke::Relief { [0.55, 0.55, 0.55] } else { e.color.0 };
+ (e.thickness.clamp(0.1, 20.0), color, matches!(e.stroke, Stroke::Dashed | Stroke::Dotted))
+ });
+ let shape = Rounded {
+ rect,
+ radii,
+ inverted: b.corners.map(|c| c.inverted),
+ fill: b.fill().map(|f| f.0),
+ edge,
+ open_top: false,
+ open_bottom: false,
+ };
+ return self.push(Item::Rounded(Box::new(shape)));
+ }
if let Some(fill) = b.fill() {
self.push(Item::Fill { rect, color: fill.0 })?;
}
- let vis = b.visible_edges();
let (x0, y0, x1, y1) = (rect.x, rect.y, rect.right(), rect.bottom());
// Top, right, bottom, left; lines sit inside the box.
let segs = [((x0, y0), (x1, y0)), ((x1, y0), (x1, y1)), ((x0, y1), (x1, y1)), ((x0, y0), (x0, y1))];
@@ -1578,6 +1850,7 @@ impl Layouter<'_> {
let inner = rect.inset(&f.common.margin);
let (mut ui, mut cap_rect) = (inner, None);
if let Some((placement, reserve)) = self.caption_reserve(f, inner.w, ctx) {
+ let reserve = auto_check_reserve(f, placement, inner.w, Some(inner.h)).unwrap_or(reserve);
let r = reserve.max(0.0);
match placement {
Placement::Top => {
@@ -1715,12 +1988,21 @@ impl Layouter<'_> {
let (kind, rect, border, value, tooltip) = match f.ui {
Ui::CheckButton => {
let s = f.check_size.unwrap_or(10.0).min(ui.w.max(1.0)).min(ui.h.max(1.0));
+ // Without a caption the box sits at the right of the content area, as if a
+ // caption on its left took the rest, so the paragraph's alignment has no room to
+ // act on; beside a caption that alignment places it. The box's own margin doesn't
+ // move it.
+ let x = match (cap_rect, fctx.para.h_align) {
+ (None, _) | (Some(_), HAlign::Right) => ui.right() - s,
+ (Some(_), HAlign::Center) => ui.x + (ui.w - s) / 2.0,
+ (Some(_), HAlign::Left | HAlign::Justify) => ui.x,
+ };
let y = match fctx.para.v_align {
- VAlign::Top => ui.y + f.ui_margin.top,
+ VAlign::Top => ui.y,
VAlign::Middle => ui.y + (ui.h - s) / 2.0,
- VAlign::Bottom => ui.bottom() - s - f.ui_margin.bottom,
+ VAlign::Bottom => ui.bottom() - s,
};
- let r = Rect::new(ui.x + f.ui_margin.left, y, s, s);
+ let r = Rect::new(x, y, s, s);
let on = f.items.first().cloned().filter(|s| !s.trim().is_empty()).unwrap_or_else(|| "1".into());
let (kind, tip, checked) = match radio {
Some((group, on_value, tip, chosen)) => (
@@ -1804,10 +2086,27 @@ impl Layouter<'_> {
default: template_default,
action,
items,
+ no_scroll: f.no_scroll,
})))
}
}
+/// The room a caption without a reserve takes beside a check box: all the box leaves of a
+/// content area `w` wide (and `h` tall, when known), the box at the size it can be drawn there.
+/// `None` for any other field, or a caption with a reserve of its own.
+fn auto_check_reserve(f: &Field, placement: Placement, w: f64, h: Option<f64>) -> Option<f64> {
+ if f.ui != Ui::CheckButton || f.caption.as_ref().is_none_or(|c| c.reserve.is_some()) {
+ return None;
+ }
+ let s = f.check_size.unwrap_or(10.0).min(w.max(1.0)).min(h.map_or(f64::INFINITY, |h| h.max(1.0)));
+ let rest = match (placement, h) {
+ (Placement::Top | Placement::Bottom, Some(h)) => h - s,
+ (Placement::Top | Placement::Bottom, None) => return None,
+ _ => w - s,
+ };
+ Some(rest.max(0.0))
+}
+
/// The widget's own border from the `<ui>` border element. Without one, a check box gets a
/// solid box, as Designer draws it, and any other field has no box of its own.
fn widget_border(b: Option<&Border>, check: bool) -> WidgetBorder {
diff --git a/crates/xfa/src/lib.rs b/crates/xfa/src/lib.rs
index 93e6682..41a250a 100644
--- a/crates/xfa/src/lib.rs
+++ b/crates/xfa/src/lib.rs
@@ -15,6 +15,7 @@ pub mod model;
pub mod packets;
pub mod parse;
pub mod pdf;
+pub mod picture;
pub mod script;
pub mod text;
@@ -91,14 +92,15 @@ pub(crate) fn xml_nesting_depth(text: &str) -> usize {
pub use data::{DataImport, ImportNode, export_data, import_data, parse_data_file, write_data_image};
pub use data::{
- DataNode, DataOp, DataPath, DatasetsWrite, FieldData, FieldDatum, add_data_instances, build_data, data_path, iso_to_pattern, parse_datasets,
- pattern_to_iso, read_values, read_values_with, remove_data_instance, som_to_path, write_data_ops, write_data_value, write_datasets,
- write_datasets_reusing, write_datasets_with,
+ DataNode, DataOp, DataPath, DatasetsWrite, FieldData, FieldDatum, add_data_instances, build_data, clear_password_values, data_path,
+ has_password_values, iso_to_pattern, parse_datasets, pattern_to_iso, read_values, read_values_with, remove_data_instance, som_to_path,
+ write_data_ops, write_data_value, write_datasets, write_datasets_reusing, write_datasets_with,
};
pub use layout::{Action, BorderShape, Form, Item, MAX_PAGES, Page, Widget, WidgetKind, formatted_value, layout};
pub use packets::{Encoding, Packets, decode as decode_packet, encode as encode_packet, read_packets};
pub use parse::{measure, parse};
pub use pdf::{CLICK_KEY, LAYOUT_KEY, SOM_KEY, Stripped, XfaShape, existing_layout, strip, xfa_shape};
+pub use picture::typed_date;
pub use script::{
FormNode, LiveForm, MAX_FORM_NODES, NodeKind, OVERRIDES_KEY, Overrides, ScriptEvent, apply_overrides, data_of, field_grows_with_text,
fields_by_som, form_tree, has_scripts, overrides, refresh_value, rerender, set_overrides, template_of,
@@ -165,6 +167,9 @@ pub fn render_into(doc: &mut Document) -> Result<Report, XfaError> {
let written = pdf::write_form(doc, &form)?;
let mut warnings = form.warnings;
warnings.extend(written.warnings);
+ if written.usage_rights {
+ warnings.push(crate::pdf::USAGE_RIGHTS_REMOVED.into());
+ }
warnings.dedup();
Ok(Report { pages: written.pages, fields: written.fields, template_bytes: packets.xdp.len(), warnings })
}
diff --git a/crates/xfa/src/model.rs b/crates/xfa/src/model.rs
index b60180b..0fac8db 100644
--- a/crates/xfa/src/model.rs
+++ b/crates/xfa/src/model.rs
@@ -125,11 +125,22 @@ impl Edge {
}
}
-/// A box border: four edges (top, right, bottom, left) and a fill.
+/// One corner of a border: how far it rounds the box (`radius`), and whether the curve goes
+/// into the box (`inverted`) rather than around it.
+#[derive(Clone, Copy, Debug, Default, PartialEq)]
+pub struct Corner {
+ pub presence: Presence,
+ pub radius: f64,
+ pub inverted: bool,
+}
+
+/// A box border: four edges (top, right, bottom, left), four corners (top-left, top-right,
+/// bottom-right, bottom-left) and a fill.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Border {
pub presence: Presence,
pub edges: [Edge; 4],
+ pub corners: [Corner; 4],
pub fill: Option<Color>,
}
@@ -144,6 +155,15 @@ impl Border {
pub fn fill(&self) -> Option<Color> {
if self.presence == Presence::Visible { self.fill } else { None }
}
+
+ /// How far each corner (top-left, top-right, bottom-right, bottom-left) rounds a box `w` by
+ /// `h`: its radius when the corner is shown, no more than half the box's shorter side, and 0
+ /// for a hidden corner or a hidden border.
+ pub fn radii(&self, w: f64, h: f64) -> [f64; 4] {
+ let most = (w.min(h) / 2.0).max(0.0);
+ let shown = self.presence == Presence::Visible;
+ self.corners.map(|c| if shown && c.presence == Presence::Visible && c.radius.is_finite() { c.radius.clamp(0.0, most) } else { 0.0 })
+ }
}
/// Font properties as written on an element; `None` inherits from the ancestors.
@@ -486,6 +506,9 @@ pub struct Field {
pub check_size: Option<f64>,
pub check_round: bool,
pub multiline: bool,
+ /// The field doesn't scroll in the direction its text runs out (`hScrollPolicy="off"` for one
+ /// line, `vScrollPolicy="off"` for several): it takes no more text than it shows.
+ pub no_scroll: bool,
pub caption: Option<Caption>,
pub value: Value,
/// Check buttons: the on value then the off value; choice lists: the items as shown.
@@ -581,7 +604,7 @@ pub enum Value {
slope_up: bool,
edge: Edge,
},
- Rectangle(Border),
+ Rectangle(Box<Border>),
}
impl Value {
@@ -633,6 +656,9 @@ pub struct Run {
pub h_scale: Option<f64>,
/// A floating field embedded in the text (`xfa:embed="#id"`), shown by its value.
pub embed: Option<String>,
+ /// Where the text links to (`<a href="…">`), as the template writes it: shared by every run
+ /// of the link's text, not copied.
+ pub link: Option<std::sync::Arc<str>>,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
diff --git a/crates/xfa/src/parse.rs b/crates/xfa/src/parse.rs
index fc9ad1a..838d173 100644
--- a/crates/xfa/src/parse.rs
+++ b/crates/xfa/src/parse.rs
@@ -5,7 +5,11 @@ use base64::Engine;
use roxmltree::Node as XmlNode;
use crate::XfaError;
-use crate::model::*;
+use crate::model::{
+ Access, Anchor, Area, Border, Caption, ChoiceList, Color, Common, Corner, Draw, Edge, ExclGroup, Field, FontSpec, HAlign, Layout, Margin, Node,
+ Occur, PageArea, PageRole, PageSet, ParaSpec, Paragraph, Placement, Presence, Rect, RichText, Run, Script, Stroke, Subform, Template, Ui, VAlign,
+ Value,
+};
/// Deepest element nesting followed (templates are shallow; hostile ones are not).
const MAX_DEPTH: usize = 64;
@@ -146,7 +150,23 @@ fn parse_border(n: Option<XmlNode>) -> Option<Border> {
3 => [e(0), e(1), e(2), e(1)],
_ => [e(0), e(1), e(2), e(3)],
};
- Some(Border { presence: Presence::parse(n.attribute("presence")), edges: four, fill: parse_fill(child(n, "fill")) })
+ Some(Border { presence: Presence::parse(n.attribute("presence")), edges: four, corners: parse_corners(n), fill: parse_fill(child(n, "fill")) })
+}
+
+/// The `<corner>` children of a border or rectangle, top-left, top-right, bottom-right then
+/// bottom-left: one applies to all four, and a corner not given is the last one given. Without
+/// any, the corners are square.
+fn parse_corners(n: XmlNode) -> [Corner; 4] {
+ let given: Vec<Corner> = children(n, "corner")
+ .take(4)
+ .map(|c| Corner {
+ presence: Presence::parse(c.attribute("presence")),
+ radius: attr_measure(c, "radius").filter(|r| r.is_finite()).unwrap_or(0.0).max(0.0),
+ inverted: c.attribute("inverted") == Some("1"),
+ })
+ .collect();
+ let Some(last) = given.last().copied() else { return [Corner::default(); 4] };
+ std::array::from_fn(|i| given.get(i).copied().unwrap_or(last))
}
/// `<font>`: typeface, size, weight, posture, underline, fill color and horizontal scale.
@@ -201,7 +221,7 @@ fn parse_common(n: XmlNode) -> Common {
}
/// Rich text: XHTML `body > p > span…`. `br` starts a new paragraph; `xfa:embed` spans become
-/// embedded fields.
+/// embedded fields; the text of an `<a href>` keeps where it links to.
fn parse_rich(body: XmlNode) -> RichText {
#[derive(Clone, Default)]
struct Style {
@@ -210,6 +230,8 @@ fn parse_rich(body: XmlNode) -> RichText {
underline: Option<bool>,
size: Option<f64>,
h_scale: Option<f64>,
+ /// The `href` of the `<a>` the text is in.
+ link: Option<std::sync::Arc<str>>,
}
/// `base` with the CSS declarations in `css` applied: weight, style, underline, size and
/// `xfa-font-horizontal-scale`. Anything else is ignored.
@@ -254,6 +276,7 @@ fn parse_rich(body: XmlNode) -> RichText {
size: style.size,
h_scale: style.h_scale,
embed: None,
+ link: style.link.clone(),
},
);
}
@@ -285,6 +308,13 @@ fn parse_rich(body: XmlNode) -> RichText {
"b" => st.bold = Some(true),
"i" => st.italic = Some(true),
"u" => st.underline = Some(true),
+ // A link's text keeps where it points; an `<a>` without one (a named
+ // anchor) leaves the text as it was.
+ "a" => {
+ if let Some(href) = c.attribute("href").map(str::trim).filter(|h| !h.is_empty()) {
+ st.link = Some(std::sync::Arc::from(href));
+ }
+ }
_ => {}
}
let embed = c.attributes().find(|a| a.name() == "embed").map(|a| a.value().trim_start_matches('#').to_string());
@@ -300,6 +330,7 @@ fn parse_rich(body: XmlNode) -> RichText {
size: st.size,
h_scale: st.h_scale,
embed: Some(e),
+ link: st.link.clone(),
},
);
}
@@ -378,7 +409,7 @@ fn parse_value(n: Option<XmlNode>, warnings: &mut Vec<String>) -> Value {
"rectangle" => {
let mut b = parse_border(Some(c)).unwrap_or_default();
b.fill = parse_fill(child(c, "fill"));
- return Value::Rectangle(b);
+ return Value::Rectangle(Box::new(b));
}
"date" | "time" | "dateTime" | "integer" | "decimal" | "float" | "boolean" => return Value::Text(text_of(c)),
_ => {}
@@ -397,7 +428,9 @@ fn parse_caption(n: Option<XmlNode>, warnings: &mut Vec<String>) -> Option<Capti
Some("inline") => Placement::Inline,
_ => Placement::Left,
},
- reserve: attr_measure(n, "reserve").filter(|r| *r >= 0.0),
+ // A reserve of zero or less sizes the caption to its content, as none does (XFA 3.3,
+ // the caption's reserve).
+ reserve: attr_measure(n, "reserve").filter(|r| *r > 0.0),
presence: Presence::parse(n.attribute("presence")),
value: parse_value(child(n, "value"), warnings),
font: parse_font(child(n, "font")),
@@ -478,6 +511,7 @@ fn parse_field(n: XmlNode, warnings: &mut Vec<String>) -> Field {
}
_ => ChoiceList::default(),
};
+ let multiline = ui_el.is_some_and(|e| e.attribute("multiLine").is_some_and(|m| m == "1" || m == "true"));
let validate_el = child(n, "validate");
let validate_message = validate_el
.and_then(|v| child(v, "message"))
@@ -492,7 +526,8 @@ fn parse_field(n: XmlNode, warnings: &mut Vec<String>) -> Field {
ui_margin: parse_margin(ui_el.and_then(|e| child(e, "margin"))),
check_size: ui_el.and_then(|e| attr_measure(e, "size")).filter(|s| *s > 0.0),
check_round: ui_el.is_some_and(|e| e.attribute("shape") == Some("round")),
- multiline: ui_el.is_some_and(|e| e.attribute("multiLine").is_some_and(|m| m == "1" || m == "true")),
+ multiline,
+ no_scroll: ui_el.is_some_and(|e| e.attribute(if multiline { "vScrollPolicy" } else { "hScrollPolicy" }) == Some("off")),
caption: parse_caption(child(n, "caption"), warnings),
value: parse_value(value_el, warnings),
items,
diff --git a/crates/xfa/src/pdf.rs b/crates/xfa/src/pdf.rs
index 8e0c47d..fd80949 100644
--- a/crates/xfa/src/pdf.rs
+++ b/crates/xfa/src/pdf.rs
@@ -8,9 +8,9 @@ use pdfcraft_cos::{Dict, Document, ObjRef, Object, PdfString, Stream};
use pdfcraft_fonts::{literal, win_ansi};
use crate::XfaError;
-use crate::layout::{Action, BorderShape, Form, Item, Page, Widget, WidgetKind};
+use crate::layout::{Action, BorderShape, Form, Item, Page, Rounded, Widget, WidgetKind};
use crate::model::Rect;
-use crate::text::{Face, Family};
+use crate::text::{Face, Family, Span};
/// Private key on generated fields: the template's SOM path, so data can be put back.
pub const SOM_KEY: &[u8] = b"PCSom";
@@ -129,6 +129,77 @@ fn all_faces() -> Vec<(&'static str, &'static str)> {
out
}
+/// The content that draws rounded box `r` on a page `page_h` tall: its fill along its curves,
+/// then its edge inside it. A side a page break cut has no edge.
+pub(crate) fn rounded(r: &Rounded, page_h: f64) -> String {
+ let mut c = String::new();
+ if let Some(color) = r.fill {
+ c.push_str(&format!("{} rg {}f\n", rgb(color), outline(r.rect, r.radii, r.inverted, (false, false), page_h)));
+ }
+ if let Some((w, color, dashed)) = r.edge {
+ // The edge's centre line, half its width inside the box, so the edge stays in: a corner
+ // curving around the box tightens by as much, and one curving into it widens.
+ let inset = Rect::new(r.rect.x + w / 2.0, r.rect.y + w / 2.0, (r.rect.w - w).max(0.0), (r.rect.h - w).max(0.0));
+ let most = inset.w.min(inset.h) / 2.0;
+ let radii: [f64; 4] = std::array::from_fn(|i| match (r.radii[i], r.inverted[i]) {
+ (v, _) if v <= 0.0 => 0.0,
+ (v, true) => (v + w / 2.0).min(most),
+ (v, false) => (v - w / 2.0).clamp(0.0, most),
+ });
+ let path = outline(inset, radii, r.inverted, (r.open_top, r.open_bottom), page_h);
+ c.push_str(&format!("q {} RG {} w {}{path}S Q\n", rgb(color), n(w), if dashed { "[2 2] 0 d " } else { "" }));
+ }
+ c
+}
+
+/// The path around `rect` (top-left based, on a page `page_h` tall) with the corners `radii`
+/// (top-left, top-right, bottom-right, bottom-left), each curving around the box or, when
+/// `inverted`, into it. `open` leaves out the top or bottom side (and doesn't close the path):
+/// those are where a page break cut the box. Ends with a space, for the paint operator.
+fn outline(rect: Rect, radii: [f64; 4], inverted: [bool; 4], open: (bool, bool), page_h: f64) -> String {
+ let (x0, y0, x1, y1) = (rect.x, rect.y, rect.right(), rect.bottom());
+ let pt = |q: (f64, f64)| format!("{} {}", n(q.0), n(page_h - q.1));
+ // Corner `i`: its point, then where its curve starts and ends, going clockwise.
+ let corner = |i: usize| {
+ let r = radii.get(i).copied().unwrap_or(0.0);
+ match i {
+ 0 => ((x0, y0), (x0, y0 + r), (x0 + r, y0)),
+ 1 => ((x1, y0), (x1 - r, y0), (x1, y0 + r)),
+ 2 => ((x1, y1), (x1, y1 - r), (x1 - r, y1)),
+ _ => ((x0, y1), (x0 + r, y1), (x0, y1 - r)),
+ }
+ };
+ // Corner `i`'s curve, from its start: a quarter circle as one Bézier curve.
+ let curve = |i: usize| {
+ if radii.get(i).copied().unwrap_or(0.0) <= 0.0 {
+ return String::new();
+ }
+ let (p, a, b) = corner(i);
+ const K: f64 = 0.5523;
+ let (c1, c2) = if inverted.get(i).copied().unwrap_or(false) {
+ // Centred on the corner itself.
+ ((a.0 + (b.0 - p.0) * K, a.1 + (b.1 - p.1) * K), (b.0 + (a.0 - p.0) * K, b.1 + (a.1 - p.1) * K))
+ } else {
+ ((a.0 + (p.0 - a.0) * K, a.1 + (p.1 - a.1) * K), (b.0 + (p.0 - b.0) * K, b.1 + (p.1 - b.1) * K))
+ };
+ format!("{} {} {} c ", pt(c1), pt(c2), pt(b))
+ };
+ // Along corners `from`, joining them with straight sides.
+ let along = |from: &[usize]| {
+ let mut s = String::new();
+ for &i in from {
+ s.push_str(&format!("{} l {}", pt(corner(i).1), curve(i)));
+ }
+ s
+ };
+ match open {
+ (false, false) => format!("{} m {}{}{}{}h ", pt(corner(0).1), curve(0), along(&[1]), along(&[2]), along(&[3])),
+ (true, false) => format!("{} m {}{} l ", pt((x1, y0)), along(&[2, 3]), pt((x0, y0))),
+ (false, true) => format!("{} m {}{} l ", pt((x0, y1)), along(&[0, 1]), pt((x1, y1))),
+ (true, true) => format!("{} m {} l {} m {} l ", pt((x0, y0)), pt((x0, y1)), pt((x1, y0)), pt((x1, y1))),
+ }
+}
+
/// A PDF appearance-state name for a check button's on value.
fn state_name(on: &str) -> String {
let s: String = on.trim().chars().map(|c| if c.is_whitespace() || "()<>[]{}/%#".contains(c) || c.is_control() { '_' } else { c }).collect();
@@ -150,16 +221,27 @@ fn js_action(js: &str) -> Object {
Object::Dict(a)
}
+/// What laying a form out says when it took the usage rights off (see [`drop_usage_rights`]).
+pub(crate) const USAGE_RIGHTS_REMOVED: &str =
+ "the form's usage rights were removed: laying it out voids them, and a form with void usage rights can open with every field locked";
+
pub struct Written {
pub pages: usize,
pub fields: usize,
pub warnings: Vec<String>,
+ /// Usage rights were taken off the catalog (laying the form out voided them).
+ pub usage_rights: bool,
}
/// On a push button generated for an XFA image field: clicking it picks a picture (the forms
/// layer reads this key).
pub const IMAGE_FIELD_KEY: &[u8] = b"PCXfaImage";
+/// On a check box or radio button generated for a round XFA check button (`shape="round"`): its
+/// background and border are drawn as a circle, not the widget's rectangle (the forms layer
+/// reads this key).
+pub const ROUND_KEY: &[u8] = b"PCXfaRound";
+
/// On an image XObject written for a picture: the SHA-256 (hex) of the picture's bytes. A
/// re-layout (after every script event) finds the XObjects on the pages it replaces by this,
/// and reuses them instead of decoding and embedding the same picture again. Nothing is kept
@@ -244,6 +326,8 @@ impl Emitter<'_> {
format!("/{} {} Tf {} rg", face.resource_name(), n(face.size), rgb(face.color)).into_bytes()
}
+ /// Write laid-out widget `w` on `page` as an AcroForm widget annotation (and its field), with
+ /// its border, background and kind, and return the annotation's object.
fn widget(&mut self, w: &Widget, page: &Page, page_ref: ObjRef) -> Result<Option<ObjRef>, XfaError> {
let r = w.rect;
let (x0, y0, x1, y1) = (r.x, page.height - r.bottom(), r.right(), page.height - r.y);
@@ -271,6 +355,9 @@ impl Emitter<'_> {
bs.set(b"W".to_vec(), Object::Real(if w.border.shape == BorderShape::None { 0.0 } else { w.border.width.clamp(0.1, 12.0) }));
bs.set(b"S".to_vec(), Object::name(if w.border.shape == BorderShape::Underline { "U" } else { "S" }));
d.set(b"BS".to_vec(), Object::Dict(bs));
+ if matches!(w.kind, WidgetKind::CheckBox { round: true, .. } | WidgetKind::Radio { round: true, .. }) {
+ d.set(ROUND_KEY.to_vec(), Object::Bool(true));
+ }
let mut ff: i64 = 0;
if w.read_only {
ff |= 1;
@@ -285,6 +372,10 @@ impl Emitter<'_> {
if w.kind == WidgetKind::Password {
ff |= 1 << 13;
}
+ // DoNotScroll (ISO 32000-2 Table 228): the field takes no more than it shows.
+ if w.no_scroll {
+ ff |= 1 << 23;
+ }
if let Some(m) = w.max_chars {
d.set(b"MaxLen".to_vec(), Object::Int(m.min(100_000) as i64));
}
@@ -574,8 +665,8 @@ impl Emitter<'_> {
}
/// Write one laid-out page under `pages_ref`: its fills, lines, text and pictures in a
- /// content stream, the fonts and images it uses as resources, and its widgets as
- /// annotations. Returns the page object.
+ /// content stream, the fonts and images it uses as resources, and its widgets and the links
+ /// in its text as annotations. Returns the page object.
fn page(&mut self, page: &Page, pages_ref: ObjRef) -> Result<ObjRef, XfaError> {
let page_ref = self.doc.add(Object::Dict(Dict::new()));
let mut content: Vec<u8> = Vec::new();
@@ -583,11 +674,27 @@ impl Emitter<'_> {
let mut xobjects = Dict::new();
let mut annots = Vec::new();
let h = page.height;
+ // The link the text before ended in, which a next piece of it on the line widens.
+ let mut last_link: Option<LinkPiece> = None;
for (i, item) in page.items.iter().enumerate() {
+ // A link's pieces join only across text and the underline drawn just before it: a fill,
+ // picture, field or any other line (a rule) between them ends the link there.
+ let keeps_link = match item {
+ Item::Text(_) => true,
+ Item::Line { from, to, .. } => matches!(page.items.get(i + 1), Some(Item::Text(s))
+ if (from.1 - to.1).abs() < 0.01
+ && (from.0 - s.x).abs() < 0.01
+ && (from.1 - (s.baseline + s.face.size * crate::layout::UNDERLINE_DROP)).abs() < 0.01),
+ _ => false,
+ };
+ if !keeps_link {
+ last_link = None;
+ }
match item {
Item::Fill { rect, color } => {
content.extend(format!("{} rg {} {} {} {} re f\n", rgb(*color), n(rect.x), n(h - rect.bottom()), n(rect.w), n(rect.h)).bytes());
}
+ Item::Rounded(r) => content.extend(rounded(r, h).bytes()),
Item::Line { from, to, width, color, dashed } => {
content.extend(
format!(
@@ -629,6 +736,9 @@ impl Emitter<'_> {
);
content.extend(literal(&win_ansi(&s.text)));
content.extend_from_slice(format!(" Tj{close}\n").as_bytes());
+ if let Some(r) = self.text_link(s, h, page_ref, &mut last_link)? {
+ annots.push(Object::Ref(r));
+ }
}
Item::Image { rect, data, content_type } => {
let Some(r) = self.image_xobject(data, content_type) else { continue };
@@ -668,6 +778,108 @@ impl Emitter<'_> {
self.doc.set(page_ref, Object::Dict(pd));
Ok(page_ref)
}
+
+ /// A link annotation over span `s` (on a page `page_height` tall), when its text links
+ /// somewhere: over the text it draws, without the spaces around it, and opening its address.
+ /// A span that goes on the link `last` ended in, on the same line, widens that annotation
+ /// instead (a link whose text changes style partway is one link). An address PdfCraft
+ /// wouldn't open from a document leaves the text as plain text, with one warning for the form.
+ fn text_link(&mut self, s: &Span, page_height: f64, page_ref: ObjRef, last: &mut Option<LinkPiece>) -> Result<Option<ObjRef>, XfaError> {
+ let piece = self.link_piece(s, page_height);
+ let Some((target, rect)) = piece else {
+ *last = None;
+ return Ok(None);
+ };
+ if let Some(prev) = last.as_mut()
+ && prev.uri == target
+ && (prev.baseline - s.baseline).abs() < 0.01
+ && (-0.01..=s.face.size).contains(&(rect[0] - prev.rect[2]))
+ {
+ prev.rect = [prev.rect[0].min(rect[0]), prev.rect[1].min(rect[1]), prev.rect[2].max(rect[2]), prev.rect[3].max(rect[3])];
+ let r = prev.rect;
+ self.doc.update_dict(prev.annot, |d| d.set(b"Rect".to_vec(), Object::Array(r.iter().map(|v| Object::Real(*v)).collect())))?;
+ return Ok(None);
+ }
+ let mut action = Dict::new();
+ action.set(b"S".to_vec(), Object::name("URI"));
+ action.set(b"URI".to_vec(), Object::String(PdfString::literal(target.as_bytes().to_vec())));
+ let mut d = Dict::new();
+ d.set(b"Type".to_vec(), Object::name("Annot"));
+ d.set(b"Subtype".to_vec(), Object::name("Link"));
+ d.set(b"Rect".to_vec(), Object::Array(rect.iter().map(|v| Object::Real(*v)).collect()));
+ d.set(b"P".to_vec(), Object::Ref(page_ref));
+ d.set(b"F".to_vec(), Object::Int(4));
+ d.set(b"Border".to_vec(), Object::Array(vec![Object::Int(0), Object::Int(0), Object::Int(0)]));
+ d.set(b"A".to_vec(), Object::Dict(action));
+ let annot = self.doc.add(Object::Dict(d));
+ *last = Some(LinkPiece { annot, uri: target, baseline: s.baseline, rect });
+ Ok(Some(annot))
+ }
+
+ /// Where span `s` links to and the rectangle (PDF user space, on a page `page_height` tall)
+ /// over the text it draws, without the spaces around it. `None` for text that links nowhere,
+ /// draws nothing, or links to an address PdfCraft wouldn't open from a document, which is
+ /// warned about once for the form.
+ fn link_piece(&mut self, s: &Span, page_height: f64) -> Option<(String, [f64; 4])> {
+ let href = s.link.as_deref()?;
+ let shown = s.text.trim();
+ if shown.is_empty() {
+ return None;
+ }
+ let Some(target) = link_target(href) else {
+ if !self.warnings.iter().any(|w| w.starts_with(LINK_LEFT_OUT)) {
+ self.warnings.push(format!("{LINK_LEFT_OUT}: PdfCraft makes links only of web (http, https) and email (mailto) addresses"));
+ }
+ return None;
+ };
+ let lead = s.text.len() - s.text.trim_start().len();
+ let x = s.x + s.face.width(s.text.get(..lead).unwrap_or_default());
+ let w = s.face.width(shown);
+ // The text's ascent and descent, as the layout measures a span's extent.
+ let rect = pdf_rect(Rect::new(x, s.baseline - s.face.size * 0.8, w, s.face.size), page_height);
+ (rect.iter().all(|v| v.is_finite()) && w > 0.0).then(|| (target.to_string(), rect))
+ }
+}
+
+/// The link annotation a page's text last ended in: the next piece of the same link on the same
+/// line widens it.
+struct LinkPiece {
+ annot: ObjRef,
+ uri: String,
+ baseline: f64,
+ rect: [f64; 4],
+}
+
+/// How the layout warning about a link left out starts.
+const LINK_LEFT_OUT: &str = "a link in the form's text was left as plain text";
+
+/// The longest link address kept, in characters: as long as PdfCraft opens from a document.
+const MAX_LINK: usize = 2048;
+
+/// `href` as the address of a link PdfCraft makes from a form's text: a web (http, https) or
+/// email (mailto) address, trimmed, of at most [`MAX_LINK`] characters and without control
+/// characters. `None` for anything else (scripts, files, data, relative paths). Opening it still
+/// goes through the app's own checks and prompt.
+fn link_target(href: &str) -> Option<&str> {
+ let href = href.trim();
+ if href.is_empty() || href.chars().count() > MAX_LINK || href.chars().any(char::is_control) {
+ return None;
+ }
+ let (scheme, rest) = href.split_once(':')?;
+ let web = scheme.eq_ignore_ascii_case("http") || scheme.eq_ignore_ascii_case("https");
+ let ok = if web { rest.strip_prefix("//").is_some_and(has_host) } else { scheme.eq_ignore_ascii_case("mailto") && !rest.is_empty() };
+ ok.then_some(href)
+}
+
+/// Whether `after` (a web address past its `//`) names a host: what comes before the path (which a
+/// backslash starts too, as web addresses read it), query or fragment, past any user name and
+/// before any port, isn't empty.
+fn has_host(after: &str) -> bool {
+ let authority = after.split(['/', '\\', '?', '#']).next().unwrap_or_default();
+ let host = authority.rsplit('@').next().unwrap_or_default();
+ // An IPv6 host is bracketed and holds colons of its own.
+ let host = if host.starts_with('[') { host } else { host.split(':').next().unwrap_or_default() };
+ !host.is_empty()
}
/// Replace the document's pages with the laid-out form and add its fields to the AcroForm. The
@@ -769,6 +981,13 @@ pub fn write_form(doc: &mut Document, form: &Form) -> Result<Written, XfaError>
z.set(b"BaseFont".to_vec(), Object::name("ZapfDingbats"));
dr_fonts.set(b"ZaDb".to_vec(), Object::Dict(z));
}
+ // Each font its own object: Acrobat shows nothing in a text field it redraws after typing
+ // when the field's /DR font is a dictionary written inline (#3441).
+ let inline: Vec<(Vec<u8>, Dict)> = dr_fonts.iter().filter_map(|(k, v)| Some((k.clone(), v.as_dict()?.clone()))).collect();
+ for (name, font) in inline {
+ let r = doc.add(Object::Dict(font));
+ dr_fonts.set(name, Object::Ref(r));
+ }
dr.set(b"Font".to_vec(), Object::Dict(dr_fonts));
acro.set(b"DR".to_vec(), Object::Dict(dr));
if !acro.contains(b"DA") {
@@ -786,10 +1005,12 @@ pub fn write_form(doc: &mut Document, form: &Form) -> Result<Written, XfaError>
catalog_changed = true;
}
}
- if catalog_changed {
+ // The pages and fields are new: usage rights signed over the form as it was are void now.
+ let usage_rights = drop_usage_rights(doc, &mut catalog);
+ if catalog_changed || usage_rights {
doc.set(catalog_ref, Object::Dict(catalog));
}
- Ok(Written { pages: count, fields: field_count, warnings })
+ Ok(Written { pages: count, fields: field_count, warnings, usage_rights })
}
/// What [`strip`] took out, for the user to be told (the packets held more than the fields).
@@ -975,27 +1196,14 @@ pub fn strip(doc: &mut Document) -> Result<Stripped, XfaError> {
None => catalog.set(b"AcroForm".to_vec(), Object::Dict(acro)),
}
catalog.remove(b"NeedsRendering");
- // Reader usage rights are void once the form changed: Reader says so on opening the file
- // and drops them, so they go now, with a note.
- if let Some(perms) = catalog.get(b"Perms").map(|p| doc.resolve(p))
- && let Some(mut perms) = perms.as_dict().cloned()
- && (perms.contains(b"UR3") || perms.contains(b"UR"))
- {
- perms.remove(b"UR3");
- perms.remove(b"UR");
- out.usage_rights = true;
- if perms.is_empty() {
- catalog.remove(b"Perms");
- } else {
- catalog.set(b"Perms".to_vec(), Object::Dict(perms));
- }
- }
+ out.usage_rights = drop_usage_rights(doc, &mut catalog);
doc.set(root, Object::Dict(catalog));
// The packet streams are referenced from nowhere else: freed, so an incremental save
// doesn't carry an unreachable copy of the data.
for r in streams {
doc.free(r);
}
+ doc.require_full_save();
Ok(out)
}
@@ -1036,6 +1244,28 @@ fn unbound_data(doc: &Document) -> Option<usize> {
Some(count)
}
+/// Take the usage rights (`/Perms /UR3`, or the older `/UR`) off a catalog, keeping the rest of
+/// `/Perms` (a certification's `/DocMDP`). They are signed over the form as it was: once its
+/// pages or fields change they are void, and a viewer may lock every field of a form whose
+/// usage rights are void, so they go, and the caller says so. Whether there were any.
+fn drop_usage_rights(doc: &mut Document, catalog: &mut Dict) -> bool {
+ let Some(entry) = catalog.get(b"Perms").cloned() else { return false };
+ let Some(mut perms) = doc.resolve(&entry).as_dict().cloned() else { return false };
+ if !perms.contains(b"UR3") && !perms.contains(b"UR") {
+ return false;
+ }
+ perms.remove(b"UR3");
+ perms.remove(b"UR");
+ match entry.as_ref() {
+ _ if perms.is_empty() => {
+ catalog.remove(b"Perms");
+ }
+ Some(r) => doc.set(r, Object::Dict(perms)),
+ None => catalog.set(b"Perms".to_vec(), Object::Dict(perms)),
+ }
+ true
+}
+
/// The layout a document already carries from an earlier pass, if any.
pub fn existing_layout(doc: &Document) -> Option<crate::Report> {
let root = doc.root()?;
diff --git a/crates/xfa/src/picture.rs b/crates/xfa/src/picture.rs
new file mode 100644
index 0000000..3ddb392
--- /dev/null
+++ b/crates/xfa/src/picture.rs
@@ -0,0 +1,65 @@
+//! Picture clauses that list alternatives (`date{YYYYMMDD}|date{YYMMDD}`): a date may be typed
+//! by any of them, and is shown, and kept in the field, by the first.
+
+use crate::data::{date_letters, iso_to_pattern, pattern_to_iso, template_field};
+use crate::layout::date_pattern;
+use crate::model::{Template, Ui};
+
+/// The alternatives of a picture clause: its parts between `|`s that aren't inside braces or
+/// quotes.
+pub(crate) fn alternatives(picture: &str) -> Vec<&str> {
+ let mut out = Vec::new();
+ let (mut depth, mut quoted, mut start) = (0usize, false, 0);
+ for (i, c) in picture.char_indices() {
+ match c {
+ '\'' => quoted = !quoted,
+ '{' if !quoted => depth = depth.saturating_add(1),
+ '}' if !quoted => depth = depth.saturating_sub(1),
+ '|' if !quoted && depth == 0 => {
+ out.extend(picture.get(start..i));
+ start = i + 1;
+ }
+ _ => {}
+ }
+ }
+ out.extend(picture.get(start..));
+ out
+}
+
+/// `text` typed into the date field at `som` by one of its edit picture's alternatives after the
+/// first, written in the first, which the field shows and checks typed dates against (`261018`
+/// becomes `20261018` for `date{YYYYMMDD}|date{YYMMDD}`). A pattern reads the text only when the
+/// date it gives, written in that pattern, is the text again, and only date clauses count. `None`
+/// when the field isn't a date field with alternatives, the first pattern reads the text, no
+/// other does, or the first pattern can't hold the date (a two-digit year for 1901).
+pub fn typed_date(tpl: &Template, som: &str, text: &str) -> Option<String> {
+ let f = template_field(tpl, som)?;
+ if f.ui != Ui::DateTimeEdit {
+ return None;
+ }
+ let picture = f.picture.as_deref()?;
+ let reads = |pattern: &str| pattern_to_iso(text, pattern).filter(|iso| iso_to_pattern(iso, pattern).eq_ignore_ascii_case(text.trim()));
+ let first = date_pattern(Some(picture));
+ if reads(&first).is_some() {
+ return None;
+ }
+ // The first later date pattern that reads the text and gives a date the first pattern keeps:
+ // written in the first, it must read back as the same date (a two-digit year can't hold 1901
+ // or 1203), else the next pattern is tried.
+ alternatives(picture).into_iter().skip(1).filter(|a| is_date_clause(a)).filter_map(date_letters).find_map(|p| {
+ let iso = reads(&p)?;
+ let shown = iso_to_pattern(&iso, &first);
+ (pattern_to_iso(&shown, &first).as_deref() == Some(iso.as_str())).then_some(shown)
+ })
+}
+
+/// Whether picture clause `clause` is a date pattern: a `date{…}` clause (with or without a
+/// locale, `date(en_US){…}`), or a bare pattern, which a date field reads as a date. A clause of
+/// another category (`text{…}`, `num{…}`, `time{…}`) is not, whatever its letters.
+fn is_date_clause(clause: &str) -> bool {
+ let clause = clause.trim();
+ match clause.find(['{', '(']) {
+ Some(i) => clause.get(..i).is_some_and(|category| category.trim().eq_ignore_ascii_case("date")),
+ None => true,
+ }
+}
diff --git a/crates/xfa/src/script.rs b/crates/xfa/src/script.rs
index cb555dc..80fb1db 100644
--- a/crates/xfa/src/script.rs
+++ b/crates/xfa/src/script.rs
@@ -7,7 +7,7 @@ use std::collections::{BTreeMap, HashMap};
use pdfcraft_cos::{Dict, Document, Object, PdfString};
use crate::data::{DataNode, data_path, parse_datasets};
-use crate::model::*;
+use crate::model::{Access, Field, Node, Presence, Script, SomIndices, Template};
use crate::{Report, XfaError};
/// Private key on the AcroForm: presence scripts set, by SOM path.
@@ -586,12 +586,44 @@ pub fn rerender(doc: &mut Document, tpl: &Template) -> Result<Report, XfaError>
if form.pages.is_empty() {
return Err(XfaError::Malformed("the template laid out to no pages".into()));
}
- // The AcroForm keeps only the fields PdfCraft did not generate.
+ // The AcroForm keeps only the fields PdfCraft did not generate. Any generated fields edited in
+ // this overlay (along with their appearance streams and widget kids) are freed so a replaced
+ // password widget's value or masked appearance cannot stay in the overlay.
let Some(root) = doc.root() else { return Err(XfaError::NotXfa) };
if let Some((acro_ref, mut acro)) = acroform(doc) {
let fields = acro.get(b"Fields").map(|f| doc.resolve(f)).and_then(|f| f.as_array().cloned()).unwrap_or_default();
- let kept: Vec<Object> =
- fields.into_iter().filter(|f| f.as_ref().is_none_or(|r| doc.get(r).as_dict().is_none_or(|d| !d.contains(crate::pdf::SOM_KEY)))).collect();
+ let mut kept = Vec::new();
+ let free_ap = |doc: &mut Document, d: &Dict| {
+ if let Some(ap) = d.get(b"AP").map(|a| doc.resolve(a)).and_then(|a| a.as_dict().cloned())
+ && let Some(n) = ap.get(b"N").and_then(Object::as_ref)
+ && doc.is_edited(n.num)
+ {
+ doc.free(n);
+ }
+ };
+ for f in fields {
+ if let Some(r) = f.as_ref()
+ && let Some(d) = doc.get(r).as_dict().cloned()
+ && d.contains(crate::pdf::SOM_KEY)
+ {
+ free_ap(doc, &d);
+ if let Some(kids) = d.get(b"Kids").map(|k| doc.resolve(k)).and_then(|k| k.as_array().cloned()) {
+ for k in kids.iter().filter_map(Object::as_ref) {
+ if let Some(kd) = doc.get(k).as_dict().cloned() {
+ free_ap(doc, &kd);
+ }
+ if doc.is_edited(k.num) {
+ doc.free(k);
+ }
+ }
+ }
+ if doc.is_edited(r.num) {
+ doc.free(r);
+ }
+ } else {
+ kept.push(f);
+ }
+ }
acro.set(b"Fields".to_vec(), Object::Array(kept));
match acro_ref {
Some(r) => doc.set(r, Object::Dict(acro)),
@@ -601,6 +633,9 @@ pub fn rerender(doc: &mut Document, tpl: &Template) -> Result<Report, XfaError>
let written = crate::pdf::write_form(doc, &form)?;
let mut warnings = form.warnings;
warnings.extend(written.warnings);
+ if written.usage_rights {
+ warnings.push(crate::pdf::USAGE_RIGHTS_REMOVED.into());
+ }
warnings.dedup();
Ok(Report { pages: written.pages, fields: written.fields, template_bytes: packets.xdp.len(), warnings })
}
diff --git a/crates/xfa/src/tests.rs b/crates/xfa/src/tests.rs
index 411529b..cb106de 100644
--- a/crates/xfa/src/tests.rs
+++ b/crates/xfa/src/tests.rs
@@ -1,6 +1,6 @@
use std::sync::Arc;
-use pdfcraft_cos::{Document, Object, SaveOptions, write_incremental};
+use pdfcraft_cos::{Dict, Document, Object, SaveOptions, write_incremental};
use super::*;
use crate::data::{
@@ -324,6 +324,12 @@ fn rendering_into_the_pdf_replaces_the_placeholder_page_and_adds_fields() {
let dr = doc.resolve(acro.get(b"DR").unwrap());
let fonts = doc.resolve(dr.as_dict().unwrap().get(b"Font").unwrap());
assert!(fonts.as_dict().unwrap().contains(b"Cour") && fonts.as_dict().unwrap().contains(b"ZaDb"));
+ // Each one its own object: Acrobat shows nothing in a text field it redraws after typing
+ // when the /DR font is written inline (#3441).
+ for (name, font) in fonts.as_dict().unwrap().iter() {
+ let r = font.as_ref().unwrap_or_else(|| panic!("{} is an object", String::from_utf8_lossy(name)));
+ assert_eq!(doc.get(r).as_dict().and_then(|f| f.name(b"Type")), Some(&b"Font"[..]));
+ }
// A field carries its SOM path for data round trips.
let first = doc.resolve(&doc.resolve(acro.get(b"Fields").unwrap()).as_array().unwrap()[0]);
assert!(first.as_dict().unwrap().contains(SOM_KEY));
@@ -350,6 +356,262 @@ fn form_text_the_standard_fonts_cannot_draw_is_reported() {
assert!(!render_into(&mut doc).unwrap().warnings.iter().any(|w| w.contains("standard fonts")));
}
+/// A field whose ui doesn't scroll in the direction its text runs out (`hScrollPolicy="off"` for
+/// one line, `vScrollPolicy="off"` for several) is written with DoNotScroll (`/Ff` bit 24), so it
+/// takes no more text than it shows; the other direction's policy, or the default, doesn't.
+#[test]
+fn fields_that_dont_scroll_are_written_with_do_not_scroll() {
+ let field = |name: &str, ui: &str| format!(r#"<field name="{name}" w="2in" h="0.4in"><ui>{ui}</ui></field>"#);
+ let xdp = format!(
+ r##"<?xml version="1.0" encoding="UTF-8"?>
+<xdp:xdp xmlns:xdp="http://ns.adobe.com/xdp/"><template xmlns="http://www.xfa.org/schema/xfa-template/3.3/"><subform name="form" layout="tb">
+{}{}{}{}{}{}{}
+</subform></template></xdp:xdp>"##,
+ field("line", r#"<textEdit hScrollPolicy="off"/>"#),
+ field("lines", r#"<textEdit multiLine="1" vScrollPolicy="off"/>"#),
+ field("number", r#"<numericEdit hScrollPolicy="off"/>"#),
+ field("when", r#"<dateTimeEdit hScrollPolicy="off"/>"#),
+ field("linesAcross", r#"<textEdit multiLine="1" hScrollPolicy="off"/>"#),
+ field("lineDown", r#"<textEdit vScrollPolicy="off"/>"#),
+ field("free", r#"<textEdit/>"#),
+ );
+ let mut doc = Document::open(Arc::new(shell(&xdp))).unwrap();
+ render_into(&mut doc).unwrap();
+ let catalog = doc.get(doc.root().unwrap());
+ let acro = doc.resolve(catalog.as_dict().unwrap().get(b"AcroForm").unwrap());
+ let fields = doc.resolve(acro.as_dict().unwrap().get(b"Fields").unwrap()).as_array().unwrap().clone();
+ let mut no_scroll = std::collections::BTreeMap::new();
+ for r in fields.iter().filter_map(Object::as_ref) {
+ let f = doc.get(r);
+ let d = f.as_dict().unwrap();
+ let name = d.get(b"T").and_then(Object::as_string).map(|t| t.to_text()).unwrap_or_default();
+ no_scroll.insert(name, d.int(b"Ff").unwrap_or(0) & (1 << 23) != 0);
+ }
+ let expected: std::collections::BTreeMap<String, bool> =
+ [("line", true), ("lines", true), ("number", true), ("when", true), ("linesAcross", false), ("lineDown", false), ("free", false)]
+ .into_iter()
+ .map(|(n, v)| (n.to_string(), v))
+ .collect();
+ assert_eq!(no_scroll, expected);
+}
+
+/// A check box or radio button laid out from a round check button (`shape="round"`) carries
+/// `ROUND_KEY`, so the forms layer draws its background and border round; a square one (the
+/// default) doesn't.
+#[test]
+fn round_check_buttons_are_marked_for_a_round_appearance() {
+ let check = |name: &str, shape: &str, items: &str| {
+ format!(r#"<field name="{name}" w="1in" h="0.3in"><ui><checkButton{shape}/></ui><items>{items}</items></field>"#)
+ };
+ let on_off = "<integer>1</integer><integer>0</integer>";
+ let xdp = format!(
+ r##"<?xml version="1.0" encoding="UTF-8"?>
+<xdp:xdp xmlns:xdp="http://ns.adobe.com/xdp/"><template xmlns="http://www.xfa.org/schema/xfa-template/3.3/"><subform name="form" layout="tb">
+{}{}<exclGroup name="pick" layout="tb">{}{}</exclGroup>
+</subform></template></xdp:xdp>"##,
+ check("roundBox", r#" shape="round""#, on_off),
+ check("squareBox", "", on_off),
+ check("roundRadio", r#" shape="round""#, "<text>a</text>"),
+ check("squareRadio", r#" shape="square""#, "<text>b</text>"),
+ );
+ let mut doc = Document::open(Arc::new(shell(&xdp))).unwrap();
+ render_into(&mut doc).unwrap();
+ // Every widget among the form's fields and their kids (a radio group's buttons), by the
+ // last step of its SOM path.
+ let catalog = doc.get(doc.root().unwrap());
+ let acro = doc.resolve(catalog.as_dict().unwrap().get(b"AcroForm").unwrap());
+ let mut todo: Vec<_> =
+ doc.resolve(acro.as_dict().unwrap().get(b"Fields").unwrap()).as_array().unwrap().iter().filter_map(Object::as_ref).collect();
+ let mut round = std::collections::BTreeMap::new();
+ while let Some(r) = todo.pop() {
+ let node = doc.get(r);
+ let d = node.as_dict().unwrap();
+ if let Some(kids) = d.get(b"Kids").map(|k| doc.resolve(k)) {
+ todo.extend(kids.as_array().unwrap().iter().filter_map(Object::as_ref));
+ continue;
+ }
+ let som = d.get(SOM_KEY).and_then(Object::as_string).map(|s| s.to_text()).unwrap_or_default();
+ let name = som.rsplit('.').next().unwrap_or_default().split('[').next().unwrap_or_default().to_string();
+ round.insert(name, matches!(d.get(crate::pdf::ROUND_KEY), Some(Object::Bool(true))));
+ }
+ let expected: std::collections::BTreeMap<String, bool> = [("roundBox", true), ("squareBox", false), ("roundRadio", true), ("squareRadio", false)]
+ .into_iter()
+ .map(|(n, r)| (n.to_string(), r))
+ .collect();
+ assert_eq!(round, expected);
+}
+
+/// A template whose one draw holds `body` as rich text, in a box `w` wide.
+fn rich_draw_form(w: &str, body: &str) -> String {
+ format!(
+ r##"<?xml version="1.0" encoding="UTF-8"?>
+<xdp:xdp xmlns:xdp="http://ns.adobe.com/xdp/"><template xmlns="http://www.xfa.org/schema/xfa-template/3.3/"><subform name="form" layout="tb">
+ <pageSet><pageArea name="page"><contentArea x="0.5in" y="0.5in" w="7.5in" h="10in"/><medium short="8.5in" long="11in"/></pageArea></pageSet>
+ <draw name="note" w="{w}"><font typeface="Arial" size="10pt"/><value><exData contentType="text/html"><body xmlns="http://www.w3.org/1999/xhtml"><p>{body}</p></body></exData></value></draw>
+</subform></template></xdp:xdp>"##
+ )
+}
+
+/// The link annotations on the pages of `doc`: each one's URI and rectangle.
+fn text_links(doc: &Document) -> Vec<(String, [f64; 4])> {
+ let catalog = doc.get(doc.root().unwrap());
+ let pages = doc.resolve(catalog.as_dict().unwrap().get(b"Pages").unwrap());
+ let kids = doc.resolve(pages.as_dict().unwrap().get(b"Kids").unwrap()).as_array().unwrap().clone();
+ let mut out = Vec::new();
+ for page in &kids {
+ let page = doc.resolve(page);
+ let Some(annots) = page.as_dict().unwrap().get(b"Annots").map(|a| doc.resolve(a).as_array().unwrap().clone()) else { continue };
+ for a in &annots {
+ let a = doc.resolve(a);
+ let d = a.as_dict().unwrap();
+ if d.name(b"Subtype") != Some(&b"Link"[..]) {
+ continue;
+ }
+ let action = doc.resolve(d.get(b"A").unwrap());
+ let uri =
+ action.as_dict().unwrap().get(b"URI").and_then(Object::as_string).map(|s| String::from_utf8_lossy(&s.bytes).into_owned()).unwrap();
+ let r: Vec<f64> = doc.resolve(d.get(b"Rect").unwrap()).as_array().unwrap().iter().map(|v| v.as_f64().unwrap()).collect();
+ out.push((uri, [r[0], r[1], r[2], r[3]]));
+ }
+ }
+ out
+}
+
+/// An `<a href>` in rich text keeps where it links to on every run of its text, styled or not;
+/// the text around it and a named anchor without an address link nowhere.
+#[test]
+fn rich_text_links_keep_their_address() {
+ let (tpl, _) = crate::parse(&rich_draw_form(
+ "4in",
+ r#"Write to <a href=" mailto:[email protected] ">forms@<b>example</b>.com</a> or see <a name="top">the top</a>."#,
+ ))
+ .unwrap();
+ let Node::Draw(d) = &tpl.root.children[0] else { panic!("the draw") };
+ let Value::Rich(rich) = &d.value else { panic!("rich text") };
+ let runs: Vec<(&str, Option<&str>)> = rich.paragraphs.iter().flat_map(|p| &p.runs).map(|r| (r.text.as_str(), r.link.as_deref())).collect();
+ assert_eq!(
+ runs,
+ [
+ ("Write to ", None),
+ ("forms@", Some("mailto:[email protected]")),
+ ("example", Some("mailto:[email protected]")),
+ (".com", Some("mailto:[email protected]")),
+ (" or see ", None),
+ ("the top", None),
+ (".", None),
+ ]
+ );
+}
+
+/// A link's address is held once, however many runs, words and lines its text takes: every
+/// piece shares it rather than copying it, so a long address over many words stays one string.
+#[test]
+fn a_links_pieces_share_one_address() {
+ let words = "one two three four five six seven eight nine ten ".repeat(8);
+ let href = format!("https://example.com/{}", "x".repeat(1500));
+ let xdp = rich_draw_form("2in", &format!(r#"<a href="{href}">{words}<b>bold</b> {words}</a>"#));
+ let form = layout_xml(&xdp).unwrap();
+ let links: Vec<std::sync::Arc<str>> =
+ form.pages.iter().flat_map(|p| &p.items).filter_map(|i| if let Item::Text(s) = i { s.link.clone() } else { None }).collect();
+ assert!(links.len() > 10, "the link's text takes many lines: {}", links.len());
+ assert!(links.iter().all(|l| std::sync::Arc::ptr_eq(l, &links[0]) && **l == *href), "every piece shares one address");
+}
+
+/// A link's text becomes a link annotation on the page, one over each line it takes when it
+/// wraps, each over its own text; a second layout replaces them rather than adding more.
+#[test]
+fn links_in_rich_text_become_link_annotations_one_per_line() {
+ let body = r#"See <a href="https://example.com/forms/help">the help pages for this form, which explain every block</a> first."#;
+ let mut doc = Document::open(Arc::new(shell(&rich_draw_form("2in", body)))).unwrap();
+ let report = render_into(&mut doc).unwrap();
+ assert!(report.warnings.iter().all(|w| !w.contains("link")), "{:?}", report.warnings);
+ let links = text_links(&doc);
+ assert!(links.len() >= 2, "the link wraps onto at least two lines: {links:?}");
+ assert!(links.iter().all(|(uri, _)| uri == "https://example.com/forms/help"));
+ // One per line: each below the one before, all inside the 2-inch box (from x = 36pt).
+ for pair in links.windows(2) {
+ assert!(pair[1].1[3] <= pair[0].1[1] + 0.01, "a line below the one before: {pair:?}");
+ }
+ for (_, r) in &links {
+ assert!(r[0] >= 36.0 - 0.01 && r[2] <= 36.0 + 144.0 + 0.01 && r[2] > r[0] && r[3] > r[1], "{r:?}");
+ }
+ // The first line's link starts after "See ", not at the box's edge.
+ assert!(links[0].1[0] > 36.0 + 5.0, "{:?}", links[0].1);
+ // A second layout replaces the pages, and their links with them.
+ let tpl = crate::script::template_of(&doc).unwrap();
+ rerender(&mut doc, &tpl).unwrap();
+ assert_eq!(text_links(&doc), links, "laid out again: the same links, not twice as many");
+ // Saved and opened again, they are still there.
+ let bytes = write_incremental(&doc, &SaveOptions::default()).unwrap();
+ assert_eq!(text_links(&Document::open(Arc::new(bytes)).unwrap()), links);
+
+ // A link whose text changes style partway is one link on its line, over all its text.
+ let mut doc =
+ Document::open(Arc::new(shell(&rich_draw_form("4in", r#"Write to <a href="mailto:[email protected]">forms@<b>example</b>.com</a> today."#))))
+ .unwrap();
+ render_into(&mut doc).unwrap();
+ let links = text_links(&doc);
+ assert_eq!(links.len(), 1, "{links:?}");
+ let arial = Font { typeface: "Arial".into(), size: 10.0, ..Default::default() };
+ let plain = crate::text::Face::of(&arial);
+ let bold = crate::text::Face::of(&Font { bold: true, ..arial.clone() });
+ let width = plain.width("forms@") + bold.width("example") + plain.width(".com");
+ let r = links[0].1;
+ assert!((r[2] - r[0] - width).abs() < 0.01, "over the whole address: {} against {width}", r[2] - r[0]);
+}
+
+/// Two pieces of one link side by side on a line join into one link, but a rule drawn between
+/// them keeps them apart, so the link never covers what lies between its pieces; an underline
+/// (a level line drawn with its text) doesn't.
+#[test]
+fn a_rule_between_two_pieces_of_a_link_keeps_them_apart() {
+ let piece = |name: &str, x: &str, underline: bool| {
+ let u = if underline { ";text-decoration:underline" } else { "" };
+ format!(
+ r#"<draw name="{name}" x="{x}" y="0in" w="0.4in" h="0.3in"><font typeface="Arial" size="10pt"/><value><exData contentType="text/html"><body xmlns="http://www.w3.org/1999/xhtml"><p style="margin:0{u}"><a href="https://example.com/form">Go</a></p></body></exData></value></draw>"#
+ )
+ };
+ let rule = r#"<draw name="rule" x="0.21in" y="0in" w="0in" h="0.3in"><value><line><edge/></line></value></draw>"#;
+ let level_rule = r#"<draw name="dash" x="0.2in" y="0.1in" w="0.04in" h="0in"><value><line><edge/></line></value></draw>"#;
+ let form = |between: &str, underline: bool| {
+ format!(
+ r##"<?xml version="1.0" encoding="UTF-8"?>
+<xdp:xdp xmlns:xdp="http://ns.adobe.com/xdp/"><template xmlns="http://www.xfa.org/schema/xfa-template/3.3/"><subform name="form" layout="position">
+ <pageSet><pageArea name="page"><contentArea x="0.5in" y="0.5in" w="7.5in" h="10in"/><medium short="8.5in" long="11in"/></pageArea></pageSet>
+ {}{between}{}
+</subform></template></xdp:xdp>"##,
+ piece("first", "0in", underline),
+ piece("second", "0.25in", underline)
+ )
+ };
+ let links = |xdp: &str| {
+ let mut doc = Document::open(Arc::new(shell(xdp))).unwrap();
+ render_into(&mut doc).unwrap();
+ text_links(&doc).len()
+ };
+ assert_eq!(links(&form("", false)), 1, "side by side, the pieces join");
+ assert_eq!(links(&form("", true)), 1, "an underline doesn't part them");
+ assert_eq!(links(&form(rule, false)), 2, "a rule between them does");
+ assert_eq!(links(&form(level_rule, false)), 2, "and so does a level one, which isn't an underline");
+}
+
+/// Only web and email addresses become links. Scripts, files, data, relative paths, web
+/// addresses without a host, and empty or overlong addresses stay plain text (still drawn), with
+/// one warning for the form.
+#[test]
+fn links_to_anything_but_web_and_email_addresses_stay_plain_text() {
+ let long = format!("https://example.com/{}", "a".repeat(2100));
+ let body = format!(
+ r#"<a href="javascript:app.alert(1)">one</a> <a href="file:///etc/passwd">two</a> <a href="data:text/html,x">three</a> <a href="help.html">four</a> <a href="HTTPS:">five</a> <a href="{long}">six</a> <a href="MailTo:[email protected]">seven</a> <a href="https:///path">eight</a> <a href="https://user@:8080/x">nine</a> <a href="https://\example.com/path">nine and a half</a> <a href="https://[email protected]:8443/x">ten</a>"#
+ );
+ let mut doc = Document::open(Arc::new(shell(&rich_draw_form("7in", &body)))).unwrap();
+ let report = render_into(&mut doc).unwrap();
+ assert_eq!(text_links(&doc).into_iter().map(|(u, _)| u).collect::<Vec<_>>(), ["MailTo:[email protected]", "https://[email protected]:8443/x"]);
+ let warned: Vec<&String> = report.warnings.iter().filter(|w| w.contains("link")).collect();
+ assert_eq!(warned.len(), 1, "one warning for the form: {:?}", report.warnings);
+ assert!(warned[0].contains("http, https") && warned[0].contains("mailto"), "{warned:?}");
+}
+
#[test]
fn documents_without_xfa_are_not_touched() {
let mut doc = Document::new_empty();
@@ -2021,6 +2283,8 @@ fn repeating_rows_in_a_wrapped_container_get_the_instances_the_data_holds() {
assert_eq!(form.pages.iter().flat_map(widgets).filter(|w| w.name.starts_with("what")).count(), 1);
}
+/// A multi-line field with a minimum height and no fixed one grows to hold its text, moving
+/// what follows down; one with a fixed height keeps it.
#[test]
fn a_multi_line_field_without_a_height_grows_to_hold_its_text() {
let place = |data: &str| {
@@ -2048,6 +2312,297 @@ fn a_multi_line_field_without_a_height_grows_to_hold_its_text() {
assert!((notes.rect.h - 108.0).abs() < 0.01, "{:?}", notes.rect);
}
+/// The rounded boxes laid out on `page`, in order.
+fn rounded(page: &Page) -> Vec<&crate::layout::Rounded> {
+ page.items.iter().filter_map(|i| if let Item::Rounded(r) = i { Some(r.as_ref()) } else { None }).collect()
+}
+
+/// A border or rectangle with rounded corners is one shape, filled and edged along its curves:
+/// one corner applies to all four, a corner not given repeats the last one given, a radius is at
+/// most half the box's shorter side, and inverted corners are kept. Hidden corners, and edges
+/// that differ from each other, keep the square box.
+#[test]
+fn rounded_corners_make_a_border_one_rounded_shape() {
+ let draw = |name: &str, y: f64, border: &str| {
+ format!(r#"<draw name="{name}" x="0in" y="{y}in" w="2in" h="1in"><value><text>{name}</text></value>{border}</draw>"#)
+ };
+ let body = [
+ draw("round", 0.0, r#"<border><edge thickness="1pt"><color value="255,0,0"/></edge><corner radius="0.25in"/><fill><color value="230,230,230"/></fill></border>"#),
+ draw("mixed", 1.2, r#"<border><edge/><corner radius="0.1in"/><corner radius="0.2in" inverted="1"/></border>"#),
+ draw("huge", 2.4, r#"<border><edge/><corner radius="3in"/></border>"#),
+ draw("hiddenCorner", 3.6, r#"<border><edge/><corner radius="0.25in" presence="hidden"/></border>"#),
+ draw("unlikeEdges", 4.8, r#"<border><edge/><edge presence="hidden"/><corner radius="0.25in"/></border>"#),
+ draw("fillOnly", 6.0, r#"<border><edge presence="hidden"/><corner radius="0.25in"/><fill><color value="200,200,200"/></fill></border>"#),
+ r#"<draw name="shape" x="0in" y="7.2in" w="2in" h="1in"><value><rectangle><edge thickness="0.5pt"/><corner radius="5.08mm"/></rectangle></value></draw>"#.to_string(),
+ ]
+ .concat();
+ let form = layout_xml(&one_area_form(r#"layout="tb""#, &format!(r#"<subform name="body" layout="position" w="7.5in" h="9in">{body}</subform>"#)))
+ .unwrap();
+ let shapes = rounded(&form.pages[0]);
+ let at = |y: f64| shapes.iter().copied().find(|r| (r.rect.y - 36.0 - y * 72.0).abs() < 0.01);
+ let round = at(0.0).expect("the rounded border is one shape");
+ assert_eq!((round.rect.w, round.rect.h, round.radii), (144.0, 72.0, [18.0; 4]));
+ assert_eq!((round.fill, round.edge), (Some([230.0 / 255.0; 3]), Some((1.0, [1.0, 0.0, 0.0], false))));
+ let mixed = at(1.2).expect("the box with two corners given");
+ assert_eq!((mixed.radii, mixed.inverted), ([7.2, 14.4, 14.4, 14.4], [false, true, true, true]));
+ assert_eq!(at(2.4).expect("the huge radius").radii, [36.0; 4], "at most half the shorter side");
+ assert!(at(3.6).is_none() && at(4.8).is_none(), "hidden corners and unlike edges keep a square box");
+ let fill_only = at(6.0).expect("a fill with hidden edges is rounded too");
+ assert_eq!((fill_only.fill.is_some(), fill_only.edge), (true, None));
+ let shape = at(7.2).expect("a rectangle drawn as a value");
+ assert!((shape.radii[0] - 5.08 * 72.0 / 25.4).abs() < 1e-9 && shape.edge.is_some());
+ // The square boxes are drawn as before: edges as lines.
+ let lines_at = |y: f64| {
+ form.pages[0]
+ .items
+ .iter()
+ .filter(|i| matches!(i, Item::Line { from, .. } if from.1 >= 36.0 + y * 72.0 - 1.0 && from.1 <= 36.0 + (y + 1.0) * 72.0 + 1.0))
+ .count()
+ };
+ assert_eq!((lines_at(3.6), lines_at(4.8)), (4, 2));
+}
+
+/// A rounded box a page break cuts keeps its rounded corners on each page, square where it was
+/// cut, and its edge stops there instead of closing across the cut.
+#[test]
+fn a_rounded_box_cut_by_a_page_break_keeps_its_corners_on_each_page() {
+ // A 12-inch box in a 10-inch content area: it is cut at the area's bottom.
+ let body = r#"<subform name="body" layout="tb" w="7.5in"><subform name="tall" layout="position" w="7.5in" h="12in"><border><edge/><corner radius="0.25in"/></border><draw name="note" x="0in" y="0in" w="2in" h="0.3in"><value><text>Note</text></value></draw></subform></subform>"#;
+ let form = layout_xml(&one_area_form(r#"layout="tb""#, body)).unwrap();
+ assert_eq!(form.pages.len(), 2);
+ let (first, last) = (rounded(&form.pages[0]), rounded(&form.pages[1]));
+ assert_eq!((first.len(), last.len()), (1, 1), "{first:?} {last:?}");
+ assert_eq!((first[0].radii, first[0].open_top, first[0].open_bottom), ([18.0, 18.0, 0.0, 0.0], false, true));
+ assert_eq!((last[0].radii, last[0].open_top, last[0].open_bottom), ([0.0, 0.0, 18.0, 18.0], true, false));
+ assert!((first[0].rect.h + last[0].rect.h - 12.0 * 72.0).abs() < 0.01, "the two parts make the whole box");
+}
+
+/// A rounded box is written as one path: filled along its curves, then edged half its width
+/// inside, the curves as quarter circles. An inverted corner curves into the box, and the edge
+/// of a box a page break cut doesn't close across the cut.
+#[test]
+fn rounded_boxes_are_written_as_curved_paths() {
+ use crate::layout::Rounded;
+ // A 2-by-1-inch box at the page's top left, on a page 792pt tall.
+ let shape = |inverted: [bool; 4], edge: bool, open: (bool, bool)| Rounded {
+ rect: Rect::new(36.0, 36.0, 144.0, 72.0),
+ radii: [18.0; 4],
+ inverted,
+ fill: Some([0.9, 0.9, 0.9]),
+ edge: edge.then_some((2.0, [1.0, 0.0, 0.0], false)),
+ open_top: open.0,
+ open_bottom: open.1,
+ };
+ let content = |r: Rounded| crate::pdf::rounded(&r, 792.0);
+ let ops = content(shape([false; 4], true, (false, false)));
+ // The fill: from the top-left corner's start, a quarter circle to (54, 36), closed.
+ assert!(ops.contains("0.9 0.9 0.9 rg 36 738 m 36 747.941 44.059 756 54 756 c "), "{ops}");
+ assert!(ops.contains(" h f\n"), "{ops}");
+ // The edge: 1pt inside, the corners 1pt tighter.
+ assert!(ops.contains("q 1 0 0 RG 2 w 37 738 m 37 747.389 44.611 755 54 755 c "), "{ops}");
+ assert!(ops.contains(" h S Q\n"), "{ops}");
+ // Inverted: the curve bends towards the box's inside.
+ let inv = content(shape([true; 4], false, (false, false)));
+ assert!(inv.contains("36 738 m 45.941 738 54 746.059 54 756 c "), "{inv}");
+ // Cut at the bottom: the edge runs from the bottom left round the top and back down, open.
+ let cut = content(Rounded { radii: [18.0, 18.0, 0.0, 0.0], ..shape([false; 4], true, (false, true)) });
+ let edge = cut.lines().find(|l| l.contains(" RG ")).unwrap_or_default();
+ assert!(edge.starts_with("q 1 0 0 RG 2 w 37 685 m 37 738 l ") && edge.ends_with(" 179 685 l S Q") && !edge.contains(" h "), "{edge}");
+}
+
+/// A flowed subform without a fixed height gets its border and fill round all it takes, margins
+/// included, drawn under its content; a flowed table too. One a page break cuts between its
+/// children gets a closed border round its part on each page, its bottom margin ending the first
+/// part and its top margin starting the next, as another viewer draws it on a synthetic form. One
+/// holding an item that doesn't fit on its page keeps no border, and the layout says so.
+#[test]
+fn a_flowed_subform_is_drawn_with_its_border_under_its_content() {
+ let field = |name: &str| format!(r#"<field name="{name}" w="3in" h="0.5in"><ui><textEdit/></ui></field>"#);
+ let boxed = |inner: &str| {
+ format!(
+ r#"<subform name="box" layout="tb" w="7.5in"><border><edge thickness="1pt"/><fill><color value="230,230,230"/></fill></border><margin topInset="0.1in" bottomInset="0.2in"/>{inner}</subform>"#
+ )
+ };
+ let lay = |body: &str| {
+ layout_xml(&one_area_form(r#"layout="tb""#, &format!(r#"<subform name="body" layout="tb" w="7.5in">{body}</subform>"#))).unwrap()
+ };
+ // Two half-inch fields between a tenth and a fifth of an inch of margin: 1.3in from the top.
+ let form = lay(&boxed(&(field("a") + &field("b"))));
+ let items = &form.pages[0].items;
+ let fill = items.iter().position(|i| matches!(i, Item::Fill { .. })).expect("the subform's fill");
+ let Some(Item::Fill { rect, .. }) = items.get(fill) else { panic!("item {fill} is the fill") };
+ assert!((rect.y - 36.0).abs() < 0.01 && (rect.h - 1.3 * 72.0).abs() < 0.01 && (rect.w - 540.0).abs() < 0.01, "{rect:?}");
+ assert_eq!(items.iter().filter(|i| matches!(i, Item::Line { .. })).count(), 4, "its four edges");
+ let first_widget = items.iter().position(|i| matches!(i, Item::Widget(_))).unwrap();
+ assert!(fill < first_widget, "the fill is under the fields");
+ assert!(form.warnings.is_empty(), "{:?}", form.warnings);
+ // A flowed table's border too.
+ let table = r#"<subform name="grid" layout="table" columnWidths="2in 2in" w="4in"><border><edge/></border><subform name="row" layout="row"><draw name="c1" h="0.4in"><value><text>One</text></value></draw><draw name="c2" h="0.4in"><value><text>Two</text></value></draw></subform></subform>"#;
+ let form = lay(table);
+ assert_eq!(form.pages[0].items.iter().filter(|i| matches!(i, Item::Line { .. })).count(), 4, "{:?}", form.pages[0].items);
+ // Thirty fields: 19 fit the first page after the top margin, 11 go to the second.
+ let many: String = (0..30).map(|i| field(&format!("f{i}"))).collect();
+ let form = lay(&boxed(&many));
+ assert_eq!(form.pages.len(), 2);
+ let fills = |page: usize| -> Vec<Rect> {
+ form.pages[page].items.iter().filter_map(|i| if let Item::Fill { rect, .. } = i { Some(*rect) } else { None }).collect()
+ };
+ let (first, second) = (fills(0), fills(1));
+ assert_eq!((first.len(), second.len()), (1, 1), "a part on each page");
+ // Page 1: from the top (36) past 0.1in of margin and 19 fields, then 0.2in of margin.
+ assert!((first[0].y - 36.0).abs() < 0.01 && (first[0].bottom() - (36.0 + 7.2 + 19.0 * 36.0 + 14.4)).abs() < 0.01, "{:?}", first[0]);
+ // Page 2: the top margin again, 11 fields, the bottom margin.
+ assert!((second[0].y - 36.0).abs() < 0.01 && (second[0].bottom() - (36.0 + 7.2 + 11.0 * 36.0 + 14.4)).abs() < 0.01, "{:?}", second[0]);
+ let lines = |page: usize| form.pages[page].items.iter().filter(|i| matches!(i, Item::Line { .. })).count();
+ assert_eq!((lines(0), lines(1)), (4, 4), "each part's border is closed");
+ let f19 = form.pages[1].items.iter().find_map(|i| if let Item::Widget(w) = i { (w.name == "f19").then_some(w.rect) } else { None }).unwrap();
+ assert!((f19.y - 43.2).abs() < 0.01, "the second part starts after the top margin: {}", f19.y);
+ assert!(form.warnings.is_empty(), "{:?}", form.warnings);
+ // A bottom margin that would run past the content area stops at its edge: 39 quarter-inch
+ // fields end at 738, and 0.4in more would reach 766.8, past 756.
+ let quarter: String = (0..39).map(|i| format!(r#"<field name="q{i}" w="3in" h="0.25in"><ui><textEdit/></ui></field>"#)).collect();
+ let low = format!(r#"<subform name="box" layout="tb" w="7.5in"><border><edge/><fill/></border><margin bottomInset="0.4in"/>{quarter}</subform>"#);
+ let form = lay(&low);
+ let edge = form.pages[0].items.iter().find_map(|i| if let Item::Fill { rect, .. } = i { Some(rect.bottom()) } else { None }).unwrap();
+ assert!((edge - 756.0).abs() < 0.01, "the box ends at the content area's bottom: {edge}");
+ // The margins come back without a border too.
+ let bare = format!(r#"<subform name="box" layout="tb" w="7.5in"><margin topInset="0.1in" bottomInset="0.2in"/>{many}</subform>"#);
+ let form = lay(&bare);
+ let f19 = form.pages[1].items.iter().find_map(|i| if let Item::Widget(w) = i { (w.name == "f19").then_some(w.rect) } else { None }).unwrap();
+ assert!((f19.y - 43.2).abs() < 0.01, "{}", f19.y);
+ // A text of its own longer than a page, cut across pages: no border, one warning.
+ let long = format!(
+ r#"<draw name="long" w="7in"><font typeface="Arial" size="10pt"/><value><text>{}</text></value></draw>"#,
+ "A line of the long text.\n".repeat(80)
+ );
+ let form = lay(&boxed(&(field("a") + &long)));
+ assert!(form.pages.len() >= 2, "the long text runs onto another page");
+ assert!(form.pages.iter().all(|p| !p.items.iter().any(|i| matches!(i, Item::Fill { .. }))), "no fill drawn");
+ assert_eq!(form.warnings.iter().filter(|w| w.contains("bordered section")).count(), 1, "{:?}", form.warnings);
+ // A field that fits a fresh page (720pt) but not after the 7.2pt top margin: the margin
+ // gives way, so the field ends at the content area's bottom, inside the second part.
+ let tall = r#"<field name="tall" w="3in" h="715pt"><ui><textEdit/></ui></field>"#;
+ let form = lay(&boxed(&(field("a") + tall)));
+ assert_eq!(form.pages.len(), 2);
+ let tall = form.pages[1].items.iter().find_map(|i| if let Item::Widget(w) = i { (w.name == "tall").then_some(w.rect) } else { None }).unwrap();
+ assert!(tall.bottom() <= 756.01, "the field stays in the content area: {tall:?}");
+ let part = form.pages[1].items.iter().find_map(|i| if let Item::Fill { rect, .. } = i { Some(*rect) } else { None }).expect("the second part");
+ assert!(part.y <= tall.y + 0.01 && part.bottom() >= tall.bottom() - 0.01, "the border holds the field: {part:?} {tall:?}");
+ assert!(form.warnings.is_empty(), "{:?}", form.warnings);
+ // A section that starts near a page's bottom, where its first field doesn't fit: the field
+ // moves to the next page whole, and the border starts there with it, none left behind.
+ let spacer = r#"<field name="spacer" w="3in" h="684pt"><ui><textEdit/></ui></field>"#;
+ let form = lay(&format!("{spacer}{}", boxed(&(field("a") + &field("b")))));
+ assert_eq!(form.pages.len(), 2);
+ let fills = |page: usize| -> Vec<Rect> {
+ form.pages[page].items.iter().filter_map(|i| if let Item::Fill { rect, .. } = i { Some(*rect) } else { None }).collect()
+ };
+ assert!(fills(0).is_empty(), "no border left behind on page 1: {:?}", fills(0));
+ let moved = fills(1);
+ assert!(moved.len() == 1 && (moved[0].y - 36.0).abs() < 0.01 && (moved[0].h - (7.2 + 2.0 * 36.0 + 14.4)).abs() < 0.01, "{moved:?}");
+ assert!(form.warnings.is_empty(), "{:?}", form.warnings);
+ // The same field first in the section, at the top of the page: after the section's own top
+ // margin it runs past the bottom, so the section has no border round it, and says so.
+ let form = lay(&boxed(r#"<field name="tall" w="3in" h="715pt"><ui><textEdit/></ui></field>"#));
+ assert!(form.pages.iter().all(|p| !p.items.iter().any(|i| matches!(i, Item::Fill { .. }))), "no fill drawn");
+ assert_eq!(form.warnings.iter().filter(|w| w.contains("bordered section")).count(), 1, "{:?}", form.warnings);
+}
+
+/// A flowed table a page break cuts between its rows gets a closed border round its part on
+/// each page, as a flowed subform does: its margins repeat, and its overflow leader starts the
+/// second part after the top margin.
+#[test]
+fn a_flowed_table_cut_between_its_rows_keeps_its_border_on_each_page() {
+ let row = |name: &str, text: &str| {
+ format!(
+ r#"<subform name="{name}" layout="row"><draw name="{name}a" h="0.3in"><value><text>{text}</text></value></draw><draw name="{name}b" h="0.3in"><value><text>-</text></value></draw></subform>"#
+ )
+ };
+ let rows: String = (0..40).map(|i| row(&format!("r{i}"), &format!("Row {i}"))).collect();
+ let table = format!(
+ r#"<subform name="grid" layout="table" columnWidths="2in 2in" w="4in"><border><edge/><fill><color value="230,230,230"/></fill></border><margin topInset="0.1in" bottomInset="0.2in"/><overflow leader="head"/>{}{rows}</subform>"#,
+ row("head", "Head")
+ );
+ let body = format!(r#"<subform name="body" layout="tb" w="7.5in">{table}</subform>"#);
+ let form = layout_xml(&one_area_form(r#"layout="tb""#, &body)).unwrap();
+ assert_eq!(form.pages.len(), 2);
+ let fills = |page: usize| -> Vec<Rect> {
+ form.pages[page].items.iter().filter_map(|i| if let Item::Fill { rect, .. } = i { Some(*rect) } else { None }).collect()
+ };
+ let lines = |page: usize| form.pages[page].items.iter().filter(|i| matches!(i, Item::Line { .. })).count();
+ let (first, second) = (fills(0), fills(1));
+ assert_eq!((first.len(), second.len()), (1, 1), "a part on each page");
+ assert_eq!((lines(0), lines(1)), (4, 4), "each part's border is closed");
+ // Page 1: 0.1in of margin, the leader and 32 rows of 0.3in fill the area to its bottom.
+ assert!((first[0].y - 36.0).abs() < 0.01 && (first[0].bottom() - 756.0).abs() < 0.01, "{:?}", first[0]);
+ // Page 2: the top margin again, the leader, the other 8 rows, the bottom margin.
+ assert!((second[0].y - 36.0).abs() < 0.01 && (second[0].bottom() - (36.0 + 7.2 + 9.0 * 21.6 + 14.4)).abs() < 0.01, "{:?}", second[0]);
+ let head = form.pages[1].items.iter().find_map(|i| if let Item::Text(t) = i { (t.text == "Head").then_some(t.baseline) } else { None });
+ assert!(head.is_some_and(|b| b > 43.2 && b < 64.8), "the leader starts the second part after its top margin: {head:?}");
+ assert!(form.warnings.is_empty(), "{:?}", form.warnings);
+}
+
+/// A flowed table's overflow leader and the row that moved are given room together on the new
+/// page; a leader and row too tall for any page, and a first row taller than its page, cost the
+/// table its border, with the warning, rather than a border round what runs off the page.
+#[test]
+fn a_tables_leader_and_oversized_rows_fit_its_border_or_lose_it() {
+ let row = |name: &str, h: &str| {
+ format!(r#"<subform name="{name}" layout="row"><draw name="{name}a" h="{h}"><value><text>{name}</text></value></draw></subform>"#)
+ };
+ let table = |rows: &str| {
+ format!(
+ r#"<subform name="body" layout="tb" w="7.5in"><subform name="grid" layout="table" columnWidths="3in" w="3in"><border><edge/><fill/></border><margin topInset="0.1in"/><overflow leader="head"/>{}{rows}</subform></subform>"#,
+ row("head", "0.3in")
+ )
+ };
+ let lay = |rows: &str| layout_xml(&one_area_form(r#"layout="tb""#, &table(rows))).unwrap();
+ let fills = |form: &Form, page: usize| -> Vec<Rect> {
+ form.pages[page].items.iter().filter_map(|i| if let Item::Fill { rect, .. } = i { Some(*rect) } else { None }).collect()
+ };
+ let small: String = (0..10).map(|i| row(&format!("r{i}"), "0.3in")).collect();
+ // A 695pt row after ten small ones moves; it and the 21.6pt leader leave 3.4pt of the 720pt
+ // page for the top margin, so the row ends at the content area's bottom, in the border.
+ let form = lay(&(small.clone() + &row("big", "695pt")));
+ assert_eq!(form.pages.len(), 2);
+ let part = fills(&form, 1);
+ assert!(part.len() == 1 && (part[0].y - 36.0).abs() < 0.01 && (part[0].bottom() - 756.0).abs() < 0.01, "{part:?}");
+ assert!(form.warnings.is_empty(), "{:?}", form.warnings);
+ // 710pt and the leader don't fit any page: no border, one warning.
+ let form = lay(&(small + &row("big", "710pt")));
+ assert!(form.pages.iter().enumerate().all(|(p, _)| fills(&form, p).is_empty()), "no fill drawn");
+ assert_eq!(form.warnings.iter().filter(|w| w.contains("bordered section")).count(), 1, "{:?}", form.warnings);
+ // A first row taller than the page: no border round it, one warning.
+ let form = lay(&row("tall", "800pt"));
+ assert!(fills(&form, 0).is_empty(), "{:?}", fills(&form, 0));
+ assert_eq!(form.warnings.iter().filter(|w| w.contains("bordered section")).count(), 1, "{:?}", form.warnings);
+}
+
+/// A child's own page break (breakBefore, breakAfter) breaks the flowed subform around it as a
+/// break between children does: a closed part on each page, no warning.
+#[test]
+fn a_childs_page_break_keeps_the_border_around_it_on_each_page() {
+ let field = |name: &str| format!(r#"<field name="{name}" w="3in" h="0.5in"><ui><textEdit/></ui></field>"#);
+ let body = format!(
+ r#"<subform name="body" layout="tb" w="7.5in"><subform name="box" layout="tb" w="7.5in"><border><edge/><fill/></border><margin topInset="0.1in" bottomInset="0.2in"/>{}<subform name="s1" layout="tb"><breakBefore targetType="pageArea"/>{}</subform><subform name="s2" layout="tb"><breakAfter targetType="pageArea"/>{}</subform>{}</subform></subform>"#,
+ field("a"),
+ field("b"),
+ field("c"),
+ field("d")
+ );
+ let form = layout_xml(&one_area_form(r#"layout="tb""#, &body)).unwrap();
+ assert_eq!(form.pages.len(), 3, "a, then b and c, then d");
+ for (page, fields) in [(0, 1.0), (1, 2.0), (2, 1.0)] {
+ let fills: Vec<Rect> =
+ form.pages[page].items.iter().filter_map(|i| if let Item::Fill { rect, .. } = i { Some(*rect) } else { None }).collect();
+ let lines = form.pages[page].items.iter().filter(|i| matches!(i, Item::Line { .. })).count();
+ assert_eq!((fills.len(), lines), (1, 4), "page {}: one closed part", page + 1);
+ // The top margin, its fields, the bottom margin.
+ assert!((fills[0].y - 36.0).abs() < 0.01 && (fills[0].h - (7.2 + fields * 36.0 + 14.4)).abs() < 0.01, "page {}: {:?}", page + 1, fills[0]);
+ }
+ assert!(form.warnings.is_empty(), "{:?}", form.warnings);
+}
+
#[test]
fn a_page_break_keeps_a_fields_border_with_the_field() {
// 6in of heading, then a bordered 5in field: it doesn't fit the 10in area and moves to
@@ -2202,6 +2757,258 @@ fn a_text_field_without_a_border_of_its_own_has_no_box() {
assert_eq!(shapes, [BorderShape::None, BorderShape::Full, BorderShape::Full]);
}
+/// One measured check box: its name, width, box size, check box children, field children, and
+/// where its box was drawn (x and y in inches from the field's top left).
+type CheckCase<'a> = (&'a str, &'a str, Option<&'a str>, String, String, f64, f64);
+
+/// A check box field for the placement tests: `extra` holds its margin, paragraph and caption,
+/// `ui` the check box's own children, and `size` its box size (none for the default 10pt).
+fn placed_check(name: &str, x: f64, y: f64, w: &str, size: Option<&str>, ui: &str, extra: &str) -> String {
+ let size = size.map(|s| format!(r#" size="{s}""#)).unwrap_or_default();
+ format!(
+ r#"<field name="{name}" x="{x}in" y="{y}in" w="{w}" h="0.6in"><ui><checkButton{size}>{ui}</checkButton></ui><font typeface="Arial" size="9pt"/>{extra}<items><integer>1</integer><integer>0</integer></items></field>"#
+ )
+}
+
+/// Where a check box is drawn inside its field, measured in inches from the field's top left in
+/// another viewer on synthetic probes: with no caption the box sits at the right of the content
+/// area whatever the paragraph's alignment, beside a reserved caption the alignment places it,
+/// a caption without a reserve takes all the box leaves, and the box's own margin doesn't move it.
+#[test]
+fn a_check_box_sits_where_its_margins_caption_and_alignment_put_it() {
+ let m = |a: &str| format!("<margin {a}/>");
+ let p = |a: &str| format!("<para {a}/>");
+ let cap = |a: &str, text: &str| format!(r#"<caption {a}><font typeface="Arial" size="9pt"/><value><text>{text}</text></value></caption>"#);
+ // (name, width, box size, check box children, field children, box x and y in inches)
+ let cases: Vec<CheckCase> = vec![
+ ("none", "1.2in", Some("0.25in"), String::new(), String::new(), 0.95, 0.0),
+ ("left_margin", "1.2in", Some("0.25in"), String::new(), m(r#"leftInset="0.3in""#), 0.95, 0.0),
+ ("right_margin", "1.2in", Some("0.25in"), String::new(), m(r#"rightInset="0.3in""#), 0.65, 0.0),
+ ("both_margins", "1.2in", Some("0.25in"), String::new(), m(r#"leftInset="0.1in" rightInset="0.4in""#), 0.55, 0.0),
+ ("h_left", "1.2in", Some("0.25in"), String::new(), p(r#"hAlign="left""#), 0.95, 0.0),
+ ("h_center", "1.2in", Some("0.25in"), String::new(), p(r#"hAlign="center""#), 0.95, 0.0),
+ ("h_right", "1.2in", Some("0.25in"), String::new(), p(r#"hAlign="right""#), 0.95, 0.0),
+ ("h_justify", "1.2in", Some("0.25in"), String::new(), p(r#"hAlign="justify""#), 0.95, 0.0),
+ ("center_right_margin", "1.2in", Some("0.25in"), String::new(), m(r#"rightInset="0.3in""#) + &p(r#"hAlign="center""#), 0.65, 0.0),
+ ("left_left_margin", "1.2in", Some("0.25in"), String::new(), m(r#"leftInset="0.3in""#) + &p(r#"hAlign="left""#), 0.95, 0.0),
+ ("v_top_margin", "1.2in", Some("0.25in"), String::new(), m(r#"topInset="0.15in""#) + &p(r#"vAlign="top""#), 0.95, 0.15),
+ ("v_middle_margin", "1.2in", Some("0.25in"), String::new(), m(r#"topInset="0.2in""#) + &p(r#"vAlign="middle""#), 0.95, 0.275),
+ ("v_bottom_margin", "1.2in", Some("0.25in"), String::new(), m(r#"bottomInset="0.15in""#) + &p(r#"vAlign="bottom""#), 0.95, 0.2),
+ ("v_bottom", "1.2in", Some("0.25in"), String::new(), p(r#"vAlign="bottom""#), 0.95, 0.35),
+ ("cap_left_reserve", "1.5in", Some("0.25in"), String::new(), cap(r#"placement="left" reserve="0.5in""#, "Cap"), 0.5, 0.0),
+ ("cap_right_reserve", "1.5in", Some("0.25in"), String::new(), cap(r#"placement="right" reserve="0.5in""#, "Cap"), 0.0, 0.0),
+ (
+ "cap_left_reserve_center",
+ "1.5in",
+ Some("0.25in"),
+ String::new(),
+ cap(r#"placement="left" reserve="0.5in""#, "Cap") + &p(r#"hAlign="center""#),
+ 0.875,
+ 0.0,
+ ),
+ (
+ "cap_left_reserve_right",
+ "1.5in",
+ Some("0.25in"),
+ String::new(),
+ cap(r#"placement="left" reserve="0.5in""#, "Cap") + &p(r#"hAlign="right""#),
+ 1.25,
+ 0.0,
+ ),
+ (
+ "cap_left_reserve_middle",
+ "1.5in",
+ Some("0.25in"),
+ String::new(),
+ cap(r#"placement="left" reserve="0.5in""#, "Cap") + &p(r#"vAlign="middle""#),
+ 0.5,
+ 0.175,
+ ),
+ (
+ "cap_right_reserve_center",
+ "1.5in",
+ Some("0.25in"),
+ String::new(),
+ cap(r#"placement="right" reserve="0.5in""#, "Cap") + &p(r#"hAlign="center""#),
+ 0.375,
+ 0.0,
+ ),
+ ("cap_top_reserve", "1.5in", Some("0.25in"), String::new(), cap(r#"placement="top" reserve="0.25in""#, "Cap"), 0.0, 0.25),
+ ("cap_bottom_reserve", "1.5in", Some("0.25in"), String::new(), cap(r#"placement="bottom" reserve="0.25in""#, "Cap"), 0.0, 0.0),
+ (
+ "cap_hidden_reserve",
+ "1.5in",
+ Some("0.25in"),
+ String::new(),
+ cap(r#"placement="left" reserve="0.5in" presence="hidden""#, "Cap"),
+ 1.25,
+ 0.0,
+ ),
+ ("cap_empty_reserve", "1.5in", Some("0.25in"), String::new(), r#"<caption placement="left" reserve="0.5in"/>"#.to_string(), 0.5, 0.0),
+ ("cap_left_auto", "1.5in", Some("0.25in"), String::new(), cap(r#"placement="left""#, "Cap"), 1.25, 0.0),
+ ("cap_left_auto_center", "1.5in", Some("0.25in"), String::new(), cap(r#"placement="left""#, "Cap") + &p(r#"hAlign="center""#), 1.25, 0.0),
+ ("cap_right_auto", "1.5in", Some("0.25in"), String::new(), cap(r#"placement="right""#, "Cap"), 0.0, 0.0),
+ ("cap_right_auto_middle", "1.5in", Some("0.25in"), String::new(), cap(r#"placement="right""#, "Cap") + &p(r#"vAlign="middle""#), 0.0, 0.175),
+ ("cap_top_auto", "1.5in", Some("0.25in"), String::new(), cap(r#"placement="top""#, "Cap"), 0.0, 0.35),
+ ("cap_top_auto_center", "1.5in", Some("0.25in"), String::new(), cap(r#"placement="top""#, "Cap") + &p(r#"hAlign="center""#), 0.625, 0.35),
+ ("cap_bottom_auto", "1.5in", Some("0.25in"), String::new(), cap(r#"placement="bottom""#, "Cap"), 0.0, 0.0),
+ ("cap_inline", "1.5in", Some("0.25in"), String::new(), cap(r#"placement="inline""#, "Cap"), 1.25, 0.0),
+ ("cap_hidden_auto", "1.5in", Some("0.25in"), String::new(), cap(r#"placement="left" presence="hidden""#, "Cap"), 1.25, 0.0),
+ ("box_margin_left", "1.5in", Some("0.25in"), m(r#"leftInset="0.1in""#), String::new(), 1.25, 0.0),
+ (
+ "box_margin_all",
+ "1.5in",
+ Some("0.25in"),
+ m(r#"leftInset="0.1in" rightInset="0.1in" topInset="0.1in" bottomInset="0.1in""#),
+ String::new(),
+ 1.25,
+ 0.0,
+ ),
+ ("default_size", "1.2in", None, String::new(), String::new(), 1.2 - 10.0 / 72.0, 0.0),
+ ("default_size_center", "1.2in", None, String::new(), p(r#"hAlign="center""#), 1.2 - 10.0 / 72.0, 0.0),
+ ];
+ let fields: String = cases
+ .iter()
+ .enumerate()
+ .map(|(i, (name, w, size, ui, extra, _, _))| placed_check(name, (i % 4) as f64 * 1.8, (i / 4) as f64 * 0.8, w, *size, ui, extra))
+ .collect();
+ // The form in the measured case the probes started from (DD Form 2946's checklist boxes).
+ let cell = r#"<field name="cell" x="0in" y="8in" w="12.7mm" h="0.6in"><ui><checkButton size="4.9389mm"><border><edge/><fill/></border></checkButton></ui><margin leftInset="0mm" rightInset="3.556mm"/><para vAlign="middle"/><items><integer>1</integer><integer>0</integer></items></field>"#;
+ let body = format!(r#"<subform name="body" layout="position" w="7.5in" h="9in">{fields}{cell}</subform>"#);
+ let form = layout_xml(&one_area_form(r#"layout="tb""#, &body)).unwrap();
+ let laid = widgets(&form.pages[0]);
+ let at = |name: &str| laid.iter().find(|w| w.name == name).map(|w| w.rect).unwrap_or_else(|| panic!("no widget {name}"));
+ // The content area starts half an inch in.
+ for (i, (name, _, size, _, _, x, y)) in cases.iter().enumerate() {
+ let r = at(name);
+ let (fx, fy) = (36.0 + (i % 4) as f64 * 1.8 * 72.0, 36.0 + (i / 4) as f64 * 0.8 * 72.0);
+ let s = if size.is_some() { 18.0 } else { 10.0 };
+ assert!((r.x - fx - x * 72.0).abs() < 0.01, "{name}: box x {} in, expected {x}", (r.x - fx) / 72.0);
+ assert!((r.y - fy - y * 72.0).abs() < 0.01, "{name}: box y {} in, expected {y}", (r.y - fy) / 72.0);
+ assert!((r.w - s).abs() < 0.01 && (r.h - s).abs() < 0.01, "{name}: box size {}x{}", r.w, r.h);
+ }
+ // Its box sits 4.2mm in, against its 3.556mm right margin, and in the middle of its height.
+ let r = at("cell");
+ let mm = 72.0 / 25.4;
+ assert!((r.x - 36.0 - (12.7 - 3.556 - 4.9389) * mm).abs() < 0.01, "cell box x {}", r.x - 36.0);
+ assert!((r.y - 36.0 - 8.0 * 72.0 - (0.6 * 72.0 - 4.9389 * mm) / 2.0).abs() < 0.01, "cell box y {}", r.y - 36.0 - 8.0 * 72.0);
+}
+
+/// Radio buttons in an exclusion group sit as check boxes do: at the right without a caption,
+/// moved in by a right margin, and placed by the alignment or the caption beside a caption.
+#[test]
+fn a_radio_button_sits_where_a_check_box_would() {
+ let radio = |name: &str, x: f64, extra: &str| {
+ format!(
+ r#"<field name="{name}" x="{x}in" y="0in" w="1.5in" h="0.6in"><ui><checkButton size="0.25in" shape="round"/></ui><font typeface="Arial" size="9pt"/>{extra}<items><text>{name}</text></items></field>"#
+ )
+ };
+ let cap = |a: &str| format!(r#"<caption {a}><font typeface="Arial" size="9pt"/><value><text>Cap</text></value></caption>"#);
+ // (name, field children, box x and y in inches from the field's top left)
+ let cases = [
+ ("plain", String::new(), 1.25, 0.0),
+ ("right_margin", r#"<margin rightInset="0.3in"/>"#.to_string(), 0.95, 0.0),
+ ("centered", r#"<para hAlign="center"/>"#.to_string(), 1.25, 0.0),
+ ("cap_right_center", cap(r#"placement="right" reserve="0.5in""#) + r#"<para hAlign="center"/>"#, 0.375, 0.0),
+ ("cap_left_auto", cap(r#"placement="left""#), 1.25, 0.0),
+ ("cap_top_auto", cap(r#"placement="top""#), 0.0, 0.35),
+ ];
+ let fields: String = cases.iter().enumerate().map(|(i, (name, extra, _, _))| radio(name, i as f64 * 1.6, extra)).collect();
+ let body = format!(
+ r#"<subform name="body" layout="position" w="7.5in" h="9in"><exclGroup name="group" x="0in" y="0in" w="9.6in" h="0.6in" layout="position">{fields}</exclGroup></subform>"#
+ );
+ let form = layout_xml(&one_area_form(r#"layout="tb""#, &body)).unwrap();
+ let laid = widgets(&form.pages[0]);
+ for (i, (name, _, x, y)) in cases.iter().enumerate() {
+ let w = laid.iter().find(|w| w.name == *name).unwrap_or_else(|| panic!("no radio button {name}"));
+ assert!(matches!(w.kind, WidgetKind::Radio { .. }), "{name} is a radio button");
+ let fx = 36.0 + i as f64 * 1.6 * 72.0;
+ assert!((w.rect.x - fx - x * 72.0).abs() < 0.01, "{name}: box x {} in, expected {x}", (w.rect.x - fx) / 72.0);
+ assert!((w.rect.y - 36.0 - y * 72.0).abs() < 0.01, "{name}: box y {} in, expected {y}", (w.rect.y - 36.0) / 72.0);
+ }
+}
+
+/// A caption without a reserve leaves room for the box at the size it is drawn, a box larger than
+/// its field shrinking to fit; and a field without a height is as tall as that caption drawn in
+/// all the box leaves, not at some narrower width.
+#[test]
+fn a_check_box_caption_without_a_reserve_is_measured_as_it_is_drawn() {
+ let cap =
+ r#"<caption placement="left"><font typeface="Arial" size="9pt"/><value><text>Caption text running on one line</text></value></caption>"#;
+ let tall = r#"<field name="tall" x="0in" y="0in" w="1.5in" h="0.25in"><ui><checkButton size="0.75in"/></ui><font typeface="Arial" size="9pt"/>"#
+ .to_string()
+ + cap
+ + "<items><integer>1</integer><integer>0</integer></items></field>";
+ let form = layout_xml(&one_area_form(r#"layout="tb""#, &format!(r#"<subform name="body" layout="position" w="7.5in" h="1in">{tall}</subform>"#)))
+ .unwrap();
+ let r = widgets(&form.pages[0]).iter().find(|w| w.name == "tall").map(|w| w.rect).unwrap();
+ assert!((r.w - 18.0).abs() < 0.01, "the box shrinks to the field's height: {}", r.w);
+ assert!((r.x - 36.0 - 1.25 * 72.0).abs() < 0.01, "and still sits at the right: {} in", (r.x - 36.0) / 72.0);
+
+ let grows = r#"<field name="grows" w="3in"><ui><checkButton size="0.25in"/></ui><font typeface="Arial" size="9pt"/>"#.to_string()
+ + cap
+ + r#"<items><integer>1</integer><integer>0</integer></items></field><field name="next" w="3in" h="0.3in"><ui><textEdit/></ui></field>"#;
+ let form = layout_xml(&one_area_form(r#"layout="tb""#, &format!(r#"<subform name="body" layout="tb" w="7.5in">{grows}</subform>"#))).unwrap();
+ let next = widgets(&form.pages[0]).iter().find(|w| w.name == "next").map(|w| w.rect).unwrap();
+ assert!((next.y - 36.0 - 18.0).abs() < 0.01, "a one-line caption beside the box keeps the field the box's height: {}", next.y - 36.0);
+}
+
+/// A caption without a reserve beside a check box takes all the room the box leaves, and starts
+/// right after it; an inline caption has no text to run with and is not drawn.
+#[test]
+fn a_check_box_caption_without_a_reserve_takes_the_rest_of_the_field() {
+ let cap = |place: &str, text: &str| {
+ format!(r#"<caption placement="{place}"><font typeface="Arial" size="9pt"/><value><text>{text}</text></value></caption>"#)
+ };
+ let body = format!(
+ r#"<subform name="body" layout="position" w="7.5in" h="9in">{}{}{}{}</subform>"#,
+ placed_check("after", 0.0, 0.0, "1.5in", Some("0.25in"), "", &cap("right", "Right")),
+ placed_check("before", 2.0, 0.0, "1.5in", Some("0.25in"), "", &cap("left", "Left")),
+ placed_check("below", 4.0, 0.0, "1.5in", Some("0.25in"), "", &cap("bottom", "Below")),
+ placed_check("inline", 0.0, 1.0, "1.5in", Some("0.25in"), "", &cap("inline", "Inline")),
+ );
+ let form = layout_xml(&one_area_form(r#"layout="tb""#, &body)).unwrap();
+ let span = |t: &str| {
+ form.pages[0].items.iter().find_map(|i| match i {
+ Item::Text(s) if s.text == t => Some(s.clone()),
+ _ => None,
+ })
+ };
+ let right = span("Right").expect("the right caption is drawn");
+ assert!((right.x - 36.0 - 18.0).abs() < 0.01, "a right caption starts after the box: {}", right.x - 36.0);
+ let left = span("Left").expect("the left caption is drawn");
+ assert!((left.x - 36.0 - 2.0 * 72.0).abs() < 0.01, "a left caption starts at the field's left: {}", left.x - 36.0);
+ let below = span("Below").expect("the bottom caption is drawn");
+ assert!(below.baseline - 36.0 > 18.0, "a bottom caption is below the box: {}", below.baseline - 36.0);
+ assert!(span("Inline").is_none(), "an inline caption beside a check box is not drawn");
+}
+
+/// A caption reserve of zero sizes the caption to its content, as no reserve does: beside a check
+/// box it takes the rest of the field, and before a text field it is as wide as its text.
+#[test]
+fn a_zero_caption_reserve_sizes_the_caption_as_none_does() {
+ let cap = |reserve: &str| {
+ format!(r#"<caption placement="right"{reserve}><font typeface="Arial" size="9pt"/><value><text>Right</text></value></caption>"#)
+ };
+ let text = |name: &str, y: &str, reserve: &str| {
+ format!(
+ r#"<field name="{name}" x="0in" y="{y}" w="3in" h="0.3in"><ui><textEdit/></ui><font typeface="Arial" size="9pt"/><caption placement="left"{reserve}><font typeface="Arial" size="9pt"/><value><text>Name</text></value></caption></field>"#
+ )
+ };
+ let body = format!(
+ r#"<subform name="body" layout="position" w="7.5in" h="9in">{}{}{}</subform>"#,
+ placed_check("zero", 0.0, 0.0, "1.5in", Some("0.25in"), "", &cap(r#" reserve="0""#)),
+ text("withZero", "1in", r#" reserve="0in""#),
+ text("without", "2in", ""),
+ );
+ let form = layout_xml(&one_area_form(r#"layout="tb""#, &body)).unwrap();
+ let right = form.pages[0].items.iter().find_map(|i| if let Item::Text(s) = i { (s.text == "Right").then_some(s.x) } else { None });
+ assert!(right.is_some_and(|x| (x - 36.0 - 18.0).abs() < 0.01), "the caption starts after the box: {right:?}");
+ let x_of = |name: &str| widgets(&form.pages[0]).iter().find(|w| w.name == name).map(|w| w.rect.x).unwrap();
+ assert!(x_of("withZero") > 36.0 + 1.0, "the caption takes its text's width: {}", x_of("withZero"));
+ assert!((x_of("withZero") - x_of("without")).abs() < 0.01, "as without a reserve: {} {}", x_of("withZero"), x_of("without"));
+}
+
#[test]
fn a_signed_signature_box_shows_the_signature_the_file_holds() {
let mut doc = Document::open(Arc::new(crate::fixtures::signed_shell())).unwrap();
@@ -2500,6 +3307,37 @@ fn an_anchor_type_places_the_named_point_of_the_box_at_its_x_and_y() {
assert!((field.rect.x - 6.0 * 72.0).abs() < 0.01 && (field.rect.y - 72.0).abs() < 0.01, "{:?}", field.rect);
}
+#[test]
+fn laying_a_form_out_takes_off_the_usage_rights_it_voids() {
+ use crate::fixtures::usage_rights_shell;
+ let xdp = fields_template("<form><page1><country>JP</country></page1></form>");
+ // What `/Perms` holds once the layout is saved and the file read again.
+ let laid_out = |bytes: Vec<u8>| {
+ let mut doc = Document::open(Arc::new(bytes)).unwrap();
+ let report = render_into(&mut doc).unwrap();
+ let doc = Document::open(Arc::new(write_incremental(&doc, &SaveOptions::default()).unwrap())).unwrap();
+ let catalog = doc.get(doc.root().unwrap()).as_dict().cloned().unwrap();
+ let indirect = catalog.get(b"Perms").and_then(Object::as_ref).is_some();
+ let perms = catalog.get(b"Perms").map(|p| doc.resolve(p)).and_then(|p| p.as_dict().cloned());
+ let said = report.warnings.iter().any(|w| w.contains("usage rights"));
+ (perms, indirect, said, report.warnings)
+ };
+ // Usage rights alone: `/Perms` goes, and the user is told.
+ let (perms, _, said, warnings) = laid_out(usage_rights_shell(&xdp, "", false));
+ assert!(perms.is_none(), "{perms:?}");
+ assert!(said, "{warnings:?}");
+ // Beside a certification, in an object of its own: only the usage rights go, and the
+ // object is rewritten where it is.
+ let (perms, indirect, said, warnings) = laid_out(usage_rights_shell(&xdp, "/DocMDP 6 0 R", true));
+ let perms = perms.expect("the certification stays");
+ assert!(perms.contains(b"DocMDP") && !perms.contains(b"UR3"), "{perms:?}");
+ assert!(indirect, "/Perms is still its own object");
+ assert!(said, "{warnings:?}");
+ // A form without usage rights says nothing about them.
+ let (perms, _, said, warnings) = laid_out(shell(&xdp));
+ assert!(perms.is_none() && !said, "{perms:?} {warnings:?}");
+}
+
#[test]
fn stripping_takes_the_xfa_out_and_leaves_an_ordinary_document() {
use crate::pdf::strip;
@@ -2512,6 +3350,7 @@ fn stripping_takes_the_xfa_out_and_leaves_an_ordinary_document() {
ur.set(b"UR3".to_vec(), Object::Dict(pdfcraft_cos::Dict::new()));
doc.update_dict(root, |d| d.set(b"Perms".to_vec(), Object::Dict(ur))).unwrap();
let r = strip(&mut doc).unwrap();
+ assert!(doc.full_save_required());
assert_eq!(r.packets, vec!["template".to_string(), "datasets".to_string()]);
assert_eq!(r.unbound_data, Some(0));
assert_eq!((r.script_buttons, r.image_fields), (0, 1), "{r:?}");
@@ -2597,6 +3436,16 @@ fn stripping_takes_the_xfa_out_and_leaves_an_ordinary_document() {
assert!(started.elapsed() < std::time::Duration::from_secs(5), "{:?}", started.elapsed());
}
+#[test]
+fn strip_marks_document_as_requiring_full_save() {
+ use crate::pdf::strip;
+ let mut doc = Document::open(Arc::new(shell(&fields_template("<form><page1><country>JP</country></page1></form>")))).unwrap();
+ render_into(&mut doc).unwrap();
+ assert!(!doc.full_save_required());
+ strip(&mut doc).unwrap();
+ assert!(doc.full_save_required(), "stripping XFA packets must require a full save to prevent data exposure in incremental saves");
+}
+
#[test]
fn som_indices_count_earlier_same_named_siblings() {
let draw = |name: Option<&str>| {
@@ -2697,6 +3546,40 @@ fn trailing_spaces_do_not_shift_centered_or_right_aligned_text() {
assert!((left_edge("right", "TITLE ") - (36.0 + w - ink)).abs() < 1e-6);
}
+/// `typed_date` rewrites a date typed by another of a field's edit-picture patterns in the first
+/// one, and leaves alone a date the first pattern reads, text no pattern reads, a field with one
+/// pattern and a field that isn't a date.
+#[test]
+fn a_date_typed_by_another_of_its_edit_pictures_patterns_is_written_in_the_first() {
+ let (tpl, _) = crate::parse(&crate::fixtures::date_alternatives_template()).unwrap();
+ let typed = |som: &str, text: &str| crate::typed_date(&tpl, som, text);
+ let leave = "form[0].leave[0]";
+ assert_eq!(typed(leave, "261018").as_deref(), Some("20261018"), "by yymmdd");
+ assert_eq!(typed(leave, "2026118").as_deref(), Some("20261108"), "by yyyymd");
+ assert_eq!(typed(leave, "26 10 18").as_deref(), Some("20261018"), "by yy mm dd");
+ assert_eq!(typed(leave, "20261018"), None, "the first pattern reads it: it stays as typed");
+ assert_eq!(typed(leave, "not a date"), None);
+ assert_eq!(typed(leave, "2618"), None, "no pattern has room for four digits");
+ assert_eq!(typed("form[0].born[0]", "181026"), None, "one pattern: nothing else to try");
+ assert_eq!(typed("form[0].name[0]", "261018"), None, "not a date field");
+}
+
+/// Only date clauses are other ways to type a date, and a date is rewritten only when the first
+/// pattern keeps it: a later `text{…}` clause is no date pattern, a year a two-digit first
+/// pattern can't hold leaves the text as typed instead of becoming another date, and a pattern
+/// whose date the first can't keep gives way to a later one whose date it can.
+#[test]
+fn a_typed_date_is_rewritten_only_by_date_clauses_into_a_first_pattern_that_keeps_it() {
+ let (tpl, _) = crate::parse(&crate::fixtures::date_alternatives_template()).unwrap();
+ let typed = |som: &str, text: &str| crate::typed_date(&tpl, som, text);
+ assert_eq!(typed("form[0].code[0]", "261018"), None, "text{{YYMMDD}} is not a date alternative");
+ let short = "form[0].short[0]";
+ assert_eq!(typed(short, "20261018").as_deref(), Some("261018"), "a year the first pattern keeps");
+ assert_eq!(typed(short, "19011018"), None, "1901 as 01 would read back as 2001");
+ // DDMMYYYY reads 20011203 as 1203-01-20, which YYMMDD can't keep; YYYYMMDD reads 2001-12-03.
+ assert_eq!(typed("form[0].pick[0]", "20011203").as_deref(), Some("011203"), "the next pattern that the first keeps");
+}
+
/// A word longer than its line is broken by character in work linear in its length.
#[test]
fn a_long_word_breaks_in_linear_work() {
@@ -2832,3 +3715,145 @@ fn long_names_repeated_by_an_index_are_capped() {
let data = build_data(&doc, &fields);
assert!(data.len() < 2_000_000, "{} bytes of data built", data.len());
}
+
+/// #3441: a font the form already holds as an object stays that object when the XFA layout
+/// writes its fields' fonts into `/DR`.
+#[test]
+fn rendering_keeps_the_forms_own_font_objects() {
+ let mut doc = Document::open(Arc::new(shell(&template(2)))).unwrap();
+ let mut font = Dict::new();
+ font.set(b"Type".to_vec(), Object::name("Font"));
+ font.set(b"Subtype".to_vec(), Object::name("Type1"));
+ font.set(b"BaseFont".to_vec(), Object::name("Symbol"));
+ let mine = doc.add(Object::Dict(font));
+ let mut fonts = Dict::new();
+ fonts.set(b"Mine".to_vec(), Object::Ref(mine));
+ let mut dr = Dict::new();
+ dr.set(b"Font".to_vec(), Object::Dict(fonts));
+ let root = doc.root().unwrap();
+ match doc.get(root).as_dict().unwrap().get(b"AcroForm").cloned().unwrap() {
+ Object::Ref(af) => doc.update_dict(af, |d| d.set(b"DR".to_vec(), Object::Dict(dr))).unwrap(),
+ _ => doc
+ .update_dict(root, |c| {
+ if let Some(Object::Dict(af)) = c.get(b"AcroForm").cloned() {
+ let mut af = af;
+ af.set(b"DR".to_vec(), Object::Dict(dr));
+ c.set(b"AcroForm".to_vec(), Object::Dict(af));
+ }
+ })
+ .unwrap(),
+ }
+ render_into(&mut doc).unwrap();
+ let catalog = doc.get(root);
+ let acro = doc.resolve(catalog.as_dict().unwrap().get(b"AcroForm").unwrap());
+ let dr = doc.resolve(acro.as_dict().unwrap().get(b"DR").unwrap());
+ let fonts = doc.resolve(dr.as_dict().unwrap().get(b"Font").unwrap());
+ assert_eq!(fonts.as_dict().unwrap().reference(b"Mine"), Some(mine), "the form's own font object");
+ assert!(fonts.as_dict().unwrap().reference(b"Helv").is_some(), "and the layout's fonts as objects");
+}
+
+/// Text is measured in the standard-14 face it is drawn in, at the widths ISO 32000-2 Annex D
+/// gives: bold and Times are no longer Helvetica scaled, and the horizontal scale still applies.
+#[test]
+fn faces_measure_text_at_their_standard_14_widths() {
+ use pdfcraft_fonts::Std14;
+ let face = |family: text::Family, bold: bool, italic: bool| text::Face {
+ family,
+ bold,
+ italic,
+ size: 10.0,
+ color: [0.0; 3],
+ underline: false,
+ h_scale: 1.0,
+ };
+ let sample = "Mill Wax 0123 Departure Date";
+ for (family, bold, italic, std14) in [
+ (text::Family::Helvetica, false, false, Std14::Helvetica),
+ (text::Family::Helvetica, true, false, Std14::HelveticaBold),
+ (text::Family::Helvetica, true, true, Std14::HelveticaBoldOblique),
+ (text::Family::Times, false, false, Std14::TimesRoman),
+ (text::Family::Times, true, false, Std14::TimesBold),
+ (text::Family::Times, false, true, Std14::TimesItalic),
+ (text::Family::Times, true, true, Std14::TimesBoldItalic),
+ (text::Family::Courier, true, false, Std14::CourierBold),
+ ] {
+ let f = face(family, bold, italic);
+ assert!(
+ (f.width(sample) - std14.text_width(sample, 10.0)).abs() < 1e-9,
+ "{std14:?}: {} vs {}",
+ f.width(sample),
+ std14.text_width(sample, 10.0)
+ );
+ assert_eq!(f.family.std14(bold, italic), std14);
+ assert_eq!(f.family.base_font(bold, italic), std14.base_font());
+ }
+ // A condensed face is narrower by its scale.
+ let condensed = text::Face { h_scale: 0.8, ..face(text::Family::Times, true, false) };
+ assert!((condensed.width(sample) - 0.8 * Std14::TimesBold.text_width(sample, 10.0)).abs() < 1e-9);
+}
+
+/// #3944: clearing XFA password values removes values typed into `<passwordEdit/>` fields from the
+/// datasets packet (including across repeating subforms), restores a field's template default
+/// `<value><text>…</text></value>` when it has one, and replaces the datasets stream in place so
+/// the typed password is not left in an unreferenced stream in the overlay.
+#[test]
+fn clear_password_values_removes_typed_passwords_from_datasets_in_place() {
+ let xdp = r#"<xdp:xdp xmlns:xdp="http://ns.adobe.com/xdp/">
+<template xmlns="http://www.xfa.org/schema/xfa-template/3.3/">
+<subform name="form" layout="tb">
+ <pageSet><pageArea name="front"><contentArea x="0.5in" y="0.5in" w="7.5in" h="10in"/><medium short="8.5in" long="11in"/></pageArea></pageSet>
+ <subform name="page1" layout="tb">
+ <field name="user" w="2in" h="0.3in"><ui><textEdit/></ui></field>
+ <field name="pin" w="2in" h="0.3in"><ui><passwordEdit/></ui></field>
+ <field name="preset" w="2in" h="0.3in"><ui><passwordEdit/></ui><value><text>0000</text></value></field>
+ <subform name="row" layout="lr-tb"><occur min="1" max="-1"/>
+ <field name="secret" w="2in" h="0.3in"><ui><passwordEdit/></ui></field>
+ </subform>
+ </subform>
+</subform>
+</template>
+<xfa:datasets xmlns:xfa="http://www.xfa.org/schema/xfa-data/1.0/">
+<xfa:data><form><page1><user>Ada</user><pin>hunter2</pin><preset>9999</preset><row><secret>first</secret></row><row><secret>second</secret></row></page1></form></xfa:data>
+</xfa:datasets>
+</xdp:xdp>"#;
+ let mut doc = Document::open(Arc::new(shell(xdp))).unwrap();
+ render_into(&mut doc).unwrap();
+ assert!(has_password_values(&doc));
+ let cleared = clear_password_values(&mut doc).unwrap();
+ assert_eq!(cleared, 4);
+ assert!(!has_password_values(&doc), "only default and non-password values remain");
+ assert_eq!(clear_password_values(&mut doc).unwrap(), 0);
+
+ let packets = read_packets(&doc).unwrap().unwrap();
+ assert!(packets.xdp.contains("<user>Ada</user>"), "non-password fields stay: {}", packets.xdp);
+ assert!(packets.xdp.contains("<preset>0000</preset>"), "template default restored: {}", packets.xdp);
+ for secret in ["hunter2", "9999", "first", "second"] {
+ assert!(!packets.xdp.contains(secret), "{secret} still in datasets: {}", packets.xdp);
+ }
+ let written = write_incremental(&doc, &SaveOptions::default()).unwrap();
+ let reopened = Document::open(Arc::new(written)).unwrap();
+ for num in reopened.object_numbers() {
+ if let Object::Stream(st) = &*reopened.get(pdfcraft_cos::ObjRef::new(num, 0)) {
+ let decoded = st.decoded().unwrap_or_default();
+ let text = String::from_utf8_lossy(&decoded);
+ for secret in ["hunter2", "9999", "first", "second"] {
+ assert!(!text.contains(secret), "object {num} still holds {secret}: {text}");
+ }
+ }
+ }
+}
+
+/// #3944: a static XFA form whose AcroForm field sets the Password flag (`/Ff 8192`) also has its
+/// typed value cleared from the datasets packet.
+#[test]
+fn clear_password_values_clears_static_xfa_password_fields() {
+ let pdf = String::from_utf8(static_shell("<form1><page1><name>hunter2</name></page1></form1>"))
+ .unwrap()
+ .replace("/T (name[0])", "/T (name[0]) /Ff 8192");
+ let mut doc = Document::open(Arc::new(pdf.into_bytes())).unwrap();
+ assert!(has_password_values(&doc));
+ assert_eq!(clear_password_values(&mut doc).unwrap(), 1);
+ assert!(!has_password_values(&doc));
+ let packets = read_packets(&doc).unwrap().unwrap();
+ assert!(!packets.xdp.contains("hunter2"), "{}", packets.xdp);
+}
diff --git a/crates/xfa/src/text.rs b/crates/xfa/src/text.rs
index 7e83212..77076b3 100644
--- a/crates/xfa/src/text.rs
+++ b/crates/xfa/src/text.rs
@@ -3,6 +3,7 @@
//! bundled here).
use crate::model::{Font, HAlign, Para, Rect, RichText, Run};
+use pdfcraft_fonts::Std14;
/// The standard-14 family a typeface maps to.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
@@ -29,24 +30,29 @@ impl Family {
}
}
- /// The PDF base font name for a face.
- pub fn base_font(self, bold: bool, italic: bool) -> &'static str {
+ /// The standard-14 font this family draws in, as `bold` and `italic` ask.
+ pub fn std14(self, bold: bool, italic: bool) -> Std14 {
match (self, bold, italic) {
- (Family::Helvetica, false, false) => "Helvetica",
- (Family::Helvetica, true, false) => "Helvetica-Bold",
- (Family::Helvetica, false, true) => "Helvetica-Oblique",
- (Family::Helvetica, true, true) => "Helvetica-BoldOblique",
- (Family::Courier, false, false) => "Courier",
- (Family::Courier, true, false) => "Courier-Bold",
- (Family::Courier, false, true) => "Courier-Oblique",
- (Family::Courier, true, true) => "Courier-BoldOblique",
- (Family::Times, false, false) => "Times-Roman",
- (Family::Times, true, false) => "Times-Bold",
- (Family::Times, false, true) => "Times-Italic",
- (Family::Times, true, true) => "Times-BoldItalic",
+ (Family::Helvetica, false, false) => Std14::Helvetica,
+ (Family::Helvetica, true, false) => Std14::HelveticaBold,
+ (Family::Helvetica, false, true) => Std14::HelveticaOblique,
+ (Family::Helvetica, true, true) => Std14::HelveticaBoldOblique,
+ (Family::Courier, false, false) => Std14::Courier,
+ (Family::Courier, true, false) => Std14::CourierBold,
+ (Family::Courier, false, true) => Std14::CourierOblique,
+ (Family::Courier, true, true) => Std14::CourierBoldOblique,
+ (Family::Times, false, false) => Std14::TimesRoman,
+ (Family::Times, true, false) => Std14::TimesBold,
+ (Family::Times, false, true) => Std14::TimesItalic,
+ (Family::Times, true, true) => Std14::TimesBoldItalic,
}
}
+ /// The PDF base font name for a face.
+ pub fn base_font(self, bold: bool, italic: bool) -> &'static str {
+ self.std14(bold, italic).base_font()
+ }
+
/// The resource name used in content streams and `/DA` strings (Acrobat's conventions).
pub fn resource_name(self, bold: bool, italic: bool) -> &'static str {
match (self, bold, italic) {
@@ -121,16 +127,12 @@ impl Face {
self.family.resource_name(self.bold, self.italic)
}
- /// Advance of `s` at this face's size.
+ /// Advance of `s` at this face's size: the standard-14 font it is drawn in, at that font's
+ /// own widths (ISO 32000-2 Annex D) and encoded as it is written, then the horizontal scale.
pub fn width(&self, s: &str) -> f64 {
#[cfg(test)]
MEASURED.with(|m| m.set(m.get().saturating_add(s.len() as u64)));
- let designed = match self.family {
- Family::Courier => s.chars().count() as f64 * 0.6 * self.size,
- Family::Helvetica => pdfcraft_fonts::helvetica_width(s, self.size) * if self.bold { 1.04 } else { 1.0 },
- Family::Times => pdfcraft_fonts::helvetica_width(s, self.size) * if self.bold { 0.96 } else { 0.92 },
- };
- designed * self.h_scale
+ self.family.std14(self.bold, self.italic).text_width(s, self.size) * self.h_scale
}
}
@@ -153,6 +155,9 @@ pub struct Span {
pub baseline: f64,
pub text: String,
pub face: Face,
+ /// Where the text links to (its run's `<a href>`), as the template writes it, shared with the
+ /// link's other spans.
+ pub link: Option<std::sync::Arc<str>>,
}
/// A laid-out block of text.
@@ -168,6 +173,9 @@ struct Word {
text: String,
face: Face,
width: f64,
+ /// The link of the run the word came from, shared, not copied, so a long link over many
+ /// words costs one address.
+ link: Option<std::sync::Arc<str>>,
}
/// The width of `w` without the spaces it ends with: what it takes at the end of a line, where
@@ -213,7 +221,7 @@ fn words(runs: &[Run], base: &Face, embed: &dyn Fn(&str, usize) -> String, embed
.filter_map(|c| match c {
'\r' | '\n' | '\t' | '\u{2028}' | '\u{2029}' | '\u{2009}' | '\u{202F}' | '\u{3000}' => Some(' '),
'\u{00AD}' | '\u{200B}' | '\u{200C}' | '\u{200D}' | '\u{FEFF}' => None,
- '\u{2011}' | '\u{2010}' | '\u{2012}' | '\u{2013}' => Some('-'),
+ '\u{2010}'..='\u{2013}' => Some('-'),
'\u{2018}' | '\u{2019}' => Some('\''),
_ => Some(c),
})
@@ -224,12 +232,12 @@ fn words(runs: &[Run], base: &Face, embed: &dyn Fn(&str, usize) -> String, embed
cur.push(ch);
if ch == ' ' {
let width = face.width(&cur);
- out.push(Word { text: std::mem::take(&mut cur), face: face.clone(), width });
+ out.push(Word { text: std::mem::take(&mut cur), face: face.clone(), width, link: run.link.clone() });
}
}
if !cur.is_empty() {
let width = face.width(&cur);
- out.push(Word { text: cur, face, width });
+ out.push(Word { text: cur, face, width, link: run.link.clone() });
}
}
out
@@ -277,7 +285,7 @@ pub fn layout(rich: &RichText, rect: Rect, para: &Para, base: &Face, embed: &dyn
if advance > avail - indent(line.first) && piece.len() > ch.len_utf8() {
piece.pop();
let width = w.face.width(&piece);
- line.words.push(Word { text: std::mem::take(&mut piece), face: w.face.clone(), width });
+ line.words.push(Word { text: std::mem::take(&mut piece), face: w.face.clone(), width, link: w.link.clone() });
line.width += width;
line.size = line.size.max(w.face.size);
let done = std::mem::replace(&mut line, Line { words: Vec::new(), width: 0.0, size: base.size, first: false });
@@ -290,7 +298,7 @@ pub fn layout(rich: &RichText, rect: Rect, para: &Para, base: &Face, embed: &dyn
let width = w.face.width(&piece);
line.size = line.size.max(w.face.size);
line.width += width;
- line.words.push(Word { text: piece, face: w.face.clone(), width });
+ line.words.push(Word { text: piece, face: w.face.clone(), width, link: w.link.clone() });
}
first_in_para = false;
continue;
@@ -335,16 +343,17 @@ pub fn layout(rich: &RichText, rect: Rect, para: &Para, base: &Face, embed: &dyn
};
// Baseline: ascent sits about 0.8 of the size below the line top for these faces.
let baseline = y + lh - (lh - line.size * 0.8).max(0.0) / 2.0 - line.size * 0.08;
+ // Words of one face and one link make one span, so a link's text is a span of its own.
let mut run: Option<Span> = None;
for w in line.words {
match &mut run {
- Some(s) if s.face == w.face => s.text.push_str(&w.text),
+ Some(s) if s.face == w.face && s.link == w.link => s.text.push_str(&w.text),
_ => {
if let Some(s) = run.take() {
x += s.face.width(&s.text);
spans.push(s);
}
- run = Some(Span { x, baseline, text: w.text, face: w.face });
+ run = Some(Span { x, baseline, text: w.text, face: w.face, link: w.link });
}
}
}
diff --git a/crates/xfdf/src/lib.rs b/crates/xfdf/src/lib.rs
index 5c0be52..6131c9c 100644
--- a/crates/xfdf/src/lib.rs
+++ b/crates/xfdf/src/lib.rs
@@ -235,7 +235,7 @@ fn hex(c: &[f64]) -> Option<String> {
fn parse_hex(s: &str) -> Option<[f64; 3]> {
let h = s.trim().trim_start_matches('#');
- if h.len() != 6 {
+ if h.len() != 6 || !h.bytes().all(|b| b.is_ascii_hexdigit()) {
return None;
}
let p = |i: usize| h.get(i..i + 2).and_then(|s| u8::from_str_radix(s, 16).ok()).map(|v| f64::from(v) / 255.0);
@@ -271,8 +271,10 @@ fn text_of(doc: &Document, d: &Dict, k: &[u8]) -> Option<String> {
})
}
+/// The numbers of a list; empty when any entry is non-finite (`nan`, `inf`), so the list is unusable as a whole.
fn csv(list: &str) -> Vec<f64> {
- list.split([',', ';', ' ']).filter(|t| !t.is_empty()).filter_map(|t| t.trim().parse().ok()).collect()
+ let v: Vec<f64> = list.split([',', ';', ' ']).filter(|t| !t.is_empty()).filter_map(|t| t.trim().parse().ok()).collect();
+ if v.iter().all(|x| x.is_finite()) { v } else { Vec::new() }
}
fn arr(v: &[f64]) -> Object {
diff --git a/crates/xfdf/src/tests.rs b/crates/xfdf/src/tests.rs
index fb88da3..17c48c2 100644
--- a/crates/xfdf/src/tests.rs
+++ b/crates/xfdf/src/tests.rs
@@ -1759,6 +1759,15 @@ fn an_imported_redaction_rect_with_a_non_number_is_not_used() {
assert!(mark.get(b"QuadPoints").is_none(), "quads were drawn from a malformed /Rect: {mark:?}");
}
+#[test]
+fn a_colour_with_non_hex_digits_is_rejected() {
+ assert!(parse_hex("#+f+f+f").is_none());
+ assert!(parse_hex("#+1+2+3").is_none());
+ assert!(parse_hex("#-1-2-3").is_none());
+ assert!(parse_hex("#ff00zz").is_none());
+ assert_eq!(parse_hex("#FF8000").map(|c| c[0]), Some(1.0));
+}
+
/// An FDF body with `body` as its `/FDF` dictionary contents and `objects` (numbered from 2).
fn fdf_with(body: &str, objects: &[String]) -> Vec<u8> {
let mut out = format!("%FDF-1.2\n1 0 obj\n<< /FDF << {body} >> >>\nendobj\n");
@@ -1865,3 +1874,62 @@ fn a_comment_locked_by_an_indirect_flag_is_not_replaced_by_an_import() {
assert!(annots.contains(&Object::Ref(note)), "the locked comment was replaced");
assert_eq!(doc.get(note), before, "the locked comment was changed");
}
+
+#[test]
+fn import_skips_annotations_with_non_finite_coordinates() {
+ for rect in ["nan,10,100,100", "0,inf,100,100", "0,10,infinity,100", "0,10,100,-inf"] {
+ let mut doc = blank();
+ let xfdf = format!(
+ r#"<xfdf xmlns="http://ns.adobe.com/xfdf/"><annots><square page="0" rect="0,0,50,50" name="good"/><square page="0" rect="{rect}" name="bad"/></annots></xfdf>"#
+ );
+ let r = import(&mut doc, xfdf.as_bytes()).unwrap();
+ assert_eq!(r.comments, 1, "rect {rect}: {r:?}");
+ let names = annots_of(&doc);
+ assert_eq!(names.len(), 1, "rect {rect}: {names:?}");
+ assert_eq!(names[0].get(b"NM"), Some(&PdfString::literal(b"good".to_vec()).into()), "rect {rect}");
+ }
+}
+
+#[test]
+fn import_drops_non_finite_numbers_from_every_coordinate_list() {
+ let xfdf = r#"<xfdf xmlns="http://ns.adobe.com/xfdf/"><annots>
+ <line page="0" rect="0,0,50,50" name="line" start="nan,0" end="10,10"/>
+ <polygon page="0" rect="0,0,50,50" name="poly"><vertices>1,2;inf,4;5,6</vertices></polygon>
+ <ink page="0" rect="0,0,50,50" name="ink"><inklist><gesture>1,2;3,-inf</gesture></inklist></ink>
+ <freetext page="0" rect="0,0,50,50" name="callout" callout="1,2,nan,4,5,6"/>
+ <highlight page="0" rect="0,0,50,50" name="hl" coords="0,0,infinity,0,0,10,10,10"/>
+ </annots></xfdf>"#;
+ let mut doc = blank();
+ let r = import(&mut doc, xfdf.as_bytes()).unwrap();
+ assert_eq!(r.comments, 5, "{r:?}");
+ fn finite(doc: &Document, o: &Object) -> bool {
+ match &*doc.resolve(o) {
+ Object::Real(x) => x.is_finite(),
+ Object::Array(a) => a.iter().all(|e| finite(doc, e)),
+ _ => true,
+ }
+ }
+ let annots = annots_of(&doc);
+ assert_eq!(annots.len(), 5);
+ for d in &annots {
+ for (k, v) in d.iter() {
+ if k.as_slice() != b"P" {
+ assert!(finite(&doc, v), "{d:?}");
+ }
+ }
+ assert!(d.get(b"L").is_none() && d.get(b"CL").is_none() && d.get(b"Vertices").is_none(), "{d:?}");
+ }
+}
+
+fn annots_of(doc: &Document) -> Vec<Dict> {
+ let page = &pdfcraft_model::pages(doc)[0];
+ page.dict
+ .get(b"Annots")
+ .map(|a| doc.resolve(a))
+ .and_then(|a| a.as_array().cloned())
+ .unwrap_or_default()
+ .iter()
+ .map(|a| doc.resolve(a).as_dict().cloned().unwrap())
+ .filter(|d| d.get(b"Subtype") != Some(&Object::name("Widget")))
+ .collect()
+}
diff --git a/vendor/README.md b/vendor/README.md
index 3f531a2..be88a91 100644
--- a/vendor/README.md
+++ b/vendor/README.md
@@ -17,23 +17,16 @@ Other resource categories retain their existing parent-chain lookup.
| Crate | Version | Licence | Patches | Test |
|---|---|---|---|---|
-| hayro-interpret | 0.7.0 | Apache-2.0 OR MIT | (1) select `/AP /N` appearance states via `/AS` (checkboxes, radios, stateful icons) and honour the NoView flag; (2) Type3 Unicode fallback to `/Encoding` glyph names, then printable ASCII; (3) `Type3Glyph::advance_width`; (4) `InterpreterSettings::ocg_overrides` for viewer layer toggles; (5) soft masks whose group lacks `/CS` were dropped (Chrome gradient text); (6) paint nesting cap `MAX_PAINT_NESTING` for tiling patterns and Type 3 glyphs (self-referencing content overflowed the stack); (7) CID width ranges in `/W` and `/W2` clamped to `MAX_CID` (a `0 4294967295 w` range hung); (8) `InterpreterSettings::hide_comments` skips markup annotations but keeps widgets and links (View ▸ Hide all comments); (9) `image_size_ok`: images and masks over 2^28 pixels are not decoded (a fuzzed `/W 4294967295` stencil mask allocated 4 GiB); (10) `MAX_NESTED_PAINTS`: nested paints (forms, Type 3 glyphs and tiling patterns inside one another) share a per-page budget of 50,000 (a glyph showing eight glyphs of its own font, sixteen deep, hung); (11) depends on skrifa 0.47 instead of 0.42 (upstream read-fonts fixed a Type 1 tokenizer that recursed through runs of numbers: a fuzzed font hung or overflowed the stack), with the one API change (`Charset::glyph_id` returns `Option`); (12) annotation appearances whose `/BBox` or `/Matrix` collapses to a line or a point are skipped (mapping them onto `/Rect` divided by zero and handed the device infinite or NaN matrices); (13) a Highlight annotation without a usable normal appearance is drawn from its `/QuadPoints`, `/C` and `/CA` with Multiply blending, as pdfcraft-annot draws highlights (it was not drawn at all); (14) simple-font `/Widths` (`read_widths`): entries only for codes 0–255 (one entry per code below `/FirstChar` was allocated: `4294967295` asked for 34 GB), an entry that isn't a number leaves its code missing instead of ending the array, and a `/LastChar` below `/FirstChar` gives no widths instead of discarding the font for a standard one; (15) the appearance box is mapped onto `/Rect` corner to corner: the translation now accounts for the scale (an appearance whose box didn't start at the origin and differed in size from `/Rect` was drawn shifted); (16) a clip set by `W`/`W*` takes effect after whichever path-painting operator ends the path (`S`, `f`, `B`, … as well as `n`; ISO 32000-2 §8.5.4): it was applied only on `n`, so `re W* S` clipped nothing and the clip stayed pending for a later, unrelated `n`; (17) `InterpreterSettings::cancelled`: once set, interpretation stops before the next content operator (a render pool sets it for every worker when dropped, after an edit or on closing, and for one worker when the watchdog gives up on its render, so renders whose answers nobody can receive stop instead of running to the end); (18) `MAX_PAGE_CONTENT`: the content a page holds at once (its contents, and the forms, tiling patterns and Type 3 glyph procedures being painted) stays within 512 MiB (`decode_content`; once it runs out, `InterpreterWarning::ContentTruncated` is reported (once per page by pdfcraft-render) so a truncated page is not a clean render; each level gives its bytes back when it finishes): forms nest fifty deep and each level kept its content while the next ran, so a form painting itself around a stream inflating to 256 MiB would have held over 12 GB; and Type 0 sampled functions take at most `MAX_SAMPLE_ENTRIES` (2^21) table points and `MAX_SAMPLE_VALUES` (2^23) samples, read no further than `/Size` asks (256 MiB of 1-bit samples asked for over 8 GB); (19) mesh shadings (types 4–7) are sampled only inside the area being drawn (`ShadingPattern::encode_within`, which the vendored hayro renderer calls with that area plus a pixel), within 8 visits per pixel of it plus 4 per triangle (`TriangleSampler`), and patches are triangulated one at a time: points far off the page were sampled over their whole bounding box, up to 65536 × 65536 entries (a fuzzed 147-byte patch stream; a synthetic page passed 6 GB in six seconds), ten thousand overlapping triangles ran for minutes, and every patch became 722 triangles before any limit; meshes hold at most `MAX_MESH_PATCHES` (2^16) patches and `MAX_MESH_TRIANGLES` (2^20) triangles, a lattice needs two to 2^19 vertices per row (`/VerticesPerRow 0` pushed empty rows for ever; one huge row read the whole stream), and a page samples at most `MAX_PAGE_MESH_TRIANGLES` (2^25) mesh triangles in all (a mesh painted a thousand times was triangulated a thousand times); each cut logs a warning; (20) PDF function construction is limited to 64 levels and 10,000 total nodes with cycle detection; calculator parsing and evaluation share procedure depth/work budgets, integer division/bitshift/rotation/index are panic-free, and fixed-size stack errors propagate; (21) a Type 0 font drawn with a substitute that isn't CID-keyed (it isn't embedded, or its program doesn't load) draws `.notdef` for a CID of an Adobe character collection (Japan1, GB1, CNS1, Korea1) that it can't find by Unicode: hayro took the CID for a glyph index of the substitute, which numbers its glyphs its own way, so the character was drawn as an unrelated one (𠮷 as "Q" in BIZ UDPGothic); (22) a Type 0 font drawn with a substitute finds a character given with a variation selector (`/ToUnicode`, or Adobe-Japan1-UCS2, which maps the JIS X 0208 forms of the kanji JIS X 0213:2004 redrew that way: CID 1247 is 噂 U+E0100) through the substitute's variation sequences, else as the character alone: such a CID found no glyph and was drawn as an unrelated one; (23) backport of hayro 0.8's `gradient` module: `EncodedShadingPattern::as_svg_gradient` turns an axial or radial shading into stops of an sRGB gradient (within 0.01 per channel, a stop at every stitching-function bound via `Function::stitching_bounds`) when a native gradient draws it exactly (extended past the box drawn in; a radial one with no background colour); (24) `DecodedImageCache`: decoded image pixels shared across renders through the interpreter cache within a 64 MiB budget (an image-heavy page decoded its thousands of images again per tile and per scale), keyed by every decode input (`DecodedImageKey`: the stream's place and dictionary bytes, its object, mask/stencil/raster output, interpolation, decode target size, preview or final); images under a transfer function and inline images are not cached, an image over the budget is never kept, and a poisoned lock decodes uncached; (25) `Device::actual_text` hands the device a marked content sequence's `/ActualText` (inline or named in `/Properties`), so text extraction keeps the Thai, Indic and Arabic clusters Chrome marks this way (their shaped tone marks and vowels have no Unicode of their own); (26) non-embedded simple fonts drawn with a standard-font stand-in build the Latin Extended-A letters the stand-in lacks (`/Gbreve`, `/Idotaccent`, `/Scedilla`, `/aogonek`, `/ccaron`…) from the base letter and accent it has (`StandardKind::composite_glyph`, `ACCENTED_LETTERS`): PDFium's Foxit stand-ins hold only the Standard/WinAnsi/Mac Roman glyphs, so iText letters with Times New Roman unembedded showed blanks for Ğ, İ, Ş, ğ and ş; the comma-below letters (`/scommaaccent`, `/Tcommaaccent`, `/kcommaaccent`…, found by character, so `/uni0136` and the glyph list's `/Kcedilla` too) are the letter and the font's comma, smaller and under the baseline, since the stand-ins have no `commaaccent` (Romanian ș drew nothing and ț a cedilla in forms laid out from XFA; ģ, whose comma is turned and above, is not built); (27) an embedded TrueType font without a base encoding reads its codes as WinAnsi for text extraction (`EmbeddedKind::code_to_unicode_name`), matching pdftotext's output, instead of Standard: OCR text layers of scans write WinAnsi codes with no `/Encoding`, and Standard has no ü, ö or ß and reads é as Ø (glyph selection unchanged); (28) an image whose pixels hold at most 16 bits of samples (an 8-bit Separation or DeviceN image, a 1-, 2- or 4-bit gray or indexed one) is converted once per possible pixel value through a lookup table instead of once per pixel (`rgb_via_lookup`): a spot-colour tint transform is often a PostScript calculator program, run for every pixel, so a fillable character sheet's 3304 × 4105 DeviceN background took four seconds and 430 MB to draw a page; each entry is converted on its own (`convert_each`), so a tint transform giving the wrong number of components for a value the image never uses cannot shift the colours of the values it does; (29) `Device::begin_annotations`/`end_annotations` bracket the page's annotations, so a device can tell comment paints from document paints (reading colours recolour the document, never a comment, #1548); (30) the Annex D.2 alias codes read as the ink they draw: WinAnsiEncoding 0xA0 and 0xAD, and MacRomanEncoding 0xCA, carry the glyph names `space` and `hyphen` -- the names those tables also give 0x20 and 0x2D -- not `nbspace` and `sfthyphen`, whose glyph list values U+00A0 and U+00AD are invisible formatting characters. Extraction hid drawn ink behind them, so search and redaction matched neither (`XiaoBiaoSong.pdf` in the pdf.js corpus drew 104 soft hyphens; across the 989 files the soft hyphens we extract fall from 117 to 13 and the non-breaking spaces from 30 to 26, what remains coming from `/ToUnicode` maps, which say so explicitly). The base table only, in the text direction only: a `/Differences` name keeps its glyph list value and glyph lookup is untouched, both as pdftotext does; (31) a Type 0 sampled function keeps its samples in one flat array indexed by strides (`Type0::entry`) instead of a hash map keyed by each grid point: the map was built again, one hashed insert per sample, every time a shading using the function was painted (a 2,097,152-sample ramp painted 30 times took 38 s; `bug1721218` in the pdf.js corpus spent most of a 1.5 s page on it); the interpolation is unchanged, so results are bit for bit the same, a sample missing from a short stream still gives no value, and the maximum sample value is computed without overflowing at 32 bits per sample; (32) the decoded-image cache (24) keys a decode by the size the image is drawn at only when a JPX stream decodes it or its soft mask or mask (`decode_reads_target`): JPX is the only filter that decodes a reduced resolution for a size, so a JPEG or Flate scan was decoded again at every zoom step and kept once per zoom level; one decode now serves every size; `InterpreterCache::decoded_image_decodes` counts the cache's decodes; (33) Coons and tensor-product patches copy their vertices' colours less: each point of a patch's 20 × 20 triangle grid is interpolated once (`generate_patch_triangles`; each cell interpolated its four corners itself, 1,444 interpolations a patch for 400 points), a cell's second triangle takes the vertices its first copied, and the mesh sampler moves a patch's triangles into device space instead of copying each vertex (`TriangleSampler::sample_owned`); the same values, 10–16% faster on mesh-gradient pages; (34) `color::tint_transform_runs`: how many colours the calling thread has run through a Separation or DeviceN tint transform (counted once per batch in `convert_f32`), so a test counts patch (28)'s once-per-sample-value runs instead of timing them (its 10 s deadline failed on a busy FreeBSD VM in CI); (35) `EncodedShadingPattern::extent`: where a mesh shading (types 4–7) can paint at all, the pixels its triangles touched when it was encoded (`None` for the types that paint everywhere, and when the shading has a `/Background`), so the renderer samples a texture there alone and skips a mesh with nothing on the canvas; (36) a mesh shading's pixel whose corner no triangle holds strictly (on an edge two triangles share, or on the mesh's side) takes the triangle that covers its centre, edges included (`Triangle::covers`): testing only the corner left a white seam along every shared edge, and the colour is still taken at the corner; (38) the `/DefaultGray`, `/DefaultRGB` and `/DefaultCMYK` colour spaces of a resource dictionary (ISO 32000-2 §8.6.5.6) replace the device space content selects: with `g`/`G`, `rg`/`RG`, `k`/`K` and `cs`/`CS` (by name, or through a `/ColorSpace` resource that is a device space), and as the `/ColorSpace` of an image XObject, an inline image or a shading painted by `sh` or as a shading pattern (`DefaultColorSpaces`, looked up once per content window in the resources and those they inherit, so a form XObject without a default of its own draws in its page's, as Poppler and MuPDF draw it); a default that is a Lab, Indexed, Pattern or device space, has another number of components or is no colour space is ignored and device colour is drawn as before; device spaces inside other spaces (an Indexed base, a Separation or DeviceN alternate, a Pattern's underlying space), shading dictionaries, masks and transparency group spaces are unchanged, and the decoded-image cache (24) keys a decode by the default it was drawn in. hayro drew device colour as it was, so pages that calibrate it this way (common in PDF/A) came out in the wrong colours; (39) knockout groups (#2971): `Device::set_knockout` right after a `/K true` group is pushed; `Device::knockout_image` for an unmasked image before its group is pushed, when `Device::in_knockout_group`: the device clears its placement rectangle only if it will draw the image (on the canvas, not a preview's tiny image, and it decodes), decoded at its draw size so the draw reuses that decode; and, when `Device::knockout_erase_wanted`, a nested group's content drawn once between `begin_knockout_erase` and `end_knockout_erase` before the group itself, which then always gets a layer of its own; (40) an optional content membership dictionary's visibility expression (`/VE`: `/And`, `/Or`, `/Not`, nested up to 32 deep) decides its visibility ahead of `/OCGs` and `/P` (ISO 32000-2 §8.11.2.2); it was ignored, so content under it stayed visible with its layers hidden; a malformed expression, including one naming an object the document doesn't list in `/OCProperties /OCGs`, falls back to `/OCGs` and `/P` (#2986); (41) a transparency group that is neither isolated nor knockout, entered at full opacity with no soft mask and Normal blending, is drawn straight onto the page instead of into a layer of its own (§11.4.7: its elements composite with the backdrop; the layer made a `/BM /Multiply` highlight appearance an opaque block, #1968); (42) text in a Type 3 font is drawn filled whatever the text rendering mode, except mode 3 (invisible): only that mode has any effect on Type 3 fonts (ISO 32000-1 §9.3.6). Stroking ran the glyph procedure a second time, so `2 Tr` made bitmap fonts look bold, `1 Tr` painted an uncoloured glyph in the stroking colour, and `7 Tr` hid it; (43) Lab colour spaces honour their own `/WhitePoint`: L\*a\*b\* goes to XYZ relative to that white, is Bradford-adapted to D65 and converted to sRGB (ISO 32000-2 §8.6.5.4) instead of through `LAB.icc` as if every white were D50 (a D65 blue came out 45 levels too red; the profile is removed); components normalised to [0, 1] (`manual_scale`, an `/Indexed` palette over Lab) map onto L\* 0..100 and the a\*/b\* `/Range`; (44) a Type 0 font whose `/ToUnicode` is the name `/Identity-H` or `/Identity-V` (not a CMap stream; WSCAD writes it) reads each code as its Unicode value, as Acrobat shows it (`Type0Font::identity_to_unicode`); the identity CMap the name resolved to maps codes to CIDs only, so such pages had no text to select or find; (46) an image XObject's group applies the fill opacity, so the fill alpha is reset to 1 before a stencil mask takes the fill colour as its paint, and a pattern paint drops the opacity it captured at `scn` (`Pattern::without_opacity`) (it was applied twice: a mask at `ca 0.5` was drawn at a quarter, #2975); (47) `path_as_rect`: a five-element path is a rectangle only when its four points are distinct, each step from one to the next runs along a single axis, and the last returns to the first. The length test admits one MoveTo and four LineTo as well as one MoveTo, three LineTo and a ClosePath, and asking only that every corner of the bounding box was visited says nothing about the order or the steps between, so a five-point polyline whose ends reached the corners was painted as that box -- a fourth side the path does not have -- and a clip of that shape was discarded; the coordinates are compared exactly, since the matrix is applied after this check and a `cm` of 10,000 turns `is_nearly_equal`'s 256th of a unit into tens of device units (#3327); (48) an `/ICCBased` colour space is cached by what its profile is read from (`IccProfileKey`): the stream object it names, looked up without reading the stream, and then the stream's dictionary and its own bytes (decrypted, not decoded), so a byte-for-byte copy of a profile in another object is read once, and a profile stream written directly in its array, which reports the object holding the array as every other stream written there does, is told apart by its bytes. hayro keyed it by the stream dictionary's bytes alone, so two different profiles with the same `/N` and `/Length` shared whichever was read first, and colours in the second were drawn through the first. `InterpreterCache::icc_profile_reads` counts the profiles read; (49) `OpenTypeFontBlob::new` also accepts a `post` table version 1.0, 2.0 or 3.0 written with its 16-bit halves swapped (`00 00 00 03`), as ScanSoft PDF Create! embeds every font; such fonts were refused and their text drawn with a substitute (Hebrew came out garbled or missing, #2946); `glyph_names` reads such a table from a copy with the version written correctly, so a 2.0 table's names serve `/Differences`. Any other unknown version is still refused (pdf.js 9462); (50) `CffFontBlob::glyph_index_by_name` looks a glyph name up in a name to glyph map built on first use (shared between clones) instead of searching the whole charset, with a string lookup per glyph, for every character code of a font; the first glyph with a name still wins; (51) `StandardFont::win_ansi_width`: the standard-14 advance widths by WinAnsiEncoding code, public, so text PdfCraft sets in the standard fonts (Office files converted by Create) is measured exactly; (52) `InterpreterSettings::hide_notes` skips sticky notes (`/Text` annotations) only, for the Android viewer, which draws its own fixed-size note icons | (1) `raster::tests::widget_appearance_states`; (2, 3) `xtask text-oracle` on corpus/pdfjs issue918; (4) `raster::tests::layer_override_hides_content`; (5) `raster::tests::soft_mask_without_group_colour_space_is_applied`; (6) `raster::tests::self_referencing_tiling_pattern_terminates`, `raster::tests::self_referencing_type3_glyph_terminates`; (7) `raster::tests::huge_cid_width_ranges_terminate`; (8) `raster::tests::hiding_comments_keeps_fields`; (9) `raster::tests::absurd_mask_and_fax_sizes_are_refused_before_decoding`; (10) `raster::tests::type3_glyphs_that_fan_out_into_themselves_finish`; (11) `raster::tests::type1_font_programs_with_long_runs_of_numbers_load_quickly`; (12) `raster::tests::degenerate_annotation_appearances_are_skipped`; (13) `raster::tests::highlights_without_an_appearance_are_drawn`; (14) `raster::tests::malformed_simple_font_widths_keep_later_widths_and_the_font`, `raster::tests::huge_simple_font_first_char_terminates`; (15) `raster::tests::annotation_appearance_box_maps_onto_rect`; (16) `raster::tests::clipping_path_applies_after_any_painting_operator`; (17) `raster::tests::dropping_the_pool_cancels_its_renders`, `raster::tests::the_watchdog_stops_the_render_it_gives_up_on`; (18) `raster::tests::page_contents_and_nested_forms_share_one_budget`, `raster::tests::content_painted_again_and_again_keeps_drawing`, `raster::tests::sampled_functions_with_billions_of_samples_are_refused`; (19) `raster::tests::mesh_shadings_far_off_the_page_render`, `raster::tests::many_overlapping_mesh_triangles_finish`, `raster::tests::mesh_shadings_with_many_patches_or_no_rows_finish`; (20) `raster::tests::function_limits_calculator_arithmetic_and_depth`, `raster::tests::function_limits_public_construction_work_and_depth`, `raster::tests::function_limits_stitching_cycles_are_refused_and_shared_children_work`, `raster::tests::function_limits_invalid_calculator_keeps_the_page_renderable`; (21) `raster::tests::cids_a_substitute_lacks_are_not_drawn_as_other_glyphs`; (22) `raster::tests::variation_sequences_draw_their_kanji_in_a_substitute`; (23) `raster::tests::axial_and_radial_shadings_draw_as_native_gradients`; (24) `raster::tests::tiles_match_full_render`, `raster::tests::skipping_paths_off_the_canvas_changes_no_pixel` (both decode through the cache), `raster::tests::decoded_images_with_identical_dictionaries_keep_their_own_pixels`, `raster::tests::decoded_images_under_a_transfer_function_are_not_shared`; (25) `text::tests::actual_text_replaces_the_glyphs_it_marks_in_every_writing_direction`, `text::tests::actual_text_follows_the_pdf_rules_for_marked_content`; (26) `raster::tests::accented_letters_the_standard_stand_ins_lack_are_built_from_their_parts`, `raster::tests::comma_below_letters_in_standard_fonts_draw_a_comma_under_the_letter`; (27) `text::tests::truetype_without_an_encoding_reads_its_codes_as_win_ansi`; (28) `raster::tests::spot_colour_images_run_their_tint_transform_once_per_sample_value`, `raster::tests::images_converted_through_a_table_keep_every_samples_colour`, `raster::tests::a_malformed_tint_for_an_unused_sample_keeps_the_used_colours`; (29) `raster::tests::reading_colors_keep_highlight_annotations_readable`; (30) `text::tests::the_annex_d2_alias_codes_read_as_an_ordinary_hyphen_and_space`; (31) `raster::tests::shadings_with_large_sampled_functions_paint_quickly`, `raster::tests::sampled_functions_interpolate_their_grid_as_before`; (32) `raster::tests::decoded_images_serve_every_size_they_are_drawn_at`; (33) `raster::tests::patch_meshes_keep_their_corner_colours`; (34) `raster::tests::spot_colour_images_run_their_tint_transform_once_per_sample_value`; (35) `mesh_extent_tests::{a_mesh_paints_its_triangles_alone, a_mesh_keeps_the_graphics_state_alpha, a_mesh_off_the_canvas_paints_nothing}` (`cargo test -p hayro`); (36) `raster::tests::mesh_triangles_sharing_an_edge_leave_no_seam`; (38) `raster::tests::default_colour_spaces::device_rgb_operators_draw_in_default_rgb`, `raster::tests::default_colour_spaces::device_cmyk_operators_draw_in_default_cmyk`, `raster::tests::default_colour_spaces::device_gray_operators_draw_in_default_gray`, `raster::tests::default_colour_spaces::device_images_draw_in_the_default_colour_spaces`, `raster::tests::default_colour_spaces::device_shadings_draw_in_the_default_colour_spaces`, `raster::tests::default_colour_spaces::an_image_drawn_with_and_without_a_default_keeps_both_colours`, `raster::tests::default_colour_spaces::forms_inherit_the_default_colour_spaces_they_do_not_override`, `raster::tests::default_colour_spaces::unusable_defaults_leave_device_colour_alone`; (39) `raster::tests::knockout_groups_replace_what_their_elements_cover`; (40) `raster::tests::visibility_expressions_decide_what_a_membership_dictionary_shows`; (41) `raster::tests::a_multiply_highlight_inside_a_transparency_group_keeps_the_text`; (42) `raster::tests::text_rendering_modes_other_than_invisible_draw_type3_glyphs_as_filled`; (43) `raster::tests::lab_honours_the_space_white_point`, `raster::tests::indexed_palettes_over_lab_keep_their_colours` |; (44) `text::tests::identity_to_unicode_names_give_text`; (46) `raster::tests::stencil_masks_are_drawn_at_the_fill_opacity_once`; (47) `raster::tests::a_five_point_polyline_is_not_painted_as_its_bounding_box`, `raster::tests::a_path_that_visits_every_corner_out_of_order_is_not_a_rectangle`, `raster::tests::a_rectangle_is_still_painted_as_a_rectangle`; (48) `raster::tests::icc_profile_cache::icc_profiles_with_identical_dictionaries_draw_their_own_colours`, `raster::tests::icc_profile_cache::icc_profiles_used_again_are_read_once`; (49) `raster::tests::a_font_whose_post_version_has_swapped_halves_is_still_used`; (50) `font::blob::tests::glyph_names_resolve_to_the_first_glyph_with_that_name`; (51) `pdfcraft-create` `office::tests::standard_font_widths_come_from_the_metrics`; (52) `raster::tests::hiding_notes_keeps_other_comments` |
-
-| hayro | 0.7.1 | Apache-2.0 OR MIT | (1) `RenderSettings::{x_offset, y_offset}` to render one tile of a large page; (2) images over `MAX_IMAGE_PIXELS` (2^28) are skipped (a fuzzed `/W 4294967295` hung in resampling); (3) `tiling_cell_scale` keeps a tiling pattern's cell pixmap within 3000 px a side whatever its `/XStep`/`/YStep` (a fuzzed step far beyond `/BBox` allocated 2 GB); (4) stroke widths clamped to 4 × (canvas width + height) device pixels (a fuzzed `/LW 9223372036854775807` allocated 10 GB in stroke expansion); (5) `usable_dash_pattern`: a stroke whose dash pattern could cut it into more than `MAX_DASHES_PER_STROKE` (250,000) pieces, counting kurbo's restart of the pattern at every subpath and `ClosePath`, is drawn solid (a fuzzed `/D [[11] 0]` on a line from x = 92234775807 allocated over 5 GB, `[0.000001] 0 d` on a 20 pt line over 10 GB); (6) a dash pattern with a negative or non-finite entry, or a period that isn't positive, is drawn solid (`[-1 -1] 0 d` looped for ever in kurbo); (7) `render_size` and `render_into`: render into a buffer the caller allocates (PdfCraft renders into pixel-aligned memory that the GUI takes over as texture data); `render` is `render_into` on a new pixmap; (8) checked image source/target/RGBA, alpha-premultiplication scratch and intermediate sizes before resampling, finite transforms and exact source/mask buffers; sources wider than u16 may shrink before backend limits, with a 2^20 source-axis cap and conservative 128 MiB filter-planning estimate; an over-limit or failed resize keeps the original image resolution and geometry when the source fits the backend, otherwise skips it, with a logged warning; staging, resampling output/scratch, RGBA conversion and padding buffers use fallible reserves; (9) `may_paint_canvas`: a fill or stroke whose control-point box, grown by how far its paint reaches past the path (half the stroke width times the larger of the miter limit and √2) plus 0.5 user units and 2 pixels, misses the canvas is not drawn, so a tile no longer strokes and fills every path of its page (item 5 of #623); `set_skip_offscreen_paths` turns this off for the regression test; (10) backport of hayro 0.8: shadings that `as_svg_gradient` can represent are painted as a `vello_cpu` linear or two-point radial gradient instead of a texture sampled pixel by pixel through the shading function (InDesign fades are luminosity soft masks of one full-page axial `sh`: 40 on a report page took 15 s at 144 dpi, now under 1 s); without upstream's half-pixel shift, which suits vello_cpu 0.3 but moves 0.0.8's gradients off pixel centres; (11) `may_paint_rect`: an image whose stream-size box, mapped to the device, misses the canvas is skipped before decoding (decoded data can only shrink against that box), so a tile of an image-heavy page no longer decodes, resamples and rasterizes every image on it; (12) preview renders (`InterpreterSettings::preview`: backdrops, thumbnails, grid cells, signature-drag backgrounds) skip images under `PREVIEW_MIN_IMAGE_AREA` device pixels, while final renders always draw them; (13) reading colours (#897): `RenderSettings::color_replacement` takes a `ColorReplacement` (text colour, background, `only_black`, `line_art`) that remaps solid text and line-art paint while rendering, glyph outlines counting as text and stencil-mask ink as line art; images, image alpha masks, soft masks and pattern cells keep their colours; `render_pdf` gains a `color_replacement: Option<ColorReplacement>` argument (pass `None` for true colours); the upstream-only `[dev-dependencies.log]` entry is removed from `Cargo.toml` (log is a normal dependency since the logging patch), so `cargo test -p hayro` runs this crate's unit tests; (14) a shrunk, interpolated, axis-aligned image is snapped to whole device pixels: shrunk once to its rounded device rectangle and drawn 1:1 at the rounded corner, instead of a ceil-sized raster resampled again at a fractional scale and offset (`snap_minified_image`; scans looked soft next to Acrobat); (15) a soft mask of another size than its image is filtered when shrunk, whatever its `/Interpolate` (#1649): such a mask carries the shape on its own (Word saves text as a tiny black image with a glyph-bitmap mask), and nearest-neighbour dropped every stroke thinner than the shrink factor; (16) under a soft mask or a blend mode, axial and radial shadings are sampled instead of drawn as native gradients (#2128): vello_cpu 0.0.8 copies an opaque gradient over fully covered tiles without the mask or blend mode, so PowerPoint's faded gradient fills came out solid; (17) the renderer keeps annotation paints out of the reading-colours mapping between `begin_annotations` and `end_annotations` (#1548); (18) the page renders as one transparency group; under reading colours its background is painted inside it as the initial backdrop, so a Multiply highlight blends with the dark background instead of staying an opaque block, and otherwise the background stays outside, so a blend mode over an empty part of the page keeps its colour instead of blending with the white paper (#2970); (19) `set_paint` samples a mesh shading's texture over its triangles alone (`EncodedShadingPattern::extent`, padded rather than repeated) and skips a mesh with none on the canvas: a BricsCAD plan's 310 one-triangle `sh` each covered the whole tile, 2 s per 1024 px tile at any zoom (the watchdog gave the page up on a busy machine), now about 70 ms; (20) a tiling pattern whose step is too large for a cell pixmap, where what is painted (a fill, or a stroke with its width) can only show the first cell (PowerPoint's `/XStep 2147480100` for a picture fill drawn once), has its `/BBox` drawn at full scale with a transparent border and padded instead of tiled (`shows_one_cell`; a cell whose scale isn't finite and positive, from a `/BBox` too thin to divide by, keeps the old path: `usable_cell_scale`); shrinking the cell to fit the 3000 px limit of (3) left the picture under a pixel, so network diagrams lost their pictures (#3349); (22) knockout groups: while one is innermost, fills, strokes, glyph outlines and shadings are drawn with `Compose::Copy` (weighted by coverage), so each element replaces what earlier elements of the group drew instead of compositing over it; an image or nested group, drawn into a layer of its own, first has what is under its shape cleared (`knockout_image` for an unmasked image's rectangle, only when `draw_image` will draw it, decoded at the size it is drawn; a knockout erase pass that draws a nested group's content with every paint clearing instead of painting, a shading fill's clear clipped to the shading's `/BBox` as its paint is) and then composites over it (#2971) | (1) `raster::tests::tiles_match_full_render`; (2) `raster::tests::absurd_image_dimensions_are_skipped`; (3) `raster::tests::tiling_cells_stay_small_whatever_the_step`; (4) `raster::tests::absurd_predictor_columns_and_line_widths_render`; (5) `raster::tests::dash_patterns_that_cut_a_stroke_into_billions_of_pieces_render`; (6) `raster::tests::invalid_dash_patterns_terminate_and_are_drawn_solid`; (7) `raster::tests::pixels_are_a_plain_renders_bytes_in_a_buffer_a_gui_can_take_over`; (8) `raster::tests::image_resampling_rejects_anisotropic_target_growth`, `raster::tests::image_resampling_bounds_intermediate_before_planning`, `raster::tests::image_resampling_rejects_invalid_sources_and_scales`, `raster::tests::image_resampling_keeps_valid_sizes_and_exact_limits`, `raster::tests::resampling_fallback_preserves_original_geometry_and_pixels`, `raster::tests::image_resampling_wide_sources_shrink_before_backend_side_limits`, `raster::tests::image_resampling_wide_transparent_sources_still_shrink`, `raster::tests::image_resampling_padded_backend_dimensions_stay_checked`, `raster::tests::image_resampling_mismatched_alpha_mask_keeps_pixels_and_placement`; (9) `raster::tests::skipping_paths_off_the_canvas_changes_no_pixel`; (10) `raster::tests::axial_and_radial_shadings_draw_as_native_gradients`; (11) `raster::tests::skipping_paths_off_the_canvas_changes_no_pixel`; (12) `raster::tests::preview_renders_skip_tiny_images_but_finals_draw_everything`; (13) `color_replacement_tests::{black_maps_to_text_colour, white_maps_to_background, midgrey_interpolates, alpha_copied_verbatim, only_black_threshold, line_art_false_skips_paths_but_not_text}`, `color_replacement_render_tests::{color_replacement_maps_text_and_line_art, color_replacement_maps_stencil_mask_ink}`; (14) `raster::tests::interpolated_minified_image_edges_snap_to_whole_pixels` (`cargo test -p hayro`); (15) `raster::tests::shrunk_soft_mask_larger_than_its_image_keeps_thin_strokes`; (16) `raster::tests::soft_mask_applies_to_a_shading_pattern_fill`; (17), (18) `raster::tests::reading_colors_keep_highlight_annotations_readable`; (19) `mesh_extent_tests::{a_mesh_paints_its_triangles_alone, a_mesh_keeps_the_graphics_state_alpha, a_mesh_off_the_canvas_paints_nothing}` (`cargo test -p hayro`); (20) `raster::tests::a_tiling_pattern_drawn_once_shows_its_cell`, `raster::tests::a_large_step_still_tiles_where_the_next_cell_shows`, `raster::tests::a_tiling_cell_too_thin_to_scale_keeps_the_old_path` |; (22) `raster::tests::knockout_groups_replace_what_their_elements_cover`
-| hayro | 0.7.1 | Apache-2.0 OR MIT | (1) `RenderSettings::{x_offset, y_offset}` to render one tile of a large page; (2) images over `MAX_IMAGE_PIXELS` (2^28) are skipped (a fuzzed `/W 4294967295` hung in resampling); (3) `tiling_cell_scale` keeps a tiling pattern's cell pixmap within 3000 px a side whatever its `/XStep`/`/YStep` (a fuzzed step far beyond `/BBox` allocated 2 GB); (4) stroke widths clamped to 4 × (canvas width + height) device pixels (a fuzzed `/LW 9223372036854775807` allocated 10 GB in stroke expansion); (5) `usable_dash_pattern`: a stroke whose dash pattern could cut it into more than `MAX_DASHES_PER_STROKE` (250,000) pieces, counting kurbo's restart of the pattern at every subpath and `ClosePath`, is drawn solid (a fuzzed `/D [[11] 0]` on a line from x = 92234775807 allocated over 5 GB, `[0.000001] 0 d` on a 20 pt line over 10 GB); (6) a dash pattern with a negative or non-finite entry, or a period that isn't positive, is drawn solid (`[-1 -1] 0 d` looped for ever in kurbo); (7) `render_size` and `render_into`: render into a buffer the caller allocates (PdfCraft renders into pixel-aligned memory that the GUI takes over as texture data); `render` is `render_into` on a new pixmap; (8) checked image source/target/RGBA, alpha-premultiplication scratch and intermediate sizes before resampling, finite transforms and exact source/mask buffers; sources wider than u16 may shrink before backend limits, with a 2^20 source-axis cap and conservative 128 MiB filter-planning estimate; an over-limit or failed resize keeps the original image resolution and geometry when the source fits the backend, otherwise skips it, with a logged warning; staging, resampling output/scratch, RGBA conversion and padding buffers use fallible reserves; (9) `may_paint_canvas`: a fill or stroke whose control-point box, grown by how far its paint reaches past the path (half the stroke width times the larger of the miter limit and √2) plus 0.5 user units and 2 pixels, misses the canvas is not drawn, so a tile no longer strokes and fills every path of its page (item 5 of #623); `set_skip_offscreen_paths` turns this off for the regression test; (10) `/Interpolate` governs the pre-resize too (#624): a minified image that does not request interpolation is pre-resized with nearest-neighbour, planned without the Catmull-Rom filter limits (`image_resampling_size` takes the flag); a Type 3 glyph image is sampled bicubically only when interpolated; a minified image with a matching soft mask is nearest-sampled straight into premultiplied RGBA; (11) `may_paint_rect`: an image whose stream-size box, mapped to the device, misses the canvas is skipped before decoding (decoded data can only shrink against that box), so a tile of an image-heavy page no longer decodes, resamples and rasterizes every image on it; (12) preview renders (`InterpreterSettings::preview`: backdrops, thumbnails, grid cells, signature-drag backgrounds) skip images under `PREVIEW_MIN_IMAGE_AREA` device pixels, while final renders always draw them; (13) reading colours (#897): `RenderSettings::color_replacement` takes a `ColorReplacement` (text colour, background, `only_black`, `line_art`) that remaps solid text and line-art paint while rendering, glyph outlines counting as text and stencil-mask ink as line art; images, image alpha masks, soft masks and pattern cells keep their colours; `render_pdf` gains a `color_replacement: Option<ColorReplacement>` argument (pass `None` for true colours); the upstream-only `[dev-dependencies.log]` entry is removed from `Cargo.toml` (log is a normal dependency since the logging patch), so `cargo test -p hayro` runs this crate's unit tests; (14) a shrunk, interpolated, axis-aligned image is snapped to whole device pixels: shrunk once to its rounded device rectangle and drawn 1:1 at the rounded corner, instead of a ceil-sized raster resampled again at a fractional scale and offset (`snap_minified_image`; scans looked soft next to Acrobat); (15) a soft mask of another size than its image is filtered when shrunk, whatever its `/Interpolate` (#1649): such a mask carries the shape on its own (Word saves text as a tiny black image with a glyph-bitmap mask), and nearest-neighbour dropped every stroke thinner than the shrink factor; (16) under a soft mask or a blend mode, axial and radial shadings are sampled instead of drawn as native gradients (#2128): vello_cpu 0.0.8 copies an opaque gradient over fully covered tiles without the mask or blend mode, so PowerPoint's faded gradient fills came out solid; (17) the renderer keeps annotation paints out of the reading-colours mapping between `begin_annotations` and `end_annotations` (#1548); (18) the page renders as one transparency group; under reading colours its background is painted inside it as the initial backdrop, so a Multiply highlight blends with the dark background instead of staying an opaque block, and otherwise the background stays outside, so a blend mode over an empty part of the page keeps its colour instead of blending with the white paper (#2970); (19) `set_paint` samples a mesh shading's texture over its triangles alone (`EncodedShadingPattern::extent`, padded rather than repeated) and skips a mesh with none on the canvas: a BricsCAD plan's 310 one-triangle `sh` each covered the whole tile, 2 s per 1024 px tile at any zoom (the watchdog gave the page up on a busy machine), now about 70 ms; (20) a tiling pattern whose step is too large for a cell pixmap, where what is painted (a fill, or a stroke with its width) can only show the first cell (PowerPoint's `/XStep 2147480100` for a picture fill drawn once), has its `/BBox` drawn at full scale with a transparent border and padded instead of tiled (`shows_one_cell`; a cell whose scale isn't finite and positive, from a `/BBox` too thin to divide by, keeps the old path: `usable_cell_scale`); shrinking the cell to fit the 3000 px limit of (3) left the picture under a pixel, so network diagrams lost their pictures (#3349); (22) knockout groups: while one is innermost, fills, strokes, glyph outlines and shadings are drawn with `Compose::Copy` (weighted by coverage), so each element replaces what earlier elements of the group drew instead of compositing over it; an image or nested group, drawn into a layer of its own, first has what is under its shape cleared (`knockout_image` for an unmasked image's rectangle, only when `draw_image` will draw it, decoded at the size it is drawn; a knockout erase pass that draws a nested group's content with every paint clearing instead of painting, a shading fill's clear clipped to the shading's `/BBox` as its paint is) and then composites over it (#2971) | (1) `raster::tests::tiles_match_full_render`; (2) `raster::tests::absurd_image_dimensions_are_skipped`; (3) `raster::tests::tiling_cells_stay_small_whatever_the_step`; (4) `raster::tests::absurd_predictor_columns_and_line_widths_render`; (5) `raster::tests::dash_patterns_that_cut_a_stroke_into_billions_of_pieces_render`; (6) `raster::tests::invalid_dash_patterns_terminate_and_are_drawn_solid`; (7) `raster::tests::pixels_are_a_plain_renders_bytes_in_a_buffer_a_gui_can_take_over`; (8) `raster::tests::image_resampling_rejects_anisotropic_target_growth`, `raster::tests::image_resampling_bounds_intermediate_before_planning`, `raster::tests::image_resampling_rejects_invalid_sources_and_scales`, `raster::tests::image_resampling_keeps_valid_sizes_and_exact_limits`, `raster::tests::resampling_fallback_preserves_original_geometry_and_pixels`, `raster::tests::image_resampling_wide_sources_shrink_before_backend_side_limits`, `raster::tests::image_resampling_wide_transparent_sources_still_shrink`, `raster::tests::image_resampling_padded_backend_dimensions_stay_checked`, `raster::tests::image_resampling_mismatched_alpha_mask_keeps_pixels_and_placement`; (9) `raster::tests::skipping_paths_off_the_canvas_changes_no_pixel`; (10) `raster::tests::non_interpolated_images_are_not_smoothed_when_minified`, `raster::tests::non_interpolated_gray_images_are_not_smoothed_when_minified`, `raster::tests::non_integer_minification_samples_the_same_columns`, `raster::tests::non_integer_minification_samples_colour_and_mask_from_the_same_columns`, `raster::tests::non_interpolated_alpha_images_keep_their_colours_and_mask_when_minified`, `raster::tests::non_interpolated_type3_glyph_images_are_not_smoothed_when_minified`, `raster::tests::image_resampling_nearest_accepts_wide_sources_the_filter_refuses`, `raster::tests::wide_non_interpolated_sources_draw_after_shrinking`; (11) `raster::tests::skipping_paths_off_the_canvas_changes_no_pixel`; (12) `raster::tests::preview_renders_skip_tiny_images_but_finals_draw_everything`; (13) `color_replacement_tests::{black_maps_to_text_colour, white_maps_to_background, midgrey_interpolates, alpha_copied_verbatim, only_black_threshold, line_art_false_skips_paths_but_not_text}`, `color_replacement_render_tests::{color_replacement_maps_text_and_line_art, color_replacement_maps_stencil_mask_ink}`; (14) `raster::tests::interpolated_minified_image_edges_snap_to_whole_pixels` (`cargo test -p hayro`); (15) `raster::tests::shrunk_soft_mask_larger_than_its_image_keeps_thin_strokes`; (16) `raster::tests::soft_mask_applies_to_a_shading_pattern_fill`; (17), (18) `raster::tests::reading_colors_keep_highlight_annotations_readable`; (19) `mesh_extent_tests::{a_mesh_paints_its_triangles_alone, a_mesh_keeps_the_graphics_state_alpha, a_mesh_off_the_canvas_paints_nothing}` (`cargo test -p hayro`); (20) `raster::tests::a_tiling_pattern_drawn_once_shows_its_cell`, `raster::tests::a_large_step_still_tiles_where_the_next_cell_shows`, `raster::tests::a_tiling_cell_too_thin_to_scale_keeps_the_old_path` |; (22) `raster::tests::knockout_groups_replace_what_their_elements_cover`
-| hayro-jbig2 | 0.3.0 | Apache-2.0 OR MIT | (1) at most 2^28 pixels per bitmap, page bitmap, halftone grid and grayscale image (each side could be 65535: 4.3 billion pixels decoded one by one); (2) at most 2^26 symbol pixels per symbol dictionary (a fuzzed dictionary decoded for minutes); (3) a symbol dictionary's height classes are capped at one per new symbol and its export runs at `2 × symbols + 1`, each plus `EXTRA_EMPTY_STEPS` (1024): an empty height class or a zero-length export run doesn't advance, and past the end of its data the arithmetic decoder can decode them for ever (one changed byte hung the renderer) | (1) `raster::tests::jbig2_regions_of_billions_of_pixels_are_refused`; (2) the nightly `cargo xtask fuzz` finding, which now finishes in about a second; (3) `raster::tests::jbig2_symbol_dictionaries_that_never_advance_terminate` |
-| lopdf | 0.45.0 | MIT | (1) PNG predictor rows longer than the data are refused before their buffers are allocated (a fuzzed `/Columns 4294967295` allocated two 4 GiB rows), and empty frames return without row buffers; (2) predictor row widths use saturating arithmetic or reject overflow; (3) sub-byte TIFF Predictor 2 scratch is bounded by the samples present in the input instead of the declared `/Colors`, aligned with [lopdf#589](https://github.com/J-F-Liu/lopdf/pull/589) | (1) `inspect::tests::png_predictor_rows_longer_than_the_data_are_refused_before_allocating`, `inspect::tests::empty_png_predictor_frames_do_not_allocate_rows`; (2) `inspect::tests::tiff_subbyte_predictor_row_width_overflow_is_refused`; (3) `inspect::tests::tiff_subbyte_predictor_scratch_is_bounded_by_available_samples`, `inspect::tests::tiff_subbyte_predictors_keep_components_rows_and_padding` |
-| hayro-syntax | 0.7.2 | Apache-2.0 OR MIT | (1) Page-tree cycle guard in `resolve_pages` (visited set + depth cap): a `/Kids` loop among compressed objects overflowed the stack and aborted the process; (2) `ccitt_size_ok`: CCITT images wider than 2^20 columns or over 2^28 pixels are not decoded (a fuzzed `/Columns 4294967295` allocated 4 GiB); (3) Flate/LZW predictor row widths are saturating `usize`, a zero width is refused and a row longer than the data is not allocated (a fuzzed `/Columns 9223372036854775807` wrapped to a 2^61-byte allocation and aborted); (4) the inline-image end-of-data check (`EI`) doesn't nest inside its own look-ahead and examines at most 256 candidates and steps (50 images with "EI" in their data ran for over ten minutes); an EI followed by a delimiter (EI%..., EI[...) ends the image like one followed by white space; only a regular character after EI skips the candidate; (5) a stream whose `/Length` is wrong is recovered only when `stream` is the next token — scanning ahead to a later object's `stream` made an indirect appearance-state dictionary (Quartz checkboxes: `/AP /N` → `<< /Yes … /Off … >>`) render as a non-form, so the widget was skipped; (6) JPX rescaling uses an exact integer sample range for 1–32-bit components (32 shifted past u32, and floating-point maxima at 25–31 bits wrapped to zero), and refuses zero-sized rows; (7) `decode_limit`: Flate (through flate2 and the fallback inflater), LZW and RunLength never write past `MAX_DECODED_STREAM` (256 MiB), or, for the last filter of an image of known size, past twice its pixel bytes (a predictor tag byte per byte), at most 1 GiB; `Stream::decoded_within` for budgeted callers; a page's `/Contents` array shares one `MAX_DECODED_STREAM` (a 2 MB page whose content stream or 8 × 8 image inflated to 2 GB took the renderer past 3 GB in under a second; naming the stream twenty times in `/Contents`, 5 GB); (8) high-precision numbers (jsPDF MediaBox coordinates with over 19 digits) parse without overflowing the u64 mantissa: fractional digits past it are dropped, integer digits past it scale the value (a real, kept finite); (9) large dictionary indexes are built on first use and shared across repeated reads within each PDF (#307); the validated-byte cache is bounded, reader contexts remain separate, repairs and inline/content dictionaries bypass sharing, and small dictionaries stay eager; (10) decoded object-stream slots publish once under contention, cold loading rejects recursive dependencies, and xref repair serializes without holding recursive read guards; this permits one parser per native render pool with private worker caches; (11) `sync.rs`: a poisoned lock is recovered instead of unwrapped (a worker panic no longer cascades into every reader of the same PDF), and xref repair takes a blocking write lock instead of asserting a non-blocking one; (12) `SegmentList` (`util.rs`) returns `None` for an out-of-range index instead of panicking; (13) a page's `/UserUnit` scales `render_dimensions` and `initial_transform`, so the page and everything on it are sized in points, as Acrobat shows them; it is read as Acrobat reads it (the page's own entry, not inherited; a number from 1 up, at most 75,000; anything else counts as 1), and a page without it keeps exactly the transform it had; (14) revision 2–4 passwords are tried as given and then in PDFDocEncoding (`legacy_passwords` in `crypto/mod.rs`, which resolves the upstream `TODO: Convert to PDFDocEncoding`): passwords arrive as UTF-8 text, so a password with characters outside ASCII (`Çok güzel`, `ılık€`) written in PDFDocEncoding, as ISO 32000-2 §7.6.4.3.2 asks and qpdf and Acrobat write it, was always wrong; (15) page content is read a piece at a time (`page::ContentReader`, `Page::content_reader`): plain streams and Flate streams without a predictor are decoded as they are read, with a budget of 64 times their compressed size and never less than `MAX_DECODED_STREAM` (a stream that expands past it is cut and reported); other streams are decoded whole, as before, and share `MAX_DECODED_STREAM`. The content tokenizer reads a window at a time (`UntypedIter::new_window`, `TypedIter::needs_more`, `TypedIter::committed`): an instruction that runs past the window is not decided until more data follows, which `Reader` records by flagging reads and `at_end` past the end of the data, including through the clones the parser makes. The Flate decoder keeps its own 32 KiB history, so it pauses at any output size. `ContentReader::new` reuses raw/decrypted stream bytes for budget accounting and piece creation, and `decoded_raw_within` applies the existing Whole-stream filters and limits to those bytes without decrypting twice; (16) revision 5–6 (AES-256) passwords are tried in their SASLprep form (RFC 4013, then UTF-8, at most 127 bytes, as ISO 32000-2 §7.6.4.3.3 Algorithm 2.A asks and pdfcraft-crypt writes them) and then, if that differs, as given (`aes256_passwords` in `crypto/mod.rs`, which resolves the upstream `TODO: Do the above.`; `stringprep`, already in the tree through pdfcraft-crypt, is an optional dependency enabled by `std`, and without `std` passwords are used as given): the renderer used the password as typed, so one that SASLprep changes (a decomposed `café`, a no-break space, the fullwidth `ab` a Japanese IME types in full-width mode) was wrong, although pdfcraft-cos accepted it: protecting a document with such an open password was rolled back ("the password is incorrect"), and a file with such a password did not open with it.; (17) CCITT `/Rows 0` means the height is not predetermined (ISO 32000-2 Table 11), not zero rows: scanned Group 4 pages written that way rendered blank; (18) The streaming Flate decoder (`lzw_flate::flate::fallback`) copies a back-reference in runs of up to its distance (`extend_from_within`), not byte by byte. The copy reads only bytes already in the output, and a copy whose source does not exist still writes nothing, so the bytes are those a byte-by-byte copy writes. Inflating the A1 sample's content stream (278.6 MB) takes about 14% less time (0.66 s to 0.56 s); the output is identical; (19) CCITT `/Rows` below the image's `/Height` decodes to the height: a plotter driver wrote `/Rows` equal to `/Columns`, so only the first rows were decoded and the rest drawn black (#3308) (20) `stream` followed by spaces or tabs and then the line break (`stream \r\n`, as Microsoft Reporting Services writes it) starts the data after the line break; the content stream was taken to start at the space and the page rendered blank.; (21) a JP2 colour specification naming an enumerated colour space the decoder refuses (CIEJab in a veraPDF fixture, YCbCr, PhotoYCC, YPbPr, bilevel…) no longer fails the image: it is decoded again from a copy whose `colr` names the space the decoder assumes without one, greyscale, sRGB or CMYK by component count, as MuPDF and Poppler draw it (`without_refused_enumerated_colour`; the page drew blank, #3306); (22) an object stream's index of `objnum offset` pairs is parsed once per stream and kept beside its decoded data (`ObjectStreamIndexes`, `XRef::with_object_stream_indexes`), and an offset past `usize` is malformed instead of wrapping: `XRef::get_with` parsed the whole index again for every object it fetched from the stream, so reading all of a stream of N objects took N² steps (a Firefox page whose 65,542 objects share one stream took 37 s to draw and 40 s to extract its text); (23) the inline-image end-of-data look-ahead no longer rejects a candidate `EI` because a byte above 0x7F lies between it and the next one: when the candidate is the end, those bytes are the content stream that follows the image, and its strings carry such bytes (WinAnsi `(Grüße) Tj`, the two-byte codes of any Type 0 font), so the operator check that follows decides alone, bounded as in (4) (a scanned page whose OCR text held an accented word and a later capital "EI" — EINGANG, BEI, KLEIN — drew and extracted nothing after the image: 40 of 275 pages across five real documents); (24) `xref::prev_offset`: a trailer `/Prev` written as a reference `N G R` is read as the offset that object holds when the section's own entries place it (iText's `indirectPrev.pdf`; each section's entries are read before its `Prev` is followed), and otherwise as offset N (tiff2pdf; JHOVE's PDF-HUL-157 files, #2366), as `pdfcraft-cos` and other readers take it, so the earlier sections' pages are seen instead of one | (1) `cos/tests/writer.rs::page_tree_loops_in_object_streams_do_not_crash_readers`; (2) `raster::tests::absurd_mask_and_fax_sizes_are_refused_before_decoding`; (3) `raster::tests::absurd_predictor_columns_and_line_widths_render`; (4) `raster::tests::inline_images_with_ei_in_their_data_parse_in_linear_time`, `content::tests::inline_image_ei_may_be_followed_by_a_delimiter`; (5) `raster::tests::indirect_appearance_state_dict_is_not_another_stream`; (6) `raster::tests::jpx_stream_bit_depth_boundaries_do_not_panic`, `raster::tests::jpx_32_bit_image_does_not_prevent_other_page_content_from_rendering`, `raster::tests::jpx_gray_rgb_and_alpha_keep_eight_bit_samples`, `raster::tests::jpx_streams_reject_out_of_range_bit_depths`; (7) `raster::tests::decompression_bombs_stop_at_the_stream_limit`, `raster::tests::page_contents_and_nested_forms_share_one_budget`; (8) `inspect::tests::jspdf_high_precision_mediabox_does_not_overflow_dimensions`, `object::number::tests::high_precision_float_does_not_overflow_mantissa` (hayro-syntax); (9) `object::dict::lazy_index_tests`, `raster::tests::large_resource_indexes_preserve_pixels_and_text`; (10) `data::tests`, `xref::tests::concurrent_cold_object_stream_reads_all_succeed`, `raster::tests::shared_parser_is_lazy_and_initializes_once_under_contention`; (11) `data::tests::panicking_initializer_wakes_waiters_and_prevents_retries`, `xref::tests::concurrent_cold_object_stream_reads_all_succeed`; (12) `util::tests::segment_list_rejects_out_of_range_indices`; (13) `raster::tests::user_unit_scales_the_page_and_everything_on_it`; (14) `crypto::pdfcraft_password_tests`, `pdfcraft-engine` `tests::legacy_passwords_with_turkish_characters_open`; (15) `content::tests::windows_keep_every_instruction_at_every_split`, `content::tests::windows_keep_every_instruction_in_pieces_of_any_size`, `content::tests::windows_match_the_slice_on_random_content`, `content::tests::windows_drop_blanks_and_keep_a_comment_that_may_go_on`, `page::content_reader_tests::content_past_the_cap_is_read_to_the_end`, `page::content_reader_tests::a_stream_that_expands_past_the_budget_is_cut_there`, `page::content_reader_tests::a_small_expansion_under_the_cap_is_not_cut`, `raster::tests::page_content_past_the_old_cap_renders`, `raster::tests::content_reader_returns_the_same_bytes_in_any_pieces`, `raster::tests::content_bombs_stop_at_the_budget_and_say_so`, `page::content_reader_tests::plain_and_whole_pieces_keep_their_bytes`, `page::content_reader_tests::repeated_content_reference_counts_compressed_bytes_once`, `page::content_reader_tests::whole_cap_still_counts_later_unique_streams`; (16) `crypto::pdfcraft_password_tests::aes256_passwords_are_tried_in_their_saslprep_form_then_as_given`, `crypto::pdfcraft_password_tests::aes256_passwords_open_as_typed_and_in_their_saslprep_form`, `pdfcraft-engine` `tests::aes256_open_passwords_that_saslprep_changes_protect_and_reopen_as_typed`, `tests::aes256_files_whose_passwords_saslprep_changes_open_as_typed`; (17) `raster::tests::group4_fax_with_rows_zero_decodes_to_the_image_height`; (18) `filter::lzw_flate::tests::back_reference_longer_than_its_distance_repeats_its_source`, `back_reference_cut_by_the_limit_resumes_in_the_next_call` and `back_reference_reads_bytes_written_by_an_earlier_call`; each fails when the copy returns the wrong remaining count; (19) `raster::tests::group4_fax_with_rows_below_its_height_decodes_to_the_image_height`; (20) `raster::tests::space_before_the_line_break_after_stream_still_renders`; (21) `raster::tests::a_jp2_image_in_a_refused_enumerated_colour_space_is_drawn`, `filter::jpx::tests::refused_enumerated_colour_spaces_become_the_component_counts_default`, `filter::jpx::tests::what_the_decoder_handles_or_cant_be_read_is_left_alone` (`cargo test --manifest-path vendor/hayro-syntax/Cargo.toml`); (22) `raster::tests::objects_in_one_large_object_stream_are_read_in_linear_time`; (23) `text::tests::text_after_an_inline_image_survives_a_non_ascii_byte_before_a_later_ei`, `content::tests::an_inline_image_ends_at_its_own_ei_when_later_text_holds_a_non_ascii_byte` (hayro-syntax); (24) `xref::tests::prev_as_reference_reaches_the_earlier_section`, `xref::tests::prev_as_reference_to_an_object_holding_the_offset_reads_that_offset`, `pdfcraft-cos` `document::tests::a_prev_written_as_a_reference_still_reaches_the_earlier_sections`, `document::tests::a_prev_reference_to_an_object_holding_the_offset_reads_that_offset`
-| hayro-syntax | 0.7.2 | Apache-2.0 OR MIT | (1) Page-tree cycle guard in `resolve_pages` (visited set + depth cap): a `/Kids` loop among compressed objects overflowed the stack and aborted the process; (2) `ccitt_size_ok`: CCITT images wider than 2^20 columns or over 2^28 pixels are not decoded (a fuzzed `/Columns 4294967295` allocated 4 GiB); (3) Flate/LZW predictor row widths are saturating `usize`, a zero width is refused and a row longer than the data is not allocated (a fuzzed `/Columns 9223372036854775807` wrapped to a 2^61-byte allocation and aborted); (4) the inline-image end-of-data check (`EI`) doesn't nest inside its own look-ahead and examines at most 256 candidates and steps (50 images with "EI" in their data ran for over ten minutes); (5) a stream whose `/Length` is wrong is recovered only when `stream` is the next token — scanning ahead to a later object's `stream` made an indirect appearance-state dictionary (Quartz checkboxes: `/AP /N` → `<< /Yes … /Off … >>`) render as a non-form, so the widget was skipped; (6) JPX rescaling uses an exact integer sample range for 1–32-bit components (32 shifted past u32, and floating-point maxima at 25–31 bits wrapped to zero), and refuses zero-sized rows; (7) `decode_limit`: Flate (through flate2 and the fallback inflater), LZW, RunLength and ASCII85 never write past `MAX_DECODED_STREAM` (256 MiB), or, for the last filter of an image of known size, past twice its pixel bytes (a predictor tag byte per byte), at most 1 GiB; `Stream::decoded_within` for budgeted callers; a page's `/Contents` array shares one `MAX_DECODED_STREAM` (a 2 MB page whose content stream or 8 × 8 image inflated to 2 GB took the renderer past 3 GB in under a second; naming the stream twenty times in `/Contents`, 5 GB); (8) high-precision numbers (jsPDF MediaBox coordinates with over 19 digits) parse without overflowing the u64 mantissa: fractional digits past it are dropped, integer digits past it scale the value (a real, kept finite); (9) large dictionary indexes are built on first use and shared across repeated reads within each PDF (#307); the validated-byte cache is bounded, reader contexts remain separate, repairs and inline/content dictionaries bypass sharing, and small dictionaries stay eager; (10) decoded object-stream slots publish once under contention, cold loading rejects recursive dependencies, and xref repair serializes without holding recursive read guards; this permits one parser per native render pool with private worker caches; (11) `sync.rs`: a poisoned lock is recovered instead of unwrapped (a worker panic no longer cascades into every reader of the same PDF), and xref repair takes a blocking write lock instead of asserting a non-blocking one; (12) `SegmentList` (`util.rs`) returns `None` for an out-of-range index instead of panicking; (13) a page's `/UserUnit` scales `render_dimensions` and `initial_transform`, so the page and everything on it are sized in points, as Acrobat shows them; it is read as Acrobat reads it (the page's own entry, not inherited; a number from 1 up, at most 75,000; anything else counts as 1), and a page without it keeps exactly the transform it had; (14) revision 2–4 passwords are tried as given and then in PDFDocEncoding (`legacy_passwords` in `crypto/mod.rs`, which resolves the upstream `TODO: Convert to PDFDocEncoding`): passwords arrive as UTF-8 text, so a password with characters outside ASCII (`Çok güzel`, `ılık€`) written in PDFDocEncoding, as ISO 32000-2 §7.6.4.3.2 asks and qpdf and Acrobat write it, was always wrong; (15) page content is read a piece at a time (`page::ContentReader`, `Page::content_reader`): plain streams and Flate streams without a predictor are decoded as they are read, with a budget of 64 times their compressed size and never less than `MAX_DECODED_STREAM` (a stream that expands past it is cut and reported); other streams are decoded whole, as before, and share `MAX_DECODED_STREAM`. The content tokenizer reads a window at a time (`UntypedIter::new_window`, `TypedIter::needs_more`, `TypedIter::committed`): an instruction that runs past the window is not decided until more data follows, which `Reader` records by flagging reads and `at_end` past the end of the data, including through the clones the parser makes. The Flate decoder keeps its own 32 KiB history, so it pauses at any output size. `ContentReader::new` reuses raw/decrypted stream bytes for budget accounting and piece creation, and `decoded_raw_within` applies the existing Whole-stream filters and limits to those bytes without decrypting twice; (16) revision 5–6 (AES-256) passwords are tried in their SASLprep form (RFC 4013, then UTF-8, at most 127 bytes, as ISO 32000-2 §7.6.4.3.3 Algorithm 2.A asks and pdfcraft-crypt writes them) and then, if that differs, as given (`aes256_passwords` in `crypto/mod.rs`, which resolves the upstream `TODO: Do the above.`; `stringprep`, already in the tree through pdfcraft-crypt, is an optional dependency enabled by `std`, and without `std` passwords are used as given): the renderer used the password as typed, so one that SASLprep changes (a decomposed `café`, a no-break space, the fullwidth `ab` a Japanese IME types in full-width mode) was wrong, although pdfcraft-cos accepted it: protecting a document with such an open password was rolled back ("the password is incorrect"), and a file with such a password did not open with it. | (1) `cos/tests/writer.rs::page_tree_loops_in_object_streams_do_not_crash_readers`; (2) `raster::tests::absurd_mask_and_fax_sizes_are_refused_before_decoding`; (3) `raster::tests::absurd_predictor_columns_and_line_widths_render`; (4) `raster::tests::inline_images_with_ei_in_their_data_parse_in_linear_time`; (5) `raster::tests::indirect_appearance_state_dict_is_not_another_stream`; (6) `raster::tests::jpx_stream_bit_depth_boundaries_do_not_panic`, `raster::tests::jpx_32_bit_image_does_not_prevent_other_page_content_from_rendering`, `raster::tests::jpx_gray_rgb_and_alpha_keep_eight_bit_samples`, `raster::tests::jpx_streams_reject_out_of_range_bit_depths`; (7) `raster::tests::decompression_bombs_stop_at_the_stream_limit`, `raster::tests::page_contents_and_nested_forms_share_one_budget`; (8) `inspect::tests::jspdf_high_precision_mediabox_does_not_overflow_dimensions`, `object::number::tests::high_precision_float_does_not_overflow_mantissa` (hayro-syntax); (9) `object::dict::lazy_index_tests`, `raster::tests::large_resource_indexes_preserve_pixels_and_text`; (10) `data::tests`, `xref::tests::concurrent_cold_object_stream_reads_all_succeed`, `raster::tests::shared_parser_is_lazy_and_initializes_once_under_contention`; (11) `data::tests::panicking_initializer_wakes_waiters_and_prevents_retries`, `xref::tests::concurrent_cold_object_stream_reads_all_succeed`; (12) `util::tests::segment_list_rejects_out_of_range_indices`; (13) `raster::tests::user_unit_scales_the_page_and_everything_on_it`; (14) `crypto::pdfcraft_password_tests`, `pdfcraft-engine` `tests::legacy_passwords_with_turkish_characters_open`; (15) `content::tests::windows_keep_every_instruction_at_every_split`, `content::tests::windows_keep_every_instruction_in_pieces_of_any_size`, `content::tests::windows_match_the_slice_on_random_content`, `content::tests::windows_drop_blanks_and_keep_a_comment_that_may_go_on`, `page::content_reader_tests::content_past_the_cap_is_read_to_the_end`, `page::content_reader_tests::a_stream_that_expands_past_the_budget_is_cut_there`, `page::content_reader_tests::a_small_expansion_under_the_cap_is_not_cut`, `raster::tests::page_content_past_the_old_cap_renders`, `raster::tests::content_reader_returns_the_same_bytes_in_any_pieces`, `raster::tests::content_bombs_stop_at_the_budget_and_say_so`, `page::content_reader_tests::plain_and_whole_pieces_keep_their_bytes`, `page::content_reader_tests::repeated_content_reference_counts_compressed_bytes_once`, `page::content_reader_tests::whole_cap_still_counts_later_unique_streams`; (16) `crypto::pdfcraft_password_tests::aes256_passwords_are_tried_in_their_saslprep_form_then_as_given`, `crypto::pdfcraft_password_tests::aes256_passwords_open_as_typed_and_in_their_saslprep_form`, `pdfcraft-engine` `tests::aes256_open_passwords_that_saslprep_changes_protect_and_reopen_as_typed`, `tests::aes256_files_whose_passwords_saslprep_changes_open_as_typed`
+| hayro-interpret | 0.7.0 | Apache-2.0 OR MIT | (1) select `/AP /N` appearance states via `/AS` (checkboxes, radios, stateful icons) and honour the NoView flag; (2) Type3 Unicode fallback to `/Encoding` glyph names, then printable ASCII; (3) `Type3Glyph::advance_width`; (4) `InterpreterSettings::ocg_overrides` for viewer layer toggles; (5) soft masks whose group lacks `/CS` were dropped (Chrome gradient text); (6) paint nesting cap `MAX_PAINT_NESTING` for tiling patterns and Type 3 glyphs (self-referencing content overflowed the stack); (7) CID width ranges in `/W` and `/W2` clamped to `MAX_CID` (a `0 4294967295 w` range hung); (8) `InterpreterSettings::hide_comments` skips markup annotations but keeps widgets and links (View ▸ Hide all comments); (9) `image_size_ok`: images and masks over 2^28 pixels are not decoded (a fuzzed `/W 4294967295` stencil mask allocated 4 GiB); (10) `MAX_NESTED_PAINTS`: nested paints (forms, Type 3 glyphs and tiling patterns inside one another) share a per-page budget of 50,000 (a glyph showing eight glyphs of its own font, sixteen deep, hung); (11) depends on skrifa 0.47 instead of 0.42 (upstream read-fonts fixed a Type 1 tokenizer that recursed through runs of numbers: a fuzzed font hung or overflowed the stack), with the one API change (`Charset::glyph_id` returns `Option`); (12) annotation appearances whose `/BBox` or `/Matrix` collapses to a line or a point are skipped (mapping them onto `/Rect` divided by zero and handed the device infinite or NaN matrices); (13) a Highlight annotation without a usable normal appearance is drawn from its `/QuadPoints`, `/C` and `/CA` with Multiply blending, as pdfcraft-annot draws highlights (it was not drawn at all); (14) simple-font `/Widths` (`read_widths`): entries only for codes 0–255 (one entry per code below `/FirstChar` was allocated: `4294967295` asked for 34 GB), an entry that isn't a number leaves its code missing instead of ending the array, and a `/LastChar` below `/FirstChar` gives no widths instead of discarding the font for a standard one; (15) the appearance box is mapped onto `/Rect` corner to corner: the translation now accounts for the scale (an appearance whose box didn't start at the origin and differed in size from `/Rect` was drawn shifted); (16) a clip set by `W`/`W*` takes effect after whichever path-painting operator ends the path (`S`, `f`, `B`, … as well as `n`; ISO 32000-2 §8.5.4): it was applied only on `n`, so `re W* S` clipped nothing and the clip stayed pending for a later, unrelated `n`; (17) `InterpreterSettings::cancelled`: once set, interpretation stops before the next content operator (a render pool sets it for every worker when dropped, after an edit or on closing, and for one worker when the watchdog gives up on its render, so renders whose answers nobody can receive stop instead of running to the end); (18) `MAX_PAGE_CONTENT`: the content a page holds at once (its contents, and the forms, tiling patterns and Type 3 glyph procedures being painted) stays within 512 MiB (`decode_content`; once it runs out, `InterpreterWarning::ContentTruncated` is reported (once per page by pdfcraft-render) so a truncated page is not a clean render; each level gives its bytes back when it finishes): forms nest fifty deep and each level kept its content while the next ran, so a form painting itself around a stream inflating to 256 MiB would have held over 12 GB; and Type 0 sampled functions take at most `MAX_SAMPLE_ENTRIES` (2^21) table points and `MAX_SAMPLE_VALUES` (2^23) samples, read no further than `/Size` asks (256 MiB of 1-bit samples asked for over 8 GB); (19) mesh shadings (types 4–7) are sampled only inside the area being drawn (`ShadingPattern::encode_within`, which the vendored hayro renderer calls with that area plus a pixel), within 8 visits per pixel of it plus 4 per triangle (`TriangleSampler`), and patches are triangulated one at a time: points far off the page were sampled over their whole bounding box, up to 65536 × 65536 entries (a fuzzed 147-byte patch stream; a synthetic page passed 6 GB in six seconds), ten thousand overlapping triangles ran for minutes, and every patch became 722 triangles before any limit; meshes hold at most `MAX_MESH_PATCHES` (2^16) patches and `MAX_MESH_TRIANGLES` (2^20) triangles, a lattice needs two to 2^19 vertices per row (`/VerticesPerRow 0` pushed empty rows for ever; one huge row read the whole stream), and a page samples at most `MAX_PAGE_MESH_TRIANGLES` (2^25) mesh triangles in all (a mesh painted a thousand times was triangulated a thousand times); each cut logs a warning; (20) PDF function construction is limited to 64 levels and 10,000 total nodes with cycle detection; calculator parsing and evaluation share procedure depth/work budgets, integer division/bitshift/rotation/index are panic-free, and fixed-size stack errors propagate; (21) a Type 0 font drawn with a substitute that isn't CID-keyed (it isn't embedded, or its program doesn't load) draws `.notdef` for a CID of an Adobe character collection (Japan1, GB1, CNS1, Korea1) that it can't find by Unicode: hayro took the CID for a glyph index of the substitute, which numbers its glyphs its own way, so the character was drawn as an unrelated one (𠮷 as "Q" in BIZ UDPGothic); (22) a Type 0 font drawn with a substitute finds a character given with a variation selector (`/ToUnicode`, or Adobe-Japan1-UCS2, which maps the JIS X 0208 forms of the kanji JIS X 0213:2004 redrew that way: CID 1247 is 噂 U+E0100) through the substitute's variation sequences, else as the character alone: such a CID found no glyph and was drawn as an unrelated one; (23) backport of hayro 0.8's `gradient` module: `EncodedShadingPattern::as_svg_gradient` turns an axial or radial shading into stops of an sRGB gradient (within 0.01 per channel, a stop at every stitching-function bound via `Function::stitching_bounds`) when a native gradient draws it exactly (extended past the box drawn in; a radial one with no background colour); (24) `DecodedImageCache`: decoded image pixels shared across renders through the interpreter cache within a 64 MiB budget (an image-heavy page decoded its thousands of images again per tile and per scale), keyed by every decode input (`DecodedImageKey`: the stream's place and dictionary bytes, its object, mask/stencil/raster output, interpolation, decode target size, preview or final); images under a transfer function and inline images are not cached, an image over the budget is never kept, and a poisoned lock decodes uncached; (25) `Device::actual_text` hands the device a marked content sequence's `/ActualText` (inline or named in `/Properties`), so text extraction keeps the Thai, Indic and Arabic clusters Chrome marks this way (their shaped tone marks and vowels have no Unicode of their own); (26) non-embedded simple fonts drawn with a standard-font stand-in build the Latin Extended-A letters the stand-in lacks (`/Gbreve`, `/Idotaccent`, `/Scedilla`, `/aogonek`, `/ccaron`…) from the base letter and accent it has (`StandardKind::composite_glyph`, `ACCENTED_LETTERS`): PDFium's Foxit stand-ins hold only the Standard/WinAnsi/Mac Roman glyphs, so iText letters with Times New Roman unembedded showed blanks for Ğ, İ, Ş, ğ and ş; the comma-below letters (`/scommaaccent`, `/Tcommaaccent`, `/kcommaaccent`…, found by character, so `/uni0136` and the glyph list's `/Kcedilla` too) are the letter and the font's comma, smaller and under the baseline, since the stand-ins have no `commaaccent` (Romanian ș drew nothing and ț a cedilla in forms laid out from XFA; ģ, whose comma is turned and above, is not built); (27) an embedded TrueType font without a base encoding reads its codes as WinAnsi for text extraction (`EmbeddedKind::code_to_unicode_name`), matching pdftotext's output, instead of Standard: OCR text layers of scans write WinAnsi codes with no `/Encoding`, and Standard has no ü, ö or ß and reads é as Ø (glyph selection unchanged); (28) an image whose pixels hold at most 16 bits of samples (an 8-bit Separation or DeviceN image, a 1-, 2- or 4-bit gray or indexed one) is converted once per possible pixel value through a lookup table instead of once per pixel (`rgb_via_lookup`): a spot-colour tint transform is often a PostScript calculator program, run for every pixel, so a fillable character sheet's 3304 × 4105 DeviceN background took four seconds and 430 MB to draw a page; each entry is converted on its own (`convert_each`), so a tint transform giving the wrong number of components for a value the image never uses cannot shift the colours of the values it does; (29) `Device::begin_annotations`/`end_annotations` bracket the page's annotations, so a device can tell comment paints from document paints (reading colours recolour the document, never a comment, #1548); (30) the Annex D.2 alias codes read as the ink they draw: WinAnsiEncoding 0xA0 and 0xAD, and MacRomanEncoding 0xCA, carry the glyph names `space` and `hyphen` -- the names those tables also give 0x20 and 0x2D -- not `nbspace` and `sfthyphen`, whose glyph list values U+00A0 and U+00AD are invisible formatting characters. Extraction hid drawn ink behind them, so search and redaction matched neither (`XiaoBiaoSong.pdf` in the pdf.js corpus drew 104 soft hyphens; across the 989 files the soft hyphens we extract fall from 117 to 13 and the non-breaking spaces from 30 to 26, what remains coming from `/ToUnicode` maps, which say so explicitly). The base table only, in the text direction only: a `/Differences` name keeps its glyph list value and glyph lookup is untouched, both as pdftotext does; (31) a Type 0 sampled function keeps its samples in one flat array indexed by strides (`Type0::entry`) instead of a hash map keyed by each grid point: the map was built again, one hashed insert per sample, every time a shading using the function was painted (a 2,097,152-sample ramp painted 30 times took 38 s; `bug1721218` in the pdf.js corpus spent most of a 1.5 s page on it); the interpolation is unchanged, so results are bit for bit the same, a sample missing from a short stream still gives no value, and the maximum sample value is computed without overflowing at 32 bits per sample; (32) the decoded-image cache (24) keys a decode by the size the image is drawn at only when a JPX stream decodes it or its soft mask or mask (`decode_reads_target`): JPX is the only filter that decodes a reduced resolution for a size, so a JPEG or Flate scan was decoded again at every zoom step and kept once per zoom level; one decode now serves every size; `InterpreterCache::decoded_image_decodes` counts the cache's decodes; (33) Coons and tensor-product patches copy their vertices' colours less: each point of a patch's 20 × 20 triangle grid is interpolated once (`generate_patch_triangles`; each cell interpolated its four corners itself, 1,444 interpolations a patch for 400 points), a cell's second triangle takes the vertices its first copied, and the mesh sampler moves a patch's triangles into device space instead of copying each vertex (`TriangleSampler::sample_owned`); the same values, 10–16% faster on mesh-gradient pages; (34) `color::tint_transform_runs`: how many colours the calling thread has run through a Separation or DeviceN tint transform (counted once per batch in `convert_f32`), so a test counts patch (28)'s once-per-sample-value runs instead of timing them (its 10 s deadline failed on a busy FreeBSD VM in CI); (35) `EncodedShadingPattern::extent`: where a mesh shading (types 4–7) can paint at all, the pixels its triangles touched when it was encoded (`None` for the types that paint everywhere, and when the shading has a `/Background`), so the renderer samples a texture there alone and skips a mesh with nothing on the canvas; (36) a mesh shading's pixel whose corner no triangle holds strictly (on an edge two triangles share, or on the mesh's side) takes the triangle that covers its centre, edges included (`Triangle::covers`): testing only the corner left a white seam along every shared edge, and the colour is still taken at the corner; (38) the `/DefaultGray`, `/DefaultRGB` and `/DefaultCMYK` colour spaces of a resource dictionary (ISO 32000-2 §8.6.5.6) replace the device space content selects: with `g`/`G`, `rg`/`RG`, `k`/`K` and `cs`/`CS` (by name, or through a `/ColorSpace` resource that is a device space), and as the `/ColorSpace` of an image XObject, an inline image or a shading painted by `sh` or as a shading pattern (`DefaultColorSpaces`, looked up once per content window in the resources and those they inherit, so a form XObject without a default of its own draws in its page's, as Poppler and MuPDF draw it); a default that is a Lab, Indexed, Pattern or device space, has another number of components or is no colour space is ignored and device colour is drawn as before; device spaces inside other spaces (an Indexed base, a Separation or DeviceN alternate, a Pattern's underlying space), shading dictionaries, masks and transparency group spaces are unchanged, and the decoded-image cache (24) keys a decode by the default it was drawn in. hayro drew device colour as it was, so pages that calibrate it this way (common in PDF/A) came out in the wrong colours; (39) knockout groups (#2971): `Device::set_knockout` right after a `/K true` group is pushed; `Device::knockout_image` for an unmasked image before its group is pushed, when `Device::in_knockout_group`: the device clears its placement rectangle only if it will draw the image (on the canvas, not a preview's tiny image, and it decodes), decoded at its draw size so the draw reuses that decode; and, when `Device::knockout_erase_wanted`, a nested group's content drawn once between `begin_knockout_erase` and `end_knockout_erase` before the group itself, which then always gets a layer of its own; (40) an optional content membership dictionary's visibility expression (`/VE`: `/And`, `/Or`, `/Not`, nested up to 32 deep) decides its visibility ahead of `/OCGs` and `/P` (ISO 32000-2 §8.11.2.2); it was ignored, so content under it stayed visible with its layers hidden; a malformed expression, including one naming an object the document doesn't list in `/OCProperties /OCGs`, falls back to `/OCGs` and `/P` (#2986); (41) a transparency group that is neither isolated nor knockout, entered at full opacity with no soft mask and Normal blending, is drawn straight onto the page instead of into a layer of its own (§11.4.7: its elements composite with the backdrop; the layer made a `/BM /Multiply` highlight appearance an opaque block, #1968); (42) text in a Type 3 font is drawn filled whatever the text rendering mode, except mode 3 (invisible): only that mode has any effect on Type 3 fonts (ISO 32000-1 §9.3.6). Stroking ran the glyph procedure a second time, so `2 Tr` made bitmap fonts look bold, `1 Tr` painted an uncoloured glyph in the stroking colour, and `7 Tr` hid it (`7 Tr` since follows 64); (43) Lab colour spaces honour their own `/WhitePoint`: L\*a\*b\* goes to XYZ relative to that white, is Bradford-adapted to D65 and converted to sRGB (ISO 32000-2 §8.6.5.4) instead of through `LAB.icc` as if every white were D50 (a D65 blue came out 45 levels too red; the profile is removed); components normalised to [0, 1] (`manual_scale`, an `/Indexed` palette over Lab) map onto L\* 0..100 and the a\*/b\* `/Range`; (44) a Type 0 font whose `/ToUnicode` is the name `/Identity-H` or `/Identity-V` (not a CMap stream; WSCAD writes it) reads each code as its Unicode value, as Acrobat shows it (`Type0Font::identity_to_unicode`); the identity CMap the name resolved to maps codes to CIDs only, so such pages had no text to select or find; (46) an image XObject's group applies the fill opacity, so the fill alpha is reset to 1 before a stencil mask takes the fill colour as its paint, and a pattern paint drops the opacity it captured at `scn` (`Pattern::without_opacity`) (it was applied twice: a mask at `ca 0.5` was drawn at a quarter, #2975); (47) `path_as_rect`: a five-element path is a rectangle only when its four points are distinct, each step from one to the next runs along a single axis, and the last returns to the first. The length test admits one MoveTo and four LineTo as well as one MoveTo, three LineTo and a ClosePath, and asking only that every corner of the bounding box was visited says nothing about the order or the steps between, so a five-point polyline whose ends reached the corners was painted as that box -- a fourth side the path does not have -- and a clip of that shape was discarded; the coordinates are compared exactly, since the matrix is applied after this check and a `cm` of 10,000 turns `is_nearly_equal`'s 256th of a unit into tens of device units (#3327); (48) an `/ICCBased` colour space is cached by what its profile is read from (`IccProfileKey`): the stream object it names, looked up without reading the stream, and then the stream's dictionary and its own bytes (decrypted, not decoded), so a byte-for-byte copy of a profile in another object is read once, and a profile stream written directly in its array, which reports the object holding the array as every other stream written there does, is told apart by its bytes. hayro keyed it by the stream dictionary's bytes alone, so two different profiles with the same `/N` and `/Length` shared whichever was read first, and colours in the second were drawn through the first. `InterpreterCache::icc_profile_reads` counts the profiles read; (49) `OpenTypeFontBlob::new` also accepts a `post` table version 1.0, 2.0 or 3.0 written with its 16-bit halves swapped (`00 00 00 03`), as ScanSoft PDF Create! embeds every font; such fonts were refused and their text drawn with a substitute (Hebrew came out garbled or missing, #2946); `glyph_names` reads such a table from a copy with the version written correctly, so a 2.0 table's names serve `/Differences`. Any other unknown version is still refused (pdf.js 9462); (50) `CffFontBlob::glyph_index_by_name` looks a glyph name up in a name to glyph map built on first use (shared between clones) instead of searching the whole charset, with a string lookup per glyph, for every character code of a font; the first glyph with a name still wins; (51) at most 4096 graphics states saved at once, holding at most 64 MiB together (each `q` copies the whole state, dash array and clip list included, so short operators multiplied one large state); a `q` past either limit is counted but not copied, and its `Q` still removes the clips added since (from storytold/craft-libs#239); (52) a `/W2` run whose first CID is past `MAX_CID` stops there, as in `/W` (7), checked before the run's metrics are read: a first CID of 4294967295 inserted one entry and then overflowed, discarding the whole `/W2` table (from storytold/craft-libs#254); (55) a Separation or DeviceN tint transform that cannot be read keeps its colour space, and one that cannot be read or evaluated paints the alternate space's initial colour, as evaluation failures already did; that fallback, and a `cs`/`CS` colour space that cannot be read (drawn in DeviceGray as before), are now reported once per content stream as `InterpreterWarning::ColorFallback` (`RenderWarning::ColourFallback` in `pdfcraft-render`) instead of silently (#4260); (56) an annotation whose Invisible flag (bit 1) is set and whose `/Subtype` is none of the standard types of ISO 32000-2 Table 171 (`is_standard_annotation_type`; no `/Subtype` counts as unknown) is not drawn (Table 167), and a `/Popup` annotation's appearance is never painted on the page (§12.5.6.14: a popup has no appearance stream of its own; the viewer shows it as a window for its parent annotation). Both were drawn from their `/AP`; (57) a simple font drawn with a standard-font stand-in because the document names a font it doesn't embed (`StandardKind` with `fallback`) narrows a glyph to a narrower `/Widths` advance but no longer widens it to a wider one: the advance already places the next glyph (ISO 32000-2 §9.2.4; /Widths in Table 109), and widening drew a non-embedded `Arial,Bold` with 600-unit widths as a heavy fixed-pitch face whose `i` and `l` were solid blocks twice their width; an exact standard-14 font still matches its standard metrics both ways; (58) the fallback request for a Type 0 font that is not embedded (`FallbackFontQuery::with_descriptor`) takes its serif, italic and small-cap flags, `/FontWeight`, `/FontFamily` and `/FontStretch` from the descendant CIDFont's font descriptor (ISO 32000-2 §9.7.4.1, §9.7.6.1; §9.8): it read them from the Type 0 dictionary, which has none, so every such request asked for a regular sans-serif face and no resolver could tell a Song or Mincho font from a Hei or Gothic one, or see `/FontWeight 700`; (59) the NoRotate flag (`/F` bit 5) is honoured: the appearance, fitted to `/Rect`, is turned against the page's `/Rotate` about the rectangle's upper-left corner, which stays where it is, so it reads upright as the page is displayed (ISO 32000-2 §12.5.3). Sticky notes, which are saved NoRotate, were drawn turned with the page (#2583). Form fields and links stay in `/Rect`, where PdfCraft takes their click targets from it; (64) text in a Type 3 font follows ISO 32000-2 §9.3.6 in the clipping modes: under `7 Tr` it is not rendered (reported to the device as clipping text, `GlyphDrawMode::Clip`, so extraction keeps it), and in modes 4 to 7 a Type 3 glyph adds nothing to the clipping path (`clip_glyph`), so text shown only in a Type 3 font leaves no clip at `ET`. Since (42) `7 Tr` painted the glyphs in the fill colour (black by default), so a fill meant to follow showed them wherever it didn't cover them; 4 to 6 still render filled; (66) a Separation colour space whose colourant is the special name `All` paints every colourant at once (ISO 32000-2 §8.6.6.4): on screen and in an RGB print raster its tint t is the gray 1 − t, complemented because the device is additive, whatever its alternate space and tint transform say (hayro drew it through the tint transform, so a `/DeviceCMYK` transform giving cyan drew registration marks light cyan); `/None` still paints nothing, any other name still goes through its alternate, and a DeviceN space naming `All` keeps its alternate, since the clause gives the name that meaning in a Separation space; (67) `StandardFont::win_ansi_width`: the standard-14 advance widths by WinAnsiEncoding code, public, so text PdfCraft sets in the standard fonts (Office files converted by Create) is measured exactly; (68) `InterpreterSettings::hide_notes` skips sticky notes (`/Text` annotations) only, for the Android viewer, which draws its own fixed-size note icons | (1) `raster::tests::widget_appearance_states`; (2, 3) `xtask text-oracle` on corpus/pdfjs issue918; (4) `raster::tests::layer_override_hides_content`; (5) `raster::tests::soft_mask_without_group_colour_space_is_applied`; (6) `raster::tests::self_referencing_tiling_pattern_terminates`, `raster::tests::self_referencing_type3_glyph_terminates`; (7) `raster::tests::huge_cid_width_ranges_terminate`; (8) `raster::tests::hiding_comments_keeps_fields`; (9) `raster::tests::absurd_mask_and_fax_sizes_are_refused_before_decoding`; (10) `raster::tests::type3_glyphs_that_fan_out_into_themselves_finish`; (11) `raster::tests::type1_font_programs_with_long_runs_of_numbers_load_quickly`; (12) `raster::tests::degenerate_annotation_appearances_are_skipped`; (13) `raster::tests::highlights_without_an_appearance_are_drawn`; (14) `raster::tests::malformed_simple_font_widths_keep_later_widths_and_the_font`, `raster::tests::huge_simple_font_first_char_terminates`; (15) `raster::tests::annotation_appearance_box_maps_onto_rect`; (16) `raster::tests::clipping_path_applies_after_any_painting_operator`; (17) `raster::tests::dropping_the_pool_cancels_its_renders`, `raster::tests::the_watchdog_stops_the_render_it_gives_up_on`; (18) `raster::tests::page_contents_and_nested_forms_share_one_budget`, `raster::tests::content_painted_again_and_again_keeps_drawing`, `raster::tests::sampled_functions_with_billions_of_samples_are_refused`; (19) `raster::tests::mesh_shadings_far_off_the_page_render`, `raster::tests::many_overlapping_mesh_triangles_finish`, `raster::tests::mesh_shadings_with_many_patches_or_no_rows_finish`; (20) `raster::tests::function_limits_calculator_arithmetic_and_depth`, `raster::tests::function_limits_public_construction_work_and_depth`, `raster::tests::function_limits_stitching_cycles_are_refused_and_shared_children_work`, `raster::tests::function_limits_invalid_calculator_keeps_the_page_renderable`; (21) `raster::tests::cids_a_substitute_lacks_are_not_drawn_as_other_glyphs`; (22) `raster::tests::variation_sequences_draw_their_kanji_in_a_substitute`; (23) `raster::tests::axial_and_radial_shadings_draw_as_native_gradients`; (24) `raster::tests::tiles_match_full_render`, `raster::tests::skipping_paths_off_the_canvas_changes_no_pixel` (both decode through the cache), `raster::tests::decoded_images_with_identical_dictionaries_keep_their_own_pixels`, `raster::tests::decoded_images_under_a_transfer_function_are_not_shared`; (25) `text::tests::actual_text_replaces_the_glyphs_it_marks_in_every_writing_direction`, `text::tests::actual_text_follows_the_pdf_rules_for_marked_content`; (26) `raster::tests::accented_letters_the_standard_stand_ins_lack_are_built_from_their_parts`, `raster::tests::comma_below_letters_in_standard_fonts_draw_a_comma_under_the_letter`; (27) `text::tests::truetype_without_an_encoding_reads_its_codes_as_win_ansi`; (28) `raster::tests::spot_colour_images_run_their_tint_transform_once_per_sample_value`, `raster::tests::images_converted_through_a_table_keep_every_samples_colour`, `raster::tests::a_malformed_tint_for_an_unused_sample_keeps_the_used_colours`; (29) `raster::tests::reading_colors_keep_highlight_annotations_readable`; (30) `text::tests::the_annex_d2_alias_codes_read_as_an_ordinary_hyphen_and_space`; (31) `raster::tests::shadings_with_large_sampled_functions_paint_quickly`, `raster::tests::sampled_functions_interpolate_their_grid_as_before`; (32) `raster::tests::decoded_images_serve_every_size_they_are_drawn_at`; (33) `raster::tests::patch_meshes_keep_their_corner_colours`; (34) `raster::tests::spot_colour_images_run_their_tint_transform_once_per_sample_value`; (35) `mesh_extent_tests::{a_mesh_paints_its_triangles_alone, a_mesh_keeps_the_graphics_state_alpha, a_mesh_off_the_canvas_paints_nothing}` (`cargo test -p hayro`); (36) `raster::tests::mesh_triangles_sharing_an_edge_leave_no_seam`; (38) `raster::tests::default_colour_spaces::device_rgb_operators_draw_in_default_rgb`, `raster::tests::default_colour_spaces::device_cmyk_operators_draw_in_default_cmyk`, `raster::tests::default_colour_spaces::device_gray_operators_draw_in_default_gray`, `raster::tests::default_colour_spaces::device_images_draw_in_the_default_colour_spaces`, `raster::tests::default_colour_spaces::device_shadings_draw_in_the_default_colour_spaces`, `raster::tests::default_colour_spaces::an_image_drawn_with_and_without_a_default_keeps_both_colours`, `raster::tests::default_colour_spaces::forms_inherit_the_default_colour_spaces_they_do_not_override`, `raster::tests::default_colour_spaces::unusable_defaults_leave_device_colour_alone`; (39) `raster::tests::knockout_groups_replace_what_their_elements_cover`; (40) `raster::tests::visibility_expressions_decide_what_a_membership_dictionary_shows`; (41) `raster::tests::a_multiply_highlight_inside_a_transparency_group_keeps_the_text`; (42) `raster::tests::rendering_modes_but_3_and_7_draw_type3_glyphs_as_filled`; (43) `raster::tests::lab_honours_the_space_white_point`, `raster::tests::indexed_palettes_over_lab_keep_their_colours`; (44) `text::tests::identity_to_unicode_names_give_text`; (46) `raster::tests::stencil_masks_are_drawn_at_the_fill_opacity_once`; (47) `raster::tests::a_five_point_polyline_is_not_painted_as_its_bounding_box`, `raster::tests::a_path_that_visits_every_corner_out_of_order_is_not_a_rectangle`, `raster::tests::a_rectangle_is_still_painted_as_a_rectangle`; (48) `raster::tests::icc_profile_cache::icc_profiles_with_identical_dictionaries_draw_their_own_colours`, `raster::tests::icc_profile_cache::icc_profiles_used_again_are_read_once`; (49) `raster::tests::a_font_whose_post_version_has_swapped_halves_is_still_used`; (50) `font::blob::tests::glyph_names_resolve_to_the_first_glyph_with_that_name`; (51) `context::saved_state_tests::repeated_saves_stay_bounded_and_balanced`; (52) `font::cid::tests::w2_run_past_the_largest_cid_keeps_the_rest_of_the_table` (hayro-interpret); (55) `raster::tests::devicen_inks::a_tint_transform_that_cannot_be_evaluated_draws_the_rest_of_the_page_and_warns`, `raster::tests::devicen_inks::a_tint_transform_that_cannot_be_read_falls_back_and_warns`; (56) `raster::tests::invisible_unknown_annotations_and_popups_paint_nothing`; (57) `substitute_widths::a_substitute_keeps_its_glyph_shapes_at_wider_advances`, `substitute_widths::a_substitute_still_narrows_glyphs_to_narrower_advances` (pdfcraft-render `tests/it`); (58) `cid_fallback_query::a_cid_font_fallback_request_carries_its_descendants_style`, `cid_fallback_query::a_cid_font_without_a_descriptor_asks_for_the_default_style` (pdfcraft-render integration tests); (59) `raster::tests::no_rotate_notes_stay_upright_at_their_corner_on_rotated_pages` (hayro-interpret); (64) `type3_text_clip::{clip_only_type3_text_is_not_rendered_and_leaves_no_clip, invisible_type3_text_is_not_rendered, other_modes_render_type3_glyphs_filled_and_never_clip, only_outline_glyphs_shape_a_clip_shared_with_type3_text, self_nesting_type3_text_in_a_clip_mode_stays_bounded}` (`cargo test -p pdfcraft-render --test it`), `raster::tests::rendering_modes_but_3_and_7_draw_type3_glyphs_as_filled`, `text::tests::clipping_mode_type3_text_is_kept_by_the_ocr_filter`; (66) `separation_all::{separation_all_fills_paint_the_complemented_tint_as_gray, separation_all_strokes_paint_the_complemented_tint_as_gray, separation_all_images_paint_each_sample_as_the_complemented_gray, separation_all_shadings_paint_the_complemented_gray, separation_none_paints_nothing, a_named_separation_still_paints_through_its_alternate, a_device_n_space_naming_all_still_paints_through_its_alternate}` (`cargo test -p pdfcraft-render --test it`) |
+| hayro | 0.7.1 | Apache-2.0 OR MIT | (1) `RenderSettings::{x_offset, y_offset}` to render one tile of a large page; (2) images over `MAX_IMAGE_PIXELS` (2^28) are skipped (a fuzzed `/W 4294967295` hung in resampling); (3) `tiling_cell_scale` keeps a tiling pattern's cell pixmap within 3000 px a side whatever its `/XStep`/`/YStep` (a fuzzed step far beyond `/BBox` allocated 2 GB); (4) stroke widths clamped to 4 × (canvas width + height) device pixels (a fuzzed `/LW 9223372036854775807` allocated 10 GB in stroke expansion); (5) `usable_dash_pattern`: a stroke whose dash pattern could cut it into more than `MAX_DASHES_PER_STROKE` (250,000) pieces, counting kurbo's restart of the pattern at every subpath and `ClosePath`, is drawn solid (a fuzzed `/D [[11] 0]` on a line from x = 92234775807 allocated over 5 GB, `[0.000001] 0 d` on a 20 pt line over 10 GB); (6) a dash pattern with a negative or non-finite entry, or a period that isn't positive, is drawn solid (`[-1 -1] 0 d` looped for ever in kurbo); (7) `render_size` and `render_into`: render into a buffer the caller allocates (PdfCraft renders into pixel-aligned memory that the GUI takes over as texture data); `render` is `render_into` on a new pixmap; (8) checked image source/target/RGBA, alpha-premultiplication scratch and intermediate sizes before resampling, finite transforms and exact source/mask buffers; sources wider than u16 may shrink before backend limits, with a 2^20 source-axis cap and conservative 128 MiB filter-planning estimate; an over-limit or failed resize keeps the original image resolution and geometry when the source fits the backend, otherwise skips it, with a logged warning; staging, resampling output/scratch, RGBA conversion and padding buffers use fallible reserves; (9) `may_paint_canvas`: a fill or stroke whose control-point box, grown by how far its paint reaches past the path (half the stroke width times the larger of the miter limit and √2) plus 0.5 user units and 2 pixels, misses the canvas is not drawn, so a tile no longer strokes and fills every path of its page (item 5 of #623); `set_skip_offscreen_paths` turns this off for the regression test; (10) `/Interpolate` governs the pre-resize too (#624): a minified image that does not request interpolation is pre-resized with nearest-neighbour, planned without the Catmull-Rom filter limits (`image_resampling_size` takes the flag); a Type 3 glyph image is sampled bicubically only when interpolated; a minified image with a matching soft mask is nearest-sampled straight into premultiplied RGBA; (11) `may_paint_rect`: an image whose stream-size box, mapped to the device, misses the canvas is skipped before decoding (decoded data can only shrink against that box), so a tile of an image-heavy page no longer decodes, resamples and rasterizes every image on it; (12) preview renders (`InterpreterSettings::preview`: backdrops, thumbnails, grid cells, signature-drag backgrounds) skip images under `PREVIEW_MIN_IMAGE_AREA` device pixels, while final renders always draw them; (13) reading colours (#897): `RenderSettings::color_replacement` takes a `ColorReplacement` (text colour, background, `only_black`, `line_art`) that remaps solid text and line-art paint while rendering, glyph outlines counting as text and stencil-mask ink as line art; images, image alpha masks, soft masks and pattern cells keep their colours; `render_pdf` gains a `color_replacement: Option<ColorReplacement>` argument (pass `None` for true colours); the upstream-only `[dev-dependencies.log]` entry is removed from `Cargo.toml` (log is a normal dependency since the logging patch), so `cargo test -p hayro` runs this crate's unit tests; (14) a shrunk, interpolated, axis-aligned image is snapped to whole device pixels: shrunk once to its rounded device rectangle and drawn 1:1 at the rounded corner, instead of a ceil-sized raster resampled again at a fractional scale and offset (`snap_minified_image`; scans looked soft next to Acrobat); (15) a soft mask of another size than its image is filtered when shrunk, whatever its `/Interpolate` (#1649): such a mask carries the shape on its own (Word saves text as a tiny black image with a glyph-bitmap mask), and nearest-neighbour dropped every stroke thinner than the shrink factor; (16) under a soft mask or a blend mode, axial and radial shadings are sampled instead of drawn as native gradients (#2128): vello_cpu 0.0.8 copies an opaque gradient over fully covered tiles without the mask or blend mode, so PowerPoint's faded gradient fills came out solid; (17) the renderer keeps annotation paints out of the reading-colours mapping between `begin_annotations` and `end_annotations` (#1548); (18) the page renders as one transparency group; under reading colours its background is painted inside it as the initial backdrop, so a Multiply highlight blends with the dark background instead of staying an opaque block, and otherwise the background stays outside, so a blend mode over an empty part of the page keeps its colour instead of blending with the white paper (#2970); (19) `set_paint` samples a mesh shading's texture over its triangles alone (`EncodedShadingPattern::extent`, padded rather than repeated) and skips a mesh with none on the canvas: a BricsCAD plan's 310 one-triangle `sh` each covered the whole tile, 2 s per 1024 px tile at any zoom (the watchdog gave the page up on a busy machine), now about 70 ms; (20) a tiling pattern whose step is too large for a cell pixmap, where what is painted (a fill, or a stroke with its width) can only show the first cell (PowerPoint's `/XStep 2147480100` for a picture fill drawn once), has its `/BBox` drawn at full scale with a transparent border and padded instead of tiled (`shows_one_cell`; a cell whose scale isn't finite and positive, from a `/BBox` too thin to divide by, keeps the old path: `usable_cell_scale`); shrinking the cell to fit the 3000 px limit of (3) left the picture under a pixel, so network diagrams lost their pictures (#3349); (22) knockout groups: while one is innermost, fills, strokes, glyph outlines and shadings are drawn with `Compose::Copy` (weighted by coverage), so each element replaces what earlier elements of the group drew instead of compositing over it; an image or nested group, drawn into a layer of its own, first has what is under its shape cleared (`knockout_image` for an unmasked image's rectangle, only when `draw_image` will draw it, decoded at the size it is drawn; a knockout erase pass that draws a nested group's content with every paint clearing instead of painting, a shading fill's clear clipped to the shading's `/BBox` as its paint is) and then composites over it (#2971); (23) backport of hayro 0.8: shadings that `as_svg_gradient` can represent are painted as a `vello_cpu` linear or two-point radial gradient instead of a texture sampled pixel by pixel through the shading function (InDesign fades are luminosity soft masks of one full-page axial `sh`: 40 on a report page took 15 s at 144 dpi, now under 1 s); without upstream's half-pixel shift, which suits vello_cpu 0.3 but moves 0.0.8's gradients off pixel centres; (25) a tiling cell is drawn at the scale that makes one `/XStep` (`/YStep`) exactly the cell pixmap's whole number of pixels (`tiling_cell_pixels`, at least 1 and at most the cap), so the repeated pixmap puts cells at whole multiples of the step at any device scale; drawing at the unrounded scale repeated the cell up to half a pixel off at every step, and the error grew with distance from the pattern's origin (ISO 32000-2 8.7.3.1) | (1) `raster::tests::tiles_match_full_render`; (2) `raster::tests::absurd_image_dimensions_are_skipped`; (3) `raster::tests::tiling_cells_stay_small_whatever_the_step`; (4) `raster::tests::absurd_predictor_columns_and_line_widths_render`; (5) `raster::tests::dash_patterns_that_cut_a_stroke_into_billions_of_pieces_render`; (6) `raster::tests::invalid_dash_patterns_terminate_and_are_drawn_solid`; (7) `raster::tests::pixels_are_a_plain_renders_bytes_in_a_buffer_a_gui_can_take_over`; (8) `raster::tests::image_resampling_rejects_anisotropic_target_growth`, `raster::tests::image_resampling_bounds_intermediate_before_planning`, `raster::tests::image_resampling_rejects_invalid_sources_and_scales`, `raster::tests::image_resampling_keeps_valid_sizes_and_exact_limits`, `raster::tests::resampling_fallback_preserves_original_geometry_and_pixels`, `raster::tests::image_resampling_wide_sources_shrink_before_backend_side_limits`, `raster::tests::image_resampling_wide_transparent_sources_still_shrink`, `raster::tests::image_resampling_padded_backend_dimensions_stay_checked`, `raster::tests::image_resampling_mismatched_alpha_mask_keeps_pixels_and_placement`; (9) `raster::tests::skipping_paths_off_the_canvas_changes_no_pixel`; (10) `raster::tests::non_interpolated_images_are_not_smoothed_when_minified`, `raster::tests::non_interpolated_gray_images_are_not_smoothed_when_minified`, `raster::tests::non_integer_minification_samples_the_same_columns`, `raster::tests::non_integer_minification_samples_colour_and_mask_from_the_same_columns`, `raster::tests::non_interpolated_alpha_images_keep_their_colours_and_mask_when_minified`, `raster::tests::non_interpolated_type3_glyph_images_are_not_smoothed_when_minified`, `raster::tests::image_resampling_nearest_accepts_wide_sources_the_filter_refuses`, `raster::tests::wide_non_interpolated_sources_draw_after_shrinking`; (11) `raster::tests::skipping_paths_off_the_canvas_changes_no_pixel`; (12) `raster::tests::preview_renders_skip_tiny_images_but_finals_draw_everything`; (13) `color_replacement_tests::{black_maps_to_text_colour, white_maps_to_background, midgrey_interpolates, alpha_copied_verbatim, only_black_threshold, line_art_false_skips_paths_but_not_text}`, `color_replacement_render_tests::{color_replacement_maps_text_and_line_art, color_replacement_maps_stencil_mask_ink}`; (14) `raster::tests::interpolated_minified_image_edges_snap_to_whole_pixels` (`cargo test -p hayro`); (15) `raster::tests::shrunk_soft_mask_larger_than_its_image_keeps_thin_strokes`; (16) `raster::tests::soft_mask_applies_to_a_shading_pattern_fill`; (17), (18) `raster::tests::reading_colors_keep_highlight_annotations_readable`; (19) `mesh_extent_tests::{a_mesh_paints_its_triangles_alone, a_mesh_keeps_the_graphics_state_alpha, a_mesh_off_the_canvas_paints_nothing}` (`cargo test -p hayro`); (20) `raster::tests::a_tiling_pattern_drawn_once_shows_its_cell`, `raster::tests::a_large_step_still_tiles_where_the_next_cell_shows`, `raster::tests::a_tiling_cell_too_thin_to_scale_keeps_the_old_path`; (22) `raster::tests::knockout_groups_replace_what_their_elements_cover`; (23) `raster::tests::axial_and_radial_shadings_draw_as_native_gradients`; (25) `tiling_cell_placement::{far_cells_of_a_fill_sit_at_whole_steps, far_cells_sit_at_whole_steps_under_a_turned_scaled_matrix, far_cells_of_a_stroke_sit_at_whole_steps, a_cell_pixmap_spans_exactly_one_step}` (`cargo test -p pdfcraft-render --test it`) |
+| hayro-jbig2 | 0.3.0 | Apache-2.0 OR MIT | (1) at most 2^28 pixels per bitmap, page bitmap, halftone grid and grayscale image (each side could be 65535: 4.3 billion pixels decoded one by one); (2) at most 2^26 symbol pixels per symbol dictionary (a fuzzed dictionary decoded for minutes); (3) a symbol dictionary's height classes are capped at one per new symbol and its export runs at `2 × symbols + 1`, each plus `EXTRA_EMPTY_STEPS` (1024): an empty height class or a zero-length export run doesn't advance, and past the end of its data the arithmetic decoder can decode them for ever (one changed byte hung the renderer); (4) a segment header's long-form referred-to segment count is capped at `u16::MAX` and a larger count is refused before its retention or referred-to bytes are read: the 29-bit count went straight to `Vec::with_capacity`, a reservation of about 2 GiB whose failure aborts the process (from storytold/craft-libs#176) | (1) `raster::tests::jbig2_regions_of_billions_of_pixels_are_refused`; (2) the nightly `cargo xtask fuzz` finding, which now finishes in about a second; (3) `raster::tests::jbig2_symbol_dictionaries_that_never_advance_terminate`; (4) `segment::tests::test_referred_to_count_is_capped` (`cargo test --manifest-path vendor/hayro-jbig2/Cargo.toml`) |
| lopdf | 0.45.0 | MIT | (1) PNG predictor rows longer than the data are refused before their buffers are allocated (a fuzzed `/Columns 4294967295` allocated two 4 GiB rows), and empty frames return without row buffers; (2) predictor row widths use saturating arithmetic or reject overflow; (3) sub-byte TIFF Predictor 2 scratch is bounded by the samples present in the input instead of the declared `/Colors`, aligned with [lopdf#589](https://github.com/J-F-Liu/lopdf/pull/589); (4) the object lookup keeps its cycle history through compressed objects, requires an ordinary in-file container, and caps the chain of indirect lookups at 16 (a chain of new objects, each a `/Length` compressed in a container whose own `/Length` names the next, or a stream whose `/Length` names the next stream, overflowed the stack: a dev build's 2 MiB thread within 800 hops); (5) object-stream members are parsed within their own extent (up to the next distinct offset), an entry whose offset repeats an earlier entry's is skipped (so a repeated object number can resolve to its earlier entry), and offsets are processed in index order; (6) `find_latest_trailer`: a rebuild takes a `/Type /XRef` stream dictionary as the trailer when the file has no `trailer` keyword (the latest in the file wins, as a later `trailer` would), so a concatenated or truncated file keeps its /Info and /ID instead of failing to load; a candidate whose /Root is the catalog beats one whose /Root is another dictionary, and an in-file /Root must match its generation (#2365) | (1) `inspect::tests::png_predictor_rows_longer_than_the_data_are_refused_before_allocating`, `inspect::tests::empty_png_predictor_frames_do_not_allocate_rows`; (2) `inspect::tests::tiff_subbyte_predictor_row_width_overflow_is_refused`; (3) `inspect::tests::tiff_subbyte_predictor_scratch_is_bounded_by_available_samples`, `inspect::tests::tiff_subbyte_predictors_keep_components_rows_and_padding`; (4) `inspect::tests::compressed_object_self_container_does_not_recurse`, `inspect::tests::compressed_object_mutual_containers_do_not_recurse`, `inspect::tests::object_stream_length_cycle_does_not_recurse`, `inspect::tests::compressed_object_container_chain_does_not_recurse`, `inspect::tests::compressed_length_chain_does_not_recurse`, `inspect::tests::plain_stream_length_chain_does_not_recurse`, `inspect::tests::compressed_objects_and_indirect_stream_length_still_load`, `inspect::tests::compressed_length_in_a_container_with_an_indirect_length_still_loads`; (5) `inspect::tests::object_stream_member_extents_bound_owned_strings`, `inspect::tests::object_stream_member_extents_preserve_index_order_and_whitespace`; (6) `inspect::tests::rebuilt_file_keeps_the_info_of_its_cross_reference_stream`, `inspect::tests::rebuilt_file_prefers_a_trailer_whose_root_is_the_catalog` |
-| hayro-syntax | 0.7.2 | Apache-2.0 OR MIT | (1) Page-tree cycle guard in `resolve_pages` (visited set + depth cap): a `/Kids` loop among compressed objects overflowed the stack and aborted the process; (2) `ccitt_size_ok`: CCITT images wider than 2^20 columns or over 2^28 pixels are not decoded (a fuzzed `/Columns 4294967295` allocated 4 GiB); (3) Flate/LZW predictor row widths are saturating `usize`, a zero width is refused and a row longer than the data is not allocated (a fuzzed `/Columns 9223372036854775807` wrapped to a 2^61-byte allocation and aborted); (4) the inline-image end-of-data check (`EI`) doesn't nest inside its own look-ahead and examines at most 256 candidates and steps (50 images with "EI" in their data ran for over ten minutes); (5) a stream whose `/Length` is wrong is recovered only when `stream` is the next token — scanning ahead to a later object's `stream` made an indirect appearance-state dictionary (Quartz checkboxes: `/AP /N` → `<< /Yes … /Off … >>`) render as a non-form, so the widget was skipped; (6) JPX rescaling uses an exact integer sample range for 1–32-bit components (32 shifted past u32, and floating-point maxima at 25–31 bits wrapped to zero), and refuses zero-sized rows; (7) `decode_limit`: Flate (through flate2 and the fallback inflater), LZW and RunLength never write past `MAX_DECODED_STREAM` (256 MiB), or, for the last filter of an image of known size, past twice its pixel bytes (a predictor tag byte per byte), at most 1 GiB; `Stream::decoded_within` for budgeted callers; a page's `/Contents` array shares one `MAX_DECODED_STREAM` (a 2 MB page whose content stream or 8 × 8 image inflated to 2 GB took the renderer past 3 GB in under a second; naming the stream twenty times in `/Contents`, 5 GB); (8) high-precision numbers (jsPDF MediaBox coordinates with over 19 digits) parse without overflowing the u64 mantissa: fractional digits past it are dropped, integer digits past it scale the value (a real, kept finite); (9) large dictionary indexes are built on first use and shared across repeated reads within each PDF (#307); the validated-byte cache is bounded, reader contexts remain separate, repairs and inline/content dictionaries bypass sharing, and small dictionaries stay eager; (10) decoded object-stream slots publish once under contention, cold loading rejects recursive dependencies, and xref repair serializes without holding recursive read guards; this permits one parser per native render pool with private worker caches; (11) `sync.rs`: a poisoned lock is recovered instead of unwrapped (a worker panic no longer cascades into every reader of the same PDF), and xref repair takes a blocking write lock instead of asserting a non-blocking one; (12) `SegmentList` (`util.rs`) returns `None` for an out-of-range index instead of panicking; (13) a page's `/UserUnit` scales `render_dimensions` and `initial_transform`, so the page and everything on it are sized in points, as Acrobat shows them; it is read as Acrobat reads it (the page's own entry, not inherited; a number from 1 up, at most 75,000; anything else counts as 1), and a page without it keeps exactly the transform it had | (1) `cos/tests/writer.rs::page_tree_loops_in_object_streams_do_not_crash_readers`; (2) `raster::tests::absurd_mask_and_fax_sizes_are_refused_before_decoding`; (3) `raster::tests::absurd_predictor_columns_and_line_widths_render`; (4) `raster::tests::inline_images_with_ei_in_their_data_parse_in_linear_time`; (5) `raster::tests::indirect_appearance_state_dict_is_not_another_stream`; (6) `raster::tests::jpx_stream_bit_depth_boundaries_do_not_panic`, `raster::tests::jpx_32_bit_image_does_not_prevent_other_page_content_from_rendering`, `raster::tests::jpx_gray_rgb_and_alpha_keep_eight_bit_samples`, `raster::tests::jpx_streams_reject_out_of_range_bit_depths`; (7) `raster::tests::decompression_bombs_stop_at_the_stream_limit`, `raster::tests::page_contents_and_nested_forms_share_one_budget`; (8) `inspect::tests::jspdf_high_precision_mediabox_does_not_overflow_dimensions`, `object::number::tests::high_precision_float_does_not_overflow_mantissa` (hayro-syntax); (9) `object::dict::lazy_index_tests`, `raster::tests::large_resource_indexes_preserve_pixels_and_text`; (10) `data::tests`, `xref::tests::concurrent_cold_object_stream_reads_all_succeed`, `raster::tests::shared_parser_is_lazy_and_initializes_once_under_contention`; (11) `data::tests::panicking_initializer_wakes_waiters_and_prevents_retries`, `xref::tests::concurrent_cold_object_stream_reads_all_succeed`; (12) `util::tests::segment_list_rejects_out_of_range_indices`; (13) `raster::tests::user_unit_scales_the_page_and_everything_on_it` |
-| lopdf | 0.45.0 | MIT | (1) PNG predictor rows longer than the data are refused before their buffers are allocated (a fuzzed `/Columns 4294967295` allocated two 4 GiB rows), and empty frames return without row buffers; (2) predictor row widths use saturating arithmetic or reject overflow; (3) sub-byte TIFF Predictor 2 scratch is bounded by the samples present in the input instead of the declared `/Colors`, aligned with [lopdf#589](https://github.com/J-F-Liu/lopdf/pull/589) | (1) `inspect::tests::png_predictor_rows_longer_than_the_data_are_refused_before_allocating`, `inspect::tests::empty_png_predictor_frames_do_not_allocate_rows`; (2) `inspect::tests::tiff_subbyte_predictor_row_width_overflow_is_refused`; (3) `inspect::tests::tiff_subbyte_predictor_scratch_is_bounded_by_available_samples`, `inspect::tests::tiff_subbyte_predictors_keep_components_rows_and_padding` |
-| hayro-syntax | 0.7.2 | Apache-2.0 OR MIT | (1) Page-tree cycle guard in `resolve_pages` (visited set + depth cap): a `/Kids` loop among compressed objects overflowed the stack and aborted the process; (2) `ccitt_size_ok`: CCITT images wider than 2^20 columns or over 2^28 pixels are not decoded (a fuzzed `/Columns 4294967295` allocated 4 GiB); (3) Flate/LZW predictor row widths are saturating `usize`, a zero width is refused and a row longer than the data is not allocated (a fuzzed `/Columns 9223372036854775807` wrapped to a 2^61-byte allocation and aborted); (4) the inline-image end-of-data check (`EI`) doesn't nest inside its own look-ahead and examines at most 256 candidates and steps (50 images with "EI" in their data ran for over ten minutes); (5) a stream whose `/Length` is wrong is recovered only when `stream` is the next token — scanning ahead to a later object's `stream` made an indirect appearance-state dictionary (Quartz checkboxes: `/AP /N` → `<< /Yes … /Off … >>`) render as a non-form, so the widget was skipped; (6) JPX rescaling uses an exact integer sample range for 1–32-bit components (32 shifted past u32, and floating-point maxima at 25–31 bits wrapped to zero), and refuses zero-sized rows; (7) `decode_limit`: Flate (through flate2 and the fallback inflater), LZW and RunLength never write past `MAX_DECODED_STREAM` (256 MiB), or, for the last filter of an image of known size, past twice its pixel bytes (a predictor tag byte per byte), at most 1 GiB; `Stream::decoded_within` for budgeted callers; a page's `/Contents` array shares one `MAX_DECODED_STREAM` (a 2 MB page whose content stream or 8 × 8 image inflated to 2 GB took the renderer past 3 GB in under a second; naming the stream twenty times in `/Contents`, 5 GB); (8) high-precision numbers (jsPDF MediaBox coordinates with over 19 digits) parse without overflowing the u64 mantissa: fractional digits past it are dropped, integer digits past it scale the value (a real, kept finite); (9) large dictionary indexes are built on first use and shared across repeated reads within each PDF (#307); the validated-byte cache is bounded, reader contexts remain separate, repairs and inline/content dictionaries bypass sharing, and small dictionaries stay eager; (10) decoded object-stream slots publish once under contention, cold loading rejects recursive dependencies, and xref repair serializes without holding recursive read guards; this permits one parser per native render pool with private worker caches; (11) `sync.rs`: a poisoned lock is recovered instead of unwrapped (a worker panic no longer cascades into every reader of the same PDF), and xref repair takes a blocking write lock instead of asserting a non-blocking one; (12) `SegmentList` (`util.rs`) returns `None` for an out-of-range index instead of panicking; (13) a page's `/UserUnit` scales `render_dimensions` and `initial_transform`, so the page and everything on it are sized in points, as Acrobat shows them; it is read as Acrobat reads it (the page's own entry, not inherited; a number from 1 up, at most 75,000; anything else counts as 1), and a page without it keeps exactly the transform it had; (14) direct arrays and dictionaries share a reader-local nesting cap of 128, counted while skipping and while parsing a dictionary (its lenient repair reads, rather than skips, an object found where a key belongs, so `<< << …` recursed through that read); deeper objects return `None` instead of overflowing the stack (including unused trailer values, trailer entries, content operands and marked-content properties); a chain of 65 direct stitching functions now stops at this cap, before the 64-function guard | (1) `cos/tests/writer.rs::page_tree_loops_in_object_streams_do_not_crash_readers`; (2) `raster::tests::absurd_mask_and_fax_sizes_are_refused_before_decoding`; (3) `raster::tests::absurd_predictor_columns_and_line_widths_render`; (4) `raster::tests::inline_images_with_ei_in_their_data_parse_in_linear_time`; (5) `raster::tests::indirect_appearance_state_dict_is_not_another_stream`; (6) `raster::tests::jpx_stream_bit_depth_boundaries_do_not_panic`, `raster::tests::jpx_32_bit_image_does_not_prevent_other_page_content_from_rendering`, `raster::tests::jpx_gray_rgb_and_alpha_keep_eight_bit_samples`, `raster::tests::jpx_streams_reject_out_of_range_bit_depths`; (7) `raster::tests::decompression_bombs_stop_at_the_stream_limit`, `raster::tests::page_contents_and_nested_forms_share_one_budget`; (8) `inspect::tests::jspdf_high_precision_mediabox_does_not_overflow_dimensions`, `object::number::tests::high_precision_float_does_not_overflow_mantissa` (hayro-syntax); (9) `object::dict::lazy_index_tests`, `raster::tests::large_resource_indexes_preserve_pixels_and_text`; (10) `data::tests`, `xref::tests::concurrent_cold_object_stream_reads_all_succeed`, `raster::tests::shared_parser_is_lazy_and_initializes_once_under_contention`; (11) `data::tests::panicking_initializer_wakes_waiters_and_prevents_retries`, `xref::tests::concurrent_cold_object_stream_reads_all_succeed`; (12) `util::tests::segment_list_rejects_out_of_range_indices`; (13) `raster::tests::user_unit_scales_the_page_and_everything_on_it`; (14) `raster::tests::deeply_nested_direct_objects_do_not_overflow_the_stack`, `raster::tests::dictionaries_nested_without_keys_in_content_do_not_overflow_the_stack`, `raster::tests::dictionaries_nested_without_keys_in_the_trailer_do_not_overflow_the_stack`, `raster::tests::dictionaries_nested_without_keys_as_marked_content_properties_do_not_overflow_the_stack`, `raster::tests::dictionaries_nested_without_keys_are_read_up_to_the_nesting_cap`, `raster::tests::nesting_at_the_cap_fits_a_512_kib_stack` (native only), `raster::tests::function_limits_depth_guard_refuses_a_chain_of_references` |
+| hayro-syntax | 0.7.2 | Apache-2.0 OR MIT | (1) Page-tree cycle guard in `resolve_pages` (visited set + depth cap): a `/Kids` loop among compressed objects overflowed the stack and aborted the process; (2) `ccitt_size_ok`: CCITT images wider than 2^20 columns or over 2^28 pixels are not decoded (a fuzzed `/Columns 4294967295` allocated 4 GiB); (3) Flate/LZW predictor row widths are saturating `usize`, a zero width is refused and a row longer than the data is not allocated (a fuzzed `/Columns 9223372036854775807` wrapped to a 2^61-byte allocation and aborted); (4) the inline-image end-of-data check (`EI`) doesn't nest inside its own look-ahead and examines at most 256 candidates and steps (50 images with "EI" in their data ran for over ten minutes); an EI followed by a delimiter (EI%..., EI[...) ends the image like one followed by white space; only a regular character after EI skips the candidate; (5) a stream whose `/Length` is wrong is recovered only when `stream` is the next token — scanning ahead to a later object's `stream` made an indirect appearance-state dictionary (Quartz checkboxes: `/AP /N` → `<< /Yes … /Off … >>`) render as a non-form, so the widget was skipped; (6) JPX rescaling uses an exact integer sample range for 1–32-bit components (32 shifted past u32, and floating-point maxima at 25–31 bits wrapped to zero), and refuses zero-sized rows; (7) `decode_limit`: Flate (through flate2 and the fallback inflater), LZW, RunLength and ASCII85 never write past `MAX_DECODED_STREAM` (256 MiB), or, for the last filter of an image of known size, past twice its pixel bytes (a predictor tag byte per byte), at most 1 GiB; `Stream::decoded_within` for budgeted callers; a page's `/Contents` array shares one `MAX_DECODED_STREAM` (a 2 MB page whose content stream or 8 × 8 image inflated to 2 GB took the renderer past 3 GB in under a second; naming the stream twenty times in `/Contents`, 5 GB); (8) high-precision numbers (jsPDF MediaBox coordinates with over 19 digits) parse without overflowing the u64 mantissa: fractional digits past it are dropped, integer digits past it scale the value (a real, kept finite); (9) large dictionary indexes are built on first use and shared across repeated reads within each PDF (#307); the validated-byte cache is bounded, reader contexts remain separate, repairs and inline/content dictionaries bypass sharing, and small dictionaries stay eager; (10) decoded object-stream slots publish once under contention, cold loading rejects recursive dependencies, and xref repair serializes without holding recursive read guards; this permits one parser per native render pool with private worker caches; (11) `sync.rs`: a poisoned lock is recovered instead of unwrapped (a worker panic no longer cascades into every reader of the same PDF), and xref repair takes a blocking write lock instead of asserting a non-blocking one; (12) `SegmentList` (`util.rs`) returns `None` for an out-of-range index instead of panicking; (13) a page's `/UserUnit` scales `render_dimensions` and `initial_transform`, so the page and everything on it are sized in points, as Acrobat shows them; it is read as Acrobat reads it (the page's own entry, not inherited; a number from 1 up, at most 75,000; anything else counts as 1), and a page without it keeps exactly the transform it had; (14) revision 2–4 passwords are tried as given and then in PDFDocEncoding (`legacy_passwords` in `crypto/mod.rs`, which resolves the upstream `TODO: Convert to PDFDocEncoding`): passwords arrive as UTF-8 text, so a password with characters outside ASCII (`Çok güzel`, `ılık€`) written in PDFDocEncoding, as ISO 32000-2 §7.6.4.3.2 asks and qpdf and Acrobat write it, was always wrong; (15) page content is read a piece at a time (`page::ContentReader`, `Page::content_reader`): plain streams and Flate streams without a predictor are decoded as they are read, with a budget of 64 times their compressed size and never less than `MAX_DECODED_STREAM` (a stream that expands past it is cut and reported); other streams are decoded whole, as before, and share `MAX_DECODED_STREAM`. The content tokenizer reads a window at a time (`UntypedIter::new_window`, `TypedIter::needs_more`, `TypedIter::committed`): an instruction that runs past the window is not decided until more data follows, which `Reader` records by flagging reads and `at_end` past the end of the data, including through the clones the parser makes. The Flate decoder keeps its own 32 KiB history, so it pauses at any output size. `ContentReader::new` reuses raw/decrypted stream bytes for budget accounting and piece creation, and `decoded_raw_within` applies the existing Whole-stream filters and limits to those bytes without decrypting twice; (16) revision 5–6 (AES-256) passwords are tried in their SASLprep form (RFC 4013, then UTF-8, at most 127 bytes, as ISO 32000-2 §7.6.4.3.3 Algorithm 2.A asks and pdfcraft-crypt writes them) and then, if that differs, as given (`aes256_passwords` in `crypto/mod.rs`, which resolves the upstream `TODO: Do the above.`; `stringprep`, already in the tree through pdfcraft-crypt, is an optional dependency enabled by `std`, and without `std` passwords are used as given): the renderer used the password as typed, so one that SASLprep changes (a decomposed `café`, a no-break space, the fullwidth `ab` a Japanese IME types in full-width mode) was wrong, although pdfcraft-cos accepted it: protecting a document with such an open password was rolled back ("the password is incorrect"), and a file with such a password did not open with it.; (17) CCITT `/Rows 0` means the height is not predetermined (ISO 32000-2 Table 11), not zero rows: scanned Group 4 pages written that way rendered blank; (18) The streaming Flate decoder (`lzw_flate::flate::fallback`) copies a back-reference in runs of up to its distance (`extend_from_within`), not byte by byte. The copy reads only bytes already in the output, and a copy whose source does not exist still writes nothing, so the bytes are those a byte-by-byte copy writes. Inflating the A1 sample's content stream (278.6 MB) takes about 14% less time (0.66 s to 0.56 s); the output is identical; (19) CCITT `/Rows` below the image's `/Height` decodes to the height: a plotter driver wrote `/Rows` equal to `/Columns`, so only the first rows were decoded and the rest drawn black (#3308) (20) `stream` followed by spaces or tabs and then the line break (`stream \r\n`, as Microsoft Reporting Services writes it) starts the data after the line break; the content stream was taken to start at the space and the page rendered blank.; (21) a JP2 colour specification naming an enumerated colour space the decoder refuses (CIEJab in a veraPDF fixture, YCbCr, PhotoYCC, YPbPr, bilevel…) no longer fails the image: it is decoded again from a copy whose `colr` names the space the decoder assumes without one, greyscale, sRGB or CMYK by component count, as MuPDF and Poppler draw it (`without_refused_enumerated_colour`; the page drew blank, #3306); (22) an object stream's index of `objnum offset` pairs is parsed once per stream and kept beside its decoded data (`ObjectStreamIndexes`, `XRef::with_object_stream_indexes`), and an offset past `usize` is malformed instead of wrapping: `XRef::get_with` parsed the whole index again for every object it fetched from the stream, so reading all of a stream of N objects took N² steps (a Firefox page whose 65,542 objects share one stream took 37 s to draw and 40 s to extract its text); (23) the inline-image end-of-data look-ahead no longer rejects a candidate `EI` because a byte above 0x7F lies between it and the next one: when the candidate is the end, those bytes are the content stream that follows the image, and its strings carry such bytes (WinAnsi `(Grüße) Tj`, the two-byte codes of any Type 0 font), so the operator check that follows decides alone, bounded as in (4) (a scanned page whose OCR text held an accented word and a later capital "EI" — EINGANG, BEI, KLEIN — drew and extracted nothing after the image: 40 of 275 pages across five real documents); (24) `xref::prev_offset`: a trailer `/Prev` written as a reference `N G R` is read as the offset that object holds when the section's own entries place it (iText's `indirectPrev.pdf`; each section's entries are read before its `Prev` is followed), and otherwise as offset N (tiff2pdf; JHOVE's PDF-HUL-157 files, #2366), as `pdfcraft-cos` and other readers take it, so the earlier sections' pages are seen instead of one; (25) direct arrays and dictionaries share a reader-local nesting cap of 128, counted while skipping and while parsing a dictionary (its lenient repair reads, rather than skips, an object found where a key belongs, so `<< << …` recursed through that read); deeper objects return `None` instead of overflowing the stack (including unused trailer values, trailer entries, content operands and marked-content properties); a chain of 65 direct stitching functions now stops at this cap, before the 64-function guard; (26) an xref stream subsection must be backed by its decoded data: all-zero `/W` widths (an entry reads no bytes) and a declared count longer than the data are refused before any entry is inserted, where a tiny stream with a large `/Size` or `/Index` count inserted that many entries (from storytold/craft-libs#239); a subsection running past object number `i32::MAX` is refused instead of overflowing or turning negative; (27) an xref stream's type field is read big-endian at its full `/W[0]` width, where only its first byte was read and wider fields shifted every later entry, and `/W[0]` over 8 bytes is refused like `/W[1]` (from storytold/craft-libs#241); (28) a content instruction keeps up to 256 operands (`MAX_OPERANDS`) instead of 10, and past that drops the oldest instead of ending the content stream: the eleventh operand of a twelve-ink DeviceN `scn` (ISO 32000-2 §8.6.6.5 allows any number of components) blanked the rest of the page (#4260) | (1) `cos/tests/writer.rs::page_tree_loops_in_object_streams_do_not_crash_readers`; (2) `raster::tests::absurd_mask_and_fax_sizes_are_refused_before_decoding`; (3) `raster::tests::absurd_predictor_columns_and_line_widths_render`; (4) `raster::tests::inline_images_with_ei_in_their_data_parse_in_linear_time`, `content::tests::inline_image_ei_may_be_followed_by_a_delimiter`; (5) `raster::tests::indirect_appearance_state_dict_is_not_another_stream`; (6) `raster::tests::jpx_stream_bit_depth_boundaries_do_not_panic`, `raster::tests::jpx_32_bit_image_does_not_prevent_other_page_content_from_rendering`, `raster::tests::jpx_gray_rgb_and_alpha_keep_eight_bit_samples`, `raster::tests::jpx_streams_reject_out_of_range_bit_depths`; (7) `raster::tests::decompression_bombs_stop_at_the_stream_limit`, `raster::tests::page_contents_and_nested_forms_share_one_budget`; (8) `inspect::tests::jspdf_high_precision_mediabox_does_not_overflow_dimensions`, `object::number::tests::high_precision_float_does_not_overflow_mantissa` (hayro-syntax); (9) `object::dict::lazy_index_tests`, `raster::tests::large_resource_indexes_preserve_pixels_and_text`; (10) `data::tests`, `xref::tests::concurrent_cold_object_stream_reads_all_succeed`, `raster::tests::shared_parser_is_lazy_and_initializes_once_under_contention`; (11) `data::tests::panicking_initializer_wakes_waiters_and_prevents_retries`, `xref::tests::concurrent_cold_object_stream_reads_all_succeed`; (12) `util::tests::segment_list_rejects_out_of_range_indices`; (13) `raster::tests::user_unit_scales_the_page_and_everything_on_it`; (14) `crypto::pdfcraft_password_tests`, `pdfcraft-engine` `tests::legacy_passwords_with_turkish_characters_open`; (15) `content::tests::windows_keep_every_instruction_at_every_split`, `content::tests::windows_keep_every_instruction_in_pieces_of_any_size`, `content::tests::windows_match_the_slice_on_random_content`, `content::tests::windows_drop_blanks_and_keep_a_comment_that_may_go_on`, `page::content_reader_tests::content_past_the_cap_is_read_to_the_end`, `page::content_reader_tests::a_stream_that_expands_past_the_budget_is_cut_there`, `page::content_reader_tests::a_small_expansion_under_the_cap_is_not_cut`, `raster::tests::page_content_past_the_old_cap_renders`, `raster::tests::content_reader_returns_the_same_bytes_in_any_pieces`, `raster::tests::content_bombs_stop_at_the_budget_and_say_so`, `page::content_reader_tests::plain_and_whole_pieces_keep_their_bytes`, `page::content_reader_tests::repeated_content_reference_counts_compressed_bytes_once`, `page::content_reader_tests::whole_cap_still_counts_later_unique_streams`; (16) `crypto::pdfcraft_password_tests::aes256_passwords_are_tried_in_their_saslprep_form_then_as_given`, `crypto::pdfcraft_password_tests::aes256_passwords_open_as_typed_and_in_their_saslprep_form`, `pdfcraft-engine` `tests::aes256_open_passwords_that_saslprep_changes_protect_and_reopen_as_typed`, `tests::aes256_files_whose_passwords_saslprep_changes_open_as_typed`; (17) `raster::tests::group4_fax_with_rows_zero_decodes_to_the_image_height`; (18) `filter::lzw_flate::tests::back_reference_longer_than_its_distance_repeats_its_source`, `back_reference_cut_by_the_limit_resumes_in_the_next_call` and `back_reference_reads_bytes_written_by_an_earlier_call`; each fails when the copy returns the wrong remaining count; (19) `raster::tests::group4_fax_with_rows_below_its_height_decodes_to_the_image_height`; (20) `raster::tests::space_before_the_line_break_after_stream_still_renders`; (21) `raster::tests::a_jp2_image_in_a_refused_enumerated_colour_space_is_drawn`, `filter::jpx::tests::refused_enumerated_colour_spaces_become_the_component_counts_default`, `filter::jpx::tests::what_the_decoder_handles_or_cant_be_read_is_left_alone` (`cargo test --manifest-path vendor/hayro-syntax/Cargo.toml`); (22) `raster::tests::objects_in_one_large_object_stream_are_read_in_linear_time`; (23) `text::tests::text_after_an_inline_image_survives_a_non_ascii_byte_before_a_later_ei`, `content::tests::an_inline_image_ends_at_its_own_ei_when_later_text_holds_a_non_ascii_byte` (hayro-syntax); (24) `xref::tests::prev_as_reference_reaches_the_earlier_section`, `xref::tests::prev_as_reference_to_an_object_holding_the_offset_reads_that_offset`, `pdfcraft-cos` `document::tests::a_prev_written_as_a_reference_still_reaches_the_earlier_sections`, `document::tests::a_prev_reference_to_an_object_holding_the_offset_reads_that_offset`; (25) `raster::tests::deeply_nested_direct_objects_do_not_overflow_the_stack`, `raster::tests::dictionaries_nested_without_keys_in_content_do_not_overflow_the_stack`, `raster::tests::dictionaries_nested_without_keys_in_the_trailer_do_not_overflow_the_stack`, `raster::tests::dictionaries_nested_without_keys_as_marked_content_properties_do_not_overflow_the_stack`, `raster::tests::dictionaries_nested_without_keys_are_read_up_to_the_nesting_cap`, `raster::tests::nesting_at_the_cap_fits_a_512_kib_stack` (native only), `raster::tests::function_limits_depth_guard_refuses_a_chain_of_references`; (26) `xref::tests::xref_stream_entries_need_backing_bytes`; (27) `xref::tests::xref_stream_type_field_uses_the_full_w0_width`, `xref::tests::xref_stream_loader_rejects_oversized_w0` (`cargo test --manifest-path vendor/hayro-syntax/Cargo.toml`); (28) `content::ops::tests::scn_with_twelve_components_keeps_them_all`, `content::ops::tests::operands_past_the_cap_keep_the_latest_in_order` (hayro-syntax), `raster::tests::devicen_inks::a_twelve_ink_devicen_colour_paints`, `raster::tests::devicen_inks::a_four_ink_devicen_colour_paints`, `raster::tests::devicen_inks::an_operator_with_hundreds_of_operands_does_not_end_the_content` |
| winit | 0.30.13 | Apache-2.0 | (1) on Windows 11 (build 22000 and later), `WM_DPICHANGED` applies the rect Windows suggests. It used to nudge the window onto the monitor `MonitorFromWindow` names, which during a drag is still the monitor being left; the nudge sent another `WM_DPICHANGED`, so a window dragged to a monitor with another scale factor grew and stayed on the wrong monitor at the wrong scale (#324). Backport of winit master 488c036a ([winit#4341](https://github.com/rust-windowing/winit/pull/4341)), which no 0.30 release has; Windows 10 keeps the old adjustment, as on winit master. (2) on Wayland, a seat's text input is destroyed when the seat goes away, not whenever it loses a capability: losing any capability (a touch screen or tablet unplugged, a remote-desktop session ending) destroyed it, and only an added capability recreated it, so IME stopped working until restart. Port of [winit#4747](https://github.com/rust-windowing/winit/pull/4747); (3) on Windows, an IME composition reports its cursor from `GCS_CURSORPOS` only when `WM_IME_COMPOSITION` says it is set, and at the end of the composition otherwise: the Microsoft Korean IME never sets it, so the cursor read as 0 (egui then drew no caret while composing; it now draws it after the syllable). Port of [winit#4746](https://github.com/rust-windowing/winit/pull/4746); (4) on Windows, a hidden window is not maximized until it is shown, and a hidden window shown while maximized gets one `ShowWindow(SW_MAXIMIZE)`: `SW_MAXIMIZE` shows a hidden window, so PdfCraft, which eframe keeps hidden until its first frame is drawn, appeared unpainted (white) when it restored a maximized window, and could lose its focus. Port of [winit#4587](https://github.com/rust-windowing/winit/pull/4587) (the later, focus-safe form of [winit#4575](https://github.com/rust-windowing/winit/pull/4575)); (5) on X11, when allowing or disallowing IME replaces the focused window's input context (egui does it each time a text field gains or loses focus), the new context is focused: no focus event follows, so it stayed unfocused until the window lost and regained focus. Port of [winit#4727](https://github.com/rust-windowing/winit/pull/4727); (6) on macOS, `insertText` commits through IME when a composition was started (`pending_commit`, set by `setMarkedText`) rather than when marked text is left: input methods that end a composition with `unmarkText` before `insertText` lost the text, and Apple Korean dropped the key typed after a syllable (`한` then `5` or `;`); other `insertText` calls stay `KeyboardInput`; a commit outside a key press (a candidate clicked with the mouse, dictation) clears the marked text and leaves no key to swallow, as in [winit#4748](https://github.com/rust-windowing/winit/pull/4748) (without it the next key, such as Backspace, was lost). `validAttributesForMarkedText` lists the underline and marked-clause attributes, without which some input methods don't compose. Port of [winit#4650](https://github.com/rust-windowing/winit/pull/4650), the 0.30 backport of [winit#4651](https://github.com/rust-windowing/winit/pull/4651) (merged on winit master), with the underline attribute spelled as AppKit's `NSUnderlineStyleAttributeName` (`NSUnderline`); (7) on macOS, disallowing IME with a composition in progress (focus leaving a text field) tells the input method to discard its marked text (`discardMarkedText`): it kept composing it once IME was allowed again, so the abandoned syllable came back (`하`, then `가` typed in the next field, became `학`, then `하` + `가`; Japanese `か` then `さ` became `傘`). Port of [winit#4745](https://github.com/rust-windowing/winit/pull/4745); (8) on macOS, text inserted outside a key press without a composition (the emoji picker) is reported as `Ime::Commit`; it was dropped. Port of the emoji-picker part of [winit#4749](https://github.com/rust-windowing/winit/pull/4749) (0.30 backport of [winit#4748](https://github.com/rust-windowing/winit/pull/4748)); its `selectedRange` change for dictation is left out because it switches on press-and-hold for every held key (an accent menu instead of key repeat, and the chosen accent added after the repeated letters); (9) on macOS, a key whose text was committed through IME isn't also sent as `KeyboardInput` unless AppKit forwards it as a command (Enter): Apple Korean answers Space with no syllable in progress with `setMarkedText(" ")`, `insertText(" ")`, `setMarkedText("")`, and the last call reset winit's state, so the space arrived twice. Same goal as [winit#4478](https://github.com/rust-windowing/winit/pull/4478), whose changes don't reach this call order (macOS 14); to be proposed upstream there; (10) on macOS, when the first key in a fresh app reaches Apple Korean's `insertText` as a raw compatibility jamo instead of starting a composition, that key is interpreted once more, synchronously, before it is sent as `KeyboardInput` (g k s typed ㅎㅏㄴ instead of 한); only an unmodified, non-repeated first key whose one callback inserts that same jamo, with IME enabled and nothing composed, focus and input source unchanged, is retried (`ime_startup.rs`). Port of [winit#4744](https://github.com/rust-windowing/winit/pull/4744), with its policy tests.; (11) on X11 without `Xft.dpi`, the scale factor comes from the X screen's configured DPI (its size in pixels and millimetres) before the output's physical density from RandR: Xorg can deliberately run a dense panel at 96 DPI, and only winit applications then looked zoomed; `Xft.dpi` still wins, `WINIT_X11_SCALE_FACTOR` still overrides, and a screen reporting no size keeps the RandR fallback. PdfCraft patch (#1150, replacing the launcher pin proposed in #908). (12) on macOS, `WinitView` answers `mouseDownCanMoveWindow` with the window's `movable_by_window_background` attribute (NO unless asked): NSView answers YES for a view that isn't opaque, so with the transparent title bar and full-size content view PdfCraft uses, AppKit moved the window for any drag that began in the 28 pt title-bar band before the app saw it, and document tabs (which live in that band) could not be dragged to reorder them. The empty strip still moves the window through `ViewportCommand::StartDrag`. PdfCraft patch. The published crate's asset files (`docs/res/*.svg`, `examples/data/*.png`) are left out, so its `window` example doesn't build; (13) on Wayland, pixel-only wheel, wheel-tilt and continuous-source scroll events report `Moved` rather than starting an unterminated finger gesture, so egui follows modifier release instead of keeping Ctrl zoom latched (#991). Finger gestures and unknown sources retain their existing phase policy | (1) `pdfcraft` `tests::winit_carries_the_windows_11_monitor_scale_fix` keeps the patch in the build; the drag itself needs two monitors with different scale factors on Windows 11; (2) `pdfcraft` `tests/winit_wayland_text_input.rs`; the capability change itself needs a Wayland session and an input method; (3) `pdfcraft` `tests/winit_windows_ime_cursor.rs`; composing itself needs the Microsoft Korean IME; (4) `pdfcraft` `tests/winit_windows_hidden_maximized.rs`; the start-up itself needs Windows and a window that was closed maximized; (5) `pdfcraft` `tests/winit_x11_ime_focus.rs`; switching fields itself needs an X11 session and an input method (IBus, fcitx5); (6) `pdfcraft` `tests/winit_macos_ime_commit.rs`; composing itself needs macOS and an input method; (7) `pdfcraft` `tests/winit_macos_ime_discard.rs`; composing itself needs macOS and an input method; (8) `pdfcraft` `tests/winit_macos_emoji_picker.rs`; the picker itself needs macOS; (9) `pdfcraft` `tests/winit_macos_korean_space.rs`; composing itself needs macOS and Apple Korean; (10) `pdfcraft` `tests/winit_macos_korean_first_key.rs` and `ime_startup.rs`'s own tests (run them with `rustc --test`); typing itself needs macOS and Apple Korean; (11) `pdfcraft` `tests/winit_x11_dpi.rs` keeps the patch in the build, and `util::randr` tests the policy (run them in the vendored crate); the scale itself needs an X11 session; (12) `pdfcraft` `tests/winit_macos_title_bar_drag.rs` keeps the patch in the build; the drag itself needs macOS and a pointer; (13) `pdfcraft` `tests/winit_wayland_scroll.rs` compiles the production phase policy and exercises modifier release through egui; live COSMIC confirmation remains open |
| egui-wgpu | 0.36.2 | MIT OR Apache-2.0 | (1) `winit::surface_fit`: a window's surface is configured within the device's `max_texture_dimension_2d`, both sides shrunk by one factor that egui then draws at (`pixels_per_point × render_scale`), so the whole window is drawn into the surface (on DX12 it is stretched over the window and lines up with the pointer; wgpu's GL backend copies it unscaled into a corner); the longer side becomes exactly the limit; the depth and MSAA textures follow, and a recreated surface starts again from the window's own size. egui-wgpu configured the window's size as is, and `Surface::configure` panics beyond the limit: a window restored at another monitor's scale (opening an Outlook attachment on a mixed-DPI laptop asked an 8192-pixel device for 8600 × 3423, #577) or stretched across monitors closed PdfCraft, before its window appeared when it happened at start-up ([emilk/egui#8361](https://github.com/emilk/egui/issues/8361)). The published crate leaves out egui's licence files; `LICENSE-APACHE` and `LICENSE-MIT` are from the 0.36.2 tag; (2) `winit::catch_errors`: a new window's surface is configured inside wgpu error scopes (validation, out of memory, internal), and a failure is returned as `WgpuError::ConfigureSurface` (for the root window at start-up eframe returns it as `Error::Wgpu`, which PdfCraft retries with OpenGL); nothing is kept for the window. wgpu's default handler panicked instead, and eframe configures the root surface before the app is created, so a driver that can't configure one closed PdfCraft at launch (a 2015 Intel GPU through wgpu's GL backend timed out waiting for the GPU to go idle, `GpuWaitTimeout`, #519). Unchanged, so still a panic: an error in a later reconfigure (resize, a lost surface), a device lost during the first configure (wgpu reports it only to a callback), and a window shown at zero size (first configured on resize) | (1) `pdfcraft` `tests::a_window_larger_than_the_gpu_limit_gets_a_surface_within_it`, `tests::surface_fit_never_empties_or_overflows_a_surface`, and `tests::egui_wgpu_carries_the_surface_size_fit`, which keeps the patch in the build and in the paths that size a surface; (2) `pdfcraft` `tests::a_gpu_error_while_a_window_is_set_up_is_returned_not_a_panic` (a real device: an error inside `catch_errors` is returned, not a panic) and `tests::egui_wgpu_returns_a_surface_it_cannot_configure_as_an_error`, which keeps it around `add_surface`'s configure |
-| vello_cpu | 0.0.8 | Apache-2.0 OR MIT | (1) an opaque gradient or image paint is composited, not copied, when a soft mask or a non-normal blend mode is in effect (`fine/mod.rs`, `fill_complex_paint!`): upstream overwrote the destination, so Chrome-printed CSS opacity and `mix-blend-mode` over gradients came out solid | `opaque_gradient_fill_honours_soft_mask_and_blend_mode` (crates/render) |
| vello_common | 0.0.8 | Apache-2.0 OR MIT | (1) `clip::intersect` (the clip step every clipped path passes through) starts its row walk at the first row both paths have strips in, not the earlier of the two first rows. The walk visited every row from the top of the clip for each path (on the A1 sample's full-page canvas, about half its strip rows per stroke), and rows where one path has no strips produce no output, so the strips are unchanged (vello_common 0.1 starts at the later row too). Its cost grew with the page, and a full-page render of the A1 sample was about 30% faster; the output is byte-identical | (1) `clip::tests::intersect_walks_only_rows_both_paths_have_strips` counts the rows the walk visits (`cargo test --manifest-path vendor/vello_common/Cargo.toml`) and fails without the patch; the render crate's pixel tests run through the patched crate |
-| hayro-cmap | 0.1.0 | Apache-2.0 OR MIT | malformed parts of a CMap (bad bfchar/bfrange entries, unresolvable `usecmap`, unparseable tail) are skipped instead of discarding the whole map, so search and redaction find text the edit layer can read (#3177) | `hayro-cmap::tests::bad_bfchar_entry_is_skipped`, `unresolvable_usecmap_is_skipped` |
+| hayro-cmap | 0.1.0 | Apache-2.0 OR MIT | (1) malformed parts of a CMap (bad bfchar/bfrange entries, unresolvable `usecmap`, unparseable tail) are skipped instead of discarding the whole map, so search and redaction find text the edit layer can read (#3177); (2) a binary CMap's `usecmap` counts against the 16-level nesting limit as a text one does, where it passed its own depth and a self-referencing binary CMap recursed until the stack overflowed (from storytold/craft-libs#254) | (1) `hayro-cmap::tests::bad_bfchar_entry_is_skipped`, `unresolvable_usecmap_is_skipped`; (2) `tests::self_referencing_binary_usecmap_stops_at_the_nesting_limit` |
+| hayro-postscript | 0.1.0 | Apache-2.0 OR MIT | (1) the token scanner's `object::read` skips `<<` and `>>` in a loop; it called itself once per delimiter, so a CMap stream holding a long run of `<` or `>` overflowed the stack and aborted the process (from storytold/craft-libs#263) | (1) `hayro-postscript::object::tests::long_open_dict_run_does_not_overflow`, `long_close_dict_run_does_not_overflow`, `dict_delimiters_are_skipped`, `nested_dict_delimiters_are_skipped` |
Renderer startup errors: `egui-wgpu::RenderState::create` also wraps `Renderer::new` in
`winit::catch_errors` when the winit feature is enabled. A rejected shader or render pipeline
@@ -100,3 +93,12 @@ are unchanged. Renderer regressions `japanese_substitute_missing_spaces_draw_no_
and `japanese_substitute_spaces_keep_pdf_widths_and_unicode` use the synthetic
MS-Mincho / UniJIS-UCS2-HW-H fixture with craft-fonts, including `/W` and `/DW`
placement controls.
+
+Symbolic TrueType `cmap` order (#4156): in `hayro-interpret` `EmbeddedKind::map_code`, an
+embedded TrueType font whose Nonsymbolic flag is not set (the branch `is_non_symbolic()` does not
+take) looks a code up in its Windows (3, 0) or (3, 1) subtables before its Macintosh and Unicode
+ones, as ISO 32000-2 §9.6.5.4 prescribes for symbolic fonts; the
+(1, 0) subtable still serves codes the (3, x) ones leave out. The records were tried in the
+order the font lists them, platform ID first, so a wrong (1, 0) table (SAS 9.4's AMT fonts)
+drew "8" as "p" and "+" as "V". Covered by `raster::tests::symbolic_truetype_cmap`, whose font
+is built in memory.
diff --git a/vendor/hayro-cmap/src/bcmap/mod.rs b/vendor/hayro-cmap/src/bcmap/mod.rs
index 997bc00..e20c459 100644
--- a/vendor/hayro-cmap/src/bcmap/mod.rs
+++ b/vendor/hayro-cmap/src/bcmap/mod.rs
@@ -109,10 +109,13 @@ pub(crate) fn parse<'a>(
SEGMENT_USECMAP => {
let base_data = get_cmap(CMapName::from_bytes(payload))?;
+ // PdfCraft patch: a binary `usecmap` counts against the nesting limit as a text
+ // one does; passing the same depth let a self-referencing CMap recurse until the
+ // stack overflowed.
base = Some(Box::new(parse::parse_inner(
base_data,
get_cmap.clone(),
- depth,
+ depth + 1,
)?));
}
SEGMENT_WMODE => {
diff --git a/vendor/hayro-cmap/src/lib.rs b/vendor/hayro-cmap/src/lib.rs
index fb42ff3..2ef3c6d 100644
--- a/vendor/hayro-cmap/src/lib.rs
+++ b/vendor/hayro-cmap/src/lib.rs
@@ -737,6 +737,17 @@ endcodespacerange
CMap::parse(&data, |_| None).unwrap()
}
+ /// PdfCraft patch test: a binary CMap whose `usecmap` names itself stops at the nesting limit.
+ #[cfg(feature = "embed-cmaps")]
+ #[test]
+ fn self_referencing_binary_usecmap_stops_at_the_nesting_limit() {
+ // Header (magic, version, file length 19), then one usecmap segment (length 9) naming "Self".
+ const SELF_REF: &[u8] = &[
+ b'b', b'c', b'm', b'a', b'p', 1, 0, 0, 0, 19, 0x09, 0, 0, 0, 9, b'S', b'e', b'l', b'f',
+ ];
+ assert!(CMap::parse(SELF_REF, |_| Some(SELF_REF)).is_none());
+ }
+
#[test]
fn metadata_parsing() {
let data = br#"
diff --git a/vendor/hayro-interpret/src/color.rs b/vendor/hayro-interpret/src/color.rs
index 2027396..a8e7d84 100644
--- a/vendor/hayro-interpret/src/color.rs
+++ b/vendor/hayro-interpret/src/color.rs
@@ -28,6 +28,22 @@ pub type ColorComponents = SmallVec<[f32; 4]>;
std::thread_local! {
// PdfCraft patch (34): see `tint_transform_runs`.
static TINT_TRANSFORM_RUNS: core::cell::Cell<u64> = const { core::cell::Cell::new(0) };
+ // PdfCraft patch (55): see `note_color_fallback`.
+ static COLOR_FALLBACK: core::cell::Cell<bool> = const { core::cell::Cell::new(false) };
+}
+
+/// PdfCraft patch (55): record that a colour could not be computed and was painted in a
+/// fallback colour, reported as `InterpreterWarning::ColorFallback` when the content stream
+/// being interpreted ends. Per thread, like the page's other budgets: one page is interpreted
+/// on one thread.
+pub(crate) fn note_color_fallback() {
+ COLOR_FALLBACK.with(|fell_back| fell_back.set(true));
+}
+
+/// PdfCraft patch (55): whether a colour fell back since the last call (or since the page
+/// started), clearing it, so each fallback is reported once.
+pub(crate) fn take_color_fallback() -> bool {
+ COLOR_FALLBACK.with(|fell_back| fell_back.replace(false))
}
/// PdfCraft patch (34): how many colours this thread has run through a Separation or DeviceN
@@ -1030,8 +1046,30 @@ impl ToRgb for Indexed {
#[derive(Debug, Clone)]
pub(crate) struct Separation {
alternate_space: ColorSpace,
- tint_transform: Function,
+ /// PdfCraft patch (55): `None` when the tint transform cannot be read (see
+ /// `eval_tint_transform`).
+ tint_transform: Option<Function>,
is_none_separation: bool,
+ /// PdfCraft patch (66): the colourant is the special name `All`.
+ is_all: bool,
+}
+
+/// PdfCraft patch (55): `tint_transform` run on the tints of one colour, or, when it cannot be
+/// read or evaluated, the initial colour of `alternate_space` (black in every device space), with
+/// the fallback recorded. hayro already fell back this way when evaluation failed, silently; a
+/// transform it could not read made the whole colour space unreadable, and the space's
+/// paints were drawn in DeviceGray from their first tint instead (white for a full tint).
+fn eval_tint_transform(
+ tint_transform: Option<&Function>,
+ alternate_space: &ColorSpace,
+ tints: &[f32],
+) -> ColorComponents {
+ tint_transform
+ .and_then(|f| f.eval(tints.to_smallvec()))
+ .unwrap_or_else(|| {
+ note_color_fallback();
+ alternate_space.initial_color()
+ })
}
impl Separation {
@@ -1041,28 +1079,46 @@ impl Separation {
let _ = iter.next::<Name<'_>>()?;
let name = iter.next::<Name<'_>>()?;
let alternate_space = ColorSpace::new(iter.next::<Object<'_>>()?, cache)?;
- let tint_transform = Function::new(&iter.next::<Object<'_>>()?)?;
- // Either I did something wrong, or no other viewers properly handles
- // `All`, so let's just ignore it as well.
+ // PdfCraft patch (55): an unreadable tint transform keeps the space (see
+ // `eval_tint_transform`).
+ let tint_transform = iter.next::<Object<'_>>().and_then(|f| Function::new(&f));
let is_none_separation = name.as_str() == "None";
+ // PdfCraft patch (66): `All` names every colourant of the output device at once
+ // (ISO 32000-2 §8.6.6.4), so its tints never go through the alternate space.
+ let is_all = name.as_str() == "All";
Some(Self {
alternate_space,
tint_transform,
is_none_separation,
+ is_all,
})
}
}
impl ToRgb for Separation {
fn convert_f32(&self, input: &[f32], output: &mut [u8], _: bool) -> Option<()> {
+ if self.is_all {
+ // PdfCraft patch (66): §8.6.6.4: the tint applies to every colourant, and on an
+ // additive device it is complemented first, so tint t is the gray 1 − t on each of
+ // R, G and B whatever the alternate space and tint transform say.
+ for (tint, rgb) in input.iter().zip(output.chunks_exact_mut(3)) {
+ // `clamp` keeps NaN, and `f32_to_u8`'s cast saturates it to 0.
+ let gray = f32_to_u8(1.0 - tint.clamp(0.0, 1.0));
+ rgb.copy_from_slice(&[gray, gray, gray]);
+ }
+ return Some(());
+ }
count_tint_transform_runs(input.len());
+ // PdfCraft patch (55): see `eval_tint_transform`.
let evaluated = input
.iter()
.flat_map(|n| {
- self.tint_transform
- .eval(smallvec![*n])
- .unwrap_or(self.alternate_space.initial_color())
+ eval_tint_transform(
+ self.tint_transform.as_ref(),
+ &self.alternate_space,
+ &[*n],
+ )
})
.collect::<Vec<_>>();
self.alternate_space.convert_f32(&evaluated, output, false)
@@ -1077,7 +1133,9 @@ impl ToRgb for Separation {
pub(crate) struct DeviceN {
alternate_space: ColorSpace,
num_components: u8,
- tint_transform: Function,
+ /// PdfCraft patch (55): `None` when the tint transform cannot be read (see
+ /// `eval_tint_transform`).
+ tint_transform: Option<Function>,
is_none: bool,
}
@@ -1094,7 +1152,9 @@ impl DeviceN {
let num_components = u8::try_from(names.len()).ok()?;
let all_none = names.iter().all(|n| n.as_str() == "None");
let alternate_space = ColorSpace::new(iter.next::<Object<'_>>()?, cache)?;
- let tint_transform = Function::new(&iter.next::<Object<'_>>()?)?;
+ // PdfCraft patch (55): an unreadable tint transform keeps the space (see
+ // `eval_tint_transform`).
+ let tint_transform = iter.next::<Object<'_>>().and_then(|f| Function::new(&f));
if num_components == 0 {
return None;
@@ -1113,12 +1173,11 @@ impl ToRgb for DeviceN {
fn convert_f32(&self, input: &[f32], output: &mut [u8], _: bool) -> Option<()> {
let colours = input.len().checked_div(usize::from(self.num_components));
count_tint_transform_runs(colours.unwrap_or(0));
+ // PdfCraft patch (55): see `eval_tint_transform`.
let evaluated = input
.chunks_exact(self.num_components as usize)
.flat_map(|n| {
- self.tint_transform
- .eval(n.to_smallvec())
- .unwrap_or(self.alternate_space.initial_color())
+ eval_tint_transform(self.tint_transform.as_ref(), &self.alternate_space, n)
})
.collect::<Vec<_>>();
self.alternate_space.convert_f32(&evaluated, output, false)
diff --git a/vendor/hayro-interpret/src/context.rs b/vendor/hayro-interpret/src/context.rs
index 39806fc..1b1655d 100644
--- a/vendor/hayro-interpret/src/context.rs
+++ b/vendor/hayro-interpret/src/context.rs
@@ -169,6 +169,30 @@ pub struct Context<'a> {
pub(crate) xref: &'a XRef,
pub(crate) ocg_state: OcgState,
nesting_depth: u32,
+ /// PdfCraft patch: estimated bytes held by saved states, and for each `q` not saved because
+ /// a limit was reached, the clip count to return to at its `Q`.
+ saved_bytes: usize,
+ skipped_saves: Vec<usize>,
+}
+
+/// PdfCraft patch: most graphics states saved at once. Every `q` copies the current state, dash
+/// array and clip list included, so without a limit short operators multiply one large state.
+const MAX_SAVED_STATES: usize = 4096;
+/// PdfCraft patch: most bytes all saved states may hold together.
+const MAX_SAVED_STATE_BYTES: usize = 64 << 20;
+
+/// Roughly what a saved copy of `state` holds.
+fn state_bytes(state: &State<'_>) -> usize {
+ size_of::<State<'_>>()
+ .saturating_add(
+ state
+ .graphics_state
+ .stroke_props
+ .dash_array
+ .len()
+ .saturating_mul(size_of::<f32>()),
+ )
+ .saturating_add(state.clips.len().saturating_mul(size_of::<ClipType>()))
}
impl<'a> Context<'a> {
@@ -185,6 +209,8 @@ impl<'a> Context<'a> {
NESTED_PAINTS.with(|n| n.set(0));
CONTENT_LEFT.with(|c| c.set(MAX_PAGE_CONTENT));
CONTENT_TRUNCATED.with(|truncated| truncated.set(false));
+ // PdfCraft patch (55): a fallback left over from another page is not this page's.
+ crate::color::take_color_fallback();
crate::encode::reset_mesh_budget();
Self::new_with(initial_transform, bbox, cache, xref, settings, state, 0)
@@ -223,15 +249,33 @@ impl<'a> Context<'a> {
interpreter_cache: cache.clone(),
ocg_state,
nesting_depth,
+ saved_bytes: 0,
+ skipped_saves: Vec::new(),
}
}
pub(crate) fn save_state(&mut self) {
- let Some(cur) = self.states.last().cloned() else {
+ let Some(cur) = self.states.last() else {
warn!("attempted to save state without existing state");
return;
};
+ // PdfCraft patch: past either limit the `q` is recorded but nothing is copied. Its `Q`
+ // still removes the clips added since; other changes made in between are kept.
+ let bytes = state_bytes(cur);
+ if !self.skipped_saves.is_empty()
+ || self.states.len() >= MAX_SAVED_STATES
+ || self.saved_bytes.saturating_add(bytes) > MAX_SAVED_STATE_BYTES
+ {
+ if self.skipped_saves.is_empty() {
+ warn!("too many saved graphics states; further saves are not kept");
+ }
+ self.skipped_saves.push(cur.clips.len());
+ return;
+ }
+
+ let cur = cur.clone();
+ self.saved_bytes = self.saved_bytes.saturating_add(bytes);
self.states.push(cur);
}
@@ -308,6 +352,14 @@ impl<'a> Context<'a> {
}
pub(crate) fn restore_state(&mut self, device: &mut impl Device<'a>) {
+ // PdfCraft patch: a save that was not kept is the most recent one.
+ if let Some(target_clips) = self.skipped_saves.pop() {
+ while self.get().clips.len() > target_clips {
+ self.pop_clip_path(device);
+ }
+ return;
+ }
+
let Some(target_clips) = self
.states
.get(self.states.len().saturating_sub(2))
@@ -324,6 +376,10 @@ impl<'a> Context<'a> {
// The first state should never be popped.
if self.states.len() > 1 {
self.states.pop();
+ // PdfCraft patch: the state now on top is the copy that was charged when saved.
+ if let Some(top) = self.states.last() {
+ self.saved_bytes = self.saved_bytes.saturating_sub(state_bytes(top));
+ }
}
device.set_soft_mask(
@@ -395,7 +451,8 @@ impl<'a> Context<'a> {
}
pub(crate) fn num_states(&self) -> usize {
- self.states.len()
+ // PdfCraft patch: saves not kept still count, so callers restore back past them.
+ self.states.len().saturating_add(self.skipped_saves.len())
}
pub(crate) fn nesting_depth(&self) -> u32 {
@@ -517,3 +574,97 @@ pub(crate) fn path_as_rect(path: &BezPath) -> Option<Rect> {
Some(path.fast_bounding_box())
}
+
+/// PdfCraft patch tests (ported from craft-libs): the graphics-state stack is bounded by count
+/// and by bytes, and every `q` still pairs with its `Q`.
+#[cfg(test)]
+mod saved_state_tests {
+ use super::*;
+ use crate::device::DummyDevice;
+ use hayro_syntax::Pdf;
+
+ fn pdf() -> Pdf {
+ let objects = [
+ "<< /Type /Catalog /Pages 2 0 R >>",
+ "<< /Type /Pages /Count 0 /Kids [] >>",
+ ];
+ let mut out = b"%PDF-1.7\n".to_vec();
+ let mut offsets = Vec::new();
+ for (i, body) in objects.iter().enumerate() {
+ offsets.push(out.len());
+ out.extend_from_slice(format!("{} 0 obj\n{body}\nendobj\n", i + 1).as_bytes());
+ }
+ let xref = out.len();
+ out.extend_from_slice(b"xref\n0 3\n0000000000 65535 f \n");
+ for offset in offsets {
+ out.extend_from_slice(format!("{offset:010} 00000 n \n").as_bytes());
+ }
+ out.extend_from_slice(
+ format!("trailer\n<< /Size 3 /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n").as_bytes(),
+ );
+ Pdf::new(out).expect("synthetic pdf")
+ }
+
+ fn triangle() -> BezPath {
+ let mut path = BezPath::new();
+ path.move_to((10.0, 10.0));
+ path.line_to((90.0, 10.0));
+ path.line_to((50.0, 90.0));
+ path.close_path();
+ path
+ }
+
+ /// Saves `saves` more times, checks a clip added after the last save goes at its `Q`, and unwinds.
+ fn save_and_unwind(ctx: &mut Context<'_>, saves: usize) {
+ let before = ctx.num_states();
+ for _ in 0..saves {
+ ctx.save_state();
+ }
+ assert!(ctx.states.len() <= MAX_SAVED_STATES);
+ assert!(ctx.saved_bytes <= MAX_SAVED_STATE_BYTES);
+ assert_eq!(ctx.num_states(), before + saves, "every q still counts");
+
+ let mut device = DummyDevice;
+ let clips = ctx.get().clips.len();
+ ctx.push_clip_path(triangle(), FillRule::NonZero, &mut device);
+ assert_eq!(ctx.get().clips.len(), clips + 1);
+ ctx.restore_state(&mut device);
+ assert_eq!(ctx.get().clips.len(), clips);
+
+ while ctx.num_states() > 1 {
+ ctx.restore_state(&mut device);
+ }
+ assert_eq!(ctx.states.len(), 1);
+ assert!(ctx.skipped_saves.is_empty());
+ assert_eq!(ctx.saved_bytes, 0);
+ }
+
+ #[test]
+ fn repeated_saves_stay_bounded_and_balanced() {
+ let pdf = pdf();
+ let cache = InterpreterCache::new();
+ let bbox = Rect::new(0.0, 0.0, 100.0, 100.0);
+ let settings = InterpreterSettings::default();
+ let mut ctx = Context::new(Affine::IDENTITY, bbox, &cache, pdf.xref(), settings);
+
+ // A small state reaches the count limit.
+ save_and_unwind(&mut ctx, 20_000);
+
+ // A large one (a 64 Ki-entry dash array, 256 KiB a copy) reaches the byte limit first.
+ ctx.get_mut().graphics_state.stroke_props.dash_array = (0..1 << 16).map(|_| 2.0).collect();
+ ctx.save_state();
+ assert_eq!(ctx.states.len(), 2);
+ while ctx.skipped_saves.is_empty() {
+ ctx.save_state();
+ }
+ assert!(ctx.states.len() < MAX_SAVED_STATES);
+ save_and_unwind(&mut ctx, 1000);
+
+ // Once unwound, a kept save restores what changed after it.
+ let mut device = DummyDevice;
+ ctx.save_state();
+ ctx.pre_concat_affine(Affine::scale(2.0));
+ ctx.restore_state(&mut device);
+ assert_eq!(ctx.get().ctm, Affine::IDENTITY);
+ }
+}
diff --git a/vendor/hayro-interpret/src/font/cid.rs b/vendor/hayro-interpret/src/font/cid.rs
index e23b243..44e076b 100644
--- a/vendor/hayro-interpret/src/font/cid.rs
+++ b/vendor/hayro-interpret/src/font/cid.rs
@@ -86,7 +86,9 @@ impl Type0Font {
if let Some((standard, _)) = select_standard_font(dict, &font_descriptor) {
(FontQuery::Standard(standard), true)
} else {
- let mut query = FallbackFontQuery::new(dict);
+ // PdfCraft patch: the style comes from the descendant's descriptor.
+ let mut query =
+ FallbackFontQuery::with_descriptor(dict, Some(font_descriptor.clone()));
query.character_collection = character_collection.clone();
warn!(
@@ -618,6 +620,12 @@ fn read_widths2(arr: &Array<'_>) -> Option<HashMap<u32, [f32; 3]>> {
let mut iter = range.iter::<f32>();
while let Some(w) = iter.next() {
+ // PdfCraft patch: as in `read_widths`, checked before the run's metrics are
+ // read. Without it, a run starting at 4294967295 overflowed `first` and
+ // discarded the whole /W2 table.
+ if first > MAX_CID {
+ break;
+ }
let v1 = iter.next()?;
let v2 = iter.next()?;
map.insert(first, [w, v1, v2]);
@@ -669,3 +677,24 @@ fn read_encoding(object: &Object<'_>, cmap_resolver: &CMapResolverFn) -> Option<
_ => None,
}
}
+
+/// PdfCraft patch test (ported from craft-libs): a /W2 run whose first CID is past `MAX_CID`
+/// is skipped and the rest of the table kept.
+#[cfg(test)]
+mod tests {
+ use super::read_widths2;
+ use hayro_syntax::object::{Array, FromBytes};
+
+ #[test]
+ fn w2_run_past_the_largest_cid_keeps_the_rest_of_the_table() {
+ let arr =
+ Array::from_bytes(b"[4294967295 [1000 500] 10 [900 450 860] 20 30 800 400 870]")
+ .unwrap();
+ let map = read_widths2(&arr).unwrap();
+
+ assert_eq!(map.get(&4_294_967_295), None);
+ assert_eq!(map.get(&10), Some(&[900.0, 450.0, 860.0]));
+ assert_eq!(map.get(&25), Some(&[800.0, 400.0, 870.0]));
+ assert_eq!(map.len(), 12);
+ }
+}
diff --git a/vendor/hayro-interpret/src/font/mod.rs b/vendor/hayro-interpret/src/font/mod.rs
index 103ee39..e0fc759 100644
--- a/vendor/hayro-interpret/src/font/mod.rs
+++ b/vendor/hayro-interpret/src/font/mod.rs
@@ -564,6 +564,13 @@ pub struct FallbackFontQuery {
impl FallbackFontQuery {
pub(crate) fn new(dict: &Dict<'_>) -> Self {
+ Self::with_descriptor(dict, dict.get::<Dict<'_>>(FONT_DESC))
+ }
+
+ /// PdfCraft patch: the query for the font `dict` names, with its style read from
+ /// `descriptor`. A Type 0 font has no font descriptor of its own; its descendant CIDFont
+ /// has it (ISO 32000-2 §9.7.4.1, §9.7.6.1).
+ pub(crate) fn with_descriptor(dict: &Dict<'_>, descriptor: Option<Dict<'_>>) -> Self {
let post_script_name = dict
.get::<Name<'_>>(BASE_FONT)
.map(|n| strip_subset_prefix(n.as_str()).to_string());
@@ -573,7 +580,7 @@ impl FallbackFontQuery {
..Default::default()
};
- if let Some(descriptor) = dict.get::<Dict<'_>>(FONT_DESC) {
+ if let Some(descriptor) = descriptor {
data.font_name = dict
.get::<Name<'_>>(FONT_NAME)
.map(|n| strip_subset_prefix(n.as_str()).to_string());
diff --git a/vendor/hayro-interpret/src/font/standard_font.rs b/vendor/hayro-interpret/src/font/standard_font.rs
index 406023e..a9b1d95 100644
--- a/vendor/hayro-interpret/src/font/standard_font.rs
+++ b/vendor/hayro-interpret/src/font/standard_font.rs
@@ -554,6 +554,15 @@ impl StandardKind {
return path;
};
+ // PdfCraft patch (57): a stand-in for a font the document names is narrowed to a
+ // narrower /Widths advance, so neighbours don't overlap, but never widened: the
+ // advance already places the next glyph, and widening drew `i` and `l` of a 600-unit
+ // `Arial,Bold` as solid blocks twice their width.
+ let should_width = if self.fallback {
+ should_width.min(actual_width)
+ } else {
+ should_width
+ };
return stretch_glyph(path, should_width, actual_width);
}
diff --git a/vendor/hayro-interpret/src/font/true_type.rs b/vendor/hayro-interpret/src/font/true_type.rs
index c650439..25b3ebc 100644
--- a/vendor/hayro-interpret/src/font/true_type.rs
+++ b/vendor/hayro-interpret/src/font/true_type.rs
@@ -360,26 +360,36 @@ impl EmbeddedKind {
}
}
} else if let Ok(cmap) = self.base_font.font_ref().cmap() {
- for record in cmap.encoding_records() {
- if record.platform_id() == PlatformId::Windows
- && matches!(record.encoding_id(), 0 | 1)
- {
- if let Ok(subtable) = record.subtable(cmap.offset_data()) {
- for offset in [0x0000_u32, 0xF000, 0xF100, 0xF200] {
- glyph = glyph
- .or_else(|| subtable.map_codepoint(code as u32 + offset))
- .filter(|g| *g != GlyphId::NOTDEF);
+ // PdfCraft patch (#4156): the Windows (3, 0) subtable comes first, and the (1, 0) one
+ // only for codes it doesn't map (ISO 32000-2 §9.6.5.4: "If the font contains a (3, 0)
+ // subtable" it is used; "Otherwise, if the font contains a (1, 0) subtable"). The
+ // records are listed by platform ID, so Macintosh came before Windows and a wrong
+ // (1, 0) table, as SAS writes for its AMT fonts, drew "8" as "p" and "+" as "V".
+ for windows_pass in [true, false] {
+ for record in cmap.encoding_records() {
+ let windows = record.platform_id() == PlatformId::Windows
+ && matches!(record.encoding_id(), 0 | 1);
+ if windows != windows_pass {
+ continue;
+ }
+ if windows {
+ if let Ok(subtable) = record.subtable(cmap.offset_data()) {
+ for offset in [0x0000_u32, 0xF000, 0xF100, 0xF200] {
+ glyph = glyph
+ .or_else(|| subtable.map_codepoint(code as u32 + offset))
+ .filter(|g| *g != GlyphId::NOTDEF);
+ }
}
+ } else if matches!(
+ record.platform_id(),
+ PlatformId::Macintosh | PlatformId::Unicode
+ ) && record.encoding_id() == 0
+ && let Ok(subtable) = record.subtable(cmap.offset_data())
+ {
+ glyph = glyph
+ .or_else(|| subtable.map_codepoint(code))
+ .filter(|g| *g != GlyphId::NOTDEF);
}
- } else if matches!(
- record.platform_id(),
- PlatformId::Macintosh | PlatformId::Unicode
- ) && record.encoding_id() == 0
- && let Ok(subtable) = record.subtable(cmap.offset_data())
- {
- glyph = glyph
- .or_else(|| subtable.map_codepoint(code))
- .filter(|g| *g != GlyphId::NOTDEF);
}
}
}
diff --git a/vendor/hayro-interpret/src/interpret/mod.rs b/vendor/hayro-interpret/src/interpret/mod.rs
index 7e1a554..3dd9cef 100644
--- a/vendor/hayro-interpret/src/interpret/mod.rs
+++ b/vendor/hayro-interpret/src/interpret/mod.rs
@@ -21,7 +21,7 @@ use hayro_syntax::object::dict::keys::{
ACTUAL_TEXT, ANNOTS, AP, AS, C, CA, F, MCID, N, OC, QUADPOINTS, RECT, SUBTYPE,
};
use hayro_syntax::object::{Array, Dict, Object, Rect, Stream, dict_or_stream};
-use hayro_syntax::page::{ContentReader, Page, Resources};
+use hayro_syntax::page::{ContentReader, Page, Resources, Rotation};
use hayro_syntax::MAX_DECODED_STREAM;
use kurbo::{Affine, BezPath, Point, Shape};
use smallvec::smallvec;
@@ -161,6 +161,10 @@ pub enum InterpreterWarning {
ImageDecodeFailure,
/// PdfCraft patch (18): a page content stream was skipped after exhausting its safety budget.
ContentTruncated,
+ /// PdfCraft patch (55): a colour could not be computed (a colour space that cannot be
+ /// read, or a Separation or DeviceN tint transform that cannot be evaluated) and was painted
+ /// in a fallback colour. Reported at most once per content stream.
+ ColorFallback,
}
/// interpret the contents of the page and render them into the device.
@@ -190,6 +194,15 @@ pub fn interpret_page<'a>(
if flags & (2 | 32) != 0 {
continue;
}
+ // PdfCraft patch (56): Invisible (bit 1) hides an annotation of a type that isn't one
+ // of the standard ones (ISO 32000-2 Table 167), and a popup has no appearance of its
+ // own (§12.5.6.14): the viewer shows it as a window for its parent, not on the page.
+ let subtype = annot.get::<hayro_syntax::object::Name<'_>>(SUBTYPE);
+ if subtype.as_deref() == Some(b"Popup")
+ || (flags & 1 != 0 && !subtype.as_deref().is_some_and(is_standard_annotation_type))
+ {
+ continue;
+ }
// PdfCraft patch: "Hide all comments" keeps widgets and links.
if context.settings.hide_comments
&& !matches!(annot.get::<hayro_syntax::object::Name<'_>>(SUBTYPE).as_deref(), Some(b"Widget" | b"Link"))
@@ -257,6 +270,13 @@ pub fn interpret_page<'a>(
annot_rect.x0 - sx * transformed_rect.x0,
annot_rect.y0 - sy * transformed_rect.y0,
]);
+ // PdfCraft patch (59): NoRotate (bit 5) keeps the appearance upright as the page is
+ // displayed (ISO 32000-2 §12.5.3).
+ let affine = if flags & 16 != 0 && no_rotate_applies(&annot) {
+ no_rotate_turn(page.rotation(), &annot_rect) * affine
+ } else {
+ affine
+ };
// PdfCraft patch: a /BBox or /Matrix that collapses the appearance box to a line
// or a point leaves nothing to map onto /Rect: the scales above divide by zero,
@@ -290,6 +310,67 @@ pub fn interpret_page<'a>(
}
}
+/// PdfCraft patch (56): whether `subtype` is one of the standard annotation types of
+/// ISO 32000-2 Table 171.
+fn is_standard_annotation_type(subtype: &[u8]) -> bool {
+ matches!(
+ subtype,
+ b"Text"
+ | b"Link"
+ | b"FreeText"
+ | b"Line"
+ | b"Square"
+ | b"Circle"
+ | b"Polygon"
+ | b"PolyLine"
+ | b"Highlight"
+ | b"Underline"
+ | b"Squiggly"
+ | b"StrikeOut"
+ | b"Caret"
+ | b"Stamp"
+ | b"Ink"
+ | b"Popup"
+ | b"FileAttachment"
+ | b"Sound"
+ | b"Movie"
+ | b"Screen"
+ | b"Widget"
+ | b"PrinterMark"
+ | b"TrapNet"
+ | b"Watermark"
+ | b"3D"
+ | b"Redact"
+ | b"Projection"
+ | b"RichMedia"
+ )
+}
+
+/// PdfCraft patch (59): whether the NoRotate flag turns this annotation's appearance. Form fields
+/// and links are left in `/Rect`: PdfCraft takes their click targets from it.
+fn no_rotate_applies(annot: &Dict<'_>) -> bool {
+ !matches!(
+ annot.get::<hayro_syntax::object::Name<'_>>(SUBTYPE).as_deref(),
+ Some(b"Widget" | b"Link")
+ )
+}
+
+/// PdfCraft patch (59): the user-space turn that keeps a NoRotate annotation upright on a page
+/// with `/Rotate`. The page is shown turned clockwise, so the appearance (already fitted to
+/// `/Rect`) is turned as far counterclockwise about the rectangle's upper-left corner, which stays
+/// where it is on the page (ISO 32000-2 §12.5.3). Its width then runs across the displayed page
+/// and its height down from that corner.
+fn no_rotate_turn(rotation: Rotation, rect: &kurbo::Rect) -> Affine {
+ let (cos, sin) = match rotation {
+ Rotation::None => return Affine::IDENTITY,
+ Rotation::Horizontal => (0.0, 1.0),
+ Rotation::Flipped => (-1.0, 0.0),
+ Rotation::FlippedHorizontal => (0.0, -1.0),
+ };
+ let (x, y) = (rect.x0.min(rect.x1), rect.y0.max(rect.y1));
+ Affine::new([cos, sin, -sin, cos, x - (cos * x - sin * y), y - (sin * x + cos * y)])
+}
+
/// PdfCraft patch: the normal appearance of a Highlight annotation that has none (ISO 32000-2
/// §12.5.6.10), drawn as PdfCraft draws its own highlights (pdfcraft-annot): each /QuadPoints
/// quadrilateral filled with /C at /CA opacity, blended with Multiply so the marked-up content
@@ -570,8 +651,13 @@ fn interpret_window<'a>(
}
TypedInstruction::ColorSpaceStroke(c) => {
// PdfCraft patch (38): see `named_color_space`.
+ // PdfCraft patch (55): a space that cannot be read is drawn in DeviceGray, as
+ // before, and the fallback is reported.
let cs = named_color_space(c.0, resources, &defaults, context)
- .unwrap_or(ColorSpace::device_gray());
+ .unwrap_or_else(|| {
+ crate::color::note_color_fallback();
+ ColorSpace::device_gray()
+ });
if !cs.is_pattern() {
context.get_mut().graphics_state.stroke_pattern = None;
@@ -581,8 +667,13 @@ fn interpret_window<'a>(
}
TypedInstruction::ColorSpaceNonStroke(c) => {
// PdfCraft patch (38): see `named_color_space`.
+ // PdfCraft patch (55): a space that cannot be read is drawn in DeviceGray, as
+ // before, and the fallback is reported.
let cs = named_color_space(c.0, resources, &defaults, context)
- .unwrap_or(ColorSpace::device_gray());
+ .unwrap_or_else(|| {
+ crate::color::note_color_fallback();
+ ColorSpace::device_gray()
+ });
if !cs.is_pattern() {
context.get_mut().graphics_state.non_stroke_pattern = None;
@@ -940,6 +1031,10 @@ pub fn interpret<'a>(
if crate::context::content_was_truncated() {
(context.settings.warning_sink)(InterpreterWarning::ContentTruncated);
}
+ // PdfCraft patch (55): and that a colour was painted in a fallback colour.
+ if crate::color::take_color_fallback() {
+ (context.settings.warning_sink)(InterpreterWarning::ColorFallback);
+ }
}
/// PdfCraft patch: the bytes of a window of page content. A window grows only while an instruction
@@ -998,4 +1093,8 @@ fn interpret_content<'a>(
if cut || content.truncated() || crate::context::content_was_truncated() {
(context.settings.warning_sink)(InterpreterWarning::ContentTruncated);
}
+ // PdfCraft patch (55): and that a colour was painted in a fallback colour.
+ if crate::color::take_color_fallback() {
+ (context.settings.warning_sink)(InterpreterWarning::ColorFallback);
+ }
}
diff --git a/vendor/hayro-interpret/src/interpret/text.rs b/vendor/hayro-interpret/src/interpret/text.rs
index cd5e147..b7b1b2a 100644
--- a/vendor/hayro-interpret/src/interpret/text.rs
+++ b/vendor/hayro-interpret/src/interpret/text.rs
@@ -69,11 +69,15 @@ pub(crate) fn show_glyph<'a>(
device.set_blend_mode(ctx.get().graphics_state.blend_mode);
let stroke_props = ctx.stroke_props();
- // PdfCraft patch: only mode 3 has any effect on text in a Type 3 font (ISO 32000-1
- // 9.3.6). Stroking ran the glyph procedure a second time, so `2 Tr` made bitmap fonts
- // look bold, and the clip modes have no outline to clip with.
+ // PdfCraft patch: text in a Type 3 font is rendered from its glyph descriptions in every mode
+ // but 3 and 7 (ISO 32000-2 §9.3.6). Stroking ran the glyph procedure a second time, so
+ // `2 Tr` made bitmap fonts look bold.
+ // PdfCraft patch (64): in modes 3 and 7 the text "shall not be rendered" (§9.3.6); `7 Tr`
+ // painted the glyphs in the fill colour. It is still reported as clipping text, but in
+ // modes 4 to 7 "nothing shall be added to the clipping path" (`clip_glyph`).
let render_mode = match (glyph, ctx.get().text_state.render_mode) {
(Glyph::Type3(_), TextRenderingMode::Invisible) => TextRenderingMode::Invisible,
+ (Glyph::Type3(_), TextRenderingMode::Clip) => TextRenderingMode::Clip,
(Glyph::Type3(_), _) => TextRenderingMode::Fill,
(_, mode) => mode,
};
@@ -187,9 +191,9 @@ pub(crate) fn clip_glyph(context: &mut Context<'_>, glyph: &Glyph<'_>, transform
context.get_mut().text_state.clip_paths.extend(outline);
}
}
- Glyph::Type3(_) => {
- warn!("text rendering mode clip not implemented for shape glyphs");
- }
+ // PdfCraft patch (64): a Type 3 glyph adds nothing to the clipping path in modes 4 to 7
+ // (ISO 32000-2 §9.3.6), so text shown only in a Type 3 font leaves no clip at `ET`.
+ Glyph::Type3(_) => {}
}
}
diff --git a/vendor/hayro-jbig2/src/segment.rs b/vendor/hayro-jbig2/src/segment.rs
index 35c17c3..db720df 100644
--- a/vendor/hayro-jbig2/src/segment.rs
+++ b/vendor/hayro-jbig2/src/segment.rs
@@ -8,6 +8,12 @@ use alloc::vec::Vec;
use crate::error::{ParseError, Result, SegmentError, bail, err};
use crate::reader::Reader;
+/// PdfCraft patch: the most segments one segment may refer to. A long-form header can claim a
+/// 29-bit count, which `Vec::with_capacity` below would turn into a multi-gigabyte reservation
+/// before a single referred-to number is read; the allocation failure aborts the process. Real
+/// files refer to a handful of segments.
+pub(crate) const MAX_REFERRED_TO_SEGMENTS: u32 = u16::MAX as u32;
+
/// "The segment type is a number between 0 and 63, inclusive. Not all values
/// are allowed." (7.3)
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -183,6 +189,12 @@ pub(crate) fn parse_segment_header(reader: &mut Reader<'_>) -> Result<SegmentHea
u32::from_be_bytes([count_and_retention & 0x1F, rest[0], rest[1], rest[2]])
};
+ // PdfCraft patch: refuse an oversized count before reserving memory for it and before
+ // skipping the retention-flag bytes it claims.
+ if referred_to_count > MAX_REFERRED_TO_SEGMENTS {
+ bail!(SegmentError::InvalidReferredCount);
+ }
+
// Skip retention flag bytes in long form.
// "The first one-byte field following the initial four-byte field is formatted
// as follows: Bit 0: Retain bit for this segment. Bit 1-7: Retain bits for
@@ -416,4 +428,34 @@ mod tests {
assert_eq!(header.data_length, Some(32));
}
+
+ /// PdfCraft patch test (ported from craft-libs): a long-form referred-to count over
+ /// `MAX_REFERRED_TO_SEGMENTS` is refused before its retention bytes are read.
+ #[test]
+ fn test_referred_to_count_is_capped() {
+ use crate::error::DecodeError;
+
+ let header = |count: u32| {
+ let mut data = vec![
+ 0x00, 0x01, 0x00, 0x00, // Segment number = 65536
+ 0x86, // Flags: type 6, page assoc 1 byte, deferred non-retain
+ ];
+ // Long form: bits 29-31 are 7, bits 0-28 the count.
+ data.extend_from_slice(&(0xE000_0000 | count).to_be_bytes());
+ parse_segment_header(&mut Reader::new(&data)).unwrap_err()
+ };
+
+ // The 29-bit maximum, 536,870,911, would reserve about 2 GiB.
+ for count in [0x1FFF_FFFF, MAX_REFERRED_TO_SEGMENTS + 1] {
+ assert!(matches!(
+ header(count),
+ DecodeError::Segment(SegmentError::InvalidReferredCount)
+ ));
+ }
+ // At the cap the header is read on and ends at its missing retention bytes.
+ assert!(matches!(
+ header(MAX_REFERRED_TO_SEGMENTS),
+ DecodeError::Parse(ParseError::UnexpectedEof)
+ ));
+ }
}
diff --git a/vendor/hayro-postscript/Cargo.lock b/vendor/hayro-postscript/Cargo.lock
new file mode 100644
index 0000000..b95d341
--- /dev/null
+++ b/vendor/hayro-postscript/Cargo.lock
@@ -0,0 +1,7 @@
+# This file is automatically @generated by Cargo.
+# It is not intended for manual editing.
+version = 4
+
+[[package]]
+name = "hayro-postscript"
+version = "0.1.0"
diff --git a/vendor/hayro-postscript/Cargo.toml b/vendor/hayro-postscript/Cargo.toml
new file mode 100644
index 0000000..b1d53c3
--- /dev/null
+++ b/vendor/hayro-postscript/Cargo.toml
@@ -0,0 +1,70 @@
+# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
+#
+# When uploading crates to the registry Cargo will automatically
+# "normalize" Cargo.toml files for maximal compatibility
+# with all versions of Cargo and also rewrite `path` dependencies
+# to registry (e.g., crates.io) dependencies.
+#
+# If you are reading this file be aware that the original Cargo.toml
+# will likely look very different (and much more reasonable).
+# See Cargo.toml.orig for the original contents.
+
+[package]
+edition = "2024"
+name = "hayro-postscript"
+version = "0.1.0"
+authors = ["Laurenz Stampfl <[email protected]>"]
+build = false
+autolib = false
+autobins = false
+autoexamples = false
+autotests = false
+autobenches = false
+description = "A lightweight PostScript scanner."
+readme = "README.md"
+license = "Apache-2.0 OR MIT"
+repository = "https://github.com/LaurenzV/hayro"
+resolver = "2"
+
+[lib]
+name = "hayro_postscript"
+path = "src/lib.rs"
+
+[[example]]
+name = "tokenize"
+path = "examples/tokenize.rs"
+
+[lints.clippy]
+collection_is_never_read = "warn"
+dbg_macro = "warn"
+debug_assert_with_mut_call = "warn"
+default_trait_access = "warn"
+doc_markdown = "warn"
+fn_to_numeric_cast_any = "warn"
+infinite_loop = "warn"
+large_stack_arrays = "warn"
+mismatching_type_param_order = "warn"
+negative_feature_names = "warn"
+redundant_feature_names = "warn"
+same_functions_in_if_condition = "warn"
+semicolon_if_nothing_returned = "warn"
+todo = "warn"
+too_many_arguments = "allow"
+unseparated_literal_suffix = "warn"
+use_self = "warn"
+wildcard_dependencies = "warn"
+
+[lints.rust]
+elided_lifetimes_in_paths = "warn"
+keyword_idents_2024 = "forbid"
+missing_docs = "warn"
+non_ascii_idents = "forbid"
+non_local_definitions = "forbid"
+trivial_numeric_casts = "warn"
+unnameable_types = "warn"
+unreachable_pub = "warn"
+unsafe_op_in_unsafe_fn = "forbid"
+unused_import_braces = "warn"
+unused_lifetimes = "warn"
+unused_macro_rules = "warn"
+unused_qualifications = "warn"
diff --git a/vendor/hayro-postscript/Cargo.toml.orig b/vendor/hayro-postscript/Cargo.toml.orig
new file mode 100644
index 0000000..6ba1eed
--- /dev/null
+++ b/vendor/hayro-postscript/Cargo.toml.orig
@@ -0,0 +1,11 @@
+[package]
+name = "hayro-postscript"
+version = "0.1.0"
+description = "A lightweight PostScript scanner."
+authors = { workspace = true }
+edition = { workspace = true }
+repository = { workspace = true }
+license = { workspace = true }
+
+[lints]
+workspace = true
diff --git a/vendor/hayro-postscript/LICENSE-APACHE b/vendor/hayro-postscript/LICENSE-APACHE
new file mode 100644
index 0000000..4947287
--- /dev/null
+++ b/vendor/hayro-postscript/LICENSE-APACHE
@@ -0,0 +1,177 @@
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
\ No newline at end of file
diff --git a/vendor/hayro-postscript/LICENSE-MIT b/vendor/hayro-postscript/LICENSE-MIT
new file mode 100644
index 0000000..ae3742d
--- /dev/null
+++ b/vendor/hayro-postscript/LICENSE-MIT
@@ -0,0 +1,7 @@
+Copyright (c) The Hayro Authors
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS 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. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
\ No newline at end of file
diff --git a/vendor/hayro-postscript/README.md b/vendor/hayro-postscript/README.md
new file mode 100644
index 0000000..3c22827
--- /dev/null
+++ b/vendor/hayro-postscript/README.md
@@ -0,0 +1,30 @@
+# hayro-postscript
+
+[![Crates.io](https://img.shields.io/crates/v/hayro-postscript.svg)](https://crates.io/crates/hayro-postscript)
+[![Documentation](https://docs.rs/hayro-postscript/badge.svg)](https://docs.rs/hayro-postscript)
+
+<!-- cargo-rdme start -->
+
+A lightweight PostScript scanner.
+
+This crate provides a scanner for tokenizing PostScript programs into typed objects.
+It currently only implements a very small subset of the PostScript language,
+with the main goal of being enough to parse CMAP files, but the scope _might_
+be expanded upon in the future.
+
+The supported types include integers and real numbers, name objects, strings and arrays.
+Unsupported is anything else, including dictionaries, procedures, etc. An error
+will be returned in case any of these is encountered.
+
+### Safety
+This crate forbids unsafe code via a crate-level attribute.
+
+<!-- cargo-rdme end -->
+
+## License
+Licensed under either of
+
+- Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or <http://www.apache.org/licenses/LICENSE-2.0>)
+- MIT license ([LICENSE-MIT](LICENSE-MIT) or <http://opensource.org/licenses/MIT>)
+
+at your option.
diff --git a/vendor/hayro-postscript/examples/tokenize.rs b/vendor/hayro-postscript/examples/tokenize.rs
new file mode 100644
index 0000000..c8cd84d
--- /dev/null
+++ b/vendor/hayro-postscript/examples/tokenize.rs
@@ -0,0 +1,74 @@
+//! A small example that shows how to tokenize a PostScript program.
+
+#![allow(missing_docs)]
+
+use hayro_postscript::{Number, Object, Scanner};
+use std::env;
+use std::fs;
+use std::process;
+
+fn main() {
+ let path = match env::args().nth(1) {
+ Some(p) => p,
+ None => {
+ eprintln!("Usage: tokenize <file>");
+ process::exit(1);
+ }
+ };
+
+ let data = match fs::read(&path) {
+ Ok(d) => d,
+ Err(e) => {
+ eprintln!("Error reading {path}: {e}");
+ process::exit(1);
+ }
+ };
+
+ let mut scanner = Scanner::new(&data);
+
+ while !scanner.at_end() {
+ match scanner.parse_object() {
+ Ok(object) => {
+ print_object(&object);
+ println!();
+ }
+ Err(e) => eprintln!("Error: {e}"),
+ }
+ }
+}
+
+fn print_object(object: &Object<'_>) {
+ match object {
+ Object::Number(Number::Integer(n)) => print!("Integer({n})"),
+ Object::Number(Number::Real(n)) => print!("Real({n})"),
+ Object::Name(name) => {
+ let kind = if name.is_literal() {
+ "literal"
+ } else {
+ "executable"
+ };
+ let text = name.as_str().unwrap_or("<non-ascii name>");
+ print!("Name({text}, {kind})");
+ }
+ Object::String(s) => {
+ let decoded = s.decode().unwrap_or_else(|_| Vec::new());
+ print!("String({})", String::from_utf8_lossy(&decoded));
+ }
+ Object::Array(arr) => {
+ print!("[");
+ let mut inner = arr.objects();
+ let mut first = true;
+ while !inner.at_end() {
+ if !first {
+ print!(" ");
+ }
+ first = false;
+ match inner.parse_object() {
+ Ok(obj) => print_object(&obj),
+ Err(e) => print!("Error({e})"),
+ }
+ }
+ print!("]");
+ }
+ }
+}
diff --git a/vendor/hayro-postscript/src/array.rs b/vendor/hayro-postscript/src/array.rs
new file mode 100644
index 0000000..b96b360
--- /dev/null
+++ b/vendor/hayro-postscript/src/array.rs
@@ -0,0 +1,127 @@
+use crate::error::{Error, Result};
+use crate::object;
+use crate::reader::Reader;
+use crate::string;
+
+/// A PostScript array object.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct Array<'a> {
+ data: &'a [u8],
+}
+
+impl<'a> Array<'a> {
+ pub(crate) fn new(data: &'a [u8]) -> Self {
+ Self { data }
+ }
+
+ /// Return a [`Scanner`](crate::Scanner) that iterates over the objects inside
+ /// this array.
+ pub fn objects(&self) -> crate::Scanner<'a> {
+ crate::Scanner::new(self.data)
+ }
+}
+
+pub(crate) fn parse<'a>(r: &mut Reader<'a>) -> Result<&'a [u8]> {
+ r.forward_tag(b"[").ok_or(Error::SyntaxError)?;
+
+ let start = r.offset();
+ skip_array(r)?;
+ let end = r.offset() - 1;
+
+ r.range(start..end).ok_or(Error::SyntaxError)
+}
+
+fn skip_array(r: &mut Reader<'_>) -> Result<()> {
+ let mut depth = 1_u32;
+
+ while depth > 0 {
+ match r.peek_byte().ok_or(Error::SyntaxError)? {
+ b'[' => {
+ r.forward();
+ depth += 1;
+ }
+ b']' => {
+ r.forward();
+ depth -= 1;
+ }
+ b'(' => {
+ let _ = string::parse_literal(r).ok_or(Error::SyntaxError)?;
+ }
+ b'<' => {
+ if r.peek_bytes(2) == Some(b"<~") {
+ let _ = string::parse_ascii85(r).ok_or(Error::SyntaxError)?;
+ } else if r.peek_bytes(2) == Some(b"<<") {
+ r.forward();
+ r.forward();
+ } else {
+ let _ = string::parse_hex(r).ok_or(Error::SyntaxError)?;
+ }
+ }
+ b'%' => object::skip_whitespace_and_comments(r),
+ _ => {
+ r.forward();
+ }
+ }
+ }
+
+ Ok(())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn parse_array(input: &[u8]) -> Result<&[u8]> {
+ let mut r = Reader::new(input);
+ parse(&mut r)
+ }
+
+ #[test]
+ fn empty() {
+ assert_eq!(parse_array(b"[]").unwrap(), b"");
+ }
+
+ #[test]
+ fn simple() {
+ assert_eq!(parse_array(b"[1 2 3]").unwrap(), b"1 2 3");
+ }
+
+ #[test]
+ fn nested() {
+ assert_eq!(parse_array(b"[1 [2 3] 4]").unwrap(), b"1 [2 3] 4");
+ }
+
+ #[test]
+ fn with_string() {
+ // The ']' inside the string should not close the array.
+ assert_eq!(parse_array(b"[1 (str]) 2]").unwrap(), b"1 (str]) 2");
+ }
+
+ #[test]
+ fn with_hex_string() {
+ assert_eq!(parse_array(b"[<48> /name]").unwrap(), b"<48> /name");
+ }
+
+ #[test]
+ fn with_ascii85_string() {
+ assert_eq!(parse_array(b"[<~87cURDZ~> 1]").unwrap(), b"<~87cURDZ~> 1");
+ }
+
+ #[test]
+ fn with_comment() {
+ assert_eq!(
+ parse_array(b"[1 % comment with ]\n2]").unwrap(),
+ b"1 % comment with ]\n2"
+ );
+ }
+
+ #[test]
+ fn unterminated() {
+ assert_eq!(parse_array(b"[1 2"), Err(Error::SyntaxError));
+ }
+
+ #[test]
+ fn not_an_array() {
+ assert_eq!(parse_array(b"1 2]"), Err(Error::SyntaxError));
+ }
+}
diff --git a/vendor/hayro-postscript/src/error.rs b/vendor/hayro-postscript/src/error.rs
new file mode 100644
index 0000000..3a2627a
--- /dev/null
+++ b/vendor/hayro-postscript/src/error.rs
@@ -0,0 +1,30 @@
+//! Error types for the PostScript scanner.
+
+use core::fmt;
+
+/// A specialized [`Result`] type for PostScript scanner operations.
+pub type Result<T> = core::result::Result<T, Error>;
+
+/// An error encountered while scanning a PostScript token stream.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum Error {
+ /// A syntax error in the input.
+ SyntaxError,
+ /// A numeric value exceeded implementation limits.
+ LimitCheck,
+ /// An unsupported PostScript type was encountered (like dictionaries or
+ /// procedures, which will be added in the future).
+ UnsupportedType,
+}
+
+impl fmt::Display for Error {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ match self {
+ Self::SyntaxError => f.write_str("syntaxerror"),
+ Self::LimitCheck => f.write_str("limitcheck"),
+ Self::UnsupportedType => f.write_str("unsupported type"),
+ }
+ }
+}
+
+impl core::error::Error for Error {}
diff --git a/vendor/hayro-postscript/src/lib.rs b/vendor/hayro-postscript/src/lib.rs
new file mode 100644
index 0000000..e16d555
--- /dev/null
+++ b/vendor/hayro-postscript/src/lib.rs
@@ -0,0 +1,179 @@
+/*!
+A lightweight PostScript scanner.
+
+This crate provides a scanner for tokenizing PostScript programs into typed objects.
+It currently only implements a very small subset of the PostScript language,
+with the main goal of being enough to parse CMAP files, but the scope _might_
+be expanded upon in the future.
+
+The supported types include integers and real numbers, name objects, strings and arrays.
+Unsupported is anything else, including dictionaries, procedures, etc. An error
+will be returned in case any of these is encountered.
+
+## Safety
+This crate forbids unsafe code via a crate-level attribute.
+*/
+
+#![no_std]
+#![forbid(unsafe_code)]
+#![allow(missing_docs)]
+
+extern crate alloc;
+
+mod array;
+mod error;
+mod name;
+mod number;
+mod object;
+mod reader;
+mod string;
+
+pub use array::Array;
+pub use error::{Error, Result};
+pub use name::Name;
+pub use number::Number;
+pub use object::Object;
+pub use string::String;
+
+use reader::Reader;
+
+/// A PostScript scanner that parses [`Object`]s from a byte stream.
+pub struct Scanner<'a> {
+ reader: Reader<'a>,
+}
+
+impl<'a> Scanner<'a> {
+ /// Create a new scanner over the given bytes of a PostScript program.
+ pub fn new(data: &'a [u8]) -> Self {
+ Self {
+ reader: Reader::new(data),
+ }
+ }
+
+ /// Returns `true` if there are no more objects to parse.
+ pub fn at_end(&mut self) -> bool {
+ object::at_end(&mut self.reader)
+ }
+
+ /// Parse the next object.
+ pub fn parse_object(&mut self) -> Result<Object<'a>> {
+ object::read(&mut self.reader)
+ }
+
+ /// Parse the next object as a [`Number`].
+ pub fn parse_number(&mut self) -> Result<Number> {
+ match self.parse_object()? {
+ Object::Number(n) => Ok(n),
+ _ => Err(Error::SyntaxError),
+ }
+ }
+
+ /// Parse the next object as a [`Name`].
+ pub fn parse_name(&mut self) -> Result<Name<'a>> {
+ match self.parse_object()? {
+ Object::Name(n) => Ok(n),
+ _ => Err(Error::SyntaxError),
+ }
+ }
+
+ /// Parse the next object as a [`String`].
+ pub fn parse_string(&mut self) -> Result<String<'a>> {
+ match self.parse_object()? {
+ Object::String(s) => Ok(s),
+ _ => Err(Error::SyntaxError),
+ }
+ }
+
+ /// Parse the next object as an [`Array`].
+ pub fn parse_array(&mut self) -> Result<Array<'a>> {
+ match self.parse_object()? {
+ Object::Array(a) => Ok(a),
+ _ => Err(Error::SyntaxError),
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn cmap_snippet() {
+ let input = br#"/CIDInit /ProcSet findresource begin
+12 dict begin
+begincmap
+/CMapName /Test-H def
+1 begincodespacerange
+<00> <FF>
+endcodespacerange
+2 beginbfchar
+<03> <0041>
+<04> <0042>
+endbfchar
+endcmap"#;
+
+ let mut s = Scanner::new(input);
+
+ assert_eq!(s.parse_name().unwrap(), Name::new(b"CIDInit", true));
+ assert_eq!(s.parse_name().unwrap(), Name::new(b"ProcSet", true));
+ assert_eq!(s.parse_name().unwrap(), Name::new(b"findresource", false));
+ assert_eq!(s.parse_name().unwrap(), Name::new(b"begin", false));
+ assert_eq!(s.parse_number().unwrap(), Number::Integer(12));
+ assert_eq!(s.parse_name().unwrap(), Name::new(b"dict", false));
+ assert_eq!(s.parse_name().unwrap(), Name::new(b"begin", false));
+ assert_eq!(s.parse_name().unwrap(), Name::new(b"begincmap", false));
+ assert_eq!(s.parse_name().unwrap(), Name::new(b"CMapName", true));
+ assert_eq!(s.parse_name().unwrap(), Name::new(b"Test-H", true));
+ assert_eq!(s.parse_name().unwrap(), Name::new(b"def", false));
+ assert_eq!(s.parse_number().unwrap(), Number::Integer(1));
+ assert_eq!(
+ s.parse_name().unwrap(),
+ Name::new(b"begincodespacerange", false)
+ );
+ assert_eq!(s.parse_string().unwrap(), String::from_hex(b"00"));
+ assert_eq!(s.parse_string().unwrap(), String::from_hex(b"FF"));
+ assert_eq!(
+ s.parse_name().unwrap(),
+ Name::new(b"endcodespacerange", false)
+ );
+ assert_eq!(s.parse_number().unwrap(), Number::Integer(2));
+ assert_eq!(s.parse_name().unwrap(), Name::new(b"beginbfchar", false));
+ assert_eq!(s.parse_string().unwrap(), String::from_hex(b"03"));
+ assert_eq!(s.parse_string().unwrap(), String::from_hex(b"0041"));
+ assert_eq!(s.parse_string().unwrap(), String::from_hex(b"04"));
+ assert_eq!(s.parse_string().unwrap(), String::from_hex(b"0042"));
+ assert_eq!(s.parse_name().unwrap(), Name::new(b"endbfchar", false));
+ assert_eq!(s.parse_name().unwrap(), Name::new(b"endcmap", false));
+ assert!(s.at_end());
+ }
+
+ #[test]
+ fn array_round_trip() {
+ let input = b"[123 /abc (xyz)]";
+ let mut scanner = Scanner::new(input);
+ let arr = scanner.parse_array().unwrap();
+ assert!(scanner.at_end());
+
+ let mut inner = arr.objects();
+ assert_eq!(inner.parse_number().unwrap(), Number::Integer(123));
+ assert_eq!(inner.parse_name().unwrap(), Name::new(b"abc", true));
+ assert_eq!(inner.parse_string().unwrap(), String::from_literal(b"xyz"));
+ assert!(inner.at_end());
+ }
+
+ #[test]
+ fn comments_skipped() {
+ let input = b"% comment\n42 % another\n/Name";
+ let mut scanner = Scanner::new(input);
+
+ assert_eq!(scanner.parse_number().unwrap(), Number::Integer(42));
+ assert_eq!(scanner.parse_name().unwrap(), Name::new(b"Name", true));
+ assert!(scanner.at_end());
+ }
+
+ #[test]
+ fn wrong_type_is_error() {
+ let mut scanner = Scanner::new(b"42 ");
+ assert!(scanner.parse_name().is_err());
+ }
+}
diff --git a/vendor/hayro-postscript/src/name.rs b/vendor/hayro-postscript/src/name.rs
new file mode 100644
index 0000000..ab78e7b
--- /dev/null
+++ b/vendor/hayro-postscript/src/name.rs
@@ -0,0 +1,191 @@
+use alloc::vec::Vec;
+
+use crate::error::{Error, Result};
+use crate::reader::{Reader, is_regular};
+use crate::string::ascii_hex::decode_hex_digit;
+
+/// A PostScript name object.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct Name<'a> {
+ data: &'a [u8],
+ literal: bool,
+}
+
+impl<'a> Name<'a> {
+ pub(crate) fn new(data: &'a [u8], literal: bool) -> Self {
+ Self { data, literal }
+ }
+
+ /// Returns `true` if this is a literal name.
+ pub fn is_literal(&self) -> bool {
+ self.literal
+ }
+
+ /// Returns the name as a string if it is valid UTF-8, or
+ /// `None` if it contains non-ASCII bytes.
+ pub fn as_str(&self) -> Option<&'a str> {
+ core::str::from_utf8(self.data).ok()
+ }
+
+ /// Decode the name into `out`, replacing any previous contents.
+ pub fn decode_into(&self, out: &mut Vec<u8>) -> Result<()> {
+ out.clear();
+
+ // Fast path: no escape sequences.
+ if !self.data.contains(&b'#') {
+ out.extend_from_slice(self.data);
+ return Ok(());
+ }
+
+ // Slow path: Process escape sequences.
+ let mut inner = Reader::new(self.data);
+
+ while let Some(b) = inner.read_byte() {
+ if b == b'#' {
+ let hex = inner.read_bytes(2).ok_or(Error::SyntaxError)?;
+ let hi = decode_hex_digit(hex[0]).ok_or(Error::SyntaxError)?;
+ let lo = decode_hex_digit(hex[1]).ok_or(Error::SyntaxError)?;
+ out.push(hi << 4 | lo);
+ } else {
+ out.push(b);
+ }
+ }
+
+ Ok(())
+ }
+
+ /// Decode the name.
+ pub fn decode(&self) -> Result<Vec<u8>> {
+ let mut out = Vec::new();
+ self.decode_into(&mut out)?;
+ Ok(out)
+ }
+}
+
+pub(crate) fn parse_literal<'a>(r: &mut Reader<'a>) -> Option<&'a [u8]> {
+ r.forward_tag(b"/")?;
+ let start = r.offset();
+ while r.eat(is_regular).is_some() {}
+ r.range(start..r.offset())
+}
+
+pub(crate) fn parse_executable<'a>(r: &mut Reader<'a>) -> Option<&'a [u8]> {
+ let start = r.offset();
+ r.forward_while(is_regular);
+ if r.offset() == start {
+ return None;
+ }
+ r.range(start..r.offset())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn read_literal(input: &[u8]) -> Option<Name<'_>> {
+ let mut r = Reader::new(input);
+ parse_literal(&mut r).map(|d| Name::new(d, true))
+ }
+
+ fn read_executable(input: &[u8]) -> Option<Name<'_>> {
+ let mut r = Reader::new(input);
+ parse_executable(&mut r).map(|d| Name::new(d, false))
+ }
+
+ #[test]
+ fn literal_simple() {
+ let n = read_literal(b"/Name1").unwrap();
+ assert_eq!(n.as_str().unwrap(), "Name1");
+ assert!(n.is_literal());
+ }
+
+ #[test]
+ fn literal_empty_name() {
+ let n = read_literal(b"/").unwrap();
+ assert_eq!(n.as_str().unwrap(), "");
+ assert!(n.is_literal());
+ }
+
+ #[test]
+ fn literal_with_hex_escape() {
+ let n = read_literal(b"/lime#20Green").unwrap();
+ assert_eq!(n.as_str().unwrap(), "lime#20Green");
+ assert_eq!(n.decode().unwrap(), b"lime Green");
+ }
+
+ #[test]
+ fn literal_multiple_hex_escapes() {
+ let n = read_literal(b"/paired#28#29parentheses").unwrap();
+ assert_eq!(n.decode().unwrap(), b"paired()parentheses");
+ }
+
+ #[test]
+ fn literal_special_chars() {
+ let n = read_literal(b"/A;Name_With-Various***Characters?").unwrap();
+ assert_eq!(n.as_str().unwrap(), "A;Name_With-Various***Characters?");
+ }
+
+ #[test]
+ fn literal_stops_at_delimiter() {
+ let mut r = Reader::new(b"/Name(rest");
+ let data = parse_literal(&mut r).unwrap();
+ assert_eq!(data, b"Name");
+ assert_eq!(r.peek_byte(), Some(b'('));
+ }
+
+ #[test]
+ fn literal_stops_at_whitespace() {
+ let mut r = Reader::new(b"/Name rest");
+ let data = parse_literal(&mut r).unwrap();
+ assert_eq!(data, b"Name");
+ assert_eq!(r.peek_byte(), Some(b' '));
+ }
+
+ #[test]
+ fn literal_not_a_name() {
+ assert!(read_literal(b"Name").is_none());
+ }
+
+ #[test]
+ fn executable_simple() {
+ let n = read_executable(b"beginbfchar ").unwrap();
+ assert_eq!(n.as_str().unwrap(), "beginbfchar");
+ assert!(!n.is_literal());
+ }
+
+ #[test]
+ fn executable_stops_at_delimiter() {
+ let mut r = Reader::new(b"def/name");
+ let data = parse_executable(&mut r).unwrap();
+ assert_eq!(data, b"def");
+ assert_eq!(r.peek_byte(), Some(b'/'));
+ }
+
+ #[test]
+ fn executable_at_eof() {
+ let n = read_executable(b"endcmap").unwrap();
+ assert_eq!(n.as_str().unwrap(), "endcmap");
+ }
+
+ #[test]
+ fn executable_empty() {
+ assert!(read_executable(b"").is_none());
+ }
+
+ #[test]
+ fn executable_starts_at_delimiter() {
+ assert!(read_executable(b"(foo)").is_none());
+ }
+
+ #[test]
+ fn decode_no_escapes() {
+ let n = Name::new(b"simple", true);
+ assert_eq!(n.decode().unwrap(), b"simple");
+ }
+
+ #[test]
+ fn decode_with_escapes() {
+ let n = Name::new(b"lime#20Green", true);
+ assert_eq!(n.decode().unwrap(), b"lime Green");
+ }
+}
diff --git a/vendor/hayro-postscript/src/number.rs b/vendor/hayro-postscript/src/number.rs
new file mode 100644
index 0000000..5c6d3ba
--- /dev/null
+++ b/vendor/hayro-postscript/src/number.rs
@@ -0,0 +1,177 @@
+use crate::error::{Error, Result};
+use crate::reader::{Reader, is_delimiter, is_whitespace};
+
+/// A PostScript number object (integer or real).
+#[derive(Debug, Clone, Copy, PartialEq)]
+pub enum Number {
+ Integer(i32),
+ Real(f32),
+}
+
+impl Number {
+ /// Return the value as an `i32`. Reals are truncated.
+ pub fn as_i32(self) -> i32 {
+ match self {
+ Self::Integer(v) => v,
+ Self::Real(v) => v as i32,
+ }
+ }
+
+ /// Return the value as an `f32`.
+ pub fn as_f32(self) -> f32 {
+ match self {
+ Self::Integer(v) => v as f32,
+ Self::Real(v) => v,
+ }
+ }
+
+ /// Return the value as an `f64`.
+ pub fn as_f64(self) -> f64 {
+ match self {
+ Self::Integer(v) => v as f64,
+ Self::Real(v) => v as f64,
+ }
+ }
+}
+
+fn is_terminated(r: &Reader<'_>) -> bool {
+ match r.peek_byte() {
+ None => true,
+ Some(b) => is_whitespace(b) || is_delimiter(b),
+ }
+}
+
+pub(crate) fn read(r: &mut Reader<'_>) -> Result<Number> {
+ let saved = r.offset();
+
+ // Optional sign.
+ let first = r.peek_byte().ok_or(Error::SyntaxError)?;
+ let has_sign = first == b'+' || first == b'-';
+
+ if has_sign {
+ r.forward();
+ }
+
+ // Consume leading digits.
+ let digit_start = r.offset();
+ r.forward_while(|b| b.is_ascii_digit());
+ let has_digits = r.offset() > digit_start;
+
+ // Check if number is a radix number.
+ if !has_sign && has_digits && r.peek_byte() == Some(b'#') {
+ let base_bytes = r.range(digit_start..r.offset()).ok_or(Error::SyntaxError)?;
+ let base_str = core::str::from_utf8(base_bytes).map_err(|_| Error::SyntaxError)?;
+ let base = base_str.parse::<u32>().map_err(|_| Error::SyntaxError)?;
+
+ if !(2..=36).contains(&base) {
+ return Err(Error::SyntaxError);
+ }
+
+ // Skip `#`.
+ r.forward();
+
+ let num_start = r.offset();
+ r.forward_while(|b| b.is_ascii_alphanumeric());
+
+ if r.offset() == num_start || !is_terminated(r) {
+ return Err(Error::SyntaxError);
+ }
+
+ let num_bytes = r.range(num_start..r.offset()).ok_or(Error::SyntaxError)?;
+ let num_str = core::str::from_utf8(num_bytes).map_err(|_| Error::SyntaxError)?;
+ let value = i32::from_str_radix(num_str, base).map_err(|_| Error::SyntaxError)?;
+
+ return Ok(Number::Integer(value));
+ }
+
+ // Check for real number indicators: `.` or `e`/`E`.
+ let has_dot = r.peek_byte() == Some(b'.');
+
+ if has_dot {
+ r.forward(); // skip '.'
+ r.forward_while(|b| b.is_ascii_digit());
+ }
+
+ // At this point we need at least some digits (before or after the dot).
+ if !has_digits && !has_dot {
+ return Err(Error::SyntaxError);
+ }
+
+ let has_exponent = matches!(r.peek_byte(), Some(b'e' | b'E'));
+ if has_exponent {
+ r.forward();
+
+ // Optional exponent sign.
+ if matches!(r.peek_byte(), Some(b'+' | b'-')) {
+ r.forward();
+ }
+
+ r.forward_while(|b| b.is_ascii_digit());
+ }
+
+ if !is_terminated(r) {
+ return Err(Error::SyntaxError);
+ }
+
+ let token = r.range(saved..r.offset()).ok_or(Error::SyntaxError)?;
+ let str = core::str::from_utf8(token).map_err(|_| Error::SyntaxError)?;
+
+ if has_dot || has_exponent {
+ let value = str.parse::<f32>().map_err(|_| Error::SyntaxError)?;
+
+ Ok(Number::Real(value))
+ } else {
+ if !has_digits {
+ return Err(Error::SyntaxError);
+ }
+
+ let value = str.parse::<i32>().map_err(|_| Error::SyntaxError)?;
+
+ Ok(Number::Integer(value))
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn read_num(input: &[u8]) -> Result<Number> {
+ let mut r = Reader::new(input);
+ read(&mut r)
+ }
+
+ #[test]
+ fn signed_integers() {
+ assert_eq!(read_num(b"123 ").unwrap(), Number::Integer(123));
+ assert_eq!(read_num(b"-98 ").unwrap(), Number::Integer(-98));
+ assert_eq!(read_num(b"43445 ").unwrap(), Number::Integer(43445));
+ assert_eq!(read_num(b"0 ").unwrap(), Number::Integer(0));
+ assert_eq!(read_num(b"+17 ").unwrap(), Number::Integer(17));
+ }
+
+ #[test]
+ fn real_numbers() {
+ assert_eq!(read_num(b"-.002 ").unwrap(), Number::Real(-0.002));
+ assert_eq!(read_num(b"34.5 ").unwrap(), Number::Real(34.5));
+ assert_eq!(read_num(b"-3.62 ").unwrap(), Number::Real(-3.62));
+ assert_eq!(read_num(b"123.6e10 ").unwrap(), Number::Real(123.6e10));
+ assert_eq!(read_num(b"1.0E-5 ").unwrap(), Number::Real(1.0E-5));
+ assert_eq!(read_num(b"1E6 ").unwrap(), Number::Real(1E6));
+ assert_eq!(read_num(b"-1. ").unwrap(), Number::Real(-1.0));
+ assert_eq!(read_num(b"0.0 ").unwrap(), Number::Real(0.0));
+ }
+
+ #[test]
+ fn radix_numbers() {
+ assert_eq!(read_num(b"8#1777 ").unwrap(), Number::Integer(0o1777));
+ assert_eq!(read_num(b"16#FFFE ").unwrap(), Number::Integer(0xFFFE));
+ assert_eq!(read_num(b"2#1000 ").unwrap(), Number::Integer(0b1000));
+ }
+
+ #[test]
+ fn invalid() {
+ assert!(read_num(b"abc").is_err());
+ assert!(read_num(b"+abc").is_err());
+ assert!(read_num(b"1a").is_err());
+ }
+}
diff --git a/vendor/hayro-postscript/src/object.rs b/vendor/hayro-postscript/src/object.rs
new file mode 100644
index 0000000..7c20075
--- /dev/null
+++ b/vendor/hayro-postscript/src/object.rs
@@ -0,0 +1,226 @@
+use crate::array::{self, Array};
+use crate::error::{Error, Result};
+use crate::name::{self, Name};
+use crate::number::{self, Number};
+use crate::reader::Reader;
+use crate::string::{self, String};
+
+/// A PostScript object.
+#[derive(Debug, Clone, PartialEq)]
+pub enum Object<'a> {
+ /// A number object.
+ Number(Number),
+ /// A name object.
+ Name(Name<'a>),
+ /// A string object.
+ String(String<'a>),
+ /// An array object.
+ Array(Array<'a>),
+}
+
+pub(crate) fn read<'a>(r: &mut Reader<'a>) -> Result<Object<'a>> {
+ // PdfCraft patch: `<<` and `>>` are skipped by looping instead of
+ // recursing once per delimiter, so a long run cannot overflow the stack.
+ loop {
+ skip_whitespace_and_comments(r);
+
+ let b = r.peek_byte().ok_or(Error::SyntaxError)?;
+
+ return match b {
+ b'(' => string::parse_literal(r)
+ .map(|s| Object::String(String::from_literal(s)))
+ .ok_or(Error::SyntaxError),
+ b'<' => {
+ if r.peek_bytes(2) == Some(b"<~") {
+ string::parse_ascii85(r)
+ .map(|s| Object::String(String::from_ascii85(s)))
+ .ok_or(Error::SyntaxError)
+ } else if r.peek_bytes(2) == Some(b"<<") {
+ // TODO: Proper dict support. For now, skip `<<` and return
+ // the next object so callers see the inner tokens.
+ r.forward();
+ r.forward();
+ continue;
+ } else {
+ string::parse_hex(r)
+ .map(|s| Object::String(String::from_hex(s)))
+ .ok_or(Error::SyntaxError)
+ }
+ }
+ b'/' => name::parse_literal(r)
+ .map(|s| Object::Name(Name::new(s, true)))
+ .ok_or(Error::SyntaxError),
+ b'[' => array::parse(r).map(|d| Object::Array(Array::new(d))),
+ b'>' => {
+ if r.peek_bytes(2) == Some(b">>") {
+ // TODO: Proper dict support. Skip `>>` closing delimiter.
+ r.forward();
+ r.forward();
+ continue;
+ } else {
+ Err(Error::SyntaxError)
+ }
+ }
+ b'{' => {
+ r.forward();
+ Err(Error::UnsupportedType)
+ }
+ b'.' | b'+' | b'-' | b'0'..=b'9' => number::read(r).map(Object::Number),
+ _ => name::parse_executable(r)
+ .map(|s| Object::Name(Name::new(s, false)))
+ .ok_or(Error::SyntaxError),
+ };
+ }
+}
+
+pub(crate) fn at_end(r: &mut Reader<'_>) -> bool {
+ skip_whitespace_and_comments(r);
+ r.peek_byte().is_none()
+}
+
+pub(crate) fn skip_whitespace_and_comments(r: &mut Reader<'_>) {
+ loop {
+ match r.peek_byte() {
+ Some(b) if crate::reader::is_whitespace(b) => {
+ r.forward();
+ }
+ Some(b'%') => {
+ r.forward();
+ r.forward_while(|b| !crate::reader::is_eol(b));
+ }
+ _ => return,
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn read_one(input: &[u8]) -> Result<Object<'_>> {
+ let mut r = Reader::new(input);
+ read(&mut r)
+ }
+
+ fn read_ok(input: &[u8]) -> Object<'_> {
+ read_one(input).unwrap()
+ }
+
+ fn read_err(input: &[u8]) -> Error {
+ read_one(input).unwrap_err()
+ }
+
+ #[test]
+ fn integer() {
+ assert_eq!(read_ok(b"42 "), Object::Number(Number::Integer(42)));
+ }
+
+ #[test]
+ fn negative_integer() {
+ assert_eq!(read_ok(b"-7 "), Object::Number(Number::Integer(-7)));
+ }
+
+ #[test]
+ fn literal_name() {
+ assert_eq!(
+ read_ok(b"/CMapName "),
+ Object::Name(Name::new(b"CMapName", true))
+ );
+ }
+
+ #[test]
+ fn executable_name() {
+ let obj = read_ok(b"beginbfchar ");
+ assert_eq!(obj, Object::Name(Name::new(b"beginbfchar", false)));
+ }
+
+ #[test]
+ fn literal_string() {
+ assert_eq!(
+ read_ok(b"(Hello)"),
+ Object::String(String::from_literal(b"Hello"))
+ );
+ }
+
+ #[test]
+ fn hex_string() {
+ assert_eq!(
+ read_ok(b"<48656C6C6F>"),
+ Object::String(String::from_hex(b"48656C6C6F"))
+ );
+ }
+
+ #[test]
+ fn ascii85_string() {
+ assert_eq!(
+ read_ok(b"<~87cURDZ~>"),
+ Object::String(String::from_ascii85(b"87cURDZ"))
+ );
+ }
+
+ #[test]
+ fn array_simple() {
+ let obj = read_ok(b"[1 2 3]");
+ assert_eq!(obj, Object::Array(Array::new(b"1 2 3")));
+ }
+
+ #[test]
+ fn stray_close_bracket() {
+ assert_eq!(read_err(b"]"), Error::SyntaxError);
+ }
+
+ #[test]
+ fn stray_gt() {
+ assert_eq!(read_err(b">x"), Error::SyntaxError);
+ }
+
+ #[test]
+ fn skips_whitespace() {
+ assert_eq!(read_ok(b" \t\n 42 "), Object::Number(Number::Integer(42)));
+ }
+
+ #[test]
+ fn skips_comments() {
+ assert_eq!(
+ read_ok(b"% this is a comment\n42 "),
+ Object::Number(Number::Integer(42))
+ );
+ }
+
+ #[test]
+ fn eof() {
+ assert!(read_one(b"").is_err());
+ assert!(read_one(b" ").is_err());
+ assert!(read_one(b"% comment only\n").is_err());
+ }
+
+ // PdfCraft patch: `<<` and `>>` runs are skipped without recursion.
+ #[test]
+ fn long_open_dict_run_does_not_overflow() {
+ let input = alloc::vec![b'<'; 1_000_000];
+ assert_eq!(read_err(&input), Error::SyntaxError);
+ }
+
+ #[test]
+ fn long_close_dict_run_does_not_overflow() {
+ let input = b">>".repeat(500_000);
+ assert_eq!(read_err(&input), Error::SyntaxError);
+ }
+
+ #[test]
+ fn dict_delimiters_are_skipped() {
+ let mut r = Reader::new(b"<< /A 1 >>");
+ assert_eq!(read(&mut r), Ok(Object::Name(Name::new(b"A", true))));
+ assert_eq!(read(&mut r), Ok(Object::Number(Number::Integer(1))));
+ assert_eq!(read(&mut r), Err(Error::SyntaxError));
+ }
+
+ #[test]
+ fn nested_dict_delimiters_are_skipped() {
+ let mut r = Reader::new(b"<<<< /X >>>> 7 <<\n% c\n<< >> 8");
+ assert_eq!(read(&mut r), Ok(Object::Name(Name::new(b"X", true))));
+ assert_eq!(read(&mut r), Ok(Object::Number(Number::Integer(7))));
+ assert_eq!(read(&mut r), Ok(Object::Number(Number::Integer(8))));
+ assert!(at_end(&mut r));
+ }
+}
diff --git a/vendor/hayro-postscript/src/reader.rs b/vendor/hayro-postscript/src/reader.rs
new file mode 100644
index 0000000..f8a4967
--- /dev/null
+++ b/vendor/hayro-postscript/src/reader.rs
@@ -0,0 +1,136 @@
+use core::ops::Range;
+
+#[derive(Clone, Debug)]
+pub(crate) struct Reader<'a> {
+ pub(crate) data: &'a [u8],
+ pub(crate) offset: usize,
+}
+
+impl<'a> Reader<'a> {
+ #[inline]
+ pub(crate) fn new(data: &'a [u8]) -> Self {
+ Self { data, offset: 0 }
+ }
+
+ #[inline]
+ pub(crate) fn jump(&mut self, offset: usize) {
+ self.offset = offset;
+ }
+
+ #[inline]
+ pub(crate) fn range(&self, range: Range<usize>) -> Option<&'a [u8]> {
+ self.data.get(range)
+ }
+
+ #[inline]
+ pub(crate) fn offset(&self) -> usize {
+ self.offset
+ }
+
+ #[inline]
+ pub(crate) fn read_bytes(&mut self, len: usize) -> Option<&'a [u8]> {
+ let v = self.peek_bytes(len)?;
+ self.offset += len;
+ Some(v)
+ }
+
+ #[inline]
+ pub(crate) fn read_byte(&mut self) -> Option<u8> {
+ let v = self.peek_byte()?;
+ self.offset += 1;
+ Some(v)
+ }
+
+ #[inline]
+ pub(crate) fn peek_bytes(&self, len: usize) -> Option<&'a [u8]> {
+ self.data.get(self.offset..self.offset + len)
+ }
+
+ #[inline]
+ pub(crate) fn peek_byte(&self) -> Option<u8> {
+ self.data.get(self.offset).copied()
+ }
+
+ #[inline]
+ pub(crate) fn eat(&mut self, f: impl Fn(u8) -> bool) -> Option<u8> {
+ let val = self.peek_byte()?;
+ if f(val) {
+ self.forward();
+ Some(val)
+ } else {
+ None
+ }
+ }
+
+ #[inline]
+ pub(crate) fn forward(&mut self) {
+ self.offset += 1;
+ }
+
+ #[inline]
+ pub(crate) fn forward_while(&mut self, f: impl Fn(u8) -> bool) {
+ while let Some(b) = self.peek_byte() {
+ if f(b) {
+ self.forward();
+ } else {
+ break;
+ }
+ }
+ }
+
+ #[inline]
+ pub(crate) fn forward_tag(&mut self, tag: &[u8]) -> Option<()> {
+ self.peek_tag(tag)?;
+ self.offset += tag.len();
+ Some(())
+ }
+
+ #[inline]
+ pub(crate) fn peek_tag(&self, tag: &[u8]) -> Option<()> {
+ let mut cloned = self.clone();
+
+ for b in tag.iter().copied() {
+ if cloned.peek_byte() == Some(b) {
+ cloned.forward();
+ } else {
+ return None;
+ }
+ }
+
+ Some(())
+ }
+
+ #[inline]
+ pub(crate) fn skip_eol(&mut self) {
+ while let Some(b) = self.peek_byte() {
+ if is_eol(b) {
+ self.forward();
+ } else {
+ return;
+ }
+ }
+ }
+}
+
+#[inline(always)]
+pub(crate) fn is_whitespace(b: u8) -> bool {
+ matches!(b, 0x00 | 0x09 | 0x0a | 0x0c | 0x0d | 0x20)
+}
+
+#[inline(always)]
+pub(crate) fn is_delimiter(b: u8) -> bool {
+ matches!(
+ b,
+ b'(' | b')' | b'<' | b'>' | b'[' | b']' | b'{' | b'}' | b'/' | b'%'
+ )
+}
+
+#[inline(always)]
+pub(crate) fn is_regular(b: u8) -> bool {
+ !is_whitespace(b) && !is_delimiter(b)
+}
+
+#[inline(always)]
+pub(crate) fn is_eol(b: u8) -> bool {
+ matches!(b, 0x0a | 0x0d)
+}
diff --git a/vendor/hayro-postscript/src/string.rs b/vendor/hayro-postscript/src/string.rs
new file mode 100644
index 0000000..ed39d57
--- /dev/null
+++ b/vendor/hayro-postscript/src/string.rs
@@ -0,0 +1,288 @@
+mod ascii_85;
+pub(crate) mod ascii_hex;
+mod literal;
+
+use alloc::vec::Vec;
+
+use crate::error::{Error, Result};
+use crate::reader::Reader;
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum StringInner<'a> {
+ Literal(&'a [u8]),
+ Hex(&'a [u8]),
+ Ascii85(&'a [u8]),
+}
+
+/// A PostScript string object.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct String<'a> {
+ inner: StringInner<'a>,
+}
+
+impl<'a> String<'a> {
+ pub(crate) const fn from_literal(data: &'a [u8]) -> Self {
+ Self {
+ inner: StringInner::Literal(data),
+ }
+ }
+
+ pub(crate) const fn from_hex(data: &'a [u8]) -> Self {
+ Self {
+ inner: StringInner::Hex(data),
+ }
+ }
+
+ pub(crate) const fn from_ascii85(data: &'a [u8]) -> Self {
+ Self {
+ inner: StringInner::Ascii85(data),
+ }
+ }
+
+ /// Decode the string content into `out`, replacing any previous contents.
+ pub fn decode_into(&self, out: &mut Vec<u8>) -> Result<()> {
+ out.clear();
+ match self.inner {
+ StringInner::Literal(data) => literal::decode_into(data, out),
+ StringInner::Hex(data) => ascii_hex::decode_into(data, out),
+ StringInner::Ascii85(data) => ascii_85::decode_into(data, out),
+ }
+ .ok_or(Error::SyntaxError)
+ }
+
+ /// Decode the string content.
+ pub fn decode(&self) -> Result<Vec<u8>> {
+ let mut out = Vec::new();
+ self.decode_into(&mut out)?;
+ Ok(out)
+ }
+}
+
+pub(crate) fn parse_literal<'a>(r: &mut Reader<'a>) -> Option<&'a [u8]> {
+ let start = r.offset();
+ skip_literal(r)?;
+ let end = r.offset();
+ // Exclude outer parentheses.
+ r.range(start + 1..end - 1)
+}
+
+pub(crate) fn parse_hex<'a>(r: &mut Reader<'a>) -> Option<&'a [u8]> {
+ r.forward_tag(b"<")?;
+ let start = r.offset();
+ while let Some(b) = r.read_byte() {
+ if b == b'>' {
+ return r.range(start..r.offset() - 1);
+ }
+ }
+ None
+}
+
+pub(crate) fn parse_ascii85<'a>(r: &mut Reader<'a>) -> Option<&'a [u8]> {
+ r.forward_tag(b"<~")?;
+ let start = r.offset();
+ loop {
+ let b = r.read_byte()?;
+ if b == b'~' {
+ let end = r.offset() - 1;
+ r.forward_tag(b">")?;
+ return r.range(start..end);
+ }
+ }
+}
+
+fn skip_literal(r: &mut Reader<'_>) -> Option<()> {
+ r.forward_tag(b"(")?;
+ let mut depth = 1_u32;
+
+ while depth > 0 {
+ let byte = r.read_byte()?;
+ match byte {
+ b'\\' => {
+ let _ = r.read_byte()?;
+ }
+ b'(' => depth += 1,
+ b')' => depth -= 1,
+ _ => {}
+ }
+ }
+
+ Some(())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn decode_literal(input: &[u8]) -> Result<Vec<u8>> {
+ let mut r = Reader::new(input);
+ let data = parse_literal(&mut r).ok_or(Error::SyntaxError)?;
+ String::from_literal(data).decode()
+ }
+
+ #[test]
+ fn literal_empty() {
+ assert_eq!(decode_literal(b"()").unwrap(), b"");
+ }
+
+ #[test]
+ fn literal_simple() {
+ assert_eq!(decode_literal(b"(Hello)").unwrap(), b"Hello");
+ }
+
+ #[test]
+ fn literal_nested_parens() {
+ assert_eq!(
+ decode_literal(b"(Hi (()) there)").unwrap(),
+ b"Hi (()) there"
+ );
+ }
+
+ #[test]
+ fn literal_escape_n() {
+ assert_eq!(decode_literal(b"(a\\nb)").unwrap(), b"a\nb");
+ }
+
+ #[test]
+ fn literal_escape_r() {
+ assert_eq!(decode_literal(b"(a\\rb)").unwrap(), b"a\rb");
+ }
+
+ #[test]
+ fn literal_escape_t() {
+ assert_eq!(decode_literal(b"(a\\tb)").unwrap(), b"a\tb");
+ }
+
+ #[test]
+ fn literal_escape_b() {
+ assert_eq!(decode_literal(b"(a\\bb)").unwrap(), &[b'a', 0x08, b'b']);
+ }
+
+ #[test]
+ fn literal_escape_f() {
+ assert_eq!(decode_literal(b"(a\\fb)").unwrap(), &[b'a', 0x0C, b'b']);
+ }
+
+ #[test]
+ fn literal_escape_backslash() {
+ assert_eq!(decode_literal(b"(a\\\\b)").unwrap(), b"a\\b");
+ }
+
+ #[test]
+ fn literal_escape_parens() {
+ assert_eq!(decode_literal(b"(Hi \\()").unwrap(), b"Hi (");
+ }
+
+ #[test]
+ fn literal_octal_three_digits() {
+ assert_eq!(decode_literal(b"(\\053)").unwrap(), b"+");
+ }
+
+ #[test]
+ fn literal_octal_two_digits() {
+ assert_eq!(decode_literal(b"(\\36)").unwrap(), b"\x1e");
+ }
+
+ #[test]
+ fn literal_octal_one_digit() {
+ assert_eq!(decode_literal(b"(\\3)").unwrap(), b"\x03");
+ }
+
+ #[test]
+ fn literal_line_continuation_lf() {
+ assert_eq!(decode_literal(b"(Hi \\\nthere)").unwrap(), b"Hi there");
+ }
+
+ #[test]
+ fn literal_line_continuation_cr() {
+ assert_eq!(decode_literal(b"(Hi \\\rthere)").unwrap(), b"Hi there");
+ }
+
+ #[test]
+ fn literal_line_continuation_crlf() {
+ assert_eq!(decode_literal(b"(Hi \\\r\nthere)").unwrap(), b"Hi there");
+ }
+
+ #[test]
+ fn literal_bare_eol_lf() {
+ assert_eq!(decode_literal(b"(a\nb)").unwrap(), b"a\nb");
+ }
+
+ #[test]
+ fn literal_bare_eol_cr() {
+ assert_eq!(decode_literal(b"(a\rb)").unwrap(), b"a\nb");
+ }
+
+ #[test]
+ fn literal_bare_eol_crlf() {
+ assert_eq!(decode_literal(b"(a\r\nb)").unwrap(), b"a\nb");
+ }
+
+ fn decode_hex(input: &[u8]) -> Result<Vec<u8>> {
+ let mut r = Reader::new(input);
+ let data = parse_hex(&mut r).ok_or(Error::SyntaxError)?;
+ String::from_hex(data).decode()
+ }
+
+ #[test]
+ fn hex_simple() {
+ assert_eq!(decode_hex(b"<48656C6C6F>").unwrap(), b"Hello");
+ }
+
+ #[test]
+ fn hex_with_whitespace() {
+ assert_eq!(decode_hex(b"<48 65 6C 6C 6F>").unwrap(), b"Hello");
+ }
+
+ #[test]
+ fn hex_odd_nibble() {
+ assert_eq!(decode_hex(b"<ABC>").unwrap(), &[0xAB, 0xC0]);
+ }
+
+ #[test]
+ fn hex_empty() {
+ assert_eq!(decode_hex(b"<>").unwrap(), b"");
+ }
+
+ #[test]
+ fn hex_lowercase() {
+ assert_eq!(decode_hex(b"<abcd>").unwrap(), &[0xAB, 0xCD]);
+ }
+
+ #[test]
+ fn hex_mixed_case() {
+ assert_eq!(decode_hex(b"<aB3E>").unwrap(), &[0xAB, 0x3E]);
+ }
+
+ fn decode_a85(input: &[u8]) -> Result<Vec<u8>> {
+ let mut r = Reader::new(input);
+ let data = parse_ascii85(&mut r).ok_or(Error::SyntaxError)?;
+ String::from_ascii85(data).decode()
+ }
+
+ #[test]
+ fn ascii85_simple() {
+ // "Hello" in ASCII85 is "87cURDZ"
+ assert_eq!(decode_a85(b"<~87cURDZ~>").unwrap(), b"Hello");
+ }
+
+ #[test]
+ fn ascii85_empty() {
+ assert_eq!(decode_a85(b"<~~>").unwrap(), b"");
+ }
+
+ #[test]
+ fn ascii85_z_shorthand() {
+ assert_eq!(decode_a85(b"<~z~>").unwrap(), &[0, 0, 0, 0]);
+ }
+
+ #[test]
+ fn ascii85_partial_group() {
+ let result = decode_a85(b"<~87~>").unwrap();
+ assert_eq!(result.len(), 1);
+ }
+
+ #[test]
+ fn ascii85_with_whitespace() {
+ assert_eq!(decode_a85(b"<~87cU RDZ~>").unwrap(), b"Hello");
+ }
+}
diff --git a/vendor/hayro-postscript/src/string/ascii_85.rs b/vendor/hayro-postscript/src/string/ascii_85.rs
new file mode 100644
index 0000000..93f7f50
--- /dev/null
+++ b/vendor/hayro-postscript/src/string/ascii_85.rs
@@ -0,0 +1,90 @@
+// Keep in sync with `hayro-syntax/src/filter/ascii_85.rs`.
+
+use crate::reader::{Reader, is_whitespace};
+use alloc::vec::Vec;
+
+pub(crate) fn decode_into(data: &[u8], out: &mut Vec<u8>) -> Option<()> {
+ const POW_85: [u32; 5] = [52200625, 614125, 7225, 85, 1];
+
+ let mut reader = Reader::new(data);
+
+ let mut read_byte = || -> Option<u8> {
+ loop {
+ let b = reader.read_byte()?;
+
+ // White space characters should be ignored.
+ if !is_whitespace(b) {
+ return Some(b);
+ }
+ }
+ };
+
+ let flush_group = |group: &mut Vec<u8>, decoded: &mut Vec<u8>| -> Option<()> {
+ let (digits, output_len): ([u32; 5], usize) = match group.len() {
+ 0 => return Some(()),
+ 1 => return None, // A single character is not valid.
+ 2 => (
+ [group[0], group[1], b'u', b'u', b'u'].map(|b| (b - b'!') as u32),
+ 1,
+ ),
+ 3 => (
+ [group[0], group[1], group[2], b'u', b'u'].map(|b| (b - b'!') as u32),
+ 2,
+ ),
+ 4 => (
+ [group[0], group[1], group[2], group[3], b'u'].map(|b| (b - b'!') as u32),
+ 3,
+ ),
+ 5 => (
+ [group[0], group[1], group[2], group[3], group[4]].map(|b| (b - b'!') as u32),
+ 4,
+ ),
+ _ => unreachable!(),
+ };
+
+ let value = digits[0]
+ .checked_mul(POW_85[0])?
+ .checked_add(digits[1].checked_mul(POW_85[1])?)?
+ .checked_add(digits[2].checked_mul(POW_85[2])?)?
+ .checked_add(digits[3].checked_mul(POW_85[3])?)?
+ .checked_add(digits[4])?;
+
+ decoded.extend_from_slice(&value.to_be_bytes()[..output_len]);
+ group.clear();
+ Some(())
+ };
+
+ out.reserve(data.len() * 4 / 5);
+ let mut group = Vec::with_capacity(5);
+
+ loop {
+ let Some(b) = read_byte() else {
+ // Be lenient and accept what we have (see PDFBOX-5910).
+ flush_group(&mut group, out)?;
+
+ return Some(());
+ };
+
+ match b {
+ b'!'..=b'u' => {
+ group.push(b);
+
+ if group.len() == 5 {
+ flush_group(&mut group, out)?;
+ }
+ }
+ b'z' => {
+ flush_group(&mut group, out)?;
+ out.extend_from_slice(&[0, 0, 0, 0]);
+ }
+ b'~' => {
+ // Technically requires a '>', but there is a PDF where it isn't
+ // appended and decodes fine in other viewers.
+ flush_group(&mut group, out)?;
+
+ return Some(());
+ }
+ _ => return None, // Invalid character.
+ }
+ }
+}
diff --git a/vendor/hayro-postscript/src/string/ascii_hex.rs b/vendor/hayro-postscript/src/string/ascii_hex.rs
new file mode 100644
index 0000000..bdf7438
--- /dev/null
+++ b/vendor/hayro-postscript/src/string/ascii_hex.rs
@@ -0,0 +1,59 @@
+// Keep in sync with `hayro-syntax/src/filter/ascii_hex.rs`.
+
+use crate::reader::is_whitespace;
+use alloc::vec::Vec;
+
+pub(crate) fn decode_into(data: &[u8], out: &mut Vec<u8>) -> Option<()> {
+ let has_whitespace = data.iter().any(|&b| is_whitespace(b));
+
+ out.reserve(data.len().div_ceil(2));
+
+ if !has_whitespace {
+ // Fast path, don't need to worry about white spaces.
+ let mut i = 0;
+ while i + 1 < data.len() {
+ out.push(decode_hex_digit(data[i])? << 4 | decode_hex_digit(data[i + 1])?);
+ i += 2;
+ }
+ if i < data.len() {
+ out.push(decode_hex_digit(data[i])? << 4);
+ }
+ } else {
+ // Slow path, need to strip white spaces.
+ let mut iter = data.iter().copied();
+ let mut read_byte = || -> Option<u8> {
+ loop {
+ let b = iter.next()?;
+ if !is_whitespace(b) {
+ return Some(b);
+ }
+ }
+ };
+
+ loop {
+ match (read_byte(), read_byte()) {
+ (Some(hi), Some(lo)) => {
+ out.push(decode_hex_digit(hi)? << 4 | decode_hex_digit(lo)?);
+ }
+ (Some(hi), None) => {
+ out.push(decode_hex_digit(hi)? << 4);
+
+ break;
+ }
+ (None, _) => break,
+ }
+ }
+ }
+
+ Some(())
+}
+
+#[inline(always)]
+pub(crate) fn decode_hex_digit(c: u8) -> Option<u8> {
+ match c {
+ b'0'..=b'9' => Some(c - b'0'),
+ b'A'..=b'F' => Some(c - b'A' + 10),
+ b'a'..=b'f' => Some(c - b'a' + 10),
+ _ => None,
+ }
+}
diff --git a/vendor/hayro-postscript/src/string/literal.rs b/vendor/hayro-postscript/src/string/literal.rs
new file mode 100644
index 0000000..37a1593
--- /dev/null
+++ b/vendor/hayro-postscript/src/string/literal.rs
@@ -0,0 +1,85 @@
+// Keep in sync with `hayro-syntax/src/object/string.rs` (`read_literal`).
+
+use alloc::vec::Vec;
+
+use crate::reader::Reader;
+
+pub(crate) fn decode_into(data: &[u8], out: &mut Vec<u8>) -> Option<()> {
+ let mut r = Reader::new(data);
+
+ while let Some(byte) = r.read_byte() {
+ match byte {
+ b'\\' => {
+ let next = r.read_byte()?;
+
+ if is_octal_digit(next) {
+ let second = r.read_byte();
+ let third = r.read_byte();
+
+ let bytes = match (second, third) {
+ (Some(n1), Some(n2)) => match (is_octal_digit(n1), is_octal_digit(n2)) {
+ (true, true) => [next, n1, n2],
+ (true, _) => {
+ r.jump(r.offset() - 1);
+ [b'0', next, n1]
+ }
+ _ => {
+ r.jump(r.offset() - 2);
+ [b'0', b'0', next]
+ }
+ },
+ (Some(n1), None) => {
+ if is_octal_digit(n1) {
+ [b'0', next, n1]
+ } else {
+ r.jump(r.offset() - 1);
+ [b'0', b'0', next]
+ }
+ }
+ _ => [b'0', b'0', next],
+ };
+
+ let str = core::str::from_utf8(&bytes).unwrap();
+
+ if let Ok(num) = u8::from_str_radix(str, 8) {
+ out.push(num);
+ }
+ } else {
+ match next {
+ b'n' => out.push(0xA),
+ b'r' => out.push(0xD),
+ b't' => out.push(0x9),
+ b'b' => out.push(0x8),
+ b'f' => out.push(0xC),
+ b'(' => out.push(b'('),
+ b')' => out.push(b')'),
+ b'\\' => out.push(b'\\'),
+ b'\n' | b'\r' => {
+ // "If the \ is followed immediately by a newline
+ // (CR, LF, or CR-LF pair), the scanner ignores
+ // both the initial \ and the newline; this breaks
+ // a string into multiple lines without including
+ // the newline character as part of the string."
+ r.skip_eol();
+ }
+ _ => out.push(next),
+ }
+ }
+ }
+ b'(' | b')' => out.push(byte),
+ // "But if a newline appears without a preceding \, the result is
+ // equivalent to \n."
+ b'\n' | b'\r' => {
+ out.push(b'\n');
+ r.skip_eol();
+ }
+ other => out.push(other),
+ }
+ }
+
+ Some(())
+}
+
+fn is_octal_digit(byte: u8) -> bool {
+ matches!(byte, b'0'..=b'7')
+}
diff --git a/vendor/hayro-syntax/src/content/mod.rs b/vendor/hayro-syntax/src/content/mod.rs
index 886383e..e37044c 100644
--- a/vendor/hayro-syntax/src/content/mod.rs
+++ b/vendor/hayro-syntax/src/content/mod.rs
@@ -37,12 +37,11 @@ use crate::content::ops::TypedInstruction;
use crate::object;
use crate::object::dict::{Dict, InlineImageDict};
use crate::object::name::{Name, skip_name_like};
-use crate::object::{Array, Null, Number, Object, Stream};
+use crate::object::{Array, Number, Object, Stream};
use crate::reader::Reader;
use crate::reader::{Readable, ReaderContext, ReaderExt, Skippable};
use crate::trivia::{Comment, is_regular_character, is_white_space_character};
use crate::util::find_needle;
-use core::array;
use core::fmt::{Debug, Formatter};
use core::ops::Deref;
use core::marker::PhantomData;
@@ -51,8 +50,18 @@ use smallvec::SmallVec;
// 6 operands are used for example for ctm or cubic curves,
// but anything above should be pretty rare (only for example for
// DeviceN color spaces, or invalid PDF files). So we settle on 10.
+// PdfCraft patch (28): this is now only how many operands are held inline; see `MAX_OPERANDS`.
const OPERANDS_THRESHOLD: usize = 10;
+/// PdfCraft patch (28): the most operands one instruction keeps. The stack held ten, and the
+/// eleventh operand of an instruction ended the whole content stream, so a DeviceN colour of
+/// eleven or more inks (ISO 32000-2 §8.6.6.5 allows "an arbitrary number of colour
+/// components") blanked the rest of the page (#4260). An `SCN`/`scn` for the largest DeviceN
+/// space the interpreter reads (255 inks) takes 255 numbers and a pattern name. Past this, the
+/// oldest operands are dropped: operators read the operands nearest to them (see `shift` in the
+/// operator macros), so this is how stray operands below an instruction are already treated.
+const MAX_OPERANDS: usize = 256;
+
impl Debug for Operator<'_> {
fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
write!(f, "{}", self.0.as_str())
@@ -436,6 +445,8 @@ impl<'a> UntypedIter<'a> {
self.operator = Some(operator);
self.committed = self.reader.offset();
+ // PdfCraft patch (28): operands in reading order, if some were dropped.
+ self.stack.settle();
return Some(Instruction {
operands: &self.stack,
operator: self.operator.as_ref().unwrap(),
@@ -594,8 +605,13 @@ impl<'b, 'a> Instruction<'b, 'a> {
pub struct Stack<'a> {
// TODO: Explore using an object pool to avoid repeatedly
// allocating/deallocating objects.
- data: [Object<'a>; OPERANDS_THRESHOLD],
- len: usize,
+ // PdfCraft patch (28): up to `MAX_OPERANDS` operands, the first `OPERANDS_THRESHOLD` inline.
+ data: SmallVec<[Object<'a>; OPERANDS_THRESHOLD]>,
+ /// PdfCraft patch (28): once `data` is full, the slot of its oldest operand, which the next
+ /// operand replaces. Always 0 while the stack is not full, and after `settle`.
+ oldest: usize,
+ /// PdfCraft patch (28): whether operands were dropped since the stack was last settled.
+ dropped: bool,
}
impl<'a> Default for Stack<'a> {
@@ -608,31 +624,53 @@ impl<'a> Stack<'a> {
/// Create a new, empty stack.
pub fn new() -> Self {
Self {
- data: array::from_fn(|_| Object::Null(Null)),
- len: 0,
+ data: SmallVec::new(),
+ oldest: 0,
+ dropped: false,
}
}
+ /// PdfCraft patch (28): push an operand, dropping the oldest once `MAX_OPERANDS` are held
+ /// (see `MAX_OPERANDS`). Never fails: it used to, and the failure ended the content stream.
fn push(&mut self, operand: Object<'a>) -> Option<()> {
- if self.len >= OPERANDS_THRESHOLD {
- return None;
+ if self.data.len() < MAX_OPERANDS {
+ self.data.push(operand);
+ return Some(());
}
- self.data[self.len] = operand;
- self.len += 1;
+ self.dropped = true;
+ if let Some(slot) = self.data.get_mut(self.oldest) {
+ *slot = operand;
+ }
+ self.oldest = (self.oldest + 1) % MAX_OPERANDS;
Some(())
}
+ /// PdfCraft patch (28): put the operands back in the order they were read, oldest first,
+ /// after `push` dropped some. Called before the instruction is handed out.
+ fn settle(&mut self) {
+ if self.dropped {
+ warn!("more than {MAX_OPERANDS} operands before an operator; the oldest were dropped");
+ // Cannot panic: operands are dropped only once `data` holds `MAX_OPERANDS`, and
+ // `oldest` stays below that.
+ self.data.rotate_left(self.oldest);
+ self.oldest = 0;
+ self.dropped = false;
+ }
+ }
+
fn clear(&mut self) {
- self.len = 0;
+ self.data.clear();
+ self.oldest = 0;
+ self.dropped = false;
}
fn len(&self) -> usize {
- self.len
+ self.data.len()
}
fn as_slice(&self) -> &[Object<'a>] {
- &self.data[..self.len]
+ &self.data
}
fn get<'b, T>(&'b self, index: usize) -> Option<T>
@@ -665,11 +703,12 @@ impl Debug for Stack<'_> {
impl Clone for Stack<'_> {
fn clone(&self) -> Self {
- let mut stack = Self::new();
- for item in self.as_slice() {
- stack.push(item.clone()).unwrap();
+ // PdfCraft patch (28): a plain copy (pushing each operand again could no longer fail).
+ Self {
+ data: self.data.clone(),
+ oldest: self.oldest,
+ dropped: self.dropped,
}
- stack
}
}
diff --git a/vendor/hayro-syntax/src/content/ops.rs b/vendor/hayro-syntax/src/content/ops.rs
index b066165..bf582c3 100644
--- a/vendor/hayro-syntax/src/content/ops.rs
+++ b/vendor/hayro-syntax/src/content/ops.rs
@@ -152,6 +152,47 @@ f
assert!(iter.next().is_none());
}
+ /// PdfCraft patch (28): a twelve-ink DeviceN colour's `scn` keeps all twelve operands, and
+ /// the instructions after it are still read (#4260). The eleventh operand ended the stream.
+ #[test]
+ fn scn_with_twelve_components_keeps_them_all() {
+ let input = b"1 2 3 4 5 6 7 8 9 10 11 12 scn 0 0 10 10 re f";
+ let mut iter = TypedIter::new(input);
+
+ match iter.next() {
+ Some(TypedInstruction::NonStrokeColorNamed(NonStrokeColorNamed(nums, None))) => {
+ let expected = (1..=12).map(Number::from_i32).collect::<Vec<_>>();
+ assert_eq!(nums.as_slice(), expected.as_slice());
+ }
+ other => panic!("unexpected instruction: {other:?}"),
+ }
+ assert!(matches!(iter.next(), Some(TypedInstruction::RectPath(_))));
+ assert!(matches!(iter.next(), Some(TypedInstruction::FillPathNonZero(_))));
+ assert!(iter.next().is_none());
+ }
+
+ /// PdfCraft patch (28): past the operand cap the oldest operands are dropped, in order, and
+ /// the operator reads the ones nearest to it.
+ #[test]
+ fn operands_past_the_cap_keep_the_latest_in_order() {
+ let mut input = String::new();
+ for i in 0..600 {
+ input.push_str(&format!("{i} "));
+ }
+ input.push_str("scn 0 1 0 rg");
+ let mut iter = TypedIter::new(input.as_bytes());
+
+ match iter.next() {
+ Some(TypedInstruction::NonStrokeColorNamed(NonStrokeColorNamed(nums, None))) => {
+ let expected = (344..600).map(Number::from_i32).collect::<Vec<_>>();
+ assert_eq!(nums.as_slice(), expected.as_slice());
+ }
+ other => panic!("unexpected instruction: {other:?}"),
+ }
+ assert!(matches!(iter.next(), Some(TypedInstruction::NonStrokeColorDeviceRgb(_))));
+ assert!(iter.next().is_none());
+ }
+
#[test]
fn scn() {
let input = b"
diff --git a/vendor/hayro-syntax/src/xref.rs b/vendor/hayro-syntax/src/xref.rs
index 2d9df16..745af95 100644
--- a/vendor/hayro-syntax/src/xref.rs
+++ b/vendor/hayro-syntax/src/xref.rs
@@ -965,17 +965,13 @@ fn populate_from_xref_stream<'a>(
let [f1_len, f2_len, f3_len] = stream.dict().get::<[u8; 3]>(W)?;
- if f2_len > size_of::<u64>() as u8 {
- error!("xref offset length is larger than the allowed limit");
+ // PdfCraft patch: the type field is read at its full width, so it is bounded like the offset.
+ if f1_len > size_of::<u64>() as u8 || f2_len > size_of::<u64>() as u8 {
+ error!("xref field length is larger than the allowed limit");
return None;
}
- // Do such files exist?
- if f1_len != 1 {
- warn!("first field in xref stream was longer than 1");
- }
-
let xref_data = stream.decoded().ok()?;
// PdfCraft patch: (#2366) this section's entries are read first, for `prev_offset`.
let mut own = XrefMap::default();
@@ -1042,15 +1038,38 @@ fn xref_stream_subsection<'a>(
f3_len: u8,
insert_map: &mut XrefMap,
) -> Option<()> {
+ // PdfCraft patch: every entry must be backed by stream bytes. With all widths zero an entry
+ // reads nothing, so a tiny stream could declare billions of entries; and a count past the
+ // decoded data is refused before any of it is inserted.
+ let width = f1_len as usize + f2_len as usize + f3_len as usize;
+ if width == 0 {
+ warn!("xref stream entries have no width");
+
+ return None;
+ }
+ let available = xref_reader.len().saturating_sub(xref_reader.offset());
+ if (num_elements as usize)
+ .checked_mul(width)
+ .is_none_or(|need| need > available)
+ {
+ warn!("xref stream subsection declares more entries than its data holds");
+
+ return None;
+ }
+
for i in 0..num_elements {
+ // A zero-width type field defaults to 1 (ISO 32000-2 §7.5.8.2, `/W`).
let f_type = if f1_len == 0 {
1
} else {
- // We assume a length of 1.
- xref_reader.read_bytes(1)?[0]
+ // PdfCraft patch: the type field is read big-endian at its full `/W[0]` width.
+ let bytes = xref_reader.read_bytes(f1_len as usize)?;
+ bytes.iter().fold(0u64, |acc, b| (acc << 8) | u64::from(*b))
};
- let obj_number = start + i;
+ // PdfCraft patch: object numbers are stored as `i32`; a subsection running past
+ // `i32::MAX` is refused instead of overflowing or turning negative.
+ let obj_number = i32::try_from(start.checked_add(i)?).ok()?;
match f_type {
// We don't care about free objects.
@@ -1073,7 +1092,7 @@ fn xref_stream_subsection<'a>(
};
insert_map.insert(
- ObjectIdentifier::new(obj_number as i32, gen_number as i32),
+ ObjectIdentifier::new(obj_number, gen_number as i32),
EntryType::Normal(offset as usize),
);
}
@@ -1091,7 +1110,7 @@ fn xref_stream_subsection<'a>(
};
insert_map.insert(
- ObjectIdentifier::new(obj_number as i32, gen_number),
+ ObjectIdentifier::new(obj_number, gen_number),
EntryType::ObjStream(obj_stream_number, index),
);
}
@@ -1248,6 +1267,72 @@ fn parse_metadata(info_dict: &Dict<'_>) -> Metadata {
mod tests {
use super::*;
+ // PdfCraft patch tests (ported from craft-libs): xref stream entries are bounded by the
+ // decoded data, and the type field is read at its full width.
+ #[test]
+ fn xref_stream_entries_need_backing_bytes() {
+ let mut map = XrefMap::default();
+ // All widths zero: an entry reads nothing, so none may be declared.
+ let mut empty = Reader::new(&[]);
+ assert!(xref_stream_subsection(&mut empty, 0, u32::MAX, 0, 0, 0, &mut map).is_none());
+ assert!(map.is_empty());
+ // Three entries of width 3 need nine bytes; eight are refused before any insert.
+ let data = [1, 0, 9, 1, 0, 9, 1, 0];
+ let mut short = Reader::new(&data);
+ assert!(xref_stream_subsection(&mut short, 0, 3, 1, 1, 1, &mut map).is_none());
+ assert!(map.is_empty());
+ let mut whole = Reader::new(&data[..6]);
+ assert!(xref_stream_subsection(&mut whole, 0, 2, 1, 1, 1, &mut map).is_some());
+ assert_eq!(map.len(), 2);
+ // A subsection running past object number i32::MAX is refused.
+ for start in [i32::MAX as u32, u32::MAX] {
+ let mut past_end = XrefMap::default();
+ let mut wrap = Reader::new(&data[..6]);
+ assert!(xref_stream_subsection(&mut wrap, start, 2, 1, 1, 1, &mut past_end).is_none());
+ assert!(past_end.keys().all(|id| id.obj_number >= 0));
+ }
+ }
+
+ #[test]
+ fn xref_stream_type_field_uses_the_full_w0_width() {
+ // /W [2 1 1]: two-byte type 0x0001 (normal), offset 7, gen 0.
+ let mut map = XrefMap::default();
+ let mut reader = Reader::new(&[0u8, 1, 7, 0]);
+ assert!(xref_stream_subsection(&mut reader, 5, 1, 2, 1, 1, &mut map).is_some());
+ assert!(matches!(
+ map.get(&ObjectIdentifier::new(5, 0)),
+ Some(EntryType::Normal(7))
+ ));
+ }
+
+ #[test]
+ fn xref_stream_loader_rejects_oversized_w0() {
+ // One normal entry (offset 7, gen 0) whose type field is `type_len` bytes wide, so only
+ // the width of /W[0] differs between the two streams.
+ let load = |type_len: usize| {
+ let mut entry = vec![0u8; type_len];
+ entry[type_len - 1] = 1;
+ entry.extend_from_slice(&[7, 0]);
+ let mut data = format!(
+ "1 0 obj\n<< /Type /XRef /Size 6 /Index [5 1] /W [{type_len} 1 1] /Length {} >>\nstream\n",
+ entry.len()
+ )
+ .into_bytes();
+ data.extend_from_slice(&entry);
+ data.extend_from_slice(b"\nendstream\nendobj\n");
+ let mut map = XrefMap::default();
+ let got = populate_from_xref_stream(
+ &data,
+ &mut Reader::new(&data),
+ &mut map,
+ &mut BTreeSet::new(),
+ );
+ got.is_some()
+ };
+ assert!(load(8));
+ assert!(!load(9));
+ }
+
// Contributor-original, MIT OR Apache-2.0. Matches the bounded, uncompressed
// synthetic regression used to reproduce the cold-publication race. A second
// stream optionally checks that racing registration never aliases two ids.
diff --git a/vendor/hayro/src/lib.rs b/vendor/hayro/src/lib.rs
index a5ce6c2..37d1a5b 100644
--- a/vendor/hayro/src/lib.rs
+++ b/vendor/hayro/src/lib.rs
@@ -61,7 +61,7 @@ use vello_cpu::{Level, Pixmap, RenderMode};
mod renderer;
/// PdfCraft patch: exported for its regression test.
-pub use renderer::{image_resampling_size, tiling_cell_scale, usable_cell_scale};
+pub use renderer::{image_resampling_size, tiling_cell_pixels, tiling_cell_scale, usable_cell_scale};
/// PdfCraft patch: exported for its regression test.
#[doc(hidden)]
pub use renderer::set_skip_offscreen_paths;
diff --git a/vendor/hayro/src/renderer.rs b/vendor/hayro/src/renderer.rs
index 8909cb6..242c54e 100644
--- a/vendor/hayro/src/renderer.rs
+++ b/vendor/hayro/src/renderer.rs
@@ -1302,13 +1302,18 @@ impl Renderer {
xs = tiling_cell_scale(xs, t.x_step, MAX_PIXMAP_SIZE);
ys = tiling_cell_scale(ys, t.y_step, MAX_PIXMAP_SIZE);
- let x_step = xs * t.x_step;
- let y_step = ys * t.y_step;
-
- let scaled_width = bbox.width() as f32 * xs;
- let scaled_height = bbox.height() as f32 * ys;
- let pix_width = x_step.abs().round() as u16;
- let pix_height = y_step.abs().round() as u16;
+ // PdfCraft patch (25): the cell pixmap repeats every `pix_width` pixels,
+ // so one step must be exactly that many pixels. The cell is drawn at the
+ // scale that makes it so, and the paint transform below maps the pixmap
+ // back onto pattern space: cells sit at whole multiples of the step at
+ // any device scale. Drawing at the unrounded scale repeated the cell a
+ // fraction of a pixel too early or late, and the error grew with every
+ // step away from the pattern's origin.
+ let (pix_width, xs) = tiling_cell_pixels(xs, t.x_step, MAX_PIXMAP_SIZE);
+ let (pix_height, ys) = tiling_cell_pixels(ys, t.y_step, MAX_PIXMAP_SIZE);
+
+ let scaled_width = bbox.width() * xs;
+ let scaled_height = bbox.height() * ys;
let mut renderer = Self {
ctx: RenderContext::new_with(
@@ -1332,7 +1337,7 @@ impl Renderer {
preview: self.preview,
image_transparency_stack: Vec::new(),
};
- let mut initial_transform = Affine::scale_non_uniform(xs as f64, ys as f64)
+ let mut initial_transform = Affine::scale_non_uniform(xs, ys)
* Affine::translate((-bbox.x0, -bbox.y0));
t.interpret(&mut renderer, initial_transform, is_stroke);
let mut pix = Pixmap::new(pix_width, pix_height);
@@ -1341,14 +1346,14 @@ impl Renderer {
renderer.ctx.render_to_pixmap(&mut resources, &mut pix);
// TODO: Fix these
- if x_step < 0.0 {
+ if t.x_step < 0.0 {
initial_transform *=
- Affine::new([-1.0, 0.0, 0.0, 1.0, scaled_width as f64, 0.0]);
+ Affine::new([-1.0, 0.0, 0.0, 1.0, scaled_width, 0.0]);
}
- if y_step < 0.0 {
+ if t.y_step < 0.0 {
initial_transform *=
- Affine::new([1.0, 0.0, 0.0, -1.0, 0.0, scaled_height as f64]);
+ Affine::new([1.0, 0.0, 0.0, -1.0, 0.0, scaled_height]);
}
paint_transform =
@@ -2186,3 +2191,26 @@ pub fn tiling_cell_scale(scale: f32, step: f32, max_pixels: f32) -> f32 {
scale
}
}
+
+/// PdfCraft patch (25): the side of a tiling cell pixmap in pixels, and the scale to draw the
+/// cell at so that one `step` spans exactly that many pixels. The pixmap repeats every whole
+/// number of pixels; drawing the cell at `scale` itself would repeat it at `round(scale × step)`
+/// instead of `scale × step`, a fraction of a pixel off at every step (ISO 32000-2 8.7.3.1: cells
+/// are displaced by multiples of `/XStep` and `/YStep`). The side is kept within 1 and
+/// `max_pixels` (itself at most `u16::MAX`). When `scale × step` isn't finite and positive,
+/// `scale` is kept and the side is `max_pixels` for an infinite product, 1 otherwise.
+pub fn tiling_cell_pixels(scale: f32, step: f32, max_pixels: f32) -> (u16, f64) {
+ // A whole number of pixels; `max` and `min` (not `clamp`, which panics on NaN) make a NaN cap 1.
+ let max = f64::from(max_pixels).floor().max(1.0).min(f64::from(u16::MAX));
+ let (scale, step) = (f64::from(scale), f64::from(step.abs()));
+ let exact = scale * step;
+ if !(exact.is_finite() && exact > 0.0) {
+ let pixels = if exact == f64::INFINITY { max } else { 1.0 };
+ // In 1..=u16::MAX, so the cast is exact.
+ return (pixels as u16, scale);
+ }
+ let pixels = exact.round().max(1.0).min(max);
+ // `pixels` is in 1..=u16::MAX, so the cast is exact; `step` is positive and finite here
+ // (`exact` is), so the division is too.
+ (pixels as u16, pixels / step)
+}