Merge upstream/main into fix/update-without-prev-is-refused

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Pq7HyCHD1R3rywQBPCHXZA
This commit is contained in:
mtlcl410andClaude Opus 5.5 committed 2026-11-08 20:50:01 +08:00
commit d6ffacbd19
134 files changed
+8929 -647

No files matched your search

+8
View File
@@ -19,7 +19,14 @@ concurrency:
cancel-in-progress: false
jobs:
# Regenerates contributors/contributors.json for the release commit; every build bundles it.
credits:
permissions:
contents: read
pull-requests: read
uses: storytold/craft-common-actions/.github/workflows/refresh-contributors.yml@main
release:
needs: credits
# Intentionally tracked at @main (not SHA-pinned) so org-wide CI improvements, security fixes, and build optimizations propagate without PR churn across all craftapp repos.
uses: storytold/craft-common-actions/.github/workflows/release.yml@main
with:
@@ -27,6 +34,7 @@ jobs:
app-title: PdfCraft
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
version: ${{ inputs.version }}
contributors-artifact: ${{ needs.credits.outputs.artifact-name }}
secrets:
APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }}
APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }}
+5 -5
View File
@@ -45,7 +45,7 @@ Every asset PdfCraft includes, bundles or uses to build its published material,
| `assets/icons/chevron-up.svg` | Lucide icon "chevron-up" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/chevron-up.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/chevrons-left.svg` | Lucide icon "chevrons-left" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/chevrons-left.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/chevrons-right.svg` | Lucide icon "chevrons-right" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/chevrons-right.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/circle-check.svg` | Lucide icon "circle-check" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/circle-check.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/circle-check.svg` | Lucide icon "circle-check" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/circle-check.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs; drawn as PDF path data by crates/sign/src/status_layers.rs into displayed signature status layers |
| `assets/icons/circle-dashed.svg` | Lucide icon "circle-dashed" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/circle-dashed.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/circle-dot.svg` | Lucide icon "circle-dot" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/circle-dot.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/circle-help.svg` | Lucide icon "circle-help" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/circle-help.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
@@ -174,7 +174,7 @@ Every asset PdfCraft includes, bundles or uses to build its published material,
| `assets/icons/text-select.svg` | Lucide icon "text-select" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/text-select.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/trash-2.svg` | Lucide icon "trash-2" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/trash-2.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/trash.svg` | Lucide icon "trash" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/trash.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/triangle-alert.svg` | Lucide icon "triangle-alert" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/triangle-alert.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/triangle-alert.svg` | Lucide icon "triangle-alert" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/triangle-alert.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs; drawn as PDF path data by crates/sign/src/status_layers.rs into displayed signature status layers |
| `assets/icons/type.svg` | Lucide icon "type" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/type.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/underline.svg` | Lucide icon "underline" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/underline.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/undo-2.svg` | Lucide icon "undo-2" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/undo-2.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
@@ -184,7 +184,7 @@ Every asset PdfCraft includes, bundles or uses to build its published material,
| `assets/icons/x.svg` | Lucide icon "x" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/x.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/zoom-in.svg` | Lucide icon "zoom-in" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/zoom-in.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/zoom-out.svg` | Lucide icon "zoom-out" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/zoom-out.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/fonts/Inter-Regular.ttf` | Inter Regular | The Inter Project Authors (Rasmus Andersson) | OFL-1.1 | https://github.com/rsms/inter | UI font, embedded in the app; demo PDF labels; slanted fallback glyphs in Fill & Sign typed signatures for characters Dancing Script lacks (Cyrillic, Greek), drawn as filled paths |
| `assets/fonts/Inter-Regular.ttf` | Inter Regular | The Inter Project Authors (Rasmus Andersson) | OFL-1.1 | https://github.com/rsms/inter | UI font, embedded in the app; demo PDF labels; slanted fallback glyphs in Fill & Sign typed signatures for characters Dancing Script lacks (Cyrillic, Greek), drawn as filled paths; embedded into displayed signature status captions beyond WinAnsi by crates/sign/src/status_layers.rs |
| `assets/fonts/Inter-Medium.ttf` | Inter Medium | The Inter Project Authors (Rasmus Andersson) | OFL-1.1 | https://github.com/rsms/inter | UI font, embedded in the app; demo PDF labels |
| `assets/fonts/Inter-SemiBold.ttf` | Inter SemiBold | The Inter Project Authors (Rasmus Andersson) | OFL-1.1 | https://github.com/rsms/inter | UI font, embedded in the app; demo PDF labels |
| `assets/fonts/JetBrainsMono-Regular.ttf` | JetBrains Mono Regular | The JetBrains Mono Project Authors | OFL-1.1 | https://github.com/JetBrains/JetBrainsMono | UI monospace font; demo PDF code |
@@ -249,7 +249,7 @@ Every asset PdfCraft includes, bundles or uses to build its published material,
| `assets/icons/thumbs-up.svg` | Lucide icon "thumbs-up" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/thumbs-up.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/thumbs-down.svg` | Lucide icon "thumbs-down" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/thumbs-down.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/message-square-plus.svg` | Lucide icon "message-square-plus" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/message-square-plus.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/circle-x.svg` | Lucide icon "circle-x" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/circle-x.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/circle-x.svg` | Lucide icon "circle-x" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/circle-x.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs; drawn as PDF path data by crates/sign/src/status_layers.rs into displayed signature status layers |
| `crates/ui-egui/tests/data/form.pdf` | One-page AcroForm test fixture (text, check box, radio group, combo box) | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: hand-written PDF objects, no third-party content | Form-filling UI tests (crates/ui-egui/tests/it/forms.rs, commands.rs) |
| `assets/icons/pentagon.svg` | Lucide icon "pentagon" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/pentagon.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/message-square-quote.svg` | Lucide icon "message-square-quote" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/message-square-quote.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
@@ -314,4 +314,4 @@ Not in this repository and never downloaded by it: compiled in only when the bui
| Input | Option | Title | Author | Licence | Source | Attribution | Used for |
|---|---|---|---|---|---|---|---|
| `craft-i18n` | `CRAFT_I18N_DIR` | Interface translations: the craft-i18n catalogs (locales/<code>/common.tsv and pdfcraft.tsv) of the 34 languages PdfCraft offers besides English | The craft-i18n translators, including every translator of PdfCraft's former in-repo catalogs (crates/ui-egui/src/i18n/*.tsv, migrated at pdfcraft@ecdd1e6) | MIT OR Apache-2.0 | https://github.com/storytold/craft-i18n (pinned by commit in craft-i18n.rev, which CI, releases and the flatpak manifests read) | https://github.com/storytold/craft-i18n/blob/main/ATTRIBUTION.md | Interface text in languages other than English, embedded by crates/ui-egui/build.rs and looked up through craft-libs' craft-i18n crate; a build without CRAFT_I18N_DIR is English only. Clean-room translations from PdfCraft's English interface labels |
| `craft-fonts` | `CRAFT_FONTS_DIR` | Japanese fonts: BIZ UDPGothic (Regular, Bold), Shippori Mincho, BIZ UDMincho; native Simplified Chinese font: LXGW WenKai Lite; Arabic font: Noto Sans Arabic | The BIZ UDGothic and BIZ UDMincho Project Authors (Morisawa Inc.), The Shippori Mincho Project Authors (FONTDASU), LXGW and the original Klee Project Authors / Fontworks (LXGW WenKai Lite), The Noto Project Authors (Noto Sans Arabic) | OFL-1.1 | https://github.com/storytold/craft-fonts (pinned by commit in .github/workflows/release.yml and .github/workflows/ci.yml); LXGW WenKai Lite from https://github.com/lxgw/LxgwWenKai-Lite/releases/tag/v1.530 (commit b712c83d98acf977bacfb7fb010207802808bda9) | https://github.com/storytold/craft-fonts/blob/main/ATTRIBUTION.md | Japanese fallback in the interface (BIZ UDPGothic first) and Japanese glyphs in edited PDF text (Shippori Mincho); Simplified Chinese interface fallback on native builds only (LXGW WenKai Lite Regular, font SHA-256 f799a538a3355877e597a0ae04050e897932c9ae7689eb9227c2953c5dd549ea, OFL SHA-256 0333a85fe077b6849f8e417acc44e8bd879442ceb681e271acf93e2d57fd4e2e, read from fonts/simplified-chinese-manifest.txt and never embedded on wasm); Arabic interface text, file names and document titles (Noto Sans Arabic); the web build embeds BIZ UDPGothic Regular and the pinned small Arabic, Hebrew, Thai and Devanagari faces; the selected craft-fonts revision contains no Telugu face. Other non-Japanese CJK faces retain the general 4 MiB cap; the reviewed native-only LXGW fallback has a separate 16 MiB cap. Open-source OFL releases are permitted under current AGENTS.md §1.1 |
| `craft-fonts` | `CRAFT_FONTS_DIR` | Japanese fonts: BIZ UDPGothic (Regular, Bold), Shippori Mincho, BIZ UDMincho; native Simplified Chinese font: LXGW WenKai Lite; Arabic font: Noto Sans Arabic | The BIZ UDGothic and BIZ UDMincho Project Authors (Morisawa Inc.), The Shippori Mincho Project Authors (FONTDASU), LXGW and the original Klee Project Authors / Fontworks (LXGW WenKai Lite), The Noto Project Authors (Noto Sans Arabic) | OFL-1.1 | https://github.com/storytold/craft-fonts (pinned by commit in .github/workflows/release.yml and .github/workflows/ci.yml); LXGW WenKai Lite from https://github.com/lxgw/LxgwWenKai-Lite/releases/tag/v1.530 (commit b712c83d98acf977bacfb7fb010207802808bda9) | https://github.com/storytold/craft-fonts/blob/main/ATTRIBUTION.md | Japanese fallback in the interface (BIZ UDPGothic first) and Japanese glyphs in edited PDF text (Shippori Mincho); Simplified Chinese interface fallback on native builds only (LXGW WenKai Lite Regular, font SHA-256 f799a538a3355877e597a0ae04050e897932c9ae7689eb9227c2953c5dd549ea, OFL SHA-256 0333a85fe077b6849f8e417acc44e8bd879442ceb681e271acf93e2d57fd4e2e, read from fonts/simplified-chinese-manifest.txt and never embedded on wasm); Arabic interface text, file names and document titles (Noto Sans Arabic); status captions of named-layer signatures in Arabic, Japanese, Thai and Devanagari, drawn as filled outlines into the display copy by crates/sign/src/status_layers.rs; the web build embeds BIZ UDPGothic Regular and the pinned small Arabic, Hebrew, Thai and Devanagari faces; the selected craft-fonts revision contains no Telugu face. Other non-Japanese CJK faces retain the general 4 MiB cap; the reviewed native-only LXGW fallback has a separate 16 MiB cap. Open-source OFL releases are permitted under current AGENTS.md §1.1 |
+5 -5
View File
@@ -425,7 +425,7 @@ source = "https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icon
licence = "ISC AND MIT"
licence_file = "assets/icons/LICENSE-lucide.txt"
kind = "icon"
usage = "UI icon, embedded via crates/ui-egui/src/icon_data.rs"
usage = "UI icon, embedded via crates/ui-egui/src/icon_data.rs; drawn as PDF path data by crates/sign/src/status_layers.rs into displayed signature status layers"
sha256 = "201e790f3a05c65b2c4b0f952c9b9e1f35cd1c5b21698b3f4be131883fe90bc8"
[[asset]]
@@ -1844,7 +1844,7 @@ source = "https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icon
licence = "ISC AND MIT"
licence_file = "assets/icons/LICENSE-lucide.txt"
kind = "icon"
usage = "UI icon, embedded via crates/ui-egui/src/icon_data.rs"
usage = "UI icon, embedded via crates/ui-egui/src/icon_data.rs; drawn as PDF path data by crates/sign/src/status_layers.rs into displayed signature status layers"
sha256 = "55aa37e0b73e7f8cd906952dbdeb96283c6595ca64aba240a17f3455cb989114"
[[asset]]
@@ -1954,7 +1954,7 @@ source = "https://github.com/rsms/inter"
licence = "OFL-1.1"
licence_file = "assets/fonts/OFL-Inter.txt"
kind = "font"
usage = "UI font, embedded in the app; demo PDF labels; slanted fallback glyphs in Fill & Sign typed signatures for characters Dancing Script lacks (Cyrillic, Greek), drawn as filled paths"
usage = "UI font, embedded in the app; demo PDF labels; slanted fallback glyphs in Fill & Sign typed signatures for characters Dancing Script lacks (Cyrillic, Greek), drawn as filled paths; embedded into displayed signature status captions beyond WinAnsi by crates/sign/src/status_layers.rs"
sha256 = "40d692fce188e4471e2b3cba937be967878f631ad3ebbbdcd587687c7ebe0c82"
[[asset]]
@@ -3004,7 +3004,7 @@ source = "https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icon
licence = "ISC AND MIT"
licence_file = "assets/icons/LICENSE-lucide.txt"
kind = "icon"
usage = "UI icon, embedded via crates/ui-egui/src/icon_data.rs"
usage = "UI icon, embedded via crates/ui-egui/src/icon_data.rs; drawn as PDF path data by crates/sign/src/status_layers.rs into displayed signature status layers"
sha256 = "ef1fec17d88794ba6c34c5cf63bdadbd234b3d4dffbcc3d55468b47e3f398472"
[[asset]]
@@ -3142,7 +3142,7 @@ source = "https://github.com/storytold/craft-fonts (pinned by commit in .github/
licence = "OFL-1.1"
attribution = "https://github.com/storytold/craft-fonts/blob/main/ATTRIBUTION.md"
kind = "font"
usage = "Japanese fallback in the interface (BIZ UDPGothic first) and Japanese glyphs in edited PDF text (Shippori Mincho); Simplified Chinese interface fallback on native builds only (LXGW WenKai Lite Regular, font SHA-256 f799a538a3355877e597a0ae04050e897932c9ae7689eb9227c2953c5dd549ea, OFL SHA-256 0333a85fe077b6849f8e417acc44e8bd879442ceb681e271acf93e2d57fd4e2e, read from fonts/simplified-chinese-manifest.txt and never embedded on wasm); Arabic interface text, file names and document titles (Noto Sans Arabic); the web build embeds BIZ UDPGothic Regular and the pinned small Arabic, Hebrew, Thai and Devanagari faces; the selected craft-fonts revision contains no Telugu face. Other non-Japanese CJK faces retain the general 4 MiB cap; the reviewed native-only LXGW fallback has a separate 16 MiB cap. Open-source OFL releases are permitted under current AGENTS.md §1.1"
usage = "Japanese fallback in the interface (BIZ UDPGothic first) and Japanese glyphs in edited PDF text (Shippori Mincho); Simplified Chinese interface fallback on native builds only (LXGW WenKai Lite Regular, font SHA-256 f799a538a3355877e597a0ae04050e897932c9ae7689eb9227c2953c5dd549ea, OFL SHA-256 0333a85fe077b6849f8e417acc44e8bd879442ceb681e271acf93e2d57fd4e2e, read from fonts/simplified-chinese-manifest.txt and never embedded on wasm); Arabic interface text, file names and document titles (Noto Sans Arabic); status captions of named-layer signatures in Arabic, Japanese, Thai and Devanagari, drawn as filled outlines into the display copy by crates/sign/src/status_layers.rs; the web build embeds BIZ UDPGothic Regular and the pinned small Arabic, Hebrew, Thai and Devanagari faces; the selected craft-fonts revision contains no Telugu face. Other non-Japanese CJK faces retain the general 4 MiB cap; the reviewed native-only LXGW fallback has a separate 16 MiB cap. Open-source OFL releases are permitted under current AGENTS.md §1.1"
[[asset]]
path = "crates/sign/tests/data/x509-rsa-sha1.pdf"
Generated
+26 -1
View File
@@ -4265,7 +4265,6 @@ version = "0.18.1"
dependencies = [
"pdfcraft-content",
"pdfcraft-cos",
"pdfcraft-filters",
"pdfcraft-fonts",
"pdfcraft-model",
"thiserror 2.0.21",
@@ -4642,6 +4641,7 @@ dependencies = [
"pdfcraft-render",
"pdfcraft-testkit",
"pdfcraft-xfa",
"regex",
"sha2 0.11.1",
"thiserror 2.0.21",
]
@@ -4688,9 +4688,11 @@ dependencies = [
"p521",
"pbkdf2",
"pdfcraft-annot",
"pdfcraft-content",
"pdfcraft-cos",
"pdfcraft-fonts",
"pdfcraft-model",
"pdfcraft-testkit",
"rc2",
"ripemd",
"rsa",
@@ -5521,6 +5523,29 @@ dependencies = [
"bitflags 2.13.2",
]
[[package]]
name = "regex"
version = "1.13.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d"
dependencies = [
"aho-corasick",
"memchr",
"regex-automata",
"regex-syntax",
]
[[package]]
name = "regex-automata"
version = "0.4.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2"
dependencies = [
"aho-corasick",
"memchr",
"regex-syntax",
]
[[package]]
name = "regex-syntax"
version = "0.8.11"
+8 -1
View File
@@ -70,7 +70,11 @@ pdfcraft-prc-render = { path = "crates/prc-render", version = "0.18.1" }
hayro = "0.7.1"
hayro-syntax = "0.7.2"
lopdf = "0.45"
flate2 = { version = "1.1", default-features = false, features = ["rust_backend"] }
# zlib-rs: miniz_oxide took about 1.7 µs for every fixed-Huffman block, empty or not
# (`pdfcraft_filters::FLATE_READ_WORK`). Other dependencies still build flate2's default
# miniz_oxide backend; flate2 prefers zlib-rs when both are built, as the Windows build already did
# through craft-update. `flate::tests::a_copy_from_before_the_start_is_damage` shows which runs.
flate2 = { version = "1.1", default-features = false, features = ["zlib-rs"] }
weezl = "0.2"
# CCITT Group 4 encoding (pdfcraft-filters); already in the tree through tiff.
fax = "0.2.7"
@@ -80,6 +84,9 @@ hayro-jbig2 = "0.3"
# foundation
thiserror = "2"
# Linear-time matching (no backtracking) for caller-supplied redaction patterns. `perf-dfa` gives
# the lazy-DFA cache that `RegexBuilder::dfa_size_limit` bounds (the limit is inert without it).
regex = { version = "1", default-features = false, features = ["std", "unicode", "perf-dfa"] }
serde = { version = "1", features = ["derive", "rc"] }
serde_json = "1"
log = "0.4"
+10
View File
@@ -3,6 +3,8 @@
> **Last reviewed:** 2026-11-03 | **Last updated:** 2026-11-03 | **Change:** patch (M5 #5850 review: indirect typewriter intent and composer edits preserve outer whitespace; movement regression commits by outside click; estimates unchanged)
> **Last reviewed:** 2026-11-03 | **Last updated:** 2026-11-03 | **Change:** patch (M5 #5850: Enter adds Fill & Sign line breaks; outside clicks commit, Escape cancels, and saved multiline appearances retain their text and height; estimates unchanged)
> **Last reviewed:** 2026-10-31 | **Last updated:** 2026-10-31 | **Change:** minor (M3/M4, #5330: Crop pages is directly available in the document quick toolbar; estimates unchanged)
> **Last reviewed:** 2026-11-01 | **Last updated:** 2026-11-01 | **Change:** patch (M7, PR #2155 further review: inherited drawing/text state, affine image gestures, paste/selection ownership, no-op scripts and menu permissions; estimates unchanged)
@@ -229,6 +231,7 @@ Ranked; detail and the full milestone table in [docs/roadmap.md](docs/roadmap.md
| 8 | 1.0 polish: performance, right-to-left, missing languages, keyboard-only (M14) | 55–95 |
## Progress log
- **2026-10-13 (M8, redact by regex):** `redact_mark` takes `regex` (caller expression, linear-time engine, length/size/nesting caps, empty-matching refused) with optional `validate` (luhn, mod97, iban). Headless only; issue #1886.
- **2026-10-28 (M10, #4119 partial):** Scan & OCR ▸ Enhance scanned file cleans scanned pages in place: background removal (level 0–100, as the camera clean-up), edge shadow removal (book gutters, copier borders) and despeckle. Each scan image is decoded, cleaned and written back into its own object at the same size and colour space (JPEG stays JPEG, others lossless, 1-bit stays 1-bit), so the OCR text layer, comments and links stay; one undo step, shared images once, unsupported images (CMYK, indexed, JPEG 2000, JBIG2, CCITT, broken data) reported. `page_enhance_scan` drives it headlessly. Not yet an option of Recognize text. Estimates unchanged.
- **2026-11-03 (M11, shared JBIG2 dictionary):** With Monochrome Images set to JBIG2, Optimize has up to 16 JBIG2 images share one symbol dictionary (`/JBIG2Globals`), the letters found on more than one page stored once, when that is smaller (`pdfcraft_filters::encode_jbig2_shared`). Eight pages of 10 pt text rendered at 300 dpi take 41% less in Helvetica and 42% in Times than coded alone, 10% in Courier; groups of 16 save 45%, of 32 only 47%. Only images redaction can store again without the dictionary share one (image masks and DeviceGray named directly, at most 64 Mi pixels), and redacting one stores the rest of its group so, which the group bounds to 15.
@@ -256,6 +259,7 @@ Ranked; detail and the full milestone table in [docs/roadmap.md](docs/roadmap.md
- 2026-11-01: PR #2155 review follow-up preserves editor crops through group moves and keeps arranged artwork outside added-item streams; unsafe nested-tag extraction is refused. Image handles and flips follow page orientation, added images accept general transforms, and clipboard/text/Home/font-discovery edge cases have focused regressions. Candidate only; estimates unchanged.
- 2026-11-01: PR #2155 maintainer edits remove redundant image/text helpers and add regressions for crop ownership, arrange scope/state fidelity, clipboard precedence, crop-drag bounds, and font scanning. Transform and Unicode-script tools complete the headless paths.
- **2026-10-31 (M3/M4, #5330):** The document quick toolbar offers Crop pages directly through the existing page.crop command, with the command’s assembly-permission check and an active-tool highlight. The existing crop, undo and headless page_set_box paths are unchanged. No toolbar customization or new shortcut. Estimates unchanged.
- **2026-10-18 (M3, #1354, local candidate):** Integrated --two-paged with current main, retaining upstream modal/picker ownership and single-tab reuse. Native launch/opening/password regressions, negative checks against the old wrapper, visual inspection, formatting, strict scoped Clippy, layers, assets, parity and scoped WASM compilation pass. Three existing socket tests are unavailable in this workspace; one existing network test remains ignored. No push or GitHub merge; estimates unchanged.
- **2026-10-31 (M2, PR #4172 review):** Added same-machine pixel oracles for GBK Song, Hei, Kai and FangSong, including all four subset-prefixed Founder aliases. Reference PDFs use explicit Unicode mappings and independently selected installed faces; font data and rasters remain in memory. All eight cases ran; wrong-glyph and wrong-family production mutations each failed the new assertion and were restored. Validation: 422 renderer unit tests, renderer all-target Clippy with -D warnings, formatting, layers/assets/parity and renderer WASM checks passed; existing optional-patch/WASM warnings and parity notes remain. Estimates unchanged.
@@ -315,6 +319,7 @@ Ranked; detail and the full milestone table in [docs/roadmap.md](docs/roadmap.md
- **2026-10-22 (M14, macOS association recovery candidate):** Successful desktop open/save/sign can queue recovery of an existing per-file binding to the running PDFCraft bundle through NSWorkspace. Metadata-only watcher changes retain undo and avoid false overwrite prompts; real same-length/same-mtime edits remain protected. Rebased on 0.12.0 and reuses #3042's shared atomic metadata preservation; the bounded recovery parser does not narrow save limits. Prior native Preview TEST-signature and Finder workflows passed on macOS 27.0.1; other versions remain unqualified. Estimates unchanged.
- **2026-10-13 (M7, free image rotation):** A selected page image has a rotate knob (Shift: 15 degree steps) and `image_edit` a `rotate_by` action; the angle is written as one undoable `cm`. Snapping to page edges while moving is in #1740; resize snapping is not done. Estimates unchanged.
- **2026-10-20 (M9 #79 review, M2, M8):** text extraction reads a marked-content /ActualText that marks no glyph where it paints (paths and images, cut to what is visible, along the direction they are drawn), so words drawn as outlines can be found, copied and exported; OCR and scan field detection still count such a page as having no text of its own. Redaction strips /ActualText, /Alt, /E and /T from inline marked content around paint it clips, as it already did around paint it removed, so a partly redacted outlined word leaves no name in the file. Named-layer recognition also needs the layer form to draw n1 and n3. Estimates unchanged.
- **2026-10-20 (M4, initial view):** Window and interface options read indirect boolean ViewerPreferences values. Synthetic regressions cover true/false, direct/indirect preference dictionaries and save/reopen; malformed entries retain false defaults. Estimates unchanged.
- **2026-10-20 (M3, #3535):** Escape with a menu open closes the menu and keeps the text selection; the next Escape clears it, as before. One keypress used to do both. A synthetic UI regression checks it. Estimates unchanged.
- **2026-10-16 (M3, close prompt keyboard):** The "Save changes?" prompt opens with Save chosen (Enter saves, as before) and the arrow keys and Tab / Shift+Tab move the choice to Cancel or Don't save, shown with a focus ring; Enter or Space press the chosen button and Escape still cancels. Before, Enter always saved whatever was Tab-focused. Estimates unchanged.
@@ -405,6 +410,8 @@ Ranked; detail and the full milestone table in [docs/roadmap.md](docs/roadmap.md
- **2026-10-16 (M10, #1201 partial):** Lossless image export applies each component's Decode pair. Indexed values round and clip before palette lookup. Color-key masks keep raw samples. The existing 16-bit precision limit remains. JPEG and mask Decode, ICC transforms, and calibrated colors remain outside this fix. Estimates unchanged.
- **2026-10-16 (M3, #2739):** Wrapped revision buttons stay above Binding in Document Properties. A synthetic regression checks control bounds and opens a saved revision at two viewport widths. Estimates unchanged.
- **2026-10-19 (M7, tracked text):** Editable paragraphs and object labels distinguish repeated glyph tracking from word gaps in TJ arrays and separately positioned glyphs. Synthetic regressions cover character spacing, horizontal scaling, rotated baselines, larger word gaps, and rows of one-glyph words or cells (inferred tracking is capped at half an em, so `a b c` and digit or Y/N columns keep their spaces). Estimates unchanged.
- **2026-10-16 (M9, #79):** a signature appearance that follows the named-layer convention (its /N draws one Form that holds and draws n1 and n3) shows the signature's real state: n1, n3 and n4 are redrawn in the display copy with the panel's icons and a caption in the interface language (Helvetica; else shaped in embedded Inter, or in a craft-fonts face for Arabic, Japanese and Telugu; else English, as Chinese always is). Exports, both print modes and the CLI's render show the redrawn state; saves never do. Every signature keeps its badge, since a document can clip or cover its own layers. Estimates unchanged.
- **2026-10-16 (M9):** the page validation overlay moves to the widget's bottom-right corner as it lies on the page (so it turns with the page and the view) and takes a quarter of the widget's shorter side, at most 48 screen points, so it annotates the signer's artwork from a corner instead of covering the middle of it; a field too small for a legible mark keeps its outline, a rectangle the screen cannot place is not drawn at all, and the whole widget answers the pointer. Estimates unchanged.
- **2026-10-16 (M5, #2669, item 5):** The Comments panel groups replies by name and counts all page roots once per frame. Estimates unchanged.
- **2026-10-16 (M7, #2140):** Header & footer (and Bates numbering, which uses the same dialog) can shrink the page content so the header and footer don't cover it: the original content is scaled evenly into the band they leave free, centred across, also on rotated pages; Remove and Update take the scaling away, and margins that leave no room are refused. Dialog checkbox with a preview of the band, `shrink` on `doc_header_footer`, all catalogs. Annotations and added text and images are not moved yet. Estimates unchanged.
- **2026-10-20 (M14, Spanish catalog gaps):** `es.tsv` gains the 143 `(context, English)` keys the other catalogs carried and it was missing, so Spanish covers the whole bundled key union like Lithuanian and Vietnamese: calendar months and weekdays, the `certificate` context, X.509 key usages, signature-revision and digital-ID lines, password validation, eight plural messages, the combine-from-folder strings, the rendering and stale-file notices and the shortcut-spelled tooltips. Counts in `localization-parity.md` re-measured against the current union (`vi` restated against it for the same reason). Status stays `partial`: no translated help, and OS details stay outside the catalog. Estimates unchanged.
@@ -793,6 +800,7 @@ Newest first: the date, what moved, and the new overall estimate.
| 2026-11-01 | patch | M7 #5657: header/footer, watermark and background operations commit all selected pages together; later-page errors preserve marks, content, shared/inherited resources and pending edits; estimates unchanged. |
| 2026-10-28 | patch | M2, PR #4172: integrate main 5af10276 and retain both roadmap histories; viewer-only CJK and print/output font policies and estimates unchanged. |
| 2026-10-27 | minor | M10: OCR stages SHA-256-verified ONNX models after the upstream RTEN URL brownout; discovery prefers a complete ONNX pair per directory, falls back to a complete RTEN pair, and never mixes formats or directories; language/web limits and estimates unchanged. |
| 2026-10-20 | minor | M9 #79 review, M2, M8: /ActualText that marks no glyph extracts where it paints, as far as it is visible; redaction strips /ActualText around paint it clips; named-layer recognition needs the layer form to draw n1 and n3. Estimates unchanged. |
| 2026-10-23 | minor | M8, #3205 follow-up: phone-pattern redaction includes the +39 country code on labelled Italian geographic numbers with a slash; dates, protocol identifiers and whole-run guards remain. Estimates unchanged. |
| 2026-10-23 | minor | M11: image downsampling measures physical resolution after page-local UserUnit scaling, including shared nested forms; synthetic measurement and optimization regressions. Estimates unchanged. |
| 2026-10-23 | minor | M10: Word table cells use the grid columns they span, including cells after a merged cell; synthetic export regression and CLI reproduction. Estimates unchanged. |
@@ -807,6 +815,8 @@ Newest first: the date, what moved, and the new overall estimate.
| 2026-10-18 | minor | M1, #1143: a live reference may match the xref generation or a same-number header at its indexed offset; neither-match and free slots remain null. Bounded repair diagnostics and synthetic cache, free-slot, edit and classic/packed save regressions; estimates unchanged. |
| 2026-10-18 | minor | M5, PR #1971: nested source `/Page` and `/Pages` dictionaries export as null without traversing page content or the page tree. Synthetic saved/reopened three-page regression retains unrelated metadata and aliases. FDF import semantics, copied-graph limits and estimates unchanged. |
| 2026-10-15 | minor | M5: budget retained FDF entries before cloning; discovery keeps lazy array owners and annotation positions, with alias/cache-eviction stress fixtures. Limits cover the copied graph; source parsing/page discovery retain existing COS/parser limits, with no total source-memory bound. FDF import semantics and estimates unchanged. |
| 2026-10-16 | minor | M9 #79: named-layer signature appearances show the signature's real state in the display copy, exports and both print modes, never in saves; captions follow the interface language. Estimates unchanged. |
| 2026-10-16 | minor | M9: the page validation overlay moves to the widget's bottom-right corner as it lies on the page and stops growing past 48 screen points, so it annotates the signer's artwork from a corner instead of covering the middle of it; a field under 32 screen points keeps its outline. Estimates unchanged. |
| 2026-10-15 | minor | M7: the Edit text caret is as tall as the row it is on in a region with several sizes; estimates unchanged. |
| 2026-10-18 | minor | M4, PR #1919 review: repeated page indices apply each rotation to the latest page-local value, preserving indirect/inherited angles. Synthetic adjacent/interleaved duplicates retain siblings and page contents through incremental and full saves. Estimates unchanged. |
| 2026-10-18 | minor | M3, #3149: page replacement cancels render demand collected for the previous geometry; all viewer raster upload paths reject empty or oversized textures before cache eviction. Synthetic regressions reproduce the reported 1880×2350 upload at a 2048 limit, retain cached images and unsaved edits, and resume bounded backdrops and tiles. Estimates unchanged. |
+3 -2
View File
@@ -366,8 +366,9 @@ pub(crate) fn render(args: &[String]) -> Result<(), CliError> {
Some("pam") => None,
_ => return Err(format!("render: --out {out}: use a .png, .jpg, .tif or .pam name").into()),
};
// The app renders a display copy that draws comments missing their /AP streams; the CLI
// must agree with it (and with independent viewers), while keeping the file it reads intact.
// The app renders a display copy that draws comments missing their /AP streams and the state
// of named-layer signatures (here with no trusted certificates); the CLI must agree with it
// (and with independent viewers), while keeping the file it reads intact.
let bytes = read(path)?;
let password = flag(args, "--password");
// The renderer takes only the user password of R2–R4 files; `Session::open` and the display
+1 -1
View File
@@ -333,7 +333,7 @@ fn native_options(integrated: bool, app_frame: bool, renderer: eframe::Renderer)
let mut viewport = egui::ViewportBuilder::default()
.with_title("PdfCraft")
.with_inner_size([1440.0, 920.0])
.with_min_inner_size([820.0, 520.0])
.with_min_inner_size(pdfcraft_ui_egui::MIN_WINDOW_SIZE)
.with_drag_and_drop(true)
// Wayland app id: matches packaging/linux/ai.storyteller.pdfcraft.desktop.
.with_app_id(APP_ID);
+5
View File
@@ -186,3 +186,8 @@ sync_github_name = true
[people.helenkwok]
real_name = "Helen Kwok"
[people.vangel76]
real_name = "Valentin Klein"
display_name = "vangel76"
sync_github_name = false
-1
View File
@@ -14,6 +14,5 @@ workspace = true
pdfcraft-cos = { workspace = true }
pdfcraft-model = { workspace = true }
pdfcraft-content = { workspace = true }
pdfcraft-filters = { workspace = true }
pdfcraft-fonts = { workspace = true }
thiserror.workspace = true
+74 -20
View File
@@ -25,6 +25,8 @@ pub enum AltError {
NotAFigure(u32),
#[error("the page has more content than can be edited")]
TooLarge,
#[error("the figure's content may be in a damaged or unreadable content stream, or after the damage, so nothing was changed")]
Damaged,
#[error("{0}")]
Cos(#[from] pdfcraft_cos::CosError),
}
@@ -52,6 +54,8 @@ pub enum ArtifactError {
ParentTree(String),
#[error("the page has more content than can be edited")]
TooLarge,
#[error("the tag's marked content may be in a damaged or unreadable content stream, or after the damage, so nothing was changed")]
Damaged,
#[error(transparent)]
Cos(#[from] pdfcraft_cos::CosError),
}
@@ -372,7 +376,19 @@ fn content_entries(doc: &Document, page: &Dict) -> Vec<Object> {
}
}
type DecodedStream = (Object, Option<(Stream, Vec<u8>)>);
/// How much of a content stream decoded.
#[derive(Clone, Copy, Debug, PartialEq)]
enum Read {
Whole,
/// Damaged partway: the data is what decoded before the damage. What follows it is unknown,
/// the syntax the later streams start in too.
Damaged,
/// Not at all (a filter this reader lacks, say): the data is empty.
Unread,
}
/// A `/Contents` entry and, for a stream, the stream, its decoded data and how much of it decoded.
type DecodedStream = (Object, Option<(Stream, Vec<u8>, Read)>);
/// Decode the page's content streams within the page decode budget. `None` when a stream is
/// rejected because the budget is exhausted.
@@ -383,14 +399,14 @@ fn decode_page_streams(doc: &Document, page: &Dict) -> Option<Vec<DecodedStream>
for entry in entries {
let decoded = match &*doc.resolve(&entry) {
Object::Stream(s) => {
let data = match budget.decode(s) {
Ok(data) => data,
let (data, read) = match budget.decode_with_damage(doc, s, usize::MAX) {
Ok((data, damaged)) => (data, if damaged { Read::Damaged } else { Read::Whole }),
// Content past the budget may hold more of the tag: editing the rest
// would leave that part marked as a tag the tree no longer has.
Err(_) if budget.exhausted() => return None,
Err(_) => Vec::new(),
Err(_) => (Vec::new(), Read::Unread),
};
Some((s.clone(), data))
Some((s.clone(), data, read))
}
_ => None,
};
@@ -403,6 +419,18 @@ fn marked_id(doc: &Document, props: &Dict, op: &pdfcraft_content::Op, ids: &Hash
(op.op == b"BDC").then(|| bdc_mcid(doc, props, op)).flatten().filter(|n| ids.contains(n))
}
/// What [`artifact_marked_content`] did.
#[derive(Debug, PartialEq)]
enum Marked {
/// The streams holding the content were rewritten.
Done,
/// None of the content is on the page, or with `require_all` not all of it: nothing changed.
NotFound,
/// Some of it is, or may be, in a stream damaged partway or one that doesn't decode, neither of
/// which can be rewritten without losing what wasn't read, or after the damage: nothing changed.
Damaged,
}
/// Turn the tag's marked-content blocks into artifacts, rewriting only the streams that
/// contain them. Other content streams, and unknown entries on a rewritten stream, stay.
/// With `require_all`, every id in `ids` must appear on the page before any stream is rewritten.
@@ -412,25 +440,45 @@ fn artifact_marked_content(
streams: Vec<DecodedStream>,
ids: &HashSet<i64>,
require_all: bool,
) -> Result<bool, pdfcraft_cos::CosError> {
) -> Result<Marked, pdfcraft_cos::CosError> {
let props = page_properties(doc, &page.dict);
let decoded: Vec<&[u8]> = streams.iter().filter_map(|(_, s)| s.as_ref().map(|(_, bytes)| bytes.as_slice())).collect();
// The pieces are the streams, in order.
let decoded: Vec<&[u8]> = streams.iter().filter_map(|(_, s)| s.as_ref().map(|(_, bytes, _)| bytes.as_slice())).collect();
let read: Vec<Read> = streams.iter().filter_map(|(_, s)| s.as_ref().map(|(_, _, read)| *read)).collect();
let damage = read.iter().position(|r| *r == Read::Damaged);
let pieces = pdfcraft_content::Pieces::join(&decoded);
let mut found = HashSet::new();
let mut edits = Vec::new();
for op in pieces.parse().ops {
if let Some(id) = marked_id(doc, &props, &op, ids) {
// What follows the damage is unknown: a string or comment the damage left open runs
// on into the next stream, so what reads as an operator after it may not be one. An
// operator whose operands start before a stream not read whole and whose keyword comes
// after it takes them from around what wasn't read: that stream may end them itself.
let (first, last) = pieces.pieces_of(&op);
if damage.is_some_and(|d| last > d) || read.get(first..last).is_some_and(|r| r.iter().any(|r| *r != Read::Whole)) {
return Ok(Marked::Damaged);
}
found.insert(id);
edits.push((op.span, b"/Artifact BMC".to_vec()));
}
}
if if require_all { found != *ids } else { found.is_empty() } {
return Ok(false);
// Content not found may be past the damage, or in a stream that doesn't decode: whether it
// is on the page isn't known.
if found != *ids && read.iter().any(|r| *r != Read::Whole) {
return Ok(Marked::Damaged);
}
let mut spliced = pieces.splice(edits).into_iter();
if if require_all { found != *ids } else { found.is_empty() } {
return Ok(Marked::NotFound);
}
let spliced = pieces.splice(edits);
if read.iter().zip(&decoded).zip(&spliced).any(|((read, old), new)| *read != Read::Whole && *old != new.as_slice()) {
return Ok(Marked::Damaged);
}
let mut spliced = spliced.into_iter();
let mut next = Vec::with_capacity(streams.len());
for (entry, stream) in streams {
let Some((stream, old)) = stream else {
let Some((stream, old, _)) = stream else {
next.push(entry);
continue;
};
@@ -456,7 +504,7 @@ fn artifact_marked_content(
_ => Object::Array(next),
};
doc.update_dict(page.obj, |p| p.set(b"Contents".to_vec(), contents))?;
Ok(true)
Ok(Marked::Done)
}
/// Decorative figure: its marked content on the page becomes an artifact, and the element
@@ -468,11 +516,15 @@ pub fn mark_decorative(doc: &mut Document, obj: ObjRef) -> Result<(), AltError>
let pg = d.get(b"Pg").and_then(Object::as_ref).or_else(|| elements(doc).into_iter().find(|e| e.object == obj).and_then(|e| e.page));
if let Some(page) = pg.and_then(|p| pages.iter().find(|x| x.obj == p)).filter(|_| !ids.is_empty()) {
let streams = decode_page_streams(doc, &page.dict).ok_or(AltError::TooLarge)?;
// The parent tree no longer points those ids at the figure.
if artifact_marked_content(doc, page, streams, &ids, false)?
&& let Some(key) = page.dict.get(b"StructParents").and_then(Object::as_int)
{
clear_parent_tree(doc, key, obj)?;
match artifact_marked_content(doc, page, streams, &ids, false)? {
// The parent tree no longer points those ids at the figure.
Marked::Done => {
if let Some(key) = page.dict.get(b"StructParents").and_then(|o| doc.resolve(o).as_int()) {
clear_parent_tree(doc, key, obj)?;
}
}
Marked::NotFound => {}
Marked::Damaged => return Err(AltError::Damaged),
}
}
// Out of its parent's kids.
@@ -513,10 +565,12 @@ pub fn mark_tag_artifact(doc: &mut Document, obj: ObjRef) -> Result<(), Artifact
let parent = element.dict.get(b"P").and_then(Object::as_ref).ok_or(ArtifactError::NoParent)?;
let replacement = replacement_kids(doc, parent, obj)?;
let streams = decode_page_streams(doc, &page.dict).ok_or(ArtifactError::TooLarge)?;
if !artifact_marked_content(doc, page, streams, &ids, true)? {
return Err(ArtifactError::ContentNotFound);
match artifact_marked_content(doc, page, streams, &ids, true)? {
Marked::Done => {}
Marked::NotFound => return Err(ArtifactError::ContentNotFound),
Marked::Damaged => return Err(ArtifactError::Damaged),
}
if let Some(key) = page.dict.get(b"StructParents").and_then(Object::as_int) {
if let Some(key) = page.dict.get(b"StructParents").and_then(|o| doc.resolve(o).as_int()) {
clear_parent_tree(doc, key, obj).map_err(|e| ArtifactError::ParentTree(e.to_string()))?;
}
doc.update_dict(parent, |p| p.set(b"K".to_vec(), replacement))?;
+17 -11
View File
@@ -4,7 +4,7 @@
//! which can then be retagged with the existing tag-property tool after human review.
use pdfcraft_content::{Op, parse, serialize_ops};
use pdfcraft_cos::{Dict, Document, ObjRef, Object, Stream};
use pdfcraft_cos::{DecodeBudget, Dict, Document, ObjRef, Object, Stream};
const MAX_PAGES: usize = 1_000;
const MAX_PAGE_BYTES: usize = 16 * 1024 * 1024;
@@ -57,18 +57,24 @@ fn content_bytes(doc: &Document, page: &pdfcraft_model::Page, index: usize) -> R
let Object::Stream(stream) = &*value else { return Err(unsupported(index, "contents include a non-stream object")) };
let remaining = MAX_PAGE_BYTES.saturating_sub(all.len().saturating_add(1));
if remaining == 0 {
return Err(unsupported(index, "decoded content exceeds 16 MiB"));
return Err(unsupported(index, "decoding the content takes more than 16 MiB"));
}
let chain = stream.filters();
let decoded = if chain.is_empty() {
if stream.raw.len() > remaining {
return Err(unsupported(index, "decoded content exceeds 16 MiB"));
// Strictly, and with `/DecodeParms` given by reference: the content is written back from it.
let mut budget = DecodeBudget::new(remaining, 0);
let decoded = budget.decode_strict(doc, stream).map_err(|e| {
// The allowance counts what every filter stage decodes, as a page's does.
if budget.remaining() == 0 {
unsupported(index, "decoding the content takes more than 16 MiB")
} else {
// The decoder's own reason: `CosError::Filter`'s text would say again that the data
// couldn't be decoded.
let why = match e {
pdfcraft_cos::CosError::Filter(why) => why,
other => other.to_string(),
};
unsupported(index, format!("content cannot be decoded strictly: {why}"))
}
stream.raw.to_vec()
} else {
pdfcraft_filters::decode(&chain, &stream.raw, remaining)
.map_err(|e| unsupported(index, format!("content cannot be decoded strictly: {e}")))?
};
})?;
all.extend_from_slice(&decoded);
all.push(b' ');
}
+241
View File
@@ -79,6 +79,68 @@ fn autotag_text_writes_marked_content_and_parent_tree_across_pages() {
assert_eq!(status(&check(&reopened, &Options::default()), Rule::TaggedContent), Status::Passed);
}
/// Page content behind a predictor whose `/DecodeParms` are given by reference is read through
/// them: autotagging writes the text back as it was, marked, not with the predictor's tag bytes in
/// it (a `\0` every eight bytes, which split `24` into `2 4`).
#[test]
fn autotag_text_reads_content_with_parameters_given_by_reference() {
use pdfcraft_cos::{Dict, ObjRef};
let mut content = b"BT /F1 24 Tf 72 700 Td (Hello World) Tj ET".to_vec();
content.resize(content.len().div_ceil(8) * 8, b' ');
// PNG rows of eight bytes, each tagged 0 (no prediction).
let rows: Vec<u8> = content.chunks(8).flat_map(|row| std::iter::once(0).chain(row.iter().copied())).collect();
let mut doc = 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 600 800] /Contents 4 0 R /Resources << /Font << /F1 5 0 R >> >> >>".into(),
stream(""),
FONT.into(),
],
"",
);
let parms: Dict = [(b"Predictor".to_vec(), Object::Int(12)), (b"Columns".to_vec(), Object::Int(8))].into_iter().collect();
let parms = doc.add(Object::Dict(parms));
let mut predicted = pdfcraft_cos::Stream::flate(Dict::new(), &rows);
predicted.dict.set(b"DecodeParms".to_vec(), Object::Ref(parms));
doc.set(ObjRef::new(4, 0), predicted);
assert_eq!(autotag_text(&mut doc).unwrap(), AutoTagResult { pages: 1, paragraphs: 1 });
let page = &pdfcraft_model::pages(&doc)[0];
let written = doc.resolve(page.dict.get(b"Contents").unwrap());
let Object::Stream(written) = &*written else { panic!("page content") };
let text = String::from_utf8_lossy(&written.decoded_strict().unwrap()).into_owned();
assert!(text.contains("/F1 24 Tf") && text.contains("(Hello World) Tj"), "{text}");
}
/// Autotagging refuses a page whose content it can't read whole, and says why: content past
/// 16 MiB, or content that doesn't decode strictly, with the decoder's reason right after.
#[test]
fn autotag_text_says_why_it_cannot_read_a_page() {
use pdfcraft_cos::{Dict, ObjRef, Stream};
let reason = |content: Stream| {
let mut doc = 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 600 800] /Contents 4 0 R /Resources << /Font << /F1 5 0 R >> >> >>".into(),
stream(""),
FONT.into(),
],
"",
);
doc.set(ObjRef::new(4, 0), content);
match autotag_text(&mut doc) {
Err(AutoTagError::Unsupported { reason, .. }) => reason,
other => panic!("{other:?}"),
}
};
assert_eq!(reason(Stream::from_raw(Dict::new(), vec![b' '; 17 << 20])), "decoding the content takes more than 16 MiB");
let mut corrupt = Stream::from_raw(Dict::new(), b"not zlib data".to_vec());
corrupt.dict.set(b"Filter".to_vec(), Object::name("FlateDecode"));
let why = reason(corrupt);
assert!(why.starts_with("content cannot be decoded strictly: FlateDecode: "), "{why}");
}
#[test]
fn autotag_text_refuses_paint_and_does_not_modify_the_document() {
let mut doc = pdf(
@@ -1087,6 +1149,185 @@ fn mark_tag_artifact_validates_parent_and_all_mcids_before_mutating_document() {
assert_eq!(*absent.get(ObjRef::new(9, 0)), before_pt);
}
/// zlib data that reads as `readable` and is then damaged, with more of the stream after the
/// damage: a stored block, then a block of the reserved type (RFC 1951 §3.2.3), then `rest`.
fn damaged_flate(readable: &[u8], rest: &[u8]) -> pdfcraft_cos::Stream {
let len = u16::try_from(readable.len()).unwrap();
let mut raw = vec![0x78, 0x01, 0x00];
raw.extend_from_slice(&len.to_le_bytes());
raw.extend_from_slice(&(!len).to_le_bytes());
raw.extend_from_slice(readable);
raw.push(0x07);
raw.extend_from_slice(rest);
let mut dict = pdfcraft_cos::Dict::new();
dict.set(b"Filter".to_vec(), pdfcraft_cos::Object::name("FlateDecode"));
pdfcraft_cos::Stream::from_raw(dict, raw)
}
/// A tag's content in a stream damaged partway stays tagged: rewriting the stream from what
/// decoded would lose what follows the damage. Nothing changes, the structure tree and the stream
/// included. Content in a whole stream before a damaged one is marked, and the damaged one kept
/// as stored.
#[test]
fn a_tags_content_in_a_stream_damaged_partway_is_not_rewritten() {
use pdfcraft_cos::{ObjRef, Object};
let content = b"/Figure << /MCID 0 >> BDC q 40 0 0 20 10 150 cm /Im Do Q EMC /Photo << /MCID 1 >> BDC 100 100 50 30 re f EMC\n";
let damaged = damaged_flate(content, b"0 0 1 rg 0 0 10 10 re f");
let mut doc = figures_doc();
doc.set(ObjRef::new(4, 0), damaged.clone());
let contents = |doc: &Document| doc.get(ObjRef::new(3, 0)).as_dict().unwrap().get(b"Contents").cloned();
let state = |doc: &Document| (contents(doc), doc.get(ObjRef::new(9, 0)), doc.get(ObjRef::new(6, 0)), doc.get(ObjRef::new(4, 0)));
let before = state(&doc);
assert_eq!(figures(&doc).len(), 2, "read up to the damage");
assert_eq!(mark_tag_artifact(&mut doc, ObjRef::new(7, 0)), Err(ArtifactError::Damaged));
assert_eq!(mark_decorative(&mut doc, ObjRef::new(7, 0)), Err(AltError::Damaged));
assert_eq!(state(&doc), before);
let mut doc = figures_doc();
let other = doc.add(damaged_flate(b"0 g\n", b"0 0 1 rg 0 0 10 10 re f"));
doc.update_dict(ObjRef::new(3, 0), |p| p.set(b"Contents".to_vec(), Object::Array(vec![Object::Ref(ObjRef::new(4, 0)), Object::Ref(other)])))
.unwrap();
mark_tag_artifact(&mut doc, ObjRef::new(7, 0)).unwrap();
let Some(Object::Array(list)) = contents(&doc) else { panic!("contents {:?}", contents(&doc)) };
assert_ne!(list.first(), Some(&Object::Ref(ObjRef::new(4, 0))), "the tag's stream is rewritten");
assert_eq!(list.get(1), Some(&Object::Ref(other)), "kept as stored");
}
/// What follows the damage is unknown, the syntax the next stream starts in too, so a tag's
/// content in a stream after a damaged one stays tagged. Here a comment the damage leaves open
/// runs on into the next stream, up to its first end of line, and a string starting there reads
/// as operators, among them what looks like the figure's content: rewritten, it would change the
/// string. Nothing changes, the structure tree included.
#[test]
fn a_tags_content_after_a_damaged_stream_is_not_rewritten() {
use pdfcraft_cos::{Dict, ObjRef, Object, Stream};
let in_a_string = b"(a note\n/Figure << /MCID 0 >> BDC 0 g EMC\n) pop /Photo << /MCID 1 >> BDC 100 100 50 30 re f EMC";
for (damaged, after) in [(b"0 g\n".as_slice(), None), (b"0 g % a comment".as_slice(), Some(in_a_string.as_slice()))] {
let mut doc = figures_doc();
if let Some(after) = after {
doc.set(ObjRef::new(4, 0), Stream::from_raw(Dict::new(), after.to_vec()));
}
let first = doc.add(damaged_flate(damaged, b"\n0 0 1 rg 0 0 10 10 re f"));
doc.update_dict(ObjRef::new(3, 0), |p| p.set(b"Contents".to_vec(), Object::Array(vec![Object::Ref(first), Object::Ref(ObjRef::new(4, 0))])))
.unwrap();
let state = |doc: &Document| {
(doc.get(ObjRef::new(3, 0)).as_dict().unwrap().get(b"Contents").cloned(), doc.get(ObjRef::new(9, 0)), doc.get(ObjRef::new(6, 0)))
};
let before = state(&doc);
assert_eq!(mark_tag_artifact(&mut doc, ObjRef::new(7, 0)), Err(ArtifactError::Damaged), "{damaged:?}");
assert_eq!(mark_decorative(&mut doc, ObjRef::new(7, 0)), Err(AltError::Damaged), "{damaged:?}");
assert_eq!(state(&doc), before, "{damaged:?}");
}
}
/// A page may split its content between an operator's operands and its keyword. When the operands
/// of the figure's `BDC` end the stream before one damaged from its start or one that doesn't
/// decode, the `BDC` the page reads is in what wasn't read: joined without it, those operands and
/// the next tag's read as one `BDC`, which reaches into the stream after it. Neither marking
/// changes anything, the structure tree included.
#[test]
fn a_tags_operands_before_a_stream_not_read_whole_are_not_rewritten() {
use pdfcraft_cos::{Dict, ObjRef, Object, Stream};
let rest = b" BDC q 40 0 0 20 10 150 cm /Im Do Q EMC";
for damaged in [true, false] {
let mut doc = figures_doc();
doc.set(ObjRef::new(4, 0), Stream::from_raw(Dict::new(), b"/Figure << /MCID 0 >>".to_vec()));
let hidden = if damaged {
damaged_flate(b"", rest)
} else {
let filter = doc.add(Object::name("FlateDecode"));
let mut s = Stream::flate(Dict::new(), rest);
s.dict.set(b"Filter".to_vec(), Object::Ref(filter));
s
};
let hidden = doc.add(hidden);
let after = doc.add(Object::Stream(Stream::from_raw(Dict::new(), b"/Photo << /MCID 1 >> BDC 100 100 50 30 re f EMC".to_vec())));
let listed = Object::Array(vec![Object::Ref(ObjRef::new(4, 0)), Object::Ref(hidden), Object::Ref(after)]);
doc.update_dict(ObjRef::new(3, 0), |p| p.set(b"Contents".to_vec(), listed)).unwrap();
let state = |doc: &Document| {
(doc.get(ObjRef::new(3, 0)).as_dict().unwrap().get(b"Contents").cloned(), doc.get(ObjRef::new(9, 0)), doc.get(ObjRef::new(6, 0)))
};
let before = state(&doc);
assert_eq!(mark_tag_artifact(&mut doc, ObjRef::new(7, 0)), Err(ArtifactError::Damaged), "damaged: {damaged}");
assert_eq!(mark_decorative(&mut doc, ObjRef::new(7, 0)), Err(AltError::Damaged), "damaged: {damaged}");
assert_eq!(state(&doc), before, "damaged: {damaged}");
}
}
/// A tag's content not found on the page may be in a stream that doesn't decode: it isn't known
/// to be off the page, so neither marking changes anything, the structure tree included.
#[test]
fn a_tags_content_not_found_beside_a_stream_that_does_not_decode_is_not_taken_for_absent() {
use pdfcraft_cos::{Dict, ObjRef, Object, Stream};
let mut doc = figures_doc();
doc.update_dict(ObjRef::new(7, 0), |d| d.set(b"K".to_vec(), Object::Int(2))).unwrap();
let mut dict = Dict::new();
dict.set(b"Filter".to_vec(), Object::name("NoSuchFilter"));
let other = doc.add(Object::Stream(Stream::from_raw(dict, b"/Figure << /MCID 2 >> BDC 0 g EMC".to_vec())));
doc.update_dict(ObjRef::new(3, 0), |p| p.set(b"Contents".to_vec(), Object::Array(vec![Object::Ref(other), Object::Ref(ObjRef::new(4, 0))])))
.unwrap();
let state = |doc: &Document| {
(doc.get(ObjRef::new(3, 0)).as_dict().unwrap().get(b"Contents").cloned(), doc.get(ObjRef::new(9, 0)), doc.get(ObjRef::new(6, 0)))
};
let before = state(&doc);
assert_eq!(mark_decorative(&mut doc, ObjRef::new(7, 0)), Err(AltError::Damaged));
assert_eq!(mark_tag_artifact(&mut doc, ObjRef::new(7, 0)), Err(ArtifactError::Damaged));
assert_eq!(state(&doc), before);
}
/// A tag's content not found before the damage in a damaged stream may be past it: it isn't known
/// to be off the page, so neither marking changes anything.
#[test]
fn a_tags_content_past_the_damage_is_not_taken_for_absent() {
use pdfcraft_cos::ObjRef;
let damaged =
damaged_flate(b"/Photo << /MCID 1 >> BDC 100 100 50 30 re f EMC\n", b"/Figure << /MCID 0 >> BDC q 40 0 0 20 10 150 cm /Im Do Q EMC");
let mut doc = figures_doc();
doc.set(ObjRef::new(4, 0), damaged);
let contents = |doc: &Document| doc.get(ObjRef::new(3, 0)).as_dict().unwrap().get(b"Contents").cloned();
let before = (contents(&doc), doc.get(ObjRef::new(9, 0)), doc.get(ObjRef::new(6, 0)));
assert_eq!(mark_decorative(&mut doc, ObjRef::new(7, 0)), Err(AltError::Damaged));
assert_eq!(mark_tag_artifact(&mut doc, ObjRef::new(7, 0)), Err(ArtifactError::Damaged));
assert_eq!((contents(&doc), doc.get(ObjRef::new(9, 0)), doc.get(ObjRef::new(6, 0))), before);
}
/// A page's `/StructParents` given by reference is read through it: the parent tree no longer
/// points the marked content at the tag.
#[test]
fn struct_parents_given_by_reference_are_read() {
use pdfcraft_cos::{ObjRef, Object};
let by_reference = || {
let mut doc = figures_doc();
let key = doc.add(Object::Int(0));
doc.update_dict(ObjRef::new(3, 0), |p| p.set(b"StructParents".to_vec(), Object::Ref(key))).unwrap();
doc
};
let nums = |doc: &Document| doc.get(ObjRef::new(9, 0)).as_dict().and_then(|d| d.get(b"Nums").cloned());
let mut doc = by_reference();
mark_decorative(&mut doc, ObjRef::new(7, 0)).unwrap();
assert_eq!(nums(&doc), Some(Object::Array(vec![Object::Int(0), Object::Array(vec![Object::Null, Object::Ref(ObjRef::new(8, 0))])])));
let mut doc = by_reference();
mark_tag_artifact(&mut doc, ObjRef::new(8, 0)).unwrap();
assert_eq!(nums(&doc), Some(Object::Array(vec![Object::Int(0), Object::Array(vec![Object::Ref(ObjRef::new(7, 0)), Object::Null])])));
}
/// A content stream that doesn't decode at all is kept as stored, and a tag in the page's other
/// streams is still marked: only running past the decode budget refuses.
#[test]
fn a_tag_beside_a_stream_that_does_not_decode_is_marked() {
use pdfcraft_cos::{Dict, ObjRef, Object, Stream};
let mut doc = figures_doc();
let mut dict = Dict::new();
dict.set(b"Filter".to_vec(), Object::name("NoSuchFilter"));
let other = doc.add(Object::Stream(Stream::from_raw(dict, b"0 g".to_vec())));
doc.update_dict(ObjRef::new(3, 0), |p| p.set(b"Contents".to_vec(), Object::Array(vec![Object::Ref(other), Object::Ref(ObjRef::new(4, 0))])))
.unwrap();
mark_tag_artifact(&mut doc, ObjRef::new(7, 0)).unwrap();
let contents = doc.get(ObjRef::new(3, 0)).as_dict().unwrap().get(b"Contents").cloned();
let Some(Object::Array(list)) = contents else { panic!("contents {contents:?}") };
assert_eq!(list.first(), Some(&Object::Ref(other)), "kept as stored");
}
fn ref_(n: u32) -> Option<pdfcraft_cos::ObjRef> {
Some(pdfcraft_cos::ObjRef::new(n, 0))
}
+2 -2
View File
@@ -283,7 +283,7 @@ impl<'a> Walker<'a> {
return Err(AuditError::TooManyForms);
}
// A form stream that cannot be decoded fails the audit: it might hide a cover.
let data = self.budget.decode_strict(stream)?;
let data = self.budget.decode_strict(self.doc, stream)?;
// The XObject matrix maps form space into the user space active at `Do`.
let mut sub_gs = gs.clone();
sub_gs.ctm = matrix.then(&gs.ctm);
@@ -326,7 +326,7 @@ pub fn filled_rects(doc: &Document, page: &Dict) -> Result<Vec<FilledRect>, Audi
let mut streams = Vec::with_capacity(contents.len());
for c in &contents {
if let Object::Stream(s) = &*doc.resolve(c) {
streams.push(budget.decode_strict(s)?);
streams.push(budget.decode_strict(doc, s)?);
}
}
let pieces = Pieces::join(&streams);
+49 -2
View File
@@ -185,6 +185,7 @@ impl Automation {
let recipe = Recipe::parse(self, args)?;
let recursive = args.opt_bool("recursive")?.unwrap_or(false);
let stop = args.opt_bool("stop_on_error")?.unwrap_or(false);
let dry_run = args.opt_bool("dry_run")?.unwrap_or(false);
let paths = args.strs("paths")?;
if paths.is_empty() || paths.len() > 1000 {
return Err(Args::wrong("paths", "1 to 1000 files or folders"));
@@ -211,11 +212,41 @@ impl Automation {
let mut files = discovery.skipped;
let (mut completed, mut failed_count) = (0, 0);
let mut stopped = false;
let mut planned_outputs: HashSet<PathBuf> = HashSet::new();
for (path, relative) in discovery.files {
if stopped || !recipe.accepts(&path) {
files.push(json!({"path":path.to_string_lossy(),"status":"skipped","reason":if stopped {"stopped after error"} else {"unsupported input extension"}}));
continue;
}
if dry_run {
let planned: Result<PathBuf> = (|| {
let target = out.join(&relative).with_extension("pdf");
let target = self.resolve(target.to_str().ok_or_else(|| failed("output path is not UTF-8"))?, true)?;
if !target.starts_with(&out) {
return Err(failed("output path leaves out_dir"));
}
let dir = target.parent().ok_or_else(|| failed("output has no parent"))?;
let stem = target.file_stem().ok_or_else(|| failed("output has no stem"))?.to_string_lossy().into_owned();
for n in 1..=10_000 {
let candidate = if n == 1 { target.clone() } else { dir.join(format!("{stem} ({n}).pdf")) };
if candidate.symlink_metadata().is_ok() || planned_outputs.contains(&candidate) {
continue;
}
planned_outputs.insert(candidate.clone());
return Ok(candidate);
}
Err(failed("all 10000 output names are occupied"))
})();
match planned {
Ok(target) => files.push(json!({"path":path.to_string_lossy(),"status":"planned","output":target.to_string_lossy().replace('\\', "/"),"steps":recipe.steps})),
Err(e) => {
failed_count += 1;
files.push(json!({"path":path.to_string_lossy(),"status":"error","error":e.to_string()}));
stopped = stop;
}
}
continue;
}
// Recheck confinement and links before reading a discovered file.
let result: Result<_> = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
let current = self.resolve(path.to_str().ok_or_else(|| failed("input path is not UTF-8"))?, false)?;
@@ -244,8 +275,8 @@ impl Automation {
}
}
}
let skipped = files.len().saturating_sub(completed + failed_count);
Ok(json!({"completed":completed,"failed":failed_count,"skipped":skipped,"stopped":stopped,"files":files}))
let skipped = files.iter().filter(|file| file["status"] == "skipped").count();
Ok(json!({"dry_run":dry_run,"completed":completed,"failed":failed_count,"skipped":skipped,"stopped":stopped,"files":files}))
}
}
@@ -279,4 +310,20 @@ mod tests {
discovery.visited = 0;
assert!(discovery.walk(Path::new("absent"), Path::new(""), Path::new("output"), true, MAX_DEPTH + 1).unwrap_err().to_string().contains("64"));
}
#[test]
fn doc_batch_dry_run_lists_outputs_without_writing() {
let dir = tempfile::tempdir().unwrap();
std::fs::create_dir(dir.path().join("input")).unwrap();
let pdf = Session::new().create_from_text("Doc", "Hello").unwrap();
std::fs::write(dir.path().join("input/a.pdf"), &*pdf).unwrap();
let auto = Automation::new().with_root(dir.path()).unwrap();
let report = auto.doc_batch(&Args(&json!({"paths":["input"],"steps":["optimize"],"out_dir":"out","dry_run":true}))).unwrap();
assert_eq!(report["dry_run"], true, "{report}");
assert_eq!(report["completed"], 0, "{report}");
assert_eq!(report["failed"], 0, "{report}");
assert_eq!(report["files"][0]["status"], "planned", "{report}");
assert!(report["files"][0]["output"].as_str().unwrap().ends_with("out/a.pdf"), "{report}");
assert!(!dir.path().join("out").exists());
}
}
+61 -3
View File
@@ -6,6 +6,10 @@ use super::{Arc, Automation, BlockKey, DocId, Document, Edit, Path, PathBuf, Tex
/// How far a watermark may be moved from the page centre, in points (a page is at most 14,400).
const WATERMARK_MAX_OFFSET: f64 = 20_000.0;
/// `doc_optimize` with `target_bytes`: (max target ppi, max JPEG quality) per extra attempt, mildest first.
/// The quality applies only to images the caller left on JPEG; zip and retain keep their encoding.
const TARGET_LADDER: [(f64, u8); 5] = [(110.0, 45), (96.0, 35), (72.0, 28), (54.0, 20), (36.0, 12)];
/// Bookmarks in one page of the bookmark list, by default and at most.
const BOOKMARK_PAGE: usize = 100;
@@ -380,7 +384,45 @@ impl Automation {
})
.collect::<Result<_>>()?,
};
let (bytes, r) = self.session.optimized_bytes(id, &settings, &discard).map_err(failed)?;
let target = match a.opt_int("target_bytes")? {
None => None,
Some(t) if t >= 1 => Some(usize::try_from(t).map_err(|_| ToolError::InvalidArgs(format!("target_bytes {t} is too large")))?),
Some(t) => return Err(ToolError::InvalidArgs(format!("target_bytes must be at least 1, not {t}"))),
};
let (mut bytes, mut r) = self.session.optimized_bytes(id, &settings, &discard).map_err(failed)?;
let mut attempts = 1;
let mut step_used = 0;
// Settings already optimized with; a rung that changes nothing is not run again.
let mut tried = vec![settings.clone()];
if let Some(t) = target {
// Stronger image settings, one rung per attempt, until the copy fits. Every attempt
// starts from the open document, so a failed one changes nothing; the number of
// attempts is fixed. The smallest copy is kept if none fits.
for (k, &(ppi, quality)) in TARGET_LADDER.iter().enumerate() {
if bytes.len() <= t {
break;
}
let mut s = settings.clone();
for img in [&mut s.color, &mut s.gray] {
img.downsample = true;
img.target_ppi = img.target_ppi.min(ppi);
img.above_ppi = img.above_ppi.min(ppi * 1.5).max(img.target_ppi);
// Only a caller who chose JPEG gets a lower quality; zip and retain stay as asked.
if let Compression::Jpeg(q) = img.compression {
img.compression = Compression::Jpeg(q.min(quality));
}
}
if tried.contains(&s) {
continue;
}
let (b2, r2) = self.session.optimized_bytes(id, &s, &discard).map_err(failed)?;
tried.push(s);
attempts += 1;
if b2.len() < bytes.len() {
(bytes, r, step_used) = (b2, r2, k + 1);
}
}
}
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 }
@@ -400,7 +442,19 @@ impl Automation {
// 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!({
let mut extra = json!({});
if let Some(t) = target {
let (ppi, quality) = step_used.checked_sub(1).and_then(|k| TARGET_LADDER.get(k)).copied().unzip();
let lossy = matches!(settings.color.compression, Compression::Jpeg(_)) || matches!(settings.gray.compression, Compression::Jpeg(_));
let quality = quality.filter(|_| lossy);
extra = json!({
"target_bytes": t,
"target_reached": bytes.len() <= t,
"attempts": attempts,
"target_settings": { "step": step_used, "max_ppi": ppi, "max_jpeg_quality": quality },
});
}
let mut out = json!({
"path": path.to_string_lossy(),
"pdf_version": pdf_version,
"object_streams": settings.effective_object_streams(),
@@ -425,7 +479,11 @@ impl Automation {
"unused_xobjects": o.unused_xobjects,
"merged_objects": r.merged,
"discarded": r.discarded.iter().map(|(h, n)| json!({ "category": h.id(), "count": n })).collect::<Vec<_>>(),
}))
});
if let (Some(o), Some(e)) = (out.as_object_mut(), extra.as_object()) {
o.extend(e.iter().map(|(k, v)| (k.clone(), v.clone())));
}
Ok(out)
}
/// A watermark or background picture: `file` (an image or a PDF) and `file_page` (1-based).
+41 -6
View File
@@ -2,8 +2,8 @@
//! (removing what they cover for good) or clear them.
use pdfcraft_engine::{
Edit, Hidden, NewAnnotation, REDACT_MAX_WORDS, REDACTION_CODE_SETS, RedactPattern, RedactionCodeSet, Shape, Style, find_pattern, rect_quad,
redact_word_list,
Edit, Hidden, NewAnnotation, REDACT_MAX_WORDS, REDACT_VALIDATORS, REDACTION_CODE_SETS, RedactPattern, RedactRegex, RedactValidator,
RedactionCodeSet, Shape, Style, find_pattern, rect_quad, redact_word_list,
};
use serde_json::{Value, json};
@@ -59,16 +59,20 @@ impl Automation {
a.get("find").is_some(),
a.get("words").is_some(),
a.get("pattern").is_some(),
a.get("regex").is_some(),
a.opt_bool("whole_pages")?.unwrap_or(false),
];
if chosen.iter().filter(|c| **c).count() != 1 {
return Err(ToolError::InvalidArgs("pass exactly one of rect (with page), find, words, pattern or whole_pages: true".into()));
return Err(ToolError::InvalidArgs("pass exactly one of rect (with page), find, words, pattern, regex or whole_pages: true".into()));
}
let case_sensitive = a.opt_bool("case_sensitive")?.unwrap_or(false);
let whole_words = a.opt_bool("whole_words")?.unwrap_or(false);
if (case_sensitive || whole_words) && a.get("find").is_none() && a.get("words").is_none() {
return Err(ToolError::InvalidArgs("case_sensitive and whole_words apply only to find or words".into()));
}
if a.get("validate").is_some() && a.get("regex").is_none() {
return Err(ToolError::InvalidArgs("validate applies only to regex".into()));
}
// Per searched word or phrase: how many marks it made.
let mut matched_words: Vec<(String, usize)> = Vec::new();
if a.get("rect").is_some() {
@@ -89,6 +93,19 @@ impl Automation {
Some(p) => Some(RedactPattern::from_id(p).ok_or_else(|| ToolError::InvalidArgs(format!("unknown pattern {p:?}")))?),
None => None,
};
let user_re = match a.opt_str("regex")? {
Some(src) => {
let validator = match a.opt_str("validate")? {
Some(v) => Some(RedactValidator::from_id(v).ok_or_else(|| {
let ids: Vec<_> = REDACT_VALIDATORS.iter().map(|v| v.id()).collect();
ToolError::InvalidArgs(format!("unknown validate {v:?}; allowed: {}", ids.join(", ")))
})?),
None => None,
};
Some(RedactRegex::new(src, validator).map_err(|e| ToolError::InvalidArgs(e.to_string()))?)
}
None => None,
};
let needles: Vec<String> = match (a.opt_str("find")?, a.get("words")) {
(Some(f), _) => vec![f.to_owned()],
(None, Some(_)) => {
@@ -108,9 +125,27 @@ impl Automation {
let texts = self.page_texts(id, &pages)?;
let info = self.doc(a)?.info.clone();
for (&p, text) in pages.iter().zip(&texts) {
let hits: Vec<(Option<usize>, _)> = match pattern {
Some(pat) => text.find_with(|chars| find_pattern(pat, chars)).into_iter().map(|h| (None, h)).collect(),
None => needles
let hits: Vec<(Option<usize>, _)> = match (&user_re, pattern) {
(Some(re), _) => {
// A page with too many matches fails the call: marking only the first ones
// would leave the rest readable after redact_apply.
let too_many = std::cell::Cell::new(false);
let found = text.find_with(|chars| {
re.find(chars).unwrap_or_else(|_| {
too_many.set(true);
Vec::new()
})
});
if too_many.get() {
return Err(ToolError::InvalidArgs(format!(
"regex has more than 10000 matches on page {}; nothing was marked. Narrow the expression so that every match can be marked",
p + 1
)));
}
found.into_iter().map(|h| (None, h)).collect()
}
(None, Some(pat)) => text.find_with(|chars| find_pattern(pat, chars)).into_iter().map(|h| (None, h)).collect(),
(None, None) => needles
.iter()
.enumerate()
.flat_map(|(i, w)| text.find_opts(w, case_sensitive, whole_words).into_iter().map(move |h| (Some(i), h)))
+1
View File
@@ -119,6 +119,7 @@ impl Automation {
"page": s.page.map(|p| p + 1),
"rect": rect,
"visible": s.visible,
"verdict_shown": s.verdict_shown,
"revision": s.revision,
"sub_filter": s.sub_filter,
"algorithm": s.algorithm,
+8 -5
View File
@@ -148,7 +148,7 @@ pub fn tools() -> Vec<ToolDef> {
"paths": {"type":"array","items":{"type":"string"},"minItems":1,"maxItems":1000},
"out_dir": {"type":"string"},
"steps": {"type":"array","items":{"type":"string","enum":["convert","ocr","optimize"]},"minItems":1,"maxItems":3,"uniqueItems":true},
"recursive": {"type":"boolean"}, "stop_on_error": {"type":"boolean"},
"recursive": {"type":"boolean"}, "stop_on_error": {"type":"boolean"}, "dry_run": {"type":"boolean"},
"ppi": {"type":"number","minimum":9,"maximum":1600},
"quality": {"type":"integer","minimum":1,"maximum":100},
"dpi": {"type":"number","minimum":72,"maximum":600},
@@ -620,7 +620,7 @@ pub fn tools() -> Vec<ToolDef> {
t(
"redact_mark",
"Mark for redaction",
"Mark content for redaction (nothing is removed until redact_apply). One of: rect [x0, y0, x1, y1] (points from the top-left of the displayed page) with page; find (text, every match); words (a list of words or phrases, every match of each; the result's matched_words says how many marks each made); pattern (phone, email, credit-card, ssn, date, iban: every match, Acrobat's Search & Redact patterns); whole_pages: true. find and words accept case_sensitive and whole_words (both default false). Select one page with page or multiple with pages (default all); do not pass both. rect requires page. overlay: text shown on the box once applied, or code_set (foia: U.S. FOIA (b)(1)(A)…(b)(9); privacy-act: U.S. Privacy Act (d)(5), (j)(1)…(k)(7)) with codes, shown as \"(b)(6), (b)(7)(C)\"; fill: box colour (default black). Undoable.",
"Mark content for redaction (nothing is removed until redact_apply). One of: rect [x0, y0, x1, y1] (points from the top-left of the displayed page) with page; find (text, every match); words (a list of words or phrases, every match of each; the result's matched_words says how many marks each made); pattern (phone, email, credit-card, ssn, date, iban: every match, Acrobat's Search & Redact patterns); regex (your own regular expression, every match, on the page text with words and lines separated by one space; Rust regex syntax: linear-time, no look-around or back-references, case-sensitive unless (?i), at most 1024 bytes, more than 10000 matches on one page fail the call, matches of the empty string are refused) with optional validate (luhn, mod97, iban: keep a match only if its checksum holds); whole_pages: true. find and words accept case_sensitive and whole_words (both default false). Select one page with page or multiple with pages (default all); do not pass both. rect requires page. overlay: text shown on the box once applied, or code_set (foia: U.S. FOIA (b)(1)(A)…(b)(9); privacy-act: U.S. Privacy Act (d)(5), (j)(1)…(k)(7)) with codes, shown as \"(b)(6), (b)(7)(C)\"; fill: box colour (default black). Undoable.",
)
.with(schema(
json!({
@@ -632,6 +632,8 @@ pub fn tools() -> Vec<ToolDef> {
"case_sensitive": { "type": "boolean", "description": "Match letter case for find or words (default false)." },
"whole_words": { "type": "boolean", "description": "Match whole words for find or words (default false)." },
"pattern": pattern_enum(),
"regex": { "type": "string", "minLength": 1, "maxLength": 1024, "description": "Regular expression (Rust regex syntax), at most 1024 bytes (maxLength counts characters, the limit is bytes); every match is marked." },
"validate": { "type": "string", "enum": ["luhn", "mod97", "iban"], "description": "With regex: keep a match only if its checksum is valid (spaces and hyphens ignored)." },
"whole_pages": { "type": "boolean" },
"pages": pages("to search or mark (default: all); mutually exclusive with page, and not valid with rect"),
"overlay": { "type": "string" },
@@ -896,7 +898,7 @@ pub fn tools() -> Vec<ToolDef> {
comment_ref(json!({ "status": { "type": "string", "enum": ["none", "accepted", "rejected", "cancelled", "completed"] }, "author": { "type": "string" } })),
&["doc", "status"],
)),
t("sign_list", "List and validate signatures", "Every signature field with its validation: status (valid, unknown = intact but the signer isn't trusted, invalid, unsigned), signer and certificate, date, reason, location, certification level, page and rect, the revision it covers and changes made after signing (none, allowed, disallowed), with Acrobat-style explanations.")
t("sign_list", "List and validate signatures", "Every signature field with its validation: status (valid, unknown = intact but the signer isn't trusted, invalid, unsigned), signer and certificate, date, reason, location, certification level, page and rect, whether PdfCraft draws that state into the signature's own appearance as displayed (verdict_shown; never written to the file), the revision it covers and changes made after signing (none, allowed, disallowed), with Acrobat-style explanations.")
.ro()
.with(schema(json!({ "doc": doc() }), &["doc"])),
t("sign_id_create", "Create a digital ID", "Create a self-signed digital ID and save it as a password-protected .p12 file (Acrobat: Configure a new digital ID ▸ Create a new digital ID ▸ Save to file). Default key: 2048-bit RSA, valid 5 years.").with(schema(
@@ -1290,7 +1292,7 @@ pub fn tools() -> Vec<ToolDef> {
"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.")
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, content not found on its page, or content that a damaged or undecodable content stream may hide or change are rejected. Undoable.")
.with(schema(json!({
"doc": doc(), "object": { "type": "integer", "minimum": 1 },
"generation": { "type": "integer", "minimum": 0, "maximum": 65535 },
@@ -1633,7 +1635,7 @@ 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. 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). mono: { downsample, ppi, above_ppi, compression: ccitt_g4|jbig2|retain } for black-and-white images and image masks (default: averaged down to 300 ppi above 450 ppi, counted in images_resampled; stored losslessly as CCITT Group 4 or JBIG2 (or 1-bit Flate, once resampled or packed from more bits) when that is smaller, up to 16 JBIG2 images sharing one symbol dictionary (/JBIG2Globals) where that is smaller still (image masks and DeviceGray images named directly, of at most 64 Mi pixels, which redaction can store again without it), Group 3 fax images, JBIG2 images, black-and-white RGB and indexed images using only palette entries 0 and 1 among them, counted in images_recompressed; retain resamples only, a CCITT image staying CCITT, a JBIG2 image JBIG2 and any other becoming Flate). Images past what one run may decode stay as they are, counted in images_refused; streams it only stores with Flate past that stay LZW, uncounted. 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.")
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). mono: { downsample, ppi, above_ppi, compression: ccitt_g4|jbig2|retain } for black-and-white images and image masks (default: averaged down to 300 ppi above 450 ppi, counted in images_resampled; stored losslessly as CCITT Group 4 or JBIG2 (or 1-bit Flate, once resampled or packed from more bits) when that is smaller, up to 16 JBIG2 images sharing one symbol dictionary (/JBIG2Globals) where that is smaller still (image masks and DeviceGray images named directly, of at most 64 Mi pixels, which redaction can store again without it), Group 3 fax images, JBIG2 images, black-and-white RGB and indexed images using only palette entries 0 and 1 among them, counted in images_recompressed; retain resamples only, a CCITT image staying CCITT, a JBIG2 image JBIG2 and any other becoming Flate). Images past what one run may decode stay as they are, counted in images_refused; streams it only stores with Flate past that stay LZW, uncounted. 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. target_bytes (optional): if the copy is larger, retry with up to 5 progressively stronger image settings (downsample to at most 110, 96, 72, 54, 36 ppi, applied to colour and grey images; images set to JPEG also get JPEG quality at most 45, 35, 28, 20, 12, while zip and retain images keep their encoding and only get the lower ppi) and stop at the first copy that fits; reports target_reached, attempts and target_settings, and writes the smallest copy with target_reached false when none fits. Without it nothing changes. The open document is unchanged.")
.cmd("optimize.advanced")
.with(schema(
json!({
@@ -1645,6 +1647,7 @@ pub fn tools() -> Vec<ToolDef> {
"color": { "type": "object" },
"gray": { "type": "object" },
"mono": { "type": "object" },
"target_bytes": { "type": "integer", "minimum": 1 },
"discard_thumbnails": { "type": "boolean" },
"discard_alternate_images": { "type": "boolean" },
"discard_tags": { "type": "boolean" },
+170
View File
@@ -4818,6 +4818,34 @@ fn redacting_through_tools() {
assert!(matches!(a.call("redact_mark", &json!({ "doc": doc })), Err(ToolError::InvalidArgs(_))));
}
#[test]
fn redacting_with_a_caller_regex_through_tools() {
let dir = workdir("redact-regex");
std::fs::write(
dir.join("ids.txt"),
"Ref 1 85 05 78 006 084 36 end\nRef 2 91 12 34 567 890 12 end\nCard 4539 1488 0343 6467 and 4539 1488 0343 6468",
)
.unwrap();
let mut a = auto(&dir);
let doc = ok(&mut a, "doc_create", json!({ "from": "text", "path": "ids.txt" }))["doc"].as_u64().unwrap();
let bad = |a: &mut Automation, args: Value| matches!(a.call("redact_mark", &args), Err(ToolError::InvalidArgs(_)));
assert!(bad(&mut a, json!({ "doc": doc, "regex": "(unclosed" })));
assert!(bad(&mut a, json!({ "doc": doc, "regex": "a*" })));
assert!(bad(&mut a, json!({ "doc": doc, "regex": "x".repeat(2000) })));
assert!(bad(&mut a, json!({ "doc": doc, "regex": "x", "pattern": "ssn" })));
assert!(bad(&mut a, json!({ "doc": doc, "regex": "x", "validate": "crc" })));
assert!(bad(&mut a, json!({ "doc": doc, "find": "x", "validate": "luhn" })));
assert!(matches!(a.call("redact_mark", &json!({ "doc": doc, "regex": "Z{3}" })), Err(ToolError::Failed(_))));
let r = ok(&mut a, "redact_mark", json!({ "doc": doc, "regex": r"\d \d\d \d\d \d\d \d{3} \d{3} \d\d" }));
assert_eq!(r["marked"].as_u64(), Some(2));
let r = ok(&mut a, "redact_mark", json!({ "doc": doc, "regex": r"\d{4}( \d{4}){3}", "validate": "luhn" }));
assert_eq!(r["marked"].as_u64(), Some(1), "only the number with a valid checksum");
ok(&mut a, "redact_apply", json!({ "doc": doc }));
let text = page_text(&mut a, doc)[0].clone();
assert!(!text.contains("85 05") && !text.contains("91 12") && !text.contains("6467"), "{text}");
assert!(text.contains("6468"), "{text}");
}
#[test]
/// Mark, apply and save remove the complete international number while retaining labels and controls.
fn redacting_italian_international_slash_numbers_through_tools() {
@@ -6899,6 +6927,43 @@ fn a_dynamic_xfa_forms_signature_box_is_signed_under_its_som_path() {
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn named_layer_verdicts_are_reported_and_rendered_through_tools() {
use pdfcraft_cos::{Dict, Document, Lexer, ObjRef, Object, SaveOptions, Stream};
let dir = workdir("named-layer-verdict");
let mut cos = Document::open(std::sync::Arc::new(fixture(1))).unwrap();
let dict = |text: &str| Lexer::new(text.as_bytes(), 0).object().unwrap().as_dict().unwrap().clone();
let form = |resources: Dict, ops: &str| {
let mut d = dict("<< /Type /XObject /Subtype /Form /BBox [0 0 100 100] >>");
d.set(b"Resources".to_vec(), resources);
Stream::from_raw(d, ops.as_bytes().to_vec())
};
let blank = cos.add(form(Dict::new(), ""));
let layers = dict(&format!("<< /XObject << /n1 {blank} /n3 {blank} >> >>"));
let layer_form = cos.add(form(layers, "/n1 Do /n3 Do"));
let normal = cos.add(form(dict(&format!("<< /XObject << /FRM {layer_form} >> >>")), "/FRM Do"));
// Deliberately malformed CMS: an invalid signature still gets the redrawn invalid state.
let value = cos.add(dict("<< /Type /Sig /SubFilter /ETSI.CAdES.detached /ByteRange [0 0 0 0] /Contents <00> >>"));
let widget = cos
.add(dict(&format!("<< /FT /Sig /T (Signature1) /Subtype /Widget /F 4 /Rect [50 50 150 150] /P 4 0 R /V {value} /AP << /N {normal} >> >>")));
cos.update_dict(ObjRef::new(4, 0), |p| p.set(b"Annots".to_vec(), vec![Object::Ref(widget)])).unwrap();
cos.update_dict(cos.root().unwrap(), |root| root.set(b"AcroForm".to_vec(), dict(&format!("<< /Fields [{widget}] >>")))).unwrap();
let original = pdfcraft_cos::write_full(&cos, &SaveOptions::default()).unwrap();
std::fs::write(dir.join("named.pdf"), &original).unwrap();
let mut a = auto(&dir);
let doc = ok(&mut a, "doc_open", json!({"path": "named.pdf"}))["doc"].as_u64().unwrap();
let list = ok(&mut a, "sign_list", json!({"doc": doc}));
assert_eq!(list["signatures"][0]["status"], "invalid");
assert_eq!(list["signatures"][0]["verdict_shown"], true);
let rendered = a.call("page_render", &json!({"doc": doc, "page": 1, "dpi": 72})).unwrap();
let Content::Png { data, .. } = &rendered[0] else { panic!("expected a PNG") };
let pixels = image::load_from_memory_with_format(data, image::ImageFormat::Png).unwrap().to_rgba8();
let red = pixels.pixels().filter(|p| p.0.iter().zip([0xD7, 0x37, 0x3F]).all(|(a, b)| a.abs_diff(b) < 30)).count();
assert!(red > 100, "the invalid state is drawn: {red} red pixels");
ok(&mut a, "doc_save", json!({"doc": doc, "path": "saved.pdf", "full": false}));
assert_eq!(std::fs::read(dir.join("saved.pdf")).unwrap(), original, "the drawn state never enters saves");
}
#[test]
fn digital_ids_signing_and_validation_through_tools() {
let dir = workdir("signing");
@@ -6957,6 +7022,8 @@ fn sign_document_and_verify_trust(a: &mut Automation, dir: &Path) -> u64 {
assert_eq!(t["trusted"].as_array().unwrap().len(), 1);
let list = ok(a, "sign_list", json!({ "doc": doc }));
assert_eq!((list["all_valid"].as_bool(), list["signatures"][0]["status"].as_str()), (Some(true), Some("valid")));
// PdfCraft's own appearance has no status layers to draw into: only the page badge shows it.
assert_eq!(list["signatures"][0]["verdict_shown"], false);
ok(a, "comment_add", json!({ "doc": doc, "page": 1, "type": "note", "at": [20, 20], "contents": "ok" }));
let s = &ok(a, "sign_list", json!({ "doc": doc }))["signatures"][0];
assert_eq!((s["status"].as_str(), s["modification"].as_str()), (Some("valid"), Some("allowed")));
@@ -7565,6 +7632,63 @@ fn a_page_printed_in_strips_gets_small_through_tools() {
assert!(matches!(a.call("doc_optimize", &json!({ "doc": doc, "path": "x.pdf", "preset": "tiny" })), Err(ToolError::InvalidArgs(_))));
}
#[test]
fn optimizing_to_a_target_size() {
// Dropped at the end of the test, also when an assertion fails.
let tmp = tempfile::TempDir::new().unwrap();
let dir = tmp.path().to_path_buf();
let (w, h) = (2400u32, 1600u32);
let px: Vec<u8> = (0..w * h)
.flat_map(|i| {
let (x, y) = (i % w, i / w);
[(x * 255 / w) as u8 ^ ((x * y) & 15) as u8, (y * 255 / h) as u8, ((x + y) & 255) as u8]
})
.collect();
let mut jpeg = Vec::new();
let mut enc = image::codecs::jpeg::JpegEncoder::new_with_quality(&mut jpeg, 95);
enc.set_pixel_density(image::codecs::jpeg::PixelDensity::dpi(600));
enc.encode(&px, w, h, image::ExtendedColorType::Rgb8).unwrap();
std::fs::write(dir.join("photo.jpg"), &jpeg).unwrap();
let mut a = auto(&dir);
let doc = ok(&mut a, "doc_create", json!({ "from": "images", "paths": ["photo.jpg"] }))["doc"].as_u64().unwrap();
// Without a target nothing changes: no target fields.
let base = ok(&mut a, "doc_optimize", json!({ "doc": doc, "path": "base.pdf" }));
assert!(base.get("target_reached").is_none(), "{base}");
let base_len = base["bytes_after"].as_u64().unwrap();
// A target below the default result is met by a stronger step.
let r = ok(&mut a, "doc_optimize", json!({ "doc": doc, "path": "fit.pdf", "target_bytes": base_len - 1 }));
assert_eq!(r["target_reached"], true, "{r}");
assert!(r["bytes_after"].as_u64().unwrap() < base_len, "{r}");
assert!(r["target_settings"]["step"].as_u64().unwrap() >= 1, "{r}");
assert_eq!(std::fs::metadata(dir.join("fit.pdf")).unwrap().len(), r["bytes_after"].as_u64().unwrap());
// A target already met by the first attempt tries nothing more.
let r = ok(&mut a, "doc_optimize", json!({ "doc": doc, "path": "easy.pdf", "target_bytes": base_len }));
assert_eq!((r["target_reached"].as_bool(), r["attempts"].as_u64()), (Some(true), Some(1)), "{r}");
// An impossible target: bounded attempts, smallest copy written, said plainly.
let r = ok(&mut a, "doc_optimize", json!({ "doc": doc, "path": "tiny.pdf", "target_bytes": 1 }));
assert_eq!((r["target_reached"].as_bool(), r["attempts"].as_u64()), (Some(false), Some(6)), "{r}");
assert!(r["bytes_after"].as_u64().unwrap() < base_len, "{r}");
assert!(std::fs::metadata(dir.join("tiny.pdf")).is_ok());
// The open document is untouched by the failed attempts, and bad targets are refused.
let again = ok(&mut a, "doc_optimize", json!({ "doc": doc, "path": "again.pdf" }));
assert_eq!(again["bytes_after"].as_u64().unwrap(), base_len);
assert!(matches!(a.call("doc_optimize", &json!({ "doc": doc, "path": "x.pdf", "target_bytes": 0 })), Err(ToolError::InvalidArgs(_))));
// A caller who asked for lossless images keeps them: retries only tighten the ppi, no JPEG quality.
let lossless = json!({ "compression": "zip" });
let r = ok(&mut a, "doc_optimize", json!({ "doc": doc, "path": "zip.pdf", "color": lossless, "gray": lossless, "target_bytes": 1 }));
assert_eq!(r["attempts"].as_u64(), Some(6), "{r}");
assert!(r["target_settings"]["max_ppi"].is_number() && r["target_settings"]["max_jpeg_quality"].is_null(), "{r}");
// A JPEG caller gets the quality step.
let r = ok(&mut a, "doc_optimize", json!({ "doc": doc, "path": "jpg.pdf", "target_bytes": 1 }));
assert!(r["target_settings"]["max_jpeg_quality"].is_number(), "{r}");
// Settings already at the ladder's floor leave every rung equal to the first run: no retries.
let floor = json!({ "ppi": 9, "above_ppi": 9, "compression": "jpeg", "quality": 1 });
let r = ok(&mut a, "doc_optimize", json!({ "doc": doc, "path": "floor.pdf", "color": floor, "gray": floor, "target_bytes": 1 }));
assert_eq!((r["target_reached"].as_bool(), r["attempts"].as_u64()), (Some(false), Some(1)), "{r}");
// Confinement still applies.
assert!(a.call("doc_optimize", &json!({ "doc": doc, "path": "../out.pdf", "target_bytes": 1000 })).is_err());
}
#[test]
fn initial_view_through_tools() {
let dir = workdir("initial-view");
@@ -8287,6 +8411,52 @@ BT /F1 11 Tf 20 20 Td (Total due: 150.00) Tj ET";
assert!(rendered.iter().any(|c| matches!(c, Content::Png { .. })));
}
/// #5149: a two-column, two-row table drawn with ruled lines reaches Word as a table with its
/// rules, not as four paragraphs one under another.
#[test]
fn exporting_a_ruled_two_by_two_table_to_word_keeps_the_table() {
let dir = workdir("ruled-table-word");
let content = "0.5 w 20 270 m 300 270 l S 20 245 m 300 245 l S 20 220 m 300 220 l S \
20 220 m 20 270 l S 160 220 m 160 270 l S 300 220 m 300 270 l S \
BT /F1 11 Tf 25 253 Td (Name) Tj 140 0 Td (Value) Tj -140 -25 Td (Alpha) Tj 140 0 Td (One) Tj ET \
BT /F1 11 Tf 20 150 Td (A paragraph after the table.) Tj ET";
let stream = format!("<< /Length {} >>\nstream\n{content}\nendstream", content.len());
let objs = [
"<< /Type /Catalog /Pages 2 0 R >>",
"<< /Type /Pages /Kids [3 0 R] /Count 1 >>",
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 320 300] /Contents 4 0 R /Resources << /Font << /F1 5 0 R >> >> >>",
stream.as_str(),
"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>",
];
std::fs::write(dir.join("table.pdf"), pdf_of(&objs)).unwrap();
let mut a = auto(&dir);
let doc = ok(&mut a, "doc_open", json!({ "path": "table.pdf" }))["doc"].as_u64().unwrap();
ok(&mut a, "doc_export_office", json!({ "doc": doc, "path": "table.docx" }));
let zip = std::fs::read(dir.join("table.docx")).unwrap();
let mut at = 0;
let mut xml = String::new();
while zip[at..].starts_with(b"PK\x03\x04") {
let size = u32::from_le_bytes(zip[at + 18..at + 22].try_into().unwrap()) as usize;
let len = u16::from_le_bytes(zip[at + 26..at + 28].try_into().unwrap()) as usize;
let data = at + 30 + len;
if &zip[at + 30..data] == b"word/document.xml" {
std::io::Read::read_to_string(&mut flate2::read::DeflateDecoder::new(&zip[data..data + size]), &mut xml).unwrap();
break;
}
at = data + size;
}
assert_eq!(xml.matches("<w:tbl>").count(), 1, "the ruled grid is a table: {xml}");
let table = xml.split_once("<w:tbl>").and_then(|(_, t)| t.split_once("</w:tbl>")).map(|(t, _)| t).unwrap();
assert_eq!(table.matches("<w:tr>").count(), 2, "{table}");
for word in ["Name", "Value", "Alpha", "One"] {
assert_eq!(table.matches(&format!(">{word}</w:t>")).count(), 1, "{word} is a cell: {xml}");
assert_eq!(xml.matches(&format!(">{word}</w:t>")).count(), 1, "{word} is written once");
}
assert!(table.contains("w:val=\"single\""), "the drawn rules become borders: {table}");
assert!(!table.contains("A paragraph after the table."));
assert_eq!(xml.matches(">A paragraph after the table.</w:t>").count(), 1);
}
/// #4158: a word set in italic inside a sentence ("Before *Chevron* after.") reaches Word as an
/// italic run of the sentence's paragraph, not as a paragraph of its own between two halves.
#[test]
+58
View File
@@ -238,3 +238,61 @@ fn mcp_batch_errors_keep_the_structured_per_file_report() {
assert_eq!(report["result"]["isError"], true, "{report}");
assert_eq!(report["result"]["structuredContent"]["failed"], 1);
}
#[test]
fn dry_run_planned_files_are_not_counted_as_skipped() {
let dir = tempfile::tempdir().unwrap();
std::fs::create_dir_all(dir.path().join("input/sub")).unwrap();
std::fs::create_dir_all(dir.path().join("out")).unwrap();
let original = pdf();
std::fs::write(dir.path().join("input/a.pdf"), &original).unwrap();
std::fs::write(dir.path().join("input/sub/a.pdf"), &original).unwrap();
std::fs::write(dir.path().join("out/a.pdf"), b"precious").unwrap();
let mut auto = Automation::new().with_root(dir.path()).unwrap();
let report = result(&mut auto, json!({"paths":["input","input/sub"],"steps":["optimize"],"out_dir":"out","dry_run":true}));
assert_eq!(report["dry_run"], true, "{report}");
assert_eq!(report["completed"], 0, "{report}");
assert_eq!(report["failed"], 0, "{report}");
assert_eq!(report["skipped"], 0, "planned files are not skipped: {report}");
let files = report["files"].as_array().unwrap();
assert_eq!(files.len(), 2, "{report}");
assert!(files.iter().all(|file| file["status"] == "planned"), "{report}");
assert!(files.iter().all(|file| file["steps"] == json!(["optimize"])), "planned files list the ordered steps: {report}");
assert!(files[0]["output"].as_str().unwrap().ends_with("out/a (2).pdf"), "existing output gets the publish collision name: {report}");
assert!(files[1]["output"].as_str().unwrap().ends_with("out/a (3).pdf"), "later planned files reserve their names: {report}");
assert_eq!(std::fs::read(dir.path().join("out/a.pdf")).unwrap(), b"precious");
assert!(!dir.path().join("out/a (2).pdf").exists(), "dry run writes nothing: {report}");
#[cfg(unix)]
{
// An output subfolder that resolves outside out_dir is a per-file error:
// it counts as failed, honors stop_on_error, and later files are skipped.
for outside_root in [false, true] {
let dir = tempfile::tempdir().unwrap();
let outside = tempfile::tempdir().unwrap();
std::fs::create_dir_all(dir.path().join("input/sub")).unwrap();
std::fs::create_dir_all(dir.path().join("out")).unwrap();
std::fs::write(dir.path().join("input/a.pdf"), pdf()).unwrap();
std::fs::write(dir.path().join("input/sub/page.pdf"), pdf()).unwrap();
std::fs::write(dir.path().join("input/z.pdf"), pdf()).unwrap();
let target = if outside_root { outside.path().to_path_buf() } else { dir.path().join("outside") };
if !outside_root {
std::fs::create_dir(&target).unwrap();
}
std::os::unix::fs::symlink(&target, dir.path().join("out/sub")).unwrap();
let mut auto = Automation::new().with_root(dir.path()).unwrap();
let report = result(
&mut auto,
json!({"paths":["input"],"steps":["optimize"],"out_dir":"out","recursive":true,"dry_run":true,"stop_on_error":true}),
);
assert_eq!(report["failed"], 1, "preview target failure is per-file: {report}");
assert_eq!(report["stopped"], true, "{report}");
assert_eq!(report["skipped"], 1, "only the unprocessed file is skipped: {report}");
let files = report["files"].as_array().unwrap();
assert_eq!(files.len(), 3, "{report}");
assert_eq!(files[0]["status"], "planned", "{report}");
assert_eq!(files[1]["status"], "error", "{report}");
assert_eq!(files[2]["status"], "skipped", "stop_on_error leaves later files unplanned: {report}");
assert!(!dir.path().join("out/a.pdf").exists(), "dry run writes nothing: {report}");
}
}
}
+189 -36
View File
@@ -11,7 +11,9 @@ use crate::{CosError, Document, ObjRef, Object, Stream};
/// 16 ns, so this is 2 to 5 minutes, and about as long again for what an operation does with the
/// pixels. A page scanned at 300 dpi takes about 17 million, 8.4 for its pixels and that again to
/// decode them, so this alone reads about 1,000 of them. A byte into or out of a filter is a step
/// too, and takes less: 3 ns at most, or up to 19 ns through a predictor on samples of a bit.
/// too, and takes less: 3 ns at most, or up to 19 ns through a predictor on samples of a bit. A
/// byte Flate reads is [`pdfcraft_filters::FLATE_READ_WORK`] steps besides, since inflating blocks
/// that make nothing takes up to 21 ns a byte: about 7 ns a step.
const IMAGE_WORK: u64 = 1 << 34;
/// The steps each byte of the file adds to [`IMAGE_WORK`], so that a long scan is read whole: such a
/// page pays for itself with about 2 KB of the file, about the smallest a page of text is stored
@@ -38,9 +40,9 @@ const JPEG_WORK: u64 = 2;
/// and images can share one, so reading it again for each has to count.
const JPEG_READ_WORK: u64 = 4;
/// A stream decode within a byte bound, with the bytes its filter stages decoded: the data or
/// the error, each with that count.
type Decoder = fn(&Stream, usize) -> Result<(Vec<u8>, usize), (FilterError, usize)>;
/// A stream decode within a byte bound, with the bytes its filter stages decoded: the data and
/// whether it stopped at damage, or the error, each with that count.
type Decoder = fn(&Stream, usize) -> Result<(Vec<u8>, bool, usize), (FilterError, usize)>;
/// What one operation over a document's images may still spend decoding them: exporting them,
/// optimizing them, and storing LZW streams with Flate as it does, clearing them for redaction.
@@ -263,45 +265,57 @@ impl DecodeBudget {
}
/// `stream` decoded like [`Stream::decoded`], charged to the allowance. Fails, without
/// decoding, once the allowance is spent.
/// decoding, once the allowance is spent. A stream damaged partway gives what decoded before
/// the damage, so code that writes the stream back reads it with
/// [`DecodeBudget::decode_with_damage`] instead.
pub fn decode(&mut self, stream: &Stream) -> Result<Vec<u8>, CosError> {
self.charge(stream, usize::MAX, Stream::decoded_within_counted)
self.charge(stream, usize::MAX, Stream::decoded_within_counted).map(|(data, _)| data)
}
/// Like [`DecodeBudget::decode`], for a stream with a tighter bound of its own: decoding
/// past `max` bytes is an error that charges `max`, the work it took to find out.
pub fn decode_within(&mut self, stream: &Stream, max: usize) -> Result<Vec<u8>, CosError> {
self.charge(stream, max, Stream::decoded_within_counted)
self.charge(stream, max, Stream::decoded_within_counted).map(|(data, _)| data)
}
/// [`DecodeBudget::decode_within`] (`usize::MAX` for no bound of its own), with the stream's
/// `/DecodeParms` given by reference read in `doc`, also saying whether the stream is damaged:
/// `true` when a filter stopped at corrupt data, so the bytes are only what decoded before it.
/// A stream written back from them loses everything after the damage, which other readers may
/// still read.
pub fn decode_with_damage(&mut self, doc: &Document, stream: &Stream, max: usize) -> Result<(Vec<u8>, bool), CosError> {
self.charge(&doc.decoding_view(stream), max, Stream::decoded_within_counted)
}
/// `stream` decoded like [`Stream::decoded_strict`] (any corruption is an error), charged to
/// the allowance.
pub fn decode_strict(&mut self, stream: &Stream) -> Result<Vec<u8>, CosError> {
self.charge(stream, usize::MAX, Stream::decoded_strict_within_counted)
/// the allowance, with its `/DecodeParms` given by reference read in `doc`.
pub fn decode_strict(&mut self, doc: &Document, stream: &Stream) -> Result<Vec<u8>, CosError> {
let strict: Decoder = |s, max| s.decoded_strict_within_counted(max).map(|(data, spent)| (data, false, spent));
self.charge(&doc.decoding_view(stream), usize::MAX, strict).map(|(data, _)| data)
}
/// Decodes `stream` within `max` and the allowance, charging what every filter stage
/// decoded: a stage's output counts even when a later stage shrinks it, and a corrupt stream
/// pays for the bytes decoded before the error, so referencing a stream again and again
/// spends the allowance by the work each decode does.
fn charge(&mut self, stream: &Stream, max: usize, decode: Decoder) -> Result<Vec<u8>, CosError> {
fn charge(&mut self, stream: &Stream, max: usize, decode: Decoder) -> Result<(Vec<u8>, bool), CosError> {
if self.bytes == 0 && !stream.raw.is_empty() {
return Err(CosError::Filter(FilterError::LimitExceeded(self.limit).to_string()));
}
if max < self.bytes {
let result = decode(stream, max);
let spent = match &result {
Ok((_, spent)) => *spent,
Ok((_, _, spent)) => *spent,
Err((FilterError::LimitExceeded(_), _)) => max,
Err((_, spent)) => *spent,
};
self.bytes = self.bytes.saturating_sub(spent);
return result.map(|(data, _)| data).map_err(|(e, _)| CosError::Filter(e.to_string()));
return result.map(|(data, damaged, _)| (data, damaged)).map_err(|(e, _)| CosError::Filter(e.to_string()));
}
match decode(stream, self.bytes) {
Ok((data, spent)) => {
Ok((data, damaged, spent)) => {
self.bytes = self.bytes.saturating_sub(spent);
Ok(data)
Ok((data, damaged))
}
Err((FilterError::LimitExceeded(_), _)) => {
self.bytes = 0;
@@ -332,17 +346,24 @@ impl DecodeBudget {
self.seen.insert(r)
}
/// Each stream `contents` names, decoded against the allowance, in order. `contents` is a
/// page's `/Contents`: one stream, or an array whose non-stream entries are left out.
/// A stream that fails to decode, or arrives after the allowance is spent, is an `Err` in its
/// place, so the caller chooses between skipping it and giving up.
/// Each stream `contents` names, decoded against the allowance, in order, its `/DecodeParms`
/// given by reference read in `doc`. `contents` is a page's `/Contents`: one stream, or an
/// array whose non-stream entries are left out. A stream that fails to decode, or arrives
/// after the allowance is spent, is an `Err` in its place, so the caller chooses between
/// skipping it and giving up.
pub fn decode_contents(&mut self, doc: &Document, contents: &Object) -> Vec<Result<Vec<u8>, CosError>> {
self.decode_contents_with_damage(doc, contents).into_iter().map(|read| read.map(|(data, _)| data)).collect()
}
/// [`DecodeBudget::decode_contents`], each stream also saying whether it is damaged partway
/// ([`DecodeBudget::decode_with_damage`], which reads `/DecodeParms` given by reference).
pub fn decode_contents_with_damage(&mut self, doc: &Document, contents: &Object) -> Vec<Result<(Vec<u8>, bool), CosError>> {
match &*doc.resolve(contents) {
Object::Stream(s) => vec![self.decode(s)],
Object::Stream(s) => vec![self.decode_with_damage(doc, s, usize::MAX)],
Object::Array(list) => list
.iter()
.filter_map(|entry| match &*doc.resolve(entry) {
Object::Stream(s) => Some(self.decode(s)),
Object::Stream(s) => Some(self.decode_with_damage(doc, s, usize::MAX)),
_ => None,
})
.collect(),
@@ -367,6 +388,11 @@ mod image_tests {
Stream::from_raw(dict, pdfcraft_filters::encode_jbig2_generic(&[0xFF; 4], 16, 2).unwrap())
}
/// What a Flate stage pays to read `n` bytes, besides what it makes.
fn read(n: usize) -> u64 {
pdfcraft_filters::FLATE_READ_WORK * n as u64
}
/// Each image spends what it took from one allowance, and those past it are refused and
/// counted, whatever their filters. What can't be decoded here costs nothing, and fails
/// without being one of these.
@@ -413,7 +439,7 @@ mod image_tests {
let mut dict = Dict::new();
dict.set(b"Filter".to_vec(), Object::Array(vec![Object::name("FlateDecode"), Object::name("FlateDecode")]));
let bomb = Stream::from_raw(dict, pdfcraft_filters::encode_flate(&inner));
let cost = (bomb.raw.len() + inner.len() + samples.len()) as u64;
let cost = (bomb.raw.len() + inner.len() + samples.len()) as u64 + read(bomb.raw.len()) + read(inner.len());
let mut budget = ImageBudget::with_work(2 * cost + 1);
for left in [cost + 1, 1] {
assert_eq!(budget.decode(&doc, &bomb, 1 << 20).unwrap(), samples);
@@ -442,17 +468,17 @@ mod image_tests {
let image = behind(pdfcraft_filters::encode_flate(&alone.raw));
let mut budget = ImageBudget::with_work(u64::MAX);
assert_eq!(budget.decode(&doc, &image, 1 << 20).unwrap(), samples);
assert_eq!(u64::MAX - budget.work_left(), decoding + (image.raw.len() + alone.raw.len()) as u64);
assert_eq!(u64::MAX - budget.work_left(), decoding + (image.raw.len() + alone.raw.len()) as u64 + read(image.raw.len()));
// Past this image's limit: an error, with what finding out took paid and the rest left.
let bomb = behind(pdfcraft_filters::encode_flate(&vec![0; 1 << 16]));
let mut budget = ImageBudget::with_work(u64::MAX);
assert!(budget.decode(&doc, &bomb, 1000).is_err());
assert_eq!(u64::MAX - budget.work_left(), bomb.raw.len() as u64 + 1000);
assert_eq!(u64::MAX - budget.work_left(), bomb.raw.len() as u64 + read(bomb.raw.len()) + 1000);
assert_eq!(budget.refused(), 0, "that image's limit isn't the run's");
// A small allowance is a limit too: it stops there, and the image is refused.
let mut budget = ImageBudget::with_work(bomb.raw.len() as u64 + 10);
let mut budget = ImageBudget::with_work(bomb.raw.len() as u64 + read(bomb.raw.len()) + 10);
assert!(budget.decode(&doc, &bomb, 1 << 20).is_err());
assert_eq!((budget.work_left(), budget.refused()), (0, 1));
}
@@ -492,7 +518,7 @@ mod image_tests {
let doc = Document::open(std::sync::Arc::new(file)).unwrap();
let image = doc.get(doc.root().unwrap()).as_dict().unwrap().reference(b"Image").unwrap();
let s = stream(&doc, image);
let filters = (raw.len() + skipped.len()) as u64;
let filters = (raw.len() + skipped.len()) as u64 + read(raw.len());
assert_eq!(spent(&doc, &s), first, "the first read undoes them");
assert_eq!(spent(&doc, &s), first - filters, "kept");
@@ -507,7 +533,7 @@ mod image_tests {
let image = jbig2(Some(Object::Dict(parms)));
let mut budget = ImageBudget::with_work(u64::MAX);
assert!(budget.decode(&doc, &image, 1 << 20).unwrap_err().to_string().contains("globals"));
assert_eq!(u64::MAX - budget.work_left(), (over.len() + crate::MAX_JBIG2_GLOBALS) as u64);
assert_eq!(u64::MAX - budget.work_left(), (over.len() + crate::MAX_JBIG2_GLOBALS) as u64 + read(over.len()));
assert_eq!(budget.refused(), 0);
}
@@ -528,7 +554,7 @@ mod image_tests {
dict.set(b"DecodeParms".to_vec(), Object::Array(vec![Object::Null, Object::Dict(parms)]));
let image = Stream::from_raw(dict, pdfcraft_filters::encode_flate(&coded));
let pixels = u64::from(w) * u64::from(h);
let cost = (image.raw.len() + coded.len() + 4 * coded.len() + 512 * h as usize) as u64 + pixels;
let cost = (image.raw.len() + coded.len() + 4 * coded.len() + 512 * h as usize) as u64 + read(image.raw.len()) + pixels;
let mut budget = ImageBudget::with_work(cost);
assert_eq!(budget.decode(&doc, &image, 1 << 20).unwrap().len(), 512 * h as usize);
assert_eq!(budget.work_left(), 0, "exactly that");
@@ -553,7 +579,7 @@ mod image_tests {
};
let rows = vec![0xFFu8; 512 * 1024];
let flate = blank(Some("FlateDecode"), pdfcraft_filters::encode_flate(&rows));
let cost = (flate.raw.len() + rows.len()) as u64 + 4096 * 1024;
let cost = (flate.raw.len() + rows.len()) as u64 + read(flate.raw.len()) + 4096 * 1024;
let mut budget = ImageBudget::with_work(cost);
assert_eq!(budget.decode(&doc, &flate, 1 << 24).unwrap(), rows);
assert_eq!((budget.work_left(), budget.refused()), (0, 0), "exactly that");
@@ -590,6 +616,36 @@ mod image_tests {
assert_eq!((budget.work_left(), budget.refused()), (0, 1));
}
/// What Flate reads is priced for blocks that make nothing, and an image an encoder made pays
/// little for it: a scan-like picture stored in under half its size costs no more than half
/// again its bytes, samples and pixels. Redaction decodes a picture once for each page that draws it, so
/// a letterhead on hundreds of pages has to fit about as often as it did unpriced (here, at
/// most half again the cost).
#[test]
fn an_image_an_encoder_made_pays_little_for_its_reading() {
let doc = Document::new_empty();
let mut seed = 0x2545_F491_4F6C_DD1Du64;
let samples: Vec<u8> = (0..256 * 256usize)
.map(|i| {
seed ^= seed << 13;
seed ^= seed >> 7;
seed ^= seed << 17;
((i % 256) as u8 / 16) ^ (seed as u8 & 3)
})
.collect();
let mut dict = Dict::new();
dict.set(b"Width".to_vec(), Object::Int(256));
dict.set(b"Height".to_vec(), Object::Int(256));
let image = Stream::flate(dict, &samples);
assert!(image.raw.len() * 2 < samples.len(), "stored smaller: {}", image.raw.len());
let unpriced = (image.raw.len() + samples.len()) as u64 + 256 * 256;
let mut budget = ImageBudget::with_work(u64::MAX);
budget.decode(&doc, &image, 1 << 20).unwrap();
let paid = u64::MAX - budget.work_left();
assert_eq!(paid, unpriced + read(image.raw.len()));
assert!(2 * paid <= 3 * unpriced, "{paid} steps against {unpriced}");
}
/// An image pays for the pixels its data holds, not those its size declares: one claiming
/// 131072 by 131072 pixels with a few bytes of Flate costs what those bytes give, and the
/// images after it are decoded as they would be without it.
@@ -609,8 +665,8 @@ mod image_tests {
budget.decode(&doc, s, 1 << 24).unwrap();
u64::MAX - budget.work_left()
};
assert_eq!(cost(&claims), (claims.raw.len() + 16 + 16 * 8) as u64, "its bytes, and a pixel a bit of them");
assert_eq!(cost(&image), (image.raw.len() + 64 * 64) as u64 + 64 * 64, "its bytes, and its pixels");
assert_eq!(cost(&claims), (claims.raw.len() + 16 + 16 * 8) as u64 + read(claims.raw.len()), "its bytes, and a pixel a bit of them");
assert_eq!(cost(&image), (image.raw.len() + 64 * 64) as u64 + read(image.raw.len()) + 64 * 64, "its bytes, and its pixels");
for decode in [ImageBudget::decode, ImageBudget::decode_filters] {
let mut budget = ImageBudget::with_work(cost(&claims) + cost(&image));
assert_eq!(decode(&mut budget, &doc, &claims, 1 << 24).unwrap(), [0; 16]);
@@ -627,7 +683,7 @@ mod image_tests {
let samples = vec![7u8; 1000];
let raw = pdfcraft_filters::encode_flate(&samples);
let chain = [(Filter::Flate, Params::default())];
let cost = (raw.len() + samples.len()) as u64;
let cost = (raw.len() + samples.len()) as u64 + read(raw.len());
let mut budget = ImageBudget::with_work(cost + 10);
assert_eq!(budget.decode_chain(&chain, &raw, 1 << 20).unwrap(), samples);
assert_eq!(budget.work_left(), 10);
@@ -664,7 +720,7 @@ mod image_tests {
assert_eq!(budget.decode_filters(&doc, &image, 1 << 20).unwrap(), rows);
let cost = u64::MAX - budget.work_left();
// The tag byte of each of its 100 rows counts, which the predictor takes off.
assert_eq!(cost, (image.raw.len() + rows.len() + 100) as u64);
assert_eq!(cost, (image.raw.len() + rows.len() + 100) as u64 + read(image.raw.len()));
let mut budget = ImageBudget::with_work(cost - 1);
assert!(budget.decode_filters(&doc, &image, 1 << 20).is_err());
assert_eq!((budget.work_left(), budget.refused()), (0, 1));
@@ -769,7 +825,7 @@ mod tests {
assert_eq!(budget.remaining(), 0);
let mut budget = DecodeBudget::new((1 << 20) - 1, 1);
let Object::Stream(stream) = &*doc.get(bomb) else { panic!("not a stream") };
assert!(budget.decode_strict(stream).is_err());
assert!(budget.decode_strict(&doc, stream).is_err());
assert_eq!(budget.remaining(), 0);
let mut budget = DecodeBudget::new(10 << 20, 1);
@@ -793,14 +849,111 @@ mod tests {
let corrupt = Stream::from_raw(whole.dict.clone(), whole.raw.get(..cut).unwrap_or_default().to_vec());
let partial = corrupt.decoded().map(|d| d.len()).unwrap_or(0);
assert!(partial > 0, "a cut flate stream decodes in part");
let doc = Document::new_empty();
let mut budget = DecodeBudget::new(10 << 20, 1);
assert!(budget.decode_strict(&corrupt).is_err());
assert!(budget.decode_strict(&doc, &corrupt).is_err());
assert_eq!(budget.remaining(), (10 << 20) - partial);
let mut budget = DecodeBudget::new(10 << 20, 1);
assert!(budget.decode_within(&corrupt, 1 << 30).is_ok());
assert_eq!(budget.remaining(), (10 << 20) - partial);
}
/// A stream damaged partway decodes to what came before the damage, and says so, so that code
/// writing it back can leave it as it is. What every reader takes is no damage: a missing
/// checksum, no filter at all.
#[test]
fn a_stream_damaged_partway_says_so() {
let doc = Document::new_empty();
let read = |budget: &mut DecodeBudget, s: &Stream, max| budget.decode_with_damage(&doc, s, max).map(|(d, damaged)| (d.len(), damaged)).ok();
let whole = Stream::flate(Dict::new(), &vec![b' '; 1 << 20]);
let cut = Stream::from_raw(whole.dict.clone(), whole.raw.get(..whole.raw.len() / 2).unwrap_or_default().to_vec());
let partial = cut.decoded().map(|d| d.len()).unwrap_or(0);
assert!(partial > 0, "a cut flate stream decodes in part");
let mut budget = DecodeBudget::new(10 << 20, 1);
assert_eq!(read(&mut budget, &cut, usize::MAX), Some((partial, true)));
assert_eq!(budget.remaining(), (10 << 20) - partial);
// Within a bound of its own, under what is left.
assert_eq!(read(&mut budget, &cut, 4 << 20), Some((partial, true)));
assert_eq!(budget.decode(&cut).map(|d| d.len()).ok(), Some(partial));
let mut budget = DecodeBudget::new(10 << 20, 1);
assert_eq!(read(&mut budget, &whole, usize::MAX), Some((1 << 20, false)));
assert_eq!(read(&mut budget, &whole, 4 << 20), Some((1 << 20, false)));
let unchecked = Stream::from_raw(whole.dict.clone(), whole.raw.get(..whole.raw.len() - 4).unwrap_or_default().to_vec());
assert_eq!(read(&mut budget, &unchecked, usize::MAX), Some((1 << 20, false)));
assert_eq!(read(&mut budget, &Stream::from_raw(Dict::new(), b"0 0 m".to_vec()), usize::MAX), Some((5, false)));
// A later stage's damage is the stream's.
let mut dict = Dict::new();
dict.set(b"Filter".to_vec(), Object::Array(vec![Object::name("FlateDecode"), Object::name("ASCIIHexDecode")]));
let hex = Stream::from_raw(dict, Stream::flate(Dict::new(), b"4142zz4344>").raw.to_vec());
assert_eq!(budget.decode_with_damage(&doc, &hex, usize::MAX).ok(), Some((b"AB".to_vec(), true)));
// So is an earlier stage's, though the stage after it reads all it was given: a stored
// block of whole hex, then a block of the reserved type (RFC 1951 §3.2.3).
let readable = b"4142>";
let len = u16::try_from(readable.len()).unwrap_or_default();
let mut raw = vec![0x78, 0x01, 0x00];
raw.extend_from_slice(&len.to_le_bytes());
raw.extend_from_slice(&(!len).to_le_bytes());
raw.extend_from_slice(readable);
raw.push(0x07);
let flate_damaged = Stream::from_raw(hex.dict.clone(), raw);
assert_eq!(budget.decode_with_damage(&doc, &flate_damaged, usize::MAX).ok(), Some((b"AB".to_vec(), true)));
}
/// `/DecodeParms` given by reference, or a parameter given by reference in them, is read: a
/// predicted stream decodes as with them direct. Of the stream, decoding copies no more than
/// its filters and their parameters.
#[test]
fn parameters_given_by_reference_are_read() {
let content = b"q 10 0 0 10 0 0 cm /Im Do Q";
// PNG Up, one column: each byte a row of its own, tagged 2.
let mut rows = Vec::new();
let mut above = 0u8;
for &b in content {
rows.extend([2, b.wrapping_sub(above)]);
above = b;
}
let raw = Stream::flate(Dict::new(), &rows).raw;
let mut doc = Document::new_empty();
let direct: Dict = [(b"Predictor".to_vec(), Object::Int(12))].into_iter().collect();
let by_reference = Object::Ref(doc.add(Object::Dict(direct.clone())));
let predictor = doc.add(Object::Int(12));
let inner = Object::Dict([(b"Predictor".to_vec(), Object::Ref(predictor))].into_iter().collect());
for parms in [Object::Dict(direct), by_reference, inner] {
let mut dict = Dict::new();
dict.set(b"Filter".to_vec(), Object::name("FlateDecode"));
dict.set(b"DecodeParms".to_vec(), parms.clone());
dict.set(b"Other".to_vec(), Object::Array(vec![Object::Int(0); 1000]));
let s = Stream::from_raw(dict, raw.to_vec());
assert_eq!(DecodeBudget::page().decode_with_damage(&doc, &s, usize::MAX).ok(), Some((content.to_vec(), false)), "{parms:?}");
assert_eq!(DecodeBudget::page().decode_strict(&doc, &s).ok(), Some(content.to_vec()), "{parms:?}");
let r = doc.add(Object::Stream(s.clone()));
let read = DecodeBudget::page().decode_contents_with_damage(&doc, &Object::Array(vec![Object::Ref(r)]));
assert_eq!(read, [Ok((content.to_vec(), false))], "{parms:?}");
assert_eq!(DecodeBudget::page().decode_contents(&doc, &Object::Ref(r)), [Ok(content.to_vec())], "{parms:?}");
let view = doc.decoding_view(&s);
assert!(matches!(view, std::borrow::Cow::Borrowed(_)) || view.dict.len() == 2, "{:?}", view.dict);
}
}
/// A page's content streams each say whether they are damaged, in their places.
#[test]
fn a_pages_streams_each_say_whether_they_are_damaged() {
let mut doc = Document::new_empty();
let whole = doc.add(Object::Stream(Stream::flate(Dict::new(), b"0 0 m 1 1 l S")));
let Object::Stream(s) = &*doc.get(whole) else { panic!("not a stream") };
let cut = Stream::from_raw(s.dict.clone(), s.raw.get(..s.raw.len() - 6).unwrap_or_default().to_vec());
let cut = doc.add(Object::Stream(cut));
let contents = Object::Array(vec![Object::Ref(whole), Object::Null, Object::Ref(cut)]);
let mut budget = DecodeBudget::page();
let read: Vec<_> = budget.decode_contents_with_damage(&doc, &contents).into_iter().map(|r| r.map(|(_, damaged)| damaged).ok()).collect();
assert_eq!(read, [Some(false), Some(true)]);
let one: Vec<_> =
budget.decode_contents_with_damage(&doc, &Object::Ref(cut)).into_iter().map(|r| r.map(|(_, damaged)| damaged).ok()).collect();
assert_eq!(one, [Some(true)]);
assert_eq!(budget.decode_contents(&doc, &contents).iter().filter(|r| r.is_ok()).count(), 2, "read up to the damage");
}
/// A stream that fails its reading as zlib, and then as raw deflate after decoding all of it,
/// gives nothing back, and each reference still pays for what it decoded.
#[test]
@@ -832,7 +985,7 @@ mod tests {
assert_eq!(budget.remaining(), (10 << 20) - charged);
assert!(budget.decode_within(&chained, 2 << 20).is_ok());
assert_eq!(budget.remaining(), (10 << 20) - 2 * charged);
assert!(budget.decode_strict(&chained).is_ok());
assert!(budget.decode_strict(&Document::new_empty(), &chained).is_ok());
assert_eq!(budget.remaining(), (10 << 20) - 3 * charged);
}
}
+2 -2
View File
@@ -24,11 +24,11 @@ pub(crate) use objects::Held;
pub(crate) use reader::find;
#[cfg(test)]
use reader::rfind;
pub(crate) use state::ObjectReader;
use state::{ObjStm, Slot, Unreadable};
pub(crate) use state::{ObjectReader, held_bytes};
pub use state::{ReadState, SourceIdentity};
#[cfg(test)]
use state::{SECTION_READS, held_bytes, objstm_member};
use state::{SECTION_READS, objstm_member};
use xref::XrefIndex;
pub use xref::{Revision, XrefEntry};
+25 -8
View File
@@ -330,7 +330,29 @@ impl Document {
/// ([`pdfcraft_filters::MAX_CHAIN`]). Only small values are copied, so a file can't have a
/// large object copied once for each key and filter.
pub fn with_direct_parms<'s>(&self, s: &'s Stream) -> Cow<'s, Stream> {
let Some(p) = s.dict.get(b"DecodeParms") else { return Cow::Borrowed(s) };
let Some(made) = self.direct_parms(s) else { return Cow::Borrowed(s) };
let mut s = s.clone();
s.dict.set(b"DecodeParms".to_vec(), made);
Cow::Owned(s)
}
/// [`Document::with_direct_parms`] for decoding alone: where that copies `s`, this makes a
/// stream of `s`'s data, shared, and a dictionary of its `/Filter` and the parameters made
/// direct, all its filters read. A stream named again and again, as a page's `/Contents` may
/// list one, isn't copied whole each time.
pub(crate) fn decoding_view<'s>(&self, s: &'s Stream) -> Cow<'s, Stream> {
let Some(made) = self.direct_parms(s) else { return Cow::Borrowed(s) };
let mut dict = Dict::new();
if let Some(f) = s.dict.get(b"Filter") {
dict.set(b"Filter".to_vec(), f.clone());
}
dict.set(b"DecodeParms".to_vec(), made);
Cow::Owned(Stream { dict, raw: s.raw.clone() })
}
/// The `/DecodeParms` [`Document::with_direct_parms`] gives `s`, or `None` when it keeps `s`.
fn direct_parms(&self, s: &Stream) -> Option<Object> {
let p = s.dict.get(b"DecodeParms")?;
let crypt = |f: &Object| matches!(f.as_name(), Some(b"Crypt"));
let filters: Vec<bool> = match s.dict.get(b"Filter") {
Some(Object::Array(a)) => a.iter().map(crypt).collect(),
@@ -338,7 +360,7 @@ impl Document {
None => Vec::new(),
};
if filters.iter().filter(|c| !**c).count() > pdfcraft_filters::MAX_CHAIN {
return Cow::Borrowed(s);
return None;
}
let mut changed = matches!(p, Object::Ref(_));
// Its numbers and flags kept, resolved; anything else is no filter's parameters (null).
@@ -365,12 +387,7 @@ impl Document {
}
_ => one(p, &mut changed),
};
if !changed {
return Cow::Borrowed(s);
}
let mut s = s.clone();
s.dict.set(b"DecodeParms".to_vec(), made);
Cow::Owned(s)
changed.then_some(made)
}
/// `o`, or the object it refers to, without copying either.
+39 -3
View File
@@ -635,10 +635,20 @@ impl Document {
// Offsets of objects that may be cross-reference streams: their dictionaries are the
// trailers of files that have no `trailer` keyword (§7.5.8).
let mut xref_streams = Vec::new();
for (num, offset, generation, body) in object_headers(&data) {
let headers = object_headers(&data);
// Where `/XRef` occurs in the file, found in one pass.
let mut xref_marks = Vec::new();
let mut mark_from = 0;
while let Some(p) = find(&data, b"/XRef", mark_from, data.len()) {
xref_marks.push(p);
mark_from = p + 1;
}
for &(num, offset, generation, body) in &headers {
entries.insert(num, XrefEntry::InFile { offset, generation });
objstms.push(num);
if find(&data, b"/XRef", body, body.saturating_add(1024)).is_some()
// `/XRef` within the 1024 bytes after the header (the first one that is there).
let first = xref_marks.partition_point(|&p| p < body);
if xref_marks.get(first).is_some_and(|&p| p + 5 <= body.saturating_add(1024).min(data.len()))
&& let Ok(at) = usize::try_from(offset)
{
xref_streams.push(at);
@@ -827,7 +837,33 @@ pub(crate) fn find(hay: &[u8], needle: &[u8], from: usize, to: usize) -> Option<
if from >= to || needle.is_empty() || to - from < needle.len() {
return None;
}
hay[from..to].windows(needle.len()).position(|w| w == needle).map(|p| p + from)
let hay = &hay[from..to];
// Look for the needle's rarest byte first, a plain byte scan, and compare the rest only there.
const COMMON: &[u8] = b" etaoinsrhldcumfpgwybvkxjqz";
let (k, rare) =
needle.iter().copied().enumerate().max_by_key(|&(_, b)| COMMON.iter().position(|&c| c == b).unwrap_or(COMMON.len())).unwrap_or((0, 0));
let mut i = k;
while let Some(p) = hay.get(i..).and_then(|rest| position_of(rest, rare)) {
let start = i + p - k;
if hay.get(start..start + needle.len()) == Some(needle) {
return Some(start + from);
}
i += p + 1;
}
None
}
/// The first position of `byte` in `hay`. Whole 32-byte blocks are tested without branching, which
/// the compiler turns into vector compares; only a block that holds the byte is searched.
fn position_of(hay: &[u8], byte: u8) -> Option<usize> {
const BLOCK: usize = 32;
let (blocks, rest) = hay.as_chunks::<BLOCK>();
for (i, block) in blocks.iter().enumerate() {
if block.iter().fold(false, |any, &b| any | (b == byte)) {
return block.iter().position(|&b| b == byte).map(|p| i * BLOCK + p);
}
}
rest.iter().position(|&b| b == byte).map(|p| blocks.len() * BLOCK + p)
}
pub(super) fn rfind(hay: &[u8], needle: &[u8], from: usize) -> Option<usize> {
+1 -1
View File
@@ -335,7 +335,7 @@ const OWNED_BYTES_DEPTH: usize = 256;
/// InDesign's `/PieceInfo` -- thousands of small numeric arrays, parsed into tens of thousands of
/// values -- weighed nothing, so the caches kept a thousand of them: a 35 MB file held 1.5 GB
/// (#5873).
pub(super) fn held_bytes(object: &Object, data: &Arc<Vec<u8>>, depth: usize) -> usize {
pub(crate) fn held_bytes(object: &Object, data: &Arc<Vec<u8>>, depth: usize) -> usize {
if depth > OWNED_BYTES_DEPTH {
return usize::MAX;
}
+26
View File
@@ -2237,3 +2237,29 @@ fn a_hybrid_update_without_prev_is_rebuilt_too() {
assert_eq!(page_tree_pages(&linked).len(), 3);
assert!(!linked.rebuilt_unlinked_update() && linked.repair_log().is_empty(), "{:?}", linked.repair_log());
}
#[test]
fn find_agrees_with_a_plain_window_search() {
let naive = |hay: &[u8], needle: &[u8], from: usize, to: usize| {
if from >= to || needle.is_empty() || to - from < needle.len() {
return None;
}
hay[from..to].windows(needle.len()).position(|w| w == needle).map(|p| p + from)
};
let mut seed = 0x9E37_79B9_7F4A_7C15u64;
let mut next = move || {
seed ^= seed << 13;
seed ^= seed >> 7;
seed ^= seed << 17;
seed
};
let alphabet = b"/XRef t\n<>0";
for _ in 0..20_000 {
let hay: Vec<u8> = (0..next() % 200).map(|_| alphabet[(next() % alphabet.len() as u64) as usize]).collect();
let needles: [&[u8]; 5] = [b"/XRef", b"trailer", b"R", b"ff", b"<<"];
let needle = needles[(next() % 5) as usize];
let from = (next() % (hay.len() as u64 + 1)) as usize;
let to = from + (next() % (hay.len() as u64 + 1 - from as u64)) as usize;
assert_eq!(find(&hay, needle, from, to), naive(&hay, needle, from, to), "{hay:?} {needle:?} {from} {to}");
}
}
+10 -5
View File
@@ -297,13 +297,18 @@ impl Stream {
/// [`Stream::decoded_within`] for a caller charging an allowance: the filter error is kept
/// typed, so a caller can tell a spent limit from corrupt data, `max` bounds all filter
/// stages together, and the result gives the bytes they decoded (the work done, on success
/// and on failure).
pub(crate) fn decoded_within_counted(&self, max: usize) -> Result<(Vec<u8>, usize), (pdfcraft_filters::FilterError, usize)> {
/// stages together, and the result gives whether the data stopped at damage (it is then what
/// decoded before it) and the bytes the stages decoded (the work done, on success and on
/// failure).
pub(crate) fn decoded_within_counted(&self, max: usize) -> Result<(Vec<u8>, bool, usize), (pdfcraft_filters::FilterError, usize)> {
let mut damaged = false;
let decode = |chain: &[(Filter, Params)], data: &[u8], max| {
pdfcraft_filters::decode_tolerant_counted(chain, data, max).map(|(v, _, spent)| (v, spent))
pdfcraft_filters::decode_tolerant_counted(chain, data, max).map(|(v, partial, spent)| {
damaged = partial;
(v, spent)
})
};
self.decode_chain(max, decode)
self.decode_chain(max, decode).map(|(v, spent)| (v, damaged, spent))
}
/// [`Stream::decoded_within`] spending from `work`, what an operation may still do across a
+129 -21
View File
@@ -15,7 +15,7 @@ use std::io::Write;
use std::sync::Arc;
use crate::CosError;
use crate::document::{Document, ObjectReader, XrefEntry};
use crate::document::{Document, ObjectReader, XrefEntry, held_bytes};
use crate::object::{Dict, ObjRef, Object, PdfString, Stream};
/// Serialize one object. Deterministic: same object → same bytes.
@@ -23,9 +23,7 @@ pub fn serialize(o: &Object, out: &mut Vec<u8>) {
match o {
Object::Null => out.extend_from_slice(b"null"),
Object::Bool(b) => out.extend_from_slice(if *b { b"true" } else { b"false" }),
Object::Int(i) => {
let _ = write!(out, "{i}");
}
Object::Int(i) => write_int(*i, out),
Object::Real(r) => write_real(*r, out),
Object::String(s) => write_string(s, out),
Object::Name(n) => write_name(n, out),
@@ -42,11 +40,46 @@ pub fn serialize(o: &Object, out: &mut Vec<u8>) {
Object::Dict(d) => write_dict(d, out),
Object::Stream(s) => write_stream(s, out),
Object::Ref(r) => {
let _ = write!(out, "{} {} R", r.num, r.generation);
write_digits(u64::from(r.num), out);
out.push(b' ');
write_digits(u64::from(r.generation), out);
out.extend_from_slice(b" R");
}
}
}
/// Upper-case hexadecimal digits.
const HEX: &[u8; 16] = b"0123456789ABCDEF";
/// The decimal digits of `v`, the same bytes `write!(out, "{v}")` gives, without the formatter.
fn write_digits(mut v: u64, out: &mut Vec<u8>) {
// `u64::MAX` has 20 digits, so `at` never goes below 0.
let mut buf = [0u8; 20];
let mut at = buf.len();
loop {
at -= 1;
buf[at] = b'0' + (v % 10) as u8;
v /= 10;
if v == 0 {
break;
}
}
out.extend_from_slice(&buf[at..]);
}
/// A signed integer in decimal, as `write!(out, "{i}")` writes it.
fn write_int(i: i64, out: &mut Vec<u8>) {
if i < 0 {
out.push(b'-');
}
write_digits(i.unsigned_abs(), out);
}
/// `b` as two upper-case hexadecimal digits.
fn hex_pair(b: u8) -> [u8; 2] {
[HEX[usize::from(b >> 4)], HEX[usize::from(b & 15)]]
}
fn write_real(r: f64, out: &mut Vec<u8>) {
if !r.is_finite() {
out.push(b'0');
@@ -55,7 +88,7 @@ fn write_real(r: f64, out: &mut Vec<u8>) {
// A whole number is written as an integer only within the integer range Annex C gives
// (±2³¹−1), so `4e9` or `1e30` stays a real token for readers with 32-bit integers.
if r.fract() == 0.0 && r.abs() <= f64::from(i32::MAX) {
let _ = write!(out, "{}", r as i32);
write_int(i64::from(r as i32), out);
return;
}
// Plain decimal notation (§7.3.3 has no exponents). Rust's `Display` for f64 prints the
@@ -76,7 +109,8 @@ fn write_name(n: &[u8], out: &mut Vec<u8>) {
if regular {
out.push(b);
} else {
let _ = write!(out, "#{b:02X}");
out.push(b'#');
out.extend_from_slice(&hex_pair(b));
}
}
}
@@ -84,9 +118,10 @@ fn write_name(n: &[u8], out: &mut Vec<u8>) {
fn write_string(s: &PdfString, out: &mut Vec<u8>) {
let binary = s.bytes.iter().filter(|b| !(b' '..=b'~').contains(*b) && !matches!(b, b'\n' | b'\r' | b'\t')).count();
if s.hex || binary * 4 > s.bytes.len().max(1) {
out.reserve(s.bytes.len().saturating_mul(2).saturating_add(2));
out.push(b'<');
for b in &s.bytes {
let _ = write!(out, "{b:02X}");
for &b in &s.bytes {
out.extend_from_slice(&hex_pair(b));
}
out.push(b'>');
return;
@@ -105,7 +140,7 @@ fn write_string(s: &PdfString, out: &mut Vec<u8>) {
0x0C => out.extend_from_slice(b"\\f"),
b' '..=b'~' => out.push(b),
_ => {
let _ = write!(out, "\\{b:03o}");
out.extend_from_slice(&[b'\\', b'0' + (b >> 6), b'0' + ((b >> 3) & 7), b'0' + (b & 7)]);
}
}
}
@@ -275,14 +310,22 @@ pub fn write_incremental(doc: &Document, opts: &SaveOptions) -> Result<Vec<u8>,
/// The objects [`write_full`] writes: everything reachable from the trailer's /Root, /Info and
/// /Encrypt and from its unknown entries, breadth-first, with the new number each gets
/// (aliases of one slot included) and, in visit order, whether it is a stream.
type SaveOrder = (HashMap<ObjRef, u32>, Vec<(ObjRef, bool)>);
/// (aliases of one slot included) and, in visit order, whether it is a stream and the parsed
/// object where the budget allowed keeping it.
type SaveOrder = (HashMap<ObjRef, u32>, Vec<(ObjRef, bool)>, Vec<Option<Arc<Object>>>);
fn full_save_order(reader: &mut ObjectReader, trailer_in: &Dict) -> Result<SaveOrder, CosError> {
/// Number the objects reachable from the trailer. `retain` keeps parsed objects for the write
/// pass, up to the budget. A caller that needs only the numbers passes `false`, so the traversal
/// holds no parsed objects beyond the current one.
fn full_save_order(reader: &mut ObjectReader, trailer_in: &Dict, retain: bool) -> Result<SaveOrder, CosError> {
// Breadth-first walk from the trailer, assigning new numbers in visit order.
let mut map: HashMap<ObjRef, u32> = HashMap::new();
// Record the type while traversing so classifying packed objects needs no second parse.
let mut order: Vec<(ObjRef, bool)> = Vec::new();
// The parsed object of each entry in `order`, kept for the write pass while the budget
// allows it. Past the budget the write pass reads the object again.
let mut kept: Vec<Option<Arc<Object>>> = Vec::new();
let mut kept_budget = KeptObjects::default();
let mut queue: VecDeque<ObjRef> = VecDeque::new();
let visit_refs = |o: &Object, queue: &mut VecDeque<ObjRef>| collect_refs(o, &mut |r| queue.push_back(r));
for key in [&b"Root"[..], b"Info", b"Encrypt"] {
@@ -321,8 +364,9 @@ fn full_save_order(reader: &mut ObjectReader, trailer_in: &Dict) -> Result<SaveO
map.insert(canonical, num);
order.push((canonical, matches!(*o, Object::Stream(_))));
visit_refs(&o, &mut queue);
kept.push((retain && kept_budget.admit(&o, reader.document.bytes())).then_some(o));
}
Ok((map, order))
Ok((map, order, kept))
}
/// The object numbers a full save of `doc` would write: exactly the objects [`write_full`]
@@ -331,7 +375,7 @@ fn full_save_order(reader: &mut ObjectReader, trailer_in: &Dict) -> Result<SaveO
pub fn reachable_objects(doc: &Document) -> Result<HashSet<u32>, CosError> {
let mut reader = doc.object_reader();
let trailer_in = reader.document.trailer().clone();
let (_, order) = full_save_order(&mut reader, &trailer_in)?;
let (_, order, _) = full_save_order(&mut reader, &trailer_in, false)?;
Ok(order.into_iter().map(|(r, _)| r.num).collect())
}
@@ -345,7 +389,7 @@ pub fn write_full(doc: &Document, opts: &SaveOptions) -> Result<Vec<u8>, CosErro
let mut reader = doc.object_reader();
stamp_mod_date(&mut reader.document, opts);
let trailer_in = reader.document.trailer().clone();
let (map, order) = full_save_order(&mut reader, &trailer_in)?;
let (map, order, mut kept) = full_save_order(&mut reader, &trailer_in, true)?;
let version = reader.document.version().chars().take(3).collect::<String>();
let version = if opts.object_streams && version.as_str() < "1.5" { "1.5".to_string() } else { version };
let mut out = Vec::new();
@@ -375,14 +419,14 @@ pub fn write_full(doc: &Document, opts: &SaveOptions) -> Result<Vec<u8>, CosErro
let mut rows: BTreeMap<u32, Row> = BTreeMap::new();
// Keep only references, not renamed copies of the entire object graph. Standalone
// objects still precede object streams, preserving the established output order.
let mut packed: Vec<(u32, ObjRef)> = Vec::new();
let mut packed: Vec<(u32, ObjRef, Option<Arc<Object>>)> = Vec::new();
for (i, (r, is_stream)) in order.iter().enumerate() {
let num = output_number(i)?;
let in_stream = opts.object_streams && !is_stream && !encryption_objects.contains(&num) && root_outside != Some(num);
if in_stream {
packed.push((num, *r));
packed.push((num, *r, kept[i].take()));
} else {
let o = reread(&mut reader, *r, *is_stream)?;
let o = written_object(&mut reader, *r, *is_stream, kept[i].take())?;
let o = renumber(&prepared(&reader.document, r.num, num, 0, &o), &map);
rows.insert(num, Row::InFile(out.len() as u64, 0));
write_indirect(num, 0, &o, &mut out);
@@ -392,9 +436,9 @@ pub fn write_full(doc: &Document, opts: &SaveOptions) -> Result<Vec<u8>, CosErro
// individually: the whole stream is (§7.5.7, §7.6.2).
let mut next = output_number(order.len())?;
let mut batch = ObjectStreamBatch::default();
for (num, reference) in packed {
for (num, reference, parsed) in packed {
let mut encoded = Vec::new();
serialize(&renumber(&*reread(&mut reader, reference, false)?, &map), &mut encoded);
serialize(&renumber(&*written_object(&mut reader, reference, false, parsed)?, &map), &mut encoded);
if batch.count > 0 && batch.body.len().saturating_add(encoded.len()).saturating_add(1) > OBJSTM_BYTES {
batch.flush(&reader.document, &mut next, &mut rows, &mut out)?;
}
@@ -428,6 +472,38 @@ pub fn write_full(doc: &Document, opts: &SaveOptions) -> Result<Vec<u8>, CosErro
Ok(out)
}
/// What `write_full` keeps of the objects it parsed while numbering them, measured with
/// [`held_bytes`] (the parsed tree and any data that is not a view into the file). Beyond the
/// budget objects are read again when written, which bounds the memory of a save of a huge
/// document.
#[derive(Default)]
struct KeptObjects {
bytes: usize,
}
impl KeptObjects {
const BYTES: usize = 64 * 1024 * 1024;
/// Whether `object` still fits the budget; if so it is counted against it.
fn admit(&mut self, object: &Object, data: &Arc<Vec<u8>>) -> bool {
let bytes = self.bytes.saturating_add(held_bytes(object, data, 0));
if bytes > Self::BYTES {
return false;
}
self.bytes = bytes;
true
}
}
/// The object to write for `r`: the one parsed while numbering when it was kept, else `r` read
/// again.
fn written_object(reader: &mut ObjectReader, r: ObjRef, is_stream: bool, kept: Option<Arc<Object>>) -> Result<Arc<Object>, CosError> {
match kept {
Some(o) => Ok(o),
None => reread(reader, r, is_stream),
}
}
/// Assemble the full rewrite's trailer and apply its identifier policy.
fn full_save_trailer(doc: &Document, trailer_in: &Dict, map: &HashMap<ObjRef, u32>, opts: &SaveOptions, out: &[u8]) -> Dict {
let mut trailer = Dict::new();
@@ -935,6 +1011,38 @@ mod tests {
Lexer::new(&out, 0).object().expect("parses")
}
#[test]
fn kept_objects_stop_at_their_byte_budget() {
let data = Arc::new(Vec::new());
let string = Object::String(PdfString::literal(vec![b'x'; 1000]));
let array = Object::Array(vec![Object::Int(1), Object::Null]);
let mut kept = KeptObjects::default();
assert!(kept.admit(&string, &data) && kept.admit(&array, &data));
assert_eq!(kept.bytes, held_bytes(&string, &data, 0) + held_bytes(&array, &data, 0));
let mut full = KeptObjects { bytes: KeptObjects::BYTES - held_bytes(&string, &data, 0) + 1 };
let before = full.bytes;
assert!(!full.admit(&string, &data), "one byte over the budget");
assert_eq!(full.bytes, before, "a refused object is not counted");
let mut deep = Object::Null;
for _ in 0..300 {
deep = Object::Array(vec![deep]);
}
assert!(!KeptObjects::default().admit(&deep, &data), "nesting past the limit is never kept");
}
#[test]
fn kept_objects_count_names_and_dictionary_keys() {
let data = Arc::new(Vec::new());
let name = Object::Name(vec![b'n'; KeptObjects::BYTES + 1]);
let mut kept = KeptObjects::default();
assert!(!kept.admit(&name, &data), "a name over the byte budget is not kept");
assert_eq!(kept.bytes, 0);
let mut dict = Dict::new();
dict.set(vec![b'k'; KeptObjects::BYTES + 1], Object::Null);
assert!(!kept.admit(&Object::Dict(dict), &data), "nor a dictionary key");
assert_eq!(kept.bytes, 0);
}
#[test]
fn a_second_read_that_differs_fails_the_save_instead_of_writing_null() {
let mut doc = Document::new_empty();
+1
View File
@@ -5,5 +5,6 @@ mod corpus;
mod encryption;
mod generations;
mod proptests;
mod serialize_format;
mod shared_streams;
mod writer;
+116
View File
@@ -0,0 +1,116 @@
//! `serialize` writes integers, references, hexadecimal strings, octal escapes and `#xx` name
//! escapes with its own digit loops. They must give the bytes the standard formatter gives.
use pdfcraft_cos::{ObjRef, Object, PdfString, serialize};
use proptest::prelude::*;
fn bytes_of(o: &Object) -> Vec<u8> {
let mut v = Vec::new();
serialize(o, &mut v);
v
}
#[test]
fn integer_extremes_and_digit_boundaries() {
let mut cases = vec![0i64, 1, -1, 9, 10, 99, 100, i64::MAX, i64::MIN, i64::MIN + 1, i64::from(i32::MAX), i64::from(i32::MIN)];
let mut p = 1i64;
while let Some(next) = p.checked_mul(10) {
cases.extend([next - 1, next, next + 1, -next]);
p = next;
}
for i in cases {
assert_eq!(bytes_of(&Object::Int(i)), i.to_string().into_bytes(), "{i}");
}
}
#[test]
fn reference_extremes() {
for (n, g) in [(0, 0), (1, 0), (u32::MAX, u16::MAX), (10, 65535), (4_000_000_000, 7)] {
assert_eq!(bytes_of(&Object::Ref(ObjRef::new(n, g))), format!("{n} {g} R").into_bytes());
}
}
#[test]
fn every_byte_value_in_hex_strings_octal_escapes_and_names() {
let all: Vec<u8> = (0..=255).collect();
let hex: String = all.iter().map(|b| format!("{b:02X}")).collect();
assert_eq!(bytes_of(&Object::String(PdfString { bytes: all.clone(), hex: true })), format!("<{hex}>").into_bytes());
// A literal string with a few control bytes escapes them in octal.
let lit = bytes_of(&Object::String(PdfString { bytes: b"abcdefghijkl\x01\x7f\xffz".to_vec(), hex: false }));
assert_eq!(lit, b"(abcdefghijkl\\001\\177\\377z)");
let name = bytes_of(&Object::Name(all.clone()));
let mut want = b"/".to_vec();
for &b in &all {
let regular = (b'!'..=b'~').contains(&b) && !matches!(b, b'(' | b')' | b'<' | b'>' | b'[' | b']' | b'{' | b'}' | b'/' | b'%' | b'#');
if regular {
want.push(b);
} else {
want.extend_from_slice(format!("#{b:02X}").as_bytes());
}
}
assert_eq!(name, want);
}
#[test]
fn whole_real_at_i32_min_stays_a_real_token() {
// -2^31 is outside the Annex C integer range (±2^31-1), so it keeps its trailing point.
assert_eq!(bytes_of(&Object::Real(f64::from(i32::MIN))), b"-2147483648.");
}
proptest! {
#[test]
fn integers_match_the_formatter(i in any::<i64>()) {
prop_assert_eq!(bytes_of(&Object::Int(i)), format!("{i}").into_bytes());
}
#[test]
fn whole_reals_match_the_formatter(i in -i32::MAX..=i32::MAX) {
prop_assert_eq!(bytes_of(&Object::Real(f64::from(i))), format!("{i}").into_bytes());
}
#[test]
fn references_match_the_formatter(n in any::<u32>(), g in any::<u16>()) {
prop_assert_eq!(bytes_of(&Object::Ref(ObjRef::new(n, g))), format!("{n} {g} R").into_bytes());
}
#[test]
fn hex_strings_match_the_formatter(bytes in proptest::collection::vec(any::<u8>(), 0..300)) {
let mut want = String::from("<");
for b in &bytes {
want.push_str(&format!("{b:02X}"));
}
want.push('>');
prop_assert_eq!(bytes_of(&Object::String(PdfString { bytes, hex: true })), want.into_bytes());
}
#[test]
fn binary_literal_strings_match_the_formatter(bytes in proptest::collection::vec(any::<u8>(), 0..300)) {
// Mostly-binary input is written as hex; mostly-text input with escapes is a literal.
let got = bytes_of(&Object::String(PdfString { bytes: bytes.clone(), hex: false }));
let binary = bytes.iter().filter(|b| !(b' '..=b'~').contains(*b) && !matches!(b, b'\n' | b'\r' | b'\t')).count();
let mut want = Vec::new();
if binary * 4 > bytes.len().max(1) {
want.push(b'<');
for b in &bytes {
want.extend_from_slice(format!("{b:02X}").as_bytes());
}
want.push(b'>');
} else {
want.push(b'(');
for &b in &bytes {
match b {
b'(' | b')' | b'\\' => want.extend_from_slice(&[b'\\', b]),
b'\n' => want.extend_from_slice(b"\\n"),
b'\r' => want.extend_from_slice(b"\\r"),
b'\t' => want.extend_from_slice(b"\\t"),
0x08 => want.extend_from_slice(b"\\b"),
0x0C => want.extend_from_slice(b"\\f"),
b' '..=b'~' => want.push(b),
_ => want.extend_from_slice(format!("\\{b:03o}").as_bytes()),
}
}
want.push(b')');
}
prop_assert_eq!(got, want);
}
}
+21 -9
View File
@@ -183,12 +183,17 @@ fn image(doc: &Document, s: &Stream, budget: &mut ImageBudget) -> Result<(&'stat
.unwrap_or(false);
// In a PDF a CMYK JPEG's samples are ink amounts unless /Decode inverts them, while image
// viewers read a CMYK JPEG file as inverted (Adobe's convention): as is, it would show as
// a negative.
let as_is_negative = jpeg && !inverted && matches!(space(doc, s.dict.get(b"ColorSpace")), Ok(Space::Cmyk));
// a negative. The space is read once: an indexed one's lookup table is paid for each time.
let read = (jpeg && !inverted).then(|| space(doc, s.dict.get(b"ColorSpace"), budget));
let as_is_negative = matches!(read, Some(Ok(Space::Cmyk)));
if jpeg && alpha.is_none() && key.is_none() && !as_is_negative {
return as_is();
}
let mut space = if mask { Space::Gray } else { space(doc, s.dict.get(b"ColorSpace"))? };
let mut space = match read {
_ if mask => Space::Gray,
Some(read) => read?,
None => space(doc, s.dict.get(b"ColorSpace"), budget)?,
};
let (samples, bpc) = if jpeg {
if !budget.pay_jpeg((w as u64).saturating_mul(h as u64).saturating_mul(space.components() as u64), &s.raw) {
return Err(FilterError::Spent.to_string());
@@ -436,7 +441,10 @@ impl Space {
/// A lookup table holds at most 256 entries of 4 bytes; decoding stops well past that.
const MAX_LOOKUP: usize = 64 << 10;
fn space(doc: &Document, cs: Option<&Object>) -> Result<Space, String> {
/// The colour space `cs` names; an indexed one's lookup table is read within `budget`, as the
/// image's samples are, since each image reads it again and its filters can do work that makes
/// nothing.
fn space(doc: &Document, cs: Option<&Object>, budget: &mut ImageBudget) -> Result<Space, String> {
let Some(cs) = cs else { return Err("the image has no colour space".into()) };
let cs = doc.resolve(cs);
let unsupported = |n: &[u8]| Err(format!("{} images can't be exported yet", String::from_utf8_lossy(n)));
@@ -470,7 +478,7 @@ fn space(doc: &Document, cs: Option<&Object>) -> Result<Space, String> {
if nested {
return Err("nested indexed colour spaces aren't valid".into());
}
let base = space(doc, a.get(1))?;
let base = space(doc, a.get(1), budget)?;
let hival = match a.get(2).map(|value| doc.resolve(value)).as_deref() {
Some(Object::Int(value)) if (0..=255).contains(value) => *value as u8,
_ => return Err("an indexed colour space with an invalid hival".into()),
@@ -478,10 +486,14 @@ fn space(doc: &Document, cs: Option<&Object>) -> Result<Space, String> {
let table = match a.get(3).map(|t| doc.resolve(t)).as_deref() {
Some(Object::String(s)) => s.bytes.clone(),
// Through its parameters given by reference too, as the image's samples.
Some(Object::Stream(t)) => doc
.with_direct_parms(t)
.decoded_within(MAX_LOOKUP)
.map_err(|_| "an indexed colour space with an oversized or damaged lookup table".to_string())?,
Some(Object::Stream(t)) => {
let refused = budget.refused();
match budget.decode_filters(doc, t, MAX_LOOKUP) {
Ok(table) => table,
Err(_) if budget.refused() > refused => return Err(FilterError::Spent.to_string()),
Err(_) => return Err("an indexed colour space with an oversized or damaged lookup table".into()),
}
}
_ => return Err("an indexed colour space without a lookup table".into()),
};
Ok(Space::Indexed(Box::new(base), hival, table))
+92
View File
@@ -2409,6 +2409,98 @@ fn flate_images_past_the_exports_allowance_are_left_out_with_the_reason() {
assert_eq!(budget.refused(), 1);
}
/// An indexed image's lookup table, given as a stream, is read within the export's allowance as
/// the image's samples are: each image reads it again, and its filters can do work that makes
/// nothing (Flate over empty blocks). Past the allowance the image is left out with the reason.
#[test]
fn a_lookup_table_is_read_within_the_exports_allowance() {
use pdfcraft_cos::{Dict, Document, ImageBudget, Object, PdfString, Stream};
let table = [255, 0, 0, 0, 0, 255];
let lookup = Stream::flate(Dict::new(), &table);
let exported = |as_stream: bool, work: u64| {
let mut doc = Document::new_empty();
let table = if as_stream { Object::Ref(doc.add(Object::Stream(lookup.clone()))) } else { Object::String(PdfString::literal(table.to_vec())) };
let mut dict = Dict::new();
dict.set(b"Subtype".to_vec(), Object::name("Image"));
dict.set(b"Width".to_vec(), Object::Int(2));
dict.set(b"Height".to_vec(), Object::Int(1));
dict.set(b"BitsPerComponent".to_vec(), Object::Int(8));
dict.set(b"ColorSpace".to_vec(), Object::Array(vec![Object::name("Indexed"), Object::name("DeviceRGB"), Object::Int(1), table]));
let image = doc.add(Object::Stream(Stream::flate(dict, &[0, 1])));
let mut budget = ImageBudget::with_work(work);
let file = crate::extract::image_file_within(&doc, image, &mut budget);
(file, work - budget.work_left(), budget.refused())
};
let (direct, image_alone, _) = exported(false, u64::MAX);
let (streamed, both, _) = exported(true, u64::MAX);
assert_eq!(streamed.unwrap(), direct.unwrap(), "the same picture");
let read = (lookup.raw.len() + table.len()) as u64 + pdfcraft_filters::FLATE_READ_WORK * lookup.raw.len() as u64;
assert_eq!(both, image_alone + read, "the table is paid for as it is read");
let (refused, _, count) = exported(true, image_alone);
assert!(refused.unwrap_err().contains("more image decoding than"));
assert_eq!(count, 1);
}
/// A JPEG's colour space is read once for an export, its lookup table paid for once: whether it is
/// CMYK (a negative as is) and what its samples are both come from that reading. An indexed JPEG
/// isn't valid, and is written as it is, but its soft mask makes it go on past the first. With the
/// mask, a table the allowance can't pay for leaves the image out, with the reason.
#[test]
fn a_jpegs_lookup_table_is_paid_for_once() {
use pdfcraft_cos::{Dict, Document, ImageBudget, Object, PdfString, Stream};
let table = [255, 0, 0, 0, 0, 255];
let lookup = Stream::flate(Dict::new(), &table);
let mut jpeg = Vec::new();
image::GrayImage::from_pixel(2, 1, image::Luma([1])).write_to(&mut std::io::Cursor::new(&mut jpeg), image::ImageFormat::Jpeg).unwrap();
// `given`: None leaves the colour space out, Some(true) gives the table as a stream.
let exported = |given: Option<bool>, work: u64| {
let mut doc = Document::new_empty();
let table = given.map(|as_stream| {
if as_stream { Object::Ref(doc.add(Object::Stream(lookup.clone()))) } else { Object::String(PdfString::literal(table.to_vec())) }
});
let mut mask = Dict::new();
for (k, v) in
[("Subtype", Object::name("Image")), ("Width", Object::Int(2)), ("Height", Object::Int(1)), ("BitsPerComponent", Object::Int(8))]
{
mask.set(k.as_bytes().to_vec(), v);
}
mask.set(b"ColorSpace".to_vec(), Object::name("DeviceGray"));
let mask = doc.add(Object::Stream(Stream::flate(mask, &[255, 128])));
let mut dict = Dict::new();
for (k, v) in
[("Subtype", Object::name("Image")), ("Width", Object::Int(2)), ("Height", Object::Int(1)), ("BitsPerComponent", Object::Int(8))]
{
dict.set(k.as_bytes().to_vec(), v);
}
if let Some(table) = table {
dict.set(b"ColorSpace".to_vec(), Object::Array(vec![Object::name("Indexed"), Object::name("DeviceRGB"), Object::Int(1), table]));
}
dict.set(b"Filter".to_vec(), Object::name("DCTDecode"));
dict.set(b"SMask".to_vec(), Object::Ref(mask));
let image = doc.add(Object::Stream(Stream::from_raw(dict, jpeg.clone())));
let mut budget = ImageBudget::with_work(work);
let file = crate::extract::image_file_within(&doc, image, &mut budget);
(file, work - budget.work_left(), budget.refused())
};
let (direct, direct_cost, _) = exported(Some(false), u64::MAX);
let (streamed, streamed_cost, _) = exported(Some(true), u64::MAX);
assert_eq!(direct, Ok(("jpg", jpeg.clone())), "written as it is");
assert_eq!(streamed, direct);
let read = (lookup.raw.len() + table.len()) as u64 + pdfcraft_filters::FLATE_READ_WORK * lookup.raw.len() as u64;
assert_eq!(streamed_cost, direct_cost + read, "one reading of the table");
// Without a colour space nothing is read after the soft mask, so this is what the mask costs.
let (none, mask, _) = exported(None, u64::MAX);
assert_eq!(none.unwrap_err(), "the image has no colour space");
// Read first, the table would be refused a step short of the mask too, and the mask after it.
assert!(read >= mask, "the table costs at least what the mask does");
assert_eq!(exported(Some(true), mask - 1).2, 1, "the mask is read first, and refused alone");
let (refused, _, count) = exported(Some(true), mask + read - 1);
let refused = refused.unwrap_err();
assert!(refused.contains("more image decoding than"), "{refused}");
assert_eq!(count, 1, "refused at the table, and nothing after it asks to be paid for");
}
/// A JPEG is written as it is, at no cost, unless something means decoding it, here a mask: that
/// pays for its samples, and past the allowance the image goes, with the reason, as it would come out without
/// its transparency otherwise.
+4 -4
View File
@@ -208,7 +208,7 @@ pub(crate) fn restore(doc: &mut Document, page: &pdfcraft_model::Page) -> Result
let same = |w: &ObjRef| match &*doc.get(*w) {
Object::Stream(s) => {
[TAG, &b"PCMark"[..], b"Subtype"].iter().all(|k| s.dict.get(k).is_none())
&& DecodeBudget::new(SCAN_BYTES, 0).decode_strict(s).ok().as_deref() == Some(bytes.as_slice())
&& DecodeBudget::new(SCAN_BYTES, 0).decode_strict(doc, s).ok().as_deref() == Some(bytes.as_slice())
}
_ => false,
};
@@ -248,7 +248,7 @@ fn restored_copy(doc: &Document, page: &pdfcraft_model::Page, copy: ObjRef) -> O
return None;
}
let hash = note.get(b"Before")?.as_string()?;
let bytes = DecodeBudget::new(SCAN_BYTES, 0).decode_strict(s).ok()?;
let bytes = DecodeBudget::new(SCAN_BYTES, 0).decode_strict(doc, s).ok()?;
let parsed = pdfcraft_content::parse(head(&bytes));
// The `n` standing in for the fill, after exactly the operators that came before it.
let fill = parsed.ops.get(index)?;
@@ -384,11 +384,11 @@ fn scan(doc: &Document, p: &pdfcraft_model::Page, swap: Option<(ObjRef, &[u8])>)
if b.len() > SCAN_BYTES.saturating_sub(total) {
return None;
}
budget.decode_strict(&Stream::from_raw(Dict::new(), b.to_vec())).ok()?
budget.decode_strict(doc, &Stream::from_raw(Dict::new(), b.to_vec())).ok()?
}
// Tolerant decoding can return an empty or partial stream after corruption.
// That cannot prove which paint preceded the candidate backdrop.
_ => budget.decode_strict(s).ok()?,
_ => budget.decode_strict(doc, s).ok()?,
};
if bytes.len() > SCAN_BYTES.saturating_sub(total).saturating_sub(1) {
return None;
+2 -2
View File
@@ -1,7 +1,7 @@
//! A page's background colour: the colour the page is painted with before anything else, as
//! Edit a PDF ▸ Background and many producers do it, for exports that keep a page colour (#2992).
use pdfcraft_content::{Matrix, Op, Pieces};
use pdfcraft_content::{Matrix, Op};
use pdfcraft_cos::{Dict, Document};
use crate::{EditError, Rgb};
@@ -51,7 +51,7 @@ pub fn page_background(doc: &Document, page: usize) -> Result<Option<Rgb>, EditE
let resources = p.dict.get(b"Resources").map(|r| doc.resolve(r)).and_then(|r| r.as_dict().cloned()).unwrap_or_default();
let gstates = resources.get(b"ExtGState").map(|g| doc.resolve(g)).and_then(|g| g.as_dict().cloned()).unwrap_or_default();
let streams = crate::text::content_streams(doc, &p.dict)?;
let pieces = Pieces::join(&streams.iter().map(|(_, d)| d.as_slice()).collect::<Vec<_>>());
let pieces = crate::text::joined(&streams);
let ops = pieces.parse().ops;
let mut st = State { ctm: Matrix::IDENTITY, space: Space::Gray, fill: Some([0.0; 3]), alpha: 1.0, plain: true, clip: Some(Vec::new()) };
+59 -46
View File
@@ -4,12 +4,12 @@
//! or delete. Only the stream that draws it is rewritten, as a new object.
use kurbo::{BezPath, Point, Shape};
use pdfcraft_content::{Matrix, Op, Pieces, parse, serialize_ops};
use pdfcraft_content::{Matrix, Op, parse, serialize_ops};
use pdfcraft_cos::{Dict, Document, ObjRef, Object};
use std::sync::Arc;
use crate::EditError;
use crate::text::content_streams;
use crate::text::{ContentStream, content_streams, joined};
/// The identity of a soft mask (`/SMask`) in the PDF graphics state.
#[derive(Clone, Debug)]
@@ -47,7 +47,7 @@ pub struct PageImage {
pub width: u32,
pub height: u32,
/// The content stream its `Do` (its first token) is in, and the `Do`'s index among the
/// operators of the page's streams joined ([`Pieces`]).
/// operators of the page's streams joined ([`pdfcraft_content::Pieces`]).
pub stream: usize,
op: usize,
/// CTM before `Do`, excluding a Form's own Matrix.
@@ -103,11 +103,6 @@ fn too_many_images() -> EditError {
EditError::Invalid(format!("the page draws more than {MAX_PAGE_IMAGES} images"))
}
/// The page's streams joined into the one stream they are: an operator may span two of them.
fn joined(streams: &[(Object, Vec<u8>)]) -> Pieces {
Pieces::join(&streams.iter().map(|(_, data)| data.as_slice()).collect::<Vec<_>>())
}
fn page_of(doc: &Document, page: usize) -> Result<pdfcraft_model::Page, EditError> {
pdfcraft_model::pages(doc).into_iter().nth(page).ok_or(EditError::NoSuchPage(page))
}
@@ -532,12 +527,17 @@ fn exclusive_clip(ops: &[Op], op: usize) -> Option<(usize, Matrix)> {
/// The `q cm … Q` whose only content after its `cm` is `start..=end` (a `Do`, or a balanced
/// `q … Q` scope), with the index and value of that `cm`. Another transform of the same
/// placement is folded into it, so repeated moves and resizes don't nest one more `q` each.
fn enclosing_transform(ops: &[Op], start: usize, end: usize) -> Option<(usize, Matrix)> {
/// None when its `Q` is at or past `hidden` ([`crate::text::first_op_after_damage`]): a stream
/// between that wasn't read may draw in that `cm` too.
fn enclosing_transform(ops: &[Op], start: usize, end: usize, hidden: usize) -> Option<(usize, Matrix)> {
let at = start.checked_sub(1)?;
let cm = ops.get(at)?;
if !ops.get(at.checked_sub(1)?)?.is("q") || !ops.get(end.checked_add(1)?)?.is("Q") || !cm.is("cm") || cm.operands.len() != 6 {
return None;
}
if end.checked_add(1)? >= hidden {
return None;
}
let m = Matrix(cm.nums::<6>()?);
m.0.iter().all(|v| v.is_finite()).then_some((at, m))
}
@@ -1057,7 +1057,9 @@ fn determine_arrange_spans(
has_other_paint: bool,
marked_unit: bool,
) -> Result<(std::ops::Range<usize>, usize, usize, usize), EditError> {
let scope = image_scopes(ops, target, "arranged")
// Nothing is hidden for Arrange: it takes out the scope it finds, so a scope that closes past a
// stream not read whole changes a stream past it, which `rewritten_contents` refuses.
let scope = image_scopes(ops, target, "arranged", ops.len())
.ok()
.and_then(|s| s.isolated)
.filter(|&(start, end, _)| start >= target_unit.start && end < target_unit.end);
@@ -1191,13 +1193,7 @@ fn build_relocated_unit_ops(
}
/// Change the stacking order of `img`, drawn on page `p` by its content streams `all`.
fn arrange_image(
doc: &mut Document,
p: &pdfcraft_model::Page,
all: &[(Object, Vec<u8>)],
img: &PageImage,
order: ArrangeOrder,
) -> Result<(), EditError> {
fn arrange_image(doc: &mut Document, p: &pdfcraft_model::Page, all: &[ContentStream], img: &PageImage, order: ArrangeOrder) -> Result<(), EditError> {
let pieces = joined(all);
let ops = pieces.parse().ops;
let target = img.op;
@@ -1264,7 +1260,7 @@ fn arrange_image(
ops.get(dest_unit.start).map(|op| pieces.piece_of(op.span.start))
};
let owned_destination = destination_piece
.filter(|piece| all.get(*piece).is_some_and(|(obj, _)| doc.resolve(obj).as_dict().is_some_and(|d| d.get(b"PCAdded").is_some())));
.filter(|piece| all.get(*piece).is_some_and(|s| doc.resolve(&s.entry).as_dict().is_some_and(|d| d.get(b"PCAdded").is_some())));
if let Some(piece) = owned_destination {
let whole_unit = ops.iter().enumerate().all(|(index, op)| {
let (first, last) = pieces.pieces_of(op);
@@ -1439,13 +1435,14 @@ fn arrange_image(
};
if let Some(piece) = owned_destination {
let insertion = piece.saturating_add(usize::from(insert_after));
crate::text::drawn_before_damage(all, insertion)?;
let changed = pieces.splice([(target_span, removal_replacement)]);
let contents = crate::text::rewritten_contents(doc, all, changed);
let contents = crate::text::rewritten_contents(doc, all, changed)?;
let mut list = match contents {
Object::Array(list) => list,
one => vec![one],
};
let insertion = piece.saturating_add(usize::from(insert_after));
if insertion > list.len() {
return Err(EditError::Invalid("the destination content stream is missing".into()));
}
@@ -1467,7 +1464,7 @@ fn arrange_image(
}
let changed = pieces.splice(edits);
let contents = crate::text::rewritten_contents(doc, all, changed);
let contents = crate::text::rewritten_contents(doc, all, changed)?;
doc.update_dict(p.obj, |d| d.set(b"Contents".to_vec(), contents))?;
Ok(())
}
@@ -1501,8 +1498,10 @@ impl ImageScopes {
}
}
/// [`ImageScopes`] of the `Do` at `target`. An image inside a text object cannot be `done`.
fn image_scopes(ops: &[Op], target: usize, done: &str) -> Result<ImageScopes, EditError> {
/// [`ImageScopes`] of the `Do` at `target`. An image inside a text object cannot be `done`. A scope
/// still open at op `hidden` ([`crate::text::first_op_after_damage`]) holds a stream that wasn't
/// read, which may paint there: it counts as painting something else.
fn image_scopes(ops: &[Op], target: usize, done: &str, hidden: usize) -> Result<ImageScopes, EditError> {
struct Scope {
start: usize,
matrix: Matrix,
@@ -1521,6 +1520,11 @@ fn image_scopes(ops: &[Op], target: usize, done: &str) -> Result<ImageScopes, Ed
let mut isolated = None;
let mut outermost = None;
for (index, op) in ops.iter().enumerate() {
if index == hidden {
for scope in &mut stack {
scope.other_paint = true;
}
}
match op.op.as_slice() {
b"q" => {
if stack.len() >= 256 {
@@ -1606,20 +1610,26 @@ fn app_crop_ranges(ops: &[Op], start: usize, target: usize) -> Vec<std::ops::Ran
}
/// Remove only crops written by PdfCraft, preserving the document author's clipping paths.
fn remove_image_crop(doc: &mut Document, p: &pdfcraft_model::Page, all: &[(Object, Vec<u8>)], img: &PageImage) -> Result<(), EditError> {
fn remove_image_crop(doc: &mut Document, p: &pdfcraft_model::Page, all: &[ContentStream], img: &PageImage) -> Result<(), EditError> {
let pieces = joined(all);
let ops = pieces.parse().ops;
let target = img.op;
let scope = image_scopes(&ops, target, "cropped")?;
let Some((start, _, _)) = scope.transform_scope(target) else {
return Err(EditError::Invalid("the image has no PdfCraft crop to remove".into()));
let crops = |hidden| -> Result<Vec<std::ops::Range<usize>>, EditError> {
let scope = image_scopes(&ops, target, "cropped", hidden)?;
Ok(scope.transform_scope(target).map(|(start, _, _)| app_crop_ranges(&ops, start, target)).unwrap_or_default())
};
let crops = app_crop_ranges(&ops, start, target);
if crops.is_empty() {
return Err(EditError::Invalid("the image has no PdfCraft crop to remove".into()));
let crops_there = crops(crate::text::first_op_after_damage(all, &pieces, &ops))?;
if crops_there.is_empty() {
// A crop in a scope that closes past a stream not read whole may clip what that stream draws.
return Err(EditError::Invalid(if crops(ops.len())?.is_empty() {
"the image has no PdfCraft crop to remove".into()
} else {
"the image's crop may also clip what a content stream that is damaged or can't be decoded draws, so it isn't removed".into()
}));
}
let crops = crops_there;
let changed = crate::text::splice(&pieces, &ops, |index| (Vec::new(), !crops.iter().any(|r| r.contains(&index))));
let contents = crate::text::rewritten_contents(doc, all, changed);
let contents = crate::text::rewritten_contents(doc, all, changed)?;
doc.update_dict(p.obj, |d| d.set(b"Contents".to_vec(), contents))?;
Ok(())
}
@@ -1666,7 +1676,7 @@ pub fn change_image(doc: &mut Document, page: usize, index: usize, change: &Imag
}
};
let changed = crate::text::splice(&pieces, &ops, |index| if index == img.op { (replacement.clone(), false) } else { (Vec::new(), true) });
let contents = crate::text::rewritten_contents(doc, &all, changed);
let contents = crate::text::rewritten_contents(doc, &all, changed)?;
doc.update_dict(p.obj, |d| {
d.set(b"Contents".to_vec(), contents);
if let Some(res) = resources {
@@ -1687,7 +1697,7 @@ pub(crate) fn selectable_images(
Ok(page_images(doc, page)?
.into_iter()
.enumerate()
.filter(|(_, image)| !all.get(image.stream).and_then(|(o, _)| o.as_ref()).is_some_and(|r| excluded.contains(&r)))
.filter(|(_, image)| !all.get(image.stream).and_then(|s| s.entry.as_ref()).is_some_and(|r| excluded.contains(&r)))
.collect())
}
@@ -1700,7 +1710,7 @@ pub(crate) fn painted_over(doc: &Document, page: usize, rect: [f64; 4], from: us
fn transform_image(
doc: &mut Document,
page: &pdfcraft_model::Page,
streams: &[(Object, Vec<u8>)],
streams: &[ContentStream],
image: &PageImage,
transform: [f64; 6],
) -> Result<(), EditError> {
@@ -1715,8 +1725,9 @@ fn transform_image(
}
// A private path crop moves with its image regardless of intervening state operators.
// Shared crops retain the existing fixed-clip behavior, preserving neighbouring paint.
let hidden = crate::text::first_op_after_damage(streams, &pieces, &ops);
let (start, end, placement) =
image_scopes(&ops, target, "transformed")?.transform_scope(target).unwrap_or((target, target, Matrix(image.draw_matrix)));
image_scopes(&ops, target, "transformed", hidden)?.transform_scope(target).unwrap_or((target, target, Matrix(image.draw_matrix)));
let inverse = placement.invert().ok_or_else(|| EditError::Invalid("the image has no area".into()))?;
let local = placement.then(&Matrix(transform)).then(&inverse);
if !local.0.iter().all(|v| v.is_finite() && v.abs() <= 1e12) {
@@ -1725,7 +1736,7 @@ fn transform_image(
// Already alone in a `q cm … Q` (its own placement, or the wrapper an earlier edit added):
// change that `cm` in place. The CTM inside is `local · cm · outer` either way.
if let Some((at, cm)) = enclosing_transform(&ops, start, end) {
if let Some((at, cm)) = enclosing_transform(&ops, start, end, hidden) {
let folded = local.then(&cm);
if !folded.0.iter().all(|v| v.is_finite() && v.abs() <= 1e12) {
return Err(EditError::Invalid("the image transform is too large".into()));
@@ -1733,7 +1744,7 @@ fn transform_image(
let changed = crate::text::splice(&pieces, &ops, |index| {
if index == at { (vec![Op::new("cm", folded.0.map(Object::Real).to_vec())], false) } else { (Vec::new(), true) }
});
let contents = crate::text::rewritten_contents(doc, streams, changed);
let contents = crate::text::rewritten_contents(doc, streams, changed)?;
doc.update_dict(page.obj, |d| d.set(b"Contents".to_vec(), contents))?;
return Ok(());
}
@@ -1754,7 +1765,7 @@ fn transform_image(
(Vec::new(), true)
}
});
let contents = crate::text::rewritten_contents(doc, streams, changed);
let contents = crate::text::rewritten_contents(doc, streams, changed)?;
doc.update_dict(page.obj, |d| d.set(b"Contents".to_vec(), contents))?;
Ok(())
}
@@ -1766,7 +1777,7 @@ fn transform_image(
fn crop_image_impl(
doc: &mut Document,
page: &pdfcraft_model::Page,
streams: &[(Object, Vec<u8>)],
streams: &[ContentStream],
image: &PageImage,
keep: [f64; 4],
) -> Result<(), EditError> {
@@ -1790,8 +1801,9 @@ fn crop_image_impl(
if !ops.get(target).is_some_and(|op| op.is("Do")) {
return Err(EditError::Invalid("the image operation could not be located".into()));
}
let (start, end, placement) =
image_scopes(&ops, target, "cropped")?.transform_scope(target).unwrap_or((target, target, Matrix(image.draw_matrix)));
let (start, end, placement) = image_scopes(&ops, target, "cropped", crate::text::first_op_after_damage(streams, &pieces, &ops))?
.transform_scope(target)
.unwrap_or((target, target, Matrix(image.draw_matrix)));
let inverse = placement.invert().ok_or_else(|| EditError::Invalid("the image has no area".into()))?;
let corners = [(x0, y0), (x1, y0), (x1, y1), (x0, y1)].map(|(x, y)| inverse.apply(x, y));
if !corners.iter().all(|(x, y)| x.is_finite() && y.is_finite() && x.abs() <= 1e12 && y.abs() <= 1e12) {
@@ -1844,7 +1856,7 @@ fn crop_image_impl(
(Vec::new(), true)
}
});
let contents = crate::text::rewritten_contents(doc, streams, changed);
let contents = crate::text::rewritten_contents(doc, streams, changed)?;
doc.update_dict(page.obj, |d| d.set(b"Contents".to_vec(), contents))?;
Ok(())
}
@@ -1872,6 +1884,7 @@ pub(crate) fn translate_images(doc: &mut Document, page: usize, indexes: &[usize
}
let pieces = joined(&all);
let ops = pieces.parse().ops;
let hidden = crate::text::first_op_after_damage(&all, &pieces, &ops);
let mut inside_text = false;
for (index, op) in ops.iter().enumerate() {
if op.is("BT") {
@@ -1889,7 +1902,7 @@ pub(crate) fn translate_images(doc: &mut Document, page: usize, indexes: &[usize
let mut folds = std::collections::BTreeMap::new();
for image in images.iter().filter(|image| image.has_editor_crop()) {
let Some(&(_, _, offset)) = plans.get(&image.op) else { continue };
let Some((start, end, placement)) = image_scopes(&ops, image.op, "moved")?.transform_scope(image.op) else {
let Some((start, end, placement)) = image_scopes(&ops, image.op, "moved", hidden)?.transform_scope(image.op) else {
return Err(EditError::Invalid("the image crop cannot be moved independently".into()));
};
let inverse = placement.invert().ok_or_else(|| EditError::Invalid("a selected image has no area".into()))?;
@@ -1906,7 +1919,7 @@ pub(crate) fn translate_images(doc: &mut Document, page: usize, indexes: &[usize
};
// An enclosing cm is before the captured placement; an inside-scope cm is after it.
// Their multiplication orders differ when that cm scales or shears a translation.
let folded = enclosing_transform(&ops, start, end)
let folded = enclosing_transform(&ops, start, end, hidden)
.map(|(at, cm)| (at, local.then(&cm)))
.or_else(|| leading_transform().map(|(at, cm)| (at, cm.then(&local))));
if let Some((at, folded)) = folded {
@@ -1942,7 +1955,7 @@ pub(crate) fn translate_images(doc: &mut Document, page: usize, indexes: &[usize
// An image already alone in `q cm Do Q` moves by changing that `cm`, not by nesting another.
for index in 0..ops.len() {
let Some(&(movement, _, _)) = plans.get(&index) else { continue };
let Some((at, cm)) = enclosing_transform(&ops, index, index) else { continue };
let Some((at, cm)) = enclosing_transform(&ops, index, index, hidden) else { continue };
let folded = movement.then(&cm);
if !folded.0.iter().all(|v| v.is_finite() && v.abs() <= 1e12) {
return Err(EditError::Invalid("the image move is too large".into()));
@@ -1977,7 +1990,7 @@ pub(crate) fn translate_images(doc: &mut Document, page: usize, indexes: &[usize
out.push(Op::new("Q", vec![]));
(out, false)
});
let contents = crate::text::rewritten_contents(doc, &all, data);
let contents = crate::text::rewritten_contents(doc, &all, data)?;
doc.update_dict(p.obj, |d| d.set(b"Contents".to_vec(), contents))?;
Ok(())
}
+2
View File
@@ -43,6 +43,8 @@ pub use backdrop::{Backdrop, backdrops_left_off, page_backdrop, page_backdrops};
pub use text::strip_subset_tag;
mod background;
pub use background::page_background;
mod rules;
pub use rules::page_rules;
pub mod objects;
pub use objects::{EditableObject, MAX_MOVE_OBJECTS, ObjectKind, ObjectTarget, editable_objects, move_objects};
+14 -9
View File
@@ -4,8 +4,9 @@
use std::collections::{BTreeMap, BTreeSet};
use pdfcraft_content::{Matrix, Op, Pieces};
use pdfcraft_cos::{Dict, Document, Object};
use pdfcraft_cos::{DecodeBudget, Dict, Document, Object};
use crate::text::ContentStream;
use crate::{Content, EditError};
pub const MAX_MOVE_OBJECTS: usize = 1_000;
@@ -152,7 +153,7 @@ fn added_geometry(doc: &Document, page: usize) -> Result<(Pieces, Vec<AddedGeome
return Ok((Pieces::default(), Vec::new()));
}
let streams = checked_streams(doc, page)?;
let pieces = Pieces::join(&streams.iter().map(|(_, bytes)| bytes.as_slice()).collect::<Vec<_>>());
let pieces = crate::text::joined(&streams);
let ops = pieces.parse().ops;
let owned: BTreeSet<_> = added.iter().map(|a| a.obj).collect();
let mut geometry = BTreeMap::new();
@@ -161,7 +162,7 @@ fn added_geometry(doc: &Document, page: usize) -> Result<(Pieces, Vec<AddedGeome
let mut stack = Vec::new();
for (index, op) in ops.iter().enumerate() {
let (stream, end) = pieces.pieces_of(op);
let object = streams.get(stream).and_then(|(r, _)| r.as_ref());
let object = streams.get(stream).and_then(|s| s.entry.as_ref());
if object.is_some_and(|r| owned.contains(&r)) {
if let std::collections::btree_map::Entry::Vacant(entry) = first.entry(stream) {
if stream != end || !op.is("q") {
@@ -275,7 +276,7 @@ fn translate_added(doc: &mut Document, page: usize, indexes: &[usize], offset: [
})
.collect::<Result<Vec<_>, EditError>>()?;
let data = pieces.splice(edits);
let contents = crate::text::rewritten_contents(doc, &streams, data);
let contents = crate::text::rewritten_contents(doc, &streams, data)?;
let refs = match &contents {
Object::Array(a) => a.clone(),
one => vec![one.clone()],
@@ -288,9 +289,9 @@ fn translate_added(doc: &mut Document, page: usize, indexes: &[usize], offset: [
Ok(())
}
/// A missing or undecodable preceding stream can hide graphics state that affects every
/// A missing, undecodable or damaged preceding stream can hide graphics state that affects every
/// later item. Refuse group editing rather than inventing an inventory from partial data.
fn checked_streams(doc: &Document, page: usize) -> Result<Vec<(Object, Vec<u8>)>, EditError> {
fn checked_streams(doc: &Document, page: usize) -> Result<Vec<ContentStream>, EditError> {
let p = pdfcraft_model::pages(doc).into_iter().nth(page).ok_or(EditError::NoSuchPage(page))?;
let contents = match p.dict.get(b"Contents") {
None => Vec::new(),
@@ -305,6 +306,7 @@ fn checked_streams(doc: &Document, page: usize) -> Result<Vec<(Object, Vec<u8>)>
},
};
let mut remaining = MAX_CONTENT_BYTES;
let mut decode = DecodeBudget::new(usize::MAX, 0);
let mut depth = 0usize;
let mut operations = 0usize;
let mut streams = Vec::with_capacity(contents.len());
@@ -313,9 +315,12 @@ fn checked_streams(doc: &Document, page: usize) -> Result<Vec<(Object, Vec<u8>)>
let Object::Stream(stream) = &*resolved else {
return Err(EditError::Invalid("a page content stream is missing".into()));
};
let bytes = stream
.decoded_within(remaining.min(64 * 1024 * 1024))
let (bytes, damaged) = decode
.decode_with_damage(doc, stream, remaining.min(64 * 1024 * 1024))
.map_err(|_| EditError::Invalid("the page content cannot be decoded within its size limit".into()))?;
if damaged {
return Err(EditError::Invalid("a page content stream is damaged partway".into()));
}
remaining =
remaining.checked_sub(bytes.len()).ok_or_else(|| EditError::Invalid("the page content is too large for group selection".into()))?;
let parsed = pdfcraft_content::parse(&bytes);
@@ -333,7 +338,7 @@ fn checked_streams(doc: &Document, page: usize) -> Result<Vec<(Object, Vec<u8>)>
return Err(EditError::Invalid("the page graphics state is nested too deeply".into()));
}
}
streams.push((object, bytes));
streams.push(ContentStream { entry: object, data: bytes, read: crate::text::Read::Whole });
}
Ok(streams)
}
+142
View File
@@ -0,0 +1,142 @@
//! A page's ruled lines: the horizontal and vertical strokes (and thin filled bars) its content
//! draws, so exports can tell a ruled table from text that merely lines up (#5149).
use pdfcraft_content::{Matrix, Pieces};
use pdfcraft_cos::Document;
use crate::EditError;
/// How deep `q` may nest (deeper saves are not tracked).
const MAX_SAVES: usize = 64;
/// At most this many rules are returned, and a path keeps at most this many segments, so a
/// hostile page stays bounded.
pub const MAX_RULES: usize = 4096;
/// A segment whose ends differ by at most this much across its run (points) is horizontal or
/// vertical; a filled rectangle at most this thick is a bar drawn as a rule.
const THIN: f64 = 2.0;
/// The page's ruled lines, each as its box `[x0, y0, x1, y1]` in default user space (`x0 <= x1`,
/// `y0 <= y1`; a stroke has zero thickness): horizontal and vertical straight segments of stroked
/// paths (rectangle edges included) and filled rectangles at most two points thick. Curves,
/// slanted lines and paths that are only clipped are left out, and so are the contents of forms.
/// At most [`MAX_RULES`] rules, in content order.
pub fn page_rules(doc: &Document, page: usize) -> Result<Vec<[f64; 4]>, EditError> {
let pages = pdfcraft_model::pages(doc);
let p = pages.get(page).ok_or(EditError::NoSuchPage(page))?;
let streams = crate::text::content_streams(doc, &p.dict)?;
let pieces = Pieces::join(&streams.iter().map(|(_, d)| d.as_slice()).collect::<Vec<_>>());
let ops = pieces.parse().ops;
let mut out: Vec<[f64; 4]> = Vec::new();
let mut ctm = Matrix::IDENTITY;
let mut saved: Vec<Matrix> = Vec::new();
let mut lost_saves = 0usize;
// The current path in page space: its straight segments, its rectangles, the current point
// and where the current subpath started.
let mut segments: Vec<[(f64, f64); 2]> = Vec::new();
let mut rects: Vec<[(f64, f64); 4]> = Vec::new();
let mut at: Option<(f64, f64)> = None;
let mut start: Option<(f64, f64)> = None;
for op in &ops {
if out.len() >= MAX_RULES {
break;
}
match op.op.as_slice() {
b"q" => {
if saved.len() < MAX_SAVES {
saved.push(ctm);
} else {
lost_saves = lost_saves.saturating_add(1);
}
}
b"Q" => {
if lost_saves > 0 {
lost_saves -= 1;
} else if let Some(m) = saved.pop() {
ctm = m;
}
}
b"cm" => {
if let Some(m) = Matrix::from_operands(&op.operands) {
ctm = m.then(&ctm);
}
}
b"m" => {
let p = op.nums::<2>().map(|[x, y]| ctm.apply(x, y));
(at, start) = (p, p);
}
b"l" => {
let p = op.nums::<2>().map(|[x, y]| ctm.apply(x, y));
if let (Some(a), Some(b)) = (at, p)
&& segments.len() < MAX_RULES
{
segments.push([a, b]);
}
at = p;
}
b"c" => at = op.nums::<6>().map(|[.., x, y]| ctm.apply(x, y)),
b"v" | b"y" => at = op.nums::<4>().map(|[.., x, y]| ctm.apply(x, y)),
b"h" => {
if let (Some(a), Some(b)) = (at, start)
&& segments.len() < MAX_RULES
{
segments.push([a, b]);
}
at = start;
}
b"re" => {
if let Some([x, y, w, h]) = op.nums::<4>() {
let q = [ctm.apply(x, y), ctm.apply(x + w, y), ctm.apply(x + w, y + h), ctm.apply(x, y + h)];
if rects.len() < MAX_RULES {
rects.push(q);
}
(at, start) = (Some(q[0]), Some(q[0]));
}
}
b"S" | b"s" | b"B" | b"B*" | b"b" | b"b*" => {
let closes = matches!(op.op.as_slice(), b"s" | b"b" | b"b*");
if closes && let (Some(a), Some(b)) = (at, start) {
segments.push([a, b]);
}
let edges = rects.iter().flat_map(|q| [[q[0], q[1]], [q[1], q[2]], [q[2], q[3]], [q[3], q[0]]]);
out.extend(segments.iter().copied().chain(edges).filter_map(axis_aligned));
(segments, rects, at, start) = (Vec::new(), Vec::new(), None, None);
}
b"f" | b"F" | b"f*" => {
out.extend(rects.iter().filter_map(thin_bar));
(segments, rects, at, start) = (Vec::new(), Vec::new(), None, None);
}
b"n" => (segments, rects, at, start) = (Vec::new(), Vec::new(), None, None),
_ => {}
}
}
out.truncate(MAX_RULES);
Ok(out)
}
/// The box of a horizontal or vertical segment, or `None` for a slanted, tiny or non-finite one.
fn axis_aligned([a, b]: [(f64, f64); 2]) -> Option<[f64; 4]> {
let r = [a.0.min(b.0), a.1.min(b.1), a.0.max(b.0), a.1.max(b.1)];
let (w, h) = (r[2] - r[0], r[3] - r[1]);
(r.iter().all(|v| v.is_finite()) && w.min(h) <= THIN && w.max(h) > THIN).then_some(r)
}
/// The box of a filled rectangle drawn as a rule: upright, at most [`THIN`] thick and longer than that.
fn thin_bar(q: &[(f64, f64); 4]) -> Option<[f64; 4]> {
let upright = |a: (f64, f64), b: (f64, f64)| (a.0 - b.0).abs() <= 0.01 || (a.1 - b.1).abs() <= 0.01;
if !(upright(q[0], q[1]) && upright(q[1], q[2])) {
return None;
}
let xs = q.map(|p| p.0);
let ys = q.map(|p| p.1);
let r = [
xs.iter().copied().fold(f64::INFINITY, f64::min),
ys.iter().copied().fold(f64::INFINITY, f64::min),
xs.iter().copied().fold(f64::NEG_INFINITY, f64::max),
ys.iter().copied().fold(f64::NEG_INFINITY, f64::max),
];
let (w, h) = (r[2] - r[0], r[3] - r[1]);
(r.iter().all(|v| v.is_finite()) && w.min(h) <= THIN && w.max(h) > THIN).then_some(r)
}
+348
View File
@@ -5306,6 +5306,308 @@ fn the_graphics_state_carries_over_between_content_streams() {
assert!(close(l.rect[0], 100.0) && close(l.size, 10.0), "{l:?}");
}
/// zlib data that reads as `readable` and is then damaged, with more of the stream after the
/// damage: a stored block, then a block of the reserved type (RFC 1951 §3.2.3), then `rest`.
fn damaged_flate(readable: &[u8], rest: &[u8]) -> pdfcraft_cos::Stream {
let len = u16::try_from(readable.len()).unwrap();
let mut raw = vec![0x78, 0x01, 0x00];
raw.extend_from_slice(&len.to_le_bytes());
raw.extend_from_slice(&(!len).to_le_bytes());
raw.extend_from_slice(readable);
raw.push(0x07);
raw.extend_from_slice(rest);
let mut dict = pdfcraft_cos::Dict::new();
dict.set(b"Filter".to_vec(), Object::name("FlateDecode"));
pdfcraft_cos::Stream::from_raw(dict, raw)
}
/// A page whose first content stream is damaged after its text, and whose second is whole.
fn damaged_page() -> (Document, pdfcraft_cos::Stream) {
let mut doc = split_page("", "BT /F1 12 Tf 72 600 Td (Whole) Tj ET");
let damaged = damaged_flate(b"BT /F1 12 Tf 72 700 Td (Damaged) Tj ET\n", b"BT /F1 12 Tf 72 500 Td (After the damage) Tj ET");
doc.set(pdfcraft_cos::ObjRef::new(4, 0), damaged.clone());
(doc, damaged)
}
/// An edit that would rewrite a content stream damaged partway is refused: written from what
/// decoded, it would lose what follows the damage, which other readers may still read. So is an
/// edit in a later stream: what the damage hides can change how that stream reads, a string or
/// comment it leaves open, or the graphics state. An edit in a stream before the damage goes on,
/// and leaves the damaged one as it is stored.
#[test]
fn an_edit_never_rewrites_a_content_stream_damaged_partway() {
let (mut doc, damaged) = damaged_page();
let texts = |doc: &Document| text::text_lines(doc, 0).unwrap().into_iter().map(|l| l.text).collect::<Vec<_>>();
assert_eq!(texts(&doc), ["Damaged", "Whole"], "read up to the damage");
let contents = |doc: &Document| pdfcraft_model::pages(doc)[0].dict.get(b"Contents").cloned();
let listed = contents(&doc);
let refused = text::replace_line(&mut doc, 0, 0, "Edited").unwrap_err();
assert!(refused.to_string().contains("is damaged partway"), "{refused}");
assert_eq!(contents(&doc), listed);
let refused = text::rewrite_block(&mut doc, 0, 0, Some("Edited"), &text::BlockStyle::default()).unwrap_err();
assert!(refused.to_string().contains("is damaged partway"), "{refused}");
assert_eq!(contents(&doc), listed);
let refused = text::replace_line(&mut doc, 0, 1, "Edited").unwrap_err();
assert!(refused.to_string().contains("comes after a content stream that is damaged or can't be decoded"), "{refused}");
assert_eq!(contents(&doc), listed);
let mut doc = split_page("BT /F1 12 Tf 72 600 Td (Whole) Tj ET", "");
doc.set(pdfcraft_cos::ObjRef::new(5, 0), damaged.clone());
text::replace_line(&mut doc, 0, 0, "Edited").unwrap();
let doc = reopen(&doc);
assert_eq!(texts(&doc), ["Edited", "Damaged"]);
let Some(Object::Array(list)) = contents(&doc) else { panic!("contents {:?}", contents(&doc)) };
assert_eq!(list.get(1), Some(&Object::Ref(pdfcraft_cos::ObjRef::new(5, 0))));
let Object::Stream(kept) = &*doc.get(pdfcraft_cos::ObjRef::new(5, 0)) else { panic!("not a stream") };
assert_eq!(kept.raw, damaged.raw, "stored as it was");
}
/// A comment the damage leaves open runs on into the next stream, up to its first end of line,
/// so a string starting there reads as operators: a line of text inside it. That line is in a
/// stream after the damage, and isn't edited.
#[test]
fn text_a_damaged_stream_runs_on_into_is_not_edited() {
let mut doc = split_page("", "(note\nBT /F1 12 Tf 72 600 Td (Inside a string) Tj ET\n) pop");
doc.set(pdfcraft_cos::ObjRef::new(4, 0), damaged_flate(b"0 g % a comment", b"\n"));
let texts = |doc: &Document| text::text_lines(doc, 0).unwrap().into_iter().map(|l| l.text).collect::<Vec<_>>();
assert_eq!(texts(&doc), ["Inside a string"], "the comment runs on into the next stream");
let listed = pdfcraft_model::pages(&doc)[0].dict.get(b"Contents").cloned();
let refused = text::replace_line(&mut doc, 0, 0, "Edited").unwrap_err();
assert!(refused.to_string().contains("comes after"), "{refused}");
assert_eq!(pdfcraft_model::pages(&doc)[0].dict.get(b"Contents").cloned(), listed);
}
/// A content stream that doesn't decode is never written over. A partial rewrite of the page's
/// last paragraph closes its marker past the last operator read, in the page's last stream, here
/// one that doesn't decode: the rewrite is refused, not that stream replaced by the close. An
/// empty stream there takes the close.
#[test]
fn a_content_stream_that_does_not_decode_is_never_written_over() {
let src = "BT /F1 12 Tf 14.4 TL 1 0 0 1 72 700 Tm (Alpha first row.) Tj T* (Alpha next row.) Tj ET";
let mut doc = split_page(src, "");
let mut dict = pdfcraft_cos::Dict::new();
dict.set(b"Filter".to_vec(), Object::name("NoSuchFilter"));
doc.set(pdfcraft_cos::ObjRef::new(5, 0), pdfcraft_cos::Stream::from_raw(dict, b"0 0 1 rg 0 0 10 10 re f".to_vec()));
let contents = |doc: &Document| pdfcraft_model::pages(doc)[0].dict.get(b"Contents").cloned();
let listed = contents(&doc);
let refused = text::replace_block(&mut doc, 0, 0, "One.\nAlpha next row.").unwrap_err();
assert!(refused.to_string().contains("can't be decoded"), "{refused}");
assert_eq!(contents(&doc), listed);
let mut doc = split_page(src, "");
text::replace_block(&mut doc, 0, 0, "One.\nAlpha next row.").unwrap();
let texts: Vec<_> = text::text_blocks(&reopen(&doc), 0).unwrap().into_iter().map(|b| b.text).collect();
assert_eq!(texts, ["One. Alpha next row."]);
}
/// A content stream that doesn't decode at all is no damage to write over: it is kept as stored,
/// and the page's streams before it are read and edited. A stream of a few MB is read for
/// selecting objects.
#[test]
fn a_content_stream_that_does_not_decode_is_kept_and_edited_before() {
let mut doc = split_page("BT /F1 12 Tf 72 600 Td (Whole) Tj ET", "");
let mut dict = pdfcraft_cos::Dict::new();
dict.set(b"Filter".to_vec(), Object::name("NoSuchFilter"));
let unknown = pdfcraft_cos::Stream::from_raw(dict, b"BT /F1 12 Tf 72 700 Td (Unread) Tj ET".to_vec());
doc.set(pdfcraft_cos::ObjRef::new(5, 0), unknown.clone());
text::replace_line(&mut doc, 0, 0, "Edited").unwrap();
let doc = reopen(&doc);
assert_eq!(text::text_lines(&doc, 0).unwrap().into_iter().map(|l| l.text).collect::<Vec<_>>(), ["Edited"]);
let Object::Stream(kept) = &*doc.get(pdfcraft_cos::ObjRef::new(5, 0)) else { panic!("not a stream") };
assert_eq!(kept.raw, unknown.raw, "stored as it was");
let large = format!("{}0 0 m 10 10 l S", " ".repeat(2 << 20));
assert!(editable_objects(&split_page(&large, "BT /F1 12 Tf 72 600 Td (Whole) Tj ET"), 0).is_ok());
}
/// A content stream that doesn't decode hides its operators as damage does. Here its `/Filter` is
/// given by reference, which a file may do and which isn't read here, and it holds a `cm` that
/// moves what the page draws after it. Text and images there aren't edited, as the edit would be
/// worked out without the `cm`.
#[test]
fn content_after_a_stream_that_does_not_decode_is_not_edited() {
use pdfcraft_cos::{Dict, ObjRef, Stream};
let hidden_move = |doc: &mut Document| {
let filter = doc.add(Object::name("FlateDecode"));
let mut s = Stream::flate(Dict::new(), b"1 0 0 1 0 -300 cm");
s.dict.set(b"Filter".to_vec(), Object::Ref(filter));
doc.set(ObjRef::new(4, 0), s);
};
let contents = |doc: &Document| pdfcraft_model::pages(doc)[0].dict.get(b"Contents").cloned();
let mut doc = split_page("", "BT /F1 12 Tf 72 600 Td (After) Tj ET");
hidden_move(&mut doc);
let listed = contents(&doc);
let refused = text::replace_line(&mut doc, 0, 0, "Edited").unwrap_err();
assert!(refused.to_string().contains("comes after a content stream that is damaged or can't be decoded"), "{refused}");
assert_eq!(contents(&doc), listed);
let mut doc = two_stream_image_page("", "q 100 0 0 100 200 200 cm /Im1 Do Q");
hidden_move(&mut doc);
let listed = contents(&doc);
let shift = images::ImageChange::Transform([1.0, 0.0, 0.0, 1.0, 10.0, 0.0]);
let refused = images::change_image(&mut doc, 0, 0, &shift).unwrap_err();
assert!(refused.to_string().contains("comes after"), "{refused}");
assert_eq!(contents(&doc), listed);
}
/// A text object still open at a stream not read whole goes on in it: the text that stream shows
/// starts where the text before it ends, so editing that text would move it. The edit is refused.
/// A change before the text object, in the same stream, goes on. The same holds when the hidden
/// stream is the page's last.
#[test]
fn text_a_stream_not_read_whole_goes_on_from_is_not_edited() {
use pdfcraft_cos::{Dict, ObjRef, Stream};
let contents = |doc: &Document| pdfcraft_model::pages(doc)[0].dict.get(b"Contents").cloned();
// The hidden stream between the text and a stream closing it, or the page's last.
for (damaged, last) in [(false, false), (true, false), (false, true), (true, true)] {
let what = format!("damaged: {damaged}, last: {last}");
let shown: &[u8] = if last { b"(World) Tj ET" } else { b"(World) Tj" };
let mut doc = split_page("BT /F1 12 Tf 72 700 Td (Before) Tj ET BT /F1 12 Tf 72 600 Td (Hello) Tj", "ET");
let hidden = if damaged {
damaged_flate(b"", shown)
} else {
let filter = doc.add(Object::name("FlateDecode"));
let mut s = Stream::flate(Dict::new(), shown);
s.dict.set(b"Filter".to_vec(), Object::Ref(filter));
s
};
let hidden = Object::Ref(doc.add(hidden));
let mut listed = vec![Object::Ref(ObjRef::new(4, 0)), hidden];
if !last {
listed.push(Object::Ref(ObjRef::new(5, 0)));
}
let listed = Object::Array(listed);
doc.update_dict(ObjRef::new(3, 0), |p| p.set(b"Contents".to_vec(), listed.clone())).unwrap();
let lines: Vec<_> = text::text_lines(&doc, 0).unwrap().into_iter().map(|l| l.text).collect();
assert_eq!(lines, ["Before", "Hello"], "{what}");
let refused = text::replace_line(&mut doc, 0, 1, "Hi").unwrap_err();
assert!(refused.to_string().contains("goes on in a content stream"), "{what}: {refused}");
assert_eq!(contents(&doc), Some(listed), "{what}");
text::replace_line(&mut doc, 0, 0, "Earlier").unwrap();
}
}
/// An image's `q cm … Q` that closes past a stream not read whole, one that doesn't decode or one
/// damaged partway, may hold what that stream draws (here a square, in the image's `cm`), also when
/// the square's operands end the stream before it and only its keyword is hidden. Moving the image
/// leaves that `cm` as it is and gives the `Do` a `cm` of its own, so the square stays, with a clip
/// on the image too, which then stays where it is as one the square may share. A crop goes around
/// the `Do` alone, and a crop PdfCraft put in that scope isn't removed. A scope that closes in a
/// damaged stream before its damage holds none of it: its `cm` takes the move.
#[test]
fn an_image_whose_scope_closes_past_a_stream_not_read_whole_moves_alone() {
use pdfcraft_cos::{Dict, ObjRef, Stream};
let contents = |doc: &Document| pdfcraft_model::pages(doc)[0].dict.get(b"Contents").cloned();
let first_stream = |doc: &Document| {
let Some(Object::Array(list)) = contents(doc) else { panic!("contents {:?}", contents(doc)) };
let Some(Object::Stream(first)) = list.first().map(|f| (*doc.resolve(f)).clone()) else { panic!("no first stream") };
String::from_utf8(first.decoded().unwrap()).unwrap()
};
let later_streams = |doc: &Document| match contents(doc) {
Some(Object::Array(list)) => list.get(1..).map(<[Object]>::to_vec),
other => panic!("contents {other:?}"),
};
// The image in `q 100 0 0 100 50 50 cm`, a stream not read whole drawing a square in that
// `cm`, then the scope's `Q`. Split, the square's operands come before the hidden keyword.
let page = |clip: &str, damaged: bool, split: bool| {
let operands = if split && !damaged { " 1.5 0 0.5 0.5" } else { "" };
let mut doc = two_stream_image_page(&format!("q 100 0 0 100 50 50 cm {clip}/Im1 Do{operands}"), "Q");
let hidden = match (damaged, split) {
(true, false) => damaged_flate(b"", b"0 0 1 rg 1.5 0 0.5 0.5 re f"),
(true, true) => damaged_flate(b"0 0 1 rg 1.5 0", b" 0.5 0.5 re f"),
(false, _) => {
let filter = doc.add(Object::name("FlateDecode"));
let mut s = Stream::flate(Dict::new(), if split { b"re f".as_slice() } else { b"0 0 1 rg 1.5 0 0.5 0.5 re f" });
s.dict.set(b"Filter".to_vec(), Object::Ref(filter));
s
}
};
let hidden = doc.add(hidden);
let listed = vec![Object::Ref(ObjRef::new(4, 0)), Object::Ref(hidden), Object::Ref(ObjRef::new(5, 0))];
doc.update_dict(ObjRef::new(3, 0), |p| p.set(b"Contents".to_vec(), Object::Array(listed))).unwrap();
doc
};
let shift = images::ImageChange::Transform([1.0, 0.0, 0.0, 1.0, 10.0, 0.0]);
for damaged in [false, true] {
for split in [false, true] {
for clip in ["", "0 0 1 1 re W n ", "/PdfCraftImageCrop MP 0 0 1 1 re W n "] {
let what = format!("damaged: {damaged}, split: {split}, clip: {clip:?}");
let mut doc = page(clip, damaged, split);
let later = later_streams(&doc);
images::change_image(&mut doc, 0, 0, &shift).unwrap();
assert_eq!(later_streams(&doc), later, "{what}: the streams after it as they were");
let first = first_stream(&doc);
assert!(first.contains("100 0 0 100 50 50 cm"), "{what}: the scope's cm stays: {first}");
assert!(close(images::page_images(&doc, 0).unwrap()[0].rect, [60.0, 50.0, 160.0, 150.0]), "{what}: the image moved");
let mut doc = page(clip, damaged, split);
images::change_image(&mut doc, 0, 0, &images::ImageChange::Crop([60.0, 60.0, 140.0, 140.0])).unwrap();
assert_eq!(later_streams(&doc), later, "{what}: cropped, the streams after it as they were");
let first = first_stream(&doc);
assert!(first.starts_with("q 100 0 0 100 50 50 cm"), "{what}: nothing put at the scope's start: {first}");
if clip.contains("PdfCraftImageCrop") {
let mut doc = page(clip, damaged, split);
let listed = contents(&doc);
let refused = images::change_image(&mut doc, 0, 0, &images::ImageChange::RemoveCrop).unwrap_err();
assert!(refused.to_string().contains("may also clip"), "{what}: {refused}");
assert_eq!(contents(&doc), listed, "{what}");
}
}
}
}
let mut doc = two_stream_image_page("q 100 0 0 100 50 50 cm /Im1 Do", "");
doc.set(ObjRef::new(5, 0), damaged_flate(b"Q\n", b"0 0 1 rg 1.5 0 0.5 0.5 re f"));
images::change_image(&mut doc, 0, 0, &shift).unwrap();
let first = first_stream(&doc);
assert!(first.contains("100 0 0 100 60 50 cm") && !first.contains("50 50 cm"), "closed before the damage: {first}");
}
/// A content stream whose `/DecodeParms`, or a parameter in them, is given by reference is read
/// through the reference: its text is listed and edited, not read with the predictor's tag bytes
/// left in it.
#[test]
fn content_with_parameters_given_by_reference_is_read_and_edited() {
use pdfcraft_cos::{Dict, ObjRef, Stream};
let content = b"BT /F1 12 Tf 72 700 Td (Predicted) Tj ET";
// PNG Up, one column: each byte a row of its own, tagged 2.
let mut rows = Vec::new();
let mut above = 0u8;
for &b in content {
rows.extend([2, b.wrapping_sub(above)]);
above = b;
}
let texts = |doc: &Document| text::text_lines(doc, 0).unwrap().into_iter().map(|l| l.text).collect::<Vec<_>>();
for given in ["parameters", "predictor"] {
let mut doc = split_page("", "BT /F1 12 Tf 72 600 Td (Whole) Tj ET");
let predictor = Object::Int(12);
let parms = if given == "parameters" {
Object::Ref(doc.add(Object::Dict([(b"Predictor".to_vec(), predictor)].into_iter().collect::<Dict>())))
} else {
Object::Dict([(b"Predictor".to_vec(), Object::Ref(doc.add(predictor)))].into_iter().collect())
};
let mut s = Stream::flate(Dict::new(), &rows);
s.dict.set(b"DecodeParms".to_vec(), parms);
doc.set(ObjRef::new(4, 0), s);
assert_eq!(texts(&doc), ["Predicted", "Whole"], "{given} by reference");
text::replace_line(&mut doc, 0, 0, "Edited").unwrap();
assert_eq!(texts(&reopen(&doc)), ["Edited", "Whole"], "{given} by reference");
}
}
/// Objects are selected only from content read whole: what a damaged stream hides past the
/// damage could change the graphics state of every later item.
#[test]
fn objects_are_not_listed_from_a_content_stream_damaged_partway() {
let (doc, _) = damaged_page();
let refused = editable_objects(&doc, 0).unwrap_err();
assert!(refused.to_string().contains("damaged partway"), "{refused}");
assert!(editable_objects(&split_page("", "BT /F1 12 Tf 72 600 Td (Whole) Tj ET"), 0).is_ok());
}
fn two_stream_image_page(first: &str, second: &str) -> Document {
let objs: Vec<String> = vec![
"<< /Type /Catalog /Pages 2 0 R >>".into(),
@@ -5356,6 +5658,52 @@ fn arrange_and_crop_image_in_second_content_stream_succeeds() {
assert_eq!(after_crop[1].visible_rect, Some(after_crop[1].rect));
}
/// What follows the damage in a content stream is unknown, the graphics state the later streams
/// draw in too: here it hides a `cm` that doubles them. An image after the damage isn't moved, as
/// the move is worked out without that `cm`, and one before it isn't arranged to after it, beside
/// an added item there. An image before the damage is moved.
#[test]
fn images_after_a_content_stream_damaged_partway_are_not_moved() {
use pdfcraft_cos::{Dict, ObjRef, Stream};
let image = "q 100 0 0 100 200 200 cm /Im1 Do Q";
let hidden_scale = || damaged_flate(b"0 g\n", b"2 0 0 2 0 0 cm");
let shift = images::ImageChange::Transform([1.0, 0.0, 0.0, 1.0, 10.0, 0.0]);
let contents = |doc: &Document| pdfcraft_model::pages(doc)[0].dict.get(b"Contents").cloned();
let mut doc = two_stream_image_page("", image);
doc.set(ObjRef::new(4, 0), hidden_scale());
let listed = contents(&doc);
let refused = images::change_image(&mut doc, 0, 0, &shift).unwrap_err();
assert!(refused.to_string().contains("comes after"), "{refused}");
assert_eq!(contents(&doc), listed);
let mut doc = two_stream_image_page(image, "");
let damaged = doc.add(hidden_scale());
let mut added = Dict::new();
added.set(b"PCAdded".to_vec(), Object::Dict(Dict::new()));
let added = doc.add(Object::Stream(Stream::from_raw(added, b"q 0 0 1 rg 0 0 10 10 re f Q".to_vec())));
doc.update_dict(ObjRef::new(3, 0), |p| {
p.set(b"Contents".to_vec(), Object::Array(vec![Object::Ref(ObjRef::new(4, 0)), Object::Ref(damaged), Object::Ref(added)]))
})
.unwrap();
let listed = contents(&doc);
let refused = images::change_image(&mut doc, 0, 0, &images::ImageChange::Arrange(images::ArrangeOrder::BringToFront)).unwrap_err();
assert!(refused.to_string().contains("comes after"), "{refused}");
assert_eq!(contents(&doc), listed);
// Arranged within the content before the damage, it goes on.
doc.update_dict(ObjRef::new(3, 0), |p| {
p.set(b"Contents".to_vec(), Object::Array(vec![Object::Ref(ObjRef::new(4, 0)), Object::Ref(added), Object::Ref(damaged)]))
})
.unwrap();
images::change_image(&mut doc, 0, 0, &images::ImageChange::Arrange(images::ArrangeOrder::BringToFront)).unwrap();
let mut doc = two_stream_image_page(image, "");
doc.set(ObjRef::new(5, 0), hidden_scale());
images::change_image(&mut doc, 0, 0, &shift).unwrap();
let moved = images::page_images(&reopen(&doc), 0).unwrap();
assert!(close(moved[0].rect, [210.0, 200.0, 310.0, 300.0]), "{:?}", moved[0].rect);
}
/// One page whose font draws a few Hebrew letters (ToUnicode): A ב, B ד, C י, D ו, E ק, F ש,
/// G ל, H ם. Content streams draw Hebrew in visual order, so "בדיוק" is `(EDCBA)`.
fn hebrew_page(content: &str) -> Document {
+4 -1
View File
@@ -55,7 +55,10 @@ use fallback::{add_type3_font, is_type3_fallback};
pub(crate) use fallback::{glyph_path, type3_font_dict, unique_font_name};
use interp::{Origin, Paint, union};
use lines::page_dict;
pub(crate) use lines::{FormBudget, content_streams, content_streams_within, dict_in_place, form_call, resource_dict, rewritten_contents, splice};
pub(crate) use lines::{
ContentStream, FormBudget, Read, content_streams, content_streams_within, dict_in_place, drawn_before_damage, first_op_after_damage, form_call,
joined, resource_dict, rewritten_contents, splice,
};
pub use lines::{MAX_FORM_DEPTH, MAX_FORM_VISITS, glyph_text_lines, text_lines};
pub use rewrite::{LineEdit, replace_line, rewrite_block};
use rewrite::{coincident_ops, rewrite_block_from};
+4 -4
View File
@@ -1,7 +1,7 @@
use super::interp::{Carry, interpret};
use super::lines::{content_streams, page_dict, reading_lines, rewritten_contents, splice, text_lines};
use super::lines::{content_streams, joined, page_dict, reading_lines, rewritten_contents, splice, text_lines};
use super::rewrite::{LineEdit, coincident_ops, rewrite_block};
use super::{Document, EditError, HashMap, Object, Op, Pieces, TextLine, group_blocks, regions};
use super::{Document, EditError, HashMap, Object, Op, TextLine, group_blocks, regions};
/// An editable text region: adjacent runs on visual rows, followed by aligned rows.
/// A region may contain several source fonts, sizes, colours and weights.
@@ -270,7 +270,7 @@ pub fn clear_block(doc: &mut Document, page: usize, block: usize) -> Result<(),
let p = page_dict(doc, page)?;
let res = p.dict.get(b"Resources").and_then(|r| doc.resolve(r).as_dict().cloned()).unwrap_or_default();
let streams = content_streams(doc, &p.dict)?;
let pieces = Pieces::join(&streams.iter().map(|(_, d)| d.as_slice()).collect::<Vec<_>>());
let pieces = joined(&streams);
let ops = pieces.parse().ops;
let shown = interpret(doc, &ops, &res, &mut HashMap::new(), &mut Carry::new(), None, None)?;
let mut patches = HashMap::new();
@@ -297,7 +297,7 @@ pub fn clear_block(doc: &mut Document, page: usize, block: usize) -> Result<(),
patches.insert(s.op, replacement);
}
let data = splice(&pieces, &ops, |i| patches.remove(&i).map_or((Vec::new(), true), |v| (v, false)));
let contents = rewritten_contents(doc, &streams, data);
let contents = rewritten_contents(doc, &streams, data)?;
doc.update_dict(p.obj, |d| d.set(b"Contents".to_vec(), contents))?;
Ok(())
}
+132 -23
View File
@@ -61,16 +61,37 @@ impl TextLine {
}
}
/// The page's content streams as listed, each with its decoded data (empty when it doesn't
/// decode), within one page's [`DecodeBudget`]. An error when the content runs past it: reading
/// or rewriting a page from part of its content would lose the rest.
pub(crate) fn content_streams(doc: &Document, page: &Dict) -> Result<Vec<(Object, Vec<u8>)>, EditError> {
/// One entry of a page's `/Contents`, and what it decoded to.
pub(crate) struct ContentStream {
/// The entry as listed.
pub(crate) entry: Object,
/// Its decoded data, empty when it doesn't decode.
pub(crate) data: Vec<u8>,
/// How much of it decoded.
pub(crate) read: Read,
}
/// How much of a content stream decoded ([`rewritten_contents`] says what each allows).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Read {
Whole,
/// Damaged partway: the data is what decoded before the damage. What follows it is unknown,
/// the graphics state and syntax the later streams start in too.
Damaged,
/// Not at all (a filter this reader lacks, say): the data is empty.
Unread,
}
/// The page's content streams as listed, each with its decoded data, within one page's
/// [`DecodeBudget`]. An error when the content runs past it: reading or rewriting a page from
/// part of its content would lose the rest.
pub(crate) fn content_streams(doc: &Document, page: &Dict) -> Result<Vec<ContentStream>, EditError> {
content_streams_within(doc, page, &mut DecodeBudget::page())
}
/// [`content_streams`], decoded against `budget`, which a walk of the page's forms then goes on
/// spending.
pub(crate) fn content_streams_within(doc: &Document, page: &Dict, budget: &mut DecodeBudget) -> Result<Vec<(Object, Vec<u8>)>, EditError> {
pub(crate) fn content_streams_within(doc: &Document, page: &Dict, budget: &mut DecodeBudget) -> Result<Vec<ContentStream>, EditError> {
let list: Vec<Object> = match page.get(b"Contents") {
None => Vec::new(),
Some(c) => match &*doc.resolve(c) {
@@ -79,20 +100,26 @@ pub(crate) fn content_streams_within(doc: &Document, page: &Dict, budget: &mut D
},
};
let mut out = Vec::with_capacity(list.len());
for o in list {
let data = match &*doc.resolve(&o) {
Object::Stream(s) => match budget.decode(s) {
Ok(data) => data,
for entry in list {
let (data, read) = match &*doc.resolve(&entry) {
Object::Stream(s) => match budget.decode_with_damage(doc, s, usize::MAX) {
Ok((data, damaged)) => (data, if damaged { Read::Damaged } else { Read::Whole }),
Err(e) if budget.remaining() == 0 => return Err(EditError::Invalid(format!("the page content is too large to read: {e}"))),
Err(_) => Vec::new(),
Err(_) => (Vec::new(), Read::Unread),
},
_ => Vec::new(),
// Nothing to lose: a null or missing entry draws nothing.
_ => (Vec::new(), Read::Whole),
};
out.push((o, data));
out.push(ContentStream { entry, data, read });
}
Ok(out)
}
/// The page's streams joined into the one stream they are: an operator may span two of them.
pub(crate) fn joined(streams: &[ContentStream]) -> Pieces {
Pieces::join(&streams.iter().map(|s| s.data.as_slice()).collect::<Vec<_>>())
}
/// Rewrite a page's content (its streams joined, see [`Pieces`]): `edit(i)` gives the operators
/// to insert before operator `i` of `ops` (parsed from the joined pieces) and whether to keep it.
/// Everything else is copied byte for byte. A page's streams are one stream in pieces, split
@@ -120,26 +147,108 @@ pub(crate) fn splice(pieces: &Pieces, ops: &[Op], mut edit: impl FnMut(usize) ->
pieces.splice(edits)
}
/// An error when content at `/Contents` index `at` (a stream there, or one inserted there) is drawn
/// after a stream not read whole, damaged partway or not decoding at all: what wasn't read can
/// change how it reads, the graphics state it draws in among it.
pub(crate) fn drawn_before_damage(streams: &[ContentStream], at: usize) -> Result<(), EditError> {
if at > first_damaged(streams) {
return Err(EditError::Invalid(
"this change comes after a content stream that is damaged or can't be decoded, and what wasn't read can change how the rest of the page reads"
.into(),
));
}
Ok(())
}
/// The index of the first stream not read whole, or the number of streams.
fn first_damaged(streams: &[ContentStream]) -> usize {
streams.iter().position(|s| s.read != Read::Whole).unwrap_or(streams.len())
}
/// The index of the first of `ops`, parsed from `pieces` (the [`joined`] `streams`), drawn after a
/// stream not read whole, or `ops.len()`. A `q … Q` still open there may hold what wasn't read,
/// painting in the state it sets. An operator counts by its keyword: one whose operands start
/// before such a stream takes them from around what wasn't read.
pub(crate) fn first_op_after_damage(streams: &[ContentStream], pieces: &Pieces, ops: &[Op]) -> usize {
let damaged = first_damaged(streams);
ops.iter().position(|op| pieces.pieces_of(op).1 > damaged).unwrap_or(ops.len())
}
/// Whether `new` changes a text object still open at the first stream not read whole. The text
/// object goes on in it, and the text it shows there starts where this text ends: a change of this
/// text moves it. A change before the text object doesn't.
fn changes_text_open_into_damage(streams: &[ContentStream], new: &[Vec<u8>]) -> bool {
let upto = first_damaged(streams).saturating_add(1);
if upto > streams.len() {
return false;
}
let before = Pieces::join(&streams.iter().take(upto).map(|s| s.data.as_slice()).collect::<Vec<_>>());
let mut open = None;
for op in before.parse().ops {
match op.op.as_slice() {
b"BT" => open = Some(op.span.start),
b"ET" => open = None,
_ => {}
}
}
let Some(at) = open else { return false };
let after = Pieces::join(&new.iter().take(upto).map(Vec::as_slice).collect::<Vec<_>>());
// Unchanged from the text object's start to the stream not read whole: it ends the same.
!before.data().get(at..).is_some_and(|text| after.data().ends_with(text))
}
/// The page's `/Contents` after a [`splice`]: pieces whose bytes changed become new streams
/// (keeping their dictionaries), the others stay as they were.
pub(crate) fn rewritten_contents(doc: &mut Document, streams: &[(Object, Vec<u8>)], new: Vec<Vec<u8>>) -> Object {
let mut contents: Vec<Object> = Vec::with_capacity(streams.len());
for ((obj, old), data) in streams.iter().zip(new) {
if *old == data {
contents.push(obj.clone());
/// (keeping their dictionaries), the others stay as they were. An error, before anything is
/// added, when a piece that changed is a stream that didn't decode whole, or comes after one.
/// Written from what decoded, a damaged stream would lose everything after the damage, and one
/// that doesn't decode all of it. What follows the damage is unknown, so a later stream may not
/// read as it seems: a string or comment the damage left open runs on into it, and operators the
/// damage hides can change the graphics state it draws in. A stream that doesn't decode hides its
/// operators all the same.
pub(crate) fn rewritten_contents(doc: &mut Document, streams: &[ContentStream], new: Vec<Vec<u8>>) -> Result<Object, EditError> {
// The last stream that changed: when it is drawn before the damage, so are the others.
if let Some(i) = streams.iter().zip(&new).rposition(|(s, data)| s.data != *data) {
drawn_before_damage(streams, i)?;
}
if changes_text_open_into_damage(streams, &new) {
return Err(EditError::Invalid(
"this change is in a text object that goes on in a content stream that is damaged or can't be decoded, whose text starts where this text ends"
.into(),
));
}
for (s, data) in streams.iter().zip(&new) {
if s.data == *data {
continue;
}
let mut dict = match &*doc.resolve(obj) {
match s.read {
Read::Whole => {}
Read::Damaged => {
return Err(EditError::Invalid(
"this change is in a content stream that is damaged partway, and rewriting it would lose what follows the damage".into(),
));
}
Read::Unread => {
return Err(EditError::Invalid("this change is in a content stream that can't be decoded, and rewriting it would lose it".into()));
}
}
}
let mut contents: Vec<Object> = Vec::with_capacity(streams.len());
for (s, data) in streams.iter().zip(new) {
if s.data == data {
contents.push(s.entry.clone());
continue;
}
let mut dict = match &*doc.resolve(&s.entry) {
Object::Stream(s) => s.dict.clone(),
_ => Dict::new(),
};
dict.remove(b"Length");
contents.push(Object::Ref(doc.add(Object::Stream(Stream::flate(dict, &data)))));
}
match <[Object; 1]>::try_from(contents) {
Ok(match <[Object; 1]>::try_from(contents) {
Ok([one]) => one,
Err(many) => Object::Array(many),
}
})
}
pub(crate) fn page_dict(doc: &Document, page: usize) -> Result<pdfcraft_model::Page, EditError> {
@@ -201,7 +310,7 @@ fn text_lines_in(doc: &Document, p: &pdfcraft_model::Page, actual_text: bool) ->
let mut carry = Carry::new();
// The streams are one stream in pieces (§7.8.2), split between any two tokens: parse them
// joined, so an operator whose operands end one piece still has them.
let pieces = Pieces::join(&content_streams(doc, &p.dict)?.into_iter().map(|(_, d)| d).collect::<Vec<_>>());
let pieces = joined(&content_streams(doc, &p.dict)?);
let ops = pieces.parse().ops;
let properties = res.get(b"Properties").and_then(|o| doc.dict(o)).unwrap_or_default();
let shown = interpret(doc, &ops, &res, &mut cache, &mut carry, None, actual_text.then_some(&properties))?;
@@ -608,7 +717,7 @@ pub(super) fn reading_lines(doc: &Document, page: usize) -> Result<(Vec<TextLine
// do: a comment, an operator's operands or a marked-content sequence (its /ActualText too)
// can run on from one stream into the next. Text still counts as the stream its operator
// starts in, which keeps lines from different streams apart.
let pieces = Pieces::join(&streams.into_iter().map(|(_, data)| data).collect::<Vec<_>>());
let pieces = joined(&streams);
let ops = pieces.parse().ops;
let stream_of = |i: usize| ops.get(i).map_or(0, |op| pieces.pieces_of(op).0);
walk(&mut w, &ops, &res, &mut carry, &stream_of)?;
+10 -10
View File
@@ -4,10 +4,10 @@ use super::fallback::{
source_program_completes, source_show, source_space, source_width, type3_encode, type3_font,
};
use super::interp::{Carry, Origin, TextState, interpret};
use super::lines::{content_streams, page_dict, rewritten_contents, splice, text_lines};
use super::lines::{content_streams, joined, page_dict, rewritten_contents, splice, text_lines};
use super::{
Dict, Document, EditError, HashMap, Matrix, Metrics, Object, Op, PdfString, Pieces, TextLine, TextSession, alignment_frame, group_blocks,
is_centred, parse, rewrite_styled_block,
Dict, Document, EditError, HashMap, Matrix, Metrics, Object, Op, PdfString, TextLine, TextSession, alignment_frame, group_blocks, is_centred,
parse, rewrite_styled_block,
};
/// What replacing a line did.
@@ -56,7 +56,7 @@ pub(crate) fn replace_line_with_limit(doc: &mut Document, page: usize, line: usi
let mut res = p.dict.get(b"Resources").map(|r| doc.resolve(r)).and_then(|r| r.as_dict().cloned()).unwrap_or_default();
let mut fonts_res = res.get(b"Font").map(|f| doc.resolve(f)).and_then(|f| f.as_dict().cloned()).unwrap_or_default();
let streams = content_streams(doc, &p.dict)?;
let pieces = Pieces::join(&streams.iter().map(|(_, d)| d.as_slice()).collect::<Vec<_>>());
let pieces = joined(&streams);
let ops = pieces.parse().ops;
let first = target.ops.first().copied().filter(|i| *i < ops.len()).ok_or_else(|| EditError::Invalid("the page's content changed".into()))?;
// The line's own font, when it can show every character.
@@ -127,7 +127,7 @@ pub(crate) fn replace_line_with_limit(doc: &mut Document, page: usize, line: usi
}
// Rebuild: the line's first operator becomes the replacement, its others go.
let new_data = splice(&pieces, &ops, |i| if i == first { (std::mem::take(&mut replacement), false) } else { (Vec::new(), !drops.contains(&i)) });
let contents = rewritten_contents(doc, &streams, new_data);
let contents = rewritten_contents(doc, &streams, new_data)?;
let page_ref = p.obj;
if substituted.is_some() {
res.set(b"Font".to_vec(), Object::Dict(fonts_res));
@@ -834,7 +834,7 @@ pub(crate) fn rewrite_block_from(
}
let upright = dispatch.upright;
let streams = content_streams(doc, &p.dict)?;
let pieces = Pieces::join(&streams.iter().map(|(_, d)| d.as_slice()).collect::<Vec<_>>());
let pieces = joined(&streams);
let ops = pieces.parse().ops;
let text = paragraph_text(text.unwrap_or(&b.text));
// The characters to show, for choosing fonts: the breaks are moves, not glyphs.
@@ -970,7 +970,7 @@ pub(crate) fn rewrite_block_from(
let insert = if i == at { std::mem::take(&mut block_ops) } else { Vec::new() };
(insert, !dropped.contains(&i))
});
let contents = rewritten_contents(doc, &streams, new_data);
let contents = rewritten_contents(doc, &streams, new_data)?;
let new_font = !reuse;
if new_font {
res.set(b"Font".to_vec(), Object::Dict(fonts_res));
@@ -1040,7 +1040,7 @@ pub(crate) fn selectable_blocks(
!b.lines
.iter()
.filter_map(|i| lines.get(*i))
.any(|l| streams.get(l.stream).and_then(|(o, _)| o.as_ref()).is_some_and(|r| excluded.contains(&r)))
.any(|l| streams.get(l.stream).and_then(|s| s.entry.as_ref()).is_some_and(|r| excluded.contains(&r)))
})
.collect())
}
@@ -1134,7 +1134,7 @@ pub(crate) fn translate_blocks(doc: &mut Document, page: usize, indexes: &[usize
}
let res = p.dict.get(b"Resources").map(|r| doc.resolve(r)).and_then(|r| r.as_dict().cloned()).unwrap_or_default();
let fonts = res.get(b"Font").map(|r| doc.resolve(r)).and_then(|r| r.as_dict().cloned()).unwrap_or_default();
let pieces = Pieces::join(&streams.iter().map(|(_, d)| d.as_slice()).collect::<Vec<_>>());
let pieces = joined(&streams);
let ops = pieces.parse().ops;
let shown = interpret(doc, &ops, &res, &mut HashMap::new(), &mut Carry::new(), None, None)?;
let mut patches = HashMap::new();
@@ -1205,7 +1205,7 @@ pub(crate) fn translate_blocks(doc: &mut Document, page: usize, indexes: &[usize
return Err(EditError::Invalid("a selected text operation cannot be moved".into()));
}
let data = splice(&pieces, &ops, |i| patches.remove(&i).map_or((Vec::new(), true), |v| (v, false)));
let contents = rewritten_contents(doc, &streams, data);
let contents = rewritten_contents(doc, &streams, data)?;
doc.update_dict(p.obj, |d| d.set(b"Contents".to_vec(), contents))?;
Ok(())
}
+2 -2
View File
@@ -962,7 +962,7 @@ pub(crate) fn rewrite_styled_block(
};
let (rows, row_ranges, row_lines, row_soft, row_gap) = wrap_styled_rows(&chars, width, measure)?;
let streams = content_streams(doc, &p.dict)?;
let pieces = Pieces::join(&streams.iter().map(|(_, d)| d.as_slice()).collect::<Vec<_>>());
let pieces = crate::text::joined(&streams);
let ops = pieces.parse().ops;
// A row the edit doesn't reach keeps its source operators, so its kerning, TJ word gaps and
// glyph widths stay exactly as they were instead of being rebuilt from the text state. A row
@@ -1206,7 +1206,7 @@ pub(crate) fn rewrite_styled_block(
// when the rewrite splits one, and a kept row's operators come later in the stream.
let marker = if marked { None } else { paragraph_marker(block, lines, &ops) };
let data = splice_with_marker(&pieces, &ops, marker, at, block_ops, &drop);
let contents = rewritten_contents(doc, &streams, data);
let contents = rewritten_contents(doc, &streams, data)?;
res.set(b"Font".to_vec(), Object::Dict(fonts));
doc.update_dict(p.obj, |d| {
d.set(b"Contents".to_vec(), contents);
+3 -1
View File
@@ -313,7 +313,9 @@ impl crate::Document {
}
// The page colour (Edit a PDF ▸ Background, a producer's page fill) for formats that keep one.
let background = pdfcraft_edit::page_background(cos, i).ok().flatten();
pdfcraft_export::Page { width: info.width as f64, height: info.height as f64, blocks, images, background }
// The ruled lines tell a drawn table from text that merely lines up (#5149).
let rules = pdfcraft_edit::page_rules(cos, i).unwrap_or_default().into_iter().map(visible_rect).collect();
pdfcraft_export::Page { width: info.width as f64, height: info.height as f64, blocks, images, background, rules }
})
.collect();
(pages, truncated)
+95 -20
View File
@@ -8,7 +8,8 @@ use pdfcraft_render::{DocInfo, RenderConfig, RenderPool};
use crate::history::Editor;
use crate::{
CalculationOrder, CheckStyle, DocId, Edit, EditError, EditableObject, FormFieldKind, Hidden, InitialView, Label, MarkKind, SecuritySummary,
SignatureInfo, TabOrder, TrustStore, XfaLayout, a11y, form_appearance, guard, js, measure, optimize, renderer_password, unrestricted,
SignatureInfo, StatusCaptions, TabOrder, TrustStore, XfaLayout, a11y, form_appearance, guard, js, measure, optimize, renderer_password,
signatures_of, unrestricted,
};
#[cfg(test)]
use crate::{record_link_scan, record_marker_scan};
@@ -19,8 +20,9 @@ pub struct Document {
pub path: Option<String>,
/// The working file: what Save writes.
pub bytes: Arc<Vec<u8>>,
/// What is displayed (the page view, `page_render`, page images): `bytes`, plus appearances
/// drawn for display only for comments that have none ([`display_bytes`]). Never saved.
/// What is displayed (the page view, `page_render`, page images): `bytes`, plus what is drawn
/// for display only ([`display_bytes`]): appearances for comments that have none, and the
/// states of named-layer signatures. Never saved.
pub display: Arc<Vec<u8>>,
pub info: DocInfo,
pub renderer: RenderPool,
@@ -41,6 +43,9 @@ pub struct Document {
/// Signature fields, validated against the session's trust store (Signatures panel).
pub signatures: Arc<Vec<SignatureInfo>>,
pub(crate) trust: Arc<TrustStore>,
/// The words signature status layers are drawn with (the session's, see
/// [`Session::set_signature_captions`](crate::Session::set_signature_captions)).
pub(crate) captions: Arc<StatusCaptions>,
pub(crate) sig_cache: Arc<pdfcraft_sign::DigestCache>,
pub(crate) editor: Option<Editor>,
pub(crate) config: RenderConfig,
@@ -649,25 +654,84 @@ pub(crate) fn is_placeholder_title(title: &str) -> bool {
address || t == "untitled"
}
/// The working file plus appearances for comments that have none, and for form fields the file
/// leaves to the viewer (#3470). Signature artwork is preserved; validation badges belong to the
/// viewer and never enter these bytes, which image/text exports and Print as Image also consume.
pub(crate) fn display_bytes(editor: Option<&mut Editor>, bytes: &Arc<Vec<u8>>) -> Arc<Vec<u8>> {
/// What is displayed: the working file plus, in memory only and never saved, the appearances
/// PdfCraft draws for comments that have none ([`pdfcraft_annot::with_missing_appearances`]) and
/// for form fields the file leaves to the viewer (#3470), and the signature states drawn into
/// named-layer signature appearances ([`pdfcraft_sign::show_status_layers`]). The working file is
/// unchanged, and so is everything that reads it (saving, signatures, …). Image and text exports
/// and Print as Image read these bytes, so they show the page as displayed; validation badges
/// belong to the viewer and never enter them.
///
/// `signatures` is input and output: each one whose state gets drawn comes back marked
/// (`verdict_shown`). A mark describes the bytes returned, so every mark is cleared first and a
/// copy that cannot be written takes its marks with it.
pub(crate) fn display_bytes(
editor: Option<&mut Editor>,
bytes: &Arc<Vec<u8>>,
signatures: &mut [SignatureInfo],
captions: &StatusCaptions,
) -> Arc<Vec<u8>> {
for sig in signatures.iter_mut() {
sig.verdict_shown = false;
}
let Some(e) = editor else { return bytes.clone() };
let comments = pdfcraft_annot::with_missing_appearances_cached(&e.cos, &mut e.appearances);
let fields = pdfcraft_forms::with_field_appearances_cached(comments.as_ref().unwrap_or(&e.cos), &mut e.field_appearances);
let Some(display) = fields.or(comments) else {
if let Some(mut display) = fields.or(comments) {
// Written whether or not a signature changed: the copy exists for the comments and fields.
let _ = pdfcraft_sign::show_status_layers(&mut display, signatures, captions);
return write_display_copy(e, bytes, &display, signatures);
}
// No comment or field needed an appearance, so there is no copy yet: build one only when a
// signature's state would change it.
if !pdfcraft_sign::has_status_layers(&e.cos, signatures) {
return bytes.clone();
};
match write_incremental(&display, &SaveOptions::default()) {
}
let mut display = e.cos.clone();
if !pdfcraft_sign::show_status_layers(&mut display, signatures, captions) {
return bytes.clone();
}
write_display_copy(e, bytes, &display, signatures)
}
/// Write the display copy, or keep the working file when it cannot be written. The page then
/// shows the file's own artwork, so the marks are cleared. Losing the copy is a repair, so it is
/// logged, once however many refreshes lose it again.
pub(crate) fn write_display_copy(
e: &mut Editor,
bytes: &Arc<Vec<u8>>,
display: &pdfcraft_cos::Document,
signatures: &mut [SignatureInfo],
) -> Arc<Vec<u8>> {
match write_incremental(display, &SaveOptions::default()) {
Ok(written) => Arc::new(written),
Err(err) => {
e.cos.note_repair(format!("missing comment or field appearances could not be drawn ({err})"));
for sig in signatures.iter_mut() {
sig.verdict_shown = false;
}
let line = format!("the display copy could not be written, so pages show the file as stored ({err})");
if !e.cos.repair_log().contains(&line) {
e.cos.note_repair(line);
}
bytes.clone()
}
}
}
/// Carry the marks across a revalidation that leaves the display copy alone, when it may: only
/// when every verdict is the one the copy was drawn with. Returns whether it did; otherwise the
/// copy has to be drawn again.
pub(crate) fn carry_verdict_marks(previous: &[SignatureInfo], next: &mut [SignatureInfo]) -> bool {
let unchanged = previous.len() == next.len()
&& previous.iter().zip(next.iter()).all(|(p, n)| p.field == n.field && p.revision == n.revision && p.status == n.status);
if unchanged {
for (p, n) in previous.iter().zip(next.iter_mut()) {
n.verdict_shown = p.verdict_shown;
}
}
unchanged
}
/// `comments` (the display copy with comment appearances, if it needed any; else the document
/// itself) with its form fields drawn from their values where the file leaves that to the viewer.
fn with_field_appearances(comments: Option<pdfcraft_cos::Document>, doc: &pdfcraft_cos::Document) -> Option<pdfcraft_cos::Document> {
@@ -694,17 +758,28 @@ pub(crate) fn info_fields<'a>(info: &'a mut DocInfo, cos: &pdfcraft_cos::Documen
]
}
/// 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
/// unparseable file, a write failure or a parser panic falls back to the original bytes.
/// The copy PDFCraft displays when opening `bytes` with no trusted certificates and English
/// captions ([`display_bytes`]): appearances drawn, in memory only, for comments that have none
/// and form fields the file leaves to the viewer, and the state of each named-layer signature.
/// 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: a file with nothing to draw, an
/// unparseable file, a write failure or a parser panic gives back the original bytes.
pub fn display_bytes_for(bytes: Arc<Vec<u8>>, password: Option<&str>) -> Arc<Vec<u8>> {
guard(|| {
pdfcraft_cos::Document::open_with_password(bytes.clone(), password)
.ok()
.and_then(|cos| with_field_appearances(pdfcraft_annot::with_missing_appearances(&cos), &cos))
.and_then(|display| write_incremental(&display, &SaveOptions::default()).ok())
.map(Arc::new)
let cos = pdfcraft_cos::Document::open_with_password(bytes.clone(), password).ok()?;
let mut signatures = signatures_of(&cos, &bytes, &TrustStore::default(), &pdfcraft_sign::DigestCache::default());
let layered = pdfcraft_sign::has_status_layers(&cos, &signatures);
let (mut display, added) = match with_field_appearances(pdfcraft_annot::with_missing_appearances(&cos), &cos) {
Some(display) => (display, true),
None if layered => (cos, false),
None => return None,
};
// As in the app, a layer recognised but not drawn after all makes no copy.
let drawn = layered && pdfcraft_sign::show_status_layers(&mut display, &mut signatures, &StatusCaptions::default());
if !(added || drawn) {
return None;
}
write_incremental(&display, &SaveOptions::default()).ok().map(Arc::new)
})
.ok()
.flatten()
+6 -5
View File
@@ -1,8 +1,8 @@
//! Export a PDF ▸ Image and Text (execution plan M10.3, the first formats).
//!
//! [`Exporter`] renders pages to PNG, JPEG or TIFF at a resolution and extracts reading-order
//! text, from a
//! document's working file (so unsaved edits and hidden layers are respected, as on screen).
//! text, from the copy a document displays ([`Document::export_source`]): its working file, so
//! unsaved edits and hidden layers are respected, with what is drawn for display only.
use std::collections::BTreeMap;
use std::panic::{AssertUnwindSafe, catch_unwind};
@@ -67,9 +67,10 @@ pub struct ExportSource {
impl Document {
/// What an export reads, for exporting on another thread. These are the displayed
/// bytes, so they may carry missing comment appearances PdfCraft drew. Signature
/// artwork stays original; viewer validation badges are not document content and
/// do not enter image/text exports or Print as Image. Saving uses the working file.
/// bytes, so they may carry appearances PdfCraft drew that the file itself does not hold:
/// missing comment appearances, and the signature states of named-layer signature
/// appearances. Exports and Print as Image follow the page as shown; the viewer's badges
/// are not document content and never enter them. Saving uses the working file.
pub fn export_source(&self) -> ExportSource {
ExportSource {
bytes: self.display.clone(),
+6 -2
View File
@@ -429,12 +429,16 @@ impl Session {
let mut out = Vec::new();
for page in list {
let Some(info) = doc.info.pages.get(page) else { continue };
let res = r.render(pdfcraft_render::RenderRequest { page, kind: pdfcraft_render::RequestKind::Text, scale: 1.0, ..Default::default() });
let shapes = pdfcraft_forms::detect::page_shapes(cos, page);
let existing: Vec<[f64; 4]> = doc.form.iter().flat_map(|f| f.widgets.iter()).filter(|w| w.page == Some(page)).map(|w| w.rect).collect();
let (found, turn) = if shapes.boxes.is_empty() && shapes.rules.is_empty() && crate::scan_fields::is_scan(doc, page, info) {
self.detect_on_scan(id, &mut r, page, res.text.as_deref(), &existing, &taken)
// Labels come from the page's own text. Words that only /ActualText names (a stamp
// drawn as outlines) are no labels, and leave the scan to be read.
let own = crate::ocr::own_text(&mut r, page).ok();
self.detect_on_scan(id, &mut r, page, own.as_ref(), &existing, &taken)
} else {
let res =
r.render(pdfcraft_render::RenderRequest { page, kind: pdfcraft_render::RequestKind::Text, scale: 1.0, ..Default::default() });
let words = res.text.map(|t| detection_words(&t, info)).unwrap_or_default();
(pdfcraft_forms::detect::detect(&words, &shapes, &existing, &taken), 0)
};
+3 -2
View File
@@ -129,8 +129,9 @@ pub use pdfcraft_redact::patterns::{
MAX_WORDS as REDACT_MAX_WORDS, PATTERNS as REDACT_PATTERNS, Pattern as RedactPattern, find as find_pattern, word_list as redact_word_list,
};
pub use pdfcraft_redact::sanitize::{HIDDEN, Hidden};
pub use pdfcraft_redact::user_regex::{UserRegex as RedactRegex, VALIDATORS as REDACT_VALIDATORS, Validator as RedactValidator};
pub use pdfcraft_sign as sign;
pub use pdfcraft_sign::{SignOptions, SignatureInfo, Status as SignatureStatus, TrustStore};
pub use pdfcraft_sign::{SignOptions, SignatureInfo, Status as SignatureStatus, StatusCaptions, TrustStore};
pub use pdfcraft_xfdf::Format as DataFormat;
pub use pdfcraft_xfdf::{Outline as CommentOutline, comment_count, comment_outlines, comments_bounds, is_xfdf_comments};
@@ -141,7 +142,7 @@ pub use comments::{SummarySort, comment_kind, comment_summary, comment_type_name
#[cfg(test)]
use document::page_runs;
pub use document::{Document, EditNotice, TextNotice, display_bytes_for, render_password_for};
use document::{display_bytes, info_fields, recovered_render_password, same_pages, shown_under_redactions, undrawn_notices};
use document::{carry_verdict_marks, display_bytes, info_fields, recovered_render_password, same_pages, shown_under_redactions, undrawn_notices};
pub use edit::{BATCH_LABELS, EDIT_LABELS, Edit};
pub use error::{EditError, SourceProblem};
pub use fill_sign::{displayed_offset, text_box_at, typed_signature_graphic, typed_signature_shape};
+44 -2
View File
@@ -11,6 +11,7 @@ use std::sync::{Arc, Mutex};
#[cfg(not(target_arch = "wasm32"))]
use std::time::{Duration, Instant};
use pdfcraft_render::text::TextFilter;
use pdfcraft_render::{PageInfo, PageRenderer, RenderConfig, RenderRequest, RequestKind};
pub use pdfcraft_ocr::{
@@ -161,6 +162,18 @@ const ALREADY_ON_PAGE: f32 = 0.5;
/// is a resolution on paper this size or smaller.
const SHEET: f32 = 842.0;
/// The text of `page`'s own: its glyphs, without the words drawn as outlines or pictures that only
/// `/ActualText` names.
pub(crate) fn own_text(r: &mut PageRenderer, page: usize) -> Result<pdfcraft_render::PageText, String> {
r.filtered_text(page, TextFilter { painted: true, ..Default::default() })
}
/// Whether `page` has text of its own ([`own_text`]). A stamp drawn as outlines on a scan still
/// leaves the scan to read; its words are not read twice, since they count as already on the page.
fn has_own_text(r: &mut PageRenderer, page: usize) -> bool {
own_text(r, page).is_ok_and(|t| t.glyphs.iter().any(|g| !g.text.trim().is_empty()))
}
/// How much of `word` the `text` boxes cover, from 0 to 1. Boxes are `[x0, y0, x1, y1]` in page
/// view space. Overlaps between the text boxes are counted twice (glyphs rarely overlap), so the
/// sum is capped at the whole word.
@@ -702,13 +715,14 @@ impl OcrJob {
}
let Some(info) = self.infos.get(page) else { continue };
let skip = |why: &str| OcrPage { page, words: Vec::new(), already_on_page: 0, skipped: Some(why.into()), notes: Vec::new() };
// The boxes of the page's own text (an earlier OCR layer's included), in view space.
// The boxes of all text on the page, in view space: an earlier OCR layer's, and words
// only /ActualText names, so neither is read again.
let existing: Vec<[f32; 4]> = r
.render(RenderRequest { page, kind: RequestKind::Text, scale: 1.0, ..Default::default() })
.text
.map(|t| t.glyphs.iter().filter(|g| !g.text.trim().is_empty()).map(|g| g.rect).collect())
.unwrap_or_default();
if self.settings.skip_text_pages && !self.settings.force_ocr && !existing.is_empty() {
if self.settings.skip_text_pages && !self.settings.force_ocr && !existing.is_empty() && has_own_text(&mut r, page) {
out.push(skip("the page already contains text"));
continue;
}
@@ -1118,6 +1132,34 @@ mod tests {
use super::*;
use crate::export;
/// One 300 × 300 page drawing `content`, with Helvetica as `/F1`.
fn page(content: &str) -> Arc<Vec<u8>> {
let pdf = format!(
"%PDF-1.7\n1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj\n2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj\n\
3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 300 300] /Contents 4 0 R /Resources << /Font << /F1 5 0 R >> >> >> endobj\n\
4 0 obj << /Length {} >> stream\n{content}\nendstream endobj\n\
5 0 obj << /Type /Font /Subtype /Type1 /BaseFont /Helvetica >> endobj\ntrailer << /Root 1 0 R >>\n%%EOF",
content.len()
);
Arc::new(pdf.into_bytes())
}
#[test]
fn a_stamp_drawn_as_outlines_leaves_a_scan_to_read() {
let stamp = page("/Span <</ActualText (APPROVED)>> BDC 100 40 60 20 re f EMC");
let mut r = PageRenderer::new(stamp, RenderConfig::default());
assert!(!has_own_text(&mut r, 0), "words only /ActualText names are no text of the page's own");
// They still count as on the page, so reading the scan doesn't add them twice.
let text = r.render(RenderRequest { page: 0, kind: RequestKind::Text, scale: 1.0, ..Default::default() }).text.unwrap();
assert_eq!(text.plain_text(), "APPROVED");
}
#[test]
fn printed_glyphs_count_as_own_text() {
let mut r = PageRenderer::new(page("BT /F1 12 Tf 20 150 Td (Total) Tj ET"), RenderConfig::default());
assert!(has_own_text(&mut r, 0));
}
/// #1028: a recognised word over the page's own text is that text again; one in an empty
/// part of the page (a picture) is new.
#[test]
+24 -8
View File
@@ -7,8 +7,8 @@ use pdfcraft_render::{DocInfo, OpenError, RenderConfig, RenderPool, inspect};
use crate::history::{Editor, Keys, TextBlocksCache};
use crate::{
AppearanceCache, DocId, Document, Session, TrustStore, XFA_SCRIPTS_OFF, XfaLayout, display_bytes, display_config, guard, info_fields, js,
note_warnings, recovered_render_password, render_threads, same_pages, signatures_of, xfa, xfa_layout, xfa_values_from_datasets,
AppearanceCache, DocId, Document, Session, StatusCaptions, TrustStore, XFA_SCRIPTS_OFF, XfaLayout, display_bytes, display_config, guard,
info_fields, js, note_warnings, recovered_render_password, render_threads, same_pages, signatures_of, xfa, xfa_layout, xfa_values_from_datasets,
};
/// Immutable session state needed while a document is prepared away from its owning thread.
@@ -17,6 +17,7 @@ pub struct OpenContext {
now: Option<i64>,
js_off: bool,
trust: Arc<TrustStore>,
captions: Arc<StatusCaptions>,
xfa_time_scale: u32,
}
@@ -54,7 +55,13 @@ impl OpenContext {
impl Session {
/// Snapshot the session state that affects open-time scripts, dates and signature trust.
pub fn open_context(&self) -> OpenContext {
OpenContext { now: self.now(), js_off: self.js_off, trust: self.trust.clone(), xfa_time_scale: self.xfa_time_scale.unwrap_or(1) }
OpenContext {
now: self.now(),
js_off: self.js_off,
trust: self.trust.clone(),
captions: self.captions.clone(),
xfa_time_scale: self.xfa_time_scale.unwrap_or(1),
}
}
/// Prepare a document without adding it to this session.
@@ -74,6 +81,14 @@ impl Session {
let id = DocId(self.next_id);
let mut document = prepared.document;
document.id = id;
// Trust or the interface language may have changed while it was prepared on another
// thread.
if !Arc::ptr_eq(&document.trust, &self.trust) {
document.captions = self.captions.clone();
Self::revalidate(&mut document, self.trust.clone());
} else if *document.captions != *self.captions {
Self::draw_captions(&mut document, self.captions.clone());
}
self.docs.push(document);
id
}
@@ -253,7 +268,7 @@ impl Session {
// XFA notes survive the document being re-read after edits.
let xfa_warnings: Vec<String> = if info.xfa.is_some() { info.warnings.clone() } else { Vec::new() };
let mut document =
Self::build_document(&context.trust, DocumentOpenData { name, path, bytes, info, structure: cos, render_password, password, xfa });
Self::build_document(context, DocumentOpenData { name, path, bytes, info, structure: cos, render_password, password, xfa });
// A script that ran away on open turns the form's scripts off for this document.
document.xfa_template = if ran_away { None } else { xfa_template };
document.js_output.append(script_output);
@@ -266,7 +281,7 @@ impl Session {
}
/// The last step of opening: build the document record and register it.
fn build_document(trust: &Arc<TrustStore>, data: DocumentOpenData<'_>) -> Document {
fn build_document(context: &OpenContext, data: DocumentOpenData<'_>) -> Document {
let DocumentOpenData { name, path, bytes, mut info, structure: cos, render_password, password, xfa } = data;
let config = RenderConfig { password: render_password.as_deref().map(Arc::from), ..Default::default() };
let (mut editor, read_only_reason) = match cos {
@@ -293,7 +308,7 @@ impl Session {
Err(_) => (None, Some("the document structure could not be read for editing".into())),
};
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();
let mut signatures = editor.as_ref().map(|e| signatures_of(&e.cos, &bytes, &context.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 {
@@ -303,7 +318,7 @@ impl Session {
}
}
}
let display = display_bytes(editor.as_mut(), &bytes);
let display = display_bytes(editor.as_mut(), &bytes, &mut signatures, &context.captions);
let renderer = RenderPool::new(display.clone(), render_threads(), display_config(&config));
let (form, adopted) = editor
.as_ref()
@@ -341,7 +356,8 @@ impl Session {
marker_scan: OnceLock::new(),
links: OnceLock::new(),
signatures: Arc::new(signatures),
trust: trust.clone(),
trust: context.trust.clone(),
captions: context.captions.clone(),
sig_cache,
editor,
config,
+7 -5
View File
@@ -11,11 +11,11 @@ use crate::edit::{EditCtx, check_permission, run_edit};
use crate::history::{Keys, MAX_UNDO, Scope, keys_after, scope_of, uses_scripts};
use crate::{
BookmarkPage, BookmarkRow, CombineSource, Combined, DataFormat, DocId, Document, Edit, EditError, Hidden, ImageResolution,
LOW_RESOLUTION_PRINT_DPI, Label, ObjectKind, OptimizeReport, RecoverySnapshot, SignOptions, SourceKind, SplitPart, SummarySort, TrustStore,
XFA_REMOVED_PREFIX, XFA_SCRIPTS_OFF, apply_layer_state, comment_list, comment_summary, decode_text, display_bytes, display_config, guard,
info_fields, js, local_utc_offset, note_warnings, open_source, open_source_with, optimize, outline_rows, parse_ymd, print, print_raster,
render_threads, scan_colours, set_default_layer_state, shown_under_redactions, signatures_of, source_kind, sync_xfa_state, undrawn_notices,
use_layer_choices, writable, xfa, xfa_sync_datasets,
LOW_RESOLUTION_PRINT_DPI, Label, ObjectKind, OptimizeReport, RecoverySnapshot, SignOptions, SourceKind, SplitPart, StatusCaptions, SummarySort,
TrustStore, XFA_REMOVED_PREFIX, XFA_SCRIPTS_OFF, apply_layer_state, carry_verdict_marks, comment_list, comment_summary, decode_text,
display_bytes, display_config, guard, info_fields, js, local_utc_offset, note_warnings, open_source, open_source_with, optimize, outline_rows,
parse_ymd, print, print_raster, render_threads, scan_colours, set_default_layer_state, shown_under_redactions, signatures_of, source_kind,
sync_xfa_state, undrawn_notices, use_layer_choices, writable, xfa, xfa_sync_datasets,
};
mod editing;
@@ -36,6 +36,8 @@ pub struct Session {
utc_offset: Option<fn() -> i64>,
/// Certificates trusted for signing (Acrobat: Trusted Certificates).
pub(crate) trust: Arc<TrustStore>,
/// The words signature status layers are drawn with, in the interface language.
pub(crate) captions: Arc<StatusCaptions>,
/// Preferences ▸ JavaScript ▸ Enable Acrobat JavaScript, inverted (on by default).
pub(crate) js_off: bool,
/// Preferences ▸ Date format, when not the default (see [`dates`]).
+24 -10
View File
@@ -2,9 +2,9 @@
use super::check_refresh_panic;
use super::{
Arc, DocId, Document, Edit, EditCtx, EditError, Label, MAX_UNDO, ObjectKind, OnceLock, RenderPool, SaveOptions, Scope, Session,
XFA_REMOVED_PREFIX, XFA_SCRIPTS_OFF, check_permission, comment_list, display_bytes, display_config, guard, info_fields, inspect, js, keys_after,
note_warnings, render_threads, run_edit, scan_colours, scope_of, shown_under_redactions, signatures_of, sync_xfa_state, undrawn_notices,
uses_scripts, write_incremental, xfa, xfa_sync_datasets,
XFA_REMOVED_PREFIX, XFA_SCRIPTS_OFF, carry_verdict_marks, check_permission, comment_list, display_bytes, display_config, guard, info_fields,
inspect, js, keys_after, note_warnings, render_threads, run_edit, scan_colours, scope_of, shown_under_redactions, signatures_of, sync_xfa_state,
undrawn_notices, uses_scripts, write_incremental, xfa, xfa_sync_datasets,
};
use crate::{EditNotice, MarkKind};
@@ -342,7 +342,14 @@ impl Session {
#[cfg(test)]
check_refresh_panic();
if !doc.signatures.is_empty() {
let signatures = signatures_of(&editor.cos, &bytes, &doc.trust, &doc.sig_cache);
let mut signatures = signatures_of(&editor.cos, &bytes, &doc.trust, &doc.sig_cache);
// The display copy is kept for a metadata edit, and so are its marks, unless the
// edit changed a verdict (a certification can forbid it): the page then draws the
// new one.
if !carry_verdict_marks(&doc.signatures, &mut signatures) {
doc.display = display_bytes(Some(editor), &bytes, &mut signatures, &doc.captions);
doc.renderer = RenderPool::new(doc.display.clone(), render_threads(), display_config(&doc.config));
}
doc.signatures = Arc::new(signatures);
}
doc.bytes = bytes;
@@ -386,8 +393,8 @@ impl Session {
}
doc.info.file_size = bytes.len();
doc.form = form;
let signatures = if doc.signatures.is_empty() { Vec::new() } else { signatures_of(&editor.cos, &bytes, &doc.trust, &doc.sig_cache) };
doc.display = display_bytes(Some(editor), &bytes);
let mut signatures = if doc.signatures.is_empty() { Vec::new() } else { signatures_of(&editor.cos, &bytes, &doc.trust, &doc.sig_cache) };
doc.display = display_bytes(Some(editor), &bytes, &mut signatures, &doc.captions);
doc.signatures = Arc::new(signatures);
doc.renderer = RenderPool::new(doc.display.clone(), render_threads(), display_config(&doc.config));
doc.bytes = bytes;
@@ -444,8 +451,8 @@ impl Session {
doc.marker_scan = OnceLock::new();
}
doc.info.file_size = bytes.len();
let signatures = if doc.signatures.is_empty() { Vec::new() } else { signatures_of(&editor.cos, &bytes, &doc.trust, &doc.sig_cache) };
doc.display = display_bytes(Some(editor), &bytes);
let mut signatures = if doc.signatures.is_empty() { Vec::new() } else { signatures_of(&editor.cos, &bytes, &doc.trust, &doc.sig_cache) };
doc.display = display_bytes(Some(editor), &bytes, &mut signatures, &doc.captions);
doc.signatures = Arc::new(signatures);
doc.renderer = RenderPool::new(doc.display.clone(), render_threads(), display_config(&doc.config));
doc.bytes = bytes;
@@ -467,6 +474,13 @@ impl Session {
doc.renderer = RenderPool::new_inline(Arc::new(Vec::new()), doc.config.clone());
doc.display = original.clone();
doc.bytes = original;
// The page shows the original's own artwork again, so nothing counts as drawn, even if
// the refresh that follows fails.
if doc.signatures.iter().any(|s| s.verdict_shown) {
for sig in Arc::make_mut(&mut doc.signatures) {
sig.verdict_shown = false;
}
}
#[cfg(test)]
check_refresh_panic();
}
@@ -528,8 +542,8 @@ impl Session {
if invalidate_links {
doc.links = OnceLock::new();
}
let signatures = signatures_of(&editor.cos, &bytes, &doc.trust, &doc.sig_cache);
doc.display = display_bytes(Some(editor), &bytes);
let mut signatures = signatures_of(&editor.cos, &bytes, &doc.trust, &doc.sig_cache);
doc.display = display_bytes(Some(editor), &bytes, &mut signatures, &doc.captions);
doc.signatures = Arc::new(signatures);
doc.renderer = RenderPool::new(doc.display.clone(), render_threads(), display_config(&doc.config));
doc.bytes = bytes;
+5
View File
@@ -170,6 +170,11 @@ impl Session {
if !doc.config.layers.is_empty() {
set_default_layer_state(&mut cos, &doc.info.layers);
}
// Signature states as the screen shows them, so not when its display copy could not be
// written. This copy is only printed, never saved.
if doc.signatures.iter().any(|s| s.verdict_shown) {
let _ = pdfcraft_sign::show_status_layers(&mut cos, &mut doc.signatures.to_vec(), &doc.captions);
}
pdfcraft_print::impose(&cos, settings).map_err(|e| EditError::Print(e.to_string()))
}
+125 -12
View File
@@ -1,6 +1,6 @@
use super::{
Arc, DocId, EditError, Keys, OpenError, RecoverySnapshot, RenderPool, SaveOptions, Session, SignOptions, TrustStore, display_bytes,
display_config, guard, render_threads, signatures_of, writable, write_full, write_incremental, xfa_sync_datasets,
Arc, DocId, Document, EditError, Keys, OpenError, RecoverySnapshot, RenderPool, SaveOptions, Session, SignOptions, StatusCaptions, TrustStore,
display_bytes, display_config, guard, render_threads, signatures_of, writable, write_full, write_incremental, xfa_sync_datasets,
};
impl Session {
@@ -242,17 +242,55 @@ impl Session {
pub fn set_trusted_certificates(&mut self, certs: Vec<pdfcraft_sign::Certificate>) {
self.trust = Arc::new(TrustStore { certs });
for doc in &mut self.docs {
doc.trust = self.trust.clone();
let Some(editor) = doc.editor.as_mut() else { continue };
// Keep verdict refresh and renderer refresh together. Viewer caches are
// invalidated by the UI trust path; trust alone changes no document artwork.
let signatures = if doc.signatures.is_empty() { Vec::new() } else { signatures_of(&editor.cos, &doc.bytes, &doc.trust, &doc.sig_cache) };
doc.display = display_bytes(Some(editor), &doc.bytes);
doc.signatures = Arc::new(signatures);
doc.renderer = RenderPool::new(doc.display.clone(), render_threads(), display_config(&doc.config));
Self::revalidate(doc, self.trust.clone());
}
}
/// Validate `doc`'s signatures against `trust`, and rebuild its display copy and renderer
/// with them: the verdicts choose what the copy draws. An unsigned document has nothing to
/// validate and keeps both. Viewer caches are invalidated by the UI trust path.
pub(crate) fn revalidate(doc: &mut Document, trust: Arc<TrustStore>) {
doc.trust = trust;
if doc.signatures.is_empty() {
return;
}
let Some(editor) = doc.editor.as_mut() else { return };
let mut signatures = signatures_of(&editor.cos, &doc.bytes, &doc.trust, &doc.sig_cache);
doc.display = display_bytes(Some(editor), &doc.bytes, &mut signatures, &doc.captions);
doc.signatures = Arc::new(signatures);
doc.renderer = RenderPool::new(doc.display.clone(), render_threads(), display_config(&doc.config));
}
/// The words the caption of a named-layer signature appearance is drawn with
/// ([`pdfcraft_sign::show_status_layers`]), in the interface language. When they change, every
/// open document's display copy and renderer are rebuilt; like trust, this is not an edit.
/// Returns whether they changed.
pub fn set_signature_captions(&mut self, captions: StatusCaptions) -> bool {
if *self.captions == captions {
return false;
}
self.captions = Arc::new(captions);
for doc in &mut self.docs {
Self::draw_captions(doc, self.captions.clone());
}
true
}
/// Draw `doc`'s signature status layers with `captions`: the display copy and renderer are
/// rebuilt when it draws a signature's state (working file, generation and dirty unchanged).
/// Whether a state is drawn does not depend on the words: a caption that can't be drawn in
/// them is drawn in English.
pub(crate) fn draw_captions(doc: &mut Document, captions: Arc<StatusCaptions>) {
doc.captions = captions;
if !doc.signatures.iter().any(|s| s.verdict_shown) {
return;
}
let Some(editor) = doc.editor.as_mut() else { return };
let signatures = Arc::make_mut(&mut doc.signatures);
doc.display = display_bytes(Some(editor), &doc.bytes, signatures, &doc.captions);
doc.renderer = RenderPool::new(doc.display.clone(), render_threads(), display_config(&doc.config));
}
/// The signing time as a PDF date in local time with its offset (`D:…+02'00'`).
pub fn signing_date(&self) -> String {
let offset = self.local_offset();
@@ -276,7 +314,7 @@ impl Session {
opts.date = self.signing_date();
}
// A typed Password-field value is not signed into the file (#3926), as it isn't saved.
let cos = writable(&editor.cos)?;
let cos = drawn_for_first_signature(writable(&editor.cos)?);
Ok(Arc::new(pdfcraft_sign::sign(&cos, id, &opts)?))
}
@@ -294,7 +332,7 @@ impl Session {
if opts.date.is_empty() {
opts.date = self.signing_date();
}
let cos = writable(&editor.cos)?;
let cos = drawn_for_first_signature(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)?;
@@ -336,3 +374,78 @@ impl Session {
Ok(())
}
}
/// `cos` with its form fields drawn, when the signature about to be made is the document's first
/// and the form sets `/NeedAppearances` (#5939). That signature removes the flag, after which
/// viewers show each field's stored appearance; a filled field whose stored appearance draws no
/// text (an empty placeholder such as `/Tx BMC EMC`, or a stale look) would go blank. So every
/// text and choice field is drawn from its value first, as the document is displayed
/// ([`pdfcraft_forms::with_field_appearances`]), and the signature covers that look.
///
/// One exception: where PdfCraft's drawing would show a character as `?` (the field's font can't
/// hold it) and the field's own appearance draws text, the field keeps its own appearance, which
/// the program that filled it drew with a font that has the character. A field whose own
/// appearance draws no text gets PdfCraft's drawing, `?` and all. Later signatures change
/// nothing here: redrawing would count as a change to the earlier signatures.
fn drawn_for_first_signature(cos: std::borrow::Cow<'_, pdfcraft_cos::Document>) -> std::borrow::Cow<'_, pdfcraft_cos::Document> {
use pdfcraft_forms::FieldKind;
if !pdfcraft_forms::need_appearances(&cos) || pdfcraft_sign::has_signatures(&cos) {
return cos;
}
let Some(mut drawn) = pdfcraft_forms::with_field_appearances(&cos) else { return cos };
for f in pdfcraft_forms::fields(&cos) {
if !matches!(f.kind, FieldKind::Text | FieldKind::Combo | FieldKind::List) {
continue;
}
for w in &f.widgets {
let own = cos.get(w.obj).as_dict().filter(|d| draws_text(&cos, d)).and_then(|d| d.get(b"AP").cloned());
// `.1`: the first character the drawing showed as `?`.
if let Some(ap) = own
&& pdfcraft_forms::appearance::field_appearance_drawn(&cos, &f, w, &f.value, true).1.is_some()
{
drawn.update_dict(w.obj, |d| d.set(b"AP".to_vec(), ap)).ok();
}
}
}
std::borrow::Cow::Owned(drawn)
}
/// Whether the widget's normal appearance stream (`/AP /N`) shows text, itself or through the
/// form XObjects it paints (a background-only one doesn't count).
fn draws_text(cos: &pdfcraft_cos::Document, widget: &pdfcraft_cos::Dict) -> bool {
let ap = widget.get(b"AP").map(|ap| cos.resolve(ap));
let normal = ap.as_deref().and_then(|ap| ap.as_dict()).and_then(|ap| ap.get(b"N")).map(|n| cos.resolve(n));
let Some(pdfcraft_cos::Object::Stream(s)) = normal.as_deref() else { return false };
stream_draws_text(cos, s, &mut 16)
}
/// Whether the form stream `s` shows text, following `Do` into its form XObjects. `budget` caps
/// the streams opened along the way; running out (deep nesting, a cycle, many XObjects) counts
/// as text, so the field keeps its own appearance as it would without the look inside.
fn stream_draws_text(cos: &pdfcraft_cos::Document, s: &pdfcraft_cos::Stream, budget: &mut u8) -> bool {
let Ok(data) = s.decoded() else { return false };
let resources = s.dict.get(b"Resources").map(|r| cos.resolve(r));
let xobjects = resources.as_deref().and_then(|r| r.as_dict()).and_then(|r| r.get(b"XObject")).map(|x| cos.resolve(x));
for op in pdfcraft_content::ops(&data) {
match op.op.as_slice() {
b"Tj" | b"TJ" | b"'" | b"\"" => return true,
b"Do" => {
let name = op.operands.first().and_then(|n| n.as_name());
let x = name.and_then(|n| xobjects.as_deref().and_then(|x| x.as_dict()).and_then(|x| x.get(n))).map(|x| cos.resolve(x));
let Some(pdfcraft_cos::Object::Stream(f)) = x.as_deref() else { continue };
if f.dict.name(b"Subtype") != Some(b"Form") {
continue;
}
if *budget == 0 {
return true;
}
*budget -= 1;
if stream_draws_text(cos, f, budget) {
return true;
}
}
_ => {}
}
}
false
}
+755 -1
View File
@@ -1,6 +1,6 @@
use std::sync::Arc;
use super::document::is_placeholder_title;
use super::document::{is_placeholder_title, write_display_copy};
use super::edit::{EditCtx, check_permission, run_edit};
use super::*;
use pdfcraft_render::{Layer, LayerOp, OpenError, ReadingColors};
@@ -2699,6 +2699,126 @@ fn a_signed_file_carries_no_password_field_value() {
assert!(!appears_in_pdf(&signed, "*******"), "nor the typed length");
}
/// A form with `/NeedAppearances true` whose filled fields have stored appearances that draw no
/// text: `name` an empty placeholder, `town` one too with a value Helvetica can't hold (`ň`),
/// `city` such a value with its own appearance that draws it (#5939), `street` no appearance at
/// all, `river` a value Helvetica can't hold (`ř`) with an appearance that paints only a
/// background form XObject, and `lake` such a value drawn by a form XObject its appearance
/// paints.
fn need_appearances_form() -> Vec<u8> {
let stream =
|content: &str| format!("<< /Type /XObject /Subtype /Form /BBox [0 0 160 20] /Length {} >>\nstream\n{content}\nendstream", content.len());
let objs = [
"<< /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [4 0 R 5 0 R 6 0 R 11 0 R 12 0 R 15 0 R] /NeedAppearances true /DA (/Helv 0 Tf 0 g) /DR << /Font << /Helv 7 0 R >> >> >> >>".to_string(),
"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 200 300] >>".into(),
"<< /Type /Page /Parent 2 0 R /Annots [4 0 R 5 0 R 6 0 R 11 0 R 12 0 R 15 0 R] >>".into(),
"<< /Type /Annot /Subtype /Widget /FT /Tx /T (name) /V (Ada Lovelace) /Rect [20 250 180 270] /P 3 0 R /AP << /N 8 0 R >> >>".into(),
"<< /Type /Annot /Subtype /Widget /FT /Tx /T (town) /V <FEFF0050006C007A00650148> /Rect [20 200 180 220] /P 3 0 R /AP << /N 9 0 R >> >>".into(),
"<< /Type /Annot /Subtype /Widget /FT /Tx /T (city) /V <FEFF00420072006E006F00200159> /Rect [20 150 180 170] /P 3 0 R /AP << /N 10 0 R >> >>".into(),
"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>".into(),
stream("/Tx BMC EMC"),
stream("/Tx BMC EMC"),
stream("/Tx BMC BT /Helv 10 Tf 2 5 Td (Brno r) Tj ET EMC"),
"<< /Type /Annot /Subtype /Widget /FT /Tx /T (street) /V (Main Street) /Rect [20 100 180 120] /P 3 0 R >>".into(),
"<< /Type /Annot /Subtype /Widget /FT /Tx /T (river) /V <FEFF004F0159006500630068> /Rect [20 50 180 70] /P 3 0 R /AP << /N 13 0 R >> >>".into(),
"<< /Type /XObject /Subtype /Form /BBox [0 0 160 20] /Resources << /XObject << /Bg 14 0 R >> >> /Length 10 >>\nstream\nq /Bg Do Q\nendstream".into(),
stream("0.9 g 0 0 160 20 re f"),
"<< /Type /Annot /Subtype /Widget /FT /Tx /T (lake) /V <FEFF004F0159006500630068> /Rect [20 20 180 40] /P 3 0 R /AP << /N 16 0 R >> >>".into(),
"<< /Type /XObject /Subtype /Form /BBox [0 0 160 20] /Resources << /XObject << /Fm 17 0 R >> >> /Length 10 >>\nstream\nq /Fm Do Q\nendstream".into(),
stream("BT /Helv 10 Tf 2 5 Td (Orech) Tj ET"),
];
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
}
/// The decoded normal appearance of the widget `num` in `doc`.
fn normal_appearance(doc: &pdfcraft_cos::Document, num: u32) -> String {
let widget = doc.get(pdfcraft_cos::ObjRef::new(num, 0));
let ap = doc.resolve(widget.as_dict().unwrap().get(b"AP").unwrap());
let n = doc.resolve(ap.as_dict().unwrap().get(b"N").unwrap());
let pdfcraft_cos::Object::Stream(s) = &*n else { panic!("{n:?}") };
String::from_utf8_lossy(&s.decoded().unwrap()).into_owned()
}
/// #5939 review: the first signature removes `/NeedAppearances`, so the fields are drawn from
/// their values first; without that, `name` and `town` would show their empty placeholders. A
/// field whose own appearance draws its value keeps it rather than get a `?` for `ř`.
#[test]
fn the_first_signature_draws_the_fields_need_appearances_left_to_the_viewer() {
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("form.pdf", None, Arc::new(need_appearances_form()), None).unwrap();
let signed = s.sign(id, &digital_id, SignOptions { rect: None, ..SignOptions::default() }).unwrap();
let doc = pdfcraft_cos::Document::open(signed.clone()).unwrap();
assert!(!pdfcraft_forms::need_appearances(&doc));
assert!(normal_appearance(&doc, 4).contains("(Ada Lovelace) Tj"), "{}", normal_appearance(&doc, 4));
assert!(normal_appearance(&doc, 5).contains("(Plze?) Tj"), "{}", normal_appearance(&doc, 5));
assert!(normal_appearance(&doc, 6).contains("(Brno r) Tj"), "{}", normal_appearance(&doc, 6));
assert!(normal_appearance(&doc, 11).contains("(Main Street) Tj"), "{}", normal_appearance(&doc, 11));
// Its own appearance only paints a background, so `river` gets the drawing, `?` and all.
assert!(normal_appearance(&doc, 12).contains("(O?ech) Tj"), "{}", normal_appearance(&doc, 12));
let city = |d: &pdfcraft_cos::Document| d.get(pdfcraft_cos::ObjRef::new(6, 0)).as_dict().unwrap().get(b"AP").cloned();
let original = pdfcraft_cos::Document::open(Arc::new(need_appearances_form())).unwrap();
assert_eq!(city(&doc), city(&original), "city keeps its own appearance");
let lake = |d: &pdfcraft_cos::Document| d.get(pdfcraft_cos::ObjRef::new(15, 0)).as_dict().unwrap().get(b"AP").cloned();
assert_eq!(lake(&doc), lake(&original), "lake keeps the appearance its form XObject draws");
s.mark_signed(id, signed, None).unwrap();
s.set_trusted_certificates(vec![digital_id.certificate.clone()]);
let sig = &s.get(id).unwrap().signatures[0];
assert_eq!((sig.signed, sig.status, sig.modification.clone()), (true, SignatureStatus::Valid, sign::Modification::None));
}
/// A later signature draws nothing and leaves the flag: either would be a change to what the
/// first signature covers.
#[test]
fn a_later_signature_leaves_need_appearances_forms_alone() {
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 mut s = Session::new().with_clock(|| 1_800_000_000);
let id = s.open("form.pdf", None, Arc::new(need_appearances_form()), None).unwrap();
let first = s.sign(id, &digital_id, SignOptions { rect: None, ..SignOptions::default() }).unwrap();
// The flag set again after the first signature, and `name` back to its empty placeholder.
let mut cos = pdfcraft_cos::Document::open(first).unwrap();
let root = cos.root().unwrap();
cos.update_dict(root, |c| {
if let Some(pdfcraft_cos::Object::Dict(af)) = c.get_mut(b"AcroForm") {
af.set(b"NeedAppearances".to_vec(), pdfcraft_cos::Object::Bool(true));
}
})
.unwrap();
let placeholder = cos.add(pdfcraft_cos::Object::Stream(pdfcraft_cos::Stream::from_raw(Default::default(), b"/Tx BMC EMC".to_vec())));
cos.update_dict(pdfcraft_cos::ObjRef::new(4, 0), |w| {
let mut ap = pdfcraft_cos::Dict::new();
ap.set(b"N".to_vec(), pdfcraft_cos::Object::Ref(placeholder));
w.set(b"AP".to_vec(), pdfcraft_cos::Object::Dict(ap));
})
.unwrap();
let flagged =
Arc::new(pdfcraft_cos::write_incremental(&cos, &pdfcraft_cos::SaveOptions { object_streams: false, ..Default::default() }).unwrap());
let id = s.open("flagged.pdf", None, flagged.clone(), None).unwrap();
let second = s.sign(id, &digital_id, SignOptions { rect: None, ..SignOptions::default() }).unwrap();
let (before, after) = (pdfcraft_cos::Document::open(flagged).unwrap(), pdfcraft_cos::Document::open(second.clone()).unwrap());
assert!(pdfcraft_forms::need_appearances(&after));
let widget = |d: &pdfcraft_cos::Document| d.get(pdfcraft_cos::ObjRef::new(4, 0));
assert_eq!(widget(&after), widget(&before));
assert_eq!(normal_appearance(&after, 4), "/Tx BMC EMC");
s.mark_signed(id, second, None).unwrap();
assert_eq!(s.get(id).unwrap().signatures.iter().filter(|x| x.signed).count(), 2);
}
/// #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.
@@ -3116,6 +3236,26 @@ fn a_word_in_a_font_set_by_an_extgstate_is_redacted() {
);
}
/// A word drawn as outlines reads through its /ActualText. A mark over part of it applies (the
/// outlines are clipped), and the name that would still read the whole word is gone from the page
/// and from the saved file.
#[test]
fn a_word_drawn_as_outlines_is_redacted_with_its_name() {
let mut s = Session::new().with_clock(|| 1_700_000_000);
let page = one_line_page("", "/Span <</ActualText (SECRET42)>> BDC 20 150 m 140 150 l 140 170 l 20 170 l h f EMC");
let id = s.open("outlines.pdf", None, Arc::new(page), None).unwrap();
assert_eq!(page_texts(&s, id), ["SECRET42"]);
let shape =
Shape::Redact { quads: vec![pdfcraft_annot::rect_quad([10.0, 140.0, 90.0, 180.0])], overlay: String::new(), look: Default::default() };
let mark =
Edit::AddAnnotation(NewAnnotation { page: 0, style: Style::default_for(&shape), shape, contents: String::new(), author: "Ada".into() });
s.apply(id, mark).unwrap();
s.apply(id, Edit::ApplyRedactions { pages: None }).unwrap();
assert_eq!(page_texts(&s, id), [""]);
let saved = s.save_bytes(id).unwrap();
assert!(!saved.windows(b"SECRET42".len()).any(|w| w == b"SECRET42"), "the name is not left in the file");
}
#[test]
fn redaction_marks_apply_for_good_and_undo() {
let (mut s, id) = session_with(2);
@@ -4855,6 +4995,17 @@ fn bytes_has(haystack: &[u8], needle: &[u8]) -> bool {
/// ranges and embed a detached CMS over them. The signed bytes keep the
/// prepared appearance, so they validate exactly like a product signer's file.
fn sign_prepared(doc: &mut pdfcraft_cos::Document, id: &sign::pkcs12::DigitalId, date: &str) -> Vec<u8> {
sign_prepared_with(doc, id, date, |_| {})
}
/// [`sign_prepared`], with `value` adding to the signature dictionary first (a certification's
/// `/Reference`, say).
fn sign_prepared_with(
doc: &mut pdfcraft_cos::Document,
id: &sign::pkcs12::DigitalId,
date: &str,
value: impl FnOnce(&mut pdfcraft_cos::Dict),
) -> Vec<u8> {
use pdfcraft_cos::{Dict, Object, PdfString};
let reserve = 8192 + id.certificate.raw.len() + id.chain.iter().map(|c| c.raw.len()).sum::<usize>();
let mut v = Dict::new();
@@ -4864,6 +5015,7 @@ fn sign_prepared(doc: &mut pdfcraft_cos::Document, id: &sign::pkcs12::DigitalId,
v.set(b"ByteRange".to_vec(), Object::Array([0].iter().chain(LAYERED_BR_MARK.iter()).map(|n| Object::Int(*n)).collect()));
v.set(b"Contents".to_vec(), Object::String(PdfString { bytes: vec![0; reserve], hex: true }));
v.set(b"M".to_vec(), PdfString::literal(date.as_bytes().to_vec()));
value(&mut v);
let sig = doc.add(Object::Dict(v));
// The field by name, never by number: a full save (encryption, repairs) is
// free to renumber objects, and a hardcoded reference would stamp the value
@@ -5104,6 +5256,442 @@ fn real_layered_signatures_round_trip_behind_a_user_password() {
assert_eq!(t.get(tid).unwrap().signatures[0].status, SignatureStatus::Valid);
}
/// A one-page file whose unsigned signature field carries a named-layer appearance, in the
/// geometry of a real one scaled by 4 (every word and drawing synthetic): /N draws /FRM, which
/// draws n0–n4; n1 a yellow question mark and n4 "Signature Not Verified". Object numbers:
/// 1 catalog, 2 pages, 3 page (400×300), 4 field, 5 AcroForm, 6 /N, 7 /FRM, 8–12 n0–n4,
/// 13 Helvetica, 14 page content. `sign_prepared` adds the value.
fn named_layer_signable_fixture() -> Vec<u8> {
named_layer_signable_fixture_with("[0 0 100 100]")
}
/// [`named_layer_signable_fixture`] with `n1_bbox` as its n1 layer's `/BBox`.
fn named_layer_signable_fixture_with(n1_bbox: &str) -> Vec<u8> {
fn form(bbox: &str, resources: &str, ops: &str) -> String {
format!("<< /Type /XObject /Subtype /Form /BBox {bbox} /Resources {resources} /Length {} >>\nstream\n{ops}\nendstream", ops.len())
}
let helv = "<< /Font << /F1 13 0 R >> >>";
let glyph = "1.08 0 0 1.08 46 6 cm";
let objs = [
"<< /Type /Catalog /Pages 2 0 R /AcroForm 5 0 R >>".to_string(),
"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_string(),
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 400 300] /Contents 14 0 R /Resources << /Font << /F1 13 0 R >> >> /Annots [4 0 R] >>"
.to_string(),
"<< /FT /Sig /T (Signature1) /Type /Annot /Subtype /Widget /F 132 /Rect [100 100 300 220] /P 3 0 R /AP << /N 6 0 R >> >>".to_string(),
"<< /Fields [4 0 R] /SigFlags 3 >>".to_string(),
form("[0 0 200 120]", "<< /XObject << /FRM 7 0 R >> >>", "q 1 0 0 1 0 0 cm /FRM Do Q"),
form(
"[0 0 200 120]",
"<< /XObject << /n0 8 0 R /n1 9 0 R /n2 10 0 R /n3 11 0 R /n4 12 0 R >> >>",
&format!("q /n0 Do Q q {glyph} /n1 Do Q q /n2 Do Q q {glyph} /n3 Do Q q /n4 Do Q"),
),
form("[0 0 100 100]", "<< >>", "% DSBlank"),
form(
n1_bbox,
"<< >>",
"q 1 0.84 0.2 rg 0.55 0.4 0 RG 3 w 30 72 m 30 88 42 98 56 98 c 72 98 84 88 84 74 c 66 50 l 58 28 l 44 28 l 44 48 l h B 44 6 14 14 re B Q",
),
form("[0 0 200 120]", helv, "BT /F1 13.6 Tf 1 0 0 1 8 62.4 Tm (Digitally signed by) Tj 1 0 0 1 8 48.8 Tm (Test Signer) Tj ET"),
form("[0 0 100 100]", "<< >>", "% DSBlank"),
form("[0 84 200 120]", helv, "BT /F1 18.8 Tf 1 0 0 1 8 93.2 Tm (Signature Not Verified) Tj ET"),
"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>".to_string(),
"<< /Length 44 >>\nstream\nBT /F1 14 Tf 20 270 Td (Contract text) Tj ET\nendstream".to_string(),
];
let mut out = b"%PDF-1.7\n".to_vec();
let mut offs = Vec::new();
for (k, o) in objs.iter().enumerate() {
offs.push(out.len());
out.extend_from_slice(format!("{} 0 obj\n{o}\nendobj\n", k + 1).as_bytes());
}
let start = out.len();
out.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objs.len() + 1).as_bytes());
for o in &offs {
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{start}\n%%EOF", objs.len() + 1).as_bytes());
out
}
/// The status colours as the regenerated icons draw them.
const VALID_GREEN: [u8; 3] = [0x2D, 0x9D, 0x78];
const UNKNOWN_AMBER: [u8; 3] = [0xE6, 0x86, 0x19];
const INVALID_RED: [u8; 3] = [0xD7, 0x37, 0x3F];
/// How many pixels of `rgba` are within 40 of `rgb` on every channel. A regenerated icon's
/// stroke covers thousands at 1 px/pt; the fixture holds none of these colours otherwise.
fn pixels_near(rgba: &[u8], rgb: [u8; 3]) -> usize {
rgba.as_chunks::<4>().0.iter().filter(|p| p.iter().zip(rgb).all(|(a, b)| a.abs_diff(b) <= 40)).count()
}
/// The displayed page at 1 px/pt.
fn displayed_pixels(s: &Session, id: DocId) -> Vec<u8> {
let doc = s.get(id).unwrap();
let mut renderer = pdfcraft_render::PageRenderer::new(doc.display.clone(), doc.config.clone());
let r = renderer.render(pdfcraft_render::RenderRequest { page: 0, scale: 1.0, ..Default::default() });
assert!(r.error.is_none(), "{:?}", r.error);
r.rgba.to_vec()
}
fn exported_text(s: &Session, id: DocId) -> String {
export::Exporter::new(s.get(id).unwrap()).text_of(&[0]).unwrap()
}
/// The test identity and the certificate that makes it trusted.
fn test_identity() -> (sign::pkcs12::DigitalId, sign::x509::Certificate) {
let p12 = std::fs::read(concat!(env!("CARGO_MANIFEST_DIR"), "/../sign/tests/data/ec-p256.p12")).unwrap();
let id = sign::pkcs12::open(&p12, "test").unwrap();
let anchor = id.chain.first().cloned().unwrap_or_else(|| id.certificate.clone());
(id, anchor)
}
/// A named-layer signature through `Session`: the unknown state drawn on opening, the valid one
/// once trusted, the signed bytes saved unchanged and still valid on reopening.
fn check_named_layer_states(signed: Arc<Vec<u8>>, password: Option<&str>, anchor: &sign::x509::Certificate) {
let mut s = Session::new().with_clock(|| 1_800_000_000);
let id = s.open("named.pdf", None, signed.clone(), password).unwrap();
let sig = &s.get(id).unwrap().signatures[0];
assert_eq!(sig.status, SignatureStatus::Unknown, "untrusted at first");
assert!(sig.verdict_shown, "the appearance shows the unknown state");
let text = exported_text(&s, id);
assert!(text.contains("Validity unknown") && !text.contains("Not Verified"), "{text:?}");
let amber = pixels_near(&displayed_pixels(&s, id), UNKNOWN_AMBER);
assert!(amber > 500, "{amber} amber pixels");
s.set_trusted_certificates(vec![anchor.clone()]);
let doc = s.get(id).unwrap();
assert_eq!(doc.signatures[0].status, SignatureStatus::Valid);
assert!(doc.signatures[0].verdict_shown);
assert!(!doc.dirty, "trust is not an edit");
let exported = exported_text(&s, id);
assert!(exported.contains("Signature valid"), "{exported}");
let page = displayed_pixels(&s, id);
assert!(pixels_near(&page, VALID_GREEN) > 500 && pixels_near(&page, UNKNOWN_AMBER) < 50, "the page redraws for the new state");
// Saving writes the working file, which never held the drawn state.
let saved = s.save_bytes(id).unwrap();
assert!(saved == signed, "an unchanged save is the signed file exactly");
let mut t = Session::new().with_clock(|| 1_800_000_000);
t.set_trusted_certificates(vec![anchor.clone()]);
let tid = t.open("named-saved.pdf", None, saved, password).unwrap();
let sig = &t.get(tid).unwrap().signatures[0];
assert!(sig.status == SignatureStatus::Valid && sig.verdict_shown);
let exported = exported_text(&t, tid);
assert!(exported.contains("Signature valid"), "{exported}");
}
#[test]
fn named_layer_signatures_show_their_state_through_trust_save_and_reopen() {
let (id, anchor) = test_identity();
let mut doc = pdfcraft_cos::Document::open(Arc::new(named_layer_signable_fixture())).unwrap();
let signed = Arc::new(sign_prepared(&mut doc, &id, "D:20261002120000+01'00'"));
check_named_layer_states(signed, None, &anchor);
}
#[test]
fn named_layer_signatures_round_trip_behind_a_user_password() {
let (id, anchor) = test_identity();
let mut doc = pdfcraft_cos::Document::open(Arc::new(named_layer_signable_fixture())).unwrap();
doc.set_encryption(&pdfcraft_cos::NewEncryption {
algorithm: pdfcraft_cos::Algorithm::Aes128,
user_password: "user",
owner_password: "owner",
permissions: -1,
encrypt_metadata: true,
seed: [7; 32],
})
.unwrap();
let encrypted = Arc::new(pdfcraft_cos::write_full(&doc, &pdfcraft_cos::SaveOptions::default()).unwrap());
let mut doc = pdfcraft_cos::Document::open_with_password(encrypted, Some("user")).unwrap();
let signed = Arc::new(sign_prepared(&mut doc, &id, "D:20261002120000+01'00'"));
check_named_layer_states(signed, Some("user"), &anchor);
}
#[test]
fn a_tampered_named_layer_signature_shows_the_invalid_state() {
let (id, _) = test_identity();
let mut doc = pdfcraft_cos::Document::open(Arc::new(named_layer_signable_fixture())).unwrap();
let mut signed = sign_prepared(&mut doc, &id, "D:20261002120000+01'00'");
let at = signed.windows(15).position(|w| w == b"(Contract text)").unwrap();
signed[at + 10] = b'X';
let mut s = Session::new().with_clock(|| 1_800_000_000);
let id = s.open("tampered.pdf", None, Arc::new(signed), None).unwrap();
let sig = &s.get(id).unwrap().signatures[0];
assert!(sig.status == SignatureStatus::Invalid && sig.verdict_shown);
let exported = exported_text(&s, id);
assert!(exported.contains("Signature invalid"), "{exported}");
let red = pixels_near(&displayed_pixels(&s, id), INVALID_RED);
assert!(red > 500, "{red} red pixels");
}
/// A trusted named-layer signature.
fn trusted_named_layer_session() -> (Session, DocId) {
let (id, anchor) = test_identity();
let mut doc = pdfcraft_cos::Document::open(Arc::new(named_layer_signable_fixture())).unwrap();
let signed = Arc::new(sign_prepared(&mut doc, &id, "D:20261002120000+01'00'"));
let mut s = Session::new().with_clock(|| 1_800_000_000);
let vid = s.open("named.pdf", None, signed, None).unwrap();
s.set_trusted_certificates(vec![anchor]);
assert_eq!(s.get(vid).unwrap().signatures[0].status, SignatureStatus::Valid);
(s, vid)
}
#[test]
fn named_layer_states_reach_exports_and_both_print_modes() {
// What is drawn on the page is what leaves it.
let (s, id) = trusted_named_layer_session();
let doc = s.get(id).unwrap();
let source = doc.export_source();
let mut file = export::Exporter::from_source(export::ExportSource { bytes: doc.bytes.clone(), ..source.clone() });
let mut shown = export::Exporter::from_source(source);
assert_ne!(shown.png(0, 72.0).unwrap(), file.png(0, 72.0).unwrap(), "image export follows the display copy");
let text = shown.text_of(&[0]).unwrap();
assert!(text.contains("Signature valid") && !text.contains("Not Verified"), "{text:?}");
let mut settings = print::Settings { pages: vec![0], paper: (400.0, 300.0), ..Default::default() };
let (_, _, vector) = printed_pixels(s.print_pdf(id, &settings).unwrap());
settings.raster = Some(print::Raster { dpi: 72.0, grayscale: false });
let (_, _, raster) = printed_pixels(s.print_pdf(id, &settings).unwrap());
for (mode, pixels) in [("vector", &vector), ("raster", &raster)] {
assert!(pixels_near(pixels, VALID_GREEN) > 500, "{mode} print draws the valid state");
assert!(pixels_near(pixels, [255, 214, 51]) < 50, "{mode} print drops the stored question mark");
}
}
#[test]
fn named_layers_show_beside_comments_that_need_appearances() {
// A comment without an appearance makes the display copy for its own sake; the signature's
// state is drawn into that same copy.
use pdfcraft_cos::{ObjRef, Object};
let (signer, anchor) = test_identity();
let mut cos = pdfcraft_cos::Document::open(Arc::new(named_layer_signable_fixture())).unwrap();
let square = cos.add(pdfcraft_cos::Lexer::new(b"<< /Type /Annot /Subtype /Square /Rect [10 10 60 60] /C [1 0 0] >>", 0).object().unwrap());
cos.update_dict(ObjRef::new(3, 0), |page| page.set(b"Annots".to_vec(), Object::Array(vec![Object::Ref(ObjRef::new(4, 0)), Object::Ref(square)])))
.unwrap();
let signed = Arc::new(sign_prepared(&mut cos, &signer, "D:20261002120000+01'00'"));
let mut s = Session::new().with_clock(|| 1_800_000_000);
let id = s.open("commented.pdf", None, signed, None).unwrap();
s.set_trusted_certificates(vec![anchor]);
let shown = pdfcraft_cos::Document::open(s.get(id).unwrap().display.clone()).unwrap();
assert!(shown.get(square).as_dict().is_some_and(|d| d.contains(b"AP")), "the comment's appearance is in the same copy");
assert!(s.get(id).unwrap().signatures[0].verdict_shown);
let green = pixels_near(&displayed_pixels(&s, id), VALID_GREEN);
assert!(green > 500, "{green} green pixels");
}
#[test]
fn named_layers_show_beside_fields_the_viewer_draws() {
// A text field without an appearance makes the display copy for its own sake; the
// signature's state is drawn into that same copy.
use pdfcraft_cos::{Lexer, ObjRef, Object};
let (signer, anchor) = test_identity();
let mut cos = pdfcraft_cos::Document::open(Arc::new(named_layer_signable_fixture())).unwrap();
let field = cos.add(
Lexer::new(
b"<< /Type /Annot /Subtype /Widget /FT /Tx /T (name) /V (Test Signer) /DA (/F1 12 Tf 0 g) /Rect [20 20 380 40] /F 4 /P 3 0 R >>",
0,
)
.object()
.unwrap(),
);
let both = Object::Array(vec![Object::Ref(ObjRef::new(4, 0)), Object::Ref(field)]);
cos.update_dict(ObjRef::new(3, 0), |page| page.set(b"Annots".to_vec(), both.clone())).unwrap();
let resources = Lexer::new(b"<< /Font << /F1 13 0 R >> >>", 0).object().unwrap();
cos.update_dict(ObjRef::new(5, 0), |form| {
form.set(b"Fields".to_vec(), both);
form.set(b"DR".to_vec(), resources);
})
.unwrap();
let signed = Arc::new(sign_prepared(&mut cos, &signer, "D:20261002120000+01'00'"));
let mut s = Session::new().with_clock(|| 1_800_000_000);
let id = s.open("filled.pdf", None, signed, None).unwrap();
s.set_trusted_certificates(vec![anchor]);
let shown = pdfcraft_cos::Document::open(s.get(id).unwrap().display.clone()).unwrap();
assert!(shown.get(field).as_dict().is_some_and(|d| d.contains(b"AP")), "the field's appearance is in the same copy");
assert!(s.get(id).unwrap().signatures[0].verdict_shown);
let green = pixels_near(&displayed_pixels(&s, id), VALID_GREEN);
assert!(green > 500, "{green} green pixels");
}
#[test]
fn a_metadata_edit_keeps_the_regenerated_state() {
let (mut s, id) = trusted_named_layer_session();
s.apply(id, Edit::SetInfo { key: "Title".into(), value: "Contract".into() }).unwrap();
let doc = s.get(id).unwrap();
assert!(doc.signatures[0].verdict_shown, "the page still draws the state");
let exported = exported_text(&s, id);
assert!(exported.contains("Signature valid"), "{exported}");
}
#[test]
fn a_metadata_edit_that_changes_a_verdict_redraws_it() {
// A certification that allows no changes: setting the title invalidates the signature, and
// the page has to say so rather than keep the valid state it drew.
let (signer, anchor) = test_identity();
let mut cos = pdfcraft_cos::Document::open(Arc::new(named_layer_signable_fixture())).unwrap();
let signed = sign_prepared_with(&mut cos, &signer, "D:20261002120000+01'00'", |v| {
let reference =
pdfcraft_cos::Lexer::new(b"[<< /Type /SigRef /TransformMethod /DocMDP /TransformParams << /Type /TransformParams /P 1 /V /1.2 >> >>]", 0)
.object()
.unwrap();
v.set(b"Reference".to_vec(), reference);
});
let mut s = Session::new().with_clock(|| 1_800_000_000);
let id = s.open("certified.pdf", None, Arc::new(signed), None).unwrap();
s.set_trusted_certificates(vec![anchor]);
assert_eq!(s.get(id).unwrap().signatures[0].status, SignatureStatus::Valid);
s.apply(id, Edit::SetInfo { key: "Title".into(), value: "Changed".into() }).unwrap();
let doc = s.get(id).unwrap();
assert_eq!(doc.signatures[0].status, SignatureStatus::Invalid);
assert!(doc.signatures[0].verdict_shown);
let exported = exported_text(&s, id);
assert!(exported.contains("Signature invalid"), "{exported}");
let red = pixels_near(&displayed_pixels(&s, id), INVALID_RED);
assert!(red > 500, "{red} red pixels");
}
#[test]
fn verdict_marks_carry_over_only_while_every_verdict_is_unchanged() {
let (s, id) = trusted_named_layer_session();
let previous = s.get(id).unwrap().signatures.to_vec();
assert!(previous[0].verdict_shown);
let mut same = previous.clone();
same[0].verdict_shown = false;
assert!(carry_verdict_marks(&previous, &mut same) && same[0].verdict_shown);
let mut changed = previous.clone();
(changed[0].verdict_shown, changed[0].status) = (false, SignatureStatus::Invalid);
assert!(!carry_verdict_marks(&previous, &mut changed) && !changed[0].verdict_shown);
let mut later = previous.clone();
(later[0].verdict_shown, later[0].revision) = (false, previous[0].revision + 1);
assert!(!carry_verdict_marks(&previous, &mut later) && !later[0].verdict_shown);
}
#[test]
fn releasing_the_working_file_drops_the_marks() {
// The page shows the original's own artwork until the refresh finishes.
let (mut s, id) = trusted_named_layer_session();
let doc = s.docs.iter_mut().find(|d| d.id == id).unwrap();
assert!(doc.signatures[0].verdict_shown);
Session::release_working(doc);
assert!(!doc.signatures[0].verdict_shown);
}
#[test]
fn background_open_uses_the_current_trust_at_commit() {
let (signer, anchor) = test_identity();
let mut cos = pdfcraft_cos::Document::open(Arc::new(named_layer_signable_fixture())).unwrap();
let signed = Arc::new(sign_prepared(&mut cos, &signer, "D:20261002120000+01'00'"));
let mut s = Session::new().with_clock(|| 1_800_000_000);
let prepared = s.open_context().prepare_open("background.pdf", None, signed, None).unwrap();
s.set_trusted_certificates(vec![anchor]);
let id = s.commit_open(prepared);
let sig = &s.get(id).unwrap().signatures[0];
assert!(sig.status == SignatureStatus::Valid && sig.verdict_shown);
let exported = exported_text(&s, id);
assert!(exported.contains("Signature valid"), "{exported}");
}
#[test]
fn background_open_uses_the_current_trust_and_language_at_commit() {
// Both changed while the document was prepared: the state and its words are both the new ones.
let (signer, anchor) = test_identity();
let mut cos = pdfcraft_cos::Document::open(Arc::new(named_layer_signable_fixture())).unwrap();
let signed = Arc::new(sign_prepared(&mut cos, &signer, "D:20261002120000+01'00'"));
let mut s = Session::new().with_clock(|| 1_800_000_000);
let prepared = s.open_context().prepare_open("background.pdf", None, signed, None).unwrap();
s.set_trusted_certificates(vec![anchor]);
s.set_signature_captions(StatusCaptions {
valid: "Signatur gültig".into(),
unknown: "Gültigkeit unbekannt".into(),
invalid: "Signatur ungültig".into(),
});
let id = s.commit_open(prepared);
assert_eq!(s.get(id).unwrap().signatures[0].status, SignatureStatus::Valid);
let exported = exported_text(&s, id);
assert!(exported.contains("Signatur gültig"), "{exported}");
}
#[test]
fn printing_draws_signature_states_only_where_the_screen_does() {
let (mut s, id) = trusted_named_layer_session();
let settings = print::Settings { pages: vec![0], paper: (400.0, 300.0), ..Default::default() };
// The screen falls back to the file's artwork when its display copy cannot be written, and
// takes the marks with it; print follows.
let doc = s.docs.iter_mut().find(|d| d.id == id).unwrap();
let mut cleared = doc.signatures.to_vec();
cleared[0].verdict_shown = false;
doc.signatures = Arc::new(cleared);
let (_, _, printed) = printed_pixels(s.print_pdf(id, &settings).unwrap());
let green = pixels_near(&printed, VALID_GREEN);
assert!(green < 50, "{green} green pixels");
}
#[test]
fn a_failed_display_write_drops_the_marks() {
let (mut s, id) = trusted_named_layer_session();
let doc = s.docs.iter_mut().find(|d| d.id == id).unwrap();
let mut signatures = doc.signatures.to_vec();
assert!(signatures[0].verdict_shown);
// A stream-limited document is read-only: the writer refuses it.
let unwritable = pdfcraft_cos::Document::open_with_stream_limit(doc.bytes.clone(), None, 1).unwrap();
let editor = doc.editor.as_mut().unwrap();
let shown = write_display_copy(editor, &doc.bytes, &unwritable, &mut signatures);
assert!(Arc::ptr_eq(&shown, &doc.bytes), "the page falls back to the file's own artwork");
assert!(!signatures[0].verdict_shown, "so nothing counts as drawn");
// Logged once, however many refreshes lose the copy again.
write_display_copy(editor, &doc.bytes, &unwritable, &mut signatures);
let logged = editor.cos.repair_log().iter().filter(|l| l.contains("the display copy could not be written")).count();
assert_eq!(logged, 1);
}
#[test]
fn background_open_uses_the_current_caption_language_at_commit() {
let (mut s, id) = trusted_named_layer_session();
let bytes = s.get(id).unwrap().bytes.clone();
let prepared = s.open_context().prepare_open("background.pdf", None, bytes, None).unwrap();
s.set_signature_captions(StatusCaptions {
valid: "Signatur gültig".into(),
unknown: "Gültigkeit unbekannt".into(),
invalid: "Signatur ungültig".into(),
});
let later = s.commit_open(prepared);
let exported = exported_text(&s, later);
assert!(exported.contains("Signatur gültig"), "{exported}");
assert!(s.get(later).unwrap().signatures[0].verdict_shown);
assert!(!s.get(later).unwrap().dirty);
}
#[test]
fn caption_language_follows_the_session_captions() {
let (mut s, id) = trusted_named_layer_session();
let generation = s.get(id).unwrap().generation;
let german = StatusCaptions { valid: "Signatur gültig".into(), unknown: "Gültigkeit unbekannt".into(), invalid: "Signatur ungültig".into() };
s.set_signature_captions(german);
let doc = s.get(id).unwrap();
assert!(!doc.dirty && doc.generation == generation, "captions are not an edit");
assert!(doc.signatures[0].verdict_shown);
let exported = exported_text(&s, id);
assert!(exported.contains("Signatur gültig"), "{exported}");
// Documents opened later draw with them too.
let (signer, _) = test_identity();
let mut cos = pdfcraft_cos::Document::open(Arc::new(named_layer_signable_fixture())).unwrap();
let later = s.open("later.pdf", None, Arc::new(sign_prepared(&mut cos, &signer, "D:20261002120000+01'00'")), None).unwrap();
let exported = exported_text(&s, later);
assert!(exported.contains("Signatur gültig"), "{exported}");
}
#[test]
fn non_win_ansi_captions_embed_inter_in_the_display_copy_only() {
// Words WinAnsi cannot encode are drawn in Inter, embedded into the display copy only.
let (mut s, id) = trusted_named_layer_session();
let russian = StatusCaptions {
valid: "Подпись действительна".into(),
unknown: "Действительность неизвестна".into(),
invalid: "Подпись недействительна".into(),
};
s.set_signature_captions(russian);
let exported = exported_text(&s, id);
assert!(exported.contains("Подпись действительна"), "{exported}");
let doc = s.get(id).unwrap();
assert!(bytes_has(&doc.display, b"/BaseFont /Inter") && !bytes_has(&doc.bytes, b"/BaseFont /Inter"), "Inter goes into the display copy only");
}
#[test]
#[ignore = "timing probe"]
fn probe_edit_latency_on_a_large_signed_document() {
@@ -7654,6 +8242,37 @@ fn free_text_without_appearance() -> Arc<Vec<u8>> {
Arc::new(bytes)
}
/// The CLI renders what the app shows with no trusted certificates: a named-layer signature in
/// the state it has then (validity unknown), not the "not verified" its file stores. The source
/// is not changed.
#[test]
fn cli_display_draws_signature_states_as_the_app_does_without_trust() {
let (id, _) = test_identity();
let mut doc = pdfcraft_cos::Document::open(Arc::new(named_layer_signable_fixture())).unwrap();
let signed = Arc::new(sign_prepared(&mut doc, &id, "D:20261002120000+01'00'"));
let display = display_bytes_for(signed.clone(), None);
assert!(!Arc::ptr_eq(&display, &signed), "the state is drawn into a copy");
let mut renderer = pdfcraft_render::PageRenderer::new(display, pdfcraft_render::RenderConfig::default());
let page = renderer.render(pdfcraft_render::RenderRequest { page: 0, scale: 1.0, ..Default::default() });
assert!(pixels_near(&page.rgba, UNKNOWN_AMBER) > 500, "the unknown state is drawn");
assert!(pixels_near(&page.rgba, [255, 214, 51]) < 50, "the stored question mark is not");
}
/// A layer recognised but too small to draw an icon in (a side so small the icon's scale rounds to
/// zero) changes nothing, so the CLI renders the source, as the app does.
#[test]
fn cli_display_makes_no_copy_when_no_state_could_be_drawn() {
let (id, _) = test_identity();
let n1 = format!("[0 0 0.{}6 100]", "0".repeat(322));
let mut doc = pdfcraft_cos::Document::open(Arc::new(named_layer_signable_fixture_with(&n1))).unwrap();
let signed = Arc::new(sign_prepared(&mut doc, &id, "D:20261002120000+01'00'"));
let cos = pdfcraft_cos::Document::open(signed.clone()).unwrap();
let trust = pdfcraft_sign::TrustStore::default();
let signatures = crate::doc_state::signatures_of(&cos, &signed, &trust, &pdfcraft_sign::DigestCache::default());
assert!(pdfcraft_sign::has_status_layers(&cos, &signatures), "the layers are recognised");
assert!(Arc::ptr_eq(&display_bytes_for(signed.clone(), None), &signed), "nothing was drawn, so there is no copy");
}
/// #2371: a comment without an appearance stream is displayed by the app, so the CLI's page image
/// must show it too. The helper's copy is for rendering only; documents that need no copy, and
/// files it can't display, keep exactly the original source bytes.
@@ -8514,6 +9133,141 @@ fn a_signed_document_rebuilt_from_object_headers_refuses_edits() {
assert!(!s.get(id).unwrap().dirty);
}
/// A one-page document whose only signature field is signed and named with `len` bytes. The
/// signature field walk reads names of up to 4096 bytes and passes longer ones over.
fn signed_field_named(len: usize) -> Vec<u8> {
pdf_of(&[
"<< /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [4 0 R] >> >>".to_string(),
"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".into(),
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 300] /Annots [4 0 R] >>".into(),
format!("<< /Type /Annot /Subtype /Widget /FT /Sig /T ({}) /V 5 0 R /Rect [20 20 180 60] /P 3 0 R >>", "a".repeat(len)),
"<< /Type /Sig /Filter /Adobe.PPKLite /SubFilter /adbe.pkcs7.detached /ByteRange [0 1 2 1] /Contents <00> >>".into(),
])
}
/// A PDF of `objs`, numbered from 1, with a cross-reference table.
fn pdf_of(objs: &[String]) -> 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
}
fn open_signed_field_named(len: usize) -> (Session, DocId) {
let mut s = Session::new();
let id = s.open("form.pdf", None, Arc::new(signed_field_named(len)), None).expect("opens");
(s, id)
}
/// The cap's boundary as the engine meets it: a 4096-byte name is read, and its signature blocks a
/// full rewrite.
#[test]
fn a_signature_named_at_the_cap_is_listed_and_blocks_a_full_rewrite() {
let (s, id) = open_signed_field_named(4096);
let doc = s.get(id).unwrap();
let listed: Vec<_> = doc.signatures.iter().map(|r| (r.field.len(), r.signed)).collect();
assert_eq!(listed, [(4096, true)], "the field is read, and no row stands for unread ones");
assert_eq!(s.save_full_bytes(id).unwrap_err(), EditError::Signed);
}
/// One byte past the cap the field goes unread: the list says so, and a full rewrite is still
/// refused.
#[test]
fn a_signature_named_one_byte_past_the_cap_still_blocks_a_full_rewrite() {
let (s, id) = open_signed_field_named(4097);
let doc = s.get(id).unwrap();
let unread = doc.signatures.iter().find(|r| r.field == "UnreadFields");
let said = unread.map(|r| (r.signed, r.status, r.details.first().is_some_and(|d| d.message.starts_with("This form has too many fields"))));
assert_eq!(said, Some((true, SignatureStatus::Unknown, true)), "{:?}", doc.signatures);
assert_eq!(s.save_full_bytes(id).unwrap_err(), EditError::Signed);
}
/// A signed field behind a kid with no /T: one merged with its widget under a named field that
/// isn't a signature field (the walk can't list it, so its row is the unread one), and one under a
/// node with no /T (listed by its full name). Either way the document is signed, and neither a full
/// save nor Optimize may rewrite it.
#[test]
fn signed_fields_behind_kids_without_a_name_block_a_full_rewrite() {
let page = |annot: u32| format!("<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 300] /Annots [{annot} 0 R] >>");
let head = |annot: u32| {
vec![
"<< /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [4 0 R] >> >>".to_string(),
"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".into(),
page(annot),
]
};
let sig = "<< /Type /Sig /SubFilter /ETSI.CAdES.detached /ByteRange [0 1 2 1] /Contents <00> >>".to_string();
let mut merged = head(5);
merged.extend([
"<< /T (parent) /Kids [5 0 R] >>".to_string(),
"<< /Type /Annot /Subtype /Widget /FT /Sig /V 6 0 R /Parent 4 0 R /Rect [20 20 180 60] /P 3 0 R >>".into(),
sig.clone(),
]);
let mut nested = head(6);
nested.extend([
"<< /T (p) /Kids [5 0 R] >>".to_string(),
"<< /Kids [6 0 R] /Parent 4 0 R >>".into(),
"<< /Type /Annot /Subtype /Widget /FT /Sig /T (s) /V 7 0 R /Parent 5 0 R /Rect [20 20 180 60] /P 3 0 R >>".into(),
sig,
]);
for (shape, objs, row) in [("merged", merged, "UnreadFields"), ("nested", nested, "p.s")] {
let mut s = Session::new();
let id = s.open("form.pdf", None, Arc::new(pdf_of(&objs)), None).expect("opens");
let doc = s.get(id).unwrap();
assert!(doc.is_signed() && doc.signatures.iter().any(|r| r.field == row), "{shape}: {:?}", doc.signatures);
assert_eq!(s.save_full_bytes(id).unwrap_err(), EditError::Signed, "{shape}");
assert!(matches!(s.optimize_job(id, &optimize::Settings::default(), &[]), Err(EditError::Signed)), "{shape}");
}
}
/// The walk stops short of a signed field, so a signature may go unlisted; the document still
/// counts as signed, and each guard against rewriting a signed document holds.
#[test]
fn a_signature_the_field_walk_passes_over_still_counts_as_signed() {
let (s, id) = open_signed_field_named(64 << 10);
let doc = s.get(id).unwrap();
assert!(doc.is_signed(), "{:?}", doc.signatures);
}
#[test]
fn a_full_rewrite_is_refused_when_the_field_walk_passes_a_signature_over() {
let (s, id) = open_signed_field_named(64 << 10);
assert_eq!(s.save_full_bytes(id).unwrap_err(), EditError::Signed);
}
#[test]
fn optimizing_is_refused_when_the_field_walk_passes_a_signature_over() {
let (s, id) = open_signed_field_named(64 << 10);
assert!(matches!(s.optimize_job(id, &optimize::Settings::default(), &[]), Err(EditError::Signed)));
}
#[test]
fn a_rewriting_edit_is_refused_when_the_field_walk_passes_a_signature_over() {
let (mut s, id) = open_signed_field_named(64 << 10);
assert!(matches!(s.apply(id, Edit::Sanitize), Err(EditError::SignedRewrite(_))));
}
#[test]
fn an_action_appends_to_a_file_whose_field_walk_passes_a_signature_over() {
let bytes = Arc::new(signed_field_named(64 << 10));
let steps = vec![actions::Step::from_id("set_title", "Checked").unwrap()];
let title = actions::Action { name: "Title".into(), description: String::new(), steps, builtin: false };
let r = actions::run_on(&title, "form.pdf", bytes.clone(), |_, _| {}).unwrap();
assert!(r.bytes.starts_with(&bytes[..]), "the action rewrote the file instead of appending to it");
let mut s = Session::new();
let id = s.open("out.pdf", None, r.bytes, None).unwrap();
assert_eq!(s.get(id).unwrap().info.title.as_deref(), Some("Checked"), "the title is in what was appended");
}
/// #1324: marking a figure decorative rewrites that figure only. The header, added text and an
/// unknown entry on the original stream stay attached to the page. This lives in the engine tests
/// because edit and a11y are the same layer and cannot depend on each other.
+1
View File
@@ -78,6 +78,7 @@ fn count_inner(source: ExportSource, pages: &[usize], options: Options, mut prog
tables: options.exclude_tables,
code: options.exclude_code,
images: options.exclude_images,
painted: false,
mcids: excluded.remove(&page).unwrap_or_default(),
};
let text = renderer.filtered_text(page, filter).map_err(|e| format!("page {}: {e}", page.saturating_add(1)))?.plain_text();
+8 -3
View File
@@ -31,15 +31,20 @@ fn run_xml(text: &str, size: f64, bold: bool, italic: bool, color: [f64; 3]) ->
format!("<w:r><w:rPr>{rpr}</w:rPr><w:t xml:space=\"preserve\">{}</w:t></w:r>", esc(text))
}
/// One Word table: explicit absent borders (alignment alone cannot prove PDF rules), a grid sized
/// from the detected column edges, `gridSpan` for spanning cells, empty cells for holes.
/// One Word table: single borders when the page's rules draw its grid, explicit absent borders
/// otherwise (alignment alone cannot prove PDF rules), a grid sized from the detected column
/// edges, `gridSpan` for spanning cells, empty cells for holes.
pub(crate) fn docx_table(t: &Table) -> String {
let mut edges = t.cols.clone();
edges.push(t.rect[2]);
let widths: Vec<i64> = edges.windows(2).map(|w| ((w[1] - w[0]).max(20.0) * 20.0).round().clamp(60.0, 31680.0) as i64).collect();
let mut s = String::from("<w:tbl><w:tblPr><w:tblW w:w=\"0\" w:type=\"auto\"/><w:tblBorders>");
for edge in ["top", "left", "bottom", "right", "insideH", "insideV"] {
s.push_str(&format!("<w:{edge} w:val=\"nil\"/>"));
if t.ruled {
s.push_str(&format!("<w:{edge} w:val=\"single\" w:sz=\"4\" w:space=\"0\" w:color=\"auto\"/>"));
} else {
s.push_str(&format!("<w:{edge} w:val=\"nil\"/>"));
}
}
s.push_str("</w:tblBorders></w:tblPr><w:tblGrid>");
for w in &widths {
+80 -8
View File
@@ -43,6 +43,9 @@ pub struct Page {
/// The colour the whole page is painted before its content (a page background), as sRGB
/// components in 0..=1; `None` for a page with no background of its own.
pub background: Option<[f64; 3]>,
/// The ruled lines the page draws (horizontal and vertical strokes, thin filled bars), each
/// as its box [x0, y0, x1, y1] on the displayed page in points (y up).
pub rules: Vec<[f64; 4]>,
}
/// One cell of a detected table. `span` is how many grid columns the cell covers (a header
@@ -65,6 +68,9 @@ pub struct Table {
pub rect: [f64; 4],
pub cols: Vec<f64>,
pub rows: Vec<Vec<Cell>>,
/// Whether the page's ruled lines separate every pair of neighbouring cells, so the writers
/// can draw the table's borders.
pub ruled: bool,
}
/// What goes into the output, in order.
@@ -248,10 +254,72 @@ fn is_cell_like(b: &Block) -> bool {
(b.rect[3] - b.rect[1]) <= b.size * 5.0 && !b.text.trim().is_empty()
}
/// A rule at most this thick (points) is a line, not a filled area.
const RULE_THICK: f64 = 3.0;
/// Rule comparisons one page may spend deciding whether its tables are ruled; past it a table
/// counts as unruled, so a hostile page of many rules and cells stays quick.
const RULE_BUDGET: usize = 4_000_000;
/// Whether `rules` separate every pair of neighbouring cells of a table whose rows are `rows`
/// (block indices, top to bottom) and whose columns start at `edges` and end at `right`: between
/// two columns a vertical rule beside each row (unless a cell of that row spans across), and
/// between two rows a horizontal rule under each column. Every check spends `budget`.
fn ruled(blocks: &[Block], rules: &[[f64; 4]], rows: &[Vec<usize>], edges: &[f64], right: f64, budget: &mut usize) -> bool {
let vertical: Vec<&[f64; 4]> = rules.iter().filter(|r| r[2] - r[0] <= RULE_THICK && r[3] - r[1] > RULE_THICK).collect();
let horizontal: Vec<&[f64; 4]> = rules.iter().filter(|r| r[3] - r[1] <= RULE_THICK && r[2] - r[0] > RULE_THICK).collect();
let mut find = |set: &[&[f64; 4]], hit: &dyn Fn(&[f64; 4]) -> bool| -> bool {
set.iter().any(|r| {
*budget = budget.saturating_sub(1);
*budget > 0 && hit(r)
})
};
// Each row's vertical span.
let spans: Vec<[f64; 2]> = rows
.iter()
.map(|row| {
let bs = || row.iter().filter_map(|&i| blocks.get(i));
[bs().map(|b| b.rect[1]).fold(f64::INFINITY, f64::min), bs().map(|b| b.rect[3]).fold(f64::NEG_INFINITY, f64::max)]
})
.collect();
for (row, span) in rows.iter().zip(&spans) {
let mid = (span[0] + span[1]) / 2.0;
for pair in edges.windows(2) {
let (lo, hi) = (pair[0], pair[1]);
let cells = || row.iter().filter_map(|&i| blocks.get(i));
if cells().any(|b| b.rect[0] < hi - COL_TOL && b.rect[2] > hi + COL_TOL) {
continue;
}
let clear = |x: f64| !cells().any(|b| b.rect[0] + COL_TOL < x && x < b.rect[2] - COL_TOL);
if !find(&vertical, &|r| {
let x = (r[0] + r[2]) / 2.0;
lo + COL_TOL < x && x <= hi + COL_TOL && r[1] <= mid && mid <= r[3] && clear(x)
}) {
return false;
}
}
}
let mids: Vec<f64> = edges.iter().zip(edges.iter().skip(1).chain(std::iter::once(&right))).map(|(a, b)| (a + b) / 2.0).collect();
for pair in spans.windows(2) {
let (below_top, above_bottom) = (pair[1][1], pair[0][0]);
for &x in &mids {
if !find(&horizontal, &|r| {
let y = (r[1] + r[3]) / 2.0;
below_top - COL_TOL <= y && y <= above_bottom + COL_TOL && r[0] <= x && x <= r[2]
}) {
return false;
}
}
}
true
}
/// Detect tables in a page's blocks from their text layout: columns are left edges shared by
/// several short blocks, rows are blocks whose vertical spans overlap. Returns the tables and,
/// several short blocks, rows are blocks whose vertical spans overlap. Two columns of two rows
/// are a table only when `rules` (the page's ruled lines) draw its grid. Returns the tables and,
/// per block, whether a table consumed it (so `items` can drop it from the paragraph flow).
pub(crate) fn tables(blocks: &[Block]) -> (Vec<Table>, Vec<bool>) {
pub(crate) fn tables(blocks: &[Block], rules: &[[f64; 4]]) -> (Vec<Table>, Vec<bool>) {
let mut budget = RULE_BUDGET;
let mut consumed = vec![false; blocks.len()];
// Candidate columns: cluster the left edges of cell-like blocks.
let mut xs: Vec<(f64, usize)> = blocks.iter().enumerate().filter(|(_, b)| is_cell_like(b)).map(|(i, b)| (b.rect[0], i)).collect();
@@ -313,7 +381,7 @@ pub(crate) fn tables(blocks: &[Block]) -> (Vec<Table>, Vec<bool>) {
}
// Runs of consecutive rows that have two or more distinct columns are tables.
let mut out = Vec::new();
let flush = |run: &mut Vec<Vec<(usize, usize)>>, out: &mut Vec<Table>, consumed: &mut Vec<bool>| {
let flush = |run: &mut Vec<Vec<(usize, usize)>>, out: &mut Vec<Table>, consumed: &mut Vec<bool>, budget: &mut usize| {
if run.len() < 2 {
run.clear();
return;
@@ -325,12 +393,16 @@ pub(crate) fn tables(blocks: &[Block]) -> (Vec<Table>, Vec<bool>) {
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;
let right = used.iter().map(|&i| blocks[i].rect[2]).fold(f64::MIN, f64::max) + COL_TOL;
let is_ruled = (2..=MAX_COLS).contains(&ncols) && !rules.is_empty() && {
let row_blocks: Vec<Vec<usize>> = run.iter().map(|row| row.iter().map(|(_, i)| *i).collect()).collect();
ruled(blocks, rules, &row_blocks, &edges, right, budget)
};
let ok = (ncols >= 3 || (ncols == 2 && (run.len() >= 3 || is_ruled))) && ncols <= MAX_COLS;
if !ok {
run.clear();
return;
}
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<usize>)>> = vec![None; ncols];
for row in run.drain(..) {
@@ -385,7 +457,7 @@ pub(crate) fn tables(blocks: &[Block]) -> (Vec<Table>, Vec<bool>) {
right,
used.iter().map(|&i| blocks[i].rect[3]).fold(f64::MIN, f64::max),
];
out.push(Table { rect, cols: edges, rows: rows_out });
out.push(Table { rect, cols: edges, rows: rows_out, ruled: is_ruled });
};
// Runs of consecutive multi-column rows are tables. Rows on either side of a run that
// hold a single cell wide enough to span two columns (a header band, a totals row) join
@@ -436,7 +508,7 @@ pub(crate) fn tables(blocks: &[Block]) -> (Vec<Table>, Vec<bool>) {
if end < rows.len() && rows[end].len() == 1 && spans_run(&run_edges(&rows[start..end]), rows[end][0].1) {
pieces.push(rows[end].clone());
}
flush(&mut pieces, &mut out, &mut consumed);
flush(&mut pieces, &mut out, &mut consumed, &mut budget);
}
(out, consumed)
}
@@ -448,7 +520,7 @@ pub(crate) fn items(pages: &[Page]) -> Vec<Item<'_>> {
if i > 0 {
out.push(Item::PageBreak);
}
let (tables, consumed) = tables(&p.blocks);
let (tables, consumed) = tables(&p.blocks, &p.rules);
// Blocks and images by their top edge, top to bottom.
// A paragraph sits where its first run does: its other runs follow along the same line.
let mut parts: Vec<(f64, f64, Item)> = paragraphs(&p.blocks, &consumed)
+1 -1
View File
@@ -127,7 +127,7 @@ pub fn pptx(pages: &[Page], title: &str) -> Vec<u8> {
let mut slides: Vec<(String, String)> = Vec::new(); // (slide_xml, slide_rels)
for p in pages {
let (tables, consumed) = crate::tables(&p.blocks);
let (tables, consumed) = crate::tables(&p.blocks, &p.rules);
let title_idx = p
.blocks
.iter()
+4 -1
View File
@@ -46,6 +46,7 @@ fn sample_page() -> Page {
rotation: 0.0,
}],
background: None,
rules: Vec::new(),
}
}
@@ -174,6 +175,7 @@ fn pptx_package_parts_are_complete_and_consistent() {
],
images: Vec::new(),
background: None,
rules: Vec::new(),
};
let bytes = pptx(&[sample_page(), table_page], "Two");
let parts = entries(&bytes);
@@ -278,7 +280,7 @@ fn hostile_sizes_do_not_overflow_the_slide_position() {
rotation: 0.0,
})
.collect();
let p = Page { width: f64::MAX, height: f64::NAN, blocks, images, background: None };
let p = Page { width: f64::MAX, height: f64::NAN, blocks, images, background: None, rules: Vec::new() };
let bytes = pptx(&[p], "Hostile");
let slide = part(&bytes, "ppt/slides/slide1.xml");
assert!(slide.contains("Title") && slide.contains("<p:pic>"), "the slide is still written");
@@ -360,6 +362,7 @@ fn pptx_table_cell_with_largest_font_stays_in_table_and_not_in_title() {
],
images: Vec::new(),
background: None,
rules: Vec::new(),
};
let bytes = pptx(&[p], "Table Check");
let slide_xml = part(&bytes, "ppt/slides/slide1.xml");
+54 -14
View File
@@ -14,7 +14,7 @@ fn varied_page(n: usize) -> Page {
space_around: [false; 2],
})
.collect();
Page { width: 612.0, height: 792.0, blocks, images: Vec::new(), background: None }
Page { width: 612.0, height: 792.0, blocks, images: Vec::new(), background: None, rules: Vec::new() }
}
fn lookup_steps(f: impl FnOnce()) -> usize {
@@ -69,6 +69,7 @@ fn page() -> Page {
rotation: 0.0,
}],
background: None,
rules: Vec::new(),
}
}
@@ -136,6 +137,7 @@ fn word_table_cell_widths_follow_the_columns_they_span() {
vec![cell("All", 3)],
vec![cell("First", 1)],
],
ruled: false,
};
let xml = docx_table(&table);
assert!(xml.contains("<w:gridCol w:w=\"1000\"/><w:gridCol w:w=\"2000\"/><w:gridCol w:w=\"3000\"/>"), "{xml}");
@@ -360,6 +362,7 @@ fn table_page() -> Page {
],
images: Vec::new(),
background: None,
rules: Vec::new(),
}
}
@@ -376,7 +379,7 @@ fn grid_text_becomes_a_real_table_in_every_format() {
let d = docx(std::slice::from_ref(&p), "Bill");
assert!(d.starts_with(b"PK"));
assert!(d.windows(b"word/document.xml".len()).any(|w| w == b"word/document.xml"));
let (tables, _) = tables(&p.blocks);
let (tables, _) = tables(&p.blocks, &p.rules);
assert_eq!(tables.len(), 1);
let table_xml = docx_table(&tables[0]);
assert!(table_xml.contains("<w:tblGrid>"));
@@ -421,7 +424,7 @@ fn a_staircase_of_blocks_is_not_a_huge_table() {
})
.collect();
let started = std::time::Instant::now();
let (tables, _) = tables(&blocks);
let (tables, _) = tables(&blocks, &[]);
assert!(tables.iter().all(|t| t.cols.len() <= MAX_COLS), "{} columns", tables.iter().map(|t| t.cols.len()).max().unwrap_or(0));
assert!(started.elapsed() < std::time::Duration::from_secs(5), "took {:?}", started.elapsed());
}
@@ -451,6 +454,7 @@ fn word_opens_tables_up_to_its_column_limit() {
.collect(),
images: Vec::new(),
background: None,
rules: Vec::new(),
};
let grid_cols = |p: &Page| part(&docx(std::slice::from_ref(p), "Grid"), "word/document.xml").matches("<w:gridCol ").count();
assert_eq!(grid_cols(&grid(63)), 63, "63 columns is still a table");
@@ -486,6 +490,7 @@ fn a_link_inside_a_sentence_is_not_a_table_column() {
],
images: Vec::new(),
background: None,
rules: Vec::new(),
};
let h = html(std::slice::from_ref(&p), "Regulations");
assert!(!h.contains("<table>"), "running text became a table: {h}");
@@ -507,7 +512,7 @@ fn sentences_that_run_on_into_links_are_not_a_table() {
blocks.push(block(lead, 72.0, y, 211.0, y + 12.0));
blocks.push(blue("https://example.org/event", 212.5, y, 360.0, y + 12.0));
}
let p = Page { width: 612.0, height: 792.0, blocks, images: Vec::new(), background: None };
let p = Page { width: 612.0, height: 792.0, blocks, images: Vec::new(), background: None, rules: Vec::new() };
let h = html(std::slice::from_ref(&p), "Event");
assert!(!h.contains("<table>"), "sentences became a table: {h}");
assert_eq!(h.matches("https://example.org/event").count(), 3, "{h}");
@@ -529,7 +534,7 @@ fn table_spans_do_not_consume_text_they_do_not_emit() {
}
}
let p = Page { width: 612.0, height: 792.0, blocks, ..Page::default() };
let (tables, consumed) = tables(&p.blocks);
let (tables, consumed) = tables(&p.blocks, &p.rules);
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");
@@ -558,11 +563,11 @@ fn a_superscript_beside_a_number_keeps_its_table() {
blocks.push(Block { size: 8.0, ..block(sup, 106.0, y + 5.0, 113.0, y + 13.0) });
blocks.push(block(&format!("{},000", 30 - 5 * n), 300.0, y, 340.0, y + 12.0));
}
let p = Page { width: 612.0, height: 792.0, blocks, images: Vec::new(), background: None };
let p = Page { width: 612.0, height: 792.0, blocks, images: Vec::new(), background: None, rules: Vec::new() };
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);
let (tables, consumed) = tables(&p.blocks, &p.rules);
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)));
@@ -591,6 +596,7 @@ fn two_column_body_text_is_not_mistaken_for_a_table() {
],
images: Vec::new(),
background: None,
rules: Vec::new(),
};
let h = html(&[p], "Paper");
assert!(!h.contains("<table>"), "tall two-column text must stay paragraphs: {h}");
@@ -675,7 +681,7 @@ fn italic_sentence() -> Vec<Block> {
fn an_italic_word_stays_in_its_sentence() {
let mut blocks = italic_sentence();
blocks.push(block("The next line is a paragraph of its own.", 72.0, 684.0, 300.0, 696.0));
let p = Page { width: 612.0, height: 792.0, blocks, images: Vec::new(), background: None };
let p = Page { width: 612.0, height: 792.0, blocks, images: Vec::new(), background: None, rules: Vec::new() };
let xml = part(&docx(std::slice::from_ref(&p), "Opinion"), "word/document.xml");
assert_eq!(
word_paragraphs(&xml),
@@ -700,7 +706,7 @@ fn an_italic_word_stays_in_its_sentence() {
fn a_sentence_keeps_its_reading_order() {
let mut blocks = vec![block("Then the next line.", 72.0, 684.0, 200.0, 696.0)];
blocks.extend(italic_sentence().into_iter().rev());
let p = Page { width: 612.0, height: 792.0, blocks, images: Vec::new(), background: None };
let p = Page { width: 612.0, height: 792.0, blocks, images: Vec::new(), background: None, rules: Vec::new() };
let xml = part(&docx(std::slice::from_ref(&p), "Opinion"), "word/document.xml");
assert_eq!(
word_paragraphs(&xml),
@@ -721,7 +727,7 @@ fn runs_keep_the_spaces_the_source_had_between_them() {
block("E = mc", 72.0, 660.0, 110.0, 672.0),
Block { size: 8.0, ..block("2", 110.0, 665.0, 115.0, 673.0) },
];
let p = Page { width: 612.0, height: 792.0, blocks, images: Vec::new(), background: None };
let p = Page { width: 612.0, height: 792.0, blocks, images: Vec::new(), background: None, rules: Vec::new() };
let xml = part(&docx(std::slice::from_ref(&p), "Spaces"), "word/document.xml");
assert_eq!(
word_paragraphs(&xml),
@@ -733,7 +739,7 @@ fn runs_keep_the_spaces_the_source_had_between_them() {
#[test]
fn turned_text_is_not_a_run_of_the_line_beside_it() {
let blocks = vec![block("Before", 72.0, 700.0, 110.0, 712.0), Block { rotation: 90.0, ..block("SIDE", 111.0, 690.0, 123.0, 720.0) }];
let p = Page { width: 612.0, height: 792.0, blocks, images: Vec::new(), background: None };
let p = Page { width: 612.0, height: 792.0, blocks, images: Vec::new(), background: None, rules: Vec::new() };
let h = html(std::slice::from_ref(&p), "Turned");
assert!(h.contains("<p>Before</p>") && h.contains("<p>SIDE</p>"), "{h}");
}
@@ -744,7 +750,7 @@ fn a_block_on_the_next_line_starts_a_paragraph() {
block("The first line ends here", 72.0, 700.0, 190.0, 712.0),
Block { italic: true, ..block("and the next starts there.", 190.5, 690.0, 320.0, 702.0) },
];
let p = Page { width: 612.0, height: 792.0, blocks, images: Vec::new(), background: None };
let p = Page { width: 612.0, height: 792.0, blocks, images: Vec::new(), background: None, rules: Vec::new() };
let xml = part(&docx(std::slice::from_ref(&p), "Lines"), "word/document.xml");
assert_eq!(word_paragraphs(&xml), vec![runs(&[("The first line ends here", false)]), runs(&[("and the next starts there.", true)])], "{xml}");
}
@@ -761,7 +767,7 @@ fn table_cells_are_not_runs_of_a_paragraph() {
blocks.push(block(&format!("{},000", 30 - 5 * n), 300.0, y, 340.0, y + 12.0));
}
blocks.extend(italic_sentence().into_iter().map(|b| Block { rect: [b.rect[0], b.rect[1] - 200.0, b.rect[2], b.rect[3] - 200.0], ..b }));
let p = Page { width: 612.0, height: 792.0, blocks, images: Vec::new(), background: None };
let p = Page { width: 612.0, height: 792.0, blocks, images: Vec::new(), background: None, rules: Vec::new() };
let xml = part(&docx(std::slice::from_ref(&p), "Prizes"), "word/document.xml");
assert_eq!(xml.matches("<w:tbl>").count(), 1, "{xml}");
for cell in ["st", "nd", "rd", "30,000"] {
@@ -781,7 +787,7 @@ fn a_paragraph_is_a_heading_only_when_its_text_is() {
Block { bold: true, ..block("Summary", 72.0, 700.0, 125.0, 712.0) },
block("the year closed with more members than it opened with, and fewer debts.", 128.0, 700.0, 540.0, 712.0),
];
let p = Page { width: 612.0, height: 792.0, blocks, images: Vec::new(), background: None };
let p = Page { width: 612.0, height: 792.0, blocks, images: Vec::new(), background: None, rules: Vec::new() };
let xml = part(&docx(std::slice::from_ref(&p), "Report"), "word/document.xml");
assert_eq!(xml.matches("<w:pStyle w:val=\"Heading1\"/>").count(), 1, "{xml}");
assert!(!xml.contains("Heading2"), "the lead-in made its paragraph a heading: {xml}");
@@ -830,6 +836,7 @@ fn markdown_escapes_markup_and_keeps_emphasis_and_tables() {
],
images: Vec::new(),
background: None,
rules: Vec::new(),
};
let md = markdown(&[p]);
assert!(md.contains("\\- not a list item"), "{md}");
@@ -859,3 +866,36 @@ fn markdown_escapes_markup_and_keeps_emphasis_and_tables() {
assert!(rows.contains(&"| A1 | kWh | 37414.00 |"), "{md}");
assert!(rows.iter().all(|r| r.matches(" | ").count() == 2), "every row has the header's three cells: {md}");
}
/// #5149: two columns of two rows are a table when ruled lines draw its grid, and the docx keeps
/// its borders; the same text without rules (or with rules that only underline it) stays paragraphs.
#[test]
fn a_ruled_two_by_two_grid_is_a_table() {
let blocks = vec![
block("Name", 25.0, 250.0, 55.0, 261.0),
block("Value", 165.0, 250.0, 195.0, 261.0),
block("Alpha", 25.0, 225.0, 55.0, 236.0),
block("One", 165.0, 225.0, 185.0, 236.0),
];
let grid = vec![
[20.0, 270.0, 300.0, 270.0],
[20.0, 245.0, 300.0, 245.0],
[20.0, 220.0, 300.0, 220.0],
[20.0, 220.0, 20.0, 270.0],
[160.0, 220.0, 160.0, 270.0],
[300.0, 220.0, 300.0, 270.0],
];
let (found, consumed) = tables(&blocks, &grid);
assert_eq!(found.len(), 1);
assert!(found[0].ruled);
assert_eq!(found[0].rows.len(), 2);
assert!(consumed.iter().all(|used| *used));
let p = Page { width: 320.0, height: 300.0, blocks: blocks.clone(), rules: grid, ..Page::default() };
let xml = part(&docx(std::slice::from_ref(&p), "Grid"), "word/document.xml");
assert_eq!(xml.matches("<w:tbl>").count(), 1, "{xml}");
assert!(xml.contains("w:val=\"single\"") && !xml.contains("w:val=\"nil\""), "{xml}");
assert!(tables(&blocks, &[]).0.is_empty(), "alignment alone does not make two by two a table");
let underlines = [[20.0, 245.0, 300.0, 245.0]];
assert!(tables(&blocks, &underlines).0.is_empty(), "a rule between the rows alone is no grid");
}
+3 -3
View File
@@ -3,7 +3,7 @@
PDF stream filters: the decoders and encoders behind `/Filter` and `/DecodeParms`.
- **Layer:** L0, standalone. No dependency on any other PdfCraft crate. `cos` depends on it (architecture §3 rule 3).
- **Licence:** MIT OR Apache-2.0. Clean-room: written from ISO 32000-2 §7.4, RFC 1950/1951 (through `flate2` with the pure-Rust `miniz_oxide` backend), TIFF 6.0 §14 (predictor 2) and RFC 2083 §6 (PNG filters). CCITT Group 4 encoding (ITU-T T.6) is the `fax` crate's (MIT, already in the tree through `tiff`), checked here by round trips through an independent decoder; CCITT decoding (T.4 and T.6) is the `hayro-ccitt` crate's, and JBIG2 decoding the `hayro-jbig2` crate's (both MIT OR Apache-2.0, already in the tree through hayro), bounded here. JBIG2 generic region encoding is written from the public ISO/IEC 14492 Final Committee Draft (WG1 N1359, 1999); Annex H.2 checks the arithmetic coder byte for byte.
- **Licence:** MIT OR Apache-2.0. Clean-room: written from ISO 32000-2 §7.4, RFC 1950/1951 (through `flate2` with the pure-Rust `zlib-rs` backend), TIFF 6.0 §14 (predictor 2) and RFC 2083 §6 (PNG filters). CCITT Group 4 encoding (ITU-T T.6) is the `fax` crate's (MIT, already in the tree through `tiff`), checked here by round trips through an independent decoder; CCITT decoding (T.4 and T.6) is the `hayro-ccitt` crate's, and JBIG2 decoding the `hayro-jbig2` crate's (both MIT OR Apache-2.0, already in the tree through hayro), bounded here. JBIG2 generic region encoding is written from the public ISO/IEC 14492 Final Committee Draft (WG1 N1359, 1999); Annex H.2 checks the arithmetic coder byte for byte.
- `#![forbid(unsafe_code)]`. Builds for `wasm32-unknown-unknown`.
@@ -38,14 +38,14 @@ encode_jbig2_shared(&[(data, columns, rows)]) -> Result<Option<SharedJbig2>, Fil
- Image codecs (DCT, JPX, JBIG2, CCITT), `Crypt` and unknown filters anywhere in a chain give `Unsupported`: callers keep such data encoded. So does a chain longer than `MAX_CHAIN` (8) filters, before any stage runs. Decryption belongs to `crypt`.
- `max_output` bounds every intermediate buffer (including the pre-predictor buffer) and gives `LimitExceeded(max_output)`. This also holds when Flate retries raw deflate after a misleading zlib header, in both strict and tolerant decoding.
- `decode_counted` and `decode_tolerant_counted` are for a caller charging a budget (`pdfcraft_cos::DecodeBudget`). `max_output` bounds all stages together (each stage gets what the earlier ones left), and they give the bytes every stage that ran decoded, on success and on failure. A stage's output counts as its decoder produced it, before a predictor or a later stage shrinks it, and a failed decode pays for what it decoded first.
- `decode_tolerant_within` is for a run of images (`pdfcraft_cos::ImageBudget`), as `decode_within` (its strict form), `decode_jbig2_within` and `decode_ccitt_within` are, all spending from one `work`, in the JBIG2 decoder's steps. `max_output` bounds each stage, as in `decode_tolerant`, and no stage decodes past what `work` has left. It pays a step a byte of `data` first and a step a byte each stage decodes, so a chain that fails has paid for what it did: 0.2 to 3 ns a byte in or out, up to 19 ns through a predictor on samples of a bit, against the 6 to 16 ns of a JBIG2 step. What `work` can't pay for spends all of it, and gives `Spent`; with nothing left nothing is read. A chain that can't be decoded at all costs nothing and gives its usual error.
- `decode_tolerant_within` is for a run of images (`pdfcraft_cos::ImageBudget`), as `decode_within` (its strict form), `decode_jbig2_within` and `decode_ccitt_within` are, all spending from one `work`, in the JBIG2 decoder's steps. `max_output` bounds each stage, as in `decode_tolerant`, and no stage decodes past what `work` has left. It pays a step a byte of `data` first and a step a byte each stage decodes, so a chain that fails has paid for what it did: 0.2 to 3 ns a byte in or out, up to 19 ns through a predictor on samples of a bit, against the 6 to 16 ns of a JBIG2 step. A Flate stage also pays `FLATE_READ_WORK` (2) steps a byte it reads, before it runs, and again if it reads them a second time as raw deflate: inflating does work for every block it reads, and a stream of empty dynamic blocks took 21 ns a byte to make nothing, about 7 ns a step at that price. flate2 inflates with its zlib-rs backend, which it prefers to miniz_oxide when other dependencies build that too; miniz_oxide, its backend here before, took 1.4 µs a byte on empty fixed blocks. What `work` can't pay for spends all of it, and gives `Spent`; with nothing left nothing is read. A chain that can't be decoded at all costs nothing and gives its usual error.
- `decode_tolerant` turns `Corrupt` into "what was decoded so far" plus `partial = true`, then runs the rest of the chain on it (predictors are applied to partial output too). `LimitExceeded` and `Unsupported` are still errors.
## Behaviour
| Filter | Decode | Encode |
|---|---|---|
| FlateDecode | zlib header checked, then inflated raw: a missing or wrong Adler-32 is tolerated; no valid header → raw deflate; trailing bytes ignored; preset dictionary → Corrupt; truncated → Corrupt (partial in tolerant mode) | zlib level 6 |
| FlateDecode | zlib header checked, then inflated raw: a missing or wrong Adler-32 is tolerated; no valid header → raw deflate; trailing bytes ignored; preset dictionary → Corrupt; truncated, a back-reference to before the start of the output, or a dynamic block without an end-of-block code → Corrupt (partial in tolerant mode) | zlib level 6 |
| LZWDecode | 9–12-bit MSB-first codes, clear (256), EOD (257), `EarlyChange` 0/1; missing EOD/initial clear tolerated; a full table stops growing | greedy, leading clear, clear-table when the table fills, EOD |
| Predictors (Flate/LZW) | 2 = TIFF (1/2/4/8/16 bpc), 10–15 = PNG with per-row tags 0–4; partial final rows decoded; bad params or tags → Corrupt | 2, 10 None, 11 Sub, 12 Up, 13 Average, 14 Paeth, 15 per-row optimum (min sum of signed residuals) |
| ASCIIHexDecode | white space ignored, odd digit padded with 0, `>` EOD (optional), other characters → Corrupt | upper case, newline every 64 digits, `>` |
+145 -14
View File
@@ -5,6 +5,11 @@
//! deflate stream is inflated raw after the 2-byte zlib header;
//! - streams without a valid zlib header are inflated as raw deflate;
//! - data after the end of the deflate stream is ignored.
//!
//! A back-reference to before the start of the output points at nothing, and is damage, as zlib
//! has it: read strictly the stream is refused, and read tolerantly what came before it is kept.
//! (miniz_oxide, flate2's backend here before zlib-rs, copied zeros and went on.) So is a dynamic
//! block whose code has no end-of-block symbol, and nothing of that block is kept.
use std::io::Write;
@@ -21,25 +26,48 @@ fn zlib_header(data: &[u8]) -> Option<(u8, u8)> {
ok.then_some((cmf, flg))
}
pub(crate) fn decode(data: &[u8], max: usize) -> Step {
/// `data` inflated within `max`, and whether it was read twice: a zlib header that only looked
/// valid is read again as raw deflate, within `again`, what a caller paying for what is read has
/// left for it once it has paid for the second reading. `None`, that reading can't be paid for,
/// and is [`FilterError::Spent`](crate::FilterError::Spent).
pub(crate) fn decode(data: &[u8], max: usize, again: Option<usize>) -> (Step, bool) {
match zlib_header(data) {
Some((_, flg)) if flg & 0x20 != 0 => Err(Failure::corrupt(NAME, "zlib preset dictionary is not allowed in PDF", Vec::new())),
Some((_, flg)) if flg & 0x20 != 0 => (Err(Failure::corrupt(NAME, "zlib preset dictionary is not allowed in PDF", Vec::new())), false),
Some(_) => match inflate_raw(&data[2..], max) {
// A header that only looked valid: retry the whole input as raw deflate.
Err(f) if f.partial.is_empty() && matches!(f.error, crate::FilterError::Corrupt { .. }) => match inflate_raw(data, max) {
// Keep the original corruption diagnostic only if the retry is corrupt
// too. A limit error must remain fatal even for tolerant decoding. What the
// retry decoded isn't kept, but a caller charging for work has to hear of it.
Err(retry) if matches!(retry.error, crate::FilterError::Corrupt { .. }) => Err(Failure { discarded: retry.partial.len(), ..f }),
retry => retry,
},
r => r,
Err(f) if f.partial.is_empty() && matches!(f.error, crate::FilterError::Corrupt { .. }) => {
let Some(again) = again else {
return (Err(Failure { error: crate::FilterError::Spent, partial: Vec::new(), discarded: 0 }), false);
};
let step = match inflate_raw(data, again) {
// Keep the original corruption diagnostic only if the retry is corrupt
// too. A limit error must remain fatal even for tolerant decoding. What the
// retry decoded isn't kept, but a caller charging for work has to hear of it.
Err(retry) if matches!(retry.error, crate::FilterError::Corrupt { .. }) => Err(Failure { discarded: retry.partial.len(), ..f }),
retry => retry,
};
(step, true)
}
r => (r, false),
},
None => inflate_raw(data, max),
None => (inflate_raw(data, max), false),
}
}
#[cfg(test)]
thread_local! {
/// Bytes inflating gave back on this thread, its partial output included.
pub(crate) static INFLATED: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
fn inflate_raw(input: &[u8], max: usize) -> Step {
let step = inflate(input, max);
#[cfg(test)]
INFLATED.with(|c| c.set(c.get() + step.as_ref().map_or_else(|f| f.partial.len(), Vec::len)));
step
}
fn inflate(input: &[u8], max: usize) -> Step {
let mut d = Decompress::new(false);
let mut out: Vec<u8> = Vec::new();
// One byte beyond the limit lets us tell "exactly max" from "more than max".
@@ -87,7 +115,7 @@ mod tests {
use crate::FilterError;
fn dec(d: &[u8]) -> Result<Vec<u8>, FilterError> {
decode(d, 1 << 24).map_err(|f| f.error)
decode(d, 1 << 24, Some(1 << 24)).0.map_err(|f| f.error)
}
#[test]
@@ -144,7 +172,7 @@ mod tests {
fn corrupt_and_truncated() {
let data: Vec<u8> = (0..10_000u32).map(|i| (i % 13) as u8).collect();
let z = encode(&data);
match decode(&z[..z.len() / 2], 1 << 24) {
match decode(&z[..z.len() / 2], 1 << 24, Some(1 << 24)).0 {
Err(f) => {
assert!(matches!(f.error, FilterError::Corrupt { .. }));
assert_eq!(&data[..f.partial.len()], &f.partial[..]);
@@ -155,6 +183,8 @@ mod tests {
assert!(matches!(dec(&[0x78, 0x9c, 0x07, 0, 0, 0]), Err(FilterError::Corrupt { .. })));
// Preset dictionary.
assert!(matches!(dec(&[0x78, 0x20, 0, 0, 0, 0]), Err(FilterError::Corrupt { .. })));
// One whose header is followed by data that inflates: refused all the same.
assert!(matches!(dec(&[0x78, 0xBB, 0x4b, 0x04, 0x00]), Err(FilterError::Corrupt { .. })));
}
#[test]
@@ -168,6 +198,107 @@ mod tests {
}
fn dec_limit(d: &[u8], max: usize) -> Result<Vec<u8>, FilterError> {
decode(d, max).map_err(|f| f.error)
decode(d, max, Some(max)).0.map_err(|f| f.error)
}
/// Deflate's bits: header fields and extra bits least significant first, Huffman codes most
/// significant first (RFC 1951 §3.1.1).
#[derive(Default)]
struct Bits {
out: Vec<u8>,
acc: u32,
n: u32,
}
impl Bits {
fn put(&mut self, value: u32, len: u32) {
for i in 0..len {
self.acc |= ((value >> i) & 1) << self.n;
self.n += 1;
if self.n == 8 {
self.out.push(self.acc as u8);
(self.acc, self.n) = (0, 0);
}
}
}
fn code(&mut self, code: u32, len: u32) {
for i in (0..len).rev() {
self.put((code >> i) & 1, 1);
}
}
fn finish(mut self) -> Vec<u8> {
if self.n > 0 {
self.out.push(self.acc as u8);
}
self.out
}
}
/// A dynamic block whose literal and length code has no end-of-block symbol can't end (RFC 1951
/// §3.2.5): it is refused, and nothing of it is kept.
#[test]
fn a_dynamic_code_without_an_end_is_damage() {
let mut bits = Bits::default();
bits.put(1, 1); // the final block,
bits.put(2, 2); // dynamic Huffman codes (§3.2.7)
bits.put(0, 5); // 257 literal and length codes
bits.put(0, 5); // 1 distance code
bits.put(14, 4); // 18 code length codes, in their order up to the one for 1
for symbol in [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1] {
bits.put(u32::from(symbol == 18 || symbol == 1), 3);
}
// Code length codes: 1 is 0, 18 is 1. 'A' and 'B' get a bit each, 256 none.
let zeros = |bits: &mut Bits, n: u32| {
bits.code(1, 1);
bits.put(n - 11, 7);
};
zeros(&mut bits, 65);
bits.code(0, 1);
bits.code(0, 1);
zeros(&mut bits, 138);
zeros(&mut bits, 52);
bits.code(0, 1); // the distance code: a bit
for _ in 0..4 {
bits.code(0, 1); // 'A'
}
let data = bits.finish();
assert!(zlib_header(&data).is_none(), "read as raw deflate");
match decode(&data, 1 << 20, Some(1 << 20)).0 {
Err(f) => {
assert!(matches!(f.error, FilterError::Corrupt { .. }), "{}", f.error);
assert_eq!(f.partial, b"");
}
Ok(out) => panic!("read as {out:?}"),
}
}
/// A back-reference to before the start of the output points at nothing: read strictly the
/// stream is refused, and what came before it is what a tolerant reading keeps. miniz_oxide,
/// flate2's backend here before zlib-rs, copied zeros and went on, so this also shows which
/// backend inflates (the price of reading Flate, `FLATE_READ_WORK`, is set for zlib-rs).
#[test]
fn a_copy_from_before_the_start_is_damage() {
let literal = |bits: &mut Bits, b: u8| bits.code(0x30 + u32::from(b), 8);
let mut bits = Bits::default();
bits.put(1, 1); // the final block,
bits.put(1, 2); // fixed Huffman codes (§3.2.6)
literal(&mut bits, b'A');
literal(&mut bits, b'B');
bits.code(1, 7); // length 3
bits.code(4, 5); // distance 5 (code 4 and an extra bit of 0), three bytes before the start
bits.put(0, 1);
literal(&mut bits, b'C');
bits.code(0, 7); // end of block
let data = bits.finish();
assert!(zlib_header(&data).is_none(), "read as raw deflate");
match decode(&data, 1 << 20, Some(1 << 20)).0 {
Err(f) => {
assert!(matches!(f.error, FilterError::Corrupt { .. }), "{}", f.error);
assert_eq!(f.partial, b"AB");
}
Ok(out) => panic!("read as {out:?}"),
}
}
}
+130 -32
View File
@@ -189,7 +189,7 @@ pub(crate) fn pay(work: &mut u64, steps: u64) -> Result<(), FilterError> {
/// [`FilterError::Unsupported`] (callers keep such data encoded), as does a chain longer than
/// [`MAX_CHAIN`]. `max_output` bounds every intermediate buffer.
pub fn decode(chain: &[(Filter, Params)], data: &[u8], max_output: usize) -> Result<Vec<u8>, FilterError> {
run(chain, data, max_output, None, true).map(|(v, _, _)| v).map_err(|(e, _)| e)
run(chain, data, max_output, None, true, false).map(|(v, _, _)| v).map_err(|(e, _)| e)
}
/// Like [`decode`] for a caller charging an allowance: `max_output` bounds the bytes all stages
@@ -197,27 +197,28 @@ pub fn decode(chain: &[(Filter, Params)], data: &[u8], max_output: usize) -> Res
/// bytes, on success and on failure. A stage's output counts even when a later stage or its
/// predictor shrinks it.
pub fn decode_counted(chain: &[(Filter, Params)], data: &[u8], max_output: usize) -> Result<(Vec<u8>, usize), (FilterError, usize)> {
run(chain, data, max_output, Some(max_output), true).map(|(v, _, spent)| (v, spent))
run(chain, data, max_output, Some(max_output), true, false).map(|(v, _, spent)| (v, spent))
}
/// Like [`decode`], but on corrupt data returns what was decoded before the error and
/// reports `partial = true` (the behaviour viewers expect). The remaining filters of the
/// chain still run on the partial data. Limit and unsupported errors are still errors.
pub fn decode_tolerant(chain: &[(Filter, Params)], data: &[u8], max_output: usize) -> Result<(Vec<u8>, bool), FilterError> {
run(chain, data, max_output, None, false).map(|(v, partial, _)| (v, partial)).map_err(|(e, _)| e)
run(chain, data, max_output, None, false, false).map(|(v, partial, _)| (v, partial)).map_err(|(e, _)| e)
}
/// [`decode_tolerant`] bounded and counted as [`decode_counted`] is.
pub fn decode_tolerant_counted(chain: &[(Filter, Params)], data: &[u8], max_output: usize) -> Result<(Vec<u8>, bool, usize), (FilterError, usize)> {
run(chain, data, max_output, Some(max_output), false)
run(chain, data, max_output, Some(max_output), false, false)
}
/// [`decode_tolerant`], spending from `work`, what decoding may still cost across a run of images:
/// a step for each byte of `data`, paid before anything is decoded, and one for each byte a stage
/// decodes, so a chain that fails, or a stage that goes past `max_output`, has paid for what it did.
/// No stage decodes past what is left: a chain that `work` can't pay for spends all of it and stops
/// there, so with nothing left nothing is read. A chain that can't be decoded at all costs nothing,
/// whatever is left, so what an image's filters are is known from the error.
/// a step for each byte of `data`, paid before anything is decoded, [`FLATE_READ_WORK`] for each
/// byte a Flate stage reads, paid before it runs (again if it reads them twice), and one for each
/// byte a stage decodes, so a chain that fails, or a stage that goes past `max_output`, has paid for
/// what it did. No stage decodes past what is left: a chain that `work` can't pay for spends all of
/// it and stops there, so with nothing left nothing is read. A chain that can't be decoded at all
/// costs nothing, whatever is left, so what an image's filters are is known from the error.
///
/// Unlike [`decode_tolerant`], no filters at all gives `data` itself, within `max_output`.
pub fn decode_tolerant_within(chain: &[(Filter, Params)], data: &[u8], max_output: usize, work: &mut u64) -> Result<Vec<u8>, FilterError> {
@@ -237,14 +238,15 @@ fn spending(chain: &[(Filter, Params)], data: &[u8], max_output: usize, work: &m
return if data.len() > max_output { Err(FilterError::LimitExceeded(max_output)) } else { Ok(data.to_vec()) };
}
let left = usize::try_from(*work).unwrap_or(usize::MAX);
match run(chain, data, max_output, Some(left), strict) {
match run(chain, data, max_output, Some(left), strict, true) {
Ok((out, _, decoded)) => pay(work, decoded as u64).map(|()| out),
// The stage stopped at the lower of the two, which took as much to find out.
Err((FilterError::LimitExceeded(_), decoded)) if left.saturating_sub(decoded) > max_output => {
pay(work, (decoded as u64).saturating_add(max_output as u64))?;
Err(FilterError::LimitExceeded(max_output))
}
Err((FilterError::LimitExceeded(_), _)) => {
// Past what is left, a stage stops, or a Flate stage doesn't start.
Err((FilterError::LimitExceeded(_) | FilterError::Spent, _)) => {
*work = 0;
Err(FilterError::Spent)
}
@@ -256,6 +258,20 @@ fn spending(chain: &[(Filter, Params)], data: &[u8], max_output: usize, work: &m
/// up to the output limit, so the chain length multiplies the work.
pub const MAX_CHAIN: usize = 8;
/// The steps each byte Flate reads costs where decoding is paid for ([`decode_tolerant_within`],
/// [`decode_within`]), besides the step it was paid as input and a step for each byte it makes.
/// Inflating does work for every block it reads, whether or not the block makes anything: an empty
/// fixed-Huffman block is ten bits (RFC 1951 §3.2.6). With flate2's zlib-rs backend (zlib-rs
/// 0.6.8, release build) the slowest blocks measured, empty dynamic ones, took 21 ns a byte read
/// to make nothing, empty fixed ones 9 and fixed ones of a literal each 6, so at this price the
/// worst per byte read comes to about 7 ns a step, inside what a step of JBIG2 decoding takes.
/// (miniz_oxide 0.9.1, flate2's backend here before, took about 1.7 µs for every fixed-Huffman
/// block, empty or not: 1,383 ns a byte read on empty ones.) A stage's start isn't priced, about
/// 0.25 µs: every way to repeat one takes bytes of the file, so what starts cost is bounded by the
/// file's length. Data a real encoder makes took 0.2 to 2.3 ns a byte made, its reading included, so
/// an image pays twice its stored length more than it would unpriced.
pub const FLATE_READ_WORK: u64 = 2;
/// Whether a chain is one [`run`] takes, and if not, the error.
fn decodable(chain: &[(Filter, Params)]) -> Result<(), FilterError> {
if chain.len() > MAX_CHAIN {
@@ -269,22 +285,39 @@ fn decodable(chain: &[(Filter, Params)]) -> Result<(), FilterError> {
/// The decoded data, whether it is partial and the bytes all stages decoded, or the error and
/// the bytes decoded before it. `max` bounds each stage, and `total` all of them together.
/// `priced`, the count is steps: each Flate stage also pays [`FLATE_READ_WORK`] for each byte it
/// reads, before it runs, so a stage `total` can't pay for doesn't run
/// ([`FilterError::Spent`]).
fn run(
chain: &[(Filter, Params)],
data: &[u8],
max: usize,
total: Option<usize>,
strict: bool,
priced: bool,
) -> Result<(Vec<u8>, bool, usize), (FilterError, usize)> {
decodable(chain).map_err(|e| (e, 0))?;
let mut cur: Cow<[u8]> = Cow::Borrowed(data);
let mut partial = false;
let mut spent = 0usize;
let price = usize::try_from(FLATE_READ_WORK).unwrap_or(usize::MAX);
for (filter, params) in chain {
let read = if priced && matches!(filter, Filter::Flate) { price.saturating_mul(cur.len()) } else { 0 };
let room = total.map_or(usize::MAX, |total| total.saturating_sub(spent));
if read > room {
return Err((FilterError::Spent, spent));
}
spent = spent.saturating_add(read);
#[cfg(test)]
STAGE_BYTES.with(|c| c.set(c.get() + cur.len()));
let limit = total.map_or(max, |total| max.min(total.saturating_sub(spent)));
let (step, work) = decode_one(filter, params, &cur, limit);
// A second reading of the same bytes (Flate's raw retry) is paid for as the first was, and
// makes no more than is left once it has been.
let again = room.checked_sub(read.saturating_mul(2)).map(|left| max.min(left));
let (step, work, again) = decode_one(filter, params, &cur, limit, again);
if again {
spent = spent.saturating_add(read);
}
spent = spent.saturating_add(work);
cur = Cow::Owned(match step {
Ok(v) => v,
@@ -299,15 +332,21 @@ fn run(
Ok((cur.into_owned(), partial, spent))
}
/// One stage's result and the bytes its decoder produced (before any predictor).
fn decode_one(filter: &Filter, params: &Params, data: &[u8], max: usize) -> (Step, usize) {
/// One stage's result, the bytes its decoder produced (before any predictor), and whether it
/// read its input twice, which it does only within `again` ([`flate::decode`]).
fn decode_one(filter: &Filter, params: &Params, data: &[u8], max: usize, again: Option<usize>) -> (Step, usize, bool) {
let once = |(step, n): (Step, usize)| (step, n, false);
match filter {
Filter::Flate => with_predictor(flate::decode(data, max), params, "FlateDecode"),
Filter::Lzw => with_predictor(lzw::decode(data, params.early_change != 0, max), params, "LZWDecode"),
Filter::AsciiHex => counted(asciihex::decode(data, max)),
Filter::Ascii85 => counted(ascii85::decode(data, max)),
Filter::RunLength => counted(runlength::decode(data, max)),
other => (Err(Failure { error: FilterError::Unsupported(other.name().to_owned()), partial: Vec::new(), discarded: 0 }), 0),
Filter::Flate => {
let (step, twice) = flate::decode(data, max, again);
let (step, n) = with_predictor(step, params, "FlateDecode");
(step, n, twice)
}
Filter::Lzw => once(with_predictor(lzw::decode(data, params.early_change != 0, max), params, "LZWDecode")),
Filter::AsciiHex => once(counted(asciihex::decode(data, max))),
Filter::Ascii85 => once(counted(ascii85::decode(data, max))),
Filter::RunLength => once(counted(runlength::decode(data, max))),
other => (Err(Failure { error: FilterError::Unsupported(other.name().to_owned()), partial: Vec::new(), discarded: 0 }), 0, false),
}
}
@@ -553,7 +592,7 @@ mod tests {
let data = encode_flate(&hex);
let chain = [(Filter::Flate, Params::default()), (Filter::AsciiHex, Params::default())];
let whole = decode(&chain, &data, 1 << 20).unwrap();
let cost = (data.len() + hex.len() + whole.len()) as u64;
let cost = (data.len() + hex.len() + whole.len()) as u64 + FLATE_READ_WORK * data.len() as u64;
let mut work = u64::MAX;
assert_eq!(decode_tolerant_within(&chain, &data, 1 << 20, &mut work).unwrap(), whole);
assert_eq!(u64::MAX - work, cost);
@@ -585,8 +624,11 @@ mod tests {
assert_eq!(work, 0);
super::STAGE_BYTES.with(|c| c.get())
};
assert_eq!(read((bomb.len() + inner.len()) as u64 + 10), bomb.len() + inner.len(), "the second stage stops");
assert_eq!(read(bomb.len() as u64 + 10), bomb.len(), "the first stops, and the second never runs");
let paid = |n: usize| (1 + FLATE_READ_WORK) * n as u64;
assert_eq!(read(paid(bomb.len()) + paid(inner.len()) + 10), bomb.len() + inner.len(), "the second stage stops");
assert_eq!(read(paid(bomb.len()) + FLATE_READ_WORK * inner.len() as u64 - 1), bomb.len(), "the second can't pay to read");
assert_eq!(read(paid(bomb.len()) + 10), bomb.len(), "the first stops, and the second never runs");
assert_eq!(read(paid(bomb.len()) - 1), 0, "the first can't pay to read");
assert_eq!(read(bomb.len() as u64 - 1), 0, "it can't pay to be read");
}
@@ -598,18 +640,19 @@ mod tests {
let chain = [(Filter::Flate, Params::default())];
let mut work = u64::MAX;
assert!(matches!(decode_tolerant_within(&chain, &data, 1000, &mut work), Err(FilterError::LimitExceeded(1000))));
assert_eq!(u64::MAX - work, data.len() as u64 + 1000);
let read = |n: usize| FLATE_READ_WORK * n as u64;
assert_eq!(u64::MAX - work, data.len() as u64 + read(data.len()) + 1000);
// The later stage of two, which pays for the first as well.
let bomb = encode_flate(&data);
let two = [(Filter::Flate, Params::default()), (Filter::Flate, Params::default())];
let mut work = u64::MAX;
assert!(matches!(decode_tolerant_within(&two, &bomb, data.len(), &mut work), Err(FilterError::LimitExceeded(_))));
assert_eq!(u64::MAX - work, (bomb.len() + 2 * data.len()) as u64);
assert_eq!(u64::MAX - work, (bomb.len() + 2 * data.len()) as u64 + read(bomb.len()) + read(data.len()));
// Both limits at once: a run that can't go on is what a caller needs to hear.
let mut work = data.len() as u64 + 1000;
let mut work = data.len() as u64 + read(data.len()) + 1000;
assert!(refused(&decode_tolerant_within(&chain, &data, 1000, &mut work).unwrap_err()));
assert_eq!(work, 0);
let mut work = data.len() as u64 + 1001;
let mut work = data.len() as u64 + read(data.len()) + 1001;
assert!(matches!(decode_tolerant_within(&chain, &data, 1000, &mut work), Err(FilterError::LimitExceeded(1000))));
assert_eq!(work, 1, "the image's limit, with a step to spare");
}
@@ -625,21 +668,22 @@ mod tests {
assert!(!partial.is_empty());
let mut work = u64::MAX;
assert_eq!(decode_tolerant_within(&chain, &cut, 1 << 20, &mut work).unwrap(), partial);
assert_eq!(u64::MAX - work, (cut.len() + partial.len()) as u64);
let read = |n: usize| FLATE_READ_WORK * n as u64;
assert_eq!(u64::MAX - work, (cut.len() + partial.len()) as u64 + read(cut.len()));
// Read strictly it is an error, for the same work.
let mut work = u64::MAX;
assert!(matches!(decode_within(&chain, &cut, 1 << 20, &mut work), Err(FilterError::Corrupt { .. })));
assert_eq!(u64::MAX - work, (cut.len() + partial.len()) as u64);
assert_eq!(u64::MAX - work, (cut.len() + partial.len()) as u64 + read(cut.len()));
let whole = encode_flate(&data);
let mut work = u64::MAX;
assert_eq!(decode_within(&chain, &whole, 1 << 20, &mut work).unwrap(), data);
assert_eq!(u64::MAX - work, (whole.len() + data.len()) as u64);
assert_eq!(u64::MAX - work, (whole.len() + data.len()) as u64 + read(whole.len()));
// A predictor that comes to nothing, after all of this was inflated for it.
let p = Params { predictor: 99, ..Params::default() };
let data = encode_flate(&vec![0; 1 << 16]);
let mut work = u64::MAX;
assert!(decode_tolerant_within(&[(Filter::Flate, p)], &data, 1 << 20, &mut work).unwrap().is_empty());
assert_eq!(u64::MAX - work, data.len() as u64 + (1 << 16));
assert_eq!(u64::MAX - work, data.len() as u64 + read(data.len()) + (1 << 16));
}
/// A stream that reads as zlib only until it fails, and as raw deflate until that fails too,
@@ -661,13 +705,67 @@ mod tests {
assert_eq!(spent, 0x0601);
let mut work = u64::MAX;
assert!(decode_tolerant_within(&chain, &data, 1 << 20, &mut work).unwrap().is_empty());
assert_eq!(u64::MAX - work, (data.len() + 0x0601) as u64);
// Read twice: as zlib, then as raw deflate.
assert_eq!(u64::MAX - work, (data.len() + 0x0601) as u64 + 2 * FLATE_READ_WORK * data.len() as u64);
// Through a predictor, which would otherwise lose the count.
let p = Params { predictor: 12, columns: 4, ..Params::default() };
let (_, _, spent) = decode_tolerant_counted(&[(Filter::Flate, p)], &data, 1 << 20).unwrap();
assert_eq!(spent, 0x0601);
}
/// Inflating does work for every block it reads, whether or not the block makes anything: empty
/// fixed-Huffman blocks, ten bits each, make nothing however many there are. Each byte of them
/// is paid for at Flate's price before any is read.
#[test]
fn a_flate_stage_pays_for_what_it_reads() {
// Four empty blocks in five bytes, as raw deflate, then an empty final block.
let mut hollow = [0x02, 0x08, 0x20, 0x80, 0x00].repeat(1 << 12);
hollow.extend([0x03, 0x00]);
let chain = [(Filter::Flate, Params::default())];
assert_eq!(decode(&chain, &hollow, 1 << 20).unwrap(), b"");
let cost = (1 + FLATE_READ_WORK) * hollow.len() as u64;
let mut work = u64::MAX;
assert_eq!(decode_tolerant_within(&chain, &hollow, 1 << 20, &mut work).unwrap(), b"");
assert_eq!(u64::MAX - work, cost);
let mut work = cost;
assert!(decode_tolerant_within(&chain, &hollow, 1 << 20, &mut work).is_ok(), "exactly enough");
assert_eq!(work, 0);
super::STAGE_BYTES.with(|c| c.set(0));
let mut work = cost - 1;
assert!(refused(&decode_tolerant_within(&chain, &hollow, 1 << 20, &mut work).unwrap_err()));
assert_eq!((work, super::STAGE_BYTES.with(|c| c.get())), (0, 0), "nothing was inflated");
// Counted for a byte allowance, as a page's content is, reading costs nothing.
assert_eq!(decode_counted(&chain, &hollow, 1 << 20).unwrap(), (Vec::new(), 0));
}
/// A zlib header that only looked valid is read again as raw deflate, and the second reading
/// is paid for as the first was. One that can't be paid for is refused, not read as damaged.
#[test]
fn a_second_reading_is_paid_for() {
// As zlib: a block of a reserved type at once. As raw deflate: a stored block of this many
// zero bytes, then an empty final block.
let mut data = vec![0x78, 0x01, 0x06, 0xFE, 0xF9];
data.extend(vec![0u8; 0x0601]);
data.extend([0x03, 0x00]);
let chain = [(Filter::Flate, Params::default())];
assert_eq!(decode(&chain, &data, 1 << 20).unwrap(), vec![0u8; 0x0601]);
let read = FLATE_READ_WORK * data.len() as u64;
let mut work = (data.len() + 0x0601) as u64 + 2 * read;
assert_eq!(decode_tolerant_within(&chain, &data, 1 << 20, &mut work).unwrap(), vec![0u8; 0x0601]);
assert_eq!(work, 0, "exactly enough");
// Enough to read it once and not twice: it isn't read again.
super::flate::INFLATED.with(|c| c.set(0));
let mut work = data.len() as u64 + 2 * read - 1;
assert!(refused(&decode_tolerant_within(&chain, &data, 1 << 20, &mut work).unwrap_err()));
assert_eq!((work, super::flate::INFLATED.with(|c| c.get())), (0, 0));
// Enough to read it twice, and a byte short of what it makes: the second reading makes no
// more than is left once it has been paid for.
super::flate::INFLATED.with(|c| c.set(0));
let mut work = (data.len() + 0x0601) as u64 + 2 * read - 1;
assert!(refused(&decode_tolerant_within(&chain, &data, 1 << 20, &mut work).unwrap_err()));
assert!(super::flate::INFLATED.with(|c| c.get()) < 0x0601, "it stopped short");
}
/// With nothing left nothing is read. What can't be decoded at all never costs anything, and
/// says so whatever is left. Without filters, what is read is the data.
#[test]
+1 -1
View File
@@ -31,7 +31,7 @@ pub use script::{
script_missing, script_outline,
};
pub use shaping::{
ShapedCluster, ShapedScript, arabic_glyph, arabic_has, hebrew_has, shape_arabic, shape_hebrew, shape_thai, shaped_glyph, thai_has,
ShapedCluster, ShapedScript, arabic_glyph, arabic_has, face_glyph, hebrew_has, shape_arabic, shape_hebrew, shape_thai, shaped_glyph, thai_has,
};
pub use std14::Std14;
+8 -5
View File
@@ -156,13 +156,13 @@ fn cids_with_outlines(doc: &Document, font: &Dict) -> Vec<u64> {
let Some(program) = dict(doc, descendant.get(b"FontDescriptor")).and_then(|d| d.get(b"FontFile2").cloned()) else { return Vec::new() };
let program = doc.resolve(&program);
let Object::Stream(stream) = program.as_ref() else { return Vec::new() };
let Ok(bytes) = stream.decoded_within(16 << 20) else { return Vec::new() };
let Ok(bytes) = doc.with_direct_parms(stream).decoded_within(16 << 20) else { return Vec::new() };
let Some(loca) = skrifa::FontRef::from_index(&bytes, 0).ok().and_then(|face| face.loca(None).ok()) else { return Vec::new() };
let outlined = |gid: u32| loca.get_raw(gid as usize).zip(loca.get_raw(gid as usize + 1)).is_some_and(|(start, end)| end > start);
match descendant.get(b"CIDToGIDMap").map(|o| doc.resolve(o)).as_deref() {
None | Some(Object::Name(_)) => bit_set_below_64k((0..loca.len().min(0x1_0000) as u32).filter(|&gid| outlined(gid))),
Some(Object::Stream(map)) => {
let Ok(map) = map.decoded_within(1 << 17) else { return Vec::new() };
let Ok(map) = doc.with_direct_parms(map).decoded_within(1 << 17) else { return Vec::new() };
bit_set_below_64k(
map.as_chunks::<2>()
.0
@@ -189,7 +189,7 @@ fn embedded_widths(doc: &Document, font: &Dict, m: &mut Metrics) {
let Some(object) = descriptor.get(key) else { continue };
let object = doc.resolve(object);
let Object::Stream(stream) = object.as_ref() else { continue };
let Ok(bytes) = stream.decoded_within(16 << 20) else { continue };
let Ok(bytes) = doc.with_direct_parms(stream).decoded_within(16 << 20) else { continue };
let Ok(face) = skrifa::FontRef::from_index(&bytes, 0) else { continue };
let upem = f64::from(face.metrics(Size::unscaled(), LocationRef::default()).units_per_em);
if upem == 0.0 {
@@ -691,7 +691,7 @@ impl Metrics {
m.codes = Codes::Two;
if let Some(e) = font.get(b"Encoding").map(|e| doc.resolve(e))
&& let Object::Stream(s) = &*e
&& let Ok(data) = s.decoded_within(MAX_CMAP_BYTES)
&& let Ok(data) = doc.with_direct_parms(s).decoded_within(MAX_CMAP_BYTES)
{
let (spaces, cids) = parse_cmap(&data);
if !spaces.is_empty() {
@@ -1293,7 +1293,10 @@ fn unicode_map(doc: &Document, font: &Dict, composite: bool) -> Unicode {
}
match font.get(b"ToUnicode").map(|t| doc.resolve(t)).as_deref() {
Some(Object::Stream(s)) => {
if let Ok(data) = s.decoded_within(MAX_CMAP_BYTES) {
// With `/DecodeParms` given by reference, as every stream of the font is read here,
// and as the redaction proof reads the map: the two must get the same text, or a copy
// redaction rightly left counts as a survivor.
if let Ok(data) = doc.with_direct_parms(s).decoded_within(MAX_CMAP_BYTES) {
parse_to_unicode(&data, &mut out);
}
}
+115 -18
View File
@@ -104,6 +104,18 @@ fn font(doc: &mut Document, entries: Vec<(&str, Object)>) -> Dict {
d
}
/// `data` behind Flate and a PNG predictor whose `/DecodeParms` is a reference: read without
/// it, every row of four bytes keeps its tag byte.
fn behind_parms_by_reference(doc: &mut Document, data: &[u8]) -> Object {
let parms = doc.add(Object::Dict(Dict::from_iter([(b"Predictor".to_vec(), Object::Int(12)), (b"Columns".to_vec(), Object::Int(4))])));
let mut data = data.to_vec();
data.resize(data.len().next_multiple_of(4), 0);
let rows: Vec<u8> = data.chunks(4).flat_map(|row| std::iter::once(0).chain(row.iter().copied())).collect();
let mut stream = Stream::flate(Dict::new(), &rows);
stream.dict.set(b"DecodeParms".to_vec(), Object::Ref(parms));
Object::Ref(doc.add(Object::Stream(stream)))
}
#[test]
fn embedded_editor_fonts_are_validated_without_installing_or_exporting() {
use pdfcraft_cos::Stream;
@@ -124,34 +136,46 @@ fn embedded_editor_fonts_are_validated_without_installing_or_exporting() {
}
/// #2130: with no `/Widths`, an embedded program's advances win over a guess from the name
/// ("Mono" would mean Courier, 600 units for every glyph).
/// ("Mono" would mean Courier, 600 units for every glyph), the program's `/DecodeParms` given
/// directly or by reference.
#[test]
fn a_font_without_widths_measures_with_its_embedded_program() {
use pdfcraft_cos::Stream;
use skrifa::MetadataProvider as _;
let mut doc = Document::new_empty();
let bytes = include_bytes!("../../../../assets/fonts/Inter-Regular.ttf");
let face = skrifa::FontRef::new(bytes).unwrap();
let (size, location) = (skrifa::instance::Size::unscaled(), skrifa::instance::LocationRef::default());
let upem = f64::from(face.metrics(size, location).units_per_em);
let advance = |c: char| f64::from(face.glyph_metrics(size, location).advance_width(face.charmap().map(c).unwrap()).unwrap()) / upem;
let program = doc.add(Object::Stream(Stream::flate(Dict::new(), bytes)));
let mut descriptor = Dict::new();
descriptor.set(b"FontFile2".to_vec(), Object::Ref(program));
let f = font(
&mut doc,
vec![
("Subtype", Object::name("TrueType")),
("BaseFont", Object::name("HouseMono")),
("Encoding", Object::name("WinAnsiEncoding")),
("FontDescriptor", Object::Dict(descriptor)),
],
);
let m = Metrics::from_dict(&doc, &f);
for c in ['i', 'l', 'W', ' '] {
assert!((m.width(u32::from(c)) - advance(c)).abs() < 1e-9, "{c}: {} vs {}", m.width(u32::from(c)), advance(c));
for by_reference in [false, true] {
let mut doc = Document::new_empty();
let program = if by_reference {
behind_parms_by_reference(&mut doc, bytes)
} else {
Object::Ref(doc.add(Object::Stream(Stream::flate(Dict::new(), bytes))))
};
let mut descriptor = Dict::new();
descriptor.set(b"FontFile2".to_vec(), program);
let f = font(
&mut doc,
vec![
("Subtype", Object::name("TrueType")),
("BaseFont", Object::name("HouseMono")),
("Encoding", Object::name("WinAnsiEncoding")),
("FontDescriptor", Object::Dict(descriptor)),
],
);
let m = Metrics::from_dict(&doc, &f);
for c in ['i', 'l', 'W', ' '] {
assert!(
(m.width(u32::from(c)) - advance(c)).abs() < 1e-9,
"{c}, by reference {by_reference}: {} vs {}",
m.width(u32::from(c)),
advance(c)
);
}
assert!(m.width(u32::from('i')) < 0.4, "not Courier's 0.6, by reference {by_reference}");
}
assert!(m.width(u32::from('i')) < 0.4, "not Courier's 0.6");
}
#[test]
@@ -342,6 +366,79 @@ fn cmap_streams_decode_within_a_size_cap() {
}
}
#[test]
fn cmap_streams_read_their_parameters_given_by_reference() {
// Both maps behind a predictor whose `/DecodeParms` is a reference: read without it, every
// row keeps its tag byte inside the map's tokens.
let to_unicode = b"1 begincodespacerange <0000> <FFFF> endcodespacerange 1 beginbfrange <0024> <0026> <0041> endbfrange";
let encoding = b"1 begincodespacerange <0000> <FFFF> endcodespacerange 1 begincidrange <0000> <FFFF> 0 endcidrange";
let mut doc = Document::new_empty();
let (tu, enc) = (behind_parms_by_reference(&mut doc, to_unicode), behind_parms_by_reference(&mut doc, encoding));
let mut desc = Dict::new();
desc.set(b"Subtype".to_vec(), Object::name("CIDFontType2"));
let f = font(
&mut doc,
vec![("Subtype", Object::name("Type0")), ("Encoding", enc), ("DescendantFonts", Object::Array(vec![Object::Dict(desc)])), ("ToUnicode", tu)],
);
let m = Metrics::from_dict(&doc, &f);
assert_eq!(m.decode(&[0, 0x24]), "A", "ToUnicode");
assert!(matches!(m.codes, Codes::Ranges(_)), "Encoding");
}
/// A Type 0 subset over Inter with `/DW` alone, whose CIDs 1 to 7 draw "A B C D" (ToUnicode
/// gives CIDs 1 and 2), its program and its `/CIDToGIDMap` each behind a predictor whose
/// `/DecodeParms` is a reference, or behind Flate alone.
fn inter_subset(program_by_reference: bool, map_by_reference: bool) -> Metrics {
use skrifa::MetadataProvider as _;
let bytes = include_bytes!("../../../../assets/fonts/Inter-Regular.ttf");
let face = skrifa::FontRef::new(bytes).unwrap();
let gid = |c: char| u16::try_from(face.charmap().map(c).unwrap().to_u32()).unwrap();
let gids: Vec<u8> = std::iter::once(0).chain("A B C D".chars().map(gid)).flat_map(u16::to_be_bytes).collect();
let stream = |doc: &mut Document, data: &[u8], by_reference: bool| {
if by_reference { behind_parms_by_reference(doc, data) } else { Object::Ref(doc.add(Object::Stream(Stream::flate(Dict::new(), data)))) }
};
let mut doc = Document::new_empty();
let program = stream(&mut doc, bytes, program_by_reference);
let map = stream(&mut doc, &gids, map_by_reference);
let to_unicode = b"1 begincodespacerange <0000> <FFFF> endcodespacerange 2 beginbfchar <0001> <0041> <0002> <0020> endbfchar";
let to_unicode = stream(&mut doc, to_unicode, false);
let mut descriptor = Dict::new();
descriptor.set(b"FontFile2".to_vec(), program);
let mut desc = Dict::new();
desc.set(b"Subtype".to_vec(), Object::name("CIDFontType2"));
desc.set(b"DW".to_vec(), Object::Int(600));
desc.set(b"FontDescriptor".to_vec(), Object::Dict(descriptor));
desc.set(b"CIDToGIDMap".to_vec(), map);
let f = font(
&mut doc,
vec![
("Subtype", Object::name("Type0")),
("BaseFont", Object::name("ABCDEF+Inter")),
("Encoding", Object::name("Identity-H")),
("DescendantFonts", Object::Array(vec![Object::Dict(desc)])),
("ToUnicode", to_unicode),
],
);
Metrics::from_dict(&doc, &f)
}
/// A subset with `/DW` alone has a glyph for a CID when the program's glyph it maps to has an
/// outline, so the space, Inter's empty glyph, is refused. Its program, or its `/CIDToGIDMap`,
/// behind parameters given by reference says the same: read without them, no program says
/// which glyphs are empty, or the map points the CIDs at other glyphs.
#[test]
fn a_subsets_program_and_cid_map_read_their_parameters_given_by_reference() {
let direct = inter_subset(false, false);
assert!(!direct.outlined_cids.is_empty());
assert_eq!(direct.encode("A").as_deref(), Some(&[0, 1][..]));
assert_eq!(direct.encode(" "), None, "the space's glyph is empty");
for (program, map) in [(true, false), (false, true)] {
let m = inter_subset(program, map);
assert_eq!(m.outlined_cids, direct.outlined_cids, "program by reference: {program}, map: {map}");
assert_eq!(m.encode(" "), None, "program by reference: {program}, map: {map}");
}
}
#[test]
fn composite_fonts_use_to_unicode() {
let mut doc = Document::new_empty();
+10
View File
@@ -147,6 +147,16 @@ pub fn arabic_glyph(id: u32) -> Result<GlyphOutline, GlyphError> {
/// A bounded outline from the same face that produced the shaped glyph id.
pub fn shaped_glyph(script: ShapedScript, id: u32) -> Result<GlyphOutline, GlyphError> {
let (font, _) = face(script).ok_or(GlyphError::NoFont)?;
glyph(font, id)
}
/// Glyph `id` of the face in `bytes`, bounded like [`shaped_glyph`]: for text shaped with
/// [`crate::source_shaping::shape`] in a face no [`ShapedScript`] names.
pub fn face_glyph(bytes: &[u8], id: u32) -> Result<GlyphOutline, GlyphError> {
glyph(&FontRef::new(bytes).map_err(|_| GlyphError::NoFont)?, id)
}
fn glyph(font: &FontRef, id: u32) -> Result<GlyphOutline, GlyphError> {
if font.maxp().map_or(true, |m| id >= u32::from(m.num_glyphs())) {
return Err(GlyphError::Missing);
}
+4 -1
View File
@@ -22,11 +22,14 @@ let report = optimize_with_progress(&mut doc, &settings, &mut |stage| keep_going
printed this way went from 4.3 MB to 231 KB (Standard) and 161 KB (Mobile). Not merged yet:
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.
A page whose content doesn't decode, or is damaged partway, is left as it is: written again from
what decoded, it would lose the rest.
- **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).
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
measured (forms nested deeper or drawn too many times, or content that doesn't decode or is
damaged partway, which may draw an image larger past the damage), 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. A
stencil `/Mask` has its own resolution, so the picture changes under it and it stays as it is.
+2 -2
View File
@@ -394,8 +394,8 @@ mod tests {
let mut budget = ImageBudget::with_work(0);
assert_eq!(merge_page(&mut doc.clone(), page, &mut Report::default(), &mut |_| true, &mut budget).unwrap(), 0);
assert_eq!(budget.refused(), 1);
// Reading each strip, and building the picture of 8 rows of 8 they make.
let cost = raw + 8 * (8 + 8) + 8 * 8;
// Reading each strip, inflating it, and building the picture of 8 rows of 8 they make.
let cost = (1 + pdfcraft_filters::FLATE_READ_WORK) * raw + 8 * (8 + 8) + 8 * 8;
let mut budget = ImageBudget::with_work(u64::MAX);
assert_eq!(merge_page(&mut doc.clone(), page, &mut Report::default(), &mut |_| true, &mut budget).unwrap(), 8);
assert_eq!(u64::MAX - budget.work_left(), cost);
+9 -8
View File
@@ -32,9 +32,10 @@ fn held_page_resources(doc: &Document, page: ObjRef) -> Option<(Dict, ObjRef)> {
}
/// The page content `contents` names, decoded against `budget` and joined. `None` when a stream
/// doesn't decode or the budget runs out: the content is not all known.
/// doesn't decode, is damaged partway or the budget runs out: the content is not all known.
pub(crate) fn content_bytes(doc: &Document, contents: &Object, budget: &mut DecodeBudget) -> Option<Vec<u8>> {
let pieces = budget.decode_contents(doc, contents).into_iter().collect::<Result<Vec<_>, _>>().ok()?;
let reads = budget.decode_contents_with_damage(doc, contents);
let pieces = reads.into_iter().map(|read| read.ok().filter(|(_, damaged)| !damaged).map(|(data, _)| data)).collect::<Option<Vec<_>>>()?;
Some(Pieces::join(&pieces).data().to_vec())
}
@@ -214,7 +215,7 @@ impl Walk<'_> {
self.complete = false;
return;
}
let Ok(data) = self.budget.decode(s) else {
let Ok((data, false)) = self.budget.decode_with_damage(doc, s, usize::MAX) else {
self.complete = false;
return;
};
@@ -245,9 +246,9 @@ fn remaps_device_spaces(doc: &Document, resources: &Dict) -> bool {
/// The effective resolution (ppi) of every image drawn by `pages`: the smallest over its uses.
///
/// If forms nest too deeply, are drawn too many times, or a page's content doesn't decode within
/// its budget, every image is given `INFINITY` (never resampled), since its largest use may be
/// among those missed.
/// If forms nest too deeply, are drawn too many times, or a page's or form's content doesn't
/// decode within its budget or is damaged partway, every image is given `INFINITY` (never
/// resampled), since its largest use may be among those missed.
pub fn effective_resolutions(doc: &Document, pages: &[ObjRef]) -> HashMap<ObjRef, f64> {
walk_pages(doc, pages).0
}
@@ -1699,7 +1700,7 @@ mod dimension_tests {
dict.set(b"BitsPerComponent".to_vec(), Object::Int(8));
dict.set(b"ColorSpace".to_vec(), Object::name("DeviceGray"));
let image = Stream::flate(dict, &samples);
let read = (image.raw.len() + samples.len()) as u64 + 256 * 256;
let read = (image.raw.len() + samples.len()) as u64 + pdfcraft_filters::FLATE_READ_WORK * image.raw.len() as u64 + 256 * 256;
let original = doc.add(Object::Stream(image.clone()));
let mut xobjects = Dict::new();
xobjects.set(b"I0".to_vec(), Object::Ref(original));
@@ -1791,7 +1792,7 @@ mod dimension_tests {
};
let mut doc = Document::new_empty();
let mask = image("DeviceGray");
let cost = (mask.raw.len() + noise.len()) as u64 + 256 * 256;
let cost = (mask.raw.len() + noise.len()) as u64 + pdfcraft_filters::FLATE_READ_WORK * mask.raw.len() as u64 + 256 * 256;
let masked = doc.add(Object::Stream(mask));
let mut with_mask = image("DeviceGray");
with_mask.dict.set(b"SMask".to_vec(), Object::Ref(masked));
+81
View File
@@ -3157,6 +3157,87 @@ fn images_that_do_not_tile_a_picture_are_left_alone() {
unmerged(&mut off, &Settings { merge_fragments: false, ..Settings::default() });
}
/// zlib data that reads as `readable` and is then damaged, with more of the stream after the
/// damage: a stored block, then a block of the reserved type (RFC 1951 §3.2.3), then `rest`.
fn damaged_flate(readable: &[u8], rest: &[u8]) -> Stream {
let len = u16::try_from(readable.len()).unwrap();
let mut raw = vec![0x78, 0x01, 0x00];
raw.extend_from_slice(&len.to_le_bytes());
raw.extend_from_slice(&(!len).to_le_bytes());
raw.extend_from_slice(readable);
raw.push(0x07);
raw.extend_from_slice(rest);
let mut dict = Dict::new();
dict.set(b"Filter".to_vec(), Object::name("FlateDecode"));
Stream::from_raw(dict, raw)
}
/// A page whose content is damaged partway isn't all known: its strips aren't merged, which would
/// write its content again without what follows the damage.
#[test]
fn strips_on_a_page_damaged_partway_are_left_as_they_are() {
let (mut doc, _) = printed_page(40, |_| false, |_, s| s);
let p = pdfcraft_annot::page_refs(&doc).unwrap()[0];
let bad = damaged_flate(b"0 g\n", b"q 1000 0 0 1 0 0 cm /R0 Do Q");
let damaged = doc.add(Object::Stream(bad.clone()));
let first = doc.get(p).as_dict().unwrap().get(b"Contents").cloned().unwrap();
let contents = Object::Array(vec![first, Object::Ref(damaged)]);
doc.update_dict(p, |d| d.set(b"Contents".to_vec(), contents.clone())).unwrap();
let r = optimize(&mut doc, &Settings::default()).unwrap();
assert_eq!((r.merged_images, r.fragments_merged), (0, 0), "{r:?}");
assert_eq!(doc.get(p).as_dict().unwrap().get(b"Contents"), Some(&contents));
assert_eq!(stream(&doc, damaged), bad);
}
/// An image may be drawn larger past the damage in a page's or a form's content, so no image is
/// resampled for the uses before it.
#[test]
fn content_damaged_partway_leaves_every_image_at_its_resolution() {
for in_form 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");
assert_eq!(effective_resolutions(&doc, &[p])[&img], 720.0);
let mut bad = damaged_flate(b"q 72 0 0 72 0 0 cm /Im Do Q\n", b"q 720 0 0 720 0 0 cm /Im Do Q");
let added = if in_form {
bad.dict.set(b"Subtype".to_vec(), Object::name("Form"));
bad.dict.set(b"BBox".to_vec(), Object::Array(vec![0.into(), 0.into(), 1.into(), 1.into()]));
bad.dict.set(b"Resources".to_vec(), Object::Dict(resources(xobjects(&[("Im", img)]))));
let f = doc.add(Object::Stream(bad));
let res = Object::Dict(resources(xobjects(&[("Im", img), ("F", f)])));
doc.update_dict(p, |d| d.set(b"Resources".to_vec(), res)).unwrap();
content(&mut doc, "/F Do")
} else {
doc.add(Object::Stream(bad))
};
let first = doc.get(p).as_dict().unwrap().get(b"Contents").cloned().unwrap();
doc.update_dict(p, |d| d.set(b"Contents".to_vec(), Object::Array(vec![first, Object::Ref(added)]))).unwrap();
// Not measured, or measured as never resampled: the image pass reads only what was measured.
let ppi = effective_resolutions(&doc, &[p]).get(&img).copied().unwrap_or(f64::INFINITY);
assert_eq!(ppi, f64::INFINITY, "in a form: {in_form}");
let r = optimize(&mut doc, &Settings::default()).unwrap();
assert_eq!(r.images_resampled, 0, "{r:?}");
}
}
/// One page damaged partway stops resampling for the whole document: another page drawing the same
/// image at its full resolution, whole, doesn't get it resampled either.
#[test]
fn content_damaged_partway_on_one_page_leaves_the_image_another_page_draws() {
let mut doc = Document::new_empty();
let img = image(&mut doc, 720, 720, 1, false, None);
let damaged = page(&mut doc, &[("Im", img)], "");
let bad = doc.add(Object::Stream(damaged_flate(b"0 g\n", b"q 720 0 0 720 0 0 cm /Im Do Q")));
doc.update_dict(damaged, |d| d.set(b"Contents".to_vec(), Object::Ref(bad))).unwrap();
let whole = page(&mut doc, &[("Im", img)], "q 72 0 0 72 0 0 cm /Im Do Q");
assert_eq!(effective_resolutions(&doc, &[whole])[&img], 720.0);
let ppi = effective_resolutions(&doc, &[damaged, whole]).get(&img).copied().unwrap_or(f64::INFINITY);
assert_eq!(ppi, f64::INFINITY);
let r = optimize(&mut doc, &Settings::default()).unwrap();
assert_eq!(r.images_resampled, 0, "{r:?}");
assert_eq!(doc.get(img).as_dict().and_then(|d| d.int(b"Width")), Some(720));
}
/// `levels` nested forms with their own resources, the innermost drawing `img` over the unit square.
fn nested_forms(doc: &mut Document, img: ObjRef, levels: usize) -> ObjRef {
let mut inner = form(doc, Some(Object::Dict(resources(xobjects(&[("Im", img)])))), "/Im Do");
+3 -2
View File
@@ -499,9 +499,10 @@ pub fn page_as_form(dst: &mut Document, src: &Document, page: usize) -> Result<(
let bbox = rect(b"CropBox").or_else(|| rect(b"MediaBox")).unwrap_or([0.0, 0.0, 612.0, 792.0]);
let (w, h) = (bbox[2] - bbox[0], bbox[3] - bbox[1]);
let rotate = d.get(b"Rotate").and_then(|r| src.resolve(r).as_int()).unwrap_or(0).rem_euclid(360);
// Content: the page's streams, decoded and joined.
// Content: the page's streams, decoded and joined. Of a stream damaged partway, the copy draws
// what decoded before the damage.
let content = match own.get(b"Contents") {
Some(c) => crate::prune::content_bytes(src, c).map_err(|e| OrganizeError::Invalid(format!("page {} content: {e}", page + 1)))?,
Some(c) => crate::prune::content_bytes(src, c).map_err(|e| OrganizeError::Invalid(format!("page {} content: {e}", page + 1)))?.0,
None => Vec::new(),
};
let mut copier = Copier::new(src, HashMap::new(), HashMap::new());
+83 -49
View File
@@ -40,12 +40,15 @@ enum Owner {
struct Pruner<'a> {
doc: &'a Document,
used: HashMap<XKey, HashSet<Vec<u8>>>,
/// Dictionaries whose drawn names can't be known for certain (undecodable content, nesting
/// past the depth limit, Type 3 glyphs drawing through them). They are left untouched:
/// pruning must never drop an XObject something still draws.
/// Dictionaries whose drawn names can't be known for certain (undecodable content, Type 3
/// glyphs drawing through them). They are left untouched: pruning must never drop an XObject
/// something still draws.
unsure: HashSet<XKey>,
/// An overlarge glyph-resource graph is not safe to prune at all.
glyph_budget_exhausted: bool,
/// Nor is a file with forms nested past [`MAX_FORM_DEPTH`]: what the forms there draw isn't
/// read, and they may draw it through resources shared with content that was.
too_deep: bool,
glyph_work_left: usize,
glyph_seen: HashSet<ObjRef>,
/// An indirect font's explicit resources have one owner regardless of which page uses it.
@@ -53,6 +56,9 @@ struct Pruner<'a> {
/// Forms already analysed, with the owner of the resources they drew against: drawing one
/// again records nothing new, and re-reading it on every `Do` is exponential in the nesting.
forms_seen: HashSet<(ObjRef, Owner)>,
/// Owners of resources that content not read whole drew against, whose every form was read
/// as drawn ([`Pruner::unread`]): once is enough.
partly_read: HashSet<Owner>,
}
impl Pruner<'_> {
@@ -185,7 +191,7 @@ impl Pruner<'_> {
return;
};
if depth > MAX_FORM_DEPTH {
self.unsure.insert(key);
self.too_deep = true;
return;
}
for op in pdfcraft_content::parse(data).ops {
@@ -194,54 +200,83 @@ impl Pruner<'_> {
}
let Some(name) = op.name(0) else { continue };
self.used.entry(key).or_default().insert(name.to_vec());
let Some(r) = xobjects.get(name).and_then(Object::as_ref) else { continue };
let Object::Stream(s) = &*self.doc.get(r) else { continue };
if s.dict.name(b"Subtype") != Some(b"Form") {
continue;
}
let (inner, inner_owner) = match s.dict.get(b"Resources") {
Some(res) => match res.as_ref() {
Some(rr) => match self.doc.get(rr).as_dict().cloned() {
Some(d) => (d, Owner::Resources(rr)),
None => continue,
},
None => match self.doc.resolve(res).as_dict().cloned() {
// The form carries its resources inline: filter them on the form itself.
Some(d) => (d, Owner::Resources(r)),
None => continue,
},
self.form(&xobjects, name, resources, owner, depth);
}
}
/// For content that can't be read whole (damaged partway, or not decoding at all): what it
/// draws is unknown, so its `/XObject` dictionary is kept whole, and every form there is read
/// as drawn, which also reads every form the part before any damage draws. A form whose
/// resources are shared keeps what it draws from them too.
fn unread(&mut self, resources: &Dict, owner: Owner, depth: u8) {
self.protect_type3_resources(resources, owner);
let Some((xobjects, key)) = self.xobjects(resources, owner) else { return };
self.unsure.insert(key);
if depth > MAX_FORM_DEPTH {
self.too_deep = true;
return;
}
if !self.partly_read.insert(owner) {
return;
}
for (name, _) in xobjects.iter() {
self.form(&xobjects, name, resources, owner, depth);
}
}
/// Record what the XObject `name` of `xobjects` draws when it is a form, drawn from content
/// with `resources`.
fn form(&mut self, xobjects: &Dict, name: &[u8], resources: &Dict, owner: Owner, depth: u8) {
let Some(r) = xobjects.get(name).and_then(Object::as_ref) else { return };
let Object::Stream(s) = &*self.doc.get(r) else { return };
// A `/Subtype` given by reference reads as no form here, as wherever the workspace tells
// forms from images (redaction, edit and Optimize among them): resolving it is a change
// across all of them.
if s.dict.name(b"Subtype") != Some(b"Form") {
return;
}
let (inner, inner_owner) = match s.dict.get(b"Resources") {
Some(res) => match res.as_ref() {
Some(rr) => match self.doc.get(rr).as_dict().cloned() {
Some(d) => (d, Owner::Resources(rr)),
None => return,
},
// A form without its own resources draws against the ones it was invoked with.
None => (resources.clone(), owner),
};
if !self.forms_seen.insert((r, inner_owner)) {
continue;
}
#[cfg(test)]
crate::work(1);
match s.decoded() {
Ok(data) => self.content(&data, &inner, inner_owner, depth + 1),
// What the form draws is unknown: keep everything it could reach.
Err(_) => {
self.protect_type3_resources(&inner, inner_owner);
self.distrust(&inner, inner_owner);
}
}
None => match self.doc.resolve(res).as_dict().cloned() {
// The form carries its resources inline: filter them on the form itself.
Some(d) => (d, Owner::Resources(r)),
None => return,
},
},
// A form without its own resources draws against the ones it was invoked with.
None => (resources.clone(), owner),
};
if !self.forms_seen.insert((r, inner_owner)) {
return;
}
#[cfg(test)]
crate::work(1);
match DecodeBudget::new(usize::MAX, 0).decode_with_damage(self.doc, s, usize::MAX) {
Ok((data, false)) => self.content(&data, &inner, inner_owner, depth + 1),
Ok((_, true)) | Err(_) => self.unread(&inner, inner_owner, depth + 1),
}
}
}
/// The page's content, concatenated (`/Contents` may be one stream or an array) with a space
/// between pieces as the renderer joins them, decoded against one page's [`DecodeBudget`]. An
/// between pieces as the renderer joins them, decoded against one page's [`DecodeBudget`], and
/// whether a stream is damaged partway (its part is then what decoded before the damage). An
/// error when a stream can't be decoded or the budget runs out: the page may draw names that
/// can't be seen.
pub(crate) fn content_bytes(doc: &Document, contents: &Object) -> Result<Vec<u8>, CosError> {
pub(crate) fn content_bytes(doc: &Document, contents: &Object) -> Result<(Vec<u8>, bool), CosError> {
let mut out = Vec::new();
for data in DecodeBudget::page().decode_contents(doc, contents) {
out.extend(data?);
let mut damaged = false;
for read in DecodeBudget::page().decode_contents_with_damage(doc, contents) {
let (data, partial) = read?;
damaged |= partial;
out.extend(data);
out.push(b' ');
}
Ok(out)
Ok((out, damaged))
}
/// The resources of a page (as `walk` reports them) with their owner.
@@ -313,10 +348,12 @@ pub(crate) fn prune_unused_xobjects(doc: &mut Document) -> Result<usize, Organiz
used: HashMap::new(),
unsure: HashSet::new(),
glyph_budget_exhausted: false,
too_deep: false,
glyph_work_left: MAX_GLYPH_RESOURCE_WORK,
glyph_seen: HashSet::new(),
glyph_fonts: HashSet::new(),
forms_seen: HashSet::new(),
partly_read: HashSet::new(),
};
for (page, attrs) in &pages {
let Some(res) = attrs.get(b"Resources") else { continue };
@@ -324,16 +361,13 @@ pub(crate) fn prune_unused_xobjects(doc: &mut Document) -> Result<usize, Organiz
let Some(pd) = pruner.doc.get(*page).as_dict().cloned() else { continue };
let Some(contents) = pd.get(b"Contents").cloned() else { continue };
match content_bytes(pruner.doc, &contents) {
Ok(data) if data.is_empty() => {}
Ok(data) => pruner.content(&data, &res_dict, owner, 0),
Err(_) => {
pruner.protect_type3_resources(&res_dict, owner);
pruner.distrust(&res_dict, owner);
}
Ok((data, false)) if data.is_empty() => {}
Ok((data, false)) => pruner.content(&data, &res_dict, owner, 0),
Ok((_, true)) | Err(_) => pruner.unread(&res_dict, owner, 0),
}
}
let Pruner { used, unsure, glyph_budget_exhausted, .. } = pruner;
if glyph_budget_exhausted {
let Pruner { used, unsure, glyph_budget_exhausted, too_deep, .. } = pruner;
if glyph_budget_exhausted || too_deep {
return Ok(0);
}
let mut removed = 0;
+256
View File
@@ -2628,6 +2628,262 @@ fn extract_keeps_images_an_undecodable_page_might_draw() {
assert!(names.iter().any(|n| n.as_slice() == b"ImB"), "an image the unreadable page may draw must stay");
}
/// zlib data that reads as `readable` and is then damaged, with more of the stream after the
/// damage: a stored block, then a block of the reserved type (RFC 1951 §3.2.3), then `rest`.
fn damaged_flate(readable: &[u8], rest: &[u8]) -> pdfcraft_cos::Stream {
let len = u16::try_from(readable.len()).unwrap();
let mut raw = vec![0x78, 0x01, 0x00];
raw.extend_from_slice(&len.to_le_bytes());
raw.extend_from_slice(&(!len).to_le_bytes());
raw.extend_from_slice(readable);
raw.push(0x07);
raw.extend_from_slice(rest);
let mut dict = Dict::new();
dict.set(b"Filter".to_vec(), Object::name("FlateDecode"));
pdfcraft_cos::Stream::from_raw(dict, raw)
}
/// A page or form damaged partway may draw images past the damage, which other readers may still
/// read: pruning keeps them, as it does for content that doesn't decode.
#[test]
fn extract_keeps_images_content_damaged_partway_might_draw() {
use pdfcraft_cos::ObjRef;
let mut page = doc_images_with(&raw("/ImA Do"), "");
page.set(ObjRef::new(6, 0), damaged_flate(b"/ImA Do\n", b"/ImB Do"));
let mut form = doc_images_with(&raw("/Fm Do"), "");
let mut fm = damaged_flate(b"/ImA Do\n", b"/ImB Do");
fm.dict.set(b"Subtype".to_vec(), Object::name("Form"));
fm.dict.set(b"BBox".to_vec(), Object::Array(vec![0.into(), 0.into(), 1.into(), 1.into()]));
let fm = form.add(fm);
let xobjects: Dict =
[(b"ImA".to_vec(), Object::Ref(ObjRef::new(8, 0))), (b"ImB".to_vec(), Object::Ref(ObjRef::new(9, 0))), (b"Fm".to_vec(), Object::Ref(fm))]
.into_iter()
.collect();
form.update_dict(ObjRef::new(7, 0), |d| d.set(b"XObject".to_vec(), Object::Dict(xobjects))).unwrap();
for (src, what) in [(page, "page"), (form, "form")] {
let part = full_roundtrip(&extract_pages(&src, &[0, 1]).unwrap());
let names = xobject_names(&part, 0);
assert!(names.iter().any(|n| n.as_slice() == b"ImB"), "{what}: an image drawn past the damage must stay: {names:?}");
}
}
/// Two pages: the first draws `/Fm` through resources of its own, `/Fm` draws `/Nested` through
/// resources of its own too, and `/Nested` draws `/ImA` through resources it shares with the second
/// page, which draws `/ImB` through them. The three streams are the first page's content, `/Fm`
/// and `/Nested`.
fn doc_shared_form_resources(page: pdfcraft_cos::Stream, fm: pdfcraft_cos::Stream, nested: pdfcraft_cos::Stream) -> Document {
use pdfcraft_cos::ObjRef;
let b: Vec<String> = vec![
"<< /Type /Catalog /Pages 2 0 R >>".into(),
"<< /Type /Pages /Kids [3 0 R 4 0 R] /Count 2 /MediaBox [0 0 200 200] >>".into(),
"<< /Type /Page /Parent 2 0 R /Contents 5 0 R /Resources << /XObject << /Fm 7 0 R >> >> >>".into(),
"<< /Type /Page /Parent 2 0 R /Contents 6 0 R /Resources 8 0 R >>".into(),
raw(""),
raw("/ImB Do"),
raw(""),
"<< /XObject << /ImA 9 0 R /ImB 10 0 R >> >>".into(),
image(1, 1, 1),
image(1, 1, 2000),
raw(""),
];
let mut doc = open(build(&b, "/Root 1 0 R"));
doc.set(ObjRef::new(5, 0), page);
let nested_res: Dict =
[(b"XObject".to_vec(), Object::Dict([(b"Nested".to_vec(), Object::Ref(ObjRef::new(11, 0)))].into_iter().collect()))].into_iter().collect();
for (num, mut form, resources) in [(7, fm, Object::Dict(nested_res)), (11, nested, Object::Ref(ObjRef::new(8, 0)))] {
form.dict.set(b"Subtype".to_vec(), Object::name("Form"));
form.dict.set(b"BBox".to_vec(), Object::Array(vec![0.into(), 0.into(), 1.into(), 1.into()]));
form.dict.set(b"Resources".to_vec(), resources);
doc.set(ObjRef::new(num, 0), form);
}
doc
}
/// Every form the resources of a page or form damaged partway name may be drawn, before the
/// damage or past it, so each is read: one whose resources another page shares keeps what it draws
/// from them. So is each one content that doesn't decode may draw.
#[test]
fn extract_keeps_images_forms_drawn_around_damage_draw_through_shared_resources() {
let whole = |content: &[u8]| pdfcraft_cos::Stream::from_raw(Dict::new(), content.to_vec());
let undecodable = |content: &[u8]| {
let mut s = whole(content);
s.dict.set(b"Filter".to_vec(), Object::name("NoSuchFilter"));
s
};
let cases = [
("page, before the damage", damaged_flate(b"/Fm Do\n", b"0 g"), whole(b"/Nested Do")),
("page, past the damage", damaged_flate(b"0 g\n", b"/Fm Do"), whole(b"/Nested Do")),
("page that doesn't decode", undecodable(b"/Fm Do"), whole(b"/Nested Do")),
("form, before the damage", whole(b"/Fm Do"), damaged_flate(b"/Nested Do\n", b"0 g")),
("form, past the damage", whole(b"/Fm Do"), damaged_flate(b"0 g\n", b"/Nested Do")),
("form that doesn't decode", whole(b"/Fm Do"), undecodable(b"/Nested Do")),
];
for (what, page, fm) in cases {
let part = full_roundtrip(&extract_pages(&doc_shared_form_resources(page, fm, whole(b"/ImA Do")), &[0, 1]).unwrap());
let names = xobject_names(&part, 1);
assert!(names.iter().any(|n| n.as_slice() == b"ImA"), "{what}: {names:?}");
assert!(names.iter().any(|n| n.as_slice() == b"ImB"), "{what}: {names:?}");
}
// What nothing draws still goes.
let src = doc_shared_form_resources(whole(b"0 g"), whole(b"/Nested Do"), whole(b"/ImA Do"));
let part = full_roundtrip(&extract_pages(&src, &[0, 1]).unwrap());
assert_eq!(xobject_names(&part, 1), [b"ImB".to_vec()]);
}
/// Forms are read 8 deep (`prune.rs`'s `MAX_FORM_DEPTH`). A damaged form that deep still has
/// every form it names read as drawn: here `/Nested`, which draws through resources another page
/// shares. Read 9 deep, it leaves the file unpruned, so what it draws from them stays.
#[test]
fn a_damaged_form_at_the_depth_limit_has_its_forms_read() {
use pdfcraft_cos::ObjRef;
let whole = |content: &[u8]| pdfcraft_cos::Stream::from_raw(Dict::new(), content.to_vec());
let mut src = doc_shared_form_resources(whole(b"/C Do"), damaged_flate(b"0 g\n", b"/Nested Do"), whole(b"/ImA Do"));
// Seven forms between the page and `/Fm`, each drawing the next as `/C`: `/Fm` is 8 deep.
let mut next = ObjRef::new(7, 0);
for _ in 1..8 {
let mut form = whole(b"/C Do");
form.dict.set(b"Subtype".to_vec(), Object::name("Form"));
form.dict.set(b"BBox".to_vec(), Object::Array(vec![0.into(), 0.into(), 1.into(), 1.into()]));
let names: Dict = [(b"C".to_vec(), Object::Ref(next))].into_iter().collect();
form.dict.set(b"Resources".to_vec(), Object::Dict([(b"XObject".to_vec(), Object::Dict(names))].into_iter().collect()));
next = src.add(Object::Stream(form));
}
let names: Dict = [(b"C".to_vec(), Object::Ref(next))].into_iter().collect();
src.update_dict(ObjRef::new(3, 0), |p| {
p.set(b"Resources".to_vec(), Object::Dict([(b"XObject".to_vec(), Object::Dict(names))].into_iter().collect()))
})
.unwrap();
let part = full_roundtrip(&extract_pages(&src, &[0, 1]).unwrap());
let names = xobject_names(&part, 1);
assert!(names.iter().any(|n| n.as_slice() == b"ImA"), "{names:?}");
}
/// Past the depth limit a form isn't read, nor what the forms it draws draw: one of those may draw
/// through resources another page shares, and keep images there that page doesn't draw, so nothing
/// is pruned. Here `/Fm` is 9 deep, whole or damaged partway, and `/Nested`, which it draws, draws
/// `/ImA` through the resources the second page draws `/ImB` through.
#[test]
fn nothing_is_pruned_past_the_depth_limit() {
use pdfcraft_cos::ObjRef;
let whole = |content: &[u8]| pdfcraft_cos::Stream::from_raw(Dict::new(), content.to_vec());
for (what, fm) in [("whole", whole(b"/Nested Do")), ("damaged", damaged_flate(b"0 g\n", b"/Nested Do"))] {
let mut src = doc_shared_form_resources(whole(b"/C Do"), fm, whole(b"/ImA Do"));
// Eight forms between the page and `/Fm`, each drawing the next as `/C`: `/Fm` is 9 deep.
let mut next = ObjRef::new(7, 0);
for _ in 0..8 {
let mut form = whole(b"/C Do");
form.dict.set(b"Subtype".to_vec(), Object::name("Form"));
form.dict.set(b"BBox".to_vec(), Object::Array(vec![0.into(), 0.into(), 1.into(), 1.into()]));
let names: Dict = [(b"C".to_vec(), Object::Ref(next))].into_iter().collect();
form.dict.set(b"Resources".to_vec(), Object::Dict([(b"XObject".to_vec(), Object::Dict(names))].into_iter().collect()));
next = src.add(Object::Stream(form));
}
let names: Dict = [(b"C".to_vec(), Object::Ref(next))].into_iter().collect();
src.update_dict(ObjRef::new(3, 0), |p| {
p.set(b"Resources".to_vec(), Object::Dict([(b"XObject".to_vec(), Object::Dict(names))].into_iter().collect()))
})
.unwrap();
let part = full_roundtrip(&extract_pages(&src, &[0, 1]).unwrap());
let names = xobject_names(&part, 1);
assert!(names.iter().any(|n| n.as_slice() == b"ImA"), "{what}: {names:?}");
}
}
/// Down to the depth limit pruning goes on: under a page whole or damaged partway, a form 8 deep,
/// whole or damaged, is read, and the image nothing draws, `/ImA`, still goes from the resources
/// the second page draws `/ImB` through.
#[test]
fn pruning_goes_on_down_to_the_depth_limit() {
use pdfcraft_cos::ObjRef;
let whole = |content: &[u8]| pdfcraft_cos::Stream::from_raw(Dict::new(), content.to_vec());
let cases = [
("whole", whole(b"/C Do"), whole(b"0 g")),
("damaged form", whole(b"/C Do"), damaged_flate(b"0 g\n", b"0 g")),
("damaged page", damaged_flate(b"/C Do\n", b"0 g"), whole(b"0 g")),
];
for (what, page, fm) in cases {
let mut src = doc_shared_form_resources(page, fm, whole(b""));
// `/Fm` names an image, not `/Nested`: nothing is read 9 deep.
let image: Dict = [(b"Img".to_vec(), Object::Ref(ObjRef::new(9, 0)))].into_iter().collect();
let resources = Object::Dict([(b"XObject".to_vec(), Object::Dict(image))].into_iter().collect());
src.update_dict(ObjRef::new(7, 0), |f| f.set(b"Resources".to_vec(), resources)).unwrap();
// Seven forms between the page and `/Fm`, each drawing the next as `/C`: `/Fm` is 8 deep.
let mut next = ObjRef::new(7, 0);
for _ in 1..8 {
let mut form = whole(b"/C Do");
form.dict.set(b"Subtype".to_vec(), Object::name("Form"));
form.dict.set(b"BBox".to_vec(), Object::Array(vec![0.into(), 0.into(), 1.into(), 1.into()]));
let names: Dict = [(b"C".to_vec(), Object::Ref(next))].into_iter().collect();
form.dict.set(b"Resources".to_vec(), Object::Dict([(b"XObject".to_vec(), Object::Dict(names))].into_iter().collect()));
next = src.add(Object::Stream(form));
}
let names: Dict = [(b"C".to_vec(), Object::Ref(next))].into_iter().collect();
src.update_dict(ObjRef::new(3, 0), |p| {
p.set(b"Resources".to_vec(), Object::Dict([(b"XObject".to_vec(), Object::Dict(names))].into_iter().collect()))
})
.unwrap();
let part = full_roundtrip(&extract_pages(&src, &[0, 1]).unwrap());
assert_eq!(xobject_names(&part, 1), [b"ImB".to_vec()], "{what}");
}
}
/// A chain of forms nested far past the depth limit, whole or each damaged partway, is read only
/// down to it: the walk's depth stays bounded however long the chain is, and the run ends without
/// an error, having pruned nothing.
#[test]
fn a_long_chain_of_forms_is_read_only_to_the_depth_limit() {
use pdfcraft_cos::ObjRef;
let whole = |content: &[u8]| pdfcraft_cos::Stream::from_raw(Dict::new(), content.to_vec());
let xobjects = |names: Dict| Object::Dict([(b"XObject".to_vec(), Object::Dict(names))].into_iter().collect());
for damaged in [false, true] {
let mut doc = doc_shared_form_resources(whole(b"/C Do"), whole(b""), whole(b""));
let mut names = Dict::new();
for _ in 0..100_000 {
let mut form = if damaged { damaged_flate(b"", b"/C Do") } else { whole(b"/C Do") };
form.dict.set(b"Subtype".to_vec(), Object::name("Form"));
form.dict.set(b"BBox".to_vec(), Object::Array(vec![0.into(), 0.into(), 1.into(), 1.into()]));
form.dict.set(b"Resources".to_vec(), xobjects(names));
let next = doc.add(Object::Stream(form));
names = [(b"C".to_vec(), Object::Ref(next))].into_iter().collect();
}
doc.update_dict(ObjRef::new(3, 0), |p| p.set(b"Resources".to_vec(), xobjects(names))).unwrap();
assert!(matches!(crate::prune::prune_unused_xobjects(&mut doc), Ok(0)), "damaged: {damaged}");
}
}
/// A form whose `/DecodeParms` is given by reference is read through it: the image it draws is
/// kept, not lost to content read with the predictor's tag bytes left in it.
#[test]
fn extract_keeps_images_a_form_with_parameters_by_reference_draws() {
use pdfcraft_cos::ObjRef;
let content = b"q 10 0 0 10 0 0 cm /ImB Do Q";
// PNG Up, one column: each byte a row of its own, tagged 2.
let mut rows = Vec::new();
let mut above = 0u8;
for &b in content {
rows.extend([2, b.wrapping_sub(above)]);
above = b;
}
let mut src = doc_images_with(&raw("/Fm Do"), "");
let parms = src.add(Object::Dict([(b"Predictor".to_vec(), Object::Int(12))].into_iter().collect::<Dict>()));
let mut fm = pdfcraft_cos::Stream::flate(Dict::new(), &rows);
fm.dict.set(b"DecodeParms".to_vec(), Object::Ref(parms));
fm.dict.set(b"Subtype".to_vec(), Object::name("Form"));
fm.dict.set(b"BBox".to_vec(), Object::Array(vec![0.into(), 0.into(), 1.into(), 1.into()]));
let fm = src.add(fm);
let xobjects: Dict =
[(b"ImA".to_vec(), Object::Ref(ObjRef::new(8, 0))), (b"ImB".to_vec(), Object::Ref(ObjRef::new(9, 0))), (b"Fm".to_vec(), Object::Ref(fm))]
.into_iter()
.collect();
src.update_dict(ObjRef::new(7, 0), |d| d.set(b"XObject".to_vec(), Object::Dict(xobjects))).unwrap();
let part = full_roundtrip(&extract_pages(&src, &[1]).unwrap());
let names = xobject_names(&part, 0);
assert!(names.iter().any(|n| n.as_slice() == b"ImB"), "{names:?}");
assert!(!names.iter().any(|n| n.as_slice() == b"ImA"), "what the part doesn't draw still goes: {names:?}");
}
#[test]
fn extract_keeps_images_type3_glyphs_may_draw() {
// A Type 3 font without its own /Resources draws through the page's: its glyphs could `Do`.
+1
View File
@@ -20,6 +20,7 @@ pdfcraft-annot = { workspace = true }
pdfcraft-xfa = { workspace = true }
# CCITT Group 4 and JBIG2 encoding for cleared one-bit images.
pdfcraft-filters = { workspace = true }
regex = { workspace = true }
thiserror = { workspace = true }
sha2 = "0.11"
+29 -8
View File
@@ -361,7 +361,7 @@ fn process_from(doc: &mut Document, scope: &mut Scope<'_>, streams: &[Vec<u8>],
processed.push((done.ops, done.changed));
}
if scope.mode == Mode::Apply {
clean_replacements(doc, resources, &original, &mut processed, scope.report);
clean_replacements(doc, resources, &original, &walk.clipped, &mut processed, scope.report);
}
walk.out.streams = processed.into_iter().zip(comment_edges).map(|((ops, changed), edges)| changed.then(|| piece_bytes(&ops, edges))).collect();
walk.out
@@ -424,6 +424,9 @@ struct Walk {
path: Vec<Op>,
path_box: Option<[f64; 4]>,
clip: bool,
/// Painting operators written again under a clip that cuts the regions out: unchanged as
/// operators, but what they paint is no longer all there.
clipped: HashSet<usize>,
out: Output,
}
@@ -442,6 +445,7 @@ impl Walk {
path: Vec::new(),
path_box: None,
clip: false,
clipped: HashSet::new(),
out: Output::default(),
}
}
@@ -474,7 +478,7 @@ impl Walk {
}
b"Tj" | b"TJ" | b"'" | b"\"" => self.show_text(scope, op, piece),
b"BI" => Self::inline_image(&self.gs, scope, &mut self.out, op, piece),
b"sh" if scope.mode == Mode::Apply => Self::shading(&self.gs, scope, op, piece),
b"sh" if scope.mode == Mode::Apply => Self::shading(&self.gs, scope, &mut self.clipped, op, piece),
b"Do" => self.draw_xobject(doc, scope, resources, op, piece),
// `/Name scn` selects a pattern as the fill colour; numbers select a plain colour
// and clear it. `cs` with a space other than /Pattern clears it too.
@@ -717,10 +721,12 @@ impl Walk {
None
}
/// A shading fills the current clip: the regions are clipped out.
fn shading(gs: &Gs, scope: &Scope<'_>, op: Op, piece: &mut Piece) -> Option<Op> {
let Some(c) = clip_out(scope.rects, &gs.ctm, [-1e6, -1e6, 1e6, 1e6]) else { return Some(op) };
/// A shading fills the current clip: the regions are clipped out. Removing hidden content has
/// no regions, so the shading and its name stay as they are.
fn shading(gs: &Gs, scope: &Scope<'_>, clipped: &mut HashSet<usize>, op: Op, piece: &mut Piece) -> Option<Op> {
let Some(c) = clip_out(scope.rects, &gs.ctm, [-1e6, -1e6, 1e6, 1e6]).filter(|c| !c.is_empty()) else { return Some(op) };
piece.changed = true;
clipped.insert(op.span.start);
piece.ops.push(Op::new("q", vec![]));
piece.ops.extend(c);
piece.ops.push(op);
@@ -739,7 +745,16 @@ impl Walk {
}
}
fn clean_replacements(doc: &Document, resources: &Dict, original: &[Op], processed: &mut [(Vec<Op>, bool)], report: &mut Report) {
/// Strip `/ActualText` (and `/Alt`, `/E`, `/T`) from the marked content around anything redaction
/// removed, changed or `clipped`: the words they name may be among what is gone.
fn clean_replacements(
doc: &Document,
resources: &Dict,
original: &[Op],
clipped: &HashSet<usize>,
processed: &mut [(Vec<Op>, bool)],
report: &mut Report,
) {
let originals: HashMap<usize, &Op> = original.iter().map(|op| (op.span.start, op)).collect();
let unchanged: HashSet<usize> =
processed.iter().flat_map(|(ops, _)| ops).filter(|op| originals.get(&op.span.start) == Some(op)).map(|op| op.span.start).collect();
@@ -751,7 +766,13 @@ fn clean_replacements(doc: &Document, resources: &Dict, original: &[Op], process
b"EMC" => {
stack.pop();
}
_ if !unchanged.contains(&op.span.start) => affected.extend(stack.iter().copied()),
// A scope joins `affected` only with every scope around it, so once the innermost one
// is in, the rest are too: deep nesting over many changed ops stays linear.
_ if (!unchanged.contains(&op.span.start) || clipped.contains(&op.span.start))
&& stack.last().is_some_and(|top| !affected.contains(top)) =>
{
affected.extend(stack.iter().copied())
}
_ => {}
}
}
@@ -979,7 +1000,7 @@ fn xobject(
}
// Strict, like page content: a Form read only in part counts as undecodable.
let data = if scope.budget.enter_form() {
scope.budget.decode_strict(s)
scope.budget.decode_strict(doc, s)
} else {
Err(CosError::Filter(format!("the page draws more than {MAX_PAGE_FORMS} form XObjects")))
};
+8 -2
View File
@@ -32,6 +32,7 @@ mod tests;
mod tests_verify;
pub(crate) mod type3;
pub(crate) mod type3_tables;
pub mod user_regex;
pub mod verify;
use interp::{Mode, Scope, process};
@@ -290,7 +291,7 @@ pub(crate) fn page_streams_within(
match &*doc.resolve(o) {
// Strict: a tolerant decode keeps what precedes corruption and drops the rest, which
// still draws in viewers that read further; anything not read can't be cleaned.
Object::Stream(s) => data.push(budget.decode_strict(s).map_err(|_| RedactError::Unreadable(index + 1))?),
Object::Stream(s) => data.push(budget.decode_strict(doc, s).map_err(|_| RedactError::Unreadable(index + 1))?),
Object::Null => data.push(Vec::new()),
_ => return Err(RedactError::Unreadable(index + 1)),
}
@@ -820,7 +821,12 @@ fn redact_page_content(
// longer draws so the removed image or form bytes cannot survive in the saved file.
let page_content: Vec<Vec<u8>> = new_list
.iter()
.map(|o| match &*doc.resolve(o) {
.zip(&list)
.zip(&data)
.map(|((now, was), read)| match &*doc.resolve(now) {
// Left as it was: what was read above, with its parameters by reference.
_ if now == was => read.clone(),
// Written above by `Stream::flate`, which leaves no `/DecodeParms`.
Object::Stream(s) => s.decoded().unwrap_or_default(),
_ => Vec::new(),
})
+147
View File
@@ -61,6 +61,68 @@ fn reopen(doc: &Document) -> Document {
Document::open(Arc::new(write_incremental(doc, &SaveOptions::default()).unwrap())).unwrap()
}
/// A word drawn as outlines names itself in /ActualText. A mark over part of it removes the
/// outlines (a shading painting them is clipped instead), and the name, which would still read the
/// whole word, goes with them. A word the mark misses keeps its own.
#[test]
fn redacted_paint_loses_the_actual_text_that_names_it() {
let mut doc = one_page(
b"/Span <</ActualText (SECRET)>> BDC 100 100 m 160 100 l 160 120 l 100 120 l h f EMC /Span <</ActualText (KEPT)>> BDC 100 200 60 20 re f EMC",
"",
vec![],
);
mark(&mut doc, 0, &[[90.0, 95.0, 130.0, 125.0]], "");
let r = apply(&mut doc, None).unwrap();
assert_eq!((r.paths_clipped, r.paths_removed), (0, 1));
let c = content(&doc, 0);
assert!(!c.contains("SECRET") && c.contains("KEPT"), "{c}");
let shading =
"<< /ShadingType 2 /ColorSpace /DeviceGray /Coords [0 0 300 0] /Function << /FunctionType 2 /Domain [0 1] /C0 [0] /C1 [1] /N 1 >> >>";
let mut doc = one_page(b"/Span <</ActualText (SHADED)>> BDC /Sh0 sh EMC", "/Shading << /Sh0 7 0 R >>", vec![shading.as_bytes().to_vec()]);
mark(&mut doc, 0, &[[90.0, 95.0, 130.0, 125.0]], "");
apply(&mut doc, None).unwrap();
let c = content(&doc, 0);
// Drawn after a clip that cuts the region out.
assert!(!c.contains("SHADED") && c.find("W*").zip(c.find(" sh")).is_some_and(|(w, s)| w < s), "{c}");
// A path that clips as it paints.
let mut doc = one_page(b"q /Span <</ActualText (CLIPS)>> BDC 100 100 m 160 100 l 160 120 l 100 120 l h W f EMC Q", "", vec![]);
mark(&mut doc, 0, &[[90.0, 95.0, 130.0, 125.0]], "");
assert_eq!(apply(&mut doc, None).unwrap().paths_removed, 1);
let c = content(&doc, 0);
assert!(!c.contains("CLIPS"), "{c}");
}
/// Nested names around redacted paint all go, the innermost too, whichever scope was cut first.
#[test]
fn redacted_paint_loses_every_name_around_it() {
let mut doc = one_page(
b"/Span <</ActualText (OUTER)>> BDC 100 100 m 160 100 l 160 120 l 100 120 l h f /Span <</ActualText (INNER)>> BDC 100 130 m 160 130 l 160 150 l 100 150 l h f EMC EMC",
"",
vec![],
);
mark(&mut doc, 0, &[[90.0, 95.0, 130.0, 155.0]], "");
assert_eq!(apply(&mut doc, None).unwrap().paths_removed, 2);
let c = content(&doc, 0);
assert!(!c.contains("OUTER") && !c.contains("INNER"), "{c}");
}
/// Removing hidden text clips nothing, so a shading on the same page keeps the words that name it.
#[test]
fn removing_hidden_text_keeps_the_alt_text_of_a_shading() {
let shading =
"<< /ShadingType 2 /ColorSpace /DeviceGray /Coords [0 0 300 0] /Function << /FunctionType 2 /Domain [0 1] /C0 [0] /C1 [1] /N 1 >> >>";
let mut doc = one_page(
b"BT /F1 10 Tf 3 Tr 10 200 Td (SECRET) Tj ET /Figure <</Alt (chart)>> BDC /Sh0 sh EMC",
"/Shading << /Sh0 7 0 R >>",
vec![shading.as_bytes().to_vec()],
);
sanitize::remove_hidden(&mut doc, &[sanitize::Hidden::HiddenText]).unwrap();
let c = content(&doc, 0);
assert!(!c.contains("SECRET") && c.contains("(chart)"), "{c}");
}
#[test]
fn glyphs_under_a_mark_go_and_the_rest_stays_put() {
// "AB1234CD" from x = 10 at 10 pt: each glyph 5 pt wide; 1234 spans x 20–40.
@@ -81,6 +143,91 @@ fn glyphs_under_a_mark_go_and_the_rest_stays_put() {
assert!(!content(&doc, 0).contains("1234"));
}
/// `content` behind a PNG Up predictor whose `/DecodeParms` is an indirect object added to `doc`,
/// in a stream with `dict`'s entries too.
fn predicted(doc: &mut Document, dict: pdfcraft_cos::Dict, content: &[u8]) -> pdfcraft_cos::Stream {
use pdfcraft_cos::{Dict, Object, Stream};
// One column: each byte a row of its own, tagged 2.
let mut rows = Vec::new();
let mut above = 0u8;
for &b in content {
rows.extend([2, b.wrapping_sub(above)]);
above = b;
}
let parms = doc.add(Object::Dict([(b"Predictor".to_vec(), Object::Int(12))].into_iter().collect::<Dict>()));
let mut s = Stream::flate(Dict::new(), &rows);
for (k, v) in dict.iter() {
s.dict.set(k.to_vec(), v.clone());
}
s.dict.set(b"DecodeParms".to_vec(), Object::Ref(parms));
s
}
/// Content whose `/DecodeParms` is given by reference is read through the reference, on the page
/// and in a form: the text under a mark goes. Read with the predictor's tag bytes left in, no glyph
/// was found under the mark, and the redaction left the text in the file and said it was done.
#[test]
fn content_with_parameters_given_by_reference_is_redacted() {
use pdfcraft_cos::{Dict, ObjRef, Object};
let secret = b"BT /F1 10 Tf 10 100 Td (SECRET) Tj ET";
let marked = [[5.0, 90.0, 120.0, 115.0]];
let mut page = one_page(b"", "", vec![]);
let s = predicted(&mut page, Dict::new(), secret);
page.set(ObjRef::new(4, 0), s);
// The parameters take object 7 and the form 8.
let mut form = one_page(b"/Fm Do", "/XObject << /Fm 8 0 R >>", vec![]);
let mut dict = Dict::new();
dict.set(b"Subtype".to_vec(), Object::name("Form"));
dict.set(b"BBox".to_vec(), Object::Array([0, 0, 300, 300].into_iter().map(Object::Int).collect()));
dict.set(
b"Resources".to_vec(),
Object::Dict(
[(b"Font".to_vec(), Object::Dict([(b"F1".to_vec(), Object::Ref(ObjRef::new(5, 0)))].into_iter().collect()))].into_iter().collect(),
),
);
let s = predicted(&mut form, dict, secret);
form.set(ObjRef::new(8, 0), s);
for (mut doc, what) in [(page, "page"), (form, "form")] {
assert_eq!(under(&mut doc, 0, &marked), 6, "{what}");
mark(&mut doc, 0, &marked, "");
let r = apply(&mut doc, None).unwrap();
assert_eq!((r.marks, r.glyphs), (1, 6), "{what}");
let mut saved = reopen(&doc);
assert_eq!(under(&mut saved, 0, &marked), 0, "{what}");
// Nor is the text left in a stream the page no longer draws, read with its parameters.
for (r, o) in saved.scan_objects() {
let Object::Stream(s) = &*o else { continue };
let data = pdfcraft_cos::DecodeBudget::new(usize::MAX, 0).decode_with_damage(&saved, s, usize::MAX).map(|(d, _)| d).unwrap_or_default();
assert!(!data.windows(6).any(|w| w == b"SECRET"), "{what}: {r:?}");
}
}
}
/// An image removed under a mark stays in the page's resources while another of its content
/// streams, with `/DecodeParms` given by reference, still draws it. Read without the parameters,
/// that stream seemed not to draw it, and the page lost the image there.
#[test]
fn an_image_drawn_again_in_content_with_parameters_by_reference_stays() {
use pdfcraft_cos::{Dict, ObjRef, Object};
let img = stream("/Type /XObject /Subtype /Image /Width 4 /Height 1 /ColorSpace /DeviceGray /BitsPerComponent 8", [255, 255, 255, 255]);
let mut doc = one_page(b"q 10 0 0 10 10 10 cm /Im1 Do Q", "/XObject << /Im1 7 0 R >>", vec![img]);
let again = predicted(&mut doc, Dict::new(), b"q 10 0 0 10 200 200 cm /Im1 Do Q");
let again = doc.add(Object::Stream(again));
doc.update_dict(ObjRef::new(3, 0), |d| d.set(b"Contents".to_vec(), Object::Array(vec![Object::Ref(ObjRef::new(4, 0)), Object::Ref(again)])))
.unwrap();
mark(&mut doc, 0, &[[5.0, 5.0, 25.0, 25.0]], "");
let r = apply(&mut doc, None).unwrap();
assert_eq!(r.images_removed, 1, "{r:?}");
let doc = reopen(&doc);
assert!(content(&doc, 0).contains("200 200 cm /Im1 Do"), "{}", content(&doc, 0));
let p = pdfcraft_model::pages(&doc).swap_remove(0);
let res = doc.resolve(p.dict.get(b"Resources").unwrap()).as_dict().cloned().unwrap();
let xo = doc.resolve(res.get(b"XObject").unwrap()).as_dict().cloned().unwrap();
// The save numbers objects afresh: the image is told by what it is.
let Some(Object::Stream(image)) = xo.reference(b"Im1").map(|r| (*doc.get(r)).clone()) else { panic!("no /Im1: {xo:?}") };
assert_eq!((image.dict.name(b"Subtype"), image.decoded().ok()), (Some(&b"Image"[..]), Some(vec![255; 4])));
}
/// #2130: a font with no /Widths is drawn with its embedded program's advances. Measured with a
/// guess from its name instead (Courier's 600 units for "Mono"), the end of the line seemed to
/// lie past a mark that covers all of it on screen, and was kept.
+39
View File
@@ -332,6 +332,45 @@ fn a_survivor_in_an_xfa_packet_is_found() {
assert!(!proof.passed(), "{}", proof.to_text());
}
#[test]
fn a_survivor_behind_parameters_given_by_reference_is_found() {
// Object 7 holds the text behind Flate and a PNG predictor whose `/DecodeParms` is object 8,
// a reference. Read without them, its rows keep their tag bytes, which split the text; the
// sweep reads them as redaction does, and reports the copy.
let text = format!("note: {SECRET} xx");
let rows: Vec<u8> = text.as_bytes().chunks(4).flat_map(|row| std::iter::once(0).chain(row.iter().copied())).collect();
let packed = stream("/Filter /FlateDecode /DecodeParms 8 0 R", Stream::flate(Dict::new(), &rows).raw.as_ref());
let parms = b"<< /Predictor 12 /Columns 4 >>".to_vec();
let doc = marked(Spec { extra: vec![packed, parms], ..Spec::default() });
let snap = Snapshot::capture(&doc, None).unwrap();
let proof = snap.prove_saved(doc.bytes(), None, &ProofOptions::default());
let s = surface(&proof, Surface::DecodedStreams);
assert_eq!(s.verdict, Verdict::Survivor, "{}", proof.to_text());
assert!(s.locations.iter().any(|l| l == "object 7 (decoded)"), "{:?}", s.locations);
assert!(!proof.passed(), "{}", proof.to_text());
}
#[test]
fn a_unicode_map_behind_parameters_given_by_reference_is_read_alike() {
// The font's /ToUnicode (object 7) reads codes A..H as "SECRETVA", behind Flate and a PNG
// predictor whose `/DecodeParms` is object 8, a reference. The page draws the codes twice,
// once under the mark. Redaction takes the removed text from that map, and the proof the page
// text it allows for: read by one and not the other, the copy that stays counted as a
// survivor of a sound redaction.
let cmap = b"/CIDInit /ProcSet findresource begin\n12 dict begin\nbegincmap\n/CMapName /Test def\n1 begincodespacerange\n<00> <FF>\nendcodespacerange\n8 beginbfchar\n<41> <0053>\n<42> <0045>\n<43> <0043>\n<44> <0052>\n<45> <0045>\n<46> <0054>\n<47> <0056>\n<48> <0041>\nendbfchar\nendcmap\nCMapName currentdict /CMap defineresource pop\nend\nend\n";
let mut data = cmap.to_vec();
data.resize(data.len().next_multiple_of(4), b' ');
let rows: Vec<u8> = data.chunks(4).flat_map(|row| std::iter::once(0).chain(row.iter().copied())).collect();
let to_unicode = stream("/Filter /FlateDecode /DecodeParms 8 0 R", Stream::flate(Dict::new(), &rows).raw.as_ref());
let parms = b"<< /Predictor 12 /Columns 4 >>".to_vec();
let content = b"BT /F1 10 Tf 10 200 Td (ABCDEFGH) Tj ET BT /F1 10 Tf 10 100 Td (ABCDEFGH) Tj ET";
let mut doc = marked_content(content, Spec { extra: vec![to_unicode, parms], ..Spec::default() });
doc.update_dict(ObjRef::new(5, 0), |font| font.set(b"ToUnicode".to_vec(), Object::Ref(ObjRef::new(7, 0)))).unwrap();
let (result, proof) = run(&mut doc);
assert!(result.is_ok(), "{result:?}");
assert!(proof.passed(), "{}", proof.to_text());
}
#[test]
fn a_survivor_in_an_unused_object_is_found() {
// Object 7 is reachable from nothing: no catalog entry, no page resource. A reader that
+235
View File
@@ -0,0 +1,235 @@
//! Caller-supplied regular expressions for Search & Redact (`redact_mark regex`).
//!
//! The expression is untrusted input. It runs on the `regex` crate, which matches in time
//! linear in the text (no backtracking, no look-around or back-references), and is compiled
//! under hard limits on source length, nesting and compiled size, so a hostile expression is
//! refused with an error instead of exhausting time or memory. An optional [`Validator`]
//! keeps a match only when its checksum holds.
use std::ops::Range;
use regex::RegexBuilder;
use thiserror::Error;
/// Longest expression accepted, in bytes.
pub const MAX_REGEX_LEN: usize = 1024;
/// Most matches accepted for one page; one more makes [`UserRegex::find`] fail, so a page is never
/// marked only in part.
pub const MAX_MATCHES_PER_TEXT: usize = 10_000;
/// Cap on the compiled program and on the lazy-DFA cache, in bytes.
const SIZE_LIMIT: usize = 1 << 20;
/// Cap on parenthesis nesting.
const NEST_LIMIT: u32 = 32;
#[derive(Debug, Error, PartialEq, Eq)]
pub enum RegexError {
#[error("regex is empty")]
Empty,
#[error("regex is {0} bytes long; at most {MAX_REGEX_LEN} are allowed")]
TooLong(usize),
#[error("invalid or too complex regex: {0}")]
Invalid(String),
#[error("regex matches the empty string, so it would mark nothing useful; require at least one character")]
MatchesEmpty,
#[error("regex has more than {MAX_MATCHES_PER_TEXT} matches on one page; narrow it so that every match can be marked")]
TooManyMatches,
}
/// Checksum a match must pass to be kept.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Validator {
/// Luhn (ISO/IEC 7812): digits only, spaces and hyphens ignored.
Luhn,
/// ISO 7064 MOD 97-10: letters count as 10..35 and the number mod 97 must be 1. Letters and
/// digits only, spaces and hyphens ignored.
Mod97,
/// IBAN check (ISO 13616): the first four characters move to the end, then MOD 97-10.
Iban,
}
/// Ids accepted for `validate`.
pub const VALIDATORS: [Validator; 3] = [Validator::Luhn, Validator::Mod97, Validator::Iban];
impl Validator {
pub fn id(self) -> &'static str {
match self {
Validator::Luhn => "luhn",
Validator::Mod97 => "mod97",
Validator::Iban => "iban",
}
}
pub fn from_id(id: &str) -> Option<Self> {
VALIDATORS.into_iter().find(|v| v.id() == id)
}
/// Whether `s` passes the checksum.
pub fn check(self, s: &str) -> bool {
match self {
Validator::Luhn => luhn(s),
Validator::Mod97 => mod97(s.chars()),
Validator::Iban => {
let kept: Vec<char> = s.chars().filter(|c| *c != ' ' && *c != '-').collect();
let (head, tail) = kept.split_at(kept.len().min(4));
mod97(tail.iter().chain(head).copied())
}
}
}
}
fn luhn(s: &str) -> bool {
let (mut sum, mut digits, mut double) = (0u32, 0usize, false);
for c in s.chars().rev() {
if c == ' ' || c == '-' {
continue;
}
let Some(d) = c.to_digit(10).filter(|_| c.is_ascii_digit()) else { return false };
let d = if double { if d * 2 > 9 { d * 2 - 9 } else { d * 2 } } else { d };
sum = sum.saturating_add(d);
digits += 1;
double = !double;
}
digits >= 2 && sum % 10 == 0
}
fn mod97(s: impl Iterator<Item = char>) -> bool {
let (mut rem, mut n) = (0u32, 0usize);
for c in s {
if c == ' ' || c == '-' {
continue;
}
if !c.is_ascii_alphanumeric() {
return false;
}
// Digits stay one decimal digit, letters become two (A = 10 .. Z = 35).
let v = c.to_digit(36).unwrap_or(0);
rem = if v >= 10 { (rem * 100 + v) % 97 } else { (rem * 10 + v) % 97 };
n += 1;
}
n >= 2 && rem == 1
}
/// Whether `re` can match the empty string, which `is_match("")` alone misses for assertions such
/// as `\b`. Tries a few short texts with letters, digits, space, newline and a non-ASCII letter.
fn can_match_empty(re: &regex::Regex) -> bool {
["", " ", "a", "1", "a a", "a\n", "\n", "é", "aa 11"].iter().any(|p| re.find_iter(p).any(|m| m.is_empty()))
}
/// A compiled caller expression with an optional checksum.
#[derive(Debug, Clone)]
pub struct UserRegex {
re: regex::Regex,
validator: Option<Validator>,
}
impl UserRegex {
pub fn new(source: &str, validator: Option<Validator>) -> Result<Self, RegexError> {
if source.is_empty() {
return Err(RegexError::Empty);
}
if source.len() > MAX_REGEX_LEN {
return Err(RegexError::TooLong(source.len()));
}
let re = RegexBuilder::new(source)
.size_limit(SIZE_LIMIT)
.dfa_size_limit(SIZE_LIMIT)
.nest_limit(NEST_LIMIT)
.build()
.map_err(|e| RegexError::Invalid(e.to_string()))?;
if can_match_empty(&re) {
return Err(RegexError::MatchesEmpty);
}
Ok(Self { re, validator })
}
/// Character ranges of `text` the expression matches (non-overlapping, left to right).
///
/// Fails with [`RegexError::TooManyMatches`] when more than [`MAX_MATCHES_PER_TEXT`] matches
/// are kept, instead of returning a partial list the caller would take for complete.
pub fn find(&self, text: &[char]) -> Result<Vec<Range<usize>>, RegexError> {
let s: String = text.iter().collect();
// Char index of every byte offset that starts a char (and of the end).
let mut byte_to_char = vec![usize::MAX; s.len().saturating_add(1)];
for (ci, (bi, _)) in s.char_indices().enumerate() {
if let Some(slot) = byte_to_char.get_mut(bi) {
*slot = ci;
}
}
if let Some(slot) = byte_to_char.get_mut(s.len()) {
*slot = text.len();
}
let mut out = Vec::new();
for m in self.re.find_iter(&s) {
if m.is_empty() || self.validator.is_some_and(|v| !v.check(m.as_str())) {
continue;
}
if let (Some(&a), Some(&b)) = (byte_to_char.get(m.start()), byte_to_char.get(m.end()))
&& a < b
&& b != usize::MAX
{
if out.len() >= MAX_MATCHES_PER_TEXT {
return Err(RegexError::TooManyMatches);
}
out.push(a..b);
}
}
Ok(out)
}
}
#[cfg(test)]
mod tests {
use super::*;
fn chars(s: &str) -> Vec<char> {
s.chars().collect()
}
#[test]
fn finds_matches_as_char_ranges_with_multibyte_text() {
let r = UserRegex::new(r"\d{2}( \d{2}){2}", None).unwrap();
let t = chars("Ré 85 05 78 et 91 12 34 fin");
let found: Vec<String> = r.find(&t).unwrap().into_iter().map(|g| t[g].iter().collect()).collect();
assert_eq!(found, ["85 05 78", "91 12 34"]);
}
#[test]
fn validators_filter_matches() {
let t = chars("ok 4539 1488 0343 6467 bad 4539 1488 0343 6468");
let r = UserRegex::new(r"\d{4}( \d{4}){3}", Some(Validator::Luhn)).unwrap();
assert_eq!(r.find(&t).unwrap().len(), 1);
let t = chars("GB82 WEST 1234 5698 7654 32 and GB83 WEST 1234 5698 7654 32");
let r = UserRegex::new(r"GB\d\d WEST( \d{4}){3} \d\d", Some(Validator::Iban)).unwrap();
assert_eq!(r.find(&t).unwrap().len(), 1);
assert!(Validator::Mod97.check("98") && !Validator::Mod97.check("99"));
assert!(!Validator::Luhn.check("12a4") && !Validator::Mod97.check("é1") && !Validator::Luhn.check("0"));
}
#[test]
fn hostile_expressions_are_refused_or_stay_linear() {
assert_eq!(UserRegex::new("", None).unwrap_err(), RegexError::Empty);
assert!(matches!(UserRegex::new(&"a".repeat(MAX_REGEX_LEN + 1), None), Err(RegexError::TooLong(_))));
assert!(matches!(UserRegex::new("(unclosed", None), Err(RegexError::Invalid(_))));
assert!(matches!(UserRegex::new(r"(a)\1", None), Err(RegexError::Invalid(_))), "no back-references");
for empty in ["a*", r"\b", "(?m)^", r"\B", "(?m)$", r"\d*|x"] {
assert_eq!(UserRegex::new(empty, None).unwrap_err(), RegexError::MatchesEmpty, "{empty}");
}
assert!(UserRegex::new(r"\bfoo\b", None).is_ok());
assert!(matches!(UserRegex::new(r"\p{L}{1000}{1000}", None), Err(RegexError::Invalid(_))), "compiled size is capped");
assert!(matches!(UserRegex::new(&format!("{}a{}", "(".repeat(100), ")".repeat(100)), None), Err(RegexError::Invalid(_))));
// Classic catastrophic pattern finishes at once on a long non-matching input.
let r = UserRegex::new(r"(a+)+$", None).unwrap();
let mut t = chars(&"a".repeat(50_000));
t.push('!');
assert!(r.find(&t).unwrap().is_empty());
}
#[test]
fn more_than_the_cap_of_matches_is_an_error_not_a_partial_list() {
let r = UserRegex::new("x", None).unwrap();
let at_cap = chars(&"x ".repeat(MAX_MATCHES_PER_TEXT));
assert_eq!(r.find(&at_cap).unwrap().len(), MAX_MATCHES_PER_TEXT);
let over = chars(&"x ".repeat(MAX_MATCHES_PER_TEXT + 1));
assert_eq!(r.find(&over).unwrap_err(), RegexError::TooManyMatches);
}
}
+3 -3
View File
@@ -58,7 +58,7 @@ impl Decoder {
let mut d = Decoder { map: HashMap::new(), width: if composite { 2 } else { 1 }, opaque: false };
let tu = font.get(b"ToUnicode").map(|t| doc.resolve(t));
if let Some(Object::Stream(s)) = tu.as_deref() {
let data = ctx.decode(s)?;
let data = ctx.decode(doc, s)?;
if data.len() > MAX_CMAP {
return Err(());
}
@@ -435,7 +435,7 @@ pub(super) fn page_content(doc: &Document, page: &Dict, ctx: &Ctx, skip_overlay:
for o in &list {
match &*resolve_strict(doc, o)? {
Object::Stream(s) => {
let d = ctx.decode(s)?;
let d = ctx.decode(doc, s)?;
if skip_overlay && ctx.is_overlay(&d) {
continue;
}
@@ -536,7 +536,7 @@ impl Extractor<'_> {
self.stack.push(r);
}
let result = (|| {
let data = self.ctx.decode(s)?;
let data = self.ctx.decode(self.doc, s)?;
let own = s.dict.get(b"Resources").and_then(|r| self.doc.resolve(r).as_dict().cloned());
self.scope(&data, own.as_ref().unwrap_or(parent), ctm, depth, placed)
})();
+4 -4
View File
@@ -98,7 +98,7 @@ impl Geo<'_> {
// own placement: where it lands comes from each `/Rect`, so the first
// placement tells nothing about the others. Repeated decodes spend the
// same bounded budget as everything else.
let Ok(data) = self.ctx.decode(&st) else {
let Ok(data) = self.ctx.decode(self.doc, &st) else {
self.unverifiable("an annotation appearance can't be read in full");
continue;
};
@@ -278,7 +278,7 @@ impl Geo<'_> {
{
return;
}
let Ok(data) = self.ctx.decode(s) else {
let Ok(data) = self.ctx.decode(self.doc, s) else {
self.unverifiable("a form under the region can't be decoded in full");
return;
};
@@ -336,7 +336,7 @@ impl Geo<'_> {
if depth > MAX_DEPTH {
return Err(());
}
let data = self.ctx.decode(s)?;
let data = self.ctx.decode(self.doc, s)?;
let own = s.dict.get(b"Resources").and_then(|r| self.doc.resolve(r).as_dict().cloned());
let res = own.as_ref().unwrap_or(parent);
let xobjects = res_dict(self.doc, res, b"XObject");
@@ -464,7 +464,7 @@ pub(super) fn image_cleared(doc: &Document, ctx: &Ctx, s: &Stream, ctm: &Matrix,
if !matches!(bpc, 1 | 2 | 4 | 8 | 16) || ncomp == 0 || ncomp > 32 {
return Err(());
}
let data = ctx.decode(s)?;
let data = ctx.decode(doc, s)?;
let bits = ncomp.checked_mul(bpc).ok_or(())?;
let row = w.checked_mul(bits).ok_or(())?.div_ceil(8);
if data.len() < row.checked_mul(h).ok_or(())? {
+5 -5
View File
@@ -252,7 +252,7 @@ pub struct ProofOptions {
#[cfg(test)]
pub(crate) mod tests_support {
use pdfcraft_content::parse;
use pdfcraft_cos::{Dict, Object, Stream};
use pdfcraft_cos::{Dict, Document, Object, Stream};
use super::extract::{carries_glyphs, parse_cmap};
use super::limits::{MAX_STREAM, MAX_TOTAL_DECODED, MAX_WORK, MIN_STRUCTURED_NEEDLE};
@@ -308,9 +308,9 @@ pub(crate) mod tests_support {
pub fn decode_budget_runs_out() -> (bool, bool) {
let ctx = Ctx::new(Default::default());
let s = Stream::from_raw(Dict::new(), vec![0u8; 100]);
let before = ctx.decode(&s).is_ok();
let before = ctx.decode(&Document::new_empty(), &s).is_ok();
let spent = Ctx::with_decode_left(50);
(before, spent.decode(&s).is_err())
(before, spent.decode(&Document::new_empty(), &s).is_err())
}
/// Does a decode that fails past the one-stream cap pay for the attempt, so the same bomb
@@ -322,9 +322,9 @@ pub(crate) mod tests_support {
drop(big);
let small = Stream::from_raw(Dict::new(), vec![0u8; 100]);
let ctx = Ctx::with_decode_left(u64::try_from(MAX_STREAM + 50).unwrap_or(u64::MAX));
let refused = ctx.decode(&bomb).is_err();
let refused = ctx.decode(&Document::new_empty(), &bomb).is_err();
let charged = ctx.decoded.get() == MAX_TOTAL_DECODED - 50;
let gone = ctx.decode(&small).is_err();
let gone = ctx.decode(&Document::new_empty(), &small).is_err();
(refused, charged, gone)
}
+1 -1
View File
@@ -200,7 +200,7 @@ impl Snapshot {
for r in created {
let obj = doc.try_get(r.num).map_err(|_| RedactError::OverlayUnreadable)?;
let Object::Stream(s) = &*obj else { continue };
let data = ctx.decode(s).map_err(|_| RedactError::OverlayUnreadable)?;
let data = ctx.decode(doc, s).map_err(|_| RedactError::OverlayUnreadable)?;
digests.insert(sha256(&[data]));
}
self.overlay = digests;
+4 -4
View File
@@ -495,7 +495,7 @@ fn sweep_objects(needles: &[Needle], doc: &Document, depth: usize, tag: &str, ac
for n in acc.bytes(Surface::DecodedStreams, needles, &s.raw, MIN_STRUCTURED_NEEDLE) {
acc.survivor(Surface::DecodedStreams, format!("{loc} (raw)"), Some(n));
}
match acc.ctx.decode(s) {
match acc.ctx.decode(doc, s) {
Ok(d) => {
let loc = format!("{loc} (decoded)");
for (n, c) in acc.counts(Surface::DecodedStreams, needles, &d, MIN_STRUCTURED_NEEDLE) {
@@ -508,7 +508,7 @@ fn sweep_objects(needles: &[Needle], doc: &Document, depth: usize, tag: &str, ac
Err(()) => acc.raw_only(Surface::DecodedStreams),
}
} else {
match acc.ctx.decode(s) {
match acc.ctx.decode(doc, s) {
// The boxes and labels this run drew are not text to look for.
Ok(d) if acc.ctx.is_overlay(&d) => overlay_raw.push(s.raw.to_vec()),
Ok(d) => {
@@ -578,7 +578,7 @@ fn sweep_attachments(needles: &[Needle], doc: &Document, embedded: &BTreeSet<u32
acc.problem(Surface::EmbeddedFiles, format!("{loc} is not a stream"));
continue;
};
let payload = match acc.ctx.decode(s) {
let payload = match acc.ctx.decode(doc, s) {
Ok(p) => p,
Err(()) => {
acc.problem(Surface::EmbeddedFiles, format!("{loc} can't be decoded in full"));
@@ -742,7 +742,7 @@ pub(super) fn sweep_xmp(needles: &[Needle], doc: &Document, tag: &str, acc: &mut
acc.problem(Surface::Xmp, format!("{loc} is not a stream"));
return;
};
let Ok(data) = acc.ctx.decode(s) else {
let Ok(data) = acc.ctx.decode(doc, s) else {
acc.problem(Surface::Xmp, format!("{loc} can't be decoded in full"));
return;
};
+3 -2
View File
@@ -33,11 +33,12 @@ impl Ctx {
/// attempt is charged to the cumulative allowance, failures included: a decode that fails
/// past the one-stream cap pays the cap, and one that fails mid-way pays what it decoded
/// before the error — the work of finding out is not work a repeated reference gets for free.
pub(super) fn decode(&self, s: &Stream) -> Result<Vec<u8>, ()> {
/// `/DecodeParms` given by reference are read in `doc`, as redaction itself reads them.
pub(super) fn decode(&self, doc: &Document, s: &Stream) -> Result<Vec<u8>, ()> {
let left = MAX_TOTAL_DECODED.saturating_sub(self.decoded.get());
let cap = usize::try_from(left).unwrap_or(usize::MAX).min(MAX_STREAM);
let mut budget = DecodeBudget::new(cap, usize::MAX);
let result = budget.decode_strict(s);
let result = budget.decode_strict(doc, s);
// The attempt's own accounting covers a success (what it decoded), a stream cut short
// by corruption (what it decoded first) and one refused past the cap (the cap): charge
// it through, whichever way the attempt went.
+3
View File
@@ -23,6 +23,9 @@ pub struct TextFilter {
pub code: bool,
/// Exclude Figure-marked text and invisible text layers, including OCR.
pub images: bool,
/// Exclude `/ActualText` that marks no glyph, whose words are drawn as outlines or pictures:
/// a page's own text, for deciding whether it still needs reading from its pixels.
pub painted: bool,
/// Page-local MCIDs whose structure ancestors match the selected exclusions.
pub mcids: HashSet<i32>,
}
+192 -15
View File
@@ -25,6 +25,16 @@ pub(super) struct TextDevice {
/// The outermost open `/ActualText` replacement: its depth, text and the glyphs drawn inside
/// it (with no text of their own yet).
actual: Option<(usize, String, Vec<Drawn>)>,
/// What the open `/ActualText` replacement paints besides glyphs (paths, images), as far as
/// it can be seen: where its text reads when it marks no glyph (words drawn as outlines).
painted: Option<Painted>,
/// Whether the open `/ActualText` replacement paints anything an exclusion leaves out.
paint_filtered: bool,
/// Whether the open `/ActualText` replacement paints anything wholly outside the crop box.
paint_cropped: bool,
/// The bounding boxes of the clip paths in force (view space), innermost last, each cut to the
/// one before it: an outer bound on what can show.
clips: Vec<Rect>,
/// Every `/ActualText` replacement made on the page.
pub(super) replaced: Vec<Replaced>,
/// Visible page bounds in view space (`intersected_crop_box` after `initial_transform`).
@@ -105,12 +115,109 @@ fn merge(drawn: &[Drawn], text: String) -> Option<Drawn> {
Some((quarter, u, TextGlyph { text, rect, quad, direction: first.2.direction }))
}
/// The widest or tallest box (view-space points) a glyph, or the paint standing in for one, may
/// have and still be placed: anything bigger is damage, not text.
const MAX_GLYPH_EXTENT: f64 = 10_000.0;
/// The quarter turn of direction `(dx, dy)` (view space, y down): 0 right, 1 down, 2 left, 3 up.
fn quarter_turn(dx: f64, dy: f64) -> usize {
if dx.abs() >= dy.abs() {
if dx >= 0.0 { 0 } else { 2 }
} else if dy > 0.0 {
1
} else {
3
}
}
/// What an `/ActualText` replacement paints besides glyphs, measured as [`merge`] measures
/// glyphs: along the writing direction of the first of it (its transform's x axis, `u`) and
/// across it.
struct Painted {
quarter: usize,
u: [f64; 2],
along: [f64; 2],
across: [f64; 2],
}
impl Painted {
fn new(transform: Affine) -> Self {
let [a, b, ..] = transform.as_coeffs();
let length = a.hypot(b);
let u = if length.is_finite() && length > 0.0 { [a / length, b / length] } else { [1.0, 0.0] };
let empty = [f64::INFINITY, f64::NEG_INFINITY];
Painted { quarter: quarter_turn(u[0], u[1]), u, along: empty, across: empty }
}
/// Grow the measure by the view-space box `b`.
fn add(&mut self, b: Rect) {
let n = [-self.u[1], self.u[0]];
for (x, y) in [(b.x0, b.y0), (b.x1, b.y0), (b.x1, b.y1), (b.x0, b.y1)] {
let (s, t) = (x * self.u[0] + y * self.u[1], x * n[0] + y * n[1]);
self.along = [self.along[0].min(s), self.along[1].max(s)];
self.across = [self.across[0].min(t), self.across[1].max(t)];
}
}
/// A stand-in glyph with no text of its own, boxed around what was painted and read along its
/// direction; `None` when that is too big to be the place of words.
fn glyph(self) -> Option<Drawn> {
let ([s0, s1], [t0, t1]) = (self.along, self.across);
// Too big to be the place of words, or NaN.
if !(s1 - s0 <= MAX_GLYPH_EXTENT && t1 - t0 <= MAX_GLYPH_EXTENT) {
return None;
}
let (u, n) = (self.u, [-self.u[1], self.u[0]]);
let point = |s: f64, t: f64| [(s * u[0] + t * n[0]) as f32, (s * u[1] + t * n[1]) as f32];
// The edge towards the next line starts the quad, as a glyph's em box does.
let quad = [point(s0, t1), point(s1, t1), point(s1, t0), point(s0, t0)];
let rect = quad.iter().fold([f32::INFINITY, f32::INFINITY, f32::NEG_INFINITY, f32::NEG_INFINITY], |r, p| {
[r[0].min(p[0]), r[1].min(p[1]), r[2].max(p[0]), r[3].max(p[1])]
});
rect.iter()
.all(|v| v.is_finite())
.then(|| (self.quarter, u, TextGlyph { text: String::new(), rect, quad, direction: [u[0] as f32, u[1] as f32] }))
}
}
/// The part of `b` inside `c`, or `None` when none of it is. A NaN edge of `c` (a damaged clip)
/// leaves that edge uncut.
fn cut(b: Rect, c: Rect) -> Option<Rect> {
let (x0, y0, x1, y1) = (b.x0.max(c.x0), b.y0.max(c.y0), b.x1.min(c.x1), b.y1.min(c.y1));
(x0 <= x1 && y0 <= y1).then(|| Rect::new(x0, y0, x1, y1))
}
/// The view-space box of `path` drawn with `transform`, from its control points (as redaction
/// measures a path), or `None` when it has no finite point.
fn control_box(path: &BezPath, transform: Affine) -> Option<Rect> {
let mut b: Option<Rect> = None;
let mut add = |p: kurbo::Point| {
let q = transform * p;
if q.is_finite() {
b = Some(b.map_or_else(|| Rect::from_points(q, q), |r| r.union_pt(q)));
}
};
for el in path.elements() {
match *el {
kurbo::PathEl::MoveTo(p) | kurbo::PathEl::LineTo(p) => add(p),
kurbo::PathEl::QuadTo(p1, p2) => [p1, p2].into_iter().for_each(&mut add),
kurbo::PathEl::CurveTo(p1, p2, p3) => [p1, p2, p3].into_iter().for_each(&mut add),
kurbo::PathEl::ClosePath => {}
}
}
b
}
impl TextDevice {
pub(super) fn new() -> Self {
TextDevice {
glyphs: Vec::new(),
depth: 0,
actual: None,
painted: None,
paint_filtered: false,
paint_cropped: false,
clips: Vec::new(),
replaced: Vec::new(),
page: Rect::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::INFINITY, f64::INFINITY),
filter: TextFilter::default(),
@@ -128,9 +235,14 @@ impl TextDevice {
/// words can't be found.
///
/// A replacement spanning several lines or writing directions stays per glyph (each glyph's own
/// Unicode). An empty one (a soft hyphen at a line break, say) stands for no text at all.
/// Unicode). An empty one (a soft hyphen at a line break, say) stands for no text at all. One
/// that marks no glyph reads where it paints, as far as that can be seen: words drawn as
/// outlines or pictures.
fn end_actual_text(&mut self) {
let Some((_, text, drawn)) = self.actual.take() else { return };
let Some((_, text, mut drawn)) = self.actual.take() else { return };
let painted = self.painted.take();
let paint_filtered = std::mem::take(&mut self.paint_filtered);
let paint_cropped = std::mem::take(&mut self.paint_cropped);
let cropped = std::mem::take(&mut self.actual_cropped);
if std::mem::take(&mut self.actual_filtered) {
// ActualText has no mapping from replacement words to individual glyphs. A mixed
@@ -138,10 +250,27 @@ impl TextDevice {
self.partial_replacement |= !drawn.is_empty();
return;
}
// Before the paint: a span whose glyphs the crop box took has none left, yet it marks
// glyphs, so its paint doesn't place it.
if cropped {
self.glyphs.extend(drawn.into_iter().filter(|d| !d.2.text.chars().all(|c| c.is_control())));
return;
}
if drawn.is_empty()
&& !self.filter.painted
&& let Some(stand_in) = painted.and_then(Painted::glyph)
{
// The paint places it, so paint left out mixes it as excluded glyphs would.
if paint_filtered {
self.partial_replacement = true;
return;
}
// Its words may be among what the crop box hides, as with a glyph cropped away.
if paint_cropped {
return;
}
drawn.push(stand_in);
}
let Some(glyph) = merge(&drawn, text.clone()) else {
self.glyphs.extend(drawn.into_iter().filter(|d| !d.2.text.chars().all(char::is_control)));
return;
@@ -156,6 +285,25 @@ impl TextDevice {
self.replaced.push(Replaced { at, text, originals });
}
/// Record view-space box `b`, drawn with `transform`, as painted by the open `/ActualText`
/// replacement, cut to the visible area (the crop box, and the clip in force); paint wholly
/// outside the crop box, or that an exclusion leaves out (`excluded`), only marks the
/// replacement.
fn paint(&mut self, b: Rect, transform: Affine, excluded: bool) {
// Wholly outside the crop box, as a glyph dropped there is: the replacement can't be read.
let Some(on_page) = cut(b, self.page) else {
self.paint_cropped = true;
return;
};
// Clipped away entirely: nothing of it shows.
let Some(seen) = self.clips.last().map_or(Some(on_page), |c| cut(on_page, *c)) else { return };
if excluded {
self.paint_filtered = true;
} else {
self.painted.get_or_insert_with(|| Painted::new(transform)).add(seen);
}
}
/// Ends the page. Some producers draw text twice, the copy for an outline, shadow or
/// glow, and mark only one drawing with `/ActualText` (Canva). The unmarked redraw of a
/// replacement's glyphs (the same text at the same places, in content order) takes the same
@@ -259,8 +407,23 @@ fn text_debug() -> bool {
impl<'a> Device<'a> for TextDevice {
fn set_soft_mask(&mut self, _: Option<SoftMask<'a>>) {}
fn set_blend_mode(&mut self, _: BlendMode) {}
fn draw_path(&mut self, _: &BezPath, _: Affine, _: &Paint<'a>, _: &PathDrawMode) {}
fn push_clip_path(&mut self, _: &ClipPath) {}
fn draw_path(&mut self, path: &BezPath, transform: Affine, _: &Paint<'a>, _: &PathDrawMode) {
// A path is no text, but it places an `/ActualText` replacement that marks no glyph.
if self.actual.is_some()
&& let Some(b) = control_box(path, transform)
{
self.paint(b, transform, self.excluded_depth.is_some());
}
}
fn push_clip_path(&mut self, clip: &ClipPath) {
// Clip paths arrive in view space. NaN edges (a damaged clip) leave that edge unclipped.
let b = clip.path.bounding_box();
let visible = match self.clips.last() {
Some(c) => Rect::new(c.x0.max(b.x0), c.y0.max(b.y0), c.x1.min(b.x1), c.y1.min(b.y1)),
None => b,
};
self.clips.push(visible);
}
fn push_transparency_group(&mut self, _: f32, _: Option<SoftMask<'a>>, _: BlendMode) {}
fn draw_glyph(&mut self, glyph: &Glyph<'a>, transform: Affine, glyph_transform: Affine, _: &Paint<'a>, mode: &GlyphDrawMode) {
if self.excluded_depth.is_some() || (self.filter.images && matches!(mode, GlyphDrawMode::Invisible)) {
@@ -309,13 +472,7 @@ impl<'a> Device<'a> for TextDevice {
} else {
(coefficients[0], coefficients[1])
};
let dir = if dx.abs() >= dy.abs() {
if dx >= 0.0 { 0 } else { 2 }
} else if dy > 0.0 {
1
} else {
3
};
let dir = quarter_turn(dx, dy);
let em = Rect::new(0.0, -200.0, advance, 800.0);
let corners = if matches!(glyph, Glyph::Outline(g) if g.is_vertical()) {
[(em.x0, em.y1), (em.x0, em.y0), (em.x1, em.y0), (em.x1, em.y1)]
@@ -328,8 +485,8 @@ impl<'a> Device<'a> for TextDevice {
});
let outside_crop = b.x0.max(self.page.x0) >= b.x1.min(self.page.x1) || b.y0.max(self.page.y0) >= b.y1.min(self.page.y1);
if !(b.x0.is_finite() && b.y0.is_finite() && b.x1.is_finite() && b.y1.is_finite())
|| b.width() > 10_000.0
|| b.height() > 10_000.0
|| b.width() > MAX_GLYPH_EXTENT
|| b.height() > MAX_GLYPH_EXTENT
|| outside_crop
{
self.actual_cropped |= replaced && outside_crop;
@@ -350,8 +507,23 @@ impl<'a> Device<'a> for TextDevice {
None => self.glyphs.push((dir, direction, glyph)),
}
}
fn draw_image(&mut self, _: Image<'a, '_>, _: Affine) {}
fn pop_clip_path(&mut self) {}
fn draw_image(&mut self, image: Image<'a, '_>, transform: Affine) {
// A picture of words, like an outline, places a replacement that marks no glyph; with
// images excluded, it is not counted.
if self.actual.is_none() {
return;
}
// The transform places the picture's pixels, not a unit square.
let (w, h) = (f64::from(image.width()), f64::from(image.height()));
let corners = [(0.0, 0.0), (w, 0.0), (w, h), (0.0, h)].map(|(x, y)| transform * kurbo::Point::new(x, y));
let [a, b, c, d] = corners;
if corners.iter().all(|p| p.is_finite()) {
self.paint(Rect::from_points(a, c).union_pt(b).union_pt(d), transform, self.excluded_depth.is_some() || self.filter.images);
}
}
fn pop_clip_path(&mut self) {
self.clips.pop();
}
fn pop_transparency_group(&mut self) {}
fn begin_marked_content(&mut self, tag: &[u8], mcid: Option<i32>) {
self.depth = self.depth.saturating_add(1);
@@ -374,6 +546,11 @@ impl<'a> Device<'a> for TextDevice {
}
self.depth = self.depth.saturating_sub(1);
}
fn begin_annotations(&mut self) {
// A replacement the page content never closed ends with it: the annotations drawn next
// are not part of it.
self.end_actual_text();
}
}
/// Extract the text of one page. Panics inside the interpreter are the caller's to catch.
+201
View File
@@ -279,6 +279,207 @@ fn actual_text_follows_the_pdf_rules_for_marked_content() {
assert_eq!(plain, ["ofice", "AB", "co op", "x\ny", "afi", "abc"]);
}
#[test]
fn actual_text_over_painted_paths_reads_where_they_are_painted() {
// Words drawn as outlines (a face that can't be embedded) carry their text in /ActualText
// (ISO 32000-2 §14.9.4): it reads at the box of the paths it marks, in view space (y down).
let pdf = marked_pages(&[
"/Span <</ActualText (valid)>> BDC 100 40 m 160 40 l 160 60 l 100 60 l f EMC",
// A curve is measured by its control points, as redaction measures it.
"/Span <</ActualText (arc)>> BDC 100 40 m 100 100 160 100 160 40 c f EMC",
"BT /F1 20 Tf 1 0 0 1 20 150 Tm (a) Tj ET /Span <</ActualText (b)>> BDC 100 140 60 20 re f EMC BT /F1 20 Tf 1 0 0 1 200 150 Tm (c) Tj ET",
// Glyphs inside the span keep their own box; the paths beside them don't widen it.
"/Span <</ActualText (x)>> BDC BT /F1 20 Tf 1 0 0 1 100 150 Tm (y) Tj ET 0 0 300 300 re f EMC",
// Paths are not text without a replacement, and an empty one stands for nothing.
"100 140 60 20 re f",
"/Span <</ActualText ()>> BDC 100 140 60 20 re f EMC",
]);
let painted = marked_text(&pdf, 0);
assert_eq!(painted.plain_text(), "valid");
assert_eq!(painted.glyphs[0].rect, [100.0, 240.0, 160.0, 260.0]);
assert_eq!(marked_text(&pdf, 1).glyphs[0].rect, [100.0, 200.0, 160.0, 260.0]);
let between = marked_text(&pdf, 2);
assert_eq!(between.glyphs.iter().map(|g| g.text.as_str()).collect::<Vec<_>>(), ["a", "b", "c"]);
let mixed = marked_text(&pdf, 3);
assert_eq!(mixed.plain_text(), "x");
assert!(mixed.glyphs[0].rect[2] - mixed.glyphs[0].rect[0] < 20.0, "{:?}", mixed.glyphs[0].rect);
for page in 4..6 {
assert_eq!(marked_text(&pdf, page).plain_text(), "", "page {page}");
}
}
#[test]
fn the_painted_filter_leaves_out_replacements_that_mark_no_glyph() {
// A page's own text, without words that only /ActualText names.
let pdf = marked_pages(&[
"/Span <</ActualText (valid)>> BDC 100 40 m 160 40 l 160 60 l 100 60 l f EMC",
"BT /F1 20 Tf 1 0 0 1 20 150 Tm (a) Tj ET /Span <</ActualText (b)>> BDC 100 140 60 20 re f EMC BT /F1 20 Tf 1 0 0 1 200 150 Tm (c) Tj ET",
]);
let own = |page| extract_page_filtered(&pdf, page, &InterpreterSettings::default(), TextFilter { painted: true, ..Default::default() });
assert_eq!(own(0).unwrap().plain_text(), "");
let between = own(1).unwrap().plain_text();
assert!(between.contains('a') && between.contains('c') && !between.contains('b'), "the glyphs stay: {between:?}");
}
#[test]
fn actual_text_over_paint_reads_only_where_it_shows() {
let pdf = marked_pages(&[
// A page-sized fill clipped to a word's box reads at that box.
"q 100 40 30 20 re W n /Span <</ActualText (c)>> BDC 0 0 300 300 re f EMC Q",
// Wholly clipped away, it reads nowhere.
"q 0 0 10 10 re W n /Span <</ActualText (gone)>> BDC 100 40 60 20 re f EMC Q",
// A clip that ended before the paint no longer cuts it.
"q 0 0 10 10 re W n Q /Span <</ActualText (back)>> BDC 100 40 60 20 re f EMC",
]);
assert_eq!(marked_text(&pdf, 0).glyphs[0].rect, [100.0, 240.0, 130.0, 260.0]);
assert_eq!(marked_text(&pdf, 1).plain_text(), "");
assert_eq!(marked_text(&pdf, 2).glyphs[0].rect, [100.0, 240.0, 160.0, 260.0]);
}
#[test]
fn actual_text_over_paint_reads_only_inside_the_crop_box() {
use lopdf::{Document, Object, Stream, dictionary};
let (page, crop) = ([0, 0, 300, 300], [50, 60, 250, 240]);
let pages = [
// Wholly outside the crop box, as a glyph there is: it reads nowhere.
("/Span <</ActualText (below)>> BDC 100 10 60 20 re f EMC", page, crop),
// Across its left edge: it reads from that edge, as a glyph across it still shows.
("/Span <</ActualText (edge)>> BDC 20 100 60 20 re f EMC", page, crop),
// Partly painted outside it: its words may be among what the crop box hides.
("/Span <</ActualText (part)>> BDC 100 100 60 20 re f 100 10 60 20 re f EMC", page, crop),
// A glyph the crop takes leaves the replacement no glyph, and the paint can't place it.
("/Span <</ActualText (split)>> BDC BT /F1 12 Tf 1 0 0 1 100 10 Tm (x) Tj ET 100 100 60 20 re f EMC", page, crop),
// On a page wide enough to hold them, paint too far apart to be the place of words.
("/Span <</ActualText (far)>> BDC 100 40 10 10 re f 12100 40 10 10 re f EMC", [0, 0, 14400, 300], [0, 0, 14400, 300]),
];
let boxed = |b: [i64; 4]| b.map(Object::Integer).to_vec();
let mut doc = Document::with_version("1.7");
let font = doc.add_object(dictionary! { "Type" => "Font", "Subtype" => "Type1", "BaseFont" => "Helvetica" });
let parent = doc.new_object_id();
let mut kids = Vec::new();
for (ops, media, crop) in pages {
let content = doc.add_object(Stream::new(dictionary! {}, ops.as_bytes().to_vec()));
kids.push(Object::Reference(doc.add_object(dictionary! {
"Type" => "Page",
"Parent" => parent,
"MediaBox" => boxed(media),
"CropBox" => boxed(crop),
"Resources" => dictionary! { "Font" => dictionary! { "F1" => font } },
"Contents" => content,
})));
}
let count = kids.len() as i64;
doc.objects.insert(parent, dictionary! { "Type" => "Pages", "Kids" => kids, "Count" => count }.into());
let catalog = doc.add_object(dictionary! { "Type" => "Catalog", "Pages" => parent });
doc.trailer.set("Root", catalog);
let mut bytes = Vec::new();
doc.save_to(&mut bytes).unwrap();
let pdf = Pdf::new(std::sync::Arc::new(bytes)).unwrap();
assert_eq!(marked_text(&pdf, 0).plain_text(), "");
// View space starts at the crop box's top-left corner.
assert_eq!(marked_text(&pdf, 1).glyphs[0].rect, [0.0, 120.0, 30.0, 140.0]);
for page in 2..5 {
assert_eq!(marked_text(&pdf, page).plain_text(), "", "page {page}");
}
}
#[test]
fn actual_text_over_paint_reads_along_the_way_it_is_drawn() {
// The same quarter turn for a path and for text: the replacement runs the way the text does.
let pdf = marked_pages(&[
"q 0 1 -1 0 150 150 cm /Span <</ActualText (turned)>> BDC 0 0 40 10 re f EMC Q",
"q 0 1 -1 0 150 150 cm BT /F1 10 Tf 0 0 Td (t) Tj ET Q",
]);
let (painted, text) = (marked_text(&pdf, 0), marked_text(&pdf, 1));
assert_eq!(painted.plain_text(), "turned");
assert_eq!(painted.glyphs[0].direction, text.glyphs[0].direction);
let [x0, y0, x1, y1] = painted.glyphs[0].rect;
assert_eq!((x1 - x0, y1 - y0), (10.0, 40.0), "40 along the turned line, 10 across it");
}
#[test]
fn actual_text_over_a_picture_reads_where_it_is_drawn() {
// Two pixels square, so a box placed in pixels rather than across the picture shows.
let pdf = marked_pages(&["/Span <</ActualText (E=mc2)>> BDC q 60 0 0 20 100 40 cm BI /W 2 /H 2 /CS /G /BPC 8 ID AAAA EI Q EMC"]);
let text = marked_text(&pdf, 0);
assert_eq!(text.plain_text(), "E=mc2");
assert_eq!(text.glyphs[0].rect, [100.0, 240.0, 160.0, 260.0]);
// Counting without images leaves it out.
let filter = TextFilter { images: true, ..Default::default() };
assert_eq!(extract_page_filtered(&pdf, 0, &InterpreterSettings::default(), filter).unwrap().plain_text(), "");
}
#[test]
fn excluded_glyphs_beside_paint_leave_the_whole_replacement_out() {
// The marked glyphs are a figure's, so the replacement goes with them; the paint beside
// them neither keeps it nor turns it into a mixed span that can't be counted.
let pdf = marked_pages(&[
"/Span <</ActualText (f)>> BDC /Figure BMC BT /F1 20 Tf 1 0 0 1 100 150 Tm (x) Tj ET EMC 100 40 60 20 re f EMC",
// Paint inside an excluded region is excluded with it.
"/Span <</ActualText (z)>> BDC /Figure BMC 100 40 60 20 re f EMC EMC",
"/Span <</ActualText (t)>> BDC /Table BMC q 60 0 0 20 100 40 cm BI /W 1 /H 1 /CS /G /BPC 8 ID A EI Q EMC EMC",
]);
let filtered = |page, filter| extract_page_filtered(&pdf, page, &InterpreterSettings::default(), filter).unwrap().plain_text();
let (figures, tables) = (TextFilter { images: true, ..Default::default() }, TextFilter { tables: true, ..Default::default() });
assert_eq!(filtered(0, figures.clone()), "");
assert_eq!((filtered(1, TextFilter::default()), filtered(1, figures)), ("z".to_string(), String::new()));
assert_eq!((filtered(2, TextFilter::default()), filtered(2, tables)), ("t".to_string(), String::new()));
}
#[test]
fn paint_split_by_an_exclusion_is_a_mixed_span_that_cant_be_counted() {
// Paint places a replacement that marks no glyph, so paint left out mixes it as excluded
// glyphs do: the words left out can't be told from the rest.
let picture = "q 60 0 0 20 100 40 cm BI /W 1 /H 1 /CS /G /BPC 8 ID A EI Q";
let (table, beside) = (
format!("/Span <</ActualText (t)>> BDC /Table BMC {picture} EMC 200 40 60 20 re f EMC"),
format!("/Span <</ActualText (p)>> BDC {picture} 200 40 60 20 re f EMC"),
);
let pdf = marked_pages(&[
"/Span <</ActualText (w)>> BDC /Figure BMC 100 40 60 20 re f EMC 200 40 60 20 re f EMC",
&table,
&beside,
// Glyphs place this one, and the paint beside them is not its words.
"/Span <</ActualText (g)>> BDC BT /F1 20 Tf 1 0 0 1 100 150 Tm (y) Tj ET /Figure BMC 100 40 60 20 re f EMC EMC",
]);
let filtered = |page, filter| extract_page_filtered(&pdf, page, &InterpreterSettings::default(), filter).map(|t| t.plain_text());
let (figures, tables) = (TextFilter { images: true, ..Default::default() }, TextFilter { tables: true, ..Default::default() });
for (page, text, filter) in [(0, "w", figures.clone()), (1, "t", tables), (2, "p", figures.clone())] {
assert_eq!(filtered(page, TextFilter::default()), Ok(text.to_string()));
assert!(filtered(page, filter).is_err(), "page {page}");
}
assert_eq!(filtered(3, figures), Ok("g".to_string()));
}
#[test]
fn annotations_never_join_a_replacement_the_page_left_open() {
use lopdf::{Document, Object, Stream, dictionary};
let mut doc = Document::with_version("1.7");
let pages = doc.new_object_id();
let content = doc.add_object(Stream::new(dictionary! {}, b"/Span <</ActualText (open)>> BDC 100 40 60 20 re f".to_vec()));
let ap = doc.add_object(Stream::new(
dictionary! { "Type" => "XObject", "Subtype" => "Form", "BBox" => vec![0.into(), 0.into(), 50.into(), 50.into()] },
b"0 0 50 50 re f".to_vec(),
));
let annot = doc.add_object(dictionary! {
"Type" => "Annot", "Subtype" => "Square", "F" => 4,
"Rect" => vec![200.into(), 200.into(), 250.into(), 250.into()], "AP" => dictionary! { "N" => ap },
});
let page = doc.add_object(dictionary! {
"Type" => "Page", "Parent" => pages, "Contents" => content, "Annots" => vec![Object::Reference(annot)],
"MediaBox" => vec![Object::Integer(0), Object::Integer(0), Object::Integer(300), Object::Integer(300)],
});
doc.objects.insert(pages, dictionary! {"Type" => "Pages", "Kids" => vec![Object::Reference(page)], "Count" => 1}.into());
let catalog = doc.add_object(dictionary! {"Type" => "Catalog", "Pages" => pages});
doc.trailer.set("Root", catalog);
let mut bytes = Vec::new();
doc.save_to(&mut bytes).unwrap();
let pdf = Pdf::new(std::sync::Arc::new(bytes)).unwrap();
let text = marked_text(&pdf, 0);
assert_eq!(text.plain_text(), "open");
assert_eq!(text.glyphs[0].rect, [100.0, 240.0, 160.0, 260.0], "the square comment is not part of it");
}
#[test]
fn an_unmarked_redraw_of_actual_text_reads_as_the_same_text() {
// Canva draws text twice (an outline or shadow) and marks only one drawing. The copy,
+4
View File
@@ -13,6 +13,7 @@ workspace = true
[dependencies]
pdfcraft-cos = { workspace = true }
pdfcraft-annot = { workspace = true }
pdfcraft-content = { workspace = true }
pdfcraft-fonts = { workspace = true }
pdfcraft-model = { workspace = true }
thiserror.workspace = true
@@ -41,6 +42,9 @@ sha3 = "0.12.0"
ripemd = "0.2.0"
ed25519-dalek = "3.0.0"
[dev-dependencies]
pdfcraft-testkit = { workspace = true }
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
aws-lc-rs = { version = "1.18", default-features = false, features = ["aws-lc-sys", "prebuilt-nasm"] }
getrandom = "0.4"
+4
View File
@@ -50,6 +50,10 @@ for s in signatures(&doc, &bytes, &trust) { // li
RFC 6960 OCSP responses (responder identity, OCSP-signing EKU for delegated responders,
CertID hash matching, validity windows); validation checks embedded evidence against the
signer's chain and a verified revocation invalidates the signature.
- **Status layers:** `show_status_layers` draws each signature's validated state (icon, and a
caption in the caller's words) into named-layer appearances, whose `/N` draws one layer form
that holds and draws `n1` and `n3`; `has_status_layers` says whether a document has any. It
works on a display copy and never edits an original object, so saving keeps the signed bytes.
Not yet: revocation fetching (AIA/CRLDP extraction and a fetcher), timestamp-server
configuration, FieldMDP locks, certificate security, direct PKCS #11 access to tokens.
+3 -1
View File
@@ -19,6 +19,7 @@ pub mod pdf;
pub mod pkcs12;
pub mod revocation;
mod rsa_pad;
pub mod status_layers;
pub mod timestamp;
#[cfg(target_os = "windows")]
pub mod windows;
@@ -29,9 +30,10 @@ pub use graphic::Graphic;
pub use keys::{DigestAlg, PrivateKey, PublicKey};
pub use pdf::{
Appearance, AppearanceLabels, Detail, DigestCache, Fill, Modification, SignOptions, SignatureInfo, Status, TrustStore, WORDINGS, Words,
in_english, kind, list as signatures, sign, sign_with_timestamp, timestamp_document, validate,
has_signatures, in_english, kind, list as signatures, sign, sign_with_timestamp, timestamp_document, validate,
};
pub use pkcs12::DigitalId;
pub use status_layers::{StatusCaptions, has_status_layers, show_status_layers, status_rgb};
pub use timestamp::{TimestampAuthority, TimestampQuery, TimestampToken};
pub use x509::{Certificate, Name};
+13 -2
View File
@@ -32,10 +32,13 @@ mod validate;
#[cfg(test)]
use changes::only_grew;
#[cfg(test)]
use listing::{DISCOVERY_CACHE_LIMIT, is_document_timestamp};
pub(crate) use listing::MAX_FIELD_NAME_BYTES;
#[cfg(test)]
use listing::{DISCOVERY_CACHE_LIMIT, Field, MAX_ENTRIES, MAX_FIELDS, MAX_NAME_BYTES, is_document_timestamp, sig_fields};
pub use listing::{DigestCache, list, list_cached};
pub(crate) use listing::{walk_sig_fields, widget_shown};
pub(crate) use signing::fmt;
pub use signing::{Appearance, AppearanceLabels, SignOptions, display_date, sign, sign_with_timestamp, timestamp_document};
pub use signing::{Appearance, AppearanceLabels, SignOptions, display_date, has_signatures, sign, sign_with_timestamp, timestamp_document};
pub use types::{Detail, Fill, Modification, Status, TrustStore, WORDINGS, Words, in_english, kind};
pub(crate) use validate::signature_contents;
pub use validate::validate;
@@ -46,6 +49,9 @@ use validate::{DssEvidence, MAX_DSS_BYTES, MAX_DSS_ENTRIES};
#[path = "pdf_discovery_tests.rs"]
mod discovery_tests;
#[cfg(test)]
#[path = "pdf_fields_tests.rs"]
mod fields_tests;
#[cfg(test)]
#[path = "pdf/revision_classification_tests.rs"]
mod revision_classification_tests;
@@ -89,6 +95,11 @@ pub struct SignatureInfo {
pub timestamp_time: Option<Time>,
pub status: Status,
pub modification: Modification,
/// The display copy draws this verdict into the appearance of at least one of the
/// signature's visible widgets (its named status layers, see [`crate::status_layers`]). The
/// document can still clip those layers away or cover them, so this never stands in for the
/// page's own validation badge. [`list`] leaves it false; [`crate::show_status_layers`] sets it.
pub verdict_shown: bool,
/// Acrobat-style sentences explaining the verdict, each one ready to read in English and ready to
/// be said in another language (see [`Detail`]).
pub details: Vec<Detail>,
+241 -37
View File
@@ -1,4 +1,6 @@
use super::types::{Modification, Status, TrustStore};
use std::rc::Rc;
use super::types::{Detail, Modification, Status, TrustStore};
use super::validate::{is_doc_timestamp, validate_doc_timestamp, validate_into};
use super::{Arc, Dict, DigestAlg, Document, HashMap, HashSet, ObjRef, Object, SignatureInfo};
@@ -176,12 +178,16 @@ pub(crate) fn text(doc: &Document, d: &Dict, key: &[u8]) -> Option<String> {
(!s.is_empty()).then_some(s)
}
pub(super) struct Field {
pub(super) name: String,
/// A signature field [`walk_sig_fields`] found.
pub(crate) struct Field {
/// Fully qualified: the `/T` parts down the tree joined with dots, at most
/// [`MAX_FIELD_NAME_BYTES`].
pub(crate) name: String,
/// The field dictionary (and its widget(s)).
pub(super) r: Option<ObjRef>,
pub(super) dict: Dict,
pub(super) widgets: Vec<(Option<ObjRef>, Dict)>,
/// A widget several fields list is listed under each of them, as one shared copy.
pub(crate) widgets: Vec<(Option<ObjRef>, Rc<Dict>)>,
}
impl Field {
@@ -198,46 +204,191 @@ impl Field {
}
}
/// Every signature field, depth first in `/Fields` order.
/// Most fields looked at for signature fields; real forms have far fewer. Past it no more are
/// taken, and [`list_cached`] stands for the ones not read with one row ([`unread_fields`]).
pub(super) const MAX_FIELDS: usize = 20_000;
/// Most entries read from `/Fields` and all the `/Kids` arrays together: room for a few widgets
/// for each of [`MAX_FIELDS`]. A `/Kids` array several fields list is read under each of them, so
/// this bounds the walk where the field count can't. Past it no more entries are read: fields
/// already taken are still listed, without the widgets past it.
pub(super) const MAX_ENTRIES: usize = 100_000;
/// Longest fully qualified field name read, in bytes. Real names are far shorter; a field named
/// longer is passed over, and counts as unread as fields past [`MAX_FIELDS`] do unless it is a leaf
/// of another type.
pub(crate) const MAX_FIELD_NAME_BYTES: usize = 4096;
/// Most bytes of names the walk keeps, all the fields it lists together. A kid's name repeats its
/// parent's, so under the caps above one long name over many kids would still come to 80 MB.
pub(super) const MAX_NAME_BYTES: usize = 4 << 20;
/// Every signature field the walk reads ([`walk_sig_fields`] has its caps), depth first in
/// `/Fields` order.
pub(super) fn sig_fields(doc: &Document) -> Vec<Field> {
walk_sig_fields(doc).0
}
/// [`sig_fields`], and whether the walk read the whole form. It did not when a cap stopped it, a
/// field that is or holds a signature field was passed over for its name, a signature had no named
/// field to be listed under (a signed field without a usable /T, or a kid without one claiming a
/// signature its field doesn't have), or the form or its `/Fields` was there but of the wrong type:
/// a field it did not read may be signed, or claim one of the widgets listed.
///
/// Kids share their parent's name instead of each copying it. A kid with no /T but kids of its own
/// is a field all the same, which adds nothing to the names below it. A widget is listed under every field
/// that lists it, so two claims on one widget stay visible, and it is copied once. A field taken
/// by reference is taken where the walk first reaches it; one written in place in an indirect
/// array is queued once, however many fields list that array.
pub(crate) fn walk_sig_fields(doc: &Document) -> (Vec<Field>, bool) {
let mut out = Vec::new();
let Some(root) = doc.root() else { return out };
let Some(af) = doc.get(root).as_dict().and_then(|c| c.get(b"AcroForm").map(|a| doc.resolve(a))).and_then(|a| a.as_dict().cloned()) else {
return out;
};
let Some(fields) = af.get(b"Fields").map(|f| doc.resolve(f)).and_then(|f| f.as_array().cloned()) else { return out };
let Some(root) = doc.root() else { return (out, true) };
// A form that isn't there holds no fields; one that is there but isn't a dictionary may hold any.
let Some(form) = doc.get(root).as_dict().and_then(|c| c.get(b"AcroForm")).map(|a| doc.resolve(a)) else { return (out, true) };
let Some(af) = form.as_dict() else { return (out, matches!(*form, Object::Null)) };
let Some(top) = af.get(b"Fields") else { return (out, true) };
let (mut fields_left, mut entries_left, mut names_left, mut whole) = (MAX_FIELDS, MAX_ENTRIES, MAX_NAME_BYTES, true);
// Fields by reference, and by slot those written in place in an indirect array.
let mut seen = HashSet::new();
let mut stack: Vec<(Object, String, Option<Vec<u8>>)> = fields.into_iter().rev().map(|f| (f, String::new(), None)).collect();
while let Some((o, prefix, inherited_ft)) = stack.pop() {
let mut copies: HashMap<(ObjRef, Option<usize>), Rc<Dict>> = HashMap::new();
let unnamed: Rc<str> = Rc::from("");
let mut stack: Vec<(Object, Rc<str>, bool)> = Vec::new();
let fields = doc.resolve(top);
if !matches!(*fields, Object::Null | Object::Array(_)) {
return (out, false);
}
for (i, f) in fields.as_array().into_iter().flatten().enumerate() {
if !take(&mut entries_left) {
whole = false;
break;
}
// A field written in place here is marked, so one that also lists this array as its /Kids
// does not walk it again.
if let Some(s) = slot(f, top.as_ref(), i) {
seen.insert(s);
}
if !take(&mut fields_left) {
whole = false;
break;
}
stack.push((f.clone(), unnamed.clone(), false));
}
stack.reverse();
while let Some((o, prefix, inherited_sig)) = stack.pop() {
if let Some(r) = o.as_ref()
&& !seen.insert(r)
&& !seen.insert((r, None))
{
continue;
}
let Some(d) = doc.resolve(&o).as_dict().cloned() else { continue };
let part = text(doc, &d, b"T");
let name = match (&part, prefix.is_empty()) {
(Some(p), true) => p.clone(),
(Some(p), false) => format!("{prefix}.{p}"),
(None, _) => prefix.clone(),
};
let ft = d.name(b"FT").map(<[u8]>::to_vec).or(inherited_ft);
let kids: Vec<Object> = d.get(b"Kids").map(|k| doc.resolve(k)).and_then(|k| k.as_array().cloned()).unwrap_or_default();
// Kids with a /T are fields; others are this field's widgets.
let (sub, widgets): (Vec<Object>, Vec<Object>) = kids.into_iter().partition(|k| doc.resolve(k).as_dict().is_some_and(|kd| kd.contains(b"T")));
for k in sub.into_iter().rev() {
stack.push((k, name.clone(), ft.clone()));
let sig = d.name(b"FT").map_or(inherited_sig, |ft| ft == b"Sig");
// Passed over for its name, a leaf of another type hides no signature: it is none, and
// has no kids to hold one.
let hides = sig || d.contains(b"Kids");
// Even as UTF-16, a name within the cap takes at most twice its length plus a two-byte
// mark. A /T stored in more is passed over undecoded, whatever it would trim to: a long
// string named by many fields would otherwise be decoded once for each.
let stored = d.get(b"T").map(|t| doc.resolve(t)).map_or(0, |t| match &*t {
Object::String(s) => s.bytes.len(),
Object::Name(n) => n.len(),
_ => 0,
});
if stored > 2 * MAX_FIELD_NAME_BYTES + 2 {
whole &= !hides;
continue;
}
if ft.as_deref() == Some(b"Sig") && part.is_some() {
let mut ws: Vec<(Option<ObjRef>, Dict)> =
widgets.iter().filter_map(|w| doc.resolve(w).as_dict().cloned().map(|wd| (w.as_ref(), wd))).collect();
if d.name(b"Subtype") == Some(b"Widget") {
ws.insert(0, (o.as_ref(), d.clone()));
let part = text(doc, &d, b"T");
let name: Rc<str> = match (&part, prefix.is_empty()) {
(Some(p), true) => p.as_str().into(),
(Some(p), false) => format!("{prefix}.{p}").into(),
(None, _) => prefix,
};
if name.len() > MAX_FIELD_NAME_BYTES {
whole &= !hides;
continue;
}
let listed = sig && part.is_some();
// Signed, but with no name to be listed under: the signature is there all the same.
if sig && part.is_none() && holds_signature(doc, &d) {
whole = false;
}
let mut ws: Vec<(Option<ObjRef>, Rc<Dict>)> = Vec::new();
if listed && d.name(b"Subtype") == Some(b"Widget") {
ws.push((o.as_ref(), Rc::new(d.clone())));
}
let array = d.get(b"Kids").and_then(Object::as_ref);
let kids = d.get(b"Kids").map(|k| doc.resolve(k));
let mut sub = Vec::new();
for (i, k) in kids.as_deref().and_then(Object::as_array).into_iter().flatten().enumerate() {
if !take(&mut entries_left) {
whole = false;
break;
}
out.push(Field { name, r: o.as_ref(), dict: d, widgets: ws });
let resolved;
let kd = match k {
Object::Ref(r) => {
resolved = doc.get(*r);
resolved.as_dict()
}
direct => direct.as_dict(),
};
let Some(kd) = kd else { continue };
let at = slot(k, array, i);
// Kids with a /T are fields, and so are those with kids of their own; the others are
// this field's widgets.
if kd.contains(b"T") || kd.contains(b"Kids") {
if at.is_some_and(|s| !seen.insert(s)) {
continue;
}
if !take(&mut fields_left) {
whole = false;
continue;
}
sub.push(k.clone());
} else if listed {
// A widget signed apart from its field holds a signature nothing lists.
if holds_signature(doc, kd) && kd.get(b"V") != d.get(b"V") {
whole = false;
}
let w = match k.as_ref().map(|r| (r, None)).or(at) {
Some(key) => copies.entry(key).or_insert_with(|| Rc::new(kd.clone())).clone(),
None => Rc::new(kd.clone()),
};
ws.push((k.as_ref(), w));
} else if kd.name(b"FT") == Some(b"Sig") || holds_signature(doc, kd) {
// A signature field and its widget in one, with no name, under a field that isn't
// a signature field: nothing lists it, yet it may be signed.
whole = false;
}
}
for k in sub.into_iter().rev() {
stack.push((k, name.clone(), sig));
}
if listed {
let Some(left) = names_left.checked_sub(name.len()) else {
whole = false;
break;
};
names_left = left;
out.push(Field { name: name.to_string(), r: o.as_ref(), dict: d, widgets: ws });
}
}
out
(out, whole)
}
/// The slot of an entry written in place in an indirect array, which tells it apart when several
/// fields list that array. An entry by reference, or in a direct array (one owner), has none.
fn slot(entry: &Object, array: Option<ObjRef>, i: usize) -> Option<(ObjRef, Option<usize>)> {
array.filter(|_| entry.as_ref().is_none()).map(|a| (a, Some(i)))
}
/// Whether `d`'s own /V is a signature dictionary.
fn holds_signature(doc: &Document, d: &Dict) -> bool {
d.get(b"V").is_some_and(|v| doc.resolve(v).as_dict().is_some())
}
/// Take one from a budget; false once it is spent.
fn take(left: &mut usize) -> bool {
let some = *left > 0;
*left = left.saturating_sub(1);
some
}
/// Which page holds each annotation.
@@ -253,11 +404,25 @@ fn annot_pages(doc: &Document) -> HashMap<ObjRef, usize> {
map
}
/// Whether a signature widget is shown on its page: it isn't Hidden (`/F` bit 2) or NoView (bit 6),
/// as the forms crate reads a widget's flags, and its `/Rect` is four finite numbers whose box,
/// corners in either order, is wider and taller than half a point. The page badge
/// ([`SignatureInfo::visible`]) and the redrawn status layers ([`crate::show_status_layers`]) both
/// go by it, so they never disagree about a widget.
pub(crate) fn widget_shown(doc: &Document, widget: &Dict) -> bool {
let flags = widget.get(b"F").and_then(|o| doc.resolve(o).as_int()).unwrap_or(0);
let spans = |a: f64, b: f64| (a - b).abs() > 0.5;
flags & (2 | 32) == 0
&& nums(doc, widget, b"Rect").is_some_and(|r| r.len() == 4 && r.iter().all(|v| v.is_finite()) && spans(r[0], r[2]) && spans(r[1], r[3]))
}
pub(super) fn nums(doc: &Document, d: &Dict, key: &[u8]) -> Option<Vec<f64>> {
doc.resolve(d.get(key)?).as_array().map(|a| a.iter().filter_map(|x| doc.resolve(x).as_f64()).collect())
}
/// List and validate every signature field. `bytes` is the file as stored (the ranges index it).
/// A form not read whole ([`walk_sig_fields`]) gets one more row, signed and of unknown validity,
/// for the fields not read: any of them may be signed, so the document still counts as signed.
pub fn list(doc: &Document, bytes: &[u8], trust: &TrustStore) -> Vec<SignatureInfo> {
list_cached(doc, bytes, trust, &DigestCache::default())
}
@@ -268,7 +433,8 @@ pub fn list_cached(doc: &Document, bytes: &[u8], trust: &TrustStore, cache: &Dig
let pages = annot_pages(doc);
let mut out = Vec::new();
let mut field_values: HashSet<ObjRef> = HashSet::new();
for f in sig_fields(doc) {
let (fields, whole) = walk_sig_fields(doc);
for f in fields {
if let Some(v_ref) = f.dict.get(b"V").and_then(Object::as_ref) {
field_values.insert(v_ref);
}
@@ -278,10 +444,7 @@ 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])]);
// 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 visible = widget.is_some_and(|(_, w)| widget_shown(doc, w));
let v = f.signature(doc);
let mut info = SignatureInfo {
field: f.name.clone(),
@@ -308,6 +471,7 @@ pub fn list_cached(doc: &Document, bytes: &[u8], trust: &TrustStore, cache: &Dig
timestamp_time: None,
status: Status::Unknown,
modification: Modification::None,
verdict_shown: false,
details: Vec::new(),
};
if let Some(v) = v {
@@ -351,14 +515,54 @@ pub fn list_cached(doc: &Document, bytes: &[u8], trust: &TrustStore, cache: &Dig
timestamp_time: None,
status: Status::Unknown,
modification: Modification::None,
verdict_shown: false,
details: Vec::new(),
};
validate_doc_timestamp(doc, bytes, d, &mut info, cache, trust);
out.push(info);
}
if !whole {
out.push(unread_fields());
}
out
}
/// The row [`list_cached`] adds for the fields a walk cut short did not read ([`walk_sig_fields`]).
/// Any of them may be signed, so the row is signed, of unknown validity: the document still counts
/// as signed, and nothing rewrites it in full.
fn unread_fields() -> SignatureInfo {
SignatureInfo {
field: "UnreadFields".to_string(),
signed: true,
page: None,
rect: None,
visible: false,
signer: None,
certificate: None,
chain: Vec::new(),
date: None,
signing_time: None,
reason: None,
location: None,
contact: None,
sub_filter: None,
doc_timestamp: false,
certify: None,
revision: 0,
signed_len: 0,
digest: None,
algorithm: None,
timestamp: false,
timestamp_time: None,
status: Status::Unknown,
modification: Modification::None,
verdict_shown: false,
details: vec![Detail::plain(
"This form has too many fields, or a field name too long, for PdfCraft to read them all. Any signature among the rest is not listed, so the document is treated as signed.",
)],
}
}
fn page_index(doc: &Document, p: ObjRef) -> Option<usize> {
pdfcraft_annot::page_refs(doc).ok()?.iter().position(|r| *r == p)
}
+63 -2
View File
@@ -1,4 +1,4 @@
use super::listing::{mk_rotation, nums, sig_fields};
use super::listing::{mk_rotation, nums, sig_fields, text, walk_sig_fields};
use super::{Certificate, Dict, DigestAlg, DigitalId, Document, HashSet, Object, PdfString, SaveOptions, SignError, SignedData, Stream};
// ── signing ─────────────────────────────────────────────────────────────────────────────────
@@ -119,14 +119,44 @@ fn check_signing_permissions(doc: &Document, opts: &SignOptions) -> Result<(), S
/// Placeholder `/ByteRange` values: fixed width, patched after writing.
const BR_MARK: [i64; 3] = [1_111_111_111, 2_222_222_222, 3_333_333_333];
/// Whether `doc` already holds a signature or a document timestamp: a signature dictionary whose
/// `/Contents` holds a nonzero byte (a field whose `/V` has an empty or zero-filled `/Contents`
/// is not signed yet). A signature field without a name (`/T`) counts too: indirect signature
/// dictionaries and document timestamps are found in one pass over the file (by `/ByteRange`,
/// or as timestamps), not through the field tree.
pub fn has_signatures(doc: &Document) -> bool {
let signed = |d: &Dict| {
let contents = d.get(b"Contents").map(|c| doc.resolve(c));
// Hex strings decode to the DER when parsed; a literal string carries hex text.
let der = contents
.as_deref()
.and_then(Object::as_string)
.and_then(|s| if s.hex { Some(s.bytes.clone()) } else { super::validate::unhex(&s.bytes) });
der.is_some_and(|der| der.iter().any(|b| *b != 0))
};
sig_fields(doc).iter().any(|f| f.dict.get(b"V").map(|v| doc.resolve(v)).as_deref().and_then(Object::as_dict).is_some_and(signed))
|| doc
.scan_objects()
.any(|(_, o)| o.as_dict().is_some_and(|d| (d.contains(b"ByteRange") || super::validate::is_doc_timestamp(d)) && signed(d)))
}
/// Sign `doc` with `id`; returns the signed file (an incremental update when possible).
///
/// The document's first signature (no [`has_signatures`]) removes the AcroForm's
/// `/NeedAppearances` flag: Acrobat does not recognise a signature while it is set. Later
/// signatures leave the flag as it is. This function draws no field appearances: once the flag is
/// gone, viewers show each field's stored normal appearance (`/AP /N`), so a filled field whose
/// stored appearance draws no text (an empty placeholder such as `/Tx BMC EMC`, or a look left
/// from an earlier value) shows that instead of its value. A caller that wants the values kept
/// draws the fields first, as `Session::sign` in the engine does.
pub fn sign(doc: &Document, id: &DigitalId, opts: &SignOptions) -> Result<Vec<u8>, SignError> {
sign_inner(doc, id, opts, None)
}
/// Sign and embed an RFC 3161 signature timestamp from `tsa` (PAdES B-T). The transport is the
/// caller's: this crate never opens a socket, and a rejected or malformed token fails the
/// signing before any file is produced.
/// signing before any file is produced. The form's `/NeedAppearances` flag is handled as in
/// [`sign`].
pub fn sign_with_timestamp(
doc: &Document,
id: &DigitalId,
@@ -153,6 +183,7 @@ fn sign_inner(
}
check_signing_permissions(doc, opts)?;
let mut doc = doc.clone();
let earlier_signatures = has_signatures(&doc);
let root = doc.root().ok_or_else(|| SignError::Pdf("the document has no catalog".into()))?;
let alg = id.key.preferred_digest();
let reserve =
@@ -232,6 +263,10 @@ fn sign_inner(
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(&fname));
// The walk lists no field without a usable name, and counts a signed one as unread.
if text(&doc, &w, b"T").is_none() {
return Err(SignError::Pdf("a signature field needs a name that isn't blank".into()));
}
w.set(b"V".to_vec(), Object::Ref(sig));
w.set(b"Rect".to_vec(), Object::Array(rect.iter().map(|x| Object::Real(*x)).collect()));
w.set(b"P".to_vec(), Object::Ref(page));
@@ -280,6 +315,14 @@ 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)))?,
}
// The walk has to read the whole form, the new field included: past its caps the
// signature would be listed as unread fields, and its name could repeat an unread one.
if !walk_sig_fields(&doc).1 {
return Err(SignError::Pdf(
"this form has too many fields, or a field name too long, for PdfCraft to read them all, so it can't add a signature field"
.into(),
));
}
(wr, rect, turn)
}
};
@@ -293,6 +336,24 @@ fn sign_inner(
doc.update_dict(r, |af| af.set(b"SigFlags".to_vec(), Object::Int(3)))?;
}
}
// Acrobat does not recognise a signature in a form that asks viewers to redraw its fields
// (`/NeedAppearances true`): redrawing would change what the signature covers. The first
// signature drops the flag; a later one leaves it, as removing it would count as a change
// to the earlier signatures. Without the flag viewers draw each field's stored `/AP /N`, so
// a filled field whose stored appearance draws no text (an empty placeholder, or a stale
// look) shows that instead of its value unless the caller drew the fields first (see `sign`).
if !earlier_signatures {
if let Some(Object::Ref(r)) = doc.get(root).as_dict().and_then(|c| c.get(b"AcroForm").cloned()) {
doc.update_dict(r, |af| {
af.remove(b"NeedAppearances");
})?;
}
doc.update_dict(root, |c| {
if let Some(Object::Dict(af)) = c.get_mut(b"AcroForm") {
af.remove(b"NeedAppearances");
}
})?;
}
// The appearance.
let ap = appearance(&mut doc, rect, turn, &name, &id.certificate, opts)?;
let ap_ref = doc.add(Object::Stream(ap));
+3 -1
View File
@@ -13,7 +13,7 @@ impl TrustStore {
}
/// Acrobat's three verdicts.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Status {
/// Intact, signed by a trusted identity, and any later changes are permitted.
Valid,
@@ -217,6 +217,8 @@ pub const WORDINGS: &[&str] = &[
"The document has been altered since this timestamp was applied in ways it does not permit ({}).",
"The timestamp token is valid and its authority is trusted.",
"The timestamp token is valid, but the timestamp authority is not in your list of trusted certificates.",
// What the list itself could not read.
"This form has too many fields, or a field name too long, for PdfCraft to read them all. Any signature among the rest is not listed, so the document is treated as signed.",
// The one line that stands for all of it.
"Unsigned signature field",
"Signature is valid",
+1 -1
View File
@@ -26,7 +26,7 @@ pub fn validate(doc: &Document, bytes: &[u8], trust: &TrustStore, field: &str) -
list(doc, bytes, trust).into_iter().find(|s| s.field == field)
}
fn unhex(s: &[u8]) -> Option<Vec<u8>> {
pub(super) fn unhex(s: &[u8]) -> Option<Vec<u8>> {
let digits: Vec<u8> = s.iter().copied().filter(|c| !c.is_ascii_whitespace()).collect();
let val = |c: u8| (c as char).to_digit(16).map(|d| d as u8);
digits.chunks(2).map(|p| Some(val(p[0])? << 4 | p.get(1).map_or(Some(0), |c| val(*c))?)).collect()
Loaded 100 of 134 files, more files were not shown because too many files have changed in this diff. Show more