mirror of
https://github.com/storytold/pdfcraft.git
synced 2026-12-05 19:51:56 -05:00
Merge remote-tracking branch 'origin/main' into pr-6984
# Conflicts: # crates/automation/tests/it/automation.rs # crates/engine/src/edit/run.rs # crates/engine/src/open.rs # crates/engine/src/session/editing.rs # crates/engine/src/tests.rs # crates/engine/src/xfa.rs # crates/engine/src/xfa_form.rs # parity/acrobat-features.toml
This commit is contained in:
@@ -2,16 +2,19 @@
|
||||
# (GitHub has no FreeBSD runners). GPU tests skip themselves when the VM has no adapter.
|
||||
name: FreeBSD
|
||||
|
||||
# The VM build is slow, so it runs nightly on main and on pushes to `release`, not on every push
|
||||
# or dependency change: a drifted dependency still shows up within a day, and always before a
|
||||
# release ships. PRs that change the FreeBSD packaging itself still run it.
|
||||
on:
|
||||
schedule:
|
||||
- cron: "27 3 * * *"
|
||||
push:
|
||||
branches: [main]
|
||||
branches: [release]
|
||||
pull_request:
|
||||
paths:
|
||||
- Cargo.toml
|
||||
- Cargo.lock
|
||||
- "**/Cargo.toml"
|
||||
- .github/workflows/freebsd.yml
|
||||
- packaging/freebsd/**
|
||||
- packaging/env.sh
|
||||
workflow_dispatch:
|
||||
|
||||
concurrency:
|
||||
@@ -27,3 +30,4 @@ jobs:
|
||||
uses: storytold/craft-common-actions/.github/workflows/freebsd.yml@main
|
||||
with:
|
||||
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
|
||||
cargo-test-extra-args: --no-fail-fast
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
name: Notify Services on Release Change
|
||||
|
||||
on:
|
||||
release:
|
||||
types:
|
||||
- published
|
||||
- unpublished
|
||||
- created
|
||||
- edited
|
||||
- deleted
|
||||
- prereleased
|
||||
- released
|
||||
|
||||
permissions: {}
|
||||
|
||||
jobs:
|
||||
notify:
|
||||
uses: storytold/craft-common-actions/.github/workflows/notify-services.yml@main
|
||||
secrets:
|
||||
ARTCRAFT_SERVICES_DISPATCH_TOKEN: ${{ secrets.ARTCRAFT_SERVICES_DISPATCH_TOKEN }}
|
||||
@@ -3,19 +3,17 @@
|
||||
# run the test suite natively on ARM64.
|
||||
name: Windows ARM64
|
||||
|
||||
# Nightly on main and on pushes to `release` (dependency and runner-image drift shows up within a
|
||||
# day, and always before a release ships), and on PRs that change the Windows packaging itself.
|
||||
on:
|
||||
schedule:
|
||||
- cron: "43 5 * * *"
|
||||
push:
|
||||
branches: [main]
|
||||
branches: [release]
|
||||
pull_request:
|
||||
paths:
|
||||
- Cargo.toml
|
||||
- Cargo.lock
|
||||
- "**/Cargo.toml"
|
||||
- "**/build.rs"
|
||||
- .github/workflows/windows-arm64.yml
|
||||
- packaging/windows/**
|
||||
schedule:
|
||||
- cron: "41 4 * * 1" # weekly, so drift in the runner images shows up
|
||||
workflow_dispatch:
|
||||
|
||||
concurrency:
|
||||
|
||||
+2
-1
@@ -4,7 +4,7 @@
|
||||
|
||||
Every asset PdfCraft includes, bundles or uses to build its published material, with its author, source and licence. The policy is in [AGENTS.md](AGENTS.md) §1. The machine-readable list, with the SHA-256 of every asset, is [ATTRIBUTION.toml](ATTRIBUTION.toml). Licence texts are kept beside the assets and summarised in [NOTICE](NOTICE).
|
||||
|
||||
## In this repository (136)
|
||||
## In this repository (137)
|
||||
|
||||
| Asset | Title | Author | Licence | Source | Used for |
|
||||
|---|---|---|---|---|---|
|
||||
@@ -50,6 +50,7 @@ Every asset PdfCraft includes, bundles or uses to build its published material,
|
||||
| `assets/icons/film.svg` | Lucide icon "film" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/film.svg) | UI icon, embedded via crates/ui-egui/src/icons.rs |
|
||||
| `assets/icons/filter.svg` | Lucide icon "filter" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/filter.svg) | UI icon, embedded via crates/ui-egui/src/icons.rs |
|
||||
| `assets/icons/folder-plus.svg` | Lucide icon "folder-plus" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/folder-plus.svg) | UI icon, embedded via crates/ui-egui/src/icons.rs |
|
||||
| `assets/icons/freehand-highlighter.svg` | Freehand highlighter | Combiler01 | CC0-1.0 | https://github.com/Combiler01/pdfcraft/blob/e41d774aaad35956985cd084b781a4c4b9e41587/assets/icons/freehand-highlighter.svg | UI icon, embedded via crates/ui-egui/src/icons.rs |
|
||||
| `assets/icons/git-compare.svg` | Lucide icon "git-compare" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/git-compare.svg) | UI icon, embedded via crates/ui-egui/src/icons.rs |
|
||||
| `assets/icons/hash.svg` | Lucide icon "hash" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/hash.svg) | UI icon, embedded via crates/ui-egui/src/icons.rs |
|
||||
| `assets/icons/heading.svg` | Lucide icon "heading" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/heading.svg) | UI icon, embedded via crates/ui-egui/src/icons.rs |
|
||||
|
||||
@@ -472,6 +472,17 @@ kind = "icon"
|
||||
usage = "UI icon, embedded via crates/ui-egui/src/icons.rs"
|
||||
sha256 = "76d62eb7796ce6c7e303c437464923de2d1ae19a5c8d010f8b36dfc1d6180890"
|
||||
|
||||
[[asset]]
|
||||
path = "assets/icons/freehand-highlighter.svg"
|
||||
title = "Freehand highlighter"
|
||||
author = "Combiler01"
|
||||
source = "https://github.com/Combiler01/pdfcraft/blob/e41d774aaad35956985cd084b781a4c4b9e41587/assets/icons/freehand-highlighter.svg"
|
||||
licence = "CC0-1.0"
|
||||
licence_file = "assets/icons/LICENSE-freehand-highlighter.txt"
|
||||
kind = "icon"
|
||||
usage = "UI icon, embedded via crates/ui-egui/src/icons.rs"
|
||||
sha256 = "6198c9cbdb182132b00ad25e8782ac7c7d237d0736c1d1c1f2f94dd6b8b87132"
|
||||
|
||||
[[asset]]
|
||||
path = "assets/icons/git-compare.svg"
|
||||
title = "Lucide icon \"git-compare\""
|
||||
|
||||
Generated
+9
-8
@@ -336,9 +336,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "async-executor"
|
||||
version = "1.14.0"
|
||||
version = "1.14.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c96bf972d85afc50bf5ab8fe2d54d1586b4e0b46c97c50a0c9e71e2f7bcd812a"
|
||||
checksum = "f426a31126c735126297bc5ea7a521263c9faff4f63ca415267ee625651c4f37"
|
||||
dependencies = [
|
||||
"async-task",
|
||||
"concurrent-queue",
|
||||
@@ -1136,9 +1136,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "clipboard-win"
|
||||
version = "5.4.1"
|
||||
version = "5.4.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "bde03770d3df201d4fb868f2c9c59e66a3e4e2bd06692a0fe701e7103c7e84d4"
|
||||
checksum = "052af7878466feccda12ba7a6a67d019d712f296809559b47c12c8cc196d3a9a"
|
||||
dependencies = [
|
||||
"error-code",
|
||||
]
|
||||
@@ -3669,9 +3669,9 @@ checksum = "aa9a19cbb55df58761df49b23516a86d432839add4af60fc256da840f66ed35b"
|
||||
|
||||
[[package]]
|
||||
name = "form_urlencoded"
|
||||
version = "1.2.2"
|
||||
version = "1.2.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf"
|
||||
checksum = "afa489199eaffb1211795df1c6236ce1ad0d41a6fa45250add73e3b02420f06e"
|
||||
dependencies = [
|
||||
"percent-encoding",
|
||||
]
|
||||
@@ -6512,6 +6512,7 @@ dependencies = [
|
||||
"hayro-syntax",
|
||||
"pdfcraft-content",
|
||||
"pdfcraft-cos",
|
||||
"pdfcraft-model",
|
||||
"pdfcraft-oracle",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
@@ -9486,9 +9487,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "url"
|
||||
version = "2.5.8"
|
||||
version = "2.5.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed"
|
||||
checksum = "f00cd2407bb42c0ef17be88d4cf020f5cceffd121665bac9b8b9493a369b3b1a"
|
||||
dependencies = [
|
||||
"form_urlencoded",
|
||||
"idna",
|
||||
|
||||
+6
-1
@@ -16,7 +16,7 @@ sha256 = "cd7032ea33b71427f188e34ffb4aee9d6868a57fd196037c5c8b2be03a2a0352"
|
||||
[[document]]
|
||||
source = "NOTICE"
|
||||
destination = "NOTICE"
|
||||
sha256 = "ac29fe01fc951570ebda159bc84b17f12129e3f0800c36759e2f4829c10d8685"
|
||||
sha256 = "c0cd7347f4c596dc01ac7fdc4aca323b6ba97385eb399bc5dd40e460bacf247d"
|
||||
|
||||
[[document]]
|
||||
source = "vendor/edit-session/LICENSE-MIT"
|
||||
@@ -55,6 +55,11 @@ source = "assets/fonts/OFL-JetBrainsMono.txt"
|
||||
destination = "assets/fonts/OFL-JetBrainsMono.txt"
|
||||
sha256 = "a76abf002c49097d146e86740a3105a5d00450b1592e820a1109a8c5680cd697"
|
||||
|
||||
[[document]]
|
||||
source = "assets/icons/LICENSE-freehand-highlighter.txt"
|
||||
destination = "assets/icons/LICENSE-freehand-highlighter.txt"
|
||||
sha256 = "83cba0ac883f6ef4866e457536bf58727a5702ebf6e7b407579e4f1863ca4c7d"
|
||||
|
||||
[[document]]
|
||||
source = "assets/icons/LICENSE-lucide.txt"
|
||||
destination = "assets/icons/LICENSE-lucide.txt"
|
||||
|
||||
@@ -14,11 +14,12 @@ Third-party material
|
||||
This product bundles third-party material under its own licenses, listed below. The per-file
|
||||
list (author, source, license) is in ATTRIBUTION.md.
|
||||
|
||||
- Lucide icons (assets/icons/*.svg) — ISC and MIT licences (Feather-derived icons). See assets/icons/LICENSE-lucide.txt.
|
||||
- Lucide icons (assets/icons/*.svg, except freehand-highlighter.svg) — ISC and MIT licences (Feather-derived icons). See assets/icons/LICENSE-lucide.txt.
|
||||
The Windows PDF file icon (assets/app-icon/pdfcraft-document.svg and .ico) adapts Lucide's
|
||||
file-text outline and combines it with contributor-original artwork. See
|
||||
assets/app-icon/LICENSE-document.txt (ISC AND (MIT OR Apache-2.0)), packaged as
|
||||
LICENSE-document.txt beside the Windows executables.
|
||||
- Freehand highlighter icon (assets/icons/freehand-highlighter.svg) — CC0-1.0, Combiler01. See assets/icons/LICENSE-freehand-highlighter.txt.
|
||||
- Inter typeface (assets/fonts/Inter-*.ttf) — SIL Open Font License 1.1. See assets/fonts/OFL-Inter.txt.
|
||||
- JetBrains Mono typeface (assets/fonts/JetBrainsMono-*.ttf) — SIL Open Font License 1.1. See assets/fonts/OFL-JetBrainsMono.txt.
|
||||
- Dancing Script typeface (assets/fonts/DancingScript.ttf), Copyright 2016 The Dancing Script Project Authors — SIL Open Font License 1.1 (Reserved Font Name "Dancing Script"). See assets/fonts/OFL-DancingScript.txt.
|
||||
|
||||
@@ -5,6 +5,8 @@
|
||||
- 2026-11-04 (M6, PR #5699 reset estimate): Charge expanded-name scans and field-name copy/comparison bytes; add three negative regressions and byte-exact refusal checks.
|
||||
# PdfCraft roadmap
|
||||
|
||||
> **Last reviewed:** 2026-11-04 | **Last updated:** 2026-11-04 | **Change:** minor (M7: paragraph boundaries respect row typography and page-wide filled panels; estimates unchanged)
|
||||
|
||||
> **Last reviewed:** 2026-11-16 | **Last updated:** 2026-11-16 | **Change:** patch (M5 #3741: Ctrl+M opens Comments on Windows/Linux without toggling it closed; macOS leaves Command+M for Minimize; platform-specific shortcut surfaces and regressions retained; estimates unchanged)
|
||||
|
||||
> **Last reviewed:** 2026-11-15 | **Last updated:** 2026-11-15 | **Change:** minor (craft-libs cutover for codecs, XFA XML, crypt/filters/COS/export/XFDF, PRC and ZIP; print colour management for pictures; M7 line replacement keeps source fonts; auto-tag headings by size and weight; arrow-key comment moves; stream-filter JPEG export; form, signature, optimize, redaction, measurement, PRC-normal and CMYK fixes; v0.21.1 Flatpak fix; estimates unchanged)
|
||||
@@ -264,6 +266,9 @@ 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-16 (M4, Insert from File):** Catalog attachments come along with inserted pages in the same undo step. Existing attachments and destination name trees stay; duplicate UTF-16 keys keep their encoding. Generated engine regressions cover save/undo/redo and failed-batch rollback. Estimates unchanged.
|
||||
|
||||
- **2026-11-18 (M7, #7687):** PDF-page watermarks clip the source CropBox to MediaBox before sizing and rotating the imported form. Synthetic geometry and save/reopen render regressions cover oversized and partially overlapping crops; estimates unchanged.
|
||||
|
||||
- **2026-11-16 (M5, #3741):** Ctrl+M opens Comments on Windows/Linux and repeated activation keeps it open. macOS leaves Command+M unbound for Minimize. Dispatch, menus, palette, shortcut help and control/headless metadata resolve the platform-specific registry binding. Mapping and real-input regressions are retained through the rebase; estimates unchanged.
|
||||
- **2026-11-03 (M3, #3669):** A drag across a table selects its rows, as Preview does, instead of reading order's detour down each column; a cell padded with spaces reads with the next cell of its row. Synthetic render and UI drag regressions; estimates unchanged.
|
||||
@@ -301,6 +306,8 @@ Ranked; detail and the full milestone table in [docs/roadmap.md](docs/roadmap.md
|
||||
- **2026-10-28 (M10, #4119 partial):** Scan & OCR ▸ Enhance scanned file cleans scanned pages in place: background removal (level 0–100, as the camera clean-up), edge shadow removal (book gutters, copier borders) and despeckle. Each scan image is decoded, cleaned and written back into its own object at the same size and colour space (JPEG stays JPEG, others lossless, 1-bit stays 1-bit), so the OCR text layer, comments and links stay; one undo step, shared images once, unsupported images (CMYK, indexed, JPEG 2000, JBIG2, CCITT, broken data) reported. `page_enhance_scan` drives it headlessly. Not yet an option of Recognize text. Estimates unchanged.
|
||||
- **2026-11-07 (M10, `ocr.ocr-web`, port onto #977):** Web OCR rebuilt on main's engines and preprocessing (#977). `OcrJob::run` is now `OcrJob::steps` a page at a time: the page renders, crops to the region and cleans each page, a Web Worker runs ocrs on the result, and `OcrShot::place` maps the words back through the region and preprocessing. Every strategy reads like this when only one engine is present, and the web build has only ocrs. The downloaded models are installed into the engine cache (`ocr::install`), so the Verify screen and the engine-status checks see them too. The batch keeps main's skipped-files bucket, low-confidence notes and cancel. The translations moved to craft-i18n (storytold/craft-i18n#141). The Verify screen starts the model download itself and runs once the models land; before, on a fresh page it failed with the desktop's "set PDFCRAFT_MODELS" message. Known limits: the cleaning steps, and the Verify screen's Run OCR and re-reads, run on the page. Estimates unchanged.
|
||||
|
||||
- **2026-11-04 (M7, paragraph boundaries):** Editable paragraphs separate across large row-size changes, font-family changes and filled rectangular panel boundaries, while compatible multiline text and inline style runs stay together. Panel identity is page-wide across content streams and transformed form invocations; rectangle construction/fill splits retain their transforms and path semantics. Synthetic regressions cover isolated-panel edits through save/reopen and preserve the delayed-background rewrite checks for #2377. Estimates unchanged.
|
||||
|
||||
- **2026-11-03 (M11, shared JBIG2 dictionary):** With Monochrome Images set to JBIG2, Optimize has up to 16 JBIG2 images share one symbol dictionary (`/JBIG2Globals`), the letters found on more than one page stored once, when that is smaller (`pdfcraft_filters::encode_jbig2_shared`). Eight pages of 10 pt text rendered at 300 dpi take 41% less in Helvetica and 42% in Times than coded alone, 10% in Courier; groups of 16 save 45%, of 32 only 47%. Only images redaction can store again without the dictionary share one (image masks and DeviceGray named directly, at most 64 Mi pixels), and redacting one stores the rest of its group so, which the group bounds to 15.
|
||||
|
||||
- **2026-11-03 (M5, #5850 review):** Resolve indirect IT when recognizing typewriter contents and Fill & Sign marks. Comment listing and property lookup retain their existing direct-Subtype behavior. A real double-click Edit composer preserves the typewriter’s text as written; ordinary comment edits keep trimming. Regressions cover direct Subtype with indirect intent, save/reopen, raw posted contents and same-index comments on different pages. The existing live-movement test now commits its setup with an outside click rather than Enter. Estimates unchanged.
|
||||
@@ -405,6 +412,7 @@ Ranked; detail and the full milestone table in [docs/roadmap.md](docs/roadmap.md
|
||||
|
||||
- **2026-10-23 (M2, #234, continuation of #1567):** Reconciled installed CJK viewer fallback with current rendering changes; Windows preserves installed Song/Hei/Kai families and bounds font reads. GBK-EUC-H CIDFontType2 regression coverage includes text extraction; viewer fallback also survives reload with retained preferences. System fonts remain display-only. No overall readiness estimate changed.
|
||||
- **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-18 (M12, #3221 mutation safety):** Decorative and artifact actions refuse unsupported ownership before any mutation. This includes form streams, annotation or object references, references to other pages, invalid references and structure children. Synthetic tests check exact preservation, undo history and save/reopen. Artifact marking also rejects missing, ambiguous or mismatched parents before mutation, including indirect MCID ownership. Direct-library tests preserve clean and edited documents. Form editing and stream-aware readouts stay outside this fix. 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.
|
||||
@@ -425,6 +433,7 @@ Ranked; detail and the full milestone table in [docs/roadmap.md](docs/roadmap.md
|
||||
- **2026-10-13 (M10, OCR review, batch and two engines):** Scan & OCR gains a review step, a second engine and Unicode output. Recognition can clean the raster first (opt-in auto-rotate, deskew, denoise, binarize; word boxes map back to the scan) and read with the built-in ocrs engine, an installed tesseract program run as a fenced external process (a validated location that fails closed instead of falling back to the PATH, allow-listed languages, a private temp directory, timeout and output caps), or both: Automatic asks tesseract when the ocrs reading is weak or of unknown confidence, and a ROVER merge keeps the more confident word (an unscored ocrs word yields only to a tesseract word of 70 or more). The OCR Verify screen (Scan & OCR ▸ Correct recognized text) reviews a recognition before it is applied: confidence-coloured word boxes, corrections, a per-language user dictionary (a plain-text file in the preferences folder, so a word added from any document stays on disk after it closes), Re-OCR of a page or a region, Accept/Reject per page or whole. Pages accepted one by one each apply once; a region re-read moves the review marks of the words it keeps, and a whole-page re-read clears that page's marks (undoable in the panel). Output is searchable (an invisible layer, one undo step) or a NEW editable document of visible text. Words beyond WinAnsi are drawn in Type3 faces from craft-fonts with a ToUnicode map in the editable output (characters no bundled face has appear as '?'); the searchable layer writes them as Type3 fonts with empty character programs and a ToUnicode map, so extraction reads them back with no fonts and no substitutions; redaction removes that layer like any other text (tests in pdfcraft-redact; the end-to-end engine test needs the craft-fonts build input and is skipped without it). Batch runs skip pages that already have text unless forced, and skip whole files that have text only with the opt-in skip-files flag (off by default; Force OCR overrides both); they refuse two inputs of the same file name and existing outputs before reading anything, and report low-confidence pages at the settings' threshold. Headless: ocr_recognize (engine, strategy, preprocessing, region; the editable output goes to an `out` that must not exist yet, and `out` is refused for a searchable run), ocr_words, ocr_review_apply, ocr_dictionary, ocr_status and ocr_recognize_files. All 21 interface catalogs carry the new strings; the Lithuanian ones were added without native review. Reading with every cleaning step off passes the render through untouched, as on main (the 300 dpi normalization runs only when a cleaning step is on: enlarging a 72 dpi render 4x on its own made the models read "due: €250" as "ue: ?250"). Still missing: the deep scan clean-up options (descreen, background and edge-shadow removal), scan images in the editable output, matching the scanned typeface, and recognition quality beyond the tested English set.
|
||||
- **2026-10-13 (M10, #1757):** Office export keeps each dotted-leader contents entry in one paragraph, with its page number, instead of inferring table cells from its separate text objects.
|
||||
- **2026-10-22 (M6, calculation scripts):** The Calculate tab and a rename read simplified field notation only from a comment, where Acrobat writes it: a string that spells `BVCALC … EVCALC` is no longer taken for the notation, or rewritten by a rename. A `/` after the condition of `if`, `while`, `for` or `with` starts a regular expression, so a rename no longer rewrites a name inside one, and a quote inside one no longer hides the `getField` calls after it. Both found in review of #3550. A `//` comment ends at `\r`, U+2028 or U+2029 as well as `\n`, so in a script with `\r` line endings the code after one is no longer hidden from a rename, or taken for the notation. Estimates unchanged.
|
||||
- **2026-10-21 (M3, startup notification on Linux):** Opened from the menu or dock with `StartupNotify=true`, PdfCraft hands the launcher's activation token back from its first window (`XDG_ACTIVATION_TOKEN` on Wayland, `DESKTOP_STARTUP_ID` on X11). GNOME kept its busy cursor for 15 seconds after the window appeared, because eframe never gives winit the token, and the window opened without keyboard focus. Vendored winit patch 14, with unit tests of the policy (later windows don't reuse the spent token; an empty or oversized token is ignored). Checked by hand in a test build on GNOME 50 (Wayland): the busy cursor clears as the window appears, and the window has keyboard focus. Estimates unchanged.
|
||||
- **2026-10-20 (M6, calculation order page):** Prepare a form ▸ Calculation order, a page of its own, lists the calculated fields in the order they calculate with their formulas and values, moved with Up/Down arrows (as Acrobat's Set Field Calculation Order), Alt+↑/↓ or by dragging. A card says what is wrong with the order and holds Fix order; a loop has a card of its own that opens one of its formulas. On the page, each calculated field shows its step, and arrows show what the field in focus reads and what reads it. Estimates unchanged.
|
||||
- **2026-10-20 (M6, calculation order):** The order a form's fields calculate in (`/CO`) is read, checked, fixed and set headlessly with `form_calculation_order`: it says which fields read one calculated later (they show stale values), which read each other in a loop, and which the PDF's order leaves out; Fix order moves only what must move, in one undo step, and the form recalculates. Editing a formula no longer moves its field to the end of the order, and a field the order lists twice calculates once. Estimates unchanged.
|
||||
- **2026-10-20 (M2, #3574):** Forms without Resources use page Properties for ActualText and layer visibility. Synthetic tests cover boundaries, nested/shared forms, and save/reopen. Estimates unchanged.
|
||||
|
||||
@@ -8,8 +8,6 @@ use std::process::Command;
|
||||
use std::thread::JoinHandle;
|
||||
use std::time::Duration;
|
||||
|
||||
const TOKEN: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
|
||||
|
||||
/// A folder for one test, removed when the test ends.
|
||||
struct Scratch(PathBuf);
|
||||
|
||||
@@ -71,24 +69,12 @@ impl Spy {
|
||||
}
|
||||
}
|
||||
|
||||
/// Write a token file the way the app does: readable by the owner only.
|
||||
fn write_private(path: &Path, text: &str) {
|
||||
let mut opts = std::fs::OpenOptions::new();
|
||||
opts.write(true).create_new(true);
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::OpenOptionsExt;
|
||||
opts.mode(0o600);
|
||||
}
|
||||
opts.open(path).unwrap().write_all(text.as_bytes()).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_token_file_of_your_own_reaches_the_app() {
|
||||
let dir = scratch("own");
|
||||
let spy = spy();
|
||||
let token_file = dir.join("token");
|
||||
write_private(&token_file, TOKEN);
|
||||
let token = craft::automation::security::server_token(None, Some(&token_file)).unwrap();
|
||||
let o = Command::new(env!("CARGO_BIN_EXE_pdfcraft-cli"))
|
||||
.arg("ui")
|
||||
.arg("--control")
|
||||
@@ -100,5 +86,5 @@ fn a_token_file_of_your_own_reaches_the_app() {
|
||||
.unwrap();
|
||||
let received = spy.received();
|
||||
assert!(o.status.success(), "{}", String::from_utf8_lossy(&o.stderr));
|
||||
assert!(received.contains(TOKEN) && received.contains("ui.state"), "{received}");
|
||||
assert!(received.contains(&token) && received.contains("ui.state"), "the listener did not receive the fixture token and state request");
|
||||
}
|
||||
|
||||
@@ -38,7 +38,10 @@ fn main() {
|
||||
let files = craft::platform::browser_files::BrowserFiles::new(move || wake.wake())
|
||||
.limits(limits)
|
||||
.page_saves(craft_web_host::files::page_save);
|
||||
let app_host = craft::host::Host::builder(pdfcraft_ui_egui::APP_INFO).files(Arc::new(files)).build();
|
||||
let app_host = craft::host::Host::builder(pdfcraft_ui_egui::APP_INFO)
|
||||
.files(Arc::new(files))
|
||||
.i18n(pdfcraft_ui_egui::i18n::host_catalogs())
|
||||
.build();
|
||||
let mut app = PdfCraftApp::with_host(Arc::new(app_host), AppServices::system(&cc.egui_ctx, intake));
|
||||
app.apply_settings(&settings.get());
|
||||
app.attach_settings(settings);
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
//! vendor/winit patch (14) (vendor/README.md).
|
||||
|
||||
#[test]
|
||||
fn winit_hands_the_launchers_activation_token_back() {
|
||||
// A launcher with `StartupNotify=true` (the packaged desktop entry) passes an activation token
|
||||
// in `XDG_ACTIVATION_TOKEN` (Wayland) or `DESKTOP_STARTUP_ID` (X11) and shows a busy cursor
|
||||
// until a window hands it back. eframe never gives winit a token, so GNOME kept the busy
|
||||
// cursor for 15 seconds and the window opened without focus. vendor/winit gives the first
|
||||
// window the environment's token. The policy is tested beside it (`startup_token::tests`, run
|
||||
// them in the vendored crate); this guards the copy, which workspace tests don't test. A
|
||||
// re-vendored copy without the patch would silently bring the bug back: re-apply the patch, or
|
||||
// drop the copy once winit or eframe hands the token back.
|
||||
let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../..");
|
||||
let linux = root.join("vendor/winit/src/platform_impl/linux");
|
||||
let module = std::fs::read_to_string(linux.join("mod.rs")).unwrap();
|
||||
assert!(module.contains("mod startup_token;"));
|
||||
let (_, new) = module.split_once(" pub(crate) fn new(\n window_target: &ActiveEventLoop,").expect("Window::new moved");
|
||||
let new = new.split_once("\n }\n").map_or(new, |(body, _)| body);
|
||||
assert!(
|
||||
new.contains("startup_token::for_new_window(given, startup_notify::WAYLAND_VAR)"),
|
||||
"a Wayland window no longer takes the launcher's token"
|
||||
);
|
||||
assert!(new.contains("startup_token::for_new_window(given, startup_notify::X11_VAR)"), "an X11 window no longer takes the launcher's token");
|
||||
assert_eq!(new.matches("reservation.commit();").count(), 2, "a created window no longer spends the launcher's token");
|
||||
// The backends mark the token spent where they hand it back, so a window that fails earlier
|
||||
// releases it for a retry and one that fails later doesn't reuse it.
|
||||
for backend in ["wayland/window/mod.rs", "x11/window.rs"] {
|
||||
let source = std::fs::read_to_string(linux.join(backend)).unwrap();
|
||||
assert!(source.contains("startup_token::handing_back();"), "{backend} no longer marks the token spent at its handoff");
|
||||
}
|
||||
let policy = std::fs::read_to_string(linux.join("startup_token.rs")).unwrap();
|
||||
assert!(policy.contains("fn the_first_window_takes_the_launchers_token"));
|
||||
assert!(policy.contains("fn a_later_window_does_not_reuse_the_spent_token"));
|
||||
assert!(policy.contains("fn a_window_that_fails_before_handing_the_token_back_releases_it"));
|
||||
// The token reaches the app only when the launcher asks for startup notification.
|
||||
let desktop = std::fs::read_to_string(root.join("packaging/linux/ai.storyteller.pdfcraft.desktop")).unwrap();
|
||||
assert!(desktop.contains("StartupNotify=true"));
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
CC0 1.0 Universal
|
||||
|
||||
Statement of Purpose
|
||||
|
||||
The laws of most jurisdictions throughout the world automatically confer
|
||||
exclusive Copyright and Related Rights (defined below) upon the creator and
|
||||
subsequent owner(s) (each and all, an "owner") of an original work of
|
||||
authorship and/or a database (each, a "Work").
|
||||
|
||||
Certain owners wish to permanently relinquish those rights to a Work for the
|
||||
purpose of contributing to a commons of creative, cultural and scientific
|
||||
works ("Commons") that the public can reliably and without fear of later
|
||||
claims of infringement build upon, modify, incorporate in other works, reuse
|
||||
and redistribute as freely as possible in any form whatsoever and for any
|
||||
purposes, including without limitation commercial purposes. These owners may
|
||||
contribute to the Commons to promote the ideal of a free culture and the
|
||||
further production of creative, cultural and scientific works, or to gain
|
||||
reputation or greater distribution for their Work in part through the use and
|
||||
efforts of others.
|
||||
|
||||
For these and/or other purposes and motivations, and without any expectation
|
||||
of additional consideration or compensation, the person associating CC0 with a
|
||||
Work (the "Affirmer"), to the extent that he or she is an owner of Copyright
|
||||
and Related Rights in the Work, voluntarily elects to apply CC0 to the Work
|
||||
and publicly distribute the Work under its terms, with knowledge of his or her
|
||||
Copyright and Related Rights in the Work and the meaning and intended legal
|
||||
effect of CC0 on those rights.
|
||||
|
||||
1. Copyright and Related Rights. A Work made available under CC0 may be
|
||||
protected by copyright and related or neighboring rights ("Copyright and
|
||||
Related Rights"). Copyright and Related Rights include, but are not limited
|
||||
to, the following:
|
||||
|
||||
i. the right to reproduce, adapt, distribute, perform, display, communicate,
|
||||
and translate a Work;
|
||||
|
||||
ii. moral rights retained by the original author(s) and/or performer(s);
|
||||
|
||||
iii. publicity and privacy rights pertaining to a person's image or likeness
|
||||
depicted in a Work;
|
||||
|
||||
iv. rights protecting against unfair competition in regards to a Work,
|
||||
subject to the limitations in paragraph 4(a), below;
|
||||
|
||||
v. rights protecting the extraction, dissemination, use and reuse of data in
|
||||
a Work;
|
||||
|
||||
vi. database rights (such as those arising under Directive 96/9/EC of the
|
||||
European Parliament and of the Council of 11 March 1996 on the legal
|
||||
protection of databases, and under any national implementation thereof,
|
||||
including any amended or successor version of such directive); and
|
||||
|
||||
vii. other similar, equivalent or corresponding rights throughout the world
|
||||
based on applicable law or treaty, and any national implementations thereof.
|
||||
|
||||
2. Waiver. To the greatest extent permitted by, but not in contravention of,
|
||||
applicable law, Affirmer hereby overtly, fully, permanently, irrevocably and
|
||||
unconditionally waives, abandons, and surrenders all of Affirmer's Copyright
|
||||
and Related Rights and associated claims and causes of action, whether now
|
||||
known or unknown (including existing as well as future claims and causes of
|
||||
action), in the Work (i) in all territories worldwide, (ii) for the maximum
|
||||
duration provided by applicable law or treaty (including future time
|
||||
extensions), (iii) in any current or future medium and for any number of
|
||||
copies, and (iv) for any purpose whatsoever, including without limitation
|
||||
commercial, advertising or promotional purposes (the "Waiver"). Affirmer makes
|
||||
the Waiver for the benefit of each member of the public at large and to the
|
||||
detriment of Affirmer's heirs and successors, fully intending that such Waiver
|
||||
shall not be subject to revocation, rescission, cancellation, termination, or
|
||||
any other legal or equitable action to disrupt the quiet enjoyment of the Work
|
||||
by the public as contemplated by Affirmer's express Statement of Purpose.
|
||||
|
||||
3. Public License Fallback. Should any part of the Waiver for any reason be
|
||||
judged legally invalid or ineffective under applicable law, then the Waiver
|
||||
shall be preserved to the maximum extent permitted taking into account
|
||||
Affirmer's express Statement of Purpose. In addition, to the extent the Waiver
|
||||
is so judged Affirmer hereby grants to each affected person a royalty-free,
|
||||
non transferable, non sublicensable, non exclusive, irrevocable and
|
||||
unconditional license to exercise Affirmer's Copyright and Related Rights in
|
||||
the Work (i) in all territories worldwide, (ii) for the maximum duration
|
||||
provided by applicable law or treaty (including future time extensions), (iii)
|
||||
in any current or future medium and for any number of copies, and (iv) for any
|
||||
purpose whatsoever, including without limitation commercial, advertising or
|
||||
promotional purposes (the "License"). The License shall be deemed effective as
|
||||
of the date CC0 was applied by Affirmer to the Work. Should any part of the
|
||||
License for any reason be judged legally invalid or ineffective under
|
||||
applicable law, such partial invalidity or ineffectiveness shall not
|
||||
invalidate the remainder of the License, and in such case Affirmer hereby
|
||||
affirms that he or she will not (i) exercise any of his or her remaining
|
||||
Copyright and Related Rights in the Work or (ii) assert any associated claims
|
||||
and causes of action with respect to the Work, in either case contrary to
|
||||
Affirmer's express Statement of Purpose.
|
||||
|
||||
4. Limitations and Disclaimers.
|
||||
|
||||
a. No trademark or patent rights held by Affirmer are waived, abandoned,
|
||||
surrendered, licensed or otherwise affected by this document.
|
||||
|
||||
b. Affirmer offers the Work as-is and makes no representations or warranties
|
||||
of any kind concerning the Work, express, implied, statutory or otherwise,
|
||||
including without limitation warranties of title, merchantability, fitness
|
||||
for a particular purpose, non infringement, or the absence of latent or
|
||||
other defects, accuracy, or the present or absence of errors, whether or not
|
||||
discoverable, all to the greatest extent permissible under applicable law.
|
||||
|
||||
c. Affirmer disclaims responsibility for clearing rights of other persons
|
||||
that may apply to the Work or any use thereof, including without limitation
|
||||
any person's Copyright and Related Rights in the Work. Further, Affirmer
|
||||
disclaims responsibility for obtaining any necessary consents, permissions
|
||||
or other rights required for any use of the Work.
|
||||
|
||||
d. Affirmer understands and acknowledges that Creative Commons is not a
|
||||
party to this document and has no duty or obligation with respect to this
|
||||
CC0 or use of the Work.
|
||||
|
||||
For more information, please see
|
||||
http://creativecommons.org/publicdomain/zero/1.0/
|
||||
@@ -0,0 +1,12 @@
|
||||
<!-- Original artwork by Combiler01, CC0-1.0 -->
|
||||
<svg xmlns="http://www.w3.org/2000/svg"
|
||||
width="24"
|
||||
height="24"
|
||||
viewBox="0 0 24 24"
|
||||
fill="currentColor"
|
||||
stroke="currentColor"
|
||||
stroke-width="0.75"
|
||||
stroke-linejoin="round"
|
||||
>
|
||||
<path d="M 10.4588 22.4944 c -0.4792 -0.043 -0.768 -0.3686 -0.768 -0.8663 c 0 -0.4178 0.1659 -0.8601 0.5959 -1.5974 c 0.5468 -0.9277 0.768 -1.4438 0.7127 -1.665 c -0.0491 -0.1966 -1.0076 0.0737 -2.7893 0.7803 c -3.3914 1.3455 -5.001 1.4622 -6.0516 0.4546 c -1.4622 -1.4069 0.5959 -3.2255 4.0487 -3.5818 l 0.2027 -0.0184 l 0.0983 0.0491 c 0.3256 0.1597 0.2396 0.6267 -0.1229 0.6697 c -3.1517 0.3379 -5.1116 1.9291 -3.2931 2.6725 c 0.9646 0.3932 2.1073 0.172 5.0563 -0.9769 c 2.1933 -0.854 2.9183 -0.983 3.3483 -0.5775 c 0.4239 0.3993 0.2826 1.0444 -0.5222 2.4391 c -0.4239 0.7311 -0.5714 1.0752 -0.5714 1.3516 l 0 0.1536 l 0.0676 0.0246 c 0.4423 0.1474 1.3086 -0.3932 2.5804 -1.6097 c 1.3762 -1.3148 2.095 -1.7633 2.7831 -1.7325 c 0.7311 0.0369 0.8847 0.6758 0.3993 1.7141 c -0.2888 0.6205 -0.301 0.6512 -0.2335 0.6328 c 0.2519 -0.0799 0.4608 -0.2212 0.897 -0.5959 c 0.725 -0.6328 1.0444 -0.8171 1.4991 -0.854 c 0.8786 -0.0737 1.9107 0.9154 1.3209 1.2595 c -0.172 0.0983 -0.3379 0.0553 -0.4976 -0.1352 c -0.2519 -0.301 -0.4423 -0.4055 -0.7311 -0.4055 h -0.1966 l -0.1413 0.0737 c -0.2089 0.1044 -0.4116 0.258 -0.9277 0.725 c -0.7127 0.6451 -1.3946 0.8294 -1.7694 0.4854 c -0.2765 -0.258 -0.258 -0.6144 0.0553 -1.2902 c 0.4055 -0.8663 0.4116 -0.9707 0.0553 -0.854 c -0.5284 0.172 -0.9646 0.4915 -1.8984 1.3823 c -1.5974 1.5236 -2.3715 1.9844 -3.207 1.9168 z m -0.9918 -5.8111 c -0.0123 -0.0061 -0.3318 -0.0983 -0.7188 -0.215 c -0.3871 -0.1167 -0.7618 -0.2273 -0.8417 -0.2519 c -0.2949 -0.086 -0.4423 -0.301 -0.3993 -0.5837 c 0.0246 -0.172 0.0307 -0.1782 1.2165 -1.4561 l 0.1659 -0.1782 l 0.0061 -0.1044 c 0.0123 -0.1843 0.0614 -0.2765 0.2642 -0.4976 c 0.6267 -0.682 0.7987 -1.1366 0.9154 -2.4083 c 0.129 -1.4315 -0.0614 -1.1182 1.7878 -2.906 c 0.4854 -0.4669 1.0321 -1.0014 1.2165 -1.1796 c 0.1843 -0.1782 0.6144 -0.6021 0.9584 -0.9338 c 0.3441 -0.3318 1.069 -1.0383 1.6035 -1.5605 c 2.777 -2.7032 2.648 -2.5804 2.777 -2.6602 c 0.5345 -0.3502 1.2165 -0.3441 1.7018 0.0246 c 0.1659 0.1229 1.7141 1.665 1.8308 1.8247 c 0.4854 0.6451 0.4546 1.4929 -0.0737 2.1073 c -0.1413 0.1659 -0.9154 1.0936 -1.4991 1.8001 c -0.5407 0.6574 -1.4499 1.7571 -2.3838 2.8876 c -0.4485 0.5407 -1.6035 1.9414 -2.3776 2.8814 c -0.7188 0.8724 -0.725 0.8786 -1.5175 0.9953 c -1.7325 0.258 -2.0459 0.3809 -2.7708 1.0874 c -0.2949 0.2888 -0.3502 0.3256 -0.5345 0.3441 l -0.1044 0.0123 l -0.2396 0.2642 c -0.4423 0.4915 -0.639 0.682 -0.7188 0.7004 c -0.0676 0.0184 -0.2335 0.0246 -0.2703 0.0123 z m 0.3748 -1.0752 m 0.3133 -0.3379 m -0.1413 -0.129 c -0.0737 -0.0737 -0.2457 -0.2335 -0.3809 -0.3625 c -0.1352 -0.129 -0.2519 -0.2335 -0.258 -0.2335 c -0.0307 0 -1.0076 1.069 -0.9891 1.0813 c 0.0123 0.0061 0.2396 0.0799 0.5099 0.1597 c 0.2703 0.0799 0.5038 0.1536 0.5284 0.1659 c 0.0799 0.0307 0.0983 0.0123 0.4178 -0.3318 z m 1.1304 -0.8847 c 0.6942 -0.6451 1.4315 -0.9523 2.6787 -1.0997 c 0.1229 -0.0123 0.1474 0.0184 -0.2273 -0.3318 c -0.4546 -0.4301 -1.5482 -1.4684 -2.1196 -2.009 c -0.3748 -0.3563 -0.4915 -0.4608 -0.4976 -0.4362 c -0.0061 0.0184 -0.0184 0.1044 -0.0246 0.1905 c -0.0922 1.2779 -0.3502 1.9721 -1.0137 2.7524 l -0.0737 0.086 l 0.5345 0.5038 c 0.6144 0.5837 0.5345 0.5468 0.7434 0.3502 z m 3.9627 -1.7325 c 0.3563 -0.4301 0.7188 -0.8663 1.3823 -1.6711 c 0.2396 -0.2888 0.6082 -0.7372 0.8171 -0.9891 c 0.2089 -0.258 0.6635 -0.8048 1.0076 -1.2165 c 0.8171 -0.983 1.1612 -1.4008 1.794 -2.1687 c 0.2826 -0.3502 0.7065 -0.8601 0.94 -1.1366 c 0.6942 -0.8294 0.7004 -0.8355 0.7127 -1.155 c 0.0184 -0.4116 0 -0.4362 -0.8233 -1.2718 c -1.1857 -1.198 -1.2595 -1.2472 -1.6097 -1.1857 c -0.2888 0.0553 -0.1229 -0.0922 -2.1319 1.8677 c -3.9197 3.8153 -4.2515 4.1409 -5.3389 5.1853 c -0.3686 0.3563 -0.6758 0.6574 -0.6881 0.6758 c -0.0369 0.0737 -0.043 0.0676 2.1933 2.1872 c 0.6021 0.5714 1.1489 1.0936 1.2226 1.1612 c 0.172 0.1659 0.1413 0.1782 0.5222 -0.2765 z" />
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 4.0 KiB |
+33
-1
@@ -12,9 +12,41 @@ disallowed-methods = [
|
||||
{ path = "egui::Ui::radio", reason = "use radio from crates/ui-egui/src/widgets.rs, which is outlined and filled" },
|
||||
{ path = "egui::Ui::radio_value", reason = "use radio_value from crates/ui-egui/src/widgets.rs, which is outlined and filled" },
|
||||
{ path = "egui::RadioButton::new", reason = "use radio from crates/ui-egui/src/widgets.rs, which is outlined and filled" },
|
||||
# The raw RSA private-key operations: see disallowed-types below.
|
||||
{ path = "rsa::hazmat::rsa_decrypt", reason = "rsa is for verification only (RUSTSEC-2023-0071, ADR-0009); use aws-lc-rs" },
|
||||
{ path = "rsa::hazmat::rsa_decrypt_and_check", reason = "rsa is for verification only (RUSTSEC-2023-0071, ADR-0009); use aws-lc-rs" },
|
||||
# The ways to make or use an `rsa` private key, so a key whose type is never named (one
|
||||
# returned by another crate, or a generic over these traits) is caught too. The generic
|
||||
# `signature` and `pkcs8` traits are left out: the ECDSA keys use them as well.
|
||||
{ path = "rsa::RsaPrivateKey::new", reason = "rsa is for verification only (RUSTSEC-2023-0071, ADR-0009); use aws-lc-rs" },
|
||||
{ path = "rsa::RsaPrivateKey::new_unchecked", reason = "rsa is for verification only (RUSTSEC-2023-0071, ADR-0009); use aws-lc-rs" },
|
||||
{ path = "rsa::RsaPrivateKey::new_with_exp", reason = "rsa is for verification only (RUSTSEC-2023-0071, ADR-0009); use aws-lc-rs" },
|
||||
{ path = "rsa::RsaPrivateKey::new_with_exp_unchecked", reason = "rsa is for verification only (RUSTSEC-2023-0071, ADR-0009); use aws-lc-rs" },
|
||||
{ path = "rsa::RsaPrivateKey::from_components", reason = "rsa is for verification only (RUSTSEC-2023-0071, ADR-0009); use aws-lc-rs" },
|
||||
{ path = "rsa::RsaPrivateKey::from_components_with_large_exponent", reason = "rsa is for verification only (RUSTSEC-2023-0071, ADR-0009); use aws-lc-rs" },
|
||||
{ path = "rsa::RsaPrivateKey::from_p_q", reason = "rsa is for verification only (RUSTSEC-2023-0071, ADR-0009); use aws-lc-rs" },
|
||||
{ path = "rsa::RsaPrivateKey::from_primes", reason = "rsa is for verification only (RUSTSEC-2023-0071, ADR-0009); use aws-lc-rs" },
|
||||
{ path = "rsa::RsaPrivateKey::decrypt", reason = "rsa is for verification only (RUSTSEC-2023-0071, ADR-0009); use aws-lc-rs" },
|
||||
{ path = "rsa::RsaPrivateKey::decrypt_blinded", reason = "rsa is for verification only (RUSTSEC-2023-0071, ADR-0009); use aws-lc-rs" },
|
||||
{ path = "rsa::RsaPrivateKey::sign", reason = "rsa is for verification only (RUSTSEC-2023-0071, ADR-0009); use aws-lc-rs" },
|
||||
{ path = "rsa::RsaPrivateKey::sign_with_rng", reason = "rsa is for verification only (RUSTSEC-2023-0071, ADR-0009); use aws-lc-rs" },
|
||||
{ path = "rsa::traits::Decryptor::decrypt", reason = "rsa is for verification only (RUSTSEC-2023-0071, ADR-0009); use aws-lc-rs" },
|
||||
{ path = "rsa::traits::RandomizedDecryptor::decrypt_with_rng", reason = "rsa is for verification only (RUSTSEC-2023-0071, ADR-0009); use aws-lc-rs" },
|
||||
{ path = "rsa::traits::PaddingScheme::decrypt", reason = "rsa is for verification only (RUSTSEC-2023-0071, ADR-0009); use aws-lc-rs" },
|
||||
{ path = "rsa::traits::SignatureScheme::sign", reason = "rsa is for verification only (RUSTSEC-2023-0071, ADR-0009); use aws-lc-rs" },
|
||||
]
|
||||
cognitive-complexity-threshold = 30
|
||||
|
||||
# deny.toml ignores the Marvin advisory (RUSTSEC-2023-0071) because `rsa` is only used to verify
|
||||
# signatures; RSA private-key operations use aws-lc-rs (ADR-0009). These are the `rsa` types
|
||||
# that hold a private key, and above are the functions and methods that make or use one, so a
|
||||
# private-key operation through `rsa` fails clippy instead.
|
||||
disallowed-types = [
|
||||
{ path = "rsa::RsaPrivateKey", reason = "rsa is for verification only (RUSTSEC-2023-0071, ADR-0009); use aws-lc-rs" },
|
||||
{ path = "rsa::pkcs1v15::SigningKey", reason = "rsa is for verification only (RUSTSEC-2023-0071, ADR-0009); use aws-lc-rs" },
|
||||
{ path = "rsa::pkcs1v15::DecryptingKey", reason = "rsa is for verification only (RUSTSEC-2023-0071, ADR-0009); use aws-lc-rs" },
|
||||
{ path = "rsa::pss::SigningKey", reason = "rsa is for verification only (RUSTSEC-2023-0071, ADR-0009); use aws-lc-rs" },
|
||||
{ path = "rsa::pss::BlindedSigningKey", reason = "rsa is for verification only (RUSTSEC-2023-0071, ADR-0009); use aws-lc-rs" },
|
||||
{ path = "rsa::oaep::DecryptingKey", reason = "rsa is for verification only (RUSTSEC-2023-0071, ADR-0009); use aws-lc-rs" },
|
||||
{ path = "egui::ComboBox", reason = "use craft_ui::ComboBox: egui's combo box menu can't grow back while open (egui#5225)" },
|
||||
]
|
||||
cognitive-complexity-threshold = 30
|
||||
|
||||
@@ -197,3 +197,11 @@ sync_github_name = true
|
||||
|
||||
[people.Yousef-Dev921]
|
||||
sync_github_name = true
|
||||
|
||||
[people.marcoarnulfo]
|
||||
real_name = "Marco Arnulfo"
|
||||
display_name = "Marco Arnulfo"
|
||||
sync_github_name = false
|
||||
|
||||
[people.gmrmad1]
|
||||
real_name = "Madhav Agarwal"
|
||||
|
||||
+100
-20
@@ -23,6 +23,10 @@ pub enum AltError {
|
||||
Untagged,
|
||||
#[error("object {0} is not a figure")]
|
||||
NotAFigure(u32),
|
||||
#[error("the tag has child structure elements; mark a leaf tag instead")]
|
||||
HasChildren,
|
||||
#[error("this action does not support form streams, annotation or object references, other pages or invalid content references")]
|
||||
UnsupportedContent,
|
||||
#[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")]
|
||||
@@ -42,6 +46,8 @@ pub enum ArtifactError {
|
||||
HasChildren,
|
||||
#[error("the tag has no direct marked content")]
|
||||
NoMarkedContent,
|
||||
#[error("this action does not support form streams, annotation or object references, other pages or invalid content references")]
|
||||
UnsupportedContent,
|
||||
#[error("the tag has no page")]
|
||||
NoPage,
|
||||
#[error("the tag's marked content was not found on its page")]
|
||||
@@ -154,6 +160,74 @@ fn mcids(doc: &Document, d: &Dict) -> Vec<i64> {
|
||||
out
|
||||
}
|
||||
|
||||
/// Validation for the page-only destructive actions. Readout keeps its existing MCID reader.
|
||||
enum MutationContentError {
|
||||
HasChildren,
|
||||
Unsupported,
|
||||
}
|
||||
|
||||
fn mutation_mcids(doc: &Document, tag: &Dict, page: Option<ObjRef>) -> Result<HashSet<i64>, MutationContentError> {
|
||||
fn visit(
|
||||
doc: &Document,
|
||||
item: &Object,
|
||||
page: Option<ObjRef>,
|
||||
depth: usize,
|
||||
remaining: &mut usize,
|
||||
ancestors: &mut HashSet<ObjRef>,
|
||||
ids: &mut HashSet<i64>,
|
||||
) -> Result<(), MutationContentError> {
|
||||
if depth > 64 || *remaining == 0 {
|
||||
return Err(MutationContentError::Unsupported);
|
||||
}
|
||||
*remaining -= 1;
|
||||
match item {
|
||||
Object::Int(id) if *id >= 0 => {
|
||||
ids.insert(*id);
|
||||
}
|
||||
Object::Array(items) => {
|
||||
for item in items {
|
||||
visit(doc, item, page, depth + 1, remaining, ancestors, ids)?;
|
||||
}
|
||||
}
|
||||
Object::Ref(reference) => {
|
||||
if reference.generation != doc.generation(reference.num) || !ancestors.insert(*reference) {
|
||||
return Err(MutationContentError::Unsupported);
|
||||
}
|
||||
let result = visit(doc, &doc.get(*reference), page, depth + 1, remaining, ancestors, ids);
|
||||
ancestors.remove(reference);
|
||||
result?;
|
||||
}
|
||||
Object::Dict(dict) => {
|
||||
if dict.contains(b"S") {
|
||||
// Retiring a parent also removes descendants whose content was not checked.
|
||||
return Err(MutationContentError::HasChildren);
|
||||
}
|
||||
// Presence matters: even a malformed stream qualifier must not become a page ID.
|
||||
// Never resolve these targets; this action does not support form streams.
|
||||
if dict.contains(b"Stm") || dict.contains(b"StmOwn") || dict.name(b"Type") != Some(b"MCR") {
|
||||
return Err(MutationContentError::Unsupported);
|
||||
}
|
||||
if let Some(explicit_page) = dict.get(b"Pg") {
|
||||
let explicit_page = explicit_page.as_ref().ok_or(MutationContentError::Unsupported)?;
|
||||
if Some(explicit_page) != page {
|
||||
return Err(MutationContentError::Unsupported);
|
||||
}
|
||||
}
|
||||
let id = dict.get(b"MCID").and_then(Object::as_int).filter(|id| *id >= 0).ok_or(MutationContentError::Unsupported)?;
|
||||
ids.insert(id);
|
||||
}
|
||||
_ => return Err(MutationContentError::Unsupported),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
let mut ids = HashSet::new();
|
||||
if let Some(kids) = tag.get(b"K") {
|
||||
visit(doc, kids, page, 0, &mut 4096, &mut HashSet::new(), &mut ids)?;
|
||||
}
|
||||
Ok(ids)
|
||||
}
|
||||
|
||||
/// The page's named property lists (`/Resources /Properties`), which a `BDC` can name instead of
|
||||
/// writing its property list inline.
|
||||
fn page_properties(doc: &Document, page: &Dict) -> Dict {
|
||||
@@ -514,13 +588,21 @@ fn artifact_marked_content(
|
||||
}
|
||||
|
||||
/// Decorative figure: its marked content on the page becomes an artifact, and the element
|
||||
/// leaves the structure tree (and the parent tree).
|
||||
/// leaves the structure tree (and the parent tree). Form references and structure children refuse
|
||||
/// before the document changes.
|
||||
pub fn mark_decorative(doc: &mut Document, obj: ObjRef) -> Result<(), AltError> {
|
||||
let d = check_figure(doc, obj)?;
|
||||
let ids: HashSet<i64> = mcids(doc, &d).into_iter().collect();
|
||||
let pages = pdfcraft_model::pages(doc);
|
||||
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 page = pg.and_then(|p| pages.iter().find(|page| page.obj == p));
|
||||
let ids = mutation_mcids(doc, &d, page.map(|page| page.obj)).map_err(|error| match error {
|
||||
MutationContentError::HasChildren => AltError::HasChildren,
|
||||
MutationContentError::Unsupported => AltError::UnsupportedContent,
|
||||
})?;
|
||||
if !ids.is_empty() && page.is_none() {
|
||||
return Err(AltError::UnsupportedContent);
|
||||
}
|
||||
if let Some(page) = page.filter(|_| !ids.is_empty()) {
|
||||
let streams = decode_page_streams(doc, &page.dict).ok_or(AltError::TooLarge)?;
|
||||
match artifact_marked_content(doc, page, streams, &ids, false)? {
|
||||
// The parent tree no longer points those ids at the figure.
|
||||
@@ -552,16 +634,18 @@ pub fn mark_decorative(doc: &mut Document, obj: ObjRef) -> Result<(), AltError>
|
||||
/// Mark a leaf structure tag's directly owned marked content as an artifact.
|
||||
///
|
||||
/// This deliberately refuses a tag with child structure elements. Converting a parent would
|
||||
/// otherwise silently discard semantic descendants. The visible page content is preserved: each
|
||||
/// otherwise silently discard semantic descendants. Form references and invalid page ownership
|
||||
/// also refuse before the document changes. A missing, ambiguous or mismatched parent also refuses before
|
||||
/// mutation. The visible page content is preserved: each
|
||||
/// matching marked-content sequence changes from `BDC` with an MCID to `/Artifact BMC`.
|
||||
pub fn mark_tag_artifact(doc: &mut Document, obj: ObjRef) -> Result<(), ArtifactError> {
|
||||
tree_root(doc).ok_or(ArtifactError::Untagged)?;
|
||||
let elements = elements(doc);
|
||||
let Some(element) = elements.iter().find(|e| e.object == obj) else { return Err(ArtifactError::NotATag(obj.num)) };
|
||||
if has_child_structure(doc, &element.dict) {
|
||||
return Err(ArtifactError::HasChildren);
|
||||
}
|
||||
let ids: HashSet<i64> = mcids(doc, &element.dict).into_iter().collect();
|
||||
let ids = mutation_mcids(doc, &element.dict, element.page).map_err(|error| match error {
|
||||
MutationContentError::HasChildren => ArtifactError::HasChildren,
|
||||
MutationContentError::Unsupported => ArtifactError::UnsupportedContent,
|
||||
})?;
|
||||
if ids.is_empty() {
|
||||
return Err(ArtifactError::NoMarkedContent);
|
||||
}
|
||||
@@ -570,6 +654,14 @@ pub fn mark_tag_artifact(doc: &mut Document, obj: ObjRef) -> Result<(), Artifact
|
||||
let page = pages.iter().find(|page| page.obj == page_ref).ok_or(ArtifactError::NoPage)?;
|
||||
let parent = element.dict.get(b"P").and_then(Object::as_ref).ok_or(ArtifactError::NoParent)?;
|
||||
let replacement = replacement_kids(doc, parent, obj)?;
|
||||
// The `/P` the tag names must be the parent it was reached from (or the structure root),
|
||||
// checked before the page changes.
|
||||
let reachable_parent = element
|
||||
.parent
|
||||
.or_else(|| doc.root().and_then(|catalog| doc.get(catalog).as_dict().and_then(|dict| dict.get(b"StructTreeRoot").and_then(Object::as_ref))));
|
||||
if reachable_parent != Some(parent) {
|
||||
return Err(ArtifactError::NoParent);
|
||||
}
|
||||
let streams = decode_page_streams(doc, &page.dict).ok_or(ArtifactError::TooLarge)?;
|
||||
match artifact_marked_content(doc, page, streams, &ids, true)? {
|
||||
Marked::Done => {}
|
||||
@@ -587,18 +679,6 @@ pub fn mark_tag_artifact(doc: &mut Document, obj: ObjRef) -> Result<(), Artifact
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn has_child_structure(doc: &Document, tag: &Dict) -> bool {
|
||||
fn child(doc: &Document, item: &Object) -> bool {
|
||||
match item {
|
||||
Object::Array(items) => items.iter().any(|item| child(doc, item)),
|
||||
Object::Ref(r) => doc.get(*r).as_dict().is_some_and(|d| d.contains(b"S")),
|
||||
Object::Dict(d) => d.contains(b"S"),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
tag.get(b"K").is_some_and(|items| child(doc, items))
|
||||
}
|
||||
|
||||
fn replacement_kids(doc: &Document, parent: ObjRef, obj: ObjRef) -> Result<Object, ArtifactError> {
|
||||
let kids = doc.get(parent).as_dict().and_then(|p| p.get(b"K").cloned()).ok_or(ArtifactError::NoParent)?;
|
||||
match kids {
|
||||
|
||||
+134
-48
@@ -2,7 +2,10 @@
|
||||
//!
|
||||
//! Each text object becomes a paragraph, or a heading when its size or weight sets it apart from
|
||||
//! the body text ([`crate::autotag_roles`]); either can be retagged with the existing tag-property
|
||||
//! tool after human review. Painted paths, shadings and images outside text objects
|
||||
//! tool after human review. Running headers, footers and page numbers, found by repetition across
|
||||
//! the pages ([`crate::autotag_running`]), are wrapped in
|
||||
//! `/Artifact <</Type /Pagination /Subtype /Header>> BDC … EMC` (or `/Footer`) instead of being
|
||||
//! tagged. Painted paths, shadings and images outside text objects
|
||||
//! are wrapped in `/Artifact BMC … EMC` so the resulting page passes the tagged-content check.
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
@@ -11,6 +14,7 @@ use pdfcraft_content::{Op, Pieces, serialize_ops};
|
||||
use pdfcraft_cos::{DecodeBudget, Dict, Document, ObjRef, Object, Stream};
|
||||
|
||||
use crate::autotag_roles::{self, Evidence};
|
||||
use crate::autotag_running::{self, Edge, Frame, PageText};
|
||||
|
||||
const MAX_PAGES: usize = 1_000;
|
||||
const MAX_PAGE_BYTES: usize = 16 * 1024 * 1024;
|
||||
@@ -26,6 +30,21 @@ pub struct AutoTagResult {
|
||||
pub pages: usize,
|
||||
pub paragraphs: usize,
|
||||
pub headings: usize,
|
||||
/// Text objects marked as running header artifacts.
|
||||
pub headers: usize,
|
||||
/// Text objects marked as running footer artifacts, page numbers included.
|
||||
pub footers: usize,
|
||||
}
|
||||
|
||||
/// A text object auto-tag marks as a running header or footer instead of tagging it.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct RunningText {
|
||||
/// 0-based page index.
|
||||
pub page: usize,
|
||||
/// `"Header"` or `"Footer"`, the artifact subtype written.
|
||||
pub subtype: &'static str,
|
||||
/// The text shown, at most 256 characters.
|
||||
pub text: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error, PartialEq)]
|
||||
@@ -50,6 +69,14 @@ struct Plan {
|
||||
spans: Vec<(usize, usize)>,
|
||||
evidence: Vec<Evidence>,
|
||||
artifacts: HashMap<usize, usize>,
|
||||
frame: Frame,
|
||||
}
|
||||
|
||||
/// What a text object's span is wrapped in.
|
||||
#[derive(Clone, Copy)]
|
||||
enum Mark {
|
||||
Tag(usize, &'static str),
|
||||
Running(Edge),
|
||||
}
|
||||
|
||||
fn unsupported(page: usize, reason: impl Into<String>) -> AutoTagError {
|
||||
@@ -269,7 +296,8 @@ fn plan_page(
|
||||
}
|
||||
let resources = page_fonts(doc, &page.dict);
|
||||
let evidence = autotag_roles::evidence(doc, fonts, &resources, &parsed.ops, &spans);
|
||||
Ok(Plan { page: page.obj, ops: parsed.ops, spans, evidence, artifacts })
|
||||
let frame = Frame { rotation: page.rotation(doc), crop: page.crop(doc) };
|
||||
Ok(Plan { page: page.obj, ops: parsed.ops, spans, evidence, artifacts, frame })
|
||||
}
|
||||
|
||||
fn plan(doc: &Document) -> Result<Vec<Plan>, AutoTagError> {
|
||||
@@ -301,21 +329,26 @@ fn plan(doc: &Document) -> Result<Vec<Plan>, AutoTagError> {
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn mark_ops(
|
||||
ops: Vec<Op>,
|
||||
starts: &HashMap<usize, (usize, &'static str)>,
|
||||
ends: &HashSet<usize>,
|
||||
artifacts: &HashMap<usize, usize>,
|
||||
) -> Result<Vec<Op>, AutoTagError> {
|
||||
fn mark_ops(ops: Vec<Op>, starts: &HashMap<usize, Mark>, ends: &HashSet<usize>, artifacts: &HashMap<usize, usize>) -> Result<Vec<Op>, AutoTagError> {
|
||||
let artifact_ends: HashSet<usize> = artifacts.values().copied().collect();
|
||||
let extra = starts.len().saturating_add(artifacts.len()).saturating_mul(2);
|
||||
let mut marked = Vec::with_capacity(ops.len().saturating_add(extra));
|
||||
for (at, op) in ops.into_iter().enumerate() {
|
||||
let is_artifact = artifacts.contains_key(&at);
|
||||
if let Some(&(mcid, role)) = starts.get(&at) {
|
||||
if let Some(&mark) = starts.get(&at) {
|
||||
let mut properties = Dict::new();
|
||||
properties.set(b"MCID".to_vec(), Object::Int(i64::try_from(mcid).map_err(|_| AutoTagError::TooManyPages)?));
|
||||
marked.push(Op::new("BDC", vec![Object::name(role), Object::Dict(properties)]));
|
||||
let tag = match mark {
|
||||
Mark::Tag(mcid, role) => {
|
||||
properties.set(b"MCID".to_vec(), Object::Int(i64::try_from(mcid).map_err(|_| AutoTagError::TooManyPages)?));
|
||||
role
|
||||
}
|
||||
Mark::Running(edge) => {
|
||||
properties.set(b"Type".to_vec(), Object::name("Pagination"));
|
||||
properties.set(b"Subtype".to_vec(), Object::name(edge.subtype()));
|
||||
"Artifact"
|
||||
}
|
||||
};
|
||||
marked.push(Op::new("BDC", vec![Object::name(tag), Object::Dict(properties)]));
|
||||
} else if is_artifact {
|
||||
marked.push(Op::new("BMC", vec![Object::name("Artifact")]));
|
||||
}
|
||||
@@ -361,54 +394,107 @@ fn write_structure(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Tag every text object in an untagged PDF as a paragraph or a heading and mark painted paths, shadings and
|
||||
/// The edge each planned text object repeats at, for running text, per page and span.
|
||||
fn running(plans: &[Plan]) -> Vec<Vec<Option<Edge>>> {
|
||||
let pages: Vec<PageText<'_>> = plans.iter().map(|p| PageText { frame: p.frame, objects: &p.evidence }).collect();
|
||||
autotag_running::find(&pages, autotag_roles::body_size(plans.iter().flat_map(|p| &p.evidence)))
|
||||
}
|
||||
|
||||
/// The running headers, footers and page numbers [`autotag_text`] would mark as artifacts, in page
|
||||
/// order. Refuses what `autotag_text` refuses, and changes nothing.
|
||||
pub fn running_text(doc: &Document) -> Result<Vec<RunningText>, AutoTagError> {
|
||||
let plans = plan(doc)?;
|
||||
let mut out = Vec::new();
|
||||
for (page, (plan, edges)) in plans.iter().zip(running(&plans)).enumerate() {
|
||||
for (evidence, edge) in plan.evidence.iter().zip(edges) {
|
||||
if let Some(edge) = edge {
|
||||
out.push(RunningText { page, subtype: edge.subtype(), text: evidence.text.clone() });
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// What [`autotag_text`] has written so far.
|
||||
struct Written {
|
||||
children: Vec<Object>,
|
||||
numbers: Vec<Object>,
|
||||
result: AutoTagResult,
|
||||
}
|
||||
|
||||
/// Tag or mark one page's text objects, and write its marked content.
|
||||
fn tag_page(
|
||||
next: &mut Document,
|
||||
document: ObjRef,
|
||||
page: Plan,
|
||||
edges: &[Option<Edge>],
|
||||
roles: &mut impl Iterator<Item = &'static str>,
|
||||
written: &mut Written,
|
||||
) -> Result<(), AutoTagError> {
|
||||
let (mut starts, mut ends, mut parents) = (HashMap::new(), HashSet::new(), Vec::new());
|
||||
let key = i64::try_from(written.result.pages).map_err(|_| AutoTagError::TooManyPages)?;
|
||||
for (at, &(first, last)) in page.spans.iter().enumerate() {
|
||||
ends.insert(last);
|
||||
if let Some(edge) = edges.get(at).copied().flatten() {
|
||||
starts.insert(first, Mark::Running(edge));
|
||||
let count = if edge == Edge::Top { &mut written.result.headers } else { &mut written.result.footers };
|
||||
*count = count.saturating_add(1);
|
||||
continue;
|
||||
}
|
||||
let role = roles.next().unwrap_or("P");
|
||||
let mcid = parents.len();
|
||||
let mut element = Dict::new();
|
||||
element.set(b"Type".to_vec(), Object::name("StructElem"));
|
||||
element.set(b"S".to_vec(), Object::name(role));
|
||||
element.set(b"P".to_vec(), Object::Ref(document));
|
||||
element.set(b"Pg".to_vec(), Object::Ref(page.page));
|
||||
element.set(b"K".to_vec(), Object::Int(i64::try_from(mcid).map_err(|_| AutoTagError::TooManyPages)?));
|
||||
let reference = next.add(element);
|
||||
parents.push(Object::Ref(reference));
|
||||
written.children.push(Object::Ref(reference));
|
||||
starts.insert(first, Mark::Tag(mcid, role));
|
||||
let count = if role == "P" { &mut written.result.paragraphs } else { &mut written.result.headings };
|
||||
*count = count.saturating_add(1);
|
||||
}
|
||||
if !parents.is_empty() {
|
||||
next.update_dict(page.page, |d| d.set(b"StructParents".to_vec(), Object::Int(key)))?;
|
||||
written.numbers.extend([Object::Int(key), Object::Array(parents)]);
|
||||
written.result.pages = written.result.pages.saturating_add(1);
|
||||
}
|
||||
let marked = mark_ops(page.ops, &starts, &ends, &page.artifacts)?;
|
||||
let stream = next.add(Stream::flate(Dict::new(), &serialize_ops(&marked)));
|
||||
next.update_dict(page.page, |d| d.set(b"Contents".to_vec(), Object::Ref(stream)))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Tag every text object in an untagged PDF as a paragraph or a heading, mark running headers,
|
||||
/// footers and page numbers as pagination artifacts, and mark painted paths, shadings and
|
||||
/// images outside text objects as artifacts. The full structure tree, parent tree and
|
||||
/// marked-content IDs are written together. Unsupported operators are refused before any
|
||||
/// mutation. On success the caller can use tag-property edits to correct the roles after review.
|
||||
pub fn autotag_text(doc: &mut Document) -> Result<AutoTagResult, AutoTagError> {
|
||||
let plans = plan(doc)?;
|
||||
let all: Vec<Evidence> = plans.iter().flat_map(|p| p.evidence.iter().copied()).collect();
|
||||
let mut roles = autotag_roles::roles(&all).into_iter();
|
||||
let running = running(&plans);
|
||||
// Running text is left out of the body style and the heading levels, as it is out of the tags.
|
||||
let tagged: Vec<Evidence> = plans
|
||||
.iter()
|
||||
.zip(&running)
|
||||
.flat_map(|(p, edges)| p.evidence.iter().zip(edges).filter(|(_, edge)| edge.is_none()).map(|(e, _)| e.clone()))
|
||||
.collect();
|
||||
let mut roles = autotag_roles::roles(&tagged).into_iter();
|
||||
let mut next = doc.clone();
|
||||
let catalog = next.root().ok_or(AutoTagError::NoCatalog)?;
|
||||
let (root, document) = (next.add(Object::Null), next.add(Object::Null));
|
||||
let (mut children, mut numbers, mut tagged_pages, mut paragraphs, mut headings) = (Vec::new(), Vec::new(), 0usize, 0usize, 0usize);
|
||||
for page in plans {
|
||||
let result = AutoTagResult { pages: 0, paragraphs: 0, headings: 0, headers: 0, footers: 0 };
|
||||
let mut written = Written { children: Vec::new(), numbers: Vec::new(), result };
|
||||
for (page, edges) in plans.into_iter().zip(running) {
|
||||
if page.spans.is_empty() && page.artifacts.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let (mut starts, mut ends) = (HashMap::new(), HashSet::new());
|
||||
if !page.spans.is_empty() {
|
||||
let key = i64::try_from(tagged_pages).map_err(|_| AutoTagError::TooManyPages)?;
|
||||
let mut parents = Vec::with_capacity(page.spans.len());
|
||||
for (mcid, (first, last)) in page.spans.iter().enumerate() {
|
||||
let role = roles.next().unwrap_or("P");
|
||||
let mut element = Dict::new();
|
||||
element.set(b"Type".to_vec(), Object::name("StructElem"));
|
||||
element.set(b"S".to_vec(), Object::name(role));
|
||||
element.set(b"P".to_vec(), Object::Ref(document));
|
||||
element.set(b"Pg".to_vec(), Object::Ref(page.page));
|
||||
element.set(b"K".to_vec(), Object::Int(i64::try_from(mcid).map_err(|_| AutoTagError::TooManyPages)?));
|
||||
let reference = next.add(element);
|
||||
parents.push(Object::Ref(reference));
|
||||
children.push(Object::Ref(reference));
|
||||
starts.insert(*first, (mcid, role));
|
||||
ends.insert(*last);
|
||||
if role == "P" {
|
||||
paragraphs = paragraphs.saturating_add(1);
|
||||
} else {
|
||||
headings = headings.saturating_add(1);
|
||||
}
|
||||
}
|
||||
next.update_dict(page.page, |d| d.set(b"StructParents".to_vec(), Object::Int(key)))?;
|
||||
numbers.extend([Object::Int(key), Object::Array(parents)]);
|
||||
tagged_pages += 1;
|
||||
}
|
||||
let marked = mark_ops(page.ops, &starts, &ends, &page.artifacts)?;
|
||||
let stream = next.add(Stream::flate(Dict::new(), &serialize_ops(&marked)));
|
||||
next.update_dict(page.page, |d| d.set(b"Contents".to_vec(), Object::Ref(stream)))?;
|
||||
tag_page(&mut next, document, page, &edges, &mut roles, &mut written)?;
|
||||
}
|
||||
write_structure(&mut next, catalog, root, document, children, numbers, tagged_pages)?;
|
||||
let Written { children, numbers, result } = written;
|
||||
write_structure(&mut next, catalog, root, document, children, numbers, result.pages)?;
|
||||
*doc = next;
|
||||
Ok(AutoTagResult { pages: tagged_pages, paragraphs, headings })
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
@@ -15,7 +15,7 @@ use pdfcraft_cos::{Dict, Document, ObjRef, Object};
|
||||
use pdfcraft_fonts::pdf::Metrics;
|
||||
|
||||
/// A line this much larger than body text reads as a heading.
|
||||
const HEADING_SIZE_RATIO: f64 = 1.15;
|
||||
pub(crate) const HEADING_SIZE_RATIO: f64 = 1.15;
|
||||
/// Bold text this much of the body size or more can be a heading by weight.
|
||||
const WEIGHT_SIZE_RATIO: f64 = 0.9;
|
||||
const MAX_LINES: usize = 3;
|
||||
@@ -25,9 +25,12 @@ const MAX_CHARS: usize = 200;
|
||||
const MAX_SAVED: usize = 64;
|
||||
/// Distinct fonts measured per document; text in any further font counts as unstyled.
|
||||
const MAX_FONTS: usize = 256;
|
||||
/// Characters of an object's text kept for finding running headers and footers; longer text is
|
||||
/// body text.
|
||||
pub(crate) const MAX_KEPT_CHARS: usize = 256;
|
||||
|
||||
/// What one text object shows.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq)]
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub(crate) struct Evidence {
|
||||
/// The size, in user space, carrying the most of the object's characters.
|
||||
pub size: f64,
|
||||
@@ -37,6 +40,13 @@ pub(crate) struct Evidence {
|
||||
/// Characters shown, whitespace excluded.
|
||||
pub chars: usize,
|
||||
pub letters: bool,
|
||||
/// The text shown, at most [`MAX_KEPT_CHARS`] characters, with a space at each line move.
|
||||
pub text: String,
|
||||
/// `[x0, y0, x1, y1]` in user space around each shown string's run from its origin to where
|
||||
/// it advances to, and from its baseline to one font size above. `None` when any of it is in
|
||||
/// glyphs whose widths the font does not declare ([`Metrics::width_declared`]) or that have no
|
||||
/// Unicode mapping, or in a font that writes vertically.
|
||||
pub extent: Option<[f64; 4]>,
|
||||
}
|
||||
|
||||
/// The structure type for each text object, in document order: `H1`–`H6` or `P`.
|
||||
@@ -73,10 +83,15 @@ fn half_points(size: f64) -> i64 {
|
||||
(size * 2.0).round() as i64
|
||||
}
|
||||
|
||||
/// The body text size: the size carrying the most characters.
|
||||
pub(crate) fn body_size<'a>(objects: impl IntoIterator<Item = &'a Evidence>) -> Option<f64> {
|
||||
body_style(objects).map(|(size, _)| size)
|
||||
}
|
||||
|
||||
/// The size carrying the most characters, and whether most of them are bold.
|
||||
fn body_style(objects: &[Evidence]) -> Option<(f64, bool)> {
|
||||
fn body_style<'a>(objects: impl IntoIterator<Item = &'a Evidence>) -> Option<(f64, bool)> {
|
||||
let mut by_size: HashMap<i64, (usize, usize)> = HashMap::new();
|
||||
for e in objects.iter().filter(|e| e.chars > 0) {
|
||||
for e in objects.into_iter().filter(|e| e.chars > 0) {
|
||||
let entry = by_size.entry(half_points(e.size)).or_default();
|
||||
entry.0 = entry.0.saturating_add(e.chars);
|
||||
if e.bold {
|
||||
@@ -94,10 +109,16 @@ struct State {
|
||||
tlm: Matrix,
|
||||
size: f64,
|
||||
leading: f64,
|
||||
/// `Ts`, in unscaled text space units.
|
||||
rise: f64,
|
||||
/// `Tc`, `Tw` and `Tz` / 100.
|
||||
spacing: [f64; 3],
|
||||
/// Text render mode 3 or 7: shown text that paints nothing, such as an OCR layer or a
|
||||
/// clip-only object.
|
||||
invisible: bool,
|
||||
metrics: Option<Rc<Metrics>>,
|
||||
/// The font writes vertically, which the extents do not measure.
|
||||
vertical: bool,
|
||||
}
|
||||
|
||||
/// Font metrics for a whole document, measured once per font object and capped at
|
||||
@@ -136,11 +157,26 @@ struct Shown {
|
||||
shown: bool,
|
||||
moved: bool,
|
||||
letters: bool,
|
||||
text: String,
|
||||
kept: usize,
|
||||
extent: Option<[f64; 4]>,
|
||||
/// Text shown whose run is not known: in glyphs without a declared width or a Unicode mapping,
|
||||
/// in a vertical font, or out of range.
|
||||
unbounded: bool,
|
||||
}
|
||||
|
||||
impl Shown {
|
||||
fn show(&mut self, state: &State, bytes: &[u8]) {
|
||||
let Some(metrics) = state.metrics.as_ref().filter(|_| !state.invisible) else { return };
|
||||
// A vertical font's glyphs advance down the page, invisible or not, so the text after
|
||||
// them is placed where the extents do not follow.
|
||||
self.unbounded |= state.vertical;
|
||||
let Some(metrics) = state.metrics.as_ref().filter(|_| !state.invisible) else {
|
||||
self.unbounded |= state.metrics.is_none();
|
||||
return;
|
||||
};
|
||||
// Codes without a Unicode mapping still paint glyphs: the text's extent is not known.
|
||||
let unmapped = metrics.codes(bytes).iter().any(|&(code, _)| metrics.text_of(code).is_none());
|
||||
self.unbounded |= unmapped;
|
||||
let text = metrics.decode(bytes);
|
||||
let chars = text.chars().filter(|c| !c.is_whitespace()).count();
|
||||
if chars == 0 {
|
||||
@@ -151,13 +187,23 @@ impl Shown {
|
||||
(self.shown, self.lines) = (true, 1);
|
||||
} else if self.moved {
|
||||
self.lines = self.lines.saturating_add(1);
|
||||
self.keep(" ");
|
||||
}
|
||||
self.moved = false;
|
||||
let [_, _, c, d, _, _] = state.tm.then(&state.ctm).0;
|
||||
let [a, b, c, d, e, f] = state.tm.then(&state.ctm).0;
|
||||
let size = (state.size * c.hypot(d)).abs();
|
||||
if !size.is_finite() || size <= 0.0 || size > 1e6 {
|
||||
return;
|
||||
}
|
||||
self.keep(&text);
|
||||
let run = advance(state, metrics, bytes);
|
||||
self.unbounded |= !run.declared;
|
||||
let (low, high) = (state.rise, state.rise + state.size);
|
||||
for along in run.span {
|
||||
let (x, y) = (e + along * a, f + along * b);
|
||||
self.reach(x + low * c, y + low * d);
|
||||
self.reach(x + high * c, y + high * d);
|
||||
}
|
||||
let entry = self.by_size.entry(half_points(size)).or_default();
|
||||
entry.0 = entry.0.saturating_add(chars);
|
||||
if metrics.bold {
|
||||
@@ -165,6 +211,22 @@ impl Shown {
|
||||
}
|
||||
}
|
||||
|
||||
fn keep(&mut self, text: &str) {
|
||||
for ch in text.chars().take(MAX_KEPT_CHARS.saturating_sub(self.kept)) {
|
||||
self.text.push(ch);
|
||||
self.kept = self.kept.saturating_add(1);
|
||||
}
|
||||
}
|
||||
|
||||
fn reach(&mut self, x: f64, y: f64) {
|
||||
if !x.is_finite() || !y.is_finite() {
|
||||
self.unbounded = true;
|
||||
return;
|
||||
}
|
||||
let [x0, y0, x1, y1] = self.extent.unwrap_or([x, y, x, y]);
|
||||
self.extent = Some([x0.min(x), y0.min(y), x1.max(x), y1.max(y)]);
|
||||
}
|
||||
|
||||
/// A line move counts once text is shown after it, so blank lines and trailing moves do not.
|
||||
fn new_line(&mut self) {
|
||||
self.moved = self.shown;
|
||||
@@ -175,16 +237,159 @@ impl Shown {
|
||||
let Some((size, (count, bold))) = self.by_size.into_iter().max_by_key(|&(s, (n, _))| (n, s)) else {
|
||||
return Evidence::default();
|
||||
};
|
||||
Evidence { size: size as f64 / 2.0, bold: bold.saturating_mul(2) > count, lines: self.lines, chars, letters: self.letters }
|
||||
Evidence {
|
||||
size: size as f64 / 2.0,
|
||||
bold: bold.saturating_mul(2) > count,
|
||||
lines: self.lines,
|
||||
chars,
|
||||
letters: self.letters,
|
||||
text: self.text,
|
||||
extent: self.extent.filter(|_| !self.unbounded),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How far a string's glyphs move and reach along the text line, in unscaled text space (§9.4.4).
|
||||
struct Run {
|
||||
/// The advance past the string.
|
||||
width: f64,
|
||||
/// The lowest and highest points any glyph or the advance reaches: negative spacing can
|
||||
/// pull glyphs back over each other, so the ends of the run alone do not bound them.
|
||||
/// Non-finite when the spacing or size is.
|
||||
span: [f64; 2],
|
||||
/// Whether the font declares every glyph's width.
|
||||
declared: bool,
|
||||
}
|
||||
|
||||
fn advance(state: &State, metrics: &Metrics, bytes: &[u8]) -> Run {
|
||||
let [char_spacing, word_spacing, scale] = state.spacing;
|
||||
let (mut at, mut low, mut high, mut declared) = (0.0f64, 0.0f64, 0.0f64, true);
|
||||
for (code, len) in metrics.codes(bytes) {
|
||||
let glyph = metrics.width(code) * state.size;
|
||||
(low, high) = (low.min(at).min(at + glyph), high.max(at).max(at + glyph));
|
||||
let word = if metrics.is_space(code, len) { word_spacing } else { 0.0 };
|
||||
at += glyph + char_spacing + word;
|
||||
declared &= metrics.width_declared(code);
|
||||
}
|
||||
// `min` and `max` drop a NaN, but once `at` is not finite it stays so: pass it on instead.
|
||||
let span = if at.is_finite() { [low.min(at), high.max(at)] } else { [at, at] };
|
||||
Run { width: at * scale, span: span.map(|v| v * scale), declared }
|
||||
}
|
||||
|
||||
/// Whether `font` writes vertically: a Type 0 font whose `/Encoding` is a predefined CMap name
|
||||
/// ending in `-V`, or an embedded CMap whose `/WMode` is 1 (§9.7.5).
|
||||
fn vertical(doc: &Document, font: &Object) -> bool {
|
||||
let font = doc.resolve(font);
|
||||
let Some(font) = font.as_dict() else { return false };
|
||||
if font.get(b"Subtype").map(|s| doc.resolve(s)).as_deref().and_then(Object::as_name) != Some(b"Type0".as_slice()) {
|
||||
return false;
|
||||
}
|
||||
match font.get(b"Encoding").map(|e| doc.resolve(e)).as_deref() {
|
||||
Some(Object::Name(n)) => n.ends_with(b"-V"),
|
||||
Some(Object::Stream(s)) => s.dict.int(b"WMode") == Some(1),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Shows `bytes` in `object`, if any, then moves the text matrix past them.
|
||||
fn show(state: &mut State, object: Option<&mut Shown>, bytes: &[u8]) {
|
||||
if let Some(o) = object {
|
||||
o.show(state, bytes);
|
||||
}
|
||||
let moved = state.metrics.as_ref().map_or(0.0, |m| advance(state, m, bytes).width);
|
||||
state.tm = Matrix::translate(moved, 0.0).then(&state.tm);
|
||||
}
|
||||
|
||||
/// The text state and text-showing operators other than `Tf`.
|
||||
fn text_op(state: &mut State, object: Option<&mut Shown>, op: &Op) {
|
||||
match op.op.as_slice() {
|
||||
b"TL" => state.leading = op.num(0).unwrap_or(state.leading),
|
||||
b"Ts" => state.rise = op.num(0).unwrap_or(state.rise),
|
||||
b"Tr" => state.invisible = matches!(op.num(0), Some(m) if m == 3.0 || m == 7.0),
|
||||
b"Tc" => state.spacing[0] = op.num(0).unwrap_or(state.spacing[0]),
|
||||
b"Tw" => state.spacing[1] = op.num(0).unwrap_or(state.spacing[1]),
|
||||
b"Tz" => state.spacing[2] = op.num(0).map_or(state.spacing[2], |z| z / 100.0),
|
||||
b"Td" | b"TD" => {
|
||||
if let Some([x, y]) = op.nums::<2>() {
|
||||
if op.op == b"TD" {
|
||||
state.leading = -y;
|
||||
}
|
||||
state.tlm = Matrix::translate(x, y).then(&state.tlm);
|
||||
state.tm = state.tlm;
|
||||
if y != 0.0
|
||||
&& let Some(o) = object
|
||||
{
|
||||
o.new_line();
|
||||
}
|
||||
}
|
||||
}
|
||||
b"Tm" => {
|
||||
if let Some(m) = op.nums::<6>() {
|
||||
let moved = m[5] != state.tlm.0[5];
|
||||
(state.tm, state.tlm) = (Matrix(m), Matrix(m));
|
||||
if moved && let Some(o) = object {
|
||||
o.new_line();
|
||||
}
|
||||
}
|
||||
}
|
||||
b"T*" | b"'" | b"\"" => {
|
||||
if op.op == b"\""
|
||||
&& let (Some(word), Some(char)) = (op.num(0), op.num(1))
|
||||
{
|
||||
state.spacing = [char, word, state.spacing[2]];
|
||||
}
|
||||
state.tlm = Matrix::translate(0.0, -state.leading).then(&state.tlm);
|
||||
state.tm = state.tlm;
|
||||
let mut object = object;
|
||||
if let Some(o) = object.as_deref_mut() {
|
||||
o.new_line();
|
||||
}
|
||||
if op.op != b"T*"
|
||||
&& let Some(Object::String(s)) = op.operands.last()
|
||||
{
|
||||
show(state, object, &s.bytes);
|
||||
}
|
||||
}
|
||||
b"Tj" => {
|
||||
if let Some(Object::String(s)) = op.operands.first() {
|
||||
show(state, object, &s.bytes);
|
||||
}
|
||||
}
|
||||
b"TJ" => {
|
||||
if let Some(Object::Array(items)) = op.operands.first() {
|
||||
let mut object = object;
|
||||
for item in items {
|
||||
match item {
|
||||
Object::String(s) => show(state, object.as_deref_mut(), &s.bytes),
|
||||
other => {
|
||||
let n = other.as_f64().unwrap_or(0.0);
|
||||
let moved = -n / 1000.0 * state.size * state.spacing[2];
|
||||
state.tm = Matrix::translate(moved, 0.0).then(&state.tm);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// The evidence for each `(BT, ET)` operator span of a page, in order. `resources` is the page's
|
||||
/// `/Font` resource dictionary; `fonts` is shared by the document's pages.
|
||||
pub(crate) fn evidence(doc: &Document, fonts: &mut Fonts, resources: &Dict, ops: &[Op], spans: &[(usize, usize)]) -> Vec<Evidence> {
|
||||
let mut by_name: HashMap<Vec<u8>, Option<Rc<Metrics>>> = HashMap::new();
|
||||
let mut state =
|
||||
State { ctm: Matrix::IDENTITY, tm: Matrix::IDENTITY, tlm: Matrix::IDENTITY, size: 0.0, leading: 0.0, invisible: false, metrics: None };
|
||||
let mut by_name: HashMap<Vec<u8>, (Option<Rc<Metrics>>, bool)> = HashMap::new();
|
||||
let mut state = State {
|
||||
ctm: Matrix::IDENTITY,
|
||||
tm: Matrix::IDENTITY,
|
||||
tlm: Matrix::IDENTITY,
|
||||
size: 0.0,
|
||||
leading: 0.0,
|
||||
rise: 0.0,
|
||||
spacing: [0.0, 0.0, 1.0],
|
||||
invisible: false,
|
||||
metrics: None,
|
||||
vertical: false,
|
||||
};
|
||||
let (mut saved, mut unsaved) = (Vec::new(), 0usize);
|
||||
let mut out = Vec::with_capacity(spans.len());
|
||||
let mut spans = spans.iter().peekable();
|
||||
@@ -211,62 +416,15 @@ pub(crate) fn evidence(doc: &Document, fonts: &mut Fonts, resources: &Dict, ops:
|
||||
b"BT" => (state.tm, state.tlm) = (Matrix::IDENTITY, Matrix::IDENTITY),
|
||||
b"Tf" => {
|
||||
state.size = op.num(1).unwrap_or(state.size);
|
||||
state.metrics = op
|
||||
.name(0)
|
||||
.and_then(|name| by_name.entry(name.to_vec()).or_insert_with(|| resources.get(name).and_then(|f| fonts.get(doc, f))).clone());
|
||||
(state.metrics, state.vertical) = op.name(0).map_or((None, false), |name| {
|
||||
let font = || resources.get(name);
|
||||
by_name
|
||||
.entry(name.to_vec())
|
||||
.or_insert_with(|| (font().and_then(|f| fonts.get(doc, f)), font().is_some_and(|f| vertical(doc, f))))
|
||||
.clone()
|
||||
});
|
||||
}
|
||||
b"TL" => state.leading = op.num(0).unwrap_or(state.leading),
|
||||
b"Tr" => state.invisible = matches!(op.num(0), Some(m) if m == 3.0 || m == 7.0),
|
||||
b"Td" | b"TD" => {
|
||||
if let Some([x, y]) = op.nums::<2>() {
|
||||
if op.op == b"TD" {
|
||||
state.leading = -y;
|
||||
}
|
||||
state.tlm = Matrix::translate(x, y).then(&state.tlm);
|
||||
state.tm = state.tlm;
|
||||
if y != 0.0
|
||||
&& let Some(o) = object
|
||||
{
|
||||
o.new_line();
|
||||
}
|
||||
}
|
||||
}
|
||||
b"Tm" => {
|
||||
if let Some(m) = op.nums::<6>() {
|
||||
let moved = m[5] != state.tlm.0[5];
|
||||
(state.tm, state.tlm) = (Matrix(m), Matrix(m));
|
||||
if moved && let Some(o) = object {
|
||||
o.new_line();
|
||||
}
|
||||
}
|
||||
}
|
||||
b"T*" | b"'" | b"\"" => {
|
||||
state.tlm = Matrix::translate(0.0, -state.leading).then(&state.tlm);
|
||||
state.tm = state.tlm;
|
||||
if let Some(o) = object {
|
||||
o.new_line();
|
||||
if op.op != b"T*"
|
||||
&& let Some(Object::String(s)) = op.operands.last()
|
||||
{
|
||||
o.show(&state, &s.bytes);
|
||||
}
|
||||
}
|
||||
}
|
||||
b"Tj" => {
|
||||
if let (Some(o), Some(Object::String(s))) = (object, op.operands.first()) {
|
||||
o.show(&state, &s.bytes);
|
||||
}
|
||||
}
|
||||
b"TJ" => {
|
||||
if let (Some(o), Some(Object::Array(items))) = (object, op.operands.first()) {
|
||||
for item in items {
|
||||
if let Object::String(s) = item {
|
||||
o.show(&state, &s.bytes);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
_ => text_op(&mut state, object, op),
|
||||
}
|
||||
if current.as_ref().is_some_and(|c| c.0 == at)
|
||||
&& let Some((_, o)) = current.take()
|
||||
@@ -283,7 +441,7 @@ mod tests {
|
||||
use super::*;
|
||||
|
||||
fn text(size: f64, chars: usize) -> Evidence {
|
||||
Evidence { size, bold: false, lines: 1, chars, letters: true }
|
||||
Evidence { size, bold: false, lines: 1, chars, letters: true, ..Evidence::default() }
|
||||
}
|
||||
|
||||
fn bold(e: Evidence) -> Evidence {
|
||||
@@ -343,15 +501,23 @@ mod tests {
|
||||
assert!(roles(&[]).is_empty());
|
||||
}
|
||||
|
||||
/// The evidence for each `BT`..`ET` of `content`, drawn in Helvetica-Bold as `/F1`.
|
||||
/// The evidence for each `BT`..`ET` of `content`, drawn in Helvetica-Bold as `/F1`, a font
|
||||
/// with no widths whose name is no standard face as `/F2`, and one whose `/Widths` covers
|
||||
/// only `a` as `/F3`.
|
||||
fn walk(content: &[u8]) -> Vec<Evidence> {
|
||||
let doc = Document::new_empty();
|
||||
let mut font = Dict::new();
|
||||
font.set(b"Type".to_vec(), Object::name("Font"));
|
||||
font.set(b"Subtype".to_vec(), Object::name("Type1"));
|
||||
font.set(b"BaseFont".to_vec(), Object::name("Helvetica-Bold"));
|
||||
let mut resources = Dict::new();
|
||||
resources.set(b"F1".to_vec(), Object::Dict(font));
|
||||
for (name, base, widths) in [("F1", "Helvetica-Bold", None), ("F2", "HouseFont", None), ("F3", "HouseFont", Some(500))] {
|
||||
let mut font = Dict::new();
|
||||
font.set(b"Type".to_vec(), Object::name("Font"));
|
||||
font.set(b"Subtype".to_vec(), Object::name("Type1"));
|
||||
font.set(b"BaseFont".to_vec(), Object::name(base));
|
||||
if let Some(w) = widths {
|
||||
font.set(b"FirstChar".to_vec(), Object::Int(97));
|
||||
font.set(b"Widths".to_vec(), Object::Array(vec![Object::Int(w)]));
|
||||
}
|
||||
resources.set(name.as_bytes().to_vec(), Object::Dict(font));
|
||||
}
|
||||
let ops = pdfcraft_content::parse(content).ops;
|
||||
let at = |name: &[u8]| -> Vec<usize> { ops.iter().enumerate().filter(|(_, o)| o.op == name).map(|(i, _)| i).collect() };
|
||||
let spans: Vec<(usize, usize)> = at(b"BT").into_iter().zip(at(b"ET")).collect();
|
||||
@@ -363,12 +529,56 @@ mod tests {
|
||||
let found = walk(
|
||||
b"q 2 0 0 2 0 0 cm BT /F1 1 Tf 9 0 0 9 10 10 Tm (Title) Tj ET Q BT /F1 12 Tf 10 50 Td (one) Tj T* (two) ' 0 -14 Td (three) Tj ET BT ET",
|
||||
);
|
||||
assert_eq!(found[0], Evidence { size: 18.0, bold: true, lines: 1, chars: 5, letters: true });
|
||||
assert_eq!(found[1], Evidence { size: 12.0, bold: true, lines: 3, chars: 11, letters: true });
|
||||
assert_eq!(found[0], Evidence { size: 18.0, bold: true, lines: 1, chars: 5, letters: true, ..found[0].clone() });
|
||||
assert_eq!(found[1], Evidence { size: 12.0, bold: true, lines: 3, chars: 11, letters: true, ..found[1].clone() });
|
||||
assert_eq!(found[0].text, "Title");
|
||||
// "Title" is 2.056 em wide in Helvetica-Bold, at 18 units from x 20.
|
||||
assert_eq!(rounded(found[0].extent), Some([20.0, 20.0, 57.008, 38.0]), "the run and one font size above it, through Tm and cm");
|
||||
assert_eq!(found[1].text, "one two three");
|
||||
assert_eq!(found[2], Evidence::default());
|
||||
assert_eq!(found.len(), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_rise_moves_the_extent() {
|
||||
// Ts is text space, so a 2x Tm doubles it; it outlives BT and is undone by Q.
|
||||
let found = walk(b"q BT /F1 10 Tf 2 0 0 2 72 760 Tm -180 Ts (Body) Tj ET BT /F1 10 Tf 1 0 0 1 72 760 Tm (Still) Tj ET Q BT /F1 10 Tf 1 0 0 1 72 760 Tm (Back) Tj ET");
|
||||
// Body, Still and Back are 2.5, 1.834 and 2.39 em wide in Helvetica-Bold.
|
||||
assert_eq!(rounded(found[0].extent), Some([72.0, 400.0, 122.0, 420.0]));
|
||||
assert_eq!(rounded(found[1].extent), Some([72.0, 580.0, 90.34, 590.0]));
|
||||
assert_eq!(rounded(found[2].extent), Some([72.0, 760.0, 95.9, 770.0]));
|
||||
}
|
||||
|
||||
fn rounded(extent: Option<[f64; 4]>) -> Option<[f64; 4]> {
|
||||
extent.map(|p| p.map(|v| (v * 1000.0).round() / 1000.0))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_extent_follows_the_run_in_any_direction_with_spacing() {
|
||||
// Turned to run down the page, "Body" reaches 30 units below its origin; one font size
|
||||
// up is to the right. Tc 1 adds 4, TJ -500 adds 6, and Tz 50 halves the whole run.
|
||||
let found = walk(b"q BT /F1 12 Tf 0 -1 1 0 72 760 Tm (Body) Tj ET BT /F1 12 Tf 1 Tc 50 Tz 1 0 0 1 72 700 Tm [(Bo) -500 (dy)] TJ ET Q");
|
||||
assert_eq!(rounded(found[0].extent), Some([72.0, 730.0, 84.0, 760.0]));
|
||||
assert_eq!(rounded(found[1].extent), Some([72.0, 700.0, 92.0, 712.0]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_in_widths_the_font_does_not_declare_has_no_extent() {
|
||||
let found = walk(b"BT /F2 10 Tf (a) Tj ET BT /F3 10 Tf (ab) Tj ET BT /F3 10 Tf (a) Tj ET BT /F1 10 Tf (a) Tj /F9 10 Tf (b) Tj ET");
|
||||
assert_eq!(found[0].extent, None, "no /Widths, and Helvetica only a guess");
|
||||
assert_eq!(found[1].extent, None, "b is past /Widths");
|
||||
assert_eq!(rounded(found[2].extent), Some([0.0, 0.0, 5.0, 10.0]), "a is in /Widths");
|
||||
assert_eq!(found[3].extent, None, "part of it has no font");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_origin_past_f64_leaves_no_extent() {
|
||||
// Two translations near f64::MAX add up to infinity; the text is kept, its position is not.
|
||||
let far = format!("{}.0", "9".repeat(308));
|
||||
let found = walk(format!("q 1 0 0 1 {far} 0 cm BT /F1 10 Tf 1 0 0 1 {far} 0 Tm (far) Tj ET Q").as_bytes());
|
||||
assert_eq!((found[0].text.as_str(), found[0].extent), ("far", None));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn line_moves_leading_invisible_text_and_absurd_sizes() {
|
||||
let found = walk(
|
||||
@@ -379,4 +589,70 @@ mod tests {
|
||||
assert_eq!(found[2].chars, 5, "render mode 3 and 7 text is not counted");
|
||||
assert_eq!(found[3], Evidence::default(), "a size past 1e6 is dropped");
|
||||
}
|
||||
|
||||
/// The evidence for each `BT`..`ET` of `content` in two-byte Type 0 fonts declaring every
|
||||
/// width as 1000: `/H` and `/V` map their codes to Unicode and write horizontally and
|
||||
/// vertically, and `/U` has no Unicode mapping; with `/F1` as in [`walk`].
|
||||
fn walk_type0(content: &[u8]) -> Vec<Evidence> {
|
||||
let cmap = "begincmap 1 begincodespacerange <0000> <FFFF> endcodespacerange 1 beginbfrange <0020> <007E> <0020> endbfrange endcmap";
|
||||
let type0 = |encoding: &str, unicode: &str| {
|
||||
format!("<< /Type /Font /Subtype /Type0 /BaseFont /House /Encoding /{encoding} /DescendantFonts [2 0 R] {unicode} >>")
|
||||
};
|
||||
let doc = crate::tests::pdf(
|
||||
&[
|
||||
"<< /Type /Catalog >>".into(),
|
||||
"<< /Type /Font /Subtype /CIDFontType2 /BaseFont /House /CIDSystemInfo << /Registry (Adobe) /Ordering (Identity) /Supplement 0 >> /DW 1000 >>".into(),
|
||||
crate::tests::stream(cmap),
|
||||
type0("Identity-H", "/ToUnicode 3 0 R"),
|
||||
type0("Identity-V", "/ToUnicode 3 0 R"),
|
||||
type0("Identity-H", ""),
|
||||
"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica-Bold >>".into(),
|
||||
],
|
||||
"",
|
||||
);
|
||||
let mut resources = Dict::new();
|
||||
for (name, n) in [("H", 4), ("V", 5), ("U", 6), ("F1", 7)] {
|
||||
resources.set(name.as_bytes().to_vec(), Object::Ref(ObjRef::new(n, 0)));
|
||||
}
|
||||
let ops = pdfcraft_content::parse(content).ops;
|
||||
let at = |name: &[u8]| -> Vec<usize> { ops.iter().enumerate().filter(|(_, o)| o.op == name).map(|(i, _)| i).collect() };
|
||||
let spans: Vec<(usize, usize)> = at(b"BT").into_iter().zip(at(b"ET")).collect();
|
||||
evidence(&doc, &mut Fonts::default(), &resources, &ops, &spans)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_in_glyphs_without_a_unicode_mapping_has_no_extent() {
|
||||
// A mapped header and, in the same object, unmapped glyphs further down the page: the
|
||||
// object reaches the body, though its text is only the header's.
|
||||
let found = walk_type0(b"BT /F1 12 Tf 72 760 Td (Header) Tj /U 12 Tf 0 -360 Td <00410042> Tj ET BT /H 12 Tf 72 760 Td <00410042> Tj ET");
|
||||
assert_eq!((found[0].text.as_str(), found[0].extent), ("Header", None));
|
||||
assert_eq!(rounded(found[1].extent), Some([72.0, 760.0, 96.0, 772.0]), "mapped Type 0 text keeps its extent");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_after_invisible_vertical_text_has_no_extent() {
|
||||
// The invisible glyph moves the text 360 units down the page before "Body" is shown.
|
||||
let found = walk_type0(b"BT /V 360 Tf 3 Tr 72 760 Td <0041> Tj /F1 12 Tf 0 Tr (Body) Tj ET BT /F1 12 Tf 72 760 Td (Body) Tj ET");
|
||||
assert_eq!((found[0].text.as_str(), found[0].extent), ("Body", None));
|
||||
assert!(found[1].extent.is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spacing_past_f64_leaves_no_extent() {
|
||||
// Tc and Tw near f64::MAX each overflow to infinity and cancel to NaN on the first space.
|
||||
let big = format!("1.0e{}", 999);
|
||||
let found =
|
||||
walk(format!("BT /F1 10 Tf {big} Tc -{big} Tw 72 760 Td ( Body) Tj ET BT /F1 10 Tf 0 Tc 0 Tw 72 760 Td ( Body) Tj ET").as_bytes());
|
||||
assert_eq!((found[0].text.as_str(), found[0].extent), (" Body", None));
|
||||
assert!(found[1].extent.is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_in_a_vertical_font_has_no_extent() {
|
||||
// Thirty glyphs at 12 run 360 units down the page in a vertical font, not along x.
|
||||
let glyphs = format!("<{}>", "0041".repeat(30));
|
||||
let found = walk_type0(format!("BT /V 12 Tf 72 760 Td {glyphs} Tj ET BT /H 12 Tf 72 760 Td {glyphs} Tj ET").as_bytes());
|
||||
assert_eq!((found[0].chars, found[0].extent), (30, None));
|
||||
assert_eq!(rounded(found[1].extent), Some([72.0, 760.0, 432.0, 772.0]));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,428 @@
|
||||
//! Running headers, footers and page numbers among auto-tagged text objects, found by repetition.
|
||||
//!
|
||||
//! A text object is running text when it lies wholly inside the top or bottom 15% of the page as
|
||||
//! displayed, and the same text appears within 4 units of the same distance from that edge on at
|
||||
//! least 40% of the pages, and at least two. Text is compared lowercase with whitespace collapsed,
|
||||
//! each run of digits, and a roman numeral standing alone or after `Page`, matching any number, so
|
||||
//! page numbers repeat. 40% lets alternating left- and right-page headers qualify. A group whose
|
||||
//! text changes from page to page and is all heading-sized (`Chapter 1`, `Chapter 2`) is a
|
||||
//! sequence of headings, not running text, unless it reads as a page number (`Page 3`, `3 of 9`).
|
||||
//! Every object in some qualifying span of distances counts, so spans that overlap and spans that
|
||||
//! lie apart are each marked. Position alone never makes running text.
|
||||
//! A text object whose extent is not known (see [`Evidence::extent`]) is never running text.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use crate::autotag_roles::{Evidence, HEADING_SIZE_RATIO, MAX_KEPT_CHARS};
|
||||
|
||||
/// Depth of the top and bottom bands, as a fraction of the page height.
|
||||
const BAND: f64 = 0.15;
|
||||
/// How far, in user-space units, the same running text may move from page to page.
|
||||
const TOLERANCE: f64 = 4.0;
|
||||
/// Height clusters marked per group of the same text; copies at further heights stay content.
|
||||
const MAX_CLUSTERS: usize = 8;
|
||||
|
||||
/// The page edge running text repeats at.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub(crate) enum Edge {
|
||||
Top,
|
||||
Bottom,
|
||||
}
|
||||
|
||||
impl Edge {
|
||||
/// The artifact subtype (ISO 32000-2 Table 363) for running text at this edge.
|
||||
pub(crate) fn subtype(self) -> &'static str {
|
||||
match self {
|
||||
Edge::Top => "Header",
|
||||
Edge::Bottom => "Footer",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How a page is displayed: its `/Rotate` (0, 90, 180 or 270) and its crop box in user space.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub(crate) struct Frame {
|
||||
pub rotation: i64,
|
||||
pub crop: [f64; 4],
|
||||
}
|
||||
|
||||
/// One page's text objects, in the order of its `(BT, ET)` spans.
|
||||
pub(crate) struct PageText<'a> {
|
||||
pub frame: Frame,
|
||||
pub objects: &'a [Evidence],
|
||||
}
|
||||
|
||||
struct Member<'a> {
|
||||
page: usize,
|
||||
object: usize,
|
||||
distance: f64,
|
||||
evidence: &'a Evidence,
|
||||
}
|
||||
|
||||
/// The edge each text object repeats at, for running text, per page and object.
|
||||
pub(crate) fn find(pages: &[PageText<'_>], body: Option<f64>) -> Vec<Vec<Option<Edge>>> {
|
||||
let mut out: Vec<Vec<Option<Edge>>> = pages.iter().map(|p| vec![None; p.objects.len()]).collect();
|
||||
if pages.len() < 2 {
|
||||
return out;
|
||||
}
|
||||
let needed = pages.len().saturating_mul(2).div_ceil(5).max(2);
|
||||
for ((edge, key), mut members) in groups(pages) {
|
||||
members.sort_by(|a, b| a.distance.total_cmp(&b.distance));
|
||||
for cluster in clusters(&members, needed) {
|
||||
if is_heading_sequence(cluster, &key, body) {
|
||||
continue;
|
||||
}
|
||||
for m in cluster {
|
||||
if let Some(slot) = out.get_mut(m.page).and_then(|p| p.get_mut(m.object)) {
|
||||
*slot = Some(edge);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// `Chapter 1`, `Chapter 2`: heading-sized text that changes, unless it reads as a page number.
|
||||
fn is_heading_sequence(window: &[Member<'_>], key: &str, body: Option<f64>) -> bool {
|
||||
let texts_differ = window.windows(2).any(|w| matches!(w, [a, b] if folded(&a.evidence.text) != folded(&b.evidence.text)));
|
||||
let heading_sized = body.is_some_and(|body| window.iter().all(|m| m.evidence.size >= body * HEADING_SIZE_RATIO));
|
||||
let worded = window.iter().all(|m| m.evidence.letters) && !is_page_number(key);
|
||||
texts_differ && heading_sized && worded
|
||||
}
|
||||
|
||||
/// Lowercase with whitespace collapsed, digits kept: `ANNUAL REPORT` and `Annual report` are the
|
||||
/// same heading, `Chapter 1` and `Chapter 2` are not.
|
||||
fn folded(text: &str) -> String {
|
||||
text.to_lowercase().split_whitespace().collect::<Vec<_>>().join(" ")
|
||||
}
|
||||
|
||||
/// A normalised key that is a page number alone or with its label: `#`, `page #`, `p. #`,
|
||||
/// `# of #`, `page # of #`, `#/#`, optionally in dashes or brackets.
|
||||
fn is_page_number(key: &str) -> bool {
|
||||
let bare = key.trim_matches(|c: char| matches!(c, '-' | '\u{2013}' | '\u{2014}' | '[' | ']' | '(' | ')' | ' '));
|
||||
matches!(bare, "#" | "page #" | "p. #" | "# of #" | "page # of #" | "#/#" | "# / #")
|
||||
}
|
||||
|
||||
/// Text objects inside a band, grouped by edge and normalised text.
|
||||
fn groups<'a>(pages: &'a [PageText<'a>]) -> HashMap<(Edge, String), Vec<Member<'a>>> {
|
||||
let mut groups: HashMap<(Edge, String), Vec<Member<'a>>> = HashMap::new();
|
||||
for (page, text) in pages.iter().enumerate() {
|
||||
let (low, high) = vertical(text.frame.rotation, text.frame.crop);
|
||||
let band = (high - low) * BAND;
|
||||
for (object, evidence) in text.objects.iter().enumerate() {
|
||||
let Some(extent) = evidence.extent.filter(|_| evidence.chars > 0 && evidence.text.chars().count() < MAX_KEPT_CHARS) else {
|
||||
continue;
|
||||
};
|
||||
let (bottom, top) = vertical(text.frame.rotation, extent);
|
||||
let (edge, distance) = if bottom >= high - band && top <= high {
|
||||
(Edge::Top, high - top)
|
||||
} else if top <= low + band && bottom >= low {
|
||||
(Edge::Bottom, bottom - low)
|
||||
} else {
|
||||
continue;
|
||||
};
|
||||
let key = normalise(&evidence.text);
|
||||
if key.is_empty() || !distance.is_finite() {
|
||||
continue;
|
||||
}
|
||||
groups.entry((edge, key)).or_default().push(Member { page, object, distance, evidence });
|
||||
}
|
||||
}
|
||||
groups
|
||||
}
|
||||
|
||||
/// The clusters of `members` (sorted by distance) that run: the union of every window of members
|
||||
/// within [`TOLERANCE`] of the window's first that covers at least `needed` pages, with windows that
|
||||
/// share a member joined into one cluster. A dense run of such windows makes one cluster wider than
|
||||
/// [`TOLERANCE`], still inside the edge band, and the heading check then judges the cluster as a
|
||||
/// whole. At most [`MAX_CLUSTERS`] are returned, nearest the edge first.
|
||||
fn clusters<'m, 'a>(members: &'m [Member<'a>], needed: usize) -> Vec<&'m [Member<'a>]> {
|
||||
let mut on_page: HashMap<usize, usize> = HashMap::new();
|
||||
let mut found: Vec<&'m [Member<'a>]> = Vec::new();
|
||||
let mut current: Option<(usize, usize)> = None;
|
||||
let mut end = 0usize;
|
||||
for (start, first) in members.iter().enumerate() {
|
||||
while let Some(next) = members.get(end).filter(|m| m.distance - first.distance <= TOLERANCE) {
|
||||
let n = on_page.entry(next.page).or_default();
|
||||
*n = n.saturating_add(1);
|
||||
end = end.saturating_add(1);
|
||||
}
|
||||
if on_page.len() >= needed {
|
||||
current = match current {
|
||||
Some((from, to)) if start < to => Some((from, to.max(end))),
|
||||
done => {
|
||||
if let Some(cluster) = done.and_then(|(from, to)| members.get(from..to)) {
|
||||
found.push(cluster);
|
||||
}
|
||||
if found.len() >= MAX_CLUSTERS {
|
||||
return found;
|
||||
}
|
||||
Some((start, end))
|
||||
}
|
||||
};
|
||||
}
|
||||
if let Some(n) = on_page.get_mut(&first.page) {
|
||||
*n = n.saturating_sub(1);
|
||||
if *n == 0 {
|
||||
on_page.remove(&first.page);
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(cluster) = current.and_then(|(from, to)| members.get(from..to)) {
|
||||
found.push(cluster);
|
||||
}
|
||||
found
|
||||
}
|
||||
|
||||
/// The bottom and top of a user-space box as the page displays it.
|
||||
fn vertical(rotation: i64, [x0, y0, x1, y1]: [f64; 4]) -> (f64, f64) {
|
||||
let (a, b) = match rotation {
|
||||
90 => (-x0, -x1),
|
||||
180 => (-y0, -y1),
|
||||
270 => (x0, x1),
|
||||
_ => (y0, y1),
|
||||
};
|
||||
(a.min(b), a.max(b))
|
||||
}
|
||||
|
||||
/// Lowercase, whitespace collapsed, and each digit run, and a roman numeral standing alone or
|
||||
/// after `page`, replaced by `#`.
|
||||
fn normalise(text: &str) -> String {
|
||||
let lower = text.to_lowercase();
|
||||
let words: Vec<&str> = lower.split_whitespace().collect();
|
||||
let roman_alone = match words.as_slice() {
|
||||
[w] | ["page", w] => is_roman(w),
|
||||
_ => false,
|
||||
};
|
||||
let mut out = String::new();
|
||||
for (i, w) in words.iter().enumerate() {
|
||||
if i > 0 {
|
||||
out.push(' ');
|
||||
}
|
||||
if roman_alone && i + 1 == words.len() {
|
||||
out.push('#');
|
||||
continue;
|
||||
}
|
||||
let mut in_digits = false;
|
||||
for c in w.chars() {
|
||||
if c.is_ascii_digit() {
|
||||
if !in_digits {
|
||||
out.push('#');
|
||||
}
|
||||
in_digits = true;
|
||||
} else {
|
||||
out.push(c);
|
||||
in_digits = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// A canonical lowercase roman numeral from 1 to 3999 (`mid` and `iiii` are not).
|
||||
fn is_roman(s: &str) -> bool {
|
||||
const UNITS: [(u32, &str); 13] = [
|
||||
(1000, "m"),
|
||||
(900, "cm"),
|
||||
(500, "d"),
|
||||
(400, "cd"),
|
||||
(100, "c"),
|
||||
(90, "xc"),
|
||||
(50, "l"),
|
||||
(40, "xl"),
|
||||
(10, "x"),
|
||||
(9, "ix"),
|
||||
(5, "v"),
|
||||
(4, "iv"),
|
||||
(1, "i"),
|
||||
];
|
||||
if s.is_empty() || s.len() > 15 {
|
||||
return false;
|
||||
}
|
||||
let (mut rest, mut value) = (s, 0u32);
|
||||
for (v, sym) in UNITS {
|
||||
let mut repeats = 0;
|
||||
while let Some(r) = rest.strip_prefix(sym) {
|
||||
(rest, value, repeats) = (r, value.saturating_add(v), repeats + 1);
|
||||
if repeats > 3 {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
if !rest.is_empty() || value == 0 {
|
||||
return false;
|
||||
}
|
||||
let mut canonical = String::new();
|
||||
for (v, sym) in UNITS {
|
||||
while value >= v {
|
||||
canonical.push_str(sym);
|
||||
value = value.saturating_sub(v);
|
||||
}
|
||||
}
|
||||
canonical == s
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const LETTER: Frame = Frame { rotation: 0, crop: [0.0, 0.0, 612.0, 792.0] };
|
||||
|
||||
/// One line of 10-unit text at baseline `y`.
|
||||
fn line(text: &str, y: f64) -> Evidence {
|
||||
Evidence {
|
||||
size: 10.0,
|
||||
lines: 1,
|
||||
chars: text.chars().filter(|c| !c.is_whitespace()).count(),
|
||||
letters: true,
|
||||
text: text.into(),
|
||||
extent: Some([72.0, y, 72.0, y + 10.0]),
|
||||
..Evidence::default()
|
||||
}
|
||||
}
|
||||
|
||||
fn run(pages: &[Vec<Evidence>], body: Option<f64>) -> Vec<Vec<Option<Edge>>> {
|
||||
let text: Vec<PageText<'_>> = pages.iter().map(|objects| PageText { frame: LETTER, objects }).collect();
|
||||
find(&text, body)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn digits_and_roman_numerals_match_any_number() {
|
||||
assert_eq!(normalise("Page 12 of 30"), "page # of #");
|
||||
assert_eq!(normalise("Annual Report 2026"), "annual report #");
|
||||
assert_eq!(normalise("xiv"), "#");
|
||||
assert_eq!(normalise("Page IX"), "page #");
|
||||
assert_eq!(normalise("mid"), "mid", "not a canonical numeral");
|
||||
assert_eq!(normalise("Chapter iv"), "chapter iv", "a numeral after another word is a word");
|
||||
assert!(is_page_number("#") && is_page_number("page # of #") && is_page_number("- # -") && is_page_number("[p. #]"));
|
||||
assert!(!is_page_number("chapter #") && !is_page_number("page") && !is_page_number("annual report #"));
|
||||
assert!(is_roman("mmmcmxcix") && !is_roman("iiii") && !is_roman("ic") && !is_roman(""));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_header_and_a_numbered_footer_repeat_but_a_body_line_does_not() {
|
||||
let page = |n: usize| vec![line("Annual report", 760.0), line("Repeated body line", 400.0), line(&format!("Page {n}"), 30.0)];
|
||||
let found = run(&[page(1), page(2), page(3)], Some(10.0));
|
||||
for page in found {
|
||||
assert_eq!(page, [Some(Edge::Top), None, Some(Edge::Bottom)]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_single_page_has_no_running_text() {
|
||||
let found = run(&[vec![line("Annual report", 760.0), line("1", 30.0)]], Some(10.0));
|
||||
assert_eq!(found, [[None, None]]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_on_too_few_pages_or_at_another_height_is_not_running() {
|
||||
// Five pages: the footer on one of them, the header 20 units lower on each.
|
||||
let pages: Vec<Vec<Evidence>> = (0..5u32)
|
||||
.map(|i| {
|
||||
let mut page = vec![line("Header", 760.0 - f64::from(i) * 20.0)];
|
||||
if i < 1 {
|
||||
page.push(line("Draft", 30.0));
|
||||
}
|
||||
page
|
||||
})
|
||||
.collect();
|
||||
assert!(run(&pages, None).iter().flatten().all(Option::is_none));
|
||||
// Within the tolerance, alternate headers on two of five pages qualify.
|
||||
let pages: Vec<Vec<Evidence>> = (0..5u32).map(|i| vec![line(if i % 2 == 0 { "Left" } else { "Right" }, 760.0 + f64::from(i))]).collect();
|
||||
let found = run(&pages, None);
|
||||
assert!(found.iter().flatten().all(|e| *e == Some(Edge::Top)), "{found:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn distinct_pages_are_counted_not_objects() {
|
||||
// Six pages need three. Copies at 30 and 32 on the first page and one at 31 on the second
|
||||
// are three objects in a row by height, but only two pages.
|
||||
let note = |y: f64| line("Note", y);
|
||||
let mut pages = vec![vec![note(30.0), note(32.0)], vec![note(31.0)], Vec::new(), Vec::new(), Vec::new(), Vec::new()];
|
||||
assert!(run(&pages, None).iter().flatten().all(Option::is_none));
|
||||
pages[2].push(note(31.0));
|
||||
assert!(run(&pages, None).iter().flatten().any(Option::is_some), "on three pages it runs");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_qualifying_cluster_of_heights_counts() {
|
||||
// Six pages need three: "Note" 20 units below the top on three pages and 40 below on the
|
||||
// other three, plus a second copy on the first page just inside the first cluster.
|
||||
let at = |distance: f64| line("Note", 792.0 - 10.0 - distance);
|
||||
let pages = vec![vec![at(20.0), at(21.0)], vec![at(20.0)], vec![at(20.0)], vec![at(40.0)], vec![at(40.0)], vec![at(40.0)]];
|
||||
let found = run(&pages, None);
|
||||
assert!(found.iter().flatten().all(|e| *e == Some(Edge::Top)), "{found:?}");
|
||||
// On two pages, a copy every 10 units from 20 down puts 9 clusters in the band, past the cap.
|
||||
let column: Vec<Evidence> = (0..12u32).map(|i| at(20.0 + f64::from(i) * 10.0)).collect();
|
||||
let found = run(&[column.clone(), column], None);
|
||||
let marked = found.iter().flatten().filter(|e| e.is_some()).count();
|
||||
assert_eq!(marked, 16, "8 clusters on 2 pages: {found:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overlapping_qualifying_spans_of_heights_both_count() {
|
||||
// Six pages need three: "Note" 20 units below the top on two pages, 24 on one and 28 on
|
||||
// two. 20..24 and 24..28 each cover three pages and share the copy at 24.
|
||||
let at = |distance: f64| line("Note", 792.0 - 10.0 - distance);
|
||||
let pages = vec![vec![at(20.0)], vec![at(20.0)], vec![at(24.0)], vec![at(28.0)], vec![at(28.0)], Vec::new()];
|
||||
let found = run(&pages, None);
|
||||
assert_eq!(found.iter().flatten().filter(|e| **e == Some(Edge::Top)).count(), 5, "{found:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn heading_sized_text_that_changes_is_a_heading_not_a_header() {
|
||||
let big = |text: &str| Evidence { size: 20.0, ..line(text, 750.0) };
|
||||
let found = run(&[vec![big("Chapter 1")], vec![big("Chapter 2")]], Some(10.0));
|
||||
assert_eq!(found, [[None], [None]]);
|
||||
let found = run(&[vec![big("Annual report")], vec![big("Annual report")]], Some(10.0));
|
||||
assert_eq!(found, [[Some(Edge::Top)], [Some(Edge::Top)]], "the same large text on every page is still a header");
|
||||
let number = |text: &str| Evidence { letters: false, ..big(text) };
|
||||
let found = run(&[vec![number("12")], vec![number("13")]], Some(10.0));
|
||||
assert_eq!(found, [[Some(Edge::Top)], [Some(Edge::Top)]], "a large page number is still a page number");
|
||||
let found = run(&[vec![big("xii")], vec![big("xiii")]], Some(10.0));
|
||||
assert_eq!(found, [[Some(Edge::Top)], [Some(Edge::Top)]], "so is a large roman one");
|
||||
let found = run(&[vec![big("Page 1")], vec![big("Page 2")], vec![big("- 3 of 9 -")], vec![big("- 4 of 9 -")]], Some(10.0));
|
||||
assert!(found.iter().flatten().all(|e| *e == Some(Edge::Top)), "a labelled page number is too: {found:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_heading_differing_only_in_case_or_spacing_does_not_change() {
|
||||
let big = |text: &str| Evidence { size: 18.0, ..line(text, 750.0) };
|
||||
let found = run(&[vec![big("ANNUAL REPORT")], vec![big("Annual report")]], Some(12.0));
|
||||
assert_eq!(found, [[Some(Edge::Top)], [Some(Edge::Top)]]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_bands_follow_the_displayed_page() {
|
||||
// Turned 90° clockwise, the displayed top is the user-space left edge (x = 0).
|
||||
let turned = Frame { rotation: 90, crop: [0.0, 0.0, 612.0, 792.0] };
|
||||
let side = Evidence { extent: Some([20.0, 300.0, 30.0, 300.0]), ..line("Side title", 0.0) };
|
||||
let objects = vec![side];
|
||||
let pages = [PageText { frame: turned, objects: &objects }, PageText { frame: turned, objects: &objects }];
|
||||
assert_eq!(find(&pages, None), [[Some(Edge::Top)], [Some(Edge::Top)]]);
|
||||
assert_eq!(run(&[objects.clone(), objects], None), [[None], [None]], "upright, it sits mid-page");
|
||||
// Upside down the displayed top is the user-space bottom; turned 270° it is the right edge.
|
||||
let upside = Frame { rotation: 180, ..turned };
|
||||
let low = vec![line("Upside down", 30.0)];
|
||||
assert_eq!(
|
||||
find(&[PageText { frame: upside, objects: &low }, PageText { frame: upside, objects: &low }], None),
|
||||
[[Some(Edge::Top)], [Some(Edge::Top)]]
|
||||
);
|
||||
let left = Frame { rotation: 270, ..turned };
|
||||
let right = vec![Evidence { extent: Some([590.0, 300.0, 600.0, 300.0]), ..line("Turned left", 0.0) }];
|
||||
assert_eq!(
|
||||
find(&[PageText { frame: left, objects: &right }, PageText { frame: left, objects: &right }], None),
|
||||
[[Some(Edge::Top)], [Some(Edge::Top)]]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_bands_follow_the_crop_box() {
|
||||
// Cropped to y 100..892, text at 860 is in the top band and text at 760 is not.
|
||||
let cropped = Frame { rotation: 0, crop: [0.0, 100.0, 612.0, 892.0] };
|
||||
let objects = vec![line("Inside", 860.0), line("Below the band", 760.0)];
|
||||
let pages = [PageText { frame: cropped, objects: &objects }, PageText { frame: cropped, objects: &objects }];
|
||||
assert_eq!(find(&pages, None), [[Some(Edge::Top), None], [Some(Edge::Top), None]]);
|
||||
assert_eq!(run(&[objects.clone(), objects], None)[0], [None, Some(Edge::Top)], "against the media box it is the other way");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
//! Heading levels for blocks of text laid out on the page, by the rules Auto-tag uses for text
|
||||
//! objects ([`crate::autotag_text`]): the body style is the size carrying the most characters,
|
||||
//! a block is a heading when it is short and larger than the body (or bold where the body is
|
||||
//! not), and levels rank the heading styles over the whole document without skipping a level.
|
||||
|
||||
use crate::autotag_roles::{Evidence, roles};
|
||||
|
||||
/// What one block of text shows: a run of lines set in one style, such as a heading that wraps.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq)]
|
||||
pub struct TextBlock {
|
||||
/// The size it is shown at, in user space.
|
||||
pub size: f64,
|
||||
pub bold: bool,
|
||||
pub lines: usize,
|
||||
/// Characters shown, whitespace excluded.
|
||||
pub chars: usize,
|
||||
/// Whether it includes a letter: a number alone is never a heading.
|
||||
pub letters: bool,
|
||||
}
|
||||
|
||||
/// The heading level of each block, in document order: `Some(1)` to `Some(6)`, or `None` for a
|
||||
/// block that is not a heading. A heading's level is at most one deeper than the heading before.
|
||||
pub fn heading_levels(blocks: &[TextBlock]) -> Vec<Option<u8>> {
|
||||
let evidence: Vec<Evidence> = blocks
|
||||
.iter()
|
||||
.map(|b| Evidence { size: b.size, bold: b.bold, lines: b.lines, chars: b.chars, letters: b.letters, ..Evidence::default() })
|
||||
.collect();
|
||||
roles(&evidence).into_iter().map(|role| role.strip_prefix('H').and_then(|n| n.parse().ok())).collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn block(size: f64, bold: bool, lines: usize, chars: usize) -> TextBlock {
|
||||
TextBlock { size, bold, lines, chars, letters: true }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blocks_take_the_levels_auto_tag_gives_text_objects() {
|
||||
let blocks = [
|
||||
block(18.0, true, 1, 12),
|
||||
block(11.0, false, 8, 600),
|
||||
block(14.0, true, 2, 30),
|
||||
block(11.0, false, 6, 500),
|
||||
block(18.0, true, 1, 9),
|
||||
block(11.0, true, 1, 20),
|
||||
TextBlock { letters: false, ..block(30.0, false, 1, 2) },
|
||||
];
|
||||
assert_eq!(heading_levels(&blocks), [Some(1), None, Some(2), None, Some(1), Some(2), None]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_text_has_no_headings() {
|
||||
assert!(heading_levels(&[]).is_empty());
|
||||
assert_eq!(heading_levels(&[TextBlock::default()]), [None]);
|
||||
}
|
||||
}
|
||||
@@ -10,7 +10,8 @@ use pdfcraft_model::Page;
|
||||
|
||||
use crate::alt::{page_content, standard, tree_root};
|
||||
|
||||
const MAX_HEADINGS: usize = 10_000;
|
||||
/// The most headings [`headings`] returns.
|
||||
pub const MAX_HEADINGS: usize = 10_000;
|
||||
const MAX_VISITS: usize = 1_000_000;
|
||||
const MAX_DEPTH: usize = 256;
|
||||
/// Characters kept of a heading's title.
|
||||
@@ -39,7 +40,13 @@ struct Walker<'a> {
|
||||
texts: HashMap<usize, HashMap<i64, String>>,
|
||||
/// What is left of [`MAX_TITLE_SOURCE_BYTES`].
|
||||
title_left: usize,
|
||||
/// [`Walker::attr`] declined a string the allowance could not hold, since the last reset.
|
||||
declined: bool,
|
||||
out: Vec<Heading>,
|
||||
/// A limit left out a heading that could have been found.
|
||||
cut: bool,
|
||||
/// [`MAX_HEADINGS`] were found and one more was met: the walk stops.
|
||||
full: bool,
|
||||
}
|
||||
|
||||
/// Bytes of `/ActualText`, `/Alt` and `/T` strings the headings of one document decode in all.
|
||||
@@ -49,7 +56,14 @@ const MAX_TITLE_SOURCE_BYTES: usize = 32 << 20;
|
||||
|
||||
/// The headings, in document order. Headings without text or a page are left out.
|
||||
pub fn headings(doc: &Document) -> Vec<Heading> {
|
||||
let Some(root) = tree_root(doc) else { return Vec::new() };
|
||||
headings_with_truncation(doc).0
|
||||
}
|
||||
|
||||
/// [`headings`], and whether headings may be missing from it: there were more than
|
||||
/// [`MAX_HEADINGS`], the structure tree nests or branches past the walk's limits, or a heading's
|
||||
/// only title source was past the title allowance.
|
||||
pub fn headings_with_truncation(doc: &Document) -> (Vec<Heading>, bool) {
|
||||
let Some(root) = tree_root(doc) else { return (Vec::new(), false) };
|
||||
let pages = pdfcraft_model::pages(doc);
|
||||
let mut w = Walker {
|
||||
doc,
|
||||
@@ -60,19 +74,27 @@ pub fn headings(doc: &Document) -> Vec<Heading> {
|
||||
visits: 0,
|
||||
texts: HashMap::new(),
|
||||
title_left: MAX_TITLE_SOURCE_BYTES,
|
||||
declined: false,
|
||||
out: Vec::new(),
|
||||
cut: false,
|
||||
full: false,
|
||||
};
|
||||
if let Some(k) = root.get(b"K") {
|
||||
w.walk(k, None, 0, 0);
|
||||
}
|
||||
w.out
|
||||
(w.out, w.cut)
|
||||
}
|
||||
|
||||
impl Walker<'_> {
|
||||
/// Whether `k` may be visited (bounded depth and size, each object once).
|
||||
/// Whether `k` may be visited (bounded depth and size, each object once). A depth or size
|
||||
/// limit only skips `k`, and is reported in `cut`.
|
||||
fn enter(&mut self, k: &Object, depth: usize) -> bool {
|
||||
self.visits += 1;
|
||||
depth <= MAX_DEPTH && self.visits <= MAX_VISITS && self.out.len() < MAX_HEADINGS && !matches!(k, Object::Ref(r) if !self.seen.insert(*r))
|
||||
if depth > MAX_DEPTH || self.visits > MAX_VISITS {
|
||||
self.cut = true;
|
||||
return false;
|
||||
}
|
||||
!self.full && !matches!(k, Object::Ref(r) if !self.seen.insert(*r))
|
||||
}
|
||||
|
||||
fn element_of(&self, k: &Object) -> Option<(Option<ObjRef>, Dict)> {
|
||||
@@ -101,6 +123,11 @@ impl Walker<'_> {
|
||||
_ => None,
|
||||
};
|
||||
if let Some(level) = level {
|
||||
if self.out.len() >= MAX_HEADINGS {
|
||||
self.cut = true;
|
||||
self.full = true;
|
||||
return;
|
||||
}
|
||||
self.heading(obj, &d, pg, level, depth);
|
||||
return;
|
||||
}
|
||||
@@ -139,6 +166,7 @@ impl Walker<'_> {
|
||||
self.marks(kids, pg, depth + 1, &mut marks);
|
||||
}
|
||||
let Some(page) = pg.or_else(|| marks.iter().find_map(|m| m.0)).and_then(|p| self.page_index.get(&p).copied()) else { return };
|
||||
self.declined = false;
|
||||
let title = match self.attr(d, b"ActualText") {
|
||||
Some(t) => Some(t),
|
||||
None => match self.marked_text(&marks, page) {
|
||||
@@ -146,7 +174,11 @@ impl Walker<'_> {
|
||||
None => self.attr(d, b"Alt").or_else(|| self.attr(d, b"T")),
|
||||
},
|
||||
};
|
||||
let Some(title) = title else { return };
|
||||
let Some(title) = title else {
|
||||
// A title the allowance turned away is a heading left out, not one without text.
|
||||
self.cut |= self.declined;
|
||||
return;
|
||||
};
|
||||
let title: String = title.split_whitespace().collect::<Vec<_>>().join(" ").chars().take(MAX_TITLE).collect();
|
||||
self.out.push(Heading { obj, level, title, page });
|
||||
}
|
||||
@@ -160,6 +192,7 @@ impl Walker<'_> {
|
||||
// not fit the remaining allowance is never decoded: the raw check alone let a string at
|
||||
// the raw limit decode to three times it before the allowance was reduced.
|
||||
if s.bytes.len().saturating_mul(3) > self.title_left {
|
||||
self.declined = true;
|
||||
return None;
|
||||
}
|
||||
let text = s.to_text();
|
||||
|
||||
@@ -16,7 +16,9 @@ mod alt;
|
||||
mod autotag;
|
||||
mod autotag_fields;
|
||||
mod autotag_roles;
|
||||
mod autotag_running;
|
||||
mod content;
|
||||
mod heading_levels;
|
||||
mod headings;
|
||||
mod layout_table;
|
||||
mod report;
|
||||
@@ -40,9 +42,10 @@ fn count_mark_reads(_n: usize) {
|
||||
}
|
||||
|
||||
pub use alt::{AltError, ArtifactError, Figure, figures, mark_decorative, mark_tag_artifact, set_alt};
|
||||
pub use autotag::{AutoTagError, AutoTagResult, autotag_text};
|
||||
pub use autotag::{AutoTagError, AutoTagResult, RunningText, autotag_text, running_text};
|
||||
pub use autotag_fields::tag_form_fields;
|
||||
pub use headings::{Heading, headings};
|
||||
pub use heading_levels::{TextBlock, heading_levels};
|
||||
pub use headings::{Heading, MAX_HEADINGS, headings, headings_with_truncation};
|
||||
pub use layout_table::{LayoutTableError, layout_table_to_blocks};
|
||||
pub use report::{REPORT_WORDS, report_html};
|
||||
pub use tags::{TagContentItem, TagError, TagInfo, TagPlacement, TagProperty, move_tag, set_tag_property, tag_content, tags};
|
||||
|
||||
+283
-6
@@ -5,7 +5,7 @@ use pdfcraft_cos::{Document, Object};
|
||||
use super::*;
|
||||
|
||||
/// A PDF from object bodies (object n = bodies[n - 1]) and extra trailer entries.
|
||||
fn pdf(bodies: &[String], trailer: &str) -> Document {
|
||||
pub(crate) fn pdf(bodies: &[String], trailer: &str) -> Document {
|
||||
let mut out = b"%PDF-1.7\n".to_vec();
|
||||
let mut offsets = Vec::new();
|
||||
for (i, b) in bodies.iter().enumerate() {
|
||||
@@ -21,7 +21,7 @@ fn pdf(bodies: &[String], trailer: &str) -> Document {
|
||||
Document::open(Arc::new(out)).unwrap()
|
||||
}
|
||||
|
||||
fn stream(data: &str) -> String {
|
||||
pub(crate) fn stream(data: &str) -> String {
|
||||
format!("<< /Length {} >>\nstream\n{data}\nendstream", data.len())
|
||||
}
|
||||
|
||||
@@ -50,7 +50,7 @@ fn autotag_text_writes_marked_content_and_parent_tree_across_pages() {
|
||||
"",
|
||||
);
|
||||
let result = autotag_text(&mut doc).unwrap();
|
||||
assert_eq!(result, AutoTagResult { pages: 2, paragraphs: 2, headings: 1 });
|
||||
assert_eq!(result, AutoTagResult { pages: 2, paragraphs: 2, headings: 1, headers: 0, footers: 0 });
|
||||
let catalog = doc.get(doc.root().unwrap());
|
||||
let root = catalog.as_dict().unwrap().reference(b"StructTreeRoot").unwrap();
|
||||
let tree = doc.get(root);
|
||||
@@ -83,6 +83,194 @@ fn autotag_text_writes_marked_content_and_parent_tree_across_pages() {
|
||||
assert_eq!(status(&check(&reopened, &Options::default()), Rule::TaggedContent), Status::Passed);
|
||||
}
|
||||
|
||||
/// Three pages with a running header, a numbered footer and a body line repeated mid-page
|
||||
/// (#7065): the header and footer become pagination artifacts without MCIDs, the rest is tagged.
|
||||
fn running_text_pdf() -> Document {
|
||||
let page = |n: usize| {
|
||||
stream(&format!(
|
||||
"BT /F1 9 Tf 72 760 Td (Annual report) Tj ET BT /F1 12 Tf 72 640 Td (Body text on page {n} that is long enough to set the body size) Tj ET \
|
||||
BT /F1 12 Tf 72 400 Td (A body line repeated on every page) Tj ET BT /F1 9 Tf 300 30 Td (Page {n}) Tj ET"
|
||||
))
|
||||
};
|
||||
let leaf = |contents: usize| format!("<< /Type /Page /Parent 2 0 R /Contents {contents} 0 R >>");
|
||||
pdf(
|
||||
&[
|
||||
"<< /Type /Catalog /Pages 2 0 R >>".into(),
|
||||
"<< /Type /Pages /Kids [3 0 R 4 0 R 5 0 R] /Count 3 /MediaBox [0 0 612 792] /Resources << /Font << /F1 9 0 R >> >> >>".into(),
|
||||
leaf(6),
|
||||
leaf(7),
|
||||
leaf(8),
|
||||
page(1),
|
||||
page(2),
|
||||
page(3),
|
||||
FONT.into(),
|
||||
],
|
||||
"",
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn autotag_text_marks_running_headers_and_footers_as_pagination_artifacts() {
|
||||
let mut doc = running_text_pdf();
|
||||
let found = running_text(&doc).unwrap();
|
||||
let listed: Vec<(usize, &str, &str)> = found.iter().map(|r| (r.page, r.subtype, r.text.as_str())).collect();
|
||||
assert_eq!(
|
||||
listed,
|
||||
[
|
||||
(0, "Header", "Annual report"),
|
||||
(0, "Footer", "Page 1"),
|
||||
(1, "Header", "Annual report"),
|
||||
(1, "Footer", "Page 2"),
|
||||
(2, "Header", "Annual report"),
|
||||
(2, "Footer", "Page 3")
|
||||
]
|
||||
);
|
||||
let result = autotag_text(&mut doc).unwrap();
|
||||
assert_eq!(result, AutoTagResult { pages: 3, paragraphs: 6, headings: 0, headers: 3, footers: 3 });
|
||||
for page in pdfcraft_model::pages(&doc) {
|
||||
let content = doc.resolve(page.dict.get(b"Contents").unwrap());
|
||||
let Object::Stream(stream) = &*content else { panic!("marked page content") };
|
||||
let text = String::from_utf8(stream.decoded_strict().unwrap()).unwrap();
|
||||
// Each BDC in order: the artifact subtype, or the tag and its MCID.
|
||||
let marks: Vec<String> = pdfcraft_content::parse(text.as_bytes())
|
||||
.ops
|
||||
.iter()
|
||||
.filter(|op| op.op == b"BDC")
|
||||
.map(|op| {
|
||||
let d = op.operands.get(1).and_then(Object::as_dict).unwrap();
|
||||
match op.name(0).unwrap() {
|
||||
b"Artifact" => {
|
||||
assert_eq!(d.name(b"Type"), Some(&b"Pagination"[..]));
|
||||
assert!(!d.contains(b"MCID"), "an artifact has no MCID");
|
||||
String::from_utf8(d.name(b"Subtype").unwrap().to_vec()).unwrap()
|
||||
}
|
||||
tag => format!("{} {}", String::from_utf8_lossy(tag), d.get(b"MCID").and_then(Object::as_int).unwrap()),
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(marks, ["Header", "P 0", "P 1", "Footer"], "{text}");
|
||||
}
|
||||
let kinds: Vec<String> = tags(&doc).iter().map(|t| t.kind.clone()).collect();
|
||||
assert_eq!(kinds, ["Document", "P", "P", "P", "P", "P", "P"]);
|
||||
assert_eq!(status(&check(&doc, &Options::default()), Rule::TaggedContent), Status::Passed);
|
||||
}
|
||||
|
||||
/// Roles are assigned over the tagged text only: a running header before a heading does not
|
||||
/// shift the heading's role onto the next object.
|
||||
#[test]
|
||||
fn autotag_text_assigns_roles_past_running_headers() {
|
||||
let body = "BT /F1 12 Tf 72 640 Td (Body text that is long enough to set the body size of the document) Tj ET";
|
||||
let page = |extra: &str| stream(&format!("BT /F1 9 Tf 72 760 Td (Annual report) Tj ET {extra} {body}"));
|
||||
let leaf = |contents: usize| format!("<< /Type /Page /Parent 2 0 R /Contents {contents} 0 R >>");
|
||||
let mut doc = pdf(
|
||||
&[
|
||||
"<< /Type /Catalog /Pages 2 0 R >>".into(),
|
||||
"<< /Type /Pages /Kids [3 0 R 4 0 R] /Count 2 /MediaBox [0 0 612 792] /Resources << /Font << /F1 7 0 R >> >> >>".into(),
|
||||
leaf(5),
|
||||
leaf(6),
|
||||
page("BT /F1 18 Tf 72 700 Td (Introduction) Tj ET"),
|
||||
page(""),
|
||||
FONT.into(),
|
||||
],
|
||||
"",
|
||||
);
|
||||
let result = autotag_text(&mut doc).unwrap();
|
||||
assert_eq!((result.headers, result.headings, result.paragraphs), (2, 1, 2));
|
||||
let kinds: Vec<String> = tags(&doc).iter().map(|t| t.kind.clone()).collect();
|
||||
assert_eq!(kinds, ["Document", "H1", "P", "P"]);
|
||||
}
|
||||
|
||||
/// A page whose only text is running text has nothing in the parent tree and gets no
|
||||
/// `StructParents`; the next tagged page takes the next key.
|
||||
#[test]
|
||||
fn autotag_text_gives_a_page_of_running_text_alone_no_struct_parents() {
|
||||
let header = "BT /F1 9 Tf 72 760 Td (Annual report) Tj ET";
|
||||
let leaf = |contents: usize| format!("<< /Type /Page /Parent 2 0 R /Contents {contents} 0 R >>");
|
||||
let mut doc = pdf(
|
||||
&[
|
||||
"<< /Type /Catalog /Pages 2 0 R >>".into(),
|
||||
"<< /Type /Pages /Kids [3 0 R 4 0 R] /Count 2 /MediaBox [0 0 612 792] /Resources << /Font << /F1 7 0 R >> >> >>".into(),
|
||||
leaf(5),
|
||||
leaf(6),
|
||||
stream(header),
|
||||
stream(&format!("{header} BT /F1 12 Tf 72 640 Td (Body) Tj ET")),
|
||||
FONT.into(),
|
||||
],
|
||||
"",
|
||||
);
|
||||
let result = autotag_text(&mut doc).unwrap();
|
||||
assert_eq!(result, AutoTagResult { pages: 1, paragraphs: 1, headings: 0, headers: 2, footers: 0 });
|
||||
let keys: Vec<Option<i64>> = pdfcraft_model::pages(&doc).iter().map(|p| p.dict.get(b"StructParents").and_then(Object::as_int)).collect();
|
||||
assert_eq!(keys, [None, Some(0)]);
|
||||
assert_eq!(status(&check(&doc, &Options::default()), Rule::TaggedContent), Status::Passed);
|
||||
}
|
||||
|
||||
/// A body line turned to run down from the top of each page starts in the header band but does
|
||||
/// not lie inside it: it is not running text.
|
||||
#[test]
|
||||
fn autotag_text_leaves_turned_text_that_runs_out_of_the_band_tagged() {
|
||||
let body = "BT /F1 12 Tf 0 -1 1 0 72 760 Tm (A body line set turned so that it runs down the page) Tj ET";
|
||||
let leaf = |contents: usize| format!("<< /Type /Page /Parent 2 0 R /Contents {contents} 0 R >>");
|
||||
let doc = pdf(
|
||||
&[
|
||||
"<< /Type /Catalog /Pages 2 0 R >>".into(),
|
||||
"<< /Type /Pages /Kids [3 0 R 4 0 R] /Count 2 /MediaBox [0 0 612 792] /Resources << /Font << /F1 7 0 R >> >> >>".into(),
|
||||
leaf(5),
|
||||
leaf(6),
|
||||
stream(body),
|
||||
stream(body),
|
||||
FONT.into(),
|
||||
],
|
||||
"",
|
||||
);
|
||||
assert_eq!(running_text(&doc).unwrap(), []);
|
||||
}
|
||||
|
||||
/// Turned body text whose negative character spacing brings each line's advance back to zero
|
||||
/// still has glyphs running down the page from the header band: it is not running text.
|
||||
#[test]
|
||||
fn autotag_text_leaves_turned_text_pulled_back_by_negative_spacing_tagged() {
|
||||
// A is 12 units wide and advances 6 at Tc -6; B is 0 wide and advances -6. Thirty of each
|
||||
// end where they began, but the A glyphs reach 186 units down from y 760.
|
||||
let body = format!("BT /F1 12 Tf -6 Tc 0 -1 1 0 72 760 Tm ({}{}) Tj ET", "A".repeat(30), "B".repeat(30));
|
||||
let font = "<< /Type /Font /Subtype /Type1 /BaseFont /HouseFont /FirstChar 65 /LastChar 66 /Widths [1000 0] >>";
|
||||
let leaf = |contents: usize| format!("<< /Type /Page /Parent 2 0 R /Contents {contents} 0 R >>");
|
||||
let mut doc = pdf(
|
||||
&[
|
||||
"<< /Type /Catalog /Pages 2 0 R >>".into(),
|
||||
"<< /Type /Pages /Kids [3 0 R 4 0 R] /Count 2 /MediaBox [0 0 612 792] /Resources << /Font << /F1 7 0 R >> >> >>".into(),
|
||||
leaf(5),
|
||||
leaf(6),
|
||||
stream(&body),
|
||||
stream(&body),
|
||||
font.into(),
|
||||
],
|
||||
"",
|
||||
);
|
||||
assert_eq!(running_text(&doc).unwrap(), []);
|
||||
let result = autotag_text(&mut doc).unwrap();
|
||||
assert_eq!((result.headers, result.footers, result.paragraphs), (0, 0, 2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn autotag_text_leaves_a_single_page_header_tagged() {
|
||||
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 612 792] /Contents 4 0 R /Resources << /Font << /F1 5 0 R >> >> >>".into(),
|
||||
stream(
|
||||
"BT /F1 9 Tf 72 760 Td (Annual report) Tj ET BT /F1 12 Tf 72 640 Td (Body text long enough to set the body size) Tj ET BT /F1 9 Tf 300 30 Td (1) Tj ET",
|
||||
),
|
||||
FONT.into(),
|
||||
],
|
||||
"",
|
||||
);
|
||||
assert_eq!(running_text(&doc).unwrap(), []);
|
||||
let result = autotag_text(&mut doc).unwrap();
|
||||
assert_eq!((result.headers, result.footers, result.paragraphs), (0, 0, 3));
|
||||
}
|
||||
|
||||
/// 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`).
|
||||
@@ -108,7 +296,7 @@ fn autotag_text_reads_content_with_parameters_given_by_reference() {
|
||||
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, headings: 0 });
|
||||
assert_eq!(autotag_text(&mut doc).unwrap(), AutoTagResult { pages: 1, paragraphs: 1, headings: 0, headers: 0, footers: 0 });
|
||||
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") };
|
||||
@@ -161,7 +349,7 @@ fn autotag_text_marks_vector_graphics_and_images_as_artifacts() {
|
||||
"",
|
||||
);
|
||||
let result = autotag_text(&mut doc).unwrap();
|
||||
assert_eq!(result, AutoTagResult { pages: 1, paragraphs: 1, headings: 0 });
|
||||
assert_eq!(result, AutoTagResult { pages: 1, paragraphs: 1, headings: 0, headers: 0, footers: 0 });
|
||||
let report = check(&doc, &Options { rules: [Rule::TaggedPdf, Rule::TaggedContent].into(), pages: None });
|
||||
assert_eq!(status(&report, Rule::TaggedPdf), Status::Passed);
|
||||
assert_eq!(status(&report, Rule::TaggedContent), Status::Passed);
|
||||
@@ -1680,8 +1868,97 @@ fn headings_naming_one_large_string_stop_decoding_it_at_the_allowance() {
|
||||
format!("({})", "a".repeat(512 << 10)),
|
||||
];
|
||||
objects.extend((0..count).map(|_| "<< /S /H1 /P 6 0 R /Pg 3 0 R /ActualText 7 0 R >>".to_string()));
|
||||
let found = headings(&pdf(&objects, ""));
|
||||
let (found, cut) = headings_with_truncation(&pdf(&objects, ""));
|
||||
assert!(!found.is_empty() && found.len() < count, "{}", found.len());
|
||||
assert!(cut, "headings whose title the allowance turned away were dropped unreported");
|
||||
}
|
||||
|
||||
/// A title source too large for the allowance is passed over for the next one, and the heading
|
||||
/// it names is kept and not reported as missing.
|
||||
#[test]
|
||||
fn a_title_too_large_for_the_allowance_falls_back_without_truncation() {
|
||||
let objects = vec![
|
||||
"<< /Type /Catalog /Pages 2 0 R /MarkInfo << /Marked true >> /StructTreeRoot 5 0 R >>".to_string(),
|
||||
"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_string(),
|
||||
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Contents 4 0 R >>".to_string(),
|
||||
stream("BT ET"),
|
||||
"<< /Type /StructTreeRoot /K 6 0 R >>".to_string(),
|
||||
"<< /S /Document /P 5 0 R /K [8 0 R] >>".to_string(),
|
||||
format!("({})", "a".repeat((32 << 20) / 3 + 1)),
|
||||
"<< /S /H1 /P 6 0 R /Pg 3 0 R /ActualText 7 0 R /Alt (Short) >>".to_string(),
|
||||
];
|
||||
let (found, cut) = headings_with_truncation(&pdf(&objects, ""));
|
||||
let titles: Vec<String> = found.into_iter().map(|h| h.title).collect();
|
||||
assert_eq!((titles, cut), (vec!["Short".to_string()], false));
|
||||
}
|
||||
|
||||
/// A tree of `count` H1 elements, each with its text and page.
|
||||
fn many_headings(count: usize) -> Vec<String> {
|
||||
let kids: String = (0..count).map(|i| format!("{} 0 R ", i + 7)).collect();
|
||||
let mut objects = vec![
|
||||
"<< /Type /Catalog /Pages 2 0 R /StructTreeRoot 5 0 R >>".to_string(),
|
||||
"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_string(),
|
||||
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Contents 4 0 R >>".to_string(),
|
||||
stream("BT ET"),
|
||||
"<< /Type /StructTreeRoot /K 6 0 R >>".to_string(),
|
||||
format!("<< /S /Document /P 5 0 R /K [{kids}] >>"),
|
||||
];
|
||||
objects.extend((0..count).map(|_| "<< /S /H1 /P 6 0 R /Pg 3 0 R /ActualText (Head) >>".to_string()));
|
||||
objects
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn headings_past_the_cap_are_reported() {
|
||||
let (at_cap, cut) = headings_with_truncation(&pdf(&many_headings(MAX_HEADINGS), ""));
|
||||
assert_eq!((at_cap.len(), cut), (MAX_HEADINGS, false));
|
||||
let (over, cut) = headings_with_truncation(&pdf(&many_headings(MAX_HEADINGS + 1), ""));
|
||||
assert_eq!((over.len(), cut), (MAX_HEADINGS, true), "a heading past the cap was dropped unreported");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_heading_nested_past_the_depth_limit_is_reported() {
|
||||
let mut objs = headings_doc();
|
||||
let (found, cut) = headings_with_truncation(&pdf(&objs, ""));
|
||||
assert!(!found.is_empty() && !cut);
|
||||
// Element 17 opens a chain of 300 sections, each holding the next, around one H1.
|
||||
let first = objs.len() + 1;
|
||||
objs[9] = format!("<< /S /Document /K [12 0 R {first} 0 R] >>");
|
||||
objs.extend((1..=300).map(|i| format!("<< /S /Sect /K {} 0 R >>", first + i)));
|
||||
objs.push("<< /S /H1 /Pg 3 0 R /ActualText (Deep) >>".into());
|
||||
let (found, cut) = headings_with_truncation(&pdf(&objs, ""));
|
||||
assert!(found.iter().all(|h| h.title != "Deep") && cut, "a heading too deep to reach was dropped unreported");
|
||||
}
|
||||
|
||||
/// A branch too deep to walk is skipped, not the end of the walk: a heading after it is found.
|
||||
#[test]
|
||||
fn a_heading_after_a_branch_past_the_depth_limit_is_found() {
|
||||
let mut objs = headings_doc();
|
||||
let first = objs.len() + 1;
|
||||
objs[9] = format!("<< /S /Document /K [{first} 0 R 12 0 R] >>");
|
||||
objs.extend((1..=300).map(|i| format!("<< /S /Sect /K {} 0 R >>", first + i)));
|
||||
objs.push("<< /S /H1 /Pg 3 0 R /ActualText (Deep) >>".into());
|
||||
let (found, cut) = headings_with_truncation(&pdf(&objs, ""));
|
||||
let titles: Vec<&str> = found.iter().map(|h| h.title.as_str()).collect();
|
||||
assert_eq!((titles, cut), (vec!["Chapter One"], true), "the deep branch stopped the walk");
|
||||
}
|
||||
|
||||
/// An H1 `sects + 1` elements down whose title is only its marked content.
|
||||
fn heading_under_sections(sects: usize) -> (Vec<Heading>, bool) {
|
||||
let mut objs = headings_doc();
|
||||
let first = objs.len() + 1;
|
||||
objs[9] = format!("<< /S /Document /K {first} 0 R >>");
|
||||
objs.extend((1..=sects).map(|i| format!("<< /S /Sect /K {} 0 R >>", first + i)));
|
||||
objs.push("<< /S /H1 /Pg 3 0 R /K 0 >>".into());
|
||||
headings_with_truncation(&pdf(&objs, ""))
|
||||
}
|
||||
|
||||
/// Marked content past the depth limit is reported too: the H1 whose title it holds is lost.
|
||||
#[test]
|
||||
fn marked_content_past_the_depth_limit_is_reported() {
|
||||
let (found, cut) = heading_under_sections(254);
|
||||
assert_eq!((found.iter().map(|h| h.title.as_str()).collect::<Vec<_>>(), cut), (vec!["Chapter One"], false));
|
||||
let (found, cut) = heading_under_sections(255);
|
||||
assert!(found.is_empty() && cut, "a heading whose text was too deep was dropped unreported");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -0,0 +1,467 @@
|
||||
//! Contributor-original synthetic stream collision; no external document assets.
|
||||
use pdfcraft_cos::{Document, ObjRef, Object};
|
||||
use std::sync::Arc;
|
||||
|
||||
fn collision_with(kids: &str, extra: &[&str]) -> Document {
|
||||
let page = "/Figure <</MCID 0>> BDC 10 10 20 20 re f EMC\nq /Form Do Q";
|
||||
let form = "/Figure <</MCID 0>> BDC 0 0 5 5 re f EMC";
|
||||
let mut objects = vec![
|
||||
"<< /Type /Catalog /Pages 2 0 R /StructTreeRoot 5 0 R /MarkInfo << /Marked true >> >>".into(),
|
||||
"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".into(),
|
||||
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 100 100] /Contents 4 0 R /StructParents 0 /Resources << /XObject << /Form 10 0 R >> >> >>"
|
||||
.into(),
|
||||
format!("<< /Length {} >>\nstream\n{}\nendstream", page.len(), page),
|
||||
"<< /Type /StructTreeRoot /K 6 0 R /ParentTree 9 0 R >>".into(),
|
||||
"<< /Type /StructElem /S /Document /P 5 0 R /K [7 0 R 8 0 R] >>".into(),
|
||||
"<< /Type /StructElem /S /Figure /Pg 3 0 R /P 6 0 R /K 0 /Alt (Page figure) >>".into(),
|
||||
format!("<< /Type /StructElem /S /Figure /Pg 3 0 R /P 6 0 R /K {kids} /Alt (Form figure) >>"),
|
||||
"<< /Nums [0 [7 0 R] 1 8 0 R] >>".into(),
|
||||
format!("<< /Type /XObject /Subtype /Form /BBox [0 0 5 5] /StructParents 1 /Length {} >>\nstream\n{}\nendstream", form.len(), form),
|
||||
];
|
||||
let extra_pages = extra
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, object)| object.contains("/Type /Page "))
|
||||
.map(|(index, _)| format!("{} 0 R", index + 11))
|
||||
.collect::<Vec<_>>();
|
||||
if !extra_pages.is_empty() {
|
||||
objects[1] = format!("<< /Type /Pages /Kids [3 0 R {}] /Count {} >>", extra_pages.join(" "), extra_pages.len() + 1);
|
||||
}
|
||||
objects.extend(extra.iter().map(|s| (*s).to_string()));
|
||||
let mut bytes = b"%PDF-1.7\n".to_vec();
|
||||
let mut offsets = Vec::new();
|
||||
for (i, object) in objects.iter().enumerate() {
|
||||
offsets.push(bytes.len());
|
||||
bytes.extend_from_slice(format!("{} 0 obj\n{}\nendobj\n", i + 1, object).as_bytes());
|
||||
}
|
||||
let start = bytes.len();
|
||||
bytes.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objects.len() + 1).as_bytes());
|
||||
for offset in offsets {
|
||||
bytes.extend_from_slice(format!("{offset:010} 00000 n \n").as_bytes());
|
||||
}
|
||||
bytes.extend_from_slice(format!("trailer << /Size {} /Root 1 0 R >>\nstartxref\n{}\n%%EOF\n", objects.len() + 1, start).as_bytes());
|
||||
Document::open(Arc::new(bytes)).unwrap()
|
||||
}
|
||||
|
||||
fn stream(doc: &Document, number: u32) -> Vec<u8> {
|
||||
let object = doc.get(ObjRef::new(number, 0));
|
||||
let Object::Stream(s) = &*object else { panic!("stream required") };
|
||||
s.decoded().unwrap()
|
||||
}
|
||||
|
||||
fn run(decorative: bool) {
|
||||
let mut doc = collision_with("<< /Type /MCR /MCID 0 /Stm 10 0 R /Pg 3 0 R >>", &[]);
|
||||
assert!(!doc.is_modified());
|
||||
let before = pdfcraft_cos::write_full(&doc, &Default::default()).unwrap();
|
||||
let original_streams = [stream(&doc, 4), stream(&doc, 10)];
|
||||
let error = mutate(&mut doc, decorative, 8).unwrap_err();
|
||||
assert!(error.contains("form"), "useful error: {error}");
|
||||
assert!(!doc.is_modified());
|
||||
assert_eq!([stream(&doc, 4), stream(&doc, 10)], original_streams);
|
||||
assert_eq!(pdfcraft_cos::write_full(&doc, &Default::default()).unwrap(), before);
|
||||
assert_eq!(pdfcraft_a11y::tags(&doc).iter().map(|t| t.object.num).collect::<Vec<_>>(), [6, 7, 8]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decorative_refuses_form_collision() {
|
||||
run(true);
|
||||
}
|
||||
#[test]
|
||||
fn artifact_refuses_form_collision() {
|
||||
run(false);
|
||||
}
|
||||
|
||||
fn mutate(doc: &mut Document, decorative: bool, number: u32) -> Result<(), String> {
|
||||
if decorative {
|
||||
pdfcraft_a11y::mark_decorative(doc, ObjRef::new(number, 0)).map_err(|e| e.to_string())
|
||||
} else {
|
||||
pdfcraft_a11y::mark_tag_artifact(doc, ObjRef::new(number, 0)).map_err(|e| e.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
fn page_owned(kids: &str, extra: &[&str]) -> Document {
|
||||
let mut doc = collision_with(kids, extra);
|
||||
let page_kids = doc.get(ObjRef::new(8, 0)).as_dict().unwrap().get(b"K").unwrap().clone();
|
||||
let original = collision_with("<< /Type /MCR /MCID 0 /Stm 10 0 R /Pg 3 0 R >>", &[]);
|
||||
let form_kids = original.get(ObjRef::new(8, 0)).as_dict().unwrap().get(b"K").unwrap().clone();
|
||||
doc.update_dict(ObjRef::new(7, 0), |d| d.set(b"K".to_vec(), page_kids)).unwrap();
|
||||
doc.update_dict(ObjRef::new(8, 0), |d| d.set(b"K".to_vec(), form_kids)).unwrap();
|
||||
// Reopen an incremental save to keep the fixture's object IDs and start from a clean state.
|
||||
Document::open(Arc::new(pdfcraft_cos::write_incremental(&doc, &Default::default()).unwrap())).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsupported_owned_references_refuse_without_changing_document_or_saved_data() {
|
||||
let other_page_content = "/P <</MCID 0>> BDC 40 40 5 5 re f EMC";
|
||||
let other_page_stream = format!("<< /Length {} >>\nstream\n{other_page_content}\nendstream", other_page_content.len());
|
||||
let cases: Vec<(&str, Vec<&str>)> = vec![
|
||||
("<< /Type /MCR /MCID 0 /Stm 10 0 R >>", vec![]),
|
||||
("<< /Type /MCR /MCID 2 /Stm 10 0 R >>", vec![]),
|
||||
("<< /Type /MCR /MCID 0 /Stm null >>", vec![]),
|
||||
("<< /Type /MCR /MCID 0 /Stm 99 0 R >>", vec![]),
|
||||
("<< /Type /MCR /MCID 0 /Stm (invalid) >>", vec![]),
|
||||
("<< /Type /MCR /MCID 0 /StmOwn 10 0 R >>", vec![]),
|
||||
("<< /Type /MCR /MCID 0 /StmOwn null >>", vec![]),
|
||||
("11 0 R", vec!["<< /Type /MCR /MCID 0 /Stm 10 0 R >>"]),
|
||||
("11 0 R", vec!["12 0 R", "<< /Type /MCR /MCID 0 /Stm 10 0 R >>"]),
|
||||
("[0 << /S /Figure /K 0 >>]", vec![]),
|
||||
("[0 11 0 R]", vec!["<< /S /Figure /K 0 >>"]),
|
||||
("[0 << /Type /MCR /MCID 0 /Stm 10 0 R >>]", vec![]),
|
||||
("11 0 R", vec!["[0 12 0 R]", "<< /Type /MCR /MCID 0 /Stm 10 0 R >>"]),
|
||||
("[0 [11 0 R]]", vec!["<< /Type /MCR /MCID 0 /Stm 10 0 R >>"]),
|
||||
("[0 << /Type /MCR /MCID 0 /Pg 99 0 R >>]", vec![]),
|
||||
("<< /Type /MCR /MCID 0 /Pg null >>", vec![]),
|
||||
("<< /Type /MCR /MCID 0 /Pg 3 1 R >>", vec![]),
|
||||
(
|
||||
"[0 << /Type /MCR /MCID 0 /Pg 11 0 R >>]",
|
||||
vec!["<< /Type /Page /Parent 2 0 R /MediaBox [0 0 100 100] /Contents 12 0 R >>", &other_page_stream],
|
||||
),
|
||||
("[0 << /MCID 0 /Pg 3 0 R >>]", vec![]),
|
||||
("[0 << /Type /MCR /Pg 3 0 R >>]", vec![]),
|
||||
("[0 99 0 R]", vec![]),
|
||||
("[0 11 1 R]", vec!["<< /Type /MCR /MCID 0 /Pg 3 0 R >>"]),
|
||||
("[0 11 0 R]", vec!["[11 0 R]"]),
|
||||
("[0 11 0 R]", vec!["<< /S /Figure /K << /Type /MCR /MCID 0 /Stm 10 0 R >> >>"]),
|
||||
("11 0 R", vec!["[12 0 R]", "<< /S /Figure /K << /Type /MCR /MCID 0 /Stm 10 0 R >> >>"]),
|
||||
];
|
||||
for decorative in [true, false] {
|
||||
for (kids, extra) in &cases {
|
||||
let mut doc = collision_with(kids, extra);
|
||||
let before = pdfcraft_cos::write_full(&doc, &Default::default()).unwrap();
|
||||
let original_streams = [stream(&doc, 4), stream(&doc, 10)];
|
||||
let original_objects: Vec<_> = (1..=10).map(|i| doc.get(ObjRef::new(i, 0))).collect();
|
||||
let original_alts = pdfcraft_a11y::figures(&doc).into_iter().map(|figure| figure.alt).collect::<Vec<_>>();
|
||||
let error = match mutate(&mut doc, decorative, 8) {
|
||||
Ok(()) => panic!("decorative={decorative} K={kids} must refuse"),
|
||||
Err(error) => error,
|
||||
};
|
||||
assert!(
|
||||
error.contains("form") || error.contains("unsupported") || error.contains("invalid") || error.contains("child structure elements"),
|
||||
"ownership refusal needs a useful reason: {error}"
|
||||
);
|
||||
assert!(!doc.is_modified(), "refusal must not create dirty state: {kids}");
|
||||
assert_eq!([stream(&doc, 4), stream(&doc, 10)], original_streams, "{kids}");
|
||||
assert_eq!(
|
||||
(1..=10).map(|i| doc.get(ObjRef::new(i, 0))).collect::<Vec<_>>(),
|
||||
original_objects,
|
||||
"tags, Alt and ParentTree stay unchanged: {kids}"
|
||||
);
|
||||
let saved = pdfcraft_cos::write_full(&doc, &Default::default()).unwrap();
|
||||
assert_eq!(saved, before, "saved object graph remains exact: {kids}");
|
||||
let reopened = Document::open(Arc::new(saved)).unwrap();
|
||||
let page = &pdfcraft_model::pages(&reopened)[0];
|
||||
let Object::Stream(page_stream) = &*reopened.resolve(page.dict.get(b"Contents").unwrap()) else { panic!("page stream") };
|
||||
assert_eq!(page_stream.decoded().unwrap(), original_streams[0]);
|
||||
let resources = reopened.dict(page.dict.get(b"Resources").unwrap()).unwrap();
|
||||
let xobjects = reopened.dict(resources.get(b"XObject").unwrap()).unwrap();
|
||||
let Object::Stream(form_stream) = &*reopened.resolve(xobjects.get(b"Form").unwrap()) else { panic!("form stream") };
|
||||
assert_eq!(form_stream.decoded().unwrap(), original_streams[1]);
|
||||
assert_eq!(
|
||||
pdfcraft_a11y::figures(&reopened).into_iter().map(|figure| figure.alt).collect::<Vec<_>>(),
|
||||
original_alts,
|
||||
"all original figures, including children, survive: {kids}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn page_only_owned_references_still_become_artifacts() {
|
||||
let cases: Vec<(&str, Vec<&str>)> = vec![
|
||||
("0", vec![]),
|
||||
("<< /Type /MCR /MCID 0 /Pg 3 0 R >>", vec![]),
|
||||
("11 0 R", vec!["<< /Type /MCR /MCID 0 /Pg 3 0 R >>"]),
|
||||
("11 0 R", vec!["12 0 R", "<< /Type /MCR /MCID 0 /Pg 3 0 R >>"]),
|
||||
("[11 0 R 11 0 R]", vec!["<< /Type /MCR /MCID 0 /Pg 3 0 R >>"]),
|
||||
("11 0 R", vec!["[12 0 R]", "<< /Type /MCR /MCID 0 /Pg 3 0 R >>"]),
|
||||
];
|
||||
for decorative in [true, false] {
|
||||
for (kids, extra) in &cases {
|
||||
let mut doc = page_owned(kids, extra);
|
||||
let original_form = stream(&doc, 10);
|
||||
mutate(&mut doc, decorative, 7).unwrap();
|
||||
let page = pdfcraft_model::pages(&doc)[0].dict.get(b"Contents").unwrap().as_ref().unwrap();
|
||||
let content = String::from_utf8(stream(&doc, page.num)).unwrap();
|
||||
assert!(content.contains("/Artifact BMC"), "page content changes for {kids}: {content}");
|
||||
assert!(!content.contains("/MCID"));
|
||||
assert_eq!(stream(&doc, 10), original_form);
|
||||
assert_eq!(pdfcraft_a11y::tags(&doc).iter().map(|t| t.object.num).collect::<Vec<_>>(), [6, 8]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ordinary_alt_edit_remains_available_for_a_stream_figure() {
|
||||
let mut doc = collision_with("<< /Type /MCR /MCID 0 /Stm 10 0 R >>", &[]);
|
||||
let original = [stream(&doc, 4), stream(&doc, 10)];
|
||||
pdfcraft_a11y::set_alt(&mut doc, ObjRef::new(8, 0), Some(" Blue square ")).unwrap();
|
||||
assert_eq!(pdfcraft_a11y::figures(&doc)[1].alt.as_deref(), Some("Blue square"));
|
||||
assert_eq!([stream(&doc, 4), stream(&doc, 10)], original);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refusal_preserves_preexisting_document_changes() {
|
||||
for decorative in [true, false] {
|
||||
let mut doc = collision_with("<< /Type /MCR /MCID 0 /Stm 10 0 R >>", &[]);
|
||||
pdfcraft_a11y::set_alt(&mut doc, ObjRef::new(8, 0), Some("Saved later")).unwrap();
|
||||
let before = pdfcraft_cos::write_full(&doc, &Default::default()).unwrap();
|
||||
let modified = doc.modified_objects();
|
||||
assert!(mutate(&mut doc, decorative, 8).is_err());
|
||||
assert!(doc.is_modified());
|
||||
assert_eq!(doc.modified_objects(), modified);
|
||||
assert_eq!(pdfcraft_cos::write_full(&doc, &Default::default()).unwrap(), before);
|
||||
assert_eq!(pdfcraft_a11y::figures(&doc)[1].alt.as_deref(), Some("Saved later"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn owned_reference_walk_accepts_limits_and_refuses_excess_depth_or_work() {
|
||||
// The root ownership array counts as one visit. Each nested array adds one depth level.
|
||||
let cases = [
|
||||
(format!("[{}]", "0 ".repeat(4095)), true),
|
||||
(format!("[{}]", "0 ".repeat(4096)), false),
|
||||
(format!("{}0{}", "[".repeat(64), "]".repeat(64)), true),
|
||||
(format!("{}0{}", "[".repeat(65), "]".repeat(65)), false),
|
||||
];
|
||||
for decorative in [true, false] {
|
||||
for (kids, supported) in &cases {
|
||||
let mut doc = page_owned(kids, &[]);
|
||||
let before = pdfcraft_cos::write_full(&doc, &Default::default()).unwrap();
|
||||
let result = mutate(&mut doc, decorative, 7);
|
||||
assert_eq!(result.is_ok(), *supported, "decorative={decorative}, result={result:?}");
|
||||
if *supported {
|
||||
let page = pdfcraft_model::pages(&doc)[0].dict.get(b"Contents").unwrap().as_ref().unwrap();
|
||||
assert!(String::from_utf8(stream(&doc, page.num)).unwrap().contains("/Artifact BMC"));
|
||||
assert_eq!(pdfcraft_a11y::tags(&doc).iter().map(|t| t.object.num).collect::<Vec<_>>(), [6, 8]);
|
||||
} else {
|
||||
assert!(!doc.is_modified());
|
||||
assert_eq!(pdfcraft_cos::write_full(&doc, &Default::default()).unwrap(), before);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decorative_refuses_matching_invalid_element_and_content_pages() {
|
||||
for page in [ObjRef::new(99, 0), ObjRef::new(3, 1)] {
|
||||
for kids in [format!("<< /Type /MCR /MCID 0 /Pg {page} >>"), "0".into(), "<< /Type /MCR /MCID 0 >>".into()] {
|
||||
let mut doc = collision_with(&kids, &[]);
|
||||
doc.update_dict(ObjRef::new(8, 0), |d| d.set(b"Pg".to_vec(), Object::Ref(page))).unwrap();
|
||||
let mut doc = Document::open(Arc::new(pdfcraft_cos::write_incremental(&doc, &Default::default()).unwrap())).unwrap();
|
||||
let before = pdfcraft_cos::write_full(&doc, &Default::default()).unwrap();
|
||||
let error = pdfcraft_a11y::mark_decorative(&mut doc, ObjRef::new(8, 0)).unwrap_err();
|
||||
assert!(error.to_string().contains("form"));
|
||||
assert!(!doc.is_modified());
|
||||
assert_eq!(pdfcraft_cos::write_full(&doc, &Default::default()).unwrap(), before);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn annotation_reference_refusal_names_the_unsupported_content_and_preserves_its_links() {
|
||||
for decorative in [true, false] {
|
||||
let mut doc = collision_with(
|
||||
"[0 << /Type /OBJR /Obj 11 0 R /Pg 3 0 R >>]",
|
||||
&["<< /Type /Annot /Subtype /Link /Rect [0 0 10 10] /P 3 0 R /StructParent 2 >>"],
|
||||
);
|
||||
doc.update_dict(ObjRef::new(3, 0), |d| d.set(b"Annots".to_vec(), Object::Array(vec![Object::Ref(ObjRef::new(11, 0))]))).unwrap();
|
||||
doc.update_dict(ObjRef::new(9, 0), |d| {
|
||||
d.set(
|
||||
b"Nums".to_vec(),
|
||||
Object::Array(vec![
|
||||
Object::Int(0),
|
||||
Object::Array(vec![Object::Ref(ObjRef::new(7, 0))]),
|
||||
Object::Int(1),
|
||||
Object::Ref(ObjRef::new(8, 0)),
|
||||
Object::Int(2),
|
||||
Object::Ref(ObjRef::new(8, 0)),
|
||||
]),
|
||||
)
|
||||
})
|
||||
.unwrap();
|
||||
let mut doc = Document::open(Arc::new(pdfcraft_cos::write_incremental(&doc, &Default::default()).unwrap())).unwrap();
|
||||
let before = pdfcraft_cos::write_full(&doc, &Default::default()).unwrap();
|
||||
let original_objects: Vec<_> = (1..=11).map(|i| doc.get(ObjRef::new(i, 0))).collect();
|
||||
let error = mutate(&mut doc, decorative, 8).unwrap_err();
|
||||
assert!(error.contains("annotation or object references"), "useful OBJR refusal: {error}");
|
||||
assert!(!doc.is_modified());
|
||||
assert_eq!((1..=11).map(|i| doc.get(ObjRef::new(i, 0))).collect::<Vec<_>>(), original_objects);
|
||||
let saved = pdfcraft_cos::write_full(&doc, &Default::default()).unwrap();
|
||||
assert_eq!(saved, before);
|
||||
let reopened = Document::open(Arc::new(saved)).unwrap();
|
||||
let page = &pdfcraft_model::pages(&reopened)[0];
|
||||
let annotation = reopened.resolve(&page.dict.get(b"Annots").unwrap().as_array().unwrap()[0]);
|
||||
assert_eq!(annotation.as_dict().unwrap().get(b"StructParent"), Some(&Object::Int(2)));
|
||||
let catalog = reopened.get(reopened.root().unwrap());
|
||||
let root = reopened.dict(catalog.as_dict().unwrap().get(b"StructTreeRoot").unwrap()).unwrap();
|
||||
let tree = reopened.dict(root.get(b"ParentTree").unwrap()).unwrap();
|
||||
let nums = tree.get(b"Nums").unwrap().as_array().unwrap();
|
||||
let tag = reopened.resolve(&nums[5]);
|
||||
assert_eq!(tag.as_dict().unwrap().get(b"K").unwrap().as_array().unwrap()[0], Object::Int(0));
|
||||
assert_eq!(nums[4], Object::Int(2));
|
||||
}
|
||||
}
|
||||
|
||||
fn assert_artifact_refusal_preserves(doc: &mut Document, expected: &pdfcraft_a11y::ArtifactError) {
|
||||
let state = doc.read_state();
|
||||
let dirty = doc.is_modified();
|
||||
let modified = doc.modified_objects();
|
||||
let saved = pdfcraft_cos::write_full(doc, &Default::default()).unwrap();
|
||||
let objects: Vec<_> = (1..=12).map(|number| doc.get(ObjRef::new(number, 0))).collect();
|
||||
let streams = [stream(doc, 4), stream(doc, 10)];
|
||||
let tags = pdfcraft_a11y::tags(doc);
|
||||
let alts = pdfcraft_a11y::figures(doc).into_iter().map(|figure| figure.alt).collect::<Vec<_>>();
|
||||
assert!(tags.iter().any(|tag| tag.object == ObjRef::new(7, 0)), "the malformed leaf remains reachable");
|
||||
assert_eq!(pdfcraft_a11y::mark_tag_artifact(doc, ObjRef::new(7, 0)).as_ref(), Err(expected));
|
||||
assert!(state.matches(doc), "refusal preserves the exact overlay and allocates no stream");
|
||||
assert_eq!(doc.is_modified(), dirty);
|
||||
assert_eq!(doc.modified_objects(), modified);
|
||||
assert_eq!((1..=12).map(|number| doc.get(ObjRef::new(number, 0))).collect::<Vec<_>>(), objects);
|
||||
assert_eq!([stream(doc, 4), stream(doc, 10)], streams);
|
||||
let after = pdfcraft_cos::write_full(doc, &Default::default()).unwrap();
|
||||
assert_eq!(after, saved);
|
||||
// Full saves renumber objects; incremental saves retain the fixture IDs checked below.
|
||||
let reopened = Document::open(Arc::new(pdfcraft_cos::write_incremental(doc, &Default::default()).unwrap())).unwrap();
|
||||
assert_eq!(pdfcraft_a11y::tags(&reopened), tags);
|
||||
assert_eq!(pdfcraft_a11y::figures(&reopened).into_iter().map(|figure| figure.alt).collect::<Vec<_>>(), alts);
|
||||
assert_eq!([stream(&reopened, 4), stream(&reopened, 10)], streams);
|
||||
assert_eq!(reopened.get(ObjRef::new(3, 0)), objects[2]);
|
||||
assert_eq!(reopened.get(ObjRef::new(9, 0)), objects[8]);
|
||||
assert_eq!(reopened.get(ObjRef::new(7, 0)), objects[6]);
|
||||
assert_eq!(
|
||||
reopened.get(ObjRef::new(9, 0)).as_dict().unwrap().get(b"Nums").unwrap().as_array().unwrap()[1],
|
||||
Object::Array(vec![Object::Ref(ObjRef::new(7, 0))])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn artifact_parent_refusals_preserve_direct_library_state_and_saved_content() {
|
||||
use pdfcraft_a11y::ArtifactError::{AmbiguousParent, NoParent};
|
||||
let cases = [
|
||||
(None, "<< >>", NoParent),
|
||||
(Some(Object::Int(6)), "<< >>", NoParent),
|
||||
(Some(Object::Ref(ObjRef::new(12, 0))), "null", NoParent),
|
||||
(Some(Object::Ref(ObjRef::new(12, 0))), "<< >>", NoParent),
|
||||
(Some(Object::Ref(ObjRef::new(12, 0))), "<< /K 3 >>", NoParent),
|
||||
(Some(Object::Ref(ObjRef::new(12, 0))), "<< /K 8 0 R >>", NoParent),
|
||||
(Some(Object::Ref(ObjRef::new(12, 0))), "<< /K [] >>", AmbiguousParent),
|
||||
(Some(Object::Ref(ObjRef::new(12, 0))), "<< /K [7 0 R 7 0 R] >>", AmbiguousParent),
|
||||
];
|
||||
for dirty in [false, true] {
|
||||
for (parent, parent_object, expected) in &cases {
|
||||
let mut doc = page_owned("11 0 R", &["<< /Type /MCR /MCID 0 /Pg 3 0 R >>", parent_object]);
|
||||
doc.update_dict(ObjRef::new(7, 0), |dict| {
|
||||
dict.remove(b"P");
|
||||
if let Some(parent) = parent {
|
||||
dict.set(b"P".to_vec(), parent.clone());
|
||||
}
|
||||
})
|
||||
.unwrap();
|
||||
let mut doc = Document::open(Arc::new(pdfcraft_cos::write_incremental(&doc, &Default::default()).unwrap())).unwrap();
|
||||
if dirty {
|
||||
pdfcraft_a11y::set_alt(&mut doc, ObjRef::new(8, 0), Some("Saved later")).unwrap();
|
||||
}
|
||||
assert_artifact_refusal_preserves(&mut doc, expected);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn artifact_mismatched_parent_refuses_before_changing_content_or_saved_state() {
|
||||
for dirty in [false, true] {
|
||||
for indirect in [false, true] {
|
||||
for root in [false, true] {
|
||||
let kids = if indirect { "11 0 R" } else { "0" };
|
||||
let mut doc = page_owned(kids, &["<< /Type /MCR /MCID 0 /Pg 3 0 R >>", "<< /Type /StructElem /S /Document /K [7 0 R] >>"]);
|
||||
if root {
|
||||
doc.update_dict(ObjRef::new(5, 0), |dict| dict.set(b"K".to_vec(), Object::Ref(ObjRef::new(7, 0)))).unwrap();
|
||||
}
|
||||
doc.update_dict(ObjRef::new(7, 0), |dict| dict.set(b"P".to_vec(), Object::Ref(ObjRef::new(12, 0)))).unwrap();
|
||||
let mut doc = Document::open(Arc::new(pdfcraft_cos::write_incremental(&doc, &Default::default()).unwrap())).unwrap();
|
||||
if dirty {
|
||||
pdfcraft_a11y::set_alt(&mut doc, ObjRef::new(7, 0), Some("Saved later")).unwrap();
|
||||
}
|
||||
assert_artifact_refusal_preserves(&mut doc, &pdfcraft_a11y::ArtifactError::NoParent);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn artifact_inline_parent_does_not_become_a_removable_indirect_ancestor() {
|
||||
for dirty in [false, true] {
|
||||
for root in [false, true] {
|
||||
let mut doc = page_owned("11 0 R", &["<< /Type /MCR /MCID 0 /Pg 3 0 R >>"]);
|
||||
let parent = ObjRef::new(if root { 5 } else { 6 }, 0);
|
||||
let mut inline = pdfcraft_cos::Dict::new();
|
||||
inline.set(b"S".to_vec(), Object::name("Document"));
|
||||
inline.set(b"K".to_vec(), Object::Ref(ObjRef::new(7, 0)));
|
||||
doc.update_dict(parent, |dict| dict.set(b"K".to_vec(), Object::Dict(inline))).unwrap();
|
||||
doc.update_dict(ObjRef::new(7, 0), |dict| dict.set(b"P".to_vec(), Object::Ref(parent))).unwrap();
|
||||
let mut doc = Document::open(Arc::new(pdfcraft_cos::write_incremental(&doc, &Default::default()).unwrap())).unwrap();
|
||||
if dirty {
|
||||
pdfcraft_a11y::set_alt(&mut doc, ObjRef::new(7, 0), Some("Saved later")).unwrap();
|
||||
}
|
||||
assert_artifact_refusal_preserves(&mut doc, &pdfcraft_a11y::ArtifactError::NoParent);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Main checks the parent before it reads the page, so a tag with both a missing `/P` and
|
||||
/// content missing from its page is refused for its parent, with nothing changed.
|
||||
#[test]
|
||||
fn artifact_invalid_parent_precedes_missing_page_content_without_mutation() {
|
||||
let mut doc = page_owned("11 0 R", &["<< /Type /MCR /MCID 1 /Pg 3 0 R >>"]);
|
||||
doc.update_dict(ObjRef::new(7, 0), |dict| {
|
||||
dict.remove(b"P");
|
||||
})
|
||||
.unwrap();
|
||||
let mut doc = Document::open(Arc::new(pdfcraft_cos::write_incremental(&doc, &Default::default()).unwrap())).unwrap();
|
||||
assert_artifact_refusal_preserves(&mut doc, &pdfcraft_a11y::ArtifactError::NoParent);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn artifact_indirect_content_removes_scalar_or_array_parent_child_and_preserves_drawing() {
|
||||
for (root, scalar) in [(false, false), (false, true), (true, false), (true, true)] {
|
||||
let mut doc = page_owned("11 0 R", &["<< /Type /MCR /MCID 0 /Pg 3 0 R >>"]);
|
||||
let parent = ObjRef::new(if root { 5 } else { 6 }, 0);
|
||||
if root {
|
||||
doc.update_dict(ObjRef::new(7, 0), |dict| dict.set(b"P".to_vec(), Object::Ref(parent))).unwrap();
|
||||
doc.update_dict(parent, |dict| {
|
||||
dict.set(b"K".to_vec(), Object::Array(vec![Object::Ref(ObjRef::new(7, 0)), Object::Ref(ObjRef::new(8, 0))]))
|
||||
})
|
||||
.unwrap();
|
||||
}
|
||||
if scalar {
|
||||
doc.update_dict(parent, |dict| dict.set(b"K".to_vec(), Object::Ref(ObjRef::new(7, 0)))).unwrap();
|
||||
}
|
||||
let original_form = stream(&doc, 10);
|
||||
let other_figure = doc.get(ObjRef::new(8, 0));
|
||||
pdfcraft_a11y::mark_tag_artifact(&mut doc, ObjRef::new(7, 0)).unwrap();
|
||||
let reopened = Document::open(Arc::new(pdfcraft_cos::write_incremental(&doc, &Default::default()).unwrap())).unwrap();
|
||||
let contents = reopened.get(ObjRef::new(3, 0)).as_dict().unwrap().get(b"Contents").unwrap().as_ref().unwrap();
|
||||
let ops = pdfcraft_content::parse(&stream(&reopened, contents.num)).ops;
|
||||
assert!(ops.iter().any(|op| op.op == b"BMC" && op.operands == [Object::name("Artifact")]));
|
||||
assert!(!ops.iter().any(|op| op.op == b"BDC"));
|
||||
let rectangle = ops.iter().find(|op| op.op == b"re").unwrap();
|
||||
assert_eq!(rectangle.nums::<4>(), Some([10.0, 10.0, 20.0, 20.0]));
|
||||
assert!(ops.iter().any(|op| op.op == b"f"));
|
||||
assert!(ops.iter().any(|op| op.op == b"Do" && op.operands == [Object::name("Form")]));
|
||||
assert_eq!(stream(&reopened, 10), original_form);
|
||||
assert_eq!(reopened.get(ObjRef::new(8, 0)), other_figure);
|
||||
let remaining = if scalar { vec![] } else { vec![Object::Ref(ObjRef::new(8, 0))] };
|
||||
assert_eq!(reopened.get(parent).as_dict().unwrap().get(b"K"), Some(&Object::Array(remaining)));
|
||||
assert!(!reopened.get(ObjRef::new(7, 0)).as_dict().unwrap().contains(b"P"));
|
||||
let expected_tags = match (root, scalar) {
|
||||
(false, false) => vec![6, 8],
|
||||
(false, true) => vec![6],
|
||||
(true, false) => vec![8],
|
||||
(true, true) => vec![],
|
||||
};
|
||||
assert_eq!(pdfcraft_a11y::tags(&reopened).iter().map(|tag| tag.object.num).collect::<Vec<_>>(), expected_tags);
|
||||
assert_eq!(
|
||||
reopened.get(ObjRef::new(9, 0)).as_dict().unwrap().get(b"Nums").unwrap().as_array().unwrap()[1],
|
||||
Object::Array(vec![Object::Null])
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -206,19 +206,31 @@ fn review_html(record: &Value) -> Result<String> {
|
||||
Ok(html)
|
||||
}
|
||||
|
||||
/// Running headers and footers listed by `accessibility_autotag_apply`, at most.
|
||||
const MAX_RUNNING_LISTED: usize = 200;
|
||||
|
||||
/// Tags in one page of `accessibility_tags`, by default and at most.
|
||||
const TAG_PAGE: usize = 200;
|
||||
const MAX_TAG_PAGE: usize = 1000;
|
||||
|
||||
impl Automation {
|
||||
pub(crate) fn accessibility_autotag_apply(&mut self, a: &Args) -> Result<Value> {
|
||||
let id = self.doc(a)?.id;
|
||||
let doc = self.doc(a)?;
|
||||
let id = doc.id;
|
||||
// Read before applying: once tagged, the document is refused. A refusal here is Apply's too.
|
||||
let running = doc.autotag_running_text().unwrap_or_default();
|
||||
let warnings = self.apply_with_warnings(id, pdfcraft_engine::Edit::AutoTagText)?;
|
||||
let tags = self.accessibility_tags(a)?;
|
||||
let out = json!({
|
||||
"tags": tags["tags"], "count": tags["count"],
|
||||
"note": "Text objects were tagged as headings (H1-H6, by size and weight against the body text) or paragraphs. Review heading roles, reading order and remaining accessibility findings manually.",
|
||||
});
|
||||
let listed: Vec<Value> =
|
||||
running.iter().take(MAX_RUNNING_LISTED).map(|r| json!({ "page": r.page + 1, "subtype": r.subtype, "text": r.text })).collect();
|
||||
let note = format!(
|
||||
"Text objects were tagged as headings (H1-H6, by size and weight against the body text) or paragraphs. \
|
||||
{} text objects repeating at the top or bottom of the pages were marked as running header or footer artifacts \
|
||||
instead (listed in running_text{}). Review heading roles, the running text, reading order and remaining accessibility findings manually.",
|
||||
running.len(),
|
||||
if running.len() > MAX_RUNNING_LISTED { format!(", first {MAX_RUNNING_LISTED}") } else { String::new() },
|
||||
);
|
||||
let out = json!({ "tags": tags["tags"], "count": tags["count"], "running_text": listed, "running_count": running.len(), "note": note });
|
||||
Ok(with_warnings(out, warnings))
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
//! Bookmark trees in and out of documents: `bookmark_export`, `bookmark_import`, `bookmark_copy`.
|
||||
//! Bookmark trees in and out of documents: `bookmark_export`, `bookmark_import`, `bookmark_copy`,
|
||||
//! and `bookmark_suggest`, which proposes a tree for review before `bookmark_import` applies it.
|
||||
//!
|
||||
//! The portable form is JSON: `{"bookmarks": [node, …]}`, where a node is `title`, `page`
|
||||
//! (1-based, or `null` for one that goes nowhere), `view` (`{"type", "values"}`: a destination
|
||||
@@ -60,6 +61,31 @@ impl Automation {
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
pub(crate) fn bookmark_suggest(&self, a: &Args) -> Result<Value> {
|
||||
// The titles are the document's text, as text_lines is.
|
||||
let doc = self.doc_to_copy(a)?;
|
||||
let id = doc.id.0;
|
||||
let s = doc.suggest_outline().ok_or_else(|| failed(format!("document {id} can't be read for editing")))?;
|
||||
let source = match s.source {
|
||||
pdfcraft_engine::suggest_outline::OutlineSource::Structure => "structure",
|
||||
pdfcraft_engine::suggest_outline::OutlineSource::Layout => "layout",
|
||||
};
|
||||
let mut out = json!({
|
||||
"source": source,
|
||||
"bookmarks": s.tree().iter().map(node_json).collect::<Vec<_>>(),
|
||||
"headings": s.entries.len(),
|
||||
"pages": s.pages,
|
||||
"pages_read": s.pages_read,
|
||||
"truncated": s.truncated,
|
||||
});
|
||||
if s.entries.is_empty() {
|
||||
out["note"] = json!(
|
||||
"no headings found: the text may be in one style; text_styles lists the styles, and bookmark_from_text_styles makes bookmarks from chosen ones"
|
||||
);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn outline_of(&self, id: DocId, path: &[usize]) -> Result<pdfcraft_engine::OutlineTree> {
|
||||
match self.session.outline_tree(id, path) {
|
||||
// The engine names the path 0-based; the caller gave it 1-based.
|
||||
|
||||
@@ -470,7 +470,10 @@ impl Automation {
|
||||
}
|
||||
style.fill = a.color("fill")?;
|
||||
if let Some(o) = a.opt_num("opacity")? {
|
||||
style.opacity = o.clamp(0.0, 1.0);
|
||||
if !(0.0..=1.0).contains(&o) {
|
||||
return Err(ToolError::InvalidArgs(format!("opacity must be between 0 and 1, got {o}")));
|
||||
}
|
||||
style.opacity = o;
|
||||
}
|
||||
// The fill's and a text box's text's own opacities (the line keeps `opacity`).
|
||||
let (fill_opacity, text_opacity) = (a.opt_num("fill_opacity")?, a.opt_num("text_opacity")?);
|
||||
@@ -758,6 +761,9 @@ impl Automation {
|
||||
edits.push(Edit::SetAnnotationContents { page, index, text: text.to_string() });
|
||||
}
|
||||
let (color, opacity, width) = (a.color("color")?, a.opt_num("opacity")?, a.opt_num("width")?);
|
||||
if let Some(o) = opacity.filter(|&o| !(0.0..=1.0).contains(&o)) {
|
||||
return Err(ToolError::InvalidArgs(format!("opacity must be between 0 and 1, got {o}")));
|
||||
}
|
||||
if color.is_some() || opacity.is_some() || width.is_some() {
|
||||
edits.push(Edit::StyleAnnotation { page, index, color, opacity, width, endings: None });
|
||||
}
|
||||
|
||||
@@ -203,6 +203,7 @@ impl Automation {
|
||||
"bookmark_export" => self.bookmark_export(&a)?,
|
||||
"bookmark_import" => self.bookmark_import(&a)?,
|
||||
"bookmark_copy" => self.bookmark_copy(&a)?,
|
||||
"bookmark_suggest" => self.bookmark_suggest(&a)?,
|
||||
"bookmark_add" => {
|
||||
let page = self.page(&a)?;
|
||||
let parent = a.opt_path("parent")?.unwrap_or_default();
|
||||
|
||||
@@ -116,6 +116,7 @@ impl Automation {
|
||||
let bytes = read_input(&path)?;
|
||||
let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
|
||||
let id = self.session.open(name, Some(path.to_string_lossy().into_owned()), Arc::new(bytes), a.opt_str("password")?).map_err(failed)?;
|
||||
let errors = self.session.take_js_errors(id);
|
||||
let doc = self.session.get(id).ok_or_else(|| failed("the document vanished"))?;
|
||||
let mut value = summary(doc);
|
||||
if let Some(destination) = destination {
|
||||
@@ -124,6 +125,10 @@ impl Automation {
|
||||
value["destination"] = destination;
|
||||
value["warning"] = json!(warning);
|
||||
}
|
||||
// warnings lists the errors of the form's scripts that ran on open, including the messages that the scripts were stopped or turned off.
|
||||
if !errors.is_empty() {
|
||||
value["warnings"] = json!(errors);
|
||||
}
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
@@ -577,11 +582,16 @@ impl Automation {
|
||||
|
||||
/// The document's summary after an edit, with what it stored as typed but drew with `?`.
|
||||
fn applied(&mut self, a: &Args) -> Result<Value> {
|
||||
let id = self.doc(a)?.id;
|
||||
let errors = self.session.take_js_errors(id);
|
||||
let doc = self.doc(a)?;
|
||||
let mut out = summary(doc);
|
||||
// Text the edit stored as typed but drew with `?` (its font can't draw it): said, not silent.
|
||||
if !doc.edit_notices.is_empty() {
|
||||
out["warnings"] = json!(doc.edit_notices.iter().map(ToString::to_string).collect::<Vec<_>>());
|
||||
let mut warnings: Vec<String> = doc.edit_notices.iter().map(ToString::to_string).collect();
|
||||
// The errors of the scripts the edit ran follow the notices, including the messages that a form's scripts were stopped or turned off.
|
||||
warnings.extend(errors);
|
||||
if !warnings.is_empty() {
|
||||
out["warnings"] = json!(warnings);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
@@ -659,7 +669,13 @@ impl Automation {
|
||||
scale: a.opt_num("scale")?.unwrap_or(d.scale).clamp(0.01, 1.0),
|
||||
font_size: a.opt_num("font_size")?.unwrap_or(0.0),
|
||||
color: color("color", d.color)?,
|
||||
opacity: a.opt_num("opacity")?.unwrap_or(d.opacity),
|
||||
opacity: match a.opt_num("opacity")? {
|
||||
Some(o) if !(0.0..=1.0).contains(&o) => {
|
||||
return Err(ToolError::InvalidArgs(format!("opacity must be between 0 and 1, got {o}")));
|
||||
}
|
||||
Some(o) => o,
|
||||
None => d.opacity,
|
||||
},
|
||||
rotation: a.opt_num("rotation")?.unwrap_or(d.rotation),
|
||||
behind: a.opt_bool("behind")?.unwrap_or(false),
|
||||
offset: [
|
||||
@@ -673,7 +689,13 @@ impl Automation {
|
||||
pages,
|
||||
settings: Background {
|
||||
color: color("color", [1.0; 3])?,
|
||||
opacity: a.opt_num("opacity")?.unwrap_or(1.0),
|
||||
opacity: match a.opt_num("opacity")? {
|
||||
Some(o) if !(0.0..=1.0).contains(&o) => {
|
||||
return Err(ToolError::InvalidArgs(format!("opacity must be between 0 and 1, got {o}")));
|
||||
}
|
||||
Some(o) => o,
|
||||
None => 1.0,
|
||||
},
|
||||
scale: a.opt_num("scale")?.unwrap_or(1.0).clamp(0.01, 1.0),
|
||||
replace_backdrop: a.opt_bool("replace_backdrop")?.unwrap_or(true),
|
||||
..Background::default()
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
//! Printing tools: list printers, and print (or save the print-ready PDF) with Acrobat's Print
|
||||
//! dialog options.
|
||||
|
||||
use pdfcraft_engine::PrinterMarks;
|
||||
use pdfcraft_engine::print::{self, Binding, BookletSubset, Layout, Orientation, PAPERS, PageOrder, SizeMode, Subset, spool};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
@@ -41,6 +42,48 @@ fn printer_in(printers: Vec<spool::Printer>, printer: &str) -> Option<spool::Pri
|
||||
printers.into_iter().find(|p| if printer == "default" { p.default } else { p.name == printer })
|
||||
}
|
||||
|
||||
/// What `doc_print`'s `marks` may name.
|
||||
const MARK_NAMES: &str = "marks must be a list of all, trim, bleed, registration, color_bars and page_info";
|
||||
|
||||
/// `doc_print`'s `marks` and `marks_weight`: the printer's marks to print around each page, or
|
||||
/// `None` when none are asked for. The information line names the document (`name`) and the
|
||||
/// date (`today`, year, month, day).
|
||||
fn printer_marks(a: &Args, layout: &Layout, name: &str, (y, m, d): (i64, u32, u32)) -> Result<Option<PrinterMarks>> {
|
||||
let Some(asked) = a.get("marks") else {
|
||||
return if a.get("marks_weight").is_some() { Err(bad("marks_weight needs marks")) } else { Ok(None) };
|
||||
};
|
||||
let names = asked.as_array().filter(|names| !names.is_empty()).ok_or_else(|| bad(MARK_NAMES))?;
|
||||
let mut marks = PrinterMarks {
|
||||
trim: false,
|
||||
bleed: false,
|
||||
registration: false,
|
||||
color_bars: false,
|
||||
page_info: false,
|
||||
label: name.to_string(),
|
||||
date: format!("{y:04}-{m:02}-{d:02}"),
|
||||
..PrinterMarks::default()
|
||||
};
|
||||
for mark in names {
|
||||
match mark.as_str() {
|
||||
Some("all") => (marks.trim, marks.bleed, marks.registration, marks.color_bars, marks.page_info) = (true, true, true, true, true),
|
||||
Some("trim") => marks.trim = true,
|
||||
Some("bleed") => marks.bleed = true,
|
||||
Some("registration") => marks.registration = true,
|
||||
Some("color_bars") => marks.color_bars = true,
|
||||
Some("page_info") => marks.page_info = true,
|
||||
_ => return Err(bad(MARK_NAMES)),
|
||||
}
|
||||
}
|
||||
marks.line_weight = a.opt_num("marks_weight")?.unwrap_or(0.25);
|
||||
if !PrinterMarks::WEIGHTS.contains(&marks.line_weight) {
|
||||
return Err(bad(format!("marks_weight must be from {} to {} points", PrinterMarks::WEIGHTS.start(), PrinterMarks::WEIGHTS.end())));
|
||||
}
|
||||
if !matches!(layout, Layout::Size(_)) {
|
||||
return Err(bad("printer marks print one page a sheet: use layout fit, actual, shrink or custom"));
|
||||
}
|
||||
Ok(Some(marks))
|
||||
}
|
||||
|
||||
/// An invalid-arguments error saying `m`.
|
||||
fn bad(m: impl Into<String>) -> ToolError {
|
||||
ToolError::InvalidArgs(m.into())
|
||||
@@ -111,7 +154,8 @@ fn resolve_paper(name: Option<&str>, printer: Option<&str>) -> Result<((f64, f64
|
||||
/// naming none got (A4 under Letter sheets on the queue in #3752), and tells CUPS which way the
|
||||
/// laid-out `sheets` run, as the Print dialog does (#2713): an orientation the caller chose in
|
||||
/// `options` stands. It asks the driver for grayscale only when the pages aren't grey pictures
|
||||
/// already ([`print::driver_needs_grayscale`]).
|
||||
/// already ([`print::driver_needs_grayscale`]). Any caller-supplied `media` option (case-insensitive)
|
||||
/// is replaced by the laid-out paper's media.
|
||||
fn spool_job(
|
||||
a: &Args,
|
||||
printer: &str,
|
||||
@@ -143,7 +187,10 @@ fn spool_job(
|
||||
grey_pages: false,
|
||||
title,
|
||||
options: {
|
||||
let mut options: Vec<(String, String)> = options.into_iter().chain(media.map(|m| ("media".to_string(), m.to_string()))).collect();
|
||||
let mut options: Vec<(String, String)> = options.into_iter().filter(|(k, _)| !k.eq_ignore_ascii_case("media")).collect();
|
||||
if let Some(m) = media {
|
||||
options.push(("media".to_string(), m.to_string()));
|
||||
}
|
||||
print::add_cups_orientation(&mut options, sheets);
|
||||
options
|
||||
},
|
||||
@@ -302,6 +349,7 @@ impl Automation {
|
||||
},
|
||||
l => Layout::Size(print::names::parse_size_mode(l, 100.0).ok_or_else(|| bad(format!("unknown layout {l:?}")))?),
|
||||
};
|
||||
let marks = printer_marks(a, &layout, &self.doc(a)?.name, self.session.today())?;
|
||||
let printer = a.opt_str("printer")?;
|
||||
// The printer whose driver a booklet's both sides were decided for. The job goes to it by
|
||||
// name, so "default" can't become another printer while the document is rendered. The
|
||||
@@ -355,6 +403,19 @@ impl Automation {
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if marks.is_some() && raster.is_some() {
|
||||
return Err(bad("printer marks print with the pages as they are: leave out as_image and color_management app"));
|
||||
}
|
||||
// A document that allows only low-resolution printing is later forced to print as
|
||||
// pictures in Session::print_pdf_marked. Refuse marks here, before Will Print runs
|
||||
// and could change the document for a print that then fails. A document that allows
|
||||
// no printing gets the engine's permission error instead.
|
||||
let doc = self.doc(a)?;
|
||||
if marks.is_some() && doc.allows_printing() && doc.permissions().is_some_and(|p| !p.print_high_quality()) {
|
||||
return Err(bad(
|
||||
"printer marks print with the pages as they are, not as pictures: a document that allows only low-resolution printing always prints as pictures",
|
||||
));
|
||||
}
|
||||
let sizes: Vec<(f64, f64)> = self.doc(a)?.info.pages.iter().map(|p| (p.width as f64, p.height as f64)).collect();
|
||||
// Print a selected area: points from the top-left of the displayed page, as other tools
|
||||
// take rectangles; the print crate takes it y up.
|
||||
@@ -366,6 +427,9 @@ impl Automation {
|
||||
Some([r[0].min(r[2]), h - r[1].max(r[3]), r[0].max(r[2]), h - r[1].min(r[3])])
|
||||
}
|
||||
};
|
||||
if marks.is_some() && area.is_some() {
|
||||
return Err(bad("area prints part of a page, without printer marks: leave out one or the other"));
|
||||
}
|
||||
let settings = print::Settings { pages, paper, orientation, layout, content, raster, crops: Vec::new(), area };
|
||||
let laid_out = print::layout(&sizes, &settings).map_err(|e| bad(e.to_string()))?;
|
||||
let sheets = laid_out.len();
|
||||
@@ -387,13 +451,20 @@ impl Automation {
|
||||
}
|
||||
_ => return Err(bad("pass either path (save the print-ready PDF) or printer (a name from printers, or \"default\")")),
|
||||
};
|
||||
// Marks that would widen a page past the largest page a PDF can have fail here, before
|
||||
// the Will Print actions run and could change the document for a print that then fails.
|
||||
if let Some(m) = marks.as_ref()
|
||||
&& self.doc(a)?.allows_printing()
|
||||
{
|
||||
self.session.check_printer_marks(id, &settings.pages, m).map_err(failed)?;
|
||||
}
|
||||
// The document's Will Print actions run first: what they change is printed (#269).
|
||||
let scripts = if self.doc(a)?.allows_printing() {
|
||||
self.session.run_document_actions(id, pdfcraft_engine::js::DocumentScriptEvent::WillPrint)
|
||||
} else {
|
||||
Default::default()
|
||||
};
|
||||
let bytes = self.session.print_pdf(id, &settings).map_err(failed)?;
|
||||
let bytes = self.session.print_pdf_marked(id, &settings, marks.as_ref()).map_err(failed)?;
|
||||
let mut out = json!({ "sheets": sheets, "pages": settings.pages.len(), "bytes": bytes.len() });
|
||||
if let Some(c) = settings.raster.as_ref().and_then(|r| r.colour.as_ref()) {
|
||||
out["color_management"] =
|
||||
@@ -581,4 +652,26 @@ mod tests {
|
||||
assert_eq!(paper_size(spec), None, "{spec}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A user-supplied `media` option must not reach the spooler alongside the
|
||||
/// laid-out paper's own `media` option: the job carries exactly one `media`
|
||||
/// entry, and it is the paper the sheets were laid out on.
|
||||
#[test]
|
||||
fn spool_job_does_not_duplicate_media_option() {
|
||||
let index = 0; // US Letter
|
||||
let media_name = print::cups_media(index).unwrap();
|
||||
let job = spool_job(
|
||||
&Args(&json!({ "options": { "InputSlot": "Tray3", "media": "A4" } })),
|
||||
"Office",
|
||||
"a.pdf".into(),
|
||||
None,
|
||||
Some(media_name),
|
||||
None,
|
||||
&[],
|
||||
)
|
||||
.unwrap();
|
||||
let media: Vec<&(String, String)> = job.options.iter().filter(|(k, _)| k == "media").collect();
|
||||
assert_eq!(media, [print::media_option(index).as_ref().unwrap()]);
|
||||
assert!(job.options.contains(&("InputSlot".to_string(), "Tray3".to_string())));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -183,7 +183,7 @@ pub fn tools() -> Vec<ToolDef> {
|
||||
)),
|
||||
t("attachment_edit", "Edit an attachment description", "Change the description of a document attachment by its exact key from doc_info, or by a unique displayed name. An empty description clears it. The file and other attachment data are preserved. Undoable.")
|
||||
.with(schema(json!({"doc": doc(), "key": {"type": "string"}, "name": {"type": "string"}, "description": {"type": "string"}}), &["doc", "description"])),
|
||||
t("doc_open", "Open a PDF", "Open a PDF file and return its document id, page count and whether it can be edited. A path that ends in open parameters, as help systems pass them (`manual.pdf#page=12`, `#nameddest=Intro` or `#Intro`), opens the file and reports its destination as link_open does; a path that names a file opens as it is.")
|
||||
t("doc_open", "Open a PDF", "Open a PDF file and return its document id, page count and whether it can be edited. A path that ends in open parameters, as help systems pass them (`manual.pdf#page=12`, `#nameddest=Intro` or `#Intro`), opens the file and reports its destination as link_open does; a path that names a file opens as it is. `warnings` lists the errors of the form's scripts on open, including the messages that they were stopped or turned off.")
|
||||
.cmd("file.open")
|
||||
.with(schema(json!({ "path": { "type": "string" }, "password": { "type": "string", "description": "User or owner password for encrypted files." } }), &["path"])),
|
||||
t("doc_list", "List open documents", "List the open documents with their ids, page counts and unsaved state.").ro().with(schema(json!({}), &[])),
|
||||
@@ -494,6 +494,13 @@ pub fn tools() -> Vec<ToolDef> {
|
||||
"Make bookmarks from the document's tagged headings (H, H1-H6), nested by level under a new first bookmark titled \"Untitled\". Fails if the document has no tagged headings. Returns the first page of the bookmark tree (see bookmark_list). Undoable.",
|
||||
)
|
||||
.with(schema(json!({ "doc": doc() }), &["doc"])),
|
||||
t(
|
||||
"bookmark_suggest",
|
||||
"Suggest bookmarks",
|
||||
"Propose a bookmark tree for the whole document, for review: its tagged headings (H, H1-H6) when it has them (source \"structure\"), or else headings found from how its text looks (source \"layout\"): short blocks set larger than the body text, or bold where the body is not, levelled by size without skipping a level, a heading set on several lines as one bookmark that goes to its top; captions such as \"Figure 3\" are left out. Reads the first 5000 pages for a layout suggestion; pages_read counts the pages whose text was read. truncated is true when headings may be missing: the document has more pages, a page's text could not be read, there were more than 10000 headings (the first 10000 are given), or the structure tree nests or branches too far to read whole. Changes nothing: bookmarks is in bookmark_export's form, so edit titles, remove entries or move them into or out of a bookmark's children to change the nesting, then apply it with bookmark_import (with replace to drop the existing outline), one undoable step. headings counts the suggested bookmarks; note says what to try when there are none. Needs the document to allow copying, as its text is returned.",
|
||||
)
|
||||
.ro()
|
||||
.with(schema(json!({ "doc": doc() }), &["doc"])),
|
||||
t(
|
||||
"text_styles",
|
||||
"List text styles",
|
||||
@@ -544,7 +551,7 @@ pub fn tools() -> Vec<ToolDef> {
|
||||
t(
|
||||
"form_fill",
|
||||
"Fill in form fields",
|
||||
"Set several fields at once (one undo step). values maps field names (from form_fields) to: a string for text fields, combo boxes and radio groups (an option), true/false for check boxes (or one of a check box's options, to check that widget and clear the others), an array of strings for multi-select lists; {\"widget\": n} turns on button n (1-based) of a check box or radio group and never turns it off (to clear, use null for a radio group that allows it, false for a check box); of radio buttons sharing an option only that one is on unless the group has RadiosInUnison. A radio option is an export value as form_fields lists it in options; where one button's on-state name equals another button's export value, the export value wins, and an on-state name that no export value matches still selects its button. A radio option may also be a JSON number: a whole number names the option spelled as that integer (1, 1.0 and 1e0 all name \"1\"), any other number only an option spelled exactly as JSON prints it (1.5). A value that names no option is refused with the options listed. Appearances are regenerated so every viewer shows the values. Thai the field's font can't hold is drawn from PdfCraft's built-in Thai face (a build without one refuses it). Any other value whose characters the field's font can't draw (Chinese in a Helvetica field) is still saved; `warnings` in the result names the field and character: PdfCraft draws `?` there and asks other viewers to redraw the field from its value.",
|
||||
"Set several fields at once (one undo step). values maps field names (from form_fields) to: a string for text fields, combo boxes and radio groups (an option), true/false for check boxes (or one of a check box's options, to check that widget and clear the others), an array of strings for multi-select lists; {\"widget\": n} turns on button n (1-based) of a check box or radio group and never turns it off (to clear, use null for a radio group that allows it, false for a check box); of radio buttons sharing an option only that one is on unless the group has RadiosInUnison. A radio option is an export value as form_fields lists it in options; where one button's on-state name equals another button's export value, the export value wins, and an on-state name that no export value matches still selects its button. A radio option may also be a JSON number: a whole number names the option spelled as that integer (1, 1.0 and 1e0 all name \"1\"), any other number only an option spelled exactly as JSON prints it (1.5). A value that names no option is refused with the options listed. Appearances are regenerated so every viewer shows the values. Thai the field's font can't hold is drawn from PdfCraft's built-in Thai face (a build without one refuses it). Any other value whose characters the field's font can't draw (Chinese in a Helvetica field) is still saved; `warnings` in the result names the field and character: PdfCraft draws `?` there and asks other viewers to redraw the field from its value. `warnings` also lists the errors of the form's scripts that the change ran, including the messages that they were stopped or turned off.",
|
||||
)
|
||||
.with(schema(json!({ "doc": doc(), "values": { "type": "object", "description": "Field name → value." } }), &["doc", "values"])),
|
||||
t(
|
||||
@@ -774,7 +781,7 @@ pub fn tools() -> Vec<ToolDef> {
|
||||
t(
|
||||
"doc_print",
|
||||
"Print",
|
||||
"Print with Acrobat's Print dialog options, or save the print-ready PDF. pages: a range such as \"1-3, 6, 9-\" (page labels allowed, \"(n)\" for the nth page whatever its label, unless a page is labelled exactly \"(n)\", since labels are looked up first; default all); subset odd/even (by page number, as Acrobat counts them: pages 2, 7-10 with even prints 2, 8 and 10, not every second page of the range); reverse. layout: fit (default), actual, shrink, custom (scale %), multiple (per_sheet 2/4/6/9/16, which turns the sheet to suit the grid, or a custom grid of cols across by rows down, each 1-99, on the sheet as oriented (auto prints portrait); order, border, auto_rotate; cut-stack order arranges single-sided sheets for cutting into piles and stacking left to right, top to bottom, keeping sheet order within each pile; duplex must be off), booklet (booklet_subset both/front/back, binding left/right; a booklet sets two-sided itself, as Acrobat does: both flips on the short edge, front or back prints one-sided), poster (scale %, overlap pt, cut_marks). orientation auto/portrait/landscape; comments_forms document / document-and-markups (default) / document-and-stamps / form-fields-only; paper Letter/Legal/Tabloid, ARCH A/B/C/D/E1/E, ANSI C/D/E, A0/A1/A2/A3/A4/A5/A6, US #10 Envelope, a driver paper name from printer_papers, or dimensions \"<w>x<h>\"; when printer is given and paper is omitted, uses the printer's default paper if available; use layout actual for 100% in the print-ready PDF; printer drivers may still substitute paper or scale. Then path (save) or printer (a name or \"default\") with copies, collate, duplex off/long-edge/short-edge, grayscale, and options (driver options from printer_options, CUPS). color_management app (Acrobat's Color Handling, the app managing colours) prints the pages as images converted into color_profile with rendering_intent and black_point_compensation; turn the driver's own colour management off for that job, or the printer converts them again.",
|
||||
"Print with Acrobat's Print dialog options, or save the print-ready PDF. pages: a range such as \"1-3, 6, 9-\" (page labels allowed, \"(n)\" for the nth page whatever its label, unless a page is labelled exactly \"(n)\", since labels are looked up first; default all); subset odd/even (by page number, as Acrobat counts them: pages 2, 7-10 with even prints 2, 8 and 10, not every second page of the range); reverse. layout: fit (default), actual, shrink, custom (scale %), multiple (per_sheet 2/4/6/9/16, which turns the sheet to suit the grid, or a custom grid of cols across by rows down, each 1-99, on the sheet as oriented (auto prints portrait); order, border, auto_rotate; cut-stack order arranges single-sided sheets for cutting into piles and stacking left to right, top to bottom, keeping sheet order within each pile; duplex must be off), booklet (booklet_subset both/front/back, binding left/right; a booklet sets two-sided itself, as Acrobat does: both flips on the short edge, front or back prints one-sided), poster (scale %, overlap pt, cut_marks). marks (Acrobat's Marks and Bleeds, with a one-page-a-sheet layout: fit, actual, shrink or custom): a list of all, trim, bleed, registration, color_bars and page_info (document name, page n of N, date), drawn around each page on the printed copy only, in registration colour except the colour bars, at marks_weight points (0.1 to 4, default 0.25); the page is widened for them, so fit shrinks it to make room, and marks the document already has print once; not with as_image, color_management app or area. orientation auto/portrait/landscape; comments_forms document / document-and-markups (default) / document-and-stamps / form-fields-only; paper Letter/Legal/Tabloid, ARCH A/B/C/D/E1/E, ANSI C/D/E, A0/A1/A2/A3/A4/A5/A6, US #10 Envelope, a driver paper name from printer_papers, or dimensions \"<w>x<h>\"; when printer is given and paper is omitted, uses the printer's default paper if available; use layout actual for 100% in the print-ready PDF; printer drivers may still substitute paper or scale. Then path (save) or printer (a name or \"default\") with copies, collate, duplex off/long-edge/short-edge, grayscale, and options (driver options from printer_options, CUPS). color_management app (Acrobat's Color Handling, the app managing colours) prints the pages as images converted into color_profile with rendering_intent and black_point_compensation; turn the driver's own colour management off for that job, or the printer converts them again. Any caller-supplied `media` option is replaced by the paper the document was laid out on."
|
||||
)
|
||||
.with(schema(
|
||||
json!({
|
||||
@@ -795,9 +802,11 @@ pub fn tools() -> Vec<ToolDef> {
|
||||
"creep": { "type": "number", "minimum": 0, "maximum": 10, "description": "Booklet creep compensation: points each sheet's pages move toward the fold, times the sheet's place from the outside (default 0)." },
|
||||
"overlap": { "type": "number", "minimum": 0 },
|
||||
"cut_marks": { "type": "boolean" },
|
||||
"marks": { "type": "array", "items": { "type": "string", "enum": ["all", "trim", "bleed", "registration", "color_bars", "page_info"] }, "description": "Printer's marks drawn around each page on the printed copy only (one page a sheet; not with as_image, color_management app or area)." },
|
||||
"marks_weight": { "type": "number", "minimum": 0.1, "maximum": 4, "description": "With marks: their line weight in points (default 0.25)." },
|
||||
"orientation": { "type": "string", "enum": ["auto", "portrait", "landscape"] },
|
||||
"comments_forms": { "type": "string", "enum": ["document", "document-and-markups", "document-and-stamps", "form-fields-only"] },
|
||||
"paper": { "type": "string", "description": "A paper name (US Letter, A4…) or a size of its own such as 8.5x14in, 210x297mm, 10x15cm or 612x792pt (1 to 200 inches a side)." },
|
||||
"paper": { "type": "string", "description": "A paper name (US Letter, A4…) or a size of its own such as 8.5x14in, 210x297mm, 10x15cm or 612x792pt (1 to 200 inches a side). The paper the document is laid out on determines the `media` option sent to the printer; any caller-supplied `media` option in `options` is replaced by this paper." },
|
||||
"path": { "type": "string" },
|
||||
"printer": { "type": "string" },
|
||||
"copies": { "type": "integer", "minimum": 1, "maximum": 999 },
|
||||
@@ -807,7 +816,7 @@ pub fn tools() -> Vec<ToolDef> {
|
||||
"area": { "type": "array", "items": { "type": "number" }, "minItems": 4, "maxItems": 4, "description": "Print a selected area: [x0, y0, x1, y1] in points from the top-left of the displayed page, of the one page in pages, sized by layout fit/actual/shrink/custom." },
|
||||
"as_image": { "type": "boolean", "description": "Print as image (Acrobat's Advanced Print Setup): every page rendered to a picture at dpi before it is placed on the paper, for printers that skip text, shading or transparency; the print is no longer searchable text, and with grayscale the pictures are grey, so the printer isn't asked for grayscale (a driver without that setting still prints them)." },
|
||||
"dpi": { "type": "number", "minimum": 72, "maximum": 600, "description": "Resolution for as_image (default 300)." },
|
||||
"options": { "type": "object", "additionalProperties": { "type": "string" }, "description": "Printer driver options from printer_options: key → choice value." },
|
||||
"options": { "type": "object", "additionalProperties": { "type": "string" }, "description": "Printer driver options from printer_options: key → choice value. Any caller-supplied `media` option is replaced by the paper the document was laid out on." },
|
||||
"color_management": { "type": "string", "enum": ["printer", "app"], "description": "Who converts the colours: printer (default, the driver does) or app, which prints the pages as images (dpi, grayscale apply) converted from sRGB into color_profile." },
|
||||
"color_profile": { "type": "string", "description": "For color_management app: a name or file name from print_color_profiles, or the path of an RGB or grey ICC printer profile." },
|
||||
"rendering_intent": { "type": "string", "enum": ["perceptual", "relative", "saturation", "absolute"], "description": "For color_management app: how colours the printer can't reach are mapped (default relative colorimetric)." },
|
||||
@@ -1320,7 +1329,7 @@ pub fn tools() -> Vec<ToolDef> {
|
||||
t("accessibility_autotag_preview", "Preview automatic tags", "Propose paragraph and heading tags for visible text blocks on one page. Returns page bounds, tentative roles and reasons. Does not change the PDF or claim accessibility compliance. Images, tables, lists, annotations and existing structure require separate review.")
|
||||
.ro()
|
||||
.with(schema(json!({ "doc": doc(), "page": { "type": "integer", "minimum": 1 } }), &["doc", "page"])),
|
||||
t("accessibility_autotag_apply", "Automatically tag text-only PDF", "Write marked content, a Document structure element, paragraph tags and a parent tree for every text object in an untagged, text-only PDF. Refuses graphics, images, annotations, forms, existing tags and malformed streams before changing anything. Review all resulting roles; this does not certify accessibility. Undoable.")
|
||||
t("accessibility_autotag_apply", "Automatically tag text-only PDF", "Write marked content, a Document structure element, heading and paragraph tags and a parent tree for every text object in an untagged, text-only PDF. Text repeating at the top or bottom of most pages (running headers, footers and page numbers) is marked as pagination artifacts instead and listed in running_text. Refuses graphics, images, annotations, forms, existing tags and malformed streams before changing anything. Review all resulting roles; this does not certify accessibility. Undoable.")
|
||||
.with(schema(json!({ "doc": doc() }), &["doc"])),
|
||||
t("accessibility_autotag_form_fields", "Tag form fields", "Write `/Form` tags, widget structure-parent keys, and a parent tree for all page widgets in an untagged AcroForm. Existing tag trees are refused for review. Text, figures, links, and other content are not tagged.")
|
||||
.cmd("a11y.autotag_fields")
|
||||
@@ -1390,7 +1399,7 @@ pub fn tools() -> Vec<ToolDef> {
|
||||
.ro()
|
||||
.cmd("a11y.alt_text")
|
||||
.with(schema(json!({ "doc": doc() }), &["doc"])),
|
||||
t("accessibility_set_alt", "Set alternate text", "Set a figure's alternate text (alt; empty or omitted clears it), or mark it decorative (decorative: true: its content becomes an artifact and the figure leaves the tags). figure is a number from accessibility_figures. Returns the figures. Undoable.")
|
||||
t("accessibility_set_alt", "Set alternate text", "Set a figure's alternate text (alt; empty or omitted clears it), or mark it decorative (decorative: true: its content becomes an artifact and the figure leaves the tags). Decorative actions reject form streams, annotation or object references, other-page or invalid content references, and tags with structure children before changing the document. figure is a number from accessibility_figures. Returns the figures. Undoable.")
|
||||
.cmd("a11y.alt_text")
|
||||
.with(schema(json!({ "doc": doc(), "figure": { "type": "integer", "minimum": 1 }, "alt": { "type": "string" }, "decorative": { "type": "boolean" } }), &["doc", "figure"])),
|
||||
t("accessibility_tags", "List structure tags", "List reachable indirect structure tags in document order with PDF object number, generation, nearest indirect parent, depth, page, type, title, actual text, alternate text, language, a table's summary and a header cell's scope, one page at a time: count is how many tags match, next the offset of the following page (null at the end). types, pages and max_depth keep only some tags. Inline tag dictionaries have no stable object reference and are not listed.")
|
||||
@@ -1418,7 +1427,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, content not found on its page, or content that a damaged or undecodable content stream may hide or change 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. Form streams, annotation or object references, other-page or invalid content references, and structure children are rejected before changing the document. Tags with no direct marked content, content not found on its page, or content that a damaged or undecodable content stream may hide or change are also rejected. Undoable.")
|
||||
.with(schema(json!({
|
||||
"doc": doc(), "object": { "type": "integer", "minimum": 1 },
|
||||
"generation": { "type": "integer", "minimum": 0, "maximum": 65535 },
|
||||
|
||||
@@ -554,6 +554,68 @@ fn autotag_apply_tags_headings_by_size_across_pages() {
|
||||
assert_eq!(nesting["status"], "passed", "{check}");
|
||||
}
|
||||
|
||||
/// #7065: Apply marks a running header and a numbered footer as pagination artifacts and lists
|
||||
/// them, and tags a body line that repeats mid-page like any other text.
|
||||
#[test]
|
||||
fn autotag_apply_marks_running_headers_and_footers_as_artifacts() {
|
||||
let dir = workdir("autotag-running");
|
||||
let page = |n: usize| {
|
||||
format!(
|
||||
"BT /FR 9 Tf 72 760 Td (Annual report) Tj ET BT /FR 11 Tf 72 640 Td (Body text on page {n} that runs long enough to set the body size) Tj ET \
|
||||
BT /FR 11 Tf 72 400 Td (A body line repeated on every page) Tj ET BT /FR 9 Tf 300 30 Td (Page {n}) Tj ET"
|
||||
)
|
||||
};
|
||||
let mut objs: Vec<String> = vec![
|
||||
"<< /Type /Catalog /Pages 2 0 R >>".into(),
|
||||
"<< /Type /Pages /Kids [3 0 R 4 0 R 5 0 R] /Count 3 /MediaBox [0 0 612 792] /Resources << /Font << /FR 9 0 R >> >> >>".into(),
|
||||
];
|
||||
objs.extend((6..9).map(|c| format!("<< /Type /Page /Parent 2 0 R /Contents {c} 0 R >>")));
|
||||
objs.extend((1..4).map(|n| {
|
||||
let content = page(n);
|
||||
format!("<< /Length {} >>\nstream\n{content}\nendstream", content.len())
|
||||
}));
|
||||
objs.push("<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>".into());
|
||||
let mut bytes = b"%PDF-1.7\n".to_vec();
|
||||
let mut offsets = Vec::new();
|
||||
for (i, o) in objs.iter().enumerate() {
|
||||
offsets.push(bytes.len());
|
||||
bytes.extend_from_slice(format!("{} 0 obj\n{o}\nendobj\n", i + 1).as_bytes());
|
||||
}
|
||||
let xref = bytes.len();
|
||||
bytes.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objs.len() + 1).as_bytes());
|
||||
for o in offsets {
|
||||
bytes.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes());
|
||||
}
|
||||
bytes.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objs.len() + 1).as_bytes());
|
||||
std::fs::write(dir.join("running.pdf"), bytes).unwrap();
|
||||
|
||||
let mut a = auto(&dir);
|
||||
let doc = ok(&mut a, "doc_open", json!({ "path": "running.pdf" }))["doc"].as_u64().unwrap();
|
||||
let applied = ok(&mut a, "accessibility_autotag_apply", json!({ "doc": doc }));
|
||||
let types: Vec<&str> = applied["tags"].as_array().unwrap().iter().map(|t| t["type"].as_str().unwrap()).collect();
|
||||
assert_eq!(types, ["Document", "P", "P", "P", "P", "P", "P"], "only the body text is tagged: {applied}");
|
||||
assert_eq!(applied["running_count"], 6);
|
||||
let listed: Vec<(u64, &str, &str)> = applied["running_text"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|r| (r["page"].as_u64().unwrap(), r["subtype"].as_str().unwrap(), r["text"].as_str().unwrap()))
|
||||
.collect();
|
||||
assert_eq!(listed[..2], [(1, "Header", "Annual report"), (1, "Footer", "Page 1")]);
|
||||
assert_eq!(listed[5], (3, "Footer", "Page 3"));
|
||||
assert!(applied["note"].as_str().unwrap().contains("6 text objects"), "{applied}");
|
||||
let check = ok(&mut a, "accessibility_check", json!({ "doc": doc, "rules": ["tagged-content"] }));
|
||||
let content = check["results"].as_array().unwrap().iter().find(|r| r["rule"] == "tagged-content").unwrap();
|
||||
assert_eq!(content["status"], "passed", "{check}");
|
||||
ok(&mut a, "doc_save", json!({ "doc": doc, "path": "tagged.pdf" }));
|
||||
let reopened = pdfcraft_cos::Document::open(std::sync::Arc::new(std::fs::read(dir.join("tagged.pdf")).unwrap())).unwrap();
|
||||
let first = pdfcraft_model::pages(&reopened).into_iter().next().unwrap();
|
||||
let pdfcraft_cos::Object::Stream(stream) = &*reopened.resolve(first.dict.get(b"Contents").unwrap()) else { panic!("page content") };
|
||||
let text = String::from_utf8(stream.decoded_strict().unwrap()).unwrap();
|
||||
assert!(text.contains("/Artifact <</Type /Pagination/Subtype /Header>> BDC"), "{text}");
|
||||
assert!(text.contains("/Artifact <</Type /Pagination/Subtype /Footer>> BDC"), "{text}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn autotag_form_fields_writes_reviewable_widget_tags() {
|
||||
let dir = workdir("autotag-form-fields");
|
||||
@@ -2758,6 +2820,19 @@ fn verify_comment_errors(a: &mut Automation, doc: u64, id: &str) {
|
||||
Err(ToolError::InvalidArgs(_))
|
||||
));
|
||||
assert!(matches!(a.call("comment_edit", &json!({ "doc": doc, "page": 1, "index": 1 })), Err(ToolError::InvalidArgs(_))));
|
||||
// #2670: opacity must be between 0 and 1.
|
||||
assert!(matches!(
|
||||
a.call("comment_add", &json!({ "doc": doc, "page": 1, "type": "note", "at": [1, 1], "opacity": -3 })),
|
||||
Err(ToolError::InvalidArgs(_))
|
||||
));
|
||||
assert!(matches!(
|
||||
a.call("comment_add", &json!({ "doc": doc, "page": 1, "type": "note", "at": [1, 1], "opacity": 1.5 })),
|
||||
Err(ToolError::InvalidArgs(_))
|
||||
));
|
||||
let first = ok(a, "comment_list", json!({ "doc": doc }))["comments"][0].clone();
|
||||
let (page, index) = (first["page"].as_u64().unwrap(), first["index"].as_u64().unwrap());
|
||||
assert!(matches!(a.call("comment_edit", &json!({ "doc": doc, "page": page, "index": index, "opacity": -1 })), Err(ToolError::InvalidArgs(_))));
|
||||
assert!(matches!(a.call("comment_edit", &json!({ "doc": doc, "page": page, "index": index, "opacity": 2.0 })), Err(ToolError::InvalidArgs(_))));
|
||||
}
|
||||
|
||||
fn save_and_reopen_comments(dir: &Path, a: &mut Automation, doc: u64) {
|
||||
@@ -4026,6 +4101,8 @@ fn watermarks_move_from_the_page_centre_through_tools() {
|
||||
// Huge offsets are clamped, and a value that isn't a number is refused.
|
||||
ok(&mut a, "doc_watermark", json!({ "doc": doc, "pages": [1], "text": "DRAFT", "offset_y": 1e300, "replace": true }));
|
||||
assert!(matches!(a.call("doc_watermark", &json!({ "doc": doc, "text": "X", "offset_x": "left" })), Err(ToolError::InvalidArgs(_))));
|
||||
assert!(matches!(a.call("doc_watermark", &json!({ "doc": doc, "text": "X", "opacity": -1 })), Err(ToolError::InvalidArgs(_))));
|
||||
assert!(matches!(a.call("doc_background", &json!({ "doc": doc, "color": "yellow", "opacity": -1 })), Err(ToolError::InvalidArgs(_))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -4377,6 +4454,145 @@ trailer << /Root 1 0 R >>
|
||||
assert!(matches!(a.call("accessibility_mark_tag_artifact", &json!({ "doc": doc, "object": 6, "generation": 0 })), Err(ToolError::Failed(_))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stream_tag_mutation_refusal_preserves_document_history_and_saved_content() {
|
||||
use pdfcraft_cos::{Document as CosDocument, Object, SaveOptions};
|
||||
use std::sync::Arc;
|
||||
|
||||
let dir = workdir("a11y-stm-refusal");
|
||||
// Contributor-original page and form use separate MCID 0 namespaces.
|
||||
let page = "/Figure <</MCID 0>> BDC 10 10 20 20 re f EMC q /Fm Do Q";
|
||||
let form = "/Figure <</MCID 0>> BDC 0 0 5 5 re f EMC";
|
||||
let source = format!(
|
||||
"%PDF-1.7\n\
|
||||
1 0 obj << /Type /Catalog /Pages 2 0 R /StructTreeRoot 5 0 R /MarkInfo << /Marked true >> >> endobj\n\
|
||||
2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj\n\
|
||||
3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 100 100] /Contents 4 0 R /StructParents 0 /Resources << /XObject << /Fm 10 0 R >> >> >> endobj\n\
|
||||
4 0 obj << /Length {} >> stream\n{page}\nendstream endobj\n\
|
||||
5 0 obj << /Type /StructTreeRoot /K 6 0 R /ParentTree 9 0 R >> endobj\n\
|
||||
6 0 obj << /S /Document /P 5 0 R /K [7 0 R 8 0 R] >> endobj\n\
|
||||
7 0 obj << /S /Figure /P 6 0 R /Pg 3 0 R /K 0 /Alt (Page figure) >> endobj\n\
|
||||
8 0 obj << /S /Figure /P 6 0 R /Pg 3 0 R /K << /Type /MCR /MCID 0 /Stm 10 0 R /Pg 3 0 R >> /Alt (Form figure) >> endobj\n\
|
||||
9 0 obj << /Nums [0 [7 0 R] 1 8 0 R] >> endobj\n\
|
||||
10 0 obj << /Type /XObject /Subtype /Form /BBox [0 0 5 5] /StructParents 1 /Length {} >> stream\n{form}\nendstream endobj\n\
|
||||
trailer << /Root 1 0 R >>\n%%EOF",
|
||||
page.len(),
|
||||
form.len()
|
||||
);
|
||||
for annotation_owned in [false, true] {
|
||||
let mut synthetic = CosDocument::open(Arc::new(source.clone().into_bytes())).unwrap();
|
||||
if annotation_owned {
|
||||
use pdfcraft_cos::{Dict, ObjRef};
|
||||
let annotation = synthetic.add(Object::Dict(Dict::from_iter([
|
||||
(b"Type".to_vec(), Object::Name(b"Annot".to_vec())),
|
||||
(b"Subtype".to_vec(), Object::Name(b"Link".to_vec())),
|
||||
(b"Rect".to_vec(), Object::Array(vec![Object::Int(0), Object::Int(0), Object::Int(10), Object::Int(10)])),
|
||||
(b"P".to_vec(), Object::Ref(ObjRef::new(3, 0))),
|
||||
(b"StructParent".to_vec(), Object::Int(2)),
|
||||
])));
|
||||
synthetic.update_dict(ObjRef::new(3, 0), |d| d.set(b"Annots".to_vec(), Object::Array(vec![Object::Ref(annotation)]))).unwrap();
|
||||
synthetic
|
||||
.update_dict(ObjRef::new(8, 0), |d| {
|
||||
d.set(
|
||||
b"K".to_vec(),
|
||||
Object::Array(vec![
|
||||
Object::Int(0),
|
||||
Object::Dict(Dict::from_iter([
|
||||
(b"Type".to_vec(), Object::Name(b"OBJR".to_vec())),
|
||||
(b"Obj".to_vec(), Object::Ref(annotation)),
|
||||
])),
|
||||
]),
|
||||
)
|
||||
})
|
||||
.unwrap();
|
||||
synthetic
|
||||
.update_dict(ObjRef::new(9, 0), |d| {
|
||||
d.set(
|
||||
b"Nums".to_vec(),
|
||||
Object::Array(vec![
|
||||
Object::Int(0),
|
||||
Object::Array(vec![Object::Ref(ObjRef::new(7, 0))]),
|
||||
Object::Int(1),
|
||||
Object::Ref(ObjRef::new(8, 0)),
|
||||
Object::Int(2),
|
||||
Object::Ref(ObjRef::new(8, 0)),
|
||||
]),
|
||||
)
|
||||
})
|
||||
.unwrap();
|
||||
}
|
||||
let source = pdfcraft_cos::write_full(&synthetic, &SaveOptions::default()).unwrap();
|
||||
std::fs::write(dir.join("stm.pdf"), source).unwrap();
|
||||
|
||||
for dirty in [false, true] {
|
||||
let mut a = auto(&dir);
|
||||
let doc = ok(&mut a, "doc_open", json!({"path":"stm.pdf"}))["doc"].as_u64().unwrap();
|
||||
let figures = ok(&mut a, "accessibility_figures", json!({"doc":doc}));
|
||||
let figure = figures["figures"].as_array().unwrap().iter().find(|f| f["alt"] == "Form figure").unwrap()["figure"].as_u64().unwrap();
|
||||
if dirty {
|
||||
ok(&mut a, "accessibility_set_alt", json!({"doc":doc,"figure":figure,"alt":"First"}));
|
||||
ok(&mut a, "accessibility_set_alt", json!({"doc":doc,"figure":figure,"alt":"Second"}));
|
||||
ok(&mut a, "edit_undo", json!({"doc":doc}));
|
||||
}
|
||||
let before = ok(&mut a, "doc_info", json!({"doc":doc}))["document"].clone();
|
||||
assert_eq!(before["dirty"], dirty);
|
||||
assert_eq!(before["undo"].is_string(), dirty);
|
||||
assert_eq!(before["redo"].is_string(), dirty);
|
||||
let tags = ok(&mut a, "accessibility_tags", json!({"doc":doc}));
|
||||
let figures = ok(&mut a, "accessibility_figures", json!({"doc":doc}));
|
||||
for (tool, args) in [
|
||||
("accessibility_set_alt", json!({"doc":doc,"figure":figure,"decorative":true})),
|
||||
("accessibility_mark_tag_artifact", json!({"doc":doc,"object":figure,"generation":0})),
|
||||
] {
|
||||
let Err(ToolError::Failed(message)) = a.call(tool, &args) else { panic!("{tool} must refuse unsupported ownership") };
|
||||
let reason = if annotation_owned { "annotation or object references" } else { "form streams" };
|
||||
assert!(message.contains(reason), "useful unsupported-content reason: {message}");
|
||||
assert_eq!(ok(&mut a, "doc_info", json!({"doc":doc}))["document"], before);
|
||||
assert_eq!(ok(&mut a, "accessibility_tags", json!({"doc":doc})), tags);
|
||||
assert_eq!(ok(&mut a, "accessibility_figures", json!({"doc":doc})), figures);
|
||||
}
|
||||
if dirty {
|
||||
ok(&mut a, "edit_redo", json!({"doc":doc}));
|
||||
let figs = ok(&mut a, "accessibility_figures", json!({"doc":doc}));
|
||||
assert_eq!(figs["figures"][1]["alt"], "Second");
|
||||
ok(&mut a, "edit_undo", json!({"doc":doc}));
|
||||
assert_eq!(ok(&mut a, "accessibility_figures", json!({"doc":doc})), figures);
|
||||
}
|
||||
let name = if dirty { "dirty.pdf" } else { "clean.pdf" };
|
||||
ok(&mut a, "doc_save", json!({"doc":doc,"path":name,"full":true}));
|
||||
let saved = CosDocument::open(Arc::new(std::fs::read(dir.join(name)).unwrap())).unwrap();
|
||||
let saved_figures = pdfcraft_engine::a11y::figures(&saved);
|
||||
assert_eq!(saved_figures.len(), 2);
|
||||
assert_eq!(saved_figures[0].alt.as_deref(), Some("Page figure"));
|
||||
assert_eq!(saved_figures[1].alt.as_deref(), Some(if dirty { "First" } else { "Form figure" }));
|
||||
assert_eq!(pdfcraft_engine::a11y::tags(&saved).len(), 3);
|
||||
let catalog = saved.get(saved.root().unwrap());
|
||||
let root = saved.dict(catalog.as_dict().unwrap().get(b"StructTreeRoot").unwrap()).unwrap();
|
||||
let tree = saved.dict(root.get(b"ParentTree").unwrap()).unwrap();
|
||||
let mut expected_nums =
|
||||
vec![Object::Int(0), Object::Array(vec![Object::Ref(saved_figures[0].obj)]), Object::Int(1), Object::Ref(saved_figures[1].obj)];
|
||||
if annotation_owned {
|
||||
expected_nums.extend([Object::Int(2), Object::Ref(saved_figures[1].obj)]);
|
||||
}
|
||||
assert_eq!(tree.get(b"Nums"), Some(&Object::Array(expected_nums)));
|
||||
let page_dict = saved.get(saved_figures[0].obj);
|
||||
let page_ref = page_dict.as_dict().unwrap().get(b"Pg").unwrap();
|
||||
let page_dict = saved.dict(page_ref).unwrap();
|
||||
if annotation_owned {
|
||||
let annotation = saved.resolve(&page_dict.get(b"Annots").unwrap().as_array().unwrap()[0]);
|
||||
assert_eq!(annotation.as_dict().unwrap().get(b"StructParent"), Some(&Object::Int(2)));
|
||||
}
|
||||
let Object::Stream(page_stream) = &*saved.resolve(page_dict.get(b"Contents").unwrap()) else { panic!("page content") };
|
||||
assert_eq!(page_stream.decoded().unwrap(), page.as_bytes());
|
||||
let resources = saved.dict(page_dict.get(b"Resources").unwrap()).unwrap();
|
||||
let xobjects = saved.dict(resources.get(b"XObject").unwrap()).unwrap();
|
||||
let Object::Stream(form_stream) = &*saved.resolve(xobjects.get(b"Fm").unwrap()) else { panic!("form content") };
|
||||
assert_eq!(form_stream.decoded().unwrap(), form.as_bytes());
|
||||
}
|
||||
}
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn accessibility_review_record_compares_two_versions_without_changing_them() {
|
||||
let dir = workdir("a11y-review-record");
|
||||
@@ -10502,6 +10718,36 @@ fn xfa_forms_flatten_and_convert_to_static_through_tools() {
|
||||
assert!(text.to_string().contains("Japan"), "{text}");
|
||||
}
|
||||
|
||||
/// A check box whose change script shows a section that needs a second page: the tools see
|
||||
/// the new page and the new fields' places, and the form saves and reopens with both pages.
|
||||
#[test]
|
||||
fn an_xfa_script_that_adds_a_page_is_seen_and_saved_through_tools() {
|
||||
let dir = workdir("xfa-script-page");
|
||||
std::fs::write(dir.join("grow.pdf"), pdfcraft_xfa::fixtures::shell(&pdfcraft_xfa::fixtures::presence_growth_template(false, "", "", "")))
|
||||
.unwrap();
|
||||
let mut a = auto(&dir);
|
||||
let doc = ok(&mut a, "doc_open", json!({ "path": "grow.pdf" }))["doc"].as_u64().unwrap();
|
||||
let pages_of = |a: &mut Automation, doc: u64| {
|
||||
let list = ok(a, "doc_list", json!({}));
|
||||
list["documents"].as_array().unwrap().iter().find(|d| d["doc"] == doc).unwrap()["pages"].as_u64().unwrap()
|
||||
};
|
||||
assert_eq!(pages_of(&mut a, doc), 1);
|
||||
ok(&mut a, "form_fill", json!({ "doc": doc, "values": { "more": true } }));
|
||||
assert_eq!(pages_of(&mut a, doc), 2);
|
||||
let fields = ok(&mut a, "form_fields", json!({ "doc": doc }));
|
||||
let d2 = fields["fields"].as_array().unwrap().iter().find(|f| f["name"] == "d2").unwrap().clone();
|
||||
assert_eq!(d2["page"], 2, "{d2}");
|
||||
assert!(d2["rect"].is_array(), "{d2}");
|
||||
ok(&mut a, "doc_save", json!({ "doc": doc, "path": "saved.pdf" }));
|
||||
let again = ok(&mut a, "doc_open", json!({ "path": "saved.pdf" }))["doc"].as_u64().unwrap();
|
||||
assert_eq!(pages_of(&mut a, again), 2);
|
||||
// The second page keeps its field: on page 2, at the place it had before saving.
|
||||
let fields = ok(&mut a, "form_fields", json!({ "doc": again }));
|
||||
let saved_d2 = fields["fields"].as_array().unwrap().iter().find(|f| f["name"] == "d2").unwrap().clone();
|
||||
assert_eq!(saved_d2["page"], 2, "{saved_d2}");
|
||||
assert_eq!(saved_d2["rect"], d2["rect"], "{saved_d2}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn xfa_data_files_export_and_import_through_tools() {
|
||||
let dir = workdir("xfa-data");
|
||||
@@ -10632,6 +10878,92 @@ fn xfa_date_fields_keep_typed_dates_as_another_viewer_does() {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// What an XFA date field shows once a date is typed into it: through its display picture, as
|
||||
/// another viewer showed the same typing on a synthetic form (the field's `formattedValue`). A
|
||||
/// date is shown in the picture; text that isn't one, as typed.
|
||||
#[test]
|
||||
fn xfa_date_fields_show_typed_dates_through_their_display_picture() {
|
||||
let dir = workdir("xfa-shown-dates");
|
||||
std::fs::write(dir.join("dates.pdf"), pdfcraft_xfa::fixtures::shell(&pdfcraft_xfa::fixtures::date_pictures_template())).unwrap();
|
||||
let mut a = auto(&dir);
|
||||
// typed, then what display, edit and either show (the field without pictures is left out:
|
||||
// the other viewer shows it in its locale's default, which isn't followed yet).
|
||||
let seen = [
|
||||
("2016-10-18", ["10/18/2016", "10/18/2016", "20161018"]),
|
||||
("10/18/2016", ["10/18/2016", "10/18/2016", "10/18/2016"]),
|
||||
("20161018", ["10/18/2016", "10/18/2016", "20161018"]),
|
||||
("18OCT16", ["18OCT16", "18OCT16", "20161018"]),
|
||||
("26 10 18", ["26 10 18", "26 10 18", "26 10 18"]),
|
||||
("xyz", ["xyz", "xyz", "xyz"]),
|
||||
];
|
||||
for (typed, shown) in seen {
|
||||
for (field, want) in ["display", "edit", "either"].into_iter().zip(shown) {
|
||||
let doc = ok(&mut a, "doc_open", json!({ "path": "dates.pdf" }))["doc"].as_u64().unwrap();
|
||||
ok(&mut a, "form_fill", json!({ "doc": doc, "values": { field: typed } }));
|
||||
let text = page_text(&mut a, doc).join("\n");
|
||||
assert_eq!(text, want, "{typed} in {field}");
|
||||
ok(&mut a, "doc_close", json!({ "doc": doc, "discard_changes": true }));
|
||||
}
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// An XFA date field whose edit picture differs from its display picture reads a typed date with
|
||||
/// the edit picture and shows it with the display picture, as another viewer did for the same
|
||||
/// typing on a synthetic form: day first in, month first out. What the edit picture can't read is
|
||||
/// kept and shown as typed.
|
||||
#[test]
|
||||
fn xfa_date_fields_read_typed_dates_through_their_edit_picture() {
|
||||
let dir = workdir("xfa-edit-dates");
|
||||
std::fs::write(dir.join("dates.pdf"), pdfcraft_xfa::fixtures::shell(&pdfcraft_xfa::fixtures::date_pictures_template())).unwrap();
|
||||
let mut a = auto(&dir);
|
||||
// typed, then what the field shows and what the data keeps.
|
||||
let seen = [
|
||||
("18/10/2016", "10/18/2016", "2016-10-18"),
|
||||
("10/11/2016", "11/10/2016", "2016-11-10"),
|
||||
("10/18/2016", "10/18/2016", "10/18/2016"),
|
||||
("2016-10-18", "10/18/2016", "2016-10-18"),
|
||||
];
|
||||
for (typed, shown, kept) in seen {
|
||||
let doc = ok(&mut a, "doc_open", json!({ "path": "dates.pdf" }))["doc"].as_u64().unwrap();
|
||||
ok(&mut a, "form_fill", json!({ "doc": doc, "values": { "swapped": typed } }));
|
||||
assert_eq!(page_text(&mut a, doc).join("\n"), shown, "{typed} shown");
|
||||
ok(&mut a, "doc_export_data", json!({ "doc": doc, "path": "data.xml", "what": "fields" }));
|
||||
let xml = std::fs::read_to_string(dir.join("data.xml")).unwrap();
|
||||
assert!(xml.contains(&format!("<swapped>{kept}</swapped>")), "{typed} kept: want {kept}, got {xml}");
|
||||
ok(&mut a, "doc_close", json!({ "doc": doc, "discard_changes": true }));
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// An XFA date field with a two-digit year in its edit picture shows the year through its display
|
||||
/// picture with the century split XFA picture clauses use, 30: `00` to `29` are 2000 to 2029,
|
||||
/// `30` to `99` are 1930 to 1999, for a date from the data and for one typed alike.
|
||||
#[test]
|
||||
fn xfa_date_fields_show_two_digit_years_with_the_century_split_of_30() {
|
||||
let xdp = r##"<?xml version="1.0" encoding="UTF-8"?>
|
||||
<xdp:xdp xmlns:xdp="http://ns.adobe.com/xdp/">
|
||||
<template xmlns="http://www.xfa.org/schema/xfa-template/3.3/">
|
||||
<subform name="form" layout="tb" locale="en_US">
|
||||
<pageSet><pageArea name="front"><contentArea x="0.5in" y="0.5in" w="7.5in" h="10in"/><medium short="8.5in" long="11in"/></pageArea></pageSet>
|
||||
<field name="born" w="2in" h="0.3in"><ui><dateTimeEdit/><picture>date{DDMMMYY}</picture></ui><value><date/></value><format><picture>date{MM/DD/YYYY}</picture></format></field>
|
||||
</subform>
|
||||
</template>
|
||||
<xfa:datasets xmlns:xfa="http://www.xfa.org/schema/xfa-data/1.0/"><xfa:data><form><born>1945-10-18</born></form></xfa:data></xfa:datasets>
|
||||
</xdp:xdp>
|
||||
"##;
|
||||
let dir = workdir("xfa-century-split");
|
||||
std::fs::write(dir.join("born.pdf"), pdfcraft_xfa::fixtures::shell(xdp)).unwrap();
|
||||
let mut a = auto(&dir);
|
||||
let doc = ok(&mut a, "doc_open", json!({ "path": "born.pdf" }))["doc"].as_u64().unwrap();
|
||||
assert_eq!(page_text(&mut a, doc).join("\n"), "10/18/1945", "from the data");
|
||||
for (typed, shown) in [("18OCT29", "10/18/2029"), ("18OCT30", "10/18/1930"), ("18OCT49", "10/18/1949"), ("18OCT50", "10/18/1950")] {
|
||||
ok(&mut a, "form_fill", json!({ "doc": doc, "values": { "born": typed } }));
|
||||
assert_eq!(page_text(&mut a, doc).join("\n"), shown, "{typed}");
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A dynamic XFA form opens laid out from its template through the tools, renders, takes values
|
||||
/// and saves them.
|
||||
#[test]
|
||||
@@ -11225,6 +11557,35 @@ fn js_run_answers_an_xfa_buttons_message_boxes() {
|
||||
assert!(r["error"].as_str().is_some_and(|e| e.contains("message box 1 (2)")), "{r}");
|
||||
}
|
||||
|
||||
/// Filling an XFA check box or radio group through form_fill clicks it, as the app does: the
|
||||
/// change scripts, then the click scripts, a radio group's before those of the button now on.
|
||||
#[test]
|
||||
fn xfa_check_box_and_radio_clicks_run_through_form_fill() {
|
||||
let dir = workdir("xfa-toggle");
|
||||
std::fs::write(dir.join("toggle.pdf"), pdfcraft_xfa::fixtures::shell(&pdfcraft_xfa::fixtures::toggle_template())).unwrap();
|
||||
let mut a = auto(&dir);
|
||||
let doc = ok(&mut a, "doc_open", json!({ "path": "toggle.pdf" }))["doc"].as_u64().unwrap();
|
||||
// What the scripts have written to the form's log field so far.
|
||||
let log = |a: &mut Automation| {
|
||||
let f = ok(a, "form_fields", json!({ "doc": doc }));
|
||||
f["fields"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.find(|f| f["name"] == "log")
|
||||
.map(|f| f["value"].as_str().unwrap_or_default().to_string())
|
||||
.unwrap_or_default()
|
||||
};
|
||||
ok(&mut a, "form_fill", json!({ "doc": doc, "values": { "agree": true } }));
|
||||
assert_eq!(log(&mut a), "change 1;click 1;");
|
||||
let fields = ok(&mut a, "form_fields", json!({ "doc": doc }));
|
||||
let answer = fields["fields"].as_array().unwrap().iter().find(|f| f["name"] == "answer").cloned().expect("the radio group");
|
||||
let no = answer["options"].as_array().and_then(|o| o.get(1)).and_then(|o| o.as_str().map(str::to_string)).unwrap_or_else(|| panic!("{answer}"));
|
||||
ok(&mut a, "form_fill", json!({ "doc": doc, "values": { "answer": no } }));
|
||||
assert!(log(&mut a).ends_with("group click;no click;no exit;group exit;"), "{}", log(&mut a));
|
||||
}
|
||||
|
||||
/// A form whose opening script runs away has its scripts turned off, and doc_info says so.
|
||||
#[test]
|
||||
fn active_xfa_skips_container_fallback_scripts_after_save_and_reopen() {
|
||||
let dir = workdir("xfa-container-scripts");
|
||||
@@ -11264,11 +11625,42 @@ fn doc_info_says_when_a_runaway_script_turned_the_forms_scripts_off() {
|
||||
);
|
||||
std::fs::write(dir.join("runaway.pdf"), pdfcraft_xfa::fixtures::shell(&tpl)).unwrap();
|
||||
let mut a = auto(&dir);
|
||||
let doc = ok(&mut a, "doc_open", json!({ "path": "runaway.pdf" }))["doc"].as_u64().unwrap();
|
||||
let opened = ok(&mut a, "doc_open", json!({ "path": "runaway.pdf" }));
|
||||
let doc = opened["doc"].as_u64().unwrap();
|
||||
// doc_open's warnings also hold the message that the form's scripts are off.
|
||||
let warnings = opened["warnings"].as_array().unwrap_or_else(|| panic!("{opened}"));
|
||||
assert!(warnings.iter().any(|w| w.as_str().is_some_and(|w| w.contains("the form's scripts are off"))), "{opened}");
|
||||
assert_eq!(ok(&mut a, "doc_info", json!({ "doc": doc }))["xfa_scripts_off"], true);
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn doc_open_and_form_fill_report_the_errors_of_the_forms_scripts() {
|
||||
let dir = workdir("xfa-script-errors");
|
||||
// The initialize script fails on open; the total's calculation fails once qty is 4.
|
||||
let tpl = pdfcraft_xfa::fixtures::scripted_template()
|
||||
.replace("if (qty.rawValue === null) qty.rawValue = 2;", "qty.rawValue = 2; throw new Error('open failed');")
|
||||
.replace(
|
||||
"<calculate><script contentType=\"application/x-javascript\">qty.rawValue * price.rawValue</script></calculate>",
|
||||
"<calculate><script contentType=\"application/x-javascript\">if (qty.rawValue == 4) throw new Error('fill failed'); qty.rawValue * price.rawValue</script></calculate>",
|
||||
);
|
||||
std::fs::write(dir.join("errors.pdf"), pdfcraft_xfa::fixtures::shell(&tpl)).unwrap();
|
||||
// Raised time limits: a busy machine does not stop the scripts this checks.
|
||||
let mut a = auto(&dir).with_xfa_time_scale(100);
|
||||
let warns = |out: &Value, text: &str| out["warnings"].as_array().is_some_and(|w| w.iter().any(|w| w.as_str().is_some_and(|w| w.contains(text))));
|
||||
let opened = ok(&mut a, "doc_open", json!({ "path": "errors.pdf" }));
|
||||
let doc = opened["doc"].as_u64().unwrap();
|
||||
assert!(warns(&opened, "open failed"), "{opened}");
|
||||
// A button click after the open returns no error, because doc_open took the open's error.
|
||||
let r = ok(&mut a, "js_run", json!({ "doc": doc, "script": "", "field": "hello" }));
|
||||
assert!(r["error"].is_null(), "{r}");
|
||||
assert_eq!(r["alerts"], json!([{ "message": "Hello 2", "title": null, "icon": "error", "buttons": "ok" }]), "{r}");
|
||||
let filled = ok(&mut a, "form_fill", json!({ "doc": doc, "values": { "qty": "4" } }));
|
||||
assert!(warns(&filled, "fill failed"), "{filled}");
|
||||
assert!(!warns(&filled, "open failed"), "{filled}");
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
/// doc_info describes a link's set-layer-visibility action by layer name, and each layer's
|
||||
/// visibility now and as the file opens.
|
||||
#[test]
|
||||
@@ -11904,7 +12296,8 @@ fn a_deleted_image_is_not_kept_by_reduce_or_optimize() {
|
||||
assert_eq!(ok(&mut a, "page_images", json!({ "doc": doc, "page": 1 }))["count"], 0);
|
||||
// The page is blank, so the copies are tiny: the picture's data is not carried along.
|
||||
let r = ok(&mut a, "doc_optimize", json!({ "doc": doc, "path": "optimized.pdf" }));
|
||||
assert_eq!(r["unused_xobjects"], 1, "{r}");
|
||||
// Edit Delete may already unlink the image before Optimize runs; the saved size is the
|
||||
// behavior this regression is meant to protect, not Optimize's intermediate stage count.
|
||||
assert!(r["bytes_after"].as_u64().unwrap() < 4_000, "{r}");
|
||||
let r = ok(&mut a, "doc_reduce", json!({ "doc": doc, "path": "reduced.pdf" }));
|
||||
assert!(r["bytes_after"].as_u64().unwrap() < 4_000, "{r}");
|
||||
@@ -12773,6 +13166,78 @@ fn printer_marks_through_tools() {
|
||||
));
|
||||
}
|
||||
|
||||
/// Marks and bleeds when printing: the marks are on the printed sheets, the document gets none.
|
||||
#[test]
|
||||
fn printing_with_printer_marks_through_tools() {
|
||||
let dir = workdir("print-marks");
|
||||
let mut a = auto(&dir);
|
||||
let doc = ok(&mut a, "doc_open", json!({ "path": "a.pdf" }))["doc"].as_u64().unwrap();
|
||||
let before = page_text(&mut a, doc);
|
||||
let width = ok(&mut a, "doc_info", json!({ "doc": doc }))["pages"][1]["width"].clone();
|
||||
let r =
|
||||
ok(&mut a, "doc_print", json!({ "doc": doc, "pages": "2", "layout": "actual", "marks": ["all"], "marks_weight": 0.5, "path": "marked.pdf" }));
|
||||
assert_eq!(r["sheets"], 1);
|
||||
let printed = ok(&mut a, "doc_open", json!({ "path": "marked.pdf" }))["doc"].as_u64().unwrap();
|
||||
let sheet = page_text(&mut a, printed).concat();
|
||||
assert!(sheet.contains("a.pdf") && sheet.contains("2 of 3"), "the page information line: {sheet}");
|
||||
ok(&mut a, "doc_close", json!({ "doc": printed }));
|
||||
ok(&mut a, "doc_print", json!({ "doc": doc, "pages": "2", "marks": ["trim", "registration"], "path": "trim.pdf" }));
|
||||
let trim = ok(&mut a, "doc_open", json!({ "path": "trim.pdf" }))["doc"].as_u64().unwrap();
|
||||
assert!(!page_text(&mut a, trim).concat().contains("2 of 3"), "only the marks asked for");
|
||||
// The document itself is untouched.
|
||||
assert_eq!(page_text(&mut a, doc), before);
|
||||
let info = ok(&mut a, "doc_info", json!({ "doc": doc }));
|
||||
assert_eq!((&info["pages"][1]["width"], &info["document"]["dirty"]), (&width, &json!(false)));
|
||||
for (wrong, says) in [
|
||||
(json!({ "marks": [] }), "marks must be a list"),
|
||||
(json!({ "marks": ["crop"] }), "marks must be a list"),
|
||||
(json!({ "marks": "all" }), "marks must be a list"),
|
||||
(json!({ "marks": ["all"], "marks_weight": 10 }), "marks_weight must be from"),
|
||||
(json!({ "marks_weight": 1 }), "marks_weight needs marks"),
|
||||
(json!({ "marks": ["all"], "layout": "multiple", "per_sheet": 2 }), "one page a sheet"),
|
||||
(json!({ "marks": ["all"], "layout": "booklet" }), "one page a sheet"),
|
||||
(json!({ "marks": ["all"], "as_image": true }), "as they are"),
|
||||
(json!({ "marks": ["all"], "pages": "1", "area": [0, 0, 50, 50] }), "without printer marks"),
|
||||
] {
|
||||
let mut args = wrong.clone();
|
||||
args["doc"] = json!(doc);
|
||||
args["path"] = json!("x.pdf");
|
||||
match a.call("doc_print", &args) {
|
||||
Err(ToolError::InvalidArgs(m)) => assert!(m.contains(says), "{wrong}: {m}"),
|
||||
other => panic!("{wrong}: {other:?}"),
|
||||
}
|
||||
}
|
||||
assert!(!dir.join("x.pdf").exists());
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
/// Marks on a protected document: low-resolution-only printing refuses the marks, since it
|
||||
/// prints as pictures; no printing at all is the permission error, not the marks one.
|
||||
#[test]
|
||||
fn printing_marks_on_a_print_restricted_document_through_tools() {
|
||||
let dir = workdir("print-marks-restricted");
|
||||
let mut a = auto(&dir);
|
||||
for (printing, file) in [("low", "low.pdf"), ("none", "none.pdf")] {
|
||||
let doc = ok(&mut a, "doc_open", json!({ "path": "a.pdf" }))["doc"].as_u64().unwrap();
|
||||
ok(&mut a, "doc_protect", json!({ "doc": doc, "permissions_password": "boss", "printing": printing }));
|
||||
ok(&mut a, "doc_save", json!({ "doc": doc, "path": file }));
|
||||
ok(&mut a, "doc_close", json!({ "doc": doc }));
|
||||
}
|
||||
let mut b = auto(&dir);
|
||||
let low = ok(&mut b, "doc_open", json!({ "path": "low.pdf" }))["doc"].as_u64().unwrap();
|
||||
match b.call("doc_print", &json!({ "doc": low, "pages": "1", "marks": ["all"], "path": "x.pdf" })) {
|
||||
Err(ToolError::InvalidArgs(m)) => assert!(m.contains("low-resolution"), "{m}"),
|
||||
other => panic!("low-resolution only: {other:?}"),
|
||||
}
|
||||
let none = ok(&mut b, "doc_open", json!({ "path": "none.pdf" }))["doc"].as_u64().unwrap();
|
||||
match b.call("doc_print", &json!({ "doc": none, "pages": "1", "marks": ["all"], "path": "x.pdf" })) {
|
||||
Err(ToolError::Failed(m)) => assert!(m.contains("don't allow printing"), "{m}"),
|
||||
other => panic!("no printing: {other:?}"),
|
||||
}
|
||||
assert!(!dir.join("x.pdf").exists());
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
/// Convert colours through the tools: counts, converts, reports nothing to do.
|
||||
#[test]
|
||||
fn convert_colours_through_tools() {
|
||||
@@ -14890,3 +15355,63 @@ fn grouped_existing_thai_body_edits_saves_reopens_and_undo_restores_original_gly
|
||||
assert_eq!(page_text(&mut a, reopened), [new, old]);
|
||||
assert_eq!(ok(&mut a, "content_list", json!({"doc":reopened}))["count"], 0, "editing existing text must not create Add Text objects");
|
||||
}
|
||||
|
||||
/// #7687: an oversized source CropBox must not expose hidden artwork or change fit.
|
||||
#[test]
|
||||
fn pdf_watermark_uses_visible_source_crop_through_tools() {
|
||||
use pdfcraft_cos::{Document, Object, SaveOptions, Stream, write_full};
|
||||
use std::sync::Arc;
|
||||
let dir = workdir("watermark-visible-crop");
|
||||
let mut source = Document::open(Arc::new(fixture(2))).unwrap();
|
||||
for (index, crop_right) in [100, 140].into_iter().enumerate() {
|
||||
let page = pdfcraft_model::page_at(&source, index).unwrap().obj;
|
||||
let content = source.add(Object::Stream(Stream::flate(
|
||||
Default::default(),
|
||||
b"1 0 0 rg 20 30 80 120 re f 0 0 1 rg 20 30 20 50 re f 1 0 1 rg 100 30 40 120 re f",
|
||||
)));
|
||||
source
|
||||
.update_dict(page, |d| {
|
||||
d.set(b"MediaBox".to_vec(), Object::Array(vec![20.into(), 30.into(), 100.into(), 150.into()]));
|
||||
d.set(b"CropBox".to_vec(), Object::Array(vec![20.into(), 30.into(), crop_right.into(), 150.into()]));
|
||||
d.set(b"Rotate".to_vec(), Object::Int(90));
|
||||
d.set(b"Contents".to_vec(), Object::Ref(content));
|
||||
})
|
||||
.unwrap();
|
||||
}
|
||||
std::fs::write(dir.join("source.pdf"), write_full(&source, &SaveOptions::default()).unwrap()).unwrap();
|
||||
let mut target = Document::open(Arc::new(fixture(3))).unwrap();
|
||||
let first = pdfcraft_model::page_at(&target, 0).unwrap().obj;
|
||||
target
|
||||
.update_dict(first, |d| {
|
||||
d.set(b"MediaBox".to_vec(), Object::Array(vec![0.into(), 0.into(), 215.into(), 280.into()]));
|
||||
d.set(b"CropBox".to_vec(), Object::Array(vec![24.into(), 18.into(), 184.into(), 258.into()]));
|
||||
})
|
||||
.unwrap();
|
||||
std::fs::write(dir.join("a.pdf"), write_full(&target, &SaveOptions::default()).unwrap()).unwrap();
|
||||
let mut a = auto(&dir);
|
||||
for rotation in [0, 270] {
|
||||
let mut rendered = Vec::new();
|
||||
for source_page in [1, 2] {
|
||||
let doc = ok(&mut a, "doc_open", json!({"path": "a.pdf"}))["doc"].as_u64().unwrap();
|
||||
if rotation != 0 {
|
||||
ok(&mut a, "page_rotate", json!({"doc": doc, "pages": [1], "degrees": rotation}));
|
||||
}
|
||||
let untouched = a.call("page_render", &json!({"doc": doc, "page": 2, "dpi": 72})).unwrap();
|
||||
ok(
|
||||
&mut a,
|
||||
"doc_watermark",
|
||||
json!({"doc": doc, "pages": [1], "file": "source.pdf", "file_page": source_page,
|
||||
"scale": 0.5, "rotation": 0, "opacity": 1, "offset_x": 22, "offset_y": 10}),
|
||||
);
|
||||
let path = format!("marked-{rotation}-{source_page}.pdf");
|
||||
ok(&mut a, "doc_save", json!({"doc": doc, "path": path}));
|
||||
let copy = ok(&mut a, "doc_open", json!({"path": path}))["doc"].as_u64().unwrap();
|
||||
assert_eq!(a.call("page_render", &json!({"doc": copy, "page": 2, "dpi": 72})).unwrap(), untouched);
|
||||
let (w, _, rgba) = a.render_pixels(copy, 1, 1.0).unwrap();
|
||||
assert!(rgba.as_ref().as_chunks::<4>().0.iter().any(|p| p[0] > 240 && p[1] < 10 && p[2] < 10), "visible red artwork remains");
|
||||
assert!(!rgba.as_ref().as_chunks::<4>().0.iter().any(|p| p[0] > 240 && p[1] < 10 && p[2] > 240), "hidden magenta stays clipped");
|
||||
rendered.push((w, rgba.as_ref().to_vec()));
|
||||
}
|
||||
assert_eq!(rendered[0], rendered[1], "same displayed source gives identical saved watermark at target rotation {rotation}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -123,3 +123,30 @@ fn js_event_runs_the_field_its_field_id_names() {
|
||||
);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// Printer marks that would widen a 14,400 pt page past the largest page a PDF can have are
|
||||
/// refused before Will Print runs, so its field change isn't left behind by a print that fails.
|
||||
#[test]
|
||||
fn marks_that_cannot_fit_fail_before_will_print() {
|
||||
let pdf = pdf_of(&[
|
||||
"<< /Type /Catalog /Pages 2 0 R /AA << /WP 6 0 R >> /AcroForm << /Fields [4 0 R] /DA (/Helv 0 Tf 0 g) /DR << /Font << /Helv 5 0 R >> >> >> >>".into(),
|
||||
"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 14400 300] >>".into(),
|
||||
"<< /Type /Page /Parent 2 0 R /Annots [4 0 R] >>".into(),
|
||||
"<< /Type /Annot /Subtype /Widget /FT /Tx /T (log) /V () /Rect [20 250 180 270] /P 3 0 R /F 4 >>".into(),
|
||||
"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>".into(),
|
||||
"<< /S /JavaScript /JS (getField\\('log'\\).value += 'print;';) >>".into(),
|
||||
]);
|
||||
let dir = std::env::temp_dir().join(format!("pdfcraft-marks-will-print-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
std::fs::write(dir.join("wide.pdf"), pdf).unwrap();
|
||||
let mut a = Automation::new().with_root(&dir).unwrap().with_clock(|| 1_700_000_000);
|
||||
let doc = tool(&mut a, "doc_open", json!({ "path": "wide.pdf" }))["doc"].as_u64().unwrap();
|
||||
let refused = a.call("doc_print", &json!({ "doc": doc, "marks": ["trim"], "path": "marked.pdf" }));
|
||||
assert!(refused.is_err(), "{refused:?}");
|
||||
assert_eq!(log(&mut a, doc).as_str().unwrap_or_default(), "", "Will Print didn't run");
|
||||
assert!(!dir.join("marked.pdf").exists());
|
||||
// Without marks the page prints, and Will Print runs.
|
||||
tool(&mut a, "doc_print", json!({ "doc": doc, "path": "plain.pdf" }));
|
||||
assert_eq!(log(&mut a, doc), "print;");
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
@@ -25,6 +25,7 @@ mod portfolio_info;
|
||||
mod redact_after_stray_q_form;
|
||||
mod redact_text_after_q;
|
||||
mod render_warnings;
|
||||
mod suggest_outline;
|
||||
mod text_copy;
|
||||
mod timesheet_compat;
|
||||
mod unreadable_objects;
|
||||
|
||||
@@ -0,0 +1,157 @@
|
||||
//! #6020: `bookmark_suggest` proposes an outline for an untagged document from how its text looks,
|
||||
//! uses the tags once there are some, and its proposal goes back in through `bookmark_import`.
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
use pdfcraft_automation::{Automation, Content};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
fn tmp(name: &str) -> PathBuf {
|
||||
let d = std::env::temp_dir().join(format!("pdfcraft-suggest-outline-{}-{name}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
std::fs::create_dir_all(&d).unwrap();
|
||||
d
|
||||
}
|
||||
|
||||
fn ok(a: &mut Automation, tool: &str, args: Value) -> Value {
|
||||
match a.call(tool, &args) {
|
||||
Ok(mut c) => match c.remove(0) {
|
||||
Content::Json(v) => v,
|
||||
other => panic!("{tool}: expected JSON, got {other:?}"),
|
||||
},
|
||||
Err(e) => panic!("{tool} {args}: {e}"),
|
||||
}
|
||||
}
|
||||
|
||||
const BODY: &str = "Body text runs on for a good many characters across the page.";
|
||||
|
||||
/// A chapter heading (Helvetica-Bold 20) set on two lines, body text (Helvetica 11), a bold
|
||||
/// caption, a section heading (Helvetica-Bold 14), and a second chapter on page 2.
|
||||
fn report_pdf() -> Vec<u8> {
|
||||
let body = |y: u32| format!("BT /FR 11 Tf 72 {y} Td ({BODY}) Tj ET ");
|
||||
let page1 = format!(
|
||||
"BT /FB 20 Tf 72 740 Td (Getting started) Tj 0 -22 Td (with the toolkit) Tj ET {}{}\
|
||||
BT /FB 14 Tf 72 640 Td (Figure 1 The toolkit) Tj ET {}\
|
||||
BT /FB 14 Tf 72 590 Td (Installing) Tj ET {}{}",
|
||||
body(690),
|
||||
body(676),
|
||||
body(620),
|
||||
body(566),
|
||||
body(552)
|
||||
);
|
||||
let page2 = format!("BT /FB 20 Tf 72 740 Td (Reference) Tj ET {}{}", body(700), body(686));
|
||||
two_pages(&page1, &page2)
|
||||
}
|
||||
|
||||
/// Two untagged pages drawing `page1` and `page2` with `/FB` (Helvetica-Bold) and `/FR`
|
||||
/// (Helvetica).
|
||||
fn two_pages(page1: &str, page2: &str) -> Vec<u8> {
|
||||
let contents = [page1, page2];
|
||||
let mut objs: Vec<String> = vec![
|
||||
"<< /Type /Catalog /Pages 2 0 R >>".into(),
|
||||
"<< /Type /Pages /Kids [3 0 R 4 0 R] /Count 2 /MediaBox [0 0 612 792] /Resources << /Font << /FB 7 0 R /FR 8 0 R >> >> >>".into(),
|
||||
"<< /Type /Page /Parent 2 0 R /Contents 5 0 R >>".into(),
|
||||
"<< /Type /Page /Parent 2 0 R /Contents 6 0 R >>".into(),
|
||||
];
|
||||
objs.extend(contents.iter().map(|c| format!("<< /Length {} >>\nstream\n{c}\nendstream", c.len())));
|
||||
objs.push("<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica-Bold /Encoding /WinAnsiEncoding >>".into());
|
||||
objs.push("<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>".into());
|
||||
let mut bytes = b"%PDF-1.7\n".to_vec();
|
||||
let mut offsets = Vec::new();
|
||||
for (i, o) in objs.iter().enumerate() {
|
||||
offsets.push(bytes.len());
|
||||
bytes.extend_from_slice(format!("{} 0 obj\n{o}\nendobj\n", i + 1).as_bytes());
|
||||
}
|
||||
let xref = bytes.len();
|
||||
bytes.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objs.len() + 1).as_bytes());
|
||||
for o in offsets {
|
||||
bytes.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes());
|
||||
}
|
||||
bytes.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objs.len() + 1).as_bytes());
|
||||
bytes
|
||||
}
|
||||
|
||||
/// (title, page, children's titles) for each top-level node.
|
||||
fn outline(nodes: &Value) -> Vec<(String, u64, Vec<String>)> {
|
||||
let title = |n: &Value| n["title"].as_str().unwrap().to_string();
|
||||
nodes
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|n| (title(n), n["page"].as_u64().unwrap(), n["children"].as_array().map_or(Vec::new(), |c| c.iter().map(title).collect())))
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn suggest_from_layout_then_import_and_undo() {
|
||||
let dir = tmp("layout");
|
||||
std::fs::write(dir.join("report.pdf"), report_pdf()).unwrap();
|
||||
let mut a = Automation::new().with_root(&dir).unwrap();
|
||||
let doc = ok(&mut a, "doc_open", json!({ "path": "report.pdf" }))["doc"].as_u64().unwrap();
|
||||
let s = ok(&mut a, "bookmark_suggest", json!({ "doc": doc }));
|
||||
assert_eq!(s["source"], "layout");
|
||||
assert_eq!(s["truncated"], false);
|
||||
assert_eq!((s["headings"].as_u64(), s["pages"].as_u64(), s["pages_read"].as_u64()), (Some(3), Some(2), Some(2)));
|
||||
let expected =
|
||||
vec![("Getting started with the toolkit".to_string(), 1, vec!["Installing".to_string()]), ("Reference".to_string(), 2, Vec::new())];
|
||||
assert_eq!(outline(&s["bookmarks"]), expected, "the caption is left out and the wrapped heading is one bookmark");
|
||||
let view = &s["bookmarks"][0]["view"];
|
||||
assert_eq!(view["type"], "XYZ");
|
||||
assert_eq!(view["values"][2], Value::Null, "the zoom is the reader's");
|
||||
assert!(view["values"][1].as_f64().is_some_and(|top| top > 740.0), "goes to the top of the heading: {view}");
|
||||
// It changed nothing; the reviewed list goes in as one undoable step.
|
||||
assert_eq!(ok(&mut a, "bookmark_list", json!({ "doc": doc }))["bookmarks"], json!([]));
|
||||
ok(&mut a, "bookmark_import", json!({ "doc": doc, "bookmarks": s["bookmarks"], "replace": true }));
|
||||
let back = ok(&mut a, "bookmark_export", json!({ "doc": doc }));
|
||||
assert_eq!(outline(&back["bookmarks"]), expected);
|
||||
ok(&mut a, "edit_undo", json!({ "doc": doc }));
|
||||
assert_eq!(ok(&mut a, "bookmark_list", json!({ "doc": doc }))["bookmarks"], json!([]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn suggest_uses_the_tags_once_there_are_some() {
|
||||
let dir = tmp("structure");
|
||||
std::fs::write(dir.join("report.pdf"), report_pdf()).unwrap();
|
||||
let mut a = Automation::new().with_root(&dir).unwrap();
|
||||
let doc = ok(&mut a, "doc_open", json!({ "path": "report.pdf" }))["doc"].as_u64().unwrap();
|
||||
ok(&mut a, "accessibility_autotag_apply", json!({ "doc": doc }));
|
||||
let s = ok(&mut a, "bookmark_suggest", json!({ "doc": doc }));
|
||||
assert_eq!(s["source"], "structure");
|
||||
let titles: Vec<&str> = s["bookmarks"].as_array().unwrap().iter().map(|n| n["title"].as_str().unwrap()).collect();
|
||||
assert!(titles.first().is_some_and(|t| t.starts_with("Getting started")), "{s}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_in_one_style_gets_no_suggestion_and_a_note() {
|
||||
let dir = tmp("plain");
|
||||
let page = format!("BT /FR 11 Tf 72 700 Td ({BODY}) Tj 0 -14 Td ({BODY}) Tj ET");
|
||||
std::fs::write(dir.join("plain.pdf"), two_pages(&page, &page)).unwrap();
|
||||
let mut a = Automation::new().with_root(&dir).unwrap();
|
||||
let doc = ok(&mut a, "doc_open", json!({ "path": "plain.pdf" }))["doc"].as_u64().unwrap();
|
||||
let s = ok(&mut a, "bookmark_suggest", json!({ "doc": doc }));
|
||||
assert_eq!((s["source"].as_str(), s["headings"].as_u64(), &s["bookmarks"]), (Some("layout"), Some(0), &json!([])));
|
||||
assert!(s["note"].as_str().is_some_and(|n| n.contains("bookmark_from_text_styles")), "{s}");
|
||||
}
|
||||
|
||||
/// A suggested bookmark has no level to edit: bookmark_import refuses one, and the nesting changes
|
||||
/// by moving a bookmark into or out of another's children, as the tool description says.
|
||||
#[test]
|
||||
fn a_suggestion_is_renested_through_children_not_levels() {
|
||||
let dir = tmp("renest");
|
||||
std::fs::write(dir.join("report.pdf"), report_pdf()).unwrap();
|
||||
let mut a = Automation::new().with_root(&dir).unwrap();
|
||||
let doc = ok(&mut a, "doc_open", json!({ "path": "report.pdf" }))["doc"].as_u64().unwrap();
|
||||
let mut bookmarks = ok(&mut a, "bookmark_suggest", json!({ "doc": doc }))["bookmarks"].clone();
|
||||
let mut leveled = bookmarks.clone();
|
||||
leveled[0]["level"] = json!(2);
|
||||
let refused = a.call("bookmark_import", &json!({ "doc": doc, "bookmarks": leveled, "replace": true }));
|
||||
assert!(refused.is_err_and(|e| e.to_string().contains("unknown key")), "a level was taken");
|
||||
let child = bookmarks[0]["children"].as_array_mut().unwrap().remove(0);
|
||||
bookmarks.as_array_mut().unwrap().push(child);
|
||||
ok(&mut a, "bookmark_import", json!({ "doc": doc, "bookmarks": bookmarks, "replace": true }));
|
||||
let back = ok(&mut a, "bookmark_export", json!({ "doc": doc }));
|
||||
let top: Vec<String> = outline(&back["bookmarks"]).into_iter().map(|(t, _, _)| t).collect();
|
||||
assert_eq!(top, ["Getting started with the toolkit", "Reference", "Installing"]);
|
||||
let tool = pdfcraft_automation::tools().into_iter().find(|t| t.name == "bookmark_suggest").unwrap();
|
||||
assert!(tool.description.contains("children") && !tool.description.contains("levels or"), "{}", tool.description);
|
||||
}
|
||||
@@ -621,6 +621,22 @@ thread_local! {
|
||||
|
||||
/// Remove flattened widgets from the AcroForm field tree, and fields left without widgets. With
|
||||
/// `on_page`, also the widgets (fields without kids) that are on no page.
|
||||
/// Whether the field at `r` is a signature field: its `/FT`, or the nearest one up its `/Parent`
|
||||
/// chain (field types are inherited). The walk stops after 64 parents, so a cycle ends.
|
||||
fn is_signature_field(doc: &Document, r: ObjRef) -> bool {
|
||||
let mut node = r;
|
||||
for _ in 0..=64 {
|
||||
let obj = doc.get(node);
|
||||
let Some(d) = obj.as_dict() else { return false };
|
||||
if let Some(ft) = d.get(b"FT").map(|v| doc.resolve(v)).and_then(|v| v.as_name().map(|n| n.to_vec())) {
|
||||
return ft == b"Sig";
|
||||
}
|
||||
let Some(parent) = d.get(b"Parent").and_then(|p| p.as_ref()) else { return false };
|
||||
node = parent;
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
fn prune_fields(doc: &mut Document, widgets: &HashSet<ObjRef>, on_page: Option<&HashSet<ObjRef>>) -> Result<(), EditError> {
|
||||
let Some(root) = doc.root() else { return Ok(()) };
|
||||
let Some(af) = doc.get(root).as_dict().and_then(|d| d.get(b"AcroForm").cloned()) else { return Ok(()) };
|
||||
@@ -680,10 +696,45 @@ fn prune_fields(doc: &mut Document, widgets: &HashSet<ObjRef>, on_page: Option<&
|
||||
let mut known = HashMap::new();
|
||||
let survivors: Vec<Object> =
|
||||
fields.iter().filter(|f| f.as_ref().is_none_or(|r| keep(doc, r, widgets, on_page, &mut known, 0).0)).cloned().collect();
|
||||
if survivors.len() == fields.len() && widgets.is_empty() {
|
||||
// A field taken out of a kept parent's `/Kids` leaves `/Fields` as long as it was, and still
|
||||
// needs `/CO` and `/SigFlags` cleaned.
|
||||
let removed_any = known.values().any(|&(survives, _)| !survives);
|
||||
if survivors.len() == fields.len() && widgets.is_empty() && !removed_any {
|
||||
return Ok(()); // only looked for fields on no page, and there were none
|
||||
}
|
||||
// Every field left in the tree, however deep: `known` stops at the depth cutoff, so walk the
|
||||
// kept tree again from `/Fields`, each node once (a cycle ends where it began).
|
||||
let mut surviving: HashSet<ObjRef> = HashSet::new();
|
||||
let mut stack: Vec<ObjRef> = survivors.iter().filter_map(Object::as_ref).collect();
|
||||
while let Some(r) = stack.pop() {
|
||||
if widgets.contains(&r) || matches!(known.get(&r), Some(&(false, _))) || !surviving.insert(r) {
|
||||
continue;
|
||||
}
|
||||
let Some(d) = doc.get(r).as_dict().cloned() else { continue };
|
||||
if let Some(kids) = d.get(b"Kids").map(|k| doc.resolve(k)).and_then(|k| k.as_array().cloned()) {
|
||||
stack.extend(kids.iter().filter_map(Object::as_ref));
|
||||
}
|
||||
}
|
||||
af_dict.set(b"Fields".to_vec(), Object::Array(survivors));
|
||||
// #2670: the calculation order keeps only the fields that are left, and goes once it is empty.
|
||||
// Only the form's keys change: an indirect `/CO` or `/SigFlags` may be shared, so it is neither
|
||||
// freed (that would null the other references) nor rewritten (they would see the shorter
|
||||
// list). A shortened order is the form's own direct array; once nothing refers to the old
|
||||
// object, a full save leaves it out.
|
||||
if let Some(co_obj) = af_dict.get(b"CO").cloned() {
|
||||
let co_array = doc.resolve(&co_obj).as_array().cloned().unwrap_or_default();
|
||||
let before = co_array.len();
|
||||
let co_survivors: Vec<Object> = co_array.into_iter().filter(|item| item.as_ref().is_some_and(|r| surviving.contains(&r))).collect();
|
||||
if co_survivors.is_empty() {
|
||||
af_dict.remove(b"CO");
|
||||
} else if co_survivors.len() != before {
|
||||
af_dict.set(b"CO".to_vec(), Object::Array(co_survivors));
|
||||
}
|
||||
}
|
||||
// #2670: with no signature field left, the form no longer claims to hold signatures.
|
||||
if !surviving.iter().any(|&r| is_signature_field(doc, r)) {
|
||||
af_dict.remove(b"SigFlags");
|
||||
}
|
||||
match af_ref {
|
||||
Some(r) => doc.set(r, Object::Dict(af_dict)),
|
||||
None => doc.update_dict(root, |d| d.set(b"AcroForm".to_vec(), Object::Dict(af_dict)))?,
|
||||
|
||||
+873
-20
@@ -4,7 +4,7 @@
|
||||
//! delete, or ungroup grouped artwork (its content drawn in place, see `ungroup`). Only the stream that draws it is rewritten, as a new object.
|
||||
|
||||
use kurbo::{BezPath, Point, Shape};
|
||||
use pdfcraft_content::{Matrix, Op, parse, serialize_ops};
|
||||
use pdfcraft_content::{Matrix, Op, Pieces, parse, serialize_ops};
|
||||
use pdfcraft_cos::{Dict, Document, ObjRef, Object};
|
||||
use std::sync::Arc;
|
||||
|
||||
@@ -123,6 +123,816 @@ fn xobjects(doc: &Document, page: &Dict) -> Dict {
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
const IMAGE_CENSUS_MAX_OBJECTS: usize = 100_000;
|
||||
const IMAGE_CENSUS_MAX_BYTES: usize = 128 * 1024 * 1024;
|
||||
const IMAGE_CENSUS_MAX_OPERATORS: usize = 5_000_000;
|
||||
const IMAGE_CENSUS_MAX_VISITS: usize = 50_000;
|
||||
const IMAGE_CENSUS_MAX_DEPTH: usize = 64;
|
||||
const IMAGE_CENSUS_MAX_ALIASES: usize = 255;
|
||||
const IMAGE_REWRITE_MAX_ENTRIES: usize = 500_000;
|
||||
const IMAGE_REWRITE_MAX_CONTAINER_ENTRIES: usize = 100_000;
|
||||
const IMAGE_REWRITE_MAX_KEY_BYTES: usize = 16 * 1024 * 1024;
|
||||
const IMAGE_REWRITE_MAX_STAGED_OBJECTS: usize = IMAGE_CENSUS_MAX_ALIASES;
|
||||
|
||||
/// Separate budget for the conservative cleanup rewrite walk. It counts every array item and
|
||||
/// dictionary entry inspected, including primitive values, without recursively visiting scalar
|
||||
/// leaves. This work is distinct from the executable-content census budget above.
|
||||
#[derive(Default)]
|
||||
struct ImageRewriteBudget {
|
||||
entries: usize,
|
||||
key_bytes: usize,
|
||||
}
|
||||
|
||||
impl ImageRewriteBudget {
|
||||
fn charge_entries(&mut self, count: usize) -> Result<(), ()> {
|
||||
if count > IMAGE_REWRITE_MAX_CONTAINER_ENTRIES {
|
||||
return Err(());
|
||||
}
|
||||
self.entries = self.entries.saturating_add(count);
|
||||
if self.entries > IMAGE_REWRITE_MAX_ENTRIES { Err(()) } else { Ok(()) }
|
||||
}
|
||||
|
||||
fn charge_dict(&mut self, dict: &Dict) -> Result<(), ()> {
|
||||
self.charge_entries(dict.len())
|
||||
}
|
||||
|
||||
fn charge_key_bytes(&mut self, count: usize) -> Result<(), ()> {
|
||||
self.key_bytes = self.key_bytes.saturating_add(count);
|
||||
if self.key_bytes > IMAGE_REWRITE_MAX_KEY_BYTES { Err(()) } else { Ok(()) }
|
||||
}
|
||||
}
|
||||
|
||||
/// A full-document, bounded census of executable resource consumers. `incomplete` means a
|
||||
/// conservative cleanup cannot prove that an image is unused, so callers must leave its bytes.
|
||||
struct ImageUseCensus<'a> {
|
||||
doc: &'a Document,
|
||||
target: ObjRef,
|
||||
used: bool,
|
||||
incomplete: bool,
|
||||
bytes: usize,
|
||||
operators: usize,
|
||||
visits: usize,
|
||||
}
|
||||
|
||||
impl ImageUseCensus<'_> {
|
||||
fn charge_visit(&mut self) -> bool {
|
||||
self.visits = self.visits.saturating_add(1);
|
||||
if self.visits > IMAGE_CENSUS_MAX_VISITS {
|
||||
self.incomplete = true;
|
||||
false
|
||||
} else {
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
fn charge_stream(&mut self, stream: &pdfcraft_cos::Stream) -> Option<Vec<u8>> {
|
||||
if !self.charge_visit() {
|
||||
return None;
|
||||
}
|
||||
// A tolerated prefix cannot prove nonuse. Bound allocation by the document's remaining
|
||||
// census allowance, and reject corrupt filters before any destructive cleanup is staged.
|
||||
let remaining = IMAGE_CENSUS_MAX_BYTES.saturating_sub(self.bytes);
|
||||
let data = match self.doc.with_direct_parms(stream).decoded_strict_within(remaining) {
|
||||
Ok(data) => data,
|
||||
Err(_) => {
|
||||
self.incomplete = true;
|
||||
return None;
|
||||
}
|
||||
};
|
||||
self.bytes = self.bytes.saturating_add(data.len());
|
||||
if self.bytes > IMAGE_CENSUS_MAX_BYTES {
|
||||
self.incomplete = true;
|
||||
return None;
|
||||
}
|
||||
Some(data)
|
||||
}
|
||||
|
||||
fn walk_stream(&mut self, object: &Object, inherited: &Dict, depth: usize, path: &mut std::collections::HashSet<ObjRef>) {
|
||||
if self.used || self.incomplete {
|
||||
return;
|
||||
}
|
||||
if !self.charge_visit() {
|
||||
return;
|
||||
}
|
||||
if depth > IMAGE_CENSUS_MAX_DEPTH {
|
||||
self.incomplete = true;
|
||||
return;
|
||||
}
|
||||
let reference = object.as_ref();
|
||||
if reference == Some(self.target) {
|
||||
self.used = true;
|
||||
return;
|
||||
}
|
||||
if let Some(reference) = reference
|
||||
&& !path.insert(reference)
|
||||
{
|
||||
// A cycle could be rendered differently under an inherited resource scope.
|
||||
self.incomplete = true;
|
||||
return;
|
||||
}
|
||||
let resolved = self.doc.resolve(object);
|
||||
let Object::Stream(stream) = &*resolved else {
|
||||
self.incomplete = true;
|
||||
return;
|
||||
};
|
||||
|
||||
// Image masks and alternates are serialized image consumers even though they are not
|
||||
// reached by a `Do` of their own.
|
||||
if stream.dict.name(b"Subtype") == Some(b"Image") {
|
||||
for key in [b"SMask".as_slice(), b"Mask".as_slice()] {
|
||||
let Some(dependency) = stream.dict.get(key) else { continue };
|
||||
if dependency.as_ref() == Some(self.target) {
|
||||
self.used = true;
|
||||
return;
|
||||
}
|
||||
match dependency {
|
||||
Object::Ref(_) => self.walk_stream(dependency, inherited, depth + 1, path),
|
||||
Object::Null => {}
|
||||
Object::Name(name) if key == b"SMask" && name == b"None" => {}
|
||||
Object::Array(values) if key == b"Mask" && values.iter().all(|value| value.as_ref().is_none()) => {}
|
||||
_ => self.incomplete = true,
|
||||
}
|
||||
if self.incomplete || self.used {
|
||||
return;
|
||||
}
|
||||
}
|
||||
if let Some(alternates) = stream.dict.get(b"Alternates").map(|o| self.doc.resolve(o)) {
|
||||
let Some(items) = alternates.as_array() else {
|
||||
self.incomplete = true;
|
||||
return;
|
||||
};
|
||||
for item in items {
|
||||
let item = self.doc.resolve(item);
|
||||
let Some(image) = item.as_dict().and_then(|d| d.get(b"Image")) else {
|
||||
self.incomplete = true;
|
||||
return;
|
||||
};
|
||||
if image.as_ref() == Some(self.target) {
|
||||
self.used = true;
|
||||
return;
|
||||
}
|
||||
self.walk_stream(image, inherited, depth + 1, path);
|
||||
if self.incomplete || self.used {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(reference) = reference {
|
||||
path.remove(&reference);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
let subtype = stream.dict.name(b"Subtype");
|
||||
let pattern = stream.dict.get(b"PatternType").map(|o| self.doc.resolve(o)).as_deref().and_then(Object::as_int) == Some(1);
|
||||
if subtype != Some(b"Form") && !pattern {
|
||||
self.incomplete = true;
|
||||
if let Some(reference) = reference {
|
||||
path.remove(&reference);
|
||||
}
|
||||
return;
|
||||
}
|
||||
let resources =
|
||||
stream.dict.get(b"Resources").map(|r| self.doc.resolve(r)).and_then(|r| r.as_dict().cloned()).unwrap_or_else(|| inherited.clone());
|
||||
let Some(data) = self.charge_stream(stream) else {
|
||||
if let Some(reference) = reference {
|
||||
path.remove(&reference);
|
||||
}
|
||||
return;
|
||||
};
|
||||
self.walk_content(&data, &resources, depth + 1, path);
|
||||
if let Some(reference) = reference {
|
||||
path.remove(&reference);
|
||||
}
|
||||
}
|
||||
|
||||
fn walk_type3(&mut self, font: &Object, _inherited: &Dict, depth: usize, path: &mut std::collections::HashSet<ObjRef>) {
|
||||
if !self.charge_visit() {
|
||||
return;
|
||||
}
|
||||
let resolved = self.doc.resolve(font);
|
||||
let Some(dict) = resolved.as_dict() else {
|
||||
self.incomplete = true;
|
||||
return;
|
||||
};
|
||||
if dict.get(b"Subtype").map(|o| self.doc.resolve(o)).as_deref().and_then(Object::as_name) != Some(b"Type3") {
|
||||
return;
|
||||
}
|
||||
let Some(resources) = dict.get(b"Resources").map(|o| self.doc.resolve(o)).and_then(|o| o.as_dict().cloned()) else {
|
||||
// The selected font survives Form calls, but its glyphs then resolve names in the
|
||||
// text-showing Form's scope. Without tracking that graphics state, nonuse is unproven.
|
||||
self.incomplete = true;
|
||||
return;
|
||||
};
|
||||
let Some(charprocs) = dict.get(b"CharProcs").map(|o| self.doc.resolve(o)).and_then(|o| o.as_dict().cloned()) else {
|
||||
self.incomplete = true;
|
||||
return;
|
||||
};
|
||||
for (_, charproc) in charprocs.iter() {
|
||||
self.walk_charproc(charproc, &resources, depth + 1, path);
|
||||
if self.used || self.incomplete {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn walk_charproc(&mut self, object: &Object, inherited: &Dict, depth: usize, path: &mut std::collections::HashSet<ObjRef>) {
|
||||
if self.used || self.incomplete {
|
||||
return;
|
||||
}
|
||||
if !self.charge_visit() {
|
||||
return;
|
||||
}
|
||||
if depth > IMAGE_CENSUS_MAX_DEPTH {
|
||||
self.incomplete = true;
|
||||
return;
|
||||
}
|
||||
let reference = object.as_ref();
|
||||
if reference.is_some_and(|r| !path.insert(r)) {
|
||||
self.incomplete = true;
|
||||
return;
|
||||
}
|
||||
let resolved = self.doc.resolve(object);
|
||||
let Object::Stream(stream) = &*resolved else {
|
||||
self.incomplete = true;
|
||||
return;
|
||||
};
|
||||
let resources =
|
||||
stream.dict.get(b"Resources").map(|o| self.doc.resolve(o)).and_then(|o| o.as_dict().cloned()).unwrap_or_else(|| inherited.clone());
|
||||
if let Some(data) = self.charge_stream(stream) {
|
||||
self.walk_content(&data, &resources, depth + 1, path);
|
||||
}
|
||||
if let Some(reference) = reference {
|
||||
path.remove(&reference);
|
||||
}
|
||||
}
|
||||
|
||||
fn walk_resources_for_operator(&mut self, op: &Op, resources: &Dict, depth: usize, path: &mut std::collections::HashSet<ObjRef>) {
|
||||
if op.is("Tf") {
|
||||
let Some(name) = op.name(0) else {
|
||||
self.incomplete = true;
|
||||
return;
|
||||
};
|
||||
if let Some(fonts) = resources.get(b"Font").map(|o| self.doc.resolve(o)).and_then(|o| o.as_dict().cloned())
|
||||
&& let Some(font) = fonts.get(name)
|
||||
{
|
||||
self.walk_type3(font, resources, depth + 1, path);
|
||||
}
|
||||
} else if op.is("gs") {
|
||||
let Some(name) = op.name(0) else {
|
||||
self.incomplete = true;
|
||||
return;
|
||||
};
|
||||
let states = resources.get(b"ExtGState").map(|o| self.doc.resolve(o)).and_then(|o| o.as_dict().cloned());
|
||||
let Some(state) = states.as_ref().and_then(|d| d.get(name)).map(|o| self.doc.resolve(o)) else {
|
||||
self.incomplete = true;
|
||||
return;
|
||||
};
|
||||
let Some(state_dict) = state.as_dict() else {
|
||||
self.incomplete = true;
|
||||
return;
|
||||
};
|
||||
if let Some(font_value) = state_dict.get(b"Font") {
|
||||
let font = self.doc.resolve(font_value);
|
||||
let Some(values) = font.as_array() else {
|
||||
self.incomplete = true;
|
||||
return;
|
||||
};
|
||||
if values.len() != 2 {
|
||||
self.incomplete = true;
|
||||
return;
|
||||
}
|
||||
self.walk_type3(&values[0], resources, depth + 1, path);
|
||||
if self.incomplete || self.used {
|
||||
return;
|
||||
}
|
||||
}
|
||||
let Some(mask_value) = state_dict.get(b"SMask") else { return };
|
||||
let mask = self.doc.resolve(mask_value);
|
||||
match &*mask {
|
||||
Object::Name(name) if name == b"None" => {}
|
||||
Object::Dict(mask_dict) => {
|
||||
let Some(group) = mask_dict.get(b"G") else {
|
||||
self.incomplete = true;
|
||||
return;
|
||||
};
|
||||
let resolved_group = self.doc.resolve(group);
|
||||
if !matches!(&*resolved_group, Object::Stream(stream) if stream.dict.name(b"Subtype") == Some(b"Form")) {
|
||||
self.incomplete = true;
|
||||
return;
|
||||
}
|
||||
self.walk_stream(group, resources, depth + 1, path);
|
||||
}
|
||||
_ => self.incomplete = true,
|
||||
}
|
||||
} else if op.is("scn") || op.is("SCN") {
|
||||
let Some(name) = op.operands.last().and_then(Object::as_name) else { return };
|
||||
let patterns = resources.get(b"Pattern").map(|o| self.doc.resolve(o)).and_then(|o| o.as_dict().cloned());
|
||||
if let Some(pattern) = patterns.as_ref().and_then(|d| d.get(name)) {
|
||||
let resolved = self.doc.resolve(pattern);
|
||||
if let Some(dict) = resolved.as_dict() {
|
||||
let kind = dict.get(b"PatternType").map(|o| self.doc.resolve(o));
|
||||
match kind.as_deref().and_then(Object::as_int) {
|
||||
Some(1) => self.walk_stream(pattern, resources, depth + 1, path),
|
||||
Some(2) if !dict.contains(b"ExtGState") => {}
|
||||
// A shading pattern's state can select a soft-mask Form. Unknown types
|
||||
// are consumers too: neither case proves image nonuse.
|
||||
_ => self.incomplete = true,
|
||||
}
|
||||
} else {
|
||||
self.incomplete = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn walk_content(&mut self, data: &[u8], resources: &Dict, depth: usize, path: &mut std::collections::HashSet<ObjRef>) {
|
||||
self.walk_parsed(parse(data), resources, depth, path);
|
||||
}
|
||||
|
||||
fn walk_parsed(&mut self, parsed: pdfcraft_content::Parsed, resources: &Dict, depth: usize, path: &mut std::collections::HashSet<ObjRef>) {
|
||||
if self.used || self.incomplete {
|
||||
return;
|
||||
}
|
||||
if depth > IMAGE_CENSUS_MAX_DEPTH {
|
||||
self.incomplete = true;
|
||||
return;
|
||||
}
|
||||
self.operators = self.operators.saturating_add(parsed.ops.len());
|
||||
if parsed.skipped != 0 || self.operators > IMAGE_CENSUS_MAX_OPERATORS {
|
||||
self.incomplete = true;
|
||||
return;
|
||||
}
|
||||
for op in &parsed.ops {
|
||||
self.walk_resources_for_operator(op, resources, depth, path);
|
||||
if self.incomplete || self.used {
|
||||
return;
|
||||
}
|
||||
if !op.is("Do") {
|
||||
continue;
|
||||
}
|
||||
let Some(name) = op.name(0) else {
|
||||
self.incomplete = true;
|
||||
return;
|
||||
};
|
||||
let Some(xobjects) = resources.get(b"XObject").map(|o| self.doc.resolve(o)).and_then(|o| o.as_dict().cloned()) else {
|
||||
self.incomplete = true;
|
||||
return;
|
||||
};
|
||||
let Some(xobject) = xobjects.get(name) else {
|
||||
self.incomplete = true;
|
||||
return;
|
||||
};
|
||||
if xobject.as_ref() == Some(self.target) {
|
||||
self.used = true;
|
||||
return;
|
||||
}
|
||||
self.walk_stream(xobject, resources, depth + 1, path);
|
||||
if self.incomplete || self.used {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn walk_annotation(&mut self, annotation: &Dict, resources: &Dict, path: &mut std::collections::HashSet<ObjRef>) {
|
||||
if let Some(ap) = annotation.get(b"AP") {
|
||||
self.walk_appearances(ap, resources, 0, path);
|
||||
}
|
||||
if let Some(mk) = annotation.get(b"MK").map(|o| self.doc.resolve(o)) {
|
||||
if let Some(characteristics) = mk.as_dict() {
|
||||
// Button icons are Form consumers independently of the /AP states.
|
||||
for key in [b"I".as_slice(), b"RI", b"IX"] {
|
||||
if let Some(icon) = characteristics.get(key) {
|
||||
self.walk_stream(icon, resources, 0, path);
|
||||
}
|
||||
}
|
||||
} else if !matches!(&*mk, Object::Null) {
|
||||
self.incomplete = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn walk_appearances(&mut self, object: &Object, resources: &Dict, depth: usize, path: &mut std::collections::HashSet<ObjRef>) {
|
||||
if self.used || self.incomplete {
|
||||
return;
|
||||
}
|
||||
if !self.charge_visit() {
|
||||
return;
|
||||
}
|
||||
if depth > IMAGE_CENSUS_MAX_DEPTH {
|
||||
self.incomplete = true;
|
||||
return;
|
||||
}
|
||||
let reference = object.as_ref();
|
||||
match &*self.doc.resolve(object) {
|
||||
Object::Stream(_) => self.walk_stream(object, resources, depth + 1, path),
|
||||
Object::Dict(dict) => {
|
||||
if let Some(reference) = reference
|
||||
&& !path.insert(reference)
|
||||
{
|
||||
self.incomplete = true;
|
||||
return;
|
||||
}
|
||||
if dict.contains(b"Resources") {
|
||||
self.incomplete = true;
|
||||
return;
|
||||
}
|
||||
for (_, value) in dict.iter() {
|
||||
self.walk_appearances(value, resources, depth + 1, path);
|
||||
if self.incomplete || self.used {
|
||||
return;
|
||||
}
|
||||
}
|
||||
if let Some(reference) = reference {
|
||||
path.remove(&reference);
|
||||
}
|
||||
}
|
||||
Object::Array(values) => {
|
||||
if let Some(reference) = reference
|
||||
&& !path.insert(reference)
|
||||
{
|
||||
self.incomplete = true;
|
||||
return;
|
||||
}
|
||||
for value in values {
|
||||
self.walk_appearances(value, resources, depth + 1, path);
|
||||
if self.incomplete || self.used {
|
||||
return;
|
||||
}
|
||||
}
|
||||
if let Some(reference) = reference {
|
||||
path.remove(&reference);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Remove a deleted/replaced image from every resource dictionary only after a bounded census
|
||||
/// proves no page, Form, Type3 glyph, soft mask, tiling pattern, or annotation appearance uses it.
|
||||
/// Any unsupported or malformed consumer preserves the image and still lets the edit succeed.
|
||||
fn prune_unused_image(doc: &mut Document, target: ObjRef) {
|
||||
let object_count = doc.scan_objects_checked().take(IMAGE_CENSUS_MAX_OBJECTS + 1).count();
|
||||
if object_count > IMAGE_CENSUS_MAX_OBJECTS {
|
||||
return;
|
||||
}
|
||||
let mut census = ImageUseCensus { doc, target, used: false, incomplete: false, bytes: 0, operators: 0, visits: 0 };
|
||||
let mut path = std::collections::HashSet::new();
|
||||
let pages = pdfcraft_model::pages(doc);
|
||||
if pages.len() > IMAGE_CENSUS_MAX_OBJECTS {
|
||||
return;
|
||||
}
|
||||
for page in &pages {
|
||||
let resources = match page.dict.get(b"Resources") {
|
||||
None => Dict::new(),
|
||||
Some(value) => {
|
||||
let resolved = doc.resolve(value);
|
||||
let Some(resources) = resolved.as_dict().cloned() else {
|
||||
census.incomplete = true;
|
||||
break;
|
||||
};
|
||||
resources
|
||||
}
|
||||
};
|
||||
let contents_object = page.dict.get(b"Contents").map(|value| doc.resolve(value));
|
||||
let contents: &[Object] = match contents_object.as_deref() {
|
||||
None => &[],
|
||||
Some(Object::Array(items)) => items,
|
||||
Some(value) => std::slice::from_ref(value),
|
||||
};
|
||||
if contents.len() > IMAGE_CENSUS_MAX_VISITS {
|
||||
census.incomplete = true;
|
||||
break;
|
||||
}
|
||||
let mut content_data = Vec::with_capacity(contents.len());
|
||||
for content in contents {
|
||||
let resolved = doc.resolve(content);
|
||||
let Object::Stream(stream) = &*resolved else {
|
||||
census.incomplete = true;
|
||||
break;
|
||||
};
|
||||
if let Some(data) = census.charge_stream(stream) {
|
||||
content_data.push(data);
|
||||
}
|
||||
if census.incomplete {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if !census.incomplete {
|
||||
census.walk_parsed(Pieces::join(&content_data).parse(), &resources, 0, &mut path);
|
||||
}
|
||||
let annots = page.dict.get(b"Annots").map(|o| doc.resolve(o));
|
||||
if let Some(annots) = annots {
|
||||
let Some(items) = annots.as_array() else {
|
||||
census.incomplete = true;
|
||||
break;
|
||||
};
|
||||
if items.len() > IMAGE_CENSUS_MAX_OBJECTS {
|
||||
census.incomplete = true;
|
||||
break;
|
||||
}
|
||||
for item in items {
|
||||
if !census.charge_visit() {
|
||||
break;
|
||||
}
|
||||
let resolved = doc.resolve(item);
|
||||
let Some(annotation) = resolved.as_dict() else { continue };
|
||||
census.walk_annotation(annotation, &resources, &mut path);
|
||||
if census.incomplete || census.used {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if census.incomplete || census.used {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if census.used || census.incomplete {
|
||||
return;
|
||||
}
|
||||
|
||||
// Unknown stream types carrying their own resource namespace could also consume XObjects.
|
||||
let checked: Vec<_> = doc.scan_objects_checked().collect();
|
||||
if checked.len() > IMAGE_CENSUS_MAX_OBJECTS || checked.iter().any(|(_, item)| item.is_err()) {
|
||||
return;
|
||||
}
|
||||
if checked.iter().any(|(_, item)| {
|
||||
item.as_ref().ok().is_some_and(|o| matches!(o.as_ref(), Object::Stream(s) if s.dict.contains(b"Resources") && s.dict.name(b"Subtype") != Some(b"Form") && s.dict.int(b"PatternType") != Some(1)))
|
||||
}) {
|
||||
return;
|
||||
}
|
||||
|
||||
let mut staged = std::collections::HashMap::new();
|
||||
let mut indirect_xobject_dicts = std::collections::HashSet::new();
|
||||
let mut indirect_alternate_arrays = std::collections::HashSet::new();
|
||||
let mut aliases = 0usize;
|
||||
let mut rewrite_budget = ImageRewriteBudget::default();
|
||||
for (reference, item) in checked {
|
||||
let Ok(object) = item else { return };
|
||||
let mut object = (*object).clone();
|
||||
let mappings_changed = match prune_xobject_mappings(&mut object, target, &mut indirect_xobject_dicts, &mut aliases, 0, &mut rewrite_budget) {
|
||||
Ok(changed) => changed,
|
||||
Err(()) => return,
|
||||
};
|
||||
let dependencies_changed =
|
||||
match prune_image_dependencies(&mut object, doc, target, &mut indirect_alternate_arrays, &mut aliases, 0, &mut rewrite_budget) {
|
||||
Ok(changed) => changed,
|
||||
Err(()) => return,
|
||||
};
|
||||
if mappings_changed || dependencies_changed {
|
||||
if aliases > IMAGE_CENSUS_MAX_ALIASES || staged.len() >= IMAGE_REWRITE_MAX_STAGED_OBJECTS {
|
||||
return;
|
||||
}
|
||||
staged.insert(reference, object);
|
||||
}
|
||||
}
|
||||
for reference in indirect_xobject_dicts {
|
||||
let was_staged = staged.contains_key(&reference);
|
||||
let mut object = staged.remove(&reference).unwrap_or_else(|| (*doc.get(reference)).clone());
|
||||
let changed = match remove_target_aliases(object.as_dict_mut(), target, &mut aliases, &mut rewrite_budget) {
|
||||
Ok(changed) => changed,
|
||||
Err(()) => return,
|
||||
};
|
||||
if changed || was_staged {
|
||||
if aliases > IMAGE_CENSUS_MAX_ALIASES || (!was_staged && staged.len() >= IMAGE_REWRITE_MAX_STAGED_OBJECTS) {
|
||||
return;
|
||||
}
|
||||
staged.insert(reference, object);
|
||||
}
|
||||
}
|
||||
for reference in indirect_alternate_arrays {
|
||||
let was_staged = staged.contains_key(&reference);
|
||||
let mut object = staged.remove(&reference).unwrap_or_else(|| (*doc.get(reference)).clone());
|
||||
let changed = match remove_target_alternate_entries(&mut object, doc, target, &mut aliases, &mut rewrite_budget) {
|
||||
Ok(changed) => changed,
|
||||
Err(()) => return,
|
||||
};
|
||||
if changed {
|
||||
if aliases > IMAGE_CENSUS_MAX_ALIASES || (!was_staged && staged.len() >= IMAGE_REWRITE_MAX_STAGED_OBJECTS) {
|
||||
return;
|
||||
}
|
||||
staged.insert(reference, object);
|
||||
} else if !matches!(&object, Object::Array(_)) {
|
||||
// An indirect `/Alternates` value that is not an array is malformed. Since the
|
||||
// census cannot establish whether it retains the target, preserve the whole edit.
|
||||
return;
|
||||
} else if was_staged {
|
||||
staged.insert(reference, object);
|
||||
}
|
||||
}
|
||||
for (reference, object) in staged {
|
||||
doc.set(reference, object);
|
||||
}
|
||||
}
|
||||
|
||||
fn remove_target_aliases(dict: Option<&mut Dict>, target: ObjRef, aliases: &mut usize, budget: &mut ImageRewriteBudget) -> Result<bool, ()> {
|
||||
let Some(dict) = dict else { return Ok(false) };
|
||||
budget.charge_dict(dict)?;
|
||||
let mut names = Vec::new();
|
||||
for (name, value) in dict.iter() {
|
||||
budget.charge_key_bytes(name.len())?;
|
||||
if value.as_ref() == Some(target) {
|
||||
if aliases.saturating_add(names.len()) >= IMAGE_CENSUS_MAX_ALIASES {
|
||||
return Err(());
|
||||
}
|
||||
names.push(name.clone());
|
||||
}
|
||||
}
|
||||
for name in &names {
|
||||
dict.remove(name);
|
||||
}
|
||||
*aliases = aliases.saturating_add(names.len());
|
||||
Ok(!names.is_empty())
|
||||
}
|
||||
|
||||
fn prune_xobject_mappings(
|
||||
object: &mut Object,
|
||||
target: ObjRef,
|
||||
indirect: &mut std::collections::HashSet<ObjRef>,
|
||||
aliases: &mut usize,
|
||||
depth: usize,
|
||||
budget: &mut ImageRewriteBudget,
|
||||
) -> Result<bool, ()> {
|
||||
if depth > IMAGE_CENSUS_MAX_DEPTH {
|
||||
return Err(());
|
||||
}
|
||||
let mut changed = false;
|
||||
match object {
|
||||
Object::Array(values) => {
|
||||
budget.charge_entries(values.len())?;
|
||||
for value in values.iter_mut().filter(|value| is_container(value)) {
|
||||
changed |= prune_xobject_mappings(value, target, indirect, aliases, depth + 1, budget)?;
|
||||
}
|
||||
}
|
||||
Object::Dict(dict) | Object::Stream(pdfcraft_cos::Stream { dict, .. }) => {
|
||||
if let Some(xobjects) = dict.get_mut(b"XObject") {
|
||||
match xobjects {
|
||||
Object::Ref(reference) => {
|
||||
indirect.insert(*reference);
|
||||
}
|
||||
Object::Dict(mappings) => changed |= remove_target_aliases(Some(mappings), target, aliases, budget)?,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let mut keys = Vec::new();
|
||||
budget.charge_dict(dict)?;
|
||||
for (key, value) in dict.iter() {
|
||||
budget.charge_key_bytes(key.len())?;
|
||||
if is_container(value) {
|
||||
keys.push(key.clone());
|
||||
}
|
||||
}
|
||||
for key in keys {
|
||||
if let Some(value) = dict.get_mut(&key) {
|
||||
changed |= prune_xobject_mappings(value, target, indirect, aliases, depth + 1, budget)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
Ok(changed)
|
||||
}
|
||||
|
||||
fn contains_target_ref(object: &Object, target: ObjRef, depth: usize, budget: &mut ImageRewriteBudget) -> Result<bool, ()> {
|
||||
if depth > IMAGE_CENSUS_MAX_DEPTH {
|
||||
return Err(());
|
||||
}
|
||||
match object {
|
||||
Object::Ref(reference) => Ok(*reference == target),
|
||||
Object::Array(values) => {
|
||||
budget.charge_entries(values.len())?;
|
||||
for value in values.iter().filter(|value| matches!(value, Object::Array(_))) {
|
||||
if contains_target_ref(value, target, depth + 1, budget)? {
|
||||
return Ok(true);
|
||||
}
|
||||
}
|
||||
Ok(false)
|
||||
}
|
||||
_ => Ok(false),
|
||||
}
|
||||
}
|
||||
|
||||
fn alternate_uses_target(object: &Object, doc: &Document, target: ObjRef) -> bool {
|
||||
doc.resolve(object).as_dict().and_then(|dict| dict.get(b"Image")).is_some_and(|image| image.as_ref() == Some(target))
|
||||
}
|
||||
|
||||
fn remove_target_alternate_entries(
|
||||
object: &mut Object,
|
||||
doc: &Document,
|
||||
target: ObjRef,
|
||||
aliases: &mut usize,
|
||||
budget: &mut ImageRewriteBudget,
|
||||
) -> Result<bool, ()> {
|
||||
let Object::Array(entries) = object else { return Ok(false) };
|
||||
budget.charge_entries(entries.len())?;
|
||||
let mut retained = Vec::new();
|
||||
let mut removed = 0;
|
||||
for entry in entries.iter() {
|
||||
if alternate_uses_target(entry, doc, target) {
|
||||
if aliases.saturating_add(removed) >= IMAGE_CENSUS_MAX_ALIASES {
|
||||
return Err(());
|
||||
}
|
||||
removed += 1;
|
||||
} else {
|
||||
retained.push(entry.clone());
|
||||
}
|
||||
}
|
||||
if removed != 0 {
|
||||
*entries = retained;
|
||||
*aliases = aliases.saturating_add(removed);
|
||||
}
|
||||
Ok(removed != 0)
|
||||
}
|
||||
|
||||
/// Remove dependencies on an image only after the document census proves no active consumer
|
||||
/// uses it. The dependent image is left in place, but its stale optional mask/alternate edge is
|
||||
/// removed so full-save garbage collection can release the target bytes.
|
||||
fn prune_image_dependencies(
|
||||
object: &mut Object,
|
||||
doc: &Document,
|
||||
target: ObjRef,
|
||||
indirect_alternate_arrays: &mut std::collections::HashSet<ObjRef>,
|
||||
aliases: &mut usize,
|
||||
depth: usize,
|
||||
budget: &mut ImageRewriteBudget,
|
||||
) -> Result<bool, ()> {
|
||||
if depth > IMAGE_CENSUS_MAX_DEPTH {
|
||||
return Err(());
|
||||
}
|
||||
let mut changed = false;
|
||||
match object {
|
||||
Object::Array(values) => {
|
||||
budget.charge_entries(values.len())?;
|
||||
for value in values.iter_mut().filter(|value| is_container(value)) {
|
||||
changed |= prune_image_dependencies(value, doc, target, indirect_alternate_arrays, aliases, depth + 1, budget)?;
|
||||
}
|
||||
}
|
||||
Object::Dict(dict) | Object::Stream(pdfcraft_cos::Stream { dict, .. }) => {
|
||||
if dict.name(b"Subtype") == Some(b"Image") {
|
||||
for key in [b"SMask".as_slice(), b"Mask".as_slice()] {
|
||||
let contains_target =
|
||||
if let Some(value) = dict.get(key) { contains_target_ref(value, target, depth + 1, budget)? } else { false };
|
||||
if contains_target {
|
||||
if aliases.saturating_add(1) > IMAGE_CENSUS_MAX_ALIASES {
|
||||
return Err(());
|
||||
}
|
||||
dict.remove(key);
|
||||
*aliases = aliases.saturating_add(1);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
match dict.get(b"Alternates") {
|
||||
Some(Object::Array(_)) => {
|
||||
let Some(Object::Array(entries)) = dict.get_mut(b"Alternates") else { return Err(()) };
|
||||
budget.charge_entries(entries.len())?;
|
||||
let mut retained = Vec::new();
|
||||
let mut removed = 0;
|
||||
for entry in entries.iter() {
|
||||
if alternate_uses_target(entry, doc, target) {
|
||||
if aliases.saturating_add(removed) >= IMAGE_CENSUS_MAX_ALIASES {
|
||||
return Err(());
|
||||
}
|
||||
removed += 1;
|
||||
} else {
|
||||
retained.push(entry.clone());
|
||||
}
|
||||
}
|
||||
if removed != 0 {
|
||||
*entries = retained;
|
||||
*aliases = aliases.saturating_add(removed);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
Some(Object::Ref(reference)) => {
|
||||
indirect_alternate_arrays.insert(*reference);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let mut keys = Vec::new();
|
||||
budget.charge_dict(dict)?;
|
||||
for (key, value) in dict.iter() {
|
||||
budget.charge_key_bytes(key.len())?;
|
||||
if is_container(value) {
|
||||
keys.push(key.clone());
|
||||
}
|
||||
}
|
||||
for key in keys {
|
||||
if let Some(value) = dict.get_mut(&key) {
|
||||
changed |= prune_image_dependencies(value, doc, target, indirect_alternate_arrays, aliases, depth + 1, budget)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
Ok(changed)
|
||||
}
|
||||
|
||||
fn is_container(object: &Object) -> bool {
|
||||
matches!(object, Object::Array(_) | Object::Dict(_) | Object::Stream(_))
|
||||
}
|
||||
|
||||
fn intersection(a: [f64; 4], b: [f64; 4]) -> Option<[f64; 4]> {
|
||||
let r = [a[0].max(b[0]), a[1].max(b[1]), a[2].min(b[2]), a[3].min(b[3])];
|
||||
(r.iter().all(|v| v.is_finite()) && r[2] > r[0] && r[3] > r[1]).then_some(r)
|
||||
@@ -1012,19 +1822,24 @@ pub(crate) fn extract_scope_state(ops: &[Op], start: usize, target: usize, initi
|
||||
}
|
||||
|
||||
/// The unit `order` puts the image's unit `target_idx` next to, and whether after it. An image that
|
||||
/// shares its unit with other paint at the limit moves within that unit, past or behind the paint.
|
||||
/// shares its unit with other paint at the limit moves within that unit, past or behind the paint,
|
||||
/// but only when that paint is on the side the move crosses: paint after it for a forward move,
|
||||
/// paint before it for a backward move. Otherwise the move would leave paint order unchanged and
|
||||
/// is refused, including when that is the only unit.
|
||||
fn target_destination_unit<'a>(
|
||||
units: &'a [std::ops::Range<usize>],
|
||||
target_idx: usize,
|
||||
target_unit: &'a std::ops::Range<usize>,
|
||||
order: ArrangeOrder,
|
||||
has_other_paint: bool,
|
||||
has_paint_before: bool,
|
||||
has_paint_after: bool,
|
||||
) -> Result<(&'a std::ops::Range<usize>, bool), EditError> {
|
||||
let forward = matches!(order, ArrangeOrder::BringToFront | ArrangeOrder::BringForward);
|
||||
let refused = || EditError::Invalid(if forward { "the image is already in front" } else { "the image is already at the back" }.into());
|
||||
let at_limit = if forward { target_idx.saturating_add(1) >= units.len() } else { target_idx == 0 };
|
||||
if at_limit {
|
||||
return if has_other_paint { Ok((target_unit, forward)) } else { Err(refused()) };
|
||||
let effective_in_unit = if forward { has_paint_after } else { has_paint_before };
|
||||
return if effective_in_unit { Ok((target_unit, forward)) } else { Err(refused()) };
|
||||
}
|
||||
let dest = match order {
|
||||
ArrangeOrder::BringToFront => units.last(),
|
||||
@@ -1204,6 +2019,34 @@ fn build_relocated_unit_ops(
|
||||
Ok(unit_ops)
|
||||
}
|
||||
|
||||
/// Paint inside `target_unit` other than the image at `target`, as `(any, before, after)`: whether
|
||||
/// there is any, and whether some of it comes before the image or after it.
|
||||
fn arrange_paint_flags(ops: &[Op], target: usize, target_unit: &std::ops::Range<usize>) -> (bool, bool, bool) {
|
||||
let mut has_other_paint = false;
|
||||
let mut has_paint_before = false;
|
||||
let mut has_paint_after = false;
|
||||
// A Form XObject counts as paint whatever the text rendering mode: `Tr 3` hides only the
|
||||
// text it shows, and its paths and images still paint.
|
||||
for (i, op) in ops.iter().enumerate() {
|
||||
if i < target_unit.start || i >= target_unit.end || i == target {
|
||||
continue;
|
||||
}
|
||||
let is_paint = matches!(
|
||||
op.op.as_slice(),
|
||||
b"Do" | b"Tj" | b"TJ" | b"'" | b"\"" | b"sh" | b"BI" | b"S" | b"s" | b"f" | b"F" | b"f*" | b"B" | b"B*" | b"b" | b"b*"
|
||||
);
|
||||
if is_paint {
|
||||
has_other_paint = true;
|
||||
if i < target {
|
||||
has_paint_before = true;
|
||||
} else {
|
||||
has_paint_after = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
(has_other_paint, has_paint_before, has_paint_after)
|
||||
}
|
||||
|
||||
/// 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: &[ContentStream], img: &PageImage, order: ArrangeOrder) -> Result<(), EditError> {
|
||||
let pieces = joined(all);
|
||||
@@ -1217,20 +2060,12 @@ fn arrange_image(doc: &mut Document, p: &pdfcraft_model::Page, all: &[ContentStr
|
||||
let Some((target_idx, target_unit)) = units.iter().enumerate().find(|(_, u)| u.contains(&target)) else {
|
||||
return Err(EditError::Invalid("the image content unit could not be located".into()));
|
||||
};
|
||||
let has_other_paint = ops.iter().enumerate().any(|(i, op)| {
|
||||
i >= target_unit.start
|
||||
&& i < target_unit.end
|
||||
&& i != target
|
||||
&& matches!(
|
||||
op.op.as_slice(),
|
||||
b"Do" | b"Tj" | b"TJ" | b"'" | b"\"" | b"sh" | b"BI" | b"S" | b"s" | b"f" | b"F" | b"f*" | b"B" | b"B*" | b"b" | b"b*"
|
||||
)
|
||||
});
|
||||
if units.len() <= 1 && !has_other_paint {
|
||||
return Err(EditError::Invalid("the page has only one content unit to arrange".into()));
|
||||
}
|
||||
// Units are counted inside a page-wide q … Q wrapper, so separate balanced inner units are not
|
||||
// mistaken for one shared unit. A sole shared unit is handled by the directional at-limit check
|
||||
// in `target_destination_unit`: an effective move within it is allowed, an ineffective one is refused.
|
||||
let (has_other_paint, has_paint_before, has_paint_after) = arrange_paint_flags(&ops, target, target_unit);
|
||||
|
||||
let (dest_unit, insert_after) = target_destination_unit(&units, target_idx, target_unit, order, has_other_paint)?;
|
||||
let (dest_unit, insert_after) = target_destination_unit(&units, target_idx, target_unit, order, has_paint_before, has_paint_after)?;
|
||||
if !balanced_arrange_span(&ops, target_unit.clone()) || !balanced_arrange_span(&ops, dest_unit.clone()) {
|
||||
return Err(EditError::Invalid("cannot arrange an image across graphics or marked-content boundaries".into()));
|
||||
}
|
||||
@@ -1633,10 +2468,15 @@ fn remove_image_crop(doc: &mut Document, p: &pdfcraft_model::Page, all: &[Conten
|
||||
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 {
|
||||
// Enumeration can also see a PdfCraft crop marker whose path (`W q Q n`, for example)
|
||||
// scope detection does not treat as a removable crop; say it cannot be removed rather
|
||||
// than that no crop exists.
|
||||
return Err(EditError::Invalid(if !crops(ops.len())?.is_empty() {
|
||||
"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()
|
||||
} else if img.has_editor_crop() {
|
||||
"the image's PdfCraft crop cannot be safely removed from its current scope".into()
|
||||
} else {
|
||||
"the image has no PdfCraft crop to remove".into()
|
||||
}));
|
||||
}
|
||||
let crops = crops_there;
|
||||
@@ -1657,6 +2497,8 @@ pub fn change_image(doc: &mut Document, page: usize, index: usize, change: &Imag
|
||||
if !ops.get(img.op).is_some_and(|op| op.is("Do")) {
|
||||
return Err(EditError::Invalid("the image operation is missing".into()));
|
||||
}
|
||||
let old_object = img.object;
|
||||
let prune_target = matches!(change, ImageChange::Delete | ImageChange::Replace(_)).then_some(old_object).flatten();
|
||||
let mut resources = None;
|
||||
let replacement: Vec<Op> = match change {
|
||||
ImageChange::Delete => Vec::new(),
|
||||
@@ -1715,6 +2557,9 @@ pub fn change_image(doc: &mut Document, page: usize, index: usize, change: &Imag
|
||||
d.set(b"Resources".to_vec(), Object::Dict(res));
|
||||
}
|
||||
})?;
|
||||
if let Some(target) = prune_target {
|
||||
prune_unused_image(doc, target);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -2084,4 +2929,12 @@ mod allocation_tests {
|
||||
tracker.step(&op, &states, &doc, Matrix::translate(50.0, 0.0)).unwrap();
|
||||
assert!(before.visually_differs(&tracker.current_state), "the same mask established under a different CTM is a different effective mask");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn arrange_paint_flags_counts_a_form_drawn_in_invisible_text_mode() {
|
||||
// `Tr 3` hides text, not the paths and images a Form draws.
|
||||
let ops =
|
||||
vec![Op::new("Do", vec![Object::name("Target")]), Op::new("Tr", vec![Object::Real(3.0)]), Op::new("Do", vec![Object::name("Form")])];
|
||||
assert_eq!(arrange_paint_flags(&ops, 0, &(0..ops.len())), (true, false, true));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,347 @@
|
||||
use super::*;
|
||||
|
||||
fn page(content: &str, second_face: &str) -> Document {
|
||||
let mut doc = text_page(content);
|
||||
doc.update_dict(pdfcraft_cos::ObjRef::new(6, 0), |font| {
|
||||
*font = Dict::new();
|
||||
font.set(b"Type".to_vec(), Object::name("Font"));
|
||||
font.set(b"Subtype".to_vec(), Object::name("Type1"));
|
||||
font.set(b"BaseFont".to_vec(), Object::name(second_face));
|
||||
font.set(b"Encoding".to_vec(), Object::name("WinAnsiEncoding"));
|
||||
})
|
||||
.unwrap();
|
||||
doc
|
||||
}
|
||||
|
||||
fn multi_stream_page(contents: &[&str]) -> Document {
|
||||
let mut doc = page("", "Helvetica");
|
||||
let streams =
|
||||
contents.iter().map(|content| Object::Ref(doc.add(Object::Stream(Stream::from_raw(Dict::new(), content.as_bytes().to_vec()))))).collect();
|
||||
set_page_contents(&mut doc, Object::Array(streams), None);
|
||||
doc
|
||||
}
|
||||
|
||||
fn panel_form(doc: &mut Document, content: &str, matrix: [i64; 6]) {
|
||||
let mut dict = Dict::new();
|
||||
dict.set(b"Subtype".to_vec(), Object::name("Form"));
|
||||
dict.set(b"BBox".to_vec(), Object::Array([0, 0, 600, 800].map(Object::Int).to_vec()));
|
||||
dict.set(b"Matrix".to_vec(), Object::Array(matrix.map(Object::Int).to_vec()));
|
||||
let form = doc.add(Object::Stream(Stream::from_raw(dict, content.as_bytes().to_vec())));
|
||||
let page = pdfcraft_model::pages(doc)[0].obj;
|
||||
doc.update_dict(page, |page| {
|
||||
let mut resources = page.get(b"Resources").and_then(Object::as_dict).cloned().unwrap();
|
||||
let mut xobjects = Dict::new();
|
||||
xobjects.set(b"Panel".to_vec(), Object::Ref(form));
|
||||
resources.set(b"XObject".to_vec(), Object::Dict(xobjects));
|
||||
page.set(b"Resources".to_vec(), Object::Dict(resources));
|
||||
})
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn separates_rows_when_background_is_in_a_separate_stream() {
|
||||
let doc = multi_stream_page(&["q 60 690 200 25 re f Q", "BT /F1 12 Tf 72 700 Td (Panel) Tj 0 -18 Td (Outside) Tj ET"]);
|
||||
|
||||
let blocks = text::text_blocks(&doc, 0).unwrap();
|
||||
|
||||
assert_eq!(blocks.iter().map(|b| b.text.as_str()).collect::<Vec<_>>(), ["Panel", "Outside"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn separates_rows_when_distinct_panels_are_in_separate_streams() {
|
||||
let doc =
|
||||
multi_stream_page(&["60 690 200 25 re f BT /F1 12 Tf 72 700 Td (Upper) Tj ET", "60 670 200 20 re f BT /F1 12 Tf 72 682 Td (Lower) Tj ET"]);
|
||||
|
||||
let blocks = text::reading_blocks(&doc, 0).unwrap();
|
||||
|
||||
assert_eq!(blocks.iter().map(|b| b.text.as_str()).collect::<Vec<_>>(), ["Upper", "Lower"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn joins_rows_when_same_panel_spans_separate_streams() {
|
||||
let doc = multi_stream_page(&["60 650 200 65 re f BT /F1 12 Tf 72 700 Td (First) Tj ET", "BT /F1 12 Tf 72 682 Td (Second) Tj ET"]);
|
||||
|
||||
let blocks = text::text_blocks(&doc, 0).unwrap();
|
||||
|
||||
assert_eq!(blocks.iter().map(|b| b.editor_text.as_str()).collect::<Vec<_>>(), ["First\nSecond"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn separates_rows_when_rectangle_and_fill_are_in_separate_streams() {
|
||||
let doc = multi_stream_page(&["q 2 0 0 2 20 10 cm 120 352.5 -100 -12.5 re", "f Q BT /F1 12 Tf 72 700 Td (Panel) Tj 0 -18 Td (Outside) Tj ET"]);
|
||||
|
||||
let blocks = text::text_blocks(&doc, 0).unwrap();
|
||||
|
||||
assert_eq!(blocks.iter().map(|b| b.text.as_str()).collect::<Vec<_>>(), ["Panel", "Outside"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn separates_page_rows_when_transformed_background_is_in_a_form_stream() {
|
||||
let mut doc = multi_stream_page(&["/Panel Do", "BT /F1 12 Tf 72 700 Td (Panel) Tj 0 -18 Td (Outside) Tj ET"]);
|
||||
panel_form(&mut doc, "20 340 100 12.5 re f", [2, 0, 0, 2, 20, 10]);
|
||||
|
||||
let blocks = text::text_blocks(&doc, 0).unwrap();
|
||||
|
||||
assert_eq!(blocks.iter().map(|b| b.text.as_str()).collect::<Vec<_>>(), ["Panel", "Outside"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn separates_rows_when_distinct_panels_are_in_form_streams() {
|
||||
let mut doc = multi_stream_page(&["/Panel Do q 1 0 0 1 0 -18 cm /Panel Do Q"]);
|
||||
panel_form(&mut doc, "60 690 200 17 re f BT /F1 12 Tf 72 700 Td (Row) Tj ET", [1, 0, 0, 1, 0, 0]);
|
||||
|
||||
let blocks = text::reading_blocks(&doc, 0).unwrap();
|
||||
|
||||
assert_eq!(blocks.iter().map(|b| b.text.as_str()).collect::<Vec<_>>(), ["Row", "Row"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn joins_rows_when_page_panel_contains_form_text() {
|
||||
let mut doc = multi_stream_page(&["60 650 200 65 re f BT /F1 12 Tf 72 700 Td (First) Tj ET", "/Panel Do"]);
|
||||
panel_form(&mut doc, "BT /F1 12 Tf 72 682 Td (Second) Tj ET", [1, 0, 0, 1, 0, 0]);
|
||||
|
||||
let blocks = text::reading_blocks(&doc, 0).unwrap();
|
||||
|
||||
assert_eq!(blocks.iter().map(|b| b.editor_text.as_str()).collect::<Vec<_>>(), ["First\nSecond"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn separates_rows_when_size_change_is_large() {
|
||||
let doc = page("BT /F1 24 Tf 72 700 Td (Heading) Tj /F1 10 Tf 0 -24 Td (Body) Tj ET", "Helvetica");
|
||||
|
||||
let blocks = text::text_blocks(&doc, 0).unwrap();
|
||||
|
||||
assert_eq!(blocks.iter().map(|b| b.text.as_str()).collect::<Vec<_>>(), ["Heading", "Body"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn separates_equal_size_rows_when_families_differ() {
|
||||
let doc = page("BT /F1 12 Tf 72 700 Td (Heading) Tj /F2 12 Tf 0 -16 Td (Body) Tj ET", "Courier");
|
||||
|
||||
let blocks = text::text_blocks(&doc, 0).unwrap();
|
||||
|
||||
assert_eq!(blocks.iter().map(|b| b.text.as_str()).collect::<Vec<_>>(), ["Heading", "Body"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn separates_equal_style_rows_when_crossing_a_filled_container() {
|
||||
let doc = page("q 0.9 g 60 690 200 25 re f Q BT /F1 12 Tf 72 700 Td (Panel) Tj 0 -18 Td (Outside) Tj ET", "Helvetica");
|
||||
|
||||
let blocks = text::text_blocks(&doc, 0).unwrap();
|
||||
|
||||
assert_eq!(blocks.iter().map(|b| b.text.as_str()).collect::<Vec<_>>(), ["Panel", "Outside"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn separates_rows_when_containers_are_adjacent() {
|
||||
let doc = page("q 60 690 200 25 re f 60 670 200 20 re f Q BT /F1 12 Tf 72 700 Td (Upper) Tj 0 -18 Td (Lower) Tj ET", "Helvetica");
|
||||
|
||||
let blocks = text::text_blocks(&doc, 0).unwrap();
|
||||
|
||||
assert_eq!(blocks.len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn joins_multiline_when_inside_the_same_filled_container() {
|
||||
let doc = page("q 0.9 g 60 650 200 65 re f Q BT /F1 12 Tf 72 700 Td (First) Tj 0 -18 Td (Second) Tj 0 -18 Td (Third) Tj ET", "Helvetica");
|
||||
|
||||
let blocks = text::text_blocks(&doc, 0).unwrap();
|
||||
|
||||
assert_eq!(blocks.iter().map(|b| b.editor_text.as_str()).collect::<Vec<_>>(), ["First\nSecond\nThird"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn joins_rows_when_a_fill_is_painted_over_one_of_them() {
|
||||
// A box painted after the text covers it (a redaction); it is not a panel behind the text.
|
||||
let doc = page("BT /F1 12 Tf 72 700 Td (First) Tj 0 -18 Td (Second) Tj ET 0 g 70 696 60 20 re f", "Helvetica");
|
||||
|
||||
let blocks = text::text_blocks(&doc, 0).unwrap();
|
||||
|
||||
assert_eq!(blocks.iter().map(|b| b.editor_text.as_str()).collect::<Vec<_>>(), ["First\nSecond"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn joins_rows_when_their_panel_is_repainted_behind_each_row() {
|
||||
let doc = page(
|
||||
"0.9 g 60 650 200 65 re f BT /F1 12 Tf 0 g 72 700 Td (First) Tj ET 0.9 g 60 650 200 65 re f BT /F1 12 Tf 0 g 72 682 Td (Second) Tj ET",
|
||||
"Helvetica",
|
||||
);
|
||||
|
||||
let blocks = text::text_blocks(&doc, 0).unwrap();
|
||||
|
||||
assert_eq!(blocks.iter().map(|b| b.editor_text.as_str()).collect::<Vec<_>>(), ["First\nSecond"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn joins_rows_when_an_edit_wraps_a_fallback_word_onto_its_own_row() {
|
||||
// The bundled Inter face draws the Cyrillic Helvetica lacks; wrapped alone onto a row, the
|
||||
// word is still part of the paragraph that was edited.
|
||||
let mut doc = page(
|
||||
"BT /F1 12 Tf 14.4 TL 72 700 Td (The quick brown fox jumps over the lazy dog) Tj T* (and keeps running through the long field.) Tj ET",
|
||||
"Helvetica",
|
||||
);
|
||||
let edited = "The quick brown fox jumps over the lazy dog \u{049b}\u{0438}\u{0437}\u{0438}\u{043b}\nand keeps running through the long field.";
|
||||
text::rewrite_block(&mut doc, 0, 0, Some(edited), &text::BlockStyle::default()).unwrap();
|
||||
|
||||
let blocks = text::text_blocks(&reopen(&doc), 0).unwrap();
|
||||
|
||||
assert_eq!(blocks.len(), 1, "{:?}", blocks.iter().map(|b| &b.editor_text).collect::<Vec<_>>());
|
||||
assert!(blocks[0].rows.len() > 2, "the word wraps onto a row of its own: {:?}", blocks[0].editor_text);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn joins_plain_multiline_when_no_container_exists() {
|
||||
let doc = page("BT /F1 12 Tf 72 700 Td (First) Tj 0 -18 Td (Second) Tj ET", "Helvetica");
|
||||
|
||||
let blocks = text::text_blocks(&doc, 0).unwrap();
|
||||
|
||||
assert_eq!(blocks.iter().map(|b| b.editor_text.as_str()).collect::<Vec<_>>(), ["First\nSecond"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn joins_inline_styles_when_family_and_size_change() {
|
||||
let doc = page("BT /F1 12 Tf 72 700 Td (Plain ) Tj /F2 20 Tf (mixed) Tj ET", "Courier-Bold");
|
||||
|
||||
let blocks = text::text_blocks(&doc, 0).unwrap();
|
||||
|
||||
assert_eq!(blocks.iter().map(|b| b.editor_text.as_str()).collect::<Vec<_>>(), ["Plain mixed"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn joins_rows_when_subset_and_weight_names_differ() {
|
||||
let mut doc = page("BT /F1 12 Tf 72 700 Td (First) Tj /F2 12 Tf 0 -18 Td (Second) Tj ET", "GHIJKL+Helvetica-Bold");
|
||||
doc.update_dict(pdfcraft_cos::ObjRef::new(5, 0), |font| font.set(b"BaseFont".to_vec(), Object::name("ABCDEF+Helvetica"))).unwrap();
|
||||
|
||||
let blocks = text::text_blocks(&doc, 0).unwrap();
|
||||
|
||||
assert_eq!(blocks.iter().map(|b| b.editor_text.as_str()).collect::<Vec<_>>(), ["First\nSecond"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn joins_rows_when_stacked_weight_suffixes_differ() {
|
||||
for (regular, bold) in [("TimesNewRomanPSMT", "TimesNewRomanPS-BoldMT"), ("MinionPro-Regular", "MinionPro-BoldIt")] {
|
||||
let mut doc = page("BT /F1 12 Tf 72 700 Td (First) Tj /F2 12 Tf 0 -18 Td (Second) Tj ET", bold);
|
||||
doc.update_dict(pdfcraft_cos::ObjRef::new(5, 0), |font| font.set(b"BaseFont".to_vec(), Object::name(regular))).unwrap();
|
||||
|
||||
let blocks = text::text_blocks(&doc, 0).unwrap();
|
||||
|
||||
assert_eq!(blocks.iter().map(|b| b.editor_text.as_str()).collect::<Vec<_>>(), ["First\nSecond"], "{regular} / {bold}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn joins_rows_when_a_highlight_hugs_one_word() {
|
||||
let doc = page("q 1 1 0 rg 98 697 36 12 re f Q BT /F1 12 Tf 72 700 Td (Plain ) Tj (word) Tj ( rest) Tj 0 -18 Td (Second row) Tj ET", "Helvetica");
|
||||
|
||||
let blocks = text::text_blocks(&doc, 0).unwrap();
|
||||
|
||||
assert_eq!(blocks.iter().map(|b| b.editor_text.as_str()).collect::<Vec<_>>(), ["Plain word rest\nSecond row"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn joins_rows_when_a_padded_highlight_surrounds_one_word() {
|
||||
// Highlighters pad the box past the glyphs; it is still a highlight, not a panel.
|
||||
for padded in ["98 695 36 16 re", "98 694 36 18 re", "96 693 40 20 re"] {
|
||||
let doc = page(
|
||||
&format!("q 1 1 0 rg {padded} f Q BT /F1 12 Tf 72 700 Td (Plain ) Tj (word) Tj ( rest) Tj 0 -18 Td (Second row) Tj ET"),
|
||||
"Helvetica",
|
||||
);
|
||||
|
||||
let blocks = text::text_blocks(&doc, 0).unwrap();
|
||||
|
||||
assert_eq!(blocks.iter().map(|b| b.editor_text.as_str()).collect::<Vec<_>>(), ["Plain word rest\nSecond row"], "{padded}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn joins_rows_when_a_padded_highlight_sits_inside_a_one_run_line() {
|
||||
// One `Tj` draws the whole line, so the highlight's word is not a run of its own.
|
||||
let doc = page("q 1 1 0 rg 98 695 36 16 re f Q BT /F1 12 Tf 72 700 Td (Plain word rest) Tj 0 -18 Td (Second row) Tj ET", "Helvetica");
|
||||
|
||||
let blocks = text::text_blocks(&doc, 0).unwrap();
|
||||
|
||||
assert_eq!(blocks.iter().map(|b| b.editor_text.as_str()).collect::<Vec<_>>(), ["Plain word rest\nSecond row"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn joins_rows_when_only_right_edges_align() {
|
||||
let doc = page("BT /F1 12 Tf 72 700 Td (Long first row) Tj ET BT /F1 12 Tf 300 682 Td (Short) Tj ET", "Helvetica");
|
||||
let lines = text::text_lines(&doc, 0).unwrap();
|
||||
let x = lines[0].rect[2] - (lines[1].rect[2] - lines[1].rect[0]);
|
||||
let doc = page(&format!("BT /F1 12 Tf 72 700 Td (Long first row) Tj ET BT /F1 12 Tf {x} 682 Td (Short) Tj ET"), "Helvetica");
|
||||
|
||||
let blocks = text::text_blocks(&doc, 0).unwrap();
|
||||
|
||||
assert_eq!(blocks.iter().map(|b| b.editor_text.as_str()).collect::<Vec<_>>(), ["Long first row\nShort"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keeps_outside_text_when_editing_a_container_paragraph() {
|
||||
let mut doc = page("q 0.9 g 60 690 200 25 re f Q BT /F1 12 Tf 72 700 Td (Panel) Tj 0 -18 Td (Outside) Tj ET", "Helvetica");
|
||||
let outside = text::text_lines(&doc, 0).unwrap()[1].clone();
|
||||
|
||||
text::replace_block(&mut doc, 0, 0, "Edited").unwrap();
|
||||
|
||||
let reopened = reopen(&doc);
|
||||
let lines = text::text_lines(&reopened, 0).unwrap();
|
||||
let kept = lines.iter().find(|line| line.text == "Outside").expect("outside paragraph survives");
|
||||
assert_eq!((kept.rect, kept.size, &kept.base_font), (outside.rect, outside.size, &outside.base_font));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keeps_neighboring_panel_when_editing_an_isolated_panel() {
|
||||
let mut doc =
|
||||
multi_stream_page(&["60 690 200 25 re f BT /F1 12 Tf 72 700 Td (Upper) Tj ET", "60 670 200 20 re f BT /F1 12 Tf 72 682 Td (Lower) Tj ET"]);
|
||||
assert_eq!(text::text_blocks(&doc, 0).unwrap().len(), 2);
|
||||
let neighbor = text::text_lines(&doc, 0).unwrap()[1].clone();
|
||||
|
||||
text::replace_block(&mut doc, 0, 0, "Edited").unwrap();
|
||||
|
||||
let reopened = reopen(&doc);
|
||||
let blocks = text::text_blocks(&reopened, 0).unwrap();
|
||||
assert_eq!(blocks.iter().map(|block| block.text.as_str()).collect::<Vec<_>>(), ["Edited", "Lower"]);
|
||||
let lines = text::text_lines(&reopened, 0).unwrap();
|
||||
let kept = lines.iter().find(|line| line.text == "Lower").expect("neighboring panel survives");
|
||||
assert_eq!(
|
||||
(kept.rect, kept.baseline(), kept.size, &kept.base_font, kept.color),
|
||||
(neighbor.rect, neighbor.baseline(), neighbor.size, &neighbor.base_font, neighbor.color)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn separates_rows_when_container_has_a_transformed_negative_rectangle() {
|
||||
let doc = page("q 2 0 0 2 20 10 cm 120 352.5 -100 -12.5 re B Q BT /F1 12 Tf 72 700 Td (Panel) Tj 0 -18 Td (Outside) Tj ET", "Helvetica");
|
||||
|
||||
let blocks = text::text_blocks(&doc, 0).unwrap();
|
||||
|
||||
assert_eq!(blocks.iter().map(|b| b.text.as_str()).collect::<Vec<_>>(), ["Panel", "Outside"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn joins_rows_when_rectangle_is_only_stroked_or_clipped() {
|
||||
for paint in ["S", "W n", "W* n"] {
|
||||
let doc = page(&format!("q 60 690 200 25 re {paint} Q BT /F1 12 Tf 72 700 Td (First) Tj 0 -18 Td (Second) Tj ET"), "Helvetica");
|
||||
|
||||
let blocks = text::text_blocks(&doc, 0).unwrap();
|
||||
|
||||
assert_eq!(blocks.iter().map(|b| b.editor_text.as_str()).collect::<Vec<_>>(), ["First\nSecond"], "{paint}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn joins_multiline_with_inline_mixed_families() {
|
||||
let doc = page("BT /F1 12 Tf 72 700 Td (Ordinary text ) Tj /F2 12 Tf (code) Tj /F1 12 Tf 0 -18 Td (Following row) Tj ET", "Courier-Bold");
|
||||
|
||||
let blocks = text::text_blocks(&doc, 0).unwrap();
|
||||
|
||||
assert_eq!(blocks.iter().map(|b| b.editor_text.as_str()).collect::<Vec<_>>(), ["Ordinary text code\nFollowing row"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn separates_inline_labels_when_a_container_edge_is_between_them() {
|
||||
let doc = page("q 60 690 50 25 re f Q BT /F1 12 Tf 72 700 Td (Panel) Tj 1 0 0 1 112 700 Tm (Outside) Tj ET", "Helvetica");
|
||||
|
||||
let blocks = text::text_blocks(&doc, 0).unwrap();
|
||||
|
||||
assert_eq!(blocks.iter().map(|b| b.text.as_str()).collect::<Vec<_>>(), ["Panel", "Outside"]);
|
||||
}
|
||||
+1844
-8
File diff suppressed because it is too large
Load Diff
@@ -29,6 +29,11 @@ pub use fallback::strip_subset_tag;
|
||||
use regions::{alignment_frame, existing_gap, group_blocks, is_centred, rewrite_changed_words, rewrite_styled_block, row_sources, source_row_step};
|
||||
pub use session::TextSession;
|
||||
|
||||
#[path = "text_containers.rs"]
|
||||
mod containers;
|
||||
#[path = "text_row_style.rs"]
|
||||
mod row_style;
|
||||
|
||||
mod blocks;
|
||||
mod editor;
|
||||
mod fallback;
|
||||
@@ -112,6 +117,7 @@ pub struct TextLine {
|
||||
scope: Option<usize>,
|
||||
/// The layers and graphics state parameters it is drawn in; see [`Paint`].
|
||||
paint: Paint,
|
||||
containers: Vec<usize>,
|
||||
/// Right-to-left `/ActualText` already supplies typing order; glyph text still needs bidi
|
||||
/// recovery. Left-to-right ActualText (e.g. a Latin ligature) joins its line as usual.
|
||||
logical_order: bool,
|
||||
|
||||
@@ -479,6 +479,7 @@ pub(super) struct Shown {
|
||||
pub(super) decodable: bool,
|
||||
pub(super) scope: Option<usize>,
|
||||
pub(super) paint: Paint,
|
||||
pub(super) containers: Vec<usize>,
|
||||
pub(super) logical_order: bool,
|
||||
pub(super) actual_text: bool,
|
||||
/// Set when a `/PCSoft` or `/PCHard` marker was seen since the previous text line.
|
||||
@@ -623,6 +624,9 @@ pub(super) struct Carry {
|
||||
pub(super) layers: Vec<Option<Vec<u8>>>,
|
||||
/// Bytes of glyph text the rest of the page may still produce (see [`MAX_PAGE_TEXT`]).
|
||||
pub(super) text_left: usize,
|
||||
pub(super) containers: Rc<super::containers::Containers>,
|
||||
/// The operator indices of the `Do`s, from the page down, that draw these operators.
|
||||
pub(super) at: Vec<usize>,
|
||||
/// Whether the last run ended in a space read from a gap, with the next operator a `Tj` or
|
||||
/// `TJ` that may start with the space glyph that gap widened.
|
||||
pub(super) gap_space: bool,
|
||||
@@ -657,7 +661,16 @@ impl Carry {
|
||||
dash: (Vec::new(), 0.0),
|
||||
line_cap: 0,
|
||||
};
|
||||
Carry { ts, stack: Vec::new(), marked: Vec::new(), layers: Vec::new(), text_left: MAX_PAGE_TEXT, gap_space: false }
|
||||
Carry {
|
||||
ts,
|
||||
stack: Vec::new(),
|
||||
marked: Vec::new(),
|
||||
layers: Vec::new(),
|
||||
text_left: MAX_PAGE_TEXT,
|
||||
containers: Rc::default(),
|
||||
at: Vec::new(),
|
||||
gap_space: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -964,6 +977,7 @@ fn show_text(op: &Op, i: usize, state: &mut TextRunState<'_>) -> Result<(), Edit
|
||||
decodable,
|
||||
scope: marked.regions.last().copied().flatten(),
|
||||
paint: Paint { layers: marked.layers.iter().flatten().cloned().collect(), gs: ts.gs.clone() },
|
||||
containers: Vec::new(),
|
||||
logical_order: false,
|
||||
actual_text: false,
|
||||
soft_break: state.soft_break,
|
||||
@@ -1233,5 +1247,52 @@ pub(super) fn interpret(
|
||||
carry.layers = marked.layers;
|
||||
out.retain(|s| s.glyph_count > 0 || s.actual_text);
|
||||
positioned_tracking(&mut out);
|
||||
assign_containers(&mut out, carry);
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The filled panels each piece of text sits in: its `membership`, less a box a highlight's
|
||||
/// height that only part of the text or of its line is in.
|
||||
fn assign_containers(out: &mut [Shown], carry: &Carry) {
|
||||
for shown in out.iter_mut() {
|
||||
shown.containers = carry.containers.membership(shown.rect, &[carry.at.as_slice(), &[shown.op]].concat());
|
||||
}
|
||||
// A box a highlight's height that does not reach across the text is a highlight behind part
|
||||
// of it, as when one `Tj` draws the whole line.
|
||||
for shown in out.iter_mut() {
|
||||
let rect = shown.rect;
|
||||
shown.containers.retain(|panel| carry.containers.spans(*panel, rect) || !carry.containers.hugs(*panel, rect));
|
||||
}
|
||||
// Text that runs on along its line keeps a box only part of it is in when the box is a
|
||||
// panel's height: a highlight padded around one word of the line is not a panel.
|
||||
let mut start = 0;
|
||||
while start < out.len() {
|
||||
let mut end = start + 1;
|
||||
while out.get(end).is_some_and(|next| runs_on(&out[end - 1].rect, &next.rect)) {
|
||||
end += 1;
|
||||
}
|
||||
if end - start > 1 {
|
||||
// How many of the run's pieces each box holds (`membership` lists a box once per piece),
|
||||
// counted in one pass: a hostile page can chain thousands of runs into one line.
|
||||
let mut held: HashMap<usize, usize> = HashMap::new();
|
||||
for shown in &out[start..end] {
|
||||
for panel in &shown.containers {
|
||||
*held.entry(*panel).or_default() += 1;
|
||||
}
|
||||
}
|
||||
for shown in &mut out[start..end] {
|
||||
let rect = shown.rect;
|
||||
shown.containers.retain(|panel| held.get(panel) == Some(&(end - start)) || !carry.containers.hugs(*panel, rect));
|
||||
}
|
||||
}
|
||||
start = end;
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether text in `next` continues `previous` along its line: about the same height across it,
|
||||
/// and starting at or after it with less than a line's height between them.
|
||||
fn runs_on(previous: &[f64; 4], next: &[f64; 4]) -> bool {
|
||||
let height = (previous[3] - previous[1]).max(next[3] - next[1]);
|
||||
let centre = |r: &[f64; 4]| (r[1] + r[3]) / 2.0;
|
||||
(centre(previous) - centre(next)).abs() < height / 2.0 && next[0] >= previous[0] && next[0] - previous[2] < height
|
||||
}
|
||||
|
||||
@@ -460,6 +460,7 @@ fn text_lines_in(doc: &Document, p: &pdfcraft_model::Page, actual_text: bool, in
|
||||
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();
|
||||
carry.containers = std::rc::Rc::new(super::containers::Containers::collect(doc, &ops, &res));
|
||||
let shown = interpret(doc, &ops, &res, &mut cache, &mut carry, None, actual_text.then_some(&properties))?;
|
||||
let mut last: Option<(usize, Pen)> = None; // the stream piece and where its last run ended
|
||||
for mut s in shown {
|
||||
@@ -478,7 +479,9 @@ fn text_lines_in(doc: &Document, p: &pdfcraft_model::Page, actual_text: bool, in
|
||||
let bt = pen.bt;
|
||||
let (near, gap) = pen.continues(&s, if bt == s.bt { 3.0 } else { 1.5 });
|
||||
piece == si
|
||||
&& lines.last().is_some_and(|l| l.scope == s.scope && l.paint == s.paint && l.logical_order == s.logical_order)
|
||||
&& lines.last().is_some_and(|l| {
|
||||
l.scope == s.scope && l.paint == s.paint && l.containers == s.containers && l.logical_order == s.logical_order
|
||||
})
|
||||
&& (bt == s.bt || lines.last().is_some_and(|l| compatible_word(l, &s)))
|
||||
&& (s.text.trim().is_empty() || lines.last().is_some_and(|l| continues_font(l, &s)))
|
||||
&& (s.text.trim().is_empty()
|
||||
@@ -534,6 +537,7 @@ fn text_lines_in(doc: &Document, p: &pdfcraft_model::Page, actual_text: bool, in
|
||||
stream: si,
|
||||
scope: s.scope,
|
||||
paint: s.paint.clone(),
|
||||
containers: s.containers.clone(),
|
||||
logical_order: s.logical_order,
|
||||
actual_text: s.actual_text,
|
||||
clips: s.state.render_mode >= 4,
|
||||
@@ -601,7 +605,7 @@ fn compatible_word(line: &TextLine, shown: &Shown) -> bool {
|
||||
fn add_shown(lines: &mut Vec<TextLine>, last: &mut Option<Pen>, s: Shown, stream: usize) {
|
||||
let joins = last.is_some_and(|pen| {
|
||||
let bt = pen.bt;
|
||||
lines.last().is_some_and(|l| l.scope == s.scope && l.paint == s.paint && l.logical_order == s.logical_order)
|
||||
lines.last().is_some_and(|l| l.scope == s.scope && l.paint == s.paint && l.containers == s.containers && l.logical_order == s.logical_order)
|
||||
&& (bt == s.bt || lines.last().is_some_and(|l| compatible_word(l, &s)))
|
||||
&& (s.text.trim().is_empty() || lines.last().is_some_and(|l| continues_font(l, &s)))
|
||||
&& (s.text.trim().is_empty()
|
||||
@@ -653,6 +657,7 @@ fn add_shown(lines: &mut Vec<TextLine>, last: &mut Option<Pen>, s: Shown, stream
|
||||
stream,
|
||||
scope: s.scope,
|
||||
paint: s.paint.clone(),
|
||||
containers: s.containers.clone(),
|
||||
logical_order: s.logical_order,
|
||||
actual_text: s.actual_text,
|
||||
clips: s.state.render_mode >= 4,
|
||||
@@ -832,8 +837,8 @@ pub(super) fn reading_lines(doc: &Document, page: usize) -> Result<(Vec<TextLine
|
||||
let mut last_stream = None;
|
||||
let mut forms = invoked.into_iter().peekable();
|
||||
for s in shown {
|
||||
while let Some((_, name, ts)) = forms.next_if(|f| f.0 < s.op) {
|
||||
enter(w, resources, &name, ts, &mut carry.text_left)?;
|
||||
while let Some((i, name, ts)) = forms.next_if(|f| f.0 < s.op) {
|
||||
enter(w, resources, &name, ts, &mut carry.text_left, carry.containers.clone(), [carry.at.as_slice(), &[i]].concat())?;
|
||||
// Text after a form starts a new line.
|
||||
last = None;
|
||||
}
|
||||
@@ -850,13 +855,21 @@ pub(super) fn reading_lines(doc: &Document, page: usize) -> Result<(Vec<TextLine
|
||||
}
|
||||
add_shown(&mut w.lines, &mut last, s, si);
|
||||
}
|
||||
for (_, name, ts) in forms {
|
||||
enter(w, resources, &name, ts, &mut carry.text_left)?;
|
||||
for (i, name, ts) in forms {
|
||||
enter(w, resources, &name, ts, &mut carry.text_left, carry.containers.clone(), [carry.at.as_slice(), &[i]].concat())?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// `text_left`: the page's text budget, shared with the forms the page draws.
|
||||
fn enter(w: &mut Walk, resources: &Dict, name: &[u8], ts: Ts, text_left: &mut usize) -> Result<(), EditError> {
|
||||
fn enter(
|
||||
w: &mut Walk,
|
||||
resources: &Dict,
|
||||
name: &[u8],
|
||||
ts: Ts,
|
||||
text_left: &mut usize,
|
||||
containers: std::rc::Rc<super::containers::Containers>,
|
||||
at: Vec<usize>,
|
||||
) -> Result<(), EditError> {
|
||||
let Some(form) = form_call(w.doc, resources, name, ts.ctm, &w.path, &mut w.budget) else { return Ok(()) };
|
||||
let ops = parse(&form.data).ops;
|
||||
// The form starts with the graphics state at its `Do`, its own matrix applied.
|
||||
@@ -873,6 +886,8 @@ pub(super) fn reading_lines(doc: &Document, page: usize) -> Result<(Vec<TextLine
|
||||
layers: Vec::new(),
|
||||
text_left: *text_left,
|
||||
gap_space: false,
|
||||
containers,
|
||||
at,
|
||||
};
|
||||
let stream = w.next_stream;
|
||||
w.next_stream = w.next_stream.saturating_add(1);
|
||||
@@ -899,6 +914,7 @@ pub(super) fn reading_lines(doc: &Document, page: usize) -> Result<(Vec<TextLine
|
||||
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);
|
||||
carry.containers = std::rc::Rc::new(super::containers::Containers::collect(doc, &ops, &res));
|
||||
walk(&mut w, &ops, &res, &mut carry, &stream_of)?;
|
||||
let mut lines = w.lines;
|
||||
// A visual-order Indic font draws pre-base vowel signs before their consonant.
|
||||
|
||||
@@ -0,0 +1,171 @@
|
||||
//! Filled rectangular panel boundaries used by editable text grouping.
|
||||
|
||||
use pdfcraft_content::{Matrix, Op};
|
||||
use pdfcraft_cos::{Dict, Document, ObjRef};
|
||||
|
||||
struct Container {
|
||||
inverse: Matrix,
|
||||
rect: [f64; 4],
|
||||
/// Where it is painted in the page's drawing order (see [`Containers::membership`]).
|
||||
at: Vec<usize>,
|
||||
/// Its bounding box on the page, whatever matrix drew it.
|
||||
page: [f64; 4],
|
||||
/// The first container with the same box on the page: a panel painted again behind each of
|
||||
/// its rows, under any matrix, is still one panel.
|
||||
id: usize,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct Containers {
|
||||
filled: Vec<Container>,
|
||||
pending: Option<Container>,
|
||||
complex: bool,
|
||||
}
|
||||
|
||||
impl Containers {
|
||||
pub(super) fn collect(doc: &Document, ops: &[Op], resources: &Dict) -> Self {
|
||||
let mut collector = Collector {
|
||||
doc,
|
||||
containers: Self::default(),
|
||||
path: Vec::new(),
|
||||
budget: super::lines::FormBudget::new(pdfcraft_cos::DecodeBudget::page()),
|
||||
};
|
||||
collector.walk(ops, resources, Matrix::IDENTITY, &[]);
|
||||
let mut first = std::collections::HashMap::new();
|
||||
for (index, container) in collector.containers.filled.iter_mut().enumerate() {
|
||||
let key = container.page.map(|v| (v * 1000.0).round() as i64);
|
||||
container.id = *first.entry(key).or_insert(index);
|
||||
}
|
||||
collector.containers
|
||||
}
|
||||
|
||||
fn observe(&mut self, op: &Op, ctm: Matrix, at: &[usize]) {
|
||||
match op.op.as_slice() {
|
||||
b"re" => {
|
||||
if self.pending.is_some() {
|
||||
self.complex = true;
|
||||
}
|
||||
self.pending = op.nums::<4>().zip(ctm.invert()).and_then(|([x, y, width, height], inverse)| {
|
||||
let rect = [x.min(x + width), y.min(y + height), x.max(x + width), y.max(y + height)];
|
||||
(rect.iter().all(|v| v.is_finite()) && rect[2] > rect[0] && rect[3] > rect[1]).then_some(Container {
|
||||
inverse,
|
||||
rect,
|
||||
at: Vec::new(),
|
||||
page: page_box(rect, ctm),
|
||||
id: 0,
|
||||
})
|
||||
});
|
||||
}
|
||||
b"m" | b"l" | b"c" | b"v" | b"y" => self.complex = true,
|
||||
b"f" | b"F" | b"f*" | b"B" | b"B*" | b"b" | b"b*" => {
|
||||
if !self.complex
|
||||
&& self.filled.len() < 4096
|
||||
&& let Some(mut rect) = self.pending.take()
|
||||
{
|
||||
rect.at = at.to_vec();
|
||||
self.filled.push(rect);
|
||||
}
|
||||
self.pending = None;
|
||||
self.complex = false;
|
||||
}
|
||||
b"n" | b"S" | b"s" => {
|
||||
self.pending = None;
|
||||
self.complex = false;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// The panels that hold `rect`'s centre and are taller than it. A highlight or inline shading
|
||||
/// drawn to the height of its glyphs is not a panel, and neither is a fill painted after the
|
||||
/// text (a redaction cover): `at` is the text's place in the drawing order, the operator
|
||||
/// indices from the page down through the forms that draw it.
|
||||
pub(super) fn membership(&self, rect: [f64; 4], at: &[usize]) -> Vec<usize> {
|
||||
let (x, y) = ((rect[0] + rect[2]) / 2.0, (rect[1] + rect[3]) / 2.0);
|
||||
let mut ids: Vec<usize> = self
|
||||
.filled
|
||||
.iter()
|
||||
.filter_map(|container| {
|
||||
let ys =
|
||||
[(rect[0], rect[1]), (rect[2], rect[1]), (rect[0], rect[3]), (rect[2], rect[3])].map(|(x, y)| container.inverse.apply(x, y).1);
|
||||
let height = ys.iter().copied().fold(f64::NEG_INFINITY, f64::max) - ys.iter().copied().fold(f64::INFINITY, f64::min);
|
||||
let (x, y) = container.inverse.apply(x, y);
|
||||
let [left, bottom, right, top] = container.rect;
|
||||
(container.at.as_slice() < at && x >= left && x <= right && y >= bottom && y <= top && top - bottom >= height * 1.15)
|
||||
.then_some(container.id)
|
||||
})
|
||||
.collect();
|
||||
ids.sort_unstable();
|
||||
ids.dedup();
|
||||
ids
|
||||
}
|
||||
}
|
||||
|
||||
fn page_box([left, bottom, right, top]: [f64; 4], ctm: Matrix) -> [f64; 4] {
|
||||
let corners = [(left, bottom), (right, bottom), (left, top), (right, top)].map(|(x, y)| ctm.apply(x, y));
|
||||
corners.iter().fold([f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY], |[x0, y0, x1, y1], &(x, y)| {
|
||||
[x0.min(x), y0.min(y), x1.max(x), y1.max(y)]
|
||||
})
|
||||
}
|
||||
|
||||
impl Containers {
|
||||
/// Whether panel `id` (from [`Containers::membership`]) is no more than a padded highlight
|
||||
/// around `rect`: under 1.75 times its height on the page.
|
||||
pub(super) fn hugs(&self, id: usize, rect: [f64; 4]) -> bool {
|
||||
self.filled.get(id).is_some_and(|panel| panel.page[3] - panel.page[1] < (rect[3] - rect[1]) * 1.75)
|
||||
}
|
||||
|
||||
/// Whether panel `id` reaches across `rect` from its left edge to its right one on the page.
|
||||
pub(super) fn spans(&self, id: usize, rect: [f64; 4]) -> bool {
|
||||
let tolerance = (rect[3] - rect[1]) * 0.25;
|
||||
self.filled.get(id).is_some_and(|panel| panel.page[0] <= rect[0] + tolerance && panel.page[2] >= rect[2] - tolerance)
|
||||
}
|
||||
}
|
||||
|
||||
struct Collector<'a> {
|
||||
doc: &'a Document,
|
||||
containers: Containers,
|
||||
path: Vec<ObjRef>,
|
||||
budget: super::lines::FormBudget,
|
||||
}
|
||||
|
||||
impl Collector<'_> {
|
||||
fn walk(&mut self, ops: &[Op], resources: &Dict, initial: Matrix, prefix: &[usize]) {
|
||||
let mut local = Containers::default();
|
||||
let mut ctm = initial;
|
||||
let mut stack = Vec::new();
|
||||
for (i, op) in ops.iter().enumerate() {
|
||||
let at = [prefix, &[i]].concat();
|
||||
local.observe(op, ctm, &at);
|
||||
match op.op.as_slice() {
|
||||
b"q" => stack.push(ctm),
|
||||
b"Q" => {
|
||||
if let Some(saved) = stack.pop() {
|
||||
ctm = saved;
|
||||
}
|
||||
}
|
||||
b"cm" => {
|
||||
if let Some(matrix) = op.nums::<6>() {
|
||||
ctm = Matrix(matrix).then(&ctm);
|
||||
}
|
||||
}
|
||||
b"Do" => {
|
||||
if let Some(name) = op.name(0)
|
||||
&& let Some(form) = super::lines::form_call(self.doc, resources, name, ctm, &self.path, &mut self.budget)
|
||||
{
|
||||
if let Some(obj) = form.obj {
|
||||
self.path.push(obj);
|
||||
}
|
||||
self.walk(&pdfcraft_content::parse(&form.data).ops, form.resources(resources), form.ctm, &at);
|
||||
if form.obj.is_some() {
|
||||
self.path.pop();
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let remaining = 4096_usize.saturating_sub(self.containers.filled.len());
|
||||
self.containers.filled.extend(local.filled.into_iter().take(remaining));
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,7 @@ fn same_plane(a: &TextLine, b: &TextLine) -> bool {
|
||||
let bt = Matrix(b.origin.tm).then(&Matrix(b.origin.ctm));
|
||||
a.scope == b.scope
|
||||
&& a.paint == b.paint
|
||||
&& a.containers == b.containers
|
||||
&& [0, 2].iter().all(|axis| {
|
||||
let ax = at.0.get(*axis).copied().unwrap_or(0.0);
|
||||
let ay = at.0.get(axis + 1).copied().unwrap_or(0.0);
|
||||
@@ -351,7 +352,7 @@ fn group_layout(lines: &[TextLine], mixed: bool) -> Vec<TextBlock> {
|
||||
// The rewrite sets every row in the first one's horizontal scale.
|
||||
&& (prev.origin.state.scale - first.origin.state.scale).abs() < 1e-6
|
||||
&& aligned
|
||||
&& first.size.min(prev.size) >= first.size.max(prev.size) * 0.4
|
||||
&& super::super::row_style::compatible(prev_row, row, lines)
|
||||
&& gap > first.size.min(prev.size) * 0.8
|
||||
&& gap < max_gap
|
||||
});
|
||||
|
||||
@@ -565,8 +565,51 @@ fn validate_contextual_rows(rows: &[Vec<StyledChar>], kept: &[bool]) -> Result<(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn line_nominal_width(
|
||||
index: usize,
|
||||
source: &TextLine,
|
||||
chars: &[(char, usize, String)],
|
||||
metrics: &std::collections::BTreeMap<String, Metrics>,
|
||||
space_of: &impl Fn(&str, &Metrics) -> f64,
|
||||
) -> Option<f64> {
|
||||
let font_name = metrics
|
||||
.get(&source.font)
|
||||
.filter(|m| source_encodes(m, &source.text))
|
||||
.map(|_| &source.font)
|
||||
.or_else(|| chars.iter().find(|c| c.1 == index && c.0 != '\n').map(|c| &c.2));
|
||||
let width_in = |name: &str, m: &Metrics, text: &str| {
|
||||
source_width(
|
||||
m,
|
||||
text,
|
||||
source.origin.state.font.as_ref().map_or(1.0, |(_, s)| *s),
|
||||
space_of(name, m),
|
||||
source.origin.state.char_spacing,
|
||||
source.origin.state.word_spacing,
|
||||
)
|
||||
};
|
||||
font_name.and_then(|name| metrics.get(name).filter(|m| source_encodes(m, &source.text)).map(|m| width_in(name, m, &source.text))).or_else(|| {
|
||||
// Generated same-face subsets can form one source line even though no one
|
||||
// subset encodes it all. Measure the ORIGINAL text, not the edited draft:
|
||||
// adding characters must retain the source's spacing, not squeeze to its width.
|
||||
// Shaped text has a separate authoritative advance below.
|
||||
if source.face.is_none() || pdfcraft_fonts::source_shaping::required(&source.text) {
|
||||
return None;
|
||||
}
|
||||
let face = pdfcraft_fonts::embedding::face_key(&source.base_font);
|
||||
source.text.chars().try_fold(0.0, |width, ch| {
|
||||
let text = ch.to_string();
|
||||
let (name, m) = metrics
|
||||
.get_key_value(&source.font)
|
||||
.filter(|(_, m)| source_encodes(m, &text))
|
||||
.or_else(|| metrics.iter().find(|(_, m)| pdfcraft_fonts::embedding::face_key(&m.base_font) == face && source_encodes(m, &text)))?;
|
||||
Some(width + width_in(name, m, &text))
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
fn calibration_factors(
|
||||
lines: &[TextLine],
|
||||
chars: &[(char, usize, String)],
|
||||
metrics: &std::collections::BTreeMap<String, Metrics>,
|
||||
style: &BlockStyle,
|
||||
overrides: &HashMap<usize, &RangeStyle>,
|
||||
@@ -574,16 +617,8 @@ fn calibration_factors(
|
||||
) -> HashMap<usize, f64> {
|
||||
let mut calibration = HashMap::new();
|
||||
for (index, source) in lines.iter().enumerate() {
|
||||
if let Some(metrics) = metrics.get(&source.font) {
|
||||
let nominal = source_width(
|
||||
metrics,
|
||||
&source.text,
|
||||
source.origin.state.font.as_ref().map_or(1.0, |(_, size)| *size),
|
||||
space_of(&source.font, metrics),
|
||||
source.origin.state.char_spacing,
|
||||
source.origin.state.word_spacing,
|
||||
) * source.origin.state.scale
|
||||
* across(source);
|
||||
if let Some(nominal) = line_nominal_width(index, source, chars, metrics, &space_of) {
|
||||
let nominal = nominal * source.origin.state.scale * across(source);
|
||||
let changed_face =
|
||||
style.resource.is_some() || overrides.get(&index).is_some_and(|range| range.family.is_some() || range.resource.is_some());
|
||||
let factor = if nominal > 0.0 && !changed_face { ((source.rect[2] - source.rect[0]) / nominal).clamp(0.5, 2.0) } else { 1.0 };
|
||||
@@ -1917,7 +1952,7 @@ pub(crate) fn rewrite_styled_block(
|
||||
spaces.borrow_mut().insert(name.to_owned(), w);
|
||||
w
|
||||
};
|
||||
let mut calibration = calibration_factors(lines, &metrics, style, &overrides, space_of);
|
||||
let mut calibration = calibration_factors(lines, &chars, &metrics, style, &overrides, space_of);
|
||||
fit_to_phrase(&mut calibration, lines, phrase_size);
|
||||
let advance = |item: &(char, usize, String)| -> f64 {
|
||||
let source = lines.get(item.1).unwrap_or(first);
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
//! Row-level typography compatibility, independent of inline style boundaries.
|
||||
|
||||
use super::TextLine;
|
||||
|
||||
fn family(line: &TextLine) -> String {
|
||||
const SUFFIXES: [&str; 16] = [
|
||||
"bolditalic",
|
||||
"boldoblique",
|
||||
"semibold",
|
||||
"demibold",
|
||||
"regular",
|
||||
"boldit",
|
||||
"italic",
|
||||
"oblique",
|
||||
"medium",
|
||||
"light",
|
||||
"bold",
|
||||
"roman",
|
||||
"psmt",
|
||||
"mt",
|
||||
"ps",
|
||||
"it",
|
||||
];
|
||||
let mut key = pdfcraft_fonts::embedding::face_key(&line.base_font);
|
||||
// Weight and style suffixes stack (TimesNewRomanPS-BoldMT), so strip until none is left.
|
||||
while let Some(base) = SUFFIXES.iter().find_map(|suffix| key.strip_suffix(suffix)).filter(|base| !base.is_empty()) {
|
||||
key = base.to_owned();
|
||||
}
|
||||
key
|
||||
}
|
||||
|
||||
pub(super) fn compatible(previous: &[usize], next: &[usize], lines: &[TextLine]) -> bool {
|
||||
let representative =
|
||||
|row: &[usize]| row.iter().filter_map(|index| lines.get(*index)).max_by(|a, b| (a.rect[2] - a.rect[0]).total_cmp(&(b.rect[2] - b.rect[0])));
|
||||
match (representative(previous), representative(next)) {
|
||||
(Some(previous), Some(next)) => {
|
||||
// A row in one of the generated fallback faces holds characters the paragraph's own
|
||||
// font lacks; the edit chose that face, so it is no change of family.
|
||||
previous.size.min(next.size) >= previous.size.max(next.size) * 0.65
|
||||
&& (previous.face.is_some() || next.face.is_some() || family(previous) == family(next))
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
@@ -83,4 +83,12 @@ impl Document {
|
||||
.collect();
|
||||
Ok(Preview { candidates, unclassified_images: self.page_images(page).len(), unclassified_text_blocks, existing_structure })
|
||||
}
|
||||
|
||||
/// The running headers, footers and page numbers that applying auto-tag would mark as
|
||||
/// pagination artifacts. Reads the working PDF and does not alter it; refuses what auto-tag
|
||||
/// refuses.
|
||||
pub fn autotag_running_text(&self) -> Result<Vec<crate::a11y::RunningText>, String> {
|
||||
let editor = self.editor.as_ref().ok_or("the document can't be read")?;
|
||||
crate::a11y::running_text(&editor.cos).map_err(|e| e.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -306,7 +306,7 @@ pub const COMMANDS: &[CommandSpec] = &[
|
||||
c("comment.underline", "Underline text", None, None, Annotate, "text_underline"),
|
||||
c("comment.strikeout", "Strikethrough text", None, None, Annotate, "text_strikethrough"),
|
||||
c("comment.squiggly", "Squiggly underline text", None, None, Annotate, "spline"),
|
||||
c("comment.freehand_highlight", "Freehand-Highlight", None, None, Annotate, "highlighter"),
|
||||
c("comment.freehand_highlight", "Freehand-Highlight", None, None, Annotate, "freehand-highlighter"),
|
||||
c("comment.ink", "Draw freehand", None, None, Annotate, "pencil"),
|
||||
c("comment.line", "Draw a line", None, None, Annotate, "minus"),
|
||||
c("comment.arrow", "Draw an arrow", None, None, Annotate, "move-right"),
|
||||
|
||||
@@ -116,6 +116,21 @@ pub(crate) fn signatures_of(
|
||||
pdfcraft_sign::pdf::list_cached(cos, bytes, trust, cache)
|
||||
}
|
||||
|
||||
/// Validate the signature fields of `editor`'s working state (written as `bytes`). While that
|
||||
/// state is still the file as opened plus only what opening appended, the file as read is
|
||||
/// validated instead: PdfCraft's own open-time revisions are not changes made since signing.
|
||||
pub(crate) fn editor_signatures(
|
||||
editor: &crate::history::Editor,
|
||||
bytes: &[u8],
|
||||
trust: &TrustStore,
|
||||
cache: &pdfcraft_sign::DigestCache,
|
||||
) -> Vec<SignatureInfo> {
|
||||
match &editor.as_opened {
|
||||
Some(o) if !editor.cos.is_modified() && Arc::ptr_eq(editor.cos.bytes(), &editor.saved) => signatures_of(&o.cos, &o.bytes, trust, cache),
|
||||
_ => signatures_of(&editor.cos, bytes, trust, cache),
|
||||
}
|
||||
}
|
||||
|
||||
/// What Optimize PDF did.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct OptimizeReport {
|
||||
|
||||
@@ -441,6 +441,16 @@ impl Document {
|
||||
self.editor.as_ref().map(|e| crate::text_style_bookmarks::styles(&e.cos)).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Suggest outline (#6020): the bookmark tree proposed for the document, from its tagged
|
||||
/// headings or else from how its text looks. `None` when the document doesn't allow copying
|
||||
/// (the titles are its text) or can't be read for editing.
|
||||
pub fn suggest_outline(&self) -> Option<crate::suggest_outline::OutlineSuggestion> {
|
||||
if !self.allows_copying() {
|
||||
return None;
|
||||
}
|
||||
self.editor.as_ref().map(|e| crate::suggest_outline::suggest(&e.cos))
|
||||
}
|
||||
|
||||
/// Edit a PDF ▸ Edit text: the lines of existing text on `page` (0-based).
|
||||
pub fn text_lines(&self, page: usize) -> Vec<pdfcraft_edit::TextLine> {
|
||||
self.editor.as_ref().and_then(|e| pdfcraft_edit::text_lines(&e.cos, page).ok()).unwrap_or_default()
|
||||
|
||||
@@ -262,6 +262,8 @@ pub(crate) struct EditCtx {
|
||||
pub(crate) xfa_time_scale: u32,
|
||||
/// The answers the edit's XFA event takes ([`Session::xfa_answers`](crate::Session)).
|
||||
pub(crate) xfa_answers: xfa::XfaAnswers,
|
||||
/// The form's scripts or new data laid it out again: its pages and widgets were replaced.
|
||||
pub(crate) xfa_relaid: bool,
|
||||
/// The edit took the XFA out of the form: what went with it, for the document's warnings.
|
||||
pub(crate) xfa_removed: Vec<String>,
|
||||
/// Pages in the document, for `xfa.layout.pageCount()`.
|
||||
@@ -334,6 +336,7 @@ impl EditCtx {
|
||||
xfa_unchanged: false,
|
||||
xfa_time_scale: 1,
|
||||
xfa_answers: Default::default(),
|
||||
xfa_relaid: false,
|
||||
xfa_removed: Vec::new(),
|
||||
pages: 0,
|
||||
highlight: false,
|
||||
@@ -612,11 +615,7 @@ pub(crate) fn run_edit(doc: &mut pdfcraft_cos::Document, edit: &Edit, cx: &mut E
|
||||
pdfcraft_organize::import_outline(doc, parent, *index, bookmarks, *replace)?;
|
||||
}
|
||||
Edit::BookmarksFromStructure => {
|
||||
let entries: Vec<_> = pdfcraft_a11y::headings(doc)
|
||||
.into_iter()
|
||||
.map(|h| pdfcraft_organize::OutlineEntry { level: h.level, title: h.title, page: h.page, element: h.obj, left: None, top: None })
|
||||
.collect();
|
||||
pdfcraft_organize::add_bookmark_tree(doc, "Untitled", &entries)?;
|
||||
pdfcraft_organize::add_bookmark_tree(doc, "Untitled", &crate::suggest_outline::structure_entries(doc).0)?;
|
||||
}
|
||||
Edit::BookmarksFromTextStyles { levels } => {
|
||||
if levels.is_empty() {
|
||||
@@ -799,6 +798,7 @@ pub(crate) fn run_edit(doc: &mut pdfcraft_cos::Document, edit: &Edit, cx: &mut E
|
||||
highlight,
|
||||
time_scale: cx.xfa_time_scale,
|
||||
answers: std::mem::take(&mut cx.xfa_answers),
|
||||
relaid: false,
|
||||
};
|
||||
let ran = if matches!(activity.as_str(), "enter" | "exit") {
|
||||
xfa::on_focus(doc, &tpl, som, activity, &mut run).map(|changes| changes.is_empty())
|
||||
@@ -807,10 +807,14 @@ pub(crate) fn run_edit(doc: &mut pdfcraft_cos::Document, edit: &Edit, cx: &mut E
|
||||
};
|
||||
cx.xfa_datasets = run.datasets;
|
||||
cx.xfa_ran_away |= run.ran_away;
|
||||
// The next XFA run of a batch starts from the page count this one left.
|
||||
cx.pages = run.page_count;
|
||||
cx.xfa_relaid |= run.relaid;
|
||||
// The next edit of a batch reads the highlight this one's scripts set.
|
||||
let on = run.highlight;
|
||||
cx.set_highlight(on);
|
||||
cx.xfa_unchanged = ran.map_err(EditError::Invalid)?;
|
||||
// A form laid out again changed, whatever its scripts counted.
|
||||
cx.xfa_unchanged = ran.map_err(EditError::Invalid)? && !cx.xfa_relaid;
|
||||
}
|
||||
Edit::SetFieldImage { name, image } | Edit::SetFieldImageTarget { name, image, .. } => {
|
||||
let object = match edit {
|
||||
|
||||
@@ -150,6 +150,17 @@ pub(crate) struct Editor {
|
||||
pub(crate) field_appearances: pdfcraft_forms::FieldAppearanceCache,
|
||||
/// The text blocks last computed for one page, reused while the document is unchanged.
|
||||
pub(crate) text_blocks: TextBlocksCache,
|
||||
/// A signed file that opening appended revisions to (an XFA form's layout, the values from
|
||||
/// its data, its open scripts): the file as it was read, which the signatures are validated
|
||||
/// against until the user changes something or saves (#2759).
|
||||
pub(crate) as_opened: Option<AsOpened>,
|
||||
}
|
||||
|
||||
/// The file as read, before opening appended PdfCraft's own revisions to it.
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct AsOpened {
|
||||
pub(crate) cos: pdfcraft_cos::Document,
|
||||
pub(crate) bytes: Arc<Vec<u8>>,
|
||||
}
|
||||
|
||||
/// One page's text blocks ([`pdfcraft_edit::text_blocks`]) and the document state they were read
|
||||
|
||||
@@ -1347,6 +1347,15 @@ impl Session {
|
||||
self.after_script(id, &o, &written);
|
||||
Ok(o)
|
||||
}
|
||||
|
||||
/// The script errors not taken yet, out of what [`Session::take_js_output`] returns; the
|
||||
/// alerts, console lines and requests stay for that call. A document script's error taken
|
||||
/// here is reported again when the document scripts fail again on a later edit.
|
||||
pub fn take_js_errors(&mut self, id: DocId) -> Vec<String> {
|
||||
let Some(d) = self.docs.iter_mut().find(|d| d.id == id) else { return Vec::new() };
|
||||
d.js_output.doc_errors.clear();
|
||||
std::mem::take(&mut d.js_output.errors)
|
||||
}
|
||||
}
|
||||
|
||||
/// A page's words for form-field detection, in user space (underscore runs split from the
|
||||
|
||||
@@ -60,6 +60,7 @@ pub mod signature_scan;
|
||||
mod sources;
|
||||
pub mod spooler;
|
||||
mod stamp_preview;
|
||||
pub mod suggest_outline;
|
||||
#[cfg(test)]
|
||||
mod test_hooks;
|
||||
pub mod text_fonts;
|
||||
@@ -191,7 +192,7 @@ pub use pdfcraft_edit::ArrangeOrder;
|
||||
|
||||
use clock::{local_utc_offset, parse_ymd};
|
||||
pub use doc_state::{DocId, ImageEdit, OptimizeReport, RecoverySnapshot, SplitPart, guard, merge_data_files};
|
||||
use doc_state::{LOW_RESOLUTION_PRINT_DPI, render_threads, renderer_password, signatures_of, writable};
|
||||
use doc_state::{LOW_RESOLUTION_PRINT_DPI, editor_signatures, render_threads, renderer_password, signatures_of, writable};
|
||||
|
||||
/// The configuration of the pool that draws the viewer: the document's own, plus installed CJK
|
||||
/// fonts for fonts a PDF does not embed (`pdfcraft_render::RenderConfig::system_fonts`). Exports,
|
||||
|
||||
@@ -5,11 +5,11 @@ use std::sync::{Arc, OnceLock};
|
||||
use pdfcraft_cos::{SaveOptions, write_incremental};
|
||||
use pdfcraft_render::{DocInfo, OpenError, RenderConfig, RenderPool, inspect};
|
||||
|
||||
use crate::history::{Editor, Keys, TextBlocksCache};
|
||||
use crate::history::{AsOpened, Editor, Keys, TextBlocksCache};
|
||||
use crate::{
|
||||
AppearanceCache, DocId, Document, Session, StatusCaptions, TrustStore, XFA_SCRIPTS_OFF, XfaLayout, display_bytes, display_config, guard,
|
||||
info_fields, js, note_warnings, print_preview_layers, 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,
|
||||
editor_signatures, guard, info_fields, js, note_warnings, print_preview_layers, recovered_render_password, render_threads, same_pages, xfa,
|
||||
xfa_layout, xfa_values_from_datasets,
|
||||
};
|
||||
|
||||
/// Immutable session state needed while a document is prepared away from its owning thread.
|
||||
@@ -37,6 +37,8 @@ struct DocumentOpenData<'a> {
|
||||
render_password: Option<String>,
|
||||
password: Option<&'a str>,
|
||||
xfa: Option<XfaLayout>,
|
||||
/// The file as read, when opening appended revisions to it ([`crate::history::AsOpened`]).
|
||||
as_opened: Option<AsOpened>,
|
||||
}
|
||||
|
||||
impl OpenContext {
|
||||
@@ -152,6 +154,11 @@ impl Session {
|
||||
}
|
||||
Ok((new_bytes, new_info, new_cos))
|
||||
};
|
||||
// The file as read, for its signatures: opening an XFA form may append revisions below.
|
||||
let as_read = match (&info.xfa, &cos) {
|
||||
(Some(_), Ok(Ok(c))) => Some(AsOpened { cos: c.clone(), bytes: bytes.clone() }),
|
||||
_ => None,
|
||||
};
|
||||
let (bytes, info, cos, xfa) = match (info.xfa, cos) {
|
||||
(Some(pdfcraft_render::Xfa::Dynamic), Ok(Ok(cos))) if pdfcraft_xfa::existing_layout(&cos).is_none() => {
|
||||
let mut work = cos.clone();
|
||||
@@ -226,6 +233,7 @@ impl Session {
|
||||
highlight: context.highlight,
|
||||
time_scale: context.xfa_time_scale,
|
||||
answers: Default::default(),
|
||||
relaid: false,
|
||||
};
|
||||
let changes = xfa::on_open(&mut work, &tpl, &mut run);
|
||||
if run.ran_away {
|
||||
@@ -286,8 +294,9 @@ 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 as_opened = as_read.filter(|o| !Arc::ptr_eq(&o.bytes, &bytes));
|
||||
let mut document =
|
||||
Self::build_document(context, 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, as_opened });
|
||||
// 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);
|
||||
@@ -301,7 +310,7 @@ impl Session {
|
||||
|
||||
/// The last step of opening: build the document record and register it.
|
||||
fn build_document(context: &OpenContext, data: DocumentOpenData<'_>) -> Document {
|
||||
let DocumentOpenData { name, path, bytes, mut info, structure: cos, render_password, password, xfa } = data;
|
||||
let DocumentOpenData { name, path, bytes, mut info, structure: cos, render_password, password, xfa, as_opened } = data;
|
||||
let mut config = RenderConfig { password: render_password.as_deref().map(Arc::from), ..Default::default() };
|
||||
let (mut editor, read_only_reason) = match cos {
|
||||
Ok(Ok(cos)) => {
|
||||
@@ -319,6 +328,7 @@ impl Session {
|
||||
appearances: AppearanceCache::default(),
|
||||
field_appearances: pdfcraft_forms::FieldAppearanceCache::default(),
|
||||
text_blocks: TextBlocksCache::default(),
|
||||
as_opened,
|
||||
}),
|
||||
None,
|
||||
)
|
||||
@@ -327,7 +337,13 @@ 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 mut signatures = editor.as_ref().map(|e| signatures_of(&e.cos, &bytes, &context.trust, &sig_cache)).unwrap_or_default();
|
||||
let mut signatures = editor.as_ref().map(|e| editor_signatures(e, &bytes, &context.trust, &sig_cache)).unwrap_or_default();
|
||||
// Only a signed file needs keeping as it was read.
|
||||
if !signatures.iter().any(|s| s.signed)
|
||||
&& let Some(e) = editor.as_mut()
|
||||
{
|
||||
e.as_opened = None;
|
||||
}
|
||||
// The inspection reads only `/Info`; a file stating its title or author only in XMP still
|
||||
// shows them (#2373).
|
||||
if let Some(e) = &editor {
|
||||
|
||||
@@ -13,9 +13,9 @@ use crate::{
|
||||
BookmarkPage, BookmarkRow, CombineSource, Combined, DataFormat, DocId, Document, Edit, EditError, Hairlines, HairlinesFixed, Hidden,
|
||||
ImageResolution, 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, office_to_pdf, open_source,
|
||||
open_source_with, optimize, outline_rows, parse_ymd, print, print_layer_states, 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,
|
||||
comment_summary, decode_text, display_bytes, display_config, editor_signatures, guard, info_fields, js, local_utc_offset, note_warnings,
|
||||
office_to_pdf, open_source, open_source_with, optimize, outline_rows, parse_ymd, print, print_layer_states, print_raster, render_threads,
|
||||
scan_colours, set_default_layer_state, shown_under_redactions, source_kind, sync_xfa_state, undrawn_notices, use_layer_choices, writable, xfa,
|
||||
xfa_sync_datasets,
|
||||
};
|
||||
|
||||
|
||||
@@ -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, 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,
|
||||
XFA_REMOVED_PREFIX, XFA_SCRIPTS_OFF, carry_verdict_marks, check_permission, comment_list, display_bytes, display_config, editor_signatures,
|
||||
guard, info_fields, inspect, js, keys_after, note_warnings, render_threads, run_edit, scan_colours, scope_of, shown_under_redactions,
|
||||
sync_xfa_state, undrawn_notices, uses_scripts, write_incremental, xfa, xfa_sync_datasets,
|
||||
};
|
||||
use crate::{EditNotice, MarkKind, print_preview_layers};
|
||||
|
||||
@@ -328,14 +328,20 @@ impl Session {
|
||||
highlight,
|
||||
time_scale: cx.xfa_time_scale,
|
||||
answers: Default::default(),
|
||||
relaid: false,
|
||||
};
|
||||
// Every changed field's scripts, then the calculations once (after a reset,
|
||||
// only those).
|
||||
let ran = guard(|| xfa::on_changes(&mut next, &tpl, &changed, &mut run, &mut exited))
|
||||
// only those). The values before the edit tell a click from a value set again.
|
||||
let before: std::collections::HashMap<String, Vec<String>> =
|
||||
doc.form.iter().filter(|f| changed.contains(&f.name)).map(|f| (f.name.clone(), f.value.clone())).collect();
|
||||
let ran = guard(|| xfa::on_changes(&mut next, &tpl, &changed, &before, &mut run, &mut exited))
|
||||
.unwrap_or_else(|m| Err(format!("the form's scripts failed unexpectedly ({m})")));
|
||||
cx.xfa_datasets = run.datasets;
|
||||
cx.xfa_ran_away |= run.ran_away;
|
||||
cx.xfa_relaid |= run.relaid;
|
||||
// The next edit of a batch reads the highlight this one's scripts set.
|
||||
// The next XFA run of a batch starts from the page count this one left.
|
||||
cx.pages = run.page_count;
|
||||
let on = run.highlight;
|
||||
cx.set_highlight(on);
|
||||
if let Err(e) = ran {
|
||||
@@ -343,6 +349,13 @@ impl Session {
|
||||
}
|
||||
}
|
||||
}
|
||||
// The form's scripts (a check box showing a section) or its new data (a picture) laid
|
||||
// it out again, even if a later script then failed: as with text growth below, its
|
||||
// pages, widgets and fields were replaced, whether or not the page count changed. The
|
||||
// view and undo/redo rebuild them instead of refreshing only field values.
|
||||
if cx.xfa_relaid {
|
||||
scope = Scope::Full;
|
||||
}
|
||||
// XFA forms keep their values in the datasets packet too, for Adobe's viewers.
|
||||
let mut xfa_notes = Vec::new();
|
||||
if is_xfa && matches!(scope_of(&edit), Scope::Form | Scope::Full | Scope::Content) {
|
||||
@@ -362,6 +375,7 @@ impl Session {
|
||||
// Layout replaces pages and widgets, even if the page count is unchanged.
|
||||
// Undo/redo must rebuild these too instead of refreshing only field values.
|
||||
scope = Scope::Full;
|
||||
rerun_layout_ready(&mut next, &mut cx);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -574,7 +588,7 @@ impl Session {
|
||||
#[cfg(test)]
|
||||
check_refresh_panic();
|
||||
if !doc.signatures.is_empty() {
|
||||
let mut signatures = signatures_of(&editor.cos, &bytes, &doc.trust, &doc.sig_cache);
|
||||
let mut signatures = editor_signatures(editor, &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.
|
||||
@@ -625,7 +639,7 @@ impl Session {
|
||||
}
|
||||
doc.info.file_size = bytes.len();
|
||||
doc.form = form;
|
||||
let mut signatures = if doc.signatures.is_empty() { Vec::new() } else { signatures_of(&editor.cos, &bytes, &doc.trust, &doc.sig_cache) };
|
||||
let mut signatures = if doc.signatures.is_empty() { Vec::new() } else { editor_signatures(editor, &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));
|
||||
@@ -690,7 +704,7 @@ impl Session {
|
||||
doc.marker_scan = OnceLock::new();
|
||||
}
|
||||
doc.info.file_size = bytes.len();
|
||||
let mut signatures = if doc.signatures.is_empty() { Vec::new() } else { signatures_of(&editor.cos, &bytes, &doc.trust, &doc.sig_cache) };
|
||||
let mut signatures = if doc.signatures.is_empty() { Vec::new() } else { editor_signatures(editor, &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));
|
||||
@@ -798,7 +812,7 @@ impl Session {
|
||||
if invalidate_links {
|
||||
doc.links = OnceLock::new();
|
||||
}
|
||||
let mut signatures = signatures_of(&editor.cos, &bytes, &doc.trust, &doc.sig_cache);
|
||||
let mut signatures = editor_signatures(editor, &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));
|
||||
@@ -807,6 +821,38 @@ impl Session {
|
||||
}
|
||||
}
|
||||
|
||||
/// After a new layout: the form's `layout:ready` scripts run again, reading its page count, as
|
||||
/// after a layout its scripts asked for. Not after a script of this edit ran away: the form's
|
||||
/// scripts turn off once it is done.
|
||||
fn rerun_layout_ready(next: &mut pdfcraft_cos::Document, cx: &mut EditCtx) {
|
||||
if cx.xfa_ran_away {
|
||||
return;
|
||||
}
|
||||
let Some(tpl) = cx.xfa.clone() else { return };
|
||||
let highlight = cx.highlight();
|
||||
let page_count = pdfcraft_organize::page_count(next).unwrap_or(cx.pages);
|
||||
let mut run = xfa::XfaRun {
|
||||
page_count,
|
||||
out: &mut cx.xfa_out,
|
||||
datasets: cx.xfa_datasets,
|
||||
ran_away: false,
|
||||
highlight,
|
||||
time_scale: cx.xfa_time_scale,
|
||||
answers: Default::default(),
|
||||
relaid: false,
|
||||
};
|
||||
let ran = guard(|| xfa::on_layout(next, &tpl, &mut run)).unwrap_or_else(|m| Err(format!("the form's scripts failed unexpectedly ({m})")));
|
||||
cx.xfa_datasets = run.datasets;
|
||||
cx.xfa_ran_away |= run.ran_away;
|
||||
cx.xfa_relaid |= run.relaid;
|
||||
cx.pages = run.page_count;
|
||||
let on = run.highlight;
|
||||
cx.set_highlight(on);
|
||||
if let Err(e) = ran {
|
||||
cx.xfa_out.errors.push(e);
|
||||
}
|
||||
}
|
||||
|
||||
/// The optional content groups `cos` lists as layers, in order (what the inspection reads: a group
|
||||
/// listed twice is one layer, and one that is not a dictionary is none).
|
||||
fn layer_ids(cos: &pdfcraft_cos::Document) -> Vec<(u32, u16)> {
|
||||
|
||||
@@ -4,6 +4,9 @@ use super::{
|
||||
print_layer_states, print_raster, set_default_layer_state, source_kind, writable, write_full,
|
||||
};
|
||||
|
||||
/// Why printer's marks were refused for a print that goes as pictures.
|
||||
const MARKS_AS_PICTURES: &str = "printer marks print with the pages as they are, not as pictures: leave out as_image and app-managed colour (a document that allows only low-resolution printing always prints as pictures)";
|
||||
|
||||
/// Whether a conversion may run LibreOffice for an Office document (seconds, in another
|
||||
/// process) or must refuse it because the caller is on the frame thread.
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
@@ -229,6 +232,36 @@ impl Session {
|
||||
|
||||
/// The print-ready PDF for `settings` (sheets laid out for the paper; see `pdfcraft-print`).
|
||||
pub fn print_pdf(&self, id: DocId, settings: &print::Settings) -> Result<Vec<u8>, EditError> {
|
||||
self.print_pdf_marked(id, settings, None)
|
||||
}
|
||||
|
||||
/// Whether printer's marks fit around `pages` (0-based): [`pdfcraft_edit::add_printer_marks`]
|
||||
/// run on a scratch copy, so a page the marks would widen past the largest page a PDF can
|
||||
/// have is refused before anything (the Will Print actions) changes the document. The copy
|
||||
/// is dropped; [`Session::print_pdf_marked`] adds the marks again on the print copy.
|
||||
pub fn check_printer_marks(&self, id: DocId, pages: &[usize], marks: &crate::PrinterMarks) -> Result<(), EditError> {
|
||||
let doc = self.get(id).ok_or(EditError::NoDocument)?;
|
||||
let mut cos = match doc.editor.as_ref() {
|
||||
Some(e) => e.cos.clone(),
|
||||
None => {
|
||||
pdfcraft_cos::Document::open_with_password(doc.bytes.clone(), doc.password.as_deref()).map_err(|e| EditError::Write(e.to_string()))?
|
||||
}
|
||||
};
|
||||
let mut pages = pages.to_vec();
|
||||
pages.sort_unstable();
|
||||
pages.dedup();
|
||||
pdfcraft_edit::add_printer_marks(&mut cos, &pages, marks, true)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// [`Session::print_pdf`] with printer's marks (Acrobat's Marks and Bleeds) drawn around each
|
||||
/// printed page on the print copy only: the document itself gets none. A page is widened for
|
||||
/// them as [`pdfcraft_edit::add_printer_marks`] widens it, and marks the document already
|
||||
/// carries are replaced, so a page never prints two sets. With form fields only, the fields
|
||||
/// and the marks print and the page content doesn't. The pages print as they are, so
|
||||
/// marks can't go with a print as pictures (Print as image, app-managed colour, or a document
|
||||
/// that allows only low-resolution printing).
|
||||
pub fn print_pdf_marked(&self, id: DocId, settings: &print::Settings, marks: Option<&crate::PrinterMarks>) -> Result<Vec<u8>, EditError> {
|
||||
let doc = self.get(id).ok_or(EditError::NoDocument)?;
|
||||
if !doc.allows_printing() {
|
||||
return Err(EditError::NotPermitted("printing"));
|
||||
@@ -243,6 +276,9 @@ impl Session {
|
||||
// Print as image: the pages used become pictures first, then the picture document is
|
||||
// imposed in their place (its page k is the k-th distinct source page used).
|
||||
if let Some(raster) = low_res.as_ref().or(settings.raster.as_ref()) {
|
||||
if marks.is_some() {
|
||||
return Err(EditError::Print(MARKS_AS_PICTURES.into()));
|
||||
}
|
||||
let mut distinct: Vec<usize> = Vec::new();
|
||||
for &p in &settings.pages {
|
||||
if !distinct.contains(&p) {
|
||||
@@ -287,6 +323,21 @@ impl Session {
|
||||
if doc.signatures.iter().any(|s| s.verdict_shown) {
|
||||
let _ = pdfcraft_sign::show_status_layers(&mut cos, &mut doc.signatures.to_vec(), &doc.captions);
|
||||
}
|
||||
let marked;
|
||||
let mut settings = settings;
|
||||
if let Some(marks) = marks {
|
||||
// Form fields only prints no page content, so the page content goes before the
|
||||
// marks are added, and the marks then print as the page content does.
|
||||
if settings.content == print::Content::FormFieldsOnly {
|
||||
pdfcraft_print::keep_printed(&mut cos, print::Content::FormFieldsOnly);
|
||||
marked = print::Settings { content: print::Content::Document, ..settings.clone() };
|
||||
settings = &marked;
|
||||
}
|
||||
let mut pages = settings.pages.clone();
|
||||
pages.sort_unstable();
|
||||
pages.dedup();
|
||||
pdfcraft_edit::add_printer_marks(&mut cos, &pages, marks, true)?;
|
||||
}
|
||||
pdfcraft_print::impose(&cos, settings).map_err(|e| EditError::Print(e.to_string()))
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use super::{
|
||||
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,
|
||||
display_bytes, display_config, editor_signatures, guard, render_threads, writable, write_full, write_incremental, xfa_sync_datasets,
|
||||
};
|
||||
|
||||
impl Session {
|
||||
@@ -90,6 +90,8 @@ impl Session {
|
||||
editor.saved = bytes;
|
||||
editor.saved_keys = keys;
|
||||
editor.unsaved_file = false;
|
||||
// The saved file holds what opening appended: from now on it is the file.
|
||||
editor.as_opened = None;
|
||||
}
|
||||
if let Some(p) = path {
|
||||
doc.name = std::path::Path::new(&p).file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| p.clone());
|
||||
@@ -269,7 +271,7 @@ impl Session {
|
||||
return;
|
||||
}
|
||||
let Some(editor) = doc.editor.as_mut() else { return };
|
||||
let mut signatures = signatures_of(&editor.cos, &doc.bytes, &doc.trust, &doc.sig_cache);
|
||||
let mut signatures = editor_signatures(editor, &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));
|
||||
|
||||
@@ -0,0 +1,510 @@
|
||||
//! Suggest outline (#6020): a bookmark tree proposed for the whole document, for review before
|
||||
//! it is applied. Tagged headings (H, H1–H6) are used when the document has them. Otherwise the
|
||||
//! headings are inferred from how the text looks, by the rules Auto-tag uses
|
||||
//! ([`pdfcraft_a11y::heading_levels`]): lines in one style that follow each other down the page
|
||||
//! are one block (a heading that wraps is one bookmark), the body style is the size carrying the
|
||||
//! most characters, a short block larger than the body (or bold where the body is not) is a
|
||||
//! heading, and levels rank the heading styles over the document without skipping a level.
|
||||
//! Captions (`Figure 3`, `Table 2`) are not headings, nor are bold words inside a sentence. Each
|
||||
//! inferred bookmark goes to the top of its heading as displayed (ISO 32000-2 §12.3.2.2 `/XYZ`);
|
||||
//! tagged ones go to their page.
|
||||
|
||||
use pdfcraft_a11y::TextBlock;
|
||||
use pdfcraft_cos::Document;
|
||||
use pdfcraft_organize::{OutlineEntry, OutlineNode};
|
||||
|
||||
use crate::text_style_bookmarks::{Line, MAX_BOOKMARKS, MAX_TITLE_CHARS, SIZE_TOLERANCE, read_lines};
|
||||
|
||||
/// Blocks looked back over for one a line continues: a heading's next line can come after lines
|
||||
/// of other columns on the same row.
|
||||
const LOOKBACK: usize = 8;
|
||||
/// The deepest a suggested tree nests: bookmark_import takes 33 levels, counting a parent.
|
||||
const MAX_DEPTH: usize = 32;
|
||||
/// How far, in ems, text may sit beside a line and still be in the same sentence: a word space is
|
||||
/// about a quarter of an em and a justified one rarely passes half. A gutter between columns can
|
||||
/// be under an em, so this stays below it.
|
||||
const BESIDE_GAP: f64 = 0.5;
|
||||
/// The most lines looked at on either side of a line for text beside it, which bounds the work on
|
||||
/// a page with many runs on one row.
|
||||
const MAX_BESIDE: usize = 64;
|
||||
|
||||
/// Where the suggested headings come from.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum OutlineSource {
|
||||
/// The structure tree's headings.
|
||||
Structure,
|
||||
/// The size and weight of the text.
|
||||
Layout,
|
||||
}
|
||||
|
||||
/// A suggested outline.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct OutlineSuggestion {
|
||||
pub source: OutlineSource,
|
||||
/// The headings in document order, nested by level (see [`OutlineSuggestion::tree`]).
|
||||
pub entries: Vec<OutlineEntry>,
|
||||
/// Pages in the document.
|
||||
pub pages: usize,
|
||||
/// Pages whose text was read: at most [`MAX_PAGES`](crate::text_style_bookmarks::MAX_PAGES)
|
||||
/// for a suggestion from layout, fewer when a page's text can't be read.
|
||||
pub pages_read: usize,
|
||||
/// Headings may have been left out: pages weren't read, layout found more than
|
||||
/// [`MAX_BOOKMARKS`], or the structure tree ran past a limit of
|
||||
/// [`pdfcraft_a11y::headings_with_truncation`].
|
||||
pub truncated: bool,
|
||||
}
|
||||
|
||||
impl OutlineSuggestion {
|
||||
/// The entries as a bookmark tree, every bookmark expanded: a level-2 entry goes under the
|
||||
/// level-1 entry before it, and so on. Levels deeper than [`MAX_DEPTH`] stay at that depth.
|
||||
pub fn tree(&self) -> Vec<OutlineNode> {
|
||||
nest(&self.entries, &mut 0, 0, 0)
|
||||
}
|
||||
}
|
||||
|
||||
/// The entries from `*at` on that go under a parent of level `above` at `depth` (recursion
|
||||
/// bounded by [`MAX_DEPTH`]); `*at` ends at the first that doesn't.
|
||||
fn nest(entries: &[OutlineEntry], at: &mut usize, above: u8, depth: usize) -> Vec<OutlineNode> {
|
||||
let mut out = Vec::new();
|
||||
while let Some(e) = entries.get(*at) {
|
||||
if depth > 0 && e.level <= above {
|
||||
break;
|
||||
}
|
||||
*at = at.saturating_add(1);
|
||||
let mut n = node(e);
|
||||
if depth.saturating_add(1) < MAX_DEPTH {
|
||||
n.children = nest(entries, at, e.level, depth.saturating_add(1));
|
||||
}
|
||||
out.push(n);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn node(e: &OutlineEntry) -> OutlineNode {
|
||||
let view = (e.left.is_some() || e.top.is_some()).then(|| (b"XYZ".to_vec(), vec![e.left, e.top, None]));
|
||||
OutlineNode { title: e.title.clone(), page: Some(e.page), view, color: None, italic: false, bold: false, open: true, children: Vec::new() }
|
||||
}
|
||||
|
||||
/// The tagged headings as outline entries, each linked to its element (`/SE`), and whether
|
||||
/// headings may be missing ([`pdfcraft_a11y::headings_with_truncation`]).
|
||||
pub(crate) fn structure_entries(doc: &Document) -> (Vec<OutlineEntry>, bool) {
|
||||
let (found, cut) = pdfcraft_a11y::headings_with_truncation(doc);
|
||||
let entries =
|
||||
found.into_iter().map(|h| OutlineEntry { level: h.level, title: h.title, page: h.page, element: h.obj, left: None, top: None }).collect();
|
||||
(entries, cut)
|
||||
}
|
||||
|
||||
/// The outline suggested for `doc`: its tagged headings, or else headings inferred from the
|
||||
/// first [`MAX_PAGES`](crate::text_style_bookmarks::MAX_PAGES) pages' text. Empty when neither
|
||||
/// finds a heading.
|
||||
pub fn suggest(doc: &Document) -> OutlineSuggestion {
|
||||
let pages = pdfcraft_organize::page_count(doc).unwrap_or(0);
|
||||
let (tagged, cut) = structure_entries(doc);
|
||||
if !tagged.is_empty() {
|
||||
return OutlineSuggestion { source: OutlineSource::Structure, entries: tagged, pages, pages_read: pages, truncated: cut };
|
||||
}
|
||||
let (lines, pages_read) = read_lines(doc);
|
||||
let (entries, capped) = inferred(lines);
|
||||
OutlineSuggestion { source: OutlineSource::Layout, entries, pages, pages_read, truncated: cut || capped || pages_read < pages }
|
||||
}
|
||||
|
||||
/// Lines in one style, one after another down a page.
|
||||
struct Block {
|
||||
first: Line,
|
||||
last: Line,
|
||||
title: String,
|
||||
lines: usize,
|
||||
chars: usize,
|
||||
letters: bool,
|
||||
/// Whether any of its lines is set inside a sentence ([`set_inline`]).
|
||||
inline: bool,
|
||||
}
|
||||
|
||||
impl Block {
|
||||
fn new(line: Line, inline: bool) -> Block {
|
||||
let mut b = Block { first: line.clone(), last: line, title: String::new(), lines: 0, chars: 0, letters: false, inline };
|
||||
b.count(&b.first.text.clone());
|
||||
b
|
||||
}
|
||||
|
||||
fn add(&mut self, line: Line, inline: bool) {
|
||||
self.inline |= inline;
|
||||
if self.title.chars().count() < MAX_TITLE_CHARS {
|
||||
self.title.push(' ');
|
||||
}
|
||||
self.count(&line.text);
|
||||
self.last = line;
|
||||
}
|
||||
|
||||
fn count(&mut self, text: &str) {
|
||||
self.lines = self.lines.saturating_add(1);
|
||||
self.chars = self.chars.saturating_add(text.chars().filter(|c| !c.is_whitespace()).count());
|
||||
self.letters |= text.chars().any(char::is_alphabetic);
|
||||
let room = MAX_TITLE_CHARS.saturating_sub(self.title.chars().count());
|
||||
self.title.extend(text.chars().take(room));
|
||||
}
|
||||
|
||||
/// What the heading rules see. A block set inside a sentence still counts toward the body
|
||||
/// style, since it is the paragraph's text, but is never a heading: the rules take no block
|
||||
/// without letters as one.
|
||||
fn evidence(&self) -> TextBlock {
|
||||
let s = &self.first.style;
|
||||
TextBlock { size: s.size, bold: s.bold, lines: self.lines, chars: self.chars, letters: self.letters && !self.inline }
|
||||
}
|
||||
}
|
||||
|
||||
/// `lines`, in reading order, grouped into blocks: a line joins the most recent of the last
|
||||
/// [`LOOKBACK`] blocks in its style that it continues ([`Line::continues`]).
|
||||
fn blocks(lines: Vec<Line>) -> Vec<Block> {
|
||||
let flags = set_inline(&lines);
|
||||
let mut out: Vec<Block> = Vec::new();
|
||||
for (line, inline) in lines.into_iter().zip(flags) {
|
||||
let start = out.len().saturating_sub(LOOKBACK);
|
||||
let found = out.get_mut(start..).and_then(|recent| {
|
||||
recent.iter_mut().rev().find(|b| b.last.page == line.page && b.first.style.matches(&line.style) && line.continues(&b.last))
|
||||
});
|
||||
match found {
|
||||
Some(b) => b.add(line, inline),
|
||||
None => out.push(Block::new(line, inline)),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// For each of `lines` (in reading order), whether it is set inside a sentence: prose in another
|
||||
/// style, no smaller than it, sits right beside it on its row. A bold word in a paragraph (a
|
||||
/// requirement keyword, a defined term) is emphasis, not a heading. Text beside it is prose only
|
||||
/// when it has a lower-case letter, so a section number set apart from its bold title (`2.3`)
|
||||
/// leaves the title a heading.
|
||||
fn set_inline(lines: &[Line]) -> Vec<bool> {
|
||||
lines
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, l)| {
|
||||
// Lines are sorted down each page, so those on its row are next to it.
|
||||
let near = |o: &&Line| o.page == l.page && (o.top - l.top).abs() < l.style.size;
|
||||
let before = lines.get(..i).unwrap_or_default().iter().rev().take(MAX_BESIDE).take_while(near);
|
||||
let after = lines.get(i.saturating_add(1)..).unwrap_or_default().iter().take(MAX_BESIDE).take_while(near);
|
||||
before.chain(after).any(|o| beside(l, o))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Whether prose `o` sits beside `l` in the same sentence: on the same row (their boxes share at
|
||||
/// least half the shorter one's height, since a box runs from the font's ascent to its descent
|
||||
/// and tight leading makes stacked lines' boxes touch), side by side rather than one over the
|
||||
/// other, no smaller than `l`, in another style, at most [`BESIDE_GAP`] ems apart. A heading set
|
||||
/// beside text more than [`SIZE_TOLERANCE`] smaller is still a heading; a word set smaller than
|
||||
/// the prose around it is not. Prose whose box spans `l` on its row also counts: a producer may
|
||||
/// set a sentence as one run with a gap, and paint the bold word into the gap.
|
||||
fn beside(l: &Line, o: &Line) -> bool {
|
||||
let size = l.style.size;
|
||||
let shared = l.top.min(o.top) - l.bottom.max(o.bottom);
|
||||
let shorter = (l.top - l.bottom).min(o.top - o.bottom);
|
||||
let gap = l.left.max(o.left) - l.right.min(o.right);
|
||||
let spans = o.left <= l.left && l.right <= o.right;
|
||||
shared >= shorter * 0.5
|
||||
&& (spans || gap >= -size * 0.25)
|
||||
&& gap <= size * BESIDE_GAP
|
||||
&& size <= o.style.size + SIZE_TOLERANCE
|
||||
&& !o.style.matches(&l.style)
|
||||
&& o.text.chars().any(char::is_lowercase)
|
||||
}
|
||||
|
||||
/// A caption's lead in any case: `Figure`, `Fig.`, `Table`, `Chart`, `Exhibit` or `Plate`, then a
|
||||
/// number.
|
||||
fn is_caption(text: &str) -> bool {
|
||||
let t = text.trim_start();
|
||||
["Figure", "Fig.", "Table", "Chart", "Exhibit", "Plate"].iter().any(|lead| {
|
||||
let rest = t.get(..lead.len()).filter(|head| head.eq_ignore_ascii_case(lead)).and_then(|_| t.get(lead.len()..));
|
||||
rest.is_some_and(|rest| rest.trim_start().chars().next().is_some_and(|c| c.is_ascii_digit()))
|
||||
})
|
||||
}
|
||||
|
||||
/// The headings among `lines`, as outline entries: the first [`MAX_BOOKMARKS`], and whether there
|
||||
/// were more.
|
||||
fn inferred(lines: Vec<Line>) -> (Vec<OutlineEntry>, bool) {
|
||||
let blocks: Vec<Block> = blocks(lines).into_iter().filter(|b| !is_caption(&b.title)).collect();
|
||||
let evidence: Vec<TextBlock> = blocks.iter().map(Block::evidence).collect();
|
||||
let mut entries: Vec<OutlineEntry> = blocks
|
||||
.iter()
|
||||
.zip(pdfcraft_a11y::heading_levels(&evidence))
|
||||
.filter_map(|(b, level)| {
|
||||
let [left, top] = b.first.anchor;
|
||||
Some(OutlineEntry { level: level?, title: b.title.clone(), page: b.first.page, element: None, left, top })
|
||||
})
|
||||
.take(MAX_BOOKMARKS.saturating_add(1))
|
||||
.collect();
|
||||
let capped = entries.len() > MAX_BOOKMARKS;
|
||||
entries.truncate(MAX_BOOKMARKS);
|
||||
(entries, capped)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::text_style_bookmarks::TextStyle;
|
||||
|
||||
/// A line at `top` (its box 0.8 of its size tall) from x 72 to 400.
|
||||
fn line(page: usize, top: f64, size: f64, bold: bool, text: &str) -> Line {
|
||||
let style = TextStyle { font: if bold { "Helvetica-Bold" } else { "Helvetica" }.into(), size, bold, italic: false };
|
||||
Line { page, text: text.into(), style, top, bottom: top - size * 0.8, left: 72.0, right: 400.0, anchor: [None, Some(top)] }
|
||||
}
|
||||
|
||||
fn body(page: usize, top: f64) -> Line {
|
||||
line(page, top, 11.0, false, "Body text that runs on for a good many characters across the page.")
|
||||
}
|
||||
|
||||
fn titles(entries: &[OutlineEntry]) -> Vec<(u8, &str, usize)> {
|
||||
entries.iter().map(|e| (e.level, e.title.as_str(), e.page)).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn headings_take_levels_by_size_and_weight_and_wrapped_lines_join() {
|
||||
let lines = vec![
|
||||
line(0, 760.0, 20.0, true, "Getting started"),
|
||||
line(0, 738.0, 20.0, true, "with the toolkit"),
|
||||
body(0, 700.0),
|
||||
body(0, 686.0),
|
||||
body(0, 672.0),
|
||||
body(0, 658.0),
|
||||
line(0, 630.0, 11.0, true, "Installing"),
|
||||
body(0, 610.0),
|
||||
body(0, 596.0),
|
||||
line(1, 760.0, 20.0, true, "Reference"),
|
||||
body(1, 730.0),
|
||||
body(1, 716.0),
|
||||
];
|
||||
let (found, capped) = inferred(lines);
|
||||
assert!(!capped);
|
||||
assert_eq!(titles(&found), [(1, "Getting started with the toolkit", 0), (2, "Installing", 0), (1, "Reference", 1)]);
|
||||
assert_eq!((found[0].left, found[0].top), (None, Some(760.0)), "a bookmark goes to the top of its first line");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_wrapped_heading_joins_across_a_line_of_another_column() {
|
||||
let mut right = body(0, 760.0);
|
||||
(right.left, right.right) = (420.0, 560.0);
|
||||
let lines = vec![line(0, 760.0, 20.0, true, "Two column"), right, line(0, 738.0, 20.0, true, "heading"), body(0, 700.0), body(0, 686.0)];
|
||||
assert_eq!(titles(&inferred(lines).0), [(1, "Two column heading", 0)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn captions_and_numbers_are_not_headings() {
|
||||
let lines = vec![line(0, 760.0, 16.0, true, "Figure 3: The toolkit"), line(0, 730.0, 16.0, true, "42"), body(0, 700.0), body(0, 686.0)];
|
||||
assert!(inferred(lines).0.is_empty());
|
||||
assert!(is_caption("Table 12 Results") && is_caption("Fig. 2") && !is_caption("Tables are useful"));
|
||||
}
|
||||
|
||||
/// A line of `text` in `style` from `left` to `right` at `top`.
|
||||
fn run(top: f64, bold: bool, text: &str, left: f64, right: f64) -> Line {
|
||||
Line { left, right, ..line(0, top, 11.0, bold, text) }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bold_word_inside_a_sentence_is_not_a_heading() {
|
||||
let lines = vec![
|
||||
line(0, 760.0, 11.0, true, "MUST"),
|
||||
body(0, 740.0),
|
||||
run(726.0, false, "A recipient", 72.0, 130.0),
|
||||
run(726.0, true, "MUST", 133.0, 165.0),
|
||||
run(726.0, false, "ignore the field.", 168.0, 400.0),
|
||||
body(0, 712.0),
|
||||
run(690.0, false, "2.3", 72.0, 88.0),
|
||||
run(690.0, true, "Numbered title", 96.0, 180.0),
|
||||
body(0, 670.0),
|
||||
body(0, 656.0),
|
||||
];
|
||||
assert_eq!(titles(&inferred(lines).0), [(1, "MUST", 0), (1, "Numbered title", 0)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bold_word_set_smaller_than_its_sentence_is_not_a_heading_but_a_larger_one_is() {
|
||||
let mut small = run(726.0, true, "MUST", 133.0, 163.0);
|
||||
small.style.size = 10.0;
|
||||
small.top = 725.2;
|
||||
small.bottom = small.top - 8.0;
|
||||
let lines = vec![
|
||||
line(0, 760.0, 11.0, true, "MUST"),
|
||||
body(0, 740.0),
|
||||
run(726.0, false, "A recipient", 72.0, 130.0),
|
||||
small,
|
||||
run(726.0, false, "ignore the field.", 166.0, 400.0),
|
||||
body(0, 712.0),
|
||||
Line { left: 72.0, right: 110.0, ..line(0, 690.0, 14.0, true, "Scope") },
|
||||
run(688.8, false, "covers the rest of this page.", 113.0, 400.0),
|
||||
body(0, 670.0),
|
||||
body(0, 656.0),
|
||||
];
|
||||
assert_eq!(titles(&inferred(lines).0), [(1, "MUST", 0), (1, "Scope", 0)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bold_word_painted_into_a_gap_in_one_run_of_prose_is_not_a_heading() {
|
||||
let mut word = run(725.2, true, "MUST", 192.0, 219.0);
|
||||
word.style.size = 10.0;
|
||||
word.bottom = word.top - 8.0;
|
||||
let lines = vec![
|
||||
line(0, 760.0, 11.0, true, "MUST"),
|
||||
body(0, 740.0),
|
||||
run(726.0, false, "A recipient ignore the field.", 72.0, 400.0),
|
||||
word,
|
||||
body(0, 712.0),
|
||||
body(0, 698.0),
|
||||
];
|
||||
assert_eq!(titles(&inferred(lines).0), [(1, "MUST", 0)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_beside_an_italic_word_still_sets_the_body_size() {
|
||||
let italic = |top: f64| {
|
||||
let mut l = run(top, false, "term", 252.0, 275.0);
|
||||
l.style.italic = true;
|
||||
l.style.font = "Helvetica-Oblique".into();
|
||||
l
|
||||
};
|
||||
let mut lines = vec![line(0, 780.0, 14.0, true, "Overview")];
|
||||
for top in [750.0, 736.0, 722.0, 708.0] {
|
||||
lines.extend([
|
||||
run(top, false, "The first part of the row runs to", 72.0, 250.0),
|
||||
italic(top),
|
||||
run(top, false, "and the rest of it follows on.", 277.0, 400.0),
|
||||
]);
|
||||
}
|
||||
assert_eq!(titles(&inferred(lines).0), [(1, "Overview", 0)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_heading_over_tightly_set_text_or_across_a_narrow_gutter_stays_a_heading() {
|
||||
let lines = vec![
|
||||
// Its box overlaps the first body line's by 1.5 pt.
|
||||
run(760.0, true, "Tight heading", 72.0, 180.0),
|
||||
body(0, 752.7),
|
||||
body(0, 740.0),
|
||||
// A gutter of 9 pt, under an em: prose ends the left column on the heading's row.
|
||||
run(700.0, false, "ends the left column here", 72.0, 291.0),
|
||||
run(700.0, true, "Right column heading", 300.0, 520.0),
|
||||
body(0, 686.0),
|
||||
body(0, 672.0),
|
||||
];
|
||||
assert_eq!(titles(&inferred(lines).0), [(1, "Tight heading", 0), (1, "Right column heading", 0)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn captions_match_in_any_case() {
|
||||
let lines = vec![line(0, 760.0, 16.0, true, "FIGURE 3: Architecture"), body(0, 700.0), body(0, 686.0)];
|
||||
assert!(inferred(lines).0.is_empty(), "an upper-case caption was suggested as a heading");
|
||||
assert!(is_caption("table 2") && is_caption("FIG. 4") && !is_caption("TABLES are useful") && !is_caption("Figé 3"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn more_headings_than_the_cap_are_reported() {
|
||||
// Each heading on a page of its own, with a line of body text under it.
|
||||
let pages = |n: usize| (0..n).flat_map(|p| [line(p, 760.0, 20.0, true, "Heading"), body(p, 700.0)]).collect::<Vec<_>>();
|
||||
let (at_cap, capped) = inferred(pages(MAX_BOOKMARKS));
|
||||
assert_eq!((at_cap.len(), capped), (MAX_BOOKMARKS, false));
|
||||
let (over, capped) = inferred(pages(MAX_BOOKMARKS + 1));
|
||||
assert_eq!((over.len(), capped), (MAX_BOOKMARKS, true), "a heading past the cap was dropped unreported");
|
||||
}
|
||||
|
||||
/// A page past the page decode allowance (two compressed streams of spaces, each just over
|
||||
/// half of it) can't be read: it doesn't count as read, and the suggestion says headings
|
||||
/// may be missing.
|
||||
#[test]
|
||||
fn a_page_whose_text_cant_be_read_is_not_counted() {
|
||||
let packed = pdfcraft_filters::encode_flate(&vec![b' '; pdfcraft_cos::MAX_PAGE_DECODED / 2 + 1]);
|
||||
let stream = |dict: &str, data: &[u8]| [format!("<< /Length {} {dict} >>\nstream\n", data.len()).as_bytes(), data, b"\nendstream"].concat();
|
||||
let objs: Vec<Vec<u8>> = vec![
|
||||
b"<< /Type /Catalog /Pages 2 0 R >>".to_vec(),
|
||||
b"<< /Type /Pages /Kids [3 0 R 4 0 R] /Count 2 /MediaBox [0 0 612 792] /Resources << /Font << /F 7 0 R >> >> >>".to_vec(),
|
||||
b"<< /Type /Page /Parent 2 0 R /Contents 5 0 R >>".to_vec(),
|
||||
b"<< /Type /Page /Parent 2 0 R /Contents [6 0 R 6 0 R] >>".to_vec(),
|
||||
stream("", b"BT /F 11 Tf 72 700 Td (Body) Tj ET"),
|
||||
stream("/Filter /FlateDecode", &packed),
|
||||
b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>".to_vec(),
|
||||
];
|
||||
let s = suggest(&doc_of(&objs));
|
||||
assert_eq!((s.pages, s.pages_read, s.truncated), (2, 1, true), "the unread page counted as read");
|
||||
}
|
||||
|
||||
/// A PDF of these objects (object n = `objs[n - 1]`), the first the catalog.
|
||||
fn doc_of(objs: &[Vec<u8>]) -> Document {
|
||||
let mut bytes = b"%PDF-1.7\n".to_vec();
|
||||
let mut offsets = Vec::new();
|
||||
for (i, o) in objs.iter().enumerate() {
|
||||
offsets.push(bytes.len());
|
||||
bytes.extend_from_slice(&[format!("{} 0 obj\n", i + 1).as_bytes(), o, b"\nendobj\n"].concat());
|
||||
}
|
||||
let xref = bytes.len();
|
||||
bytes.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objs.len() + 1).as_bytes());
|
||||
for o in offsets {
|
||||
bytes.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes());
|
||||
}
|
||||
bytes.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objs.len() + 1).as_bytes());
|
||||
Document::open(std::sync::Arc::new(bytes)).unwrap()
|
||||
}
|
||||
|
||||
/// More tagged headings than the structure reader returns: the suggestion says some are missing.
|
||||
#[test]
|
||||
fn tagged_headings_past_the_cap_are_reported() {
|
||||
let tagged = |count: usize| {
|
||||
let kids: String = (0..count).map(|i| format!("{} 0 R ", i + 6)).collect();
|
||||
let mut objs = vec![
|
||||
b"<< /Type /Catalog /Pages 2 0 R /StructTreeRoot 4 0 R >>".to_vec(),
|
||||
b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_vec(),
|
||||
b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >>".to_vec(),
|
||||
b"<< /Type /StructTreeRoot /K 5 0 R >>".to_vec(),
|
||||
format!("<< /S /Document /K [{kids}] >>").into_bytes(),
|
||||
];
|
||||
objs.extend((0..count).map(|_| b"<< /S /H1 /Pg 3 0 R /ActualText (Head) >>".to_vec()));
|
||||
suggest(&doc_of(&objs))
|
||||
};
|
||||
let cap = pdfcraft_a11y::MAX_HEADINGS;
|
||||
let at_cap = tagged(cap);
|
||||
assert_eq!((at_cap.source, at_cap.entries.len(), at_cap.truncated), (OutlineSource::Structure, cap, false));
|
||||
let over = tagged(cap + 1);
|
||||
assert_eq!((over.entries.len(), over.truncated), (cap, true), "a tagged heading past the cap was dropped unreported");
|
||||
}
|
||||
|
||||
/// A tagged heading too deep for the structure walk, on a page without text: layout finds
|
||||
/// nothing either, and the suggestion still says a heading may be missing. The same page
|
||||
/// untagged is not truncated.
|
||||
#[test]
|
||||
fn a_tagged_heading_past_the_depth_limit_is_reported_from_layout() {
|
||||
let mut objs = vec![
|
||||
b"<< /Type /Catalog /Pages 2 0 R /StructTreeRoot 4 0 R >>".to_vec(),
|
||||
b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_vec(),
|
||||
b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >>".to_vec(),
|
||||
b"<< /Type /StructTreeRoot /K 5 0 R >>".to_vec(),
|
||||
];
|
||||
objs.extend((5..305).map(|n| format!("<< /S /Sect /K {} 0 R >>", n + 1).into_bytes()));
|
||||
objs.push(b"<< /S /H1 /Pg 3 0 R /ActualText (Deep) >>".to_vec());
|
||||
let s = suggest(&doc_of(&objs));
|
||||
assert_eq!((s.source, s.entries.len(), s.truncated), (OutlineSource::Layout, 0, true), "the structure walk's cut was dropped");
|
||||
objs[0] = b"<< /Type /Catalog /Pages 2 0 R >>".to_vec();
|
||||
let s = suggest(&doc_of(&objs));
|
||||
assert_eq!((s.entries.len(), s.pages_read, s.truncated), (0, 1, false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_tree_nests_by_level_and_caps_the_depth() {
|
||||
let entry = |level: u8, title: &str| OutlineEntry { level, title: title.into(), page: 0, element: None, left: None, top: Some(700.0) };
|
||||
let mut entries = vec![entry(1, "A"), entry(2, "A.1"), entry(3, "A.1.a"), entry(2, "A.2"), entry(1, "B")];
|
||||
let s = OutlineSuggestion { source: OutlineSource::Layout, entries: entries.clone(), pages: 1, pages_read: 1, truncated: false };
|
||||
let tree = s.tree();
|
||||
assert_eq!(tree.iter().map(|n| n.title.as_str()).collect::<Vec<_>>(), ["A", "B"]);
|
||||
assert_eq!(tree[0].children.iter().map(|n| n.title.as_str()).collect::<Vec<_>>(), ["A.1", "A.2"]);
|
||||
assert_eq!(tree[0].children[0].children[0].title, "A.1.a");
|
||||
assert_eq!(tree[0].view, Some((b"XYZ".to_vec(), vec![None, Some(700.0), None])));
|
||||
// A tagged H nested in 40 sections stops at the deepest level bookmark_import takes.
|
||||
entries = (1..=40).map(|l| entry(l, "deep")).collect();
|
||||
let deep = OutlineSuggestion { entries, ..s }.tree();
|
||||
let mut depth = 0;
|
||||
let mut at = &deep;
|
||||
while let Some(n) = at.first() {
|
||||
depth += 1;
|
||||
at = &n.children;
|
||||
}
|
||||
assert_eq!(depth, MAX_DEPTH);
|
||||
}
|
||||
}
|
||||
+517
-17
@@ -5,6 +5,8 @@ use super::edit::{EditCtx, check_permission, run_edit};
|
||||
use super::*;
|
||||
use pdfcraft_render::{Layer, LayerOp, OpenError, ReadingColors};
|
||||
|
||||
mod print_marks;
|
||||
|
||||
/// A minimal `n`-page document; page `i` shows "Page i+1".
|
||||
pub(crate) fn fixture(n: usize) -> Vec<u8> {
|
||||
let mut objs: Vec<Vec<u8>> = vec![b"<< /Type /Catalog /Pages 2 0 R >>".to_vec()];
|
||||
@@ -7500,6 +7502,38 @@ fn active_xfa_does_not_run_pdf_container_scripts_but_keeps_requested_alerts() {
|
||||
assert!(s.run_javascript(id, "", None).unwrap().alerts.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn take_js_errors_leaves_the_alerts_for_take_js_output() {
|
||||
let template = pdfcraft_xfa::fixtures::scripted_template()
|
||||
.replace("if (qty.rawValue === null) qty.rawValue = 2;", "qty.rawValue = 2; xfa.host.messageBox('opened'); throw new Error('open failed');");
|
||||
// Raised time limits: a busy machine does not stop the scripts this checks.
|
||||
let mut s = Session::new().with_xfa_time_scale(100);
|
||||
let id = s.open("xfa.pdf", None, Arc::new(pdfcraft_xfa::fixtures::shell(&template)), None).unwrap();
|
||||
let errors = s.take_js_errors(id);
|
||||
assert!(errors.iter().any(|e| e.contains("open failed")), "{errors:?}");
|
||||
assert!(s.take_js_errors(id).is_empty());
|
||||
let out = s.take_js_output(id);
|
||||
assert!(out.errors.is_empty(), "{out:?}");
|
||||
assert_eq!(out.alerts, [js::Message::plain("opened")]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn take_js_errors_reports_a_document_scripts_error_again_on_the_next_edit() {
|
||||
let helpers = "function times\\(a, b\\) { return a * b; } this.getField\\('go'\\).missingTestMethod\\(\\);";
|
||||
let mut s = Session::new().with_clock(|| 1_700_000_000);
|
||||
let id = s.open("order.pdf", None, Arc::new(scripted_form_with(helpers)), None).unwrap();
|
||||
assert_eq!(s.take_js_errors(id).len(), 1, "the document script fails at open");
|
||||
// The document scripts run again when the script list changes, which each pass does.
|
||||
for qty in ["4", "5"] {
|
||||
let script = format!("/* {qty} */ function times(a, b) {{ return a * b; }} this.getField('go').missingTestMethod();");
|
||||
s.apply(id, Edit::SetDocumentScript { name: "helpers".into(), script: Some(script) }).unwrap();
|
||||
s.apply(id, Edit::SetFieldValue { name: "qty".into(), value: FieldValue::Text(qty.into()) }).unwrap();
|
||||
let errors = s.take_js_errors(id);
|
||||
assert_eq!(errors.len(), 1, "qty {qty}: {errors:?}");
|
||||
assert!(errors[0].starts_with("document script 1: TypeError"), "qty {qty}: {errors:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn active_xfa_without_template_scripts_does_not_initialize_pdf_fallback_scripts() {
|
||||
let template = r#"<template xmlns="http://www.xfa.org/schema/xfa-template/3.3/">
|
||||
@@ -8320,8 +8354,9 @@ fn on_changes_notes_only_the_exits_that_ran() {
|
||||
highlight: false,
|
||||
time_scale: 1,
|
||||
answers: Default::default(),
|
||||
relaid: false,
|
||||
};
|
||||
crate::xfa::on_changes(&mut cos, &tpl, &names, &mut stopped, &mut exited).unwrap();
|
||||
crate::xfa::on_changes(&mut cos, &tpl, &names, &Default::default(), &mut stopped, &mut exited).unwrap();
|
||||
assert!(exited.is_empty(), "no exit ran: {exited:?}");
|
||||
let mut out = crate::js::JsOutput::default();
|
||||
let mut running = crate::xfa::XfaRun {
|
||||
@@ -8332,8 +8367,9 @@ fn on_changes_notes_only_the_exits_that_ran() {
|
||||
highlight: false,
|
||||
time_scale: 1,
|
||||
answers: Default::default(),
|
||||
relaid: false,
|
||||
};
|
||||
crate::xfa::on_changes(&mut cos, &tpl, &names, &mut running, &mut exited).unwrap();
|
||||
crate::xfa::on_changes(&mut cos, &tpl, &names, &Default::default(), &mut running, &mut exited).unwrap();
|
||||
assert_eq!(exited.len(), 1, "the exit ran: {exited:?}");
|
||||
}
|
||||
|
||||
@@ -8371,8 +8407,8 @@ fn a_widget_the_field_doesnt_have_runs_no_focus_scripts() {
|
||||
|
||||
/// Each radio button of a group is a field of its own: reaching the second button runs its
|
||||
/// enter script, reaching the first (which has none) runs nothing. Choosing the button changes
|
||||
/// the group's value, which runs the group's scripts, not the button's: leaving the button
|
||||
/// still runs its exit.
|
||||
/// the group's value, which runs the group's scripts and the new button's (its exit among them,
|
||||
/// as when leaving it), so leaving the button does not run that exit a second time.
|
||||
#[test]
|
||||
fn a_radio_buttons_own_focus_scripts_run() {
|
||||
use crate::js::FieldFocus::{Enter, Exit};
|
||||
@@ -8384,7 +8420,8 @@ fn a_radio_buttons_own_focus_scripts_run() {
|
||||
assert!(!s.field_focus(id, &group, 2, Enter).unwrap(), "there is no third button");
|
||||
assert_eq!(field_text(&s, id, "picks"), "1");
|
||||
s.apply(id, Edit::SetFieldValue { name: group.clone(), value: FieldValue::Radio(Some("L".into())) }).unwrap();
|
||||
assert!(s.field_focus(id, &group, 1, Exit).unwrap(), "the button's exit runs on leaving it");
|
||||
assert_eq!(field_text(&s, id, "drops"), "1", "the click ran the button's exit");
|
||||
assert!(!s.field_focus(id, &group, 1, Exit).unwrap(), "that exit is not run again on leaving");
|
||||
assert_eq!(field_text(&s, id, "drops"), "1");
|
||||
}
|
||||
|
||||
@@ -8569,6 +8606,8 @@ fn an_xfa_form_without_a_template_opens_with_its_placeholder_and_a_warning() {
|
||||
assert!(doc.info.warnings.iter().any(|w| w.contains("could not be laid out") && w.contains("no template")), "{:?}", doc.info.warnings);
|
||||
}
|
||||
|
||||
/// A dynamic form opens laid out with the values its datasets hold, and with the rows its data
|
||||
/// adds to a repeating table row.
|
||||
#[test]
|
||||
fn dynamic_xfa_forms_open_with_the_values_and_rows_of_their_data() {
|
||||
let data = "<form><head><familyName>Kaur</familyName><born>2001-02-03</born><answer>Y</answer></head><table><row><what0>a</what0></row><row><what0>b</what0></row><row><what0>c</what0></row></table></form>";
|
||||
@@ -8584,6 +8623,29 @@ fn dynamic_xfa_forms_open_with_the_values_and_rows_of_their_data() {
|
||||
assert!(!doc.dirty);
|
||||
}
|
||||
|
||||
/// A dynamic form a viewer saved with its pages drawn holds only its signature box, so it opened as
|
||||
/// a picture with nothing to fill in. When its configuration says it must be rendered dynamically
|
||||
/// it is laid out from its template on opening, and its text field can be filled; once signed, it
|
||||
/// opens as saved, its pages and signature untouched.
|
||||
#[test]
|
||||
fn a_form_saved_with_its_pages_that_requires_dynamic_rendering_is_laid_out_unless_signed() {
|
||||
let mut s = Session::new().with_clock(|| 1_700_000_000);
|
||||
let unsigned = Arc::new(pdfcraft_xfa::fixtures::saved_with_pages_shell("required", false));
|
||||
let id = s.open("saved.pdf", None, unsigned, None).expect("opens");
|
||||
let doc = s.get(id).unwrap();
|
||||
assert_eq!(doc.info.xfa, Some(pdfcraft_render::Xfa::Dynamic));
|
||||
assert!(doc.xfa.is_some(), "laid out from the template");
|
||||
let name = doc.form.iter().find(|f| f.name.contains("name")).map(|f| f.name.clone()).expect("the template's text field");
|
||||
s.apply(id, Edit::SetFieldValue { name: name.clone(), value: FieldValue::Text("Ada".into()) }).expect("fills");
|
||||
assert_eq!(s.get(id).unwrap().form.iter().find(|f| f.name == name).map(|f| f.value.clone()), Some(vec!["Ada".to_string()]));
|
||||
let signed = Arc::new(pdfcraft_xfa::fixtures::saved_with_pages_shell("required", true));
|
||||
let id = s.open("signed.pdf", None, signed.clone(), None).expect("opens");
|
||||
let doc = s.get(id).unwrap();
|
||||
assert_eq!(doc.info.xfa, Some(pdfcraft_render::Xfa::Static), "signed: as saved");
|
||||
assert!(doc.xfa.is_none(), "nothing was laid out");
|
||||
assert_eq!(doc.bytes[..], signed[..], "no revision was appended on open");
|
||||
}
|
||||
|
||||
/// #3180: an XFA form with no fields whose configuration says `dynamicRender` is `forbidden` is a
|
||||
/// static form: its pages are the form. Opening it used to lay the template out into new pages
|
||||
/// and write them as a revision, so even a save with no change replaced the pages.
|
||||
@@ -9133,6 +9195,58 @@ fn xfa_data_import_on_a_static_form_replaces_every_value_and_pictures_reach_its_
|
||||
assert!(xml.contains("<name>Bob</name>") && !xml.contains("<agree>1</agree>"), "{xml}");
|
||||
}
|
||||
|
||||
/// A click on an XFA check box or radio button runs its change scripts, then its click scripts,
|
||||
/// which read the new value, show messages and may ask for the focus; a radio group's run before
|
||||
/// those of the button now on. All as one undo step. A text field's click script doesn't run when
|
||||
/// its value changes.
|
||||
#[test]
|
||||
fn xfa_check_box_and_radio_button_clicks_run_their_click_scripts() {
|
||||
let bytes = Arc::new(pdfcraft_xfa::fixtures::shell(&pdfcraft_xfa::fixtures::toggle_template()));
|
||||
let mut s = Session::new();
|
||||
let id = s.open("toggle.pdf", None, bytes, None).expect("opens");
|
||||
// What the scripts have written to the form's log field so far.
|
||||
let log = |s: &Session| s.get(id).unwrap().form.iter().find(|f| f.name == "log").and_then(|f| f.value.first().cloned()).unwrap_or_default();
|
||||
s.apply(id, Edit::SetFieldValue { name: "agree".into(), value: FieldValue::Check(true) }).unwrap();
|
||||
assert_eq!(log(&s), "change 1;click 1;", "change, then click, each seeing the new value");
|
||||
let out = s.take_js_output(id);
|
||||
assert_eq!(out.alerts, [crate::js::Message::plain("Agreed")]);
|
||||
assert!(
|
||||
out.requests.iter().any(|r| matches!(r, pdfcraft_js::Request::FocusField { name, .. } if name == "note")),
|
||||
"a click may move the focus: {out:?}"
|
||||
);
|
||||
s.apply(id, Edit::SetFieldValue { name: "agree".into(), value: FieldValue::Check(false) }).unwrap();
|
||||
assert_eq!(log(&s), "change 1;click 1;change 0;click 0;", "turning it off is a click too");
|
||||
// One undo step takes back the click and what its scripts did.
|
||||
s.undo(id).unwrap();
|
||||
assert_eq!(log(&s), "change 1;click 1;");
|
||||
// A radio group runs each activity's scripts, then the button now on runs its own; the
|
||||
// button turned off runs none. Exit scripts follow, the button's first.
|
||||
let state = |s: &Session, i: usize| s.get(id).unwrap().form.iter().find(|f| f.name == "answer").and_then(|f| f.widgets.get(i)?.on_state.clone());
|
||||
let (yes, no) = (state(&s, 0).expect("yes"), state(&s, 1).expect("no"));
|
||||
s.apply(id, Edit::SetFieldValue { name: "answer".into(), value: FieldValue::Radio(Some(no)) }).unwrap();
|
||||
assert!(log(&s).ends_with("group change N;no change;group click;no click;no exit;group exit;"), "{}", log(&s));
|
||||
s.apply(id, Edit::SetFieldValue { name: "answer".into(), value: FieldValue::Radio(Some(yes)) }).unwrap();
|
||||
assert!(log(&s).ends_with("no exit;group exit;group change Y;yes change;group click;yes click;yes exit;group exit;"), "{}", log(&s));
|
||||
// A text field's value isn't set by a click.
|
||||
s.apply(id, Edit::SetFieldValue { name: "note".into(), value: FieldValue::Text("typed".into()) }).unwrap();
|
||||
assert!(!log(&s).contains("note click"), "{}", log(&s));
|
||||
// A value set again, unchanged, isn't a click: no click script, no message or request.
|
||||
let _ = s.take_js_output(id);
|
||||
let seen = log(&s);
|
||||
s.apply(id, Edit::SetFieldValue { name: "agree".into(), value: FieldValue::Check(true) }).unwrap();
|
||||
s.apply(id, Edit::SetFieldValue { name: "answer".into(), value: FieldValue::Radio(Some(state(&s, 0).unwrap())) }).unwrap();
|
||||
let after = log(&s);
|
||||
assert!(!after.get(seen.len()..).unwrap_or_default().contains("click"), "{after}");
|
||||
let out = s.take_js_output(id);
|
||||
assert!(out.alerts.is_empty() && out.requests.is_empty(), "{out:?}");
|
||||
// A batch that turns the check box off twice clicks it once: the second set changes nothing.
|
||||
let off = || Edit::SetFieldValue { name: "agree".into(), value: FieldValue::Check(false) };
|
||||
let seen = log(&s);
|
||||
s.apply(id, Edit::Batch { label: "twice".into(), edits: vec![off(), off()] }).unwrap();
|
||||
let after = log(&s);
|
||||
assert_eq!(after.get(seen.len()..).unwrap_or_default().matches("click 0;").count(), 1, "{after}");
|
||||
}
|
||||
|
||||
/// Importing data into a dynamic form adds and removes the rows of its repeating subform to
|
||||
/// match, and the calculations over them run again.
|
||||
#[test]
|
||||
@@ -9405,6 +9519,204 @@ fn filling_growable_xfa_text_reflows_and_undo_restores_the_layout() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Typing text that makes a growable field take another page lays the form out again, and its
|
||||
/// layout:ready scripts run again, reading the new page count.
|
||||
#[test]
|
||||
fn layout_ready_scripts_run_again_after_text_grows_the_form() {
|
||||
let template = pdfcraft_xfa::fixtures::growable_text_template(false).replacen(
|
||||
"<pageSet>",
|
||||
r#"<event activity="ready" ref="$layout"><script contentType="application/x-javascript">xfa.form.form.pages.rawValue = String(xfa.layout.pageCount());</script></event><field name="pages" w="1in" h="0.3in"><ui><textEdit/></ui></field><pageSet>"#,
|
||||
1,
|
||||
);
|
||||
let text: String = (0..150).map(|i| format!("Row{i:03} {}sample\n", "sample ".repeat(8))).collect();
|
||||
let mut s = Session::new();
|
||||
let id = s.open("growing.pdf", None, Arc::new(pdfcraft_xfa::fixtures::shell(&template)), None).unwrap();
|
||||
let pages = |s: &Session| s.get(id).unwrap().form.iter().find(|f| f.name == "pages").map(|f| f.value.clone()).unwrap_or_default();
|
||||
let before = s.get(id).unwrap().info.pages.len();
|
||||
assert_eq!(pages(&s), vec![before.to_string()]);
|
||||
s.apply(id, Edit::SetFieldValue { name: "ACTIVIDADES".into(), value: FieldValue::Text(text) }).unwrap();
|
||||
let after = s.get(id).unwrap().info.pages.len();
|
||||
assert_eq!(after, before + 1, "the text takes another page");
|
||||
assert_eq!(pages(&s), vec![after.to_string()], "layout:ready read the new page count");
|
||||
}
|
||||
|
||||
/// An edit whose change script runs away runs no more of the form's scripts, even when its text
|
||||
/// lays the form out again: the layout:ready scripts that a new layout runs wait, and the scripts
|
||||
/// turn off once the edit is done.
|
||||
#[test]
|
||||
fn a_new_layout_after_a_runaway_change_script_runs_no_layout_ready_scripts() {
|
||||
let template = pdfcraft_xfa::fixtures::growable_text_template(false)
|
||||
.replacen(
|
||||
"<pageSet>",
|
||||
r#"<event activity="ready" ref="$layout"><script contentType="application/x-javascript">xfa.form.form.log.rawValue = (xfa.form.form.log.rawValue || "") + "L";</script></event><field name="log" w="1in" h="0.3in"><ui><textEdit/></ui></field><pageSet>"#,
|
||||
1,
|
||||
)
|
||||
.replacen(
|
||||
r#"<field name="ACTIVIDADES" w="540pt" minH="207.017mm">"#,
|
||||
r#"<field name="ACTIVIDADES" w="540pt" minH="207.017mm"><event activity="exit"><script contentType="application/x-javascript">function f() { for (var j = 0; j < 99999; j++) {} } for (var k = 0; k < 5000; k++) f();</script></event>"#,
|
||||
1,
|
||||
);
|
||||
let text: String = (0..150).map(|i| format!("Row{i:03} {}sample\n", "sample ".repeat(8))).collect();
|
||||
let mut s = Session::new();
|
||||
let id = s.open("growing.pdf", None, Arc::new(pdfcraft_xfa::fixtures::shell(&template)), None).unwrap();
|
||||
let log = |s: &Session| s.get(id).unwrap().form.iter().find(|f| f.name == "log").map(|f| f.value.clone()).unwrap_or_default();
|
||||
assert_eq!(log(&s), vec!["L".to_string()], "layout:ready ran once on opening");
|
||||
let before = s.get(id).unwrap().info.pages.len();
|
||||
s.apply(id, Edit::SetFieldValue { name: "ACTIVIDADES".into(), value: FieldValue::Text(text) }).unwrap();
|
||||
assert_eq!(s.get(id).unwrap().info.pages.len(), before + 1, "the text still takes another page");
|
||||
let out = s.take_js_output(id);
|
||||
assert!(out.errors.iter().any(|e| e.contains("abandoned")), "{:?}", out.errors);
|
||||
assert!(s.get(id).unwrap().xfa_scripts_off());
|
||||
assert_eq!(log(&s), vec!["L".to_string()], "no layout:ready run after the runaway");
|
||||
}
|
||||
|
||||
/// What the last edit (the top of the undo stack) said it changed.
|
||||
fn last_scope(s: &Session, id: DocId) -> crate::history::Scope {
|
||||
s.get(id).unwrap().editor.as_ref().unwrap().undo.last().unwrap().3
|
||||
}
|
||||
|
||||
/// The view's entry for field `name`: its page index and first widget's rectangle.
|
||||
fn field_place(s: &Session, id: DocId, name: &str) -> (Option<usize>, Option<[f32; 4]>) {
|
||||
let f = s.get(id).unwrap().info.fields.iter().find(|f| f.name == name).unwrap_or_else(|| panic!("no field {name}")).clone();
|
||||
(f.page, f.rect)
|
||||
}
|
||||
|
||||
/// Bytes that save and reopen as the document the session shows (the save check of #1698).
|
||||
fn saves_and_reopens(s: &mut Session, id: DocId, pages: usize) {
|
||||
let bytes = s.save_bytes(id).unwrap();
|
||||
s.check_save(id, &bytes).unwrap();
|
||||
let again = s.open("saved.pdf", None, bytes, None).unwrap();
|
||||
assert_eq!(s.get(again).unwrap().info.pages.len(), pages);
|
||||
s.close(again);
|
||||
}
|
||||
|
||||
/// A check box's change script that shows a hidden section lays the form out onto a second
|
||||
/// page: the view's pages and fields are rebuilt, the file saves and reopens, undo and redo
|
||||
/// rebuild them too, and hiding the section again takes the page away.
|
||||
#[test]
|
||||
fn an_xfa_script_that_shows_a_section_adds_its_page_and_undo_takes_it_away() {
|
||||
let template = pdfcraft_xfa::fixtures::presence_growth_template(false, "", "", "");
|
||||
let mut s = Session::new().with_clock(|| 1_700_000_000);
|
||||
let id = s.open("grow.pdf", None, Arc::new(pdfcraft_xfa::fixtures::shell(&template)), None).unwrap();
|
||||
let pages = |s: &Session| s.get(id).unwrap().info.pages.len();
|
||||
let fields = |s: &Session| s.get(id).unwrap().info.fields.len();
|
||||
assert_eq!(pages(&s), 1);
|
||||
let before = fields(&s);
|
||||
assert!(s.get(id).unwrap().info.fields.iter().all(|f| f.name != "d1"), "a hidden section has no widgets");
|
||||
s.apply(id, Edit::SetFieldValue { name: "more".into(), value: FieldValue::Check(true) }).unwrap();
|
||||
let out = s.take_js_output(id);
|
||||
assert_eq!(pages(&s), 2, "{:?}", out.errors);
|
||||
assert_eq!(last_scope(&s, id), crate::history::Scope::Full);
|
||||
assert_eq!(fields(&s), s.get(id).unwrap().form.len(), "the field list is the form's");
|
||||
assert!(fields(&s) > before);
|
||||
for name in ["d1", "d2"] {
|
||||
let (page, rect) = field_place(&s, id, name);
|
||||
assert_eq!(page, Some(1), "{name}");
|
||||
assert!(rect.is_some(), "{name}");
|
||||
}
|
||||
saves_and_reopens(&mut s, id, 2);
|
||||
// A value typed into the new section lays nothing out: only the values are refreshed.
|
||||
s.apply(id, Edit::SetFieldValue { name: "d1".into(), value: FieldValue::Text("typed".into()) }).unwrap();
|
||||
assert_eq!(last_scope(&s, id), crate::history::Scope::Form);
|
||||
assert_eq!(pages(&s), 2);
|
||||
s.undo(id).unwrap();
|
||||
s.undo(id).unwrap();
|
||||
assert_eq!(pages(&s), 1);
|
||||
assert_eq!(fields(&s), before);
|
||||
saves_and_reopens(&mut s, id, 1);
|
||||
s.redo(id).unwrap();
|
||||
assert_eq!(pages(&s), 2);
|
||||
assert_eq!(field_place(&s, id, "d2").0, Some(1));
|
||||
saves_and_reopens(&mut s, id, 2);
|
||||
// Hidden again: the form shrinks back to one page.
|
||||
s.apply(id, Edit::SetFieldValue { name: "more".into(), value: FieldValue::Check(false) }).unwrap();
|
||||
assert_eq!(pages(&s), 1);
|
||||
assert_eq!(fields(&s), before);
|
||||
saves_and_reopens(&mut s, id, 1);
|
||||
}
|
||||
|
||||
/// A relayout that keeps the page count still replaces the pages: a field the shown section
|
||||
/// pushes onto the second page is placed there in the view.
|
||||
#[test]
|
||||
fn an_xfa_script_relayout_that_keeps_the_page_count_moves_fields_in_the_view() {
|
||||
let after = r#"<field name="late" w="3in" h="0.5in"><ui><textEdit/></ui></field><draw name="tail" w="7.5in" h="2in"><value><text>Tail</text></value></draw>"#;
|
||||
let template = pdfcraft_xfa::fixtures::presence_growth_template(false, "", after, "");
|
||||
let mut s = Session::new().with_clock(|| 1_700_000_000);
|
||||
let id = s.open("moves.pdf", None, Arc::new(pdfcraft_xfa::fixtures::shell(&template)), None).unwrap();
|
||||
assert_eq!(s.get(id).unwrap().info.pages.len(), 2);
|
||||
assert_eq!(field_place(&s, id, "late").0, Some(0));
|
||||
s.apply(id, Edit::SetFieldValue { name: "more".into(), value: FieldValue::Check(true) }).unwrap();
|
||||
assert_eq!(s.get(id).unwrap().info.pages.len(), 2, "{:?}", s.take_js_output(id).errors);
|
||||
let (page, rect) = field_place(&s, id, "late");
|
||||
assert_eq!(page, Some(1));
|
||||
let widget = s.get(id).unwrap().form.iter().find(|f| f.name == "late").unwrap().widgets[0].rect;
|
||||
assert_eq!(rect, Some(widget.map(|v| v as f32)), "the view has the new widget's place");
|
||||
s.undo(id).unwrap();
|
||||
assert_eq!(field_place(&s, id, "late").0, Some(0));
|
||||
saves_and_reopens(&mut s, id, 2);
|
||||
}
|
||||
|
||||
/// A reset whose calculations hide the section lays the form out again too.
|
||||
#[test]
|
||||
fn an_xfa_reset_whose_calculations_hide_a_section_takes_its_page_away() {
|
||||
let template = pdfcraft_xfa::fixtures::presence_growth_template(true, "", "", "");
|
||||
let mut s = Session::new().with_clock(|| 1_700_000_000);
|
||||
let id = s.open("reset.pdf", None, Arc::new(pdfcraft_xfa::fixtures::shell(&template)), None).unwrap();
|
||||
assert_eq!(s.get(id).unwrap().info.pages.len(), 1);
|
||||
s.apply(id, Edit::SetFieldValue { name: "more".into(), value: FieldValue::Check(true) }).unwrap();
|
||||
assert_eq!(s.get(id).unwrap().info.pages.len(), 2, "{:?}", s.take_js_output(id).errors);
|
||||
s.apply(id, Edit::ResetForm { names: None }).unwrap();
|
||||
assert_eq!(s.get(id).unwrap().info.pages.len(), 1, "{:?}", s.take_js_output(id).errors);
|
||||
assert_eq!(last_scope(&s, id), crate::history::Scope::Full);
|
||||
saves_and_reopens(&mut s, id, 1);
|
||||
s.undo(id).unwrap();
|
||||
assert_eq!(s.get(id).unwrap().info.pages.len(), 2);
|
||||
}
|
||||
|
||||
/// Two relayouts in one event, and a script that fails after them: the form was still laid
|
||||
/// out again, so the view is rebuilt.
|
||||
#[test]
|
||||
fn an_xfa_event_that_lays_out_twice_then_fails_still_rebuilds_the_view() {
|
||||
let template = pdfcraft_xfa::fixtures::presence_growth_template(false, "", "", r#"xfa.layout.relayout(); throw new Error("late failure");"#);
|
||||
let mut s = Session::new().with_clock(|| 1_700_000_000);
|
||||
let id = s.open("twice.pdf", None, Arc::new(pdfcraft_xfa::fixtures::shell(&template)), None).unwrap();
|
||||
s.apply(id, Edit::SetFieldValue { name: "more".into(), value: FieldValue::Check(true) }).unwrap();
|
||||
let out = s.take_js_output(id);
|
||||
assert!(out.errors.iter().any(|e| e.contains("late failure")), "{:?}", out.errors);
|
||||
assert_eq!(s.get(id).unwrap().info.pages.len(), 2);
|
||||
assert_eq!(last_scope(&s, id), crate::history::Scope::Full);
|
||||
saves_and_reopens(&mut s, id, 2);
|
||||
}
|
||||
|
||||
/// A picture chosen for an image field lays the form out again from its data.
|
||||
#[test]
|
||||
fn an_xfa_picture_lays_the_form_out_again_and_rebuilds_the_view() {
|
||||
let after = r#"<field name="photo" w="1in" h="1in"><ui><imageEdit/></ui></field>"#;
|
||||
let template = pdfcraft_xfa::fixtures::presence_growth_template(false, "", after, "");
|
||||
let mut s = Session::new().with_clock(|| 1_700_000_000);
|
||||
let id = s.open("photo.pdf", None, Arc::new(pdfcraft_xfa::fixtures::shell(&template)), None).unwrap();
|
||||
s.apply(id, Edit::SetFieldImage { name: "photo".into(), image: Arc::new(pdfcraft_xfa::fixtures::TINY_GIF.to_vec()) }).unwrap();
|
||||
assert_eq!(last_scope(&s, id), crate::history::Scope::Full, "{:?}", s.take_js_output(id).errors);
|
||||
saves_and_reopens(&mut s, id, 1);
|
||||
}
|
||||
|
||||
/// Text growth, then a script: each lays the form out onto one more page, and it saves.
|
||||
#[test]
|
||||
fn xfa_text_growth_then_a_script_relayout_both_add_pages() {
|
||||
let before = r#"<field name="notes" w="7.5in" minH="0.5in"><ui><textEdit multiLine="1"/></ui></field>"#;
|
||||
let template = pdfcraft_xfa::fixtures::presence_growth_template(false, before, "", "");
|
||||
let mut s = Session::new().with_clock(|| 1_700_000_000);
|
||||
let id = s.open("mixed.pdf", None, Arc::new(pdfcraft_xfa::fixtures::shell(&template)), None).unwrap();
|
||||
assert_eq!(s.get(id).unwrap().info.pages.len(), 1);
|
||||
let notes: String = (1..=60).map(|i| format!("line {i}\n")).collect();
|
||||
s.apply(id, Edit::SetFieldValue { name: "notes".into(), value: FieldValue::Text(notes) }).unwrap();
|
||||
assert_eq!(s.get(id).unwrap().info.pages.len(), 2);
|
||||
saves_and_reopens(&mut s, id, 2);
|
||||
s.apply(id, Edit::SetFieldValue { name: "more".into(), value: FieldValue::Check(true) }).unwrap();
|
||||
assert_eq!(s.get(id).unwrap().info.pages.len(), 3, "{:?}", s.take_js_output(id).errors);
|
||||
saves_and_reopens(&mut s, id, 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn xfa_text_growth_refreshes_widget_geometry_but_fixed_height_fields_keep_their_widgets() {
|
||||
for fixed in [false, true] {
|
||||
@@ -12053,6 +12365,71 @@ fn cropping_an_existing_image_clips_it_and_moves_with_it() {
|
||||
assert!(s.apply(id, Edit::EditPageImage { page: 0, index: 0, change: ImageEdit::Crop([10.0, 10.0, 10.0, 50.0]) }).is_err());
|
||||
}
|
||||
|
||||
/// A certified (DocMDP P=2) form, as a certifying application leaves it: signed over the whole
|
||||
/// file, with nothing appended.
|
||||
fn certified_xfa(original: &[u8]) -> Arc<Vec<u8>> {
|
||||
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 cos = pdfcraft_cos::Document::open(Arc::new(original.to_vec())).unwrap();
|
||||
let opts = SignOptions { certify: Some(2), date: "D:20270115080000Z".into(), ..SignOptions::default() };
|
||||
Arc::new(sign::sign(&cos, &id, &opts).unwrap())
|
||||
}
|
||||
|
||||
/// What opening an XFA form writes (its layout, the values from its data, its open scripts) is
|
||||
/// PdfCraft's own working revision, not a change to the file: a certified government form
|
||||
/// opened untouched is not "altered since it was signed" (#2759). Once the user changes it, or
|
||||
/// saves, the file Save writes is what is judged, open-time revisions included.
|
||||
#[test]
|
||||
fn certified_xfa_forms_open_unaltered() {
|
||||
let p12 = std::fs::read(concat!(env!("CARGO_MANIFEST_DIR"), "/../sign/tests/data/ec-p256.p12")).unwrap();
|
||||
let signer = sign::pkcs12::open(&p12, "test").unwrap().certificate;
|
||||
let forms = [
|
||||
// Laying the template out adds pages: a change the certification doesn't permit.
|
||||
("dynamic", pdfcraft_xfa::fixtures::shell(&pdfcraft_xfa::fixtures::template(3)), "familyName", sign::kind::PAGES, SignatureStatus::Invalid),
|
||||
// Taking the values from the data fills the fields: a permitted change.
|
||||
(
|
||||
"static",
|
||||
pdfcraft_xfa::fixtures::static_shell("<form1><page1><name>Ada</name><agree>1</agree></page1></form1>"),
|
||||
"form1[0].page1[0].name[0]",
|
||||
sign::kind::FORM_FILL,
|
||||
SignatureStatus::Valid,
|
||||
),
|
||||
];
|
||||
for (what, form, field, saved_kind, saved_status) in forms {
|
||||
let certified = certified_xfa(&form);
|
||||
let mut s = Session::new().with_clock(|| 1_800_000_000);
|
||||
let id = s.open("imm.pdf", None, certified.clone(), None).expect("opens");
|
||||
let doc = s.get(id).unwrap();
|
||||
assert!(doc.bytes.len() > certified.len() && !doc.dirty, "{what}: opening wrote a working revision, not an edit");
|
||||
let verdict = |s: &Session| {
|
||||
let sig = s.get(id).unwrap().signatures[0].clone();
|
||||
(sig.status, sig.modification)
|
||||
};
|
||||
assert_eq!(s.get(id).unwrap().signatures[0].certify, Some(2), "{what}");
|
||||
assert_eq!(verdict(&s), (SignatureStatus::Unknown, sign::Modification::None), "{what}: {:?}", s.get(id).unwrap().signatures[0].details);
|
||||
// Trusting the signer revalidates the file as opened too.
|
||||
s.set_trusted_certificates(vec![signer.clone()]);
|
||||
assert_eq!(verdict(&s), (SignatureStatus::Valid, sign::Modification::None), "{what}");
|
||||
// An edit is judged with everything Save would write; undoing it is the file as opened.
|
||||
s.apply(id, Edit::SetFieldValue { name: field.into(), value: FieldValue::Text("Singh".into()) }).unwrap();
|
||||
assert_ne!(verdict(&s).1, sign::Modification::None, "{what}");
|
||||
s.undo(id).unwrap();
|
||||
assert_eq!(verdict(&s), (SignatureStatus::Valid, sign::Modification::None), "{what}");
|
||||
s.revert(id).unwrap();
|
||||
assert_eq!(verdict(&s), (SignatureStatus::Valid, sign::Modification::None), "{what}");
|
||||
// Saved, the open-time revision is part of the file.
|
||||
let saved = s.save_bytes(id).unwrap();
|
||||
s.mark_saved(id, saved, None).unwrap();
|
||||
let (status, modification) = verdict(&s);
|
||||
assert_eq!(status, saved_status, "{what}: {modification:?}");
|
||||
let kinds = match &modification {
|
||||
sign::Modification::Allowed(k) | sign::Modification::Disallowed(k) => k.clone(),
|
||||
sign::Modification::None => Vec::new(),
|
||||
};
|
||||
assert!(kinds.contains(&saved_kind), "{what}: {modification:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Convert colours re-encodes pictures too (RGB → gray, the JPEG staying JPEG) and is one undo
|
||||
/// step; a document with nothing to convert refuses rather than leaving an empty step.
|
||||
#[test]
|
||||
@@ -12722,7 +13099,7 @@ fn a_field_that_only_reads_the_page_count_keeps_its_scripts_value() {
|
||||
|
||||
/// layout:ready scripts run once on opening: the root's turns field highlighting on (only when it
|
||||
/// is off), a field's sets a value and a later script reads the new highlight, while page
|
||||
/// numbering is left to the layout and form:ready is another event.
|
||||
/// numbering is left to the layout. form:ready is another event, and runs too.
|
||||
#[test]
|
||||
fn a_forms_layout_ready_scripts_run_once_it_is_laid_out() {
|
||||
let bytes = Arc::new(pdfcraft_xfa::fixtures::shell(&pdfcraft_xfa::fixtures::layout_ready_template()));
|
||||
@@ -12734,13 +13111,78 @@ fn a_forms_layout_ready_scripts_run_once_it_is_laid_out() {
|
||||
assert_eq!(value(&s, "stamp"), vec!["laid out".to_string()]);
|
||||
assert_eq!(value(&s, "seen"), vec!["true".to_string()], "a later script reads the highlight the root's turned on");
|
||||
assert!(value(&s, "pageNo").iter().all(|v| v.is_empty()), "page numbers are the layout's: {:?}", value(&s, "pageNo"));
|
||||
assert!(value(&s, "note").iter().all(|v| v.is_empty()), "form:ready is another event");
|
||||
assert_eq!(value(&s, "note"), vec!["form ready".to_string()], "form:ready runs on opening too");
|
||||
// With highlighting already on, the form has nothing to ask for.
|
||||
s.set_field_highlight(true);
|
||||
let id = s.open("ready.pdf", None, bytes, None).expect("opens");
|
||||
assert!(s.take_js_output(id).requests.is_empty());
|
||||
}
|
||||
|
||||
/// The ready events run on opening in the order another viewer ran them on a synthetic form:
|
||||
/// initialize children first, form:ready and layout:ready parents first, docReady after the first
|
||||
/// layout:ready. A click that lays the form out again (showing a tall section: a second page)
|
||||
/// runs every layout:ready script again, once each, and they read the new page count.
|
||||
#[test]
|
||||
fn ready_events_run_in_order_and_layout_ready_runs_again_after_a_new_layout() {
|
||||
let bytes = Arc::new(pdfcraft_xfa::fixtures::shell(&pdfcraft_xfa::fixtures::ready_events_template()));
|
||||
let mut s = Session::new();
|
||||
let id = s.open("ready.pdf", None, bytes, None).expect("opens");
|
||||
let log = |s: &Session| s.get(id).unwrap().form.iter().find(|f| f.name == "log").map(|f| f.value.join("")).unwrap_or_default();
|
||||
let opened = "title initialize|root initialize|root form:ready|title form:ready|root layout:ready pages=1|title layout:ready|root docReady";
|
||||
assert_eq!(log(&s), opened);
|
||||
assert_eq!(s.get(id).unwrap().info.pages.len(), 1);
|
||||
s.apply(id, Edit::XfaEvent { som: "form[0].grow[0]".into(), activity: "click".into() }).expect("clicks");
|
||||
assert_eq!(s.get(id).unwrap().info.pages.len(), 2, "the tall section takes a second page");
|
||||
assert_eq!(log(&s), format!("{opened}|root layout:ready pages=2|title layout:ready"));
|
||||
}
|
||||
|
||||
/// On opening, the calculations run once the initialize scripts have, before form:ready (XFA
|
||||
/// 3.3 fires the form ready event after them), and form:ready runs in the reverse of
|
||||
/// initialize's order (the root, then its fields last to first), while layout:ready keeps
|
||||
/// document order, as another viewer logged on a synthetic form. Since the ready scripts wrote a
|
||||
/// value (the log), the calculations run once more after them: which ones read it isn't known
|
||||
/// here. A form whose ready scripts write nothing runs them once.
|
||||
#[test]
|
||||
fn calculations_run_before_form_ready_which_runs_in_reverse() {
|
||||
let js = |what: &str| {
|
||||
format!(r#"var l = xfa.form.form.log; l.rawValue = (l.rawValue == null || l.rawValue == "" ? "" : l.rawValue + "|") + "{what}";"#)
|
||||
};
|
||||
let event = |activity: &str, reference: &str, what: &str| {
|
||||
format!(r#"<event activity="{activity}"{reference}><script contentType="application/x-javascript">{}</script></event>"#, js(what))
|
||||
};
|
||||
let field = |name: &str, extra: &str| {
|
||||
format!(
|
||||
r#"<field name="{name}" w="2in" h="0.3in"><ui><textEdit/></ui>{}{}{extra}</field>"#,
|
||||
event("initialize", "", &format!("{name} initialize")),
|
||||
event("ready", r#" ref="$form""#, &format!("{name} form:ready")),
|
||||
)
|
||||
};
|
||||
let calc = format!(r#"<calculate><script contentType="application/x-javascript">{} 42;</script></calculate>"#, js("calc calculate"));
|
||||
let layout = |name: &str| event("ready", r#" ref="$layout""#, &format!("{name} layout:ready"));
|
||||
let fields = [field("calc", &calc), field("a", &layout("a")), field("b", &layout("b"))].concat();
|
||||
let xdp = pdfcraft_xfa::fixtures::ready_events_template().replace(r#" <field name="grow""#, &format!(" {fields}\n <field name=\"grow\""));
|
||||
let mut s = Session::new();
|
||||
let id = s.open("ready.pdf", None, Arc::new(pdfcraft_xfa::fixtures::shell(&xdp)), None).expect("opens");
|
||||
let value = |s: &Session, n: &str| s.get(id).unwrap().form.iter().find(|f| f.name == n).map(|f| f.value.join("")).unwrap_or_default();
|
||||
let initialize = "title initialize|calc initialize|a initialize|b initialize|root initialize";
|
||||
let ready = "root form:ready|b form:ready|a form:ready|calc form:ready|title form:ready";
|
||||
let layout = "root layout:ready pages=1|title layout:ready|a layout:ready|b layout:ready";
|
||||
assert_eq!(value(&s, "log"), format!("{initialize}|calc calculate|{ready}|{layout}|root docReady|calc calculate"));
|
||||
assert_eq!(value(&s, "calc"), "42");
|
||||
// Ready scripts that write nothing: the calculations run once, before form:ready.
|
||||
let mut quiet = xdp.clone();
|
||||
for start in
|
||||
[r#"<event activity="ready" ref="$form">"#, r#"<event activity="ready" ref="$layout">"#, r#"<event activity="docReady" ref="$host">"#]
|
||||
{
|
||||
// Each ready script writes nothing; its logging moves to an event that never fires.
|
||||
quiet =
|
||||
quiet.replace(start, &format!(r#"{start}<script contentType="application/x-javascript">1;</script></event><event activity="never">"#));
|
||||
}
|
||||
let id = s.open("quiet.pdf", None, Arc::new(pdfcraft_xfa::fixtures::shell(&quiet)), None).expect("opens");
|
||||
let log = s.get(id).unwrap().form.iter().find(|f| f.name == "log").map(|f| f.value.join("")).unwrap_or_default();
|
||||
assert_eq!(log.matches("calc calculate").count(), 1, "{log}");
|
||||
}
|
||||
|
||||
/// An edit's two script runtimes share one field highlight: a change an XFA script makes reaches
|
||||
/// the field scripts' runner, and one the field scripts make is what the next XFA script reads.
|
||||
#[test]
|
||||
@@ -12756,6 +13198,31 @@ fn an_edits_xfa_and_field_scripts_share_the_field_highlight() {
|
||||
assert!(!cx.highlight(), "the next XFA script reads the field scripts' change");
|
||||
}
|
||||
|
||||
/// In a batch of value edits, a later field's change script reads the page count an earlier one's
|
||||
/// layout left: `bump`'s change shows a tall section (a second page), and `count`'s change, in the
|
||||
/// same batch, records `xfa.layout.pageCount()`.
|
||||
#[test]
|
||||
fn a_later_xfa_edit_in_a_batch_reads_the_page_count_an_earlier_one_left() {
|
||||
let script = |js: &str| format!(r#"<event activity="change"><script contentType="application/x-javascript">{js}</script></event>"#);
|
||||
let xdp = pdfcraft_xfa::fixtures::ready_events_template().replace(
|
||||
"<field name=\"log\"",
|
||||
&format!(
|
||||
r#"<field name="bump" w="1in" h="0.3in"><ui><textEdit/></ui>{bump}</field>
|
||||
<field name="count" w="1in" h="0.3in"><ui><textEdit/></ui>{count}</field>
|
||||
<field name="seen" w="1in" h="0.3in"><ui><textEdit/></ui></field>
|
||||
<field name="log""#,
|
||||
bump = script(r#"xfa.form.form.tall.presence = "visible";"#),
|
||||
count = script("xfa.form.form.seen.rawValue = String(xfa.layout.pageCount());"),
|
||||
),
|
||||
);
|
||||
let mut s = Session::new();
|
||||
let id = s.open("batch.pdf", None, Arc::new(pdfcraft_xfa::fixtures::shell(&xdp)), None).expect("opens");
|
||||
let type_in = |name: &str| Edit::SetFieldValue { name: name.into(), value: FieldValue::Text("x".into()) };
|
||||
s.apply(id, Edit::Batch { edits: vec![type_in("bump"), type_in("count")], label: "Type".into() }).expect("types");
|
||||
let seen = s.get(id).unwrap().form.iter().find(|f| f.name == "seen").map(|f| f.value.clone()).unwrap_or_default();
|
||||
assert_eq!(seen, vec!["2".to_string()]);
|
||||
}
|
||||
|
||||
/// In a batch of value edits, a later field's change script reads the field highlight an earlier
|
||||
/// one's set: `on`'s change turns it on, and `look`'s, in the same batch, records what it reads.
|
||||
/// (A form-script event itself can't be batched.)
|
||||
@@ -13980,6 +14447,44 @@ fn repeated_backdrop_artwork_survives_background_undo_redo_and_both_save_modes()
|
||||
black(&s, rewritten);
|
||||
}
|
||||
|
||||
/// A form saved with its pages whose signature box sits deeper than the 32 nested fields looked
|
||||
/// through counts as signed, as the xfa crate counts it, so it is left as saved rather than laid
|
||||
/// out again over a signature that may be there; nested less deep, unsigned, it is laid out.
|
||||
#[test]
|
||||
fn a_saved_form_too_deep_to_read_through_is_left_as_saved() {
|
||||
let xfa = |depth: usize| {
|
||||
let mut s = Session::new();
|
||||
let id = s.open("deep.pdf", None, Arc::new(pdfcraft_xfa::fixtures::deep_saved_with_pages_shell(depth)), None).expect("opens");
|
||||
s.get(id).unwrap().info.xfa
|
||||
};
|
||||
assert_eq!(xfa(5), Some(pdfcraft_render::Xfa::Dynamic), "nested, unsigned: laid out");
|
||||
assert_eq!(xfa(40), Some(pdfcraft_render::Xfa::Static), "too deep to tell: left as saved");
|
||||
}
|
||||
|
||||
/// The renderer's inspection and the xfa crate each decide whether a form saved with its pages
|
||||
/// is laid out again from its template, each walking the field tree for a signature in its own
|
||||
/// way (the renderer reads the file through lopdf, the xfa crate through cos). They agree on every
|
||||
/// such form: required or not, signed or not, and a signature box nested from shallow to past
|
||||
/// the depth either looks through.
|
||||
#[test]
|
||||
fn the_renderer_and_the_xfa_crate_agree_on_which_saved_forms_are_laid_out() {
|
||||
let mut forms: Vec<(String, Vec<u8>)> = Vec::new();
|
||||
for render in ["required", "forbidden", ""] {
|
||||
for signed in [false, true] {
|
||||
forms.push((format!("{render:?}, signed {signed}"), pdfcraft_xfa::fixtures::saved_with_pages_shell(render, signed)));
|
||||
}
|
||||
}
|
||||
for depth in [1, 5, 30, 31, 32, 33, 34, 40] {
|
||||
forms.push((format!("nested {depth} deep"), pdfcraft_xfa::fixtures::deep_saved_with_pages_shell(depth)));
|
||||
}
|
||||
for (what, bytes) in forms {
|
||||
let bytes = Arc::new(bytes);
|
||||
let info = pdfcraft_render::inspect(bytes.clone(), None).expect("inspects");
|
||||
let cos = pdfcraft_cos::Document::open(bytes).expect("opens");
|
||||
assert_eq!(info.xfa == Some(pdfcraft_render::Xfa::Dynamic), pdfcraft_xfa::is_dynamic(&cos), "{what}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A page still exists after its only master widget is hidden: its master nodes stay in the
|
||||
/// script model, so a later script can address them again (test from wireless89's review of
|
||||
/// #5368).
|
||||
@@ -14378,13 +14883,12 @@ fn a_batch_that_applies_redactions_and_copies_a_page_is_refused() {
|
||||
/// so when the form is saved.
|
||||
#[test]
|
||||
fn an_opening_reset_reaches_a_row_added_while_opening() {
|
||||
let tpl = pdfcraft_xfa::fixtures::scripted_template().replace(
|
||||
"if (qty.rawValue === null) qty.rawValue = 2;",
|
||||
r#"if (qty.rawValue === null) qty.rawValue = 2; table._row.addInstance(1);"#,
|
||||
)
|
||||
// The row is added by a script of a field before `grand`: the initialize scripts run children
|
||||
// before their parents, so a script of `page1` would come after `grand`'s.
|
||||
let tpl = pdfcraft_xfa::fixtures::scripted_template()
|
||||
.replace(
|
||||
r#"<field name="grand" w="2in" h="0.3in" access="readOnly">"#,
|
||||
r#"<field name="grand" w="2in" h="0.3in" access="readOnly"><event activity="initialize"><script contentType="application/x-javascript">xfa.resolveNode("form.page1.table.row[1].item").rawValue = "X"; xfa.host.resetData("form.page1.table.row[1].item");</script></event>"#,
|
||||
r#"<field name="grand" w="2in" h="0.3in" access="readOnly"><event activity="initialize"><script contentType="application/x-javascript">table._row.addInstance(1);</script></event><event activity="initialize"><script contentType="application/x-javascript">xfa.resolveNode("form.page1.table.row[1].item").rawValue = "X"; xfa.host.resetData("form.page1.table.row[1].item");</script></event>"#,
|
||||
);
|
||||
let mut s = Session::new().with_clock(|| 1_700_000_000);
|
||||
let id = s.open("rows.pdf", None, Arc::new(pdfcraft_xfa::fixtures::shell(&tpl)), None).unwrap();
|
||||
@@ -14403,14 +14907,10 @@ fn an_opening_reset_reaches_a_row_added_while_opening() {
|
||||
fn an_opening_reset_reaches_an_exclusion_group_of_a_row_added_while_opening() {
|
||||
let group = r#"<exclGroup name="pick" w="1in" h="0.3in"><field name="a" w="0.5in" h="0.3in"><ui><checkButton/></ui><items><text>A</text></items><value><text>A</text></value></field><field name="b" w="0.5in" h="0.3in"><ui><checkButton/></ui><items><text>B</text></items></field></exclGroup>"#;
|
||||
let tpl = pdfcraft_xfa::fixtures::scripted_template()
|
||||
.replace(
|
||||
"if (qty.rawValue === null) qty.rawValue = 2;",
|
||||
r#"if (qty.rawValue === null) qty.rawValue = 2; table._row.addInstance(1);"#,
|
||||
)
|
||||
.replace(r#"<field name="amount" h="0.3in"><ui><numericEdit/></ui></field>"#, &format!(r#"<field name="amount" h="0.3in"><ui><numericEdit/></ui></field>{group}"#))
|
||||
.replace(
|
||||
r#"<field name="grand" w="2in" h="0.3in" access="readOnly">"#,
|
||||
r#"<field name="grand" w="2in" h="0.3in" access="readOnly"><event activity="initialize"><script contentType="application/x-javascript">xfa.resolveNode("form.page1.table.row[1].pick").rawValue = "B"; xfa.host.resetData("form.page1.table.row[1].pick");</script></event>"#,
|
||||
r#"<field name="grand" w="2in" h="0.3in" access="readOnly"><event activity="initialize"><script contentType="application/x-javascript">table._row.addInstance(1);</script></event><event activity="initialize"><script contentType="application/x-javascript">xfa.resolveNode("form.page1.table.row[1].pick").rawValue = "B"; xfa.host.resetData("form.page1.table.row[1].pick");</script></event>"#,
|
||||
);
|
||||
let mut s = Session::new().with_clock(|| 1_700_000_000);
|
||||
let id = s.open("rows.pdf", None, Arc::new(pdfcraft_xfa::fixtures::shell(&tpl)), None).unwrap();
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
//! Printer's marks on the printed copy only (Acrobat's Marks and Bleeds).
|
||||
|
||||
use super::*;
|
||||
|
||||
fn marks() -> PrinterMarks {
|
||||
PrinterMarks { label: "proof.pdf".into(), date: "2026-11-12".into(), ..PrinterMarks::default() }
|
||||
}
|
||||
|
||||
fn actual(pages: Vec<usize>) -> print::Settings {
|
||||
print::Settings { pages, layout: print::Layout::Size(print::SizeMode::Actual), ..Default::default() }
|
||||
}
|
||||
|
||||
/// The pixels on the first sheet that aren't white.
|
||||
fn inked(bytes: Vec<u8>) -> usize {
|
||||
let (_, _, rgba) = printed_pixels(bytes);
|
||||
rgba.as_chunks::<4>().0.iter().filter(|p| p[0] < 200 || p[1] < 200 || p[2] < 200).count()
|
||||
}
|
||||
|
||||
fn sheet_texts(bytes: Vec<u8>) -> Vec<String> {
|
||||
let mut s = Session::new();
|
||||
let id = s.open("sheets.pdf", None, Arc::new(bytes), None).unwrap();
|
||||
page_texts(&s, id)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn printer_marks_go_on_the_printed_sheets_and_not_the_document() {
|
||||
let (s, id) = session_with(3);
|
||||
let before = s.get(id).unwrap().bytes.clone();
|
||||
let plain = s.print_pdf(id, &actual(vec![1])).unwrap();
|
||||
let marked = s.print_pdf_marked(id, &actual(vec![1]), Some(&marks())).unwrap();
|
||||
assert!(inked(marked.clone()) > inked(plain.clone()) + 200, "trim and bleed marks, targets and colour bars are drawn");
|
||||
let texts = sheet_texts(marked);
|
||||
assert!(texts[0].contains("proof.pdf") && texts[0].contains("2 of 3") && texts[0].contains("2026-11-12"), "{texts:?}");
|
||||
assert!(!sheet_texts(plain)[0].contains("2 of 3"));
|
||||
let doc = s.get(id).unwrap();
|
||||
assert!(Arc::ptr_eq(&doc.bytes, &before) && !doc.dirty, "the document itself is untouched");
|
||||
}
|
||||
|
||||
/// Each printed page carries its own place in the document, in the order printed, a page
|
||||
/// printed twice included.
|
||||
#[test]
|
||||
fn each_printed_page_is_marked_with_its_own_number() {
|
||||
let (s, id) = session_with(4);
|
||||
let texts = sheet_texts(s.print_pdf_marked(id, &actual(vec![2, 0, 2]), Some(&marks())).unwrap());
|
||||
assert_eq!(texts.len(), 3, "{texts:?}");
|
||||
for (text, page) in texts.iter().zip(["3 of 4", "1 of 4", "3 of 4"]) {
|
||||
assert_eq!(text.matches(" of 4").count(), 1, "{texts:?}");
|
||||
assert!(text.contains(page), "{page}: {texts:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn marks_the_document_already_has_are_replaced_on_paper() {
|
||||
let (mut s, id) = session_with(2);
|
||||
let old = PrinterMarks { label: "old.pdf".into(), date: "2020-01-01".into(), ..PrinterMarks::default() };
|
||||
s.apply(id, Edit::AddPrinterMarks { pages: vec![0], settings: old, replace: true }).unwrap();
|
||||
let texts = sheet_texts(s.print_pdf_marked(id, &actual(vec![0]), Some(&marks())).unwrap());
|
||||
assert!(texts[0].contains("proof.pdf") && texts[0].contains("2026-11-12"), "the print's marks: {texts:?}");
|
||||
assert!(!texts[0].contains("old.pdf") && !texts[0].contains("2020-01-01"), "the document's marks are replaced: {texts:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn printer_marks_are_refused_for_a_print_as_pictures() {
|
||||
let (s, id) = session_with(1);
|
||||
let raster = Some(print::Raster { dpi: 72.0, grayscale: false, colour: None });
|
||||
let settings = print::Settings { raster, ..actual(vec![0]) };
|
||||
assert!(matches!(s.print_pdf_marked(id, &settings, Some(&marks())), Err(EditError::Print(m)) if m.contains("as_image")));
|
||||
assert!(s.print_pdf_marked(id, &settings, None).is_ok());
|
||||
}
|
||||
|
||||
/// Form fields only prints the fields and the marks, without the page content or comments.
|
||||
#[test]
|
||||
fn printer_marks_print_with_form_fields_only() {
|
||||
let mut s = Session::new();
|
||||
let id = s.open("fields.pdf", None, Arc::new(print_content_pdf()), None).unwrap();
|
||||
let marks = PrinterMarks { color_bars: false, registration: false, ..marks() };
|
||||
let settings = print::Settings { paper: (300.0, 600.0), content: print::Content::FormFieldsOnly, ..actual(vec![0]) };
|
||||
let bytes = s.print_pdf_marked(id, &settings, Some(&marks)).unwrap();
|
||||
assert!(sheet_texts(bytes.clone())[0].contains("1 of 1"), "the page information line prints");
|
||||
let (_, _, rgba) = printed_pixels(bytes);
|
||||
let count = |c: [u8; 3]| rgba.as_chunks::<4>().0.iter().filter(|p| p[..3].iter().zip(c).all(|(&a, b)| a.abs_diff(b) < 40)).count();
|
||||
assert!(count([0, 255, 0]) > 5000, "the field prints");
|
||||
assert_eq!((count([0, 0, 255]), count([255, 0, 0]), count([255, 255, 0])), (0, 0, 0), "no page content, stamp or comment");
|
||||
let plain = s.print_pdf(id, &settings).unwrap();
|
||||
let (with, without) = (inked(s.print_pdf_marked(id, &settings, Some(&marks)).unwrap()), inked(plain));
|
||||
assert!(with > without + 100, "trim and bleed marks print: {with} inked pixels, {without} without marks");
|
||||
}
|
||||
@@ -30,7 +30,7 @@ impl TextStyle {
|
||||
}
|
||||
|
||||
/// How far apart two sizes may be and still be one style.
|
||||
const SIZE_TOLERANCE: f64 = 0.25;
|
||||
pub(crate) const SIZE_TOLERANCE: f64 = 0.25;
|
||||
|
||||
/// A style and how much text is set in it.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
@@ -49,29 +49,41 @@ pub const MAX_PAGES: usize = 5000;
|
||||
/// The most bookmarks made at once.
|
||||
pub const MAX_BOOKMARKS: usize = 10_000;
|
||||
/// The longest bookmark title kept, in characters (a heading run on into a paragraph).
|
||||
const MAX_TITLE_CHARS: usize = 300;
|
||||
pub(crate) const MAX_TITLE_CHARS: usize = 300;
|
||||
/// The longest sample shown for a style.
|
||||
const SAMPLE_CHARS: usize = 60;
|
||||
/// The most styles listed, the largest first.
|
||||
const MAX_STYLES: usize = 200;
|
||||
|
||||
/// One line of text in reading order.
|
||||
struct Line {
|
||||
page: usize,
|
||||
text: String,
|
||||
style: TextStyle,
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct Line {
|
||||
pub(crate) page: usize,
|
||||
pub(crate) text: String,
|
||||
pub(crate) style: TextStyle,
|
||||
/// Top, bottom, left and right of its box as displayed (after the page's `/Rotate`, y up), so
|
||||
/// reading order and the join of a heading's lines are right on a turned page. Only
|
||||
/// differences between these values are used: they are offset from points on the page.
|
||||
top: f64,
|
||||
bottom: f64,
|
||||
left: f64,
|
||||
right: f64,
|
||||
pub(crate) top: f64,
|
||||
pub(crate) bottom: f64,
|
||||
pub(crate) left: f64,
|
||||
pub(crate) right: f64,
|
||||
/// The `/XYZ` position `[left, top]` (user space) that puts the top of the line as displayed
|
||||
/// at the top of the window. The box edge displayed on top depends on the rotation: the top
|
||||
/// edge, the left edge (90), the bottom edge (180) or the right edge (270). On a page turned
|
||||
/// a quarter it is a user-space x, so it is `left`, and `top` stays unspecified.
|
||||
anchor: [Option<f64>; 2],
|
||||
pub(crate) anchor: [Option<f64>; 2],
|
||||
}
|
||||
|
||||
impl Line {
|
||||
/// Whether this line goes on with a heading whose last line is `above`: on the same page, on
|
||||
/// the next row down, close below it and under it. A line on the same row (two headings side
|
||||
/// by side), or in another column, starts a heading of its own.
|
||||
pub(crate) fn continues(&self, above: &Line) -> bool {
|
||||
let size = self.style.size;
|
||||
let under = self.left < above.right && above.left < self.right;
|
||||
self.page == above.page && self.top < above.top - size * 0.5 && above.bottom - self.top < size * 0.6 && under
|
||||
}
|
||||
}
|
||||
|
||||
/// A box in user space `[x0, y0, x1, y1]` on a page turned `rotation` degrees clockwise → its
|
||||
@@ -96,13 +108,21 @@ fn without_subset_tag(name: &str) -> &str {
|
||||
|
||||
/// The text lines of `doc`'s first [`MAX_PAGES`] pages, each page's in reading order. Text that
|
||||
/// is only whitespace, or whose size can't be read, is left out.
|
||||
fn lines(doc: &Document) -> Vec<Line> {
|
||||
pub(crate) fn lines(doc: &Document) -> Vec<Line> {
|
||||
read_lines(doc).0
|
||||
}
|
||||
|
||||
/// [`lines`], and how many pages' text was read: a page whose text can't be read (its content
|
||||
/// past the page's decode allowance, say) is skipped and not counted.
|
||||
pub(crate) fn read_lines(doc: &Document) -> (Vec<Line>, usize) {
|
||||
let pages = pdfcraft_organize::page_count(doc).unwrap_or(0).min(MAX_PAGES);
|
||||
let rotations = pdfcraft_organize::page_rotations(doc).unwrap_or_default();
|
||||
let mut out = Vec::new();
|
||||
let mut read = 0usize;
|
||||
for page in 0..pages {
|
||||
let rotation = rotations.get(page).copied().unwrap_or(0);
|
||||
let Ok(found) = pdfcraft_edit::text_lines(doc, page) else { continue };
|
||||
read = read.saturating_add(1);
|
||||
let mut on_page: Vec<Line> = found
|
||||
.into_iter()
|
||||
.filter_map(|l| {
|
||||
@@ -135,7 +155,7 @@ fn lines(doc: &Document) -> Vec<Line> {
|
||||
on_page.sort_by(|a, b| (b.top * 10.0).round().total_cmp(&(a.top * 10.0).round()).then(a.left.total_cmp(&b.left)));
|
||||
out.extend(on_page);
|
||||
}
|
||||
out
|
||||
(out, read)
|
||||
}
|
||||
|
||||
/// The styles `doc`'s text is set in, the largest size first (then the most used): headings
|
||||
@@ -183,22 +203,14 @@ pub fn styles(doc: &Document) -> Vec<TextStyleUse> {
|
||||
/// is one bookmark. Each goes to the top of its heading as displayed, also on a turned page.
|
||||
pub fn headings(doc: &Document, levels: &[TextStyle]) -> Vec<OutlineEntry> {
|
||||
let mut entries: Vec<OutlineEntry> = Vec::new();
|
||||
// The heading the previous line belonged to: its level, and the top, bottom, left and right
|
||||
// of its last line.
|
||||
let mut open: Option<(usize, f64, f64, f64, f64)> = None;
|
||||
// The heading the previous line belonged to: its level and its last line.
|
||||
let mut open: Option<(usize, Line)> = None;
|
||||
for line in lines(doc) {
|
||||
let Some(level) = levels.iter().position(|s| s.matches(&line.style)) else {
|
||||
open = None;
|
||||
continue;
|
||||
};
|
||||
// A heading goes on to the next row down, close below its last line and under it. A line
|
||||
// on the same row (two headings side by side), or in another column, is a heading of
|
||||
// its own.
|
||||
let continues = open.is_some_and(|(l, top, bottom, left, right)| {
|
||||
let size = line.style.size;
|
||||
let under = line.left < right && left < line.right;
|
||||
l == level && line.top < top - size * 0.5 && bottom - line.top < size * 0.6 && under
|
||||
}) && entries.last().is_some_and(|e| e.page == line.page);
|
||||
let continues = open.as_ref().is_some_and(|(l, above)| *l == level && line.continues(above));
|
||||
if continues {
|
||||
if let Some(e) = entries.last_mut()
|
||||
&& e.title.chars().count() < MAX_TITLE_CHARS
|
||||
@@ -217,7 +229,7 @@ pub fn headings(doc: &Document, levels: &[TextStyle]) -> Vec<OutlineEntry> {
|
||||
let [left, top] = line.anchor;
|
||||
entries.push(OutlineEntry { level, title: line.text.chars().take(MAX_TITLE_CHARS).collect(), page: line.page, element: None, left, top });
|
||||
}
|
||||
open = Some((level, line.top, line.bottom, line.left, line.right));
|
||||
open = Some((level, line));
|
||||
}
|
||||
entries
|
||||
}
|
||||
|
||||
+218
-38
@@ -145,6 +145,9 @@ pub(crate) struct XfaRun<'a> {
|
||||
pub time_scale: u32,
|
||||
/// The answers to the event's message boxes.
|
||||
pub answers: XfaAnswers,
|
||||
/// The form was laid out again: its pages, widgets and fields were replaced, so the edit
|
||||
/// must rebuild the document's page and field lists, not only refresh their values.
|
||||
pub relaid: bool,
|
||||
}
|
||||
|
||||
/// The answers to one event's message boxes (`xfa.host.messageBox`, `$host.messageBox`,
|
||||
@@ -450,15 +453,29 @@ struct FieldInfo {
|
||||
on_state: String,
|
||||
/// List boxes that take several values (one per line in the data).
|
||||
multi: bool,
|
||||
/// Radio groups: each button's on state and SOM path (each button of an XFA radio group is a
|
||||
/// field of its own, with scripts of its own).
|
||||
buttons: Vec<(String, String)>,
|
||||
}
|
||||
|
||||
/// The generated fields of `doc`, by name, as the runner tracks them.
|
||||
fn field_infos(doc: &pdfcraft_cos::Document) -> HashMap<String, FieldInfo> {
|
||||
// The SOM path a widget or field records for its XFA object.
|
||||
let som_of = |obj: pdfcraft_cos::ObjRef| {
|
||||
let object = doc.get(obj);
|
||||
object.as_dict()?.get(pdfcraft_xfa::SOM_KEY).map(|s| doc.resolve(s))?.as_string().map(|s| s.to_text())
|
||||
};
|
||||
pdfcraft_forms::fields(doc)
|
||||
.into_iter()
|
||||
.map(|f| {
|
||||
let on_state = f.widgets.first().and_then(|w| w.on_state.clone()).unwrap_or_else(|| "1".into());
|
||||
let multi = f.kind == pdfcraft_forms::FieldKind::List && f.has(pdfcraft_forms::flags::MULTI_SELECT);
|
||||
(f.name, FieldInfo { kind: f.kind, value: f.value, on_state, multi })
|
||||
let buttons = if f.kind == pdfcraft_forms::FieldKind::Radio {
|
||||
f.widgets.iter().filter_map(|w| Some((w.on_state.clone()?, som_of(w.obj)?))).collect()
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
(f.name, FieldInfo { kind: f.kind, value: f.value, on_state, multi, buttons })
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
@@ -489,6 +506,9 @@ struct Runner<'a, 'b> {
|
||||
skipped: usize,
|
||||
relayouts: usize,
|
||||
relayouts_skipped: bool,
|
||||
/// The form was laid out again since its layout:ready scripts last ran: they run once more
|
||||
/// when the event ends.
|
||||
laid_out: bool,
|
||||
/// Lay the form out once, when the event ends, rather than after every script that changed
|
||||
/// its structure (opening: see [`on_open`]).
|
||||
defer_relayout: bool,
|
||||
@@ -542,6 +562,7 @@ impl<'a, 'b> Runner<'a, 'b> {
|
||||
skipped: 0,
|
||||
relayouts: 0,
|
||||
relayouts_skipped: false,
|
||||
laid_out: false,
|
||||
defer_relayout: false,
|
||||
relayout_owed: false,
|
||||
dropped_output: 0,
|
||||
@@ -801,9 +822,17 @@ impl<'a, 'b> Runner<'a, 'b> {
|
||||
return Ok(());
|
||||
}
|
||||
self.relayouts += 1;
|
||||
self.laid_out = true;
|
||||
self.flush()?;
|
||||
// Set before the layout: one that fails part way may already have replaced fields.
|
||||
self.run.relaid = true;
|
||||
self.embedded_changed = false;
|
||||
let report = pdfcraft_xfa::rerender(self.doc, self.tpl).map_err(|e| e.to_string())?;
|
||||
if report.pages != self.run.page_count {
|
||||
// Later scripts read the new page count (`xfa.layout.pageCount()`) from a new session.
|
||||
self.run.page_count = report.pages;
|
||||
self.session = None;
|
||||
}
|
||||
self.console(report.warnings);
|
||||
crate::xfa_redraw(self.doc)?;
|
||||
self.console(crate::undrawn_field_warnings(self.doc));
|
||||
@@ -1096,21 +1125,84 @@ impl<'a, 'b> Runner<'a, 'b> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The SOM path of what a click on field `name` (at `som`) turned on or off, when it is a
|
||||
/// check box or a radio group: the check box itself, or the group's radio button now on.
|
||||
/// `None` for other fields, for a group left with no button on, and when the value is still
|
||||
/// `before` (set again, not clicked).
|
||||
fn clicked(&mut self, name: &str, som: &str, before: Option<&Vec<String>>) -> Option<String> {
|
||||
use pdfcraft_forms::FieldKind as K;
|
||||
let f = self.fields().get(name)?;
|
||||
if before.is_some_and(|b| *b == f.value) {
|
||||
return None;
|
||||
}
|
||||
match f.kind {
|
||||
K::CheckBox => Some(som.to_string()),
|
||||
K::Radio => {
|
||||
let on = f.value.first()?;
|
||||
f.buttons.iter().find(|(state, _)| state == on).map(|(_, button)| button.clone())
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The `activity` scripts of the object at `som` in the live form.
|
||||
fn events_of(&mut self, som: &str, activity: &str) -> Vec<ScriptEvent> {
|
||||
self.live().events.iter().filter(|e| e.som == som && e.activity == activity).cloned().collect()
|
||||
}
|
||||
|
||||
/// End the event: write what is left, lay the form out if a capped relayout is owed, and
|
||||
/// report what the limits cut.
|
||||
fn finish(mut self) -> Result<Changes, String> {
|
||||
#[cfg(test)]
|
||||
self.check_live();
|
||||
/// Every script of `activity`, in document order (parents before their children).
|
||||
fn events_named(&mut self, activity: &str) -> Vec<ScriptEvent> {
|
||||
self.live().events.iter().filter(|e| e.activity == activity).cloned().collect()
|
||||
}
|
||||
|
||||
/// Every layout:ready script, parents first. A field that numbers pages keeps the number the
|
||||
/// layout gave each page: the value a script writes to it is dropped (one value would put the
|
||||
/// same number on every page).
|
||||
fn layout_ready(&mut self) -> Result<(), String> {
|
||||
self.laid_out = false;
|
||||
let (ready, numbered) = {
|
||||
let live = self.live();
|
||||
let ready: Vec<ScriptEvent> = live.events.iter().filter(|e| e.activity == "layoutReady").cloned().collect();
|
||||
// The fields, gathered in one walk rather than one per script.
|
||||
let mut fields = HashSet::new();
|
||||
field_soms(&live.root, &mut fields, 0);
|
||||
let numbered: HashSet<String> = ready
|
||||
.iter()
|
||||
.filter(|e| fields.contains(&e.som) && pdfcraft_xfa::numbers_pages(&e.script, e.formcalc))
|
||||
.map(|e| e.som.clone())
|
||||
.collect();
|
||||
(ready, numbered)
|
||||
};
|
||||
self.numbered = numbered;
|
||||
for ev in &ready {
|
||||
self.run(ev, "")?;
|
||||
}
|
||||
self.numbered.clear();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Lay the form out once more if a capped relayout is owed.
|
||||
fn owed_relayout(&mut self) -> Result<(), String> {
|
||||
if self.relayouts_skipped || self.relayout_owed || self.embedded_changed {
|
||||
self.relayouts = 0;
|
||||
self.relayouts_skipped = false;
|
||||
self.relayout_owed = false;
|
||||
self.relayout()?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// End the event: lay the form out if a capped relayout is owed, run the layout:ready scripts
|
||||
/// again if the form was laid out again (once: what they lay out doesn't run them a third
|
||||
/// time), write what is left, and report what the limits cut.
|
||||
fn finish(mut self) -> Result<Changes, String> {
|
||||
#[cfg(test)]
|
||||
self.check_live();
|
||||
self.owed_relayout()?;
|
||||
if self.laid_out {
|
||||
self.layout_ready()?;
|
||||
self.owed_relayout()?;
|
||||
}
|
||||
self.flush()?;
|
||||
if !self.focus_requests.is_empty() {
|
||||
self.by_som();
|
||||
@@ -1278,62 +1370,139 @@ fn value_unchanged(doc: &pdfcraft_cos::Document, f: &pdfcraft_forms::Field, v: O
|
||||
}
|
||||
}
|
||||
|
||||
/// On open: initialize scripts, then layout:ready scripts (the form is laid out by now), then
|
||||
/// calculations. Returns what they changed.
|
||||
/// On open, in the order another viewer runs them: initialize scripts (children before their
|
||||
/// parent), form:ready (parents first), layout:ready (parents first; the form is laid out by
|
||||
/// now), docReady, then the calculations. Returns what they changed.
|
||||
///
|
||||
/// layout:ready runs once here, where forms set themselves up (turning field highlighting on,
|
||||
/// say); a viewer runs it after every layout. Every layout:ready script runs, but a field that
|
||||
/// numbers pages keeps the number the layout gave each page: the value a script writes to it is
|
||||
/// dropped (one value would put the same number on every page).
|
||||
/// layout:ready runs here, where forms set themselves up (turning field highlighting on, say),
|
||||
/// and again whenever a later script lays the form out again ([`Runner::finish`]).
|
||||
pub(crate) fn on_open(doc: &mut pdfcraft_cos::Document, tpl: &Template, run: &mut XfaRun) -> Result<Changes, String> {
|
||||
let mut r = Runner::new(doc, tpl, run, OPEN_BUDGET_MS);
|
||||
// The scripts read the live form (template, data and overrides), not the pages, so the
|
||||
// pages are laid out once, after the last of them. Laying a large form out after every
|
||||
// script that hides a subform spent the time limit on the first few, and the form was kept
|
||||
// half initialized: a page its initialize scripts hide stayed open to typing until the
|
||||
// next opening hid it and reset its data.
|
||||
// pages are laid out once, after the last of the initialize scripts. Laying a large form out
|
||||
// after every script that hides a subform spent the time limit on the first few, and the
|
||||
// form was kept half initialized: a page its initialize scripts hide stayed open to typing
|
||||
// until the next opening hid it and reset its data.
|
||||
r.defer_relayout = true;
|
||||
let events: Vec<ScriptEvent> = r.live().events.iter().filter(|e| e.activity == "initialize" || e.activity == "docReady").cloned().collect();
|
||||
for ev in &events {
|
||||
let initialize = children_first(r.events_named("initialize"));
|
||||
for ev in &initialize {
|
||||
r.run(ev, "")?;
|
||||
}
|
||||
let (ready, numbered) = {
|
||||
let live = r.live();
|
||||
let ready: Vec<ScriptEvent> = live.events.iter().filter(|e| e.activity == "layoutReady").cloned().collect();
|
||||
// The fields, gathered in one walk rather than one per script.
|
||||
let mut fields = HashSet::new();
|
||||
field_soms(&live.root, &mut fields, 0);
|
||||
let numbered: HashSet<String> =
|
||||
ready.iter().filter(|e| fields.contains(&e.som) && pdfcraft_xfa::numbers_pages(&e.script, e.formcalc)).map(|e| e.som.clone()).collect();
|
||||
(ready, numbered)
|
||||
};
|
||||
r.numbered = numbered;
|
||||
for ev in &ready {
|
||||
r.run(ev, "")?;
|
||||
}
|
||||
r.numbered.clear();
|
||||
// The calculations, before form:ready (XFA 3.3 fires the form ready event once they have run;
|
||||
// another viewer runs them there too).
|
||||
r.calculates()?;
|
||||
let calculated = r.field_changes.clone();
|
||||
// `ready` without `ref="$layout"` is form:ready: in the reverse of initialize's order, the
|
||||
// root first and the objects inside it last to first, as another viewer runs it.
|
||||
for ev in &objects_reversed(children_first(r.events_named("ready"))) {
|
||||
r.run(ev, "")?;
|
||||
}
|
||||
// Lay the form out once for what the scripts so far changed, then the layout:ready scripts
|
||||
// see the new pages.
|
||||
r.defer_relayout = false;
|
||||
r.owed_relayout()?;
|
||||
r.layout_ready()?;
|
||||
for ev in &r.events_named("docReady") {
|
||||
r.run(ev, "")?;
|
||||
}
|
||||
// A ready script wrote a value: the calculations run again, as after any change (which of
|
||||
// them read it isn't known here, so all of them).
|
||||
if r.field_changes != calculated {
|
||||
r.calculates()?;
|
||||
}
|
||||
r.finish()
|
||||
}
|
||||
|
||||
/// What a click on a check box or radio button runs once it has set the value, in order: the
|
||||
/// change scripts, then the click scripts, each reading the new value. A radio group runs each
|
||||
/// activity's scripts, then the radio button now on runs its own; the button it turned off runs
|
||||
/// none. Exit scripts follow, as after any change: the button's, then the group's. This is the
|
||||
/// order another viewer showed on a synthetic form.
|
||||
const TOGGLE_ORDER: [&str; 2] = ["change", "click"];
|
||||
|
||||
/// `events` with their objects in the reverse order, each object's own events keeping theirs.
|
||||
fn objects_reversed(events: Vec<ScriptEvent>) -> Vec<ScriptEvent> {
|
||||
let mut objects: Vec<Vec<ScriptEvent>> = Vec::new();
|
||||
for ev in events {
|
||||
match objects.last_mut() {
|
||||
Some(last) if last.first().is_some_and(|e| e.som == ev.som) => last.push(ev),
|
||||
_ => objects.push(vec![ev]),
|
||||
}
|
||||
}
|
||||
objects.into_iter().rev().flatten().collect()
|
||||
}
|
||||
|
||||
/// `events` (in document order) reordered so that each object's come after those of the objects
|
||||
/// inside it, siblings keeping their order; an object's own events keep theirs.
|
||||
fn children_first(events: Vec<ScriptEvent>) -> Vec<ScriptEvent> {
|
||||
let mut out = Vec::with_capacity(events.len());
|
||||
// The objects whose events wait for their children's, outermost first.
|
||||
let mut open: Vec<Vec<ScriptEvent>> = Vec::new();
|
||||
for ev in events {
|
||||
while let Some(top) = open.last() {
|
||||
let parent = top.first().map_or("", |e| e.som.as_str());
|
||||
// The same object, or one inside it (the root may have an empty path).
|
||||
let inside = parent.is_empty() || ev.som == parent || ev.som.strip_prefix(parent).is_some_and(|rest| rest.starts_with('.'));
|
||||
if inside {
|
||||
break;
|
||||
}
|
||||
out.extend(open.pop().unwrap_or_default());
|
||||
}
|
||||
match open.last_mut() {
|
||||
Some(top) if top.first().is_some_and(|e| e.som == ev.som) => top.push(ev),
|
||||
_ => open.push(vec![ev]),
|
||||
}
|
||||
}
|
||||
while let Some(top) = open.pop() {
|
||||
out.extend(top);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// After fields `names` took new values: each one's change, exit and validate scripts, then
|
||||
/// the calculations once (or only those, after a reset). A validate script that answers false,
|
||||
/// or fails, shows its message; the value stays, as Acrobat marks the field invalid rather
|
||||
/// than reverting it. The SOM paths whose exit scripts ran go into `exited`.
|
||||
/// the calculations once (or only those, after a reset). A check box or radio button runs its
|
||||
/// click scripts too ([`TOGGLE_ORDER`]): it changes only when it is clicked, and a click script
|
||||
/// reads the new value. A validate script that answers false, or fails, shows its message; the
|
||||
/// value stays, as Acrobat marks the field invalid rather than reverting it. `before` holds each
|
||||
/// field's value before the edit: a check box or radio group set to the value it had runs no
|
||||
/// click scripts, since nothing was clicked. A field named twice (a batch that sets it twice)
|
||||
/// is compared the second time with what the first left, so it is clicked once at most. The
|
||||
/// SOM paths whose exit scripts ran go into `exited`.
|
||||
pub(crate) fn on_changes(
|
||||
doc: &mut pdfcraft_cos::Document,
|
||||
tpl: &Template,
|
||||
names: &[String],
|
||||
before: &HashMap<String, Vec<String>>,
|
||||
run: &mut XfaRun,
|
||||
exited: &mut Vec<String>,
|
||||
) -> Result<(), String> {
|
||||
let mut r = Runner::new(doc, tpl, run, OPEN_BUDGET_MS);
|
||||
// Each field's value once its scripts have run, for a later mention of the same field.
|
||||
let mut done: HashMap<String, Vec<String>> = HashMap::new();
|
||||
for name in names {
|
||||
let som = r.by_som().iter().find(|(_, f)| *f == name).map(|(s, _)| s.clone());
|
||||
let Some(som) = som else { continue };
|
||||
let value = r.fields().get(name).map(|f| f.value.join("\n")).unwrap_or_default();
|
||||
for ev in r.events_of(&som, "change") {
|
||||
r.run(&ev, &value)?;
|
||||
let clicked = r.clicked(name, &som, done.get(name).or_else(|| before.get(name)));
|
||||
let steps: &[&str] = if clicked.is_some() { &TOGGLE_ORDER } else { &["change"] };
|
||||
// A radio group's button now on runs each activity's scripts after the group's, and
|
||||
// its exit scripts before the group's, as when leaving it.
|
||||
let button = clicked.as_deref().filter(|b| *b != som);
|
||||
for activity in steps.iter().copied() {
|
||||
for at in [Some(som.as_str()), button].into_iter().flatten() {
|
||||
for ev in r.events_of(at, activity) {
|
||||
r.run(&ev, &value)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(b) = button {
|
||||
let mut ran_exit = false;
|
||||
for ev in r.events_of(b, "exit") {
|
||||
ran_exit |= r.run(&ev, &value)?.is_some();
|
||||
}
|
||||
if ran_exit {
|
||||
exited.push(b.to_string());
|
||||
}
|
||||
}
|
||||
// Noted only when an exit script ran, whether it succeeded or failed: it has run for this
|
||||
// focus loss, and a failed script keeps what it changed before its error, so running it
|
||||
@@ -1353,11 +1522,22 @@ pub(crate) fn on_changes(
|
||||
r.alert(crate::js::Message::plain(ev.message.clone().unwrap_or_else(|| format!("{name}: the value is not valid"))));
|
||||
}
|
||||
}
|
||||
if let Some(f) = r.fields().get(name) {
|
||||
done.insert(name.clone(), f.value.clone());
|
||||
}
|
||||
}
|
||||
r.calculates()?;
|
||||
r.finish().map(|_| ())
|
||||
}
|
||||
|
||||
/// The form was laid out again outside its scripts (a field's text grew or shrank): its
|
||||
/// layout:ready scripts run, as after any new layout, and what they change is written.
|
||||
pub(crate) fn on_layout(doc: &mut pdfcraft_cos::Document, tpl: &Template, run: &mut XfaRun) -> Result<(), String> {
|
||||
let mut r = Runner::new(doc, tpl, run, OPEN_BUDGET_MS);
|
||||
r.layout_ready()?;
|
||||
r.finish().map(|_| ())
|
||||
}
|
||||
|
||||
/// The form's data changed outside its scripts (a data file imported, a picture chosen): lay
|
||||
/// the form out again from the data, then, when `calculate`, run every calculation.
|
||||
pub(crate) fn on_data_replaced(doc: &mut pdfcraft_cos::Document, tpl: &Template, calculate: bool, run: &mut XfaRun) -> Result<(), String> {
|
||||
|
||||
@@ -244,11 +244,15 @@ pub(crate) fn xfa_after_data_change(doc: &mut pdfcraft_cos::Document, cx: &mut E
|
||||
highlight,
|
||||
time_scale: cx.xfa_time_scale,
|
||||
answers: Default::default(),
|
||||
relaid: false,
|
||||
};
|
||||
let r = guard(|| xfa::on_data_replaced(doc, &tpl, calculate, &mut run))
|
||||
.unwrap_or_else(|m| Err(format!("laying the form out again failed unexpectedly ({m})")));
|
||||
cx.xfa_datasets = run.datasets;
|
||||
cx.xfa_ran_away |= run.ran_away;
|
||||
// The next XFA run of a batch starts from the page count this one left.
|
||||
cx.pages = run.page_count;
|
||||
cx.xfa_relaid |= run.relaid;
|
||||
// The next edit of a batch reads the highlight this one's scripts set.
|
||||
let on = run.highlight;
|
||||
cx.set_highlight(on);
|
||||
|
||||
@@ -0,0 +1,234 @@
|
||||
use std::{collections::BTreeMap, sync::Arc};
|
||||
|
||||
use pdfcraft_cos::{Dict, Document, Object, PdfString, SaveOptions, Stream, write_full};
|
||||
use pdfcraft_engine::{Edit, Session};
|
||||
use pdfcraft_organize::FieldConflicts;
|
||||
|
||||
fn dict<const N: usize>(entries: [(&str, Object); N]) -> Dict {
|
||||
let mut out = Dict::new();
|
||||
for (key, value) in entries {
|
||||
out.set(key.as_bytes().to_vec(), value);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn packet(title: &str, attachment_key: Option<Vec<u8>>, indirect_names: bool) -> Arc<Vec<u8>> {
|
||||
let mut doc = Document::new_empty();
|
||||
let pages = doc.add(Object::Null);
|
||||
let font = doc.add(dict([("Type", Object::name("Font")), ("Subtype", Object::name("Type1")), ("BaseFont", Object::name("Helvetica"))]));
|
||||
let body = format!("BT /F1 12 Tf 72 720 Td ({title}) Tj ET");
|
||||
let content = doc.add(Object::Stream(Stream::from_raw(Dict::new(), body.into_bytes())));
|
||||
let page = doc.add(dict([
|
||||
("Type", Object::name("Page")),
|
||||
("Parent", Object::Ref(pages)),
|
||||
("MediaBox", Object::Array([0, 0, 612, 792].map(Object::Int).to_vec())),
|
||||
("Contents", Object::Ref(content)),
|
||||
("Resources", Object::Dict(dict([("Font", Object::Dict(dict([("F1", Object::Ref(font))])))]))),
|
||||
]));
|
||||
doc.set(pages, dict([("Type", Object::name("Pages")), ("Kids", Object::Array(vec![Object::Ref(page)])), ("Count", Object::Int(1))]));
|
||||
let destinations = doc.add(dict([(
|
||||
"Names",
|
||||
Object::Array(vec![Object::String(PdfString::text("PaymentSchedule")), Object::Array(vec![Object::Ref(page), Object::name("Fit")])]),
|
||||
)]));
|
||||
let mut names = dict([("Dests", Object::Ref(destinations))]);
|
||||
if let Some(key) = attachment_key {
|
||||
let payload = format!("{title}: vendor insurance verified; review owner Procurement Operations; next review 2027-01-31.\n");
|
||||
let file = doc.add(Object::Stream(Stream::from_raw(
|
||||
dict([
|
||||
("Type", Object::name("EmbeddedFile")),
|
||||
("Subtype", Object::name("text/plain")),
|
||||
("Params", Object::Dict(dict([("Size", Object::Int(payload.len() as i64))]))),
|
||||
]),
|
||||
payload.into_bytes(),
|
||||
)));
|
||||
let spec = doc.add(dict([
|
||||
("Type", Object::name("Filespec")),
|
||||
("F", Object::String(PdfString::text("vendor-compliance.txt"))),
|
||||
("EF", Object::Dict(dict([("F", Object::Ref(file))]))),
|
||||
]));
|
||||
let leaf = doc.add(dict([
|
||||
("Names", Object::Array(vec![Object::String(PdfString::literal(key.clone())), Object::Ref(spec)])),
|
||||
("Limits", Object::Array(vec![Object::String(PdfString::literal(key.clone())), Object::String(PdfString::literal(key))])),
|
||||
]));
|
||||
let tree = doc.add(dict([("Kids", Object::Array(vec![Object::Ref(leaf)]))]));
|
||||
names.set(b"EmbeddedFiles".to_vec(), Object::Ref(tree));
|
||||
}
|
||||
let names = if indirect_names { Object::Ref(doc.add(names)) } else { Object::Dict(names) };
|
||||
let root = doc.add(dict([("Type", Object::name("Catalog")), ("Pages", Object::Ref(pages)), ("Names", names)]));
|
||||
doc.trailer_mut().set(b"Root".to_vec(), Object::Ref(root));
|
||||
Arc::new(write_full(&doc, &SaveOptions::default()).unwrap())
|
||||
}
|
||||
|
||||
fn attachments(doc: &Document) -> Vec<(Vec<u8>, Vec<u8>)> {
|
||||
fn visit(doc: &Document, tree: &Object, out: &mut Vec<(Vec<u8>, Vec<u8>)>) {
|
||||
let tree = doc.resolve(tree);
|
||||
let tree = tree.as_dict().unwrap();
|
||||
if let Some(names) = tree.get(b"Names") {
|
||||
for pair in doc.resolve(names).as_array().unwrap().as_chunks::<2>().0 {
|
||||
let key = pair[0].as_string().unwrap();
|
||||
let spec = doc.resolve(&pair[1]);
|
||||
let ef = doc.resolve(spec.as_dict().unwrap().get(b"EF").unwrap());
|
||||
let file = doc.resolve(ef.as_dict().unwrap().get(b"F").unwrap());
|
||||
let Object::Stream(file) = file.as_ref() else { panic!("embedded file stream expected") };
|
||||
out.push((key.bytes.to_vec(), file.decoded().unwrap()));
|
||||
}
|
||||
}
|
||||
if let Some(kids) = tree.get(b"Kids") {
|
||||
for kid in doc.resolve(kids).as_array().unwrap() {
|
||||
visit(doc, kid, out);
|
||||
}
|
||||
}
|
||||
}
|
||||
let catalog = doc.get(doc.root().unwrap());
|
||||
let names = doc.resolve(catalog.as_dict().unwrap().get(b"Names").unwrap());
|
||||
let mut out = Vec::new();
|
||||
if let Some(tree) = names.as_dict().unwrap().get(b"EmbeddedFiles") {
|
||||
visit(doc, tree, &mut out);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn assert_destination_retained(doc: &Document) {
|
||||
let catalog = doc.get(doc.root().unwrap());
|
||||
let names = doc.resolve(catalog.as_dict().unwrap().get(b"Names").unwrap());
|
||||
let dests = doc.resolve(names.as_dict().unwrap().get(b"Dests").expect("target destination tree retained"));
|
||||
let values = dests.as_dict().unwrap().get(b"Names").unwrap().as_array().unwrap();
|
||||
assert_eq!(values[0].as_string().unwrap().to_text(), "PaymentSchedule");
|
||||
let page = values[1].as_array().unwrap()[0].as_ref().unwrap();
|
||||
assert_eq!(doc.get(page).as_dict().unwrap().name(b"Type"), Some(b"Page".as_slice()));
|
||||
}
|
||||
|
||||
fn insert(bytes: Arc<Vec<u8>>) -> Edit {
|
||||
Edit::InsertPagesFrom { name: "Facilities Compliance Annex.pdf".into(), bytes, pages: None, at: 1, field_conflicts: FieldConflicts::Rename }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inserted_catalog_attachments_follow_native_undo_redo() {
|
||||
let unicode = "合规审查.txt";
|
||||
let be: Vec<u8> = [0xfe, 0xff].into_iter().chain(unicode.encode_utf16().flat_map(u16::to_be_bytes)).collect();
|
||||
let le: Vec<u8> = [0xff, 0xfe].into_iter().chain(unicode.encode_utf16().flat_map(u16::to_le_bytes)).collect();
|
||||
for key in [b"vendor-compliance.txt".to_vec(), be, le] {
|
||||
// Check raw keys to preserve the incoming encoding, including LE files
|
||||
// whose labels PdfString::to_text does not currently decode.
|
||||
let mut renamed = key.clone();
|
||||
match key.get(..2) {
|
||||
Some([0xfe, 0xff]) => renamed.extend(" (2)".encode_utf16().flat_map(u16::to_be_bytes)),
|
||||
Some([0xff, 0xfe]) => renamed.extend(" (2)".encode_utf16().flat_map(u16::to_le_bytes)),
|
||||
_ => renamed.extend_from_slice(b" (2)"),
|
||||
}
|
||||
for indirect in [false, true] {
|
||||
let target = packet("Facilities Service Agreement", Some(key.clone()), indirect);
|
||||
let source = packet("Facilities Compliance Annex", Some(key.clone()), true);
|
||||
let mut session = Session::new();
|
||||
session.set_javascript(false);
|
||||
let id = session.open("Facilities Contract.pdf", None, target, None).unwrap();
|
||||
session.apply(id, Edit::Batch { label: "Merge Annex".into(), edits: vec![insert(source.clone())] }).unwrap();
|
||||
let bytes = session.save_bytes(id).unwrap();
|
||||
let merged = Document::open(bytes).unwrap();
|
||||
let entries = attachments(&merged);
|
||||
assert_eq!(entries.len(), 2, "target and source attachments must survive");
|
||||
assert!(entries.windows(2).all(|p| p[0].0 < p[1].0), "name tree keys sorted and unique");
|
||||
let by_key: BTreeMap<_, _> = entries.into_iter().collect();
|
||||
assert!(by_key[&key].starts_with(b"Facilities Service Agreement:"));
|
||||
assert!(by_key[&renamed].starts_with(b"Facilities Compliance Annex:"));
|
||||
assert_destination_retained(&merged);
|
||||
assert_eq!(session.get(id).unwrap().info.pages.len(), 2);
|
||||
assert_eq!(session.get(id).unwrap().can_undo(), Some("Merge Annex"));
|
||||
session.undo(id).unwrap();
|
||||
let undone = Document::open(session.save_bytes(id).unwrap()).unwrap();
|
||||
assert_eq!(attachments(&undone).len(), 1);
|
||||
assert_destination_retained(&undone);
|
||||
assert_eq!(session.get(id).unwrap().info.pages.len(), 1);
|
||||
session.redo(id).unwrap();
|
||||
let redone = Document::open(session.save_bytes(id).unwrap()).unwrap();
|
||||
assert_eq!(attachments(&redone).len(), 2);
|
||||
assert_destination_retained(&redone);
|
||||
assert_eq!(session.get(id).unwrap().info.pages.len(), 2);
|
||||
assert_eq!(attachments(&Document::open(source).unwrap()).len(), 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inserting_into_a_document_without_attachments_retains_other_names() {
|
||||
let mut session = Session::new();
|
||||
session.set_javascript(false);
|
||||
let id = session.open("Facilities Contract.pdf", None, packet("Facilities Service Agreement", None, true), None).unwrap();
|
||||
session.apply(id, insert(packet("Facilities Compliance Annex", Some(b"vendor-compliance.txt".to_vec()), true))).unwrap();
|
||||
let result = Document::open(session.save_bytes(id).unwrap()).unwrap();
|
||||
assert_eq!(attachments(&result).len(), 1);
|
||||
assert_destination_retained(&result);
|
||||
session.undo(id).unwrap();
|
||||
assert!(attachments(&Document::open(session.save_bytes(id).unwrap()).unwrap()).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inserting_without_source_attachments_does_not_rewrite_target_names() {
|
||||
let mut session = Session::new();
|
||||
session.set_javascript(false);
|
||||
let id = session
|
||||
.open("Facilities Contract.pdf", None, packet("Facilities Service Agreement", Some(b"contract-evidence.txt".to_vec()), true), None)
|
||||
.unwrap();
|
||||
let before = Document::open(session.save_bytes(id).unwrap()).unwrap();
|
||||
let names = before.get(before.root().unwrap()).as_dict().unwrap().get(b"Names").unwrap().clone();
|
||||
assert!(matches!(names, Object::Ref(_)));
|
||||
session.apply(id, insert(packet("Facilities Payment Schedule", None, false))).unwrap();
|
||||
let after = Document::open(session.save_bytes(id).unwrap()).unwrap();
|
||||
assert_eq!(after.get(after.root().unwrap()).as_dict().unwrap().get(b"Names"), Some(&names));
|
||||
assert_eq!(attachments(&after), attachments(&before));
|
||||
assert_destination_retained(&after);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selecting_no_pages_does_not_import_catalog_attachments() {
|
||||
let mut session = Session::new();
|
||||
session.set_javascript(false);
|
||||
let id = session
|
||||
.open("Facilities Contract.pdf", None, packet("Facilities Service Agreement", Some(b"contract-evidence.txt".to_vec()), true), None)
|
||||
.unwrap();
|
||||
let before = Document::open(session.save_bytes(id).unwrap()).unwrap();
|
||||
session
|
||||
.apply(
|
||||
id,
|
||||
Edit::InsertPagesFrom {
|
||||
name: "Facilities Compliance Annex.pdf".into(),
|
||||
bytes: packet("Facilities Compliance Annex", Some(b"vendor-compliance.txt".to_vec()), true),
|
||||
pages: Some(Vec::new()),
|
||||
at: 1,
|
||||
field_conflicts: FieldConflicts::Rename,
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(session.get(id).unwrap().info.pages.len(), 1);
|
||||
let after = Document::open(session.save_bytes(id).unwrap()).unwrap();
|
||||
assert_eq!(attachments(&after), attachments(&before));
|
||||
assert_destination_retained(&after);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_insert_batch_rolls_back_pages_and_attachments() {
|
||||
let mut session = Session::new();
|
||||
session.set_javascript(false);
|
||||
let id = session
|
||||
.open("Facilities Contract.pdf", None, packet("Facilities Service Agreement", Some(b"contract-evidence.txt".to_vec()), true), None)
|
||||
.unwrap();
|
||||
assert!(
|
||||
session
|
||||
.apply(
|
||||
id,
|
||||
Edit::Batch {
|
||||
label: "Merge Annex".into(),
|
||||
edits: vec![
|
||||
insert(packet("Facilities Compliance Annex", Some(b"vendor-compliance.txt".to_vec()), true)),
|
||||
Edit::RotatePages { pages: vec![99], degrees: 90 },
|
||||
]
|
||||
}
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
assert_eq!(session.get(id).unwrap().info.pages.len(), 1);
|
||||
assert_eq!(session.get(id).unwrap().can_undo(), None);
|
||||
let result = Document::open(session.save_bytes(id).unwrap()).unwrap();
|
||||
assert_eq!(attachments(&result).len(), 1);
|
||||
assert_destination_retained(&result);
|
||||
}
|
||||
+192
-28
@@ -42,6 +42,8 @@ pub struct Metrics {
|
||||
explicit_default: bool,
|
||||
/// The standard-14 face to measure with when the dictionary carries no `/Widths`.
|
||||
std14: Option<crate::Std14>,
|
||||
/// [`Metrics::std14`] is the face `/BaseFont` names (or a common alias of it), not a guess.
|
||||
std14_named: bool,
|
||||
/// Glyph units → text space (0.001, or `/FontMatrix[0]` for Type 3).
|
||||
pub scale: f64,
|
||||
/// Glyph box in text space per unit of font size.
|
||||
@@ -67,6 +69,8 @@ pub struct Metrics {
|
||||
/// Subset CIDFontType2 only: one bit per CID (below 65 536) whose glyph has an outline in the
|
||||
/// embedded program. See [`cids_with_outlines`].
|
||||
outlined_cids: Vec<u64>,
|
||||
/// Whether this font is an OCR placeholder font with no real letterforms (e.g. `/Glyphless`).
|
||||
glyphless: bool,
|
||||
/// A stream these metrics come from (a CMap, the program, `/CIDToGIDMap`, a Type 3 glyph
|
||||
/// description) was left unread because the decode allowance [`Metrics::from_dict_within`]
|
||||
/// was given was spent: what it would have decided (code lengths, CIDs, widths, meanings, a
|
||||
@@ -91,6 +95,79 @@ fn dict(doc: &Document, o: Option<&Object>) -> Option<Dict> {
|
||||
o.and_then(|o| doc.resolve(o).as_dict().cloned())
|
||||
}
|
||||
|
||||
/// Strip a six-letter uppercase `ABCDEF+` subset prefix, if present.
|
||||
fn strip_subset_prefix(name: &str) -> &str {
|
||||
name.split_once('+').filter(|(tag, _)| tag.len() == 6 && tag.bytes().all(|b| b.is_ascii_uppercase())).map_or(name, |(_, rest)| rest)
|
||||
}
|
||||
|
||||
/// Whether `name` identifies an OCR placeholder font that carries widths and Unicode mappings
|
||||
/// for invisible (`3 Tr`) text selection but no real letterforms.
|
||||
fn glyphless_font_name(name: &str) -> bool {
|
||||
let stem = strip_subset_prefix(name).to_ascii_lowercase();
|
||||
stem.starts_with("glyphless") || stem.starts_with("hiddenhorzocr") || stem.starts_with("hiddenvertocr")
|
||||
}
|
||||
|
||||
/// Whether `font` carries a known OCR placeholder font name (`Glyphless*`, `HiddenHorzOCR`,
|
||||
/// `HiddenVertOCR`, with optional six-letter `ABCDEF+` subset prefix).
|
||||
fn has_glyphless_font_name(doc: &Document, font: &Dict) -> bool {
|
||||
let descendant = dict(doc, font.get(b"DescendantFonts").and_then(|o| doc.resolve(o).as_array().and_then(|a| a.first()).cloned()).as_ref());
|
||||
let descriptor = dict(doc, descendant.as_ref().unwrap_or(font).get(b"FontDescriptor"));
|
||||
[font.name(b"BaseFont"), descendant.as_ref().and_then(|d| d.name(b"BaseFont")), descriptor.as_ref().and_then(|d| d.name(b"FontName"))]
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.any(|name| glyphless_font_name(&String::from_utf8_lossy(name)))
|
||||
}
|
||||
|
||||
/// If every non-zero `/CIDToGIDMap` entry (skipping CID 0) maps to the exact same glyph ID and
|
||||
/// there are at least 64 such entries, returns that shared glyph ID.
|
||||
fn shared_single_gid(map: &[u8]) -> Option<usize> {
|
||||
let mut gids = map.as_chunks::<2>().0.iter().skip(1).map(|gid| usize::from(u16::from_be_bytes(*gid))).filter(|&gid| gid != 0);
|
||||
let mapped_gid = gids.next()?;
|
||||
let mut mapped = 1usize;
|
||||
for gid in gids {
|
||||
if gid != mapped_gid {
|
||||
return None;
|
||||
}
|
||||
mapped += 1;
|
||||
}
|
||||
(mapped >= 64).then_some(mapped_gid)
|
||||
}
|
||||
|
||||
/// Returns `Some(gid)` when `loca` has exactly one outlined glyph ID (`>= 1`), stopping at the
|
||||
/// second outlined glyph.
|
||||
fn only_outlined_gid_from_loca(loca: &skrifa::raw::tables::loca::Loca<'_>) -> Option<usize> {
|
||||
let mut outlined =
|
||||
(1..loca.len().min(0x1_0000)).filter(|&gid| loca.get_raw(gid).zip(loca.get_raw(gid + 1)).is_some_and(|(start, end)| end > start));
|
||||
let gid = outlined.next()?;
|
||||
outlined.next().is_none().then_some(gid)
|
||||
}
|
||||
|
||||
/// Returns `Some(gid)` when the TrueType program in `face` has exactly one outlined glyph ID.
|
||||
fn only_outlined_gid(face: &skrifa::FontRef<'_>) -> Option<usize> {
|
||||
use skrifa::raw::TableProvider as _;
|
||||
let loca = face.loca(None).ok()?;
|
||||
only_outlined_gid_from_loca(&loca)
|
||||
}
|
||||
|
||||
/// Whether `descendant`'s `/CIDToGIDMap` stream maps at least 64 CIDs solely to `mapped_gid`.
|
||||
/// Returns `None` if decoding failed or spent the allowance.
|
||||
fn stream_shares_single_gid(doc: &Document, descendant: Option<&Dict>, mapped_gid: usize, budget: &mut DecodeBudget) -> Option<bool> {
|
||||
let cid_to_gid = descendant.and_then(|d| d.get(b"CIDToGIDMap")).map(|o| doc.resolve(o));
|
||||
let Some(Object::Stream(map)) = cid_to_gid.as_deref() else { return Some(false) };
|
||||
let mut reads = Reads::new(doc, budget);
|
||||
let Some(map) = reads.decode(map, MAX_CID_TO_GID) else {
|
||||
return (!reads.refused).then_some(false);
|
||||
};
|
||||
Some(shared_single_gid(&map) == Some(mapped_gid))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn is_glyphless(doc: &Document, font: &Dict) -> bool {
|
||||
let mut budget = DecodeBudget::new(usize::MAX, 0);
|
||||
let mut reads = Reads::new(doc, &mut budget);
|
||||
has_glyphless_font_name(doc, font) || composite_outlines_and_glyphless(doc, font, false, None, &mut reads).1
|
||||
}
|
||||
|
||||
/// Whether `font`'s `/Encoding` is the name Identity-H, given directly or through a reference,
|
||||
/// as [`Metrics::from_dict`] reads it (a Type 0 font's `/Encoding` may be indirect).
|
||||
fn identity_h(doc: &Document, font: &Dict) -> bool {
|
||||
@@ -100,9 +177,7 @@ fn identity_h(doc: &Document, font: &Dict) -> bool {
|
||||
/// Whether `base_font` (subset tag allowed) names a legacy Indic font family that is laid out in
|
||||
/// visual order (Kruti Dev, DevLys, Chanakya, Shusha, Shivaji, Walkman, Akruti, APS-DV, DV-TT…).
|
||||
fn legacy_indic_font(base_font: &str) -> bool {
|
||||
let name =
|
||||
base_font.split_once('+').filter(|(tag, _)| tag.len() == 6 && tag.bytes().all(|b| b.is_ascii_uppercase())).map_or(base_font, |(_, n)| n);
|
||||
let name = name.to_ascii_lowercase();
|
||||
let name = strip_subset_prefix(base_font).to_ascii_lowercase();
|
||||
["kruti", "devlys", "chanakya", "shusha", "shivaji", "walkman", "akruti"].iter().any(|n| name.contains(n))
|
||||
|| ["aps-", "dv-"].iter().any(|p| name.starts_with(p))
|
||||
}
|
||||
@@ -123,6 +198,9 @@ const MAX_SFNT: usize = 16 << 20;
|
||||
/// streams of the metrics read that adapts a program without a Unicode cmap.
|
||||
pub fn embedded_sfnt_within(doc: &Document, font: &Dict, budget: &mut DecodeBudget) -> Option<Vec<u8>> {
|
||||
use skrifa::{MetadataProvider as _, raw::TableProvider as _};
|
||||
if has_glyphless_font_name(doc, font) {
|
||||
return None;
|
||||
}
|
||||
let descendant = dict(doc, font.get(b"DescendantFonts").and_then(|o| doc.resolve(o).as_array().and_then(|a| a.first()).cloned()).as_ref());
|
||||
let descriptor = dict(doc, descendant.as_ref().unwrap_or(font).get(b"FontDescriptor"))?;
|
||||
for key in [b"FontFile2".as_slice(), b"FontFile3".as_slice()] {
|
||||
@@ -138,10 +216,16 @@ pub fn embedded_sfnt_within(doc: &Document, font: &Dict, budget: &mut DecodeBudg
|
||||
continue;
|
||||
}
|
||||
let own_cmap = face.charmap().mappings().next().is_some();
|
||||
let single_gid = only_outlined_gid(&face);
|
||||
// A legacy THSarabunPSK subset may keep a Latin-only cmap beside its Thai glyphs, which
|
||||
// only the PDF's verified maps reach (`composite_glyph_maps`); other programs keep theirs.
|
||||
let base_font = font.name(b"BaseFont").map(String::from_utf8_lossy).unwrap_or_default();
|
||||
if own_cmap && !base_font.rsplit('+').next().is_some_and(|f| f.starts_with("THSarabunPSK")) {
|
||||
if let Some(gid) = single_gid
|
||||
&& stream_shares_single_gid(doc, descendant.as_ref(), gid, budget) != Some(false)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
return Some(bytes);
|
||||
}
|
||||
// A composite font's cmap is rebuilt only through Identity-H codes (`composite_glyph_maps`):
|
||||
@@ -149,6 +233,11 @@ pub fn embedded_sfnt_within(doc: &Document, font: &Dict, budget: &mut DecodeBudg
|
||||
// cmap of its own is kept as it is, as when the rebuild finds nothing.
|
||||
if font.name(b"Subtype") == Some(b"Type0") && !identity_h(doc, font) {
|
||||
if own_cmap {
|
||||
if let Some(gid) = single_gid
|
||||
&& stream_shares_single_gid(doc, descendant.as_ref(), gid, budget) != Some(false)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
return Some(bytes);
|
||||
}
|
||||
continue;
|
||||
@@ -156,9 +245,10 @@ pub fn embedded_sfnt_within(doc: &Document, font: &Dict, budget: &mut DecodeBudg
|
||||
// PDF subsets may remove the Unicode cmap entirely. Rebuild an editor-only
|
||||
// cmap from ToUnicode and the actual CID-to-glyph map; source bytes stay unchanged.
|
||||
// Metrics read past the allowance, its widths' read of the program again included,
|
||||
// adapt no copy.
|
||||
let metrics = Metrics::from_dict_within(doc, font, budget);
|
||||
if metrics.past_allowance {
|
||||
// adapt no copy. Skip redundant structural glyphless check when >=2 (or 0) outlined glyphs exist.
|
||||
let known_glyphless = single_gid.is_none().then_some(false);
|
||||
let metrics = Metrics::from_dict_with_glyphless(doc, font, budget, known_glyphless);
|
||||
if metrics.glyphless || metrics.past_allowance {
|
||||
continue;
|
||||
}
|
||||
let mut mappings = std::collections::BTreeMap::new();
|
||||
@@ -206,35 +296,66 @@ pub fn embedded_sfnt_within(doc: &Document, font: &Dict, budget: &mut DecodeBudg
|
||||
None
|
||||
}
|
||||
|
||||
/// The CIDs (below 65 536) of a Type 0 font over an embedded TrueType program whose glyph has
|
||||
/// outline data, through `/CIDToGIDMap`; empty when the program or the map can't be read.
|
||||
/// Subsetters keep glyph ids and empty the glyphs they drop, so an empty glyph is a missing one.
|
||||
fn cids_with_outlines(doc: &Document, font: &Dict, reads: &mut Reads<'_>) -> Vec<u64> {
|
||||
/// The CIDs (below 65 536) of a subset Type 0 font over an embedded TrueType program whose glyph
|
||||
/// has outline data, plus whether the font is a shared-glyph placeholder font. Decodes
|
||||
/// `FontFile2` and `/CIDToGIDMap` at most once each against `reads`.
|
||||
fn composite_outlines_and_glyphless(
|
||||
doc: &Document,
|
||||
font: &Dict,
|
||||
is_subset: bool,
|
||||
known_glyphless: Option<bool>,
|
||||
reads: &mut Reads<'_>,
|
||||
) -> (Vec<u64>, bool) {
|
||||
use skrifa::raw::TableProvider as _;
|
||||
if known_glyphless == Some(true) {
|
||||
return (Vec::new(), true);
|
||||
}
|
||||
let Some(descendant) = dict(doc, font.get(b"DescendantFonts").and_then(|o| doc.resolve(o).as_array().and_then(|a| a.first()).cloned()).as_ref())
|
||||
else {
|
||||
return Vec::new();
|
||||
return (Vec::new(), false);
|
||||
};
|
||||
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 Some(bytes) = reads.decode(stream, MAX_SFNT) 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 font_file2 = |doc: &Document, reads: &mut Reads<'_>| {
|
||||
let program = dict(doc, descendant.get(b"FontDescriptor")).and_then(|d| d.get(b"FontFile2").cloned())?;
|
||||
let program = doc.resolve(&program);
|
||||
let Object::Stream(stream) = program.as_ref() else { return None };
|
||||
reads.decode(stream, MAX_SFNT)
|
||||
};
|
||||
if !is_subset {
|
||||
if known_glyphless == Some(false) {
|
||||
return (Vec::new(), false);
|
||||
}
|
||||
let cid_to_gid = descendant.get(b"CIDToGIDMap").map(|o| doc.resolve(o));
|
||||
let Some(Object::Stream(map)) = cid_to_gid.as_deref() else { return (Vec::new(), false) };
|
||||
let Some(map) = reads.decode(map, MAX_CID_TO_GID) else { return (Vec::new(), false) };
|
||||
let Some(mapped_gid) = shared_single_gid(&map) else { return (Vec::new(), false) };
|
||||
let Some(bytes) = font_file2(doc, reads) else { return (Vec::new(), false) };
|
||||
let glyphless = skrifa::FontRef::from_index(&bytes, 0).ok().and_then(|face| only_outlined_gid(&face)) == Some(mapped_gid);
|
||||
return (Vec::new(), glyphless);
|
||||
}
|
||||
let Some(bytes) = font_file2(doc, reads) else { return (Vec::new(), false) };
|
||||
let Some(loca) = skrifa::FontRef::from_index(&bytes, 0).ok().and_then(|face| face.loca(None).ok()) else { return (Vec::new(), false) };
|
||||
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))),
|
||||
None | Some(Object::Name(_)) => (bit_set_below_64k((0..loca.len().min(0x1_0000) as u32).filter(|&gid| outlined(gid))), false),
|
||||
Some(Object::Stream(map)) => {
|
||||
let Some(map) = reads.decode(map, MAX_CID_TO_GID) else { return Vec::new() };
|
||||
bit_set_below_64k(
|
||||
let Some(map) = reads.decode(map, MAX_CID_TO_GID) else { return (Vec::new(), false) };
|
||||
if known_glyphless.is_none()
|
||||
&& let Some(single_gid) = only_outlined_gid_from_loca(&loca)
|
||||
&& shared_single_gid(&map) == Some(single_gid)
|
||||
{
|
||||
return (Vec::new(), true);
|
||||
}
|
||||
let cids = bit_set_below_64k(
|
||||
map.as_chunks::<2>()
|
||||
.0
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, gid)| outlined(u32::from(u16::from_be_bytes(**gid))))
|
||||
.map(|(cid, _)| cid as u32),
|
||||
)
|
||||
);
|
||||
(cids, false)
|
||||
}
|
||||
Some(_) => Vec::new(),
|
||||
Some(_) => (Vec::new(), false),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -899,6 +1020,7 @@ impl Metrics {
|
||||
default: 500.0,
|
||||
explicit_default: false,
|
||||
std14: Some(crate::Std14::Helvetica),
|
||||
std14_named: false,
|
||||
scale: 0.001,
|
||||
ascent: 0.9,
|
||||
descent: -0.25,
|
||||
@@ -912,6 +1034,7 @@ impl Metrics {
|
||||
code_len: 1,
|
||||
explicit_reverse: (32..127u8).map(|c| (char::from(c), u32::from(c))).collect(),
|
||||
outlined_cids: Vec::new(),
|
||||
glyphless: false,
|
||||
past_allowance: false,
|
||||
codespaces_dropped: false,
|
||||
}
|
||||
@@ -930,6 +1053,10 @@ impl Metrics {
|
||||
/// it reads (a page's, say): each stream pays for what it decodes, usable or not. A stream the
|
||||
/// allowance can't pay for is left unread, and [`Metrics::past_allowance`] says so.
|
||||
pub fn from_dict_within(doc: &Document, font: &Dict, budget: &mut DecodeBudget) -> Self {
|
||||
Self::from_dict_with_glyphless(doc, font, budget, None)
|
||||
}
|
||||
|
||||
fn from_dict_with_glyphless(doc: &Document, font: &Dict, budget: &mut DecodeBudget, known_glyphless: Option<bool>) -> Self {
|
||||
let mut reads = Reads::new(doc, budget);
|
||||
let mut m = Self::read_metrics(doc, font, &mut reads);
|
||||
let base = base_font_name(doc, font);
|
||||
@@ -938,8 +1065,11 @@ impl Metrics {
|
||||
m.bold |= bold;
|
||||
m.italic |= italic;
|
||||
m.base_font = base;
|
||||
if m.composite && m.subset {
|
||||
m.outlined_cids = cids_with_outlines(doc, font, &mut reads);
|
||||
m.glyphless = has_glyphless_font_name(doc, font);
|
||||
if m.composite && !m.glyphless {
|
||||
let (outlines, structural_glyphless) = composite_outlines_and_glyphless(doc, font, m.subset, known_glyphless, &mut reads);
|
||||
m.outlined_cids = outlines;
|
||||
m.glyphless = structural_glyphless;
|
||||
}
|
||||
m.code_len = match &m.codes {
|
||||
Codes::One => 1,
|
||||
@@ -947,7 +1077,7 @@ impl Metrics {
|
||||
Codes::Ranges(r) => r.last().map_or(2, |x| x.0.clamp(1, 4)),
|
||||
};
|
||||
m.unicode = unicode_map(doc, font, m.composite, &mut reads);
|
||||
if m.std14.is_some() {
|
||||
if m.std14.is_some() && !m.glyphless {
|
||||
embedded_widths(doc, font, &mut m, &mut reads);
|
||||
}
|
||||
m.past_allowance = reads.refused;
|
||||
@@ -1067,7 +1197,9 @@ impl Metrics {
|
||||
let base = String::from_utf8_lossy(font.name(b"BaseFont").unwrap_or(b"")).into_owned();
|
||||
// The real face, bold and italic included: the published metrics differ by style,
|
||||
// so Times-Bold is not Times-Roman and neither is Helvetica scaled.
|
||||
m.std14 = crate::Std14::from_base_font(&base).or(Some(crate::Std14::Helvetica));
|
||||
let recognised = crate::Std14::recognise(&base);
|
||||
m.std14_named = matches!(recognised, Some((_, crate::Std14Match::Alias)));
|
||||
m.std14 = recognised.map(|(face, _)| face).or(Some(crate::Std14::Helvetica));
|
||||
}
|
||||
}
|
||||
if let Some(d) = descriptor {
|
||||
@@ -1144,6 +1276,24 @@ impl Metrics {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether [`Metrics::width`] of `code` is a width the font declares: a `/Widths` entry (or
|
||||
/// the embedded program's advance where `/Widths` is absent), a `/W` entry or an explicit
|
||||
/// `/DW`, or the published metrics of the standard-14 face `/BaseFont` names. It is not for a
|
||||
/// `/MissingWidth`, the implied `/DW` of 1000, or a standard-14 face guessed from the name.
|
||||
pub fn width_declared(&self, code: u32) -> bool {
|
||||
if self.composite {
|
||||
let cid = self.cid(code);
|
||||
return self.explicit_default || self.cid_widths.contains_key(&cid) || self.cid_ranges.find(cid).is_some();
|
||||
}
|
||||
if code.checked_sub(self.first).and_then(|i| self.widths.get(i as usize)).is_some() {
|
||||
return true;
|
||||
}
|
||||
match self.std14.filter(|_| self.std14_named) {
|
||||
Some(f) => u8::try_from(self.std14_code(f, code)).is_ok_and(|c| f.width(c) != 0.0),
|
||||
None => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Where the standard-14 table, indexed by WinAnsi, holds the glyph `code` draws in this font:
|
||||
/// its encoding (base and `/Differences`) names the glyph, so a remapped code is measured as
|
||||
/// the glyph it now shows (#2894). Symbol and ZapfDingbats are indexed by their own encodings,
|
||||
@@ -1177,6 +1327,9 @@ impl Metrics {
|
||||
/// Only asked for codes the font's Unicode mapping gives: a subset's `ToUnicode` lists the
|
||||
/// glyphs it kept, while its `/W` leaves out those of the default width (#1443).
|
||||
fn has_glyph(&self, code: u32) -> bool {
|
||||
if self.glyphless {
|
||||
return false;
|
||||
}
|
||||
if self.composite {
|
||||
let cid = self.cid(code);
|
||||
// CID 0 is `.notdef` (an unmapped code lands there too), whatever ToUnicode says: Word
|
||||
@@ -1226,9 +1379,9 @@ impl Metrics {
|
||||
/// no glyph in it, or the metrics were read past their allowance (the caller then substitutes
|
||||
/// another font). Empty text needs no verified glyph and always encodes.
|
||||
pub fn encode(&self, text: &str) -> Option<Vec<u8>> {
|
||||
// A refused read cannot establish the mappings or glyphs needed to write new text.
|
||||
// Empty text needs neither and remains usable for erasing existing text.
|
||||
if self.past_allowance && !text.is_empty() {
|
||||
// A glyphless OCR font has no real letterforms; a refused read cannot establish the mappings
|
||||
// or glyphs needed to write new text (empty text still encodes unless glyphless).
|
||||
if self.glyphless || (self.past_allowance && !text.is_empty()) {
|
||||
return None;
|
||||
}
|
||||
// The lowest code showing each wanted character. Explicit entries and the encoding are
|
||||
@@ -2044,6 +2197,17 @@ mod encoding_tests {
|
||||
}
|
||||
assert_eq!(budget.remaining(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn named_glyphless_ocr_fonts_are_recognised_without_a_shared_gid_map() {
|
||||
for base in ["GlyphlessFont", "ABCDEF+Glyphless", "HiddenHorzOCR", "ABCDEF+HiddenVertOCR"] {
|
||||
let (doc, d) = simple(base, None, Some(Object::name("WinAnsiEncoding")));
|
||||
let m = Metrics::from_dict(&doc, &d);
|
||||
assert!(m.glyphless && is_glyphless(&doc, &d), "{base} must be marked glyphless by name alone");
|
||||
assert!(!m.has_glyph(b'A'.into()), "{base} must not claim visible glyph outlines");
|
||||
assert!(m.encode("A").is_none(), "{base} must not encode replacement text");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
mod thai;
|
||||
|
||||
@@ -135,6 +135,161 @@ fn embedded_editor_fonts_are_validated_without_installing_or_exporting() {
|
||||
assert!(embedded_sfnt(&doc, &Dict::new()).is_none());
|
||||
}
|
||||
|
||||
/// #3803: OCR placeholder fonts (`/Glyphless`, `/GlyphlessFont`, `/HiddenHorzOCR`, or a
|
||||
/// dummy TrueType program whose non-zero CIDs all share a single rectangle glyph) still decode
|
||||
/// and measure the invisible OCR layer, but never encode replacement text or expose their
|
||||
/// dummy program to the inline editor.
|
||||
#[test]
|
||||
fn glyphless_ocr_fonts_decode_and_measure_without_encoding_or_exposing_sfnt() {
|
||||
use pdfcraft_cos::Stream;
|
||||
// Build a 1-outline TrueType program (only GID 1 has an outline) from Inter-Regular.ttf.
|
||||
let mut one_glyph_ttf = include_bytes!("../../../../assets/fonts/Inter-Regular.ttf").to_vec();
|
||||
let count = u16::from_be_bytes(one_glyph_ttf[4..6].try_into().unwrap()) as usize;
|
||||
let loca_rec = (0..count).map(|i| 12 + i * 16).find(|i| &one_glyph_ttf[*i..*i + 4] == b"loca").unwrap();
|
||||
let loca_off = u32::from_be_bytes(one_glyph_ttf[loca_rec + 8..loca_rec + 12].try_into().unwrap()) as usize;
|
||||
let loca_len = u32::from_be_bytes(one_glyph_ttf[loca_rec + 12..loca_rec + 16].try_into().unwrap()) as usize;
|
||||
let mut zero_glyph_ttf = one_glyph_ttf.clone();
|
||||
zero_glyph_ttf[loca_off..loca_off + loca_len].fill(0);
|
||||
// Set loca[0] = 0, loca[1] = 0, and loca[2..] = 4 so only GID 1 has start < end.
|
||||
one_glyph_ttf[loca_off..loca_off + 8].fill(0);
|
||||
for chunk in one_glyph_ttf[loca_off + 8..loca_off + loca_len].as_chunks_mut::<4>().0 {
|
||||
*chunk = 4u32.to_be_bytes();
|
||||
}
|
||||
|
||||
for base in ["Glyphless", "GlyphlessFont", "ABCDEF+GlyphlessFont", "HiddenHorzOCR", "HiddenVertOCR", "CustomOCR"] {
|
||||
let mut doc = Document::new_empty();
|
||||
let program = doc.add(Object::Stream(Stream::flate(Dict::new(), &one_glyph_ttf)));
|
||||
let cmap = b"1 begincodespacerange <0000> <FFFF> endcodespacerange 1 beginbfrange <0000> <00FF> <0000> endbfrange";
|
||||
let tu = doc.add(Object::Stream(Stream::flate(Dict::new(), cmap)));
|
||||
let mut descriptor = Dict::new();
|
||||
descriptor.set(b"Type".to_vec(), Object::name("FontDescriptor"));
|
||||
descriptor.set(b"FontName".to_vec(), Object::name(base));
|
||||
descriptor.set(b"FontFile2".to_vec(), Object::Ref(program));
|
||||
let mut desc = Dict::new();
|
||||
desc.set(b"Type".to_vec(), Object::name("Font"));
|
||||
desc.set(b"Subtype".to_vec(), Object::name("CIDFontType2"));
|
||||
desc.set(b"BaseFont".to_vec(), Object::name(base));
|
||||
if base == "CustomOCR" {
|
||||
let cid_to_gid = doc.add(Object::Stream(Stream::flate(Dict::new(), &[0, 1].repeat(256))));
|
||||
desc.set(b"CIDToGIDMap".to_vec(), Object::Ref(cid_to_gid));
|
||||
}
|
||||
desc.set(b"DW".to_vec(), Object::Int(500));
|
||||
desc.set(b"W".to_vec(), Object::Array(vec![Object::Int(32), Object::Array(vec![Object::Int(285)])]));
|
||||
desc.set(b"FontDescriptor".to_vec(), Object::Dict(descriptor));
|
||||
let f = font(
|
||||
&mut doc,
|
||||
vec![
|
||||
("Subtype", Object::name("Type0")),
|
||||
("BaseFont", Object::name(base)),
|
||||
("Encoding", Object::name("Identity-H")),
|
||||
("DescendantFonts", Object::Array(vec![Object::Dict(desc)])),
|
||||
("ToUnicode", Object::Ref(tu)),
|
||||
],
|
||||
);
|
||||
assert!(embedded_sfnt(&doc, &f).is_none(), "{base} must not be exposed as an editor sfnt");
|
||||
let m = Metrics::from_dict(&doc, &f);
|
||||
assert_eq!(m.decode(b"\x00D\x00e\x00 \x00k"), "De k", "{base} still decodes OCR text");
|
||||
assert!((m.width(32) - 0.285).abs() < 1e-9 && (m.width(68) - 0.5).abs() < 1e-9, "{base} still measures OCR widths");
|
||||
assert_eq!(m.encode("De"), None, "{base} must not encode visible replacement text");
|
||||
assert_eq!(m.encode(" "), None, "{base} must not encode spaces");
|
||||
assert_eq!(m.encode(""), None, "{base} must not claim empty words");
|
||||
}
|
||||
|
||||
// Regression fixture 1: a valid whitespace-only subset (0 outlined glyphs in `loca` because
|
||||
// space has no contours) remains exposed as an editor sfnt and encodes whitespace.
|
||||
let mut doc = Document::new_empty();
|
||||
let program = doc.add(Object::Stream(Stream::flate(Dict::new(), &zero_glyph_ttf)));
|
||||
let mut descriptor = Dict::new();
|
||||
descriptor.set(b"FontName".to_vec(), Object::name("ABCDEF+WhitespaceSubset"));
|
||||
descriptor.set(b"FontFile2".to_vec(), Object::Ref(program));
|
||||
let whitespace_subset = font(
|
||||
&mut doc,
|
||||
vec![
|
||||
("Subtype", Object::name("TrueType")),
|
||||
("BaseFont", Object::name("ABCDEF+WhitespaceSubset")),
|
||||
("Encoding", Object::name("WinAnsiEncoding")),
|
||||
("FirstChar", Object::Int(32)),
|
||||
("LastChar", Object::Int(32)),
|
||||
("Widths", Object::Array(vec![Object::Int(250)])),
|
||||
("FontDescriptor", Object::Dict(descriptor)),
|
||||
],
|
||||
);
|
||||
assert!(embedded_sfnt(&doc, &whitespace_subset).is_some(), "whitespace-only subset keeps its sfnt");
|
||||
assert_eq!(Metrics::from_dict(&doc, &whitespace_subset).encode(" ").as_deref(), Some(&[32][..]));
|
||||
|
||||
// Regression fixture 2: a 1-glyph font with intentional cmap aliases (e.g. U+002D, U+2010,
|
||||
// U+2011 hyphen variants sharing GID 1) remains exposed and encodes its characters.
|
||||
let mut alias_cmap_ttf = one_glyph_ttf.clone();
|
||||
append_editor_cmap(&mut alias_cmap_ttf, &std::collections::BTreeMap::from([(0x002D, 1), (0x2010, 1), (0x2011, 1)])).unwrap();
|
||||
let program = doc.add(Object::Stream(Stream::flate(Dict::new(), &alias_cmap_ttf)));
|
||||
let mut descriptor = Dict::new();
|
||||
descriptor.set(b"FontName".to_vec(), Object::name("ABCDEF+HyphenSubset"));
|
||||
descriptor.set(b"FontFile2".to_vec(), Object::Ref(program));
|
||||
let cmap_alias_font = font(
|
||||
&mut doc,
|
||||
vec![
|
||||
("Subtype", Object::name("TrueType")),
|
||||
("BaseFont", Object::name("ABCDEF+HyphenSubset")),
|
||||
("Encoding", Object::name("WinAnsiEncoding")),
|
||||
("FirstChar", Object::Int(45)),
|
||||
("LastChar", Object::Int(45)),
|
||||
("Widths", Object::Array(vec![Object::Int(333)])),
|
||||
("FontDescriptor", Object::Dict(descriptor)),
|
||||
],
|
||||
);
|
||||
assert!(embedded_sfnt(&doc, &cmap_alias_font).is_some(), "intentional cmap alias subset keeps its sfnt");
|
||||
assert_eq!(Metrics::from_dict(&doc, &cmap_alias_font).encode("-").as_deref(), Some(&[45][..]));
|
||||
|
||||
// Regression fixture 3: a legitimate 1-glyph composite subset with intentional CIDToGIDMap
|
||||
// aliases (CIDs 1..=3 all mapping to GID 1) stays usable and keeps its sfnt.
|
||||
let mut single_char_ttf = one_glyph_ttf;
|
||||
append_editor_cmap(&mut single_char_ttf, &std::collections::BTreeMap::from([(65, 1), (0xFF21, 1)])).unwrap();
|
||||
let program = doc.add(Object::Stream(Stream::flate(Dict::new(), &single_char_ttf)));
|
||||
let cid_to_gid = doc.add(Object::Stream(Stream::flate(Dict::new(), &[0, 0, 0, 1, 0, 1, 0, 1])));
|
||||
let tu = doc.add(Object::Stream(Stream::flate(Dict::new(), b"2 beginbfchar <0001> <0041> <0002> <FF21> endbfchar")));
|
||||
let mut descriptor = Dict::new();
|
||||
descriptor.set(b"FontName".to_vec(), Object::name("ABCDEF+SingleCharSubset"));
|
||||
descriptor.set(b"FontFile2".to_vec(), Object::Ref(program));
|
||||
let mut desc = Dict::new();
|
||||
desc.set(b"Subtype".to_vec(), Object::name("CIDFontType2"));
|
||||
desc.set(b"BaseFont".to_vec(), Object::name("ABCDEF+SingleCharSubset"));
|
||||
desc.set(b"CIDToGIDMap".to_vec(), Object::Ref(cid_to_gid));
|
||||
desc.set(b"W".to_vec(), Object::Array(vec![Object::Int(1), Object::Array(vec![Object::Int(600), Object::Int(600)])]));
|
||||
desc.set(b"FontDescriptor".to_vec(), Object::Dict(descriptor));
|
||||
let valid_subset = font(
|
||||
&mut doc,
|
||||
vec![
|
||||
("Subtype", Object::name("Type0")),
|
||||
("BaseFont", Object::name("ABCDEF+SingleCharSubset")),
|
||||
("Encoding", Object::name("Identity-H")),
|
||||
("DescendantFonts", Object::Array(vec![Object::Dict(desc)])),
|
||||
("ToUnicode", Object::Ref(tu)),
|
||||
],
|
||||
);
|
||||
assert!(embedded_sfnt(&doc, &valid_subset).is_some(), "legitimate 1-glyph subset with CID aliases keeps its sfnt");
|
||||
assert_eq!(Metrics::from_dict(&doc, &valid_subset).encode("A").as_deref(), Some(&[0, 1][..]));
|
||||
|
||||
// Distinct non-zero GIDs across >= 64 CIDs, or a single-GID map whose FontFile2 has 0 or
|
||||
// multiple outlined glyphs (or a different outlined GID), are not classified as glyphless.
|
||||
let mut multi_gid_map = [0u8, 1].repeat(65);
|
||||
multi_gid_map.extend_from_slice(&[0, 2]);
|
||||
let multi_gid = doc.add(Object::Stream(Stream::flate(Dict::new(), &multi_gid_map)));
|
||||
let single_gid_64 = doc.add(Object::Stream(Stream::flate(Dict::new(), &[0u8, 1].repeat(65))));
|
||||
let single_gid_2_64 = doc.add(Object::Stream(Stream::flate(Dict::new(), &[0u8, 2].repeat(65))));
|
||||
let full_ttf = doc.add(Object::Stream(Stream::flate(Dict::new(), include_bytes!("../../../../assets/fonts/Inter-Regular.ttf"))));
|
||||
let zero_ttf = doc.add(Object::Stream(Stream::flate(Dict::new(), &zero_glyph_ttf)));
|
||||
for (map_ref, prog_ref) in [(multi_gid, program), (single_gid_64, full_ttf), (single_gid_64, zero_ttf), (single_gid_2_64, program)] {
|
||||
let mut fd = Dict::new();
|
||||
fd.set(b"FontFile2".to_vec(), Object::Ref(prog_ref));
|
||||
let mut desc = Dict::new();
|
||||
desc.set(b"Subtype".to_vec(), Object::name("CIDFontType2"));
|
||||
desc.set(b"CIDToGIDMap".to_vec(), Object::Ref(map_ref));
|
||||
desc.set(b"FontDescriptor".to_vec(), Object::Dict(fd));
|
||||
let d = font(&mut doc, vec![("Subtype", Object::name("Type0")), ("DescendantFonts", Object::Array(vec![Object::Dict(desc)]))]);
|
||||
assert!(!is_glyphless(&doc, &d));
|
||||
}
|
||||
}
|
||||
|
||||
/// #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), the program's `/DecodeParms` given
|
||||
/// directly or by reference.
|
||||
@@ -299,13 +454,14 @@ fn a_fonts_streams_are_paid_for_from_its_allowance() {
|
||||
let m = Metrics::from_dict_within(&doc, &f, &mut budget);
|
||||
assert!(m.past_allowance && m.outlined_cids.is_empty());
|
||||
assert_eq!(m.codes, Codes::Two, "the Encoding CMap was left unread");
|
||||
// Only a subset's program says which glyphs it lacks: the whole font pays for its CMaps alone.
|
||||
// Only a subset's program says which glyphs it lacks: the whole font inspects `/CIDToGIDMap`
|
||||
// once for shared-glyph placeholders and leaves the `FontFile2` program unread.
|
||||
let mut whole_font = f.clone();
|
||||
whole_font.set(b"BaseFont".to_vec(), Object::name("Inter"));
|
||||
let mut budget = DecodeBudget::new(cost, 0);
|
||||
let m = Metrics::from_dict_within(&doc, &whole_font, &mut budget);
|
||||
assert!(!m.past_allowance && m.outlined_cids.is_empty());
|
||||
assert_eq!(cost - budget.remaining(), sizes[0] + sizes[3]);
|
||||
assert_eq!(cost - budget.remaining(), sizes[0] + sizes[2] + sizes[3]);
|
||||
}
|
||||
|
||||
/// With nothing left, an empty stream still reads, as the allowance reads one, and is no reason to
|
||||
@@ -2165,3 +2321,42 @@ fn a_dropped_codespace_range_is_reported() {
|
||||
assert!(parse_cmap(b"1 begincodespacerange <00> <FFFF> endcodespacerange").2);
|
||||
assert!(!parse_cmap(b"2 begincodespacerange <0000> <FFFF> <0000> <FFFF> endcodespacerange").2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn widths_the_font_declares_are_told_from_fallbacks() {
|
||||
let mut doc = Document::new_empty();
|
||||
let simple = |doc: &mut Document, base: &str, widths: Option<Vec<Object>>| {
|
||||
let mut entries = vec![("Subtype", Object::name("Type1")), ("BaseFont", Object::name(base))];
|
||||
if let Some(w) = widths {
|
||||
entries.extend([("FirstChar", Object::Int(65)), ("Widths", Object::Array(w))]);
|
||||
}
|
||||
let dict = font(doc, entries);
|
||||
Metrics::from_dict(doc, &dict)
|
||||
};
|
||||
let listed = simple(&mut doc, "HouseFont", Some(vec![Object::Int(500)]));
|
||||
assert!(listed.width_declared(65));
|
||||
assert!(!listed.width_declared(66), "a code past /Widths takes /MissingWidth");
|
||||
assert!(simple(&mut doc, "Helvetica", None).width_declared(65));
|
||||
assert!(simple(&mut doc, "Arial", None).width_declared(65), "a common alias names the face");
|
||||
assert!(!simple(&mut doc, "HouseSerif", None).width_declared(65), "Times is a guess from the name");
|
||||
assert!(!simple(&mut doc, "HouseFont", None).width_declared(65), "Helvetica is a guess");
|
||||
let cid = |doc: &mut Document, dw: Option<i64>| {
|
||||
let mut desc = Dict::new();
|
||||
desc.set(b"Subtype".to_vec(), Object::name("CIDFontType2"));
|
||||
desc.set(b"W".to_vec(), Object::Array(vec![Object::Int(1), Object::Array(vec![Object::Int(600)])]));
|
||||
if let Some(dw) = dw {
|
||||
desc.set(b"DW".to_vec(), Object::Int(dw));
|
||||
}
|
||||
let entries = vec![
|
||||
("Subtype", Object::name("Type0")),
|
||||
("Encoding", Object::name("Identity-H")),
|
||||
("DescendantFonts", Object::Array(vec![Object::Dict(desc)])),
|
||||
];
|
||||
let dict = font(doc, entries);
|
||||
Metrics::from_dict(doc, &dict)
|
||||
};
|
||||
let implied = cid(&mut doc, None);
|
||||
assert!(implied.width_declared(1));
|
||||
assert!(!implied.width_declared(2), "a CID /W leaves out, with no /DW, takes the implied 1000");
|
||||
assert!(cid(&mut doc, Some(500)).width_declared(2));
|
||||
}
|
||||
|
||||
+37
-12
@@ -20,6 +20,7 @@ mod script;
|
||||
#[cfg(test)]
|
||||
use calc::{Notation, eval_notation, notation_name, notation_tokens, unique};
|
||||
pub use calc::{calculate, calculation_reads, notation_js, reads_built_names, rename_in_calculation};
|
||||
use format::parse_date_split;
|
||||
pub use format::{
|
||||
DATE_PRESETS, DateNames, DateTime, ENGLISH_DATE_NAMES, TIME_PRESETS, date_names, format_date, format_date_in, format_value, format_value_in,
|
||||
js_number, keystroke, make_number, parse_date, set_date_names, validate,
|
||||
@@ -119,6 +120,10 @@ pub struct Actions {
|
||||
/// A date field PdfCraft laid out for an XFA form (`/PCXfaDate true`): text its format doesn't
|
||||
/// read is kept and shown as typed rather than refused, as an XFA form keeps it.
|
||||
pub xfa_date: bool,
|
||||
/// Such a field's edit pattern (its `AFDate_KeystrokeEx`) when it differs from the display
|
||||
/// pattern [`Actions::format`] names: the value is typed and kept in this one, and shown in
|
||||
/// that one.
|
||||
pub edit_date: Option<String>,
|
||||
}
|
||||
|
||||
/// Field scripts that aren't AF calls, by event.
|
||||
@@ -130,42 +135,62 @@ pub struct Scripts {
|
||||
pub calculate: Option<String>,
|
||||
}
|
||||
|
||||
/// The century split of a two-digit year in an XFA picture clause (XFA 3.3, Picture Clause
|
||||
/// Reference): `00` to `29` are 2000 to 2029 and `30` to `99` are 1930 to 1999.
|
||||
const XFA_CENTURY_SPLIT: i32 = 30;
|
||||
|
||||
impl Actions {
|
||||
/// Whether the field has no format, validation or calculation PdfCraft recognises.
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.format == Format::None && self.validate == Validate::None && self.calculate == Calculate::None
|
||||
}
|
||||
|
||||
/// The Keystroke event on commit ([`keystroke`]); an XFA date field keeps text its format
|
||||
/// doesn't read, as typed.
|
||||
/// The Keystroke event on commit ([`keystroke`]); an XFA date field checks the text against its
|
||||
/// edit pattern and keeps what that doesn't read, as typed.
|
||||
pub fn keystroke(&self, field: &str, value: &str) -> Result<String, String> {
|
||||
match keystroke(&self.format, field, value) {
|
||||
let edit = self.edit_pattern().map(|p| Format::Date(p.to_string()));
|
||||
match keystroke(edit.as_ref().unwrap_or(&self.format), field, value) {
|
||||
Err(_) if self.xfa_date => Ok(value.to_string()),
|
||||
checked => checked,
|
||||
}
|
||||
}
|
||||
|
||||
/// What the Format event shows for `value` ([`format_value`]). An XFA date field shows a date
|
||||
/// only for a value that is one, in its format already or as an ISO date (`2026-10-18` or
|
||||
/// `20261018`); anything else, which its format would read loosely, shows as typed.
|
||||
/// only for a value that is one, in its edit pattern (written in the display pattern, a
|
||||
/// two-digit year read as XFA reads it, [`XFA_CENTURY_SPLIT`]) or as an ISO date (`2026-10-18`
|
||||
/// or `20261018`); anything else, which its format would read loosely, shows as typed.
|
||||
pub fn format_value(&self, value: &str) -> String {
|
||||
self.format_value_in(value, &date_names())
|
||||
}
|
||||
|
||||
/// [`Self::format_value`] with month and weekday names from `names`.
|
||||
pub fn format_value_in(&self, value: &str, names: &DateNames) -> String {
|
||||
match &self.format {
|
||||
Format::Date(fmt) if self.xfa_date => {
|
||||
match (&self.format, self.edit_pattern()) {
|
||||
(Format::Date(fmt), Some(edit)) => {
|
||||
let t = value.trim();
|
||||
let in_format = parse_date(t, fmt).is_some_and(|dt| format_date(dt, fmt).eq_ignore_ascii_case(t));
|
||||
match iso_date(t) {
|
||||
Some(dt) if !in_format => format_date_in(dt, fmt, names),
|
||||
_ => value.to_string(),
|
||||
match parse_date_split(t, edit, XFA_CENTURY_SPLIT).filter(|dt| format_date(*dt, edit).eq_ignore_ascii_case(t)) {
|
||||
// Typed as it shows: kept as it is, its case too.
|
||||
Some(_) if edit == fmt => value.to_string(),
|
||||
Some(dt) => format_date_in(dt, fmt, names),
|
||||
None => iso_date(t).map_or_else(|| value.to_string(), |dt| format_date_in(dt, fmt, names)),
|
||||
}
|
||||
}
|
||||
f => format_value_in(f, value, names),
|
||||
(f, _) => format_value_in(f, value, names),
|
||||
}
|
||||
}
|
||||
|
||||
/// An XFA date field's edit pattern: [`Actions::edit_date`], else its display pattern.
|
||||
fn edit_pattern(&self) -> Option<&str> {
|
||||
match &self.format {
|
||||
Format::Date(fmt) if self.xfa_date => Some(self.edit_date.as_deref().unwrap_or(fmt)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The pattern an `AFDate_KeystrokeEx("…")` keystroke script checks dates against.
|
||||
pub fn parse_date_keystroke(js: &str) -> Option<String> {
|
||||
call(js, "AFDate_KeystrokeEx")?.first().and_then(Arg::string)
|
||||
}
|
||||
|
||||
/// `text` as an ISO 8601 calendar date, `yyyy-mm-dd` or `yyyymmdd` (digits only, a real day).
|
||||
|
||||
@@ -359,21 +359,27 @@ fn order(fmt: &str) -> Vec<Part> {
|
||||
}
|
||||
|
||||
/// Parse typed text against a date/time format (AFDate_KeystrokeEx's leniency: any
|
||||
/// separators, month names, two-digit years). `None` when it isn't a valid date.
|
||||
/// separators, month names, two-digit years, read as 1950 to 2049). `None` when it isn't a
|
||||
/// valid date.
|
||||
pub fn parse_date(text: &str, fmt: &str) -> Option<DateTime> {
|
||||
parse_date_split(text, fmt, 50)
|
||||
}
|
||||
|
||||
/// [`parse_date`] with a two-digit year below `century_split` read as 20xx and the rest as 19xx.
|
||||
pub(super) fn parse_date_split(text: &str, fmt: &str, century_split: i32) -> Option<DateTime> {
|
||||
let names = date_names();
|
||||
let lists: [&[&str]; 4] = [&names.months, &names.months_short, &names.days, &names.days_short];
|
||||
// Weekdays are shown, not typed (see `order`): where the format has one but none was typed, a
|
||||
// name the language shares between a weekday and a month (Italian "mar") is the month, as
|
||||
// the names are read again with no weekday expected (#5303).
|
||||
read_date(&english_names(text, fmt, lists), fmt, &names).or_else(|| {
|
||||
read_date(&english_names(text, fmt, lists), fmt, &names, century_split).or_else(|| {
|
||||
let no_weekday = fmt.replace("dddd", " ").replace("ddd", " ");
|
||||
(no_weekday != fmt).then(|| read_date(&english_names(text, &no_weekday, lists), fmt, &names)).flatten()
|
||||
(no_weekday != fmt).then(|| read_date(&english_names(text, &no_weekday, lists), fmt, &names, century_split)).flatten()
|
||||
})
|
||||
}
|
||||
|
||||
/// [`parse_date`] of `english`, typed text whose month and weekday names are English.
|
||||
fn read_date(english: &str, fmt: &str, names: &DateNames) -> Option<DateTime> {
|
||||
/// [`parse_date_split`] of `english`, typed text whose month and weekday names are English.
|
||||
fn read_date(english: &str, fmt: &str, names: &DateNames, century_split: i32) -> Option<DateTime> {
|
||||
let t = english.trim();
|
||||
if t.is_empty() {
|
||||
return None;
|
||||
@@ -473,7 +479,7 @@ fn read_date(english: &str, fmt: &str, names: &DateNames) -> Option<DateTime> {
|
||||
'd' => dt.d = take(&mut nums, &mut tail)?,
|
||||
'y' => {
|
||||
let y = i32::try_from(take(&mut nums, &mut tail)?).ok()?;
|
||||
dt.y = if y < 100 { if y < 50 { 2000 + y } else { 1900 + y } } else { y };
|
||||
dt.y = if y < 100 { if y < century_split { 2000 + y } else { 1900 + y } } else { y };
|
||||
have_y = true;
|
||||
}
|
||||
// Times may be left out; a number that is there must be readable.
|
||||
|
||||
@@ -364,6 +364,28 @@ fn xfa_date_fields_keep_and_show_what_their_pattern_does_not_read() {
|
||||
assert_eq!(mdy.format_value("xyz"), "xyz");
|
||||
assert_eq!(mdy.format_value("2016-02-30"), "2016-02-30", "not a real day: as typed");
|
||||
assert_eq!(xfa("ddmmmyy").format_value("18OCT16"), "18OCT16", "in the pattern, its case kept");
|
||||
// Typed in an edit pattern unlike the display pattern: read with the one, shown in the other.
|
||||
let swapped = Actions { edit_date: Some("dd/mm/yyyy".into()), ..xfa("mm/dd/yyyy") };
|
||||
assert_eq!(swapped.format_value("18/10/2016"), "10/18/2016");
|
||||
assert_eq!(swapped.format_value("10/11/2016"), "11/10/2016", "10 November");
|
||||
assert_eq!(swapped.format_value("10/18/2016"), "10/18/2016", "not a day-first date: as typed");
|
||||
assert_eq!(swapped.format_value("2016-10-18"), "10/18/2016");
|
||||
assert_eq!(swapped.keystroke("Date", " 18/10/2016 "), Ok("18/10/2016".to_string()), "checked against the edit pattern");
|
||||
assert_eq!(swapped.keystroke("Date", "10/18/2016"), Ok("10/18/2016".to_string()));
|
||||
}
|
||||
|
||||
/// An XFA date field reads a two-digit year in its edit pattern as XFA picture clauses do, with
|
||||
/// the century split at 30 (`00` to `29` are 2000 to 2029, `30` to `99` are 1930 to 1999), when
|
||||
/// it shows the date through its display pattern. An ordinary date field keeps AFDate's split at 50.
|
||||
#[test]
|
||||
fn an_xfa_date_field_splits_a_two_digit_years_century_at_30() {
|
||||
let shown = Actions { format: Format::Date("mmmm d, yyyy".into()), xfa_date: true, edit_date: Some("ddmmmyy".into()), ..Actions::default() };
|
||||
for (typed, date) in
|
||||
[("18OCT29", "October 18, 2029"), ("18OCT30", "October 18, 1930"), ("18OCT49", "October 18, 1949"), ("18OCT50", "October 18, 1950")]
|
||||
{
|
||||
assert_eq!(shown.format_value(typed), date, "{typed}");
|
||||
}
|
||||
assert_eq!(format_value(&Format::Date("mmmm d, yyyy".into()), "10/18/45"), "October 18, 2045", "an ordinary date field");
|
||||
}
|
||||
|
||||
/// Date, time and mask formats show values in their pattern and refuse what doesn't fit.
|
||||
|
||||
@@ -191,7 +191,14 @@ fn actions_of(doc: &Document, d: &Dict, widgets: &[ObjRef], scripts: &mut Decode
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
if let Some(k) = js(b"K")
|
||||
let k = js(b"K");
|
||||
// An XFA date field typed in another pattern than it shows.
|
||||
if out.xfa_date
|
||||
&& let af::Format::Date(shown) = &out.format
|
||||
{
|
||||
out.edit_date = k.as_deref().and_then(af::parse_date_keystroke).filter(|edit| edit != shown);
|
||||
}
|
||||
if let Some(k) = k
|
||||
&& out.format == af::Format::None
|
||||
{
|
||||
// A mask has only a keystroke script.
|
||||
|
||||
+81
-11
@@ -18,18 +18,31 @@ pub struct Page {
|
||||
pub dict: Dict,
|
||||
}
|
||||
|
||||
/// The side, in points, at or below which a `/MediaBox` has no area and the page falls back to
|
||||
/// US Letter (the renderer's `is_nearly_zero`, 1/4096).
|
||||
/// The side, in points, at or below which a `/MediaBox` or clipped `/CropBox` has no area and
|
||||
/// falls back (the renderer's `is_nearly_zero`, 1/4096).
|
||||
const MIN_BOX_SIDE: f64 = 1.0 / 4096.0;
|
||||
|
||||
fn rect(doc: &Document, o: Option<&Object>) -> Option<[f64; 4]> {
|
||||
/// Normalized `[x0, y0, x1, y1]` of a page box when its first four entries form a finite, positive rectangle.
|
||||
///
|
||||
/// Origin and size are unscaled; overflowing widths are returned so [`Page::crop`] can clip them
|
||||
/// to the media box.
|
||||
fn box_coords(doc: &Document, o: Option<&Object>) -> Option<[f64; 4]> {
|
||||
let o = doc.resolve(o?);
|
||||
// Four entries, or not a rectangle: a longer array (one shared by many pages, say) is not
|
||||
// resolved entry by entry only to be discarded.
|
||||
let [a, b, c, d] = o.as_array()?.as_slice() else { return None };
|
||||
let v = [a, b, c, d].map(|x| doc.resolve(x).as_f64());
|
||||
let [Some(x0), Some(y0), Some(x1), Some(y1)] = v else { return None };
|
||||
[x0, y0, x1, y1].iter().all(|x| x.is_finite()).then(|| [x0.min(x1), y0.min(y1), x0.max(x1), y0.max(y1)])
|
||||
let [a, b, c, d, ..] = o.as_array()?.as_slice() else { return None };
|
||||
let coords = [doc.resolve(a).as_f64()?, doc.resolve(b).as_f64()?, doc.resolve(c).as_f64()?, doc.resolve(d).as_f64()?];
|
||||
if !coords.iter().all(|x| x.is_finite()) {
|
||||
return None;
|
||||
}
|
||||
let r = [coords[0].min(coords[2]), coords[1].min(coords[3]), coords[0].max(coords[2]), coords[1].max(coords[3])];
|
||||
let (w, h) = (r[2] - r[0], r[3] - r[1]);
|
||||
(w > 0.0 && h > 0.0).then_some(r)
|
||||
}
|
||||
|
||||
/// Like [`box_coords`], also rejecting boxes whose span overflows when scaled by [`MAX_USER_UNIT`].
|
||||
fn rect(doc: &Document, o: Option<&Object>) -> Option<[f64; 4]> {
|
||||
let r = box_coords(doc, o)?;
|
||||
let (w, h) = (r[2] - r[0], r[3] - r[1]);
|
||||
((w * MAX_USER_UNIT).is_finite() && (h * MAX_USER_UNIT).is_finite()).then_some(r)
|
||||
}
|
||||
|
||||
impl Page {
|
||||
@@ -40,10 +53,10 @@ impl Page {
|
||||
let media = rect(doc, self.dict.get(b"MediaBox"))
|
||||
.filter(|m| m[2] - m[0] > MIN_BOX_SIDE && m[3] - m[1] > MIN_BOX_SIDE)
|
||||
.unwrap_or([0.0, 0.0, 612.0, 792.0]);
|
||||
match rect(doc, self.dict.get(b"CropBox")) {
|
||||
match box_coords(doc, self.dict.get(b"CropBox")) {
|
||||
Some(c) => {
|
||||
let r = [c[0].max(media[0]), c[1].max(media[1]), c[2].min(media[2]), c[3].min(media[3])];
|
||||
if r[2] > r[0] && r[3] > r[1] { r } else { media }
|
||||
if r[2] - r[0] > MIN_BOX_SIDE && r[3] - r[1] > MIN_BOX_SIDE { r } else { media }
|
||||
}
|
||||
None => media,
|
||||
}
|
||||
@@ -512,4 +525,61 @@ mod tests {
|
||||
assert_eq!(pages(&d)[0].user_unit(&d), unit, "{pages_attrs} {page_attrs}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn degenerate_or_malformed_boxes_fall_back() {
|
||||
for bad_media in ["[0 0 0 792]", "[10 10 100 10]", "[10 10 10 10]", "[0 0 /Bad 400 500]"] {
|
||||
let d = doc_with(0, &format!("/MediaBox {bad_media}"), "/CropBox null");
|
||||
let p = &pages(&d)[0];
|
||||
assert_eq!(p.crop(&d), [0.0, 0.0, 612.0, 792.0], "{bad_media}");
|
||||
assert_eq!(p.display_size(&d), (612.0, 792.0), "{bad_media}");
|
||||
}
|
||||
// Rejected /CropBox falls back to /MediaBox ([0 0 600 800] from doc_with).
|
||||
for bad_crop in ["[0 0 0 800]", "[0 0 /Bad 400 500]"] {
|
||||
let d = doc_with(0, "", &format!("/CropBox {bad_crop}"));
|
||||
assert_eq!(pages(&d)[0].crop(&d), [0.0, 0.0, 600.0, 800.0], "{bad_crop}");
|
||||
}
|
||||
// Reversed coordinates are normalized, and four valid leading coordinates with trailing
|
||||
// entries match the renderer's crop bounds.
|
||||
let reversed = doc_with(0, "", "/CropBox [300 400 10 20]");
|
||||
assert_eq!(pages(&reversed)[0].crop(&reversed), [10.0, 20.0, 300.0, 400.0]);
|
||||
let trailing = doc_with(0, "", "/CropBox [0 0 300 792 /Extra]");
|
||||
assert_eq!(pages(&trailing)[0].crop(&trailing), [0.0, 0.0, 300.0, 792.0]);
|
||||
// An overflowing /CropBox still intersects a normal /MediaBox; the visible region is that
|
||||
// intersection, not the full media box (hidden-text cleanup uses this crop), unless the
|
||||
// clipped intersection is a sliver at or below MIN_BOX_SIDE, matching the renderer.
|
||||
let overflow = doc_with(0, "/MediaBox [0 0 600 800]", "/CropBox [-1e308 0 1e308 792]");
|
||||
assert_eq!(pages(&overflow)[0].crop(&overflow), [0.0, 0.0, 600.0, 792.0]);
|
||||
for sliver in ["/CropBox [-1e308 0 1e308 0.0001]", "/CropBox [-1e308 0 0.0001 800]"] {
|
||||
let d = doc_with(0, "/MediaBox [0 0 600 800]", sliver);
|
||||
assert_eq!(pages(&d)[0].crop(&d), [0.0, 0.0, 600.0, 800.0], "{sliver}");
|
||||
}
|
||||
|
||||
let mut d = doc_with(0, "", "/CropBox null");
|
||||
let leaf = ObjRef { num: 3, generation: 0 };
|
||||
// Indirect box array and indirect coordinate numbers resolve cleanly.
|
||||
let w_ref = d.add(Object::Int(250));
|
||||
let h_ref = d.add(Object::Real(350.0));
|
||||
let box_ref = d.add(Object::Array(vec![Object::Int(0), Object::Int(0), Object::Ref(w_ref), Object::Ref(h_ref)]));
|
||||
d.update_dict(leaf, |dict| dict.set(b"CropBox".to_vec(), Object::Ref(box_ref))).unwrap();
|
||||
assert_eq!(pages(&d)[0].crop(&d), [0.0, 0.0, 250.0, 350.0]);
|
||||
d.update_dict(leaf, |dict| dict.set(b"CropBox".to_vec(), Object::Null)).unwrap();
|
||||
|
||||
for extreme in [
|
||||
vec![Object::Real(-1e308), Object::Real(0.0), Object::Real(1e308), Object::Real(792.0)],
|
||||
vec![Object::Real(0.0), Object::Real(0.0), Object::Real(1e308), Object::Real(792.0)],
|
||||
vec![Object::Real(0.0), Object::Real(0.0), Object::Real(1e306), Object::Real(792.0)],
|
||||
vec![Object::Real(0.0), Object::Real(0.0), Object::Real(f64::NAN), Object::Real(792.0)],
|
||||
] {
|
||||
d.update_dict(leaf, |dict| {
|
||||
dict.set(b"MediaBox".to_vec(), Object::Array(extreme.clone()));
|
||||
dict.set(b"UserUnit".to_vec(), Object::Real(1000.0));
|
||||
})
|
||||
.unwrap();
|
||||
let p = &pages(&d)[0];
|
||||
assert_eq!(p.crop(&d), [0.0, 0.0, 612.0, 792.0], "{extreme:?}");
|
||||
let (w, h) = p.display_size(&d);
|
||||
assert!(w.is_finite() && h.is_finite() && w > 0.0 && h > 0.0, "{extreme:?}: ({w}, {h})");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,6 +11,7 @@ workspace = true
|
||||
[dependencies]
|
||||
pdfcraft-content = { workspace = true }
|
||||
pdfcraft-cos = { workspace = true }
|
||||
pdfcraft-model = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
|
||||
@@ -114,7 +114,7 @@ pub fn set_attachment_description(doc: &mut Document, key: &str, description: Op
|
||||
}
|
||||
|
||||
/// The `/EmbeddedFiles` entries (key, file specification), in tree order.
|
||||
fn entries(doc: &Document) -> Vec<(Vec<u8>, Object)> {
|
||||
pub(crate) fn entries(doc: &Document) -> Vec<(Vec<u8>, Object)> {
|
||||
let Some(tree) = doc
|
||||
.root()
|
||||
.and_then(|r| doc.get(r).as_dict().cloned())
|
||||
|
||||
@@ -105,7 +105,9 @@ fn added_objects(dst: &Document, before: &HashSet<u32>) -> Vec<ObjRef> {
|
||||
/// under one new bookmark titled `title` (the file's name) at its first inserted page, as Combine
|
||||
/// Files does for each file. That bookmark goes among the top-level bookmarks where the pages went:
|
||||
/// before the first one that points after them. Bookmarks to pages left out stay behind, unless a
|
||||
/// bookmark below them leads to an inserted page; a file without bookmarks adds none.
|
||||
/// bookmark below them leads to an inserted page; a file without bookmarks adds none. Catalog
|
||||
/// attachments are merged with the destination's attachments, with duplicate name-tree keys
|
||||
/// renamed, as in Combine Files.
|
||||
pub fn insert_file_pages(
|
||||
dst: &mut Document,
|
||||
src: &Document,
|
||||
@@ -125,6 +127,15 @@ pub fn insert_file_pages(
|
||||
let after = at.min(crate::page_count(dst)?.saturating_sub(imported.pages.len())).saturating_add(imported.pages.len());
|
||||
insert_file_bookmark(dst, &Mark { title: title.to_string(), page: *first, outline }, after)?;
|
||||
}
|
||||
if !imported.pages.is_empty() {
|
||||
let mut incoming = Vec::new();
|
||||
carry::collect_attachments(dst, src, &mut incoming)?;
|
||||
if !incoming.is_empty() {
|
||||
let mut attachments = crate::attachments::entries(dst);
|
||||
attachments.append(&mut incoming);
|
||||
set_attachments(dst, attachments)?;
|
||||
}
|
||||
}
|
||||
Ok(ImportOutcome { pages: imported.pages, renamed_fields: imported.renamed_fields })
|
||||
}
|
||||
|
||||
@@ -571,9 +582,9 @@ pub fn import_value(dst: &mut Document, src: &Document, value: &Object) -> Resul
|
||||
}
|
||||
|
||||
/// Page `page` of `src` as a form XObject in `dst` (its content and resources, no annotations),
|
||||
/// for backgrounds and watermarks taken from a PDF. The form's `/BBox` is the page's crop box
|
||||
/// and its `/Matrix` undoes the page rotation, so it draws upright as displayed. Returns the
|
||||
/// form and its displayed size in points.
|
||||
/// for backgrounds and watermarks taken from a PDF. The form's `/BBox` is the visible crop box
|
||||
/// (clipped to the media box), and its `/Matrix` undoes the page rotation, so it draws upright
|
||||
/// as displayed. Returns the form and its displayed size in points.
|
||||
pub fn page_as_form(dst: &mut Document, src: &Document, page: usize) -> Result<(ObjRef, (f64, f64)), OrganizeError> {
|
||||
use pdfcraft_cos::Stream;
|
||||
let all = walk(src)?;
|
||||
@@ -581,12 +592,20 @@ pub fn page_as_form(dst: &mut Document, src: &Document, page: usize) -> Result<(
|
||||
// the page's own.
|
||||
let (pr, d) = all.get(page).cloned().ok_or(OrganizeError::NoSuchPage(page))?;
|
||||
let own = src.get(pr).as_dict().cloned().unwrap_or_default();
|
||||
let rect = |k: &[u8]| -> Option<[f64; 4]> {
|
||||
let a = src.resolve(d.get(k)?);
|
||||
let v: Vec<f64> = a.as_array()?.iter().filter_map(|x| src.resolve(x).as_f64()).collect();
|
||||
(v.len() == 4).then(|| [v[0].min(v[2]), v[1].min(v[3]), v[0].max(v[2]), v[1].max(v[3])])
|
||||
// Use the viewer's effective bounds: an oversized CropBox must not reveal artwork
|
||||
// outside MediaBox or change the watermark's aspect ratio and fit (#7687).
|
||||
let source_page = pdfcraft_model::Page { obj: pr, dict: d };
|
||||
let d = &source_page.dict;
|
||||
// Keep an explicitly empty source empty: callers such as 3D posters reject it.
|
||||
// The viewer's Letter fallback must not turn that invalid input into a usable picture.
|
||||
let raw_rect = |key: &[u8]| -> Option<[f64; 4]> {
|
||||
let obj = src.resolve(d.get(key)?);
|
||||
let [a, b, c, e] = obj.as_array()?.as_slice() else { return None };
|
||||
let [Some(x0), Some(y0), Some(x1), Some(y1)] = [a, b, c, e].map(|v| src.resolve(v).as_f64()) else { return None };
|
||||
[x0, y0, x1, y1].iter().all(|v| v.is_finite()).then(|| [x0.min(x1), y0.min(y1), x0.max(x1), y0.max(y1)])
|
||||
};
|
||||
let bbox = rect(b"CropBox").or_else(|| rect(b"MediaBox")).unwrap_or([0.0, 0.0, 612.0, 792.0]);
|
||||
let bbox =
|
||||
raw_rect(b"CropBox").or_else(|| raw_rect(b"MediaBox")).filter(|b| b[0] == b[2] || b[1] == b[3]).unwrap_or_else(|| source_page.crop(src));
|
||||
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. Of a stream damaged partway, the copy draws
|
||||
|
||||
@@ -36,28 +36,28 @@ fn write_attachments(dst: &mut Document, entries: &mut [(Vec<u8>, Object)], uniq
|
||||
if entries.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
// Names are compared and numbered as text: a key written as UTF-16 (a name with an accent
|
||||
// or Chinese letters) must not get ASCII bytes appended to it.
|
||||
// Names are compared and numbered as text, and a renamed key keeps the encoding it came in:
|
||||
// " (2)" is appended as UTF-16 to a UTF-16 key (either byte order) and as bytes to a
|
||||
// PDFDocEncoding one, so a name with an accent or Chinese letters never gets ASCII bytes
|
||||
// appended to it and the rest of the key stays byte for byte as the file wrote it.
|
||||
if uniquify {
|
||||
let reserved: std::collections::HashSet<String> =
|
||||
entries.iter().map(|(k, _)| pdfcraft_cos::PdfString::literal(k.clone()).to_text()).collect();
|
||||
let reserved: std::collections::HashSet<String> = entries.iter().map(|(k, _)| key_text(k)).collect();
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
for (k, _) in entries.iter_mut() {
|
||||
let base = pdfcraft_cos::PdfString::literal(k.clone()).to_text();
|
||||
let mut text = base.clone();
|
||||
let base = key_text(k);
|
||||
if seen.insert(base.clone()) {
|
||||
continue;
|
||||
}
|
||||
let mut n = 2;
|
||||
if !seen.insert(text.clone()) {
|
||||
loop {
|
||||
text = format!("{base} ({n})");
|
||||
n += 1;
|
||||
if !reserved.contains(&text) && seen.insert(text.clone()) {
|
||||
break;
|
||||
}
|
||||
let suffix = loop {
|
||||
let suffix = format!(" ({n})");
|
||||
n += 1;
|
||||
let text = format!("{base}{suffix}");
|
||||
if !reserved.contains(&text) && seen.insert(text) {
|
||||
break suffix;
|
||||
}
|
||||
}
|
||||
if text != base {
|
||||
*k = pdfcraft_cos::PdfString::text(&text).bytes;
|
||||
}
|
||||
};
|
||||
append_in_encoding(k, &suffix);
|
||||
}
|
||||
}
|
||||
entries.sort_by(|a, b| a.0.cmp(&b.0));
|
||||
@@ -256,6 +256,36 @@ pub(super) fn add_outline(doc: &mut Document, marks: &[Mark]) -> Result<(), Orga
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A name-tree key as text: UTF-16 with either byte-order mark, else PDFDocEncoding.
|
||||
fn key_text(key: &[u8]) -> String {
|
||||
match key {
|
||||
[0xff, 0xfe, rest @ ..] => {
|
||||
let units: Vec<u16> = rest.as_chunks::<2>().0.iter().map(|c| u16::from_le_bytes(*c)).collect();
|
||||
String::from_utf16_lossy(&units)
|
||||
}
|
||||
_ => pdfcraft_cos::PdfString::literal(key.to_vec()).to_text(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Appends `suffix` (ASCII) to `key` in the key's own encoding.
|
||||
fn append_in_encoding(key: &mut Vec<u8>, suffix: &str) {
|
||||
match key.get(..2) {
|
||||
Some([0xfe, 0xff]) | Some([0xff, 0xfe]) => {
|
||||
// A leftover last byte is not a unit (readers leave it out when decoding). Drop it
|
||||
// so the suffix stays aligned, then append in the key's byte order.
|
||||
if key.len() % 2 == 1 {
|
||||
key.pop();
|
||||
}
|
||||
if key[0] == 0xfe {
|
||||
key.extend(suffix.encode_utf16().flat_map(u16::to_be_bytes));
|
||||
} else {
|
||||
key.extend(suffix.encode_utf16().flat_map(u16::to_le_bytes));
|
||||
}
|
||||
}
|
||||
_ => key.extend_from_slice(suffix.as_bytes()),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::sync::Arc;
|
||||
@@ -279,6 +309,26 @@ mod tests {
|
||||
Document::open(Arc::new(out)).expect("opens")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_attachments_renames_a_truncated_utf16_key_without_misaligning_the_suffix() {
|
||||
// A UTF-16 "A" with a leftover trailing byte: to_text ignores that byte, and a
|
||||
// byte-preserving append of " (2)" would pair it with the suffix and store the wrong name.
|
||||
let bodies = [
|
||||
"<< /Type /Catalog /Pages 2 0 R >>",
|
||||
"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 100 100] >>",
|
||||
"<< /Type /Page /Parent 2 0 R >>",
|
||||
];
|
||||
for (order, truncated) in [("BE", [0xfe, 0xff, 0x00, 0x41, 0x00].as_slice()), ("LE", [0xff, 0xfe, 0x41, 0x00, 0x00].as_slice())] {
|
||||
let mut doc = build(&bodies);
|
||||
set_attachments(&mut doc, vec![(truncated.to_vec(), Object::Null), (truncated.to_vec(), Object::Null)]).unwrap();
|
||||
let entries = crate::attachments::entries(&doc);
|
||||
let names: Vec<String> = entries.iter().map(|(k, _)| key_text(k)).collect();
|
||||
assert_eq!(names, ["A", "A (2)"], "{order}");
|
||||
let renamed = entries.iter().map(|(k, _)| k).find(|k| key_text(k) == "A (2)").expect("{order}: renamed key");
|
||||
assert_eq!(renamed.len() % 2, 0, "{order}: the renamed key is a complete UTF-16 string");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_attachments_does_not_clobber_later_numbered_attachment_name() {
|
||||
let mut doc = build(&[
|
||||
|
||||
@@ -4984,3 +4984,91 @@ fn combining_some_pages_brings_only_their_bookmarks_and_no_attachments() {
|
||||
assert_eq!(source_bookmarks(&all), [("Chapter one".to_string(), vec!["Section".to_string()])]);
|
||||
assert!(attachments(&all));
|
||||
}
|
||||
|
||||
/// #7687: a watermark source must clip and size the same visible area as the page.
|
||||
#[test]
|
||||
fn page_form_clips_crop_to_media_before_rotation() {
|
||||
for (crop, bbox, rotations) in [
|
||||
(
|
||||
[10, 20, 140, 170],
|
||||
[20., 30., 100., 150.],
|
||||
[
|
||||
(0, [1., 0., 0., 1., -20., -30.], (80., 120.)),
|
||||
(90, [0., -1., 1., 0., -30., 100.], (120., 80.)),
|
||||
(180, [-1., 0., 0., -1., 100., 150.], (80., 120.)),
|
||||
(270, [0., 1., -1., 0., 150., -20.], (120., 80.)),
|
||||
],
|
||||
),
|
||||
// Neither input box equals the intersection: ignoring CropBox must fail too.
|
||||
(
|
||||
[40, 10, 140, 110],
|
||||
[40., 30., 100., 110.],
|
||||
[
|
||||
(0, [1., 0., 0., 1., -40., -30.], (60., 80.)),
|
||||
(90, [0., -1., 1., 0., -30., 100.], (80., 60.)),
|
||||
(180, [-1., 0., 0., -1., 100., 110.], (60., 80.)),
|
||||
(270, [0., 1., -1., 0., 110., -40.], (80., 60.)),
|
||||
],
|
||||
),
|
||||
// The opposite overlap takes the bottom and right edges from CropBox.
|
||||
(
|
||||
[10, 50, 80, 170],
|
||||
[20., 50., 80., 150.],
|
||||
[
|
||||
(0, [1., 0., 0., 1., -20., -50.], (60., 100.)),
|
||||
(90, [0., -1., 1., 0., -50., 80.], (100., 60.)),
|
||||
(180, [-1., 0., 0., -1., 80., 150.], (60., 100.)),
|
||||
(270, [0., 1., -1., 0., 150., -20.], (100., 60.)),
|
||||
],
|
||||
),
|
||||
] {
|
||||
for (rotation, matrix, size) in rotations {
|
||||
for inherited in [false, true] {
|
||||
let mut src = open(fixture());
|
||||
let page = pages(&src).unwrap()[0].obj;
|
||||
let target = if inherited { src.get(page).as_dict().unwrap().reference(b"Parent").unwrap() } else { page };
|
||||
src.update_dict(target, |d| {
|
||||
d.set(b"MediaBox".to_vec(), Object::Array(vec![20.into(), 30.into(), 100.into(), 150.into()]));
|
||||
d.set(b"CropBox".to_vec(), Object::Array(crop.into_iter().map(Object::Int).collect()));
|
||||
d.set(b"Rotate".to_vec(), Object::Int(rotation));
|
||||
})
|
||||
.unwrap();
|
||||
let mut dst = Document::new_empty();
|
||||
let (form, actual_size) = page_as_form(&mut dst, &src, 0).unwrap();
|
||||
assert_eq!(actual_size, size);
|
||||
let obj = dst.get(form);
|
||||
let Object::Stream(stream) = &*obj else { panic!("form stream") };
|
||||
let numbers =
|
||||
|key: &[u8]| -> Vec<f64> { stream.dict.get(key).unwrap().as_array().unwrap().iter().map(|x| x.as_f64().unwrap()).collect() };
|
||||
assert_eq!(numbers(b"BBox"), bbox);
|
||||
assert_eq!(numbers(b"Matrix"), matrix);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Importers such as 3D posters must still be able to reject an explicitly empty source.
|
||||
#[test]
|
||||
fn page_form_keeps_explicit_zero_area_for_caller_validation() {
|
||||
for key in [b"MediaBox".as_slice(), b"CropBox".as_slice()] {
|
||||
for inherited in [false, true] {
|
||||
let mut src = open(fixture());
|
||||
let page = pages(&src).unwrap()[0].obj;
|
||||
src.update_dict(page, |d| d.set(b"Rotate".to_vec(), Object::Int(0))).unwrap();
|
||||
let target = if inherited { src.get(page).as_dict().unwrap().reference(b"Parent").unwrap() } else { page };
|
||||
if inherited {
|
||||
src.update_dict(page, |d| {
|
||||
d.remove(key);
|
||||
})
|
||||
.unwrap();
|
||||
}
|
||||
src.update_dict(target, |d| {
|
||||
d.set(key.to_vec(), Object::Array(vec![20.into(), 30.into(), 100.into(), 30.into()]));
|
||||
})
|
||||
.unwrap();
|
||||
let mut dst = Document::new_empty();
|
||||
let (_, size) = page_as_form(&mut dst, &src, 0).unwrap();
|
||||
assert_eq!(size, (80.0, 0.0));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -141,7 +141,14 @@ or in a form under an area (a stray `)` or `}` in a `TJ` array, say): the interp
|
||||
them, so text they hide, which other readers may draw, would be neither found nor removed. Remove
|
||||
hidden information refuses a page for both too, in whatever content it walks. A Redact annotation with neither a usable `/QuadPoints` array nor a usable
|
||||
`/Rect` makes it fail with `RedactError::UnreadableMark` before anything changes, instead of
|
||||
skipping that mark. The count covers the marks on the pages being applied.
|
||||
skipping that mark. The count covers the marks on the pages being applied. Where the walk or a
|
||||
cleanup can't read what it must to show something gone (content or forms with bytes the parser
|
||||
can't read, or past what one page may read or is followed, a form whose `/Matrix` isn't six
|
||||
numbers, a Type 3 font without the entries its cleanup reads), the operation fails with
|
||||
`RedactError::PageRefused`, naming the page whose content or forms are the cause, marked or not, or
|
||||
with `RedactError::Refused` where no one page is (a Type 3 font, or forms shared across the
|
||||
document). `remove_hidden` may have changed the document by then, as for its other refusals: a
|
||||
caller passes a copy it can drop.
|
||||
|
||||
Tiling-pattern cells are separate streams. Applying a mark removes a pattern resource when no
|
||||
surviving paint uses it. If a cell remains reachable after rewriting the selected pages and may
|
||||
|
||||
+62
-47
@@ -158,7 +158,7 @@ pub(crate) struct Output {
|
||||
/// rewrite would drop the bytes but keep the strings. A redaction must not trust it.
|
||||
pub unparsed: bool,
|
||||
pub tag_changes: Vec<(ObjRef, ObjRef, HashSet<i64>, HashSet<i64>)>,
|
||||
pub error: Option<CosError>,
|
||||
pub error: Option<RedactError>,
|
||||
}
|
||||
|
||||
pub(crate) struct Scope<'a> {
|
||||
@@ -1108,6 +1108,57 @@ fn show(scope: &mut Scope<'_>, gs: &Gs, tm: &mut Matrix, items: &[Object]) -> (V
|
||||
(out, removed)
|
||||
}
|
||||
|
||||
/// The content of form `s` (named `name`, object `r`) for [`xobject`], or what `xobject` returns
|
||||
/// for a form it can't read: Apply refuses the page once the page's budget is spent and drops a
|
||||
/// form that won't decode; the scans count a form past the budget, and the hidden-information
|
||||
/// scans one that won't decode as well.
|
||||
fn form_data(doc: &Document, scope: &mut Scope<'_>, s: &Stream, name: &[u8], r: ObjRef, out: &mut Output) -> Result<Vec<u8>, Option<Option<Op>>> {
|
||||
// Strict, like page content: a Form read only in part counts as undecodable. With its
|
||||
// `/DecodeParms` given by reference too, as the cleanups after the walk read it: read
|
||||
// without them, it looks empty and is left as it was, drawing whatever lies under a mark.
|
||||
let refused = scope.budget.refused();
|
||||
let entered = scope.budget.enter_form();
|
||||
let data = if entered {
|
||||
scope.budget.decode_strict(doc, s)
|
||||
} else {
|
||||
Err(CosError::Filter(format!("the page draws more than {MAX_PAGE_FORMS} form XObjects")))
|
||||
};
|
||||
match data {
|
||||
Ok(d) => Ok(d),
|
||||
// Past the page's budget nothing more is read: apply refuses the page, and
|
||||
// verification counts the form as content that may remain.
|
||||
Err(e) if scope.budget.exhausted() => {
|
||||
if scope.mode == Mode::Apply {
|
||||
// The budget spent says nothing of this form: it went past what the page
|
||||
// may read only where it was refused for that; one that doesn't decode
|
||||
// says why.
|
||||
let past = !entered || scope.budget.refused() > refused;
|
||||
out.error = Some(if past { RedactError::past_allowance(e) } else { e.into() });
|
||||
} else if scope.everywhere() {
|
||||
scope.layer_blocks += 1;
|
||||
} else {
|
||||
out.residue += 1;
|
||||
}
|
||||
Err(None)
|
||||
}
|
||||
Err(_) if scope.mode == Mode::Apply => {
|
||||
scope.report.forms_removed += 1;
|
||||
scope.removed_cut = true;
|
||||
out.replaced.push(name.to_vec());
|
||||
out.doomed.push(r);
|
||||
Err(Some(None))
|
||||
}
|
||||
Err(_) => {
|
||||
// Apply drops an undecodable Form while sanitizing. Count it during Verify
|
||||
// so a zero-count preflight cannot leave its potentially hidden bytes behind.
|
||||
if scope.everywhere() {
|
||||
scope.layer_blocks += 1;
|
||||
}
|
||||
Err(None)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `Do`: `None` = leave the operator alone; `Some(None)` = drop it; `Some(Some(op))` = replace it.
|
||||
fn xobject(
|
||||
doc: &mut Document,
|
||||
@@ -1177,16 +1228,14 @@ fn xobject(
|
||||
// the form is walked as it stands.
|
||||
Err(()) if scope.everywhere() && scope.hidden_text.is_none() => Matrix::IDENTITY,
|
||||
// Otherwise where the form draws, and so whether it reaches a mark or leaves the
|
||||
// page, can't be told. Apply refuses the page, and the scans count it, as for a
|
||||
// form past the page's budget below.
|
||||
// page, can't be told. Apply refuses the page, and the scans count it, as
|
||||
// `form_data` does for a form past the page's budget.
|
||||
Err(()) => {
|
||||
if scope.mode == Mode::Apply {
|
||||
out.error = Some(CosError::Syntax {
|
||||
offset: 0,
|
||||
detail:
|
||||
"a form XObject's /Matrix isn't six numbers given directly or through one reference, so where it draws can't be told"
|
||||
.into(),
|
||||
});
|
||||
out.error = Some(RedactError::Refused(
|
||||
"a form XObject's /Matrix isn't six numbers given directly or through one reference, so where it draws can't be told"
|
||||
.into(),
|
||||
));
|
||||
} else if scope.everywhere() {
|
||||
scope.layer_blocks += 1;
|
||||
} else {
|
||||
@@ -1207,8 +1256,8 @@ fn xobject(
|
||||
return None;
|
||||
}
|
||||
// Too deep: this form cannot be read, so it goes (Apply) or the page is left alone
|
||||
// (Verify), as a form that will not decode does. The page's decode budget below is what
|
||||
// keeps a fan-out or a cycle from costing 2^50 walks.
|
||||
// (Verify), as a form that will not decode does. The page's decode budget, which
|
||||
// `form_data` reads within, is what keeps a fan-out or a cycle from costing 2^50 walks.
|
||||
if scope.depth >= MAX_DEPTH {
|
||||
if scope.mode == Mode::Verify {
|
||||
// Sanitization removes a Form it cannot enter, so the verification scan
|
||||
@@ -1225,43 +1274,9 @@ fn xobject(
|
||||
out.doomed.push(r);
|
||||
return Some(None);
|
||||
}
|
||||
// Strict, like page content: a Form read only in part counts as undecodable. With its
|
||||
// `/DecodeParms` given by reference too, as the cleanups after the walk read it: read
|
||||
// without them, it looks empty and is left as it was, drawing whatever lies under a mark.
|
||||
let data = if scope.budget.enter_form() {
|
||||
scope.budget.decode_strict(doc, s)
|
||||
} else {
|
||||
Err(CosError::Filter(format!("the page draws more than {MAX_PAGE_FORMS} form XObjects")))
|
||||
};
|
||||
let data = match data {
|
||||
let data = match form_data(doc, scope, s, &name, r, out) {
|
||||
Ok(d) => d,
|
||||
// Past the page's budget nothing more is read: apply refuses the page, and
|
||||
// verification counts the form as content that may remain.
|
||||
Err(e) if scope.budget.exhausted() => {
|
||||
if scope.mode == Mode::Apply {
|
||||
out.error = Some(e);
|
||||
} else if scope.everywhere() {
|
||||
scope.layer_blocks += 1;
|
||||
} else {
|
||||
out.residue += 1;
|
||||
}
|
||||
return None;
|
||||
}
|
||||
Err(_) if scope.mode == Mode::Apply => {
|
||||
scope.report.forms_removed += 1;
|
||||
scope.removed_cut = true;
|
||||
out.replaced.push(name);
|
||||
out.doomed.push(r);
|
||||
return Some(None);
|
||||
}
|
||||
Err(_) => {
|
||||
// Apply drops an undecodable Form while sanitizing. Count it during Verify
|
||||
// so a zero-count preflight cannot leave its potentially hidden bytes behind.
|
||||
if scope.everywhere() {
|
||||
scope.layer_blocks += 1;
|
||||
}
|
||||
return None;
|
||||
}
|
||||
Err(leave_or_drop) => return leave_or_drop,
|
||||
};
|
||||
let own = s.dict.get(b"Resources").and_then(|r| doc.resolve(r).as_dict().cloned());
|
||||
let res = own.clone().unwrap_or_else(|| resources.clone());
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use super::{
|
||||
CosError, DecodeBudget, Dict, Document, HashMap, HashSet, MAX_DEPTH, Matrix, Metrics, ObjRef, Object, Op, Pieces, Rc, RedactError, Scope,
|
||||
is_vertical, num, overlaps, page_streams, res_dict,
|
||||
DecodeBudget, Dict, Document, HashMap, HashSet, MAX_DEPTH, Matrix, Metrics, ObjRef, Object, Op, Pieces, Rc, RedactError, Scope, is_vertical, num,
|
||||
overlaps, page_streams, res_dict,
|
||||
};
|
||||
|
||||
/// Drop every `replaced` name of the XObject resources `xo` that the rewritten `content` no
|
||||
@@ -13,7 +13,7 @@ use super::{
|
||||
/// fonts' cleanup, an allowance of its own when no Type 3 font is listed), the walk passes
|
||||
/// 2,000,000 operators, or the parser can't read all of such a form or of `content`.
|
||||
/// Corrupt data in such a form is read, tolerantly, up to the damage, which may be nothing.
|
||||
pub(crate) fn prune(doc: &Document, budget: &mut DecodeBudget, xo: &mut Dict, replaced: &[Vec<u8>], content: &[Vec<u8>]) -> Result<(), CosError> {
|
||||
pub(crate) fn prune(doc: &Document, budget: &mut DecodeBudget, xo: &mut Dict, replaced: &[Vec<u8>], content: &[Vec<u8>]) -> Result<(), RedactError> {
|
||||
if replaced.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
@@ -313,10 +313,14 @@ pub(crate) fn unlink_doomed(doc: &mut Document, doomed: &[ObjRef], retired_prope
|
||||
continue;
|
||||
}
|
||||
let mut contents = Vec::with_capacity(users.len());
|
||||
// Which page each content is, where the page tree lists it.
|
||||
let mut numbers = Vec::with_capacity(users.len());
|
||||
for user in &users {
|
||||
let page = doc.get(*user).as_dict().cloned().unwrap_or_default();
|
||||
let at = index.get(user).copied();
|
||||
// A page whose content cannot be read may still draw the name: fail closed.
|
||||
contents.push(page_streams(doc, &page, index.get(user).copied().unwrap_or(0))?.1);
|
||||
contents.push(page_streams(doc, &page, at.unwrap_or(0))?.1);
|
||||
numbers.push(at.map(|at| at + 1));
|
||||
}
|
||||
let mut pruned = false;
|
||||
// What each page draws through this dictionary, worked out once for all the names.
|
||||
@@ -329,13 +333,21 @@ pub(crate) fn unlink_doomed(doc: &mut Document, doomed: &[ObjRef], retired_prope
|
||||
xo.remove(&n);
|
||||
pruned = true;
|
||||
}
|
||||
None => return Err(RedactError::Residue(1)),
|
||||
// A page sharing these resources draws through them forms that can't all be read.
|
||||
None => {
|
||||
let reason = "a form it draws through resources shared with what was removed can't all be read".to_string();
|
||||
let page = drawn.iter().zip(&numbers).find(|((_, unknown), _)| *unknown).and_then(|(_, page)| *page);
|
||||
return Err(match page {
|
||||
Some(page) => RedactError::PageRefused { page, reason },
|
||||
None => RedactError::Refused(reason),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
if pruned {
|
||||
res.set(b"XObject".to_vec(), Object::Dict(xo));
|
||||
}
|
||||
pruned |= prune_retired_properties(doc, &mut res, &property_names, &contents)?;
|
||||
pruned |= prune_retired_properties(doc, &mut res, &property_names, &contents, &numbers)?;
|
||||
if pruned {
|
||||
doc.update_dict(node, |d| d.set(b"Resources".to_vec(), Object::Dict(res)))?;
|
||||
}
|
||||
@@ -349,14 +361,26 @@ pub(crate) fn unlink_doomed(doc: &mut Document, doomed: &[ObjRef], retired_prope
|
||||
|
||||
/// Retire only properties removed from a rewritten scope, preserving names still used by any
|
||||
/// content sharing this holder. Different pages' streams must never be concatenated together.
|
||||
fn prune_retired_properties(doc: &Document, res: &mut Dict, names: &[Vec<u8>], contents: &[Vec<Vec<u8>>]) -> Result<bool, CosError> {
|
||||
/// `pages` are the (1-based) pages whose content `contents` are, in order, named when theirs
|
||||
/// refuses; a form's content has none, nor a page the page tree doesn't list.
|
||||
fn prune_retired_properties(
|
||||
doc: &Document,
|
||||
res: &mut Dict,
|
||||
names: &[Vec<u8>],
|
||||
contents: &[Vec<Vec<u8>>],
|
||||
pages: &[Option<usize>],
|
||||
) -> Result<bool, RedactError> {
|
||||
if names.is_empty() {
|
||||
return Ok(false);
|
||||
}
|
||||
let mut used = HashSet::new();
|
||||
for content in contents {
|
||||
for (i, content) in contents.iter().enumerate() {
|
||||
// Each is one page's content or one form's, with the allowance of a page.
|
||||
for op in resource_ops(doc, &mut DecodeBudget::page(), res, content)? {
|
||||
let ops = resource_ops(doc, &mut DecodeBudget::page(), res, content).map_err(|e| match pages.get(i).copied().flatten() {
|
||||
Some(page) => e.on_page(page),
|
||||
None => e,
|
||||
})?;
|
||||
for op in ops {
|
||||
if matches!(op.op.as_slice(), b"BDC" | b"DP")
|
||||
&& let Some(name) = op.last_name()
|
||||
{
|
||||
@@ -384,7 +408,7 @@ fn prune_retired_properties(doc: &Document, res: &mut Dict, names: &[Vec<u8>], c
|
||||
/// Unlink retired properties and `doomed` XObjects from the resources of the forms reachable from
|
||||
/// the page-tree `holders`, each unless the form's own content (or a form inheriting its
|
||||
/// resources) still uses the name. Fails closed when that cannot be determined.
|
||||
fn unlink_from_forms(doc: &mut Document, holders: &[ObjRef], doomed: &HashSet<ObjRef>, retired: &[Object]) -> Result<(), CosError> {
|
||||
fn unlink_from_forms(doc: &mut Document, holders: &[ObjRef], doomed: &HashSet<ObjRef>, retired: &[Object]) -> Result<(), RedactError> {
|
||||
if retired.is_empty() && doomed.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
@@ -400,7 +424,7 @@ fn unlink_from_forms(doc: &mut Document, holders: &[ObjRef], doomed: &HashSet<Ob
|
||||
continue;
|
||||
}
|
||||
if seen.len() > 1_000_000 {
|
||||
return Err(CosError::Syntax { offset: 0, detail: "redaction could not fully inspect shared form resources".into() });
|
||||
return Err(RedactError::Refused("the forms the document's resources draw are more than can be followed".into()));
|
||||
}
|
||||
let object = doc.get(reference);
|
||||
let Object::Stream(form) = &*object else { continue };
|
||||
@@ -422,7 +446,7 @@ fn unlink_from_forms(doc: &mut Document, holders: &[ObjRef], doomed: &HashSet<Ob
|
||||
if pruned {
|
||||
res.set(b"XObject".to_vec(), Object::Dict(xo));
|
||||
}
|
||||
pruned |= prune_retired_properties(doc, &mut res, &names, &[vec![data]])?;
|
||||
pruned |= prune_retired_properties(doc, &mut res, &names, &[vec![data]], &[])?;
|
||||
if pruned {
|
||||
doc.update_dict(reference, |d| d.set(b"Resources".to_vec(), Object::Dict(res.clone())))?;
|
||||
}
|
||||
@@ -432,7 +456,7 @@ fn unlink_from_forms(doc: &mut Document, holders: &[ObjRef], doomed: &HashSet<Ob
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn prune_doomed_xobjects(doc: &Document, content: &[Vec<u8>], xo: &mut Dict, doomed_names: &[Vec<u8>]) -> Result<bool, CosError> {
|
||||
fn prune_doomed_xobjects(doc: &Document, content: &[Vec<u8>], xo: &mut Dict, doomed_names: &[Vec<u8>]) -> Result<bool, RedactError> {
|
||||
let mut pruned = false;
|
||||
if doomed_names.is_empty() {
|
||||
return Ok(false);
|
||||
@@ -442,7 +466,9 @@ fn prune_doomed_xobjects(doc: &Document, content: &[Vec<u8>], xo: &mut Dict, doo
|
||||
match any_draws(&drawn, name) {
|
||||
Some(true) => {}
|
||||
Some(false) => pruned |= xo.remove(name).is_some(),
|
||||
None => return Err(CosError::Syntax { offset: 0, detail: "redaction could not fully inspect shared form resources".into() }),
|
||||
None => {
|
||||
return Err(RedactError::Refused("a form that may still draw what was removed draws forms that can't all be read".into()));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(pruned)
|
||||
@@ -479,14 +505,16 @@ pub(super) fn clip_out(rects: &[[f64; 4]], ctm: &Matrix, around: [f64; 4]) -> Op
|
||||
/// when that can't all be read: the parser can't read all of `content` or of such a form, the walk
|
||||
/// passes 2,000,000 operators, or such a form doesn't decode or runs past `budget`. Operators are
|
||||
/// read one at a time, so the walk stops at one past the limit rather than holding them all.
|
||||
pub(crate) fn resource_ops(doc: &Document, budget: &mut DecodeBudget, res: &Dict, content: &[Vec<u8>]) -> Result<Vec<Op>, CosError> {
|
||||
pub(crate) fn resource_ops(doc: &Document, budget: &mut DecodeBudget, res: &Dict, content: &[Vec<u8>]) -> Result<Vec<Op>, RedactError> {
|
||||
const MAX_OPS: usize = 2_000_000;
|
||||
let joined = Pieces::join(content);
|
||||
let mut read = pdfcraft_content::ops(joined.data());
|
||||
let mut ops: Vec<Op> = read.by_ref().take(MAX_OPS + 1).collect();
|
||||
// Under the limit the reader ran to the end, so `skipped` counts all of it.
|
||||
if read.skipped() > 0 || ops.len() > MAX_OPS {
|
||||
return Err(CosError::Syntax { offset: 0, detail: "redaction could not fully read the content that uses these resources".into() });
|
||||
return Err(RedactError::Refused(
|
||||
"content that draws with its resources has bytes that can't be read, or more than 2,000,000 operators".into(),
|
||||
));
|
||||
}
|
||||
let xobjects = res_dict(doc, res, b"XObject");
|
||||
let mut seen = HashSet::new();
|
||||
@@ -500,12 +528,19 @@ pub(crate) fn resource_ops(doc: &Document, budget: &mut DecodeBudget, res: &Dict
|
||||
&& s.dict.name(b"Subtype") == Some(b"Form")
|
||||
&& s.dict.get(b"Resources").is_none_or(|r| doc.resolve(r).as_dict().is_none())
|
||||
{
|
||||
let data = budget.decode(&doc.with_direct_parms(s))?;
|
||||
// Past what the page may read where the budget refused it; a form that doesn't decode
|
||||
// says why.
|
||||
let refused = budget.refused();
|
||||
let data = budget
|
||||
.decode(&doc.with_direct_parms(s))
|
||||
.map_err(|e| if budget.refused() > refused { RedactError::past_allowance(e) } else { e.into() })?;
|
||||
let mut read = pdfcraft_content::ops(&data);
|
||||
ops.extend(read.by_ref().take((MAX_OPS + 1).saturating_sub(ops.len())));
|
||||
// `seen` gains at most one form for each `Do` in `ops`, so this bounds it too.
|
||||
if ops.len() > MAX_OPS || read.skipped() > 0 {
|
||||
return Err(CosError::Syntax { offset: 0, detail: "redaction could not fully inspect inherited form resources".into() });
|
||||
return Err(RedactError::Refused(
|
||||
"a form without resources of its own has bytes that can't be read, or takes what draws with those resources past 2,000,000 operators".into(),
|
||||
));
|
||||
}
|
||||
}
|
||||
cursor += 1;
|
||||
@@ -513,7 +548,7 @@ pub(crate) fn resource_ops(doc: &Document, budget: &mut DecodeBudget, res: &Dict
|
||||
Ok(ops)
|
||||
}
|
||||
|
||||
pub(crate) fn prune_properties(doc: &Document, budget: &mut DecodeBudget, res: &mut Dict, content: &[Vec<u8>]) -> Result<Vec<Object>, CosError> {
|
||||
pub(crate) fn prune_properties(doc: &Document, budget: &mut DecodeBudget, res: &mut Dict, content: &[Vec<u8>]) -> Result<Vec<Object>, RedactError> {
|
||||
let mut properties = res_dict(doc, res, b"Properties");
|
||||
if properties.is_empty() {
|
||||
return Ok(Vec::new());
|
||||
@@ -536,7 +571,7 @@ pub(crate) fn prune_properties(doc: &Document, budget: &mut DecodeBudget, res: &
|
||||
Ok(retired)
|
||||
}
|
||||
|
||||
pub(super) fn prune_form_resources(doc: &Document, budget: &mut DecodeBudget, res: &mut Dict, content: &[Vec<u8>]) -> Result<(), CosError> {
|
||||
pub(super) fn prune_form_resources(doc: &Document, budget: &mut DecodeBudget, res: &mut Dict, content: &[Vec<u8>]) -> Result<(), RedactError> {
|
||||
let ops = resource_ops(doc, budget, res, content)?;
|
||||
let mut xo = res_dict(doc, res, b"XObject");
|
||||
let names: Vec<Vec<u8>> = xo.iter().map(|(n, _)| n.to_vec()).collect();
|
||||
|
||||
@@ -131,6 +131,17 @@ pub enum RedactError {
|
||||
"finding and storing again what shares JBIG2 symbol data with something being removed would read more of this file than one run allows, so it can't be shown that the data leaves with it; this was refused"
|
||||
)]
|
||||
SharedJbig2Budget,
|
||||
/// What cleaning a page needs to read whole, or to find, isn't there to read: content with
|
||||
/// bytes the parser can't read, or past what one page may read or is followed, forms nesting
|
||||
/// past what is followed, a form whose placement can't be told. What it holds can't be shown
|
||||
/// gone.
|
||||
#[error("page {page} can't be redacted safely: {reason}; the operation was refused")]
|
||||
PageRefused { page: usize, reason: String },
|
||||
/// [`RedactError::PageRefused`] where no one page is the cause: a Type 3 font's own entries,
|
||||
/// glyphs or forms, forms and resources shared across the document, or a page the page tree
|
||||
/// doesn't list.
|
||||
#[error("the document can't be redacted safely: {0}; the operation was refused")]
|
||||
Refused(String),
|
||||
#[error(transparent)]
|
||||
Edit(#[from] pdfcraft_edit::EditError),
|
||||
#[error(transparent)]
|
||||
@@ -139,6 +150,40 @@ pub enum RedactError {
|
||||
Cos(#[from] pdfcraft_cos::CosError),
|
||||
}
|
||||
|
||||
/// What a `DecodeBudget` said when it refused: a filter's message as it stands, another error as
|
||||
/// it displays.
|
||||
fn budget_detail(error: pdfcraft_cos::CosError) -> String {
|
||||
match error {
|
||||
pdfcraft_cos::CosError::Filter(detail) => detail,
|
||||
other => other.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
impl RedactError {
|
||||
/// The refusal of content and forms that go past what one page may read, from what the page's
|
||||
/// `DecodeBudget` said.
|
||||
pub(crate) fn past_allowance(error: pdfcraft_cos::CosError) -> Self {
|
||||
RedactError::Refused(format!("content and forms go past what one page may read ({})", budget_detail(error)))
|
||||
}
|
||||
|
||||
/// The refusal of the glyph programs the document's Type 3 fonts keep, which the cleanup
|
||||
/// reads under one allowance the size of a page's, when together they go past it.
|
||||
pub(crate) fn past_glyph_allowance(error: pdfcraft_cos::CosError) -> Self {
|
||||
RedactError::Refused(format!(
|
||||
"the glyph programs the document's Type 3 fonts keep go, together, past what one page may read ({})",
|
||||
budget_detail(error)
|
||||
))
|
||||
}
|
||||
|
||||
/// This error as met while cleaning page `page` (1-based): a refusal names the page.
|
||||
pub(crate) fn on_page(self, page: usize) -> Self {
|
||||
match self {
|
||||
RedactError::Refused(reason) => RedactError::PageRefused { page, reason },
|
||||
other => other,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// [`RedactError::SharedJbig2Globals`]'s text, which says what keeps the data.
|
||||
fn shared_jbig2_text(stuck: usize) -> String {
|
||||
let why = match stuck {
|
||||
@@ -624,7 +669,7 @@ fn apply_within(doc: &mut Document, pages: Option<&[usize]>, images: pdfcraft_co
|
||||
for &(pi, page_marks) in &groups {
|
||||
let page = pdfcraft_model::pages(doc).swap_remove(pi);
|
||||
let rects: Vec<[f64; 4]> = page_marks.iter().flat_map(|m| m.rects.iter().copied()).collect();
|
||||
redact_page_content(doc, &mut applying, pi, &page, &rects)?;
|
||||
redact_page_content(doc, &mut applying, pi, &page, &rects).map_err(|e| e.on_page(pi + 1))?;
|
||||
remove_page_annotations(doc, &mut applying, pi, &page, &rects, page_marks)?;
|
||||
}
|
||||
if applying.images.refused() > 0 {
|
||||
@@ -904,7 +949,7 @@ fn redact_page_content(
|
||||
// document). The error does not claim the text was under the mark. Full vertical-text
|
||||
// removal is a future enhancement.
|
||||
if let Some(error) = out.error {
|
||||
return Err(error.into());
|
||||
return Err(error);
|
||||
}
|
||||
if out.vertical {
|
||||
return Err(RedactError::VerticalText(pi + 1));
|
||||
|
||||
@@ -658,7 +658,7 @@ fn content_pass(doc: &mut Document, text: bool, layers: bool, write: bool) -> Re
|
||||
scope.layers_enabled = layers;
|
||||
let out = process(doc, &mut scope, &data, &resources, Matrix::IDENTITY);
|
||||
if let Some(error) = out.error {
|
||||
return Err(error.into());
|
||||
return Err(error.on_page(pi + 1));
|
||||
}
|
||||
// Bytes the parser can't read, or an inline image whose end is a guess: the walk reads past
|
||||
// them, so what it reads around them may not be what other readers draw (hidden text in a
|
||||
@@ -714,11 +714,11 @@ fn content_pass(doc: &mut Document, text: bool, layers: bool, write: bool) -> Re
|
||||
}
|
||||
// A full save keeps whatever is still referenced: unlink the originals this page no
|
||||
// longer draws so the removed form or image bytes cannot survive in the saved file.
|
||||
crate::interp::prune(doc, &mut budget, &mut xo, &out.replaced, &page_content)?;
|
||||
crate::interp::prune(doc, &mut budget, &mut xo, &out.replaced, &page_content).map_err(|e| e.on_page(pi + 1))?;
|
||||
res.set(b"XObject".to_vec(), Object::Dict(xo));
|
||||
}
|
||||
retired_properties.extend(crate::interp::prune_properties(doc, &mut budget, &mut res, &page_content)?);
|
||||
crate::type3::prune_type3_from_resources(doc, &mut budget, &mut res, &page_content, Some(&page.dict))?;
|
||||
retired_properties.extend(crate::interp::prune_properties(doc, &mut budget, &mut res, &page_content).map_err(|e| e.on_page(pi + 1))?);
|
||||
crate::type3::prune_type3_from_resources(doc, &mut budget, &mut res, &page_content, Some(&page.dict)).map_err(|e| e.on_page(pi + 1))?;
|
||||
doc.update_dict(page.obj, |d| {
|
||||
d.set(b"Contents".to_vec(), Object::Array(new_list));
|
||||
d.set(b"Resources".to_vec(), Object::Dict(res));
|
||||
|
||||
@@ -3475,7 +3475,7 @@ fn unreadable_bytes_in_a_stream_left_as_it_was_refuse_the_redaction_of_an_image(
|
||||
mark(&mut doc, 0, &[[0.0, 200.0, 300.0, 300.0]], "");
|
||||
let result = apply(&mut doc, None);
|
||||
assert!(
|
||||
matches!(&result, Err(RedactError::Cos(pdfcraft_cos::CosError::Syntax { detail, .. })) if detail == "redaction could not fully inspect inherited form resources"),
|
||||
matches!(&result, Err(RedactError::PageRefused { page: 1, reason }) if reason.starts_with("a form without resources of its own has bytes")),
|
||||
"{result:?}"
|
||||
);
|
||||
}
|
||||
@@ -6406,6 +6406,7 @@ mod metadata_fail_closed;
|
||||
mod metadata_matching;
|
||||
mod operands_from_the_end;
|
||||
mod property_retirement;
|
||||
mod refusal_pages;
|
||||
mod surviving_references;
|
||||
mod text_state;
|
||||
mod unparsed;
|
||||
|
||||
@@ -65,13 +65,48 @@ fn a_form_whose_matrix_is_not_six_numbers_is_refused() {
|
||||
mark(&mut doc, 0, &[MARK], "");
|
||||
let result = apply(&mut doc, None);
|
||||
assert!(
|
||||
matches!(&result, Err(RedactError::Cos(pdfcraft_cos::CosError::Syntax { detail, .. })) if detail.contains("/Matrix")),
|
||||
matches!(&result, Err(RedactError::PageRefused { page: 1, reason }) if reason.contains("/Matrix")),
|
||||
"{matrix} with 8 0 obj {}: {result:?}",
|
||||
String::from_utf8_lossy(extra)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// The refusal names the page whose form can't be placed, and says the operation was refused: here the
|
||||
/// second, which shares the first's resources and draws the form the first doesn't, for Apply
|
||||
/// Redactions and for Remove Hidden Information.
|
||||
#[test]
|
||||
fn a_refusal_names_the_page_whose_form_can_t_be_placed() {
|
||||
use crate::sanitize::{Hidden, remove_hidden};
|
||||
let two_pages = || {
|
||||
pdf(vec![
|
||||
b"<< /Type /Catalog /Pages 2 0 R >>".to_vec(),
|
||||
b"<< /Type /Pages /Kids [3 0 R 9 0 R] /Count 2 >>".to_vec(),
|
||||
b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 300] /Contents 4 0 R /Resources 10 0 R >>".to_vec(),
|
||||
stream("", b"BT /F1 10 Tf 20 260 Td (PLAIN) Tj ET"),
|
||||
FONT.replace("95 0 R", "6 0 R").into_bytes(),
|
||||
widths(),
|
||||
stream(
|
||||
"/Type /XObject /Subtype /Form /BBox [0 0 300 100] /Matrix [1 0 0 1 0 (up)] /Resources << /Font << /F1 5 0 R >> >>",
|
||||
b"BT /F1 10 Tf 20 60 Td (SECRET) Tj ET",
|
||||
),
|
||||
b"null".to_vec(),
|
||||
b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 300] /Contents 11 0 R /Resources 10 0 R >>".to_vec(),
|
||||
b"<< /Font << /F1 5 0 R >> /XObject << /Fm 7 0 R >> >>".to_vec(),
|
||||
stream("", b"/Fm Do"),
|
||||
])
|
||||
};
|
||||
let said = "page 2 can't be redacted safely: a form XObject's /Matrix isn't six numbers given directly or through one reference, so where it draws can't be told; the operation was refused";
|
||||
let mut doc = two_pages();
|
||||
mark(&mut doc, 1, &[MARK], "");
|
||||
let applied = apply(&mut doc, None);
|
||||
assert!(matches!(&applied, Err(RedactError::PageRefused { page: 2, .. })), "{applied:?}");
|
||||
assert_eq!(applied.map(|_| ()).unwrap_err().to_string(), said);
|
||||
let removed = remove_hidden(&mut two_pages(), &[Hidden::HiddenText]);
|
||||
assert!(matches!(&removed, Err(RedactError::PageRefused { page: 2, .. })), "{removed:?}");
|
||||
assert_eq!(removed.map(|_| ()).unwrap_err().to_string(), said);
|
||||
}
|
||||
|
||||
/// A reference to a reference, for the matrix or one of its entries: Poppler doesn't follow it (it
|
||||
/// reads such a matrix as the identity, such an entry as 0), the app's renderer follows it and
|
||||
/// reads the move, so where the form draws can't be told, and the page is refused, as for a matrix that isn't six numbers. Read as either,
|
||||
@@ -88,7 +123,7 @@ fn a_form_whose_matrix_goes_through_a_reference_to_a_reference_is_refused() {
|
||||
mark(&mut doc, 0, &[mark_at], "");
|
||||
let result = apply(&mut doc, None);
|
||||
assert!(
|
||||
matches!(&result, Err(RedactError::Cos(pdfcraft_cos::CosError::Syntax { detail, .. })) if detail.contains("/Matrix")),
|
||||
matches!(&result, Err(RedactError::PageRefused { page: 1, reason }) if reason.contains("/Matrix")),
|
||||
"{matrix}, 8 0 obj 9 0 R, 9 0 obj {}, mark at {mark_at:?}: {result:?}",
|
||||
String::from_utf8_lossy(target)
|
||||
);
|
||||
@@ -106,7 +141,7 @@ fn a_form_whose_matrix_is_not_six_numbers_counts_in_the_scans() {
|
||||
let counts: std::collections::HashMap<Hidden, usize> = scan(&doc).into_iter().collect();
|
||||
assert_eq!(counts[&Hidden::HiddenText], 1);
|
||||
let removed = remove_hidden(&mut doc, &[Hidden::HiddenText]);
|
||||
assert!(matches!(&removed, Err(RedactError::Cos(pdfcraft_cos::CosError::Syntax { detail, .. })) if detail.contains("/Matrix")), "{removed:?}");
|
||||
assert!(matches!(&removed, Err(RedactError::PageRefused { page: 1, reason }) if reason.contains("/Matrix")), "{removed:?}");
|
||||
}
|
||||
|
||||
/// Removing hidden layers alone never asks where content lands, so such a form is walked as it
|
||||
|
||||
@@ -156,7 +156,15 @@ fn uninspectable_forms_with_candidate_properties_fail_closed() {
|
||||
add_second_page(&mut doc, b"/Fm Do", Object::Ref(shared));
|
||||
assert_eq!(under(&mut doc, 0, &[[5.0, 195.0, 60.0, 212.0]]), 6);
|
||||
let error = redact_first(&mut doc).unwrap_err();
|
||||
assert!(matches!(error, RedactError::Cos(_)), "own Resources={own}, malformed={malformed}: {error:?}");
|
||||
// A form that doesn't decode says so; one the parser can't read is a refusal, of the
|
||||
// second page when it draws the form through the page's resources, and of the document
|
||||
// when the form is read for its own.
|
||||
let expected = match (own, malformed) {
|
||||
(_, false) => matches!(error, RedactError::Cos(pdfcraft_cos::CosError::Filter(_))),
|
||||
(false, true) => matches!(&error, RedactError::PageRefused { page: 2, reason } if reason.contains("without resources of its own")),
|
||||
(true, true) => matches!(&error, RedactError::Refused(reason) if reason.contains("draws with its resources")),
|
||||
};
|
||||
assert!(expected, "own Resources={own}, malformed={malformed}: {error:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,147 @@
|
||||
//! Redaction refusals name the page whose content or forms are their cause
|
||||
//! (`RedactError::PageRefused`), in Apply Redactions and Remove Hidden Information, and errors
|
||||
//! that aren't refusals keep their own text.
|
||||
|
||||
use super::*;
|
||||
use crate::sanitize::{Hidden, remove_hidden};
|
||||
|
||||
/// Two pages: the first plain, the second showing hidden text (`3 Tr`) and then `content`, with
|
||||
/// `res` as its resources; objects from 9 on are `extra`.
|
||||
fn second_page_hidden(content: &[u8], res: &str, extra: Vec<Vec<u8>>) -> Document {
|
||||
let mut objs = vec![
|
||||
b"<< /Type /Catalog /Pages 2 0 R >>".to_vec(),
|
||||
b"<< /Type /Pages /Kids [3 0 R 7 0 R] /Count 2 >>".to_vec(),
|
||||
b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 300] /Contents 4 0 R /Resources << /Font << /F1 5 0 R >> >> >>".to_vec(),
|
||||
stream("", b"BT /F1 10 Tf 20 260 Td (PLAIN) Tj ET"),
|
||||
FONT.replace("95 0 R", "6 0 R").into_bytes(),
|
||||
widths(),
|
||||
format!("<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 300] /Contents 8 0 R /Resources << {res} >> >>").into_bytes(),
|
||||
stream("", [b"BT /F1 10 Tf 3 Tr 20 60 Td (HIDDEN) Tj ET ".as_slice(), content].concat()),
|
||||
];
|
||||
objs.extend(extra);
|
||||
pdf(objs)
|
||||
}
|
||||
|
||||
/// Asserts that removing hidden text from `doc` is refused, naming page 2, for a reason that holds
|
||||
/// `reason`.
|
||||
fn refuses_page_two(mut doc: Document, reason: &str) {
|
||||
let removed = remove_hidden(&mut doc, &[Hidden::HiddenText]);
|
||||
assert!(matches!(&removed, Err(RedactError::PageRefused { page: 2, reason: r }) if r.contains(reason)), "{removed:?}");
|
||||
}
|
||||
|
||||
/// Past 2,000,000 operators, what the second page's resources still draw can't be told: the
|
||||
/// refusal of the properties' cleanup names that page.
|
||||
#[test]
|
||||
fn the_properties_cleanup_names_the_page_it_refuses() {
|
||||
let many = b"n ".repeat(2_000_001);
|
||||
refuses_page_two(second_page_hidden(&many, "/Font << /F1 5 0 R >> /Properties << /P0 << >> >>", vec![]), "more than 2,000,000 operators");
|
||||
}
|
||||
|
||||
/// The same for the cleanup of the forms the page replaced, which reads the page first.
|
||||
#[test]
|
||||
fn the_replaced_forms_cleanup_names_the_page_it_refuses() {
|
||||
let many = [b"/Fm Do ".as_slice(), &b"n ".repeat(2_000_001)].concat();
|
||||
let form = stream(
|
||||
"/Type /XObject /Subtype /Form /BBox [0 0 300 300] /Resources << /Font << /F1 5 0 R >> >>",
|
||||
b"BT /F1 10 Tf 3 Tr 20 100 Td (FORMHIDDEN) Tj ET",
|
||||
);
|
||||
refuses_page_two(second_page_hidden(&many, "/Font << /F1 5 0 R >> /XObject << /Fm 9 0 R >>", vec![form]), "more than 2,000,000 operators");
|
||||
}
|
||||
|
||||
/// With a Type 3 font listed, the fonts' cleanup reads the soft masks without resources of their
|
||||
/// own that the page sets, which the walk doesn't enter: one with bytes the parser can't read is
|
||||
/// refused, naming the page.
|
||||
#[test]
|
||||
fn the_type3_cleanup_names_the_page_it_refuses() {
|
||||
let group = stream("/Type /XObject /Subtype /Form /BBox [0 0 300 300] /Group << /S /Transparency >>", b"BT ( ET");
|
||||
let font = b"<< /Type /Font /Subtype /Type3 /FontBBox [0 0 1000 1000] /FontMatrix [0.001 0 0 0.001 0 0] /FirstChar 65 /LastChar 65 /Widths [500] /Encoding << /Differences [65 /A] >> /CharProcs << >> >>".to_vec();
|
||||
let res = "/Font << /F1 5 0 R /T3 10 0 R >> /ExtGState << /GS1 << /SMask << /S /Luminosity /G 9 0 R >> >> >>";
|
||||
refuses_page_two(second_page_hidden(b"/GS1 gs", res, vec![group, font]), "a soft mask or form without resources of its own has bytes");
|
||||
}
|
||||
|
||||
/// A page whose forms go past what one page may read is refused, named, by Apply Redactions and by
|
||||
/// Remove Hidden Information: here it draws a form more often than the page may enter forms.
|
||||
#[test]
|
||||
fn a_page_past_what_it_may_read_is_named() {
|
||||
let many = [b"BT /F1 10 Tf 20 260 Td (SECRET) Tj ET ".as_slice(), &b"/Fm Do ".repeat(pdfcraft_cos::MAX_PAGE_FORMS + 1)].concat();
|
||||
let page = || one_page(&many, "/XObject << /Fm 7 0 R >>", vec![stream("/Type /XObject /Subtype /Form /BBox [0 0 300 300]", b"0 0 m")]);
|
||||
let past = |error: &RedactError| {
|
||||
matches!(error, RedactError::PageRefused { page: 1, reason }
|
||||
if reason == &format!("content and forms go past what one page may read (the page draws more than {} form XObjects)", pdfcraft_cos::MAX_PAGE_FORMS))
|
||||
};
|
||||
let mut doc = page();
|
||||
mark(&mut doc, 0, &[[0.0, 250.0, 300.0, 280.0]], "");
|
||||
let applied = apply(&mut doc, None).map(|_| ());
|
||||
assert!(applied.as_ref().is_err_and(past), "{applied:?}");
|
||||
let removed = remove_hidden(&mut page(), &[Hidden::HiddenText]).map(|_| ());
|
||||
assert!(removed.as_ref().is_err_and(past), "{removed:?}");
|
||||
}
|
||||
|
||||
/// Pages sharing a resource dictionary with an image a mark removed: the second draws, through
|
||||
/// the shared resources, a form that doesn't decode, so whether it still draws the image can't be
|
||||
/// told. The refusal names the second page, and doesn't say anything was found under the mark.
|
||||
#[test]
|
||||
fn a_page_sharing_resources_whose_forms_can_t_be_read_is_named() {
|
||||
let mut doc = pdf(vec![
|
||||
b"<< /Type /Catalog /Pages 2 0 R >>".to_vec(),
|
||||
b"<< /Type /Pages /Kids [3 0 R 9 0 R] /Count 2 >>".to_vec(),
|
||||
b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 300] /Contents 4 0 R /Resources 11 0 R >>".to_vec(),
|
||||
stream("", b"q 50 0 0 50 20 230 cm /Im1 Do Q"),
|
||||
b"null".to_vec(),
|
||||
b"null".to_vec(),
|
||||
stream("/Type /XObject /Subtype /Image /Width 16 /Height 1 /ColorSpace /DeviceGray /BitsPerComponent 8", b"REDIMGONECOVERED"),
|
||||
stream("/Type /XObject /Subtype /Form /BBox [0 0 300 300] /Filter /UnsupportedForTheTest", b"opaque"),
|
||||
b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 300] /Contents 10 0 R /Resources 11 0 R >>".to_vec(),
|
||||
stream("", b"/FmBad Do"),
|
||||
b"<< /XObject << /Im1 7 0 R /FmBad 8 0 R >> >>".to_vec(),
|
||||
]);
|
||||
mark(&mut doc, 0, &[[0.0, 200.0, 300.0, 300.0]], "");
|
||||
let applied = apply(&mut doc, None).map(|_| ());
|
||||
assert!(matches!(&applied, Err(RedactError::PageRefused { page: 2, reason }) if reason.contains("can't all be read")), "{applied:?}");
|
||||
}
|
||||
|
||||
/// A page whose forms spend exactly what it may enter, nothing refused, and a form that doesn't
|
||||
/// decode: that form says why, and the page isn't said to go past what it may read. In the walk, as
|
||||
/// the page's last entry, where with room left the walk would remove it, it still refuses the
|
||||
/// page, as before, now with its own text; in the cleanup of the page's properties, outside the
|
||||
/// mark, which the walk doesn't enter, for Apply Redactions; and in the Type 3 cleanup's read of an
|
||||
/// annotation appearance, for Apply Redactions and Remove Hidden Information.
|
||||
#[test]
|
||||
fn a_form_that_doesn_t_decode_at_the_page_s_last_entry_says_why() {
|
||||
const MAX: usize = pdfcraft_cos::MAX_PAGE_FORMS;
|
||||
const SECRET: &[u8] = b"BT /F1 10 Tf 20 260 Td (SECRET) Tj ET ";
|
||||
const BAD: &str = "/Type /XObject /Subtype /Form /BBox [0 0 300 300] /Filter /UnsupportedForTheTest";
|
||||
let says_why = |result: Result<(), RedactError>| {
|
||||
assert!(matches!(&result, Err(RedactError::Cos(pdfcraft_cos::CosError::Filter(why))) if why.contains("UnsupportedForTheTest")), "{result:?}");
|
||||
};
|
||||
let form = || stream("/Type /XObject /Subtype /Form /BBox [0 0 300 300]", b"0 0 m");
|
||||
let marked = |mut doc: Document| {
|
||||
mark(&mut doc, 0, &[[0.0, 250.0, 300.0, 280.0]], "");
|
||||
apply(&mut doc, None).map(|_| ())
|
||||
};
|
||||
// The walk: the form that doesn't decode is the page's last entry.
|
||||
let content = [SECRET, &b"/Fm Do ".repeat(MAX - 1), b"/Fc Do"].concat();
|
||||
says_why(marked(one_page(&content, "/XObject << /Fm 7 0 R /Fc 8 0 R >>", vec![form(), stream(BAD, b"opaque")])));
|
||||
// The properties' cleanup, after the walk entered every form the page may.
|
||||
let content = [SECRET, &b"/Fm Do ".repeat(MAX), b"/Fbad Do"].concat();
|
||||
let resources = "/XObject << /Fm 7 0 R /Fbad 8 0 R >> /Properties << /P0 << >> >>";
|
||||
says_why(marked(one_page(&content, resources, vec![form(), stream(&BAD.replace("300 300", "10 10"), b"opaque")])));
|
||||
// The Type 3 cleanup's appearances.
|
||||
let with_type3 = |content: Vec<u8>| {
|
||||
pdf(vec![
|
||||
b"<< /Type /Catalog /Pages 2 0 R >>".to_vec(),
|
||||
b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_vec(),
|
||||
b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 300] /Contents 4 0 R /Resources << /Font << /F1 5 0 R /T3 9 0 R >> /XObject << /Fm 7 0 R >> >> /Annots [10 0 R] >>".to_vec(),
|
||||
stream("", &content),
|
||||
FONT.replace("95 0 R", "6 0 R").into_bytes(),
|
||||
widths(),
|
||||
form(),
|
||||
stream(BAD, b"opaque"),
|
||||
b"<< /Type /Font /Subtype /Type3 /FontBBox [0 0 1000 1000] /FontMatrix [0.001 0 0 0.001 0 0] /FirstChar 65 /LastChar 65 /Widths [500] /Encoding << /Differences [65 /A] >> /CharProcs << >> >>".to_vec(),
|
||||
b"<< /Type /Annot /Subtype /Square /Rect [0 0 10 10] /AP << /N 8 0 R >> >>".to_vec(),
|
||||
])
|
||||
};
|
||||
says_why(marked(with_type3([SECRET, &b"/Fm Do ".repeat(MAX)].concat())));
|
||||
let hidden = [b"BT /F1 10 Tf 3 Tr 20 60 Td (HIDDEN) Tj ET ".as_slice(), &b"/Fm Do ".repeat(MAX)].concat();
|
||||
says_why(remove_hidden(&mut with_type3(hidden), &[Hidden::HiddenText]).map(|_| ()));
|
||||
}
|
||||
@@ -245,13 +245,63 @@ fn the_form_a_kept_type3_glyph_draws_is_walked_within_the_allowance_of_a_page()
|
||||
mark(&mut doc, 0, &[[9.0, 95.0, 14.9, 110.0]], "");
|
||||
let out = apply(&mut doc, None);
|
||||
if refused {
|
||||
assert!(matches!(out, Err(RedactError::Cos(pdfcraft_cos::CosError::Filter(_)))), "forms of {size} bytes each: {out:?}");
|
||||
// The font's forms are cleaned for the document, not for one page.
|
||||
assert!(
|
||||
matches!(&out, Err(RedactError::Refused(reason)) if reason.starts_with("content and forms go past what one page may read")),
|
||||
"forms of {size} bytes each: {out:?}"
|
||||
);
|
||||
} else {
|
||||
assert_eq!(out.unwrap().glyphs, 1, "forms of {size} bytes each");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The kept glyph programs a Type 3 cleanup reads share one page's allowance: two compressed ones,
|
||||
/// each past half of it, refuse the redaction for the document, as the font's forms do, with a
|
||||
/// reason that names them. One that doesn't decode keeps its own error, and two small ones are
|
||||
/// the control.
|
||||
#[test]
|
||||
fn kept_type3_glyph_programs_past_the_allowance_of_a_page_refuse_the_document() {
|
||||
enum Then {
|
||||
PastTheAllowance,
|
||||
DoesNotDecode,
|
||||
Cleaned,
|
||||
}
|
||||
for (size, filter, then) in [
|
||||
(pdfcraft_cos::MAX_PAGE_DECODED / 2 + 1, "/FlateDecode", Then::PastTheAllowance),
|
||||
(1, "/UnsupportedForTheTest", Then::DoesNotDecode),
|
||||
(1, "/FlateDecode", Then::Cleaned),
|
||||
] {
|
||||
let packed = pdfcraft_filters::encode_flate(&vec![b' '; size]);
|
||||
let glyph = || stream(&format!("/Filter {filter}"), packed.as_slice());
|
||||
let mut doc = pdf(vec![
|
||||
b"<< /Type /Catalog /Pages 2 0 R >>".to_vec(),
|
||||
b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_vec(),
|
||||
b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 300] /Contents 4 0 R /Resources 5 0 R >>".to_vec(),
|
||||
stream("", b"BT /T3 10 Tf 10 100 Td (ABC) Tj ET"),
|
||||
b"<< /Font << /T3 6 0 R >> >>".to_vec(),
|
||||
b"<< /Type /Font /Subtype /Type3 /FontBBox [0 -200 1000 800] /FontMatrix [0.001 0 0 0.001 0 0] /FirstChar 65 /LastChar 67 /Widths [500 500 500] /Encoding << /Differences [65 /A /B /C] >> /CharProcs << /A 7 0 R /B 8 0 R /C 9 0 R >> /Resources << /XObject << /ImA 10 0 R >> >> >>".to_vec(),
|
||||
stream("", b"/ImA Do"),
|
||||
glyph(),
|
||||
glyph(),
|
||||
stream("/Type /XObject /Subtype /Image /Width 1 /Height 1 /ColorSpace /DeviceGray /BitsPerComponent 8", b"CONFIDENTIAL_IMAGE_A"),
|
||||
]);
|
||||
mark(&mut doc, 0, &[[9.0, 95.0, 14.9, 110.0]], "");
|
||||
let out = apply(&mut doc, None);
|
||||
match then {
|
||||
Then::PastTheAllowance => assert!(
|
||||
matches!(&out, Err(RedactError::Refused(reason)) if reason.starts_with("the glyph programs the document's Type 3 fonts keep go, together, past what one page may read")),
|
||||
"glyph programs of {size} bytes each: {out:?}"
|
||||
),
|
||||
Then::DoesNotDecode => assert!(
|
||||
matches!(&out, Err(RedactError::Cos(pdfcraft_cos::CosError::Filter(why))) if why.contains("UnsupportedForTheTest")),
|
||||
"glyph programs that don't decode: {out:?}"
|
||||
),
|
||||
Then::Cleaned => assert_eq!(out.unwrap().glyphs, 1, "glyph programs of {size} bytes each"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// When all glyphs of a Type 3 font are redacted, the entire font is removed from Resources (F-011).
|
||||
#[test]
|
||||
fn all_redacted_type3_glyphs_cause_font_removal_from_resources() {
|
||||
@@ -503,9 +553,14 @@ fn an_image_a_type3_glyph_with_parameters_by_reference_draws_is_kept() {
|
||||
assert!(full_save_holds(&doc, b"PUBLIC_IMG_B"), "glyph B still draws its image");
|
||||
}
|
||||
|
||||
/// Whether `out` is the redaction refused with a syntax error whose detail holds `detail`.
|
||||
fn refused_for(out: &Result<Report, RedactError>, detail: &str) -> bool {
|
||||
matches!(out, Err(RedactError::Cos(pdfcraft_cos::CosError::Syntax { detail: d, .. })) if d.contains(detail))
|
||||
/// Whether `out` is the redaction refused, of `page` (1-based) or, with `None`, of the document, for
|
||||
/// a reason that holds `reason`.
|
||||
fn refused_for(out: &Result<Report, RedactError>, page: Option<usize>, reason: &str) -> bool {
|
||||
match out {
|
||||
Err(RedactError::PageRefused { page: p, reason: r }) => page == Some(*p) && r.contains(reason),
|
||||
Err(RedactError::Refused(r)) => page.is_none() && r.contains(reason),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// The font's cleanup scans every page and form for the glyphs they show. A string left open in a
|
||||
@@ -527,7 +582,7 @@ fn unreadable_bytes_in_a_form_the_type3_cleanup_scans_refuse_the_redaction() {
|
||||
]);
|
||||
mark(&mut doc, 0, &[[9.0, 95.0, 16.0, 110.0]], "");
|
||||
let out = apply(&mut doc, None);
|
||||
assert!(refused_for(&out, "content stream syntax"), "{out:?}");
|
||||
assert!(refused_for(&out, Some(1), "content that may show a Type 3 font has bytes that can't be read"), "{out:?}");
|
||||
}
|
||||
|
||||
/// The font's cleanup reads the program of each glyph it keeps, for the resources it uses. A
|
||||
@@ -549,7 +604,32 @@ fn unreadable_bytes_in_a_kept_type3_glyph_program_refuse_the_redaction() {
|
||||
]);
|
||||
mark(&mut doc, 0, &[[9.0, 95.0, 16.0, 110.0]], "");
|
||||
let out = apply(&mut doc, None);
|
||||
assert!(refused_for(&out, "glyph stream syntax"), "{out:?}");
|
||||
assert!(refused_for(&out, None, "a Type 3 font's glyph has bytes that can't be read"), "{out:?}");
|
||||
assert_eq!(
|
||||
out.map(|_| ()).unwrap_err().to_string(),
|
||||
"the document can't be redacted safely: a Type 3 font's glyph has bytes that can't be read; the operation was refused"
|
||||
);
|
||||
}
|
||||
|
||||
/// The font's cleanup scans every page, marked or not: where a page's content can't be read, the
|
||||
/// refusal names that page, here the second, which no mark is on.
|
||||
#[test]
|
||||
fn unreadable_bytes_on_another_page_the_type3_cleanup_scans_refuse_that_page() {
|
||||
let mut doc = pdf(vec![
|
||||
b"<< /Type /Catalog /Pages 2 0 R >>".to_vec(),
|
||||
b"<< /Type /Pages /Kids [3 0 R 9 0 R] /Count 2 >>".to_vec(),
|
||||
b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 300] /Contents 4 0 R /Resources 5 0 R >>".to_vec(),
|
||||
stream("", b"BT /T3 10 Tf 10 100 Td (A) Tj ET"),
|
||||
b"<< /Font << /T3 6 0 R >> >>".to_vec(),
|
||||
TYPE3.as_bytes().to_vec(),
|
||||
stream("", b"% SECRET_TYPE3_GLYPH_A"),
|
||||
stream("", b"% PUBLIC_TYPE3_GLYPH_B"),
|
||||
b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 300] /Contents 10 0 R /Resources 5 0 R >>".to_vec(),
|
||||
stream("", b"BT /T3 10 Tf 10 20 Td ( (B) Tj ET"),
|
||||
]);
|
||||
mark(&mut doc, 0, &[[9.0, 95.0, 16.0, 110.0]], "");
|
||||
let out = apply(&mut doc, None);
|
||||
assert!(refused_for(&out, Some(2), "content that may show a Type 3 font has bytes that can't be read"), "{out:?}");
|
||||
}
|
||||
|
||||
/// A Form the surviving glyph draws holds `/Resources` as an array that references the removed
|
||||
@@ -739,7 +819,10 @@ fn a_page_s_appearances_share_one_decoded_byte_allowance() {
|
||||
]);
|
||||
mark(&mut doc, 0, &[[9.0, 95.0, 14.9, 110.0]], "");
|
||||
let refused = apply(&mut doc, None);
|
||||
assert!(refused.is_err(), "two appearances past the page's decoded-byte allowance together were read in full: {refused:?}");
|
||||
assert!(
|
||||
matches!(&refused, Err(RedactError::PageRefused { page: 1, reason }) if reason.starts_with("content and forms go past what one page may read")),
|
||||
"two appearances past the page's decoded-byte allowance together were read in full: {refused:?}"
|
||||
);
|
||||
}
|
||||
|
||||
/// The appearances are read within what the page's content left of the page's allowance, not
|
||||
|
||||
+55
-57
@@ -3,7 +3,7 @@
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
use pdfcraft_content::Pieces;
|
||||
use pdfcraft_cos::{CosError, DecodeBudget, Dict, Document, ObjRef, Object};
|
||||
use pdfcraft_cos::{DecodeBudget, Dict, Document, ObjRef, Object};
|
||||
|
||||
use crate::{RedactError, page_streams};
|
||||
|
||||
@@ -24,9 +24,9 @@ pub(crate) enum FontKey {
|
||||
|
||||
/// Build the mapping from character code (0..=255) to glyph name in a Type 3 font.
|
||||
/// Fails closed if the encoding cannot be safely resolved or parsed.
|
||||
pub(crate) fn type3_code_to_glyph(doc: &Document, font_dict: &Dict) -> Result<[Option<Vec<u8>>; 256], CosError> {
|
||||
pub(crate) fn type3_code_to_glyph(doc: &Document, font_dict: &Dict) -> Result<[Option<Vec<u8>>; 256], RedactError> {
|
||||
let Some(enc_obj) = font_dict.get(b"Encoding") else {
|
||||
return Err(CosError::Syntax { offset: 0, detail: "redaction could not establish safe Type 3 font cleanup: missing Encoding".into() });
|
||||
return Err(RedactError::Refused("a Type 3 font has no /Encoding".into()));
|
||||
};
|
||||
let resolved_enc = doc.resolve(enc_obj);
|
||||
|
||||
@@ -61,10 +61,7 @@ pub(crate) fn type3_code_to_glyph(doc: &Document, font_dict: &Dict) -> Result<[O
|
||||
base_name = Some(name.clone());
|
||||
}
|
||||
_ => {
|
||||
return Err(CosError::Syntax {
|
||||
offset: 0,
|
||||
detail: "redaction could not establish safe Type 3 font cleanup: invalid Encoding object".into(),
|
||||
});
|
||||
return Err(RedactError::Refused("a Type 3 font's /Encoding is neither a name nor a dictionary".into()));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -74,13 +71,10 @@ pub(crate) fn type3_code_to_glyph(doc: &Document, font_dict: &Dict) -> Result<[O
|
||||
Some(b"MacRomanEncoding") => Some(&crate::type3_tables::MAC_ROMAN),
|
||||
Some(b"MacExpertEncoding") => Some(&crate::type3_tables::MAC_EXPERT),
|
||||
Some(other) => {
|
||||
return Err(CosError::Syntax {
|
||||
offset: 0,
|
||||
detail: format!(
|
||||
"redaction could not establish safe Type 3 font cleanup: unsupported BaseEncoding: {}",
|
||||
String::from_utf8_lossy(other)
|
||||
),
|
||||
});
|
||||
return Err(RedactError::Refused(format!(
|
||||
"a Type 3 font's base encoding /{} isn't one whose glyph names are known",
|
||||
String::from_utf8_lossy(other)
|
||||
)));
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
@@ -149,13 +143,13 @@ struct GlyphReads {
|
||||
budget: DecodeBudget,
|
||||
}
|
||||
|
||||
fn collect_used_resources_in_stream(data: &[u8], used: &mut UsedInGlyphs) -> Result<(), CosError> {
|
||||
fn collect_used_resources_in_stream(data: &[u8], used: &mut UsedInGlyphs) -> Result<(), RedactError> {
|
||||
// One operator at a time, so a glyph program of millions of them is never held whole. A byte
|
||||
// that can't be read anywhere in it still refuses, once the loop has read it all.
|
||||
let mut read = pdfcraft_content::ops(data);
|
||||
read.by_ref().for_each(|op| record_used(&op, used));
|
||||
if read.skipped() > 0 {
|
||||
return Err(CosError::Syntax { offset: 0, detail: "redaction could not fully inspect glyph stream syntax".into() });
|
||||
return Err(RedactError::Refused("a Type 3 font's glyph has bytes that can't be read".into()));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -209,7 +203,7 @@ fn record_used(op: &pdfcraft_content::Op, used: &mut UsedInGlyphs) {
|
||||
/// surviving glyph draws may name, unused, an image only a removed glyph drew; that entry would
|
||||
/// keep the image in the file. Pruning only unused entries is safe for a shared Form: no drawer
|
||||
/// of it can use a name its content doesn't. Fails closed when a Form can't be read.
|
||||
fn prune_font_forms(doc: &mut Document, font_res: &Dict) -> Result<(), CosError> {
|
||||
fn prune_font_forms(doc: &mut Document, font_res: &Dict) -> Result<(), RedactError> {
|
||||
let mut pending: Vec<(ObjRef, usize)> = res_dict(doc, font_res, b"XObject").iter().filter_map(|(_, v)| v.as_ref()).map(|r| (r, 0)).collect();
|
||||
let mut seen = HashSet::new();
|
||||
while let Some((form_ref, depth)) = pending.pop() {
|
||||
@@ -217,7 +211,7 @@ fn prune_font_forms(doc: &mut Document, font_res: &Dict) -> Result<(), CosError>
|
||||
continue;
|
||||
}
|
||||
if depth > MAX_DEPTH || seen.len() > MAX_HOLDERS {
|
||||
return Err(CosError::Syntax { offset: 0, detail: "redaction could not establish safe Type 3 font cleanup: forms nest too deep".into() });
|
||||
return Err(RedactError::Refused("the forms a Type 3 font's resources draw nest deeper, or are more, than can be followed".into()));
|
||||
}
|
||||
let Object::Stream(form) = &*doc.get(form_ref) else { continue };
|
||||
if form.dict.name(b"Subtype") != Some(b"Form") {
|
||||
@@ -232,10 +226,7 @@ fn prune_font_forms(doc: &mut Document, font_res: &Dict) -> Result<(), CosError>
|
||||
Some(r) => match r.as_dict() {
|
||||
Some(d) => d.clone(),
|
||||
None => {
|
||||
return Err(CosError::Syntax {
|
||||
offset: 0,
|
||||
detail: "redaction could not establish safe Type 3 font cleanup: a form's /Resources is not a dictionary".into(),
|
||||
});
|
||||
return Err(RedactError::Refused("a form a Type 3 font's resources draw has /Resources that isn't a dictionary".into()));
|
||||
}
|
||||
},
|
||||
};
|
||||
@@ -307,9 +298,11 @@ fn scan_content_stream(
|
||||
res: &Dict,
|
||||
initial_font: Option<FontKey>,
|
||||
depth: usize,
|
||||
) -> Result<(), CosError> {
|
||||
) -> Result<(), RedactError> {
|
||||
if depth > MAX_DEPTH {
|
||||
return Err(CosError::Syntax { offset: 0, detail: "redaction exceeded max depth inspecting Type 3 font content".into() });
|
||||
return Err(RedactError::Refused(
|
||||
"content that may show a Type 3 font nests forms, patterns or soft masks deeper than can be followed".into(),
|
||||
));
|
||||
}
|
||||
let joined = Pieces::join(content);
|
||||
// One operator at a time, so content of millions of them is never held whole. The scan only
|
||||
@@ -347,7 +340,7 @@ fn scan_content_stream(
|
||||
}
|
||||
}
|
||||
if read.skipped() > 0 {
|
||||
return Err(CosError::Syntax { offset: 0, detail: "redaction could not fully inspect content stream syntax".into() });
|
||||
return Err(RedactError::Refused("content that may show a Type 3 font has bytes that can't be read".into()));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -405,7 +398,7 @@ fn scan_xobject(
|
||||
name: &[u8],
|
||||
current_font: Option<FontKey>,
|
||||
depth: usize,
|
||||
) -> Result<(), CosError> {
|
||||
) -> Result<(), RedactError> {
|
||||
let xo = res_dict(ctx.doc, res, b"XObject");
|
||||
let Some(r) = xo.get(name).and_then(Object::as_ref) else { return Ok(()) };
|
||||
if !matches!(&*ctx.doc.get(r), Object::Stream(s) if s.dict.name(b"Subtype") == Some(b"Form")) {
|
||||
@@ -417,7 +410,7 @@ fn scan_xobject(
|
||||
/// Scan the tiling pattern `name` that an `scn` or `SCN` operator selects. Its cell is content of
|
||||
/// its own and can show glyphs of a font the page lists too. A shading pattern is not a stream and
|
||||
/// draws no text.
|
||||
fn scan_pattern(ctx: &mut ScanContext<'_>, res: &Dict, holder_ref: ObjRef, name: &[u8], depth: usize) -> Result<(), CosError> {
|
||||
fn scan_pattern(ctx: &mut ScanContext<'_>, res: &Dict, holder_ref: ObjRef, name: &[u8], depth: usize) -> Result<(), RedactError> {
|
||||
let patterns = res_dict(ctx.doc, res, b"Pattern");
|
||||
let Some(r) = patterns.get(name).and_then(Object::as_ref) else { return Ok(()) };
|
||||
scan_stream_object(ctx, res, holder_ref, r, None, depth)
|
||||
@@ -425,7 +418,7 @@ fn scan_pattern(ctx: &mut ScanContext<'_>, res: &Dict, holder_ref: ObjRef, name:
|
||||
|
||||
/// Scan the transparency group of the soft mask that the ExtGState `name` sets: what it shows
|
||||
/// shapes the page, so its glyphs are in use.
|
||||
fn scan_soft_mask(ctx: &mut ScanContext<'_>, res: &Dict, holder_ref: ObjRef, name: &[u8], depth: usize) -> Result<(), CosError> {
|
||||
fn scan_soft_mask(ctx: &mut ScanContext<'_>, res: &Dict, holder_ref: ObjRef, name: &[u8], depth: usize) -> Result<(), RedactError> {
|
||||
let states = res_dict(ctx.doc, res, b"ExtGState");
|
||||
let Some(state) = states.get(name).and_then(|s| ctx.doc.resolve(s).as_dict().cloned()) else { return Ok(()) };
|
||||
let Some(mask) = state.get(b"SMask").and_then(|m| ctx.doc.resolve(m).as_dict().cloned()) else { return Ok(()) };
|
||||
@@ -436,7 +429,7 @@ fn scan_soft_mask(ctx: &mut ScanContext<'_>, res: &Dict, holder_ref: ObjRef, nam
|
||||
/// Scan the appearance streams of a page's annotations. A comment, stamp or field can show glyphs
|
||||
/// of a Type 3 font that the page lists too. An appearance without resources of its own draws
|
||||
/// through the page's.
|
||||
fn scan_appearances(ctx: &mut ScanContext<'_>, page: &Dict, page_ref: ObjRef, page_res: &Dict) -> Result<(), CosError> {
|
||||
fn scan_appearances(ctx: &mut ScanContext<'_>, page: &Dict, page_ref: ObjRef, page_res: &Dict) -> Result<(), RedactError> {
|
||||
for annot in crate::annots_of(ctx.doc, page) {
|
||||
for r in appearance_streams(ctx.doc, &annot) {
|
||||
scan_stream_object(ctx, page_res, page_ref, r, None, 0)?;
|
||||
@@ -488,7 +481,7 @@ fn resourceless_appearances(doc: &Document, page: &Dict) -> Vec<ObjRef> {
|
||||
/// already. Tiling patterns are not read here: a tiling pattern must have resources of its own,
|
||||
/// so its cell draws through them, and Apply Redactions refuses one without them
|
||||
/// (`pattern_guard`).
|
||||
fn add_soft_mask_ops(doc: &Document, res: &Dict, ops: &mut Vec<pdfcraft_content::Op>, known: usize) -> Result<(), CosError> {
|
||||
fn add_soft_mask_ops(doc: &Document, res: &Dict, ops: &mut Vec<pdfcraft_content::Op>, known: usize) -> Result<(), RedactError> {
|
||||
let xobjects = res_dict(doc, res, b"XObject");
|
||||
let states = res_dict(doc, res, b"ExtGState");
|
||||
let mut seen = HashSet::new();
|
||||
@@ -519,7 +512,9 @@ fn add_soft_mask_ops(doc: &Document, res: &Dict, ops: &mut Vec<pdfcraft_content:
|
||||
}
|
||||
let parsed = pdfcraft_content::parse(&doc.with_direct_parms(s).decoded()?);
|
||||
if parsed.skipped > 0 || ops.len().saturating_add(parsed.ops.len()) > 2_000_000 {
|
||||
return Err(CosError::Syntax { offset: 0, detail: "redaction could not fully inspect soft mask content".into() });
|
||||
return Err(RedactError::Refused(
|
||||
"a soft mask or form without resources of its own has bytes that can't be read, or takes what draws with those resources past 2,000,000 operators".into(),
|
||||
));
|
||||
}
|
||||
ops.extend(parsed.ops);
|
||||
}
|
||||
@@ -536,7 +531,7 @@ fn scan_stream_object(
|
||||
r: ObjRef,
|
||||
current_font: Option<FontKey>,
|
||||
depth: usize,
|
||||
) -> Result<(), CosError> {
|
||||
) -> Result<(), RedactError> {
|
||||
let obj = ctx.doc.get(r);
|
||||
let Object::Stream(s) = &*obj else { return Ok(()) };
|
||||
let own_res = s.dict.get(b"Resources").and_then(|ro| ctx.doc.resolve(ro).as_dict().cloned());
|
||||
@@ -577,7 +572,7 @@ pub(crate) fn prune_type3_from_resources(
|
||||
res: &mut Dict,
|
||||
content: &[Vec<u8>],
|
||||
page: Option<&Dict>,
|
||||
) -> Result<(), CosError> {
|
||||
) -> Result<(), RedactError> {
|
||||
let mut fonts = res_dict(doc, res, b"Font");
|
||||
if fonts.is_empty() {
|
||||
return Ok(());
|
||||
@@ -605,10 +600,16 @@ pub(crate) fn prune_type3_from_resources(
|
||||
// only in its turn, so they are never all held at once.
|
||||
for r in resourceless_appearances(doc, page) {
|
||||
let Object::Stream(s) = &*doc.get(r) else { continue };
|
||||
let data = budget.decode(&doc.with_direct_parms(s))?;
|
||||
// Past what the page may read where the budget refused it, as in `resource_ops`.
|
||||
let refused = budget.refused();
|
||||
let data = budget
|
||||
.decode(&doc.with_direct_parms(s))
|
||||
.map_err(|e| if budget.refused() > refused { RedactError::past_allowance(e) } else { e.into() })?;
|
||||
let more = crate::interp::resource_ops(doc, budget, res, std::slice::from_ref(&data))?;
|
||||
if ops.len().saturating_add(more.len()) > 2_000_000 {
|
||||
return Err(CosError::Syntax { offset: 0, detail: "redaction could not fully inspect annotation appearances".into() });
|
||||
return Err(RedactError::Refused(
|
||||
"the page's annotation appearances take what draws with its resources past 2,000,000 operators".into(),
|
||||
));
|
||||
}
|
||||
ops.extend(more);
|
||||
}
|
||||
@@ -736,8 +737,9 @@ pub(crate) fn unlink_type3(doc: &mut Document) -> Result<(), RedactError> {
|
||||
})
|
||||
.unwrap_or_default();
|
||||
|
||||
scan_content_stream(&mut ctx, &content, p.obj, &page_res, None, 0)?;
|
||||
scan_appearances(&mut ctx, &p.dict, p.obj, &page_res)?;
|
||||
scan_content_stream(&mut ctx, &content, p.obj, &page_res, None, 0)
|
||||
.and_then(|()| scan_appearances(&mut ctx, &p.dict, p.obj, &page_res))
|
||||
.map_err(|e| e.on_page(pi + 1))?;
|
||||
}
|
||||
|
||||
// Also scan any surviving form that wasn't reached by page streams directly.
|
||||
@@ -761,7 +763,7 @@ pub(crate) fn unlink_type3(doc: &mut Document) -> Result<(), RedactError> {
|
||||
|
||||
/// Every reachable Form XObject with resources of its own, with those resources, found by
|
||||
/// walking the resources of the holders and of the forms they draw.
|
||||
fn reachable_form_holders(doc: &Document, holders: &[(ObjRef, Vec<ObjRef>)]) -> Result<Vec<(ObjRef, Dict)>, CosError> {
|
||||
fn reachable_form_holders(doc: &Document, holders: &[(ObjRef, Vec<ObjRef>)]) -> Result<Vec<(ObjRef, Dict)>, RedactError> {
|
||||
let mut form_holders: Vec<(ObjRef, Dict)> = Vec::new();
|
||||
let mut pending_res: Vec<Dict> = holders
|
||||
.iter()
|
||||
@@ -775,7 +777,7 @@ fn reachable_form_holders(doc: &Document, holders: &[(ObjRef, Vec<ObjRef>)]) ->
|
||||
continue;
|
||||
}
|
||||
if seen_forms.len() > MAX_HOLDERS {
|
||||
return Err(CosError::Syntax { offset: 0, detail: "redaction exceeded max depth inspecting form resources".into() });
|
||||
return Err(RedactError::Refused("the forms the document's resources draw are more than can be followed".into()));
|
||||
}
|
||||
let object = doc.get(reference);
|
||||
let Object::Stream(form) = &*object else { continue };
|
||||
@@ -794,12 +796,9 @@ fn reachable_form_holders(doc: &Document, holders: &[(ObjRef, Vec<ObjRef>)]) ->
|
||||
/// Record every Type 3 font named by a resource dictionary's `/Font` and `/ExtGState` entries.
|
||||
/// A Type 3 font held directly in a resource dictionary can neither be named reliably nor have its
|
||||
/// glyph programs rewritten, so redaction fails closed rather than leaving its glyphs unchecked.
|
||||
fn collect_type3_fonts(doc: &Document, res: &Dict, t3_fonts: &mut HashMap<FontKey, Dict>) -> Result<(), CosError> {
|
||||
let direct = || CosError::Syntax {
|
||||
offset: 0,
|
||||
detail: "redaction could not establish safe Type 3 font cleanup: a Type 3 font is not an indirect object".into(),
|
||||
};
|
||||
let mut consider = |font_obj: &Object| -> Result<(), CosError> {
|
||||
fn collect_type3_fonts(doc: &Document, res: &Dict, t3_fonts: &mut HashMap<FontKey, Dict>) -> Result<(), RedactError> {
|
||||
let direct = || RedactError::Refused("a Type 3 font is written inside a resource dictionary, not as an object of its own".into());
|
||||
let mut consider = |font_obj: &Object| -> Result<(), RedactError> {
|
||||
if let Some(dict) = doc.resolve(font_obj).as_dict().cloned()
|
||||
&& dict.name(b"Subtype") == Some(b"Type3")
|
||||
{
|
||||
@@ -831,12 +830,10 @@ fn clean_type3_font(
|
||||
reads: &mut GlyphReads,
|
||||
) -> Result<(), RedactError> {
|
||||
let Some(char_procs_val) = font_dict.get(b"CharProcs") else {
|
||||
return Err(CosError::Syntax { offset: 0, detail: "redaction could not establish safe Type 3 font cleanup: missing CharProcs".into() }.into());
|
||||
return Err(RedactError::Refused("a Type 3 font has no /CharProcs".into()));
|
||||
};
|
||||
let mut char_procs = doc.resolve(char_procs_val).as_dict().cloned().ok_or_else(|| CosError::Syntax {
|
||||
offset: 0,
|
||||
detail: "redaction could not establish safe Type 3 font cleanup: CharProcs is not a dict".into(),
|
||||
})?;
|
||||
let mut char_procs =
|
||||
doc.resolve(char_procs_val).as_dict().cloned().ok_or_else(|| RedactError::Refused("a Type 3 font's /CharProcs isn't a dictionary".into()))?;
|
||||
|
||||
let mut procs_changed = false;
|
||||
let glyph_names: Vec<Vec<u8>> = char_procs.iter().map(|(n, _)| n.to_vec()).collect();
|
||||
@@ -878,14 +875,15 @@ fn clean_type3_font(
|
||||
}
|
||||
let resolved = doc.resolve(proc_val);
|
||||
let Object::Stream(s) = &*resolved else {
|
||||
return Err(CosError::Syntax {
|
||||
offset: 0,
|
||||
detail: "redaction could not establish safe Type 3 font cleanup: CharProc is not a stream".into(),
|
||||
}
|
||||
.into());
|
||||
return Err(RedactError::Refused("a Type 3 font's glyph isn't a stream".into()));
|
||||
};
|
||||
// Past the allowance the cleanup can't be shown complete, and the redaction is refused.
|
||||
let data = reads.budget.decode(&doc.with_direct_parms(s))?;
|
||||
// Past the allowance the cleanup can't be shown complete, and the redaction is refused, as
|
||||
// in `resource_ops`; a glyph that doesn't decode says why.
|
||||
let refused = reads.budget.refused();
|
||||
let data = reads
|
||||
.budget
|
||||
.decode(&doc.with_direct_parms(s))
|
||||
.map_err(|e| if reads.budget.refused() > refused { RedactError::past_glyph_allowance(e) } else { e.into() })?;
|
||||
let mut used = UsedInGlyphs::default();
|
||||
collect_used_resources_in_stream(&data, &mut used)?;
|
||||
used_in_glyphs.merge(&used);
|
||||
|
||||
@@ -171,8 +171,9 @@ impl<'a> Inspector<'a> {
|
||||
}
|
||||
|
||||
/// Reads what `info` holds beyond the page list: encryption, document information, tagging,
|
||||
/// page labels, bookmarks, annotations, transitions, form fields, layers, fonts, attachments
|
||||
/// (and, for a PDF portfolio, how it presents them), JavaScript and the opening destination.
|
||||
/// page labels, bookmarks, annotations, transitions, form fields, XFA kind (dynamic when it
|
||||
/// must be laid out from its template, else static), layers, fonts, attachments (and, for a
|
||||
/// PDF portfolio, how it presents them), JavaScript and the opening destination.
|
||||
pub(super) fn fill(&self, info: &mut DocInfo) {
|
||||
// lopdf drops /Encrypt from the trailer once it has decrypted the file.
|
||||
info.encrypted = self.doc.encrypted();
|
||||
@@ -260,8 +261,24 @@ impl<'a> Inspector<'a> {
|
||||
// A form with no fields is taken to be laid out from its template, unless its
|
||||
// configuration says it is a static form (#3180): Designer writes
|
||||
// `<dynamicRender>forbidden</dynamicRender>` for one, whose pages are the form.
|
||||
let static_form = self.xfa_dynamic_render(xfa).as_deref() == Some("forbidden");
|
||||
info.xfa = Some(if needs_rendering || (info.fields.is_empty() && !static_form) { Xfa::Dynamic } else { Xfa::Static });
|
||||
let render = self.xfa_dynamic_render(xfa);
|
||||
let static_form = render.as_deref() == Some("forbidden");
|
||||
// A form a viewer saved with its pages drawn, whose configuration says it must be
|
||||
// rendered dynamically, is laid out from its template too: its fields live there.
|
||||
// Not once it is signed: the signature covers the pages as saved (the xfa crate's
|
||||
// `is_dynamic` keeps the same rule).
|
||||
let signed = self.signed_form(catalog);
|
||||
let required = render.as_deref() == Some("required") && !signed;
|
||||
// Whether the AcroForm lists any field, as the xfa crate's `has_fields` reads it, so
|
||||
// both call the same forms dynamic: fields nested too deep to read through count.
|
||||
let listed = catalog
|
||||
.get(b"AcroForm")
|
||||
.ok()
|
||||
.and_then(|o| self.dict(o))
|
||||
.and_then(|f| f.get(b"Fields").ok())
|
||||
.and_then(|f| self.resolve(f).as_array().ok())
|
||||
.is_some_and(|a| !a.is_empty());
|
||||
info.xfa = Some(if needs_rendering || required || (!listed && !static_form) { Xfa::Dynamic } else { Xfa::Static });
|
||||
}
|
||||
self.layers(catalog, &mut info.layers);
|
||||
info.layer_groups = self.layer_groups(catalog);
|
||||
@@ -288,6 +305,40 @@ impl<'a> Inspector<'a> {
|
||||
info.open_dest = catalog.get(b"OpenAction").ok().and_then(|o| self.open_dest(o));
|
||||
}
|
||||
|
||||
/// Whether the form holds a signature field with a value, read as the xfa crate's
|
||||
/// `has_signature` reads it so that both say the same of a form: down the field tree from the
|
||||
/// AcroForm's `/Fields`, the field type inherited from the parent, and a tree deeper than 32
|
||||
/// fields or larger than 10,000 taken as signed. A form too big to read through is then left
|
||||
/// as saved rather than laid out again over a signature.
|
||||
pub(super) fn signed_form(&self, catalog: &'a Dictionary) -> bool {
|
||||
let Some(acro) = catalog.get(b"AcroForm").ok().and_then(|o| self.dict(o)) else { return false };
|
||||
let Some(fields) = acro.get(b"Fields").ok().and_then(|f| self.resolve(f).as_array().ok()) else { return false };
|
||||
// (field, signature type inherited, depth)
|
||||
let mut todo: Vec<(&Object, bool, usize)> = fields.iter().map(|f| (f, false, 0)).collect();
|
||||
let mut seen = HashSet::new();
|
||||
let mut budget = 10_000usize;
|
||||
while let Some((f, sig_above, depth)) = todo.pop() {
|
||||
if budget == 0 || depth > 32 {
|
||||
return true;
|
||||
}
|
||||
if let Some(id) = self.resolved_id(f)
|
||||
&& !seen.insert(id)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
budget -= 1;
|
||||
let Some(d) = self.dict(f) else { continue };
|
||||
let sig = d.get(b"FT").ok().and_then(|t| self.resolve(t).as_name().ok()).map_or(sig_above, |t| t == b"Sig");
|
||||
if sig && d.get(b"V").ok().is_some_and(|v| !matches!(self.resolve(v), Object::Null)) {
|
||||
return true;
|
||||
}
|
||||
if let Some(kids) = d.get(b"Kids").ok().and_then(|k| self.resolve(k).as_array().ok()) {
|
||||
todo.extend(kids.iter().map(|k| (k, sig, depth + 1)));
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// A portfolio's collection dictionary (Table 153). `/D` names the initial document's key in
|
||||
/// the `/EmbeddedFiles` name tree, decoded as the keys are.
|
||||
fn portfolio(&self, collection: &Dictionary, attachments: &[Attachment]) -> Portfolio {
|
||||
|
||||
@@ -105,6 +105,15 @@ fn is_complex(c: char) -> bool {
|
||||
matches!(c as u32, 0x0300..=0x036F | 0x0900..=0x0DFF | 0x0E00..=0x0EFF | 0x1000..=0x109F | 0x1780..=0x17FF)
|
||||
}
|
||||
|
||||
/// Hangul, which [`is_cjk`] counts as CJK: syllables, the two jamo blocks, the compatibility
|
||||
/// jamo and the halfwidth jamo. Korean is written with spaces between its words (띄어쓰기), unlike Chinese and Japanese,
|
||||
/// so a gap between two Korean syllables may be a word gap and is read as one from half a line
|
||||
/// height upwards -- a document that writes its spaces as position rather than as space
|
||||
/// characters would otherwise lose them (#3722 review).
|
||||
fn is_hangul(c: char) -> bool {
|
||||
matches!(c as u32, 0x1100..=0x11FF | 0x3130..=0x318F | 0xA960..=0xA97F | 0xAC00..=0xD7AF | 0xFFA0..=0xFFDC)
|
||||
}
|
||||
|
||||
/// Whether `text` is only combining marks (Unicode Mn and Me, which take bidi class NSM) of a
|
||||
/// left-to-right script: Thai tone marks and above or below vowels, Indic signs such as virama,
|
||||
/// Latin combining accents. Right-to-left marks are ordered with their script by [`reverse_rtl`].
|
||||
@@ -200,27 +209,127 @@ pub fn layout(glyphs: Vec<TextGlyph>) -> PageText {
|
||||
PageText { glyphs, line_of, space_before, truncated: false }
|
||||
}
|
||||
|
||||
/// [`layout`] as the reading order of indices into `glyphs`, with each one's line and word gap.
|
||||
fn arrange(glyphs: &[TextGlyph]) -> (Vec<usize>, Vec<u32>, Vec<bool>) {
|
||||
/// The word-gap threshold between neighbouring glyphs `p` and `c` on a line whose threshold is `threshold`: it follows
|
||||
/// the smaller of the two, not the tallest glyph of the line (#3172). A sub- or superscript keeps the line's threshold,
|
||||
/// since its smaller height says nothing about the gap next to its host.
|
||||
fn pair_threshold(p: &TextGlyph, c: &TextGlyph, typical: f32, threshold: f32) -> f32 {
|
||||
let height = |g: &TextGlyph| (g.rect[3] - g.rect[1]).max(0.1);
|
||||
let (hp, hc) = (height(p), height(c));
|
||||
// A glyph under the script test's size floor (a small `²`) is still a script when it sits off its neighbour's
|
||||
// baseline inside its line, unlike body text beside a big digit, which shares the digit's baseline.
|
||||
let off_baseline = |host: &[f32; 4], host_h: f32, s: &[f32; 4], s_h: f32| {
|
||||
s_h < host_h * 0.45 && (host[3] - s[3]).abs() >= host_h * 0.15 && s[3] > host[1] && s[1] < host[3]
|
||||
};
|
||||
if is_script_on(&p.rect, hp, &c.rect, hc)
|
||||
|| is_script_on(&c.rect, hc, &p.rect, hp)
|
||||
|| off_baseline(&p.rect, hp, &c.rect, hc)
|
||||
|| off_baseline(&c.rect, hc, &p.rect, hp)
|
||||
{
|
||||
return threshold;
|
||||
}
|
||||
let h = hp.min(hc);
|
||||
(typical + h * WORD_GAP).max(h * WORD_GAP).min(threshold)
|
||||
}
|
||||
|
||||
/// How many grid cells around a glyph the far redraw check looks at in each direction, however large the glyph is next to
|
||||
/// the page's median glyph.
|
||||
const MAX_REDRAW_REACH: i32 = 8;
|
||||
|
||||
/// A 64-bit FNV-1a hash of one glyph text.
|
||||
fn text_hash(text: &str) -> u64 {
|
||||
text.bytes().fold(0xcbf2_9ce4_8422_2325, |h, b| (h ^ u64::from(b)).wrapping_mul(0x0000_0100_0000_01b3))
|
||||
}
|
||||
|
||||
/// Marks glyphs retained after the bounded near and far redraw checks.
|
||||
fn glyphs_without_redraws(glyphs: &[TextGlyph]) -> Vec<bool> {
|
||||
// Drop "fake bold" duplicates: the same character redrawn at (almost) the same place. A redraw
|
||||
// also overlaps most of its own width: a narrow letter in condensed text (80 Tz and below) sits
|
||||
// closer than a fifth of its height to its double, as the second "l" of "Alle" (#1467), and
|
||||
// OCR layers squeeze words to 20 Tz and below (#2457). Only a zero-width mark, which has no
|
||||
// width to overlap, is matched by its height alone.
|
||||
//
|
||||
// The twin is usually among the last few glyphs. A page drawn once per column clip also redraws the glyph on the clip
|
||||
// edge thousands of glyphs later: the last glyph of one run is the first of another (#3173). So a glyph that starts a
|
||||
// run is also checked against the kept glyphs of its text in the grid cells around it, if one of them ends a run. A
|
||||
// glyph inside a run stays for the redraw check on whole runs below, which keeps a run that only starts like an
|
||||
// earlier one. The grid has one cell size for the whole page (a fifth of the median glyph height), so equal places
|
||||
// land in equal cells whatever the glyph sizes. `older[k]` links each kept glyph to the previous one with the same
|
||||
// key, so the earlier candidates are checked newest first, up to `REDRAW_CANDIDATES`, as the runs are below.
|
||||
let mut keep = vec![true; glyphs.len()];
|
||||
for i in 1..glyphs.len() {
|
||||
// `q` continues the run of `p` as `arrange` joins glyphs into a segment: a sub- or superscript right next to
|
||||
// its glyph may sit off the line by up to half the taller one's height.
|
||||
let follows = |p: usize, q: usize| {
|
||||
let (a, b) = (&glyphs[p].rect, &glyphs[q].rect);
|
||||
let (ha, hb) = ((a[3] - a[1]).max(0.1), (b[3] - b[1]).max(0.1));
|
||||
let ph = ha.min(hb);
|
||||
let gap = b[0] - a[2];
|
||||
let centre_limit = if gap.abs() < ph { ha.max(hb) * 0.5 } else { ph * 0.5 };
|
||||
((a[1] + a[3]) / 2.0 - (b[1] + b[3]) / 2.0).abs() < centre_limit && gap < ph * 3.0 && b[0] > a[0] - ph * 2.0
|
||||
};
|
||||
let mut heights: Vec<f32> = glyphs.iter().map(|g| (g.rect[3] - g.rect[1]).max(0.1)).collect();
|
||||
let cell = match heights.len() {
|
||||
0 => 0.02,
|
||||
n => 0.2 * *heights.select_nth_unstable_by(n / 2, f32::total_cmp).1,
|
||||
};
|
||||
let mut latest: HashMap<(u64, i32, i32), usize> = HashMap::new();
|
||||
let mut older = vec![NONE; glyphs.len()];
|
||||
// `next_kept[j]`: the kept glyph after kept glyph `j`, recorded when it is kept, so a dropped
|
||||
// fake-bold copy does not count and no lookup rescans the dropped glyphs in between.
|
||||
let mut next_kept = vec![NONE; glyphs.len()];
|
||||
let mut prev_kept: Option<usize> = None;
|
||||
for i in 0..glyphs.len() {
|
||||
let g = &glyphs[i];
|
||||
let h = (g.rect[3] - g.rect[1]).max(0.1);
|
||||
let w = g.rect[2] - g.rect[0];
|
||||
let dx = if w > 0.0 { (h * 0.2).min(w * 0.5) } else { h * 0.2 };
|
||||
for j in (i.saturating_sub(4)..i).rev() {
|
||||
let same = |j: usize| {
|
||||
let p = &glyphs[j];
|
||||
if keep[j] && p.text == g.text && (p.rect[0] - g.rect[0]).abs() < dx && (p.rect[1] - g.rect[1]).abs() < h * 0.2 {
|
||||
keep[i] = false;
|
||||
break;
|
||||
keep[j] && p.text == g.text && (p.rect[0] - g.rect[0]).abs() < dx && (p.rect[1] - g.rect[1]).abs() < h * 0.2
|
||||
};
|
||||
// The last kept glyph is checked too: copies of it drawn more than four times in a row
|
||||
// are all past the window, and the far check is skipped for a glyph that follows it.
|
||||
let near = (i.saturating_sub(4)..i).rev().any(&same) || prev_kept.is_some_and(&same);
|
||||
let (fp, cx, cy_) = (text_hash(&g.text), (g.rect[0] / cell).floor() as i32, (g.rect[1] / cell).floor() as i32);
|
||||
// The glyph after a kept one is the next kept glyph (or this one, while it has none).
|
||||
let next_of = |j: usize| next_kept.get(j).copied().filter(|&k| k != NONE).unwrap_or(i);
|
||||
let mut far = false;
|
||||
if prev_kept.is_none_or(|p| !follows(p, i)) {
|
||||
// `same` takes a horizontal offset below `dx` and a vertical one below a fifth of the height.
|
||||
let reach = ((dx.max(h * 0.2) / cell).ceil() as i32).clamp(1, MAX_REDRAW_REACH);
|
||||
let mut checks = REDRAW_CANDIDATES;
|
||||
'cells: for ox in -reach..=reach {
|
||||
for oy in -reach..=reach {
|
||||
let mut link = latest.get(&(fp, cx.saturating_add(ox), cy_.saturating_add(oy))).copied();
|
||||
while let Some(j) = link {
|
||||
if checks == 0 {
|
||||
break 'cells;
|
||||
}
|
||||
checks -= 1;
|
||||
if same(j) && !follows(j, next_of(j)) {
|
||||
far = true;
|
||||
break 'cells;
|
||||
}
|
||||
link = older.get(j).copied().filter(|&o| o != NONE);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if near || far {
|
||||
keep[i] = false;
|
||||
} else {
|
||||
older[i] = latest.insert((fp, cx, cy_), i).unwrap_or(NONE);
|
||||
if let Some(slot) = prev_kept.and_then(|p| next_kept.get_mut(p)) {
|
||||
*slot = i;
|
||||
}
|
||||
prev_kept = Some(i);
|
||||
}
|
||||
}
|
||||
keep
|
||||
}
|
||||
|
||||
/// [`layout`] as the reading order of indices into `glyphs`, with each one's line and word gap.
|
||||
fn arrange(glyphs: &[TextGlyph]) -> (Vec<usize>, Vec<u32>, Vec<bool>) {
|
||||
let keep = glyphs_without_redraws(glyphs);
|
||||
let kept: Vec<usize> = (0..glyphs.len()).filter(|i| keep[*i]).collect();
|
||||
let glyphs: Vec<&TextGlyph> = kept.iter().map(|i| &glyphs[*i]).collect();
|
||||
let n = glyphs.len();
|
||||
@@ -516,8 +625,32 @@ fn arrange(glyphs: &[TextGlyph]) -> (Vec<usize>, Vec<u32>, Vec<bool>) {
|
||||
for (w, pair) in sc.placed.windows(2).enumerate() {
|
||||
let &[p, c] = pair else { continue };
|
||||
let Some(&Some(gap)) = sc.cluster_gap.get(w + 1) else { continue };
|
||||
// A combining mark is measured by its cluster's base, as its text is: its own small box would lower the
|
||||
// threshold next to it.
|
||||
let base = |i: usize| glyphs.get(sc.anchor.get(i).copied().unwrap_or(i)).copied().unwrap_or(glyphs[i]);
|
||||
let pair_threshold = pair_threshold(base(p), base(c), typical, threshold);
|
||||
let (pt, ct) = (cluster_text(p), cluster_text(c));
|
||||
let cjk = pt.chars().any(is_cjk) && ct.chars().any(is_cjk) && gap < h * 0.5;
|
||||
// Character spacing is added after every glyph of a show (`Tc`, ISO 32000-2 §9.3.2), so text spread to a
|
||||
// wider column -- a Chinese label on a form, 分散對齊 -- repeats one gap, while the gap between two cells
|
||||
// of a row stands on its own. A repeated gap is therefore spacing at any width. Chinese and Japanese
|
||||
// write no spaces between these characters, so a space inferred inside a label changes what Copy gives
|
||||
// and stops Find matching it (#3713). The whole-line typical gap cannot tell the two apart: on these
|
||||
// lines most gaps are the zero of the value beside the label.
|
||||
//
|
||||
// A gap of its own is read as spacing only below half a line height, the same width Hangul uses. A
|
||||
// whole line height swallowed the gap between two cells of a form row whenever it was under one em --
|
||||
// 9pt on a 12pt line -- so 姓名 followed by 王小明 copied as 姓名王小明 (noted in review). Repetition,
|
||||
// not width, is what tells spread text apart from two cells.
|
||||
// `cluster_gap[w + 1]` is this pair's gap, so the pairs beside it are at `w` and `w + 2`.
|
||||
let spread = |w: usize| {
|
||||
let same = |other: Option<&Option<f32>>| other.copied().flatten().is_some_and(|o| (o - gap).abs() <= h * 0.02);
|
||||
same(sc.cluster_gap.get(w)) || same(sc.cluster_gap.get(w + 2))
|
||||
};
|
||||
// Korean keeps the narrower tolerance and no repetition: its words are separated by spaces, which
|
||||
// a file may write as position rather than as space characters. Measured on three Korean words at
|
||||
// one em, drawn without space glyphs: with the Chinese rule they read as 안녕하세요여러분.
|
||||
let hangul = pt.chars().any(is_hangul) || ct.chars().any(is_hangul);
|
||||
let cjk = pt.chars().any(is_cjk) && ct.chars().any(is_cjk) && (gap < h * 0.5 || (!hangul && spread(w)));
|
||||
// A combining sign that rides on no glyph before it (drawn apart from its base, or in a run of its own)
|
||||
// may sit anywhere over its base, so it never takes a space next to it. Two base letters of these
|
||||
// scripts are measured like any others: a Thai or Indic word gap is narrower than half an em.
|
||||
@@ -525,7 +658,7 @@ fn arrange(glyphs: &[TextGlyph]) -> (Vec<usize>, Vec<u32>, Vec<bool>) {
|
||||
let tight_cluster = (loose_sign(pt) || loose_sign(ct)) && gap < h * 0.6;
|
||||
let run_start = sc.breaks.binary_search(&c).is_ok();
|
||||
if let Some(space) = spaces.get_mut(w + 1) {
|
||||
*space = (gap > threshold || run_start)
|
||||
*space = (gap > pair_threshold || run_start)
|
||||
&& !cjk
|
||||
&& !tight_cluster
|
||||
&& !pt.trim().is_empty()
|
||||
|
||||
@@ -232,6 +232,10 @@ pub(super) struct Scratch {
|
||||
pub(super) logical: Vec<usize>,
|
||||
/// `placed` with the marks merged in, built before it is swapped in.
|
||||
pub(super) merged: Vec<usize>,
|
||||
/// The merged ink intervals of the current segment, each with the ink length before it, for `drop_covered_blanks`.
|
||||
pub(super) ink: Vec<[f32; 3]>,
|
||||
/// The ink glyphs of the current segment as (left, right, run), by left edge, for `drop_covered_blanks`.
|
||||
pub(super) ink_runs: Vec<(f32, f32, usize)>,
|
||||
/// For each glyph of the page, the glyph a combining mark drawn right after it rides on (the start of its cluster),
|
||||
/// or the glyph itself. Placement sorts clusters, so a mark keeps its content-stream place after its base (#6517).
|
||||
/// A glyph past its end is its own anchor.
|
||||
@@ -395,6 +399,8 @@ pub(super) fn place_glyphs(glyphs: &[&TextGlyph], height: &dyn Fn(usize) -> f32,
|
||||
sc.placed.sort_unstable_by(|a, b| by_cluster(glyphs, &sc.anchor, *a, *b));
|
||||
} else {
|
||||
collide(glyphs, height, s.h, sc);
|
||||
// Only another run can draw over a run's blanks: a single run is left as it is.
|
||||
drop_covered_blanks(glyphs, sc);
|
||||
}
|
||||
// Each mark goes before the first placed glyph whose x is greater than its own, or its letter's when it is a
|
||||
// combining mark riding on one. Marks are visited in that order, and that position never moves back, so one pass
|
||||
@@ -532,6 +538,99 @@ fn keep_taken_back_blanks(glyphs: &[&TextGlyph], placed: &mut [usize]) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Removes blank glyphs from `sc.placed` that are mostly covered by the ink of other glyphs on the line. A run of blanks
|
||||
/// drawn over the digits of an earlier run (a cover headline that overprints a number with spaces) would otherwise sort
|
||||
/// between the digits and show as spaces inside the number (#3172). Only other runs' ink counts: a blank its own run's
|
||||
/// letters overlap (kerned into a tight word gap) is that run's word break. A blank that stands in a gap is kept. A
|
||||
/// forced word break on a removed blank moves to the next glyph of its run that is kept. Each blank costs two binary
|
||||
/// searches over the line's ink, and a blank that ink mostly covers then a scan of the glyphs that can reach it.
|
||||
fn drop_covered_blanks(glyphs: &[&TextGlyph], sc: &mut Scratch) {
|
||||
let blank = |i: usize| glyphs[i].text.trim().is_empty();
|
||||
if !sc.placed.iter().any(|&i| blank(i)) {
|
||||
return;
|
||||
}
|
||||
let ink = &mut sc.ink;
|
||||
ink.clear();
|
||||
ink.extend(sc.placed.iter().filter(|&&i| !blank(i)).map(|&i| [glyphs[i].rect[0], glyphs[i].rect[2], 0.0]));
|
||||
ink.sort_by(|a, b| a[0].total_cmp(&b[0]));
|
||||
// Merge into disjoint intervals.
|
||||
ink.dedup_by(|cur, prev| {
|
||||
let overlaps = cur[0] <= prev[1];
|
||||
if overlaps {
|
||||
prev[1] = prev[1].max(cur[1]);
|
||||
}
|
||||
overlaps
|
||||
});
|
||||
// `iv[2]` is the ink length of all intervals before this one.
|
||||
let mut total = 0.0;
|
||||
for iv in ink.iter_mut() {
|
||||
iv[2] = total;
|
||||
total += iv[1] - iv[0];
|
||||
}
|
||||
let ink = &sc.ink;
|
||||
let covered = |l: f32, r: f32| {
|
||||
let first = ink.partition_point(|iv| iv[1] <= l);
|
||||
let end = ink.partition_point(|iv| iv[0] < r);
|
||||
let (Some(head), Some(last)) = (ink.get(first), end.checked_sub(1).and_then(|k| ink.get(k))) else { return 0.0 };
|
||||
if end <= first {
|
||||
return 0.0;
|
||||
}
|
||||
let after = ink.get(end).map_or(total, |iv| iv[2]);
|
||||
after - head[2] - (l - head[0]).max(0.0) - (last[1] - r).max(0.0)
|
||||
};
|
||||
// The ink glyphs with their runs, by left edge, and the widest of them: only a glyph starting less than that left
|
||||
// of a blank can reach it.
|
||||
let by_x = &mut sc.ink_runs;
|
||||
by_x.clear();
|
||||
by_x.extend(sc.owner.iter().filter(|&&(i, _)| !blank(i)).map(|&(i, r)| (glyphs[i].rect[0], glyphs[i].rect[2], r)));
|
||||
by_x.sort_by(|a, b| a.0.total_cmp(&b.0));
|
||||
let widest = by_x.iter().map(|g| g.1 - g.0).fold(0.0f32, f32::max);
|
||||
let by_x = &sc.ink_runs;
|
||||
// How much of [l, r] the ink of runs other than `run` covers. The intervals come in order of their left edges.
|
||||
let covered_by_others = |l: f32, r: f32, run: usize| {
|
||||
let (from, to) = (by_x.partition_point(|g| g.0 < l - widest), by_x.partition_point(|g| g.0 < r));
|
||||
let (mut sum, mut reach) = (0.0, l);
|
||||
for &(a, b, _) in by_x.get(from..to).unwrap_or_default().iter().filter(|g| g.2 != run) {
|
||||
let (a, b) = (a.max(reach), b.min(r));
|
||||
if b > a {
|
||||
sum += b - a;
|
||||
reach = b;
|
||||
}
|
||||
}
|
||||
sum
|
||||
};
|
||||
sc.merged.clear();
|
||||
for &(i, run) in &sc.owner {
|
||||
let (l, r) = (glyphs[i].rect[0], glyphs[i].rect[2]);
|
||||
if blank(i) && r - l > 0.0 && covered(l, r) > 0.5 * (r - l) && covered_by_others(l, r, run) > 0.5 * (r - l) {
|
||||
sc.merged.push(i);
|
||||
}
|
||||
}
|
||||
if sc.merged.is_empty() {
|
||||
return;
|
||||
}
|
||||
// `placed` is not sorted by index, so the dropped glyphs are sorted for the lookups.
|
||||
sc.merged.sort_unstable();
|
||||
let dropped = &sc.merged;
|
||||
sc.placed.retain(|i| dropped.binary_search(i).is_err());
|
||||
for b in sc.breaks.iter_mut() {
|
||||
if dropped.binary_search(b).is_err() {
|
||||
continue;
|
||||
}
|
||||
let x0 = |i: usize| glyphs[i].rect[0];
|
||||
let run = sc.text.iter().find(|run| run.range().contains(b));
|
||||
let kept = run.and_then(|run| {
|
||||
let left = run.range().filter(|j| dropped.binary_search(j).is_err());
|
||||
left.min_by(|a, c| x0(*a).total_cmp(&x0(*c)).then(a.cmp(c)))
|
||||
});
|
||||
*b = kept.unwrap_or(NONE);
|
||||
}
|
||||
sc.breaks.retain(|&b| b != NONE);
|
||||
sc.breaks.sort_unstable();
|
||||
sc.breaks.dedup();
|
||||
sc.merged.clear();
|
||||
}
|
||||
|
||||
/// `place_glyphs` for a segment of two or more text runs. `h` is the segment's line height. Returns whether the segment
|
||||
/// was too dense to sweep ([`COLLIDE_PAIRS_PER_GLYPH`]), in which case all its text runs form one component.
|
||||
///
|
||||
|
||||
@@ -1327,6 +1327,85 @@ fn limited_search_stops_after_the_requested_matches() {
|
||||
assert_eq!(text.find_opts_limited("o", false, false, 10), vec![0..1, 1..2, 2..3, 3..4]);
|
||||
}
|
||||
|
||||
fn tall(t: &str, x0: f32, y0: f32, x1: f32, h: f32) -> TextGlyph {
|
||||
let rect = [x0, y0, x1, y0 + h];
|
||||
TextGlyph { text: t.into(), rect, quad: [[x0, y0], [x1, y0], [x1, rect[3]], [x0, rect[3]]], direction: [1.0, 0.0] }
|
||||
}
|
||||
|
||||
/// #3172: blanks drawn over big digits must not show inside the number, and the word gap next to big digits follows
|
||||
/// the glyphs it lies between.
|
||||
#[test]
|
||||
fn blanks_under_a_number_and_a_word_gap_next_to_big_digits() {
|
||||
// Big dark digits, then a smaller sentence drawn over them with blanks where the digits sit.
|
||||
let mut v = Vec::new();
|
||||
for (t, x) in [("5", 0.0), ("0", 6.0), ("1", 100.0), ("4", 106.0)] {
|
||||
v.push(tall(t, x, 3.0, x + 6.0, 34.0));
|
||||
}
|
||||
for (t, x) in [("F", 16.5), ("R", 22.5), (" ", 100.0), (" ", 106.0), ("C", 130.0), ("D", 136.0)] {
|
||||
v.push(tall(t, x, 6.0, x + 6.0, 28.0));
|
||||
}
|
||||
assert_eq!(layout(v).plain_text(), "50 FR 14 CD");
|
||||
}
|
||||
|
||||
/// #3172: a word break on the covered blank that opens an overprinted run moves to the run's next glyph.
|
||||
#[test]
|
||||
fn a_covered_leading_blank_keeps_the_word_break_of_its_run() {
|
||||
let v = vec![
|
||||
g("1", 0.0, 10.0, 6.0),
|
||||
// " X" drawn over the "1": the blank is covered, and "X" sits right behind it.
|
||||
g(" ", 0.0, 10.0, 6.0),
|
||||
g("X", 6.0, 10.0, 12.0),
|
||||
];
|
||||
assert_eq!(layout(v).plain_text(), "1 X");
|
||||
}
|
||||
|
||||
/// #3172: a superscript keeps the line's word-gap threshold, not its own smaller height's, so a small gap before it is
|
||||
/// no word break.
|
||||
#[test]
|
||||
fn a_superscript_close_to_its_host_takes_no_space() {
|
||||
let v = vec![g("a", 0.0, 10.0, 6.0), g("x", 6.0, 10.0, 12.0), tall("2", 13.2, 7.0, 16.8, 6.0)];
|
||||
assert_eq!(layout(v).plain_text(), "ax2");
|
||||
}
|
||||
|
||||
/// #3172: a combining mark is measured by its cluster's base. Its own small box would shrink the word-gap threshold
|
||||
/// next to it, so a close letter after "á" read as a new word (noted in review).
|
||||
#[test]
|
||||
fn a_letter_close_after_a_combining_mark_takes_no_space() {
|
||||
let v = vec![
|
||||
g("x", 0.0, 10.0, 6.0),
|
||||
g("a", 6.0, 10.0, 12.0),
|
||||
tall("\u{301}", 10.0, 19.0, 12.0, 1.0),
|
||||
g("b", 13.0, 10.0, 19.0),
|
||||
g("y", 19.0, 10.0, 25.0),
|
||||
];
|
||||
assert_eq!(layout(v).plain_text(), "xa\u{301}by");
|
||||
}
|
||||
|
||||
/// #3172: a superscript too small for the sub- and superscript test (under half its host's height) still keeps the
|
||||
/// line's word-gap threshold next to its host: its height says no more about that gap (noted in review).
|
||||
#[test]
|
||||
fn a_tiny_superscript_close_to_its_host_takes_no_space() {
|
||||
let v = vec![g("a", 0.0, 10.0, 6.0), g("b", 6.0, 10.0, 12.0), tall("2", 13.0, 9.5, 15.4, 4.0)];
|
||||
assert_eq!(layout(v).plain_text(), "ab2");
|
||||
}
|
||||
|
||||
/// #3172: only another run's ink drops a blank. A space its own run's letter is kerned over is still that run's word
|
||||
/// break, even on a line where another run overprints elsewhere.
|
||||
#[test]
|
||||
fn a_blank_its_own_letters_overlap_stays_a_word_break() {
|
||||
let v = vec![
|
||||
// "A B" with the space pulled back under the "A", and the "B" kerned close: the space is the only word break.
|
||||
g("A", 0.0, 10.0, 6.0),
|
||||
g(" ", 2.0, 10.0, 8.0),
|
||||
g("B", 6.5, 10.0, 12.5),
|
||||
// A word far right, then a run drawn back over the "B", so the line's runs collide.
|
||||
g("Q", 200.0, 10.0, 206.0),
|
||||
g("1", 7.5, 10.0, 13.5),
|
||||
];
|
||||
let text = layout(v).plain_text();
|
||||
assert!(text.starts_with("A B"), "{text:?}");
|
||||
}
|
||||
|
||||
fn word(v: &mut Vec<TextGlyph>, s: &str, x: f32, y: f32, advance: f32) {
|
||||
for (i, c) in s.chars().enumerate() {
|
||||
let x0 = x + i as f32 * advance;
|
||||
@@ -1348,6 +1427,122 @@ fn fake_bold_duplicates_are_removed() {
|
||||
assert_eq!(layout(v).plain_text(), "e\u{301}");
|
||||
}
|
||||
|
||||
/// Text drawn once per column clip: "WO" and the `edge` glyphs, lots of other text, then the `second_pass`.
|
||||
fn column_passes(edge: &[TextGlyph], second_pass: &[TextGlyph]) -> String {
|
||||
let mut v = Vec::new();
|
||||
word(&mut v, "WO", 10.0, 10.0, 6.0);
|
||||
v.extend_from_slice(edge);
|
||||
for k in 0..50 {
|
||||
word(&mut v, "xx", 100.0, 40.0 + 14.0 * k as f32, 6.0);
|
||||
}
|
||||
v.extend_from_slice(second_pass);
|
||||
layout(v).plain_text()
|
||||
}
|
||||
|
||||
/// #3173: a page drawn once per column clip draws a glyph on the clip edge in both passes, far apart in drawing order.
|
||||
#[test]
|
||||
fn a_glyph_redrawn_by_the_other_column_pass_is_dropped() {
|
||||
let mut v = Vec::new();
|
||||
word(&mut v, "WO", 10.0, 10.0, 6.0);
|
||||
v.push(g("R", 22.0, 10.0, 28.0));
|
||||
word(&mut v, "illu", 10.0, 30.0, 6.0);
|
||||
v.push(g("s", 34.0, 30.0, 40.0));
|
||||
// The other pass: lots of other text, then the same glyphs at (almost) the same place and the rest of each word.
|
||||
for k in 0..50 {
|
||||
word(&mut v, "xx", 100.0, 40.0 + 14.0 * k as f32, 6.0);
|
||||
}
|
||||
v.push(g("R", 22.0, 10.0, 28.0));
|
||||
word(&mut v, "LD", 28.0, 10.0, 6.0);
|
||||
v.push(g("s", 33.99, 30.0, 39.99));
|
||||
word(&mut v, "trated", 40.0, 30.0, 6.0);
|
||||
let text = layout(v).plain_text();
|
||||
assert!(text.lines().any(|l| l == "WORLD"), "{text}");
|
||||
assert!(text.lines().any(|l| l == "illustrated"), "{text}");
|
||||
}
|
||||
|
||||
/// #3173: the second pass draws the glyph a little taller, so its grid cell must still be the one of the first copy.
|
||||
#[test]
|
||||
fn a_redrawn_glyph_of_slightly_different_height_is_dropped() {
|
||||
// Far from the page origin, a grid cell sized by each glyph's own height would put the two copies three cells apart.
|
||||
let mut v = Vec::new();
|
||||
word(&mut v, "WO", 150.0, 150.0, 6.0);
|
||||
v.push(em_box("R", 162.0, 150.0, 168.0, 160.0));
|
||||
for k in 0..50 {
|
||||
word(&mut v, "xx", 300.0, 200.0 + 14.0 * k as f32, 6.0);
|
||||
}
|
||||
v.push(em_box("R", 162.0, 150.0, 168.0, 160.3));
|
||||
word(&mut v, "LD", 168.0, 150.0, 6.0);
|
||||
let text = layout(v).plain_text();
|
||||
assert!(text.lines().any(|l| l == "WORLD"), "{text}");
|
||||
}
|
||||
|
||||
/// #3173: a fake-bold copy after the last glyph of a pass does not hide that the glyph ends its run.
|
||||
#[test]
|
||||
fn a_fake_bold_copy_at_the_end_of_a_pass_does_not_hide_the_run_end() {
|
||||
let mut second = vec![g("R", 22.0, 10.0, 28.0)];
|
||||
word(&mut second, "LD", 28.0, 10.0, 6.0);
|
||||
let text = column_passes(&[g("R", 22.0, 10.0, 28.0), g("R", 22.1, 10.0, 28.1)], &second);
|
||||
assert!(text.lines().any(|l| l == "WORLD"), "{text}");
|
||||
}
|
||||
|
||||
/// A glyph redrawn five or more times in a row at its own place prints once: the copies past the
|
||||
/// four-glyph window still match the kept glyph they follow.
|
||||
#[test]
|
||||
fn many_copies_of_a_glyph_in_a_row_print_once() {
|
||||
let mut v = Vec::new();
|
||||
word(&mut v, "WOR", 10.0, 10.0, 6.0);
|
||||
for _ in 0..7 {
|
||||
v.push(g("L", 28.0, 10.0, 34.0));
|
||||
}
|
||||
v.push(g("D", 34.0, 10.0, 40.0));
|
||||
assert_eq!(layout(v).plain_text(), "WORLD");
|
||||
}
|
||||
|
||||
/// #3173: the far redraw check reaches as far as a redraw may sit vertically, for a tall, narrow
|
||||
/// glyph whose horizontal tolerance is much smaller than its vertical one.
|
||||
#[test]
|
||||
fn a_tall_narrow_glyph_redrawn_a_little_higher_is_dropped() {
|
||||
let mut v = vec![em_box("|", 10.0, 100.0, 11.0, 140.0)];
|
||||
for k in 0..50 {
|
||||
word(&mut v, "xx", 100.0, 200.0 + 14.0 * k as f32, 6.0);
|
||||
}
|
||||
v.push(em_box("|", 10.0, 107.0, 11.0, 147.0));
|
||||
let text = layout(v).plain_text();
|
||||
assert_eq!(text.matches('|').count(), 1, "{text}");
|
||||
}
|
||||
|
||||
/// #3173: a glyph followed by its superscript is inside a run, so a later run starting at its place is not its redraw.
|
||||
#[test]
|
||||
fn a_glyph_followed_by_its_superscript_is_not_a_run_end() {
|
||||
let mut v = vec![em_box("H", 10.0, 10.0, 16.0, 20.0), em_box("2", 16.0, 16.0, 19.0, 22.0)];
|
||||
for k in 0..50 {
|
||||
word(&mut v, "xx", 100.0, 40.0 + 14.0 * k as f32, 6.0);
|
||||
}
|
||||
v.push(em_box("H", 10.0, 10.0, 16.0, 20.0));
|
||||
v.push(em_box("O", 16.0, 10.0, 22.0, 20.0));
|
||||
let text = layout(v).plain_text();
|
||||
assert_eq!(text.matches('H').count(), 2, "{text}");
|
||||
}
|
||||
|
||||
/// #3173: a glyph kept in a cell does not hide the earlier glyph there that the redraw matches.
|
||||
#[test]
|
||||
fn a_redraw_is_matched_against_earlier_glyphs_of_the_same_cell() {
|
||||
// A narrow "l" at 10 ends its line, a second one 0.8 pt to the right (more than a half of its width) is its own letter,
|
||||
// and the last one, more than 4 glyphs later, redraws the first.
|
||||
let v = vec![
|
||||
g("l", 10.0, 10.0, 11.0),
|
||||
g("Z", 200.0, 100.0, 206.0),
|
||||
g("l", 10.8, 10.0, 11.8),
|
||||
g("Y", 300.0, 200.0, 306.0),
|
||||
g("Z", 300.0, 300.0, 306.0),
|
||||
g("Y", 300.0, 400.0, 306.0),
|
||||
g("Z", 300.0, 500.0, 306.0),
|
||||
g("l", 10.0, 10.0, 11.0),
|
||||
];
|
||||
let text = layout(v).plain_text();
|
||||
assert_eq!(text.matches('l').count(), 2, "{text}");
|
||||
}
|
||||
|
||||
/// #1467: condensed text (80 Tz and below, OCR layers fitted to the scan) sets narrow letters
|
||||
/// closer than a fifth of their height apart; a doubled letter there is two letters, not a redraw.
|
||||
#[test]
|
||||
@@ -3184,6 +3379,104 @@ fn truetype_without_an_encoding_reads_its_codes_as_win_ansi() {
|
||||
assert_eq!(ocr_layer_text(32, true), expected, "nonsymbolic, /ToUnicode for ASCII only");
|
||||
}
|
||||
|
||||
/// #3713: a Chinese label spread to the width of a longer one (分散對齊, as on Taiwanese forms)
|
||||
/// is one show with character spacing, so every gap of the label is the same, while the value
|
||||
/// beside it has none. The line's typical gap is therefore the value's zero, and from half a
|
||||
/// line height upwards each of the label's gaps read as a word gap: 「受文者」 copied as
|
||||
/// 「受 文 者」 and Find no longer matched it. A repeated gap is spacing, whatever its width.
|
||||
#[test]
|
||||
fn a_chinese_label_spread_by_character_spacing_keeps_its_characters_together() {
|
||||
// `Tc` is added after every glyph of the string (ISO 32000-2 §9.3.2), so the gap before
|
||||
// the value is the spacing too; the value's own glyphs follow at `0 Tc`.
|
||||
let line = |tc: f32| {
|
||||
let mut v = Vec::new();
|
||||
let mut x = 0.0;
|
||||
for ch in ["受", "文", "者"] {
|
||||
v.push(em_box(ch, x, 0.0, x + 12.0, 12.0));
|
||||
x += 12.0 + tc;
|
||||
}
|
||||
for ch in ["如", "正", "本"] {
|
||||
v.push(em_box(ch, x, 0.0, x + 12.0, 12.0));
|
||||
x += 12.0;
|
||||
}
|
||||
layout(v).plain_text()
|
||||
};
|
||||
// A tenth of the font size up to a whole em: the issue's nine steps, the last three of
|
||||
// which used to break.
|
||||
for tc in [1.2, 2.4, 3.0, 3.6, 4.2, 4.8, 6.0, 9.0, 12.0] {
|
||||
assert_eq!(line(tc), "受文者如正本", "{tc} pt of character spacing");
|
||||
}
|
||||
|
||||
// A gap that stands on its own is still a word gap. The width is what the review caught: a
|
||||
// whole line height swallowed any isolated gap under one em, so two cells of a form row set
|
||||
// 9pt apart on a 12pt line copied as one word. Half a line height upwards is a gap, which is
|
||||
// the width Hangul already used; below it is still spacing.
|
||||
let cells = |gap: f32| {
|
||||
let mut v = Vec::new();
|
||||
for (i, ch) in ["姓", "名"].iter().enumerate() {
|
||||
let x = i as f32 * 12.0;
|
||||
v.push(em_box(ch, x, 0.0, x + 12.0, 12.0));
|
||||
}
|
||||
for (i, ch) in ["王", "小", "明"].iter().enumerate() {
|
||||
let x = 24.0 + gap + i as f32 * 12.0;
|
||||
v.push(em_box(ch, x, 0.0, x + 12.0, 12.0));
|
||||
}
|
||||
layout(v).plain_text()
|
||||
};
|
||||
// Two character widths, as before, and then the band that used to be lost: half a line
|
||||
// height and up. 6.0 is the boundary itself, which is a gap.
|
||||
for gap in [24.0, 18.0, 12.0, 9.0, 7.2, 6.0] {
|
||||
assert_eq!(cells(gap), "姓名 王小明", "{gap} pt between the two cells");
|
||||
}
|
||||
// And below it, still spacing rather than a gap -- one isolated narrow gap must not start
|
||||
// splitting a label that happens to carry one.
|
||||
for gap in [5.4, 3.0, 1.2, 0.0] {
|
||||
assert_eq!(cells(gap), "姓名王小明", "{gap} pt is spacing, not a gap");
|
||||
}
|
||||
}
|
||||
|
||||
/// Korean is written with spaces between words (띄어쓰기), and a file may write them as
|
||||
/// position rather than as space characters, so the rule for Chinese and Japanese -- where a
|
||||
/// gap between two characters is never a word gap -- must not reach Hangul (#3722 review).
|
||||
#[test]
|
||||
fn korean_words_separated_by_position_keep_their_spaces() {
|
||||
let line = |gap: f32| {
|
||||
let mut v = Vec::new();
|
||||
let mut x = 0.0;
|
||||
for word in ["안녕", "하세요", "여러분"] {
|
||||
for ch in word.chars() {
|
||||
v.push(em_box(&ch.to_string(), x, 0.0, x + 12.0, 12.0));
|
||||
x += 12.0;
|
||||
}
|
||||
x += gap;
|
||||
}
|
||||
layout(v).plain_text()
|
||||
};
|
||||
// Half the line height upwards is a word gap, as it was before the Chinese rule changed.
|
||||
for gap in [6.0, 7.0, 9.0, 12.0] {
|
||||
assert_eq!(line(gap), "안녕 하세요 여러분", "{gap} pt between the words");
|
||||
}
|
||||
// Below that it is letter spacing, which is unchanged.
|
||||
assert_eq!(line(3.0), "안녕하세요여러분");
|
||||
}
|
||||
|
||||
/// Halfwidth Hangul jamo are Hangul too: equal gaps between them from half a line height up are
|
||||
/// word gaps, not the character spacing of spread Chinese text.
|
||||
#[test]
|
||||
fn halfwidth_hangul_separated_by_equal_gaps_keeps_its_spaces() {
|
||||
let mut v = Vec::new();
|
||||
let mut x = 0.0;
|
||||
// A one-letter word between two others: its two word gaps repeat each other.
|
||||
for word in ["\u{FFA1}\u{FFA2}", "\u{FFA4}", "\u{FFA7}\u{FFA8}"] {
|
||||
for ch in word.chars() {
|
||||
v.push(em_box(&ch.to_string(), x, 0.0, x + 6.0, 12.0));
|
||||
x += 6.0;
|
||||
}
|
||||
x += 7.0;
|
||||
}
|
||||
assert_eq!(layout(v).plain_text(), "\u{FFA1}\u{FFA2} \u{FFA4} \u{FFA7}\u{FFA8}");
|
||||
}
|
||||
|
||||
/// Issue #2929: a footnote reference (superscript) on a line stays in that line instead of
|
||||
/// splitting out as a raised segment that steals the block's tail and pushes the host line
|
||||
/// after the paragraph.
|
||||
|
||||
@@ -982,7 +982,7 @@ fn extensions_kept(doc: &Document, old: &Document, d: &Dict, b: &Dict) -> bool {
|
||||
|
||||
/// A change to the signed catalog `b`, now `d`.
|
||||
fn catalog_kind(doc: &Document, old: &Document, d: &Dict, b: &Dict) -> &'static str {
|
||||
let keys: &[&[u8]] = &[b"AcroForm", b"DSS", b"Perms", b"Metadata", b"NeedsRendering", b"Extensions"];
|
||||
let keys: &[&[u8]] = &[b"AcroForm", b"DSS", b"Perms", b"Metadata", b"Extensions"];
|
||||
if !same_entries(d, b, keys) {
|
||||
kind::STRUCTURE
|
||||
} else if !extensions_kept(doc, old, d, b) {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use std::rc::Rc;
|
||||
|
||||
use super::types::{Detail, Modification, Status, TrustStore};
|
||||
use super::validate::{is_doc_timestamp, validate_doc_timestamp, validate_into};
|
||||
use super::validate::{SignatureValidation, is_doc_timestamp, validate_doc_timestamp, validate_into};
|
||||
use super::{Arc, Dict, DigestAlg, Document, HashMap, HashSet, ObjRef, Object, SignatureInfo};
|
||||
|
||||
/// Digests of signed byte ranges (and parsed signed revisions), kept across revalidations of
|
||||
@@ -486,7 +486,7 @@ pub fn list_cached(doc: &Document, bytes: &[u8], trust: &TrustStore, cache: &Dig
|
||||
details: Vec::new(),
|
||||
};
|
||||
if let Some(v) = v {
|
||||
validate_into(doc, bytes, trust, &v, &mut info, cache);
|
||||
validate_into(SignatureValidation { doc, bytes, trust, field: Some(&f), stamp_ref: None, info: &mut info, cache }, &v);
|
||||
}
|
||||
if let Some(r) = shared {
|
||||
judged.insert(r, out.len());
|
||||
@@ -532,7 +532,7 @@ pub fn list_cached(doc: &Document, bytes: &[u8], trust: &TrustStore, cache: &Dig
|
||||
verdict_shown: false,
|
||||
details: Vec::new(),
|
||||
};
|
||||
validate_doc_timestamp(doc, bytes, d, &mut info, cache, trust);
|
||||
validate_doc_timestamp(SignatureValidation { doc, bytes, trust, field: None, stamp_ref: Some(r), info: &mut info, cache }, d);
|
||||
out.push(info);
|
||||
}
|
||||
if !whole {
|
||||
|
||||
+142
-37
@@ -1,19 +1,23 @@
|
||||
use super::changes::classify_changes;
|
||||
use super::listing::{DigestCache, list, nums, sig_fields, text};
|
||||
use super::listing::{DigestCache, Field, list, nums, sig_fields, text};
|
||||
use super::locks::{Locked, locked_fields};
|
||||
use super::types::{Detail, Fill, Modification, Status, TrustStore, kind};
|
||||
use super::{
|
||||
Certificate, Dict, DigestAlg, Document, HashSet, ObjRef, Object, SignError, SignatureInfo, SignedData, Time, build_chain, build_chain_noted,
|
||||
};
|
||||
|
||||
struct SignatureValidation<'a> {
|
||||
doc: &'a Document,
|
||||
bytes: &'a [u8],
|
||||
trust: &'a TrustStore,
|
||||
info: &'a mut SignatureInfo,
|
||||
cache: &'a DigestCache,
|
||||
/// Inputs and output target for validating one signature or document timestamp.
|
||||
pub(super) struct SignatureValidation<'a> {
|
||||
pub(super) doc: &'a Document,
|
||||
pub(super) bytes: &'a [u8],
|
||||
pub(super) trust: &'a TrustStore,
|
||||
pub(super) field: Option<&'a Field>,
|
||||
pub(super) stamp_ref: Option<ObjRef>,
|
||||
pub(super) info: &'a mut SignatureInfo,
|
||||
pub(super) cache: &'a DigestCache,
|
||||
}
|
||||
|
||||
/// Cryptographically verified signature material before chain, trust, and change checks.
|
||||
struct VerifiedSignature<'a> {
|
||||
covered: usize,
|
||||
certificate: Certificate,
|
||||
@@ -82,42 +86,118 @@ fn set_certification(doc: &Document, v: &Dict, info: &mut SignatureInfo) {
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn validate_into(doc: &Document, bytes: &[u8], trust: &TrustStore, v: &Dict, info: &mut SignatureInfo, cache: &DigestCache) {
|
||||
/// Whether `covered` spans the entire file (ignoring trailing whitespace and NUL padding).
|
||||
fn whole_file(bytes: &[u8], covered: usize) -> bool {
|
||||
covered == bytes.len() || bytes.get(covered..).is_some_and(|rest| rest.iter().all(|b| b.is_ascii_whitespace() || *b == 0))
|
||||
}
|
||||
|
||||
/// The raw bytes of `d`'s `/Contents` string.
|
||||
fn dict_contents(doc: &Document, d: &Dict) -> Option<Vec<u8>> {
|
||||
let contents = d.get(b"Contents").map(|c| doc.resolve(c))?;
|
||||
let s = contents.as_string()?;
|
||||
if s.hex { Some(s.bytes.clone()) } else { unhex(&s.bytes) }
|
||||
}
|
||||
|
||||
/// Locate the signature or standalone timestamp dictionary in an earlier revision `rev`.
|
||||
fn find_sig_in_revision(rev: &Document, field: Option<&Field>, stamp_ref: Option<ObjRef>) -> Option<Dict> {
|
||||
if let Some(f) = field {
|
||||
// A later field that reuses the name is a different field. Match the object when we
|
||||
// have one, and the name only when neither side has an object. Two candidates is not
|
||||
// a match: the signature must not be reported on an attacker-chosen widget.
|
||||
let mut matched = sig_fields(rev).into_iter().filter(|of| match f.r {
|
||||
Some(want) => of.r == Some(want),
|
||||
None => of.r.is_none() && of.name == f.name,
|
||||
});
|
||||
let found = matched.next()?;
|
||||
if matched.next().is_some() {
|
||||
return None;
|
||||
}
|
||||
found.signature(rev)
|
||||
} else if let Some(r) = stamp_ref {
|
||||
rev.try_get(r.num).ok().and_then(|o| o.as_dict().cloned()).filter(is_doc_timestamp)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// The revision in which this signature or timestamp first appeared (when an earlier revision
|
||||
/// already holds it), or the current document.
|
||||
fn earliest_signed_dict(context: &SignatureValidation<'_>, v: &Dict) -> (Document, Dict) {
|
||||
let ends = context.doc.revision_ends();
|
||||
if ends.len() > 1 {
|
||||
for &end in &ends[..ends.len() - 1] {
|
||||
if end < context.bytes.len()
|
||||
&& !whole_file(context.bytes, end)
|
||||
&& let Some(old) = context.cache.revision(context.doc, context.bytes, end)
|
||||
&& let Some(old_v) = find_sig_in_revision(&old, context.field, context.stamp_ref)
|
||||
{
|
||||
return (old, old_v);
|
||||
}
|
||||
}
|
||||
}
|
||||
(context.doc.clone(), v.clone())
|
||||
}
|
||||
|
||||
/// Validate a signature field's dictionary `v` and record the verdict in `context.info`.
|
||||
pub(super) fn validate_into(context: SignatureValidation<'_>, v: &Dict) {
|
||||
let (mut sig_doc, mut sig_v) = earliest_signed_dict(&context, v);
|
||||
// A document timestamp can also be the value of a signature field (Documenso writes
|
||||
// `Timestamp_1` that way). Its `/Contents` is a bare RFC 3161 token, not a signature over the
|
||||
// document, so it must not be read as one.
|
||||
if is_doc_timestamp(v) {
|
||||
info.sub_filter = Some("ETSI.RFC3161".to_string());
|
||||
info.doc_timestamp = true;
|
||||
info.timestamp = true;
|
||||
validate_doc_timestamp(doc, bytes, v, info, cache, trust);
|
||||
if is_doc_timestamp(&sig_v) || is_doc_timestamp(v) {
|
||||
context.info.sub_filter = Some("ETSI.RFC3161".to_string());
|
||||
context.info.doc_timestamp = true;
|
||||
context.info.timestamp = true;
|
||||
validate_doc_timestamp(context, v);
|
||||
return;
|
||||
}
|
||||
info.date = text(doc, v, b"M");
|
||||
info.reason = text(doc, v, b"Reason");
|
||||
info.location = text(doc, v, b"Location");
|
||||
info.contact = text(doc, v, b"ContactInfo");
|
||||
info.sub_filter = v.name(b"SubFilter").map(|s| String::from_utf8_lossy(s).into_owned());
|
||||
info.signer = text(doc, v, b"Name");
|
||||
set_certification(doc, v, info);
|
||||
let SignatureValidation { doc, bytes, trust, field, stamp_ref, info, cache } = context;
|
||||
let fill_metadata = |d_doc: &Document, d_v: &Dict, info: &mut SignatureInfo| {
|
||||
info.date = text(d_doc, d_v, b"M");
|
||||
info.reason = text(d_doc, d_v, b"Reason");
|
||||
info.location = text(d_doc, d_v, b"Location");
|
||||
info.contact = text(d_doc, d_v, b"ContactInfo");
|
||||
info.sub_filter = d_v.name(b"SubFilter").map(|s| String::from_utf8_lossy(s).into_owned());
|
||||
info.signer = text(d_doc, d_v, b"Name");
|
||||
set_certification(d_doc, d_v, info);
|
||||
};
|
||||
fill_metadata(&sig_doc, &sig_v, info);
|
||||
let invalid = |info: &mut SignatureInfo, why: Detail| {
|
||||
info.status = Status::Invalid;
|
||||
info.details.push(why);
|
||||
};
|
||||
// Byte ranges: [0 a b c] with the gap holding exactly the hex /Contents.
|
||||
let Some(br) = nums(doc, v, b"ByteRange").filter(|b| b.len() == 4 && b.iter().all(|x| *x >= 0.0)) else {
|
||||
let Some(br) = nums(&sig_doc, &sig_v, b"ByteRange").filter(|b| b.len() == 4 && b.iter().all(|x| *x >= 0.0)) else {
|
||||
return invalid(info, Detail::plain("The signature has no valid byte range."));
|
||||
};
|
||||
let [o0, l0, o1, l1] = [br[0] as usize, br[1] as usize, br[2] as usize, br[3] as usize];
|
||||
if o0 != 0 || o1 < l0 || o1.checked_add(l1).is_none_or(|end| end > bytes.len()) || o1 - l0 < 2 {
|
||||
return invalid(info, Detail::plain("The signature's byte range does not match the file."));
|
||||
}
|
||||
};
|
||||
let gap = &bytes[l0..o1];
|
||||
if gap.first() != Some(&b'<') || gap.last() != Some(&b'>') {
|
||||
return invalid(info, Detail::plain("The signature's byte range does not exclude exactly its contents."));
|
||||
}
|
||||
let Some(contents) = unhex(&gap[1..gap.len() - 1]) else { return invalid(info, Detail::plain("The signature contents are not hexadecimal.")) };
|
||||
let covered = o1 + l1;
|
||||
if !whole_file(bytes, covered) {
|
||||
let Some(old) = cache.revision(doc, bytes, covered) else {
|
||||
return invalid(info, Detail::plain("The signature's byte range does not match the file."));
|
||||
};
|
||||
let Some(old_v) = find_sig_in_revision(&old, field, stamp_ref) else {
|
||||
return invalid(info, Detail::plain("The signature's byte range does not match the file."));
|
||||
};
|
||||
if nums(&old, &old_v, b"ByteRange") != Some(br) {
|
||||
return invalid(info, Detail::plain("The signature's byte range does not match the file."));
|
||||
}
|
||||
fill_metadata(&old, &old_v, info);
|
||||
(sig_doc, sig_v) = (old, old_v);
|
||||
}
|
||||
let expected_contents =
|
||||
sig_doc.bytes().get(l0..o1).filter(|g| g.first() == Some(&b'<') && g.last() == Some(&b'>')).and_then(|g| unhex(&g[1..g.len() - 1]));
|
||||
if dict_contents(&sig_doc, &sig_v) != expected_contents {
|
||||
return invalid(info, Detail::plain("The signature's byte range does not exclude exactly its contents."));
|
||||
}
|
||||
info.signed_len = covered;
|
||||
// The signed revision's number: its cross-reference sections (1 for a reconstructed file).
|
||||
info.revision = cache.revision(doc, bytes, covered).map_or(1, |d| d.revisions().len().max(1));
|
||||
@@ -129,7 +209,13 @@ pub(super) fn validate_into(doc: &Document, bytes: &[u8], trust: &TrustStore, v:
|
||||
info.details.push(Detail::of("PdfCraft can't check this signature yet: {}.", Fill::Reason(why.to_owned())));
|
||||
};
|
||||
if info.sub_filter.as_deref() == Some("adbe.x509.rsa_sha1") {
|
||||
return validate_x509_rsa_sha1(SignatureValidation { doc, bytes, trust, info, cache }, v, (l0, o1, covered), &contents);
|
||||
return validate_x509_rsa_sha1(
|
||||
SignatureValidation { doc, bytes, trust, field, stamp_ref, info, cache },
|
||||
&sig_doc,
|
||||
&sig_v,
|
||||
(l0, o1, covered),
|
||||
&contents,
|
||||
);
|
||||
}
|
||||
let sd = match SignedData::parse(&contents) {
|
||||
Ok(sd) => sd,
|
||||
@@ -240,7 +326,7 @@ pub(super) fn validate_into(doc: &Document, bytes: &[u8], trust: &TrustStore, v:
|
||||
}
|
||||
}
|
||||
finish_validation(
|
||||
SignatureValidation { doc, bytes, trust, info, cache },
|
||||
SignatureValidation { doc, bytes, trust, field, stamp_ref, info, cache },
|
||||
VerifiedSignature { covered, certificate: cert, embedded: &sd.certificates, cms_time: s.signing_time, unverified_time },
|
||||
);
|
||||
}
|
||||
@@ -248,7 +334,7 @@ pub(super) fn validate_into(doc: &Document, bytes: &[u8], trust: &TrustStore, v:
|
||||
/// The verdict once the signature value has been checked: chain and trust, the signing time
|
||||
/// against the certificate's validity, and what later revisions changed.
|
||||
fn finish_validation(context: SignatureValidation<'_>, verified: VerifiedSignature<'_>) {
|
||||
let SignatureValidation { doc, bytes, trust, info, cache } = context;
|
||||
let SignatureValidation { doc, bytes, trust, info, cache, .. } = context;
|
||||
let VerifiedSignature { covered, certificate: cert, embedded, cms_time, unverified_time } = verified;
|
||||
info.signing_time = cms_time.or_else(|| info.date.as_deref().and_then(Time::from_pdf));
|
||||
let mut pool = embedded.to_vec();
|
||||
@@ -272,7 +358,7 @@ fn finish_validation(context: SignatureValidation<'_>, verified: VerifiedSignatu
|
||||
let revoked = revocation == DssRevocation::Revoked;
|
||||
// Changes after signing.
|
||||
let mut locks = Locked::Kept;
|
||||
info.modification = if covered == bytes.len() || bytes[covered..].iter().all(|b| b.is_ascii_whitespace() || *b == 0) {
|
||||
info.modification = if whole_file(bytes, covered) {
|
||||
Modification::None
|
||||
} else {
|
||||
// The permissions are the signed revision's: a later one can rewrite `/P` (#1788) or the
|
||||
@@ -410,7 +496,6 @@ fn finish_validation(context: SignatureValidation<'_>, verified: VerifiedSignatu
|
||||
|
||||
/// Distinct evidence streams read from one `/DSS` array.
|
||||
pub(crate) const MAX_DSS_ENTRIES: usize = 1024;
|
||||
|
||||
/// Decoded bytes read from one `/DSS` array; real CRLs and OCSP responses are kilobytes each.
|
||||
pub(crate) const MAX_DSS_BYTES: usize = 64 << 20;
|
||||
|
||||
@@ -565,15 +650,17 @@ fn check_dss_revocation(doc: &Document, signer: Option<&Certificate>, at: &Optio
|
||||
}
|
||||
}
|
||||
|
||||
/// Validate a standalone document timestamp dictionary (`/ETSI.RFC3161`): the token must be
|
||||
/// cryptographically valid and its message imprint must cover the file's signed bytes.
|
||||
pub(super) fn validate_doc_timestamp(doc: &Document, bytes: &[u8], v: &Dict, info: &mut SignatureInfo, cache: &DigestCache, trust: &TrustStore) {
|
||||
info.date = text(doc, v, b"M");
|
||||
/// Validate a standalone or field document timestamp dictionary (`/ETSI.RFC3161`): the token must
|
||||
/// be cryptographically valid and its message imprint must cover the file's signed bytes.
|
||||
pub(super) fn validate_doc_timestamp(context: SignatureValidation<'_>, v: &Dict) {
|
||||
let (mut sig_doc, mut sig_v) = earliest_signed_dict(&context, v);
|
||||
let SignatureValidation { doc, bytes, trust, field, stamp_ref, info, cache } = context;
|
||||
info.date = text(&sig_doc, &sig_v, b"M");
|
||||
let invalid = |info: &mut SignatureInfo, why: Detail| {
|
||||
info.status = Status::Invalid;
|
||||
info.details.push(why);
|
||||
};
|
||||
let Some(br) = nums(doc, v, b"ByteRange").filter(|b| b.len() == 4 && b.iter().all(|x| *x >= 0.0)) else {
|
||||
let Some(br) = nums(&sig_doc, &sig_v, b"ByteRange").filter(|b| b.len() == 4 && b.iter().all(|x| *x >= 0.0)) else {
|
||||
return invalid(info, Detail::plain("The timestamp has no valid byte range."));
|
||||
};
|
||||
let [o0, l0, o1, l1] = [br[0] as usize, br[1] as usize, br[2] as usize, br[3] as usize];
|
||||
@@ -588,6 +675,24 @@ pub(super) fn validate_doc_timestamp(doc: &Document, bytes: &[u8], v: &Dict, inf
|
||||
return invalid(info, Detail::plain("The timestamp contents are not hexadecimal."));
|
||||
};
|
||||
let covered = o1 + l1;
|
||||
if !whole_file(bytes, covered) {
|
||||
let Some(old) = cache.revision(doc, bytes, covered) else {
|
||||
return invalid(info, Detail::plain("The timestamp's byte range does not match the file."));
|
||||
};
|
||||
let Some(old_v) = find_sig_in_revision(&old, field, stamp_ref) else {
|
||||
return invalid(info, Detail::plain("The timestamp's byte range does not match the file."));
|
||||
};
|
||||
if nums(&old, &old_v, b"ByteRange") != Some(br) {
|
||||
return invalid(info, Detail::plain("The timestamp's byte range does not match the file."));
|
||||
}
|
||||
info.date = text(&old, &old_v, b"M");
|
||||
(sig_doc, sig_v) = (old, old_v);
|
||||
}
|
||||
let expected_contents =
|
||||
sig_doc.bytes().get(l0..o1).filter(|g| g.first() == Some(&b'<') && g.last() == Some(&b'>')).and_then(|g| unhex(&g[1..g.len() - 1]));
|
||||
if dict_contents(&sig_doc, &sig_v) != expected_contents {
|
||||
return invalid(info, Detail::plain("The timestamp's byte range does not exclude exactly its contents."));
|
||||
}
|
||||
info.signed_len = covered;
|
||||
info.revision = cache.revision(doc, bytes, covered).map_or(1, |d| d.revisions().len().max(1));
|
||||
let token = match crate::timestamp::parse_token(&contents) {
|
||||
@@ -694,14 +799,14 @@ pub(crate) fn signature_contents(doc: &Document) -> Vec<Vec<u8>> {
|
||||
/// `adbe.x509.rsa_sha1` (ISO 32000-2 §12.8.3.2, deprecated): `/Contents` is the PKCS #1
|
||||
/// signature as a DER OCTET STRING over the SHA-1 digest of the byte ranges, and `/Cert` holds the
|
||||
/// signer's certificate (then any others) as DER byte strings.
|
||||
fn validate_x509_rsa_sha1(context: SignatureValidation<'_>, v: &Dict, (l0, o1, covered): (usize, usize, usize), contents: &[u8]) {
|
||||
let SignatureValidation { doc, bytes, trust, info, cache } = context;
|
||||
fn validate_x509_rsa_sha1(context: SignatureValidation<'_>, sig_doc: &Document, v: &Dict, (l0, o1, covered): (usize, usize, usize), contents: &[u8]) {
|
||||
let SignatureValidation { doc, bytes, trust, field, stamp_ref, info, cache } = context;
|
||||
let fail = |info: &mut SignatureInfo, why: Detail| {
|
||||
info.status = Status::Invalid;
|
||||
info.details.push(why);
|
||||
};
|
||||
let certs: Vec<Certificate> = match v.get(b"Cert").map(|c| doc.resolve(c)).as_deref() {
|
||||
Some(Object::Array(a)) => a.iter().filter_map(|c| doc.resolve(c).as_string().map(|s| s.bytes.clone())).collect::<Vec<_>>(),
|
||||
let certs: Vec<Certificate> = match v.get(b"Cert").map(|c| sig_doc.resolve(c)).as_deref() {
|
||||
Some(Object::Array(a)) => a.iter().filter_map(|c| sig_doc.resolve(c).as_string().map(|s| s.bytes.clone())).collect::<Vec<_>>(),
|
||||
Some(Object::String(s)) => vec![s.bytes.clone()],
|
||||
_ => Vec::new(),
|
||||
}
|
||||
@@ -743,7 +848,7 @@ fn validate_x509_rsa_sha1(context: SignatureValidation<'_>, v: &Dict, (l0, o1, c
|
||||
info.details.push(Detail::plain("The signature uses the legacy adbe.x509.rsa_sha1 format."));
|
||||
info.details.extend(DigestAlg::Sha1.weakness().map(Detail::plain));
|
||||
finish_validation(
|
||||
SignatureValidation { doc, bytes, trust, info, cache },
|
||||
SignatureValidation { doc, bytes, trust, field, stamp_ref, info, cache },
|
||||
VerifiedSignature { covered, certificate: cert, embedded: &certs, cms_time: None, unverified_time: None },
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1416,6 +1416,66 @@ fn xfa_page_swap(doc: &mut Document) {
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
/// A second widget that reuses the signed field's name and `/V` is not that signature.
|
||||
#[test]
|
||||
fn a_later_field_with_the_same_name_does_not_inherit_the_signature() {
|
||||
let id = pkcs12::open(&data("rsa-aes.p12"), "test").unwrap();
|
||||
let trust = TrustStore { certs: vec![id.certificate.clone()] };
|
||||
let signed = pdfcraft_sign::sign(&open(&fixture()), &id, &SignOptions { field: Some("Approval".into()), ..opts() }).unwrap();
|
||||
let edited = edit_after(&signed, |doc| {
|
||||
let root = doc.root().unwrap();
|
||||
let form = doc.get(root).as_dict().and_then(|c| c.get(b"AcroForm")).map(|a| doc.resolve(a)).and_then(|a| a.as_dict().cloned()).unwrap();
|
||||
let fields = form.get(b"Fields").map(|f| doc.resolve(f)).and_then(|f| f.as_array().cloned()).unwrap();
|
||||
let original = fields.iter().find_map(Object::as_ref).unwrap();
|
||||
let value = doc.get(original).as_dict().unwrap().get(b"V").cloned().expect("the signed field has /V");
|
||||
let mut widget = pdfcraft_cos::Dict::new();
|
||||
widget.set(b"Type".to_vec(), Object::name("Annot"));
|
||||
widget.set(b"Subtype".to_vec(), Object::name("Widget"));
|
||||
widget.set(b"FT".to_vec(), Object::name("Sig"));
|
||||
widget.set(b"T".to_vec(), PdfString::text("Approval"));
|
||||
widget.set(b"Rect".to_vec(), Object::Array(vec![Object::Int(10), Object::Int(10), Object::Int(80), Object::Int(40)]));
|
||||
widget.set(b"P".to_vec(), Object::Ref(pdfcraft_cos::ObjRef { num: 3, generation: 0 }));
|
||||
let cloned_v = doc.add((*doc.resolve(&value)).clone());
|
||||
widget.set(b"V".to_vec(), Object::Ref(cloned_v));
|
||||
let planted = doc.add(Object::Dict(widget));
|
||||
doc.update_dict(root, |c| {
|
||||
if let Some(Object::Dict(form)) = c.get_mut(b"AcroForm")
|
||||
&& let Some(Object::Array(list)) = form.get_mut(b"Fields")
|
||||
{
|
||||
list.push(Object::Ref(planted));
|
||||
}
|
||||
})
|
||||
.unwrap();
|
||||
doc.update_dict(pdfcraft_cos::ObjRef { num: 3, generation: 0 }, |p| {
|
||||
if let Some(Object::Array(annots)) = p.get_mut(b"Annots") {
|
||||
annots.push(Object::Ref(planted));
|
||||
}
|
||||
})
|
||||
.unwrap();
|
||||
});
|
||||
let listed = signatures(&open(&edited), &edited, &trust);
|
||||
let original = listed.iter().find(|s| s.rect == Some([150.0, 20.0, 280.0, 70.0])).expect("original field");
|
||||
let planted = listed.iter().find(|s| s.rect == Some([10.0, 10.0, 80.0, 40.0])).expect("planted field");
|
||||
assert_eq!(original.status, Status::Valid, "{:?}", original.details);
|
||||
assert_ne!(planted.status, Status::Valid, "the planted widget inherited the signature: {:?}", planted.details);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn toggling_needs_rendering_is_a_structure_change() {
|
||||
let id = pkcs12::open(&data("rsa-aes.p12"), "test").unwrap();
|
||||
let trust = TrustStore { certs: vec![id.certificate.clone()] };
|
||||
let check = |bytes: &[u8]| signatures(&open(bytes), bytes, &trust).into_iter().find(|s| s.signed).unwrap();
|
||||
let certified = pdfcraft_sign::sign(&open(&fixture()), &id, &SignOptions { certify: Some(1), ..opts() }).unwrap();
|
||||
assert_eq!(check(&certified).status, Status::Valid);
|
||||
let edited = edit_after(&certified, |doc| {
|
||||
let root = doc.root().unwrap();
|
||||
doc.update_dict(root, |c| c.set(b"NeedsRendering".to_vec(), Object::Bool(true))).unwrap();
|
||||
});
|
||||
let s = check(&edited);
|
||||
assert_eq!(s.status, Status::Invalid, "{:?}", s.details);
|
||||
assert!(matches!(&s.modification, Modification::Disallowed(k) if k.contains(&kind::STRUCTURE)), "{:?}", s.modification);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn declaring_a_form_xfa_does_not_excuse_replacing_the_pages() {
|
||||
let id = pkcs12::open(&data("rsa-aes.p12"), "test").unwrap();
|
||||
@@ -3546,6 +3606,174 @@ fn signing_a_field_with_a_null_value_after_another_signature_keeps_the_first_val
|
||||
);
|
||||
}
|
||||
|
||||
/// The signed catalog and page-tree nodes keep their structural roles even if a later revision
|
||||
/// drops `/Type /Catalog` or `/Type /Pages` and adds form keys (`/FT /Tx`, `/DR`) while swapping
|
||||
/// the page tree (#3998).
|
||||
#[test]
|
||||
fn signed_catalog_and_page_tree_keep_their_role_when_relabelled_or_dropped() {
|
||||
use pdfcraft_cos::{ObjRef, Stream};
|
||||
// Rewriting the signed catalog without `/Type /Catalog` while pointing `/Pages` at a new page tree
|
||||
// and adding `/FT /Tx` is refused as a structure change at every DocMDP level.
|
||||
assert_refused_at_every_level(&fixture(), kind::STRUCTURE, |doc| {
|
||||
let new_content = doc.add(Object::Stream(Stream::from_raw(Dict::new(), b"BT /F1 14 Tf 20 250 Td (Forged) Tj ET".to_vec())));
|
||||
let new_page = doc.add(Object::Dict(dict_of(vec![
|
||||
("Type", Object::name("Page")),
|
||||
("Parent", oref(2)),
|
||||
("MediaBox", Object::Array(vec![Object::Int(0), Object::Int(0), Object::Int(300), Object::Int(300)])),
|
||||
("Contents", Object::Ref(new_content)),
|
||||
])));
|
||||
let new_pages = doc.add(Object::Dict(dict_of(vec![
|
||||
("Type", Object::name("Pages")),
|
||||
("Kids", Object::Array(vec![Object::Ref(new_page)])),
|
||||
("Count", Object::Int(1)),
|
||||
])));
|
||||
let af = doc.get(ObjRef { num: 1, generation: 0 }).as_dict().and_then(|c| c.get(b"AcroForm").cloned()).unwrap();
|
||||
doc.set(
|
||||
ObjRef { num: 1, generation: 0 },
|
||||
Object::Dict(dict_of(vec![("Pages", Object::Ref(new_pages)), ("AcroForm", af), ("FT", Object::name("Tx"))])),
|
||||
);
|
||||
});
|
||||
|
||||
// Rewriting the signed `/Pages` dictionary without `/Type /Pages` while replacing `/Kids` and
|
||||
// adding `/FT /Tx` is refused as a page-tree change (`kind::PAGES`) at every DocMDP level.
|
||||
assert_refused_at_every_level(&fixture(), kind::PAGES, |doc| {
|
||||
let new_content = doc.add(Object::Stream(Stream::from_raw(Dict::new(), b"BT /F1 14 Tf 20 250 Td (Forged) Tj ET".to_vec())));
|
||||
let new_page = doc.add(Object::Dict(dict_of(vec![
|
||||
("Type", Object::name("Page")),
|
||||
("Parent", oref(2)),
|
||||
("MediaBox", Object::Array(vec![Object::Int(0), Object::Int(0), Object::Int(300), Object::Int(300)])),
|
||||
("Contents", Object::Ref(new_content)),
|
||||
])));
|
||||
doc.set(
|
||||
ObjRef { num: 2, generation: 0 },
|
||||
Object::Dict(dict_of(vec![
|
||||
("Kids", Object::Array(vec![Object::Ref(new_page), oref(3)])),
|
||||
("Count", Object::Int(2)),
|
||||
("FT", Object::name("Tx")),
|
||||
])),
|
||||
);
|
||||
});
|
||||
|
||||
// Rewriting a signed non-form dictionary (such as an `/Action` dictionary) by adding `/FT /Tx`
|
||||
// or `/DR` in a later revision is classified as `kind::OTHER` rather than `kind::FORM_FILL`,
|
||||
// and is refused even under DocMDP `P = 2` (and `P = 3`).
|
||||
let with_action = fixture_with(
|
||||
b"<< /Type /Catalog /Pages 2 0 R /OpenAction 7 0 R /AcroForm << /Fields [6 0 R] >> >>",
|
||||
&[b"<< /Type /Action /S /URI /URI (https://example.test/signed) >>"],
|
||||
);
|
||||
assert_refused_at_every_level(&with_action, kind::OTHER, |doc| {
|
||||
doc.set(
|
||||
ObjRef { num: 7, generation: 0 },
|
||||
Object::Dict(dict_of(vec![
|
||||
("Type", Object::name("Action")),
|
||||
("S", Object::name("URI")),
|
||||
("URI", Object::String(PdfString::text("https://attacker.invalid/phish"))),
|
||||
("FT", Object::name("Tx")),
|
||||
("DR", Object::Dict(Dict::new())),
|
||||
])),
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
/// Signature dictionaries (`/ByteRange`, `/Contents`, `/Reference`) are read from the revision
|
||||
/// covered by the signature, and rewriting a signed signature object or attaching a signature in a
|
||||
/// later revision whose `/ByteRange` only covers an earlier revision is refused (#3998).
|
||||
#[test]
|
||||
fn signed_signature_objects_and_byte_ranges_are_read_from_the_signed_revision() {
|
||||
let id = pkcs12::open(&data("ec-p256.p12"), "test").unwrap();
|
||||
let trust = TrustStore { certs: vec![id.certificate.clone()] };
|
||||
let signed = pdfcraft_sign::sign(&open(&fixture()), &id, &SignOptions { certify: Some(1), ..opts() }).unwrap();
|
||||
let sig_ref = open(&signed)
|
||||
.object_numbers()
|
||||
.into_iter()
|
||||
.map(|num| pdfcraft_cos::ObjRef { num, generation: 0 })
|
||||
.find(|r| open(&signed).get(*r).as_dict().is_some_and(|d| d.name(b"Type") == Some(b"Sig")))
|
||||
.unwrap();
|
||||
|
||||
// Rewriting the signed `/Type /Sig` dictionary in a later revision (trying to relax `/P` from
|
||||
// 1 to 3 and adding `/FT /Sig` so the rewrite looks like a signature field) keeps `certify` as
|
||||
// `Some(1)` from the signed revision and invalidates the signature.
|
||||
let relaxed = edit_after(&signed, |doc| {
|
||||
doc.update_dict(sig_ref, |d| {
|
||||
d.remove(b"Type");
|
||||
d.set(b"FT".to_vec(), Object::name("Sig"));
|
||||
d.set(
|
||||
b"Reference".to_vec(),
|
||||
Object::Array(vec![Object::Dict(dict_of(vec![
|
||||
("Type", Object::name("SigRef")),
|
||||
("TransformMethod", Object::name("DocMDP")),
|
||||
(
|
||||
"TransformParams",
|
||||
Object::Dict(dict_of(vec![("Type", Object::name("TransformParams")), ("P", Object::Int(3)), ("V", Object::name("1.2"))])),
|
||||
),
|
||||
]))]),
|
||||
);
|
||||
})
|
||||
.unwrap();
|
||||
});
|
||||
let s = signatures(&open(&relaxed), &relaxed, &trust).into_iter().find(|s| s.signed).unwrap();
|
||||
assert_eq!(s.certify, Some(1), "DocMDP level must come from the signed revision");
|
||||
assert_eq!(s.status, Status::Invalid, "{:?}", s.modification);
|
||||
assert!(matches!(&s.modification, Modification::Disallowed(k) if k.contains(&kind::OTHER)), "{:?}", s.modification);
|
||||
|
||||
// A signature object added in a later revision whose `/ByteRange` only covers the earlier
|
||||
// revision (where that signature field did not hold that signature) is refused.
|
||||
let sig_dict = open(&signed).get(sig_ref).as_dict().cloned().unwrap();
|
||||
let replayed = edit_after(&signed, |doc| {
|
||||
let replayed_v = doc.add(Object::Dict(sig_dict.clone()));
|
||||
doc.update_dict(pdfcraft_cos::ObjRef { num: 6, generation: 0 }, |f| {
|
||||
f.set(b"V".to_vec(), Object::Ref(replayed_v));
|
||||
})
|
||||
.unwrap();
|
||||
});
|
||||
let all = signatures(&open(&replayed), &replayed, &trust);
|
||||
let approval = all.iter().find(|s| s.field == "Approval").unwrap();
|
||||
assert_eq!(approval.status, Status::Invalid, "a later signature whose ByteRange only covers an earlier revision must be invalid: {approval:?}");
|
||||
}
|
||||
|
||||
/// Under DocMDP `P = 1` (no changes permitted), adding a signature field or counter-signing an
|
||||
/// existing unsigned signature field invalidates the certifying signature, whereas adding an
|
||||
/// RFC 3161 document timestamp (PAdES-LTA) remains permitted (#3998).
|
||||
#[test]
|
||||
fn certify_level_one_forbids_adding_signature_fields_or_counter_signing() {
|
||||
let id = pkcs12::open(&data("ec-p256.p12"), "test").unwrap();
|
||||
let tsa = TestTsa { id: tsa_id(), time: Time { year: 2026, month: 10, day: 6, hour: 12, minute: 0, second: 0 } };
|
||||
let trust = TrustStore { certs: vec![id.certificate.clone(), tsa.id.certificate.clone()] };
|
||||
let certified_p1 = pdfcraft_sign::sign(&open(&fixture()), &id, &SignOptions { certify: Some(1), ..opts() }).unwrap();
|
||||
let counter_p1 = pdfcraft_sign::sign(&open(&certified_p1), &id, &SignOptions { field: Some("Approval".into()), ..opts() }).unwrap();
|
||||
let first_p1 = signatures(&open(&counter_p1), &counter_p1, &trust).into_iter().find(|s| s.field == "Signature1").unwrap();
|
||||
assert_eq!(first_p1.status, Status::Invalid, "{:?}", first_p1.modification);
|
||||
assert_eq!(first_p1.modification, Modification::Disallowed(vec![kind::SIGNATURE]));
|
||||
|
||||
// Adding an RFC 3161 document timestamp to a P = 1 certified document is permitted for
|
||||
// long-term validation and keeps the certifying signature valid.
|
||||
let stamped_p1 = pdfcraft_sign::timestamp_document(&open(&certified_p1), &tsa, "D:20261006120000Z").unwrap();
|
||||
let stamped_sigs = signatures(&open(&stamped_p1), &stamped_p1, &trust);
|
||||
let cert_after_ts = stamped_sigs.iter().find(|s| s.field == "Signature1").unwrap();
|
||||
assert_eq!(cert_after_ts.status, Status::Valid, "{:?}", cert_after_ts.modification);
|
||||
assert!(matches!(&cert_after_ts.modification, Modification::Allowed(k) if k.contains(&kind::SIGNATURE)), "{:?}", cert_after_ts.modification);
|
||||
let doc_ts = stamped_sigs.iter().find(|s| s.doc_timestamp).unwrap();
|
||||
assert_eq!(doc_ts.status, Status::Valid, "{:?}", doc_ts.details);
|
||||
|
||||
// Dropping `/Perms` from the catalog after certification is a structure change.
|
||||
let dropped_perms = edit_after(&certified_p1, |doc| {
|
||||
let root = doc.root().unwrap();
|
||||
doc.update_dict(root, |c| {
|
||||
c.remove(b"Perms");
|
||||
})
|
||||
.unwrap();
|
||||
});
|
||||
let after_drop = signatures(&open(&dropped_perms), &dropped_perms, &trust).into_iter().find(|s| s.field == "Signature1").unwrap();
|
||||
assert_eq!(after_drop.status, Status::Invalid, "{:?}", after_drop.modification);
|
||||
assert_eq!(after_drop.modification, Modification::Disallowed(vec![kind::STRUCTURE]));
|
||||
|
||||
// Under P = 2 (filling forms and signing allowed), the same counter-signature is permitted.
|
||||
let certified_p2 = pdfcraft_sign::sign(&open(&fixture()), &id, &SignOptions { certify: Some(2), ..opts() }).unwrap();
|
||||
let counter_p2 = pdfcraft_sign::sign(&open(&certified_p2), &id, &SignOptions { field: Some("Approval".into()), ..opts() }).unwrap();
|
||||
let first_p2 = signatures(&open(&counter_p2), &counter_p2, &trust).into_iter().find(|s| s.field == "Signature1").unwrap();
|
||||
assert_eq!(first_p2.status, Status::Valid, "{:?}", first_p2.modification);
|
||||
}
|
||||
|
||||
/// Fields that name one signature value are listed each, under their own name, with the verdict
|
||||
/// the value earned once.
|
||||
#[test]
|
||||
|
||||
@@ -175,7 +175,7 @@ impl PdfCraftApp {
|
||||
pub fn with_intake(ctx: &egui::Context, intake: FileIntake) -> Self {
|
||||
let services = AppServices::system(ctx, intake);
|
||||
let (files, panels) = craft::dialogs::service::FileService::new(services.wake.clone());
|
||||
let host = Host::builder(APP_INFO).files(Arc::new(files)).build();
|
||||
let host = Host::builder(APP_INFO).files(Arc::new(files)).i18n(i18n::host_catalogs()).build();
|
||||
let mut app = Self::with_host(Arc::new(host), services);
|
||||
app.file_panels = Some(panels);
|
||||
app
|
||||
@@ -267,6 +267,7 @@ impl PdfCraftApp {
|
||||
font_scan: queue(&host, &wake, "pdfcraft-font-scan"),
|
||||
print_tasks: print_ui::PrintTasks::new(host.jobs_shared().clone(), wake.clone()),
|
||||
host,
|
||||
host_date_language: None,
|
||||
wake,
|
||||
intake,
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
@@ -845,10 +846,10 @@ impl PdfCraftApp {
|
||||
view.session.pending_pick = None;
|
||||
}
|
||||
}
|
||||
panes::frame(self, &ctx);
|
||||
// Forms' scripts read Highlight fields as `app.runtimeHighlight`.
|
||||
let highlight = self.active.and_then(|i| self.views.get(i)).map_or(self.highlight_fields, |v| v.session.highlight_fields);
|
||||
self.session.set_field_highlight(highlight);
|
||||
panes::frame(self, &ctx);
|
||||
self.sync_titles(&ctx);
|
||||
// The accessible window takes the same name, so a screen reader (AT-SPI on Linux, UIA on
|
||||
// Windows) can tell it apart (#4614). egui builds the root node afresh every pass.
|
||||
|
||||
@@ -90,8 +90,14 @@ impl PdfCraftApp {
|
||||
("default-mode", _) => {
|
||||
self.default_mode = Mode::parse(value).ok_or("default-mode must be all, read, edit, convert or sign")?;
|
||||
}
|
||||
("date-format", _) => self.session.set_date_format(value)?,
|
||||
("date-language", _) => self.session.set_date_language(Some(value).filter(|v| *v != "auto"))?,
|
||||
("date-format", _) => {
|
||||
self.session.set_date_format(value)?;
|
||||
self.sync_open_date_format();
|
||||
}
|
||||
("date-language", _) => {
|
||||
self.session.set_date_language(Some(value).filter(|v| *v != "auto"))?;
|
||||
self.sync_open_date_language();
|
||||
}
|
||||
("tool", _) => {
|
||||
let g = pdfcraft_engine::catalog::group(value).ok_or_else(|| format!("unknown tool {value}"))?;
|
||||
self.select_tool(ctx, g.id);
|
||||
@@ -540,6 +546,8 @@ impl PdfCraftApp {
|
||||
}
|
||||
"none" => {
|
||||
self.cancel_dialogs(ctx);
|
||||
// Preferences is a separate live window, not part of the dialog host.
|
||||
self.preferences = None;
|
||||
self.redact_props = None;
|
||||
self.redact_search_open = false;
|
||||
self.hidden_draft = None;
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user