Migrate PdfCraft to egui 0.37 with reconciled platform and editor behavior

Preserve current main, pin the reviewed forks, and cover hidden input,
IME lifecycle, bidi rendering, persisted settings, and editor geometry.

Repository gates pass; native/browser acceptance and paired app performance
remain explicitly open for human review.
This commit is contained in:
skylartaylor committed 2026-10-25 02:45:21 +01:00
commit ba77d792f1
342 files changed
+28709 -2959

No files matched your search

+1 -1
View File
@@ -73,7 +73,7 @@ jobs:
# the org's 5 macOS slots are kept for release builds, and release.yml builds macOS.
os: ${{ (github.event_name != 'pull_request' || contains(github.event.pull_request.labels.*.name, 'full-ci')) && '["ubuntu-24.04","windows-latest"]' || '["ubuntu-24.04"]' }}
# Same craft-fonts commit as release.yml and freebsd.yml.
craft-fonts-ref: 3d9ab3a132ed0eff457e424226a435a901da30d3
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
# egui/winit/rfd, and the independent oracles (crates/oracle).
packages: >-
libxkbcommon-dev libwayland-dev libx11-dev libxrandr-dev libxi-dev libgl1-mesa-dev
+1 -1
View File
@@ -26,4 +26,4 @@ jobs:
# Intentionally tracked at @main (not SHA-pinned) so org-wide CI improvements, security fixes, and build optimizations propagate without PR churn across all craftapp repos.
uses: storytold/craft-common-actions/.github/workflows/freebsd.yml@main
with:
craft-fonts-ref: 3d9ab3a132ed0eff457e424226a435a901da30d3
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
+1 -1
View File
@@ -24,7 +24,7 @@ jobs:
with:
app-name: pdfcraft
app-title: PdfCraft
craft-fonts-ref: 3d9ab3a132ed0eff457e424226a435a901da30d3
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
version: ${{ inputs.version }}
secrets:
APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }}
+40 -39
View File
@@ -8,33 +8,33 @@ Every asset PdfCraft includes, bundles or uses to build its published material,
| Asset | Title | Author | Licence | Source | Used for |
|---|---|---|---|---|---|
| `crates/ui-egui/src/i18n/el.tsv` | Greek interface translation catalog | Camthalion77 and contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft English UI labels; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed | Greek UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
| `crates/ui-egui/src/i18n/zh-hans.tsv` | Simplified Chinese interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed | Simplified Chinese UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
| `crates/ui-egui/src/i18n/zh-hant.tsv` | Traditional Chinese (Taiwan) interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed | Traditional Chinese UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
| `crates/ui-egui/src/i18n/cs.tsv` | Czech interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 signature-check and standard-identification wordings are contributor-original AI-assisted translations from English, not separately native-reviewed | Czech UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
| `crates/ui-egui/src/i18n/pt-br.tsv` | Brazilian Portuguese interface translation catalog | André Cardoso (andrecards), PdfCraft contributors | MIT OR Apache-2.0 | Clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources: the ~1,826-entry gist posted in issue #288 (https://gist.github.com/andrecards/ac388c25fba17312ce83207f8b7b467e), completed and reviewed by PdfCraft contributors; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 text-field-table limit messages are contributor-original AI-assisted translations from English, not separately native-reviewed | Brazilian Portuguese UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
| `crates/ui-egui/src/i18n/es.tsv` | Spanish interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; the 2026-10-20 coverage additions are AI-assisted and not separately native-reviewed; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 signature-check wordings are contributor-original AI-assisted translations from English, not separately native-reviewed | Spanish UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
| `crates/ui-egui/src/i18n/fr.tsv` | French interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed | French UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
| `crates/ui-egui/src/i18n/de.tsv` | German interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed | German UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
| `crates/ui-egui/src/i18n/lo.tsv` | Lao interface translation catalog | @bounkirdni-2025 | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft English UI labels, no proprietary localisation resources; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed | Lao UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
| `crates/ui-egui/src/i18n/te.tsv` | Telugu interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed | Telugu UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
| `crates/ui-egui/src/i18n/it.tsv` | Italian interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed | Italian UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
| `crates/ui-egui/src/i18n/pl.tsv` | Polish interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 signature-check wordings are contributor-original AI-assisted translations from English, not separately native-reviewed | Polish UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
| `crates/ui-egui/src/i18n/ru.tsv` | Russian interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed | Russian UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
| `crates/ui-egui/src/i18n/hu.tsv` | Hungarian interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed | Hungarian UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
| `crates/ui-egui/src/i18n/bg.tsv` | Bulgarian interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed | Bulgarian UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
| `crates/ui-egui/src/i18n/kk.tsv` | Kazakh interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of the English UI labels into Kazakh, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed | Kazakh UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
| `crates/ui-egui/src/i18n/ja.tsv` | Japanese interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed | Japanese UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
| `crates/ui-egui/src/i18n/uk.tsv` | Ukrainian interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed | Ukrainian UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
| `crates/ui-egui/src/i18n/ar.tsv` | Arabic interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed | Arabic UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
| `crates/ui-egui/src/i18n/ckb.tsv` | Central Kurdish (Sorani) interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed | Central Kurdish UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
| `crates/ui-egui/src/i18n/tr.tsv` | Turkish interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed | Turkish UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
| `crates/ui-egui/src/i18n/lt.tsv` | Lithuanian interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels and user-facing messages; original catalog reviewed by a native Lithuanian-speaking contributor; 2026-10-15 coverage additions are AI-assisted and not separately native-reviewed; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed | Lithuanian UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
| `crates/ui-egui/src/i18n/hi.tsv` | Hindi interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 text-field-table labels are contributor-original AI-assisted translations from English, not separately native-reviewed | Hindi UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
| `crates/ui-egui/src/i18n/id.tsv` | Indonesian interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 text-field-table labels are contributor-original AI-assisted translations from English, not separately native-reviewed | Indonesian UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
| `crates/ui-egui/src/i18n/ko.tsv` | Korean interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 text-field-table labels are contributor-original AI-assisted translations from English, not separately native-reviewed | Korean UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
| `crates/ui-egui/src/i18n/ro.tsv` | Romanian interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels and user-facing messages; AI-assisted and not yet reviewed line by line by a native Romanian speaker; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 text-field-table labels are contributor-original AI-assisted translations from English, not separately native-reviewed | Romanian UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
| `crates/ui-egui/src/i18n/fi.tsv` | Finnish interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: AI-assisted (Claude Code) clean-room translations of PdfCraft's English UI labels and user-facing messages; not yet proofread by a native Finnish speaker; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 text-field-table labels are contributor-original AI-assisted translations from English, not separately native-reviewed | Finnish UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
| `crates/ui-egui/src/i18n/el.tsv` | Greek interface translation catalog | Camthalion77 and contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft English UI labels; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed | Greek UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
| `crates/ui-egui/src/i18n/zh-hans.tsv` | Simplified Chinese interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed | Simplified Chinese UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
| `crates/ui-egui/src/i18n/zh-hant.tsv` | Traditional Chinese (Taiwan) interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed | Traditional Chinese UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
| `crates/ui-egui/src/i18n/cs.tsv` | Czech interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 signature-check and standard-identification wordings are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed | Czech UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
| `crates/ui-egui/src/i18n/pt-br.tsv` | Brazilian Portuguese interface translation catalog | André Cardoso (andrecards), PdfCraft contributors | MIT OR Apache-2.0 | Clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources: the ~1,826-entry gist posted in issue #288 (https://gist.github.com/andrecards/ac388c25fba17312ce83207f8b7b467e), completed and reviewed by PdfCraft contributors; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 text-field-table limit messages are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed | Brazilian Portuguese UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
| `crates/ui-egui/src/i18n/es.tsv` | Spanish interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; the 2026-10-20 coverage additions are AI-assisted and not separately native-reviewed; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 signature-check wordings are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed | Spanish UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
| `crates/ui-egui/src/i18n/fr.tsv` | French interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed | French UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
| `crates/ui-egui/src/i18n/de.tsv` | German interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed | German UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
| `crates/ui-egui/src/i18n/lo.tsv` | Lao interface translation catalog | @bounkirdni-2025 | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft English UI labels, no proprietary localisation resources; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed | Lao UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
| `crates/ui-egui/src/i18n/te.tsv` | Telugu interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed | Telugu UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
| `crates/ui-egui/src/i18n/it.tsv` | Italian interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed | Italian UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
| `crates/ui-egui/src/i18n/pl.tsv` | Polish interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 signature-check wordings are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed | Polish UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
| `crates/ui-egui/src/i18n/ru.tsv` | Russian interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed | Russian UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
| `crates/ui-egui/src/i18n/hu.tsv` | Hungarian interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed | Hungarian UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
| `crates/ui-egui/src/i18n/bg.tsv` | Bulgarian interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed | Bulgarian UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
| `crates/ui-egui/src/i18n/kk.tsv` | Kazakh interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of the English UI labels into Kazakh, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed | Kazakh UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
| `crates/ui-egui/src/i18n/ja.tsv` | Japanese interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed | Japanese UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
| `crates/ui-egui/src/i18n/uk.tsv` | Ukrainian interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed | Ukrainian UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
| `crates/ui-egui/src/i18n/ar.tsv` | Arabic interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed | Arabic UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
| `crates/ui-egui/src/i18n/ckb.tsv` | Central Kurdish (Sorani) interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed | Central Kurdish UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
| `crates/ui-egui/src/i18n/tr.tsv` | Turkish interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed | Turkish UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
| `crates/ui-egui/src/i18n/lt.tsv` | Lithuanian interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels and user-facing messages; original catalog reviewed by a native Lithuanian-speaking contributor; 2026-10-15 coverage additions are AI-assisted and not separately native-reviewed; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed | Lithuanian UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
| `crates/ui-egui/src/i18n/hi.tsv` | Hindi interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 text-field-table labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed | Hindi UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
| `crates/ui-egui/src/i18n/id.tsv` | Indonesian interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 text-field-table labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed | Indonesian UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
| `crates/ui-egui/src/i18n/ko.tsv` | Korean interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 text-field-table labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed | Korean UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
| `crates/ui-egui/src/i18n/ro.tsv` | Romanian interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels and user-facing messages; AI-assisted and not yet reviewed line by line by a native Romanian speaker; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 text-field-table labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed | Romanian UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
| `crates/ui-egui/src/i18n/fi.tsv` | Finnish interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: AI-assisted (Claude Code) clean-room translations of PdfCraft's English UI labels and user-facing messages; not yet proofread by a native Finnish speaker; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 text-field-table labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 calculation-order, text-format, print, thumbnail, layer, comment-reshape and signature labels (previously English placeholders) are contributor-original AI-assisted translations from English, not separately native-reviewed | Finnish UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
| `assets/icons/accessibility.svg` | Lucide icon "accessibility" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/accessibility.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/align-left.svg` | Lucide icon "align-left" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/align-left.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/align-center.svg` | Lucide icon "align-center" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/align-center.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
@@ -285,26 +285,27 @@ Every asset PdfCraft includes, bundles or uses to build its published material,
| `packaging/macos/dmg/background.tiff` | PdfCraft macOS DMG window background (rendered) | @XusBadia | MIT OR Apache-2.0 | Rendered from packaging/macos/dmg/background.svg by packaging/macos/dmg/generate.py | 1x + 2x HiDPI 16-colour palette TIFF copied into the macOS DMG by packaging/macos/package.sh; includes the app icon and the free LittleCMS built-in sRGB profile |
| `crates/sign/tests/data/x509-rsa-sha1.pdf` | One-page PDF with a legacy adbe.x509.rsa_sha1 signature by the RSA test key | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: hand-written PDF objects; signature made with `openssl dgst -sha1 -sign` over its byte ranges (see crates/sign/tests/data/README.md) | Signature validation tests (crates/sign/tests/it/pdf.rs): the legacy adbe.x509.rsa_sha1 format |
| `assets/icons/monitor.svg` | Lucide icon "monitor" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/monitor.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `crates/ui-egui/src/i18n/vi.tsv` | Vietnamese interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels; PhotoCraft and VectorCraft Vietnamese catalogs used only as translation memory when English source and semantic context matched; original catalog reviewed by a native Vietnamese-speaking contributor; 2026-10-15 coverage additions are AI-assisted and not separately native-reviewed; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 signature-check wordings are contributor-original AI-assisted translations from English, not separately native-reviewed | Vietnamese UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
| `crates/ui-egui/src/i18n/sl.tsv` | Slovene interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed | Slovene UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
| `crates/ui-egui/src/i18n/vi.tsv` | Vietnamese interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels; PhotoCraft and VectorCraft Vietnamese catalogs used only as translation memory when English source and semantic context matched; original catalog reviewed by a native Vietnamese-speaking contributor; 2026-10-15 coverage additions are AI-assisted and not separately native-reviewed; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 signature-check wordings are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed | Vietnamese UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
| `crates/ui-egui/src/i18n/sl.tsv` | Slovene interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed | Slovene UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
| `vendor/vello_common/assets/probe.png` | vello_common probe reference image (rendered from probe.rgba) | Linebender vello contributors | MIT OR Apache-2.0 | vello_common 0.0.8 (crates.io), vendored in vendor/vello_common; regenerated by its vello_sparse_tests regenerate_probe_reference binary | Reference picture of the vendored vello_common probe module, for people only; the build reads probe.rgba, not this file |
| `crates/ui-egui/src/i18n/nb.tsv` | Norwegian Bokmål interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed | Norwegian Bokmål UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
| `crates/ui-egui/src/i18n/nb.tsv` | Norwegian Bokmål interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed | Norwegian Bokmål UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
| `assets/icons/superscript.svg` | Lucide icon "superscript" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/superscript.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/subscript.svg` | Lucide icon "subscript" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/subscript.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/pilcrow.svg` | Lucide icon "pilcrow" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/pilcrow.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/move-horizontal.svg` | Lucide icon "move-horizontal" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/move-horizontal.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `crates/ui-egui/src/i18n/sq.tsv` | Albanian interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 signature-appearance labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 text-field-table labels are contributor-original AI-assisted translations from English, not separately native-reviewed | Albanian UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
| `crates/ui-egui/src/i18n/th.tsv` | Thai interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed | Thai UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
| `crates/ui-egui/src/i18n/ca.tsv` | Catalan interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, written from their meaning; no proprietary localisation resources; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 text-field-table labels are contributor-original AI-assisted translations from English, not separately native-reviewed | Catalan UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
| `crates/ui-egui/src/i18n/sq.tsv` | Albanian interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 signature-appearance labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 text-field-table labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed | Albanian UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
| `crates/ui-egui/src/i18n/th.tsv` | Thai interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed | Thai UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
| `crates/ui-egui/src/i18n/ca.tsv` | Catalan interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, written from their meaning; no proprietary localisation resources; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 text-field-table labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed | Catalan UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
## Compiled in through dependencies (5)
## Compiled in through dependencies (6)
| Crate | File | Title | Author | Licence | Source | Used for |
|---|---|---|---|---|---|---|
| `epaint_default_fonts` 0.36.2 | `fonts/Ubuntu-Light.ttf` | Ubuntu Light | Canonical Ltd. / Dalton Maag | Ubuntu-font-1.0 | https://design.ubuntu.com/font | egui fallback fonts (eframe feature default_fonts) |
| `epaint_default_fonts` 0.36.2 | `fonts/Hack-Regular.ttf` | Hack Regular | Source Foundry Authors (derived from Bitstream Vera / DejaVu) | MIT AND Bitstream-Vera | https://github.com/source-foundry/Hack | egui fallback fonts (eframe feature default_fonts) |
| `epaint_default_fonts` 0.36.2 | `fonts/NotoEmoji-Regular.ttf` | Noto Emoji (monochrome) | Google Inc. | OFL-1.1 | https://github.com/googlefonts/noto-emoji | egui fallback fonts (eframe feature default_fonts) |
| `epaint_default_fonts` 0.36.2 | `fonts/emoji-icon-font.ttf` | emoji-icon-font | John Slegers | MIT | https://github.com/jslegers/emoji-icon-font | egui fallback fonts (eframe feature default_fonts) |
| `epaint_default_fonts` 0.37.0 | `fonts/Ubuntu-Light.ttf` | Ubuntu Light | Canonical Ltd. / Dalton Maag | Ubuntu-font-1.0 | https://design.ubuntu.com/font | egui fallback fonts (eframe feature default_fonts) |
| `epaint_default_fonts` 0.37.0 | `fonts/Hack-Regular.ttf` | Hack Regular | Source Foundry Authors (derived from Bitstream Vera / DejaVu) | MIT AND Bitstream-Vera | https://github.com/source-foundry/Hack | egui fallback fonts (eframe feature default_fonts) |
| `epaint_default_fonts` 0.37.0 | `fonts/NotoEmoji-Regular.ttf` | Noto Emoji (monochrome) | Google Inc. | OFL-1.1 | https://github.com/googlefonts/noto-emoji | egui monochrome fallback font (egui feature monochrome_emoji_fonts) |
| `epaint_default_fonts` 0.37.0 | `fonts/emoji-icon-font.ttf` | emoji-icon-font | John Slegers | MIT | https://github.com/jslegers/emoji-icon-font | egui monochrome fallback font (egui feature monochrome_emoji_fonts) |
| `epaint_default_fonts` 0.37.0 | `fonts/egui-icons.ttf` | egui icons (monochrome emoji-icon-font subset) | John Slegers | MIT | https://github.com/jslegers/emoji-icon-font | Small special-icon subset embedded by egui default_fonts; retained in FontDefinitions::default(). Provenance: https://github.com/storytold/egui/blob/6d518fc799681571963842f95b55a6b68431b15a/crates/epaint_default_fonts/fonts/egui-icons.txt; complete MIT copyright and permission text in NOTICE. |
| `hayro-interpret` 0.7.0 | `src/font/generated/metrics.rs` | Standard-14 font metrics and encodings (as Rust tables) (non-visual data, AGENTS.md §1.1) | Adobe (Core 14 AFM metrics, PDF specification encodings); tables by The Hayro Authors | MIT OR Apache-2.0 | ISO 32000-2 Annex D; Adobe Core14 AFM files (via vendored hayro-interpret) | Glyph widths and encodings for non-embedded standard fonts. Non-visual data, allowed by AGENTS.md §1.1 |
## Downloaded at build time (22)
@@ -342,4 +343,4 @@ Not in this repository and never downloaded by it: compiled in only when the bui
| Input | Option | Title | Author | Licence | Source | Attribution | Used for |
|---|---|---|---|---|---|---|---|
| `craft-fonts` | `CRAFT_FONTS_DIR` | Japanese fonts: BIZ UDPGothic (Regular, Bold), Shippori Mincho, BIZ UDMincho; Arabic font: Noto Sans Arabic | The BIZ UDGothic and BIZ UDMincho Project Authors (Morisawa Inc.), The Shippori Mincho Project Authors (FONTDASU), The Noto Project Authors (Noto Sans Arabic) | OFL-1.1 | https://github.com/storytold/craft-fonts (pinned by commit in .github/workflows/release.yml) | https://github.com/storytold/craft-fonts/blob/main/ATTRIBUTION.md | Japanese fallback in the interface (BIZ UDPGothic first) and Japanese glyphs in edited PDF text (Shippori Mincho); Arabic interface text, file names and document titles (Noto Sans Arabic); the web build embeds only BIZ UDPGothic Regular and Noto Sans Arabic. The checkout also holds Noto Sans CJK SC, which crates/fonts/build.rs leaves out for size |
| `craft-fonts` | `CRAFT_FONTS_DIR` | Japanese fonts: BIZ UDPGothic (Regular, Bold), Shippori Mincho, BIZ UDMincho; native Simplified Chinese font: LXGW WenKai Lite; Arabic font: Noto Sans Arabic | The BIZ UDGothic and BIZ UDMincho Project Authors (Morisawa Inc.), The Shippori Mincho Project Authors (FONTDASU), LXGW and the original Klee Project Authors / Fontworks (LXGW WenKai Lite), The Noto Project Authors (Noto Sans Arabic) | OFL-1.1 | https://github.com/storytold/craft-fonts (pinned by commit in .github/workflows/release.yml and .github/workflows/ci.yml); LXGW WenKai Lite from https://github.com/lxgw/LxgwWenKai-Lite/releases/tag/v1.530 (commit b712c83d98acf977bacfb7fb010207802808bda9) | https://github.com/storytold/craft-fonts/blob/main/ATTRIBUTION.md | Japanese fallback in the interface (BIZ UDPGothic first) and Japanese glyphs in edited PDF text (Shippori Mincho); Simplified Chinese interface fallback on native builds only (LXGW WenKai Lite Regular, font SHA-256 f799a538a3355877e597a0ae04050e897932c9ae7689eb9227c2953c5dd549ea, OFL SHA-256 0333a85fe077b6849f8e417acc44e8bd879442ceb681e271acf93e2d57fd4e2e, read from fonts/simplified-chinese-manifest.txt and never embedded on wasm); Arabic interface text, file names and document titles (Noto Sans Arabic); the web build embeds BIZ UDPGothic Regular and the pinned small Arabic, Hebrew, Thai and Devanagari faces; the selected craft-fonts revision contains no Telugu face. Other non-Japanese CJK faces retain the general 4 MiB cap; the reviewed native-only LXGW fallback has a separate 16 MiB cap. Open-source OFL releases are permitted under current AGENTS.md §1.1 |
+55 -43
View File
@@ -2,7 +2,7 @@
path = "crates/ui-egui/src/i18n/el.tsv"
title = "Greek interface translation catalog"
author = "Camthalion77 and contributors"
source = "Contributor-original: clean-room translations of PdfCraft English UI labels; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed"
source = "Contributor-original: clean-room translations of PdfCraft English UI labels; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed"
licence = "MIT OR Apache-2.0"
licence_file = "LICENSE-MIT"
kind = "translation"
@@ -26,7 +26,7 @@ usage = "Greek UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs"
path = "crates/ui-egui/src/i18n/zh-hans.tsv"
title = "Simplified Chinese interface translation catalog"
author = "PdfCraft contributors"
source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed"
source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed"
licence = "MIT OR Apache-2.0"
licence_file = "LICENSE-MIT"
kind = "translation"
@@ -36,7 +36,7 @@ usage = "Simplified Chinese UI strings, compiled in by crates/ui-egui/src/i18n/m
path = "crates/ui-egui/src/i18n/zh-hant.tsv"
title = "Traditional Chinese (Taiwan) interface translation catalog"
author = "PdfCraft contributors"
source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed"
source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed"
licence = "MIT OR Apache-2.0"
licence_file = "LICENSE-MIT"
kind = "translation"
@@ -46,7 +46,7 @@ usage = "Traditional Chinese UI strings, compiled in by crates/ui-egui/src/i18n/
path = "crates/ui-egui/src/i18n/cs.tsv"
title = "Czech interface translation catalog"
author = "PdfCraft contributors"
source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 signature-check and standard-identification wordings are contributor-original AI-assisted translations from English, not separately native-reviewed"
source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 signature-check and standard-identification wordings are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed"
licence = "MIT OR Apache-2.0"
licence_file = "LICENSE-MIT"
kind = "translation"
@@ -56,7 +56,7 @@ usage = "Czech UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs"
path = "crates/ui-egui/src/i18n/pt-br.tsv"
title = "Brazilian Portuguese interface translation catalog"
author = "André Cardoso (andrecards), PdfCraft contributors"
source = "Clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources: the ~1,826-entry gist posted in issue #288 (https://gist.github.com/andrecards/ac388c25fba17312ce83207f8b7b467e), completed and reviewed by PdfCraft contributors; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 text-field-table limit messages are contributor-original AI-assisted translations from English, not separately native-reviewed"
source = "Clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources: the ~1,826-entry gist posted in issue #288 (https://gist.github.com/andrecards/ac388c25fba17312ce83207f8b7b467e), completed and reviewed by PdfCraft contributors; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 text-field-table limit messages are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed"
licence = "MIT OR Apache-2.0"
licence_file = "LICENSE-MIT"
kind = "translation"
@@ -66,7 +66,7 @@ usage = "Brazilian Portuguese UI strings, compiled in by crates/ui-egui/src/i18n
path = "crates/ui-egui/src/i18n/es.tsv"
title = "Spanish interface translation catalog"
author = "PdfCraft contributors"
source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; the 2026-10-20 coverage additions are AI-assisted and not separately native-reviewed; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 signature-check wordings are contributor-original AI-assisted translations from English, not separately native-reviewed"
source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; the 2026-10-20 coverage additions are AI-assisted and not separately native-reviewed; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 signature-check wordings are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed"
licence = "MIT OR Apache-2.0"
licence_file = "LICENSE-MIT"
kind = "translation"
@@ -76,7 +76,7 @@ usage = "Spanish UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs"
path = "crates/ui-egui/src/i18n/fr.tsv"
title = "French interface translation catalog"
author = "PdfCraft contributors"
source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed"
source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed"
licence = "MIT OR Apache-2.0"
licence_file = "LICENSE-MIT"
kind = "translation"
@@ -86,7 +86,7 @@ usage = "French UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs"
path = "crates/ui-egui/src/i18n/de.tsv"
title = "German interface translation catalog"
author = "PdfCraft contributors"
source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed"
source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed"
licence = "MIT OR Apache-2.0"
licence_file = "LICENSE-MIT"
kind = "translation"
@@ -96,7 +96,7 @@ usage = "German UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs"
path = "crates/ui-egui/src/i18n/lo.tsv"
title = "Lao interface translation catalog"
author = "@bounkirdni-2025"
source = "Contributor-original: clean-room translations of PdfCraft English UI labels, no proprietary localisation resources; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed"
source = "Contributor-original: clean-room translations of PdfCraft English UI labels, no proprietary localisation resources; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed"
licence = "MIT OR Apache-2.0"
licence_file = "LICENSE-MIT"
kind = "translation"
@@ -106,7 +106,7 @@ usage = "Lao UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs"
path = "crates/ui-egui/src/i18n/te.tsv"
title = "Telugu interface translation catalog"
author = "PdfCraft contributors"
source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed"
source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed"
licence = "MIT OR Apache-2.0"
licence_file = "LICENSE-MIT"
kind = "translation"
@@ -116,7 +116,7 @@ usage = "Telugu UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs"
path = "crates/ui-egui/src/i18n/it.tsv"
title = "Italian interface translation catalog"
author = "PdfCraft contributors"
source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed"
source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed"
licence = "MIT OR Apache-2.0"
licence_file = "LICENSE-MIT"
kind = "translation"
@@ -126,7 +126,7 @@ usage = "Italian UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs"
path = "crates/ui-egui/src/i18n/pl.tsv"
title = "Polish interface translation catalog"
author = "PdfCraft contributors"
source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 signature-check wordings are contributor-original AI-assisted translations from English, not separately native-reviewed"
source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 signature-check wordings are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed"
licence = "MIT OR Apache-2.0"
licence_file = "LICENSE-MIT"
kind = "translation"
@@ -136,7 +136,7 @@ usage = "Polish UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs"
path = "crates/ui-egui/src/i18n/ru.tsv"
title = "Russian interface translation catalog"
author = "PdfCraft contributors"
source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed"
source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed"
licence = "MIT OR Apache-2.0"
licence_file = "LICENSE-MIT"
kind = "translation"
@@ -146,7 +146,7 @@ usage = "Russian UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs"
path = "crates/ui-egui/src/i18n/hu.tsv"
title = "Hungarian interface translation catalog"
author = "PdfCraft contributors"
source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed"
source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed"
licence = "MIT OR Apache-2.0"
licence_file = "LICENSE-MIT"
kind = "translation"
@@ -156,7 +156,7 @@ usage = "Hungarian UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs"
path = "crates/ui-egui/src/i18n/bg.tsv"
title = "Bulgarian interface translation catalog"
author = "PdfCraft contributors"
source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed"
source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed"
licence = "MIT OR Apache-2.0"
licence_file = "LICENSE-MIT"
kind = "translation"
@@ -166,7 +166,7 @@ usage = "Bulgarian UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs"
path = "crates/ui-egui/src/i18n/kk.tsv"
title = "Kazakh interface translation catalog"
author = "PdfCraft contributors"
source = "Contributor-original: clean-room translations of the English UI labels into Kazakh, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed"
source = "Contributor-original: clean-room translations of the English UI labels into Kazakh, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed"
licence = "MIT OR Apache-2.0"
licence_file = "LICENSE-MIT"
kind = "translation"
@@ -176,7 +176,7 @@ usage = "Kazakh UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs"
path = "crates/ui-egui/src/i18n/ja.tsv"
title = "Japanese interface translation catalog"
author = "PdfCraft contributors"
source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed"
source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed"
licence = "MIT OR Apache-2.0"
licence_file = "LICENSE-MIT"
kind = "translation"
@@ -186,7 +186,7 @@ usage = "Japanese UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs"
path = "crates/ui-egui/src/i18n/uk.tsv"
title = "Ukrainian interface translation catalog"
author = "PdfCraft contributors"
source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed"
source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed"
licence = "MIT OR Apache-2.0"
licence_file = "LICENSE-MIT"
kind = "translation"
@@ -196,7 +196,7 @@ usage = "Ukrainian UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs"
path = "crates/ui-egui/src/i18n/ar.tsv"
title = "Arabic interface translation catalog"
author = "PdfCraft contributors"
source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed"
source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed"
licence = "MIT OR Apache-2.0"
licence_file = "LICENSE-MIT"
kind = "translation"
@@ -206,7 +206,7 @@ usage = "Arabic UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs"
path = "crates/ui-egui/src/i18n/ckb.tsv"
title = "Central Kurdish (Sorani) interface translation catalog"
author = "PdfCraft contributors"
source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed"
source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed"
licence = "MIT OR Apache-2.0"
licence_file = "LICENSE-MIT"
kind = "translation"
@@ -216,7 +216,7 @@ usage = "Central Kurdish UI strings, compiled in by crates/ui-egui/src/i18n/mod.
path = "crates/ui-egui/src/i18n/tr.tsv"
title = "Turkish interface translation catalog"
author = "PdfCraft contributors"
source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed"
source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed"
licence = "MIT OR Apache-2.0"
licence_file = "LICENSE-MIT"
kind = "translation"
@@ -226,7 +226,7 @@ usage = "Turkish UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs"
path = "crates/ui-egui/src/i18n/lt.tsv"
title = "Lithuanian interface translation catalog"
author = "PdfCraft contributors"
source = "Contributor-original: clean-room translations of PdfCraft's English UI labels and user-facing messages; original catalog reviewed by a native Lithuanian-speaking contributor; 2026-10-15 coverage additions are AI-assisted and not separately native-reviewed; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed"
source = "Contributor-original: clean-room translations of PdfCraft's English UI labels and user-facing messages; original catalog reviewed by a native Lithuanian-speaking contributor; 2026-10-15 coverage additions are AI-assisted and not separately native-reviewed; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed"
licence = "MIT OR Apache-2.0"
licence_file = "LICENSE-MIT"
kind = "translation"
@@ -236,7 +236,7 @@ usage = "Lithuanian UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs"
path = "crates/ui-egui/src/i18n/hi.tsv"
title = "Hindi interface translation catalog"
author = "PdfCraft contributors"
source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 text-field-table labels are contributor-original AI-assisted translations from English, not separately native-reviewed"
source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 text-field-table labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed"
licence = "MIT OR Apache-2.0"
licence_file = "LICENSE-MIT"
kind = "translation"
@@ -245,7 +245,7 @@ usage = "Hindi UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs"
path = "crates/ui-egui/src/i18n/id.tsv"
title = "Indonesian interface translation catalog"
author = "PdfCraft contributors"
source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 text-field-table labels are contributor-original AI-assisted translations from English, not separately native-reviewed"
source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 text-field-table labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed"
licence = "MIT OR Apache-2.0"
licence_file = "LICENSE-MIT"
kind = "translation"
@@ -254,7 +254,7 @@ usage = "Indonesian UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs"
path = "crates/ui-egui/src/i18n/ko.tsv"
title = "Korean interface translation catalog"
author = "PdfCraft contributors"
source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 text-field-table labels are contributor-original AI-assisted translations from English, not separately native-reviewed"
source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 text-field-table labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed"
licence = "MIT OR Apache-2.0"
licence_file = "LICENSE-MIT"
kind = "translation"
@@ -264,7 +264,7 @@ usage = "Korean UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs"
path = "crates/ui-egui/src/i18n/ro.tsv"
title = "Romanian interface translation catalog"
author = "PdfCraft contributors"
source = "Contributor-original: clean-room translations of PdfCraft's English UI labels and user-facing messages; AI-assisted and not yet reviewed line by line by a native Romanian speaker; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 text-field-table labels are contributor-original AI-assisted translations from English, not separately native-reviewed"
source = "Contributor-original: clean-room translations of PdfCraft's English UI labels and user-facing messages; AI-assisted and not yet reviewed line by line by a native Romanian speaker; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 text-field-table labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed"
licence = "MIT OR Apache-2.0"
licence_file = "LICENSE-MIT"
kind = "translation"
@@ -275,7 +275,7 @@ usage = "Romanian UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs"
path = "crates/ui-egui/src/i18n/fi.tsv"
title = "Finnish interface translation catalog"
author = "PdfCraft contributors"
source = "Contributor-original: AI-assisted (Claude Code) clean-room translations of PdfCraft's English UI labels and user-facing messages; not yet proofread by a native Finnish speaker; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 text-field-table labels are contributor-original AI-assisted translations from English, not separately native-reviewed"
source = "Contributor-original: AI-assisted (Claude Code) clean-room translations of PdfCraft's English UI labels and user-facing messages; not yet proofread by a native Finnish speaker; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 text-field-table labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 calculation-order, text-format, print, thumbnail, layer, comment-reshape and signature labels (previously English placeholders) are contributor-original AI-assisted translations from English, not separately native-reviewed"
licence = "MIT OR Apache-2.0"
licence_file = "LICENSE-MIT"
kind = "translation"
@@ -2429,7 +2429,7 @@ sha256 = "f225e0b044875b8fa6375b6b5ad935f0d99fcc1ad03ecf9f0baae2cedbfca4d2"
[[bundled]]
crate = "epaint_default_fonts"
version = "0.36.2"
version = "0.37.0"
path = "fonts/Ubuntu-Light.ttf"
title = "Ubuntu Light"
author = "Canonical Ltd. / Dalton Maag"
@@ -2441,7 +2441,7 @@ sha256 = "80307b8da7649aa4ee4d484b232140e3ce1ec0ca093073d3c53c8f5a5ced7a70"
[[bundled]]
crate = "epaint_default_fonts"
version = "0.36.2"
version = "0.37.0"
path = "fonts/Hack-Regular.ttf"
title = "Hack Regular"
author = "Source Foundry Authors (derived from Bitstream Vera / DejaVu)"
@@ -2453,28 +2453,40 @@ sha256 = "15f55cc0c85a2988d2b4b3a8cdb5d77fdfbaf319e1bb5309d725db9818fb7125"
[[bundled]]
crate = "epaint_default_fonts"
version = "0.36.2"
version = "0.37.0"
path = "fonts/NotoEmoji-Regular.ttf"
title = "Noto Emoji (monochrome)"
author = "Google Inc."
source = "https://github.com/googlefonts/noto-emoji"
licence = "OFL-1.1"
kind = "font"
usage = "egui fallback fonts (eframe feature default_fonts)"
usage = "egui monochrome fallback font (egui feature monochrome_emoji_fonts)"
sha256 = "415dc6290378574135b64c808dc640c1df7531973290c4970c51fdeb849cb0c5"
[[bundled]]
crate = "epaint_default_fonts"
version = "0.36.2"
version = "0.37.0"
path = "fonts/emoji-icon-font.ttf"
title = "emoji-icon-font"
author = "John Slegers"
source = "https://github.com/jslegers/emoji-icon-font"
licence = "MIT"
kind = "font"
usage = "egui fallback fonts (eframe feature default_fonts)"
usage = "egui monochrome fallback font (egui feature monochrome_emoji_fonts)"
sha256 = "f426bec371f484646d002717e2c555a95cd5145e635d83a48bbef83f3abf18ca"
[[bundled]]
crate = "epaint_default_fonts"
version = "0.37.0"
path = "fonts/egui-icons.ttf"
title = "egui icons (monochrome emoji-icon-font subset)"
author = "John Slegers"
source = "https://github.com/jslegers/emoji-icon-font"
licence = "MIT"
kind = "font"
usage = "Small special-icon subset embedded by egui default_fonts; retained in FontDefinitions::default(). Provenance: https://github.com/storytold/egui/blob/6d518fc799681571963842f95b55a6b68431b15a/crates/epaint_default_fonts/fonts/egui-icons.txt; complete MIT copyright and permission text in NOTICE."
sha256 = "122806555c73df7cef55aa1d945289ae27fbc4dbbd31abbb4204ee0cda829cc8"
[[asset]]
path = "vendor/hayro-cmap/assets/cmaps.brotli"
title = "Adobe CMap resources (predefined CJK CMaps)"
@@ -3362,13 +3374,13 @@ sha256 = "e484866d4cce403175bd8d00b128feb08ab42e208de30e42cd9889d8f1735a6e"
[[build_input]]
name = "craft-fonts"
option = "CRAFT_FONTS_DIR"
title = "Japanese fonts: BIZ UDPGothic (Regular, Bold), Shippori Mincho, BIZ UDMincho; Arabic font: Noto Sans Arabic"
author = "The BIZ UDGothic and BIZ UDMincho Project Authors (Morisawa Inc.), The Shippori Mincho Project Authors (FONTDASU), The Noto Project Authors (Noto Sans Arabic)"
source = "https://github.com/storytold/craft-fonts (pinned by commit in .github/workflows/release.yml)"
title = "Japanese fonts: BIZ UDPGothic (Regular, Bold), Shippori Mincho, BIZ UDMincho; native Simplified Chinese font: LXGW WenKai Lite; Arabic font: Noto Sans Arabic"
author = "The BIZ UDGothic and BIZ UDMincho Project Authors (Morisawa Inc.), The Shippori Mincho Project Authors (FONTDASU), LXGW and the original Klee Project Authors / Fontworks (LXGW WenKai Lite), The Noto Project Authors (Noto Sans Arabic)"
source = "https://github.com/storytold/craft-fonts (pinned by commit in .github/workflows/release.yml and .github/workflows/ci.yml); LXGW WenKai Lite from https://github.com/lxgw/LxgwWenKai-Lite/releases/tag/v1.530 (commit b712c83d98acf977bacfb7fb010207802808bda9)"
licence = "OFL-1.1"
attribution = "https://github.com/storytold/craft-fonts/blob/main/ATTRIBUTION.md"
kind = "font"
usage = "Japanese fallback in the interface (BIZ UDPGothic first) and Japanese glyphs in edited PDF text (Shippori Mincho); Arabic interface text, file names and document titles (Noto Sans Arabic); the web build embeds only BIZ UDPGothic Regular and Noto Sans Arabic. The checkout also holds Noto Sans CJK SC, which crates/fonts/build.rs leaves out for size"
usage = "Japanese fallback in the interface (BIZ UDPGothic first) and Japanese glyphs in edited PDF text (Shippori Mincho); Simplified Chinese interface fallback on native builds only (LXGW WenKai Lite Regular, font SHA-256 f799a538a3355877e597a0ae04050e897932c9ae7689eb9227c2953c5dd549ea, OFL SHA-256 0333a85fe077b6849f8e417acc44e8bd879442ceb681e271acf93e2d57fd4e2e, read from fonts/simplified-chinese-manifest.txt and never embedded on wasm); Arabic interface text, file names and document titles (Noto Sans Arabic); the web build embeds BIZ UDPGothic Regular and the pinned small Arabic, Hebrew, Thai and Devanagari faces; the selected craft-fonts revision contains no Telugu face. Other non-Japanese CJK faces retain the general 4 MiB cap; the reviewed native-only LXGW fallback has a separate 16 MiB cap. Open-source OFL releases are permitted under current AGENTS.md §1.1"
[[asset]]
path = "crates/sign/tests/data/x509-rsa-sha1.pdf"
@@ -3396,7 +3408,7 @@ sha256 = "d1a443233345724859de8e4fb48968ba91e885e12ddbd710701548bd91b39428"
path = "crates/ui-egui/src/i18n/vi.tsv"
title = "Vietnamese interface translation catalog"
author = "PdfCraft contributors"
source = "Contributor-original: clean-room translations of PdfCraft's English UI labels; PhotoCraft and VectorCraft Vietnamese catalogs used only as translation memory when English source and semantic context matched; original catalog reviewed by a native Vietnamese-speaking contributor; 2026-10-15 coverage additions are AI-assisted and not separately native-reviewed; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 signature-check wordings are contributor-original AI-assisted translations from English, not separately native-reviewed"
source = "Contributor-original: clean-room translations of PdfCraft's English UI labels; PhotoCraft and VectorCraft Vietnamese catalogs used only as translation memory when English source and semantic context matched; original catalog reviewed by a native Vietnamese-speaking contributor; 2026-10-15 coverage additions are AI-assisted and not separately native-reviewed; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 signature-check wordings are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed"
licence = "MIT OR Apache-2.0"
licence_file = "LICENSE-MIT"
kind = "translation"
@@ -3406,7 +3418,7 @@ usage = "Vietnamese UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs"
path = "crates/ui-egui/src/i18n/sl.tsv"
title = "Slovene interface translation catalog"
author = "PdfCraft contributors"
source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed"
source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed"
licence = "MIT OR Apache-2.0"
licence_file = "LICENSE-MIT"
kind = "translation"
@@ -3428,7 +3440,7 @@ sha256 = "78c59a0cfd2c829909d77006f94e34dac1ae5d1f90e7f10f72e84de541fef697"
path = "crates/ui-egui/src/i18n/nb.tsv"
title = "Norwegian Bokmål interface translation catalog"
author = "PdfCraft contributors"
source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed"
source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed"
licence = "MIT OR Apache-2.0"
licence_file = "LICENSE-MIT"
kind = "translation"
@@ -3482,7 +3494,7 @@ sha256 = "864ab2f19254e6ac7240bc6a98323197332e8f714d4d3f94831f41309e5ef2f7"
path = "crates/ui-egui/src/i18n/sq.tsv"
title = "Albanian interface translation catalog"
author = "PdfCraft contributors"
source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 signature-appearance labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 text-field-table labels are contributor-original AI-assisted translations from English, not separately native-reviewed"
source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 signature-appearance labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 text-field-table labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed"
licence = "MIT OR Apache-2.0"
licence_file = "LICENSE-MIT"
kind = "translation"
@@ -3492,7 +3504,7 @@ usage = "Albanian UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs"
path = "crates/ui-egui/src/i18n/th.tsv"
title = "Thai interface translation catalog"
author = "PdfCraft contributors"
source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed"
source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed"
licence = "MIT OR Apache-2.0"
licence_file = "LICENSE-MIT"
kind = "translation"
@@ -3502,7 +3514,7 @@ usage = "Thai UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs"
path = "crates/ui-egui/src/i18n/ca.tsv"
title = "Catalan interface translation catalog"
author = "PdfCraft contributors"
source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, written from their meaning; no proprietary localisation resources; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 text-field-table labels are contributor-original AI-assisted translations from English, not separately native-reviewed"
source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, written from their meaning; no proprietary localisation resources; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 text-field-table labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed"
licence = "MIT OR Apache-2.0"
licence_file = "LICENSE-MIT"
kind = "translation"
Generated
+197 -105
View File
@@ -4,9 +4,9 @@ version = 4
[[package]]
name = "accesskit"
version = "0.24.1"
version = "0.25.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d3b7f7f85a7e5f68090000ed7622545829afd484d210358702ae4cb97dd0c320"
checksum = "ad442f58ee04714aaa0ba0a2768c1ea1935b29507bb22ddece8cbbc76db02932"
dependencies = [
"enumn",
"serde",
@@ -15,57 +15,51 @@ dependencies = [
[[package]]
name = "accesskit_atspi_common"
version = "0.18.1"
version = "0.21.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e8c61bee90b42a772d39d06a740207dc71a4e780004ace1db8d99fb1baaa954"
checksum = "52c182f9c282ac9c5638d876d551d15e5f7d397ec263349a0c6a2b61595dd5e4"
dependencies = [
"accesskit",
"accesskit_consumer 0.36.0",
"accesskit_consumer",
"atspi-common",
"phf 0.13.1",
"phf 0.14.0",
"serde",
"zvariant",
]
[[package]]
name = "accesskit_consumer"
version = "0.35.0"
version = "0.39.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "53cf47daed85312e763fbf85ceca136e0d7abc68e0a7e12abe11f48172bc3b10"
checksum = "8a45e2bb300bea6d5f33a82c3e051c3ddc6f41c209750f68a0acbe991a284344"
dependencies = [
"accesskit",
"hashbrown 0.16.1",
"hashbrown 0.17.1",
]
[[package]]
name = "accesskit_consumer"
version = "0.36.0"
name = "accesskit_ios"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "25e0d7e25d06f4dc21d1774d67146e9e80d6789216cbd4d1e88185b0095dba60"
checksum = "28e539d64b27fd4c14de8f78ada8f7c944c092f52f7e49fb63316507a57f6937"
dependencies = [
"accesskit",
"hashbrown 0.16.1",
]
[[package]]
name = "accesskit_consumer"
version = "0.38.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5d10a236f96f87d70732e44520046785431ef01d5bcd6b041317bfadd2f88245"
dependencies = [
"accesskit",
"hashbrown 0.16.1",
"accesskit_consumer",
"hashbrown 0.17.1",
"objc2 0.5.2",
"objc2-foundation 0.2.2",
"objc2-ui-kit 0.2.2",
]
[[package]]
name = "accesskit_macos"
version = "0.26.3"
version = "0.27.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ce02dc63b43f0c9296af9ac946312a2dc8814427d7a64d2d600971dac55b6076"
checksum = "5701624bf6a11efb6d4c8e922bf44126ed96250e5faa9a7a0468c979635839a4"
dependencies = [
"accesskit",
"accesskit_consumer 0.38.0",
"hashbrown 0.16.1",
"accesskit_consumer",
"hashbrown 0.17.1",
"objc2 0.5.2",
"objc2-app-kit 0.2.2",
"objc2-foundation 0.2.2",
@@ -73,9 +67,9 @@ dependencies = [
[[package]]
name = "accesskit_unix"
version = "0.21.1"
version = "0.24.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b016ca8db0ea0ea2ceff29a9d6240391492d960716aa471967c00e8cc8cb197c"
checksum = "202f24df034a7476d07b7f74284de84f6d62aabd858dbe7ee9cad3b7ad6f8f9d"
dependencies = [
"accesskit",
"accesskit_atspi_common",
@@ -91,13 +85,13 @@ dependencies = [
[[package]]
name = "accesskit_windows"
version = "0.32.1"
version = "0.35.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "eff7009f1a532e917d66970a1e80c965140c6cfbbabbdde3d64e5431e6c78e21"
checksum = "ce63f35d6bdcf59f26b76b3379063f738e6412cef46999cc772d46aa3de35adb"
dependencies = [
"accesskit",
"accesskit_consumer 0.35.0",
"hashbrown 0.16.1",
"accesskit_consumer",
"hashbrown 0.17.1",
"static_assertions",
"windows",
"windows-core",
@@ -105,11 +99,12 @@ dependencies = [
[[package]]
name = "accesskit_winit"
version = "0.32.2"
version = "0.34.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fe9a94394896352cc4660ca2288bd4ef883d83238853c038b44070c8f134313"
checksum = "ee96dd150375c05912d8a473f98c2fb155fb3234fac88292d396548a2460fa77"
dependencies = [
"accesskit",
"accesskit_ios",
"accesskit_macos",
"accesskit_unix",
"accesskit_windows",
@@ -235,6 +230,7 @@ dependencies = [
"parking_lot",
"percent-encoding",
"windows-sys 0.60.2",
"wl-clipboard-rs",
"x11rb",
]
@@ -1150,8 +1146,9 @@ source = "git+https://github.com/storytold/craft-libs?rev=82a24b006eefa036b43c09
[[package]]
name = "craft-print"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=666c358065261a2816b376fa3bb10538dbf53040#666c358065261a2816b376fa3bb10538dbf53040"
source = "git+https://github.com/storytold/craft-libs?rev=25da1314d443171b4adeaad2cd9454b273f35c6f#25da1314d443171b4adeaad2cd9454b273f35c6f"
dependencies = [
"craft-winprint-gdi",
"miniz_oxide 0.8.9",
"roxmltree",
"tempfile",
@@ -1162,7 +1159,7 @@ dependencies = [
[[package]]
name = "craft-quit"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=f58bc1a3df490992d633393d0898af0588ce882c#f58bc1a3df490992d633393d0898af0588ce882c"
source = "git+https://github.com/storytold/craft-libs?rev=25da1314d443171b4adeaad2cd9454b273f35c6f#25da1314d443171b4adeaad2cd9454b273f35c6f"
dependencies = [
"dispatch2",
"egui",
@@ -1174,12 +1171,20 @@ dependencies = [
[[package]]
name = "craft-ui"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=5c874d51eeb3de70e735c8ce87a59a7dedd47675#5c874d51eeb3de70e735c8ce87a59a7dedd47675"
source = "git+https://github.com/storytold/craft-libs?rev=25da1314d443171b4adeaad2cd9454b273f35c6f#25da1314d443171b4adeaad2cd9454b273f35c6f"
dependencies = [
"egui",
"serde",
]
[[package]]
name = "craft-winprint-gdi"
version = "0.1.0"
source = "git+https://github.com/storytold/winprint.rs?rev=417ac3c4d14d3da5485a99c7d5ce8f05664ec312#417ac3c4d14d3da5485a99c7d5ce8f05664ec312"
dependencies = [
"windows-sys 0.61.2",
]
[[package]]
name = "crc32fast"
version = "1.5.2"
@@ -1243,9 +1248,9 @@ checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5"
[[package]]
name = "crypto-bigint"
version = "0.7.5"
version = "0.7.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1a52aa3fcda4e6302a9f48734f234d35d4721b96f8fe07d073f07ce9df4f0271"
checksum = "6bb08299a6046833a879ace115697f12fd2bd6c8d3e93c909ffc9e0738e7cae0"
dependencies = [
"cpubits",
"ctutils",
@@ -1535,9 +1540,8 @@ dependencies = [
[[package]]
name = "ecolor"
version = "0.36.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0656a7530b9e2841ee7a5f983965bdd9840c32f4012f759cfd44b912cced6b34"
version = "0.37.0"
source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a"
dependencies = [
"bytemuck",
"emath",
@@ -1568,9 +1572,8 @@ dependencies = [
[[package]]
name = "eframe"
version = "0.36.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "55ad41fac6e3149abb4866e93df37dbd33baa95db525c3368c944584e95a5dc2"
version = "0.37.0"
source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a"
dependencies = [
"ahash",
"bytemuck",
@@ -1594,6 +1597,7 @@ dependencies = [
"profiling",
"raw-window-handle",
"ron",
"send_wrapper",
"serde",
"static_assertions",
"wasm-bindgen",
@@ -1606,9 +1610,8 @@ dependencies = [
[[package]]
name = "egui"
version = "0.36.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dc938cc27cd911415e1e4d151bc56ff9df063d8db081374e87aeb805ea74b2ba"
version = "0.37.0"
source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a"
dependencies = [
"accesskit",
"ahash",
@@ -1628,7 +1631,8 @@ dependencies = [
[[package]]
name = "egui-wgpu"
version = "0.36.2"
version = "0.37.0"
source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a"
dependencies = [
"ahash",
"bytemuck",
@@ -1646,32 +1650,35 @@ dependencies = [
[[package]]
name = "egui-winit"
version = "0.36.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "98466000559d66ba4db786a30448b01483946add4188e7f10f522a27b4fb89cc"
version = "0.37.0"
source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a"
dependencies = [
"accesskit_winit",
"arboard",
"block2 0.6.2",
"bytemuck",
"egui",
"image",
"log",
"objc2 0.6.4",
"objc2-app-kit 0.3.2",
"objc2-foundation 0.3.2",
"objc2-ui-kit 0.3.2",
"parking_lot",
"profiling",
"raw-window-handle",
"serde",
"smithay-clipboard",
"web-time",
"webbrowser",
"windows-sys 0.61.2",
"winit",
]
[[package]]
name = "egui_extras"
version = "0.36.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "05cbdc785020861553f230f23d330ba1fb72613b9d8e0e457f3bdc8ba6db6dcf"
version = "0.37.0"
source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a"
dependencies = [
"ahash",
"egui",
@@ -1684,9 +1691,8 @@ dependencies = [
[[package]]
name = "egui_glow"
version = "0.36.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "606ed4167daf341e5753d703285c4c1d562324b2c07aa8f405cd7d066fe58f3b"
version = "0.37.0"
source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a"
dependencies = [
"bytemuck",
"egui",
@@ -1698,9 +1704,8 @@ dependencies = [
[[package]]
name = "egui_kittest"
version = "0.36.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5eb3f3effb2726fee23449293e67acbf6cc6ce35525b1722bd5743bb348114d5"
version = "0.37.0"
source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a"
dependencies = [
"eframe",
"egui",
@@ -1742,9 +1747,8 @@ dependencies = [
[[package]]
name = "emath"
version = "0.36.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "52c8d4141cf0f60fb2f7aefaf352d3ffa5171ef0ab09731c64391801e95e48f1"
version = "0.37.0"
source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a"
dependencies = [
"bytemuck",
"serde",
@@ -1772,22 +1776,22 @@ checksum = "66b7e2430c6dff6a955451e2cfc438f09cea1965a9d6f87f7e3b90decc014099"
[[package]]
name = "enum-map"
version = "2.7.3"
version = "3.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6866f3bfdf8207509a033af1a75a7b08abda06bbaaeae6669323fd5a097df2e9"
checksum = "d4532960034c15ba2f55e9eee631040ecc473c32e6c4b200828c759840f13a06"
dependencies = [
"enum-map-derive",
]
[[package]]
name = "enum-map-derive"
version = "0.17.0"
version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f282cfdfe92516eb26c2af8589c274c7c17681f5ecc03c18255fe741c6aa64eb"
checksum = "7127272f64b3e098f7d81f350d672081b879bff896d219c42370dc858b1af9ff"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
"syn 3.0.6",
]
[[package]]
@@ -1824,9 +1828,8 @@ dependencies = [
[[package]]
name = "epaint"
version = "0.36.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a0ec0308dc23130fc1a7d4623a8534c2ed069c6dc84e258ee4f3de99615aa1a3"
version = "0.37.0"
source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a"
dependencies = [
"ahash",
"bytemuck",
@@ -1843,16 +1846,17 @@ dependencies = [
"serde",
"skrifa 0.44.0",
"smallvec",
"unicode-bidi",
"unicode-general-category",
"unicode-properties",
"unicode-segmentation",
"vello_cpu 0.1.0",
"vello_cpu 0.2.0",
]
[[package]]
name = "epaint_default_fonts"
version = "0.36.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "773fa9c96dd0dbef887e39d0ed6177f141cce4d68e6041df77570aa3702dfa13"
version = "0.37.0"
source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a"
[[package]]
name = "equator"
@@ -1887,7 +1891,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
dependencies = [
"libc",
"windows-sys 0.60.2",
"windows-sys 0.61.2",
]
[[package]]
@@ -2068,6 +2072,12 @@ version = "1.0.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1"
[[package]]
name = "foldhash"
version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2"
[[package]]
name = "foldhash"
version = "0.2.0"
@@ -2318,7 +2328,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d99fc21d493812643aae86d53b7bbd02f376434a90317e8a790bc209fdd6605e"
dependencies = [
"bytemuck",
"foldhash",
"foldhash 0.2.0",
"hashbrown 0.17.1",
"log",
"peniko",
@@ -2330,18 +2340,18 @@ dependencies = [
[[package]]
name = "glifo"
version = "0.2.0"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ed4a1bb24121291d27230c1b1b44e07d6a9b28cefdb32fe1581dfb84e14f940a"
checksum = "282a26c1e23de04bdab3e34a21b6f877a479b96737792516b9b8b8f69b6661be"
dependencies = [
"bytemuck",
"foldhash",
"foldhash 0.2.0",
"hashbrown 0.17.1",
"log",
"peniko",
"skrifa 0.44.0",
"smallvec",
"vello_common 0.1.0",
"vello_common 0.2.0",
]
[[package]]
@@ -2505,6 +2515,15 @@ version = "0.14.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1"
[[package]]
name = "hashbrown"
version = "0.15.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1"
dependencies = [
"foldhash 0.1.5",
]
[[package]]
name = "hashbrown"
version = "0.16.1"
@@ -2513,7 +2532,7 @@ checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100"
dependencies = [
"allocator-api2",
"equivalent",
"foldhash",
"foldhash 0.2.0",
]
[[package]]
@@ -2524,7 +2543,7 @@ checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"
dependencies = [
"allocator-api2",
"equivalent",
"foldhash",
"foldhash 0.2.0",
]
[[package]]
@@ -2591,8 +2610,6 @@ dependencies = [
[[package]]
name = "hayro-postscript"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "885c5ef0654933139a9b9546fc2c69e18d37f38aa2520f079092b1be18f1fcaa"
[[package]]
name = "hayro-syntax"
@@ -3067,12 +3084,12 @@ checksum = "e2db585e1d738fc771bf08a151420d3ed193d9d895a36df7f6f8a9456b911ddc"
[[package]]
name = "kittest"
version = "0.4.0"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "90ceaa75eb0036a32b6b9833962eb18137449e9817e2e586006471925b727fd5"
checksum = "0bb81a721ba76aa095b7f45deb180504f786904e56ca4b8e141f66eb89a78b75"
dependencies = [
"accesskit",
"accesskit_consumer 0.35.0",
"accesskit_consumer",
]
[[package]]
@@ -3306,7 +3323,7 @@ dependencies = [
"objc2-foundation 0.3.2",
"png 0.18.1",
"thiserror 2.0.21",
"windows-sys 0.60.2",
"windows-sys 0.61.2",
]
[[package]]
@@ -3848,6 +3865,16 @@ dependencies = [
"pin-project-lite",
]
[[package]]
name = "os_pipe"
version = "1.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967"
dependencies = [
"libc",
"windows-sys 0.61.2",
]
[[package]]
name = "p256"
version = "0.14.0"
@@ -4235,9 +4262,11 @@ dependencies = [
"pdfcraft-annot",
"pdfcraft-content",
"pdfcraft-cos",
"pdfcraft-filters",
"pdfcraft-model",
"pdfcraft-render",
"thiserror 2.0.21",
"zune-jpeg",
]
[[package]]
@@ -4407,6 +4436,7 @@ dependencies = [
"wasm-bindgen",
"wasm-bindgen-futures",
"web-sys",
"web-time",
"winsafe",
"xattr",
]
@@ -4496,6 +4526,17 @@ version = "2.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220"
[[package]]
name = "petgraph"
version = "0.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8701b58ea97060d5e5b155d383a69952a60943f0e6dfe30b04c287beb0b27455"
dependencies = [
"fixedbitset",
"hashbrown 0.15.5",
"indexmap",
]
[[package]]
name = "phf"
version = "0.13.1"
@@ -4504,7 +4545,6 @@ checksum = "c1562dc717473dbaa4c1f85a36410e03c047b2e7df7f45ee938fbef64ae7fadf"
dependencies = [
"phf_macros 0.13.1",
"phf_shared 0.13.1",
"serde",
]
[[package]]
@@ -4515,6 +4555,7 @@ checksum = "010378780309880b08997fae13be7834dba947d36393bd372f2b1556deb2a2f6"
dependencies = [
"phf_macros 0.14.0",
"phf_shared 0.14.0",
"serde",
]
[[package]]
@@ -4969,7 +5010,7 @@ dependencies = [
"once_cell",
"socket2",
"tracing",
"windows-sys 0.60.2",
"windows-sys 0.61.2",
]
[[package]]
@@ -5519,7 +5560,7 @@ dependencies = [
"errno",
"libc",
"linux-raw-sys 0.12.1",
"windows-sys 0.60.2",
"windows-sys 0.61.2",
]
[[package]]
@@ -5589,7 +5630,7 @@ dependencies = [
"security-framework",
"security-framework-sys",
"webpki-root-certs",
"windows-sys 0.60.2",
"windows-sys 0.61.2",
]
[[package]]
@@ -5719,6 +5760,12 @@ version = "1.0.28"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd"
[[package]]
name = "send_wrapper"
version = "0.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cd0b0ec5f1c1ca621c432a25813d8d60c88abe6d3e08a3eb9cf37d97a0fe3d73"
[[package]]
name = "serde"
version = "1.0.229"
@@ -6244,7 +6291,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4"
dependencies = [
"libc",
"windows-sys 0.60.2",
"windows-sys 0.61.2",
]
[[package]]
@@ -6466,7 +6513,7 @@ dependencies = [
"getrandom 0.3.4",
"once_cell",
"rustix 1.1.5",
"windows-sys 0.60.2",
"windows-sys 0.61.2",
]
[[package]]
@@ -6800,6 +6847,17 @@ dependencies = [
"once_cell",
]
[[package]]
name = "tree_magic_mini"
version = "3.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b8765b90061cba6c22b5831f675da109ae5561588290f9fa2317adab2714d5a6"
dependencies = [
"memchr",
"nom",
"petgraph",
]
[[package]]
name = "try-lock"
version = "0.2.5"
@@ -6835,7 +6893,7 @@ checksum = "f2f6fb2847f6742cd76af783a2a2c49e9375d0a111c7bef6f71cd9e738c72d6e"
dependencies = [
"memoffset",
"tempfile",
"windows-sys 0.60.2",
"windows-sys 0.61.2",
]
[[package]]
@@ -7025,9 +7083,9 @@ dependencies = [
[[package]]
name = "vello_common"
version = "0.1.0"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b2e9aed918117e8152c9eddfd8362d73c465c23f26c44786aa331707b8a64fa2"
checksum = "bbb2141a2bca6e6d598e471fd4d1d7eed8e020aad6a28187edda07f091a325dd"
dependencies = [
"bytemuck",
"fearless_simd",
@@ -7053,14 +7111,14 @@ dependencies = [
[[package]]
name = "vello_cpu"
version = "0.1.0"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ac7349e1f55f6b801c7c277958df4ea53e7f20f21e8014910ad888b2ecda93ea"
checksum = "ace506ca414548966fcf3c283be94eb1cad8254de488791ee698bf438b0890a9"
dependencies = [
"bytemuck",
"glifo 0.2.0",
"glifo 0.3.0",
"hashbrown 0.17.1",
"vello_common 0.1.0",
"vello_common 0.2.0",
]
[[package]]
@@ -7549,7 +7607,7 @@ version = "0.1.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
dependencies = [
"windows-sys 0.60.2",
"windows-sys 0.61.2",
]
[[package]]
@@ -7832,6 +7890,7 @@ checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650"
[[package]]
name = "winit"
version = "0.30.13"
source = "git+https://github.com/storytold/winit.git?rev=a517b3846ee8457d84ee4975110bfda6797c44dc#a517b3846ee8457d84ee4975110bfda6797c44dc"
dependencies = [
"ahash",
"android-activity",
@@ -7930,6 +7989,24 @@ version = "0.57.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e"
[[package]]
name = "wl-clipboard-rs"
version = "0.9.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4d7888ccd4896447b2d14d3a9350a85df2aeb6f181e2e7a31349d104ac46cac1"
dependencies = [
"libc",
"log",
"os_pipe",
"rustix 1.1.5",
"thiserror 2.0.21",
"tree_magic_mini",
"wayland-backend",
"wayland-client",
"wayland-protocols",
"wayland-protocols-wlr",
]
[[package]]
name = "wnaf"
version = "0.14.1"
@@ -8370,3 +8447,18 @@ dependencies = [
"syn 3.0.6",
"winnow",
]
[[patch.unused]]
name = "egui_demo_lib"
version = "0.37.0"
source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a"
[[patch.unused]]
name = "egui_inspection"
version = "0.37.0"
source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a"
[[patch.unused]]
name = "egui_system_font_provider"
version = "0.37.0"
source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a"
+30 -9
View File
@@ -13,11 +13,11 @@ repository = "https://github.com/storytold/pdfcraft"
[workspace.dependencies]
# Shared frontend components; engines remain independent of egui.
craft-ui = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "5c874d51eeb3de70e735c8ce87a59a7dedd47675", features = ["serde"] }
craft-ui = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "25da1314d443171b4adeaad2cd9454b273f35c6f", features = ["serde"] }
# Quit the macOS way (#1136): ⌘Q asks about unsaved changes, and closing quits through `terminate:`.
craft-quit = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "f58bc1a3df490992d633393d0898af0588ce882c" }
craft-quit = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "25da1314d443171b4adeaad2cd9454b273f35c6f" }
# Shared system spooler; document composition remains in pdfcraft-print.
craft-print = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "666c358065261a2816b376fa3bb10538dbf53040" }
craft-print = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "25da1314d443171b4adeaad2cd9454b273f35c6f" }
# Whether a path stored in a document may be opened (GoToR link targets).
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "82a24b006eefa036b43c09a67fb9a3fbd17ffe63" }
# internal
@@ -75,11 +75,13 @@ chrono = { version = "0.4.45", default-features = false, features = ["std"] }
proptest = "1"
# ui
egui = "0.36"
egui_extras = { version = "0.36", default-features = false, features = ["svg"] }
eframe = { version = "0.36", default-features = false }
egui_kittest = "0.36"
egui = "0.37"
egui_extras = { version = "0.37", default-features = false, features = ["svg"] }
eframe = { version = "0.37", default-features = false }
egui_kittest = "0.37"
rfd = "0.17"
# Monotonic time for logic-only work on native and web (`App::logic` runs without a UI pass).
web-time = "1.1"
[workspace.lints.rust]
unsafe_code = "forbid"
@@ -115,8 +117,27 @@ hayro-interpret = { path = "vendor/hayro-interpret" }
hayro = { path = "vendor/hayro" }
hayro-syntax = { path = "vendor/hayro-syntax" }
hayro-cmap = { path = "vendor/hayro-cmap" }
hayro-postscript = { path = "vendor/hayro-postscript" }
hayro-jbig2 = { path = "vendor/hayro-jbig2" }
lopdf = { path = "vendor/lopdf" }
winit = { path = "vendor/winit" }
egui-wgpu = { path = "vendor/egui-wgpu" }
vello_common = { path = "vendor/vello_common" }
# The egui and winit crates below are pinned to immutable storytold git revisions (egui
# 6d518fc799681571963842f95b55a6b68431b15a, winit a517b3846ee8457d84ee4975110bfda6797c44dc).
# Only the retained `vendor/winit` and `vendor/egui-wgpu` copies are provenance for the app's
# earlier patches and their source guards, not path patches; the other `vendor/` entries above
# remain real path patches. See vendor/README.md and the migration plan.
ecolor = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
emath = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
epaint = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
eframe = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" }
+18
View File
@@ -58,3 +58,21 @@ dependencies change (plan/adr/0002, 0006).
Vendored (vendor/, patched; see vendor/README.md):
- hayro 0.7.1 — Apache-2.0 OR MIT, Copyright the hayro authors (licence files kept in vendor/hayro).
- hayro-interpret 0.7.0 — Apache-2.0 OR MIT, Copyright the hayro authors (LICENSE-APACHE, LICENSE-MIT kept in vendor/hayro-interpret).
Bundled egui font icons
The pinned egui dependency includes egui-icons.ttf, a small subset of John Slegers'
emoji-icon-font, through default_fonts. The parent emoji-icon-font.ttf face is
included through monochrome_emoji_fonts. Their upstream project is
https://github.com/jslegers/emoji-icon-font; both use the same exact copyright
and permission notice below.
MIT License
Copyright (c) 2014 John Slegers
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+55 -4
View File
@@ -2,7 +2,13 @@
**Stage: alpha** · next: beta, ~25% (ready for real work 50% → 75%) and ~400–700 h away
> **Last reviewed:** 2026-10-22 · **Last updated:** 2026-10-22 · **Change:** minor (M14, #3558: rebase guarded macOS per-file association recovery onto current main; estimates unchanged)
> **Last reviewed:** 2026-10-25 | **Last updated:** 2026-10-25 | **Change:** minor (M14 localization current state: Arabic logical catalog, explicit RTL label direction and mirrored stock chrome; native/browser RTL workflows unqualified. Native release Hans face via LXGW WenKai Lite; estimates unchanged)
> **Last reviewed:** 2026-10-23 · **Last updated:** 2026-10-23 · **Change:** minor (M7, #2636 partial: pasting added text boxes and images in the engine and through `content_copy`; estimates unchanged)
> **Last reviewed:** 2026-10-23 · **Last updated:** 2026-10-23 · **Change:** minor (M11: image optimization accounts for page-local UserUnit; estimates unchanged)
> **Last reviewed:** 2026-10-23 | **Last updated:** 2026-10-23 | **Change:** minor (M10: Word table cells use the widths of their own grid columns; estimates unchanged)
> **Last reviewed:** 2026-10-23 | **Last updated:** 2026-10-23 | **Change:** minor (M10: table spans retain text from covered slots in Office exports; estimates unchanged)
> **Last reviewed:** 2026-10-23 · **Last updated:** 2026-10-23 · **Change:** minor (M10: image export preserves soft-mask Decode opacity ranges; estimates unchanged)
> **Last reviewed:** 2026-10-23 · **Last updated:** 2026-10-23 · **Change:** minor (M10: vector printing preserves existing page XObjects when adding annotation appearances; estimates unchanged)
> **Last reviewed:** 2026-10-21 · **Last updated:** 2026-10-21 · **Change:** minor (M3, #3808: the Pages inspector has an independent 50–150% thumbnail size slider and buttons; selection and current-page following are retained, with headless ui.set coverage. Estimates unchanged.)
> **Last reviewed:** 2026-10-20 | **Last updated:** 2026-10-20 | **Change:** minor (M11 #3507: image merging preserves content stream boundaries; estimates unchanged)
> **Last reviewed:** 2026-10-20 | **Last updated:** 2026-10-20 | **Change:** minor (M10, #3532 partial: vector printing retains existing appearances with absent Subtype; estimates unchanged)
@@ -54,6 +60,8 @@
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-11 · **Change:** minor (architectural paper controls from #599; localized shortcut labels, #496; readiness table with hours per audience; full number as weighted sum 49%; earlier: second look: ready 40% → 47%, mainstream 55% added; core-workflow gate applied → alpha) · **Target:** Adobe Acrobat Pro (Acrobat DC, continuous track 26.002.21931, macOS)
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-11 · **Change:** minor (closed issues synced: #774, #756 and the #799–#821 batch; earlier: localized shortcut labels, #496; readiness table with hours per audience; full number as weighted sum 49%; earlier: second look: ready 40% → 47%, mainstream 55% added; core-workflow gate applied → alpha) · **Target:** Adobe Acrobat Pro (Acrobat DC, continuous track 26.002.21931, macOS)
> **Last reviewed:** 2026-10-18 - **Last updated:** 2026-10-18 - **Change:** minor (M6 #2892: Push-button normal labels are editable per widget through Options and form_set_props, independently of field names; rendering, undo/redo and incremental/full save/reopen are covered. Estimates unchanged)
> **Last reviewed:** 2026-10-18 - **Last updated:** 2026-10-18 - **Change:** minor (M12 #2589: Active XFA skips PDF-container fallback scripts while retaining requested messages and saved scripts; ordinary/static/unlaid-out documents and explicit console/field calls keep their existing behavior. Estimates unchanged)
> **Last reviewed:** 2026-10-18 - **Last updated:** 2026-10-18 - **Change:** minor (M7 #2592: Styled fallback fonts batch up to 240 glyphs per actual face and retain source styles. Budget refusal and distinct same-BaseFont descriptor weights have mutation-checked regressions; coverage and complex mixed runs remain limited. Estimates unchanged)
> **Last reviewed:** 2026-10-18 - **Last updated:** 2026-10-18 - **Change:** minor (M7 #3187: Added-image automation normalizes extreme signed rotation angles before combining them with the current orientation; integer bounds, history, pixels, save/reopen and MCP have regressions. Estimates unchanged)
> **Last reviewed:** 2026-10-18 - **Last updated:** 2026-10-18 - **Change:** minor (M12 #2569: Growable multiline XFA text reflows after edits, with undo/redo, save/reopen and print coverage; oversized fields still become read-only page text. Structured-data synchronization warnings retain accepted whitespace without relayout from stale data. Estimates unchanged)
> **Last reviewed:** 2026-10-18 - **Last updated:** 2026-10-18 - **Change:** minor (M12 #2572: Every repeated page-master button resolves its own field to the shared XFA click script, including print buttons. Estimates unchanged)
@@ -157,10 +165,10 @@ Portuguese and Spanish vs the current union). Detail and script notes: [localiza
| Language | Code | Strings | Status |
|---|---|---|---|
| English | `en` | 100% | full |
| Simplified Chinese | `zh-hans` | 97.4% | partial (no Hans UI face in releases, #826) |
| Simplified Chinese | `zh-hans` | 97.4% | partial (native LXGW WenKai Lite; no Hans face in the web build, #826) |
| Spanish | `es` | 100% of current union | partial (dialogs / tooltips; no help) |
| Hindi | `hi` | 0% | none |
| Arabic | `ar` | 100% | partial (layout not mirrored) |
| Arabic | `ar` | 100% | partial (logical catalog, explicit RTL labels, mirrored stock chrome; native/browser/IME workflows unqualified) |
| French | `fr` | 99.3% | partial |
| Portuguese (Brazil) | `pt-br` | 100% of current union | partial |
| Indonesian | `id` | 0% | none |
@@ -180,7 +188,7 @@ Ranked; detail and the full milestone table in [docs/roadmap.md](docs/roadmap.md
| Rank | Milestone | Estimate (h) |
|---|---|---|
| 0 | Convert and share: Create PDF from Office, Word export that keeps layout (#773) | 32–55 |
| 1 | Backlog and platform: crash and wrong-result reports, Chinese UI face (#826) | 50–90 |
| 1 | Backlog and platform: crash and wrong-result reports, Chinese web UI face (#826) | 50–90 |
| 2 | Fidelity harness against Acrobat and the renderer decision (M2; owner decision on #841) | 110–190 |
| 3 | Editing existing content (M7) | 100–180 |
| 4 | OCR languages and Office export/import (M10) | 95–175 |
@@ -191,7 +199,25 @@ Ranked; detail and the full milestone table in [docs/roadmap.md](docs/roadmap.md
## Progress log
- **2026-10-24 (M14, #4253):** The annotation quick bar remembers Keep tool selected across restarts, including unpinning. Old and malformed settings keep safe defaults; the opt-in UI control channel reads and changes the same preference. Estimates unchanged.
- **2026-10-23 (M7, #4280):** Edit text names each standard stand-in font after its face (`PCEdTimesBold`, ...) instead of one shared `PCEdHelv`. Rewriting a bold paragraph whose subset lacks an accent no longer repoints the paragraphs set earlier in a regular stand-in at Times-Bold, and the editor's frame stays on the paragraph being edited. Pages saved by older builds keep their shared name and are not repaired. Estimates unchanged.
- **2026-10-23 (M8, #3205 follow-up):** Phone-pattern redaction matches complete labelled Italian geographic numbers such as `Tel. +39 0426/123456`, with synthetic matcher and mark/apply/save/reopen coverage; unlabelled international slash numbers remain unsupported.
- **2026-10-23 (M7, #2636 partial):** A new `PasteContent` edit pastes an added text box or image copied in the same document or another, keeping its style, picture, turns, flips and crop, as one undo step; `content_copy` drives it headlessly. A paste lands beside earlier copies (18 pt steps) and stays on the page. A pasted image reuses its picture object in its own document and after the first paste into another; there a colour profile is dropped and CMYK colours stored losslessly are turned to RGB. The desktop keys and menus follow in separate PRs. Estimates unchanged.
- **2026-10-23 (M11, optimizer resolution):** Image downsampling includes each page's `/UserUnit` scale, preserving images already below the physical resolution threshold, including shared nested forms.
Synthetic measurement and optimization regressions cover direct and indirect units and page-local defaults.
Estimates unchanged.
- **2026-10-23 (M10, Word table widths):** Word export sizes each cell from the grid columns it spans, keeping unequal columns and cells after a merged cell consistent with the table grid.
- **2026-10-23 (M10, table continuation text):** Office exporters retain text from table slots covered by another cell's span as paragraph text.
Synthetic regressions check every input fragment survives exactly once in Word, HTML, RTF and PowerPoint, while ordinary superscripts stay in their table cells.
- **2026-10-23 (M10, image export):** Soft-mask Decode intervals preserve partial opacity in Export all images and Save Image As.
Synthetic regressions cover direct and indirect ranges, inverted/subrange alpha, packed masks, JPEG masks and unchanged image component Decode.
- **2026-10-23 (M10, print resources):** Vector printing preserves original page artwork when existing XObjects use annotation resource names.
The regression checks two distinct appearances, inherited resources, print/reopen pixels and unchanged source data.
Estimates unchanged.
- **2026-10-21 (M3, window resize and move on Wayland):** With PdfCraft's own title bar on GNOME/Wayland, a second resize by a window edge, or a second move by the empty tab strip, works straight after the first; it waited for a click inside the window, because the compositor keeps the button's release from egui. A unit test covers the release given back; checked by hand in a test build. Estimates unchanged.
- **2026-10-22 (M4, #3916 partial):** Document edits and Undo/Redo cancel an Organize page drag. Pointer-release regressions check exact page order and save/reopen.
- **2026-10-22 (M10, #3752 paper):** CUPS jobs ask for the chosen paper in every size. The 13 sizes the Print dialog sent no paper for (A6, A0–A2, ARCH, ANSI C–E) use PWG 5101.1 names, checked against a synthetic PPD with `cupsfilter`, and `doc_print` to a printer sends the paper too. The macOS tray half (Auto Select instead of the PPD's default tray) is a craft-print change that needs a pin bump here. Estimates unchanged.
- **2026-10-22 (M14, macOS association recovery candidate):** Successful desktop open/save/sign can queue recovery of an existing per-file binding to the running PDFCraft bundle through NSWorkspace. Metadata-only watcher changes retain undo and avoid false overwrite prompts; real same-length/same-mtime edits remain protected. Rebased on 0.12.0 and reuses #3042's shared atomic metadata preservation; the bounded recovery parser does not narrow save limits. Prior native Preview TEST-signature and Finder workflows passed on macOS 27.0.1; other versions remain unqualified. Estimates unchanged.
- **2026-10-13 (M7, free image rotation):** A selected page image has a rotate knob (Shift: 15 degree steps) and `image_edit` a `rotate_by` action; the angle is written as one undoable `cm`. Snapping to page edges while moving is in #1740; resize snapping is not done. Estimates unchanged.
@@ -230,6 +256,8 @@ Ranked; detail and the full milestone table in [docs/roadmap.md](docs/roadmap.md
- **2026-10-20 (M3, #3541/#3620):** Comment hover follows the individual marked lines instead of the enclosing multiline rectangle, and overlapping comments follow paint order. Synthetic UI regressions cover all four text-markup kinds, page/view rotations, neighboring highlights, legacy rectangle fallback and unchanged PDF bytes. Estimates unchanged.
- **2026-10-20 (M10, #3532 partial):** Vector printing retains existing widget artwork when its appearance lacks Subtype. A print-owned copy adds Form dispatch metadata. The source stream and all explicit subtypes stay unchanged. Synthetic source/output raster checks cover resources, selected/shared appearances, placement, flags and content modes. Appearance regeneration and physical printer validation remain outside this fix. Estimates unchanged.
- **2026-10-20 (M5, arrow keys move comments):** With a comment selected, the arrow keys move it a screen pixel and ⌘/Ctrl or Shift and an arrow ten, instead of scrolling the view or turning the page; up is up on screen at any zoom and rotation, and each press is one undo step. Text markup and locked comments stay put. Estimates unchanged.
- **2026-10-19 (M14, #3373):** The main menu and its long submenus scroll in short windows, keeping their commands reachable. Estimates unchanged.
- **2026-10-19 (M3, #3387):** Save-prompt shortcuts yield to later consent and utility dialogs; a synthetic UI regression checks that an edited document stays open. Estimates unchanged.
@@ -248,6 +276,8 @@ Ranked; detail and the full milestone table in [docs/roadmap.md](docs/roadmap.md
- **2026-10-18 (M6, #2892):** Push-button normal labels are editable per widget through Options and form_set_props, independently of field names; rendering, undo/redo and incremental/full save/reopen are covered. Estimates unchanged.
- **2026-10-18 (M7, #3212):** Headers, Bates numbers, watermarks and added text stay visible after unfinished marked content, with original content preserved.
- **2026-10-18 (M12, #2589):** Active XFA skips PDF-container fallback scripts while retaining requested messages and saved scripts; ordinary/static/unlaid-out documents and explicit console/field calls keep their existing behavior. Estimates unchanged.
- **2026-10-18 (M7, #2592):** Styled fallback fonts batch up to 240 glyphs per actual face and retain source styles. Budget refusal and distinct same-BaseFont descriptor weights have mutation-checked regressions; coverage and complex mixed runs remain limited. Estimates unchanged.
- **2026-10-18 (M7, #3187):** Added-image automation normalizes extreme signed rotation angles before combining them with the current orientation; integer bounds, history, pixels, save/reopen and MCP have regressions. Estimates unchanged.
- **2026-10-18 (M12, #2569):** Growable multiline XFA text reflows after edits, with undo/redo, save/reopen and print coverage; oversized fields still become read-only page text. Structured-data synchronization warnings retain accepted whitespace without relayout from stale data. Estimates unchanged.
- **2026-10-18 (M12, #2572):** Every repeated page-master button resolves its own field to the shared XFA click script, including print buttons. Estimates unchanged.
@@ -275,6 +305,8 @@ Ranked; detail and the full milestone table in [docs/roadmap.md](docs/roadmap.md
- **2026-10-16 (M7, #2140):** Header & footer (and Bates numbering, which uses the same dialog) can shrink the page content so the header and footer don't cover it: the original content is scaled evenly into the band they leave free, centred across, also on rotated pages; Remove and Update take the scaling away, and margins that leave no room are refused. Dialog checkbox with a preview of the band, `shrink` on `doc_header_footer`, all catalogs. Annotations and added text and images are not moved yet. Estimates unchanged.
- **2026-10-20 (M14, Spanish catalog gaps):** `es.tsv` gains the 143 `(context, English)` keys the other catalogs carried and it was missing, so Spanish covers the whole bundled key union like Lithuanian and Vietnamese: calendar months and weekdays, the `certificate` context, X.509 key usages, signature-revision and digital-ID lines, password validation, eight plural messages, the combine-from-folder strings, the rendering and stale-file notices and the shortcut-spelled tooltips. Counts in `localization-parity.md` re-measured against the current union (`vi` restated against it for the same reason). Status stays `partial`: no translated help, and OS details stay outside the catalog. Estimates unchanged.
- **2026-10-16 (M14, localization):** Czech goes from menus-and-dialogs to the whole surface: 2,674 entries after adding the ~220 keys the other catalogs had -- the sentences the engine words (signature details, accessibility findings and report, PDF/A problems, pages to print, history labels), the date picker's weekday heads, the certificate viewer's fields and shared buttons. "Tag" is *tag* throughout (the Tags panel said *značky*, which is also a redaction mark), and "{n} tags" no longer reads "1 značek". Two new catalog tests. Estimates unchanged.
- **2026-10-16 (M5, #2583, #1869):** A sticky note on a page with `/Rotate` is drawn upright, with its top-left where it was placed. Notes are saved with the NoRotate flag, and the renderer now honours it: the appearance is turned against the page's rotation about the upper-left corner of `/Rect`, which stays put (ISO 32000-2 §12.5.3; vendored hayro-interpret patch 37). Attachment icons follow the same rule. Selection, hover, the edit composer, the Comments panel's flash and the `comment_list` and `doc_info` rectangles use the drawn box, and `comment_add` anchors an icon's displayed top-left at `at`. Estimates unchanged.
- **2026-10-16 (M11, #1201):** Optimize decodes a JPEG with its colour transform: an Adobe APP14 marker's flag, else the filter's `/ColorTransform` (ISO 32000-2 §7.4.8). An RGB JPEG stored untransformed (`/ColorTransform 0`, no marker) used to be converted from YCbCr anyway and came out in other colours, recompressed or merged from strips; it now keeps them. A JPEG whose marker and `/ColorTransform` disagree, or whose components are named R, G and B without `/ColorTransform 0`, is left as it is, since readers differ on it. Estimates unchanged.
- **2026-10-15 (M2, gap 12):** `cargo xtask text-oracle` scores reading order as well as word F1: the longest common subsequence of the two word sequences over the longer one. F1 is a bag of words and cannot see order at all -- measuring #2431, a change that moves text and nothing else, it called 26 of the 29 files whose output changed identical, where the order score separated 18 improvements from 6 regressions. Reports, does not gate; a disagreement with Poppler, not a verdict. Estimates unchanged.
- **2026-10-15 (M2, #2305 follow-up):** WinAnsiEncoding 0xA0 and 0xAD and MacRomanEncoding 0xCA extract as the ordinary space and hyphen Annex D.2 names them, in the vendored hayro tables (patch 30) as well as `crates/fonts`, so search, copy and redaction see characters that were hidden behind U+00A0 and U+00AD. Across the pdf.js corpus the soft hyphens we extract fall 117 to 13 and the non-breaking spaces 30 to 26; the rest come from `/ToUnicode`. An explicit `/Differences` name keeps its glyph list value, as pdftotext does. Estimates unchanged.
- **2026-10-15 (M12, XFA, #2574):** A `pageArea` with no `<occur>` repeats without limit instead of taking a subform's default of one use, so a later page area with `occur max="1"` is no longer drawn (with a copy of its fields) over every body page. A page area's `occur min` is honoured too: one the body never reached gets the pages it still needs after the body (the once-only closing page of a form, with its button, comes last). Acrobat Pro also puts that page last, and when printing keeps it but leaves it blank (`relevant="-print"` on the page area), which PdfCraft does not do yet; both re-observed on a synthetic fixture, see the 2026-10-19 line. Synthetic regression tests. Estimates unchanged.
@@ -301,6 +333,7 @@ Ranked; detail and the full milestone table in [docs/roadmap.md](docs/roadmap.md
- **2026-10-22 (M14, JPEG and TIFF export):** Export ▸ Image as JPEG or TIFF refuses a raster that is not exactly width × height pixels, as PNG export has since #2425. A raster a pixel short panicked inside the JPEG and TIFF encoders, and a partial pixel at the end was dropped and the rest written as a valid image. Rendered pages are always the right size, so what exports is unchanged. Estimates unchanged.
- **2026-10-13 (G14, Vietnamese localization):** Added Vietnamese (`vi`, Tiếng Việt) as an interface and date language with a 2,591-entry catalog (`plural_none`) covering 100% of the current localizable key union (plus `theme`/`Appearance`). Locale tags `vi` / `vi-VN` / `vi_VN.UTF-8` resolve; calendar months use numeric `Tháng 1`…`12` / `tháng 1`…`12`. Native-speaker community review recorded. The twelve-language localization mean moves from ≈59% to ≈68%; weighted readiness ≈49% → ≈50%. Status stays `partial`: engine/OS details, document contents, filenames, CLI/MCP and external help stay outside the catalog by design.
- **2026-10-12 (M10, Edit on a scanned page):** Turning Edit on (its tab, Edit text & images or Add text) for a scanned page (an image covering at least half of a page with no text of its own; comments and text boxes over it do not count) recognizes the page first, like Acrobat's "Converting scanned page to Editable Text and Images", so its words open for editing. Once per page per window, one undoable "Recognize text" step, with the language of the Recognize Text dialog (English only for now, gap 7). Pages with real text (a flyer with a background picture), read-only files and other tools are left alone. The photographs on a scan are still part of the one page image.
- **2026-10-13 (M3, typed zoom):** The right rail's zoom percentage is an editable field: type 150, 150% or 62.5 % and press Enter, Escape discards, and nonsense keeps the current zoom. The control channel's zoom option shares its parser, which now refuses zero, negative and non-finite values.
- **2026-10-13 (M4, indirect page rotation):** Rotation queries and edits resolve indirect integer values on pages and their page-tree ancestors. Turning a page already at 270° by 90° now saves it at 0°, including when its rotation is inherited. Synthetic full/incremental save-and-reopen tests cover nested inheritance, sibling preservation, negative/large angles and invalid-value fallback. Estimates unchanged.
- **2026-10-14 (M1, Flate fallback):** Raw deflate whose first bytes resemble a zlib header no longer loses a decoding-limit error during fallback. Strict and tolerant filter regressions and a COS stream regression cover refusal at the caller limit and successful decoding within it. No parity status or estimate changes.
@@ -348,6 +381,9 @@ Ranked; detail and the full milestone table in [docs/roadmap.md](docs/roadmap.md
- **2026-10-15 (community, M14, Polish signature panel):** A Polish signature panel listed its details in English: the catalog lacked every signature wording, the changes after signing they name and 34 UI literals. All 101 are translated; `polish_covers_ui_literals` and `polish_says_what_a_signature_says` keep them so. Estimates unchanged.
- **2026-10-14 (M14, Finnish localization):** Added Finnish as another interface and date language, with a 2,674-entry catalog covering every key of the other bundled catalogs and two-form plurals (partitive after numbers other than 1). Calendar dates use partitive month names (`14. lokakuuta 2026`). Coverage tests check commands/tools, scanned UI literals and bundled catalog keys. AI-assisted; native proofreading pending.
- **2026-10-14 (M14, Catalan localization):** Added Catalan as another interface and date language, with a 2,592-entry clean-room catalog, one/other plurals and coverage tests for commands, tools, UI literals and every key in the other catalogs. A native Catalan speaker (the contributor) has reviewed the translation. Estimates unchanged.
- **2026-10-15 (M3, #1248):** A fresh install follows the desktop's appearance: the theme preference defaults to System (dark on a dark desktop, Light where the desktop says nothing); saved settings and `--theme` still win. Dark page rendering is Reading colours, and the page reading themes are #1732.
- **2026-10-15 (M3, #1767):** Restore last view settings when reopening documents, as Acrobat's preference does: a file opened again shows the page, zoom and page display it was last shown with (remembered for the last 100 files when a tab closes or settings are saved), over the file's own initial view; on by default, Preferences ▸ Documents and view turns it off.
- **2026-10-13 (M3, native-opening candidate):** Chosen tools survive preparation, conversion and password retries; startup intake waits for pending preparation. Regression tests cover completion, cancellation and document identity. Estimates unchanged.
- **2026-10-13 (community, M3, #531 touchpad momentum):** On Wayland a two-finger swipe keeps gliding after the fingers lift and slows to a stop, measured from the gesture's last 0.1 s and decaying with a 0.35 s time constant through the #759 1:1 path. Any wheel input, click, key, zoom or edge ends it (fingers resting on the touchpad don't yet: the vendored winit binds no Wayland hold gestures); single-page paging, macOS (which sends its own momentum), the web, and Animation effects Off never glide. Unit tests for the physics and two headless view tests. Estimates unchanged.
- **2026-10-13 (M3, native-open admission):** Later prepared replies stay queued while a modal or native picker owns the foreground. Picker completion, cancellation and abandonment wake retained opens. Regressions cover recipient ownership, exactly-once admission, source/history preservation and one-shot repaint requests. Estimates unchanged.
@@ -636,10 +672,18 @@ Newest first: the date, what moved, and the new overall estimate.
## Revision history
**2026-10-25 · minor:** M14 localization current state: Arabic catalogs stay logical, Arabic/Kurdish labels take an explicit RTL direction, and stock chrome mirrors; native/browser RTL input, IME and complex workflows remain unqualified. Native Simplified Chinese uses LXGW WenKai Lite; the web build has no Hans face. Estimates unchanged.
**2026-10-15 · minor:** M14/#2383 candidate: GPU device requests clamp unsupported limits while retaining the adapter texture extent. Synthetic V3D/downlevel regressions and Windows GPU-required tests pass; Raspberry Pi hardware remains unverified. Estimates unchanged.
| Date | Change | Summary |
|---|---|---|
| 2026-10-23 | minor | M8, #3205 follow-up: phone-pattern redaction includes the +39 country code on labelled Italian geographic numbers with a slash; dates, protocol identifiers and whole-run guards remain. Estimates unchanged. |
| 2026-10-23 | minor | M11: image downsampling measures physical resolution after page-local UserUnit scaling, including shared nested forms; synthetic measurement and optimization regressions. Estimates unchanged. |
| 2026-10-23 | minor | M10: Word table cells use the grid columns they span, including cells after a merged cell; synthetic export regression and CLI reproduction. Estimates unchanged. |
| 2026-10-23 | minor | M10: covered table slots retain their text in paragraph flow across Office exporters; emitted superscripts remain in their cells. Synthetic source and CLI regressions; estimates unchanged. |
| 2026-10-23 | minor | M10: Export all images and Save Image As apply soft-mask Decode intervals to PNG alpha before resizing, including inverted/subrange, indirect, packed and JPEG masks. Estimates unchanged. |
| 2026-10-23 | minor | M10: annotation appearances use unoccupied XObject names, preserving original page artwork and distinct appearances through inherited resources and print/reopen. Estimates unchanged. |
| 2026-10-22 | minor | M4, #3916 partial: document edits and Undo/Redo cancel Organize drags. Pointer-release and save/reopen regressions check page order. Estimates unchanged. |
| 2026-10-20 | minor | M4: initial-view window and interface options resolve indirect boolean ViewerPreferences values; synthetic true/false and save/reopen regressions retain defaults for malformed entries. Estimates unchanged. |
| 2026-10-20 | minor | M6, #3502: form detection preserves comments across content streams; estimates unchanged. |
@@ -685,8 +729,15 @@ Newest first: the date, what moved, and the new overall estimate.
- **2026-10-13 (M7):** Edit a PDF ▸ Add content: Header and footer, Watermark and Background open an Add / Update / Remove menu (Update and Remove enabled only when the document has that mark), as Acrobat's Watermark control does. The catalogue gains `ToolItem::actions`, so any tool can list more commands (#1192).
- **2026-10-18 (M8, #1350):** Published the history-preserving integration; simplified the inherited-form resource guard for Rust 1.96 Clippy. Formatting, 64 redaction tests, scoped Clippy, layering, assets and the scoped wasm check pass locally. CI remains pending; estimates unchanged.
- 2026-10-18: M11 / #3227: mark target-version compatibility partial; document the unchecked newer-content limitation.
- **2026-10-18 (PR #3227 integration):** M11: integrate upstream b0e5c6eb; retain partial target-version compatibility claims and effective-version reporting, correcting the borrowed version parser lifetime. Scope and estimates unchanged.
- **2026-10-12 (i18n):** Albanian (`sq`, Shqip) added: 2,343-entry catalog, month and weekday names, Preferences entry; not yet reviewed by a native speaker.
- **2026-10-21 (M4, #3865):** A new bookmark records where the reader is: the top-left of the selected text, or the top of the window, as `/XYZ left top null` (zoom kept), instead of the page top (`Edit::AddBookmark` takes `left` and `top`; `bookmark_add` takes `top` and `left`; `PageInfo::xyz_for_view`).
- **2026-10-18 (renderer, hayro patches 19/35):** A mesh shading (types 4–7) is sampled over its own triangles instead of the whole path: a BricsCAD plan with 310 one-triangle `sh` fills took 2 s per 1024 px tile at every zoom (and hit the 20 s watchdog on a busy machine); now about 70 ms, so zooming into dense topology drawings stays fluid. Estimates unchanged.
- **2026-10-22 (PR #3227 integration):** M11: integrate upstream `80b7d215`; retain partial target-version compatibility and upstream content-boundary and image-size regression coverage. Scope and estimates unchanged.
+94 -30
View File
@@ -84,7 +84,24 @@ help and feedback: https://discord.gg/artcraft"
);
fn main() -> ExitCode {
let args: Vec<String> = std::env::args().skip(1).collect();
// `std::env::args` panics on an argument that is not UTF-8 ("called `Result::unwrap()` on an
// `Err` value"), which a Latin-1 file name is, and it panics while collecting them: even
// `--help` ended that way. Such a name cannot be passed on either, since the paths here are
// `str`, so it is a usage error (photocraft#1108).
let mut args: Vec<String> = Vec::new();
for arg in std::env::args_os().skip(1) {
match arg.into_string() {
Ok(a) => args.push(a),
Err(bad) => {
let _ = writeln!(
std::io::stderr().lock(),
"pdfcraft-cli: `{}` is not valid UTF-8, so it cannot be used as an argument",
bad.to_string_lossy()
);
return ExitCode::FAILURE;
}
}
}
// `<command> --help` too; only right after the command, so a later `-h` (a value) still reaches it.
let command = match args.get(1).map(String::as_str) {
Some("--help" | "-h") => Some("--help"),
@@ -169,7 +186,7 @@ fn version() -> Result<(), CliError> {
/// found so scripts and CI can gate on it, and when the audit itself cannot run.
fn audit(args: &[String]) -> Result<(), CliError> {
validate_options("audit", args, AUDIT_OPTIONS)?;
let path = *positional(args).first().ok_or("audit: missing file")?;
let path = *positional(args, AUDIT_OPTIONS).first().ok_or("audit: missing file")?;
let bytes = read(path)?;
let password = flag(args, "--password");
let doc = pdfcraft_cos::Document::open_with_password(bytes.clone(), password).map_err(|e| format!("{path}: {e}"))?;
@@ -208,6 +225,28 @@ struct OptionSpec {
takes_value: bool,
}
/// The options whose value is a file or folder. Only these refuse a value that is another
/// option: a file named `--password` is never what was meant, while a password can be anything
/// (`--password --page` is a password of `--page`, which tests/text.rs pins), and so can a title.
/// The way to name a file that does start with `-` is `./--name`, as `--root` already offered.
const PATH_VALUE_OPTIONS: [&str; 6] = ["--out", "--out-dir", "--json", "--root", "--control", "--script"];
/// Whether a token can be the value of a path option. Another option cannot: `--out --password`
/// used to write the PDF to a file called `--password` and exit 0 (photocraft#6944).
fn can_be_path_value(name: &str, value: Option<&str>) -> bool {
!PATH_VALUE_OPTIONS.contains(&name) || value.is_some_and(|v| !v.is_empty() && !v.starts_with("--"))
}
/// The complaint about a path option whose value is missing or is another option.
fn needs_value(command: &str, name: &str, value: Option<&str>) -> String {
match value {
Some(v) if !v.is_empty() => {
format!("{command}: {name} needs a value and `{v}` is another option; write `./{v}` for a file of that name")
}
_ => format!("{command}: {name} needs a value"),
}
}
/// Refuse unknown options and malformed confinement flags before any file is read.
fn validate_options(command: &str, args: &[String], specs: &[OptionSpec]) -> Result<(), CliError> {
if specs.iter().any(|spec| spec.name == "--root") {
@@ -230,9 +269,19 @@ fn validate_options(command: &str, args: &[String], specs: &[OptionSpec]) -> Res
let Some(spec) = specs.iter().find(|spec| spec.name == arg) else {
return Err(format!("{command}: unknown option --{name}").into());
};
// Other missing or malformed values are left to the command, which reports them in its own
// terms (`text` and `extract` explain what a page value must be).
i += if spec.takes_value { 2 } else { 1 };
// A file's name is not another option, which also closes the gap the walk left for
// those: an unknown option in that value position was skipped along with it. Other
// values, missing or malformed, are left to the command, which reports them in its
// own terms (`text` and `extract` explain what a page value must be).
i += if spec.takes_value {
let value = args.get(i + 1).map(String::as_str);
if !can_be_path_value(spec.name, value) {
return Err(needs_value(command, spec.name, value).into());
}
2
} else {
1
};
} else {
i += 1;
}
@@ -278,19 +327,24 @@ const UI_OPTIONS: &[OptionSpec] = &[OptionSpec { name: "--control", takes_value:
#[cfg(feature = "mcp")]
const MCP_OPTIONS: &[OptionSpec] = &[OptionSpec { name: "--root", takes_value: true }, OptionSpec { name: "--compact", takes_value: false }];
fn positional(args: &[String]) -> Vec<&str> {
/// The arguments that are not options or their values. Which tokens are values is the spec's
/// answer: skipping the one after every option made `check-one --edit file.pdf` report "missing
/// file", the file having been read as `--edit`'s value.
fn positional<'a>(args: &'a [String], specs: &[OptionSpec]) -> Vec<&'a str> {
let mut out = Vec::new();
let mut skip = false;
for a in args {
if skip {
skip = false;
continue;
let mut i = 0;
while let Some(a) = args.get(i) {
match specs.iter().find(|spec| spec.name == a.as_str()) {
Some(spec) if spec.takes_value => i += 2,
// An option that takes no value, and an unknown one, which `validate_options` has
// already refused by the time this runs.
Some(_) => i += 1,
None if a.starts_with("--") => i += 1,
None => {
out.push(a.as_str());
i += 1;
}
}
if a.starts_with("--") {
skip = true;
continue;
}
out.push(a.as_str());
}
out
}
@@ -301,7 +355,7 @@ fn read(path: &str) -> Result<Arc<Vec<u8>>, String> {
fn info(args: &[String]) -> Result<(), CliError> {
validate_options("info", args, INFO_OPTIONS)?;
let path = *positional(args).first().ok_or("info: missing file")?;
let path = *positional(args, INFO_OPTIONS).first().ok_or("info: missing file")?;
let bytes = read(path)?;
let password = flag(args, "--password");
// The renderer takes only the user password of R2–R4 files; `Session::open` takes either.
@@ -354,7 +408,7 @@ fn info(args: &[String]) -> Result<(), CliError> {
fn text(args: &[String]) -> Result<(), CliError> {
validate_options("text", args, TEXT_OPTIONS)?;
let path = *positional(args).first().ok_or("text: missing file")?;
let path = *positional(args, TEXT_OPTIONS).first().ok_or("text: missing file")?;
let mut selected_page = None;
// Validate every supplied value before reading, retaining the first valid selection.
let mut options = args.iter();
@@ -482,7 +536,13 @@ fn edit(args: &[String]) -> Result<(), CliError> {
continue;
}
}
let value = args.get(i + 1).map(String::as_str).ok_or_else(|| format!("edit: {arg} needs a value"))?;
// `edit` parses its own options (they run in order), so `--out` is checked here in the
// same way: it wrote a PDF to a file called `--full`.
let value = args.get(i + 1).map(String::as_str);
if !can_be_path_value(arg, value) {
return Err(needs_value("edit", arg, value).into());
}
let value = value.ok_or_else(|| format!("edit: {arg} needs a value"))?;
match arg {
"--out" => out = Some(value),
"--password" => password = Some(value),
@@ -569,7 +629,7 @@ fn file_stem(path: &str) -> String {
fn combine(args: &[String]) -> Result<(), CliError> {
validate_options("combine", args, COMBINE_OPTIONS)?;
let out = flag(args, "--out").ok_or("combine: missing --out")?;
let inputs = positional(args);
let inputs = positional(args, COMBINE_OPTIONS);
if inputs.len() < 2 {
return Err("combine: give at least two input files".into());
}
@@ -580,7 +640,7 @@ fn combine(args: &[String]) -> Result<(), CliError> {
fn extract(args: &[String]) -> Result<(), CliError> {
validate_options("extract", args, EXTRACT_OPTIONS)?;
let path = *positional(args).first().ok_or("extract: missing file")?;
let path = *positional(args, EXTRACT_OPTIONS).first().ok_or("extract: missing file")?;
let out = flag(args, "--out").ok_or("extract: missing --out")?;
let pages = page_list(flag(args, "--pages").ok_or("extract: missing --pages")?)?;
let mut session = pdfcraft_engine::Session::new();
@@ -592,7 +652,7 @@ fn extract(args: &[String]) -> Result<(), CliError> {
fn split(args: &[String]) -> Result<(), CliError> {
validate_options("split", args, SPLIT_OPTIONS)?;
use pdfcraft_engine::SplitBy;
let path = *positional(args).first().ok_or("split: missing file")?;
let path = *positional(args, SPLIT_OPTIONS).first().ok_or("split: missing file")?;
let by = match (flag(args, "--every"), flag(args, "--before")) {
(Some(n), None) => {
// A count the splitter cannot hold is refused here, before the file is opened,
@@ -637,14 +697,14 @@ fn parse_dpi(value: &str) -> Result<f32, String> {
fn render(args: &[String]) -> Result<(), CliError> {
validate_options("render", args, RENDER_OPTIONS)?;
let path = *positional(args).first().ok_or("render: missing file")?;
let path = *positional(args, RENDER_OPTIONS).first().ok_or("render: missing file")?;
let page: usize =
flag(args, "--page").unwrap_or("1").parse().ok().filter(|page| *page > 0).ok_or("bad --page: expected a positive page number")?;
let page_index = page - 1;
let dpi = parse_dpi(flag(args, "--dpi").unwrap_or("96"))?;
let out = flag(args, "--out").ok_or("render: missing --out (.png, .jpg, .tif or .pam)")?;
// The file is what its name says (#248): a `.png` used to get a netpbm PAM stream.
let format = match Path::new(out).extension().and_then(|e| e.to_str()).map(str::to_ascii_lowercase).as_deref() {
let format = match Path::new(out).extension().and_then(std::ffi::OsStr::to_str).map(str::to_ascii_lowercase).as_deref() {
Some("png") => Some(ImageFormat::Png),
Some("jpg" | "jpeg") => Some(ImageFormat::Jpeg { quality: 90 }),
Some("tif" | "tiff") => Some(ImageFormat::Tiff),
@@ -688,6 +748,10 @@ fn render(args: &[String]) -> Result<(), CliError> {
pdfcraft_render::RenderWarning::ContentTruncated => {
let _ = writeln!(std::io::stderr().lock(), "warning: page {page}: content past the page's safety budget was skipped");
}
pdfcraft_render::RenderWarning::ColourFallback => {
let _ =
writeln!(std::io::stderr().lock(), "warning: page {page}: a colour that could not be computed was painted in a fallback colour");
}
}
}
Ok(())
@@ -696,7 +760,7 @@ fn render(args: &[String]) -> Result<(), CliError> {
/// Child-process body for `check`: prints one JSON line.
fn check_one(args: &[String]) -> Result<(), CliError> {
validate_options("check-one", args, CHECK_ONE_OPTIONS)?;
let path = *positional(args).first().ok_or("check-one: missing file")?;
let path = *positional(args, CHECK_ONE_OPTIONS).first().ok_or("check-one: missing file")?;
let dpi = parse_dpi(flag(args, "--dpi").unwrap_or("36"))?;
let start = Instant::now();
let bytes = read(path)?;
@@ -779,7 +843,7 @@ fn collect(paths: &[&str]) -> Vec<PathBuf> {
if let Ok(rd) = std::fs::read_dir(&p) {
stack.extend(rd.flatten().map(|e| e.path()));
}
} else if p.extension().and_then(|e| e.to_str()).is_some_and(|e| e.eq_ignore_ascii_case("pdf")) {
} else if p.extension().and_then(std::ffi::OsStr::to_str).is_some_and(|e| e.eq_ignore_ascii_case("pdf")) {
out.push(p);
}
}
@@ -802,7 +866,7 @@ fn check(args: &[String]) -> Result<(), CliError> {
);
let dpi = flag(args, "--dpi").unwrap_or("36").to_string();
parse_dpi(&dpi)?;
let files = collect(&positional(args));
let files = collect(&positional(args, CHECK_OPTIONS));
if files.is_empty() {
return Err("check: no PDF files found".into());
}
@@ -985,9 +1049,9 @@ fn run(args: &[String]) -> Result<(), CliError> {
}
return Ok(());
}
let tool = *positional(args).first().ok_or("run: missing tool name (see `pdfcraft-cli tools`)")?;
let tool = *positional(args, RUN_OPTIONS).first().ok_or("run: missing tool name (see `pdfcraft-cli tools`)")?;
let mut obj = serde_json::Map::new();
for kv in positional(args).iter().skip(1) {
for kv in positional(args, RUN_OPTIONS).iter().skip(1) {
let (k, v) = kv.split_once('=').ok_or(format!("run: expected key=value, got {kv:?}"))?;
let value = serde_json::from_str(v).unwrap_or_else(|_| serde_json::Value::String(v.to_string()));
obj.insert(k.to_string(), value);
@@ -1053,7 +1117,7 @@ fn ui(args: &[String]) -> Result<(), CliError> {
// Refused rather than truncated, which would quietly reach some other port.
let port = u16::try_from(port).map_err(|_| format!("{file}: {port} is not a port number"))?;
let token = info["token"].as_str().ok_or(format!("{file}: no token"))?;
let pos = positional(args);
let pos = positional(args, UI_OPTIONS);
let method = *pos.first().ok_or("ui: missing method (state, inspect, click, drag, type, key, command, commands, set, open, screenshot)")?;
let method = if method.starts_with("ui.") { method.to_string() } else { format!("ui.{method}") };
let mut params = serde_json::Map::new();
+86
View File
@@ -27,3 +27,89 @@ fn non_edit_commands_reject_unknown_options_before_io() {
assert!(stderr.contains("unknown option") && stderr.contains(unknown), "{args:?}: {stderr}");
}
}
/// photocraft#6944: an option took the next token whatever it was, so a line with a value missing
/// in the middle of it did something else entirely — `extract in.pdf --pages 1 --out --password`
/// wrote the PDF to a file called `--password` and exited 0. The unknown option hidden in a value
/// position passed the check above too, since the walk skipped it along with the option.
///
/// Only the options whose value is a file or folder refuse one: a password or a title can be any
/// string, `--page` included, which `text`'s own tests pin and this does not change.
#[test]
fn a_file_option_refuses_a_value_that_is_another_option() {
let dir = std::env::temp_dir().join(format!("pdfcraft-cli-values-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).expect("temp dir");
for (option, args) in [
("--out", vec!["extract", "missing.pdf", "--pages", "1", "--out", "--password"]),
("--out", vec!["combine", "a.pdf", "b.pdf", "--out", "--nonsense"]),
("--out", vec!["render", "missing.pdf", "--out", "--dpi", "96"]),
("--out-dir", vec!["split", "missing.pdf", "--every", "2", "--out-dir", "--password"]),
("--json", vec!["check", "missing.pdf", "--json", "--dpi"]),
("--control", vec!["ui", "--control", "--out", "state"]),
// `edit` parses its own options, in the order given, and had the same gap.
("--out", vec!["edit", "missing.pdf", "--out", "--full"]),
] {
let out = Command::new(BIN).current_dir(&dir).args(&args).output().expect("run cli");
let stderr = String::from_utf8_lossy(&out.stderr);
assert!(!out.status.success(), "{args:?} unexpectedly succeeded");
assert!(stderr.contains(&format!("{option} needs a value")), "{args:?}: {stderr}");
assert!(stderr.contains("another option"), "{args:?}: {stderr}");
}
assert_eq!(std::fs::read_dir(&dir).expect("read dir").count(), 0, "nothing was written");
let _ = std::fs::remove_dir_all(&dir);
}
/// And a file whose name really does start with `-` is still reachable, the way the shell reaches
/// one and `--root` already documented: `./--name`. The error is then about the input file, which
/// is as far as these lines get here.
#[test]
fn a_file_whose_name_starts_with_dashes_is_still_reachable() {
// The error is about the file the command could not open, so the test asks which file it
// names -- not how the OS words "not found", which differs on Windows (#3849 review).
for (names, args) in [
("missing.pdf", vec!["extract", "missing.pdf", "--pages", "1", "--out", "./--dash.pdf"]),
("missing.pdf", vec!["edit", "missing.pdf", "--out", "./--dash.pdf"]),
("./--dash.pdf", vec!["info", "./--dash.pdf"]),
] {
let out = Command::new(BIN).args(&args).output().expect("run cli");
let stderr = String::from_utf8_lossy(&out.stderr);
assert!(!out.status.success(), "{args:?}: no such file either way");
assert!(stderr.contains(names), "{args:?}: the error is about {names}: {stderr}");
// Not a usage error: the `./--dash.pdf` reached the command as a file name.
assert!(!stderr.contains("needs a value") && !stderr.contains("unknown option"), "{args:?}: {stderr}");
}
}
/// The token after an option that takes no value is not its value: `check-one --edit file.pdf`
/// reported "check-one: missing file", the file having been read as `--edit`'s operand.
#[test]
fn a_flag_that_takes_no_value_does_not_swallow_the_file() {
for args in [vec!["check-one", "--edit", "missing.pdf"], vec!["check-one", "missing.pdf", "--edit"]] {
let out = Command::new(BIN).args(&args).output().expect("run cli");
let stderr = String::from_utf8_lossy(&out.stderr);
assert!(!out.status.success(), "{args:?}");
// Which file the error is about, not how the OS says it is missing (#3849 review).
assert!(stderr.contains("missing.pdf"), "{args:?}: the error is about the file: {stderr}");
assert!(!stderr.contains("missing file"), "the file was found, and then not found: {stderr}");
assert!(!stderr.contains("needs a value"), "{args:?}: {stderr}");
}
}
/// photocraft#1108: an argument that is not UTF-8 panicked in `std::env::args` ("called
/// `Result::unwrap()` on an `Err` value"), while collecting the arguments — so it panicked even
/// for `--help`. Such a name cannot be used here, where paths are `str`, so it is a usage error.
#[cfg(unix)]
#[test]
fn an_argument_that_is_not_utf8_is_an_error_not_a_panic() {
use std::ffi::OsStr;
use std::os::unix::ffi::OsStrExt;
for args in [vec![OsStr::new("info"), OsStr::from_bytes(b"/tmp/caf\xe9.pdf")], vec![OsStr::new("--help"), OsStr::from_bytes(b"caf\xe9")]] {
let out = Command::new(BIN).args(&args).output().expect("run cli");
let stderr = String::from_utf8_lossy(&out.stderr);
assert_eq!(out.status.code(), Some(1), "an error, not a panic (101): {stderr}");
assert!(stderr.contains("not valid UTF-8"), "{stderr}");
assert!(!stderr.contains("panicked"), "{stderr}");
}
}
+1 -1
View File
@@ -12,7 +12,7 @@ workspace = true
[dependencies]
pdfcraft-ui-egui = { workspace = true }
eframe = { workspace = true, features = ["default_fonts", "glow", "persistence", "accesskit"] }
egui = { workspace = true }
egui = { workspace = true, features = ["default_fonts", "monochrome_emoji_fonts"] }
[target.'cfg(target_arch = "wasm32")'.dependencies]
wasm-bindgen-futures = "0.4"
+2 -2
View File
@@ -18,8 +18,8 @@ pdfcraft-ui-egui = { workspace = true }
pdfcraft-engine = { workspace = true }
# wgpu draws; OpenGL (glow) is the fallback when wgpu can't start on an old or unusual GPU or
# driver (#461, #435, #392), and can be chosen with PDFCRAFT_RENDERER=gl.
eframe = { workspace = true, features = ["default_fonts", "wgpu", "glow", "accesskit", "wayland", "x11", "persistence", "links"] }
egui = { workspace = true }
eframe = { workspace = true, features = ["default_fonts", "wgpu", "glow", "accesskit", "wayland", "x11", "persistence", "links", "clipboard"] }
egui = { workspace = true, features = ["default_fonts", "monochrome_emoji_fonts"] }
serde_json = { workspace = true }
# Records from every crate go to standard error and the log file (src/logging.rs).
log = { workspace = true }
+72 -41
View File
@@ -357,6 +357,9 @@ fn native_options(integrated: bool, app_frame: bool, renderer: eframe::Renderer)
let persistence_path = settings_dir().map(|d| d.join("app.ron"));
// Set explicitly, so the renderer never depends on which one eframe defaults to.
let mut native = eframe::NativeOptions { viewport, persistence_path, renderer, ..Default::default() };
// PdfCraft installs its own last-resort system face (`PDFCRAFT_SYSTEM_FONTS`); eframe's
// provider would read every installed face, including proprietary ones, into every UI pass.
native.system_font_fallback = false;
if renderer == eframe::Renderer::Wgpu {
configure_gpu(&mut native);
}
@@ -795,6 +798,41 @@ fn pick_adapter(adapters: &[(u32, u32, eframe::wgpu::DeviceType)], displays: &[D
#[cfg(test)]
mod tests {
/// The lockfile package block for `name`, or a panic naming the missing package.
fn locked_package(root: &std::path::Path, name: &str) -> String {
let lock = std::fs::read_to_string(root.join("Cargo.lock")).expect("Cargo.lock");
lock.split("[[package]]")
.find(|p| p.contains(&format!("\nname = \"{name}\"\n")))
.map(str::to_owned)
.unwrap_or_else(|| panic!("{name} is not in Cargo.lock"))
}
/// Interim graph check for the window stack while the reviewed fork revision is not yet
/// published. The old `vendor/winit` / `vendor/egui-wgpu` path patches were removed from the
/// published manifest; local integration supplies the reviewed worktrees through an external
/// Cargo config patch. A git source must name the public storytold fork; a path source is the
/// local integration graph. Behaviour (surface fitting, error scopes, scroll phases) is tested
/// directly elsewhere; the retained vendor copies keep provenance until the fork revision is
/// pinned. No public revision is invented here.
fn assert_window_stack_graph(root: &std::path::Path, name: &str, version: &str) -> String {
let package = locked_package(root, name);
assert!(package.contains(&format!("\nversion = \"{version}\"\n")), "{name} must resolve to {version}: {package}");
if let Some(source) = package.lines().find_map(|line| line.strip_prefix("source = ")) {
assert!(source.contains("github.com/storytold/"), "{name} must come from the reviewed storytold fork once published, not {source}");
assert!(
source.split(|c: char| !c.is_ascii_hexdigit()).any(|part| part.len() == 40),
"{name} must pin the fork's 40-character revision, not {source}"
);
}
// A path patch has no `source =` in Cargo.lock. The local integration config is the only
// allowed path source; a machine-local path must never be in the published manifest,
// which the root-manifest assertion below checks. A path entry carries no remote identity
// to verify, so this test does not claim the resolved code is the published fork.
let manifest = std::fs::read_to_string(root.join("Cargo.toml")).expect("root Cargo.toml");
assert!(!manifest.contains(&format!("{name} = {{ path = \"vendor/")), "vendor/{name} must not be a published path patch");
package
}
use pdfcraft_ui_egui::control::Endpoint;
fn endpoint() -> std::io::Result<Endpoint> {
@@ -1064,27 +1102,16 @@ mod tests {
}
#[test]
fn egui_wgpu_carries_the_surface_size_fit() {
// Issue #577: egui-wgpu 0.36.2 configures a window's surface at the window's size, and
fn vendor_provenance_egui_wgpu_surface_fit_identity() {
// Issue #577: egui-wgpu configured a window's surface at the window's size, and
// `Surface::configure` panics when that's beyond the device's `max_texture_dimension_2d`
// (emilk/egui#8361). vendor/egui-wgpu fits it within the limit. A dependency bump that
// resolves egui-wgpu from crates.io again, or a re-vendored copy without the patch, would
// bring the crash back: re-apply the patch, or drop the copy once an egui release has a
// fix (vendor/README.md).
// (emilk/egui#8361). The reviewed egui 0.37 worktree carries E2 (`surface_fit`); the
// behavioural test above exercises it. The old 0.36 vendor copy is retained for
// provenance only and is no longer a published path patch, so reading it would not prove
// what the app runs.
let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../..");
let lock = std::fs::read_to_string(root.join("Cargo.lock")).unwrap();
let egui_wgpu = lock.split("[[package]]").find(|p| p.contains("\nname = \"egui-wgpu\"\n")).expect("egui-wgpu is in Cargo.lock");
assert!(!egui_wgpu.contains("\nsource = "), "egui-wgpu must resolve to vendor/egui-wgpu, not:{egui_wgpu}");
// `surface_fit` is tested above; these keep it in the paths that size a surface.
let painter = std::fs::read_to_string(root.join("vendor/egui-wgpu/src/winit.rs")).unwrap().replace("\r\n", "\n");
for patch in [
"let (width, height, render_scale) = surface_fit(window_width, window_height, max_side);",
"let (fit_width, fit_height, _) = surface_fit(width, height, self.max_surface_side());",
"pixels_per_point: pixels_per_point * surface_state.render_scale,",
"old_state.window_width,\n old_state.window_height,",
] {
assert!(painter.contains(patch), "vendor/egui-wgpu lost its surface size patch: {patch}");
}
assert_window_stack_graph(&root, "egui-wgpu", "0.37.0");
assert!(root.join("vendor/egui-wgpu/src/winit.rs").exists(), "the vendor copy and its provenance stay until the fork revision is pinned");
}
#[test]
@@ -1141,23 +1168,17 @@ mod tests {
}
#[test]
fn egui_wgpu_returns_a_surface_it_cannot_configure_as_an_error() {
// Issue #519: `catch_errors` is tested above; this keeps it around the first configure of
// every new window's surface, and its error reaching eframe as `WgpuError` (eframe then
// returns `Error::Wgpu`, which `main` retries with OpenGL). Without it a failed configure
// panics before the app is created, and the OpenGL retry never runs.
fn vendor_provenance_egui_wgpu_catch_errors_identity() {
// Issue #519: E3 (`catch_errors`) is tested above against a real device. The reviewed 0.37
// worktree carries it around the first configure of every new window's surface, and its
// error reaches eframe as `WgpuError` (eframe then returns `Error::Wgpu`, which `main`
// retries with OpenGL). Without it a failed configure panics before the app is created.
// `catch_errors` is exercised against a real device in the test above and below; the
// graph check makes sure the app runs the reviewed 0.37 worktree (the retained vendor
// copy is not read as proof of behaviour).
let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../..");
let lock = std::fs::read_to_string(root.join("Cargo.lock")).unwrap();
let egui_wgpu = lock.split("[[package]]").find(|p| p.contains("\nname = \"egui-wgpu\"\n")).expect("egui-wgpu is in Cargo.lock");
assert!(!egui_wgpu.contains("\nsource = "), "egui-wgpu must resolve to vendor/egui-wgpu, not:{egui_wgpu}");
let painter = std::fs::read_to_string(root.join("vendor/egui-wgpu/src/winit.rs")).unwrap().replace("\r\n", "\n");
let add_surface = painter.split("async fn add_surface(").nth(1).and_then(|s| s.split("\n fn ").next()).expect("add_surface");
for patch in [
"let installed = catch_errors(&device, || {\n self.install_surface(surface, viewport_id, size.width, size.height, false);\n })",
"return Err(crate::WgpuError::ConfigureSurface(error));",
] {
assert!(add_surface.contains(patch), "vendor/egui-wgpu lost its surface configure patch: {patch}");
}
assert_window_stack_graph(&root, "egui-wgpu", "0.37.0");
assert!(root.join("vendor/egui-wgpu/src/winit.rs").exists(), "the vendor copy and its provenance stay until the fork revision is pinned");
}
#[test]
@@ -1199,13 +1220,23 @@ mod tests {
// dependency bump that resolves winit from crates.io again, or a re-vendored copy without
// the patch, would silently bring the bug back: re-apply the patch, or drop the copy once a
// winit 0.30 release has the fix (vendor/README.md).
// W1 (and W2–W13) were audited against the reviewed winit worktree: the vendor rows in
// `vendor/README.md` match the fork's PATCHES.md entries W1–W13. The vendor source is no
// longer a published path patch, so this checks the actual graph, not the old copy.
let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../..");
let lock = std::fs::read_to_string(root.join("Cargo.lock")).unwrap();
let winit = lock.split("[[package]]").find(|p| p.contains("\nname = \"winit\"\n")).expect("winit is in Cargo.lock");
assert!(!winit.contains("\nsource = "), "winit must resolve to vendor/winit, not:{winit}");
let dpi_changed = std::fs::read_to_string(root.join("vendor/winit/src/platform_impl/windows/event_loop.rs")).unwrap();
let patch = "if !WIN10_BUILD_VERSION.is_some_and(|build| build < 22000) {\n new_outer_rect = suggested_rect;";
assert!(dpi_changed.contains(patch), "vendor/winit lost its WM_DPICHANGED patch");
assert_window_stack_graph(&root, "winit", "0.30.13");
let event_loop = std::fs::read_to_string(root.join("vendor/winit/src/platform_impl/windows/event_loop.rs")).unwrap();
// The audited W1 hunk itself, not merely the file's presence: Windows 11 applies the
// rect Windows suggests, while Windows 10 keeps the old adjustment.
for marker in [
"PdfCraft patch: from Windows 11 (build 22000) on, apply the rect Windows suggests",
"if !WIN10_BUILD_VERSION.is_some_and(|build| build < 22000) {",
"new_outer_rect = suggested_rect;",
] {
assert!(event_loop.contains(marker), "vendor/winit lost the W1 monitor-scale patch: {marker}");
}
let provenance = std::fs::read_to_string(root.join("vendor/winit/.cargo_vcs_info.json")).unwrap();
assert!(provenance.contains("e9809ef54b18499bb4f2cac945719ecc2a61061b"), "vendor/winit keeps its upstream base provenance");
}
const NVIDIA: (u32, u32) = (0x10de, 0x2684);
+1
View File
@@ -7,6 +7,7 @@ mod event {
pub use winit::event::TouchPhase;
}
mod vendor_graph;
mod winit_macos_emoji_picker;
mod winit_macos_ime_commit;
mod winit_macos_ime_discard;
+78
View File
@@ -0,0 +1,78 @@
//! Dependency-graph verification for the egui 0.37 window stack.
//!
//! The twelve `winit_*` modules next to this one read the retained `vendor/winit` /
//! `vendor/egui-wgpu` copies. They are provenance for W1–W13 and E2+E3, not proof of what the app
//! runs: the root manifest pins both crates to immutable storytold git revisions, and the retained
//! copies are not path patches. These tests check the resolved graph and the retained evidence
//! instead of treating the copies as the runtime source. The winit fork's own W17 tests own patch
//! behaviour.
fn root() -> std::path::PathBuf {
std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../..")
}
/// Every `[[package]]` block in `Cargo.lock` whose `name` is exactly `name`.
fn locked_packages(name: &str) -> Vec<String> {
let lock = std::fs::read_to_string(root().join("Cargo.lock")).expect("Cargo.lock");
let needle = format!("name = \"{name}\"");
lock.split("[[package]]").filter(|package| package.lines().any(|line| line.trim() == needle.as_str())).map(str::to_owned).collect()
}
/// The one resolved package called `name`. A duplicate name is a lockfile problem, not something
/// to resolve by taking the first match.
fn locked(name: &str) -> String {
let mut packages = locked_packages(name);
assert_eq!(packages.len(), 1, "Cargo.lock must contain exactly one `{name}` package, found {}", packages.len());
packages.remove(0)
}
/// The resolved package must be the exact canonical storytold git source at the reviewed
/// 40-character revision, including the `Cargo.lock` URL and fragment. A path source (no `source`
/// line) is refused: it would make the graph depend on a developer's checkout. A published path
/// patch is refused as well.
fn assert_resolved(name: &str, version: &str, url: &str, rev: &str) {
let package = locked(name);
let expected_version = format!("version = \"{version}\"");
assert!(package.lines().any(|line| line.trim() == expected_version.as_str()), "{name} must resolve to {version}: {package}");
let sources: Vec<&str> = package.lines().filter_map(|line| line.trim().strip_prefix("source = ")).collect();
assert_eq!(sources.len(), 1, "{name} must have exactly one `source` in Cargo.lock; a local path source is not accepted: {package}");
let expected_source = format!("\"git+{url}?rev={rev}#{rev}\"");
assert_eq!(sources[0], expected_source.as_str(), "{name} must resolve to the exact canonical git URL, revision and fragment, not {}", sources[0]);
let manifest = std::fs::read_to_string(root().join("Cargo.toml")).expect("root Cargo.toml");
assert!(!manifest.contains(&format!("{name} = {{ path = \"vendor/")), "vendor/{name} cannot stay a published path patch");
}
#[test]
fn vendor_provenance_window_stack_graph_is_resolved() {
assert_resolved("winit", "0.30.13", "https://github.com/storytold/winit.git", "a517b3846ee8457d84ee4975110bfda6797c44dc");
assert_resolved("egui-wgpu", "0.37.0", "https://github.com/storytold/egui.git", "6d518fc799681571963842f95b55a6b68431b15a");
// Retained provenance: the audited copies and their recorded W1–W13 / E2+E3 rows.
let readme = std::fs::read_to_string(root().join("vendor/README.md")).expect("vendor/README.md");
for marker in ["W1–W13", "surface_fit", "catch_errors", "e9809ef54b18499bb4f2cac945719ecc2a61061b"] {
assert!(readme.contains(marker), "vendor/README.md lost window-stack provenance: {marker}");
}
let vcs = std::fs::read_to_string(root().join("vendor/winit/.cargo_vcs_info.json")).expect("vendor/winit provenance");
assert!(vcs.contains("e9809ef54b18499bb4f2cac945719ecc2a61061b"), "vendor/winit keeps its upstream base");
for path in ["vendor/winit/src/platform_impl", "vendor/egui-wgpu/src/winit.rs"] {
assert!(root().join(path).exists(), "retain {path} as provenance for the pinned fork");
}
}
/// Renderer, security and PostScript vendors are unrelated to the UI port and must stay path patches.
#[test]
fn renderer_and_security_vendors_remain() {
let manifest = std::fs::read_to_string(root().join("Cargo.toml")).expect("root Cargo.toml");
for vendor in [
"vendor/hayro",
"vendor/hayro-interpret",
"vendor/hayro-syntax",
"vendor/hayro-cmap",
"vendor/hayro-jbig2",
"vendor/hayro-postscript",
"vendor/lopdf",
"vendor/vello_common",
] {
assert!(manifest.contains(&format!("path = \"{vendor}\"")), "{vendor} must stay a path patch");
}
}
@@ -1,7 +1,9 @@
//! vendor/winit patch (8) (vendor/README.md).
//! Provenance-only: reads the retained `vendor/` copy, not the resolved dependency, so it is
//! not runtime coverage. `vendor_graph.rs` checks the resolved graph identity.
//! Retained vendor provenance for winit patch (8) (vendor/README.md); `vendor_graph.rs` checks the resolved graph.
#[test]
fn winit_commits_macos_text_inserted_outside_a_key_press() {
fn vendor_provenance_winit_macos_text_inserted_outside_a_key_press() {
// The macOS emoji picker inserts its text with `insertText` outside any key press and without
// a composition. winit 0.30.13 reports `insertText` only as part of a key press or a
// composition, so an emoji picked into a PdfCraft text field was dropped. vendor/winit commits
@@ -1,7 +1,9 @@
//! vendor/winit patch (6) (vendor/README.md).
//! Provenance-only: reads the retained `vendor/` copy, not the resolved dependency, so it is
//! not runtime coverage. `vendor_graph.rs` checks the resolved graph identity.
//! Retained vendor provenance for winit patch (6) (vendor/README.md); `vendor_graph.rs` checks the resolved graph.
#[test]
fn winit_commits_macos_compositions_that_end_without_marked_text() {
fn vendor_provenance_winit_macos_compositions_that_end_without_marked_text() {
// winit 0.30.13 treats `insertText` as an IME commit only while marked text is left. Input
// methods that end a composition with `unmarkText` first lost the committed text, and Apple
// Korean, which clears its marked text before inserting the key typed after a syllable (`한`
@@ -1,7 +1,9 @@
//! vendor/winit patch (7) (vendor/README.md).
//! Provenance-only: reads the retained `vendor/` copy, not the resolved dependency, so it is
//! not runtime coverage. `vendor_graph.rs` checks the resolved graph identity.
//! Retained vendor provenance for winit patch (7) (vendor/README.md); `vendor_graph.rs` checks the resolved graph.
#[test]
fn winit_discards_the_macos_composition_when_ime_is_disallowed() {
fn vendor_provenance_winit_discards_the_macos_composition_when_ime_is_disallowed() {
// egui disallows IME when a text field loses focus. winit 0.30.13 then forgets the marked text
// but doesn't tell the input method, which keeps the composition and continues it once IME is
// allowed again: the abandoned syllable comes back in the next field. vendor/winit calls
@@ -1,7 +1,9 @@
//! vendor/winit patch (10) (vendor/README.md).
//! Provenance-only: reads the retained `vendor/` copy, not the resolved dependency, so it is
//! not runtime coverage. `vendor_graph.rs` checks the resolved graph identity.
//! Retained vendor provenance for winit patch (10) (vendor/README.md); `vendor_graph.rs` checks the resolved graph.
#[test]
fn winit_retries_the_first_apple_korean_key_once() {
fn vendor_provenance_winit_retries_the_first_apple_korean_key_once() {
// On the first key in a freshly started app, Apple Korean can answer with `insertText` and the
// raw compatibility jamo instead of starting a composition, so typing g k s in PdfCraft gave
// ㅎㅏㄴ instead of 한. vendor/winit interprets that one key again before sending it to the
@@ -1,7 +1,9 @@
//! vendor/winit patch (9) (vendor/README.md).
//! Provenance-only: reads the retained `vendor/` copy, not the resolved dependency, so it is
//! not runtime coverage. `vendor_graph.rs` checks the resolved graph identity.
//! Retained vendor provenance for winit patch (9) (vendor/README.md); `vendor_graph.rs` checks the resolved graph.
#[test]
fn winit_sends_a_key_committed_through_macos_ime_only_once() {
fn vendor_provenance_winit_sends_a_key_committed_through_macos_ime_only_once() {
// Apple Korean answers Space with no syllable in progress with `setMarkedText(" ")`,
// `insertText(" ")` and `setMarkedText("")`. The last call resets winit 0.30.13's IME state, so
// the key went to the app both as `Ime::Commit(" ")` and as `KeyboardInput` with text " ", and
@@ -1,7 +1,9 @@
//! vendor/winit patch (12) (vendor/README.md).
//! Provenance-only: reads the retained `vendor/` copy, not the resolved dependency, so it is
//! not runtime coverage. `vendor_graph.rs` checks the resolved graph identity.
//! Retained vendor provenance for winit patch (12) (vendor/README.md); `vendor_graph.rs` checks the resolved graph.
#[test]
fn winit_lets_macos_title_bar_drags_reach_the_app() {
fn vendor_provenance_winit_lets_macos_title_bar_drags_reach_the_app() {
// On macOS the tab strip is the title bar: a transparent title bar over a full-size content
// view. NSView answers YES to `mouseDownCanMoveWindow` for a view that isn't opaque, so AppKit
// moved the whole window for a drag that began on a document tab, and tabs could not be
+13 -5
View File
@@ -1,3 +1,5 @@
//! Provenance-only: reads the retained `vendor/` copy, not the resolved dependency, so it is
//! not runtime coverage. `vendor_graph.rs` checks the resolved graph identity.
#![cfg(target_os = "linux")]
use egui::{Event, Modifiers, MouseWheelUnit, RawInput, TouchPhase, vec2};
@@ -27,7 +29,13 @@ fn wheel_trace(source: AxisSource, discrete: bool) -> Vec<(f32, egui::Vec2)> {
let (unit, dy) = if discrete { (MouseWheelUnit::Line, 1.0) } else { (MouseWheelUnit::Point, 24.0) };
let input = RawInput {
time: Some(frame as f64 / 60.0),
events: vec![Event::MouseWheel { unit, delta: vec2(0.0, dy), phase: egui_phase(phase), modifiers }],
events: vec![Event::MouseWheel {
unit,
delta: vec2(0.0, dy),
phase: egui_phase(phase),
modifiers,
source: egui::MouseWheelSource::Unknown,
}],
..Default::default()
};
ctx.run_ui(input, |ui| seen.push(ui.input(|i| (i.zoom_delta(), i.smooth_scroll_delta)))).textures_delta.clear();
@@ -36,7 +44,7 @@ fn wheel_trace(source: AxisSource, discrete: bool) -> Vec<(f32, egui::Vec2)> {
}
#[test]
fn releasing_ctrl_after_pixel_wheel_zoom_returns_to_scrolling() {
fn vendor_provenance_releasing_ctrl_after_pixel_wheel_zoom_returns_to_scrolling() {
for source in [AxisSource::Wheel, AxisSource::WheelTilt, AxisSource::Continuous] {
let seen = wheel_trace(source, false);
assert!(seen[1].0 > 1.0, "Ctrl must zoom: {source:?}");
@@ -46,7 +54,7 @@ fn releasing_ctrl_after_pixel_wheel_zoom_returns_to_scrolling() {
}
#[test]
fn discrete_wheels_still_follow_current_modifiers() {
fn vendor_provenance_discrete_wheels_still_follow_current_modifiers() {
let seen = wheel_trace(AxisSource::Wheel, true);
assert!(seen[1].0 > 1.0);
assert_eq!(seen[2].0, 1.0);
@@ -54,7 +62,7 @@ fn discrete_wheels_still_follow_current_modifiers() {
}
#[test]
fn finger_gestures_keep_their_modifier_until_the_gesture_ends() {
fn vendor_provenance_finger_gestures_keep_their_modifier_until_the_gesture_ends() {
// A finger scroll's momentum may arrive after Ctrl is released.
let seen = wheel_trace(AxisSource::Finger, false);
assert!(seen[1].0 > 1.0);
@@ -65,7 +73,7 @@ fn finger_gestures_keep_their_modifier_until_the_gesture_ends() {
}
#[test]
fn unknown_sources_keep_the_existing_phase_policy() {
fn vendor_provenance_unknown_sources_keep_the_existing_phase_policy() {
assert_eq!(scroll::phase(event::TouchPhase::Ended, None, false, false), event::TouchPhase::Started);
assert_eq!(scroll::phase(event::TouchPhase::Started, None, false, false), event::TouchPhase::Moved);
assert_eq!(scroll::phase(event::TouchPhase::Ended, None, true, false), event::TouchPhase::Moved);
@@ -1,7 +1,9 @@
//! vendor/winit patch (2) (vendor/README.md).
//! Provenance-only: reads the retained `vendor/` copy, not the resolved dependency, so it is
//! not runtime coverage. `vendor_graph.rs` checks the resolved graph identity.
//! Retained vendor provenance for winit patch (2) (vendor/README.md); `vendor_graph.rs` checks the resolved graph.
#[test]
fn winit_keeps_the_wayland_text_input_until_the_seat_goes() {
fn vendor_provenance_winit_keeps_the_wayland_text_input_until_the_seat_goes() {
// winit 0.30.13 destroys a Wayland seat's text input whenever the seat loses any capability (a
// touch screen or tablet unplugged, a remote-desktop session ending) and recreates it only when
// a capability is added, so IME stops working in a running PdfCraft until it is restarted.
@@ -1,7 +1,9 @@
//! vendor/winit patch (4) (vendor/README.md).
//! Provenance-only: reads the retained `vendor/` copy, not the resolved dependency, so it is
//! not runtime coverage. `vendor_graph.rs` checks the resolved graph identity.
//! Retained vendor provenance for winit patch (4) (vendor/README.md); `vendor_graph.rs` checks the resolved graph.
#[test]
fn winit_maximizes_a_hidden_windows_window_only_when_it_is_shown() {
fn vendor_provenance_winit_maximizes_a_hidden_windows_window_only_when_it_is_shown() {
// eframe creates PdfCraft's window hidden, restores the saved maximized state and shows the
// window once its first frame is drawn. winit 0.30.13 applies the maximized state with
// `ShowWindow(SW_MAXIMIZE)`, which shows a hidden window, so a window closed maximized came back
@@ -1,7 +1,9 @@
//! vendor/winit patch (3) (vendor/README.md).
//! Provenance-only: reads the retained `vendor/` copy, not the resolved dependency, so it is
//! not runtime coverage. `vendor_graph.rs` checks the resolved graph identity.
//! Retained vendor provenance for winit patch (3) (vendor/README.md); `vendor_graph.rs` checks the resolved graph.
#[test]
fn winit_reads_the_windows_ime_cursor_only_when_it_is_reported() {
fn vendor_provenance_winit_reads_the_windows_ime_cursor_only_when_it_is_reported() {
// winit 0.30.13 reads `GCS_CURSORPOS` for every composition without a target clause, whether
// or not `WM_IME_COMPOSITION` says the IME set it. The Microsoft Korean IME never sets it, so
// the composition's cursor read as 0, before the syllable being composed. vendor/winit puts it
+3 -1
View File
@@ -1,5 +1,7 @@
//! Provenance-only: reads the retained `vendor/` copy, not the resolved dependency, so it is
//! not runtime coverage. `vendor_graph.rs` checks the resolved graph identity.
#[test]
fn winit_carries_the_x11_server_dpi_fallback() {
fn vendor_provenance_winit_carries_the_x11_server_dpi_fallback() {
// The behavior tests live beside the policy in winit (util::randr::tests).
// This guards PdfCraft's vendored copy, which workspace tests do not test itself.
let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../..");
@@ -1,7 +1,9 @@
//! vendor/winit patch (5) (vendor/README.md).
//! Provenance-only: reads the retained `vendor/` copy, not the resolved dependency, so it is
//! not runtime coverage. `vendor_graph.rs` checks the resolved graph identity.
//! Retained vendor provenance for winit patch (5) (vendor/README.md); `vendor_graph.rs` checks the resolved graph.
#[test]
fn winit_focuses_the_x11_input_context_it_replaces() {
fn vendor_provenance_winit_focuses_the_x11_input_context_it_replaces() {
// egui allows IME when a text field gains focus and disallows it when the field loses focus.
// On X11, winit 0.30.13 replaces the window's input context each time and leaves focusing the
// new one to the next focus event, which never comes while PdfCraft's window keeps the focus:
+39 -39
View File
@@ -14,27 +14,27 @@
(highlight, sticky note, stamp, ...), so annotation geometry follows the layout.
-->
<style>
@font-face { font-family: "PC Mono"; src: url("{{ASSETS}}/fonts/JetBrainsMono-Regular.ttf"); }
@font-face { font-family: "PC Inter"; src: url("{{FONTS}}/Inter[opsz,wght].ttf"); font-weight: 100 900; }
@font-face { font-family: "PC Inter"; src: url("{{FONTS}}/Inter-Italic[opsz,wght].ttf"); font-weight: 100 900; font-style: italic; }
@font-face { font-family: "PC Garamond"; src: url("{{FONTS}}/EBGaramond[wght].ttf"); font-weight: 400 800; }
@font-face { font-family: "PC Garamond"; src: url("{{FONTS}}/EBGaramond-Italic[wght].ttf"); font-weight: 400 800; font-style: italic; }
@font-face { font-family: "PC Playfair"; src: url("{{FONTS}}/PlayfairDisplay[wght].ttf"); font-weight: 400 900; }
@font-face { font-family: "PC Playfair"; src: url("{{FONTS}}/PlayfairDisplay-Italic[wght].ttf"); font-weight: 400 900; font-style: italic; }
@font-face { font-family: "PC Vibes"; src: url("{{FONTS}}/GreatVibes-Regular.ttf"); }
@font-face { font-family: "PC Math"; src: url("{{FONTS}}/STIXTwoMath-Regular.ttf"); }
@font-face { font-family: "PC Amiri"; src: url("{{FONTS}}/Amiri-Regular.ttf"); }
@font-face { font-family: "PC Hebrew"; src: url("{{FONTS}}/NotoSansHebrew[wdth,wght].ttf"); font-weight: 100 900; }
@font-face { font-family: "PC Devanagari"; src: url("{{FONTS}}/NotoSansDevanagari[wdth,wght].ttf"); font-weight: 100 900; }
@font-face { font-family: "PC Thai"; src: url("{{FONTS}}/NotoSansThai[wdth,wght].ttf"); font-weight: 100 900; }
@font-face { font-family: "PC Armenian"; src: url("{{FONTS}}/NotoSansArmenian[wdth,wght].ttf"); font-weight: 100 900; }
@font-face { font-family: "PC Georgian"; src: url("{{FONTS}}/NotoSansGeorgian[wdth,wght].ttf"); font-weight: 100 900; }
@font-face { font-family: "PC Tamil"; src: url("{{FONTS}}/NotoSansTamil[wdth,wght].ttf"); font-weight: 100 900; }
@font-face { font-family: "PC Charis"; src: url("{{FONTS}}/CharisSIL-Regular.ttf"); }
@font-face { font-family: "PC XiaoWei"; src: url("{{FONTS}}/ZCOOLXiaoWei-Regular.ttf"); }
@font-face { font-family: "PC Mincho"; src: url("{{FONTS}}/ShipporiMincho-Regular.ttf"); }
@font-face { font-family: "PC Gowun"; src: url("{{FONTS}}/GowunBatang-Regular.ttf"); }
@font-face { font-family: "PC Emoji"; src: url("{{FONTS}}/NotoColorEmoji-Regular.ttf"); }
@font-face { font-display: block; font-family: "PC Mono"; src: url("{{ASSETS}}/fonts/JetBrainsMono-Regular.ttf"); }
@font-face { font-display: block; font-family: "PC Inter"; src: url("{{FONTS}}/Inter[opsz,wght].ttf"); font-weight: 100 900; }
@font-face { font-display: block; font-family: "PC Inter"; src: url("{{FONTS}}/Inter-Italic[opsz,wght].ttf"); font-weight: 100 900; font-style: italic; }
@font-face { font-display: block; font-family: "PC Garamond"; src: url("{{FONTS}}/EBGaramond[wght].ttf"); font-weight: 400 800; }
@font-face { font-display: block; font-family: "PC Garamond"; src: url("{{FONTS}}/EBGaramond-Italic[wght].ttf"); font-weight: 400 800; font-style: italic; }
@font-face { font-display: block; font-family: "PC Playfair"; src: url("{{FONTS}}/PlayfairDisplay[wght].ttf"); font-weight: 400 900; }
@font-face { font-display: block; font-family: "PC Playfair"; src: url("{{FONTS}}/PlayfairDisplay-Italic[wght].ttf"); font-weight: 400 900; font-style: italic; }
@font-face { font-display: block; font-family: "PC Vibes"; src: url("{{FONTS}}/GreatVibes-Regular.ttf"); }
@font-face { font-display: block; font-family: "PC Math"; src: url("{{FONTS}}/STIXTwoMath-Regular.ttf"); }
@font-face { font-display: block; font-family: "PC Amiri"; src: url("{{FONTS}}/Amiri-Regular.ttf"); }
@font-face { font-display: block; font-family: "PC Hebrew"; src: url("{{FONTS}}/NotoSansHebrew[wdth,wght].ttf"); font-weight: 100 900; }
@font-face { font-display: block; font-family: "PC Devanagari"; src: url("{{FONTS}}/NotoSansDevanagari[wdth,wght].ttf"); font-weight: 100 900; }
@font-face { font-display: block; font-family: "PC Thai"; src: url("{{FONTS}}/NotoSansThai[wdth,wght].ttf"); font-weight: 100 900; }
@font-face { font-display: block; font-family: "PC Armenian"; src: url("{{FONTS}}/NotoSansArmenian[wdth,wght].ttf"); font-weight: 100 900; }
@font-face { font-display: block; font-family: "PC Georgian"; src: url("{{FONTS}}/NotoSansGeorgian[wdth,wght].ttf"); font-weight: 100 900; }
@font-face { font-display: block; font-family: "PC Tamil"; src: url("{{FONTS}}/NotoSansTamil[wdth,wght].ttf"); font-weight: 100 900; }
@font-face { font-display: block; font-family: "PC Charis"; src: url("{{FONTS}}/CharisSIL-Regular.ttf"); }
@font-face { font-display: block; font-family: "PC XiaoWei"; src: url("{{FONTS}}/ZCOOLXiaoWei-Regular.ttf"); }
@font-face { font-display: block; font-family: "PC Mincho"; src: url("{{FONTS}}/ShipporiMincho-Regular.ttf"); }
@font-face { font-display: block; font-family: "PC Gowun"; src: url("{{FONTS}}/GowunBatang-Regular.ttf"); }
@font-face { font-display: block; font-family: "PC Emoji"; src: url("{{FONTS}}/NotoColorEmoji-Regular.ttf"); }
@page { size: Letter; margin: 0; }
@@ -598,11 +598,11 @@ a.box { position: absolute; display: block; color: transparent; font-size: 1pt;
<p class="dek">Nine small plates, each exercising one piece of the PDF imaging model.</p>
<div class="gfx">
<figure>
<svg viewBox="0 0 160 120"><defs><linearGradient id="lg1" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="#2a6fdb"/><stop offset="0.5" stop-color="#1a9e8f"/><stop offset="1" stop-color="#e9a100"/></linearGradient></defs><rect width="160" height="120" rx="6" fill="url(#lg1)"/></svg>
<svg role="img" aria-label="Axial shading: three-stop linear gradient" viewBox="0 0 160 120"><defs><linearGradient id="lg1" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="#2a6fdb"/><stop offset="0.5" stop-color="#1a9e8f"/><stop offset="1" stop-color="#e9a100"/></linearGradient></defs><rect width="160" height="120" rx="6" fill="url(#lg1)"/></svg>
<figcaption class="caption"><b>Axial shading</b> &middot; three-stop linear gradient</figcaption>
</figure>
<figure>
<svg viewBox="0 0 160 120"><defs><radialGradient id="rg1" cx="0.35" cy="0.35" r="0.75"><stop offset="0" stop-color="#fff5d6"/><stop offset="0.35" stop-color="#e9a100"/><stop offset="0.75" stop-color="#e4572e"/><stop offset="1" stop-color="#16213b"/></radialGradient></defs><rect width="160" height="120" rx="6" fill="#16213b"/><circle cx="80" cy="60" r="52" fill="url(#rg1)"/></svg>
<svg role="img" aria-label="Radial shading: off-centre focal point" viewBox="0 0 160 120"><defs><radialGradient id="rg1" cx="0.35" cy="0.35" r="0.75"><stop offset="0" stop-color="#fff5d6"/><stop offset="0.35" stop-color="#e9a100"/><stop offset="0.75" stop-color="#e4572e"/><stop offset="1" stop-color="#16213b"/></radialGradient></defs><rect width="160" height="120" rx="6" fill="#16213b"/><circle cx="80" cy="60" r="52" fill="url(#rg1)"/></svg>
<figcaption class="caption"><b>Radial shading</b> &middot; off-centre focal point</figcaption>
</figure>
<figure>
@@ -614,31 +614,31 @@ a.box { position: absolute; display: block; color: transparent; font-size: 1pt;
<figcaption class="caption"><b>Screen</b> &middot; additive light, /BM /Screen</figcaption>
</figure>
<figure>
<svg viewBox="0 0 160 120"><defs><clipPath id="cp1"><text x="80" y="88" text-anchor="middle" font-family="PC Playfair, serif" font-size="70" font-weight="bold">Clip</text></clipPath><linearGradient id="lg2" x1="0" x2="0" y1="0" y2="1"><stop offset="0" stop-color="#e4572e"/><stop offset="1" stop-color="#b83b5e"/></linearGradient></defs><rect width="160" height="120" rx="6" fill="#f1ece2"/><g clip-path="url(#cp1)"><rect width="160" height="120" fill="url(#lg2)"/><g stroke="#f2c14e" stroke-width="3">
<svg role="img" aria-label="Clipping path: glyph outlines as a clip" viewBox="0 0 160 120"><defs><clipPath id="cp1"><text x="80" y="88" text-anchor="middle" font-family="PC Playfair, serif" font-size="70" font-weight="bold">Clip</text></clipPath><linearGradient id="lg2" x1="0" x2="0" y1="0" y2="1"><stop offset="0" stop-color="#e4572e"/><stop offset="1" stop-color="#b83b5e"/></linearGradient></defs><rect width="160" height="120" rx="6" fill="#f1ece2"/><g clip-path="url(#cp1)"><rect width="160" height="120" fill="url(#lg2)"/><g stroke="#f2c14e" stroke-width="3">
<line x1="0" y1="10" x2="160" y2="130"/><line x1="0" y1="40" x2="160" y2="160"/><line x1="0" y1="-20" x2="160" y2="100"/><line x1="0" y1="-50" x2="160" y2="70"/></g></g></svg>
<figcaption class="caption"><b>Clipping path</b> &middot; glyph outlines as a clip</figcaption>
</figure>
<figure>
<svg viewBox="0 0 160 120"><defs><linearGradient id="fade" x1="0" x2="1"><stop offset="0" stop-color="#fff"/><stop offset="1" stop-color="#fff" stop-opacity="0"/></linearGradient><mask id="m1"><rect width="160" height="120" fill="url(#fade)"/></mask></defs><rect width="160" height="120" rx="6" fill="#f1ece2"/><g mask="url(#m1)"><rect x="12" y="14" width="136" height="92" rx="8" fill="#2a6fdb"/><circle cx="60" cy="60" r="26" fill="#f2c14e"/><circle cx="104" cy="60" r="26" fill="#e4572e"/></g></svg>
<svg role="img" aria-label="Soft mask: luminosity gradient fades artwork" viewBox="0 0 160 120"><defs><linearGradient id="fade" x1="0" x2="1"><stop offset="0" stop-color="#fff"/><stop offset="1" stop-color="#fff" stop-opacity="0"/></linearGradient><mask id="m1"><rect width="160" height="120" fill="url(#fade)"/></mask></defs><rect width="160" height="120" rx="6" fill="#f1ece2"/><g mask="url(#m1)"><rect x="12" y="14" width="136" height="92" rx="8" fill="#2a6fdb"/><circle cx="60" cy="60" r="26" fill="#f2c14e"/><circle cx="104" cy="60" r="26" fill="#e4572e"/></g></svg>
<figcaption class="caption"><b>Soft mask</b> &middot; luminosity gradient fades artwork</figcaption>
</figure>
<figure>
<svg viewBox="0 0 160 120"><rect width="160" height="120" rx="6" fill="#fffdf8" stroke="#e2dccf"/><g fill="none" stroke="#16213b" stroke-width="2.5"><path d="M16 26 H144" stroke-dasharray="12 6"/><path d="M16 46 H144" stroke-dasharray="2 6" stroke-linecap="round"/><path d="M16 66 H144" stroke-dasharray="18 5 3 5" stroke="#e4572e"/><path d="M16 96 Q 50 70 80 96 T 144 96" stroke="#1a9e8f" stroke-width="5" stroke-linejoin="round" stroke-dasharray="1 9" stroke-linecap="round"/></g></svg>
<svg role="img" aria-label="Dash patterns: caps, joins and phase" viewBox="0 0 160 120"><rect width="160" height="120" rx="6" fill="#fffdf8" stroke="#e2dccf"/><g fill="none" stroke="#16213b" stroke-width="2.5"><path d="M16 26 H144" stroke-dasharray="12 6"/><path d="M16 46 H144" stroke-dasharray="2 6" stroke-linecap="round"/><path d="M16 66 H144" stroke-dasharray="18 5 3 5" stroke="#e4572e"/><path d="M16 96 Q 50 70 80 96 T 144 96" stroke="#1a9e8f" stroke-width="5" stroke-linejoin="round" stroke-dasharray="1 9" stroke-linecap="round"/></g></svg>
<figcaption class="caption"><b>Dash patterns</b> &middot; caps, joins and phase</figcaption>
</figure>
<figure>
<svg viewBox="0 0 160 120"><defs><pattern id="checks" width="16" height="16" patternUnits="userSpaceOnUse"><rect width="16" height="16" fill="#f1ece2"/><rect width="8" height="8" fill="#16213b"/><rect x="8" y="8" width="8" height="8" fill="#16213b"/></pattern><pattern id="hatch" width="8" height="8" patternUnits="userSpaceOnUse" patternTransform="rotate(45)"><rect width="8" height="8" fill="#fbeccc"/><line x1="0" y1="0" x2="0" y2="8" stroke="#e9a100" stroke-width="3"/></pattern></defs><rect width="160" height="120" rx="6" fill="url(#checks)"/><circle cx="80" cy="60" r="40" fill="url(#hatch)" stroke="#16213b" stroke-width="2"/></svg>
<svg role="img" aria-label="Tiling patterns: checks and rotated hatch" viewBox="0 0 160 120"><defs><pattern id="checks" width="16" height="16" patternUnits="userSpaceOnUse"><rect width="16" height="16" fill="#f1ece2"/><rect width="8" height="8" fill="#16213b"/><rect x="8" y="8" width="8" height="8" fill="#16213b"/></pattern><pattern id="hatch" width="8" height="8" patternUnits="userSpaceOnUse" patternTransform="rotate(45)"><rect width="8" height="8" fill="#fbeccc"/><line x1="0" y1="0" x2="0" y2="8" stroke="#e9a100" stroke-width="3"/></pattern></defs><rect width="160" height="120" rx="6" fill="url(#checks)"/><circle cx="80" cy="60" r="40" fill="url(#hatch)" stroke="#16213b" stroke-width="2"/></svg>
<figcaption class="caption"><b>Tiling patterns</b> &middot; checks and rotated hatch</figcaption>
</figure>
<figure>
<svg viewBox="0 0 160 120"><rect width="160" height="120" rx="6" fill="#16213b"/><g transform="translate(80 60)"><g fill="none" stroke-width="1.2">
<svg role="img" aria-label="Fill rules: even-odd pentagram at 45% opacity" viewBox="0 0 160 120"><rect width="160" height="120" rx="6" fill="#16213b"/><g transform="translate(80 60)"><g fill="none" stroke-width="1.2">
<path id="star" d="M0 -46 L13 -14 L46 -14 L19 6 L29 40 L0 20 L-29 40 L-19 6 L-46 -14 L-13 -14 Z" stroke="#f2c14e" fill="#f2c14e" fill-opacity="0.25" fill-rule="evenodd"/>
<path d="M0 -46 L27 37 L-44 -14 L44 -14 L-27 37 Z" stroke="#e4572e" fill="#e4572e" fill-opacity="0.45" fill-rule="evenodd"/></g></g></svg>
<figcaption class="caption"><b>Fill rules</b> &middot; even-odd pentagram, 45% opacity</figcaption>
</figure>
</div>
<div class="rule"></div>
<svg viewBox="0 0 520 110" style="width:100%;height:auto;display:block">
<svg role="img" aria-label="Blend spectrum: multiplied gradient bands" viewBox="0 0 520 110" style="width:100%;height:auto;display:block">
<defs><linearGradient id="spec" x1="0" x2="1"><stop offset="0" stop-color="#16213b"/><stop offset="0.25" stop-color="#2a6fdb"/><stop offset="0.5" stop-color="#1a9e8f"/><stop offset="0.75" stop-color="#e9a100"/><stop offset="1" stop-color="#e4572e"/></linearGradient></defs>
<g style="mix-blend-mode:multiply">
<path d="M0 80 C 80 10, 160 110, 260 50 S 440 20, 520 70 L520 110 L0 110Z" fill="url(#spec)" opacity="0.85"/>
@@ -789,16 +789,16 @@ a.box { position: absolute; display: block; color: transparent; font-size: 1pt;
</div>
<div class="canvas">
<span class="lab" style="left:10pt;top:8pt">Review canvas</span>
<a class="box" style="left:12pt;top:26pt;width:152pt;height:40pt" href="https://mark.pdfcraft.invalid/freetext/1">.</a>
<a class="box" style="left:196pt;top:22pt;width:20pt;height:20pt" href="https://mark.pdfcraft.invalid/note/1">.</a>
<a class="box" style="left:196pt;top:60pt;width:18pt;height:22pt" href="https://mark.pdfcraft.invalid/attach/1">.</a>
<a class="box" style="left:16pt;top:88pt;width:90pt;height:60pt" href="https://mark.pdfcraft.invalid/square/1">.</a>
<a class="box" style="left:120pt;top:92pt;width:90pt;height:60pt" href="https://mark.pdfcraft.invalid/circle/1">.</a>
<a class="box" style="left:16pt;top:170pt;width:94pt;height:80pt" href="https://mark.pdfcraft.invalid/polygon/1">.</a>
<a class="box" style="left:120pt;top:170pt;width:96pt;height:80pt" href="https://mark.pdfcraft.invalid/polyline/1">.</a>
<a class="box" style="left:16pt;top:268pt;width:196pt;height:40pt" href="https://mark.pdfcraft.invalid/line/1">.</a>
<a class="box" style="left:16pt;top:322pt;width:196pt;height:50pt" href="https://mark.pdfcraft.invalid/ink/1">.</a>
<a class="box" style="left:30pt;top:388pt;width:170pt;height:56pt" href="https://mark.pdfcraft.invalid/stamp/1">.</a>
<a class="box" style="left:12pt;top:26pt;width:152pt;height:40pt" href="https://mark.pdfcraft.invalid/freetext/1">freetext</a>
<a class="box" style="left:196pt;top:22pt;width:20pt;height:20pt" href="https://mark.pdfcraft.invalid/note/1">note</a>
<a class="box" style="left:196pt;top:60pt;width:18pt;height:22pt" href="https://mark.pdfcraft.invalid/attach/1">attach</a>
<a class="box" style="left:16pt;top:88pt;width:90pt;height:60pt" href="https://mark.pdfcraft.invalid/square/1">square</a>
<a class="box" style="left:120pt;top:92pt;width:90pt;height:60pt" href="https://mark.pdfcraft.invalid/circle/1">circle</a>
<a class="box" style="left:16pt;top:170pt;width:94pt;height:80pt" href="https://mark.pdfcraft.invalid/polygon/1">polygon</a>
<a class="box" style="left:120pt;top:170pt;width:96pt;height:80pt" href="https://mark.pdfcraft.invalid/polyline/1">polyline</a>
<a class="box" style="left:16pt;top:268pt;width:196pt;height:40pt" href="https://mark.pdfcraft.invalid/line/1">line</a>
<a class="box" style="left:16pt;top:322pt;width:196pt;height:50pt" href="https://mark.pdfcraft.invalid/ink/1">ink</a>
<a class="box" style="left:30pt;top:388pt;width:170pt;height:56pt" href="https://mark.pdfcraft.invalid/stamp/1">stamp</a>
</div>
</div>
<div class="folio"><span>Review &amp; Markup</span><b>9</b></div>
+4
View File
@@ -176,3 +176,7 @@ real_name = "Nick Nyssen"
[people.agent-reed]
sync_github_name = true
[people.dotCooCoo]
real_name = "Robert Lee"
sync_github_name = true
+20 -14
View File
@@ -211,6 +211,25 @@ fn close(marks: &mut Vec<Mark>, matching: &mut usize, out: &mut HashMap<i64, [f6
draw(marks, b);
}
/// The page-space box a `Do` operator paints: a form's transformed `/BBox`, or the unit square for an image.
/// `None` when the operand is not a resolvable XObject or the form's box is malformed.
fn xobject_bbox(doc: &Document, xobjects: &Dict, op: &pdfcraft_content::Op, top: &Matrix) -> Option<[f64; 4]> {
let r = op.name(0).and_then(|n| xobjects.get(n)).and_then(Object::as_ref)?;
Some(match &*doc.get(r) {
Object::Stream(s) if s.dict.name(b"Subtype") == Some(b"Form") => {
let bb: Vec<f64> =
s.dict.get(b"BBox").and_then(|b| b.as_array().map(|a| a.iter().filter_map(Object::as_f64).collect())).unwrap_or_default();
let m = Matrix::from_operands(s.dict.get(b"Matrix").and_then(|m| m.as_array()).map(Vec::as_slice).unwrap_or(&[]))
.unwrap_or(Matrix([1.0, 0.0, 0.0, 1.0, 0.0, 0.0]));
match bb[..] {
[a, b, c, d] => m.then(top).bbox([a, b, c, d]),
_ => return None,
}
}
_ => top.bbox([0.0, 0.0, 1.0, 1.0]),
})
}
/// Where each of the marked content `ids` is drawn on a page (images, forms and paths), in one pass
/// over the page. What a sequence draws counts for every sequence of `ids` around it too.
pub(crate) fn content_bboxes(doc: &Document, page: &Dict, ids: &HashSet<i64>) -> HashMap<i64, [f64; 4]> {
@@ -274,20 +293,7 @@ pub(crate) fn content_bboxes(doc: &Document, page: &Dict, ids: &HashSet<i64>) ->
path.clear();
}
b"Do" if inside => {
let Some(r) = op.name(0).and_then(|n| xobjects.get(n)).and_then(Object::as_ref) else { continue };
let unit = match &*doc.get(r) {
Object::Stream(s) if s.dict.name(b"Subtype") == Some(b"Form") => {
let bb: Vec<f64> =
s.dict.get(b"BBox").and_then(|b| b.as_array().map(|a| a.iter().filter_map(Object::as_f64).collect())).unwrap_or_default();
let m = Matrix::from_operands(s.dict.get(b"Matrix").and_then(|m| m.as_array()).map(Vec::as_slice).unwrap_or(&[]))
.unwrap_or(Matrix([1.0, 0.0, 0.0, 1.0, 0.0, 0.0]));
match bb[..] {
[a, b, c, d] => m.then(&top).bbox([a, b, c, d]),
_ => continue,
}
}
_ => top.bbox([0.0, 0.0, 1.0, 1.0]),
};
let Some(unit) = xobject_bbox(doc, &xobjects, &op, &top) else { continue };
draw(&mut marks, unit);
}
b"BI" if inside => draw(&mut marks, top.bbox([0.0, 0.0, 1.0, 1.0])),
+33 -27
View File
@@ -132,6 +132,38 @@ fn harmless_inside(op: &[u8]) -> bool {
)
}
/// The `(BT, ET)` operator index pairs of each text object that shows text, or why the page cannot be tagged.
fn text_spans(ops: &[Op], index: usize) -> Result<Vec<(usize, usize)>, AutoTagError> {
let mut start = None;
let mut has_text = false;
let mut spans = Vec::new();
for (at, op) in ops.iter().enumerate() {
match op.op.as_slice() {
b"BT" if start.is_none() => {
start = Some(at);
has_text = false;
}
b"ET" => {
let Some(first) = start.take() else { return Err(unsupported(index, "unmatched ET operator")) };
if has_text {
spans.push((first, at));
if spans.len() > MAX_TEXT_OBJECTS {
return Err(unsupported(index, "too many text objects (maximum 4096)"));
}
}
}
b"Tj" | b"TJ" | b"'" | b"\"" if start.is_some() => has_text = true,
name if start.is_some() && harmless_inside(name) => {}
name if start.is_none() && harmless_outside(name) => {}
_ => return Err(unsupported(index, format!("unsupported or painted operator {}", String::from_utf8_lossy(&op.op)))),
}
}
if start.is_some() {
return Err(unsupported(index, "unterminated BT text object"));
}
Ok(spans)
}
fn plan(doc: &Document) -> Result<Vec<Plan>, AutoTagError> {
let root = doc.root().ok_or(AutoTagError::NoCatalog)?;
let catalog = doc.get(root);
@@ -163,33 +195,7 @@ fn plan(doc: &Document) -> Result<Vec<Plan>, AutoTagError> {
if parsed.skipped > 0 || parsed.ops.len() > MAX_OPERATORS {
return Err(unsupported(index, "content has malformed or too many operators"));
}
let mut start = None;
let mut has_text = false;
let mut spans = Vec::new();
for (at, op) in parsed.ops.iter().enumerate() {
match op.op.as_slice() {
b"BT" if start.is_none() => {
start = Some(at);
has_text = false;
}
b"ET" => {
let Some(first) = start.take() else { return Err(unsupported(index, "unmatched ET operator")) };
if has_text {
spans.push((first, at));
if spans.len() > MAX_TEXT_OBJECTS {
return Err(unsupported(index, "too many text objects (maximum 4096)"));
}
}
}
b"Tj" | b"TJ" | b"'" | b"\"" if start.is_some() => has_text = true,
name if start.is_some() && harmless_inside(name) => {}
name if start.is_none() && harmless_outside(name) => {}
_ => return Err(unsupported(index, format!("unsupported or painted operator {}", String::from_utf8_lossy(&op.op)))),
}
}
if start.is_some() {
return Err(unsupported(index, "unterminated BT text object"));
}
let spans = text_spans(&parsed.ops, index)?;
total = total.saturating_add(spans.len());
out.push(Plan { page: page.obj, ops: parsed.ops, spans });
}
+10 -11
View File
@@ -53,6 +53,15 @@ struct Walk<'a> {
budget: DecodeBudget,
}
fn bdc_marks(doc: &Document, op: &pdfcraft_content::Op, props: &Dict) -> bool {
op.name(0) == Some(b"Artifact")
|| match op.operands.get(1) {
Some(Object::Dict(d)) => d.contains(b"MCID"),
Some(Object::Name(n)) => props.get(n).map(|x| doc.resolve(x)).and_then(|x| x.as_dict().map(|d| d.contains(b"MCID"))).unwrap_or(false),
_ => false,
}
}
impl Walk<'_> {
fn sub(&self, res: &Dict, key: &[u8]) -> Dict {
res.get(key).map(|x| self.doc.resolve(x)).and_then(|x| x.as_dict().cloned()).unwrap_or_default()
@@ -68,17 +77,7 @@ impl Walk<'_> {
let inside = covered || stack.last().copied().unwrap_or(false);
match op.op.as_slice() {
b"BMC" => stack.push(inside || op.name(0) == Some(b"Artifact")),
b"BDC" => {
let marks = op.name(0) == Some(b"Artifact")
|| match op.operands.get(1) {
Some(Object::Dict(d)) => d.contains(b"MCID"),
Some(Object::Name(n)) => {
props.get(n).map(|x| self.doc.resolve(x)).and_then(|x| x.as_dict().map(|d| d.contains(b"MCID"))).unwrap_or(false)
}
_ => false,
};
stack.push(inside || marks);
}
b"BDC" => stack.push(inside || bdc_marks(self.doc, &op, &props)),
b"EMC" => {
stack.pop();
}
+1 -1
View File
@@ -380,7 +380,7 @@ fn table_doc(th: &str, extra: &[&str], kids: &str) -> Document {
th.to_string(),
"<< /S /TD >>".to_string(),
];
objs.extend(extra.iter().map(|s| s.to_string()));
objs.extend(extra.iter().map(ToString::to_string));
pdf(&objs, "")
}
+9 -2
View File
@@ -9,10 +9,12 @@ Comments (annotations), ISO 32000-2 §12.5. Layer L3, depends on `pdfcraft-cos`,
line and arrow (`Line` with `/LE`), freehand drawing (`Ink`) and text box (`FreeText`).
- **Appearance streams** (`appearance::build`) generated from the annotation dictionary, so new
and restyled comments look the same in every viewer. Highlights multiply (`/BM /Multiply`).
A line's leader lines (`/LL`, `/LLE`, `/LLO`) and caption (`/Cap`, `/CP`, `/CO`) are drawn as
ISO 32000-2 Table 178 places them, the caption in black Helvetica 10.
Note icons are PdfCraft's own drawings. Text boxes use standard Helvetica (WinAnsi), with
line breaking by approximate Helvetica proportions (no font program is bundled). Text it can't
draw (in a text box, callout, Fill & Sign text, measurement label or dynamic stamp's by-line;
`appearance::undrawable_text`) is kept as typed and drawn as `?`, and the comment is marked with
draw (in a text box, callout, Fill & Sign text, line caption, measurement label or dynamic
stamp's by-line; `appearance::undrawable_text`) is kept as typed and drawn as `?`, and the comment is marked with
the first such character (`pdfcraft_fonts::UNDRAWN_MARK`) so the engine reports the edit and
flattening refuses to make it permanent. Two refusals (`AnnotError::Undrawable`): a redaction
mark's overlay text, which becomes page content when applied; and a restyle or resize of a
@@ -51,6 +53,11 @@ deterministic; the engine supplies them.
signature) and PdfCraft's rubber stamps counterrotate their appearance on rotated pages, so
the picture or label reads upright as the page is displayed. Restyling a picture stamp keeps
that appearance matrix. The rotation is the page's `/Rotate` at placement.
- Sticky notes and file attachments are not counterrotated: they carry the NoRotate flag and
their icon is drawn in an unturned 20 × 20 box. A viewer keeps them upright on a turned page,
about the upper-left corner of `/Rect` (ISO 32000-2 §12.5.3). PdfCraft's renderer does so
(vendored hayro-interpret patch 37), and `Summary::no_rotate` tells the UI where the icon is
drawn.
## Not yet
+397 -41
View File
@@ -180,23 +180,42 @@ fn interior_color(d: &Dict, fallback: Option<Rgb>) -> Option<Rgb> {
color(d, b"IC").flatten().or(fallback)
}
/// The border width (ISO 32000-2 §12.5.4): `/BS /W` when there is a border style dictionary, which
/// makes `/Border` ignored (Table 166), else the third element of `/Border [hr vr w [dash]]`, read
/// whether or not the optional fourth element, a dash array, follows. 1 when neither says, and
/// when the number given is negative or not finite.
pub(crate) fn border_width(d: &Dict) -> f64 {
if let Some(w) = d.get(b"BS").and_then(|b| b.as_dict()).and_then(|b| b.get(b"W")).and_then(|w| w.as_f64()) {
return w.max(0.0);
}
match nums(d, b"Border") {
Some(b) if b.len() >= 3 => b[2].max(0.0),
_ => 1.0,
}
let width = match d.get(b"BS").and_then(Object::as_dict) {
Some(bs) => bs.get(b"W").and_then(Object::as_f64),
None => d.get(b"Border").and_then(Object::as_array).and_then(|b| b.get(2)).and_then(Object::as_f64),
};
width.filter(|w| w.is_finite() && *w >= 0.0).unwrap_or(1.0)
}
/// Dash pattern operator for a dashed border, if any.
/// Elements a dash array may have before it is drawn solid instead: the lengths are written into
/// the appearance as they are, so a file can't make it arbitrarily large.
const MAX_DASH: usize = 64;
/// A dash array (§8.4.3.6) as drawn: every element finite and non-negative, not all zero (that
/// pattern is invalid) and at most [`MAX_DASH`] long. `None` for anything else, which is drawn solid.
fn dash_array(o: &Object) -> Option<Vec<f64>> {
let a = o.as_array().filter(|a| !a.is_empty() && a.len() <= MAX_DASH)?;
let v: Vec<f64> = a.iter().map(Object::as_f64).collect::<Option<_>>()?;
(v.iter().all(|x| x.is_finite() && *x >= 0.0) && v.iter().any(|x| *x > 0.0)).then_some(v)
}
/// Dash pattern operator for a dashed border, if any: `/BS /S /D` with its `/D` (default `[3]`,
/// Table 168), or, without `/BS`, the dash array that may follow the width in `/Border` (Table 166).
fn dash(d: &Dict) -> String {
let Some(bs) = d.get(b"BS").and_then(|b| b.as_dict()) else { return String::new() };
if bs.name(b"S") != Some(b"D") {
return String::new();
}
let arr = nums(bs, b"D").filter(|a| !a.is_empty() && a.iter().all(|x| *x >= 0.0)).unwrap_or_else(|| vec![3.0]);
let arr = match d.get(b"BS").and_then(Object::as_dict) {
Some(bs) if bs.name(b"S") != Some(b"D") => return String::new(),
Some(bs) => match bs.get(b"D") {
None => Some(vec![3.0]),
Some(o) => dash_array(o),
},
None => d.get(b"Border").and_then(Object::as_array).and_then(|b| b.get(3)).and_then(dash_array),
};
let Some(arr) = arr else { return String::new() };
format!("[{}] 0 d\n", arr.iter().map(|x| n(*x)).collect::<Vec<_>>().join(" "))
}
@@ -283,13 +302,14 @@ fn text_turn(d: &Dict) -> i64 {
/// The first text [`build`] would draw in the standard fonts (Helvetica, WinAnsiEncoding) that
/// they can't, which would come out as `?`: what it is (for the message) and the character. The
/// text of a text box, callout or Fill & Sign text, a measurement's label, a dynamic stamp's
/// "By …" line, and a redaction mark's overlay text (drawn when it is applied). `None` when all of
/// text of a text box, callout or Fill & Sign text, a line's caption, a measurement's label, a
/// dynamic stamp's "By …" line, and a redaction mark's overlay text (drawn when it is applied). `None` when all of
/// it can be drawn.
pub fn undrawable_text(d: &Dict) -> Option<(&'static str, char)> {
let text = |key: &[u8]| d.get(key).and_then(Object::as_string).map(PdfString::to_text);
let (what, text) = match d.name(b"Subtype")? {
b"FreeText" => ("the comment's text", text(b"Contents")?),
b"Line" if !d.contains(b"PCMeasureValue") => ("the line's caption", line_caption(d)?),
b"Line" | b"PolyLine" | b"Polygon" => ("the measurement label", text(b"PCMeasureValue")?),
b"Stamp" if matches!(d.get(b"PCStamp"), Some(Object::Bool(true))) => ("the stamp's \"By\" line", text(b"PCByLine")?),
// Drawn in Helvetica when the redaction is applied: refused when it is marked.
@@ -299,6 +319,55 @@ pub fn undrawable_text(d: &Dict) -> Option<(&'static str, char)> {
Some((what, first_undrawable(&text)?))
}
/// `/Font` resources naming `/Helv`: standard Helvetica with WinAnsiEncoding.
fn helvetica_resource() -> Object {
let mut font = Dict::new();
font.set(b"Type".to_vec(), Object::name("Font"));
font.set(b"Subtype".to_vec(), Object::name("Type1"));
font.set(b"BaseFont".to_vec(), Object::name("Helvetica"));
font.set(b"Encoding".to_vec(), Object::name("WinAnsiEncoding"));
let mut fonts = Dict::new();
fonts.set(b"Helv".to_vec(), Object::Dict(font));
Object::Dict(fonts)
}
/// Where a caret and its paragraph symbol go within `rect`: the box the caret is drawn in, and for
/// `/Sy /P` the symbol's baseline origin and font size (ISO 32000-2 Table 183).
///
/// The caret lies within `/Rect` less `/RD` (left, top, right, bottom), when `/RD` is four finite,
/// non-negative numbers that leave a box; otherwise within `/Rect`. The ¶ sits to the right of the
/// caret, its height a little over half the caret's, in the room `/RD` leaves on the right; when
/// that is too narrow, the caret gives up to half its width and the symbol shrinks to what is left,
/// so both stay inside `/Rect` (the form's `/BBox`).
fn caret_layout(d: &Dict, rect: [f64; 4]) -> ([f64; 4], Option<(f64, f64, f64)>) {
let rd = nums(d, b"RD").filter(|r| r.len() == 4 && r.iter().all(|x| x.is_finite() && *x >= 0.0));
let mut caret = match rd {
Some(rd) => [rect[0] + rd[0], rect[1] + rd[3], rect[2] - rd[2], rect[3] - rd[1]],
None => rect,
};
if !(caret[2] > caret[0] && caret[3] > caret[1]) {
caret = rect;
}
if d.name(b"Sy") != Some(b"P") {
return (caret, None);
}
let size = (caret[3] - caret[1]) * 0.6;
let (gap, glyph) = (size * 0.1, text_width("\u{b6}", size));
let need = gap + glyph;
let room = rect[2] - caret[2];
if room < need {
caret[2] -= (need - room).min((caret[2] - caret[0]) * 0.5);
}
let room = rect[2] - caret[2];
let scale = if need > room { room / need } else { 1.0 };
let size = size * scale;
if !(size.is_finite() && size > 0.0) {
return (caret, None);
}
// The pilcrow descends about a sixth of the size below its baseline.
(caret, Some((caret[2] + gap * scale, caret[1] + size * 0.18, size)))
}
/// Draw the normal appearance of an annotation, or `None` if this subtype/variant isn't supported.
/// Text the standard fonts can't draw comes out as `?`: [`undrawable_text`] says which, and
/// [`crate::set_appearance`] marks the annotation with it (`pdfcraft_fonts::UNDRAWN_MARK`).
@@ -321,6 +390,8 @@ pub fn build(d: &Dict) -> Option<Stream> {
let w = border_width(d);
let mut res = Dict::new();
let mut c = String::new();
// Content after `c` that isn't UTF-8 (WinAnsi text).
let mut tail: Vec<u8> = Vec::new();
let markup = matches!(subtype.as_slice(), b"Highlight" | b"Underline" | b"StrikeOut" | b"Squiggly");
if let Some(gs) = ext_gstate(opacity, subtype == b"Highlight") {
res.set(b"ExtGState".to_vec(), Object::Dict(gs));
@@ -445,13 +516,29 @@ pub fn build(d: &Dict) -> Option<Stream> {
return None;
}
let fill = interior_color(d, Some(col)).unwrap_or(col);
let layout = line_layout(d, [(l[0], l[1]), (l[2], l[3])], w);
let [p, q] = layout.line;
c.push_str(&format!("{}{}{} w 1 J 1 j\n{}", rg_stroke(col), rg(fill), n(w), dash(d)));
c.push_str(&format!("{} {} m {} {} l S\n[] 0 d\n", n(l[0]), n(l[1]), n(l[2]), n(l[3])));
for (end, (tip, from)) in ends.iter().zip([((l[0], l[1]), (l[2], l[3])), ((l[2], l[3]), (l[0], l[1]))]) {
for [s, e] in layout.leaders.iter().chain(&layout.strokes).chain(&layout.tick) {
c.push_str(&format!("{} {} m {} {} l S\n", n(s.0), n(s.1), n(e.0), n(e.1)));
}
c.push_str("[] 0 d\n");
for (end, (tip, from)) in ends.iter().zip([(p, q), (q, p)]) {
if !line_end(&mut c, end, tip, from, w) {
return None;
}
}
if let Some((text, m)) = layout.caption {
// The caption is black, in the standard font the measurement label uses.
tail.extend(
format!("q 0 g BT /Helv {} Tf {} {} {} {} {} {} Tm ", n(CAPTION_SIZE), n(m[0]), n(m[1]), n(m[2]), n(m[3]), n(m[4]), n(m[5]))
.bytes(),
);
// WinAnsi bytes go into the stream as-is, not through UTF-8.
tail.extend(literal(&win_ansi(&text)));
tail.extend_from_slice(b" Tj ET Q\n");
res.set(b"Font".to_vec(), helvetica_resource());
}
}
b"Polygon" | b"PolyLine" => {
let v = nums(d, b"Vertices").filter(|v| v.len() >= 4 && v.len() % 2 == 0 && v.iter().all(|x| x.is_finite()))?;
@@ -512,7 +599,8 @@ pub fn build(d: &Dict) -> Option<Stream> {
b"Caret" => {
// A filled caret: two curved flanks meeting at the top centre.
let col = stroke.unwrap_or([0.0, 0.47, 0.84]);
let [x0, y0, x1, y1] = rect;
let (caret, pilcrow) = caret_layout(d, rect);
let [x0, y0, x1, y1] = caret;
let (cx, h) = ((x0 + x1) / 2.0, y1 - y0);
c.push_str(&format!(
"{}{} {} m {} {} {} {} {} {} c {} {} {} {} {} {} c h f\n",
@@ -532,11 +620,22 @@ pub fn build(d: &Dict) -> Option<Stream> {
n(x1),
n(y0)
));
if let Some((x, y, size)) = pilcrow {
// `/Sy /P`: a new paragraph symbol beside the caret (Table 183), in its colour.
// 0xB6 is the pilcrow in WinAnsiEncoding.
let mut out = c.into_bytes();
out.extend(format!("BT /Helv {} Tf {} {} Td (", n(size), n(x), n(y)).bytes());
out.push(0xB6);
out.extend_from_slice(b") Tj ET\n");
res.set(b"Font".to_vec(), helvetica_resource());
return Some(form(rect, &out, res));
}
}
b"Ink" => {
let col = stroke?;
let list = d.get(b"InkList")?.as_array()?;
c.push_str(&format!("{}{} w 1 J 1 j\n", rg_stroke(col), n(w)));
// `/BS` gives an ink stroke its width and dash pattern (Table 182).
c.push_str(&format!("{}{} w 1 J 1 j\n{}", rg_stroke(col), n(w), dash(d)));
for s in list {
let pts: Vec<f64> = s.as_array()?.iter().map(|o| o.as_f64()).collect::<Option<_>>()?;
let pts: Vec<(f64, f64)> = pts.as_chunks::<2>().0.iter().map(|p| (p[0], p[1])).collect();
@@ -670,7 +769,8 @@ pub fn build(d: &Dict) -> Option<Stream> {
}
let kind = crate::StampKind::from_name(other)?;
let by = d.get(b"PCByLine").and_then(|o| o.as_string()).map(PdfString::to_text);
return Some(turned(stamp(kind, draw, stroke.unwrap_or(kind.color()), by.as_deref(), opacity, res)));
let sign_here = kind.group() == crate::StampGroup::SignHere;
return Some(turned(stamp(kind.label(), sign_here, draw, stroke.unwrap_or(kind.color()), by.as_deref(), opacity, res)));
}
}
if turn != 0 {
@@ -773,14 +873,7 @@ pub fn build(d: &Dict) -> Option<Stream> {
y -= size * 1.2;
}
out.extend_from_slice(b"ET\n");
let mut font = Dict::new();
font.set(b"Type".to_vec(), Object::name("Font"));
font.set(b"Subtype".to_vec(), Object::name("Type1"));
font.set(b"BaseFont".to_vec(), Object::name("Helvetica"));
font.set(b"Encoding".to_vec(), Object::name("WinAnsiEncoding"));
let mut fonts = Dict::new();
fonts.set(b"Helv".to_vec(), Object::Dict(font));
res.set(b"Font".to_vec(), Object::Dict(fonts));
res.set(b"Font".to_vec(), helvetica_resource());
let mut stream = form(full, &out, res);
if let Some(m) = matrix {
stream.dict.set(b"Matrix".to_vec(), Object::Array(m.iter().copied().map(Object::Real).collect()));
@@ -792,6 +885,7 @@ pub fn build(d: &Dict) -> Option<Stream> {
// PdfCraft measurement captions are kept separate from the comment's free-form text.
// A restyle regenerates the path and its value together.
let mut out = c.into_bytes();
out.extend(tail);
if let Some(value) = d.get(b"PCMeasureValue").and_then(Object::as_string) {
let value = value.to_text();
if value.chars().count() <= 256 && matches!(subtype.as_slice(), b"Line" | b"PolyLine" | b"Polygon") {
@@ -803,22 +897,285 @@ pub fn build(d: &Dict) -> Option<Stream> {
// WinAnsi bytes (e.g. 0xB2 for "²") go into the stream as-is, not through UTF-8.
out.extend(literal(&win_ansi(&value)));
out.extend_from_slice(b" Tj ET\n");
let mut font = Dict::new();
font.set(b"Type".to_vec(), Object::name("Font"));
font.set(b"Subtype".to_vec(), Object::name("Type1"));
font.set(b"BaseFont".to_vec(), Object::name("Helvetica"));
font.set(b"Encoding".to_vec(), Object::name("WinAnsiEncoding"));
let mut fonts = Dict::new();
fonts.set(b"Helv".to_vec(), Object::Dict(font));
res.set(b"Font".to_vec(), Object::Dict(fonts));
res.set(b"Font".to_vec(), helvetica_resource());
}
}
Some(form(rect, &out, res))
}
/// The label and colour of a standard rubber stamp name (ISO 32000-2 Table 184), for a stamp
/// another program wrote without an appearance. Names are matched byte for byte, as PDF names
/// are compared (§7.3.5). Eight are stamps of PdfCraft's palette; the other six take a label of
/// their own and the palette's colour for their meaning.
fn standard_stamp(name: &[u8]) -> Option<(&'static str, Rgb)> {
use crate::StampKind::*;
let palette = [Approved, NotApproved, NotForPublicRelease, Confidential, Final, ForComment, Draft, ForPublicRelease];
if let Some(kind) = palette.into_iter().find(|k| k.name().as_bytes() == name) {
return Some((kind.label(), kind.color()));
}
let (label, like) = match name {
b"Experimental" => ("EXPERIMENTAL", Draft),
b"AsIs" => ("AS IS", Draft),
b"Expired" => ("EXPIRED", NotApproved),
b"Sold" => ("SOLD", Approved),
b"Departmental" => ("DEPARTMENTAL", Draft),
b"TopSecret" => ("TOP SECRET", Confidential),
_ => return None,
};
Some((label, like.color()))
}
/// The neutral grey of a stamp whose name has no drawing.
const PLACEHOLDER_GREY: Rgb = [0.45, 0.45, 0.45];
/// The display appearance of a rubber stamp another program wrote without one: the stamp its
/// `/Name` names (Draft when there is none, Table 184's default) in its `/C` colour or the
/// stamp's own, or for any other name a thin grey frame with both diagonals, so the stamp stays
/// visible and can be selected. The frame is grey whatever the `/C`: it stands in for a stamp
/// that cannot be drawn, so it takes none of that stamp's colour. The name is never drawn as text.
///
/// For display only ([`crate::with_missing_appearances`]): [`build`] declines these stamps, so
/// edits (restyling, flattening) never write this drawing into the file. `None` for any other
/// annotation, one of PdfCraft's own stamps, a dictionary with an `/AP` (a stamp's own artwork is
/// never replaced; the display copy passes the dictionary without an `/AP` that has no normal
/// appearance), or a `/Rect` that isn't finite or is under a point wide or high.
pub(crate) fn display_stamp(d: &Dict) -> Option<Stream> {
let own = matches!(d.get(b"PCStamp"), Some(Object::Bool(true))) || d.contains(b"PCPicture") || d.contains(b"PCOutline");
if d.name(b"Subtype") != Some(b"Stamp") || own || d.contains(b"AP") {
return None;
}
let rect = nums(d, b"Rect")?;
let [a, b, c, e] = rect.as_slice() else { return None };
let rect = [a.min(*c), b.min(*e), a.max(*c), b.max(*e)];
if !rect.iter().all(|v| v.is_finite()) || rect[2] - rect[0] < 1.0 || rect[3] - rect[1] < 1.0 {
return None;
}
let opacity = d.get(b"CA").and_then(|o| o.as_f64()).unwrap_or(1.0).clamp(0.0, 1.0);
// A malformed `/C` falls back to the stamp's own colour rather than hiding the stamp.
let stroke = color(d, b"C").flatten();
let mut res = Dict::new();
if let Some(gs) = ext_gstate(opacity, false) {
res.set(b"ExtGState".to_vec(), Object::Dict(gs));
}
// A stamp whose intent (`/IT`, PDF 2.0) is an image or a snapshot has no `/Name` to default.
let stamp_intent = d.name(b"IT").is_none_or(|it| it == b"Stamp");
let name = d.name(b"Name").or(stamp_intent.then_some(b"Draft".as_slice()));
if let Some((label, col)) = name.and_then(standard_stamp) {
return Some(stamp(label, false, rect, stroke.unwrap_or(col), None, opacity, res));
}
let [x0, y0, x1, y1] = rect;
let (a0, b0, a1, b1) = (x0 + 0.5, y0 + 0.5, x1 - 0.5, y1 - 0.5);
let mut c = String::new();
if opacity < 1.0 {
c.push_str("/GS0 gs\n");
}
c.push_str(&format!(
"{}1 w\n{} {} {} {} re\n{} {} m {} {} l\n{} {} m {} {} l\nS\n",
// Grey whatever the `/C`: the placeholder is not the stamp, so it takes none of its colour.
rg_stroke(PLACEHOLDER_GREY),
n(a0),
n(b0),
n(a1 - a0),
n(b1 - b0),
n(a0),
n(b0),
n(a1),
n(b1),
n(a0),
n(b1),
n(a1),
n(b0)
));
Some(form(rect, c.as_bytes(), res))
}
/// Size of a line's caption, as of a measurement's label.
const CAPTION_SIZE: f64 = 10.0;
/// Characters of a line's caption drawn at most, as for a measurement's label.
const MAX_CAPTION_CHARS: usize = 256;
/// Leader lengths and caption offsets (Table 178) are held within this many points (200 inches,
/// the largest page side ISO 32000-2 Annex C allows), so an absurd value can't overflow.
const MAX_LINE_EXTENT: f64 = 14_400.0;
/// A Table 178 length or offset: finite and within [`MAX_LINE_EXTENT`], 0 when absent or not one.
fn line_length(v: Option<f64>) -> f64 {
v.filter(|v| v.is_finite()).map_or(0.0, |v| v.clamp(-MAX_LINE_EXTENT, MAX_LINE_EXTENT))
}
/// The caption a Line with `/Cap true` shows (ISO 32000-2 Table 178): its `/Contents`, else the
/// plain text of its `/RC`, on one line and cut to [`MAX_CAPTION_CHARS`]. `None` without a
/// caption, and for PdfCraft's own measurements, whose label (`/PCMeasureValue`) is the caption.
fn line_caption(d: &Dict) -> Option<String> {
if !matches!(d.get(b"Cap"), Some(Object::Bool(true))) || d.contains(b"PCMeasureValue") {
return None;
}
let text = |key: &[u8]| d.get(key).and_then(Object::as_string).map(PdfString::to_text);
let raw = text(b"Contents").filter(|t| !t.trim().is_empty()).or_else(|| text(b"RC").map(|rc| rich_plain(&rc)))?;
let words: Vec<&str> = raw.split_whitespace().collect();
let caption: String = words.join(" ").chars().filter(|c| !c.is_control()).take(MAX_CAPTION_CHARS).collect();
(!caption.is_empty()).then_some(caption)
}
/// The text of rich text (§12.7.4.3, XHTML): its markup dropped, the five XML entities and
/// numeric character references read, block ends read as spaces.
fn rich_plain(rc: &str) -> String {
let mut out = String::new();
let mut tag: Option<String> = None;
// Rich text past this is not caption material; it bounds the work.
for ch in rc.chars().take(MAX_CAPTION_CHARS * 64) {
match (&mut tag, ch) {
(None, '<') => tag = Some(String::new()),
(Some(name), '>') => {
let name =
name.trim_start_matches('/').split(|c: char| c.is_whitespace() || c == '/').next().unwrap_or_default().to_ascii_lowercase();
if matches!(name.as_str(), "p" | "br" | "div" | "li") {
out.push(' ');
}
tag = None;
}
(Some(name), c) => {
if name.len() < 16 {
name.push(c);
}
}
(None, c) => out.push(c),
}
}
let mut text = String::new();
let mut rest = out.as_str();
while let Some(at) = rest.find('&') {
text.push_str(rest.get(..at).unwrap_or_default());
let after = rest.get(at + 1..).unwrap_or_default();
let entity = after.find(';').filter(|&end| end <= 10).and_then(|end| Some((after.get(..end)?, end)));
let decoded = entity.and_then(|(name, end)| {
let c = match name {
"amp" => '&',
"lt" => '<',
"gt" => '>',
"quot" => '"',
"apos" => '\'',
_ => {
let num = name.strip_prefix('#')?;
let code = match num.strip_prefix(['x', 'X']) {
Some(hex) => u32::from_str_radix(hex, 16).ok()?,
None => num.parse().ok()?,
};
char::from_u32(code)?
}
};
Some((c, end))
});
match decoded {
Some((c, end)) => {
text.push(c);
rest = after.get(end + 1..).unwrap_or_default();
}
None => {
text.push('&');
rest = after;
}
}
}
text.push_str(rest);
text
}
/// Where a Line annotation's parts go (ISO 32000-2 §12.5.6.7, Table 178).
#[derive(Debug, Default)]
struct LineLayout {
/// The line itself, start to end: `/L`, or `/L` moved out by its leader lines.
line: [(f64, f64); 2],
/// Strokes along the line: the whole line, or the two pieces either side of an inline caption.
strokes: Vec<[(f64, f64); 2]>,
/// The leader lines, from `/L` (past the `/LLO` gap) to the line and on by `/LLE`.
leaders: Vec<[(f64, f64); 2]>,
/// A short stroke from the line to a caption `/CO` moved off it.
tick: Option<[(f64, f64); 2]>,
/// The caption and its text matrix.
caption: Option<(String, [f64; 6])>,
}
/// Lay out a Line annotation from `/L` = `[a b]`, line width `w`, and its leader and caption
/// entries.
///
/// Leader lines: a positive `/LL` puts the line on the left of travel from `a` to `b` (above `/L`
/// for a line drawn left to right), so the leader lines, followed from the line to `/L`, turn
/// clockwise from the direction of travel; a negative one puts it on the right. The line sits
/// `|LL| + LLO` from `/L`. `/LLE` and `/LLO` are non-negative: a negative one counts as 0.
///
/// Caption (`/Cap true`): centred on the line's midpoint and turned with it so it reads left to
/// right (bottom to top for a vertical line). `/CP /Inline` (the default) centres it on the line,
/// which is broken around it; `/Top` sets it on top of the unbroken line. `/CO [h v]` moves it `h`
/// along the line and `v` across it (positive: up in reading direction); a caption moved off an
/// inline line gets a tick from the line to it.
///
/// A zero-length or overflowing `/L` has no direction: it gets neither leader lines nor caption.
/// Every point is finite; if anything derived from the entries is not, they are left out.
fn line_layout(d: &Dict, [a, b]: [(f64, f64); 2], w: f64) -> LineLayout {
let plain = LineLayout { line: [a, b], strokes: vec![[a, b]], ..LineLayout::default() };
let (dx, dy) = (b.0 - a.0, b.1 - a.1);
let len = dx.hypot(dy);
if !len.is_finite() || len <= 0.0 {
return plain;
}
let (ux, uy) = (dx / len, dy / len);
let mut out = LineLayout { line: [a, b], ..LineLayout::default() };
let ll = line_length(d.get(b"LL").and_then(Object::as_f64));
if ll != 0.0 {
// The unit normal from `/L` towards the line: left of travel for a positive /LL.
let s = ll.signum();
let (nx, ny) = (-uy * s, ux * s);
let llo = line_length(d.get(b"LLO").and_then(Object::as_f64)).max(0.0);
let lle = line_length(d.get(b"LLE").and_then(Object::as_f64)).max(0.0);
let at = |p: (f64, f64), k: f64| (p.0 + nx * k, p.1 + ny * k);
let off = ll.abs() + llo;
out.line = [at(a, off), at(b, off)];
out.leaders = vec![[at(a, llo), at(a, off + lle)], [at(b, llo), at(b, off + lle)]];
}
let [p, _] = out.line;
let along = |t: f64| (p.0 + ux * t, p.1 + uy * t);
let mut gap = None;
if let Some(text) = line_caption(d) {
let size = CAPTION_SIZE;
let width = text_width(&text, size);
// Reading direction, and "up" across it.
let (tx, ty) = if ux < 0.0 || (ux == 0.0 && uy < 0.0) { (-ux, -uy) } else { (ux, uy) };
let (vx, vy) = (-ty, tx);
let co = nums(d, b"CO").filter(|c| c.len() == 2).unwrap_or_default();
let h = line_length(co.first().copied());
let v = line_length(co.get(1).copied());
let top = d.name(b"CP") == Some(b"Top");
// The caption's centre, as a distance along the line from `p`.
let centre = len / 2.0 + h * (tx * ux + ty * uy);
let mid = along(centre);
// Baseline across the line: on top of it, or with the text centred on it.
let base = if top { w.max(0.0) / 2.0 + 2.0 + v } else { v - size * 0.35 };
let origin = (mid.0 - tx * width / 2.0 + vx * base, mid.1 - ty * width / 2.0 + vy * base);
out.caption = Some((text, [tx, ty, -ty, tx, origin.0, origin.1]));
if !top && v.abs() < size / 2.0 {
let half = width / 2.0 + 2.0;
gap = Some(((centre - half).clamp(0.0, len), (centre + half).clamp(0.0, len)));
} else if !top {
let reach = v - v.signum() * size * 0.4;
out.tick = Some([mid, (mid.0 + vx * reach, mid.1 + vy * reach)]);
}
}
out.strokes = match gap {
Some((g0, g1)) => [(0.0, g0), (g1, len)].into_iter().filter(|(s, e)| e > s).map(|(s, e)| [along(s), along(e)]).collect(),
None => vec![out.line],
};
let finite = |q: &(f64, f64)| q.0.is_finite() && q.1.is_finite();
let all_finite =
out.line.iter().chain(out.strokes.iter().flatten()).chain(out.leaders.iter().flatten()).chain(out.tick.iter().flatten()).all(finite)
&& out.caption.as_ref().is_none_or(|(_, m)| m.iter().all(|x| x.is_finite()));
if all_finite { out } else { plain }
}
/// A rubber stamp: a rounded frame (a pointed tag for sign-here stamps) with the label in bold
/// capitals, and the dynamic stamps' "By … at …" line.
fn stamp(kind: crate::StampKind, rect: [f64; 4], col: Rgb, by: Option<&str>, opacity: f64, mut res: Dict) -> Stream {
fn stamp(label: &str, sign_here: bool, rect: [f64; 4], col: Rgb, by: Option<&str>, opacity: f64, mut res: Dict) -> Stream {
let [x0, y0, x1, y1] = rect;
let h = y1 - y0;
let mut c = String::new();
@@ -827,7 +1184,7 @@ fn stamp(kind: crate::StampKind, rect: [f64; 4], col: Rgb, by: Option<&str>, opa
}
let lw = (h * 0.07).clamp(1.0, 3.0);
let inset = lw / 2.0 + 0.5;
if kind.group() == crate::StampGroup::SignHere {
if sign_here {
// A tag pointing left, filled, with white text.
let tip = h * 0.45;
c.push_str(&format!(
@@ -893,16 +1250,15 @@ fn stamp(kind: crate::StampKind, rect: [f64; 4], col: Rgb, by: Option<&str>, opa
n(b0)
));
}
let label = kind.label();
let (title_h, by_h) = if by.is_some() { (h * 0.5, h * 0.22) } else { (h * 0.52, 0.0) };
let text_area = if kind.group() == crate::StampGroup::SignHere { (x0 + h * 0.45, x1 - lw * 2.0) } else { (x0 + lw * 2.0, x1 - lw * 2.0) };
let text_area = if sign_here { (x0 + h * 0.45, x1 - lw * 2.0) } else { (x0 + lw * 2.0, x1 - lw * 2.0) };
let mut size = title_h;
let tw = text_width(label, size) * 1.12;
if tw > text_area.1 - text_area.0 - 4.0 {
size *= (text_area.1 - text_area.0 - 4.0) / tw;
}
let tw = text_width(label, size) * 1.12;
let text_col = if kind.group() == crate::StampGroup::SignHere { [1.0, 1.0, 1.0] } else { col };
let text_col = if sign_here { [1.0, 1.0, 1.0] } else { col };
let ty = if by.is_some() { y0 + h * 0.48 } else { y0 + (h - size * 0.72) / 2.0 };
let mut out = c.into_bytes();
out.extend(
+24 -3
View File
@@ -842,6 +842,17 @@ fn annotation_flags(doc: &Document, d: &Dict) -> i64 {
d.get(b"F").and_then(|f| doc.resolve(f).as_int()).unwrap_or(0)
}
/// Whether the renderer keeps the annotation upright on a turned page: the NoRotate flag, with
/// `/F` read as the renderer reads it (a real truncated, a value that isn't a `u32` no flags).
fn drawn_upright(doc: &Document, d: &Dict) -> bool {
let f = match d.get(b"F").map(|f| doc.resolve(f)).as_deref() {
Some(Object::Int(i)) => *i,
Some(Object::Real(r)) => *r as i64,
_ => 0,
};
u32::try_from(f).is_ok_and(|f| i64::from(f) & FLAG_NO_ROTATE != 0)
}
/// Whether any page has a Fill & Sign annotation that flatten would bake in (not hidden).
pub fn has_visible_fill_sign(doc: &Document) -> bool {
let Ok(pages) = page_refs(doc) else { return false };
@@ -1010,7 +1021,7 @@ fn rect_for(shape: &Shape, style: &Style) -> Result<[f64; 4], AnnotError> {
grow(bounds([*from, *to].into_iter()).unwrap_or_default(), pad + 1.0)
}
Shape::Ink { strokes } | Shape::Signature { strokes } => {
if strokes.iter().all(|s| s.is_empty()) || !strokes.iter().flatten().all(|p| finite(p)) {
if strokes.iter().all(Vec::is_empty) || !strokes.iter().flatten().all(|p| finite(p)) {
return Err(bad("drawing (no points)"));
}
// Strokes of three or more points are drawn as curves, which stay within their
@@ -1221,7 +1232,7 @@ pub fn add_annotation(doc: &mut Document, new: &NewAnnotation, meta: &Meta) -> R
d.set(b"PCOutline".to_vec(), Object::Array(list));
}
Shape::CustomStamp { name, picture, image, size, .. } => {
let clean: String = name.chars().filter(|c| c.is_ascii_alphanumeric()).collect();
let clean: String = name.chars().filter(char::is_ascii_alphanumeric).collect();
d.set(b"Name".to_vec(), Object::name(&format!("PCCustom{clean}")));
d.set(b"PCPicture".to_vec(), Object::Ref(*picture));
d.set(b"PCPictureImage".to_vec(), Object::Bool(*image));
@@ -1586,7 +1597,14 @@ pub fn with_missing_appearances_cached(doc: &Document, cache: &mut AppearanceCac
apply_appearance(copy.get_or_insert_with(|| doc.clone()), r, &d, stream).ok();
continue;
}
let Some(stream) = build_appearance(doc, &d) else { continue };
// Another program's stamp gets a drawing for display only (ISO 32000-2 Table 184). Its
// `/AP`, if any, has no `/N` to keep here.
let other_stamp = || {
let mut bare = d.clone();
bare.remove(b"AP");
appearance::display_stamp(&bare)
};
let Some(stream) = build_appearance(doc, &d).or_else(other_stamp) else { continue };
cache.insert(r, &stream);
// Fails only when `r` isn't a dictionary, which the build just ruled out.
apply_appearance(copy.get_or_insert_with(|| doc.clone()), r, &d, stream).ok();
@@ -2262,6 +2280,8 @@ pub struct Summary {
pub intent: Option<String>,
/// A Fill & Sign mark ([`is_fill_sign`]).
pub fill_sign: bool,
/// The NoRotate flag (`/F` bit 5), as `pdfcraft_render::Annotation::no_rotate`.
pub no_rotate: bool,
/// A line's two ends (`/L`), or the corners of connected lines, a polygon or a cloud
/// (`/Vertices`), in user space; empty for other comments.
pub points: Vec<[f32; 2]>,
@@ -2344,6 +2364,7 @@ pub fn summaries(doc: &Document) -> Vec<Summary> {
locked: annotation_flags(doc, d) & FLAG_LOCKED != 0,
intent: d.get(b"IT").and_then(|o| doc.resolve(o).as_name().map(|n| String::from_utf8_lossy(n).into_owned())),
fill_sign: is_fill_sign(doc, d),
no_rotate: drawn_upright(doc, d),
points,
});
}
+421 -2
View File
@@ -1014,6 +1014,89 @@ fn a_note_without_an_appearance_is_shown_at_icon_size() {
assert_eq!(rects(&doc), original, "the source document is unchanged");
}
/// The fourteen rubber stamp names viewers draw without an appearance (ISO 32000-2 Table 184).
const TABLE_184_STAMPS: [(&str, &str); 14] = [
("Approved", "APPROVED"),
("Experimental", "EXPERIMENTAL"),
("NotApproved", "NOT APPROVED"),
("AsIs", "AS IS"),
("Expired", "EXPIRED"),
("NotForPublicRelease", "NOT FOR PUBLIC RELEASE"),
("Confidential", "CONFIDENTIAL"),
("Final", "FINAL"),
("Sold", "SOLD"),
("Departmental", "DEPARTMENTAL"),
("ForComment", "FOR COMMENT"),
("TopSecret", "TOP SECRET"),
("Draft", "DRAFT"),
("ForPublicRelease", "FOR PUBLIC RELEASE"),
];
fn stamp_dict(extra: &str) -> Dict {
let doc = document_of(&[
b"<< /Type /Catalog /Pages 2 0 R >>",
b"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 612 792] >>",
b"<< /Type /Page /Parent 2 0 R /Annots [4 0 R] >>",
format!("<< /Type /Annot /Subtype /Stamp /Rect [20 40 140 100] {extra} >>").as_bytes(),
]);
list(&doc, 0).remove(0)
}
fn drawn(d: &Dict) -> String {
String::from_utf8_lossy(&appearance::display_stamp(d).expect("a stamp is drawn").decoded().unwrap()).into_owned()
}
/// A stamp another program wrote without an appearance draws the stamp its `/Name` names, Draft
/// when it has none, and a frame with both diagonals for any other name, never the name itself.
#[test]
fn a_stamp_without_an_appearance_draws_the_stamp_it_names() {
for (name, label) in TABLE_184_STAMPS {
let content = drawn(&stamp_dict(&format!("/Name /{name}")));
assert!(content.contains(&format!("({label}) Tj")), "{name}: {content}");
}
assert!(drawn(&stamp_dict("")).contains("(DRAFT) Tj"), "Table 184's default");
assert!(drawn(&stamp_dict("/IT /Stamp")).contains("(DRAFT) Tj"), "a stamp intent keeps the default");
// Any other name, a name in another case (names are compared byte for byte, §7.3.5), and an
// image stamp (`/IT`, which has no `/Name` to default): the frame and its diagonals.
for extra in ["/Name /MyCustomStamp", "/Name /draft", "/Name /APPROVED", "/IT /StampImage", "/Name /PCVoid"] {
let content = drawn(&stamp_dict(extra));
assert!(!content.contains("Tj") && content.contains(" re\n") && content.matches(" l\n").count() == 2, "{extra}: {content}");
}
// `/C` colours the stamp, as it does PdfCraft's own.
assert!(drawn(&stamp_dict("/Name /Final /C [1 0 1]")).contains("1 0 1 RG"));
// The placeholder stays grey whatever the `/C`: it is not the stamp, so it takes none of its colour.
let placeholder = drawn(&stamp_dict("/Name /MyCustomStamp /C [1 0 0]"));
assert!(placeholder.contains("0.45 0.45 0.45 RG") && !placeholder.contains("1 0 0 RG"), "{placeholder}");
// A stamp's own artwork is never replaced, and the drawing is for display only: edits
// (restyling, flattening) still find nothing they may write.
assert!(appearance::display_stamp(&stamp_dict("/Name /Draft /AP << /N 9 0 R >>")).is_none());
assert!(appearance::build(&stamp_dict("/Name /Draft")).is_none());
assert!(appearance::display_stamp(&stamp_dict("/Name /Draft /PCStamp true")).is_none(), "PdfCraft's own stamps are drawn by `build`");
assert!(appearance::display_stamp(&stamp_dict("/Name /Draft /Rect [5 5 5 50]")).is_none(), "no width");
}
/// The display copy draws a stamp that has no normal appearance, and keeps one that has.
#[test]
fn the_display_copy_draws_stamps_without_a_normal_appearance_only() {
let doc = document_of(&[
b"<< /Type /Catalog /Pages 2 0 R >>",
b"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 612 792] >>",
b"<< /Type /Page /Parent 2 0 R /Annots [4 0 R 5 0 R 6 0 R 7 0 R] >>",
b"<< /Type /Annot /Subtype /Stamp /Rect [20 40 140 100] /Name /TopSecret >>",
b"<< /Type /Annot /Subtype /Stamp /Rect [20 140 140 200] /Name /Draft /AP << /N 8 0 R >> >>",
b"<< /Type /Annot /Subtype /Stamp /Rect [20 240 140 300] /Name /Sold /AP << /D 8 0 R >> >>",
b"<< /Type /Annot /Subtype /Stamp /Rect [20 340 140 400] /Name /Unheard >>",
b"<< /Type /XObject /Subtype /Form /BBox [0 0 10 10] /Length 8 >>\nstream\n1 0 0 rg\nendstream",
]);
let display = with_missing_appearances(&doc).expect("three stamps need an appearance");
let shown = list(&display, 0);
assert!(ap_content(&display, &shown[0]).contains("(TOP SECRET) Tj"));
assert_eq!(shown[1].get(b"AP"), list(&doc, 0)[1].get(b"AP"), "an existing appearance is kept");
assert!(ap_content(&display, &shown[2]).contains("(SOLD) Tj"), "an /AP without /N has nothing to keep");
assert!(!ap_content(&display, &shown[3]).contains("Tj"), "an unknown name gets the placeholder");
assert!(list(&doc, 0)[0].get(b"AP").is_none(), "the document itself is untouched");
}
#[test]
fn every_line_ending_is_drawn() {
let filled = [LineEnding::Square, LineEnding::Circle, LineEnding::Diamond, LineEnding::ClosedArrow, LineEnding::RClosedArrow];
@@ -1316,9 +1399,9 @@ fn cached_appearances_are_reused_while_annotations_are_unchanged() {
.expect("strips");
let mut cache = AppearanceCache::default();
let first = with_missing_appearances_cached(&doc, &mut cache).expect("builds");
assert_eq!((cache.builds(), cache.hits()), (1, 0), "only the note needs an appearance");
assert_eq!((cache.builds(), cache.hits()), (2, 0), "the note and the file's stamp need an appearance");
let second = with_missing_appearances_cached(&doc, &mut cache).expect("reuses");
assert_eq!((cache.builds(), cache.hits()), (1, 1), "nothing is redrawn");
assert_eq!((cache.builds(), cache.hits()), (2, 2), "nothing is redrawn");
let [a, b] = [&first, &second].map(|copy| ap_content(copy, &list(copy, 0)[idx]));
assert!(!a.is_empty());
assert_eq!(a, b, "the reused appearance is byte-identical");
@@ -1675,3 +1758,339 @@ fn a_star_note_keeps_its_star_when_recoloured() {
let Object::Stream(s) = &*doc.get(n) else { panic!() };
assert_eq!(s.decoded().unwrap(), note_drawing(Some("Star"), [0.0, 0.0, 1.0]));
}
/// The built appearance's content for an annotation dictionary written in PDF syntax.
fn content_of(src: &str) -> String {
let doc = document_of(&[src.as_bytes()]);
let d = doc.get(ObjRef::new(1, 0)).as_dict().cloned().expect("a dictionary");
let stream = appearance::build(&d).expect("drawn");
String::from_utf8_lossy(&stream.decoded().unwrap()).into_owned()
}
/// ISO 32000-2 Table 166: `/Border [hr vr w [dash]]`; the optional fourth element, a dash array,
/// used to hide the width (drawn 1 pt solid instead of 3 pt dashed).
#[test]
fn legacy_border_width_and_dash_are_drawn() {
let square = |border: &str| content_of(&format!("<< /Subtype /Square /Rect [0 0 100 100] /C [1 0 0] {border} >>"));
let c = square("/Border [0 0 3 [6 3]]");
assert!(c.contains("3 w") && c.contains("[6 3] 0 d"), "{c}");
assert!(c.contains("1.5 1.5 97 97 re"), "the stroke is inset by half its width: {c}");
let c = square("/Border [0 0 3]");
assert!(c.contains("3 w") && !c.contains(" d\n"), "no dash array: solid: {c}");
// `/BS` overrides `/Border` (Table 166), for the width and the dashes alike.
let c = square("/Border [0 0 3 [6 3]] /BS << /W 2 >>");
assert!(c.contains("2 w") && !c.contains(" d\n"), "{c}");
let c = square("/Border [0 0 3 [6 3]] /BS << /W 2 /S /D /D [4 1] >>");
assert!(c.contains("2 w") && c.contains("[4 1] 0 d"), "{c}");
// A /BS without /W means its default width 1, not the ignored /Border's.
let c = square("/Border [0 0 3] /BS << /S /S >>");
assert!(c.contains("1 w") && !c.contains("3 w"), "{c}");
// A FreeText border and a line take the legacy dash array too.
let c = content_of("<< /Subtype /FreeText /Rect [0 0 100 40] /Contents (x) /Border [0 0 2 [5 2]] >>");
assert!(c.contains("2 w") && c.contains("[5 2] 0 d"), "{c}");
let c = content_of("<< /Subtype /Line /Rect [0 0 100 100] /L [10 10 90 90] /C [0 0 1] /Border [0 0 2 [5 2]] >>");
assert!(c.contains("[5 2] 0 d"), "{c}");
}
/// Dash arrays that can't be drawn (§8.4.3.6: all zeros is invalid; negative or non-numeric
/// lengths, and absurdly long arrays) draw solid, without a panic. A non-finite or negative
/// width falls back to 1.
#[test]
fn bad_dash_arrays_draw_solid() {
let square = |border: &str| content_of(&format!("<< /Subtype /Square /Rect [0 0 100 100] /C [1 0 0] {border} >>"));
let long = format!("[{}]", vec!["1"; 65].join(" "));
for bad in ["[0 0]", "[-3 2]", "[]", "[(a) 2]", "5", long.as_str()] {
let c = square(&format!("/Border [0 0 3 {bad}]"));
assert!(c.contains("3 w") && !c.contains(" d\n"), "{bad}: {c}");
let c = square(&format!("/BS << /W 3 /S /D /D {bad} >>"));
assert!(c.contains("3 w") && !c.contains(" d\n"), "{bad}: {c}");
}
assert!(square(&format!("/Border [0 0 3 [{}]]", vec!["1"; 64].join(" "))).contains(" 0 d\n"), "64 elements are drawn");
// `/S /D` without `/D` uses the default `[3]` (Table 168).
assert!(square("/BS << /W 3 /S /D >>").contains("[3] 0 d"));
let mut d = Dict::new();
d.set(b"Subtype".to_vec(), Object::name("Square"));
d.set(b"Rect".to_vec(), Object::Array([0.0, 0.0, 100.0, 100.0].map(Object::Real).to_vec()));
d.set(b"C".to_vec(), Object::Array([1.0, 0.0, 0.0].map(Object::Real).to_vec()));
for w in [f64::NAN, f64::INFINITY, -2.0] {
let dash = Object::Array([f64::NAN, 2.0].map(Object::Real).to_vec());
d.set(b"Border".to_vec(), Object::Array(vec![Object::Int(0), Object::Int(0), Object::Real(w), dash]));
let c = String::from_utf8_lossy(&appearance::build(&d).unwrap().decoded().unwrap()).into_owned();
assert!(c.contains("1 w") && !c.contains(" d\n") && !c.contains("NaN") && !c.contains("inf"), "{w}: {c}");
}
}
/// Table 182: an ink annotation's `/BS` gives the width and dash pattern its paths are drawn with.
#[test]
fn ink_draws_its_border_style_dashes() {
let ink = |style: &str| content_of(&format!("<< /Subtype /Ink /Rect [0 0 100 100] /C [1 0 0] /InkList [[5 5 50 95 95 5]] {style} >>"));
let c = ink("/BS << /W 3 /S /D /D [6 3] >>");
assert!(c.contains("3 w 1 J 1 j\n[6 3] 0 d"), "{c}");
assert!(!ink("/BS << /W 3 >>").contains(" d\n"));
assert!(ink("/Border [0 0 2 [4 4]]").contains("[4 4] 0 d"));
}
/// Table 183: `/Sy /P` associates a new paragraph symbol (¶) with the caret. It is drawn to the
/// caret's right in the caret's colour, inside `/Rect`; `/Sy /None` (the default) draws none.
#[test]
fn a_caret_with_a_paragraph_symbol_draws_the_pilcrow() {
let caret = |extra: &str| {
let doc = document_of(&[format!("<< /Subtype /Caret /Rect [30 30 60 60] /C [0.9 0.1 0.1] {extra} >>").as_bytes()]);
let d = doc.get(ObjRef::new(1, 0)).as_dict().cloned().unwrap();
let s = appearance::build(&d).unwrap();
(s.decoded().unwrap(), s.dict.get(b"Resources").and_then(Object::as_dict).is_some_and(|r| r.contains(b"Font")))
};
let has_pilcrow = |c: &[u8]| c.windows(5).any(|w| w == b"(\xb6) T");
let (c, font) = caret("/Sy /P");
assert!(has_pilcrow(&c) && font, "{}", String::from_utf8_lossy(&c));
let text = String::from_utf8_lossy(&c).into_owned();
assert!(text.starts_with("0.9 0.1 0.1 rg"), "{text}");
// The caret gives up room on the right for the symbol, which stays within /Rect.
let td: Vec<f64> = text.split("Tf ").nth(1).unwrap().split_whitespace().take(2).map(|v| v.parse().unwrap()).collect();
let size: f64 = text.split("/Helv ").nth(1).unwrap().split_whitespace().next().unwrap().parse().unwrap();
assert!(td[0] > 45.0 && td[0] + appearance::text_width("\u{b6}", size) <= 60.0 + 1e-6 && td[1] >= 30.0, "{text}");
assert!(!text.contains("60 30 c h f"), "the caret no longer reaches the right edge: {text}");
for none in ["/Sy /None", ""] {
let (c, font) = caret(none);
assert!(!has_pilcrow(&c) && !font, "{none}");
assert!(String::from_utf8_lossy(&c).contains("60 30 c h f"), "{none}: the caret fills /Rect as before");
}
// With /RD leaving room on the right, the caret keeps its box and the symbol fits beside it.
let (c, _) = caret("/Sy /P /RD [0 0 15 0]");
let text = String::from_utf8_lossy(&c).into_owned();
assert!(text.contains("45 30 c h f") && has_pilcrow(&c), "{text}");
// Malformed /RD and a degenerate /Rect don't panic.
for rd in ["/RD [40 0 40 0]", "/RD [-1 0 0 0]", "/RD [1 2]", "/RD (x)"] {
assert!(has_pilcrow(&caret(&format!("/Sy /P {rd}")).0), "{rd}");
}
let doc = document_of(&[b"<< /Subtype /Caret /Rect [30 30 30 30] /Sy /P >>"]);
let d = doc.get(ObjRef::new(1, 0)).as_dict().cloned().unwrap();
assert!(appearance::build(&d).is_some());
}
// ── Line annotations: leader lines and captions (ISO 32000-2 §12.5.6.7, Table 178) ──────────
/// A red Line from `l` with a 1 pt border, a generous `/Rect`, and `extra` entries.
fn table_178_line(l: [f64; 4], extra: &[(&str, Object)]) -> Dict {
let mut d = Dict::new();
d.set(b"Subtype".to_vec(), Object::name("Line"));
d.set(b"Rect".to_vec(), Object::Array([0.0, 0.0, 600.0, 800.0].map(Object::Real).to_vec()));
d.set(b"C".to_vec(), Object::Array([1.0, 0.0, 0.0].map(Object::Real).to_vec()));
d.set(b"L".to_vec(), Object::Array(l.map(Object::Real).to_vec()));
for (k, v) in extra {
d.set(k.as_bytes().to_vec(), v.clone());
}
d
}
/// The built appearance's content.
fn line_drawing(d: &Dict) -> String {
let s = crate::appearance::build(d).expect("the line is drawn");
String::from_utf8_lossy(&s.decoded().unwrap()).into_owned()
}
/// Every straight two-point stroke (`x0 y0 m x1 y1 l S`) in a drawing.
fn segments(content: &str) -> Vec<[f64; 4]> {
content
.lines()
.filter_map(|line| {
let t: Vec<&str> = line.split_whitespace().collect();
if t.len() != 7 || t[2] != "m" || t[5] != "l" || t[6] != "S" {
return None;
}
let v: Vec<f64> = [t[0], t[1], t[3], t[4]].iter().map(|x| x.parse().unwrap()).collect();
Some([v[0], v[1], v[2], v[3]])
})
.collect()
}
/// The caption's text matrix (`a b c d e f Tm`), if any.
fn caption_matrix(content: &str) -> Option<[f64; 6]> {
let at = content.find(" Tm")?;
let before: Vec<f64> = content[..at].split_whitespace().rev().take(6).map(|x| x.parse().unwrap()).collect();
Some([before[5], before[4], before[3], before[2], before[1], before[0]])
}
fn has(segs: &[[f64; 4]], want: [f64; 4]) -> bool {
segs.iter().any(|s| s.iter().zip(want).all(|(a, b)| (a - b).abs() < 0.01))
}
#[test]
fn a_positive_leader_length_puts_the_line_above_a_left_to_right_line_and_a_negative_one_below() {
let up = segments(&line_drawing(&table_178_line([72.0, 620.0, 272.0, 620.0], &[("LL", Object::Real(20.0))])));
assert!(has(&up, [72.0, 640.0, 272.0, 640.0]), "the line is 20 above /L: {up:?}");
assert!(has(&up, [72.0, 620.0, 72.0, 640.0]) && has(&up, [272.0, 620.0, 272.0, 640.0]), "leader lines from /L up to it: {up:?}");
assert!(!has(&up, [72.0, 620.0, 272.0, 620.0]), "nothing along /L itself: {up:?}");
let down = segments(&line_drawing(&table_178_line([72.0, 540.0, 272.0, 540.0], &[("LL", Object::Real(-20.0)), ("LLE", Object::Real(10.0))])));
assert!(has(&down, [72.0, 520.0, 272.0, 520.0]), "the line is 20 below /L: {down:?}");
assert!(has(&down, [72.0, 540.0, 72.0, 510.0]) && has(&down, [272.0, 540.0, 272.0, 510.0]), "leaders run 10 past it: {down:?}");
}
#[test]
fn a_leader_offset_leaves_a_gap_and_the_endings_sit_on_the_line_itself() {
let d = table_178_line(
[72.0, 460.0, 272.0, 460.0],
&[("LL", Object::Real(20.0)), ("LLO", Object::Real(10.0)), ("LE", Object::Array(vec![Object::name("OpenArrow"), Object::name("OpenArrow")]))],
);
let content = line_drawing(&d);
let segs = segments(&content);
assert!(has(&segs, [72.0, 490.0, 272.0, 490.0]), "the line sits |LL| + LLO above /L: {segs:?}");
assert!(has(&segs, [72.0, 470.0, 72.0, 490.0]) && has(&segs, [272.0, 470.0, 272.0, 490.0]), "leaders start LLO from /L: {segs:?}");
// The open arrows' tips (`tip l`) are at the ends of the line, not of /L.
assert!(content.contains(" 72 490 l ") && content.contains(" 272 490 l "), "arrows at the moved line: {content}");
assert!(!content.contains(" 72 460 l "), "no arrow on /L: {content}");
}
#[test]
fn an_inline_caption_breaks_the_line_around_its_text() {
let d =
table_178_line([72.0, 380.0, 272.0, 380.0], &[("Cap", Object::Bool(true)), ("Contents", Object::String(PdfString::text("Inline 50 mm")))]);
let content = line_drawing(&d);
assert!(content.contains("(Inline 50 mm) Tj"), "the caption is drawn: {content}");
assert!(content.contains("/Helv 10 Tf"), "in Helvetica 10: {content}");
let m = caption_matrix(&content).expect("text matrix");
let width = crate::appearance::text_width("Inline 50 mm", 10.0);
assert!((m[4] - (172.0 - width / 2.0)).abs() < 0.01 && m[5] < 380.0 && m[5] > 380.0 - 10.0, "centred on the line: {m:?}");
let segs = segments(&content);
assert_eq!(segs.len(), 2, "two pieces: {segs:?}");
assert!(segs.iter().all(|s| s[2] <= 172.0 - width / 2.0 || s[0] >= 172.0 + width / 2.0), "no stroke under the text: {segs:?}");
assert!(has(&segs, [72.0, 380.0, 172.0 - width / 2.0 - 2.0, 380.0]), "the left piece starts at the line's start: {segs:?}");
}
#[test]
fn a_top_caption_sits_above_the_unbroken_line() {
let d = table_178_line(
[72.0, 300.0, 272.0, 300.0],
&[("Cap", Object::Bool(true)), ("CP", Object::name("Top")), ("Contents", Object::String(PdfString::text("Top 50 mm")))],
);
let content = line_drawing(&d);
let m = caption_matrix(&content).expect("text matrix");
assert!(m[5] > 300.0 && m[5] < 305.0, "baseline just above the line: {m:?}");
assert_eq!(segments(&content), vec![[72.0, 300.0, 272.0, 300.0]], "the line is whole");
}
#[test]
fn a_caption_offset_moves_it_along_and_off_the_line_with_a_tick() {
let co = |h: f64, v: f64| Object::Array(vec![Object::Real(h), Object::Real(v)]);
let text = ("Contents", Object::String(PdfString::text("Offset 15")));
let base = caption_matrix(&line_drawing(&table_178_line([330.0, 700.0, 530.0, 700.0], &[("Cap", Object::Bool(true)), text.clone()]))).unwrap();
let content = line_drawing(&table_178_line([330.0, 700.0, 530.0, 700.0], &[("Cap", Object::Bool(true)), ("CO", co(0.0, 15.0)), text.clone()]));
let up = caption_matrix(&content).unwrap();
assert!((up[5] - base[5] - 15.0).abs() < 0.01 && (up[4] - base[4]).abs() < 0.01, "15 up: {base:?} → {up:?}");
let segs = segments(&content);
assert!(has(&segs, [330.0, 700.0, 530.0, 700.0]), "a caption off the line leaves it whole: {segs:?}");
assert!(segs.iter().any(|s| s[0] == 430.0 && s[2] == 430.0 && s[1] == 700.0 && s[3] > 705.0), "a tick from the midpoint up: {segs:?}");
let along =
caption_matrix(&line_drawing(&table_178_line([330.0, 700.0, 530.0, 700.0], &[("Cap", Object::Bool(true)), ("CO", co(-30.0, 0.0)), text])))
.unwrap();
assert!((along[4] - base[4] + 30.0).abs() < 0.01 && (along[5] - base[5]).abs() < 0.01, "30 left: {base:?} → {along:?}");
}
#[test]
fn without_cap_true_no_caption_is_drawn() {
for cap in [None, Some(Object::Bool(false)), Some(Object::Int(1))] {
let mut extra = vec![("Contents", Object::String(PdfString::text("Hidden caption")))];
if let Some(c) = cap.clone() {
extra.push(("Cap", c));
}
let d = table_178_line([330.0, 620.0, 530.0, 620.0], &extra);
let content = line_drawing(&d);
assert!(!content.contains("Tj"), "{cap:?}: {content}");
assert_eq!(segments(&content), vec![[330.0, 620.0, 530.0, 620.0]]);
assert!(crate::appearance::undrawable_text(&d).is_none());
}
}
#[test]
fn a_diagonal_lines_leaders_are_perpendicular_and_its_caption_turns_with_it() {
let d = table_178_line(
[330.0, 460.0, 530.0, 560.0],
&[
("LL", Object::Real(20.0)),
("LLE", Object::Real(10.0)),
("Cap", Object::Bool(true)),
("Contents", Object::String(PdfString::text("Diagonal"))),
],
);
let content = line_drawing(&d);
let segs = segments(&content);
let (ux, uy) = (200.0 / 100f64.hypot(200.0), 100.0 / 100f64.hypot(200.0));
let leaders: Vec<&[f64; 4]> = segs.iter().filter(|s| (s[2] - s[0]) * ux + (s[3] - s[1]) * uy < 1e-2).collect();
assert_eq!(leaders.len(), 2, "two leader lines across the line: {segs:?}");
for l in leaders {
let (dx, dy) = (l[2] - l[0], l[3] - l[1]);
assert!((dx.hypot(dy) - 30.0).abs() < 0.01, "|LL| + LLE long: {l:?}");
assert!(dx < 0.0 && dy > 0.0, "up and to the left (left of travel): {l:?}");
}
let m = caption_matrix(&content).expect("caption");
assert!((m[0] - ux).abs() < 1e-3 && (m[1] - uy).abs() < 1e-3, "the text runs along the line: {m:?}");
// Drawn right to left, it still reads left to right.
let back = caption_matrix(&line_drawing(&table_178_line(
[530.0, 560.0, 330.0, 460.0],
&[("Cap", Object::Bool(true)), ("Contents", Object::String(PdfString::text("x")))],
)))
.unwrap();
assert!(back[0] > 0.0, "{back:?}");
}
#[test]
fn a_caption_from_rich_text_and_one_the_font_cant_draw() {
let rc = "<?xml version=\"1.0\"?><body xmlns=\"http://www.w3.org/1999/xhtml\"><p>Dim &amp; <b>5</b>0&#x20;mm &lt;x&gt;</p></body>";
let d = table_178_line([0.0, 0.0, 100.0, 0.0], &[("Cap", Object::Bool(true)), ("RC", Object::String(PdfString::text(rc)))]);
let s = crate::appearance::build(&d).unwrap().decoded().unwrap();
assert!(s.windows(17).any(|w| w == b"(Dim & 50 mm <x>)"), "{}", String::from_utf8_lossy(&s));
let cjk = table_178_line([0.0, 0.0, 100.0, 0.0], &[("Cap", Object::Bool(true)), ("Contents", Object::String(PdfString::text("長さ")))]);
assert_eq!(crate::appearance::undrawable_text(&cjk), Some(("the line's caption", '長')));
// A PdfCraft measurement's label is its caption: the comment text isn't drawn a second time.
let mut measured = cjk.clone();
measured.set(b"PCMeasureValue".to_vec(), Object::String(PdfString::text("5 mm")));
assert_eq!(crate::appearance::undrawable_text(&measured), None);
let content = line_drawing(&measured);
assert_eq!(content.matches(" Tj").count(), 1, "{content}");
}
#[test]
fn degenerate_and_absurd_leader_and_caption_values_do_not_panic() {
let cap = ("Cap", Object::Bool(true));
let text = ("Contents", Object::String(PdfString::text(&"w".repeat(10_000))));
// A zero-length line has no direction: no leader lines, no caption, no NaN.
let point =
line_drawing(&table_178_line([50.0, 50.0, 50.0, 50.0], &[("LL", Object::Real(20.0)), ("LLE", Object::Real(5.0)), cap.clone(), text.clone()]));
assert!(!point.contains("NaN") && !point.contains("inf") && !point.contains("Tj"), "{point}");
assert_eq!(segments(&point).len(), 1);
for bad in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, 1e300, -1e300, f64::MAX] {
let d = table_178_line(
[0.0, 0.0, 100.0, 0.0],
&[
("LL", Object::Real(bad)),
("LLE", Object::Real(bad)),
("LLO", Object::Real(bad)),
("CO", Object::Array(vec![Object::Real(bad), Object::Real(bad)])),
cap.clone(),
text.clone(),
],
);
let content = line_drawing(&d);
assert!(!content.contains("NaN") && !content.contains("inf"), "{bad}: {content}");
for s in segments(&content) {
assert!(s.iter().all(|x| x.abs() <= 50_000.0), "{bad}: {s:?}");
}
}
// Negative LLE and LLO count as 0.
let neg = segments(&line_drawing(&table_178_line(
[0.0, 0.0, 100.0, 0.0],
&[("LL", Object::Real(10.0)), ("LLE", Object::Real(-5.0)), ("LLO", Object::Real(-5.0))],
)));
assert!(has(&neg, [0.0, 0.0, 0.0, 10.0]) && has(&neg, [0.0, 10.0, 100.0, 10.0]), "{neg:?}");
// Huge endpoints whose midpoint would overflow fall back to the plain line.
let huge = line_drawing(&table_178_line([f64::MAX, f64::MAX, f64::MAX / 2.0, f64::MAX], &[("LL", Object::Real(20.0)), cap, text]));
assert!(!huge.contains("NaN") && !huge.contains("inf"), "{huge}");
// The caption is cut to 256 characters.
let long = line_drawing(&table_178_line(
[0.0, 0.0, 100.0, 0.0],
&[("Cap", Object::Bool(true)), ("Contents", Object::String(PdfString::text(&"w".repeat(10_000))))],
));
assert!(long.contains(&format!("({}) Tj", "w".repeat(256))), "cut to 256");
assert!(!long.contains(&"w".repeat(257)));
}
+49 -9
View File
@@ -138,16 +138,25 @@ struct Budget {
}
impl Budget {
/// Resets the comparison count for a page with these `lines`.
/// Resets the comparison count for a page with these `lines`. A line costs its word boxes
/// or its runs, whichever are more (at least one): a cover check walks the boxes, and the
/// covered text walks the runs, which can draw no words at all (`( ) Tj`).
fn start_page(&mut self, lines: &[TextLine]) {
self.comparisons = 0;
self.page_cost = lines.iter().fold(0, |n, line| n.saturating_add(line.ink.len().max(1)));
self.page_cost = lines.iter().fold(0, |n, line| n.saturating_add(line.ink.len().max(line.runs().count()).max(1)));
}
/// The text of the `lines` that `hides`, joined with single spaces, or `None` when they show
/// no text. Without `copying` the text is empty and never assembled: one long line under many
/// covers would otherwise be copied once per cover, outside both bounds.
fn hidden_text(&mut self, lines: &[TextLine], copying: bool, hides: impl Fn(&TextLine) -> bool) -> Result<Option<String>, AuditError> {
/// The text `cover` hides in the `lines` that `hides` ([`covered_words`]), joined with single
/// spaces, or `None` when they show no text. Without `copying` the text is empty and never
/// assembled: one long line under many covers would otherwise be copied once per cover,
/// outside both bounds.
fn hidden_text(
&mut self,
lines: &[TextLine],
copying: bool,
cover: &[f64; 4],
hides: impl Fn(&TextLine) -> bool,
) -> Result<Option<String>, AuditError> {
self.comparisons = self.comparisons.saturating_add(self.page_cost);
if self.comparisons > self.limits.comparisons {
return Err(AuditError::TooManyComparisons);
@@ -160,7 +169,7 @@ impl Budget {
if !covered.is_empty() {
covered.push(' ');
}
covered.push_str(line.text.trim());
covered_words(cover, line, &mut covered);
}
Ok((!covered.trim().is_empty()).then_some(covered))
}
@@ -188,14 +197,17 @@ fn audit(doc: &Document, limits: Limits) -> Result<Vec<AuditFinding>, AuditError
budget.start_page(&lines);
// 1. Opaque filled rectangles over extractable text.
for r in cover::filled_rects(doc, &page.dict)? {
if let Some(covered) = budget.hidden_text(&lines, copying, |line| is_cover(&r, line))? {
if let Some(covered) = budget.hidden_text(&lines, copying, &r.rect, |line| is_cover(&r, line))? {
let covered_text = budget.report_text(covered, copying)?;
out.push(AuditFinding { page: n, kind: FindingKind::CoveredText, rect: r.rect, covered_text });
}
}
// 2. Annotation covers over extractable text.
for annot in annots(doc, &page.dict)? {
if let Some(covered) = budget.hidden_text(&lines, copying, |line| match &annot {
let cover = match &annot {
AnnotationCover::Redact(rect) | AnnotationCover::Square { rect, .. } => *rect,
};
if let Some(covered) = budget.hidden_text(&lines, copying, &cover, |line| match &annot {
AnnotationCover::Redact(rect) => covers(rect, line),
AnnotationCover::Square { rect, rgb } => covers(rect, line) && contrast(line.color, *rgb) < COVER_CONTRAST,
})? {
@@ -250,6 +262,34 @@ fn covers(cover: &[f64; 4], line: &TextLine) -> bool {
inked || (boxed && (line.ink.is_empty() || word_intersects()))
}
/// Appends the text of `line` that `cover` lies on to `out`: the runs whose words it overlaps
/// (#4164), so the words of the line painted beside the cover, which stay visible, are not
/// reported as hidden. Neighbouring runs are joined as the line joins them, so a word split
/// across runs stays one word; runs with others left out between them are spaced. The whole
/// line when its runs can't say: a single run, a line whose text was reordered for reading, or
/// a cover that overlaps the line's box but none of its words.
fn covered_words(cover: &[f64; 4], line: &TextLine, out: &mut String) {
let overlaps = |w: &[f64; 4]| area(&[cover[0].max(w[0]), cover[1].max(w[1]), cover[2].min(w[2]), cover[3].min(w[3])]) > 0.0;
let mut words = String::new();
let mut last = None;
for (i, (text, ink, spaced)) in line.runs().enumerate() {
if text.trim().is_empty() || !ink.iter().any(overlaps) {
continue;
}
let apart = last.is_some_and(|l: usize| l.saturating_add(1) != i || spaced);
if apart && !words.ends_with(char::is_whitespace) && !text.starts_with(char::is_whitespace) {
words.push(' ');
}
words.push_str(text);
last = Some(i);
}
if line.runs().nth(1).is_none() || last.is_none() {
out.push_str(line.text.trim());
} else {
out.push_str(words.trim());
}
}
/// The area of a rectangle, 0 when it is empty or inverted.
fn area(r: &[f64; 4]) -> f64 {
(r[2] - r[0]).max(0.0) * (r[3] - r[1]).max(0.0)
+53 -3
View File
@@ -645,6 +645,33 @@ fn later_text_on_the_line_does_not_clear_an_earlier_cover() {
assert!(findings[0].covered_text.contains("SECRET"), "{findings:?}");
}
/// #4164: a cover over part of a line reports the words under it, not the words of the same
/// line painted beside it, which stay visible.
#[test]
fn covered_text_leaves_out_the_words_beside_the_cover() {
let covered = |content: &[u8]| {
let findings = audit_redactions(&open(one_page(content, ""))).expect("audit must run");
findings.into_iter().map(|f| f.covered_text).collect::<Vec<_>>()
};
assert_eq!(covered(b"0 g\nBT /F1 24 Tf 100 700 Td (SECRET) Tj ET\n98 688 94 32 re f\nBT /F1 24 Tf 200 700 Td (tail) Tj ET\n"), ["SECRET"]);
// A word shown in two runs with nothing between them stays one word (review on #4198).
assert_eq!(covered(b"0 g\nBT /F1 24 Tf 100 700 Td (SE) Tj (CRET) Tj ET\n98 688 94 32 re f\nBT /F1 24 Tf 200 700 Td (tail) Tj ET\n"), ["SECRET"]);
// The same for an unapplied redaction mark over the first run only. A mark over both runs
// reports both, with the space the line has between them (`tail` is set apart here).
for (rect, expected) in [("[98 688 192 720]", "SECRET"), ("[98 688 310 720]", "SECRET tail")] {
let mut b = Builder::new();
b.add("<< /Type /Catalog /Pages 2 0 R >>");
b.add("<< /Type /Pages /Kids [3 0 R] /Count 1 >>");
b.add("<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents 4 0 R /Resources << /Font << /F1 5 0 R >> >> /Annots [6 0 R] >>");
b.add_stream(b"BT /F1 24 Tf 100 700 Td (SECRET) Tj ET\nBT /F1 24 Tf 250 700 Td (tail) Tj ET\n");
b.add(FONT);
b.add(&format!("<< /Type /Annot /Subtype /Redact /Rect {rect} >>"));
let findings = audit_redactions(&open(b.build())).expect("audit must run");
assert_eq!(findings.iter().map(|f| (f.kind.clone(), f.covered_text.as_str())).collect::<Vec<_>>(), [(FindingKind::UnappliedMark, expected)]);
}
}
/// Many covers over the same long line repeat its text in every finding: a small file must not
/// expand into an unbounded report. Past the budget the audit fails rather than truncate.
#[test]
@@ -677,6 +704,28 @@ fn cover_and_line_comparisons_are_bounded() {
assert!(crate::audit(&doc, limits).expect("within the budget").is_empty());
}
/// A run that draws no word still costs a comparison: the covered text walks every run of a
/// covered line, so a word followed by many `( ) Tj` must not be checked for free (review on
/// #4198).
#[test]
fn runs_without_words_count_against_the_comparison_bound() {
let mut content = b"BT /F1 24 Tf 100 700 Td (SECRET) Tj".to_vec();
content.extend_from_slice(&b" ( ) Tj".repeat(50));
content.extend_from_slice(
b" ET
0 g
98 688 94 32 re f
",
);
let doc = open(one_page(&content, ""));
let lines = pdfcraft_edit::glyph_text_lines(&doc, &pdfcraft_model::pages(&doc)[0]).expect("text");
assert_eq!(lines.iter().map(|l| (l.ink.len(), l.runs().count())).collect::<Vec<_>>(), [(1, 51)]);
let limits = crate::Limits { comparisons: 50, covered_text: usize::MAX };
assert!(matches!(crate::audit(&doc, limits), Err(crate::AuditError::TooManyComparisons)));
let limits = crate::Limits { comparisons: 51, covered_text: usize::MAX };
assert_eq!(crate::audit(&doc, limits).expect("within the budget").len(), 1);
}
/// Covered text is document text: a document whose permissions withhold copying reports where
/// its covers are but not what they hide, unless it was opened with the owner password.
#[test]
@@ -714,14 +763,15 @@ fn copy_restricted_documents_withhold_covered_text() {
/// per cover, a volume neither the comparison nor the output bound charges.
#[test]
fn withheld_covered_text_is_not_assembled() {
const PAGE: [f64; 4] = [0.0, 0.0, 612.0, 792.0];
let doc = open(one_page(b"BT /F1 24 Tf 100 700 Td (SECRET DATA 123) Tj ET\n", ""));
let lines = pdfcraft_edit::text_lines(&doc, 0).expect("text");
let mut budget = crate::Budget { limits: crate::Limits::DEFAULT, comparisons: 0, page_cost: 0, covered_text: 0 };
budget.start_page(&lines);
let withheld = budget.hidden_text(&lines, false, |_| true).expect("within the budget");
let withheld = budget.hidden_text(&lines, false, &PAGE, |_| true).expect("within the budget");
assert_eq!(withheld.map(|t| t.capacity()), Some(0), "a finding, with no text built for it");
assert_eq!(budget.hidden_text(&lines, false, |_| false).expect("within the budget"), None);
let copied = budget.hidden_text(&lines, true, |_| true).expect("within the budget");
assert_eq!(budget.hidden_text(&lines, false, &PAGE, |_| false).expect("within the budget"), None);
let copied = budget.hidden_text(&lines, true, &PAGE, |_| true).expect("within the budget");
assert_eq!(copied.as_deref(), Some("SECRET DATA 123"));
}
+1 -1
View File
@@ -33,7 +33,7 @@ its undo/redo history.
- For proportional image signature resizing, use the embedded image layer's width/height ratio rather than a previously stretched annotation rectangle. The GUI preserves this ratio at corners with the opposite corner anchored; edge midpoint handles change only their own axis. `comment_edit` accepts the resulting rectangle.
- `doc_close` refuses to drop unsaved changes unless `discard_changes: true`. `doc_save` writes atomically, incrementally in place, and in full for a new path. Atomic output writes call `sync_all` on the staging file before replacing the destination. A write or sync error leaves the destination intact, removes staging and leaves the document dirty for retry. A filesystem that does not support syncing returns an error; there is no unsynced fallback. This flushes file contents, but does not guarantee persistence of the parent-directory rename across power loss.
- With a root set, every read and write path must resolve inside it (symlinks and `..` included). Relative paths resolve inside the root, and `..` is resolved by name before the check. Every path outside the root gets the same refusal (`<path> is outside the allowed directory <root>`), whether or not it exists, so a confined agent can't probe the rest of the disk; on Windows another network share or device path (`\\host\share`, `\\?\UNC\…`, `\\.\…`) is refused without being contacted. "Not found" and other filesystem errors are reported only for paths inside the root. Tools that write several files into a folder name them after the document or input file, with separators, colons and control characters replaced by `_`, so a name can't lead them out of the folder. The root itself must be a folder.
- `Automation::with_automation_roots` holds a read folder and a write folder (`pdfcraft-cli mcp --automation-read-root DIR --automation-write-root DIR`, see [docs/mcp.md](../../docs/mcp.md)). Reads must lie inside the read root and writes inside the write root, links followed. A root left out grants none of its access. Refusals read `automation path rejected: outside the read root <root>: <path>`. It applies on top of `with_root`.
- `Automation::with_automation_roots` holds a read folder and a write folder (`pdfcraft-cli mcp --automation-read-root DIR --automation-write-root DIR`, see [docs/mcp.md](../../docs/mcp.md)). Reads must lie inside the read root and writes inside the write root, links followed. A root left out grants none of its access. Refusals read `automation path rejected: outside the read root <root>: <path>`. As with a root set, on Windows a path on another network share or device path is refused with that refusal without being contacted (#4003). It applies on top of `with_root`.
## Text search and cache limits
+81 -7
View File
@@ -575,6 +575,8 @@ impl Automation {
}
impl Automation {
/// Recognition settings from the arguments: `dpi` (clamped to 72–600), `language` (refused
/// unless the models read it) and `skip_text_pages`, each left at its default when absent.
pub(crate) fn ocr_settings(&self, a: &Args) -> Result<pdfcraft_engine::ocr::OcrSettings> {
let mut settings = pdfcraft_engine::ocr::OcrSettings::default();
if let Some(d) = a.opt_num("dpi")? {
@@ -592,6 +594,9 @@ impl Automation {
Ok(settings)
}
/// Recognizes text in each of `paths` and writes the result under the same file name in
/// `folder`, reporting per file its output, word count and skipped pages, or its error. A
/// path outside the root refuses the whole call before any work starts.
pub(crate) fn ocr_recognize_files(&mut self, a: &Args) -> Result<Value> {
let settings = self.ocr_settings(a)?;
let folder = self.resolve(a.str("folder")?, true)?;
@@ -601,15 +606,26 @@ impl Automation {
for p in &paths {
self.resolve_for(p, crate::file_access::Access::Read, true)?;
}
// Two inputs that would write the same output file overwrite each other while both report
// success, so the whole batch is refused here: before the folder is created, anything is
// read, or the OCR engines load.
let targets: Vec<std::path::PathBuf> = paths.iter().map(|p| child(&folder, &input_file_name(p))).collect();
let shared = shared_file_names(&targets);
if !shared.is_empty() {
return Err(ToolError::InvalidArgs(format!(
"more than one input would write to the same output file, so each would replace the one before it. Colliding file names: {}. Give each input a different file name, or run them in separate batches with different folders.",
shared.join(", ")
)));
}
std::fs::create_dir_all(&folder).map_err(|e| failed(e.to_string()))?;
let ocr = pdfcraft_engine::ocr::engine().map_err(failed)?;
let mut out = Vec::new();
for p in paths {
let name = std::path::Path::new(p).file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| "document.pdf".into());
let name = input_file_name(p);
let result =
self.resolve(p, false).map_err(|e| e.to_string()).and_then(|src| std::fs::read(&src).map_err(|e| e.to_string())).and_then(|bytes| {
pdfcraft_engine::ocr::recognize_file(&name, std::sync::Arc::new(bytes), None, settings.clone(), &ocr, |_, _| true)
});
self.resolve(p, false).map_err(|e| e.to_string()).and_then(|src| crate::read_input_bytes(&src).map_err(|e| e.to_string())).and_then(
|bytes| pdfcraft_engine::ocr::recognize_file(&name, std::sync::Arc::new(bytes), None, settings.clone(), &ocr, |_, _| true),
);
out.push(match result {
Ok(r) => {
let target = child(&folder, &name);
@@ -623,6 +639,8 @@ impl Automation {
Ok(json!({ "files": out }))
}
/// Recognizes text on the open document's `pages` (every page when absent) and adds it,
/// reporting the total word count and, per page, why it was skipped or what it found.
pub(crate) fn ocr_recognize(&mut self, a: &Args) -> Result<Value> {
let settings = self.ocr_settings(a)?;
let pages = if a.opt_ints("pages")?.is_some() { self.pages(a, "pages")? } else { Vec::new() };
@@ -642,6 +660,8 @@ impl Automation {
Ok(json!({ "words": found.iter().map(|p| p.words.len()).sum::<usize>(), "pages": list }))
}
/// Whether text recognition's models are installed, the directories searched for them (in
/// order), and the languages it reads, each as a code and a name.
pub(crate) fn ocr_status(&self) -> Result<Value> {
use pdfcraft_engine::ocr;
let dirs: Vec<String> = ocr::Models::search_dirs().iter().map(|d| d.to_string_lossy().into_owned()).collect();
@@ -650,6 +670,39 @@ impl Automation {
}
}
/// The file name an input is written under: its own file name, or `document.pdf` when it has none.
fn input_file_name(path: &str) -> String {
std::path::Path::new(path).file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| "document.pdf".into())
}
/// The output file names that two or more of `targets` share, each spelling listed once, in input
/// order. Names are compared without regard to case on Windows and macOS and exactly elsewhere; on
/// Windows a trailing dot or space is not part of the name (`scan.pdf.` is `scan.pdf`). Unicode
/// normalization forms (NFC and NFD spellings of one name) are not compared, so such inputs are
/// not caught. The folder is the same for every target, so only the names are compared.
fn shared_file_names(targets: &[std::path::PathBuf]) -> Vec<String> {
let mut groups: std::collections::BTreeMap<String, (usize, Vec<String>)> = std::collections::BTreeMap::new();
for target in targets {
let name = target.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
let key = if cfg!(windows) {
name.trim_end_matches(['.', ' ']).to_lowercase()
} else if cfg!(target_os = "macos") {
// Case only; NFC and NFD spellings of one name stay distinct here (a known limit).
name.to_lowercase()
} else {
name.clone()
};
let (count, spellings) = groups.entry(key).or_insert_with(|| (0, Vec::new()));
*count += 1;
if !spellings.contains(&name) {
spellings.push(name);
}
}
groups.into_values().filter(|(count, _)| *count > 1).flat_map(|(_, spellings)| spellings).collect()
}
/// A script's request to the viewer as the JSON that running a script reports; a side panel
/// goes by its fixed id.
fn request_json(r: &pdfcraft_engine::js::Request) -> Value {
use pdfcraft_engine::js::Request as R;
match r {
@@ -661,6 +714,7 @@ fn request_json(r: &pdfcraft_engine::js::Request) -> Value {
R::Focus(f) => json!({ "focus": f }),
R::Beep => json!({ "beep": true }),
R::SaveAs => json!({ "save_as": true }),
R::ShowPanel(p) => json!({ "panel": p.id() }),
}
}
@@ -669,7 +723,9 @@ impl Automation {
let id = self.doc(a)?.id;
let o = self.session.run_javascript(id, a.str("script")?, a.opt_str("field")?).map_err(failed)?;
let reqs: Vec<Value> = o.requests.iter().map(request_json).collect();
Ok(json!({ "alerts": o.alerts, "console": o.console, "requests": reqs, "error": o.error, "result": o.result }))
Ok(
json!({ "alerts": o.alerts, "console": o.console, "requests": reqs, "error": o.error, "document_errors": o.doc_errors, "result": o.result }),
)
}
pub(crate) fn js_document_scripts(&self, a: &Args) -> Result<Value> {
@@ -700,7 +756,7 @@ impl Automation {
let mut files = Vec::new();
for p in a.strs("paths")? {
let path = self.resolve(p, false)?;
files.push((p.to_string(), std::fs::read(&path).map_err(|e| failed(format!("{p}: {e}")))?));
files.push((p.to_string(), crate::read_input_bytes(&path).map_err(|e| failed(format!("{p}: {e}")))?));
}
let csv = pdfcraft_engine::merge_data_files(&files).map_err(failed)?;
let target = self.resolve(a.str("path")?, true)?;
@@ -845,7 +901,7 @@ impl Automation {
let result = self
.resolve(p, false)
.map_err(|e| e.to_string())
.and_then(|src| std::fs::read(&src).map_err(|e| e.to_string()))
.and_then(|src| crate::read_input_bytes(&src).map_err(|e| e.to_string()))
.and_then(|bytes| run_on(&action, &name, std::sync::Arc::new(bytes), |_, _| {}));
out.push(match result {
Ok(r) => {
@@ -1042,3 +1098,21 @@ mod review_html_tests {
assert!(!html.contains("<script>"));
}
}
#[cfg(test)]
mod shared_output_name_tests {
use super::*;
#[test]
fn shared_output_names_follow_the_default_filesystem() {
let targets = |names: &[&str]| -> Vec<std::path::PathBuf> { names.iter().map(|n| std::path::Path::new("out").join(n)).collect() };
// A spelling that repeats is one shared name, listed once.
assert_eq!(shared_file_names(&targets(&["a.pdf", "b.pdf", "a.pdf"])), vec!["a.pdf".to_string()]);
assert!(shared_file_names(&targets(&["a.pdf", "b.pdf"])).is_empty());
// Case is ignored on Windows and macOS only; a trailing dot is ignored on Windows only.
let case = shared_file_names(&targets(&["scan.pdf", "Scan.PDF"]));
let dot = shared_file_names(&targets(&["scan.pdf", "scan.pdf."]));
assert_eq!(case.len(), if cfg!(any(windows, target_os = "macos")) { 2 } else { 0 }, "{case:?}");
assert_eq!(dot.len(), if cfg!(windows) { 2 } else { 0 }, "{dot:?}");
}
}
+2 -2
View File
@@ -58,7 +58,7 @@ impl<'a> Recipe<'a> {
}
fn accepts(&self, path: &Path) -> bool {
let extension = path.extension().and_then(|s| s.to_str()).unwrap_or("").to_ascii_lowercase();
let extension = path.extension().and_then(std::ffi::OsStr::to_str).unwrap_or("").to_ascii_lowercase();
extension == "pdf" || (self.steps.contains(&"convert") && pdfcraft_engine::CONVERTIBLE.contains(&extension.as_str()))
}
@@ -70,7 +70,7 @@ impl<'a> Recipe<'a> {
if input.len() as u64 > MAX_INPUT {
return Err(failed("input exceeds 512 MiB"));
}
let name = path.file_name().and_then(|n| n.to_str()).ok_or_else(|| failed("input name is not UTF-8"))?;
let name = path.file_name().and_then(std::ffi::OsStr::to_str).ok_or_else(|| failed("input name is not UTF-8"))?;
let mut bytes = Arc::new(input);
let mut log = Vec::new();
for step in &self.steps {
+14 -14
View File
@@ -3,9 +3,7 @@
//! Geometry follows the automation convention: points from the top-left of the displayed page,
//! y down. It is converted to PDF user space (crop box, `/Rotate`) here.
use pdfcraft_engine::{
Edit, LineEnding, Markup, NOTE_SIZE, NewAnnotation, NoteIcon, ReviewState, Rgb, Shape, StampGroup, StampKind, Style, SummarySort,
};
use pdfcraft_engine::{Edit, LineEnding, Markup, NewAnnotation, NoteIcon, ReviewState, Rgb, Shape, StampGroup, StampKind, Style, SummarySort};
use pdfcraft_render::{Annotation, PageInfo};
use serde_json::{Value, json};
@@ -81,13 +79,11 @@ fn rect_to_user(p: &PageInfo, r: [f64; 4]) -> [f64; 4] {
}
/// The engine's `at` for a note or attachment icon whose top-left corner *as displayed* is the
/// view point (x, y): the top-left (`[x0, y1]`) of the icon's square in user space. Converting
/// the point alone is only right on unrotated pages — under `/Rotate` that corner of the
/// displayed square is another corner of the user-space one, and the icon lands one icon-width
/// away from where it was asked for.
/// view point (x, y): the upper-left corner (`[x0, y1]`) of its `/Rect`. Notes and attachments
/// are NoRotate, so on a turned page the icon is drawn upright with its top-left at that corner
/// (ISO 32000-2 §12.5.3), and `comment_list` reports that square (`Annotation::shown_rect`).
fn icon_anchor(p: &PageInfo, x: f64, y: f64) -> [f64; 2] {
let r = rect_to_user(p, [x, y, x + NOTE_SIZE, y + NOTE_SIZE]);
[r[0], r[3]]
to_user(p, x, y)
}
/// A user-space rectangle as the displayed-page rectangle every tool reports and accepts:
@@ -183,8 +179,7 @@ impl Automation {
"author": c.author,
"contents": c.contents,
"modified": c.modified,
// Unchanged on a page the viewer could not read (#2660), as `doc_info` reports it.
"rect": crate::view_rect(&doc.info, c.page, c.rect),
"rect": crate::view_rect(&doc.info, c.page, c.shown_rect(doc.info.pages.get(c.page).map_or(0, |p| p.rotation))),
"color": c.color.map(hex),
});
// A line's ends, or the corners of connected lines, a polygon or a cloud, as
@@ -387,7 +382,7 @@ impl Automation {
"attachment" => {
let [x, y] = a.need::<2>("at", "an attachment (its icon's top-left)")?;
let path = self.resolve(a.str("path")?, false)?;
let data = std::fs::read(&path).map_err(|e| failed(format!("{}: {e}", path.display())))?;
let data = crate::read_input(&path)?;
let file = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
let icon = match a.opt_str("icon")? {
Some(n) => pdfcraft_engine::AttachIcon::from_name(n)
@@ -640,7 +635,12 @@ impl Automation {
edits.push(Edit::FontSizeAnnotation { page, index, size });
}
if let Some(r) = a.nums::<4>("rect")? {
edits.push(Edit::ResizeAnnotation { page, index, rect: rect_to_user(&info, r) });
// The rectangle as comment_list reports it: where the comment is drawn.
let doc = self.doc(a)?;
let rect = rect_to_user(&info, r);
let rect =
doc.info.annotations.iter().find(|c| c.page == page && c.index == index).map_or(rect, |c| c.rect_for_shown(rect, info.rotation));
edits.push(Edit::ResizeAnnotation { page, index, rect });
}
if let Some([dx, dy]) = a.nums::<2>("move")? {
let (o, d) = (to_user(&info, 0.0, 0.0), to_user(&info, dx, dy));
@@ -698,7 +698,7 @@ impl Automation {
}
};
let path = self.resolve(a.str("path")?, false)?;
let bytes = std::fs::read(&path).map_err(|e| failed(format!("{}: {e}", path.display())))?;
let bytes = crate::read_input(&path)?;
let file = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
let name = a.opt_str("name")?.map(str::to_owned).unwrap_or_else(|| file.rsplit_once('.').map_or(file.clone(), |(s, _)| s.to_owned()));
let edit = Edit::AddCustomStamp {
+69 -5
View File
@@ -2,7 +2,7 @@
//! move/resize/retype/restyle it, delete it. Geometry is in points from the top-left of the
//! displayed page (y down), like every other tool.
use pdfcraft_engine::{AddedContent, AddedText, Edit, FontFamily, TextAlign};
use pdfcraft_engine::{ADDED_CHAR_SPACING_LIMIT, AddedContent, AddedText, Edit, FontFamily, TextAlign};
use serde_json::{Value, json};
use crate::comments::parse_color;
@@ -61,6 +61,12 @@ fn style(a: &Args, t: &mut AddedText) -> Result<()> {
other => return Err(bad(format!("unknown align {other:?}"))),
};
}
if let Some(c) = a.opt_num("char_spacing")? {
if !(-ADDED_CHAR_SPACING_LIMIT..=ADDED_CHAR_SPACING_LIMIT).contains(&c) {
return Err(bad(format!("char_spacing must be between -{ADDED_CHAR_SPACING_LIMIT} and {ADDED_CHAR_SPACING_LIMIT} points")));
}
t.char_spacing = c;
}
Ok(())
}
@@ -85,6 +91,7 @@ impl Automation {
v["size"] = json!(t.size);
v["bold"] = json!(t.bold);
v["italic"] = json!(t.italic);
v["char_spacing"] = json!(t.char_spacing);
}
AddedContent::Image(_) => v["type"] = json!("image"),
}
@@ -118,7 +125,7 @@ impl Automation {
let page = self.page(a)?;
let ph = self.doc(a)?.info.pages[page].height as f64;
let path = self.resolve(a.str("path")?, false)?;
let bytes = std::fs::read(&path).map_err(|e| failed(format!("{}: {e}", path.display())))?;
let bytes = crate::read_input(&path)?;
let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
let rect = rect_arg(a, "rect")?.map(|r| to_display(r, ph));
let mut out = self.apply(a, Edit::AddImage { page, rect, name, bytes: std::sync::Arc::new(bytes) })?;
@@ -164,8 +171,8 @@ impl Automation {
if a.get("text").is_some() {
return Err(bad("images have no text"));
}
if ["font", "size", "bold", "italic", "color", "align"].iter().any(|k| a.get(k).is_some()) {
return Err(bad("font, size, bold, italic, color and align apply to text"));
if ["font", "size", "bold", "italic", "color", "align", "char_spacing"].iter().any(|k| a.get(k).is_some()) {
return Err(bad("font, size, bold, italic, color, align and char_spacing apply to text"));
}
if let Some(deg) = a.opt_int("rotate")? {
if deg.rem_euclid(90) != 0 {
@@ -188,7 +195,7 @@ impl Automation {
}
if let Some(p) = a.opt_str("image")? {
let path = self.resolve(p, false)?;
let bytes = std::fs::read(&path).map_err(|e| failed(format!("{}: {e}", path.display())))?;
let bytes = crate::read_input(&path)?;
let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
// Box and transforms first, then the new picture.
self.apply(a, Edit::UpdateContent { page, index, content: content.clone() })?;
@@ -203,6 +210,63 @@ impl Automation {
let (page, index, _, _) = self.item(a)?;
self.apply(a, Edit::DeleteContent { page, index })
}
/// Edit ▸ Copy, then Paste: an added item onto `to_page` of `to_doc` (its own page and
/// document by default), as it is, at `at` (its top-left) or where it was, stepped down and to
/// the right past copies of it already on that page.
pub(crate) fn content_copy(&mut self, a: &Args) -> Result<Value> {
let (page, index, content, _) = self.item(a)?;
let source = self.doc(a)?;
source.check_copying()?;
let from = source.id;
let file = match &content {
AddedContent::Text(_) => None,
AddedContent::Image(_) => {
let (ext, bytes) = source.added_image_file(page, index).map_err(failed)?;
Some((format!("Pasted image.{ext}"), std::sync::Arc::new(bytes)))
}
};
let to_doc = match a.opt_int("to_doc")? {
Some(d) => {
let d = u64::try_from(d).map_err(|_| bad("to_doc must be positive"))?;
self.session.get(pdfcraft_engine::DocId(d)).ok_or_else(|| failed(format!("no open document with id {d} (see doc_list)")))?.id
}
None => from,
};
let doc = self.session.get(to_doc).ok_or_else(|| failed("the document is no longer open"))?;
let n = doc.info.pages.len();
let to_page = match a.opt_int("to_page")? {
Some(p) => usize::try_from(p)
.ok()
.and_then(|p| p.checked_sub(1))
.filter(|p| *p < n)
.ok_or_else(|| bad(format!("to_page {p} is out of range: the document has {n} pages")))?,
None if page < n => page,
None => return Err(bad(format!("page {} is out of range in the target: it has {n} pages; pass to_page", page + 1))),
};
let info = doc.info.pages.get(to_page).ok_or_else(|| bad("the page no longer exists"))?;
let (pw, ph) = (f64::from(info.width), f64::from(info.height));
let at = match a.get("at") {
Some(v) => {
let p: Option<Vec<f64>> = v.as_array().and_then(|x| x.iter().map(Value::as_f64).collect());
let [x, y]: [f64; 2] = p.and_then(|p| p.try_into().ok()).ok_or_else(|| bad("at must be [x, y]"))?;
Some([x, ph - y])
}
None => None,
};
let on_page = || doc.added().iter().filter(|x| x.page == to_page);
let rect = match at {
Some(at) => pdfcraft_engine::added_paste_rect(content.rect(), [pw, ph], 0, Some(at)),
None => pdfcraft_engine::added_paste_place(on_page().map(|x| &x.content), &content, [pw, ph]),
};
let before = on_page().count();
let target = json!({ "doc": to_doc.0 });
let mut out = self.apply(&Args(&target), Edit::PasteContent { page: to_page, content: content.with_rect(rect), file })?;
out["page"] = json!(to_page + 1);
out["index"] = json!(before + 1);
out["rect"] = json!(to_view(rect, ph).map(|x| (x * 100.0).round() / 100.0));
Ok(out)
}
}
impl Automation {
+59 -8
View File
@@ -9,6 +9,9 @@
//! links are followed: for a file that doesn't exist yet, the links of its nearest existing
//! folder, the rest of the path being plain names (`..` below a missing folder is refused, and so
//! is a link that leads nowhere).
//! - A path on another network share or in a device namespace (`\\host\share`, `\\.\pipe\x`)
//! than the root's is refused by name, before anything is resolved: resolving it would contact
//! the host.
//! - The result must lie inside the root, compared by whole components (`/work2` isn't inside
//! `/work`), without regard to case on Windows.
//! - Read and write access are separate: a root given alone grants only its own kind of access.
@@ -97,7 +100,10 @@ impl AutomationRoots {
Access::Write => Err(format!("automation filesystem access is not granted: write authority is absent: {shown}")),
};
};
if inside(&resolve(shown, target)?, folder) {
let absolute = absolute(shown, target)?;
// Another network share or a device is refused by name, as `--root` refuses it: even
// resolving the path would contact the host (#4003).
if !foreign_share(&absolute, folder) && inside(&resolve(shown, &absolute)?, folder) {
return Ok(());
}
let root = root_shown.display();
@@ -123,9 +129,8 @@ fn plain(path: PathBuf) -> PathBuf {
}
}
/// `path` made absolute with its links followed; for a path that doesn't exist (yet), its nearest
/// existing folder's links followed and the rest appended.
fn resolve(shown: &str, path: &Path) -> Result<PathBuf, String> {
/// `path` made absolute against the working directory, by name: nothing on disk is read.
fn absolute(shown: &str, path: &Path) -> Result<PathBuf, String> {
if path.as_os_str().is_empty() {
return Err("automation path rejected: path is empty".into());
}
@@ -133,10 +138,15 @@ fn resolve(shown: &str, path: &Path) -> Result<PathBuf, String> {
if cfg!(windows) && path.components().any(|c| matches!(c, Component::Normal(n) if is_device_name(&n.to_string_lossy()))) {
return Err(format!("automation path rejected: reserved device names are not allowed: {shown}"));
}
let absolute = std::path::absolute(path).map_err(|e| format!("automation path rejected: cannot resolve {shown}: {e}"))?;
std::path::absolute(path).map_err(|e| format!("automation path rejected: cannot resolve {shown}: {e}"))
}
/// `absolute` with its links followed; for a path that doesn't exist (yet), its nearest existing
/// folder's links followed and the rest appended.
fn resolve(shown: &str, absolute: &Path) -> Result<PathBuf, String> {
// The names below the nearest existing folder, last first.
let mut missing: Vec<OsString> = vec![];
let mut at = absolute.as_path();
let mut at = absolute;
loop {
match std::fs::canonicalize(at) {
Ok(mut found) => {
@@ -189,6 +199,24 @@ fn same_component(a: Component, b: Component) -> bool {
}
}
/// Whether `path` names another network share or device namespace than `root` (Windows
/// `\\host\share`, `\\?\UNC\…`, `\\.\…`, `\\?\…`). Those are refused by name: even checking
/// that one exists would contact the host. Drive letters are left to the normal check.
pub(crate) fn foreign_share(path: &Path, root: &Path) -> bool {
use std::path::Prefix;
fn share(p: &Path) -> Option<String> {
let Some(Component::Prefix(prefix)) = p.components().next() else { return None };
let (kind, a, b) = match prefix.kind() {
Prefix::Disk(_) | Prefix::VerbatimDisk(_) => return None,
Prefix::UNC(host, share) | Prefix::VerbatimUNC(host, share) => ("unc", host, share),
Prefix::DeviceNS(name) => ("device", name, std::ffi::OsStr::new("")),
Prefix::Verbatim(name) => ("verbatim", name, std::ffi::OsStr::new("")),
};
Some(format!("{kind}\\{}\\{}", a.to_string_lossy(), b.to_string_lossy()).to_lowercase())
}
share(path).is_some_and(|s| share(root).as_ref() != Some(&s))
}
/// A Windows device name (`CON`, `NUL`, `COM1`… also with an extension), which names no file.
fn is_device_name(component: &str) -> bool {
let stem = component.split('.').next().unwrap_or(component).trim_end_matches(' ').to_ascii_uppercase();
@@ -233,6 +261,27 @@ mod tests {
let _ = std::fs::remove_dir_all(base);
}
/// #4003: another share or a device namespace is refused by name, with the same words as any
/// other path outside the root, before anything is resolved (which would contact the host).
#[cfg(windows)]
#[test]
fn other_shares_and_devices_are_refused_before_they_are_resolved() {
let (base, roots) = folders("shares");
for p in [
r"\\.\pipe\pdfcraft-4003.pdf",
r"\\?\GLOBALROOT\Device\Null",
r"\\pdfcraft-no-such-host.invalid\share\a.pdf",
"//pdfcraft-no-such-host.invalid/share/a.pdf",
r"\\?\UNC\pdfcraft-no-such-host.invalid\share\a.pdf",
] {
let e = roots.check(p, Access::Read).unwrap_err();
assert!(e.starts_with("automation path rejected: outside the read root"), "{p}: {e}");
let e = roots.check(p, Access::Write).unwrap_err();
assert!(e.starts_with("automation path rejected: outside the write root"), "{p}: {e}");
}
let _ = std::fs::remove_dir_all(base);
}
#[test]
fn a_sibling_with_the_same_prefix_is_outside() {
let (base, roots) = folders("prefix");
@@ -345,7 +394,8 @@ mod tests {
// Helpers that are only called with a resolved path. `doc_batch` (batch.rs) resolves its
// inputs and out_dir, walks only inside them (skipping links) and resolves every
// discovered file again before `process` reads it or `publish` writes it.
const RESOLVED_BY_CALLER: &[&str] = &["write_atomic", "write_atomic_with", "read_review_sidecar", "process", "linked", "walk", "publish"];
const RESOLVED_BY_CALLER: &[&str] =
&["write_atomic", "write_atomic_with", "read_input", "read_input_bytes", "read_review_sidecar", "process", "linked", "walk", "publish"];
let dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("src");
let mut offenders = vec![];
for entry in std::fs::read_dir(&dir).unwrap() {
@@ -365,7 +415,8 @@ mod tests {
|| !(trimmed.contains("std::fs")
|| trimmed.contains("File::open")
|| trimmed.contains("File::create")
|| trimmed.contains("OpenOptions"))
|| trimmed.contains("OpenOptions")
|| trimmed.contains("read_input"))
{
continue;
}
+18 -1
View File
@@ -288,6 +288,23 @@ impl Automation {
let edit = if edits.len() == 1 { edits.remove(0) } else { Edit::Batch { label: "Fill in form".into(), edits } };
let mut out = self.apply(a, edit)?;
out["filled"] = json!(values.len());
// A value the box cuts off at a fixed font size is saved whole but shows only in part:
// said, not silent (#4018).
let doc = self.doc(a)?;
let cut: Vec<Value> = values
.keys()
.filter_map(|name| doc.field_overflow(name).map(|(page, o)| (name, page, o)))
.map(|(name, page, o)| {
let page = page.map(|p| format!(" (page {})", p.saturating_add(1))).unwrap_or_default();
json!(format!("form field {name:?}{page}: {o}, so the box shows only part of it (the whole value is saved)"))
})
.collect();
if !cut.is_empty() {
match out.get_mut("warnings").and_then(Value::as_array_mut) {
Some(w) => w.extend(cut),
None => out["warnings"] = Value::Array(cut),
}
}
Ok(out)
}
@@ -684,7 +701,7 @@ impl Automation {
pub(crate) fn doc_import_data(&mut self, a: &Args) -> Result<Value> {
let path = self.resolve(a.str("path")?, false)?;
let bytes = std::fs::read(&path).map_err(|e| failed(format!("{}: {e}", path.display())))?;
let bytes = crate::read_input(&path)?;
let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
let before = (self.doc(a)?.info.annotations.len(), self.doc(a)?.form.iter().filter(|f| !f.value.is_empty()).count());
let mut out = self.apply(a, Edit::ImportData { name, bytes: std::sync::Arc::new(bytes) })?;
+129 -32
View File
@@ -106,6 +106,7 @@ const MAX_BOOKMARK_POSITION: f64 = 1_000_000.0;
const FIND_FIRST_BATCH: usize = 8;
const FIND_MAX_BATCH: usize = 128;
use file_access::foreign_share;
use text_cache::TextCache;
type PageTexts = Vec<(usize, std::result::Result<Arc<PageText>, String>)>;
@@ -424,7 +425,7 @@ impl Automation {
"page_replace" => {
let pages = self.pages(&a, "pages")?;
let path = self.resolve(a.str("path")?, false)?;
let bytes = Arc::new(std::fs::read(&path).map_err(|e| failed(format!("{}: {e}", path.display())))?);
let bytes = Arc::new(read_input(&path)?);
let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
let src_pages = match a.opt_ints("from_pages")? {
Some(p) => one_based(&p)?,
@@ -573,7 +574,7 @@ impl Automation {
"delete" => ImageEdit::Delete,
"replace" => {
let path = self.resolve(a.str("path")?, false)?;
let bytes = std::fs::read(&path).map_err(|e| failed(format!("{}: {e}", path.display())))?;
let bytes = read_input(&path)?;
ImageEdit::Replace {
name: path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(),
bytes: Arc::new(bytes),
@@ -803,7 +804,7 @@ impl Automation {
"form_fill" => self.form_fill(&a)?,
"form_set_image" => {
let path = self.resolve(a.str("path")?, false)?;
let bytes = std::fs::read(&path).map_err(|e| failed(format!("{}: {e}", path.display())))?;
let bytes = read_input(&path)?;
self.apply(&a, Edit::SetFieldImage { name: a.str("field")?.to_owned(), image: Arc::new(bytes) })?
}
"form_reset" => self.form_reset(&a)?,
@@ -835,7 +836,27 @@ impl Automation {
"page_add_image" => self.page_add_image(&a)?,
"content_update" => self.content_update(&a)?,
"content_delete" => self.content_delete(&a)?,
"content_copy" => self.content_copy(&a)?,
"doc_print" => self.doc_print(&a)?,
"attachment_add" => {
let path = self.resolve(a.str("path")?, false)?;
let bytes = read_input(&path)?;
let name = match a.opt_str("name")? {
Some(n) => n.to_string(),
None => path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(),
};
let mime = pdfcraft_engine::mime_for_name(&name).map(str::to_string);
let description = a.opt_str("description")?.map(str::to_string);
// Only the document-level keys: an annotation attachment of the same name is not the new one.
let before = document_attachment_keys(self.doc(&a)?);
let out = self.apply(&a, Edit::AddAttachment { name, bytes, description, mime })?;
let key = document_attachment_keys(self.doc(&a)?).into_iter().find(|n| !before.contains(n)).unwrap_or_default();
json!({ "name": key, "document": out })
}
"attachment_delete" => {
let edit = Edit::DeleteAttachment { key: a.str("name")?.into() };
self.apply(&a, edit)?
}
"doc_remove_hidden" => self.doc_remove_hidden(&a)?,
"doc_audit_redactions" => self.doc_audit_redactions(&a)?,
"fill_sign_add" => self.fill_sign_add(&a)?,
@@ -1037,7 +1058,7 @@ impl Automation {
fn doc_open(&mut self, a: &Args) -> Result<Value> {
let path = self.resolve(a.str("path")?, false)?;
let bytes = std::fs::read(&path).map_err(|e| failed(format!("{}: {e}", path.display())))?;
let bytes = read_input(&path)?;
let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
let id = self.session.open(name, Some(path.to_string_lossy().into_owned()), Arc::new(bytes), a.opt_str("password")?).map_err(failed)?;
let doc = self.session.get(id).ok_or_else(|| failed("the document vanished"))?;
@@ -1215,7 +1236,7 @@ impl Automation {
}
fn doc_optimize(&mut self, a: &Args) -> Result<Value> {
use pdfcraft_engine::optimize::{Compression, ImageSettings, Preset};
use pdfcraft_engine::optimize::{Compatibility, Compression, ImageSettings, Preset};
let id = self.doc(a)?.id;
let before = self.doc(a)?.bytes.len();
let path = self.resolve(a.str("path")?, true)?;
@@ -1223,6 +1244,10 @@ impl Automation {
None => Preset::Standard.settings(),
Some(p) => Preset::from_name(p).ok_or_else(|| ToolError::InvalidArgs(format!("unknown preset {p:?} (standard, mobile)")))?.settings(),
};
if let Some(c) = a.opt_str("compatibility")? {
settings.compatibility = Compatibility::from_name(c)
.ok_or_else(|| ToolError::InvalidArgs(format!("unknown compatibility {c:?} (retain, 1.4, 1.5, 1.6, 1.7, 2.0)")))?;
}
let images = |key: &str, base: ImageSettings| -> Result<ImageSettings> {
let Some(v) = a.get(key) else { return Ok(base) };
let mut s = base;
@@ -1256,6 +1281,8 @@ impl Automation {
("discard_tags", &mut settings.discard_tags),
("discard_print_settings", &mut settings.discard_print_settings),
("flate_unencoded", &mut settings.flate_unencoded),
("object_streams", &mut settings.object_streams),
("lzw_to_flate", &mut settings.lzw_to_flate),
("remove_invalid_links", &mut settings.remove_invalid_links),
("remove_unreferenced_dests", &mut settings.remove_unreferenced_dests),
] {
@@ -1278,9 +1305,26 @@ impl Automation {
};
let (bytes, r) = self.session.optimized_bytes(id, &settings, &discard).map_err(failed)?;
write_atomic(&path, &bytes)?;
fn valid_version(v: &[u8]) -> Option<&str> {
if matches!(v, [b'1'..=b'9', b'.', b'0'..=b'9']) { std::str::from_utf8(v).ok() } else { None }
}
let catalog_version = (settings.compatibility == Compatibility::Retain)
.then(|| {
let pw = self.doc(a).ok().and_then(|d| d.password.as_deref());
let doc = pdfcraft_cos::Document::open_with_password(bytes.clone(), pw).ok()?;
let root = doc.root()?;
doc.get(root).as_dict()?.name(b"Version").and_then(valid_version).map(str::to_owned)
})
.flatten();
let header_version = bytes.strip_prefix(b"%PDF-").and_then(|b| b.get(..3)).and_then(valid_version);
// Viewers read the later of the two (object streams raise the header past a lower catalog
// entry). Both are "d.d", so text order is version order.
let pdf_version = catalog_version.as_deref().into_iter().chain(header_version).max();
let o = &r.optimize;
Ok(json!({
"path": path.to_string_lossy(),
"pdf_version": pdf_version,
"object_streams": settings.effective_object_streams(),
"bytes_before": before,
"bytes_after": bytes.len(),
"merged_images": o.merged_images,
@@ -1294,6 +1338,7 @@ impl Automation {
"alternate_images": o.alternate_images,
"tags_removed": o.tags_removed,
"streams_compressed": o.streams_compressed,
"lzw_streams": o.lzw_streams,
"invalid_links": o.invalid_links,
"invalid_bookmarks": o.invalid_bookmarks,
"unreferenced_dests": o.unreferenced_dests,
@@ -1307,7 +1352,7 @@ impl Automation {
fn mark_file(&self, a: &Args) -> Result<Option<pdfcraft_engine::MarkFile>> {
let Some(p) = a.opt_str("file")? else { return Ok(None) };
let path = self.resolve(p, false)?;
let bytes = std::fs::read(&path).map_err(|e| failed(format!("{}: {e}", path.display())))?;
let bytes = read_input(&path)?;
let page = a.opt_int("file_page")?.unwrap_or(1).max(1) as usize - 1;
Ok(Some(pdfcraft_engine::MarkFile {
name: path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(),
@@ -1481,7 +1526,7 @@ impl Automation {
let mut images = Vec::new();
for p in a.strs("paths")? {
let path = self.resolve(p, false)?;
let bytes = std::fs::read(&path).map_err(|e| failed(format!("{}: {e}", path.display())))?;
let bytes = read_input(&path)?;
images.push((path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(), bytes));
}
let name = if images.len() == 1 {
@@ -1496,7 +1541,7 @@ impl Automation {
(Some(t), _) => ("Text".to_string(), t.to_string()),
(None, Some(p)) => {
let path = self.resolve(p, false)?;
let t = std::fs::read(&path).map_err(|e| failed(format!("{}: {e}", path.display())))?;
let t = read_input(&path)?;
(path.file_stem().map(|s| s.to_string_lossy().into_owned()).unwrap_or_default(), pdfcraft_engine::decode_text(&t))
}
(None, None) => return Err(ToolError::InvalidArgs("text needs `text` or `path`".into())),
@@ -1671,7 +1716,7 @@ impl Automation {
fn insert_file(&mut self, a: &Args) -> Result<Value> {
let at = self.position(a, "at")?;
let path = self.resolve(a.str("path")?, false)?;
let bytes = std::fs::read(&path).map_err(|e| failed(format!("{}: {e}", path.display())))?;
let bytes = read_input(&path)?;
let pages = a.opt_ints("pages")?.map(|p| one_based(&p)).transpose()?;
let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
self.apply(a, Edit::InsertPagesFrom { name, bytes: Arc::new(bytes), pages, at, field_conflicts: pdfcraft_organize::FieldConflicts::Rename })
@@ -1714,7 +1759,7 @@ impl Automation {
// Each file is read, converted and copied in turn, so a long list holds one file at a time.
let sources = paths.into_iter().zip(ranges).map(|(p, range)| -> std::result::Result<pdfcraft_engine::CombineSource, ToolError> {
let path = self.resolve(p, false)?;
let bytes = std::fs::read(&path).map_err(|e| failed(format!("{}: {e}", path.display())))?;
let bytes = read_input(&path)?;
let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
let (_, pdf) = self.session.convert_to_pdf(&name, &Arc::new(bytes)).map_err(failed)?;
let title = path.file_stem().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
@@ -1731,7 +1776,7 @@ impl Automation {
let mut out = Vec::new();
for &p in paths {
let converted = self.resolve(p, false).map_err(|e| e.to_string()).and_then(|src| {
let bytes = std::fs::read(&src).map_err(|e| format!("{}: {e}", src.display()))?;
let bytes = read_input_bytes(&src).map_err(|e| format!("{}: {e}", src.display()))?;
let name = src.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
let stem = src.file_stem().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| "document".into());
let (kind, pdf) = self.session.convert_to_pdf(&name, &Arc::new(bytes)).map_err(|e| e.to_string())?;
@@ -1835,7 +1880,7 @@ impl Automation {
if let Some(g) = group {
firsts.push((g, path.clone(), sources.len()));
}
let bytes = Arc::new(std::fs::read(&path).map_err(|e| failed(format!("{}: {e}", path.display())))?);
let bytes = Arc::new(read_input(&path)?);
// Images and text files are made into PDFs first (#569), as in the Combine files tab.
let file_name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
self.session.as_pdf(&file_name, &bytes).map_err(failed)?
@@ -2328,24 +2373,6 @@ fn lexical(path: &Path) -> Option<PathBuf> {
Some(parts.iter().collect())
}
/// Whether `path` names another network share or device namespace than `root` (Windows
/// `\\host\share`, `\\?\UNC\…`, `\\.\…`, `\\?\…`). Those are refused by name: even checking
/// that one exists would contact the host. Drive letters are left to the normal check.
fn foreign_share(path: &Path, root: &Path) -> bool {
use std::path::{Component, Prefix};
fn share(p: &Path) -> Option<String> {
let Some(Component::Prefix(prefix)) = p.components().next() else { return None };
let (kind, a, b) = match prefix.kind() {
Prefix::Disk(_) | Prefix::VerbatimDisk(_) => return None,
Prefix::UNC(host, share) | Prefix::VerbatimUNC(host, share) => ("unc", host, share),
Prefix::DeviceNS(name) => ("device", name, std::ffi::OsStr::new("")),
Prefix::Verbatim(name) => ("verbatim", name, std::ffi::OsStr::new("")),
};
Some(format!("{kind}\\{}\\{}", a.to_string_lossy(), b.to_string_lossy()).to_lowercase())
}
share(path).is_some_and(|s| share(root).as_ref() != Some(&s))
}
// ---- JSON helpers ----------------------------------------------------------------------------
fn parse_style_ranges(value: Option<&Value>) -> Result<Vec<pdfcraft_engine::RangeStyle>> {
@@ -2462,6 +2489,18 @@ impl Args<'_> {
}
}
/// The name-tree keys of a document's own attachments, leaving out the files attached to pages as comments.
fn document_attachment_keys(doc: &Document) -> Vec<String> {
doc.info
.attachments
.iter()
.filter_map(|x| match &x.source {
pdfcraft_render::AttachmentSource::Document { key } => Some(key.clone()),
pdfcraft_render::AttachmentSource::Annotation { .. } => None,
})
.collect()
}
/// Bookmark rows in listing order as JSON: a row holds the rows that follow it on the page at the
/// next level down in `children`, and paths and pages are 1-based.
fn nest_rows(rows: &[pdfcraft_engine::BookmarkRow], pages: &[pdfcraft_render::PageInfo]) -> Vec<Value> {
@@ -2596,6 +2635,9 @@ fn info(d: &Document) -> Value {
"creator": i.creator, "producer": i.producer,
"tagged": i.tagged,
"has_javascript": i.has_javascript,
// Where the document opens (/OpenAction, named destinations resolved): 1-based page and
// destination, null without one.
"open_destination": i.open_dest.as_ref().map(|(p, view)| json!({ "page": page1(*p), "destination": i.pages.get(*p).and_then(|pg| destination(view, pg)) })),
// XFA forms: "static" (the PDF's own fields work; the XFA data is ignored) or "dynamic"
// (laid out from the template by PdfCraft, see xfa_layout; placeholder pages when that failed).
"xfa": i.xfa.map(|x| match x { pdfcraft_render::Xfa::Static => "static", pdfcraft_render::Xfa::Dynamic => "dynamic" }),
@@ -2616,7 +2658,8 @@ fn info(d: &Document) -> Value {
// geometry-taking tools (#129).
"annotations": i.annotations.iter().map(|a| json!({
"page": page1(a.page), "type": a.subtype, "author": a.author, "contents": a.contents,
"modified": a.modified, "name": a.name, "in_reply_to": a.in_reply_to, "rect": view_rect(i, a.page, a.rect),
"modified": a.modified, "name": a.name, "in_reply_to": a.in_reply_to,
"rect": view_rect(i, a.page, a.shown_rect(i.pages.get(a.page).map_or(0, |p| p.rotation))),
})).collect::<Vec<_>>(),
"fields": i.fields.iter().map(|f| json!({
"name": f.name, "kind": format!("{:?}", f.kind), "value": f.value, "page": f.page.map(page1),
@@ -2700,7 +2743,7 @@ fn extract_parallel(bytes: &Arc<Vec<u8>>, password: Option<Arc<str>>, pages: &[u
}
};
let config = RenderConfig { password, ..Default::default() };
let workers = if cfg!(target_arch = "wasm32") { 1 } else { std::thread::available_parallelism().map_or(1, |n| n.get()).min(8) };
let workers = if cfg!(target_arch = "wasm32") { 1 } else { std::thread::available_parallelism().map_or(1, std::num::NonZeroUsize::get).min(8) };
// Small jobs aren't worth a second parse of the document.
if workers == 1 || pages.len() < 8 {
let mut r = PageRenderer::new(bytes.clone(), config);
@@ -2748,6 +2791,28 @@ fn unused(dir: &Path, stem: &str) -> PathBuf {
(2..10_000u32).map(|n| child(dir, &format!("{stem} ({n}).pdf"))).find(|p| !p.exists()).unwrap_or(first)
}
/// Largest input file a tool reads into memory (512 MiB, matching `doc_batch`).
pub(crate) const MAX_INPUT: u64 = 512 * 1024 * 1024;
/// Read a resolved input file of at most [`MAX_INPUT`] bytes without buffering past the cap.
pub(crate) fn read_input_bytes(path: &Path) -> std::io::Result<Vec<u8>> {
use std::io::Read as _;
let file = std::fs::File::open(path)?;
if file.metadata().is_ok_and(|m| m.is_file() && m.len() > MAX_INPUT) {
return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "input exceeds 512 MiB"));
}
let mut bytes = Vec::new();
file.take(MAX_INPUT + 1).read_to_end(&mut bytes)?;
if bytes.len() as u64 > MAX_INPUT {
return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "input exceeds 512 MiB"));
}
Ok(bytes)
}
pub(crate) fn read_input(path: &Path) -> Result<Vec<u8>> {
read_input_bytes(path).map_err(|e| failed(format!("{}: {e}", path.display())))
}
/// Write and sync a temporary file in the same directory, then rename over the target.
/// This flushes staged contents; it does not promise parent-directory durability after a
/// power loss. Filesystems that refuse sync cause the save to fail before publication.
@@ -3305,4 +3370,36 @@ mod tests {
assert!(a.session.get(id).is_none());
}
}
#[test]
fn tool_file_reads_refuse_inputs_exceeding_512_mib() {
let dir = staging_dir("capped-read");
let huge = dir.join("huge.bin");
let file = std::fs::File::create(&huge).unwrap();
file.set_len(MAX_INPUT + 1).unwrap();
drop(file);
let huge_str = huge.to_string_lossy().into_owned();
let mut a = Automation::new();
let id = a.session.open("a.pdf", None, Arc::new(numbered_pages(2)), None).unwrap().0;
for (tool, args) in [
("doc_open", json!({ "path": huge_str })),
("page_insert_file", json!({ "doc": id, "at": 1, "path": huge_str })),
("page_replace", json!({ "doc": id, "pages": [1], "path": huge_str })),
("page_add_image", json!({ "doc": id, "page": 1, "path": huge_str })),
("doc_import_data", json!({ "doc": id, "path": huge_str })),
("doc_create", json!({ "from": "text", "path": huge_str })),
("doc_create", json!({ "from": "images", "paths": [huge_str] })),
("doc_combine", json!({ "paths": [huge_str, huge_str] })),
("form_merge_data", json!({ "paths": [huge_str], "path": dir.join("out.csv").to_string_lossy() })),
("comment_add", json!({ "doc": id, "page": 1, "type": "attachment", "at": [72.0, 72.0], "path": huge_str })),
("stamp_custom", json!({ "doc": id, "page": 1, "at": [72.0, 72.0], "path": huge_str })),
("sign_trust", json!({ "paths": [huge_str] })),
("attachment_add", json!({ "doc": id, "path": huge_str })),
] {
let err = a.call(tool, &args).unwrap_err().to_string();
assert!(err.contains("input exceeds 512 MiB"), "{tool}: {err}");
}
let _ = std::fs::remove_dir_all(&dir);
}
}
+145 -9
View File
@@ -25,6 +25,10 @@ const PARSE_ERROR: i64 = -32700;
const INVALID_REQUEST: i64 = -32600;
const METHOD_NOT_FOUND: i64 = -32601;
const INVALID_PARAMS: i64 = -32602;
const INTERNAL_ERROR: i64 = -32603;
/// Longest JSON-RPC request line [`McpServer::serve`] buffers into memory (16 MiB).
pub const MAX_LINE_BYTES: usize = 16 * 1024 * 1024;
const INSTRUCTIONS: &str = "PdfCraft edits PDFs. Open a file with doc_open to get a document id, then inspect \
(doc_info, text_extract, text_find, page_render) or edit it (page_*, doc_set_info). Edits are undoable \
@@ -83,18 +87,36 @@ impl McpServer {
}
/// Serve until `input` reaches end of file.
pub fn serve(&mut self, input: impl BufRead, mut output: impl Write) -> std::io::Result<()> {
for line in input.lines() {
let line = line?;
if line.trim().is_empty() {
continue;
pub fn serve(&mut self, mut input: impl BufRead, mut output: impl Write) -> std::io::Result<()> {
let mut buf = Vec::new();
loop {
match read_line_limited(&mut input, &mut buf, MAX_LINE_BYTES)? {
LineRead::End => return Ok(()),
LineRead::TooLong => {
drain_line(&mut input)?;
buf.clear();
buf.shrink_to(64 * 1024);
let reply = error(Value::Null, INVALID_REQUEST, &format!("request line exceeds {MAX_LINE_BYTES} bytes"));
writeln!(output, "{reply}")?;
output.flush()?;
continue;
}
LineRead::Line => {}
}
if let Some(reply) = self.handle_line(&line) {
let reply = match std::str::from_utf8(&buf) {
Ok(line) if line.trim().is_empty() => None,
Ok(line) => self.handle_line(line),
Err(e) => Some(error(Value::Null, PARSE_ERROR, &format!("parse error: {e}")).to_string()),
};
if buf.capacity() > 64 * 1024 {
buf.clear();
buf.shrink_to(64 * 1024);
}
if let Some(reply) = reply {
writeln!(output, "{reply}")?;
output.flush()?;
}
}
Ok(())
}
/// Handle one JSON-RPC message; returns the serialized reply, if one is due.
@@ -116,7 +138,7 @@ impl McpServer {
};
let params = obj.get("params").cloned().unwrap_or(Value::Null);
let id = id?; // notifications/initialized, notifications/cancelled, …: nothing to answer
let result = if method == "tools/call" { guarded_tool(|| self.dispatch(method, &params)) } else { self.dispatch(method, &params) };
let result = guarded_dispatch(method, || self.dispatch(method, &params));
Some(match result {
Ok(result) => json!({ "jsonrpc": "2.0", "id": id, "result": result }),
Err((code, message)) => error(id, code, &message),
@@ -323,11 +345,67 @@ fn unwrap_tool_call(args: &Value) -> Result<(String, Value), String> {
Ok((name.to_owned(), inner))
}
/// What [`read_line_limited`] found.
#[derive(Debug, PartialEq, Eq)]
enum LineRead {
/// A line, now in the buffer (newline and a trailing `\r` stripped).
Line,
/// End of stream.
End,
/// The line is longer than the limit; at most `max + 1` bytes of it were read.
TooLong,
}
/// Read one `\n`-terminated line of at most `max` bytes into `buf`.
fn read_line_limited(reader: &mut impl BufRead, buf: &mut Vec<u8>, max: usize) -> std::io::Result<LineRead> {
use std::io::Read as _;
buf.clear();
// `take` bounds what is buffered for one line: never more than `max + 1` bytes.
let limit = u64::try_from(max).unwrap_or(u64::MAX).saturating_add(1);
if reader.take(limit).read_until(b'\n', buf)? == 0 {
return Ok(LineRead::End);
}
if buf.last() == Some(&b'\n') {
buf.pop();
if buf.last() == Some(&b'\r') {
buf.pop();
}
return Ok(LineRead::Line);
}
// No newline: either the limit was passed, or this is a last line before end of stream.
Ok(if buf.len() > max { LineRead::TooLong } else { LineRead::Line })
}
/// Discard the rest of an overlong line up to `\n` or end of stream without buffering it.
fn drain_line(reader: &mut impl BufRead) -> std::io::Result<()> {
loop {
let chunk = reader.fill_buf()?;
if chunk.is_empty() {
return Ok(());
}
if let Some(pos) = chunk.iter().position(|&b| b == b'\n') {
reader.consume(pos + 1);
return Ok(());
}
let len = chunk.len();
reader.consume(len);
}
}
/// Last-resort boundary shared by every tools/call route, including compact dispatch.
fn guarded_tool(f: impl FnOnce() -> Result<Value, (i64, String)>) -> Result<Value, (i64, String)> {
pdfcraft_engine::guard(f).unwrap_or_else(|message| Ok(tool_error(&format!("internal error: {message}"))))
}
/// Last-resort boundary for every JSON-RPC method: tool calls report panics in the tool result
/// (`isError: true`), while resource and protocol methods report a JSON-RPC internal error.
fn guarded_dispatch(method: &str, f: impl FnOnce() -> Result<Value, (i64, String)>) -> Result<Value, (i64, String)> {
if method == "tools/call" {
return guarded_tool(f);
}
pdfcraft_engine::guard(f).unwrap_or_else(|message| Err((INTERNAL_ERROR, format!("internal error: {message}"))))
}
fn tool_content(name: &str, content: Vec<Content>) -> Value {
let failed = matches!(name, "command_batch" | "doc_batch")
&& content.iter().any(|c| match c {
@@ -509,7 +587,12 @@ fn call_result(content: Vec<Content>) -> Value {
#[cfg(test)]
mod tests {
use super::{Resource, first_sentence, parse_uri};
use std::io::{BufReader, Read as _};
use serde_json::{Value, json};
use super::{McpServer, Resource, first_sentence, parse_uri};
use crate::Automation;
#[test]
fn conventions_panic_is_a_tool_error() {
@@ -520,6 +603,59 @@ mod tests {
assert_eq!(next["ok"], true);
}
#[test]
fn guarded_dispatch_catches_resource_and_protocol_panics() {
for method in ["resources/read", "resources/list", "resources/templates/list", "initialize"] {
let (code, msg) = super::guarded_dispatch(method, || panic!("synthetic {method} failure")).unwrap_err();
assert_eq!(code, -32603, "{method}");
assert!(msg.contains(&format!("synthetic {method} failure")), "{msg}");
}
let ok = super::guarded_dispatch("resources/list", || Ok(json!({"resources": []}))).unwrap();
assert_eq!(ok["resources"], json!([]));
}
#[test]
fn read_line_limited_and_drain_line_respect_boundaries() {
use super::{LineRead, drain_line, read_line_limited};
let mut buf = Vec::new();
let mut input: &[u8] = b"aaaaaaaaaa\nbb\r\ncc";
assert_eq!(read_line_limited(&mut input, &mut buf, 10).unwrap(), LineRead::Line);
assert_eq!(buf, b"aaaaaaaaaa", "a line exactly at the limit is accepted");
assert_eq!(read_line_limited(&mut input, &mut buf, 10).unwrap(), LineRead::Line);
assert_eq!(buf, b"bb", "CRLF is stripped");
assert_eq!(read_line_limited(&mut input, &mut buf, 10).unwrap(), LineRead::Line);
assert_eq!(buf, b"cc", "a last line without a newline is still read");
assert_eq!(read_line_limited(&mut input, &mut buf, 10).unwrap(), LineRead::End);
let mut overlong: &[u8] = b"0123456789abcdef\nafter\n";
assert_eq!(read_line_limited(&mut overlong, &mut buf, 10).unwrap(), LineRead::TooLong);
assert_eq!(buf.len(), 11, "at most max + 1 bytes are buffered");
drain_line(&mut overlong).unwrap();
assert_eq!(read_line_limited(&mut overlong, &mut buf, 10).unwrap(), LineRead::Line);
assert_eq!(buf, b"after", "the next line after an overlong line is read cleanly");
}
#[test]
fn serve_answers_non_utf8_and_overlong_lines_and_keeps_serving() {
let init = json!({
"jsonrpc": "2.0",
"id": 1,
"method": "initialize",
"params": { "protocolVersion": "2025-06-18", "capabilities": {}, "clientInfo": { "name": "test", "version": "0" } }
})
.to_string();
let tail = format!("\n{init}\n");
let stream = (&b"\xff\n"[..]).chain(std::io::repeat(b'a').take(64 * 1024 * 1024)).chain(tail.as_bytes());
let mut out = Vec::new();
McpServer::new(Automation::new()).serve(BufReader::new(stream), &mut out).unwrap();
let replies: Vec<Value> = String::from_utf8(out).unwrap().lines().map(|l| serde_json::from_str(l).unwrap()).collect();
assert_eq!(replies.len(), 3, "{replies:?}");
assert_eq!(replies[0]["error"]["code"], -32700);
assert_eq!(replies[1]["error"]["code"], -32600);
assert_eq!(replies[2]["id"], 1);
assert_eq!(replies[2]["result"]["serverInfo"]["name"], "pdfcraft");
}
#[test]
fn first_sentence_skips_abbreviations() {
assert_eq!(first_sentence("Rotate pages. Undoable."), "Rotate pages.");
+105 -36
View File
@@ -22,11 +22,72 @@ fn duplex(value: &str, cut_stack: bool) -> Result<Option<spool::Duplex>> {
})
}
/// [`duplex`] for a job laid out as `layout`: the name is checked either way, and a booklet
/// decides two-sided itself (#2707), as the Print dialog does (`print::booklet_duplex`).
fn job_duplex(value: &str, layout: &Layout) -> Result<Option<spool::Duplex>> {
let chosen = duplex(value, matches!(layout, Layout::Multiple { order: PageOrder::CutStack, .. }))?;
Ok(match layout {
Layout::Booklet { subset, .. } => Some(print::booklet_duplex(*subset)),
_ => chosen,
})
}
/// An invalid-arguments error saying `m`.
fn bad(m: impl Into<String>) -> ToolError {
ToolError::InvalidArgs(m.into())
}
/// `doc_print`'s `paper`, by its name or a short form ("Letter", "ARCH D"), as its `PAPERS`
/// index and size; US Letter when none is given.
fn paper_named(name: Option<&str>) -> Result<(usize, (f64, f64))> {
let mut papers = PAPERS.iter().enumerate();
let found = match name {
None => papers.next(),
Some(p) => papers.find(|(_, (n, _))| {
n.eq_ignore_ascii_case(p)
|| n.replace("US ", "").eq_ignore_ascii_case(p)
|| n.split(" (").next().is_some_and(|name| name.eq_ignore_ascii_case(p))
}),
};
found.map(|(index, (_, size))| (index, *size)).ok_or_else(|| {
bad(format!(
"unknown paper {:?}; choose one of {}",
name.unwrap_or_default(),
PAPERS.iter().map(|(name, _)| *name).collect::<Vec<_>>().join(", ")
))
})
}
/// The spooler job for `doc_print` to `printer`. It feeds the paper the PDF was laid out on
/// (`PAPERS[paper]`, as `media` after the driver's `options`) rather than the queue's default
/// paper, which a job naming none got (A4 under Letter sheets on the queue in #3752).
fn spool_job(a: &Args, printer: &str, title: String, duplex: Option<spool::Duplex>, paper: usize) -> Result<spool::Job> {
let options = match a.get("options") {
None => Vec::new(),
Some(Value::Object(m)) => m
.iter()
.map(|(k, v)| match v.as_str() {
Some(v) => Ok((k.clone(), v.to_string())),
None => Err(bad(format!("options.{k} must be a string (a choice from printer_options)"))),
})
.collect::<Result<Vec<_>>>()?,
Some(_) => return Err(bad("options must be an object of option keys and choices from printer_options")),
};
Ok(spool::Job {
printer: if printer == "default" { None } else { Some(printer.to_string()) },
copies: a.opt_int("copies")?.unwrap_or(1).clamp(1, 999) as u32,
collate: a.opt_bool("collate")?.unwrap_or(true),
duplex,
scaling: spool::Scaling::Exact,
grayscale: a.opt_bool("grayscale")?.unwrap_or(false),
title,
options: options.into_iter().chain(print::media_option(paper)).collect(),
})
}
impl Automation {
/// `printers`: the system's printers, the default marked, and each one's two-sided support
/// where the spooler reports it.
pub(crate) fn printers(&self) -> Result<Value> {
let list: Vec<Value> = spool::printers()
.into_iter()
@@ -53,6 +114,8 @@ impl Automation {
Ok(json!({ "printer": printer, "count": list.len(), "options": list }))
}
/// `doc_print`: lay the document out with the Print dialog's options, then save the
/// print-ready PDF to `path` or send it to `printer` with the chosen paper.
pub(crate) fn doc_print(&mut self, a: &Args) -> Result<Value> {
let doc = self.doc(a)?;
let (id, count) = (doc.id, doc.info.pages.len());
@@ -108,7 +171,7 @@ impl Automation {
},
l => return Err(bad(format!("unknown layout {l:?}"))),
};
let duplex = duplex(a.opt_str("duplex")?.unwrap_or("off"), matches!(layout, Layout::Multiple { order: PageOrder::CutStack, .. }))?;
let duplex = job_duplex(a.opt_str("duplex")?.unwrap_or("off"), &layout)?;
if a.opt_str("order")? == Some("cut-stack") && !matches!(layout, Layout::Multiple { .. }) {
return Err(bad("cut-stack order needs layout multiple"));
}
@@ -125,20 +188,7 @@ impl Automation {
"form-fields-only" => Content::FormFieldsOnly,
c => return Err(bad(format!("unknown comments_forms {c:?}"))),
};
let paper = match a.opt_str("paper")? {
None => PAPERS[0].1,
Some(p) => PAPERS
.iter()
.find(|(n, _)| {
n.eq_ignore_ascii_case(p)
|| n.replace("US ", "").eq_ignore_ascii_case(p)
|| n.split(" (").next().is_some_and(|name| name.eq_ignore_ascii_case(p))
})
.map(|x| x.1)
.ok_or_else(|| {
bad(format!("unknown paper {p:?}; choose one of {}", PAPERS.iter().map(|(name, _)| *name).collect::<Vec<_>>().join(", ")))
})?,
};
let (paper_index, paper) = paper_named(a.opt_str("paper")?)?;
// Print as image (Acrobat's Advanced Print Setup): pictures at `dpi`, grey when
// `grayscale` is also asked for.
let raster = if a.opt_bool("as_image")?.unwrap_or(false) {
@@ -162,27 +212,7 @@ impl Automation {
out["path"] = json!(path.to_string_lossy());
}
(None, Some(printer)) => {
let name = self.doc(a)?.name.clone();
let job = spool::Job {
printer: if printer == "default" { None } else { Some(printer.to_string()) },
copies: a.opt_int("copies")?.unwrap_or(1).clamp(1, 999) as u32,
collate: a.opt_bool("collate")?.unwrap_or(true),
duplex,
scaling: spool::Scaling::Exact,
grayscale: a.opt_bool("grayscale")?.unwrap_or(false),
title: name,
options: match a.get("options") {
None => Vec::new(),
Some(Value::Object(m)) => m
.iter()
.map(|(k, v)| match v.as_str() {
Some(v) => Ok((k.clone(), v.to_string())),
None => Err(bad(format!("options.{k} must be a string (a choice from printer_options)"))),
})
.collect::<Result<Vec<_>>>()?,
Some(_) => return Err(bad("options must be an object of option keys and choices from printer_options")),
},
};
let job = spool_job(a, printer, self.doc(a)?.name.clone(), duplex, paper_index)?;
out["job"] = json!(spool::submit(&bytes, &job).map_err(|e| failed(e.to_string()))?);
}
_ => return Err(bad("pass either path (save the print-ready PDF) or printer (a name from printers, or \"default\")")),
@@ -195,6 +225,19 @@ impl Automation {
mod tests {
use super::*;
/// #2707: a booklet sets two-sided itself whatever `duplex` asks; a bad name is still an error.
#[test]
fn a_booklet_decides_two_sided_itself() {
let booklet = |subset| Layout::Booklet { subset, binding: Binding::Left };
for asked in ["printer", "off", "long-edge", "short-edge"] {
assert_eq!(job_duplex(asked, &booklet(BookletSubset::BothSides)).ok(), Some(Some(spool::Duplex::ShortEdge)), "{asked}");
assert_eq!(job_duplex(asked, &booklet(BookletSubset::FrontOnly)).ok(), Some(Some(spool::Duplex::Off)), "{asked}");
assert_eq!(job_duplex(asked, &booklet(BookletSubset::BackOnly)).ok(), Some(Some(spool::Duplex::Off)), "{asked}");
}
assert!(job_duplex("sideways", &booklet(BookletSubset::BothSides)).is_err());
assert_eq!(job_duplex("long-edge", &Layout::Size(SizeMode::Fit)).ok(), Some(Some(spool::Duplex::LongEdge)), "other layouts keep it");
}
/// `printer` leaves two-sided to the printer's own default (#2422); cut and stack still asks
/// for single-sided sheets, and refuses an explicit edge.
#[test]
@@ -207,4 +250,30 @@ mod tests {
assert!(duplex("long-edge", true).is_err());
assert!(duplex("sideways", false).is_err());
}
/// #3752: `doc_print` to a printer sent no paper, so the queue's default paper stood in for
/// the one the sheets were laid out on (A4 under Letter sheets on the report's queue).
#[test]
fn printing_to_a_printer_feeds_the_laid_out_paper() {
let job = |args: Value, paper_name: Option<&str>| {
let (index, _) = paper_named(paper_name).unwrap();
spool_job(&Args(&args), "Office", "a.pdf".into(), None, index).unwrap()
};
let media = |m: &str| ("media".to_string(), m.to_string());
// US Letter when no paper is asked for, after the driver's own options.
let letter = job(json!({ "options": { "InputSlot": "Tray3" } }), None);
assert_eq!(letter.options, [("InputSlot".to_string(), "Tray3".to_string()), media("Letter")]);
assert_eq!((letter.printer.as_deref(), letter.title.as_str()), (Some("Office"), "a.pdf"));
// Every paper, by its full name, goes out as its own media name.
for (i, (name, size)) in PAPERS.iter().enumerate() {
assert_eq!(paper_named(Some(name)).ok(), Some((i, *size)), "{name}");
assert_eq!(job(json!({}), Some(name)).options, print::media_option(i).into_iter().collect::<Vec<_>>(), "{name}");
}
// Short forms find the same paper.
assert_eq!(job(json!({}), Some("letter")).options, [media("Letter")]);
assert_eq!(job(json!({}), Some("ARCH D")).options, [media("na_arch-d_24x36in")]);
assert!(matches!(paper_named(Some("Quarto")), Err(ToolError::InvalidArgs(m)) if m.contains("US Letter")));
assert_eq!(spool_job(&Args(&json!({})), "default", String::new(), None, 0).ok().map(|j| j.printer), Some(None));
assert!(spool_job(&Args(&json!({ "options": { "InputSlot": 3 } })), "Office", String::new(), None, 0).is_err());
}
}
+2 -2
View File
@@ -189,7 +189,7 @@ impl Automation {
return Err(failed(format!("windows:{r}: Windows certificate store identities are only available on Windows")));
}
let path = self.resolve(a.str("id")?, false)?;
let bytes = std::fs::read(&path).map_err(|e| failed(format!("{}: {e}", path.display())))?;
let bytes = crate::read_input(&path)?;
sign::pkcs12::open(&bytes, a.opt_str("password")?.unwrap_or("")).map_err(|e| match e {
sign::SignError::WrongPassword => bad("the digital ID password is incorrect"),
e => failed(e),
@@ -320,7 +320,7 @@ impl Automation {
};
for p in paths {
let path = self.resolve(&p, false)?;
let bytes = std::fs::read(&path).map_err(|e| failed(format!("{}: {e}", path.display())))?;
let bytes = crate::read_input(&path)?;
let lower = p.to_ascii_lowercase();
let found = if lower.ends_with(".p12") || lower.ends_with(".pfx") {
let id = sign::pkcs12::open(&bytes, a.opt_str("password")?.unwrap_or("")).map_err(failed)?;
+34 -9
View File
@@ -129,11 +129,17 @@ pub fn tools() -> Vec<ToolDef> {
"dpi": {"type":"number","minimum":72,"maximum":600},
"language": {"type":"string"}, "skip_text_pages": {"type":"boolean"}
}), &["paths","out_dir","steps"])),
t("attachment_add", "Attach a file", "Attach the file at path to the document (document level, the Attachments panel; not a paper-clip comment on a page). name defaults to the file's name; the attachment's key, unique in the document, is returned. Undoable.")
.cmd("edit.attach")
.with(schema(json!({"doc": doc(), "path": {"type": "string"}, "name": {"type": "string"}, "description": {"type": "string"}}), &["doc", "path"])),
t("attachment_delete", "Delete an attachment", "Remove the document-level attachment with this name (as doc_info lists it). Undoable.")
.destructive()
.with(schema(json!({"doc": doc(), "name": {"type": "string"}}), &["doc", "name"])),
t("doc_open", "Open a PDF", "Open a PDF file and return its document id, page count and whether it can be edited.")
.cmd("file.open")
.with(schema(json!({ "path": { "type": "string" }, "password": { "type": "string", "description": "User or owner password for encrypted files." } }), &["path"])),
t("doc_list", "List open documents", "List the open documents with their ids, page counts and unsaved state.").ro().with(schema(json!({}), &[])),
t("doc_info", "Inspect a document", "Metadata, page sizes and labels, bookmarks, annotations, form fields, links, layers, page transitions and display times, attachments, fonts, security and repair notes.")
t("doc_info", "Inspect a document", "Metadata, page sizes and labels, bookmarks, annotations, form fields, links, layers, page transitions and display times, the destination it opens at, attachments, fonts, security and repair notes.")
.ro()
.cmd("file.properties")
.with(schema(json!({ "doc": doc() }), &["doc"])),
@@ -364,7 +370,7 @@ pub fn tools() -> Vec<ToolDef> {
t(
"form_add_field",
"Prepare form: add a field",
"Add a form field on a page. type: text, date, checkbox, radio, combo, list, button, image (a picture placeholder; fill it with form_set_image), signature. rect in points from the top-left of the displayed page [x0, y0, x1, y1]. name defaults to Acrobat's next free name (Text1, Check Box1, Group1, Dropdown1, List Box1, Button1, Image1, Signature1, Date1). Radio buttons join the radio group named by group (a new group otherwise) with the export value export. Returns the field's name. Undoable.",
"Add a form field on a page. type: text, date, checkbox, radio, combo, list, button, image (a picture placeholder; fill it with form_set_image), signature. rect in points from the top-left of the displayed page [x0, y0, x1, y1]. name defaults to Acrobat's next free name (Text1, Check Box1, Group1, Dropdown1, List Box1, Button1, Image1, Signature1, Date1); a dotted name such as MASTER.first makes the field first under the parent field MASTER. Radio buttons join the radio group named by group (a new group otherwise) with the export value export. Returns the field's name. Undoable.",
)
.with(schema(
json!({
@@ -424,7 +430,7 @@ pub fn tools() -> Vec<ToolDef> {
t(
"form_set_props",
"Field properties",
"Change field properties: give field for one field, or fields for a list of unique field names (1–1000). A bulk change is atomic and one Undo step; an invalid or locked field leaves every field unchanged. Only the given properties change, and partial appearance changes preserve each field's other colours and font. name (rename), rect (position), rotation and caption require a single field. A rename also renames the field in the calculations that read it (calculate field lists and notation, and getField calls naming it in a string literal; names built at run time are not rewritten), in the same Undo step, and formulas_updated lists the fields whose calculation changed. caption changes one push-button normal label (widget: 1-based index, default 1); an empty string clears it. Other widgets and icon-only layouts are preserved. General and Options: tooltip, read_only, required, multiline, max_length (0 = no limit), options (combo/list items), font_size (0 = auto), format, validate, calculate (Acrobat's native AF rules). Options: align (left, center, right), default (Reset form's value; check boxes/radio buttons use their on state, \"\" for off), flags { scroll, rich_text, password, file_select, spell_check, comb (needs max_length), sort, editable, multi_select, commit_immediately }, check_style (check boxes/radio buttons: check, circle, cross, diamond, square, star). rotation is 0, 90, 180 or 270 degrees counterclockwise and swaps width/height when the axis changes. Undoable.",
"Change field properties: give field for one field, or fields for a list of unique field names (1–1000). A bulk change is atomic and one Undo step; an invalid or locked field leaves every field unchanged. Only the given properties change, and partial appearance changes preserve each field's other colours and font. name (rename: a dotted name such as MASTER.first is the full name and moves the field under those parent fields; a plain name renames it within its parent), rect (position), rotation and caption require a single field. A rename also renames the field in the calculations that read it (calculate field lists and notation, and getField calls naming it in a string literal; names built at run time are not rewritten), in the same Undo step, and formulas_updated lists the fields whose calculation changed. caption changes one push-button normal label (widget: 1-based index, default 1); an empty string clears it. Other widgets and icon-only layouts are preserved. General and Options: tooltip, read_only, required, multiline, max_length (0 = no limit), options (combo/list items), font_size (0 = auto), format, validate, calculate (Acrobat's native AF rules). Options: align (left, center, right), default (Reset form's value; check boxes/radio buttons use their on state, \"\" for off), flags { scroll, rich_text, password, file_select, spell_check, comb (needs max_length), sort, editable, multi_select, commit_immediately }, check_style (check boxes/radio buttons: check, circle, cross, diamond, square, star). rotation is 0, 90, 180 or 270 degrees counterclockwise and swaps width/height when the axis changes. Undoable.",
)
.with(schema(
json!({
@@ -543,7 +549,7 @@ pub fn tools() -> Vec<ToolDef> {
t(
"doc_print",
"Print",
"Print with Acrobat's Print dialog options, or save the print-ready PDF. pages: a range such as \"1-3, 6, 9-\" (page labels allowed; default all); subset odd/even (by page number, as Acrobat counts them: pages 2, 7-10 with even prints 2, 8 and 10, not every second page of the range); reverse. layout: fit (default), actual, shrink, custom (scale %), multiple (per_sheet 2/4/6/9/16, order, border, auto_rotate; cut-stack order arranges single-sided sheets for cutting into piles and stacking left to right, top to bottom, keeping sheet order within each pile; duplex must be off), booklet (booklet_subset both/front/back, binding left/right), poster (scale %, overlap pt, cut_marks). orientation auto/portrait/landscape; comments_forms document / document-and-markups (default) / document-and-stamps / form-fields-only; paper Letter/Legal/Tabloid, ARCH A/B/C/D/E1/E, ANSI C/D/E, A0/A1/A2/A3/A4/A5/A6, or US #10 Envelope (short names or full preset labels); use layout actual for 100% in the print-ready PDF; printer drivers may still substitute paper or scale. Then path (save) or printer (a name or \"default\") with copies, collate, duplex off/long-edge/short-edge, grayscale, and options (driver options from printer_options, CUPS).",
"Print with Acrobat's Print dialog options, or save the print-ready PDF. pages: a range such as \"1-3, 6, 9-\" (page labels allowed; default all); subset odd/even (by page number, as Acrobat counts them: pages 2, 7-10 with even prints 2, 8 and 10, not every second page of the range); reverse. layout: fit (default), actual, shrink, custom (scale %), multiple (per_sheet 2/4/6/9/16, order, border, auto_rotate; cut-stack order arranges single-sided sheets for cutting into piles and stacking left to right, top to bottom, keeping sheet order within each pile; duplex must be off), booklet (booklet_subset both/front/back, binding left/right; a booklet sets two-sided itself, as Acrobat does: both flips on the short edge, front or back prints one-sided), poster (scale %, overlap pt, cut_marks). orientation auto/portrait/landscape; comments_forms document / document-and-markups (default) / document-and-stamps / form-fields-only; paper Letter/Legal/Tabloid, ARCH A/B/C/D/E1/E, ANSI C/D/E, A0/A1/A2/A3/A4/A5/A6, or US #10 Envelope (short names or full preset labels); use layout actual for 100% in the print-ready PDF; printer drivers may still substitute paper or scale. Then path (save) or printer (a name or \"default\") with copies, collate, duplex off/long-edge/short-edge, grayscale, and options (driver options from printer_options, CUPS).",
)
.with(schema(
json!({
@@ -582,7 +588,7 @@ pub fn tools() -> Vec<ToolDef> {
t(
"page_add_text",
"Add text to a page",
"Add text as page content (not a comment). Place it with at [x, y] (top-left, points from the top-left of the displayed page) and width (wrap width, default 200), or rect. Newlines start new lines; long lines wrap. Style: font helvetica/times/courier, size, bold, italic, color (#RRGGBB or a name), align left/center/right. Text must be Western European (WinAnsi) characters, or Arabic, Hebrew or Thai when the build has their craft-fonts faces (drawn right to left where the text is); others are refused. It stays editable with content_update. Undoable.",
"Add text as page content (not a comment). Place it with at [x, y] (top-left, points from the top-left of the displayed page) and width (wrap width, default 200), or rect. Newlines start new lines; long lines wrap. Style: font helvetica/times/courier, size, bold, italic, color (#RRGGBB or a name), align left/center/right, char_spacing (points after each character). Text must be Western European (WinAnsi) characters, or Arabic, Hebrew or Thai when the build has their craft-fonts faces (drawn right to left where the text is); others are refused. It stays editable with content_update. Undoable.",
)
.cmd("edit.text")
.with(schema(
@@ -594,6 +600,7 @@ pub fn tools() -> Vec<ToolDef> {
"font": { "type": "string", "enum": ["helvetica", "times", "courier"] }, "size": { "type": "number", "minimum": 1, "maximum": 500 },
"bold": { "type": "boolean" }, "italic": { "type": "boolean" }, "color": { "type": "string" },
"align": { "type": "string", "enum": ["left", "center", "right", "justify"] },
"char_spacing": { "type": "number", "minimum": -500, "maximum": 500, "description": "Points after each character." },
}),
&["doc", "page", "text"],
)),
@@ -607,7 +614,7 @@ pub fn tools() -> Vec<ToolDef> {
json!({ "doc": doc(), "page": { "type": "integer", "minimum": 1 }, "path": { "type": "string" }, "rect": { "type": "array", "items": { "type": "number" }, "minItems": 4, "maxItems": 4 } }),
&["doc", "page", "path"],
)),
t("content_update", "Edit added content", "Move/resize (rect), retype (text) or restyle (font, size, bold, italic, color, align) an added item (page, index from content_list). Images: rotate (degrees, multiple of 90, counter-clockwise), flip_h / flip_v (toggle), crop [left, bottom, right, top] as fractions trimmed, image (a file that replaces the picture). Undoable.")
t("content_update", "Edit added content", "Move/resize (rect), retype (text) or restyle (font, size, bold, italic, color, align, char_spacing in points) an added item (page, index from content_list). Images: rotate (degrees, multiple of 90, counter-clockwise), flip_h / flip_v (toggle), crop [left, bottom, right, top] as fractions trimmed, image (a file that replaces the picture). Undoable.")
.with(schema(
json!({
"doc": doc(), "page": { "type": "integer", "minimum": 1 }, "index": { "type": "integer", "minimum": 1 },
@@ -615,12 +622,27 @@ pub fn tools() -> Vec<ToolDef> {
"font": { "type": "string", "enum": ["helvetica", "times", "courier"] }, "size": { "type": "number", "minimum": 1, "maximum": 500 },
"bold": { "type": "boolean" }, "italic": { "type": "boolean" }, "color": { "type": "string" },
"align": { "type": "string", "enum": ["left", "center", "right", "justify"] },
"char_spacing": { "type": "number", "minimum": -500, "maximum": 500, "description": "Points after each character." },
"rotate": { "type": "integer" }, "flip_h": { "type": "boolean" }, "flip_v": { "type": "boolean" },
"crop": { "type": "array", "items": { "type": "number", "minimum": 0, "maximum": 0.49 }, "minItems": 4, "maxItems": 4 },
"image": { "type": "string", "description": "Replace the picture with this file." },
}),
&["doc", "page", "index"],
)),
t(
"content_copy",
"Copy and paste added content",
"Copy an added item (page, index from content_list) and paste it, as Edit ▸ Copy and Paste do: onto to_page of to_doc (by default its own page and document) as it is: a text box's text, font, size, colour, alignment and box; an image's picture, box, turns, flips and crop (within its document the same image object is drawn again; into another one the picture goes as its JPEG or JPEG 2000 file, or else a PNG, without a colour profile and with CMYK colours turned to RGB). It goes at at [x, y] (its top-left, points from the top-left of the page), else where it was, 18 points down and to the right past each copy of it already there; kept on the page. Refused when the source document doesn't allow copying. Returns the new item's page, index and rect. Undoable in the target document.",
)
.with(schema(
json!({
"doc": doc(), "page": { "type": "integer", "minimum": 1 }, "index": { "type": "integer", "minimum": 1 },
"to_doc": { "type": "integer", "minimum": 1, "description": "The document to paste into (default doc)." },
"to_page": { "type": "integer", "minimum": 1, "description": "The page to paste onto (default page)." },
"at": { "type": "array", "items": { "type": "number" }, "minItems": 2, "maxItems": 2 },
}),
&["doc", "page", "index"],
)),
t("content_delete", "Delete added content", "Delete an added item (page, index from content_list). Undoable.")
.destructive()
.with(schema(json!({ "doc": doc(), "page": { "type": "integer", "minimum": 1 }, "index": { "type": "integer", "minimum": 1 } }), &["doc", "page", "index"])),
@@ -1110,7 +1132,7 @@ pub fn tools() -> Vec<ToolDef> {
t("form_merge_data", "Merge data files into spreadsheet", "Collect the field values of form data files (FDF, XFDF) or filled-in PDF forms into one CSV file at path: a column per field name, a row per file. Returns the row and column counts.")
.cmd("form.merge_data")
.with(schema(json!({ "paths": { "type": "array", "items": { "type": "string" }, "minItems": 1 }, "path": { "type": "string" } }), &["paths", "path"])),
t("js_run", "Run JavaScript", "Run Acrobat JavaScript in the document, as the JavaScript console does (or as push button `field`'s Mouse Up script when field is given; on a laid-out XFA form, `field` runs that button's XFA click script instead, JavaScript or FormCalc, which can add and remove rows and show or hide subforms). The form object model is available: this/getField, event, app, util, console, display, color, and the document-level scripts. Field changes and resetForm are applied as one undoable step; returns the script's alerts, console output, requests (print, page, url, submit) and error.")
t("js_run", "Run JavaScript", "Run Acrobat JavaScript in the document, as the JavaScript console does (or as push button `field`'s Mouse Up script when field is given; on a laid-out XFA form, `field` runs that button's XFA click script instead, JavaScript or FormCalc, which can add and remove rows and show or hide subforms). The form object model is available: this/getField, event, app, util, console, display, color, and the document-level scripts (except the PDF container scripts when XFA layout is active; they remain available through js_document_scripts). Field changes and resetForm are applied as one undoable step; returns the script's alerts, console output, requests (print, page, url, submit), error, and the errors of document-level scripts that failed (the rest still ran).")
.cmd("tools.js_console")
.with(schema(
json!({ "doc": doc(), "script": { "type": "string" }, "field": { "type": "string", "description": "Run as this button's Mouse Up event." } }),
@@ -1200,7 +1222,7 @@ pub fn tools() -> Vec<ToolDef> {
}),
&["doc"],
)),
t("ocr_recognize_files", "Recognize text in multiple files", "Scan & OCR ▸ Recognize text ▸ In multiple files: read every page of each PDF in paths and write the searchable result into folder under the same name (pages that already have text are left alone unless skip_text_pages is false, as in ocr_recognize). Returns, per file, the output path, word count and skipped pages, or the error.")
t("ocr_recognize_files", "Recognize text in multiple files", "Scan & OCR ▸ Recognize text ▸ In multiple files: read every page of each PDF in paths and write the searchable result into folder under the same name (pages that already have text are left alone unless skip_text_pages is false, as in ocr_recognize). Two inputs that would write the same output file are refused before anything is read or written. Returns, per file, the output path, word count and skipped pages, or the error.")
.cmd("ocr.recognize_batch")
.with(schema(
json!({
@@ -1375,13 +1397,14 @@ pub fn tools() -> Vec<ToolDef> {
.with(schema(json!({ "doc": doc() }), &["doc"])),
t("doc_open_revision", "Open a revision", "Open saved revision `revision` (1 = the oldest) of a document as a new, unsaved document, to see the file as it was then.")
.with(schema(json!({ "doc": doc(), "revision": { "type": "integer", "minimum": 1 } }), &["doc", "revision"])),
t("doc_optimize", "Optimize PDF", "Write an optimized copy to `path` (Acrobat's PDF Optimizer). preset: standard (default; Reduce File Size's choices) or mobile (images to 96 ppi above 144, JPEG high quality); the options below change it. merge_fragments (default true) first puts a page picture drawn as many stacked image strips (as some PDF printers write it) back together into one image, so it can be resampled (merged_images, fragments_merged). color / gray: { downsample, ppi, above_ppi, compression: jpeg|zip|retain, quality 1–100 } (defaults: downsample to 150 ppi above 225, JPEG 60). Images are measured where pages draw them and replaced only when smaller. discard_*: thumbnails (default true), alternate_images (true), tags, print_settings; flate_unencoded (true); remove_invalid_links and remove_unreferenced_dests (true); images and forms the pages list but never draw are always dropped (unused_xobjects). discard: Remove Hidden Information categories (metadata, attachments, comments, form-fields, hidden-text, hidden-layers, bookmarks, links-actions-scripts, private-data). Signed documents are refused. The open document is unchanged.")
t("doc_optimize", "Optimize PDF", "Write an optimized copy to `path` (Acrobat's PDF Optimizer). preset: standard (default; Reduce File Size's choices) or mobile (images to 96 ppi above 144, JPEG high quality); the options below change it. compatibility: retain (default; keeps the document's version, or 1.5 when object streams are written), 1.4, 1.5, 1.6, 1.7 or 2.0. merge_fragments (default true) first puts a page picture drawn as many stacked image strips (as some PDF printers write it) back together into one image, so it can be resampled (merged_images, fragments_merged). color / gray: { downsample, ppi, above_ppi, compression: jpeg|zip|retain, quality 1–100 } (defaults: downsample to 150 ppi above 225, JPEG 60). Images are measured where pages draw them and replaced only when smaller. discard_*: thumbnails (default true), alternate_images (true), tags, print_settings; flate_unencoded (true); object_streams (default true; always off for 1.4); lzw_to_flate (true) decodes LZW streams and stores them with Flate instead, leaving any it cannot decode unchanged (lzw_streams counts the streams converted); remove_invalid_links and remove_unreferenced_dests (true); images and forms the pages list but never draw are always dropped (unused_xobjects). discard: Remove Hidden Information categories (metadata, attachments, comments, form-fields, hidden-text, hidden-layers, bookmarks, links-actions-scripts, private-data). Signed documents are refused. The open document is unchanged.")
.cmd("optimize.advanced")
.with(schema(
json!({
"doc": doc(),
"path": { "type": "string" },
"preset": { "type": "string", "enum": ["standard", "mobile"] },
"compatibility": { "type": "string", "enum": ["retain", "1.4", "1.5", "1.6", "1.7", "2.0"] },
"merge_fragments": { "type": "boolean" },
"color": { "type": "object" },
"gray": { "type": "object" },
@@ -1390,6 +1413,8 @@ pub fn tools() -> Vec<ToolDef> {
"discard_tags": { "type": "boolean" },
"discard_print_settings": { "type": "boolean" },
"flate_unencoded": { "type": "boolean" },
"object_streams": { "type": "boolean" },
"lzw_to_flate": { "type": "boolean" },
"remove_invalid_links": { "type": "boolean" },
"remove_unreferenced_dests": { "type": "boolean" },
"discard": { "type": "array", "items": { "type": "string" } },
@@ -0,0 +1,34 @@
//! `attachment_add` reports the name-tree key of the file it added, even when a file attached to
//! a page as a comment already has the same name.
use pdfcraft_automation::{Automation, Content};
use pdfcraft_engine::{AttachIcon, Edit, NewAnnotation, Session, Shape, Style};
use serde_json::{Value, json};
fn tool(a: &mut Automation, name: &str, args: Value) -> Value {
match a.call(name, &args).unwrap().remove(0) {
Content::Json(value) => value,
other => panic!("expected JSON: {other:?}"),
}
}
#[test]
fn attachment_add_reports_its_own_key_when_a_page_comment_has_the_same_file_name() {
let dir = tempfile::tempdir().unwrap();
let mut session = Session::new();
let bytes = session.create_blank(300.0, 400.0, 1).unwrap();
let id = session.open("a.pdf", None, bytes, None).unwrap();
let shape = Shape::Attachment { at: [20.0, 300.0], icon: AttachIcon::Paperclip, file: "notes.txt".into(), data: b"on the page".to_vec() };
session
.apply(id, Edit::AddAnnotation(NewAnnotation { page: 0, shape, style: Style::default(), contents: String::new(), author: "Ada".into() }))
.unwrap();
std::fs::write(dir.path().join("a.pdf"), session.save_bytes(id).unwrap().as_slice()).unwrap();
std::fs::write(dir.path().join("notes.txt"), b"for the document").unwrap();
let mut auto = Automation::new().with_root(dir.path()).unwrap();
let doc = tool(&mut auto, "doc_open", json!({ "path": "a.pdf" }))["doc"].as_u64().unwrap();
let added = tool(&mut auto, "attachment_add", json!({ "doc": doc, "path": "notes.txt" }));
assert_eq!(added["name"], "notes.txt", "{added}");
let again = tool(&mut auto, "attachment_add", json!({ "doc": doc, "path": "notes.txt" }));
assert_eq!(again["name"], "notes.txt (2)", "{again}");
}
+577 -13
View File
@@ -213,6 +213,49 @@ fn doc_info_lists_page_transitions_and_display_times() {
);
}
/// `doc_info` says where the document opens: the `/OpenAction` destination, a named one
/// resolved (ISO 32000-2 §12.3.2.4), as a 1-based page and a destination in view coordinates.
#[test]
fn doc_info_reports_the_open_destination() {
let dir = workdir("open-destination");
let write = |name: &str, catalog: &str| {
let objects: Vec<String> = vec![
format!("<< /Type /Catalog /Pages 2 0 R {catalog} >>"),
"<< /Type /Pages /Kids [3 0 R 4 0 R] /Count 2 /MediaBox [0 0 612 792] >>".into(),
"<< /Type /Page /Parent 2 0 R >>".into(),
"<< /Type /Page /Parent 2 0 R >>".into(),
];
let mut bytes = b"%PDF-1.7\n".to_vec();
let mut offsets = Vec::new();
for (i, object) in objects.iter().enumerate() {
offsets.push(bytes.len());
bytes.extend_from_slice(format!("{} 0 obj\n{object}\nendobj\n", i + 1).as_bytes());
}
let xref = bytes.len();
bytes.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objects.len() + 1).as_bytes());
for o in offsets {
bytes.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes());
}
bytes.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objects.len() + 1).as_bytes());
std::fs::write(dir.join(name), bytes).unwrap();
};
write("named.pdf", "/OpenAction << /S /GoTo /D /there >> /Dests << /there [4 0 R /XYZ 100 500 2] >>");
write("script.pdf", "/OpenAction << /S /JavaScript /JS (1) >>");
let mut a = auto(&dir);
let doc = ok(&mut a, "doc_open", json!({ "path": "named.pdf" }))["doc"].as_u64().unwrap();
let open = ok(&mut a, "doc_info", json!({ "doc": doc }))["open_destination"].clone();
assert_eq!(open["page"], 2, "{open}");
// y 500 is 292 points below the top of the 792-point page.
assert_eq!(
(open["destination"]["fit"].as_str(), open["destination"]["left"].as_f64(), open["destination"]["top"].as_f64()),
(Some("XYZ"), Some(100.0), Some(292.0)),
"{open}"
);
assert_eq!(open["destination"]["zoom"].as_f64(), Some(2.0));
let doc = ok(&mut a, "doc_open", json!({ "path": "script.pdf" }))["doc"].as_u64().unwrap();
assert!(ok(&mut a, "doc_info", json!({ "doc": doc }))["open_destination"].is_null());
}
/// Page transitions through the tools: set on chosen pages, written to the file as `/Trans` and
/// `/Dur`, removed again, bad values refused, and one undo step. (Read through `pdfcraft_cos`,
/// so this does not lean on `doc_info` listing them.)
@@ -2331,6 +2374,51 @@ fn forms_through_tools() {
assert_ne!(v, "Filled by an agent");
}
/// A PDF of the given objects (numbered from 1).
fn pdf_of(objs: &[&str]) -> Vec<u8> {
let mut out = b"%PDF-1.7\n".to_vec();
let mut offsets = Vec::new();
for (i, o) in objs.iter().enumerate() {
offsets.push(out.len());
out.extend_from_slice(format!("{} 0 obj\n{o}\nendobj\n", i + 1).as_bytes());
}
let xref = out.len();
out.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objs.len() + 1).as_bytes());
for o in offsets {
out.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes());
}
out.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objs.len() + 1).as_bytes());
out
}
/// #4018: `form_fill` warns about a value its box cuts off at the field's fixed font size (the
/// value is saved whole), and not about one that fits.
#[test]
fn form_fill_warns_when_a_value_does_not_fit() {
let objs = [
"<< /Type /Catalog /Pages 2 0 R /AcroForm 4 0 R >>",
"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 400 300] >>",
"<< /Type /Page /Parent 2 0 R /Annots [5 0 R 6 0 R] >>",
"<< /Fields [5 0 R 6 0 R] /DA (/Helv 12 Tf 0 g) /DR << /Font << /Helv 7 0 R >> >> >>",
"<< /Type /Annot /Subtype /Widget /FT /Tx /T (narrow) /Rect [10 250 150 268] /P 3 0 R >>",
"<< /Type /Annot /Subtype /Widget /FT /Tx /T (wide) /Rect [10 200 310 218] /P 3 0 R >>",
"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>",
];
let dir = workdir("form-overflow");
std::fs::write(dir.join("form.pdf"), pdf_of(&objs)).unwrap();
let mut a = auto(&dir);
let doc = ok(&mut a, "doc_open", json!({ "path": "form.pdf" }))["doc"].as_u64().unwrap();
let long = "Doe, Jane (represented by John Doe)";
let r = ok(&mut a, "form_fill", json!({ "doc": doc, "values": { "narrow": long, "wide": long } }));
let warnings: Vec<&str> = r["warnings"].as_array().map(|w| w.iter().filter_map(Value::as_str).collect()).unwrap_or_default();
assert_eq!(warnings.len(), 1, "{r}");
assert!(warnings[0].starts_with("form field \"narrow\" (page 1): the value does not fit"), "{}", warnings[0]);
let after = ok(&mut a, "form_fields", json!({ "doc": doc }));
assert_eq!(after["fields"][0]["value"], long, "saved whole");
let r = ok(&mut a, "form_fill", json!({ "doc": doc, "values": { "narrow": "Ada" } }));
assert!(r.get("warnings").is_none(), "{r}");
}
/// A form whose fields are only page widgets (the `/Fields` list is empty) still lists, fills and
/// resets through the tools, and the leniency shows up as a repair note.
#[test]
@@ -2346,19 +2434,7 @@ fn orphan_form_fields_through_tools() {
"<< /Type /Annot /Subtype /Widget /FT /Tx /T (beta) /Rect [10 150 90 170] /P 3 0 R >>", // 6
"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>", // 7
];
let mut out = b"%PDF-1.7\n".to_vec();
let mut offsets = Vec::new();
for (i, o) in objs.iter().enumerate() {
offsets.push(out.len());
out.extend_from_slice(format!("{} 0 obj\n{o}\nendobj\n", i + 1).as_bytes());
}
let xref = out.len();
out.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objs.len() + 1).as_bytes());
for o in offsets {
out.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes());
}
out.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objs.len() + 1).as_bytes());
out
pdf_of(&objs)
}
let dir = workdir("orphan-forms");
std::fs::write(dir.join("orphan.pdf"), orphan_form()).unwrap();
@@ -2970,6 +3046,43 @@ fn editing_existing_text_through_tools() {
assert_eq!(p["lines"].as_array().map(Vec::len), Some(2), "{p}");
}
#[test]
fn styled_cyrillic_fallback_is_batched_through_tools_and_reopen() {
if pdfcraft_fonts::document_japanese_font().is_none() {
eprintln!("skipping: built without craft-fonts");
return;
}
let dir = workdir("styled-fallback");
std::fs::write(
dir.join("mixed.pdf"),
helvetica_page(
"BT /F1 12 Tf 14.4 TL 72 700 Td (The quick brown fox jumps over the lazy dog) Tj T* (and keeps running through the long field.) Tj ET",
),
)
.unwrap();
let mut a = auto(&dir);
let doc = ok(&mut a, "doc_open", json!({"path": "mixed.pdf"}))["doc"].as_u64().unwrap();
let replacement = "The quick brown fox jumps over the lazy dog шалом\nand keeps running through the long field.";
ok(&mut a, "text_edit", json!({"doc":doc,"page":1,"paragraph":1,"text":replacement,"width":520}));
ok(&mut a, "doc_save", json!({"doc":doc,"path":"saved.pdf"}));
let saved = pdfcraft_cos::Document::open(std::sync::Arc::new(std::fs::read(dir.join("saved.pdf")).unwrap())).unwrap();
let page = pdfcraft_model::pages(&saved).swap_remove(0);
let resources = saved.dict(page.dict.get(b"Resources").unwrap()).unwrap();
let fonts = saved.dict(resources.get(b"Font").unwrap()).unwrap();
let fallback_count = fonts.iter().filter(|(name, _)| name.starts_with(b"PCJp")).count();
assert_eq!(fallback_count, 1, "one shared fallback font for the new word");
ok(&mut a, "edit_undo", json!({"doc":doc}));
assert!(!page_text(&mut a, doc)[0].contains("шалом"));
ok(&mut a, "edit_redo", json!({"doc":doc}));
assert!(page_text(&mut a, doc)[0].contains("шалом"));
let reopened = ok(&mut a, "doc_open", json!({"path":"saved.pdf"}))["doc"].as_u64().unwrap();
let lines = ok(&mut a, "text_lines", json!({"doc":reopened,"page":1}));
let runs = lines["lines"].as_array().unwrap();
assert!(runs.iter().any(|l| l["text"].as_str().is_some_and(|t| t.starts_with("The quick")) && l["font"] == "Helvetica"), "{lines}");
assert_eq!(runs.iter().filter(|l| l["text"] == "шалом").count(), 1, "{lines}");
assert!(page_text(&mut a, reopened)[0].contains("шалом"));
}
/// #2593: a paragraph whose own font cannot show a character is written from PdfCraft's fallback
/// faces. The Cyrillic the craft-fonts faces lack (Uzbek қ ғ ҳ, Kazakh ә ө ү ұ һ) comes from the
/// bundled Inter face, so the edit is not refused even without `CRAFT_FONTS_DIR`, and the words
@@ -3942,6 +4055,28 @@ fn redacting_through_tools() {
assert!(matches!(a.call("redact_mark", &json!({ "doc": doc })), Err(ToolError::InvalidArgs(_))));
}
#[test]
/// Mark, apply and save remove the complete international number while retaining labels and controls.
fn redacting_italian_international_slash_numbers_through_tools() {
let dir = workdir("redact-italian-international-slash");
std::fs::write(dir.join("phones.txt"), "A tel. +39 0426/123456\nB tel. 0426/123456\nC protocol 2024/123456\nD on 01/10/2026").unwrap();
let mut a = auto(&dir);
let doc = ok(&mut a, "doc_create", json!({ "from": "text", "path": "phones.txt" }))["doc"].as_u64().unwrap();
let marked = ok(&mut a, "redact_mark", json!({ "doc": doc, "pattern": "phone" }));
assert_eq!(marked["marked"], 2, "both complete phone numbers need marks");
assert!(page_text(&mut a, doc)[0].contains("+39 0426/123456"), "marks alone remove nothing");
assert_eq!(ok(&mut a, "redact_apply", json!({ "doc": doc }))["applied"], 2);
ok(&mut a, "doc_save", json!({ "doc": doc, "path": "redacted.pdf" }));
let reopened = ok(&mut a, "doc_open", json!({ "path": "redacted.pdf" }))["doc"].as_u64().unwrap();
let text = &page_text(&mut a, reopened)[0];
assert!(!text.contains("+39") && !text.contains("0426"), "{text}");
for label in ["A tel.", "B tel."] {
assert!(text.lines().any(|line| line.trim() == label), "only the surrounding label remains: {text}");
}
assert!(text.contains("protocol 2024/123456") && text.contains("on 01/10/2026"), "unrelated digit runs remain: {text}");
std::fs::remove_dir_all(dir).unwrap();
}
/// One page with the text "Secret 1234" and a Redact annotation that has neither a usable
/// QuadPoints array nor a Rect, so there is no area to redact.
fn redact_pdf_with_unreadable_mark() -> Vec<u8> {
@@ -4271,6 +4406,91 @@ fn adding_content_through_tools() {
assert!(matches!(a.call("content_delete", &json!({ "doc": doc, "page": 1, "index": 5 })), Err(ToolError::Failed(_))));
}
/// Edit ▸ Copy and Paste headlessly (#2636): an added text box or image, as it is, onto its own
/// page beside it, onto a point, and into another document.
#[test]
fn copying_added_content_through_tools() {
let dir = workdir("content-copy");
let mut png = Vec::new();
{
let mut enc = png::Encoder::new(&mut png, 40, 20);
enc.set_color(png::ColorType::Rgb);
enc.write_header().unwrap().write_image_data(&[90u8; 2400]).unwrap();
}
std::fs::write(dir.join("logo.png"), png).unwrap();
let mut a = auto(&dir);
let doc = ok(&mut a, "doc_open", json!({ "path": "a.pdf" }))["doc"].as_u64().unwrap();
let other = ok(&mut a, "doc_open", json!({ "path": "b.pdf" }))["doc"].as_u64().unwrap();
ok(
&mut a,
"page_add_text",
json!({ "doc": doc, "page": 1, "text": "Approved", "at": [20, 20], "width": 100, "size": 18, "bold": true, "font": "times", "color": "red", "align": "center" }),
);
ok(&mut a, "page_add_image", json!({ "doc": doc, "page": 1, "path": "logo.png", "rect": [100, 200, 180, 240] }));
ok(&mut a, "content_update", json!({ "doc": doc, "page": 1, "index": 2, "rotate": 90, "flip_h": true }));
let original = ok(&mut a, "content_list", json!({ "doc": doc }))["items"].clone();
// Beside itself on its own page: 18 points down and to the right, with the style content_list
// shows (the engine test checks colour, alignment and the image transforms).
let r = ok(&mut a, "content_copy", json!({ "doc": doc, "page": 1, "index": 1 }));
assert_eq!((r["page"].as_u64(), r["index"].as_u64()), (Some(1), Some(3)));
let items = ok(&mut a, "content_list", json!({ "doc": doc }))["items"].clone();
let (from, to) = (&original[0], &items[2]);
for key in ["type", "text", "font", "size", "bold", "italic"] {
assert_eq!(from[key], to[key], "{key}");
}
let shifted: Vec<f64> = from["rect"].as_array().unwrap().iter().map(|v| v.as_f64().unwrap() + 18.0).collect();
assert_eq!(to["rect"], json!(shifted));
assert_eq!(r["rect"], to["rect"]);
// An image onto another page at a point, and into another document where it was.
let r = ok(&mut a, "content_copy", json!({ "doc": doc, "page": 1, "index": 2, "to_page": 2, "at": [10, 30] }));
assert_eq!((r["page"].as_u64(), r["index"].as_u64()), (Some(2), Some(1)));
assert_eq!(r["rect"][0].as_f64().zip(r["rect"][1].as_f64()), Some((10.0, 30.0)), "its top-left at the point");
let r = ok(&mut a, "content_copy", json!({ "doc": doc, "page": 1, "index": 2, "to_doc": other }));
assert_eq!(r["rect"], original[1]["rect"], "in the same place");
let theirs = ok(&mut a, "content_list", json!({ "doc": other }));
assert_eq!((theirs["count"].as_u64(), theirs["items"][0]["type"].as_str()), (Some(1), Some("image")));
// Copied there again: it steps past the first copy, whose picture that document stores itself.
let r = ok(&mut a, "content_copy", json!({ "doc": doc, "page": 1, "index": 2, "to_doc": other }));
let stepped: Vec<f64> = original[1]["rect"].as_array().unwrap().iter().map(|v| v.as_f64().unwrap() + 18.0).collect();
assert_eq!(r["rect"], json!(stepped), "beside the first copy, not on it");
// Each paste is one undo step in the document it went into.
ok(&mut a, "edit_undo", json!({ "doc": other }));
ok(&mut a, "edit_undo", json!({ "doc": other }));
assert_eq!(ok(&mut a, "content_list", json!({ "doc": other }))["count"], 0);
assert_eq!(ok(&mut a, "content_list", json!({ "doc": doc }))["count"], 4);
// Out of range: a readable failure.
assert!(matches!(a.call("content_copy", &json!({ "doc": doc, "page": 1, "index": 9 })), Err(ToolError::Failed(_))));
assert!(matches!(a.call("content_copy", &json!({ "doc": doc, "page": 1, "index": 1, "to_page": 9 })), Err(ToolError::InvalidArgs(_))));
assert!(matches!(a.call("content_copy", &json!({ "doc": doc, "page": 1, "index": 1, "to_doc": 999 })), Err(ToolError::Failed(_))));
for at in [json!([1]), json!([10, "x", 30]), json!("10, 30")] {
assert!(matches!(a.call("content_copy", &json!({ "doc": doc, "page": 1, "index": 1, "at": at })), Err(ToolError::InvalidArgs(_))), "{at}");
}
// A second copy onto its own page steps past the first.
let r = ok(&mut a, "content_copy", json!({ "doc": doc, "page": 1, "index": 1 }));
let twice: Vec<f64> = from["rect"].as_array().unwrap().iter().map(|v| v.as_f64().unwrap() + 36.0).collect();
assert_eq!(r["rect"], json!(twice));
// A document that doesn't allow copying keeps its content in, even with changes allowed.
let mut cos = pdfcraft_cos::Document::open(std::sync::Arc::new(fixture(1))).unwrap();
cos.set_encryption(&pdfcraft_cos::NewEncryption {
algorithm: pdfcraft_cos::Algorithm::Aes256,
user_password: "",
owner_password: "owner",
permissions: -1 ^ 0b1_0000,
encrypt_metadata: true,
seed: [3; 32],
})
.unwrap();
std::fs::write(dir.join("no-copy.pdf"), pdfcraft_cos::write_full(&cos, &Default::default()).unwrap()).unwrap();
let locked = ok(&mut a, "doc_open", json!({ "path": "no-copy.pdf" }))["doc"].as_u64().unwrap();
ok(&mut a, "page_add_text", json!({ "doc": locked, "page": 1, "text": "Secret", "at": [20, 20], "width": 100 }));
for to in [locked, other] {
let refused = a.call("content_copy", &json!({ "doc": locked, "page": 1, "index": 1, "to_doc": to }));
assert!(matches!(&refused, Err(ToolError::Failed(m)) if m.contains("copying")), "{refused:?}");
}
assert_eq!(ok(&mut a, "content_list", json!({ "doc": locked }))["count"], 1);
}
/// An out-of-range `index` (including `i64::MIN`, which overflowed `index - 1`) is a readable
/// failure for `content_update` and `content_delete`, not a panic.
#[test]
@@ -4289,6 +4509,24 @@ fn content_index_out_of_range_is_an_error_not_a_panic() {
assert_eq!(ok(&mut a, "content_list", json!({ "doc": doc }))["count"], 1);
}
/// Character spacing on added text (#4245): set when adding or restyling, listed back, and refused
/// out of range or on images.
#[test]
fn added_text_takes_character_spacing() {
let dir = workdir("content-char-spacing");
let mut a = auto(&dir);
let doc = ok(&mut a, "doc_open", json!({ "path": "a.pdf" }))["doc"].as_u64().unwrap();
ok(&mut a, "page_add_text", json!({ "doc": doc, "page": 1, "text": "Spaced", "at": [20, 20], "char_spacing": 2 }));
assert_eq!(ok(&mut a, "content_list", json!({ "doc": doc }))["items"][0]["char_spacing"], 2.0);
ok(&mut a, "content_update", json!({ "doc": doc, "page": 1, "index": 1, "char_spacing": -0.5 }));
assert_eq!(ok(&mut a, "content_list", json!({ "doc": doc }))["items"][0]["char_spacing"], -0.5);
for bad in [json!(1000), json!(-1000), json!("wide")] {
let args = json!({ "doc": doc, "page": 1, "index": 1, "char_spacing": bad });
assert!(matches!(a.call("content_update", &args), Err(ToolError::InvalidArgs(_))), "{bad}");
}
assert_eq!(ok(&mut a, "content_list", json!({ "doc": doc }))["items"][0]["char_spacing"], -0.5);
}
fn added_rotation_image(dir: &Path) {
let mut png = Vec::new();
let mut enc = png::Encoder::new(&mut png, 2, 1);
@@ -5718,6 +5956,28 @@ fn optimizing_through_tools() {
assert!(reduced["bytes_after"].as_u64().unwrap() < reduced["bytes_before"].as_u64().unwrap());
assert_eq!(reduced["written"], true);
assert_eq!(std::fs::metadata(dir.join("reduced.pdf")).unwrap().len(), reduced["bytes_after"].as_u64().unwrap());
// Target PDF 1.4 (disables object streams) and PDF 2.0 (with object_streams toggled off).
let v14 = ok(&mut a, "doc_optimize", json!({ "doc": doc, "path": "v14.pdf", "compatibility": "1.4" }));
assert_eq!((v14["pdf_version"].as_str(), v14["object_streams"].as_bool()), (Some("1.4"), Some(false)), "{v14}");
let v14_bytes = std::fs::read(dir.join("v14.pdf")).unwrap();
assert!(v14_bytes.starts_with(b"%PDF-1.4\n") && !v14_bytes.windows(7).any(|w| w == b"/ObjStm"));
let v20 = ok(&mut a, "doc_optimize", json!({ "doc": doc, "path": "v20.pdf", "compatibility": "2.0", "object_streams": false }));
assert_eq!((v20["pdf_version"].as_str(), v20["object_streams"].as_bool()), (Some("2.0"), Some(false)), "{v20}");
assert!(std::fs::read(dir.join("v20.pdf")).unwrap().starts_with(b"%PDF-2.0\n"));
// In retain mode, a catalog /Version override is reported as the effective PDF version.
let mut cos14 = pdfcraft_cos::Document::open(std::sync::Arc::new(v14_bytes)).unwrap();
let root = cos14.root().unwrap();
cos14.update_dict(root, |c| c.set(b"Version".to_vec(), pdfcraft_cos::Object::name("1.6"))).unwrap();
let cat16 = pdfcraft_cos::write_full(&cos14, &pdfcraft_cos::SaveOptions { object_streams: false, ..Default::default() }).unwrap();
std::fs::write(dir.join("cat16.pdf"), &cat16).unwrap();
let cat_doc = ok(&mut a, "doc_open", json!({ "path": "cat16.pdf" }))["doc"].as_u64().unwrap();
let retained = ok(&mut a, "doc_optimize", json!({ "doc": cat_doc, "path": "retained.pdf", "compatibility": "retain", "object_streams": false }));
assert_eq!(retained["pdf_version"].as_str(), Some("1.6"), "{retained}");
assert!(matches!(a.call("doc_optimize", &json!({ "doc": doc, "path": "x.pdf", "compatibility": "1.3" })), Err(ToolError::InvalidArgs(_))));
assert!(matches!(
a.call("doc_optimize", &json!({ "doc": doc, "path": "x.pdf", "color": { "compression": "gif" } })),
Err(ToolError::InvalidArgs(_))
@@ -5725,6 +5985,76 @@ fn optimizing_through_tools() {
assert!(matches!(a.call("doc_optimize", &json!({ "doc": doc, "path": "x.pdf", "discard": ["everything"] })), Err(ToolError::InvalidArgs(_))));
}
/// #3227 review: retaining the version, a catalog `/Version` below the 1.5 an object stream
/// needs is not what viewers read: the header is raised, and the later of the two is reported.
#[test]
fn retained_pdf_version_reports_the_header_raised_for_object_streams() {
let dir = workdir("optimize-retain-version");
let mut a = auto(&dir);
let blank = ok(&mut a, "doc_create", json!({ "from": "blank", "width": 300, "height": 400 }))["doc"].as_u64().unwrap();
ok(&mut a, "doc_optimize", json!({ "doc": blank, "path": "v14.pdf", "compatibility": "1.4" }));
let mut cos = pdfcraft_cos::Document::open(std::sync::Arc::new(std::fs::read(dir.join("v14.pdf")).unwrap())).unwrap();
let root = cos.root().unwrap();
cos.update_dict(root, |c| c.set(b"Version".to_vec(), pdfcraft_cos::Object::name("1.4"))).unwrap();
let bytes = pdfcraft_cos::write_full(&cos, &pdfcraft_cos::SaveOptions { object_streams: false, ..Default::default() }).unwrap();
std::fs::write(dir.join("cat14.pdf"), &bytes).unwrap();
let doc = ok(&mut a, "doc_open", json!({ "path": "cat14.pdf" }))["doc"].as_u64().unwrap();
let r = ok(&mut a, "doc_optimize", json!({ "doc": doc, "path": "out.pdf", "compatibility": "retain", "object_streams": true }));
let out = std::fs::read(dir.join("out.pdf")).unwrap();
assert!(out.starts_with(b"%PDF-1.5\n") && out.windows(7).any(|w| w == b"/ObjStm"), "{r}");
assert_eq!(r["pdf_version"].as_str(), Some("1.5"), "{r}");
}
/// `data` as LZW with one 9-bit literal code per byte (clear-table first, EOD last): valid for
/// fewer than 250 bytes, before the code width grows.
fn lzw_literals(data: &[u8]) -> Vec<u8> {
let codes: Vec<u16> = std::iter::once(256).chain(data.iter().map(|&b| u16::from(b))).chain([257]).collect();
let bits: Vec<bool> = codes.iter().flat_map(|c| (0..9).rev().map(move |i| c >> i & 1 == 1)).collect();
bits.chunks(8).map(|byte| byte.iter().enumerate().fold(0u8, |acc, (i, &b)| acc | (u8::from(b) << (7 - i)))).collect()
}
#[test]
fn lzw_streams_are_stored_with_flate_through_tools() {
use pdfcraft_cos::{Dict, Document, Object, SaveOptions, Stream, write_full};
let dir = workdir("optimize-lzw");
let ops = b"0.2 0.4 0.8 rg 72 72 200 100 re f 0 0 1 RG 72 300 m 400 500 l S".to_vec();
let mut doc = Document::new_empty();
let pages = doc.get(doc.root().unwrap()).as_dict().unwrap().reference(b"Pages").unwrap();
let lzw = Stream::from_raw(Dict::from_iter([(b"Filter".to_vec(), Object::name("LZWDecode"))]), lzw_literals(&ops));
assert_eq!(lzw.decoded_strict().unwrap(), ops);
let content = doc.add(Object::Stream(lzw));
let page = doc.add(Object::Dict(Dict::from_iter([
(b"Type".to_vec(), Object::name("Page")),
(b"Parent".to_vec(), Object::Ref(pages)),
(b"MediaBox".to_vec(), Object::Array(vec![0.into(), 0.into(), 612.into(), 792.into()])),
(b"Contents".to_vec(), Object::Ref(content)),
])));
doc.update_dict(pages, |d| {
d.set(b"Kids".to_vec(), Object::Array(vec![Object::Ref(page)]));
d.set(b"Count".to_vec(), Object::Int(1));
})
.unwrap();
std::fs::write(dir.join("lzw.pdf"), write_full(&doc, &SaveOptions::default()).unwrap()).unwrap();
let mut a = auto(&dir);
let doc = ok(&mut a, "doc_open", json!({ "path": "lzw.pdf" }))["doc"].as_u64().unwrap();
let filters = |name: &str| {
let saved = pdfcraft_cos::Document::open(std::sync::Arc::new(std::fs::read(dir.join(name)).unwrap())).unwrap();
let catalog = saved.get(saved.root().unwrap()).as_dict().cloned().unwrap();
let pages = saved.get(catalog.reference(b"Pages").unwrap()).as_dict().cloned().unwrap();
let page = saved.get(pages.get(b"Kids").and_then(|k| k.as_array()?.first()?.as_ref()).unwrap()).as_dict().cloned().unwrap();
match &*saved.get(page.reference(b"Contents").unwrap()) {
Object::Stream(s) => (s.dict.get(b"Filter").cloned(), s.decoded_strict().unwrap()),
_ => panic!("the page content is not a stream"),
}
};
let r = ok(&mut a, "doc_optimize", json!({ "doc": doc, "path": "flate.pdf" }));
assert_eq!(r["lzw_streams"].as_u64(), Some(1), "{r}");
assert_eq!(filters("flate.pdf"), (Some(Object::name("FlateDecode")), ops.clone()));
let off = ok(&mut a, "doc_optimize", json!({ "doc": doc, "path": "kept.pdf", "lzw_to_flate": false }));
assert_eq!(off["lzw_streams"].as_u64(), Some(0), "{off}");
assert_eq!(filters("kept.pdf"), (Some(Object::name("LZWDecode")), ops));
}
/// A one-page PDF whose page picture is drawn as `rows` grey images one pixel row high, 600 px
/// wide on a 72 pt square (600 ppi), as some PDF printers write it.
fn printed_in_strips(rows: usize) -> Vec<u8> {
@@ -5947,6 +6277,60 @@ fn ocr_recognize_files_writes_searchable_copies() {
assert!(found.to_string().contains("\"page\""), "{found}");
}
/// Two inputs that share a file name (from different folders) would both write `out/scan.pdf`:
/// the second output replaces the first while both results report success. The batch is refused
/// up front, naming the file, before the folder is created, anything is read or the OCR engines
/// load, so the outcome is the same with or without the models installed.
#[test]
fn ocr_recognize_files_refuses_inputs_that_share_a_file_name() {
let dir = workdir("ocr-files-same-name");
let mut a = auto(&dir);
let doc = ok(&mut a, "doc_open", json!({ "path": "a.pdf" }))["doc"].as_u64().unwrap();
ok(&mut a, "doc_save", json!({ "doc": doc, "path": "one/scan.pdf" }));
ok(&mut a, "doc_save", json!({ "doc": doc, "path": "two/scan.pdf" }));
let r = a.call("ocr_recognize_files", &json!({ "paths": ["one/scan.pdf", "two/scan.pdf"], "folder": "out" }));
assert!(matches!(&r, Err(ToolError::InvalidArgs(m)) if m.contains("scan.pdf")), "{r:?}");
assert!(!dir.join("out").exists(), "nothing was started: the output folder was not created");
}
/// File names are compared without regard to case on Windows and macOS (`scan.pdf` and `Scan.PDF`
/// are one file there), and exactly elsewhere, where they are two files and the batch is not
/// refused.
#[test]
fn ocr_recognize_files_compares_names_the_way_the_filesystem_does() {
let dir = workdir("ocr-files-case");
let mut a = auto(&dir);
let doc = ok(&mut a, "doc_open", json!({ "path": "a.pdf" }))["doc"].as_u64().unwrap();
ok(&mut a, "doc_save", json!({ "doc": doc, "path": "one/scan.pdf" }));
ok(&mut a, "doc_save", json!({ "doc": doc, "path": "two/Scan.PDF" }));
let r = a.call("ocr_recognize_files", &json!({ "paths": ["one/scan.pdf", "two/Scan.PDF"], "folder": "out" }));
if cfg!(any(windows, target_os = "macos")) {
assert!(matches!(&r, Err(ToolError::InvalidArgs(m)) if m.contains("Scan.PDF")), "{r:?}");
assert!(!dir.join("out").exists(), "nothing was started: the output folder was not created");
} else {
assert!(!matches!(&r, Err(ToolError::InvalidArgs(_))), "{r:?}");
}
}
/// Inputs with distinct names are not refused, and the batch writes one searchable copy per input
/// under its own name. Without the models it stops at the models error, as it did before.
#[test]
fn ocr_recognize_files_with_distinct_names_runs_as_before() {
let dir = workdir("ocr-files-distinct");
let mut a = auto(&dir);
let doc = ok(&mut a, "doc_open", json!({ "path": "a.pdf" }))["doc"].as_u64().unwrap();
ok(&mut a, "doc_save", json!({ "doc": doc, "path": "one/scan.pdf" }));
ok(&mut a, "doc_save", json!({ "doc": doc, "path": "two/other.pdf" }));
if ok(&mut a, "ocr_status", json!({}))["available"] == true {
let r = ok(&mut a, "ocr_recognize_files", json!({ "paths": ["one/scan.pdf", "two/other.pdf"], "folder": "out" }));
assert!(r["files"][0]["error"].is_null() && r["files"][1]["error"].is_null(), "{r}");
assert!(dir.join("out/scan.pdf").is_file() && dir.join("out/other.pdf").is_file(), "{r}");
} else {
let r = a.call("ocr_recognize_files", &json!({ "paths": ["one/scan.pdf", "two/other.pdf"], "folder": "out" }));
assert!(matches!(&r, Err(ToolError::Failed(m)) if m.contains("not installed")), "{r:?}");
}
}
#[test]
fn javascript_through_tools() {
let dir = workdir("js");
@@ -5990,6 +6374,12 @@ fn javascript_through_tools() {
assert_eq!(total["value"], "3750");
let r = ok(&mut a, "js_run", json!({ "doc": doc, "script": "nope()" }));
assert!(r["error"].as_str().unwrap().contains("nope"));
assert_eq!(r["document_errors"], json!([]));
// A document script that throws (#3940) is reported, and the others and the script still run.
ok(&mut a, "js_set_document_script", json!({ "doc": doc, "name": "zz", "script": "getField('Total').buttonSetIcon(null);" }));
let r = ok(&mut a, "js_run", json!({ "doc": doc, "script": "money(5)" }));
assert_eq!((r["error"].clone(), r["result"].clone()), (json!(null), json!("EUR 5,00")));
assert!(r["document_errors"][0].as_str().unwrap().starts_with("document script 2: TypeError"), "{r}");
assert_eq!(ok(&mut a, "js_enabled", json!({ "enabled": false }))["enabled"], false);
assert!(a.call("js_run", &json!({ "doc": doc, "script": "1" })).is_err());
}
@@ -6500,6 +6890,33 @@ fn xfa_rich_text_max_length_is_reported_and_enforced_through_tools() {
assert_eq!(family["value"], "éàöüñ");
}
/// A link in a dynamic XFA form's rich text is a link on the laid-out page, as link_list reports
/// it, and stays one after a save and a fresh open.
#[test]
fn links_in_xfa_rich_text_are_listed_through_tools() {
let dir = workdir("xfa-links");
let xdp = r##"<?xml version="1.0" encoding="UTF-8"?>
<xdp:xdp xmlns:xdp="http://ns.adobe.com/xdp/"><template xmlns="http://www.xfa.org/schema/xfa-template/3.3/"><subform name="form" layout="tb">
<pageSet><pageArea name="page"><contentArea x="0.5in" y="0.5in" w="7.5in" h="10in"/><medium short="8.5in" long="11in"/></pageArea></pageSet>
<draw name="help" w="6in"><font typeface="Arial" size="10pt"/><value><exData contentType="text/html"><body xmlns="http://www.w3.org/1999/xhtml"><p>Questions? Email <a href="mailto:forms@example.com">forms@example.com</a>.</p></body></exData></value></draw>
<field name="name" w="3in" h="0.3in"><ui><textEdit/></ui></field>
</subform></template></xdp:xdp>"##;
std::fs::write(dir.join("links.pdf"), pdfcraft_xfa::fixtures::shell(xdp)).unwrap();
let mut a = auto(&dir);
let doc = ok(&mut a, "doc_open", json!({ "path": "links.pdf" }))["doc"].as_u64().unwrap();
let urls = |a: &mut Automation, doc: u64| -> Vec<String> {
let listed = ok(a, "link_list", json!({ "doc": doc }));
let links = listed["links"].as_array().cloned().unwrap_or_default();
links.iter().filter_map(|l| l["url"].as_str().map(str::to_string)).collect()
};
assert_eq!(urls(&mut a, doc), ["mailto:forms@example.com"]);
ok(&mut a, "form_fill", json!({ "doc": doc, "values": { "name": "Ada" } }));
ok(&mut a, "doc_save", json!({ "doc": doc, "path": "saved.pdf" }));
ok(&mut a, "doc_close", json!({ "doc": doc }));
let doc = ok(&mut a, "doc_open", json!({ "path": "saved.pdf" }))["doc"].as_u64().unwrap();
assert_eq!(urls(&mut a, doc), ["mailto:forms@example.com"], "one link after a save and a fresh open, not two");
}
#[test]
fn dynamic_xfa_forms_open_render_fill_and_save_through_tools() {
let dir = workdir("xfa");
@@ -6833,6 +7250,35 @@ fn xfa_scripts_run_for_buttons_and_field_changes_through_tools() {
assert_eq!(r["alerts"], json!(["Hello 4"]));
}
#[test]
fn active_xfa_skips_container_fallback_scripts_after_save_and_reopen() {
let dir = workdir("xfa-container-scripts");
std::fs::write(dir.join("form.pdf"), pdfcraft_xfa::fixtures::shell(&pdfcraft_xfa::fixtures::scripted_template())).unwrap();
let mut a = auto(&dir);
let doc = ok(&mut a, "doc_open", json!({"path": "form.pdf"}))["doc"].as_u64().unwrap();
let fallback = "app.alert('This PDF form requires a newer version of Adobe Acrobat');";
ok(&mut a, "js_set_document_script", json!({"doc":doc,"name":"viewerFallback","script":fallback}));
let out = ok(&mut a, "js_run", json!({"doc":doc,"script":"app.alert('Console message');"}));
assert!(out["error"].is_null(), "{out}");
assert_eq!(out["alerts"], json!(["Console message"]));
ok(&mut a, "doc_save", json!({"doc":doc,"path":"saved.pdf"}));
ok(&mut a, "doc_close", json!({"doc":doc}));
let doc = ok(&mut a, "doc_open", json!({"path":"saved.pdf"}))["doc"].as_u64().unwrap();
assert_eq!(ok(&mut a, "js_document_scripts", json!({"doc":doc}))["scripts"], json!([{"name":"viewerFallback","script":fallback}]));
let out = ok(&mut a, "js_run", json!({"doc":doc,"script":""}));
assert!(out["error"].is_null(), "{out}");
assert_eq!(out["alerts"], json!([]));
let out = ok(&mut a, "js_run", json!({"doc":doc,"script":"","field":"hello"}));
assert!(out["error"].is_null(), "{out}");
assert_eq!(out["alerts"], json!(["Hello 2"]));
ok(&mut a, "xfa_to_static", json!({"doc":doc}));
let out = ok(&mut a, "js_run", json!({"doc":doc,"script":""}));
assert_eq!(out["alerts"].as_array().unwrap().len(), 1);
ok(&mut a, "edit_undo", json!({"doc":doc}));
assert_eq!(ok(&mut a, "js_run", json!({"doc":doc,"script":""}))["alerts"], json!([]));
let _ = std::fs::remove_dir_all(dir);
}
#[test]
fn doc_info_says_when_a_runaway_script_turned_the_forms_scripts_off() {
let dir = workdir("xfa-scripts-off");
@@ -7988,6 +8434,46 @@ fn a_root_less_write_output_is_atomic_too() {
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn attaching_and_deleting_files_through_the_tools() {
let dir = workdir("attach");
std::fs::write(dir.join("notes.txt"), b"keep this with the PDF").unwrap();
let mut a = auto(&dir);
let doc = ok(&mut a, "doc_open", json!({ "path": "a.pdf" }))["doc"].as_u64().unwrap();
assert!(ok(&mut a, "doc_info", json!({ "doc": doc }))["attachments"].as_array().unwrap().is_empty());
// A text file and a PDF, the PDF under a name of its own; the second notes.txt is kept apart.
let r = ok(&mut a, "attachment_add", json!({ "doc": doc, "path": "notes.txt", "description": "Meeting notes" }));
assert_eq!(r["name"], "notes.txt");
let r = ok(&mut a, "attachment_add", json!({ "doc": doc, "path": "b.pdf", "name": "annex.pdf" }));
assert_eq!(r["name"], "annex.pdf");
let r = ok(&mut a, "attachment_add", json!({ "doc": doc, "path": "notes.txt" }));
assert_eq!(r["name"], "notes.txt (2)");
let listed = ok(&mut a, "doc_info", json!({ "doc": doc }))["attachments"].clone();
let names: Vec<&str> = listed.as_array().unwrap().iter().map(|x| x["name"].as_str().unwrap()).collect();
assert_eq!(names, ["annex.pdf", "notes.txt", "notes.txt (2)"]);
assert_eq!(listed[1]["description"], "Meeting notes");
assert_eq!(listed[1]["size"], 22);
// Saved and reopened, the attachment is there with its bytes.
ok(&mut a, "doc_save", json!({ "doc": doc, "path": "with-notes.pdf" }));
let saved = std::fs::read(dir.join("with-notes.pdf")).unwrap();
let info = pdfcraft_render::inspect(std::sync::Arc::new(saved.clone()), None).unwrap();
let att = info.attachments.iter().find(|x| x.name == "notes.txt").expect("notes.txt is in the file");
assert_eq!(pdfcraft_render::attachment_data(&saved, None, att).unwrap(), b"keep this with the PDF");
// Deleting one leaves the others; a name that is not there is refused; undo brings it back.
ok(&mut a, "attachment_delete", json!({ "doc": doc, "name": "notes.txt" }));
let names: Vec<String> = ok(&mut a, "doc_info", json!({ "doc": doc }))["attachments"]
.as_array()
.unwrap()
.iter()
.map(|x| x["name"].as_str().unwrap().to_string())
.collect();
assert_eq!(names, ["annex.pdf", "notes.txt (2)"]);
assert!(a.call("attachment_delete", &json!({ "doc": doc, "name": "notes.txt" })).is_err());
ok(&mut a, "edit_undo", json!({ "doc": doc }));
assert_eq!(ok(&mut a, "doc_info", json!({ "doc": doc }))["attachments"].as_array().unwrap().len(), 3);
assert!(a.call("attachment_add", &json!({ "doc": doc, "path": "missing.txt" })).is_err(), "a file that is not there is refused");
}
#[test]
fn fdf_nested_comment_values_survive_export_import_and_save_through_tools() {
use pdfcraft_cos::{Dict, Document, Object, PdfString, SaveOptions, write_full};
@@ -8424,3 +8910,81 @@ fn bookmark_list_reports_colour_and_style() {
let re = ok(&mut b, "doc_open", json!({ "path": "restyled.pdf" }))["doc"].as_u64().unwrap();
assert_eq!(style(&ok(&mut b, "bookmark_list", json!({ "doc": re }))["bookmarks"]), style(&set), "saved");
}
/// An editable combo box (ISO 32000-2 Table 233, Edit) takes a value that isn't one of its
/// options, and its page appearance shows it, before and after a save; one without Edit takes
/// only its options.
#[test]
fn form_fill_takes_free_text_only_in_an_editable_combo_box() {
let dir = workdir("editable-combo");
let mut a = auto(&dir);
let doc = ok(&mut a, "doc_open", json!({ "path": "a.pdf" }))["doc"].as_u64().unwrap();
let combo = |name: &str, top: f64, editable: bool| json!({ "doc": doc, "page": 1, "type": "combo", "rect": [20, top, 200, top + 22.0], "name": name, "options": ["Apple", "Banana"], "editable": editable });
ok(&mut a, "form_add_field", combo("fruit", 20.0, true));
ok(&mut a, "form_add_field", combo("veg", 60.0, false));
ok(&mut a, "form_fill", json!({ "doc": doc, "values": { "fruit": "Cherry" } }));
assert!(page_text(&mut a, doc)[0].contains("Cherry"), "the typed value is drawn");
let refused = err(&mut a, "form_fill", json!({ "doc": doc, "values": { "veg": "Cherry" } }));
assert!(matches!(&refused, ToolError::Failed(m) | ToolError::InvalidArgs(m) if m.contains("no option")), "{refused:?}");
// A choice from the list still works in both.
ok(&mut a, "form_fill", json!({ "doc": doc, "values": { "veg": "Banana" } }));
ok(&mut a, "doc_save", json!({ "doc": doc, "path": "filled.pdf" }));
let saved = ok(&mut a, "doc_open", json!({ "path": "filled.pdf" }))["doc"].as_u64().unwrap();
let fields = ok(&mut a, "form_fields", json!({ "doc": saved }));
let value = |name: &str| fields["fields"].as_array().unwrap().iter().find(|f| f["name"] == name).map(|f| f["value"].clone());
assert_eq!(value("fruit"), Some(json!("Cherry")), "{fields}");
assert_eq!(value("veg"), Some(json!("Banana")), "{fields}");
let text = page_text(&mut a, saved);
assert!(text[0].contains("Cherry") && text[0].contains("Banana"), "{text:?}");
let _ = std::fs::remove_dir_all(&dir);
}
/// `page_render`'s pixels show a rubber stamp written without an appearance as the stamp its
/// `/Name` names (ISO 32000-2 Table 184), and one with an unknown name as a grey placeholder.
#[test]
fn page_render_draws_stamps_without_an_appearance() {
let dir = workdir("stamps-without-appearance");
let objects: Vec<&[u8]> = vec![
b"<< /Type /Catalog /Pages 2 0 R >>",
b"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 300 100] >>",
b"<< /Type /Page /Parent 2 0 R /Annots [4 0 R 5 0 R] >>",
b"<< /Type /Annot /Subtype /Stamp /Rect [10 20 130 80] /Name /Approved >>",
b"<< /Type /Annot /Subtype /Stamp /Rect [170 20 290 80] /Name /MyCustomStamp >>",
];
let mut bytes = b"%PDF-1.7\n".to_vec();
let mut offsets = Vec::new();
for (i, object) in objects.iter().enumerate() {
offsets.push(bytes.len());
bytes.extend_from_slice(format!("{} 0 obj\n", i + 1).as_bytes());
bytes.extend_from_slice(object);
bytes.extend_from_slice(b"\nendobj\n");
}
let xref = bytes.len();
bytes.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objects.len() + 1).as_bytes());
for o in offsets {
bytes.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes());
}
bytes.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objects.len() + 1).as_bytes());
std::fs::write(dir.join("stamps.pdf"), bytes).unwrap();
let mut a = auto(&dir);
let doc = ok(&mut a, "doc_open", json!({ "path": "stamps.pdf" }))["doc"].as_u64().unwrap();
let (width, _, pixels) = a.render_pixels(doc, 1, 1.0).unwrap();
let pixels = pixels.as_ref();
// Ink in columns `x0..x1` of rows 20..80, which are the stamps' rows whether counted from the top or the bottom.
let ink = |x0: u32, x1: u32| -> Vec<[u8; 3]> {
(20..80u32)
.flat_map(|y| (x0..x1).map(move |x| (y, x)))
.map(|(y, x)| {
let i = ((y * width + x) * 4) as usize;
[pixels[i], pixels[i + 1], pixels[i + 2]]
})
.filter(|p| p.iter().any(|v| *v < 200))
.collect()
};
let approved = ink(10, 130);
let green = approved.iter().filter(|p| p[1] > p[0] && p[1] > p[2]).count();
assert!(green > 300 && green * 10 > approved.len() * 9, "Approved is drawn green: {green} of {}", approved.len());
let custom = ink(170, 290);
let grey = custom.iter().filter(|p| p[0].abs_diff(p[1]) < 24 && p[1].abs_diff(p[2]) < 24).count();
assert!(grey > 100 && grey == custom.len(), "an unknown name is a grey placeholder: {grey} of {}", custom.len());
}
@@ -352,6 +352,19 @@ fn links_out_of_a_root_are_refused() {
assert_eq!(names(&base.join("outside")), ["pic.png", "secret.pdf"]);
}
/// #4003: without `--root`, another network share or a device is refused by name through the
/// tools too, with the same words as any other path outside a root.
#[cfg(windows)]
#[test]
fn other_shares_and_devices_are_refused_by_name() {
let (mut server, base) = confined("shares", true, true);
ok(&mut server, "doc_open", json!({"path": s(&base.join("in/a.pdf"))}));
for p in [r"\\.\pipe\pdfcraft-4003.pdf", r"\\pdfcraft-no-such-host.invalid\share\a.pdf", "//pdfcraft-no-such-host.invalid/share/a.pdf"] {
refused(&mut server, "doc_open", json!({"path": p}), "outside the read root");
refused(&mut server, "doc_save", json!({"doc": 1, "path": p}), "outside the write root");
}
}
#[test]
fn without_roots_nothing_is_confined() {
let base = folders("none");
+1
View File
@@ -1,5 +1,6 @@
//! The crate's integration tests, linked into one test binary.
mod attachment_key;
mod automation;
mod automation_roots;
mod batch;
+5
View File
@@ -897,6 +897,11 @@ impl Document {
&self.version
}
/// Set the PDF header version (`"1.4"`, `"1.7"`, `"2.0"`, …) written by a full save.
pub fn set_version(&mut self, version: impl Into<String>) {
self.version = version.into();
}
pub fn trailer(&self) -> &Dict {
&self.trailer
}
+3 -1
View File
@@ -27,5 +27,7 @@ Every function returns a `pdfcraft_cos::Document`; the caller writes it.
Image export and Save Image As apply each lossless image's Decode pair before converting its color components.
Indexed Decode values select palette entries after rounding and clipping. Color-key masks compare the original samples.
Missing, null or malformed Decode arrays keep the default mapping.
The existing 16-bit path still uses each sample's high byte. JPEG and mask Decode handling remain limited.
Soft-mask Decode intervals map samples to opacity before the mask is resized, including reversed ranges and indirect entries.
The existing 16-bit path still uses each sample's high byte.
JPEG image Decode handling remains limited.
ICC transforms and calibrated color conversion remain outside this export path.
+6 -9
View File
@@ -465,7 +465,7 @@ fn stencil_mask(doc: &Document, s: &Stream, w: usize, h: usize) -> Option<Vec<u8
Some(gray_plane(doc, m, w, h)?.into_iter().map(|v| 255 - v).collect())
}
/// A one-component mask image as 8-bit values (its `/Decode` inversion applied), scaled to
/// A one-component mask image as 8-bit values (its `/Decode` interval applied), scaled to
/// `w` × `h`. `None` when it can't be decoded (JPEG 2000, JBIG2 and CCITT masks).
fn gray_plane(doc: &Document, m: &Stream, w: usize, h: usize) -> Option<Vec<u8>> {
let (mw, mh) = size(m.dict.int(b"Width")?, m.dict.int(b"Height")?)?;
@@ -491,14 +491,11 @@ fn gray_plane(doc: &Document, m: &Stream, w: usize, h: usize) -> Option<Vec<u8>>
unpack(&m.decoded().ok()?, mw, mh, 1, bpc)?.into_iter().map(|v| (v as u32 * 255 / max) as u8).collect()
}
};
let invert = m
.dict
.get(b"Decode")
.map(|d| doc.resolve(d))
.and_then(|d| d.as_array().map(|a| a.first().and_then(Object::as_f64) > a.get(1).and_then(Object::as_f64)))
.unwrap_or(false);
if invert {
px.iter_mut().for_each(|v| *v = 255 - *v);
if let Some([lo, hi]) = decode(doc, m, 1).and_then(|pairs| pairs.first().copied()) {
for value in &mut px {
let t = f64::from(*value) / 255.0;
*value = (((1.0 - t) * lo + t * hi).clamp(0.0, 1.0) * 255.0).round() as u8;
}
}
if (mw, mh) == (w, h) {
return Some(px);
+1 -1
View File
@@ -269,7 +269,7 @@ fn jpeg(name: &str, bytes: &[u8]) -> Result<Embedded, CreateError> {
0xEE if seg.starts_with(b"Adobe") => adobe = true,
// APP2 ICC profile, possibly split over several chunks.
0xE2 => {
if let Some(([seq, count], data)) = seg.strip_prefix(b"ICC_PROFILE\0").and_then(|r| r.split_first_chunk::<2>()) {
if let Some(([seq, count], data)) = seg.strip_prefix(b"ICC_PROFILE\0").and_then(<[u8]>::split_first_chunk::<2>) {
icc_chunks.push((*seq, *count, data));
}
}
+68
View File
@@ -682,6 +682,74 @@ fn jpeg_images_with_a_soft_mask_export_as_png_with_alpha() {
assert_eq!((out.images[0].extension, &out.images[0].data), ("jpg", &real_jpeg()));
}
#[test]
/// Both image export paths apply mask intervals independently of the image's component Decode.
fn soft_mask_decode_ranges_become_exported_alpha() {
for indirect in [false, true] {
for (range, expected) in [
([0.25, 0.75], [64, 128, 191]),
([0.75, 0.25], [191, 127, 64]),
([1.0, 0.0], [255, 127, 0]),
([-1.0, 2.0], [0, 129, 255]),
([0.5, 0.5], [128, 128, 128]),
] {
let mut doc = from_images(&[("flat.png".into(), png_bytes(false))]).unwrap();
with_image(&mut doc, |doc| {
let endpoints = range.into_iter().map(|v| {
let value = Object::Real(v);
if indirect { Object::Ref(doc.add(value)) } else { value }
});
let decode = Object::Array(endpoints.collect());
let decode = if indirect { Object::Ref(doc.add(decode)) } else { decode };
let mut mask = image_dict(3, 1, "DeviceGray", 8);
mask.set(b"Decode".to_vec(), decode);
let mask = doc.add(Object::Stream(Stream::from_raw(mask, vec![0, 128, 255])));
let mut image = image_dict(3, 1, "DeviceRGB", 8);
image.set(b"SMask".to_vec(), Object::Ref(mask));
image.set(b"Decode".to_vec(), decode_array(&[1.0, 0.0, 0.0, 1.0, 0.0, 1.0]));
Stream::from_raw(image, [0, 64, 255].repeat(3))
});
let doc = reopen(&doc);
let out = extract_images(&doc, &[0], 0);
assert!(out.skipped.is_empty(), "{:?}", out.skipped);
assert_eq!(out.images.len(), 1);
let pixels = exported_png_pixels(&out.images[0].data);
assert_eq!(alphas(&pixels), expected, "Decode {range:?}, indirect={indirect}");
assert!(pixels.as_chunks::<4>().0.iter().all(|p| p[..3] == [255, 64, 255]), "image component Decode stays independent");
let (ext, bytes) = image_file(&doc, out.images[0].object).unwrap();
assert_eq!(ext, "png");
assert_eq!(exported_png_pixels(&bytes), pixels, "Save Image As and Export all images agree");
}
}
}
#[test]
/// Packed and JPEG samples map to opacity before resizing to their image's dimensions.
fn soft_mask_decode_maps_packed_and_jpeg_masks_before_resizing() {
for jpeg in [false, true] {
let mut doc = from_images(&[("flat.png".into(), png_bytes(false))]).unwrap();
with_image(&mut doc, |doc| {
let mask = if jpeg {
let mut mask = image_dict(4, 2, "DeviceGray", 8);
mask.set(b"Filter".to_vec(), Object::name("DCTDecode"));
mask.set(b"Decode".to_vec(), decode_array(&[0.25, 0.25]));
Stream::from_raw(mask, real_jpeg())
} else {
let mut mask = image_dict(2, 1, "DeviceGray", 1);
mask.set(b"Decode".to_vec(), decode_array(&[-1.0, 2.0]));
Stream::from_raw(mask, vec![0b0100_0000])
};
let mask = doc.add(Object::Stream(mask));
let mut image = image_dict(4, 2, "DeviceRGB", 8);
image.set(b"SMask".to_vec(), Object::Ref(mask));
Stream::from_raw(image, vec![10; 24])
});
// Clipping before resizing differs from resizing first, then clipping to [0, 255].
let expected = if jpeg { vec![64; 8] } else { vec![0, 64, 191, 255, 0, 64, 191, 255] };
assert_eq!(alphas(&exported_rgba(&reopen(&doc)).1), expected, "jpeg={jpeg}");
}
}
#[test]
fn soft_masks_of_another_size_and_stencil_and_colour_key_masks_become_alpha() {
// A 2×1 soft mask on a 4×2 image is scaled to the image's size.
+96 -10
View File
@@ -20,6 +20,9 @@ use crate::{EditError, MarkKind, check, contents, matrix_number, n, page_list, p
const TAG: &str = "Added";
/// The most character spacing an added text takes either way, in points: as far as the font size goes.
pub const CHAR_SPACING_LIMIT: f64 = 500.0;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum Family {
#[default]
@@ -116,6 +119,8 @@ pub struct AddedText {
pub size: f64,
pub color: [f64; 3],
pub align: Align,
/// Extra space after every character, in points: the PDF's character spacing (`Tc`).
pub char_spacing: f64,
}
impl Default for AddedText {
@@ -129,6 +134,7 @@ impl Default for AddedText {
size: 12.0,
color: [0.0; 3],
align: Align::Left,
char_spacing: 0.0,
}
}
}
@@ -192,7 +198,9 @@ impl Content {
fn scaled(self, factor: f64) -> Content {
match self {
_ if factor == 1.0 => self,
Content::Text(t) => Content::Text(AddedText { rect: t.rect.map(|v| v * factor), size: t.size * factor, ..t }),
Content::Text(t) => {
Content::Text(AddedText { rect: t.rect.map(|v| v * factor), size: t.size * factor, char_spacing: t.char_spacing * factor, ..t })
}
Content::Image(i) => Content::Image(AddedImage { rect: i.rect.map(|v| v * factor), ..i }),
}
}
@@ -230,6 +238,12 @@ fn norm(r: [f64; 4]) -> [f64; 4] {
[r[0].min(r[2]), r[1].min(r[3]), r[0].max(r[2]), r[1].max(r[3])]
}
/// The advance of `s` in the item's standard font: its glyphs' widths and the character spacing
/// after each of them, as `Tc` moves the pen (ISO 32000-2 §9.3.2).
fn latin_width(t: &AddedText, s: &str) -> f64 {
t.family.width(s, t.size, t.bold, t.italic) + t.char_spacing * s.chars().count() as f64
}
/// The lines of a text item after wrapping to its box width.
pub fn lines(t: &AddedText) -> Vec<String> {
wrapped(t).into_iter().map(|(line, _)| line).collect()
@@ -264,7 +278,7 @@ fn wrapped(t: &AddedText) -> Vec<(String, bool)> {
// sum of its words' and shaping stays linear in the paragraph's length. The space is the
// paragraph's; a space between Latin words is drawn in the item's font, a few hundredths
// of an em apart.
let measure = |s: &str| if rtl_script || thai { shaped_width(t, s, rtl) } else { t.family.width(s, t.size, t.bold, t.italic) };
let measure = |s: &str| if rtl_script || thai { shaped_width(t, s, rtl) } else { latin_width(t, s) };
let space = measure(" ");
let (mut line, mut line_w) = (String::new(), 0.0);
for word in para.split(' ') {
@@ -292,10 +306,10 @@ fn thai_lines(t: &AddedText, para: &str, width: f64) -> Result<Vec<String>, Edit
let mut atoms = Vec::new();
for piece in pieces {
match piece {
Piece::Shaped(clusters) => atoms.extend(clusters.into_iter().map(|c| (c.text, c.advance * t.size))),
Piece::Shaped(clusters) => atoms.extend(clusters.into_iter().map(|c| (c.text, c.advance * t.size + t.char_spacing))),
Piece::Latin(s) => atoms.extend(s.chars().map(|c| {
let text = c.to_string();
let w = t.family.width(&text, t.size, t.bold, t.italic);
let w = latin_width(t, &text);
(text, w)
})),
}
@@ -459,8 +473,9 @@ fn shaped_layout(t: &AddedText, line: &str, rtl: bool) -> Result<(Vec<Piece>, f6
let width = pieces
.iter()
.map(|p| match p {
Piece::Latin(s) => t.family.width(s, t.size, t.bold, t.italic),
Piece::Shaped(clusters) => clusters.iter().map(|c| c.advance).sum::<f64>() * t.size,
Piece::Latin(s) => latin_width(t, s),
// Each cluster is shown on its own, so the spacing follows each once.
Piece::Shaped(clusters) => clusters.iter().map(|c| c.advance * t.size + t.char_spacing).sum::<f64>(),
})
.sum();
Ok((pieces, width))
@@ -469,7 +484,7 @@ fn shaped_layout(t: &AddedText, line: &str, rtl: bool) -> Result<(Vec<Piece>, f6
/// The width of `s` in a shaped-text item; the item's font's estimate if it can't be shaped (drawing
/// then reports why).
fn shaped_width(t: &AddedText, s: &str, rtl: bool) -> f64 {
shaped_layout(t, s, rtl).map(|(_, w)| w).unwrap_or_else(|_| t.family.width(s, t.size, t.bold, t.italic))
shaped_layout(t, s, rtl).map(|(_, w)| w).unwrap_or_else(|_| latin_width(t, s))
}
fn arabic_error(e: GlyphError, text: &str) -> EditError {
@@ -509,6 +524,61 @@ pub fn text_rect(t: &AddedText) -> [f64; 4] {
[r[0], r[3] - h, r[2], r[3]]
}
/// How far each paste onto a page already holding the copy is offset, down and to the right, so a
/// copy doesn't hide what it was copied from (points).
pub const PASTE_STEP: f64 = 18.0;
/// Where a pasted item of box `rect` goes on a page of `size` (display space): with its top-left
/// corner at `at`, else where it was, `steps` paste steps ([`PASTE_STEP`]) down and to the right.
/// It is kept on the page; one larger than the page keeps its left and top edges on it. A page
/// or point that isn't a number leaves the box where it was.
pub fn paste_rect(rect: [f64; 4], size: [f64; 2], steps: u32, at: Option<[f64; 2]>) -> [f64; 4] {
let [x0, y0, x1, y1] = norm(rect);
let (w, h) = (x1 - x0, y1 - y0);
let (left, top) = match at {
Some([x, y]) => (x, y),
None => {
let d = PASTE_STEP * f64::from(steps);
(x0 + d, y1 - d)
}
};
if !size.iter().chain(&[left, top, w, h]).all(|v| v.is_finite()) {
return rect;
}
let left = left.min(size[0] - w).max(0.0);
let top = top.max(h).min(size[1]);
[left, top - h, left + w, top]
}
/// Most paste steps [`paste_place`] tries before giving up on finding a free place.
const MAX_PASTE_STEPS: u32 = 64;
/// Where Edit ▸ Paste puts `content` on a page of `size` already holding `items` (display space):
/// where it was, or as many paste steps down and to the right as it takes not to land exactly on
/// a copy of it (the original it was copied from, or an earlier paste).
pub fn paste_place<'a>(items: impl IntoIterator<Item = &'a Content>, content: &Content, size: [f64; 2]) -> [f64; 4] {
let same = copy_key(content);
let copies: Vec<[f64; 4]> = items.into_iter().filter(|i| copy_key(i) == same).map(Content::rect).collect();
let taken = |rect: [f64; 4]| copies.iter().any(|c| c.iter().zip(rect).all(|(a, b)| (a - b).abs() < 0.5));
let mut rect = paste_rect(content.rect(), size, 0, None);
for steps in 1..=MAX_PASTE_STEPS {
if !taken(rect) {
break;
}
rect = paste_rect(content.rect(), size, steps, None);
}
rect
}
/// What makes two items copies of each other for [`paste_place`]: all but the box, and for an
/// image all but the object holding its picture, which a paste into another document stores anew.
fn copy_key(c: &Content) -> Content {
match c.with_rect([0.0; 4]) {
Content::Image(img) => Content::Image(AddedImage { image: ObjRef::new(0, 0), ..img }),
text => text,
}
}
/// The widest explicit line before wrapping, measured with the PDF writing fonts.
pub fn text_width(t: &AddedText) -> f64 {
t.text.split('\n').map(|line| shaped_width(t, line, unicode_bidi::get_base_direction(line) == unicode_bidi::Direction::Rtl)).fold(0.0, f64::max)
@@ -596,6 +666,9 @@ fn draw_laid_shaped(
}
let [cr, cg, cb] = t.color.map(|v| v.clamp(0.0, 1.0));
out.extend(format!("BT {} {} {} rg\n", n(cr), n(cg), n(cb)).bytes());
if t.char_spacing != 0.0 {
out.extend(format!("{} Tc\n", n(t.char_spacing)).bytes());
}
for (i, (line, rtl, pieces, w)) in laid.iter().enumerate() {
// Shaped glyphs are painted in visual order. Keep the original line's typing order
// explicitly, including marks, ligatures, digits and mixed-script punctuation.
@@ -621,7 +694,7 @@ fn draw_laid_shaped(
out.extend(literal(&win_ansi(s)));
out.extend_from_slice(b" Tj\n");
current = Some(latin.as_str());
pen += t.family.width(s, t.size, t.bold, t.italic) + tw * s.matches(' ').count() as f64;
pen += latin_width(t, s) + tw * s.matches(' ').count() as f64;
}
Piece::Shaped(clusters) => {
for c in clusters {
@@ -636,7 +709,7 @@ fn draw_laid_shaped(
out.extend(format!("1 0 0 1 {} {} Tm ", n(pen), n(y)).bytes());
out.extend(literal(&[code]));
out.extend_from_slice(b" Tj\n");
pen += c.advance * t.size + if c.text == " " { tw } else { 0.0 };
pen += c.advance * t.size + t.char_spacing + if c.text == " " { tw } else { 0.0 };
}
}
}
@@ -788,9 +861,12 @@ fn draw(doc: &mut Document, c: &Content, view: [f64; 6], taken: &Dict, existing:
let r = text_rect(t);
let [cr, cg, cb] = t.color.map(|v| v.clamp(0.0, 1.0));
out.extend(format!("BT /{name} {} Tf {} {} {} rg\n", n(t.size), n(cr), n(cg), n(cb)).bytes());
if t.char_spacing != 0.0 {
out.extend(format!("{} Tc\n", n(t.char_spacing)).bytes());
}
let all = lines(t);
for (i, line) in all.iter().enumerate() {
let w = t.family.width(line, t.size, t.bold, t.italic);
let w = latin_width(t, line);
let x = match t.align {
Align::Left | Align::Justify => r[0],
Align::Center => r[0] + ((r[2] - r[0]) - w) / 2.0,
@@ -861,6 +937,9 @@ fn params(c: &Content) -> Dict {
}),
);
d.set(b"Rect".to_vec(), arr(&text_rect(t)));
if t.char_spacing != 0.0 {
d.set(b"CharSpacing".to_vec(), Object::Real(t.char_spacing));
}
}
Content::Image(i) => {
d.set(b"Kind".to_vec(), Object::name("Image"));
@@ -904,6 +983,8 @@ fn parse(doc: &Document, d: &Dict) -> Option<Content> {
Some(3) => Align::Justify,
_ => Align::Left,
},
// Items written before character spacing have none.
char_spacing: d.get(b"CharSpacing").and_then(Object::as_f64).filter(|v| v.is_finite()).unwrap_or(0.0),
}))
}
b"Image" => {
@@ -1004,6 +1085,11 @@ fn validate(c: &Content) -> Result<(), EditError> {
if !(t.size.is_finite() && (1.0..=500.0).contains(&t.size)) {
return Err(EditError::Invalid("the font size must be between 1 and 500 points".into()));
}
if !(t.char_spacing.is_finite() && (-CHAR_SPACING_LIMIT..=CHAR_SPACING_LIMIT).contains(&t.char_spacing)) {
return Err(EditError::Invalid(format!(
"the character spacing must be between -{CHAR_SPACING_LIMIT} and {CHAR_SPACING_LIMIT} points"
)));
}
if (r[2] - r[0]).abs() < 1.0 {
return Err(EditError::Invalid("the text box is too narrow".into()));
}
+737
View File
@@ -983,6 +983,52 @@ fn added_text_and_images_are_page_content_that_stays_editable() {
assert!(marks_present(&doc).is_empty());
}
/// Edit ▸ Paste (#2636): where a pasted item lands.
#[test]
fn a_paste_lands_where_the_copy_was_offset_per_paste_and_stays_on_the_page() {
use crate::added::{PASTE_STEP, paste_rect};
let page = [300.0, 400.0];
let rect = [40.0, 300.0, 140.0, 320.0];
assert_eq!(paste_rect(rect, page, 0, None), rect, "in place");
let d = 2.0 * PASTE_STEP;
assert_eq!(paste_rect(rect, page, 2, None), [40.0 + d, 300.0 - d, 140.0 + d, 320.0 - d], "two steps down and right");
assert_eq!(paste_rect(rect, page, 1, Some([10.0, 50.0])), [10.0, 30.0, 110.0, 50.0], "its top-left corner at the point");
assert_eq!(paste_rect(rect, page, 0, Some([290.0, 5.0])), [200.0, 0.0, 300.0, 20.0], "pulled back onto the page");
assert_eq!(paste_rect([0.0, 0.0, 500.0, 600.0], page, 0, Some([10.0, 10.0])), [0.0, -200.0, 500.0, 400.0], "too large: left and top on the page");
assert_eq!(paste_rect([140.0, 320.0, 40.0, 300.0], page, 0, None), rect, "a reversed box is normalized");
assert_eq!(paste_rect(rect, [f64::NAN, 400.0], 1, None), rect, "a page without a size leaves the box alone");
assert_eq!(paste_rect(rect, page, 1, Some([f64::INFINITY, 5.0])), rect, "so does a point that isn't a number");
assert_eq!(paste_rect(rect, page, u32::MAX, None), [200.0, 0.0, 300.0, 20.0], "many pastes stop at the page's corner");
}
/// A paste steps on past exact copies of the item (its original, earlier pastes), and only those.
#[test]
fn a_paste_steps_past_copies_of_itself_only() {
use crate::added::{PASTE_STEP, paste_place};
let page = [300.0, 400.0];
let text = |rect, t: &str| Content::Text(AddedText { rect, text: t.into(), ..AddedText::default() });
let item = text([40.0, 300.0, 140.0, 314.4], "Note");
let step = |n: f64| [40.0 + n * PASTE_STEP, 300.0 - n * PASTE_STEP, 140.0 + n * PASTE_STEP, 314.4 - n * PASTE_STEP];
assert_eq!(paste_place([], &item, page), step(0.0), "an empty page: where it was");
assert_eq!(paste_place([&item], &item, page), step(1.0), "beside its original");
let first = item.with_rect(step(1.0));
assert_eq!(paste_place([&item, &first], &item, page), step(2.0), "beside the last copy");
assert_eq!(paste_place([&first], &item, page), step(0.0), "its place is free again (the original was cut)");
let other = text(step(0.0), "Other text");
assert_eq!(paste_place([&other], &item, page), step(0.0), "a different item in the way doesn't count");
// A page full of copies at its corner: the search ends.
let corner = item.with_rect([200.0, 0.0, 300.0, 14.4]);
let stuck = paste_place([&corner], &item.with_rect([200.0, 0.0, 300.0, 14.4]), page);
assert_eq!(stuck, [200.0, 0.0, 300.0, 14.4]);
// An image pasted into another document draws its picture from an object of that document:
// still a copy, so the next paste steps past it.
let image = Content::Image(AddedImage { crop: [0.1, 0.0, 0.0, 0.0], ..AddedImage::new(step(0.0), pdfcraft_cos::ObjRef::new(7, 0)) });
let pasted = Content::Image(AddedImage { crop: [0.1, 0.0, 0.0, 0.0], ..AddedImage::new(step(0.0), pdfcraft_cos::ObjRef::new(42, 0)) });
assert_eq!(paste_place([&pasted], &image, page), step(1.0), "a copy whose picture is stored anew");
let turned = Content::Image(AddedImage { rotation: 1, ..AddedImage::new(step(0.0), pdfcraft_cos::ObjRef::new(7, 0)) });
assert_eq!(paste_place([&turned], &image, page), step(0.0), "the same picture turned or cropped otherwise isn't a copy");
}
#[test]
fn added_arabic_text_is_shaped_in_display_order_and_stays_searchable() {
let mut doc = fixture();
@@ -1685,6 +1731,214 @@ fn japanese_replacement_over_240_unique_glyphs_is_split_across_fallback_fonts()
assert_eq!(glyphs, 300);
}
#[test]
fn styled_paragraph_batches_cyrillic_without_changing_source_fonts() {
if without_craft_fonts("styled_paragraph_batches_cyrillic_without_changing_source_fonts") {
return;
}
let mut doc = text_page(
"BT /F1 12 Tf 14.4 TL 1 0 0 1 72 700 Tm (The quick brown fox jumps over the lazy dog) Tj T* (and keeps running through the long field.) Tj ET",
);
let replacement = "The quick brown fox jumps over the lazy dog шалом\nand keeps running through the long field.";
text::rewrite_block(&mut doc, 0, 0, Some(replacement), &text::BlockStyle { width: Some(520.0), ..Default::default() }).unwrap();
let doc = reopen(&doc);
assert_eq!(fallback_fonts(&doc).len(), 1, "the five letters must share one font");
let lines = text::text_lines(&doc, 0).unwrap();
assert!(lines.iter().any(|l| l.base_font == "Helvetica" && l.text.starts_with("The quick brown fox")), "{lines:?}");
let fallback: Vec<_> = lines.iter().filter(|l| l.font.starts_with("PCJp")).collect();
assert_eq!(fallback.len(), 1, "one word must be one text run: {fallback:?}");
assert_eq!(fallback[0].text, "шалом");
assert_eq!(lines.iter().map(|l| l.text.as_str()).collect::<String>().replace(' ', ""), replacement.replace([' ', '\n'], ""));
}
#[test]
fn styled_paragraph_over_240_fallback_glyphs_splits_and_refuses_atomically() {
let replacement = format!("{}\nLatin", covered_japanese_chars(300));
let mut doc = text_page("BT /F1 12 Tf 14.4 TL 72 700 Td (Original) Tj T* (Latin) Tj ET");
let original = write_incremental(&doc, &SaveOptions::default()).unwrap();
if without_craft_fonts("styled_paragraph_over_240_fallback_glyphs_splits_and_refuses_atomically") {
assert!(text::replace_block(&mut doc, 0, 0, &replacement).is_err());
assert_eq!(write_incremental(&doc, &SaveOptions::default()).unwrap(), original);
return;
}
text::rewrite_block(&mut doc, 0, 0, Some(&replacement), &text::BlockStyle { width: Some(14000.0), ..Default::default() }).unwrap();
let reopened = reopen(&doc);
let fonts = fallback_fonts(&reopened);
assert_eq!(fonts.len(), 2, "300 glyphs need two fonts, not an error at glyph 241");
let counts: Vec<_> = fonts.iter().map(|(_, f)| reopened.dict(f.get(b"CharProcs").unwrap()).unwrap().len()).collect();
assert_eq!(counts.iter().sum::<usize>(), 300);
assert!(counts.iter().all(|n| *n <= 240));
assert_eq!(text::text_lines(&reopened, 0).unwrap().iter().map(|l| l.text.as_str()).collect::<String>(), replacement.replace('\n', ""));
let before = write_incremental(&doc, &SaveOptions::default()).unwrap();
let snapshot = doc.clone();
let err = text::replace_block(&mut doc, 0, 0, &format!("{replacement}\u{10ffff}")).unwrap_err();
assert!(err.to_string().contains("U+10FFFF"), "{err}");
assert_eq!(write_incremental(&doc, &SaveOptions::default()).unwrap(), before);
assert_eq!(write_incremental(&snapshot, &SaveOptions::default()).unwrap(), before);
}
#[test]
fn styled_fallback_batches_keep_face_choices_and_range_styles() {
if without_craft_fonts("styled_fallback_batches_keep_face_choices_and_range_styles") {
return;
}
if !pdfcraft_fonts::CRAFT_FONTS.iter().any(|f| f.family == "BIZ UDPGothic" && f.style == "Bold") {
eprintln!("skipping: no bold Gothic face");
return;
}
let mut doc = text_page("BT /F1 12 Tf 72 700 Td (Original) Tj ET");
let range = |range, family, bold| text::RangeStyle {
range,
family: Some((family, bold, false)),
resource: None,
size: None,
color: None,
underline: None,
char_spacing: None,
scale: None,
};
let style = text::BlockStyle {
width: Some(520.0),
ranges: vec![
range(3..6, added::Family::Times, false),
range(6..9, added::Family::Helvetica, true),
range(9..11, added::Family::Times, false),
],
..Default::default()
};
let original = write_incremental(&doc, &SaveOptions::default()).unwrap();
let err = text::rewrite_block(&mut doc, 0, 0, Some("見見見ш見ш\nLatin\u{10ffff}"), &style).unwrap_err();
assert!(err.to_string().contains("U+10FFFF"), "{err}");
assert_eq!(write_incremental(&doc, &SaveOptions::default()).unwrap(), original, "all faces must validate before writing fallback objects");
text::rewrite_block(&mut doc, 0, 0, Some("見見見ш見ш\nLatin"), &style).unwrap();
let doc = reopen(&doc);
let fonts = fallback_fonts(&doc);
let mut summary: Vec<_> = fonts
.iter()
.map(|(_, f)| {
let face = pdfcraft_fonts::pdf::Metrics::from_dict(&doc, f).base_font;
let count = doc.dict(f.get(b"CharProcs").unwrap()).unwrap().len();
(face, count)
})
.collect();
summary.sort();
assert_eq!(
summary,
[
("BIZUDMincho-Regular".into(), 1),
("BIZUDPGothic-Bold".into(), 1),
("BIZUDPGothic-Regular".into(), 2),
("ShipporiMincho-Regular".into(), 1)
]
);
assert_eq!(text::text_lines(&doc, 0).unwrap().iter().map(|l| l.text.as_str()).collect::<String>(), "見見見ш見шLatin");
}
#[test]
fn styled_fallback_budget_is_enforced_before_objects_are_written() {
let glyphs = covered_japanese_chars(65);
let mut doc = text_page("BT /F1 12 Tf 72 700 Td (Original) Tj ET");
let original = write_incremental(&doc, &SaveOptions::default()).unwrap();
let snapshot = doc.clone();
let style = text::BlockStyle { width: Some(14000.0), ..Default::default() };
let over_budget = format!("{glyphs}\nLatin");
let err = text::rewrite_block_with_limit(&mut doc, 0, 0, Some(&over_budget), &style, 1).unwrap_err().to_string();
assert_eq!(write_incremental(&doc, &SaveOptions::default()).unwrap(), original, "refusal must add no objects");
assert_eq!(write_incremental(&snapshot, &SaveOptions::default()).unwrap(), original);
if without_craft_fonts("styled_fallback_budget_is_enforced_before_objects_are_written") {
assert!(err.contains("CRAFT_FONTS_DIR"), "{err}");
return;
}
assert!(err.contains("more than 64 fallback glyphs"), "{err}");
// One glyph per font gives a small, real budget of 64 distinct glyphs. At the
// boundary a repeated glyph is free: this is not a limit on text length.
let at_budget: String = glyphs.chars().take(64).chain(glyphs.chars().take(1)).collect();
text::rewrite_block_with_limit(&mut doc, 0, 0, Some(&format!("{at_budget}\nLatin")), &style, 1).unwrap();
let doc = reopen(&doc);
assert_eq!(fallback_fonts(&doc).len(), 64);
assert_eq!(text::text_lines(&doc, 0).unwrap().iter().map(|l| l.text.as_str()).collect::<String>(), format!("{at_budget}Latin"));
}
#[test]
fn styled_fallback_same_base_font_and_character_keep_both_weights() {
if without_craft_fonts("styled_fallback_same_base_font_and_character_keep_both_weights") {
return;
}
if !pdfcraft_fonts::CRAFT_FONTS.iter().any(|f| f.family == "BIZ UDPGothic" && f.style == "Bold") {
eprintln!("skipping: no bold Gothic face");
return;
}
let mut doc = text_page("BT /F1 12 Tf 72 700 Td (alpha ) Tj /F2 12 Tf (beta ) Tj ET");
let source = doc.get(pdfcraft_cos::ObjRef::new(5, 0)).as_dict().unwrap().clone();
for (object, weight) in [(5, 400), (6, 700)] {
let mut font = source.clone();
// The same BaseFont can have different descriptor weights. Changing a
// RangeStyle family would also rename BaseFont and miss this cache key.
font.set(b"BaseFont".to_vec(), Object::name("NeutralFace"));
let mut descriptor = Dict::new();
descriptor.set(b"FontName".to_vec(), Object::name("NeutralFace"));
descriptor.set(b"FontWeight".to_vec(), Object::Int(weight));
font.set(b"FontDescriptor".to_vec(), Object::Dict(descriptor));
doc.set(pdfcraft_cos::ObjRef::new(object, 0), Object::Dict(font));
}
let lines = text::text_lines(&doc, 0).unwrap();
assert_eq!(lines.len(), 2);
assert_eq!(lines[0].base_font, lines[1].base_font);
assert_eq!((lines[0].bold, lines[1].bold), (false, true));
// Unchanged words anchor each inserted copy of the same letter in its own source style.
let block = text::text_blocks(&doc, 0).unwrap().remove(0);
let mut inherited = Vec::new();
for (range, source) in block.edited_spans("alpha ш beta ш") {
for _ in "alpha ш beta ш".get(range).unwrap().chars().filter(|ch| *ch == 'ш') {
inherited.push(lines[source].bold);
}
}
assert_eq!(inherited, [false, true], "the fixture must exercise both weights of the same BaseFont");
text::replace_block(&mut doc, 0, 0, "alpha ш beta ш").unwrap();
let doc = reopen(&doc);
let fonts = fallback_fonts(&doc);
let mut names: Vec<_> = fonts.iter().map(|(_, f)| pdfcraft_fonts::pdf::Metrics::from_dict(&doc, f).base_font).collect();
names.sort();
assert_eq!(names, ["BIZUDPGothic-Bold", "BIZUDPGothic-Regular"]);
let outlines: Vec<_> = fonts
.iter()
.map(|(_, f)| {
let procs = doc.dict(f.get(b"CharProcs").unwrap()).unwrap();
assert_eq!(procs.len(), 1, "each weight needs just the shared letter");
stream_bytes(&doc, procs.iter().next().unwrap().1).unwrap()
})
.collect();
assert_ne!(outlines[0], outlines[1], "weight must change the outline, not only the descriptor");
let lines = text::text_lines(&doc, 0).unwrap();
assert_eq!(lines.iter().map(|l| l.text.as_str()).collect::<String>(), "alpha ш beta ш");
}
#[test]
fn styled_fallback_shards_keep_text_advances_and_alignment() {
if without_craft_fonts("styled_fallback_shards_keep_text_advances_and_alignment") {
return;
}
let source = "BT /F1 12 Tf 0.5 Tc 5 Tw 80 Tz 14.4 TL 72 700 Td (Original row) Tj T* (Second row) Tj ET";
let style =
text::BlockStyle { width: Some(520.0), align: Some(added::Align::Center), char_spacing: Some(0.7), scale: Some(80.0), ..Default::default() };
let mut whole = text_page(source);
let mut split = text_page(source);
let replacement = "Latin шалом ш\nSecond row";
text::rewrite_block_with_limit(&mut whole, 0, 0, Some(replacement), &style, 240).unwrap();
text::rewrite_block_with_limit(&mut split, 0, 0, Some(replacement), &style, 2).unwrap();
let (whole, split) = (reopen(&whole), reopen(&split));
assert_eq!(fallback_fonts(&whole).len(), 1);
assert_eq!(fallback_fonts(&split).len(), 3);
let (one, many) = (text::text_lines(&whole, 0).unwrap(), text::text_lines(&split, 0).unwrap());
assert_eq!(one.len(), many.len(), "{one:?} vs {many:?}");
for (a, b) in one.iter().zip(&many) {
assert_eq!(a.text, b.text);
for (a, b) in a.rect.iter().zip(b.rect) {
assert!((a - b).abs() < 0.002, "sharding must preserve alignment and advances: {a} vs {b}");
}
}
}
/// A replacement whose last glyph no face draws (in a later font) changes nothing: neither the
/// document nor a snapshot taken before the edit, which is what undo restores.
#[test]
@@ -2414,6 +2668,44 @@ fn missing_glyphs_substitute_helvetica_and_impossible_text_is_refused() {
assert!(text::replace_line(&mut doc, 0, 5, "x").is_err(), "no such line");
}
/// #4280: two paragraphs in subsets without Ç or Ã, one regular and one bold. Each edit that adds
/// an accent sets the paragraph in a standard font of its own weight. Editing the bold one must
/// not turn the regular one, set in its stand-in earlier, bold too, and the editor's frame for the
/// bold one must not reach the regular one.
#[test]
fn a_bold_stand_in_font_leaves_an_earlier_regular_one_alone() {
let widths = vec!["600"; 26].join(" ");
let font = |base: &str| {
format!("<< /Type /Font /Subtype /Type1 /BaseFont /{base} /FirstChar 65 /LastChar 90 /Widths [{widths}] /Encoding /WinAnsiEncoding >>")
};
let (regular, bold) = (font("ABCDEF+Garamond"), font("ABCDEF+Garamond-Bold"));
let content = stream("", "BT /F1 12 Tf 72 700 Td (ACAO) Tj ET BT /F2 12 Tf 300 400 Td (TENSAO) Tj ET");
let mut doc = build(&[
"<< /Type /Catalog /Pages 2 0 R >>",
"<< /Type /Pages /Kids [3 0 R] /Count 1 >>",
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 600 800] /Contents 4 0 R /Resources << /Font << /F1 5 0 R /F2 6 0 R >> >> >>",
&content,
&regular,
&bold,
]);
let block = |doc: &Document, text: &str| text::text_blocks(doc, 0).unwrap().iter().position(|b| b.text == text).unwrap();
let acao = block(&doc, "ACAO");
assert_eq!(text::replace_block(&mut doc, 0, acao, "AÇÃO").unwrap().substituted.as_deref(), Some("Times-Roman"));
let first = text::text_lines(&doc, 0).unwrap().into_iter().find(|l| l.text == "AÇÃO").unwrap();
let tensao = block(&doc, "TENSAO");
let layout = text::text_edit_layout(&doc, 0, tensao, "TENSÃO", &text::BlockStyle::default()).unwrap();
let draft = layout.draft_rect.unwrap();
assert!(draft[3] < first.rect[1] || draft[1] > first.rect[3], "the frame {draft:?} reaches the regular paragraph at {:?}", first.rect);
assert_eq!(text::replace_block(&mut doc, 0, tensao, "TENSÃO").unwrap().substituted.as_deref(), Some("Times-Bold"));
let doc = reopen(&doc);
let lines = text::text_lines(&doc, 0).unwrap();
let font_of = |text: &str| lines.iter().find(|l| l.text == text).map(|l| l.base_font.clone());
assert_eq!(font_of("AÇÃO").as_deref(), Some("Times-Roman"), "{lines:?}");
assert_eq!(font_of("TENSÃO").as_deref(), Some("Times-Bold"), "{lines:?}");
}
#[test]
fn paragraphs_are_found_and_rewrapped() {
let mut doc = text_page(
@@ -6434,6 +6726,35 @@ fn added_text_is_wrapped_once_per_write() {
assert!(calls <= 4, "the text was wrapped {calls} times for 40 lines");
}
/// Character spacing on added text (#4245) is the PDF's `Tc`, kept in `/PCAdded` so the item
/// reopens with it; an item written without it reads 0.
#[test]
fn added_text_character_spacing_is_drawn_and_reopens() {
let mut doc = fixture();
let plain = AddedText { rect: [72.0, 600.0, 400.0, 700.0], text: "Approved".into(), size: 10.0, ..AddedText::default() };
add_content(&mut doc, 0, &Content::Text(plain.clone())).unwrap();
add_content(&mut doc, 0, &Content::Text(AddedText { char_spacing: 2.5, ..plain })).unwrap();
let doc = reopen(&doc);
let spacings: Vec<f64> = list_added(&doc).iter().map(|a| if let Content::Text(t) = &a.content { t.char_spacing } else { f64::NAN }).collect();
assert_eq!(spacings, [0.0, 2.5]);
let page = streams(&doc, 0);
let tc: Vec<bool> = page.iter().filter(|s| s.contains("(Approved) Tj")).map(|s| s.contains("2.5 Tc")).collect();
assert_eq!(tc, [false, true], "{page:?}");
}
/// Spacing widens every measure the layout takes: the widest line and wrapping.
#[test]
fn added_text_character_spacing_widens_its_layout() {
let plain = AddedText { rect: [0.0, 0.0, 1000.0, 100.0], text: "Approved".into(), size: 10.0, ..AddedText::default() };
let spaced = AddedText { char_spacing: 3.0, ..plain.clone() };
// After each of the 8 letters, like `Tc`.
assert!((added::text_width(&spaced) - added::text_width(&plain) - 24.0).abs() < 1e-9);
let w = added::text_width(&plain);
let narrow = |t: &AddedText| AddedText { text: "Approved Approved".into(), rect: [0.0, 0.0, 2.0 * w + 5.0, 100.0], ..t.clone() };
assert_eq!(added::lines(&narrow(&plain)).len(), 1);
assert_eq!(added::lines(&narrow(&spaced)).len(), 2, "the spaced words no longer fit one line");
}
/// A field tree whose every node lists its child twice is pruned in work linear in its nodes, not
/// in its paths, and a node listing itself is visited once.
#[test]
@@ -6638,3 +6959,419 @@ fn a_flatten_refused_on_a_later_page_changes_nothing() {
assert!(matches!(flatten(&mut doc, &[0, 1], true, false), Err(EditError::Invalid(_))));
assert_eq!((*doc.get(first)).clone(), before, "the first page keeps its comment and content");
}
/// How each glyph-showing operator on page 0 is painted, read the way a renderer reads the page:
/// its text, `Tr`, stroke colour operators, line width (from `w` or an ExtGState's `/LW`) and
/// the ExtGStates selected before it, following `q`/`Q`.
#[derive(Clone, Debug, PartialEq)]
struct Painted {
text: String,
render_mode: i64,
stroke: Vec<String>,
line_width: f64,
gs: Vec<String>,
}
fn painted_shows(doc: &Document) -> Vec<Painted> {
let (_, ops) = joined_ops(doc);
let p = &pdfcraft_model::pages(doc)[0];
let res = doc.resolve(p.dict.get(b"Resources").unwrap());
let ext = res.as_dict().unwrap().get(b"ExtGState").map(|g| doc.resolve(g).as_dict().cloned().unwrap()).unwrap_or_default();
let mut state = Painted { text: String::new(), render_mode: 0, stroke: Vec::new(), line_width: 1.0, gs: Vec::new() };
let mut stack = Vec::new();
let mut out = Vec::new();
let show = |op: &pdfcraft_content::Op| String::from_utf8_lossy(&pdfcraft_content::serialize_ops(std::slice::from_ref(op))).trim().to_string();
for op in ops {
match op.op.as_slice() {
b"q" => stack.push(state.clone()),
b"Q" => state = stack.pop().unwrap(),
b"Tr" => state.render_mode = op.operands[0].as_int().unwrap(),
b"G" | b"RG" | b"K" | b"CS" => state.stroke = vec![show(&op)],
b"SC" | b"SCN" => state.stroke.push(show(&op)),
b"w" => state.line_width = op.num(0).unwrap(),
b"gs" => {
let name = op.name(0).unwrap();
state.gs.push(String::from_utf8_lossy(name).into_owned());
let lw = ext.get(name).and_then(|g| doc.resolve(g).as_dict().and_then(|g| g.get(b"LW")).and_then(|w| w.as_f64()));
state.line_width = lw.unwrap_or(state.line_width);
}
b"Tj" => {
let Some(Object::String(s)) = op.operands.last() else { continue };
if !s.bytes.is_empty() {
out.push(Painted { text: String::from_utf8_lossy(&s.bytes).into_owned(), ..state.clone() });
}
}
_ => {}
}
}
out
}
/// A page with Helvetica as /F1, /GS1, an ExtGState that paints at 20 % opacity, /GS2, one that
/// sets the line width to 4, /GS3, another at 20 % opacity, and /GS4, at 20 % opacity and dashed.
fn faint_page(content: &str) -> Document {
build(&[
"<< /Type /Catalog /Pages 2 0 R >>",
"<< /Type /Pages /Kids [3 0 R] /Count 1 >>",
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 600 800] /Contents 4 0 R /Resources << /Font << /F1 5 0 R >> /ExtGState << /GS1 6 0 R /GS2 7 0 R /GS3 8 0 R /GS4 9 0 R >> >> >>",
&format!("<< /Length {} >>\nstream\n{content}\nendstream", content.len()),
"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>",
"<< /Type /ExtGState /ca 0.2 >>",
"<< /Type /ExtGState /LW 4 >>",
"<< /Type /ExtGState /ca 0.2 >>",
"<< /Type /ExtGState /ca 0.2 /D [[6 3] 0] >>",
])
}
/// Rewriting a paragraph drew it before its text object, restating only the font, spacing and
/// fill: a `1 Tr 1 0 0 RG 2 w` set inside `BT` was lost, and red outline text came back filled
/// black, even with the text unchanged (#3508). Set before `BT` (the control), it already worked.
#[test]
fn a_rewritten_paragraph_keeps_the_rendering_mode_stroke_and_width_set_inside_its_text_object() {
let outline = |text: &str| Painted { text: text.into(), render_mode: 1, stroke: vec!["1 0 0 RG".into()], line_width: 2.0, gs: Vec::new() };
for content in ["BT /F1 72 Tf 1 Tr 1 0 0 RG 2 w 40 400 Td (OUTLINE) Tj ET\n", "1 Tr 1 0 0 RG 2 w BT /F1 72 Tf 40 400 Td (OUTLINE) Tj ET\n"] {
assert_eq!(painted_shows(&text_page(content)), [outline("OUTLINE")], "the fixture: {content}");
for new in ["OUTLINE", "OUTLINED"] {
let mut doc = text_page(content);
text::rewrite_block(&mut doc, 0, 0, Some(new), &BlockStyle::default()).unwrap();
let doc = reopen(&doc);
assert_eq!(painted_shows(&doc), [outline(new)], "{content} -> {new}: {}", streams(&doc, 0).join("\n"));
}
}
}
/// The same for transparency: `/GS1 gs` (`/ca 0.2`) inside `BT` was not in force for the
/// rewritten paragraph, so 20 % blue text came back opaque (#3509).
#[test]
fn a_rewritten_paragraph_keeps_the_extgstate_selected_inside_its_text_object() {
for content in ["BT /GS1 gs /F1 72 Tf 0 0 1 rg 40 400 Td (FAINT) Tj ET\n", "/GS1 gs BT /F1 72 Tf 0 0 1 rg 40 400 Td (FAINT) Tj ET\n"] {
for new in ["FAINT", "FAINTER"] {
let mut doc = faint_page(content);
text::rewrite_block(&mut doc, 0, 0, Some(new), &BlockStyle::default()).unwrap();
let doc = reopen(&doc);
let shows = painted_shows(&doc);
assert_eq!(shows.len(), 1, "{content} -> {new}: {shows:?}");
assert_eq!(
(shows[0].text.as_str(), shows[0].gs.as_slice()),
(new, ["GS1".to_string()].as_slice()),
"{content} -> {new}: {}",
streams(&doc, 0).join("\n")
);
}
}
}
/// A paragraph of differently coloured runs goes through the styled rewrite, which draws each
/// run in its own text object: each keeps the state its source set inside `BT`.
#[test]
fn a_styled_rewrite_keeps_the_paint_state_set_inside_the_text_object() {
let content = "BT /GS1 gs 1 Tr 1 0 0 RG 2 w /F1 72 Tf 40 400 Td (FAI) Tj 0 0 1 rg (NT) Tj ET\n";
let mut doc = faint_page(content);
assert_eq!(text::text_blocks(&doc, 0).unwrap()[0].rows[0].len(), 2, "two runs on one row");
text::rewrite_block(&mut doc, 0, 0, Some("FAINTS"), &BlockStyle::default()).unwrap();
let doc = reopen(&doc);
let shows = painted_shows(&doc);
let joined = streams(&doc, 0).join("\n");
assert_eq!(shows.iter().map(|s| s.text.as_str()).collect::<String>(), "FAINTS", "{joined}");
for s in &shows {
assert_eq!((s.render_mode, s.stroke.as_slice(), s.line_width), (1, ["1 0 0 RG".to_string()].as_slice(), 2.0), "{s:?}: {joined}");
assert_eq!(s.gs, ["GS1"], "{s:?}: {joined}");
}
}
/// A `gs` has no inverse, so one run's ExtGState stayed in force for the runs the styled rewrite
/// drew after it. Two ExtGStates at the same opacity paint the same (see `Paint`), so their runs
/// share a paragraph, but either may set what that doesn't compare (a dash, a line cap): each run
/// is drawn with only the ones its source selected.
#[test]
fn a_styled_rewrite_does_not_carry_one_runs_extgstate_into_the_next() {
// "FAI" ends at 40 + 72 * (0.611 + 0.667 + 0.278) = 152.032; "NT" is blue, so another run.
let content = "q BT /GS3 gs /F1 72 Tf 40 400 Td (FAI) Tj ET Q BT /GS1 gs /F1 72 Tf 0 0 1 rg 152.032 400 Td (NT) Tj ET
";
for new in ["FAINT", "FAINTS"] {
let mut doc = faint_page(content);
assert_eq!(text::text_blocks(&doc, 0).unwrap()[0].rows[0].len(), 2, "two runs on one row");
text::rewrite_block(&mut doc, 0, 0, Some(new), &BlockStyle::default()).unwrap();
let doc = reopen(&doc);
let shows = painted_shows(&doc);
let joined = streams(&doc, 0).join(
"
",
);
assert_eq!(shows.iter().map(|s| s.text.as_str()).collect::<String>(), new, "{joined}");
let gs: Vec<_> = shows.iter().map(|s| (s.text.as_str(), s.gs.as_slice())).collect();
assert_eq!(gs.first(), Some(&("FAI", ["GS3".to_string()].as_slice())), "{gs:?}: {joined}");
assert!(gs.iter().skip(1).all(|(_, gs)| *gs == ["GS1"]), "{gs:?}: {joined}");
}
}
/// An ExtGState's `/LW` sets the line width as `w` does: `2 w /GS2 gs` (`/LW 4`) outlines at 4,
/// and the rewrite replayed `/GS2 gs` and then `2 w`. `/GS2 gs 1 w` outlines at 1, and the
/// rewrite replayed only `/GS2 gs`, since 1 is the initial width.
#[test]
fn a_rewritten_paragraph_keeps_the_line_width_an_extgstate_set() {
for (content, width) in [
("BT /F1 72 Tf 1 Tr 2 w /GS2 gs 40 400 Td (OUTLINE) Tj ET\n", 4.0),
("BT /F1 72 Tf 1 Tr /GS2 gs 2 w 40 400 Td (OUTLINE) Tj ET\n", 2.0),
("BT /F1 72 Tf 1 Tr /GS2 gs 1 w 40 400 Td (OUTLINE) Tj ET\n", 1.0),
] {
assert_eq!(painted_shows(&faint_page(content))[0].line_width, width, "the fixture: {content}");
for new in ["OUTLINE", "OUTLINED"] {
let mut doc = faint_page(content);
text::rewrite_block(&mut doc, 0, 0, Some(new), &BlockStyle::default()).unwrap();
let doc = reopen(&doc);
let shows = painted_shows(&doc);
assert_eq!(
shows.iter().map(|s| (s.text.as_str(), s.render_mode, s.line_width)).collect::<Vec<_>>(),
[(new, 1, width)],
"{content} -> {new}: {}",
streams(&doc, 0).join("\n")
);
}
}
}
/// A line is rewritten in the state of its first run, so outline text partway through a text
/// object came back filled: "FAI" filled and "NT" a red outline came back all filled. The change
/// of `Tr` now starts a run. (A `gs` partway already starts a paragraph; see `Paint`.)
#[test]
fn a_rendering_mode_partway_through_a_line_starts_a_run_of_its_own() {
let content = "BT /F1 72 Tf 40 400 Td (FAI) Tj 1 Tr 1 0 0 RG 2 w (NT) Tj ET
";
for new in ["FAINT", "FAINTS"] {
let mut doc = faint_page(content);
assert_eq!(text::text_blocks(&doc, 0).unwrap()[0].rows[0].len(), 2, "two runs on one row");
text::rewrite_block(&mut doc, 0, 0, Some(new), &BlockStyle::default()).unwrap();
let doc = reopen(&doc);
let shows = painted_shows(&doc);
let joined = streams(&doc, 0).join(
"
",
);
assert_eq!(shows.iter().map(|s| s.text.as_str()).collect::<String>(), new, "{joined}");
let modes: Vec<_> = shows.iter().map(|s| (s.text.as_str(), s.render_mode, s.stroke.as_slice(), s.line_width)).collect();
assert_eq!(modes.first().map(|m| (m.0, m.1)), Some(("FAI", 0)), "{modes:?}: {joined}");
let outline = ["1 0 0 RG".to_string()];
assert!(modes.iter().skip(1).all(|m| (m.1, m.2, m.3) == (1, outline.as_slice(), 2.0)), "{modes:?}: {joined}");
}
}
/// Two ExtGStates at the same opacity paint text the same (see `Paint`), but one of them dashes
/// its outline: a dashed outline after a solid one in the same text object joined its line and
/// came back solid, drawn with the first run's selections. A different dash now starts a run.
#[test]
fn a_dash_partway_through_an_outlined_line_starts_a_run_of_its_own() {
let content = "BT /GS3 gs /F1 72 Tf 1 Tr 1 0 0 RG 2 w 40 400 Td (FAI) Tj /GS4 gs (NT) Tj ET
";
for new in ["FAINT", "FAINTS"] {
let mut doc = faint_page(content);
assert_eq!(text::text_blocks(&doc, 0).unwrap()[0].rows[0].len(), 2, "two runs on one row");
text::rewrite_block(&mut doc, 0, 0, Some(new), &BlockStyle::default()).unwrap();
let doc = reopen(&doc);
let shows = painted_shows(&doc);
let joined = streams(&doc, 0).join(
"
",
);
assert_eq!(shows.iter().map(|s| s.text.as_str()).collect::<String>(), new, "{joined}");
let gs: Vec<_> = shows.iter().map(|s| (s.text.as_str(), s.gs.as_slice())).collect();
assert_eq!(gs.first(), Some(&("FAI", ["GS3".to_string()].as_slice())), "{gs:?}: {joined}");
assert!(gs.iter().skip(1).all(|(_, gs)| gs.last().is_some_and(|g| g == "GS4")), "{gs:?}: {joined}");
}
}
/// The dash and cap are compared as the operators set them too: `d` or `J` partway through an
/// outlined line starts a run, and a malformed one (too long, not numbers, out of range) is ignored.
#[test]
fn a_dash_or_cap_operator_partway_through_an_outlined_line_starts_a_run() {
let long = format!("[{}] 0 d", "1 ".repeat(40));
for (change, runs) in [("[6 3] 0 d", 2), ("1 J", 2), (long.as_str(), 1), ("[(a) 3] 0 d", 1), ("[6 3] /x d", 1), ("7 J", 1), ("J", 1)] {
let content = format!("BT /F1 72 Tf 1 Tr 1 0 0 RG 2 w 40 400 Td (FAI) Tj {change} (NT) Tj ET\n");
let mut doc = faint_page(&content);
assert_eq!(text::text_blocks(&doc, 0).unwrap()[0].rows[0].len(), runs, "{change}");
text::rewrite_block(&mut doc, 0, 0, Some("FAINTS"), &BlockStyle::default()).unwrap();
let shows = painted_shows(&reopen(&doc));
assert_eq!(shows.iter().map(|s| s.text.as_str()).collect::<String>(), "FAINTS", "{change}");
}
}
/// #4199, #3797: every space typed into a paragraph is saved, not folded into one.
#[test]
fn an_edited_paragraph_keeps_every_space_typed() {
for typed in ["Hello world", "Hello world end", " indented and trailing "] {
let mut doc = text_page("BT /F1 12 Tf 72 700 Td (Hello world) Tj ET");
assert_eq!(text::replace_block(&mut doc, 0, 0, typed).unwrap().substituted, None);
let doc = reopen(&doc);
let content = String::from_utf8_lossy(&page_content_bytes(&doc, 0)).into_owned();
assert!(content.contains(&format!("({typed}) Tj")), "{typed:?}: {content}");
assert_eq!(text::text_lines(&doc, 0).unwrap()[0].text, typed);
}
}
/// Spaces after a row's last word are kept but take no part in its alignment: a justified row
/// still reaches the margin, and a centred or right-aligned one sits where it would without them.
#[test]
fn spaces_after_a_rows_last_word_do_not_move_its_alignment() {
let shown = |text: &str, align: added::Align| {
let mut doc = text_page("BT /F1 12 Tf 72 700 Td (Hello world) Tj ET");
let style =
text::BlockStyle { family: Some((added::Family::Helvetica, false, false)), align: Some(align), width: Some(300.0), ..Default::default() };
text::rewrite_block(&mut doc, 0, 0, Some(text), &style).unwrap();
String::from_utf8_lossy(&page_content_bytes(&doc, 0)).into_owned()
};
for (plain, trailing, align) in [
("aaa bbb ccc\nddd eee", "aaa bbb ccc \nddd eee", added::Align::Justify),
("Title", "Title ", added::Align::Center),
("Title", "Title ", added::Align::Right),
] {
let first = trailing.split('\n').next().unwrap();
let expected = shown(plain, align);
let actual = shown(trailing, align).replace(&format!("({first})"), &format!("({})", first.trim_end()));
assert_eq!(actual, expected, "{trailing:?} {align:?}");
}
}
/// A justified row runs from the paragraph's left edge to the margin. Word spacing reaches only
/// the spaces between its words: the spaces before its first word and after its last are left
/// out of a stretched row (as before #4199), so the reopened rows stay inside the paragraph and
/// can be edited again in place.
#[test]
fn a_justified_row_keeps_its_indent_and_ends_at_the_margin() {
let style = text::BlockStyle {
family: Some((added::Family::Helvetica, false, false)),
align: Some(added::Align::Justify),
width: Some(300.0),
..Default::default()
};
for typed in [" Pack my box with five dozen jugs\nof liquor", " Pack my box with five dozen jugs \nof liquor"] {
let mut doc = text_page("BT /F1 12 Tf 72 700 Td (Hello world) Tj ET");
text::rewrite_block(&mut doc, 0, 0, Some(typed), &style).unwrap();
let mut doc = reopen(&doc);
let lines = text::text_lines(&doc, 0).unwrap();
let first = lines.iter().find(|l| l.text.contains("Pack")).unwrap();
assert_eq!(first.text, "Pack my box with five dozen jugs", "{typed:?}");
assert!((first.rect[0] - 72.0).abs() < 0.5, "{typed:?}: {:?}", first.rect);
assert!(lines.iter().all(|l| l.rect[0] >= 72.0 - 0.5 && l.rect[2] <= 372.5), "{typed:?}: {lines:?}");
let blocks = text::text_blocks(&doc, 0).unwrap();
assert_eq!(blocks.len(), 1, "{typed:?}: {blocks:?}");
text::replace_block(&mut doc, 0, 0, "Edited again").unwrap();
let again = text::text_lines(&reopen(&doc), 0).unwrap();
assert!(again.iter().all(|l| l.rect[0] >= 0.0 && l.rect[2] <= 600.0), "{typed:?}: {again:?}");
}
}
/// A justified paragraph whose first row was typed with an indent is edited again through the
/// styled path (a draft with a line break): its rows keep their scaling and stay one paragraph
/// inside its width.
#[test]
fn a_justified_paragraph_with_an_indent_edits_again_at_its_own_scale() {
let style = text::BlockStyle {
family: Some((added::Family::Helvetica, false, false)),
align: Some(added::Align::Justify),
width: Some(300.0),
..Default::default()
};
let mut doc = text_page("BT /F1 12 Tf 72 700 Td (Hello world) Tj ET");
text::rewrite_block(&mut doc, 0, 0, Some(" aaa bbb ccc \nddd"), &style).unwrap();
let mut doc = reopen(&doc);
let draft = text::text_blocks(&doc, 0).unwrap()[0].editor_text.replacen("ccc", "cc", 1);
assert!(draft.contains('\n'), "{draft:?}");
text::replace_block(&mut doc, 0, 0, &draft).unwrap();
let content = String::from_utf8_lossy(&page_content_bytes(&doc, 0)).into_owned();
let scales: Vec<&str> = content.lines().filter(|l| l.ends_with(" Tz")).collect();
assert!(scales.iter().all(|l| *l == "100 Tz"), "{scales:?}: {content}");
let doc = reopen(&doc);
let blocks = text::text_blocks(&doc, 0).unwrap();
assert_eq!(blocks.len(), 1, "{blocks:?}");
let lines = text::text_lines(&doc, 0).unwrap();
assert!(lines.iter().all(|l| l.rect[0] >= 72.0 - 0.5 && l.rect[2] <= 372.5), "{lines:?}");
}
/// A paragraph drawn at `0 Tz` has no width to justify into: nothing is divided by it. The
/// writer writes a number that isn't finite as 0, so the test looks for the word spacing and
/// the move a division by zero would add, rather than for `NaN`.
#[test]
fn justifying_text_at_zero_horizontal_scaling_divides_by_nothing() {
let mut doc = text_page("BT /F1 12 Tf 0 Tz 72 700 Td (Hello world) Tj ET");
let style = text::BlockStyle { family: Some((added::Family::Helvetica, false, false)), align: Some(added::Align::Justify), ..Default::default() };
text::rewrite_block(&mut doc, 0, 0, Some(" aaa bbb\nccc"), &style).unwrap();
let content = String::from_utf8_lossy(&page_content_bytes(&doc, 0)).into_owned();
let block = content.split("ET").next().unwrap();
assert_eq!(block.matches(" Tw").count(), 1, "only the paragraph's own 0 Tw: {content}");
let first_row = block.split(" Tm").nth(1).and_then(|rest| rest.split(" Tj").next()).unwrap();
assert!(!first_row.contains(" Td"), "no move before the first row: {content}");
}
/// The preview's box is the box of the rows Apply writes, measured to their last glyphs.
#[test]
fn a_drafts_box_is_the_box_apply_draws() {
let doc = text_page("BT /F1 12 Tf 14 TL 72 700 Td [(First) -2000 (row here )] TJ T* (Second row ) Tj ET");
let source = text::text_blocks(&doc, 0).unwrap().swap_remove(0);
let draft = source.editor_text.replacen("Second", "Third", 1);
let layout = text::text_edit_layout(&doc, 0, 0, &draft, &text::BlockStyle::default()).unwrap();
let mut applied = doc.clone();
text::replace_block(&mut applied, 0, 0, &draft).unwrap();
let boxed = text::text_lines(&applied, 0)
.unwrap()
.into_iter()
.map(|l| {
let end = l.ink.iter().map(|r| r[2]).fold(f64::NEG_INFINITY, f64::max);
[l.rect[0], l.rect[1], if end.is_finite() { end.min(l.rect[2]) } else { l.rect[2] }, l.rect[3]]
})
.reduce(|a, r| [a[0].min(r[0]), a[1].min(r[1]), a[2].max(r[2]), a[3].max(r[3])]);
let (d, b) = (layout.draft_rect.unwrap(), boxed.unwrap());
assert!(d.iter().zip(b).all(|(x, y)| (x - y).abs() < 0.01), "{draft:?}: preview {d:?}, applied {b:?}");
}
/// The draft's box is measured to its last glyph, not over the spaces typed after it.
#[test]
fn a_drafts_box_leaves_out_spaces_after_the_last_word() {
let doc = text_page("BT /F1 12 Tf 72 700 Td (Hello world) Tj ET");
let layout = |text: &str| text::text_edit_layout(&doc, 0, 0, text, &text::BlockStyle::default()).unwrap().draft_rect;
assert_eq!(layout("Hello there "), layout("Hello there"));
}
/// A lone carriage return (an old Mac line ending) breaks the row, as `\n` and `\r\n` do.
#[test]
fn a_lone_carriage_return_breaks_an_edited_paragraph() {
let mut doc = text_page("BT /F1 12 Tf 72 700 Td (Hello world) Tj ET");
text::replace_block(&mut doc, 0, 0, "one\rtwo").unwrap();
let lines: Vec<String> = text::text_lines(&reopen(&doc), 0).unwrap().into_iter().map(|l| l.text).collect();
assert_eq!(lines, ["one", "two"]);
}
/// On the styled rewrite path too, `\r\n` is one row break and a lone `\r` another, and no
/// carriage return reaches the page: with no other formatting, and with a part set in red.
#[test]
fn carriage_returns_break_rows_on_the_styled_path() {
let draft = "one\r\ntwo\rthree";
let red = text::RangeStyle {
range: 0..3,
family: None,
resource: None,
size: None,
color: Some([1.0, 0.0, 0.0]),
underline: None,
char_spacing: None,
scale: None,
};
for style in [text::BlockStyle::default(), text::BlockStyle { ranges: vec![red], ..Default::default() }] {
let mut doc = text_page("BT /F1 12 Tf 72 700 Td (Hello world) Tj ET");
text::rewrite_block(&mut doc, 0, 0, Some(draft), &style).unwrap();
let doc = reopen(&doc);
let content = page_content_bytes(&doc, 0);
assert!(!content.contains(&b'\r') && !content.windows(2).any(|w| w == b"\\r"), "{}", String::from_utf8_lossy(&content));
let lines: Vec<String> = text::text_lines(&doc, 0).unwrap().into_iter().map(|l| l.text).collect();
assert_eq!(lines, ["one", "two", "three"], "{style:?}");
}
}
/// A subset with no space glyph shows each space as a positioning gap one space wide, so a run
/// of spaces still takes a run's width (#4199).
#[test]
fn a_run_of_spaces_in_a_subset_without_a_space_glyph_keeps_its_width() {
let mut doc = text_page("BT /F2 12 Tf 72 700 Td (ab) Tj /F1 12 Tf ( ) Tj /F2 12 Tf (ba) Tj ET");
assert_eq!(text::replace_block(&mut doc, 0, 0, "ab ba ab").unwrap().substituted, None);
let content = String::from_utf8_lossy(&page_content_bytes(&reopen(&doc), 0)).into_owned();
assert_eq!(content.matches("[-330] TJ").count(), 5, "{content}");
}
+308 -51
View File
@@ -80,6 +80,10 @@ pub struct TextLine {
/// Why the line can't be edited: its font's writing mode (its CMap's `WMode`) couldn't be read,
/// so which way its glyphs advance is unknown. The line is listed as horizontal text.
unreadable_mode: Option<String>,
/// The runs the line joins, in content order: each one's text, the end of its words in
/// `ink`, and whether joining put a space before it. Empty when the line's text was put
/// into another order (see [`TextLine::runs`]).
runs: Vec<(String, usize, bool)>,
}
impl TextLine {
@@ -204,7 +208,17 @@ fn layout_draft(
*count -= 1;
continue;
}
rect = Some(rect.map_or(line.rect, |r| [r[0].min(line.rect[0]), r[1].min(line.rect[1]), r[2].max(line.rect[2]), r[3].max(line.rect[3])]));
// Spaces typed after a row's last word are drawn but show nothing, so an upright row is
// measured to the end of its last word: they don't make a draft overflow (#4199).
let mut r = line.rect;
if line.upright() && !line.ink.is_empty() {
if crate::bidi::rtl_base(&line.text) {
r[0] = r[0].max(line.ink.iter().map(|i| i[0]).fold(f64::INFINITY, f64::min));
} else {
r[2] = r[2].min(line.ink.iter().map(|i| i[2]).fold(f64::NEG_INFINITY, f64::max));
}
}
rect = Some(rect.map_or(r, |a| [a[0].min(r[0]), a[1].min(r[1]), a[2].max(r[2]), a[3].max(r[3])]));
}
let overflow = rect
.is_some_and(|r| r[0] < source.rect[0] - 0.5 || r[1] < source.rect[1] - 0.5 || r[2] > source.rect[2] + 0.5 || r[3] > source.rect[3] + 0.5);
@@ -223,6 +237,14 @@ struct TextState {
fill: Vec<Op>,
/// The text rendering mode (`Tr`); 3 is invisible text, as in an OCR layer over a scan.
render_mode: i64,
/// The stroke colour operators, the line width and the ExtGStates selected (see [`Ts`]):
/// graphics state the text was painted with that [`TextState::ops`] doesn't restate.
stroke: Vec<Op>,
line_width: Option<f64>,
ext_gstate: Vec<Vec<u8>>,
/// The dash pattern and line cap in force (see [`Ts`]): compared, not restated.
dash: Dash,
line_cap: i64,
}
impl TextState {
@@ -236,9 +258,53 @@ impl TextState {
rise: ts.rise,
fill: ts.fill.clone(),
render_mode: ts.render_mode,
stroke: ts.stroke.clone(),
line_width: ts.line_width,
ext_gstate: ts.ext_gstate.clone(),
dash: ts.dash.clone(),
line_cap: ts.line_cap,
}
}
/// Operators that change how text is painted from `current` (the state where they run) to
/// this one: the ExtGStates, stroke colour, line width and a visible rendering mode. A
/// rewritten paragraph is drawn before its text object, so whatever that object set before
/// its first show (`/GS1 gs`, `1 Tr 1 0 0 RG 2 w` inside `BT`, #3508/#3509) must be stated
/// again. Empty when nothing differs.
///
/// Only fill, stroke and fill-then-stroke (`Tr` 0–2) are restated: invisible text is revealed
/// by [`reveal_ops`] and clipping text is refused, so neither is ever drawn this way.
///
/// A `gs` has no inverse, so a selection `current` has and this state doesn't stays in force:
/// run these inside a `q`/`Q` that starts from `current`, one per state drawn.
fn paint_ops(&self, current: &TextState) -> Vec<Op> {
let n = pdfcraft_content::num;
let mut v = Vec::new();
// The selections both share stay in force; the ones after them are selected again in order.
let shared = self.ext_gstate.iter().zip(&current.ext_gstate).take_while(|(a, b)| a == b).count();
for name in self.ext_gstate.iter().skip(shared) {
v.push(Op::new("gs", vec![Object::Name(name.clone())]));
}
// A reselected ExtGState may set `/LW`, so the width (already the effective one) follows it.
let reselected = !v.is_empty();
if self.stroke != current.stroke {
if self.stroke.is_empty() {
// The initial stroke colour: black in DeviceGray.
v.push(Op::new("G", vec![n(0.0)]));
} else {
v.extend(self.stroke.iter().cloned());
}
}
let width = self.line_width.unwrap_or(1.0);
if reselected || width != current.line_width.unwrap_or(1.0) {
v.push(Op::new("w", vec![n(width)]));
}
if (0..=2).contains(&self.render_mode) && self.render_mode != current.render_mode {
v.push(Op::new("Tr", vec![Object::Int(self.render_mode)]));
}
v
}
/// Operators that set this state (inside a text object).
fn ops(&self) -> Vec<Op> {
let n = pdfcraft_content::num;
@@ -539,6 +605,20 @@ impl TextLine {
(self.stream, self.ops.iter().min().copied().unwrap_or(0))
}
/// The runs of text the line joins, in content order: each run's text as its glyphs show it,
/// the boxes of its words (a part of `ink`), and whether joining put a space between it and
/// the run before (`text` has one there; runs closer together join with none, so one word
/// can span runs). None when the line's text was reordered for reading (right-to-left or
/// visual-order Indic text): then only the line's text as a whole says what it reads.
pub fn runs(&self) -> impl Iterator<Item = (&str, &[[f64; 4]], bool)> {
let mut start = 0;
self.runs.iter().map(move |(text, end, spaced)| {
let ink = self.ink.get(start..*end).unwrap_or_default();
start = *end;
(text.as_str(), ink, *spaced)
})
}
fn rotation(&self) -> f64 {
let m = Matrix(self.origin.tm).then(&Matrix(self.origin.ctm)).0;
m[1].atan2(m[0]).to_degrees()
@@ -616,6 +696,50 @@ struct Ts {
/// Why the font's writing mode couldn't be read (a broken or cyclic CMap). Its text is then
/// listed as horizontal, but the lines in it are refused for editing.
unreadable: Option<Rc<str>>,
/// The operators that set the current stroke colour (`G`, `RG`, `K`, or `CS` + `SC`/`SCN`).
stroke: Vec<Op>,
/// The line width a `w` or an ExtGState's `/LW` set (`None`: the initial 1.0).
line_width: Option<f64>,
/// The ExtGState resources selected with `gs`, oldest first (see [`select_gs`]).
ext_gstate: Vec<Vec<u8>>,
/// The dash pattern a `d` or an ExtGState's `/D` set (initially solid: `[] 0`).
dash: Dash,
/// The line cap a `J` or an ExtGState's `/LC` set (initially 0, butt).
line_cap: i64,
}
/// A dash pattern (ISO 32000-2 §8.4.3.6): the dash array and the phase.
type Dash = (Vec<f64>, f64);
/// The most dash array entries a pattern keeps; a longer one is ignored, as is a malformed one.
const MAX_DASH: usize = 32;
/// The dash pattern `array phase`, as `d` takes it and an ExtGState's `/D` holds it.
fn dash_pattern(doc: &Document, array: Option<&Object>, phase: Option<&Object>) -> Option<Dash> {
let array = doc.resolve(array?);
let items = array.as_array().filter(|a| a.len() <= MAX_DASH)?;
let finite = |o: &Object| doc.resolve(o).as_f64().filter(|v| v.is_finite());
Some((items.iter().map(finite).collect::<Option<Vec<_>>>()?, finite(phase?)?))
}
/// A line cap style, as `J` takes it and an ExtGState's `/LC` holds it: 0, 1 or 2.
fn line_cap(doc: &Document, cap: Option<&Object>) -> Option<i64> {
doc.resolve(cap?).as_int().filter(|c| (0..=2).contains(c))
}
/// The most `gs` selections a state remembers. Repeating a selection moves it to the end, so
/// this bounds the distinct ExtGStates in force, not the operators a hostile stream repeats.
const MAX_GS: usize = 32;
/// Record `gs /name` in `list`. A `gs` sets every parameter its dictionary names to an absolute
/// value, so a later selection of the same dictionary overrides the earlier one completely: the
/// earlier entry goes, which keeps replaying the list equivalent to replaying the stream.
fn select_gs(list: &mut Vec<Vec<u8>>, name: &[u8]) {
list.retain(|n| n != name);
if list.len() >= MAX_GS {
list.remove(0);
}
list.push(name.to_vec());
}
/// The page's content streams as listed, each with its decoded data (empty when it doesn't
@@ -929,6 +1053,11 @@ impl Carry {
gs: Gs::default(),
vertical: None,
unreadable: None,
stroke: Vec::new(),
line_width: None,
ext_gstate: Vec::new(),
dash: (Vec::new(), 0.0),
line_cap: 0,
};
Carry { ts, stack: Vec::new(), marked: Vec::new(), layers: Vec::new(), text_left: MAX_PAGE_TEXT }
}
@@ -1042,6 +1171,14 @@ fn interpret(
ts.fill.retain(|o| o.is("cs"));
ts.fill.push(op.clone());
}
b"G" | b"RG" | b"K" | b"CS" => ts.stroke = vec![op.clone()],
b"SC" | b"SCN" => {
ts.stroke.retain(|o| o.is("CS"));
ts.stroke.push(op.clone());
}
b"w" => ts.line_width = op.num(0).filter(|w| w.is_finite()).or(ts.line_width),
b"d" => ts.dash = dash_pattern(doc, op.operands.first(), op.operands.get(1)).unwrap_or_else(|| ts.dash.clone()),
b"J" => ts.line_cap = line_cap(doc, op.operands.first()).unwrap_or(ts.line_cap),
b"Tf" => {
ts.size = op.num(1).unwrap_or(ts.size);
if let Some(name) = op.name(0) {
@@ -1069,9 +1206,21 @@ fn interpret(
b"Ts" => ts.rise = op.num(0).unwrap_or(0.0),
b"Tr" => ts.render_mode = op.operands.first().and_then(Object::as_int).unwrap_or(-1),
b"gs" => {
if let Some(name) = op.name(0) {
select_gs(&mut ts.ext_gstate, name);
}
let params = op.name(0).and_then(|name| states.get(name)).map(|p| doc.resolve(p));
if let Some(params) = params.as_deref().and_then(Object::as_dict) {
ts.gs.apply(doc, params);
// `/LW` sets the line width as `w` does (ISO 32000-2 §8.4.5).
let lw = params.get(b"LW").and_then(|w| doc.resolve(w).as_f64()).filter(|w| w.is_finite());
ts.line_width = lw.or(ts.line_width);
let dash = params.get(b"D").map(|d| doc.resolve(d));
let dash = dash.as_deref().and_then(Object::as_array);
if let Some(d) = dash.and_then(|d| dash_pattern(doc, d.first(), d.get(1))) {
ts.dash = d;
}
ts.line_cap = line_cap(doc, params.get(b"LC")).unwrap_or(ts.line_cap);
}
}
b"Do" => {
@@ -1351,7 +1500,11 @@ fn text_lines_in(doc: &Document, p: &pdfcraft_model::Page, actual_text: bool) ->
&& (s.text.trim().is_empty() || lines.last().is_some_and(|l| same_font(l, &s.font, &s.base_font, s.face.as_deref())))
&& (s.text.trim().is_empty()
|| lines.last().is_some_and(|l| {
(s.size - l.size).abs() < 0.01 && s.bold == l.bold && s.italic == l.italic && fill_color(&s.state.fill) == l.color
(s.size - l.size).abs() < 0.01
&& s.bold == l.bold
&& s.italic == l.italic
&& fill_color(&s.state.fill) == l.color
&& same_paint(l, &s.state)
}))
&& near
// An OCR layer is one text object over the whole scan: its words continue a line
@@ -1360,13 +1513,15 @@ fn text_lines_in(doc: &Document, p: &pdfcraft_model::Page, actual_text: bool) ->
});
if joins && let Some(l) = lines.last_mut() {
let gap = last.map_or(0.0, |(_, pen)| pen.continues(&s, 0.0).1);
if gap - s.tracking > l.size * s.state.scale.abs() * 0.2 && !l.text.ends_with(' ') && !s.text.starts_with(' ') {
let spaced = gap - s.tracking > l.size * s.state.scale.abs() * 0.2 && !l.text.ends_with(' ') && !s.text.starts_with(' ');
if spaced {
l.text.push(' ');
}
l.text.push_str(&s.text);
l.rect = [l.rect[0].min(s.rect[0]), l.rect[1].min(s.rect[1]), l.rect[2].max(s.rect[2]), l.rect[3].max(s.rect[3])];
l.frame = union(l.frame, s.frame);
l.ink.extend(s.ink.iter().copied());
l.runs.push((s.text.clone(), l.ink.len(), spaced));
l.ops.push(s.op);
l.ops.extend(s.extra_ops.iter().copied());
l.decodable &= s.decodable;
@@ -1399,6 +1554,7 @@ fn text_lines_in(doc: &Document, p: &pdfcraft_model::Page, actual_text: bool) ->
actual_text: s.actual_text,
clips: s.state.render_mode >= 4,
unreadable_mode: s.state.unreadable.as_deref().map(str::to_owned),
runs: vec![(s.text.clone(), s.ink.len(), false)],
ops: std::iter::once(s.op).chain(s.extra_ops.iter().copied()).collect(),
origin: Origin {
tm: s.tm.0,
@@ -1418,10 +1574,15 @@ fn text_lines_in(doc: &Document, p: &pdfcraft_model::Page, actual_text: bool) ->
// Content streams draw right-to-left lines in visual order; the editor works in typing order.
for l in lines.iter_mut().filter(|l| !l.logical_order) {
// A visual-order Indic font draws pre-base vowel signs before their consonant.
let shown = l.text.clone();
if l.visual_order && !l.actual_text {
l.text = crate::indic::to_logical(&l.text);
}
l.text = crate::bidi::to_logical(&l.text);
// The runs hold the text in drawing order, which no longer reads as the line does.
if l.text != shown {
l.runs.clear();
}
}
// Lines of only spaces aren't editable text.
lines.retain(|l| !l.text.trim().is_empty());
@@ -1457,19 +1618,25 @@ fn add_shown(lines: &mut Vec<TextLine>, last: &mut Option<Pen>, s: Shown, stream
&& (s.text.trim().is_empty() || lines.last().is_some_and(|l| same_font(l, &s.font, &s.base_font, s.face.as_deref())))
&& (s.text.trim().is_empty()
|| lines.last().is_some_and(|l| {
(s.size - l.size).abs() < 0.01 && s.bold == l.bold && s.italic == l.italic && fill_color(&s.state.fill) == l.color
(s.size - l.size).abs() < 0.01
&& s.bold == l.bold
&& s.italic == l.italic
&& fill_color(&s.state.fill) == l.color
&& same_paint(l, &s.state)
}))
&& pen.continues(&s, if bt == s.bt { 3.0 } else { 1.5 }).0
});
if joins && let Some(l) = lines.last_mut() {
let gap = last.map_or(0.0, |pen| pen.continues(&s, 0.0).1);
if gap - s.tracking > l.size * s.state.scale.abs() * 0.2 && !l.text.ends_with(' ') && !s.text.starts_with(' ') {
let spaced = gap - s.tracking > l.size * s.state.scale.abs() * 0.2 && !l.text.ends_with(' ') && !s.text.starts_with(' ');
if spaced {
l.text.push(' ');
}
l.text.push_str(&s.text);
l.rect = [l.rect[0].min(s.rect[0]), l.rect[1].min(s.rect[1]), l.rect[2].max(s.rect[2]), l.rect[3].max(s.rect[3])];
l.frame = union(l.frame, s.frame);
l.ink.extend(s.ink.iter().copied());
l.runs.push((s.text.clone(), l.ink.len(), spaced));
l.ops.push(s.op);
l.ops.extend(s.extra_ops.iter().copied());
l.decodable &= s.decodable;
@@ -1501,6 +1668,7 @@ fn add_shown(lines: &mut Vec<TextLine>, last: &mut Option<Pen>, s: Shown, stream
actual_text: s.actual_text,
clips: s.state.render_mode >= 4,
unreadable_mode: s.state.unreadable.as_deref().map(str::to_owned),
runs: vec![(s.text.clone(), s.ink.len(), false)],
ops: std::iter::once(s.op).chain(s.extra_ops.iter().copied()).collect(),
origin: Origin {
tm: s.tm.0,
@@ -1681,7 +1849,11 @@ fn reading_lines(doc: &Document, page: usize) -> Result<(Vec<TextLine>, bool), E
let mut lines = w.lines;
// A visual-order Indic font draws pre-base vowel signs before their consonant.
for l in lines.iter_mut().filter(|l| l.visual_order && !l.actual_text) {
let shown = l.text.clone();
l.text = crate::indic::to_logical(&l.text);
if l.text != shown {
l.runs.clear();
}
}
lines.retain(|l| !l.text.trim().is_empty());
Ok((lines, w.budget.truncated))
@@ -1817,6 +1989,24 @@ fn same_font(line: &TextLine, font: &[u8], base_font: &str, face: Option<&str>)
line.font.as_bytes() == font || same_base_font(&line.base_font, base_font) || (line.face.is_some() && line.face.as_deref() == face)
}
/// Whether a run painted with `ts` continues `line` as it is painted: a line is rewritten in the
/// state of its first run, so a `Tr`, stroke colour or line width that changes partway starts
/// another run (see [`TextState::paint_ops`]; the `gs` parameters are compared as [`Paint`]).
/// The stroke colour, width, dash and cap only count for text that is stroked, so a rule drawn
/// between two words doesn't split their line. They are compared as values, wherever they were
/// set: two ExtGStates with the same settings under other names still continue a line.
///
/// Only the visible modes (`Tr` 0–2) that `paint_ops` restates are compared: a line that goes on
/// as invisible or clipping text stays one line, which the clipping refusal reads whole (#3447).
fn same_paint(line: &TextLine, ts: &Ts) -> bool {
let a = &line.origin.state;
let visible = |m: i64| (0..=2).contains(&m);
let same_mode = a.render_mode == ts.render_mode || !visible(a.render_mode) || !visible(ts.render_mode);
let stroked = matches!((a.render_mode, ts.render_mode), (1 | 2, 1 | 2));
let outline = a.stroke == ts.stroke && a.line_width == ts.line_width && a.dash == ts.dash && a.line_cap == ts.line_cap;
same_mode && (!stroked || outline)
}
/// Whether two `/BaseFont` names name the same font: a subset's six-letter tag and `+` prefix do
/// not change the font (ISO 32000-2 §9.6.4), so `ABCDEF+Arial` and `GHIJKL+Arial` are one font.
/// A name that is missing, or only a tag (`ABCDEF+`), names no font and matches nothing.
@@ -1845,8 +2035,6 @@ fn source_family(base_font: &str) -> crate::added::Family {
}
}
const SUBSTITUTE_NAME: &str = "PCEdHelv";
const SUBSTITUTE: &[u8] = SUBSTITUTE_NAME.as_bytes();
const MAX_TYPE3_GLYPHS: usize = 240;
/// The generated fonts for one replacement: one per run of at most `max_glyphs` unique characters,
@@ -2064,6 +2252,19 @@ fn type3_font(
.map_err(|_| EditError::Invalid("replacement text has too many unique characters".into()))?;
glyphs.push(Type3Glyph { code, ch, path, width });
}
Ok(write_type3_glyphs(doc, fonts_res, face, hebrew, glyphs, per_font))
}
/// Write already validated outlines; callers can prepare every face before adding any objects.
fn write_type3_glyphs(
doc: &mut Document,
fonts_res: &mut Dict,
face: &CraftFont,
hebrew: bool,
glyphs: Vec<Type3Glyph>,
per_font: usize,
) -> Type3Fallback {
let per_font = per_font.clamp(1, MAX_TYPE3_GLYPHS);
let mut codes = HashMap::with_capacity(glyphs.len());
let mut widths = Vec::with_capacity(glyphs.len());
let mut names = Vec::new();
@@ -2079,7 +2280,7 @@ fn type3_font(
}
names.push(add_type3_font(doc, fonts_res, face, hebrew, group));
}
Ok(Type3Fallback { family: face.family, names, widths, codes })
Type3Fallback { family: face.family, names, widths, codes }
}
/// Adds one generated font whose codes 1 to `glyphs.len()` show `glyphs`, and returns its resource
@@ -2565,20 +2766,28 @@ fn paragraph_separator(c: char) -> bool {
/// Greedy word wrapping to `width` with `advance` giving a string's width. Each `\n` starts a
/// new line. A row may also end inside a word of Chinese or Japanese text ([`crate::linebreak`]);
/// those pieces join without a space.
/// those pieces join without a space. Every white-space character is written as one space, so
/// a run of spaces typed between, before or after words stays (#4199); only the spaces where a
/// row wraps are dropped.
fn wrap(text: &str, width: f64, advance: impl Fn(&str) -> f64) -> Vec<String> {
let mut out = Vec::new();
for row in text.split('\n') {
let mut line = String::new();
let start = out.len();
for word in row.split(paragraph_separator).filter(|word| !word.is_empty()) {
// The separators read since the last word: each one boundary between `split` pieces.
let mut gap = 0usize;
for (k, word) in row.split(paragraph_separator).enumerate() {
if k > 0 {
gap = gap.saturating_add(1);
}
if word.is_empty() {
continue;
}
let spaces = " ".repeat(std::mem::take(&mut gap));
for (i, piece) in crate::linebreak::pieces(word).into_iter().enumerate() {
let candidate = match (line.is_empty(), i) {
(true, _) => piece.to_string(),
(false, 0) => format!("{line} {piece}"),
(false, _) => format!("{line}{piece}"),
};
if !line.is_empty() && advance(&candidate) > width {
let candidate = if i == 0 { format!("{line}{spaces}{piece}") } else { format!("{line}{piece}") };
// A row holding only the spaces that indent it doesn't wrap before its first word.
if line.chars().any(|c| c != ' ') && advance(&candidate) > width {
out.push(std::mem::take(&mut line));
line = piece.to_string();
} else {
@@ -2586,6 +2795,7 @@ fn wrap(text: &str, width: f64, advance: impl Fn(&str) -> f64) -> Vec<String> {
}
}
}
line.push_str(&" ".repeat(gap));
if !line.is_empty() || out.len() == start {
out.push(line);
}
@@ -2707,7 +2917,8 @@ fn rewrite_block_from(
&& (!style.ranges.is_empty()
|| style.resource.is_some()
|| (text.is_some_and(|draft| {
draft.contains('\n')
// A row break, `\n` or a carriage return, takes the path that keeps untouched rows.
draft.contains(['\n', '\r'])
|| pdfcraft_fonts::source_shaping::required(draft)
|| !pdfcraft_fonts::embedding::matching_faces(&b.base_font).is_empty()
}) || registered_face
@@ -2717,18 +2928,24 @@ fn rewrite_block_from(
&& style.family.is_none()
&& style.bold.is_none())
{
return rewrite_styled_block(doc, page, &b, &lines, text, style);
return rewrite_styled_block(doc, page, &b, &lines, text, style, max_glyphs);
}
let streams = content_streams(doc, &p.dict)?;
let pieces = Pieces::join(&streams.iter().map(|(_, d)| d.as_slice()).collect::<Vec<_>>());
let ops = pieces.parse().ops;
// Explicit line breaks stay (#1443); within a line, runs of white space become one space.
let text = text
// Explicit line breaks stay (#1443), and so does each typed U+0020 space: a run of them is
// not folded into one (#4199, #3797). `\r\n` and a lone `\r` are breaks too; other white
// space is written as one space.
let text: String = text
.unwrap_or(&b.text)
.split('\n')
.map(|row| row.split(paragraph_separator).filter(|word| !word.is_empty()).collect::<Vec<_>>().join(" "))
.collect::<Vec<_>>()
.join("\n");
.replace("\r\n", "\n")
.chars()
.map(|c| match c {
'\r' => '\n',
c if c != '\n' && paragraph_separator(c) => ' ',
c => c,
})
.collect();
// The characters to show, for choosing fonts: the breaks are moves, not glyphs.
let flat = text.replace('\n', " ");
let o = &first.origin;
@@ -2883,7 +3100,9 @@ fn rewrite_block_from(
f.set(b"Subtype".to_vec(), Object::name("Type1"));
f.set(b"BaseFont".to_vec(), Object::name(base));
f.set(b"Encoding".to_vec(), Object::name("WinAnsiEncoding"));
let name = if style.family.is_none() { String::from_utf8_lossy(SUBSTITUTE).into_owned() } else { format!("PCEd{}", base.replace('-', "")) };
// Named after its face, as the line and region rewrites name theirs: one name for every
// stand-in would repoint the paragraphs set in an earlier one at this face (#4280).
let name = format!("PCEd{}", base.replace('-', ""));
fonts_res.set(name.clone().into_bytes(), Object::Dict(f));
if style.family.is_none() {
substituted = Some(base.to_string());
@@ -2908,6 +3127,21 @@ fn rewrite_block_from(
None => size * 1.2,
};
let n = pdfcraft_content::num;
// The paragraph's operators go, and so does another drawing on the same baseline (a fake-bold
// second copy, an invisible text layer): the new text is all that may show.
let drop = dropped;
// Text shown earlier in the same text object stays first: the paragraph then goes where its
// last row was, after any backgrounds between the rows, or between two halves of the text object.
let start = last.ops.first().copied().unwrap_or(emit.bt_op);
let split = ops
.get(emit.bt_op..start)
.unwrap_or_default()
.iter()
.enumerate()
.any(|(i, op)| matches!(op.op.as_slice(), b"Tj" | b"TJ" | b"'" | b"\"") && !drop.contains(&(emit.bt_op + i)));
// What the text after the paragraph expects, and what is in force where the paragraph is
// drawn: the state at its BT (or where it was split).
let after = if split { &emit.state } else { &emit.bt_state };
// In its own graphics state, so a new colour (or anything else) stops at the paragraph.
let mut block_ops = vec![Op::new("q", vec![])];
block_ops.extend(reveal_ops(&b, &lines, style, emit.ctm)?);
@@ -2915,6 +3149,8 @@ fn rewrite_block_from(
if let Some((ax, ay)) = movement {
block_ops.push(Op::new("cm", vec![n(1.0), n(0.0), n(0.0), n(1.0), n(ax), n(ay)]));
}
// Painted as the paragraph was, including what its text object set before the first show.
block_ops.extend(o_state.paint_ops(after));
block_ops.push(Op::new("BT", vec![]));
let mut state = o_state.clone();
state.word_spacing = 0.0;
@@ -2927,12 +3163,13 @@ fn rewrite_block_from(
block_ops.extend(state.ops());
block_ops.push(Op::new("Tm", tm.iter().map(|v| n(*v)).collect()));
// Alignment: each line's offset from the left edge, in text space.
let offset = |line: &str| -> f64 {
let free = (width - advance(line)).max(0.0) / k;
// `visible` is the width the line is aligned on (see the loop below).
let offset = |visible: f64| -> f64 {
let free = (width - visible).max(0.0) / k;
match align {
Some(crate::added::Align::Center) => free / 2.0,
// A right-to-left line anchored at its right edge may start left of the old box.
Some(crate::added::Align::Right) if anchored_right => (right_edge - advance(line)) / k,
Some(crate::added::Align::Right) if anchored_right => (right_edge - visible) / k,
Some(crate::added::Align::Right) => free,
// A justified right-to-left paragraph ends its last line at the right edge.
Some(crate::added::Align::Justify) if rtl => free,
@@ -2952,11 +3189,29 @@ fn rewrite_block_from(
let mut tw_set = 0.0;
let mut underlines: Vec<(f64, f64, f64)> = Vec::new(); // (x0, x1, y) in text space
for (i, line) in wrapped.iter().enumerate() {
let spaces = line.matches(' ').count();
let tw =
if justify && i + 1 < wrapped.len() && spaces > 0 { (width - advance(line)).max(0.0) / k / o_state.scale / spaces as f64 } else { 0.0 };
// A stretched line fills the width from the left edge.
let dx = if tw > 0.0 { 0.0 } else { offset(line) };
// A stretched (justified) line shows only its words, as before #4199: word spacing would
// reach the spaces before its first word and after its last, so they are left out, and
// the line fills the width from the left edge. Nothing to stretch over, or a paragraph
// drawn at `0 Tz`, isn't justified.
let body = line.trim_matches(' ');
let interior = body.matches(' ').count();
let tw = if justify && i + 1 < wrapped.len() && interior > 0 && o_state.scale.abs() > 1e-6 {
Some((width - advance(body)).max(0.0) / k / o_state.scale / interior as f64).filter(|tw| tw.is_finite())
} else {
None
}
.unwrap_or(0.0);
// Other lines show every space typed. A left-to-right one is aligned on its width up to
// its last word; a right-to-left one on its whole width, since the spaces typed after its
// last word are drawn on its left and the ones before its first on its right.
let (shown, visible) = if tw > 0.0 {
(body, advance(body))
} else if crate::bidi::rtl_base(line) {
(line.as_str(), advance(line))
} else {
(line.as_str(), advance(line.trim_end_matches(' ')))
};
let dx = if tw > 0.0 { 0.0 } else { offset(visible) };
if i > 0 || dx != 0.0 {
block_ops.push(Op::new("Td", vec![n(dx - x), n(if i > 0 { -lead } else { 0.0 })]));
}
@@ -2968,7 +3223,7 @@ fn rewrite_block_from(
tw_set = tw;
}
// Each wrapped line in typing order; drawn left to right (right-to-left runs reversed).
let visual = crate::bidi::to_visual(line);
let visual = crate::bidi::to_visual(shown);
// Stretched without word spacing: shown up to and including each space, then moved on.
let pieces = if stretch > 0.0 { visual.split_inclusive(' ').collect() } else { vec![visual.as_str()] };
for piece in pieces {
@@ -2989,7 +3244,8 @@ fn rewrite_block_from(
}
}
let tw = tw + stretch;
let w = (advance(line) + tw * spaces as f64 * o_state.scale * k) / k;
// Underlined to the line's last word, over its stretched gaps.
let w = (visible + tw * interior as f64 * o_state.scale * k) / k;
underlines.push((dx, dx + w, -(i as f64) * lead - size * 0.12));
}
block_ops.push(Op::new("ET", vec![]));
@@ -3019,21 +3275,6 @@ fn rewrite_block_from(
block_ops.push(Op::new("Q", vec![]));
}
block_ops.push(Op::new("Q", vec![]));
// The paragraph's operators go, and so does another drawing on the same baseline (a fake-bold
// second copy, an invisible text layer): the new text is all that may show.
let mut drop = coincident_ops(&lines, &members);
drop.extend(members.iter().flat_map(|l| l.ops.iter().copied()));
// Text shown earlier in the same text object stays first: the paragraph then goes where its
// last row was, after any backgrounds between the rows, or between two halves of the text object.
let start = last.ops.first().copied().unwrap_or(emit.bt_op);
let split = ops
.get(emit.bt_op..start)
.unwrap_or_default()
.iter()
.enumerate()
.any(|(i, op)| matches!(op.op.as_slice(), b"Tj" | b"TJ" | b"'" | b"\"") && !drop.contains(&(emit.bt_op + i)));
// What the text after the paragraph expects: the state at its BT (or where it was split).
let after = if split { &emit.state } else { &emit.bt_state };
block_ops.extend(after.ops().into_iter().filter(|op| !op.is("Tf") || after.font.is_some()));
if split {
block_ops.insert(0, Op::new("ET", vec![]));
@@ -3355,7 +3596,23 @@ mod tests {
assert_eq!(wrap("A  B C", 4.0, width), ["A  B", "C"]);
assert_eq!(wrap("A\u{a0}B C", 3.0, width), ["A B", "C"]);
assert_eq!(wrap("A\u{2028}B C", 3.0, width), ["A B", "C"]);
assert_eq!(wrap(" \tA B\r\nC ", 3.0, width), ["A B", "C"]);
}
/// #4199: a run of spaces stays a run, before, between and after words; the spaces where a
/// row wraps go, and each other white-space character is one space.
#[test]
fn paragraph_wrapping_keeps_every_space_typed() {
let width = |s: &str| s.chars().count() as f64;
assert_eq!(wrap("a b c", 20.0, width), ["a b c"]);
assert_eq!(wrap(" a b ", 20.0, width), [" a b "]);
assert_eq!(wrap("a\t\tb", 20.0, width), ["a b"]);
assert_eq!(wrap("aa bb cc", 6.0, width), ["aa bb", "cc"]);
// An indent alone on a row doesn't wrap before its first word.
assert_eq!(wrap(" abc", 3.0, width), [" abc"]);
// The rewrite turns `\r\n` and `\r` into `\n` before wrapping.
assert_eq!(wrap(" \tA B\nC ", 3.0, width), [" A", "B", "C "]);
assert_eq!(wrap(" ", 3.0, width), [" "]);
assert_eq!(wrap("", 3.0, width), [""]);
}
#[test]
+104 -32
View File
@@ -2,6 +2,18 @@
use super::*;
// The draft is capped at 4 MiB; also bound the outline data prepared across all fallback faces.
// A glyph budget worth 64 full batches (15,360 glyphs with the production batch size).
// Lowering the internal batch size for tests lowers the budget by the same ratio.
const MAX_STYLED_FALLBACK_BATCHES: usize = 64;
struct FallbackGroup {
face: &'static CraftFont,
seen: std::collections::HashSet<char>,
glyphs: Vec<Type3Glyph>,
positions: Vec<usize>,
}
fn same_plane(a: &TextLine, b: &TextLine) -> bool {
let at = Matrix(a.origin.tm).then(&Matrix(a.origin.ctm));
let bt = Matrix(b.origin.tm).then(&Matrix(b.origin.ctm));
@@ -166,8 +178,8 @@ fn opens_with_marker(text: &str) -> bool {
if !first.is_ascii_digit() && !first.is_ascii_alphabetic() {
return false;
}
let digits = text.chars().take_while(|c| c.is_ascii_digit()).count();
let letters = text.chars().take_while(|c| c.is_ascii_alphabetic()).count();
let digits = text.chars().take_while(char::is_ascii_digit).count();
let letters = text.chars().take_while(char::is_ascii_alphabetic).count();
// Both runs are ASCII characters, so their length in characters is their length in bytes:
// the slice below starts on a character boundary.
let rest = if digits > 0 {
@@ -178,7 +190,7 @@ fn opens_with_marker(text: &str) -> bool {
return false;
};
let mut after = rest.chars();
matches!(after.next(), Some('.' | ')')) && after.next().is_none_or(|c| c.is_whitespace())
matches!(after.next(), Some('.' | ')')) && after.next().is_none_or(char::is_whitespace)
}
/// A row that opens with a list marker opens its own item: joining it to the row above is what
@@ -400,6 +412,7 @@ pub(super) fn rewrite_styled_block(
lines: &[TextLine],
text: Option<&str>,
style: &BlockStyle,
max_glyphs: usize,
) -> Result<LineEdit, EditError> {
let first = block.lines.first().and_then(|i| lines.get(*i)).ok_or_else(|| EditError::Invalid("the paragraph has no source runs".into()))?;
let draft = match text {
@@ -542,16 +555,29 @@ pub(super) fn rewrite_styled_block(
// Each tuple is a character, its source style and an encodable resource name.
let mut chars = Vec::new();
let mut substituted = None;
let mut fallback_names: std::collections::BTreeMap<(String, char), String> = std::collections::BTreeMap::new();
let mut fallback_groups: Vec<FallbackGroup> = Vec::new();
let mut fallback_names: std::collections::BTreeMap<(String, bool, char), usize> = std::collections::BTreeMap::new();
let mut fallback_glyphs = 0_usize;
let per_font = max_glyphs.clamp(1, MAX_TYPE3_GLYPHS);
let fallback_budget = per_font.saturating_mul(MAX_STYLED_FALLBACK_BATCHES);
let mut full_faces: HashMap<String, String> = HashMap::new();
let mut programs: HashMap<String, Option<std::sync::Arc<Vec<u8>>>> = HashMap::new();
for (range, index) in styled_spans {
let source = lines.get(index).unwrap_or(first);
for ch in draft.get(range).unwrap_or_default().chars() {
let start = range.start;
for (offset, ch) in draft.get(range).unwrap_or_default().char_indices() {
if ch == '\n' {
chars.push((ch, index, source.font.clone()));
continue;
}
// A carriage return breaks the row too. Before `\n` the pair is one break, so the
// CR stays a `\r` the rows skip. Either way it keeps its place among the draft's
// characters, which rows are counted in.
if ch == '\r' {
let crlf = start.checked_add(offset).and_then(|at| draft.get(at.saturating_add(1)..)).is_some_and(|rest| rest.starts_with('\n'));
chars.push((if crlf { '\r' } else { '\n' }, index, source.font.clone()));
continue;
}
let s = ch.to_string();
let name = if let Some(resource) = overrides.get(&index).and_then(|r| r.resource.as_ref()).or(style.resource.as_ref()) {
if !metrics.get(resource).is_some_and(|m| source_encodes(m, &s)) {
@@ -605,24 +631,40 @@ pub(super) fn rewrite_styled_block(
} else {
let family = source_family(&source.base_font);
if needs_type3(&s) {
let key = (source.base_font.rsplit('+').next().unwrap_or(&source.base_font).to_owned(), ch);
if let Some(name) = fallback_names.get(&key) {
chars.push((ch, index, name.clone()));
continue;
let key = (source.base_font.clone(), source.bold, ch);
let group_index = if let Some(index) = fallback_names.get(&key) {
*index
} else {
// Keep the old per-character face choice: a serif Japanese character
// and a Cyrillic character may need different faces even in one style.
// Hebrew uses the separate RTL path before reaching this writer.
let (faces, _) = type3_faces(&s, family, source.bold)?;
let face =
fallback_face(&faces, &[ch], |face, ch| japanese_glyph_from(face, ch).is_ok()).ok_or_else(|| no_fallback_font(&s))?;
let index = fallback_groups.iter().position(|group| std::ptr::eq(group.face, face)).unwrap_or_else(|| {
let index = fallback_groups.len();
fallback_groups.push(FallbackGroup { face, seen: Default::default(), glyphs: Vec::new(), positions: Vec::new() });
index
});
fallback_names.insert(key, index);
index
};
let group = fallback_groups.get_mut(group_index).ok_or_else(|| EditError::Invalid("the fallback face is missing".into()))?;
if group.seen.insert(ch) {
if fallback_glyphs >= fallback_budget {
return Err(EditError::Invalid(format!(
"the replacement needs more than {fallback_budget} fallback glyphs; edit a smaller paragraph or load a complete font"
)));
}
let (path, width) = type3_glyph(group.face, ch)?.ok_or_else(|| no_glyph_for(group.face, ch))?;
let code = u8::try_from((group.glyphs.len() % per_font).saturating_add(1))
.map_err(|_| EditError::Invalid("replacement text has too many unique characters".into()))?;
group.glyphs.push(Type3Glyph { code, ch, path, width });
fallback_glyphs = fallback_glyphs.saturating_add(1);
}
if fallback_names.len() >= MAX_TYPE3_GLYPHS {
return Err(EditError::Invalid("the replacement has too many fallback glyphs".into()));
}
let fallback = type3_font(doc, &mut fonts, &s, family, source.bold, MAX_TYPE3_GLYPHS)?;
let name = fallback.names.first().cloned().ok_or_else(no_japanese_font)?;
let dict = fonts
.get(name.as_bytes())
.and_then(|f| doc.resolve(f).as_dict().cloned())
.ok_or_else(|| EditError::Invalid("the fallback font could not be loaded".into()))?;
metrics.insert(name.clone(), Metrics::from_dict(doc, &dict));
substituted = Some(fallback.family.to_string());
fallback_names.insert(key, name.clone());
name
group.positions.push(chars.len());
// Filled from the prepared font/code map before measuring or drawing.
String::new()
} else {
let base = family.base_font(source.bold, source.italic);
let name = format!("PCEd{}", base.replace('-', ""));
@@ -640,6 +682,24 @@ pub(super) fn rewrite_styled_block(
chars.push((ch, index, name));
}
}
// All fallback outlines have now succeeded. Batch by actual face, preserving source
// style indices; the existing writer then coalesces adjacent equal-font/style characters.
for group in fallback_groups {
let fallback = write_type3_glyphs(doc, &mut fonts, group.face, false, group.glyphs, per_font);
for name in &fallback.names {
let font = fonts
.get(name.as_bytes())
.and_then(|f| doc.dict(f))
.ok_or_else(|| EditError::Invalid("the fallback font could not be loaded".into()))?;
metrics.insert(name.clone(), Metrics::from_dict(doc, &font));
}
for position in group.positions {
let item = chars.get_mut(position).ok_or_else(|| EditError::Invalid("the fallback character is missing".into()))?;
let (font, _) = fallback.codes.get(&item.0).ok_or_else(|| EditError::Invalid("the fallback glyph is missing".into()))?;
item.2 = fallback.names.get(*font).cloned().ok_or_else(|| EditError::Invalid("the fallback font is missing".into()))?;
}
substituted = Some(fallback.family.to_owned());
}
let size_of = |source: &TextLine, index: usize| {
overrides.get(&index).and_then(|r| r.size).or(style.size).unwrap_or(source.size).max(0.1) / source.origin.k.max(1e-6)
};
@@ -735,6 +795,11 @@ pub(super) fn rewrite_styled_block(
let mut at = 0;
while at < chars.len() {
let Some(item) = chars.get(at) else { break };
// The CR of a CRLF: the `\n` after it breaks the row.
if item.0 == '\r' {
at += 1;
continue;
}
if item.0 == '\n' {
row_ranges.push(row_start..row_start + row.len());
rows.push(std::mem::take(&mut row));
@@ -800,6 +865,17 @@ pub(super) fn rewrite_styled_block(
}
};
let o = &lead.origin;
let mut drop = coincident_ops(lines, &members);
drop.extend(members.iter().flat_map(|l| l.ops.iter().copied()));
let start = lead.ops.first().copied().unwrap_or(o.bt_op);
let split = ops
.get(o.bt_op..start)
.unwrap_or_default()
.iter()
.enumerate()
.any(|(i, op)| matches!(op.op.as_slice(), b"Tj" | b"TJ" | b"'" | b"\"") && !drop.contains(&(o.bt_op + i)));
// What is in force where the rewrite is drawn, and what the text after it expects.
let after = if split { &o.state } else { &o.bt_state };
for (row, _) in rows.iter().zip(&kept).filter(|(_, k)| !**k) {
let text: String = row.iter().map(|v| v.0).collect();
if pdfcraft_fonts::source_shaping::required(&text) && row.first().is_some_and(|first| row.iter().any(|v| v.1 != first.1 || v.2 != first.2)) {
@@ -910,6 +986,11 @@ pub(super) fn rewrite_styled_block(
tm[4] += ax;
tm[5] += ay;
let mut segment_width = segment_advances.get(&(row_index, pos)).copied().unwrap_or(0.0);
// Each run in its own graphics state, restating what its source set inside its text
// object (`gs`, stroke, line width, `Tr`; #3508/#3509) from the state the rewrite is
// drawn in: a `gs` has no inverse, so one run's ExtGState would stay for the next.
block_ops.push(Op::new("q", vec![]));
block_ops.extend(state.paint_ops(after));
if let Some((_, shaped, _)) = shaped_runs.get(&(row_index, pos)) {
let resource = glyph_resources.get(&(row_index, pos)).ok_or_else(|| EditError::Invalid("shaped font is missing".into()))?;
let mut properties = Dict::new();
@@ -996,6 +1077,7 @@ pub(super) fn rewrite_styled_block(
block_ops.push(Op::new("l", vec![n(x1), n(y1)]));
block_ops.push(Op::new("S", vec![]));
}
block_ops.push(Op::new("Q", vec![]));
x += segment_width;
pos = end;
}
@@ -1006,16 +1088,6 @@ pub(super) fn rewrite_styled_block(
};
}
block_ops.push(Op::new("Q", vec![]));
let mut drop = coincident_ops(lines, &members);
drop.extend(members.iter().flat_map(|l| l.ops.iter().copied()));
let start = lead.ops.first().copied().unwrap_or(o.bt_op);
let split = ops
.get(o.bt_op..start)
.unwrap_or_default()
.iter()
.enumerate()
.any(|(i, op)| matches!(op.op.as_slice(), b"Tj" | b"TJ" | b"'" | b"\"") && !drop.contains(&(o.bt_op + i)));
let after = if split { &o.state } else { &o.bt_state };
block_ops.extend(after.ops());
if split {
block_ops.insert(0, Op::new("ET", vec![]));
+8
View File
@@ -16,6 +16,14 @@ Two frontends exist on top of it today: `pdfcraft-ui-egui` (desktop and web) and
`pdfcraft-automation` (headless tools, the CLI and MCP). Anything one can do, the other must be
able to do — see AGENTS.md §3.
When dynamic XFA layout is active, `JsRunner` does not initialize Acrobat JavaScript with
scripts from the PDF container's `/Names /JavaScript` tree. Those scripts belong to the
fallback PDF view and can otherwise show a misleading viewer-compatibility warning.
They remain in the document and in `Document::document_scripts`. Requested console scripts,
field actions and XFA events can still show messages; ordinary PDFs, static XFA and shells
without an active layout keep their document scripts. Converting XFA to a static form and
undoing that conversion switches the context with the document state.
## The editing model
Each open document holds a `pdfcraft_cos::Document`: the object graph plus a copy-on-write overlay.
+30 -24
View File
@@ -311,6 +311,35 @@ fn refine(q: [Point; 4], edges: &[Option<Edge>], w: usize, h: usize) -> Option<[
order_quad(refined)
}
/// A candidate quad's score (its area times the square of its sides' mean support), or `None` when it
/// strays off the image, is too small, or has a side without enough edge support.
fn quad_score(q: &[Point; 4], edges: &[Option<Edge>], w: usize, h: usize) -> Option<f64> {
let (fw, fh) = (w as f64, h as f64);
let (mx, my) = (MARGIN * fw, MARGIN * fh);
if q.iter().any(|p| p[0] < -mx || p[1] < -my || p[0] > fw + mx || p[1] > fh + my) {
return None;
}
let area = (0..4)
.map(|k| {
let (p, n) = (q[k], q[(k + 1) % 4]);
p[0] * n[1] - n[0] * p[1]
})
.sum::<f64>()
.abs()
/ 2.0;
if area < MIN_AREA * fw * fh {
return None;
}
let sides: Vec<f64> = (0..4).map(|k| support(q[k], q[(k + 1) % 4], edges, w, h)).collect();
if sides.iter().any(|&s| s < MIN_SUPPORT) {
return None;
}
// Large, and with every side on its edge: a slightly larger quad with a side
// off the sheet loses to the sheet itself.
let mean = sides.iter().sum::<f64>() / 4.0;
Some(area * mean * mean)
}
/// The convex quadrilateral of two near-horizontal and two near-vertical lines whose four sides
/// all lie on edges, scored by its area times the square of its sides' mean support.
fn best_quad(lines: &[Line], edges: &[Option<Edge>], w: usize, h: usize) -> Option<[Point; 4]> {
@@ -318,8 +347,6 @@ fn best_quad(lines: &[Line], edges: &[Option<Edge>], w: usize, h: usize) -> Opti
let flat = |l: &&Line| (l.theta.to_degrees() - 90.0).abs() <= 45.0;
let horizontal: Vec<&Line> = lines.iter().filter(flat).collect();
let vertical: Vec<&Line> = lines.iter().filter(|l| !flat(l)).collect();
let (fw, fh) = (w as f64, h as f64);
let (mx, my) = (MARGIN * fw, MARGIN * fh);
let mut best: Option<(f64, [Point; 4])> = None;
for (i, &h1) in horizontal.iter().enumerate() {
for &h2 in horizontal.iter().skip(i + 1) {
@@ -328,28 +355,7 @@ fn best_quad(lines: &[Line], edges: &[Option<Edge>], w: usize, h: usize) -> Opti
let corners = [intersect(*h1, *v1), intersect(*h1, *v2), intersect(*h2, *v2), intersect(*h2, *v1)];
let [Some(a), Some(b), Some(c), Some(d)] = corners else { continue };
let Some(q) = order_quad([a, b, c, d]) else { continue };
if q.iter().any(|p| p[0] < -mx || p[1] < -my || p[0] > fw + mx || p[1] > fh + my) {
continue;
}
let area = (0..4)
.map(|k| {
let (p, n) = (q[k], q[(k + 1) % 4]);
p[0] * n[1] - n[0] * p[1]
})
.sum::<f64>()
.abs()
/ 2.0;
if area < MIN_AREA * fw * fh {
continue;
}
let sides: Vec<f64> = (0..4).map(|k| support(q[k], q[(k + 1) % 4], edges, w, h)).collect();
if sides.iter().any(|&s| s < MIN_SUPPORT) {
continue;
}
// Large, and with every side on its edge: a slightly larger quad with a side
// off the sheet loses to the sheet itself.
let mean = sides.iter().sum::<f64>() / 4.0;
let score = area * mean * mean;
let Some(score) = quad_score(&q, edges, w, h) else { continue };
if best.is_none_or(|(b, _)| score > b) {
best = Some((score, q));
}
+1 -1
View File
@@ -147,7 +147,7 @@ pub static TOOL_GROUPS: &[ToolGroup] = &[
item("Link", "link-2", "edit.link", Ready),
item("Bates numbering", "hash", "edit.bates", Ready),
menu_item("Background", "palette", &["edit.background", "edit.background.update", "edit.background.remove"]),
item("Attach file", "paperclip", "edit.attach", Planned("M12")),
item("Attach file", "paperclip", "edit.attach", Ready),
],
},
],
+1
View File
@@ -282,6 +282,7 @@ pub const COMMANDS: &[CommandSpec] = &[
c("edit.text", "Add text", None, None, Modification, "type"),
c("edit.edit_text", "Edit text & images", None, None, Modification, "text-cursor-input"),
c("edit.link", "Add or edit links", None, None, Modification, "link-2"),
c("edit.attach", "Attach a file…", EDIT, None, Modification, "paperclip"),
c("edit.links_from_urls", "Create links from URLs", None, None, Modification, "link-2"),
c("edit.remove_links", "Remove all links", None, None, Modification, "trash-2"),
c("edit.bates", "Add Bates numbering…", None, None, Modification, "hash"),
+51
View File
@@ -59,6 +59,57 @@ impl Document {
let rgba = image::DynamicImage::from_decoder(decoder).map_err(|e| e.to_string())?.into_rgba8();
Ok((rgba.width(), rgba.height(), rgba.into_raw()))
}
/// Edit ▸ Copy of an added image (`index` among `page`'s added items): its picture as a file
/// (extension, bytes), a JPEG or JPEG 2000 file as stored, otherwise a lossless PNG, for
/// [`Edit::PasteContent`](crate::Edit::PasteContent). Refused when the document doesn't allow
/// copying.
pub fn added_image_file(&self, page: usize, index: usize) -> Result<(&'static str, Vec<u8>), String> {
self.check_copying().map_err(|e| e.to_string())?;
let editor = self.editor.as_ref().ok_or("the document can't be read")?;
let item = self.added().iter().filter(|a| a.page == page).nth(index);
let Some(pdfcraft_edit::Content::Image(img)) = item.map(|a| &a.content) else {
return Err(format!("item {} on page {} is not an added image", index + 1, page + 1));
};
picture_file(&editor.cos, img.image)
}
}
/// An added image's picture as a file: [`pdfcraft_create::image_file`], except that a JPEG 2000
/// picture, which Add Image stores as the file it was given, is that file.
fn picture_file(cos: &Cos, image: ObjRef) -> Result<(&'static str, Vec<u8>), String> {
match &*cos.get(image) {
Object::Stream(s) if s.dict.name(b"Subtype") == Some(b"Image") && s.dict.name(b"Filter") == Some(b"JPXDecode") => Ok(("jp2", s.raw.to_vec())),
_ => pdfcraft_create::image_file(cos, image),
}
}
/// Whether image object `image` in `cos` is the picture `file` (as [`picture_file`] writes it).
/// The sizes are compared first, so an unrelated image is not re-encoded to find out.
pub(crate) fn is_picture(cos: &Cos, image: ObjRef, file: &[u8]) -> bool {
let size = |s: &pdfcraft_cos::Stream| Some((u32::try_from(s.dict.int(b"Width")?).ok()?, u32::try_from(s.dict.int(b"Height")?).ok()?));
// The object at that number now, not one of an earlier generation of it.
if cos.generation(image.num) != image.generation {
return false;
}
let stored = match &*cos.get(image) {
// A JPEG 2000 picture is stored as its file.
Object::Stream(s) if s.dict.name(b"Subtype") == Some(b"Image") && s.dict.name(b"Filter") == Some(b"JPXDecode") => return s.raw[..] == *file,
Object::Stream(s) if s.dict.name(b"Subtype") == Some(b"Image") => size(s),
_ => return false,
};
let given = image::ImageReader::new(std::io::Cursor::new(file)).with_guessed_format().ok().and_then(|r| r.into_dimensions().ok());
stored.is_some() && stored == given && picture_file(cos, image).is_ok_and(|(_, data)| data == file)
}
/// The image object an added image in `cos` already draws picture `file` from, if any: where a
/// second paste from another document finds the first one's.
pub(crate) fn added_picture(cos: &Cos, file: &[u8]) -> Option<ObjRef> {
let mut seen = std::collections::HashSet::new();
pdfcraft_edit::list_added(cos).into_iter().find_map(|a| match a.content {
pdfcraft_edit::Content::Image(img) if seen.insert(img.image) && is_picture(cos, img.image, file) => Some(img.image),
_ => None,
})
}
/// The largest raster image Form `form` draws through its resources (nested Forms included).
+82 -17
View File
@@ -7,7 +7,7 @@
//! off, scripts don't run and AF calls keep working natively.
use pdfcraft_forms::{Field, FieldChange, FieldEvent, FieldKind, FieldProps, ScriptResult, Scripts};
pub use pdfcraft_js::{Limits, Outcome, Request};
pub use pdfcraft_js::{Limits, Outcome, Panel, Request};
use crate::{DocId, Edit, EditError, Session};
@@ -19,25 +19,63 @@ pub struct JsOutput {
pub requests: Vec<Request>,
/// Script errors (as Acrobat's console shows them).
pub errors: Vec<String>,
/// Which of `errors` are document scripts' (#3940), told apart by where they came from and
/// not by their text, which a field script's error can share: each is reported once, however
/// often the document scripts run again.
pub doc_errors: Vec<String>,
}
impl JsOutput {
/// Whether scripts produced nothing: no alerts, console lines, requests or errors.
pub fn is_empty(&self) -> bool {
self.alerts.is_empty() && self.console.is_empty() && self.requests.is_empty() && self.errors.is_empty()
}
/// Adds what a field's own script produced: its alerts, console lines, errors and requests,
/// except a request to show a side panel or open Save As, which is noted on the console
/// and dropped.
fn absorb(&mut self, o: &Outcome) {
self.alerts.extend(o.alerts.iter().cloned());
self.console.extend(o.console.iter().cloned());
self.requests.extend(o.requests.iter().cloned());
// A field's own scripts (keystroke, format, validate, calculate) run unasked: only a
// button's may show or hide a side panel, or open Save As.
for r in &o.requests {
match r {
Request::ShowPanel(_) => self.console.push("A field script asked to show a side panel; only a button may show a side panel".into()),
Request::SaveAs => {
self.console.push("A field script asked to save the document as a new file; only a button may open Save As".into())
}
r => self.requests.push(r.clone()),
}
}
self.errors.extend(o.error.iter().cloned());
// The document scripts run before every field script, so a failing one would repeat
// once per calculation; it is reported once.
for e in &o.doc_errors {
if !self.doc_errors.contains(e) {
self.doc_errors.push(e.clone());
self.errors.push(e.clone());
}
}
}
pub(crate) fn append(&mut self, other: JsOutput) {
self.alerts.extend(other.alerts);
self.console.extend(other.console);
self.requests.extend(other.requests);
self.errors.extend(other.errors);
// As in `absorb`: a document script's error, already reported, is not repeated; a field
// script's errors are each their own, even one worded like a document script's.
let mut docs = other.doc_errors;
for e in other.errors {
if let Some(k) = docs.iter().position(|d| *d == e) {
docs.swap_remove(k);
if self.doc_errors.contains(&e) {
continue;
}
self.doc_errors.push(e.clone());
}
self.errors.push(e);
}
}
}
@@ -132,20 +170,16 @@ impl JsRunner {
/// A runner for `cos`: what scripts read about the document (pages, info, whether it is
/// an XFA form) and its document-level scripts, read once.
pub fn new(cos: &pdfcraft_cos::Document, file_name: &str) -> JsRunner {
let doc = pdfcraft_js::DocInfo {
file_name: file_name.to_string(),
num_pages: pdfcraft_model::pages(cos).len(),
page: 0,
info: info(cos),
xfa: pdfcraft_xfa::xfa_shape(cos).is_some(),
};
JsRunner {
doc,
doc_scripts: pdfcraft_forms::document_scripts(cos),
output: JsOutput::default(),
cos: cos.clone(),
displays: std::collections::HashMap::new(),
}
let xfa = pdfcraft_xfa::xfa_shape(cos).is_some();
let doc =
pdfcraft_js::DocInfo { file_name: file_name.to_string(), num_pages: pdfcraft_model::pages(cos).len(), page: 0, info: info(cos), xfa };
// Once XFA owns the form, the PDF container's scripts belong to its fallback view.
// Keep them in the file and in Document JavaScripts, but do not initialize an
// AcroForm context with them: a viewer-compatibility alert would be misleading.
// Packets alone are not enough: static XFA and an unlaid-out shell keep their scripts.
let xfa_active = xfa && pdfcraft_xfa::existing_layout(cos).is_some();
let doc_scripts = if xfa_active { Vec::new() } else { pdfcraft_forms::document_scripts(cos) };
JsRunner { doc, doc_scripts, output: JsOutput::default(), cos: cos.clone(), displays: std::collections::HashMap::new() }
}
}
@@ -200,6 +234,11 @@ impl crate::Document {
self.editor.as_ref().and_then(|e| pdfcraft_forms::field_actions(&e.cos, name).ok()).unwrap_or_default()
}
/// Field Properties ▸ Actions: how many actions are chained after each trigger's first one.
pub fn field_action_chains(&self, name: &str) -> Vec<(pdfcraft_forms::Trigger, usize)> {
self.editor.as_ref().and_then(|e| pdfcraft_forms::field_action_chains(&e.cos, name).ok()).unwrap_or_default()
}
/// Document JavaScripts (name, source), in name order.
pub fn document_scripts(&self) -> Vec<(String, String)> {
self.editor.as_ref().map(|e| document_scripts(&e.cos)).unwrap_or_default()
@@ -448,6 +487,32 @@ mod review_tests {
assert!(read <= 4 * n, "{read} characters read for {n} glyphs");
}
/// Review on #3985: merging two outputs reports a failing document script once, as one run
/// does, while each field script error stays: told apart by where an error came from, so a
/// field script that throws a document script's very words is still reported.
#[test]
fn merged_output_reports_a_document_script_error_once() {
let doc = "document script 2: TypeError: not a callable function";
let field = "ReferenceError: x is not defined";
let run = |error: &str| {
let mut out = JsOutput::default();
out.absorb(&Outcome { error: Some(error.into()), doc_errors: vec![doc.into()], ..Outcome::default() });
out
};
let mut out = run(field);
out.append(run(field));
assert_eq!(out.errors, [field, doc, field]);
// CodeRabbit on #3985: a field script that throws the document script's text.
out.append(run(doc));
assert_eq!(out.errors, [field, doc, field, doc]);
let alone = run(doc);
assert_eq!(alone.errors, [doc, doc], "the field's error and the document script's");
let count = |o: &JsOutput| o.errors.iter().filter(|e| *e == doc).count();
let mut merged = run(field);
merged.append(alone);
assert_eq!(count(&merged), 2, "the field's copy stays; the document script's is listed once");
}
#[test]
fn duplicate_field_names_diff_against_first_original() {
let first = pdfcraft_js::FieldState::new("duplicate", pdfcraft_js::FieldType::Text, vec!["first".into()]);
+204 -29
View File
@@ -46,16 +46,20 @@ pub use signature_scan::{PhotoRect, ScanError, SignaturePhoto, Turn};
pub use stamp_preview::StampPreview;
pub use text_preview::TextEditPreview;
pub use pdfcraft_organize::{BoxSpec, FieldConflicts, PageBox, SplitBy, Transition, TransitionSpec, split_ranges};
pub use pdfcraft_organize::{BoxSpec, FieldConflicts, PageBox, SplitBy, Transition, TransitionSpec, mime_for_name, split_ranges};
/// One file produced by a split: (1-based first page, last page, PDF bytes).
pub use pdfcraft_organize::LabelStyle;
pub use pdfcraft_organize::Standard;
pub use pdfcraft_organize::check_custom_key;
pub use pdfcraft_organize::view::{InitialView, Layout as InitialLayout, Magnification, Navigation};
pub use pdfcraft_cos::Algorithm;
pub use pdfcraft_create::{CONVERTIBLE, CreateError, ImageResolution, SourceKind, decode_text, source_kind};
pub use pdfcraft_edit::added::{text_rect as added_text_rect, text_width as added_text_width};
pub use pdfcraft_edit::added::{
CHAR_SPACING_LIMIT as ADDED_CHAR_SPACING_LIMIT, paste_place as added_paste_place, paste_rect as added_paste_rect, text_rect as added_text_rect,
text_width as added_text_width,
};
pub use pdfcraft_edit::{
Added, AddedImage, AddedText, Align as TextAlign, Background, Content as AddedContent, Family as FontFamily, HeaderFooter, MarkKind, Watermark,
};
@@ -276,6 +280,8 @@ fn uses_scripts(edit: &Edit) -> bool {
fn scope_of(edit: &Edit) -> Scope {
match edit {
Edit::SetInfo { .. } => Scope::Metadata,
// The Attachments list is read from the whole document.
Edit::AddAttachment { .. } | Edit::DeleteAttachment { .. } => Scope::Full,
// A file attachment also changes the Attachments list.
Edit::AddAnnotation(a) if matches!(a.shape, Shape::Attachment { .. }) => Scope::Full,
Edit::AddMeasurement(_)
@@ -309,6 +315,7 @@ fn scope_of(edit: &Edit) -> Scope {
| Edit::UpdateContent { .. }
| Edit::DeleteContent { .. }
| Edit::ReplaceImage { .. }
| Edit::PasteContent { .. }
| Edit::AddHeaderFooter { .. }
| Edit::AddWatermark { .. }
| Edit::AddBackground { .. }
@@ -787,6 +794,17 @@ impl Document {
self.editable() && self.permissions().is_none_or(|p| p.modify())
}
/// How widget `widget` of text field `name` lays its value out, for asking whether a typed
/// value fits it ([`form_appearance::TextBox::fits`]): a field that doesn't scroll takes no
/// more than fits. `None` without such a field or widget, or when the document can't be
/// edited.
pub fn field_text_box(&self, name: &str, widget: usize) -> Option<form_appearance::TextBox> {
let cos = &self.editor.as_ref()?.cos;
let f = self.form.iter().find(|f| f.name == name)?;
let w = f.widgets.get(widget)?;
Some(form_appearance::text_box(cos, f, w))
}
/// Filling in form fields is allowed (Table 22, bits 6 and 9).
pub fn allows_form_filling(&self) -> bool {
self.editable() && self.permissions().is_none_or(|p| p.fill_forms())
@@ -847,6 +865,14 @@ impl Document {
matches!(f.kind, FormFieldKind::CheckBox | FormFieldKind::Radio).then(|| pdfcraft_forms::check_style(&e.cos, f))
}
/// Whether text field `name`'s value is cut off by its box at the field's font size (#4018):
/// the page (0-based) of the first widget that cuts it, and how.
pub fn field_overflow(&self, name: &str) -> Option<(Option<usize>, pdfcraft_forms::appearance::Overflow)> {
let e = self.editor.as_ref()?;
let f = self.form.iter().find(|f| f.name == name)?;
f.widgets.iter().find_map(|w| pdfcraft_forms::appearance::value_overflow(&e.cos, f, w).map(|o| (w.page, o)))
}
/// Remove Hidden Information: what each category would remove.
pub fn hidden_info(&self) -> Vec<(Hidden, usize)> {
self.editor.as_ref().map(|e| pdfcraft_redact::sanitize::scan(&e.cos)).unwrap_or_default()
@@ -870,6 +896,11 @@ impl Document {
self.editor.as_ref().and_then(|e| pdfcraft_organize::info(&e.cos, key))
}
/// Whether the document information has an entry `key`, of any type, listed or not.
pub fn has_info(&self, key: &str) -> bool {
self.editor.as_ref().is_some_and(|e| pdfcraft_organize::has_info(&e.cos, key))
}
/// The custom document properties as they are now (name, text), Document Properties ▸ Custom.
pub fn custom_info(&self) -> Vec<(String, String)> {
self.editor.as_ref().map(|e| pdfcraft_organize::custom_info(&e.cos)).unwrap_or_default()
@@ -946,6 +977,20 @@ fn same_pages(a: &[pdfcraft_render::PageInfo], b: &[pdfcraft_render::PageInfo])
&& a.iter().zip(b).all(|(x, y)| (x.width - y.width).abs() < 0.01 && (x.height - y.height).abs() < 0.01 && x.rotation == y.rotation)
}
/// Each document-information field of `info` with its value in `cos` (`/Info`, else XMP), read
/// the way the full inspection reads them: NULs and spaces trimmed, empty is none.
fn info_fields<'a>(info: &'a mut DocInfo, cos: &pdfcraft_cos::Document) -> [(&'a mut Option<String>, Option<String>); 6] {
let read = |key| pdfcraft_organize::info(cos, key).map(|v| v.trim_matches('\0').trim().to_string()).filter(|v| !v.is_empty());
[
(&mut info.title, read("Title")),
(&mut info.author, read("Author")),
(&mut info.subject, read("Subject")),
(&mut info.keywords, read("Keywords")),
(&mut info.creator, read("Creator")),
(&mut info.producer, read("Producer")),
]
}
/// The copy PDFCraft displays when opening `bytes`: with appearances drawn, in memory only, for
/// comments that have none and form fields the file leaves to the viewer. Render paths outside the app, such as the CLI, use this so their page
/// images agree with the app and independent viewers. It never changes the source document, and an
@@ -1050,7 +1095,7 @@ fn shown_under_redactions(
}
fn render_threads() -> usize {
std::thread::available_parallelism().map(|n| n.get()).unwrap_or(4).clamp(2, 8) - 1
std::thread::available_parallelism().map(std::num::NonZeroUsize::get).unwrap_or(4).clamp(2, 8) - 1
}
/// Write `layers`' visibility into the default optional-content configuration of `cos` (a copy
@@ -1311,7 +1356,7 @@ impl Protection {
(Some(a), Some(b)) if a == b => return bad("the open password and the permissions password must be different"),
_ => {}
}
if [&self.open_password, &self.permissions_password].into_iter().flatten().any(|p| p.is_empty()) {
if [&self.open_password, &self.permissions_password].into_iter().flatten().any(String::is_empty) {
return bad("passwords can't be empty");
}
if self.algorithm != pdfcraft_cos::Algorithm::Aes256
@@ -1615,6 +1660,18 @@ pub enum Edit {
},
/// Document Properties ▸ Initial View (and the language and binding).
SetInitialView(Box<InitialView>),
/// Edit ▸ Attach a file: a document-level attachment (`/Names /EmbeddedFiles`) under
/// `name`, made unique; `mime` is the embedded file's `/Subtype` when known.
AddAttachment {
name: String,
bytes: Vec<u8>,
description: Option<String>,
mime: Option<String>,
},
/// Remove the document-level attachment whose name-tree key is `key`.
DeleteAttachment {
key: String,
},
/// Build a tagged structure tree for an untagged, text-only document.
AutoTagText,
/// Add alternate text: set (or clear, with `None`) a figure's alternate text. `figure` is
@@ -1782,6 +1839,16 @@ pub enum Edit {
name: String,
bytes: Arc<Vec<u8>>,
},
/// Edit ▸ Paste: an added item copied in this document or another, as it was: text with its
/// style, an image in its box (display space) with its turns, flips and crop. An image's
/// picture is `file` (from [`Document::added_image_file`]): the copied image object is reused
/// while it is still that picture in this document, else one an added image here already draws
/// it from, else the file is embedded.
PasteContent {
page: usize,
content: AddedContent,
file: Option<(String, Arc<Vec<u8>>)>,
},
/// Apply redaction marks (all, or those on `pages`): remove what they cover for good.
ApplyRedactions {
pages: Option<Vec<usize>>,
@@ -1938,6 +2005,8 @@ pub const EDIT_LABELS: &[&str] = &[
"Insert pages from {name}",
"Insert pages from {name} — 1 field renamed",
"Insert pages from {name} — fields renamed",
"Attach {name}",
"Delete attachment {key}",
"Add bookmark",
"Rename bookmark",
"Delete bookmark",
@@ -2034,6 +2103,7 @@ pub const EDIT_LABELS: &[&str] = &[
"Add image",
"Edit content",
"Delete content",
"Paste",
"Apply redactions",
"Remove redaction marks",
"Remove hidden information",
@@ -2135,6 +2205,8 @@ impl Edit {
Edit::SetTabOrder { .. } | Edit::MoveInTabOrder { .. } => Label::of("Set tab order"),
Edit::SetCalculationOrder { .. } => Label::of("Set calculation order"),
Edit::SetInitialView(_) => Label::of("Change initial view"),
Edit::AddAttachment { name, .. } => Label::with("Attach {name}", name.as_str()),
Edit::DeleteAttachment { key } => Label::with("Delete attachment {key}", key.as_str()),
Edit::AutoTagText => Label::of("Automatically tag text"),
Edit::SetAltText { .. } => Label::of("Set alternate text"),
Edit::AutoTagFormFields => Label::of("Tag form fields"),
@@ -2176,6 +2248,7 @@ impl Edit {
Edit::UpdateContent { .. } => Label::of("Edit content"),
Edit::DeleteContent { .. } => Label::of("Delete content"),
Edit::ReplaceImage { .. } => Label::of("Replace image"),
Edit::PasteContent { .. } => Label::of("Paste"),
Edit::ApplyRedactions { .. } => Label::of("Apply redactions"),
Edit::ClearRedactions => Label::of("Remove redaction marks"),
Edit::RemoveHidden { .. } => Label::of("Remove hidden information"),
@@ -2329,6 +2402,7 @@ fn check_permission(edit: &Edit, p: &pdfcraft_cos::Permissions) -> Result<(), Ed
| Edit::MoveObjects { .. }
| Edit::DeleteContent { .. }
| Edit::ReplaceImage { .. }
| Edit::PasteContent { .. }
| Edit::ClearRedactions
| Edit::RemoveHidden { .. }
| Edit::ImportData { .. }
@@ -2346,6 +2420,8 @@ fn check_permission(edit: &Edit, p: &pdfcraft_cos::Permissions) -> Result<(), Ed
| Edit::MoveInTabOrder { .. }
| Edit::SetCalculationOrder { .. }
| Edit::SetInitialView(_)
| Edit::AddAttachment { .. }
| Edit::DeleteAttachment { .. }
| Edit::AutoTagText
| Edit::SetAltText { .. }
| Edit::AutoTagFormFields
@@ -2553,6 +2629,10 @@ fn run_edit(doc: &mut pdfcraft_cos::Document, edit: &Edit, cx: &mut EditCtx) ->
Edit::EraseInk { page, index, path, radius } => {
pdfcraft_annot::erase_ink(doc, *page, *index, path, *radius, &cx.meta())?;
}
Edit::AddAttachment { name, bytes, description, mime } => {
pdfcraft_organize::add_attachment(doc, name, bytes, description.as_deref(), mime.as_deref(), cx.date.as_deref())?;
}
Edit::DeleteAttachment { key } => pdfcraft_organize::delete_attachment(doc, key)?,
Edit::ReplaceText { page, quads, text, author, strike, caret } => {
// One `/NM` each: the caret replies to the strikeout, and XFDF names that reply by
// the strikeout's `/NM` (#2666).
@@ -2574,10 +2654,23 @@ fn run_edit(doc: &mut pdfcraft_cos::Document, edit: &Edit, cx: &mut EditCtx) ->
Edit::SetAnnotationInfo { page, index, author, subject, icon } => {
pdfcraft_annot::set_info(doc, *page, *index, author.as_deref(), subject.as_deref(), *icon, &cx.meta())?;
}
Edit::SetFieldValue { name, value } => match cx.js.as_mut() {
Some(js) => pdfcraft_forms::set_value_with(doc, name, value, js)?,
None => pdfcraft_forms::set_value(doc, name, value)?,
},
Edit::SetFieldValue { name, value } => {
let mut set = |doc: &mut pdfcraft_cos::Document, value: &FieldValue| match cx.js.as_mut() {
Some(js) => pdfcraft_forms::set_value_with(doc, name, value, js),
None => pdfcraft_forms::set_value(doc, name, value),
};
match set(doc, value) {
Ok(()) => {}
// A date the field's format doesn't read may be typed by another of an XFA date
// field's patterns: it is kept in the first. Only a format refusal is tried
// again: it comes before any of the field's scripts run, so they run once.
Err(refused @ pdfcraft_forms::FormError::Format(_)) => match xfa::typed_date(doc, cx.xfa.as_deref(), name, value) {
Some(typed) => set(doc, &typed)?,
None => return Err(refused.into()),
},
Err(refused) => return Err(refused.into()),
}
}
Edit::ApplyScriptChanges { changes } => match cx.js.as_mut() {
Some(js) => pdfcraft_forms::apply_script_changes(doc, changes, js)?,
None => pdfcraft_forms::apply_script_changes(doc, changes, &mut pdfcraft_forms::NoScripts)?,
@@ -2784,6 +2877,28 @@ fn run_edit(doc: &mut pdfcraft_cos::Document, edit: &Edit, cx: &mut EditCtx) ->
let (image, _) = embed_image(doc, name, bytes)?;
pdfcraft_edit::update_content(doc, *page, *index, &AddedContent::Image(pdfcraft_edit::AddedImage { image, ..old }))?;
}
Edit::PasteContent { page, content, file } => {
let content = match content {
AddedContent::Text(_) => content.clone(),
AddedContent::Image(img) => {
let Some((name, bytes)) = file else {
return Err(EditError::Edit(pdfcraft_edit::EditError::Invalid("a pasted image needs its picture".into())));
};
// The same picture in this document (copied here, pasted here before, or an
// identical file): drawn again from the one image object rather than stored twice.
let image = if copy_image::is_picture(doc, img.image, bytes) {
img.image
} else {
match copy_image::added_picture(doc, bytes) {
Some(image) => image,
None => embed_image(doc, name, bytes)?.0,
}
};
AddedContent::Image(pdfcraft_edit::AddedImage { image, ..img.clone() })
}
};
pdfcraft_edit::add_content(doc, *page, &content)?;
}
Edit::ApplyRedactions { pages } => {
cx.redaction_overlays = pdfcraft_redact::apply(doc, pages.as_deref())?.overlays;
}
@@ -2908,6 +3023,7 @@ fn comment_list(doc: &pdfcraft_cos::Document) -> Vec<pdfcraft_render::Annotation
locked: s.locked,
intent: s.intent,
fill_sign: s.fill_sign,
no_rotate: s.no_rotate,
points: s.points,
})
.collect()
@@ -2950,6 +3066,19 @@ fn renderer_password(bytes: &[u8]) -> String {
}
}
/// The document as it may be written to a file (#3926): a copy without the values of text fields
/// with the Password flag, or `cos` itself when it holds none. ISO 32000-2 §12.7.5.3, Table 231
/// (a note to the Password flag): "it is imperative that PDF processors never store the value of
/// the text field in the PDF file if this flag is set". The open document keeps them in memory.
fn writable(cos: &pdfcraft_cos::Document) -> Result<std::borrow::Cow<'_, pdfcraft_cos::Document>, EditError> {
if !pdfcraft_forms::has_password_values(cos) {
return Ok(std::borrow::Cow::Borrowed(cos));
}
let mut copy = cos.clone();
pdfcraft_forms::clear_password_values(&mut copy).map_err(|e| EditError::Write(e.to_string()))?;
Ok(std::borrow::Cow::Owned(copy))
}
/// The last-resort guard (AGENTS.md §4): run `f`, turning a panic that escapes it into an error
/// message, so one bad file or edit can't take the app and its other documents down. It is a
/// safety net for bugs, not a substitute for returning errors.
@@ -3711,7 +3840,7 @@ impl Session {
name: String,
path: Option<String>,
bytes: Arc<Vec<u8>>,
info: DocInfo,
mut info: DocInfo,
cos: Result<Result<pdfcraft_cos::Document, pdfcraft_cos::CosError>, Box<dyn std::any::Any + Send>>,
render_password: Option<String>,
password: Option<&str>,
@@ -3743,6 +3872,15 @@ impl Session {
};
let sig_cache = Arc::new(pdfcraft_sign::DigestCache::default());
let signatures = editor.as_ref().map(|e| signatures_of(&e.cos, &bytes, trust, &sig_cache)).unwrap_or_default();
// The inspection reads only `/Info`; a file stating its title or author only in XMP still
// shows them (#2373).
if let Some(e) = &editor {
for (field, value) in info_fields(&mut info, &e.cos) {
if field.is_none() {
*field = value;
}
}
}
let display = display_bytes(editor.as_mut(), &bytes);
let renderer = RenderPool::new(display.clone(), render_threads(), config.clone());
let (form, adopted) = editor
@@ -4108,15 +4246,9 @@ impl Session {
editor.cos.bytes().clone()
};
if scope == Scope::Metadata {
// Read the way the full inspection reads them (NULs and spaces trimmed, empty is
// none), so editing one entry doesn't change how the others display.
let info = |key| pdfcraft_organize::info(&editor.cos, key).map(|v| v.trim_matches('\0').trim().to_string()).filter(|v| !v.is_empty());
doc.info.title = info("Title");
doc.info.author = info("Author");
doc.info.subject = info("Subject");
doc.info.keywords = info("Keywords");
doc.info.creator = info("Creator");
doc.info.producer = info("Producer");
for (field, value) in info_fields(&mut doc.info, &editor.cos) {
*field = value;
}
doc.info.custom = pdfcraft_organize::custom_info(&editor.cos);
doc.info.file_size = bytes.len();
#[cfg(test)]
@@ -4177,10 +4309,22 @@ impl Session {
/// Which derived lists a content-only edit can change: added content (`None`, from
/// undo/redo, re-reads both: always correct, rarely paid).
fn content_refresh_lists(edit: Option<&Edit>) -> (bool, bool) {
if let Some(Edit::Batch { edits, .. }) = edit {
// A batch of content edits (from a script, say) changes what its parts change.
return edits.iter().fold((false, false), |(added, marks), part| {
let (a, m) = Self::content_refresh_lists(Some(part));
(added || a, marks || m)
});
}
let touches_added = edit.is_none_or(|e| {
matches!(
e,
Edit::AddText { .. } | Edit::AddImage { .. } | Edit::UpdateContent { .. } | Edit::DeleteContent { .. } | Edit::ReplaceImage { .. }
Edit::AddText { .. }
| Edit::AddImage { .. }
| Edit::UpdateContent { .. }
| Edit::DeleteContent { .. }
| Edit::ReplaceImage { .. }
| Edit::PasteContent { .. }
) || matches!(e, Edit::MoveObjects { objects, .. } if objects.iter().any(|o| o.kind == ObjectKind::Added))
});
let touches_marks = edit.is_none_or(|e| {
@@ -4277,6 +4421,13 @@ impl Session {
}
}
note_warnings(&mut info.warnings, &doc.xfa_warnings);
// As in `build_document`: the inspection reads only `/Info`, so fields stated only in XMP
// are filled in again after every full refresh.
for (field, value) in info_fields(&mut info, &editor.cos) {
if field.is_none() {
*field = value;
}
}
doc.info = info;
doc.fonts_stale = false;
let mut form = pdfcraft_forms::fields(&editor.cos);
@@ -4315,12 +4466,13 @@ impl Session {
// file so that revision stays in the chain. A full rewrite (redaction, new encryption,
// a reconstructed file) still writes the current graph on its own.
let rewrite = editor.cos.full_save_required() || editor.cos.encryption_changed() || editor.cos.revisions().is_empty();
let cos = writable(&editor.cos)?;
guard(|| {
if on_saved || rewrite {
write_incremental(&editor.cos, &opts)
write_incremental(&cos, &opts)
} else {
let mut base = pdfcraft_cos::Document::open_with_password(editor.saved.clone(), editor.saved_keys.reopen.as_deref())?;
base.overlay_changes_from(&editor.cos)?;
base.overlay_changes_from(&cos)?;
write_incremental(&base, &opts)
}
})
@@ -4337,7 +4489,8 @@ impl Session {
}
let editor = doc.editor.as_ref().ok_or_else(|| EditError::ReadOnly(doc.read_only_reason.clone().unwrap_or_default()))?;
let opts = SaveOptions { mod_date: self.now().map(pdfcraft_cos::pdf_date), ..SaveOptions::default() };
guard(|| write_full(&editor.cos, &opts)).map_err(EditError::Write)?.map(Arc::new).map_err(|e| EditError::Write(e.to_string()))
let cos = writable(&editor.cos)?;
guard(|| write_full(&cos, &opts)).map_err(EditError::Write)?.map(Arc::new).map_err(|e| EditError::Write(e.to_string()))
}
/// Check that `bytes`, from [`Self::save_bytes`] or [`Self::save_full_bytes`], reopen as this
@@ -4358,8 +4511,11 @@ impl Session {
// An encrypted file needs the password it is protected with now (the owner
// password when known, so saving never downgrades this session's rights).
let keys = editor.keys.clone();
// The saved file carries no Password-field values (#3943); the open document keeps them.
let typed = pdfcraft_forms::password_values(&editor.cos);
editor.cos =
pdfcraft_cos::Document::open_with_password(bytes.clone(), keys.reopen.as_deref()).map_err(|e| EditError::Reopen(e.to_string()))?;
pdfcraft_forms::restore_password_values(&mut editor.cos, &typed).map_err(|e| EditError::Reopen(e.to_string()))?;
editor.saved = bytes;
editor.saved_keys = keys;
editor.unsaved_file = false;
@@ -4692,7 +4848,7 @@ impl Session {
pub fn combine_field_conflicts(&self, sources: &[CombineSource], passwords: &[Option<&str>]) -> Vec<Vec<(String, String)>> {
let docs: Vec<Option<pdfcraft_cos::Document>> =
sources.iter().enumerate().map(|(i, (n, b, _))| open_source_with(n, b, passwords.get(i).copied().flatten()).ok()).collect();
let refs: Vec<&pdfcraft_cos::Document> = docs.iter().filter_map(|d| d.as_ref()).collect();
let refs: Vec<&pdfcraft_cos::Document> = docs.iter().filter_map(Option::as_ref).collect();
let mut opened = pdfcraft_organize::combine_field_conflicts(&refs).into_iter();
// One preview per source, in step with it: a file that cannot be opened has none.
docs.iter().map(|d| if d.is_some() { opened.next().unwrap_or_default() } else { Default::default() }).collect()
@@ -4945,9 +5101,12 @@ impl Session {
}
/// [`Self::write_new`] without the check, for bytes nobody writes: measuring a part's size.
/// Like a save, a new file never carries a typed Password-field value (#3926): Extract and
/// Split copy the fields of the pages they take.
fn write_unchecked(&self, doc: &pdfcraft_cos::Document) -> Result<Arc<Vec<u8>>, EditError> {
let opts = SaveOptions { mod_date: self.now().map(pdfcraft_cos::pdf_date), ..SaveOptions::default() };
write_full(doc, &opts).map(Arc::new).map_err(|e| EditError::Write(e.to_string()))
let doc = writable(doc)?;
write_full(&doc, &opts).map(Arc::new).map_err(|e| EditError::Write(e.to_string()))
}
/// Whether a changed document still needs a recovery snapshot. This does not consume it.
@@ -4961,12 +5120,23 @@ impl Session {
let mut out = Vec::new();
for d in &mut self.docs {
if d.dirty && d.generation != d.snapshot_generation {
// The working bytes hold typed Password-field values (#3926): a recovery file is
// written from a copy without them, and none is written if that copy fails.
let bytes = match d.editor.as_ref().filter(|e| pdfcraft_forms::has_password_values(&e.cos)) {
Some(e) => match writable(&e.cos)
.and_then(|c| write_incremental(&c, &SaveOptions::default()).map_err(|e| EditError::Write(e.to_string())))
{
Ok(b) => Arc::new(b),
Err(_) => continue,
},
None => d.bytes.clone(),
};
d.snapshot_generation = d.generation;
out.push(RecoverySnapshot {
doc: d.id,
name: d.name.clone(),
path: d.path.clone(),
bytes: d.bytes.clone(),
bytes,
encrypted: d.info.encrypted || d.editor.as_ref().is_some_and(|e| e.cos.security().is_some()),
});
}
@@ -5120,7 +5290,9 @@ impl Session {
if opts.date.is_empty() {
opts.date = self.signing_date();
}
Ok(Arc::new(pdfcraft_sign::sign(&editor.cos, id, &opts)?))
// A typed Password-field value is not signed into the file (#3926), as it isn't saved.
let cos = writable(&editor.cos)?;
Ok(Arc::new(pdfcraft_sign::sign(&cos, id, &opts)?))
}
/// [`Session::sign`], embedding an RFC 3161 signature timestamp (PAdES B-T) produced by
@@ -5137,7 +5309,8 @@ impl Session {
if opts.date.is_empty() {
opts.date = self.signing_date();
}
let signed = Arc::new(pdfcraft_sign::sign_with_timestamp(&editor.cos, id, &opts, tsa)?);
let cos = writable(&editor.cos)?;
let signed = Arc::new(pdfcraft_sign::sign_with_timestamp(&cos, id, &opts, tsa)?);
// Checked like a save before anyone writes it (#2166).
self.check_save(doc, &signed)?;
Ok(signed)
@@ -5149,7 +5322,8 @@ impl Session {
let d = self.get(doc).ok_or(EditError::NoDocument)?;
let editor = d.editor.as_ref().ok_or_else(|| EditError::ReadOnly(d.read_only_reason.clone().unwrap_or_default()))?;
let date = if date.is_empty() { self.signing_date() } else { date };
let stamped = Arc::new(pdfcraft_sign::timestamp_document(&editor.cos, tsa, &date)?);
let cos = writable(&editor.cos)?;
let stamped = Arc::new(pdfcraft_sign::timestamp_document(&cos, tsa, &date)?);
self.check_save(doc, &stamped)?;
Ok(stamped)
}
@@ -5159,7 +5333,8 @@ impl Session {
pub fn embed_ltv(&self, doc: DocId, evidence: &pdfcraft_sign::dss::Evidence) -> Result<Arc<Vec<u8>>, EditError> {
let d = self.get(doc).ok_or(EditError::NoDocument)?;
let editor = d.editor.as_ref().ok_or_else(|| EditError::ReadOnly(d.read_only_reason.clone().unwrap_or_default()))?;
let embedded = Arc::new(pdfcraft_sign::dss::embed(&editor.cos, evidence)?);
let cos = writable(&editor.cos)?;
let embedded = Arc::new(pdfcraft_sign::dss::embed(&cos, evidence)?);
self.check_save(doc, &embedded)?;
Ok(embedded)
}
+9 -3
View File
@@ -24,6 +24,11 @@ pub struct OcrSettings {
/// text" and skips them). When `false`, such pages are read too (a picture on a page that
/// also has text, #1028) and only the words that aren't already there are added.
pub skip_text_pages: bool,
/// What counts as the page's text when `skip_text_pages` is on: only its own (page content
/// and form fields). Comments and text boxes are left out, and are not drawn into the picture
/// that is read, so a scan with a few comments on it is still a scan. `false`: everything
/// the page shows.
pub native_text_only: bool,
}
/// A recognised word whose box is at least this much covered by the page's own text is that
@@ -51,7 +56,7 @@ fn covered(word: [f32; 4], text: &[[f32; 4]]) -> f32 {
impl Default for OcrSettings {
fn default() -> Self {
OcrSettings { dpi: 300.0, language: "en".into(), skip_text_pages: true }
OcrSettings { dpi: 300.0, language: "en".into(), skip_text_pages: true, native_text_only: false }
}
}
@@ -75,7 +80,7 @@ impl OcrPage {
/// The recogniser, loaded once (it takes a moment) and shared.
pub fn engine() -> Result<Arc<Ocr>, String> {
static OCR: Mutex<Option<Arc<Ocr>>> = Mutex::new(None);
let mut slot = OCR.lock().unwrap_or_else(|e| e.into_inner());
let mut slot = OCR.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
if let Some(o) = slot.as_ref() {
return Ok(o.clone());
}
@@ -105,7 +110,8 @@ impl OcrJob {
/// Read the pages. `progress(done, total)` is called before each page; returning `false`
/// stops (the pages read so far are returned).
pub fn run(self, ocr: &Ocr, mut progress: impl FnMut(usize, usize) -> bool) -> Vec<OcrPage> {
let config = RenderConfig { password: self.password.as_deref().map(Arc::from), ..Default::default() };
let config =
RenderConfig { password: self.password.as_deref().map(Arc::from), hide_comments: self.settings.native_text_only, ..Default::default() };
let mut r = PageRenderer::new(self.bytes.clone(), config);
let mut out = Vec::new();
let total = self.pages.len();
+7 -1
View File
@@ -68,7 +68,11 @@ impl Session {
cos: editor.cos.clone(),
settings: settings.clone(),
discard: discard.to_vec(),
opts: SaveOptions { mod_date: self.now().map(pdfcraft_cos::pdf_date), ..SaveOptions::default() },
opts: SaveOptions {
mod_date: self.now().map(pdfcraft_cos::pdf_date),
object_streams: settings.effective_object_streams(),
..SaveOptions::default()
},
})
}
}
@@ -83,6 +87,8 @@ impl OptimizeJob {
fn work(self, progress: &mut dyn FnMut(OptimizeStage) -> bool) -> Result<Optimized, EditError> {
let OptimizeJob { mut cos, settings, discard, opts } = self;
// Like every file written, without the values of Password-flag fields (#3926).
pdfcraft_forms::clear_password_values(&mut cos).map_err(|e| EditError::Write(e.to_string()))?;
let mut step = |stage| if progress(stage) { Ok(()) } else { Err(EditError::Cancelled) };
step(OptimizeStage::Discarding)?;
let discarded = if discard.is_empty() { Vec::new() } else { pdfcraft_redact::sanitize::remove_hidden(&mut cos, &discard)? };
+887 -1
View File
@@ -196,6 +196,47 @@ fn rubber_stamps_point_left_as_displayed_on_rotated_pages() {
}
}
/// #2583, #1869: a sticky note placed on a turned page is drawn upright, with its top-left as
/// displayed where it was placed (the corner its `/Rect` keeps, as the NoRotate flag it is saved
/// with asks), exactly as on an unturned page, including after save. The comment list's
/// `shown_rect`, which the UI hit-tests, is that square.
#[test]
fn sticky_notes_stay_upright_where_they_are_placed_on_rotated_pages() {
// The displayed 20 × 20 pt square whose top-left is (100, 40), in device pixels at scale 2.
let crop = |rendered: &pdfcraft_render::RenderedPage| -> Vec<[u8; 4]> {
(80..120).flat_map(|y| (200..240).map(move |x| (x, y))).map(|(x, y)| stamp_pixel(rendered, x, y)).collect()
};
let mut upright = None;
for degrees in [0, 90, 180, 270] {
let (mut session, id) = rotated_blank(degrees);
let info = session.get(id).unwrap().info.pages[0].clone();
let [x, y] = info.view_to_user(100.0, 40.0);
let shape = Shape::Note { at: [f64::from(x), f64::from(y)], icon: NoteIcon::Comment };
let style = Style::default_for(&shape);
session.apply(id, Edit::AddAnnotation(NewAnnotation { page: 0, style, shape, contents: "Turned".into(), author: "Test".into() })).unwrap();
let mut check = |session: &Session, id: DocId| {
let doc = session.get(id).unwrap();
let info = &doc.info.pages[0];
let note = &doc.info.annotations[0];
assert!(note.no_rotate, "rotation {degrees}: notes are saved NoRotate");
let shown = note.shown_rect(info.rotation);
let (a, b) = (info.user_to_view(shown[0], shown[1]), info.user_to_view(shown[2], shown[3]));
let shown = [a[0].min(b[0]), a[1].min(b[1]), a[0].max(b[0]), a[1].max(b[1])];
assert!(shown.iter().zip([100.0, 40.0, 120.0, 60.0]).all(|(v, w)| (v - w).abs() < 0.01), "rotation {degrees}: shown at {shown:?}");
let icon = crop(&render_page(session, id));
let reference = upright.get_or_insert_with(|| icon.clone());
assert!(reference.iter().filter(|c| c.iter().any(|v| *v < 200)).count() > 100, "the note's icon is drawn");
let off = icon.iter().zip(reference.iter()).filter(|(a, b)| a.iter().zip(b.iter()).any(|(a, b)| a.abs_diff(*b) > 48)).count();
assert!(off <= 8, "rotation {degrees}: {off} of the icon's {} pixels differ from the unturned page's", icon.len());
};
check(&session, id);
let saved = session.save_bytes(id).unwrap();
let mut reopened = Session::new().with_clock(|| 1_700_000_000);
let again = reopened.open("drawing.pdf", None, saved, None).unwrap();
check(&reopened, again);
}
}
/// #2392: Fill & Sign marks are drawn as displayed on every page rotation, including after save:
/// a checkmark's long stroke rises to the right, and a line runs across.
#[test]
@@ -492,6 +533,38 @@ impl RenderRequestFor {
}
}
/// A file with its title and author only in XMP shows them in the document information and in
/// Document Properties ▸ Description (#2373).
#[test]
fn document_information_stated_only_in_xmp_is_shown() {
let mut cos = pdfcraft_cos::Document::open(Arc::new(fixture(1))).unwrap();
let xmp = "<x:xmpmeta xmlns:x=\"adobe:ns:meta/\"><rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\">\
<rdf:Description rdf:about=\"\" xmlns:dc=\"http://purl.org/dc/elements/1.1/\">\
<dc:title><rdf:Alt><rdf:li xml:lang=\"x-default\">Quarterly report</rdf:li></rdf:Alt></dc:title>\
<dc:creator><rdf:Seq><rdf:li>Ada</rdf:li></rdf:Seq></dc:creator></rdf:Description></rdf:RDF></x:xmpmeta>";
let mut dict = pdfcraft_cos::Dict::new();
dict.set(b"Type".to_vec(), pdfcraft_cos::Object::name("Metadata"));
dict.set(b"Subtype".to_vec(), pdfcraft_cos::Object::name("XML"));
let m = cos.add(pdfcraft_cos::Object::Stream(pdfcraft_cos::Stream::from_raw(dict, xmp.as_bytes().to_vec())));
let root = cos.root().unwrap();
cos.update_dict(root, |c| c.set(b"Metadata".to_vec(), pdfcraft_cos::Object::Ref(m))).unwrap();
let bytes = pdfcraft_cos::write_full(&cos, &pdfcraft_cos::SaveOptions::default()).unwrap();
let mut s = Session::new();
let id = s.open("xmp.pdf", None, Arc::new(bytes), None).unwrap();
let doc = s.get(id).unwrap();
assert_eq!((doc.info.title.as_deref(), doc.info.author.as_deref(), doc.info.subject.as_deref()), (Some("Quarterly report"), Some("Ada"), None));
assert_eq!(doc.info_value("Title").as_deref(), Some("Quarterly report"));
assert_eq!(doc.info_value("Author").as_deref(), Some("Ada"));
// A full refresh (any structural edit, undo, redo) reads /Info again and must not lose them.
s.apply(id, Edit::RotatePages { pages: vec![0], degrees: 90 }).unwrap();
let doc = s.get(id).unwrap();
assert_eq!((doc.info.title.as_deref(), doc.info.author.as_deref()), (Some("Quarterly report"), Some("Ada")), "after an edit");
s.undo(id).unwrap();
let doc = s.get(id).unwrap();
assert_eq!((doc.info.title.as_deref(), doc.info.author.as_deref()), (Some("Quarterly report"), Some("Ada")), "after undo");
}
#[test]
fn edits_update_view_data_and_mark_dirty() {
let (mut s, id) = session_with(3);
@@ -2120,6 +2193,97 @@ fn form_fixture() -> Vec<u8> {
out
}
/// Whether `needle` appears in `bytes`, or in any stream of the PDF they hold once decoded (so
/// compressed object streams are searched too), as literal or hex string bytes.
fn appears_in_pdf(bytes: &Arc<Vec<u8>>, needle: &str) -> bool {
let hex: String = needle.bytes().map(|b| format!("{b:02x}")).collect();
let forms = [needle.as_bytes().to_vec(), hex.clone().into_bytes(), hex.to_uppercase().into_bytes()];
let found = |hay: &[u8]| forms.iter().any(|f| hay.windows(f.len()).any(|w| w == f.as_slice()));
if found(bytes) {
return true;
}
let doc = pdfcraft_cos::Document::open(bytes.clone()).unwrap();
doc.object_numbers().into_iter().any(|num| match &*doc.get(pdfcraft_cos::ObjRef { num, generation: 0 }) {
pdfcraft_cos::Object::Stream(st) => st.decoded().is_ok_and(|d| found(&d)),
_ => false,
})
}
/// #3926: a value typed into a text field with the Password flag stays in the open document but
/// is written to no file: Save, a full rewrite, Reduce File Size, a recovery snapshot, or a new
/// file made from its pages (Extract, Split, Combine). ISO
/// 32000-2 §12.7.5.3, Table 231, note to the Password flag: PDF processors should never store
/// the value in the PDF file.
#[test]
fn password_field_values_are_kept_in_memory_but_written_to_no_file() {
let fixture = String::from_utf8(form_fixture()).unwrap().replace("/T (name)", "/T (name) /Ff 8192");
// Offsets shift by the inserted text; the parser rebuilds the cross-reference table.
let mut s = Session::new().with_clock(|| 1_700_000_000);
let id = s.open("form.pdf", None, Arc::new(fixture.into_bytes()), None).unwrap();
s.apply(id, Edit::SetFieldValue { name: "name".into(), value: FieldValue::Text("hunter2".into()) }).unwrap();
let field = s.get(id).unwrap().form.iter().find(|f| f.name == "name").cloned().unwrap();
assert!(field.has(pdfcraft_forms::flags::PASSWORD));
assert_eq!(field.value, vec!["hunter2".to_string()], "the open document keeps the value");
assert!(appears_in_pdf(&s.get(id).unwrap().bytes, "hunter2"), "the working bytes do hold it (the test can see it)");
let saved = s.save_bytes(id).unwrap();
assert!(!appears_in_pdf(&saved, "hunter2"), "Save");
// As Acrobat saves it (#3943 review): no default value, so an empty field whose appearance
// no longer shows how long the typed password was.
assert!(!appears_in_pdf(&saved, "*******"), "the typed length is not kept in the appearance");
assert!(!appears_in_pdf(&s.save_full_bytes(id).unwrap(), "hunter2"), "a full rewrite");
assert!(!appears_in_pdf(&s.reduced_bytes(id).unwrap().0, "hunter2"), "Reduce File Size");
let snaps = s.autosave_snapshots();
assert_eq!(snaps.len(), 1);
assert!(!appears_in_pdf(&snaps[0].bytes, "hunter2"), "the recovery snapshot");
// New files built from its pages too (#3943 review): Extract copies the fields of the pages it
// takes, and Split writes each part the same way.
let extracted = s.extract(id, &[0]).unwrap();
assert!(!appears_in_pdf(&extracted, "hunter2"), "Extract Pages");
assert!(!appears_in_pdf(&extracted, "*******"), "nor on the extracted page");
for (_, _, part) in s.split_by_size(id, 1).unwrap() {
assert!(!appears_in_pdf(&part, "hunter2"), "Split");
}
assert!(!appears_in_pdf(&s.combine(&[("form.pdf".into(), s.get(id).unwrap().bytes.clone())]).unwrap(), "hunter2"), "Combine");
// Reopened, the field is empty, as in any reader.
let mut t = Session::new();
let reopened = t.open("saved.pdf", None, saved, None).unwrap();
assert!(t.get(reopened).unwrap().form.iter().find(|f| f.name == "name").unwrap().value.iter().all(|v| v.is_empty()));
}
/// #3943 review: recording a save rebases editing on the saved file, which carries no Password
/// value; the typed value stays in the open document all the same, and a later save still omits it.
#[test]
fn a_typed_password_value_survives_save_and_mark_saved() {
let fixture = String::from_utf8(form_fixture()).unwrap().replace("/T (name)", "/T (name) /Ff 8192");
let mut s = Session::new().with_clock(|| 1_700_000_000);
let id = s.open("form.pdf", None, Arc::new(fixture.into_bytes()), None).unwrap();
s.apply(id, Edit::SetFieldValue { name: "name".into(), value: FieldValue::Text("hunter2".into()) }).unwrap();
let saved = s.save_bytes(id).unwrap();
s.mark_saved(id, saved, Some("saved.pdf".into())).unwrap();
let value = |s: &Session| s.get(id).unwrap().form.iter().find(|f| f.name == "name").unwrap().value.clone();
assert_eq!(value(&s), ["hunter2"], "the open document keeps the value after Save");
assert!(!s.get(id).unwrap().dirty, "restoring it is not an unsaved change");
assert!(!appears_in_pdf(&s.save_bytes(id).unwrap(), "hunter2"), "the next save still omits it");
}
/// #3926 / #3943 review: signing writes the signed file from the same copy a save does, so a
/// typed Password-field value is not signed into the file either.
#[test]
fn a_signed_file_carries_no_password_field_value() {
let p12 = std::fs::read(concat!(env!("CARGO_MANIFEST_DIR"), "/../sign/tests/data/ec-p256.p12")).unwrap();
let digital_id = sign::pkcs12::open(&p12, "test").unwrap();
let fixture = String::from_utf8(form_fixture()).unwrap().replace("/T (name)", "/T (name) /Ff 8192");
// After the test certificate's start date (2026-10-02).
let mut s = Session::new().with_clock(|| 1_800_000_000);
let id = s.open("form.pdf", None, Arc::new(fixture.into_bytes()), None).unwrap();
s.apply(id, Edit::SetFieldValue { name: "name".into(), value: FieldValue::Text("hunter2".into()) }).unwrap();
assert!(appears_in_pdf(&s.get(id).unwrap().bytes, "hunter2"), "the working bytes hold it");
let signed = s.sign(id, &digital_id, SignOptions { rect: None, ..SignOptions::default() }).unwrap();
assert!(!appears_in_pdf(&signed, "hunter2"), "the signed file");
assert!(!appears_in_pdf(&signed, "*******"), "nor the typed length");
}
/// A value its field's font can't draw is kept, and the edit that drew it reports it in
/// `edit_notices` (the interface shows it, tools return it): not a later unrelated edit, not a
/// failed one, and not a value that can be drawn. The form (an inline AcroForm here) asks other
@@ -3155,6 +3319,143 @@ fn added_text_and_images_render_and_stay_editable() {
assert_eq!(s.get(id).unwrap().added().len(), 2);
}
/// Edit ▸ Copy and Paste of added content (#2636): a text box comes back with all its style, an
/// image with its picture and transforms, in the same document and in another.
#[test]
fn pasted_added_content_keeps_its_style_and_picture() {
let (mut s, id) = session_with(2);
let text = AddedText {
rect: [20.0, 250.0, 180.0, 264.4],
text: "Styled note".into(),
family: FontFamily::Times,
bold: true,
italic: true,
size: 12.0,
color: [0.8, 0.1, 0.2],
align: TextAlign::Center,
char_spacing: 0.0,
};
s.apply(id, Edit::AddText { page: 0, text: text.clone() }).unwrap();
let copied = s.get(id).unwrap().added()[0].content.clone();
let moved = copied.with_rect([40.0, 100.0, 200.0, 114.4]);
s.apply(id, Edit::PasteContent { page: 1, content: moved.clone(), file: None }).unwrap();
let doc = s.get(id).unwrap();
assert_eq!(doc.can_undo(), Some("Paste"));
assert_eq!(doc.added()[1].page, 1);
assert_eq!(doc.added()[1].content, moved, "every part of the style, in the new box");
// An image, turned, flipped and cropped.
let mut png = Vec::new();
{
let mut enc = png::Encoder::new(&mut png, 20, 10);
enc.set_color(png::ColorType::Rgb);
let px: Vec<u8> = (0..200).flat_map(|i| [(i % 256) as u8, 40, 200]).collect();
enc.write_header().unwrap().write_image_data(&px).unwrap();
}
s.apply(id, Edit::AddImage { page: 0, rect: Some([50.0, 100.0, 150.0, 150.0]), name: "p.png".into(), bytes: Arc::new(png) }).unwrap();
let AddedContent::Image(mut img) = s.get(id).unwrap().added()[1].content.clone() else { panic!("the image is the page's second item") };
(img.rotation, img.flip_h, img.crop) = (1, true, [0.1, 0.0, 0.2, 0.05]);
s.apply(id, Edit::UpdateContent { page: 0, index: 1, content: AddedContent::Image(img.clone()) }).unwrap();
let (ext, file) = s.get(id).unwrap().added_image_file(0, 1).unwrap();
assert_eq!(ext, "png");
let file = Some(("Pasted image.png".to_string(), Arc::new(file)));
assert!(s.get(id).unwrap().added_image_file(0, 0).is_err(), "the first item is text");
let pasted = AddedImage { rect: [60.0, 90.0, 160.0, 140.0], ..img.clone() };
s.apply(id, Edit::PasteContent { page: 0, content: AddedContent::Image(pasted.clone()), file: file.clone() }).unwrap();
let AddedContent::Image(got) = s.get(id).unwrap().added()[2].content.clone() else { panic!("an image was pasted") };
assert_eq!(got, pasted, "the same picture object, box, turn, flip and crop");
// Into another document: the picture comes along as a file of its own.
let other = s.open("other.pdf", None, Arc::new(fixture(1)), None).unwrap();
s.apply(other, Edit::PasteContent { page: 0, content: AddedContent::Image(pasted.clone()), file: file.clone() }).unwrap();
s.apply(other, Edit::PasteContent { page: 0, content: copied.clone(), file: None }).unwrap();
let d = s.get(other).unwrap();
let AddedContent::Image(theirs) = &d.added()[0].content else { panic!("an image was pasted") };
assert_eq!(AddedImage { image: img.image, ..theirs.clone() }, pasted, "the same box and transforms");
assert_eq!(d.added_image_file(0, 0).unwrap().1, file.as_ref().unwrap().1.as_slice(), "the same picture");
assert_eq!(d.added()[1].content, copied);
// Pasted there again, it draws the first paste's picture object rather than storing a third.
let first = theirs.image;
s.apply(other, Edit::PasteContent { page: 0, content: AddedContent::Image(pasted.clone()), file: file.clone() }).unwrap();
let AddedContent::Image(again) = s.get(other).unwrap().added()[2].content.clone() else { panic!("an image was pasted") };
assert_eq!(again.image, first, "one picture object for both pastes");
// The object holds another picture of the same size (another document's numbering, an undone
// add): the file is embedded instead of drawing the wrong picture.
let mut other_png = Vec::new();
{
let mut enc = png::Encoder::new(&mut other_png, 20, 10);
enc.set_color(png::ColorType::Rgb);
enc.write_header().unwrap().write_image_data(&[7u8; 600]).unwrap();
}
let other_file = Some(("other.png".to_string(), Arc::new(other_png)));
s.apply(id, Edit::PasteContent { page: 0, content: AddedContent::Image(pasted.clone()), file: other_file }).unwrap();
let AddedContent::Image(fresh) = s.get(id).unwrap().added()[3].content.clone() else { panic!("an image was pasted") };
assert_ne!(fresh.image, img.image, "a picture object of its own");
assert_ne!(s.get(id).unwrap().added_image_file(0, 3).unwrap().1, file.as_ref().unwrap().1.as_slice());
assert!(matches!(
s.apply(id, Edit::PasteContent { page: 0, content: AddedContent::Image(pasted), file: None }),
Err(EditError::Edit(pdfcraft_edit::EditError::Invalid(_)))
));
// Four items on page 1 and the pasted text on page 2.
assert_eq!(s.get(id).unwrap().added().len(), 5, "refused pastes add nothing");
s.undo(id).unwrap();
assert_eq!(s.get(id).unwrap().added().len(), 4, "a paste is one undo step");
}
/// An added JPEG 2000 picture is copied as the file it was added from: pasted into its own
/// document it draws the same object, and into another one it is embedded once.
#[test]
fn an_added_jpeg_2000_image_is_copied_as_its_file() {
// A JP2 file (30 × 20, three components) with a stub codestream, as Add Image takes it.
let bx = |ty: &[u8], payload: &[u8]| [((payload.len() + 8) as u32).to_be_bytes().as_slice(), ty, payload].concat();
let ihdr = [20u32.to_be_bytes().as_slice(), &30u32.to_be_bytes(), &[0, 3, 7, 7, 0, 0]].concat();
let signature = [0, 0, 0, 0x0C, b'j', b'P', b' ', b' ', 0x0D, 0x0A, 0x87, 0x0A];
let file = [signature.as_slice(), &bx(b"ftyp", b"jp2 \0\0\0\0jp2 "), &bx(b"jp2h", &bx(b"ihdr", &ihdr)), &bx(b"jp2c", &[0xFF, 0x4F, 0xFF, 0x51])]
.concat();
let (mut s, id) = session_with(1);
s.apply(id, Edit::AddImage { page: 0, rect: Some([50.0, 100.0, 110.0, 140.0]), name: "photo.jp2".into(), bytes: Arc::new(file.clone()) })
.unwrap();
let (ext, copied) = s.get(id).unwrap().added_image_file(0, 0).unwrap();
assert_eq!((ext, &copied), ("jp2", &file), "the file as it was added");
let AddedContent::Image(img) = s.get(id).unwrap().added()[0].content.clone() else { panic!("an image was added") };
let copied = Arc::new(copied);
let file = Some(("Pasted image.jp2".to_string(), copied.clone()));
let pasted = AddedContent::Image(AddedImage { rect: [70.0, 80.0, 130.0, 120.0], ..img.clone() });
s.apply(id, Edit::PasteContent { page: 0, content: pasted.clone(), file: file.clone() }).unwrap();
assert!(matches!(&s.get(id).unwrap().added()[1].content, AddedContent::Image(i) if i.image == img.image), "the same picture object");
let other = s.open("other.pdf", None, Arc::new(fixture(1)), None).unwrap();
for _ in 0..2 {
s.apply(other, Edit::PasteContent { page: 0, content: pasted.clone(), file: file.clone() }).unwrap();
}
let d = s.get(other).unwrap();
let images: Vec<_> = d
.added()
.iter()
.filter_map(|a| match &a.content {
AddedContent::Image(i) => Some(i.image),
_ => None,
})
.collect();
assert_eq!(images.len(), 2);
assert_eq!(images[0], images[1], "embedded once");
assert_eq!(d.added_image_file(0, 0).unwrap().1, copied.as_slice());
}
#[test]
fn a_batch_of_content_edits_refreshes_the_added_content_and_marks() {
let (mut s, id) = session_with(1);
let text = |t: &str, y: f64| AddedText { rect: [20.0, y, 180.0, y + 14.4], text: t.into(), ..AddedText::default() };
let edits = vec![Edit::AddText { page: 0, text: text("One", 200.0) }, Edit::AddText { page: 0, text: text("Two", 150.0) }];
s.apply(id, Edit::Batch { label: "Script".into(), edits }).unwrap();
assert_eq!(s.get(id).unwrap().added().len(), 2);
s.apply(id, Edit::Batch { label: "Script".into(), edits: vec![Edit::DeleteContent { page: 0, index: 0 }] }).unwrap();
assert_eq!(s.get(id).unwrap().added().len(), 1);
let watermark =
Edit::AddWatermark { pages: vec![0], settings: Watermark { text: "Draft".into(), ..Watermark::default() }, file: None, replace: false };
s.apply(id, Edit::Batch { label: "Script".into(), edits: vec![watermark] }).unwrap();
assert_eq!(s.get(id).unwrap().marks().len(), 1);
}
#[test]
fn added_images_rotate_flip_and_crop_as_drawn() {
// A 20×10 image: left half red, right half blue.
@@ -4107,9 +4408,70 @@ fn recognize_text_reads_a_picture_on_a_page_that_has_text() {
assert_eq!((count(&s, "invoice"), count(&s, "brown")), (1, 1));
}
/// Edit reads a scan that only has comments on it, not a page with real text and a picture
/// (`native_text_only`): a text box over the picture is not the page's text, page content is.
#[test]
fn native_text_only_ignores_comments_but_not_page_text() {
if !ocr::available() {
eprintln!("skipped: OCR models not installed");
return;
}
let mut s = Session::new().with_clock(|| 1_700_000_000);
let text = s.create_from_text("t", "The quick brown fox jumps over the lazy dog.").unwrap();
let id = s.open("text.pdf", None, text, None).unwrap();
let png = export::Exporter::new(s.get(id).unwrap()).png(0, 150.0).unwrap();
let scan = s.create_from_images(&[("scan.png".into(), png)]).unwrap();
let comment_only = |s: &mut Session| {
let id = s.open("scan.pdf", None, scan.clone(), None).unwrap();
let (w, h) = {
let p = &s.get(id).unwrap().info.pages[0];
(p.width as f64, p.height as f64)
};
let shape = pdfcraft_annot::Shape::TextBox { rect: [w * 0.1, h * 0.75, w * 0.9, h * 0.85], font_size: 18.0 };
s.apply(
id,
Edit::AddAnnotation(NewAnnotation {
page: 0,
style: pdfcraft_annot::Style::default_for(&shape),
shape,
contents: "Invoice reference 4711".into(),
author: "Test".into(),
}),
)
.unwrap();
id
};
let native = ocr::OcrSettings { native_text_only: true, ..Default::default() };
// A comment over the picture: the default run counts it as text and skips the page, the
// native-text run reads the picture.
let id = comment_only(&mut s);
let skipped = s.recognize_text(id, &[], ocr::OcrSettings::default()).unwrap();
assert!(skipped[0].skipped.is_some(), "a comment is text for the default run");
let found = s.recognize_text(id, &[], native.clone()).unwrap();
assert_eq!(found[0].skipped, None, "{:?}", found[0]);
assert!(found[0].text().to_lowercase().contains("brown"), "{:?}", found[0]);
// Page content over the picture is the page's own text: skipped, whatever the setting.
let id = comment_only(&mut s);
let (w, h) = {
let p = &s.get(id).unwrap().info.pages[0];
(p.width as f64, p.height as f64)
};
let note = AddedText { rect: [w * 0.1, h * 0.6, w * 0.9, h * 0.7], text: "Page text".into(), size: 18.0, ..Default::default() };
s.apply(id, Edit::AddText { page: 0, text: note }).unwrap();
let skipped = s.recognize_text(id, &[], native).unwrap();
assert!(skipped[0].skipped.is_some(), "{:?}", skipped[0]);
}
/// A form whose scripts are custom JavaScript: total = price × qty (calculate, through a
/// document-level function), shown with a custom format; qty is validated; a button script.
fn scripted_form() -> Vec<u8> {
scripted_form_with("function times\\(a, b\\) { console.println('times'); return a * b; }")
}
/// [`scripted_form`] with `helpers` (PDF string syntax) as its document-level script.
fn scripted_form_with(helpers: &str) -> Vec<u8> {
let text = |name: &str, y: u32, aa: &str| {
format!("<< /Type /Annot /Subtype /Widget /FT /Tx /T ({name}) /Rect [20 {y} 180 {}] /P 3 0 R /F 4 {aa} >>", y + 20)
};
@@ -4123,7 +4485,7 @@ fn scripted_form() -> Vec<u8> {
"<< /Type /Annot /Subtype /Widget /FT /Btn /Ff 65536 /T (go) /Rect [20 150 80 170] /P 3 0 R /F 4 >>".to_string(),
"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>".to_string(),
"<< >>".to_string(),
"<< /S /JavaScript /JS (function times\\(a, b\\) { console.println('times'); return a * b; }) >>".to_string(),
format!("<< /S /JavaScript /JS ({helpers}) >>"),
];
let mut out = b"%PDF-1.7\n".to_vec();
let mut offsets = Vec::new();
@@ -4185,6 +4547,99 @@ fn scripts_in_an_xfa_form_see_the_xfa_plugin_installed() {
assert_eq!((o.error, o.result.as_deref()), (None, Some("undefined number 3.5")));
}
/// #3940: a document-level script that defines the helper and then calls a method PdfCraft lacks
/// (an Acrobat form copying a button icon at open) left every calculated field blank. The
/// helper stays defined, the form calculates, and the error is reported once.
#[test]
fn a_document_script_that_throws_still_lets_the_form_calculate() {
let helpers =
"function times\\(a, b\\) { return a * b; } this.getField\\('go'\\).buttonSetIcon\\(this.getField\\('go'\\).buttonGetIcon\\(\\)\\);";
let mut s = Session::new().with_clock(|| 1_700_000_000);
let id = s.open("order.pdf", None, Arc::new(scripted_form_with(helpers)), None).unwrap();
let _ = s.take_js_output(id);
s.apply(id, Edit::SetFieldValue { name: "qty".into(), value: FieldValue::Text("4".into()) }).unwrap();
let total = s.get(id).unwrap().form.iter().find(|f| f.name == "total").unwrap().value.clone();
assert_eq!(total, ["10"], "calculated through the helper the failing script defined");
let out = s.take_js_output(id);
assert_eq!(out.errors.len(), 1, "reported once, not once per script: {out:?}");
assert!(out.errors[0].starts_with("document script 1: TypeError"), "{out:?}");
// The console runs too, and says which document script failed.
let o = s.run_javascript(id, "times(2, 3)", None).unwrap();
assert_eq!((o.error, o.result.as_deref(), o.doc_errors.len()), (None, Some("6"), 1));
}
#[test]
fn active_xfa_does_not_run_pdf_container_scripts_but_keeps_requested_alerts() {
let template = pdfcraft_xfa::fixtures::scripted_template().replace(
r#"xfa.host.messageBox("Hello " + qty.rawValue);"#,
r#"xfa.host.messageBox("Hello " + qty.rawValue); xfa.host.print(1, "0", "0", 0, 0, 0, 0, 0);"#,
);
let mut cos = pdfcraft_cos::Document::open(Arc::new(pdfcraft_xfa::fixtures::shell(&template))).unwrap();
let fallback = "app.alert('This PDF form requires a newer version of Adobe Acrobat');";
pdfcraft_forms::set_document_script(&mut cos, "viewerFallback", Some(fallback)).unwrap();
let bytes = Arc::new(pdfcraft_cos::write_full(&cos, &Default::default()).unwrap());
let mut s = Session::new();
let id = s.open("xfa.pdf", None, bytes, None).unwrap();
assert!(s.get(id).unwrap().xfa.is_some());
assert!(s.take_js_output(id).alerts.is_empty());
let out = s.run_javascript(id, "app.alert('Console message');", None).unwrap();
assert!(out.error.is_none(), "{out:?}");
assert_eq!(out.alerts, ["Console message"]);
assert_eq!(s.get(id).unwrap().document_scripts(), [("viewerFallback".into(), fallback.into())]);
let out = s.run_javascript(id, "", Some("hello")).unwrap();
assert!(out.error.is_none(), "{out:?}");
assert_eq!(out.alerts, ["Hello 2"]);
assert_eq!(out.requests, [js::Request::Print]);
// The same context rule applies to format/validate/calculate through JsRunner.
s.apply(id, Edit::SetFieldScript { name: "qty".into(), event: "validate".into(), script: Some("app.alert('Field message');".into()) }).unwrap();
s.take_js_output(id);
s.apply(id, Edit::SetFieldValue { name: "qty".into(), value: FieldValue::Text("3".into()) }).unwrap();
assert_eq!(s.take_js_output(id).alerts, ["Field message"]);
// Saved XFA keeps its container scripts for inspection, but does not execute them.
let saved = s.get(id).unwrap().bytes.clone();
let reopened = s.open("saved.pdf", None, saved, None).unwrap();
assert!(s.run_javascript(reopened, "", None).unwrap().alerts.is_empty());
// Making the form static restores the ordinary PDF context; undo restores XFA's.
s.apply(id, Edit::XfaToStatic).unwrap();
assert_eq!(s.run_javascript(id, "", None).unwrap().alerts.len(), 1);
s.undo(id).unwrap();
assert!(s.run_javascript(id, "", None).unwrap().alerts.is_empty());
}
#[test]
fn active_xfa_without_template_scripts_does_not_initialize_pdf_fallback_scripts() {
let template = r#"<template xmlns="http://www.xfa.org/schema/xfa-template/3.3/">
<subform name="form" layout="tb"><pageSet><pageArea name="page">
<contentArea x="36pt" y="36pt" w="540pt" h="720pt"/><medium short="612pt" long="792pt"/>
</pageArea></pageSet><field name="text" w="200pt" h="30pt"><ui><textEdit/></ui></field></subform></template>"#;
let mut s = Session::new();
let id = s.open("no-scripts.pdf", None, Arc::new(pdfcraft_xfa::fixtures::shell(template)), None).unwrap();
assert!(s.get(id).unwrap().xfa.is_some());
assert!(s.get(id).unwrap().xfa_template.is_none());
s.apply(id, Edit::SetDocumentScript { name: "fallback".into(), script: Some("throw new Error('PDF fallback ran');".into()) }).unwrap();
let out = s.run_javascript(id, "app.alert('Console message');", None).unwrap();
assert!(out.error.is_none(), "{out:?}");
assert_eq!(out.alerts, ["Console message"]);
}
#[test]
fn inactive_xfa_and_ordinary_pdfs_keep_document_helpers_and_alerts() {
for bytes in [
fixture(1),
pdfcraft_xfa::fixtures::static_shell("<form1><page1><name>Test</name></page1></form1>"),
pdfcraft_xfa::fixtures::shell(&pdfcraft_xfa::fixtures::scripted_template()),
] {
let mut cos = pdfcraft_cos::Document::open(Arc::new(bytes)).unwrap();
pdfcraft_forms::set_document_script(&mut cos, "helper", Some("function twice(n) { return n * 2; } app.alert('PDF message');")).unwrap();
// The raw dynamic shell has not been laid out: XFA's presence alone is not enough.
let runner = js::JsRunner::new(&cos, "control.pdf");
let out = pdfcraft_js::run("twice(3)", &pdfcraft_js::Event::doc("Console"), &runner.doc, &[], &runner.doc_scripts, Default::default());
assert!(out.error.is_none(), "{out:?}");
assert_eq!(out.result.as_deref(), Some("6"));
assert_eq!(out.alerts, ["PDF message"]);
}
}
#[test]
fn edit_history_does_not_replay_field_script_side_effects() {
let mut s = Session::new().with_clock(|| 1_700_000_000);
@@ -4675,6 +5130,80 @@ fn measurement_edits_are_transactional_and_honour_annotation_permissions() {
);
}
/// A laid-out XFA field that doesn't scroll (`hScrollPolicy="off"`) opens as a text field with
/// DoNotScroll, and its text box says what fits it: what the editor takes no more than.
#[test]
fn an_xfa_field_that_doesnt_scroll_opens_with_do_not_scroll_and_a_text_box() {
let xdp = r##"<?xml version="1.0" encoding="UTF-8"?>
<xdp:xdp xmlns:xdp="http://ns.adobe.com/xdp/"><template xmlns="http://www.xfa.org/schema/xfa-template/3.3/"><subform name="form" layout="tb">
<field name="code" w="1in" h="0.3in"><ui><textEdit hScrollPolicy="off"/></ui><font typeface="Arial" size="10pt"/></field>
<field name="note" w="1in" h="0.3in"><ui><textEdit/></ui><font typeface="Arial" size="10pt"/></field>
</subform></template></xdp:xdp>"##;
let mut s = Session::new();
let id = s.open("form.pdf", None, Arc::new(pdfcraft_xfa::fixtures::shell(xdp)), None).expect("opens");
let doc = s.get(id).unwrap();
let field = |end: &str| doc.form.iter().find(|f| f.name.ends_with(end)).unwrap_or_else(|| panic!("no field {end}"));
assert!(field("code").has(field_flags::DO_NOT_SCROLL) && !field("note").has(field_flags::DO_NOT_SCROLL));
let tb = doc.field_text_box(&field("code").name, 0).expect("a text box");
assert!(tb.fits("A1B2") && !tb.fits(&"W".repeat(40)), "a 1-inch field at 10 pt");
assert!(doc.field_text_box("no such field", 0).is_none() && doc.field_text_box(&field("code").name, 5).is_none());
}
/// A round XFA check button opens drawn round: the appearance its laid-out widget gets draws a
/// circle, the on state with its mark in it, while a square one keeps its box.
#[test]
fn round_xfa_check_buttons_open_drawn_round() {
let xdp = r##"<?xml version="1.0" encoding="UTF-8"?>
<xdp:xdp xmlns:xdp="http://ns.adobe.com/xdp/"><template xmlns="http://www.xfa.org/schema/xfa-template/3.3/"><subform name="form" layout="tb">
<field name="round" w="1in" h="0.3in"><ui><checkButton shape="round"/></ui><items><integer>1</integer><integer>0</integer></items></field>
<field name="square" w="1in" h="0.3in"><ui><checkButton/></ui><items><integer>1</integer><integer>0</integer></items></field>
</subform></template></xdp:xdp>"##;
let mut s = Session::new();
let id = s.open("form.pdf", None, Arc::new(pdfcraft_xfa::fixtures::shell(xdp)), None).expect("opens");
let cos = s.get(id).unwrap().editor.as_ref().unwrap().cos.clone();
let all = pdfcraft_forms::fields(&cos);
// The decoded appearance of `name`'s widget in `state`.
let drawn = |name: &str, state: &[u8]| {
let w = all.iter().find(|f| f.name.ends_with(name)).unwrap_or_else(|| panic!("no field {name}")).widgets[0].obj;
let wd = cos.get(w).as_dict().cloned().unwrap();
let n = cos.resolve(wd.get(b"AP").unwrap().as_dict().unwrap().get(b"N").unwrap());
let r = n.as_dict().unwrap().reference(state).unwrap_or_else(|| panic!("{name} has no {} state", String::from_utf8_lossy(state)));
let pdfcraft_cos::Object::Stream(st) = &*cos.get(r) else { panic!("a stream") };
String::from_utf8_lossy(&st.decoded().unwrap()).into_owned()
};
for state in [&b"Off"[..], b"1"] {
let round = drawn("round", state);
assert!(round.contains(" c S") && !round.contains(" re S"), "the round one's border is a circle: {round}");
assert!(drawn("square", state).contains(" re S"), "the square one keeps its box");
}
}
#[test]
fn a_dynamic_xfa_form_is_saved_without_the_usage_rights_its_layout_voided() {
let xdp = pdfcraft_xfa::fixtures::template(3);
let original = Arc::new(pdfcraft_xfa::fixtures::usage_rights_shell(&xdp, "", false));
let mut s = Session::new().with_clock(|| 1_700_000_000);
let id = s.open("form.pdf", None, original.clone(), None).expect("opens");
let doc = s.get(id).unwrap();
let warnings = &doc.xfa.as_ref().expect("laid out from the template").warnings;
assert!(warnings.iter().any(|w| w.contains("usage rights")), "the user is told: {warnings:?}");
assert!(!doc.dirty, "laying out is still not an edit");
s.apply(id, Edit::SetFieldValue { name: "familyName".into(), value: FieldValue::Text("Singh".into()) }).unwrap();
let incremental = s.save_bytes(id).unwrap();
assert!(incremental.starts_with(&original[..]), "still an incremental save");
// Saved either way, the file no longer carries them, and keeps what was filled in.
for saved in [incremental, s.save_full_bytes(id).unwrap()] {
let cos = pdfcraft_cos::Document::open(saved.clone()).unwrap();
let catalog = cos.get(cos.root().unwrap()).as_dict().cloned().unwrap();
assert!(!catalog.contains(b"Perms"), "{catalog:?}");
let again = s.open("saved.pdf", None, saved, None).unwrap();
let d2 = s.get(again).unwrap();
assert_eq!(d2.form.iter().find(|f| f.name == "familyName").unwrap().value, vec!["Singh".to_string()]);
let warnings = &d2.xfa.as_ref().expect("the layout is remembered").warnings;
assert!(!warnings.iter().any(|w| w.contains("usage rights")), "nothing left to say: {warnings:?}");
}
}
#[test]
fn dynamic_xfa_forms_are_laid_out_on_open_filled_and_saved_incrementally() {
let original = Arc::new(pdfcraft_xfa::fixtures::shell(&pdfcraft_xfa::fixtures::template(3)));
@@ -5884,6 +6413,149 @@ fn comments_without_appearances_are_drawn_but_not_saved() {
}
}
/// ISO 32000-2 Table 178: with `/LL`, `/L` gives the ends of the leader lines, and the line itself
/// is drawn `/LL` from it (above, for a positive `/LL` on a line drawn left to right). The page
/// view shows the line there, with its leaders down to `/L`, and nothing along `/L` itself.
#[test]
fn a_line_without_an_appearance_is_drawn_at_its_leader_length() {
let objs: Vec<&[u8]> = vec![
b"<< /Type /Catalog /Pages 2 0 R >>",
b"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 200 300] >>",
b"<< /Type /Page /Parent 2 0 R /Annots [4 0 R] >>",
b"<< /Type /Annot /Subtype /Line /Rect [0 0 200 300] /L [40 100 160 100] /LL 30 /C [1 0 0] /BS << /W 4 >> >>",
];
let mut bytes = b"%PDF-1.7\n".to_vec();
let mut offsets = Vec::new();
for (i, o) in objs.iter().enumerate() {
offsets.push(bytes.len());
bytes.extend_from_slice(format!("{} 0 obj\n", i + 1).as_bytes());
bytes.extend_from_slice(o);
bytes.extend_from_slice(b"\nendobj\n");
}
let xref = bytes.len();
bytes.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objs.len() + 1).as_bytes());
for o in offsets {
bytes.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes());
}
bytes.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objs.len() + 1).as_bytes());
let mut s = Session::new().with_clock(|| 1_700_000_000);
let id = s.open("line.pdf", None, Arc::new(bytes), None).expect("opens");
let p = shown(&s, id, 0);
let px = |x: u32, y: u32| p.rgba[((y * p.width + x) * 4) as usize..][..4].to_vec();
// y down: /L is row 200, the line itself row 170.
assert_eq!(px(100, 170), vec![255, 0, 0, 255], "the line, 30 above /L");
assert_eq!(px(40, 185), vec![255, 0, 0, 255], "the leader line at the start");
assert_eq!(px(160, 185), vec![255, 0, 0, 255], "the leader line at the end");
assert_eq!(px(100, 200), vec![255, 255, 255, 255], "nothing along /L");
}
/// A stamp's `/Rect` and the colour family expected inside it.
type StampRect = ([f64; 4], char);
/// Rubber stamps without an appearance (ISO 32000-2 Table 184): the fourteen standard names, one
/// without `/Name`, one custom name, and last a Draft stamp with artwork of its own (magenta).
/// Each sits in a 120 × 60 `/Rect` on a 612 × 792 page; the name and the expected colour family
/// (`'r'`, `'g'`, `'b'`, or `'n'` for the neutral placeholder) of each, in page order.
fn stamps_without_appearances() -> (Arc<Vec<u8>>, Vec<StampRect>) {
let stamps: [(Option<&str>, char); 16] = [
(Some("Approved"), 'g'),
(Some("Experimental"), 'b'),
(Some("NotApproved"), 'r'),
(Some("AsIs"), 'b'),
(Some("Expired"), 'r'),
(Some("NotForPublicRelease"), 'r'),
(Some("Confidential"), 'r'),
(Some("Final"), 'g'),
(Some("Sold"), 'g'),
(Some("Departmental"), 'b'),
(Some("ForComment"), 'b'),
(Some("TopSecret"), 'r'),
(Some("Draft"), 'b'),
(Some("ForPublicRelease"), 'b'),
(None, 'b'),
(Some("MyCustomStamp"), 'n'),
];
let mut objs: Vec<String> =
vec!["<< /Type /Catalog /Pages 2 0 R >>".into(), "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 612 792] >>".into(), String::new()];
let mut expected = Vec::new();
for (i, (name, family)) in stamps.iter().enumerate() {
let (x, y) = (30 + (i % 4) * 145, 660 - (i / 4) * 150);
let rect = [x as f64, y as f64, x as f64 + 120.0, y as f64 + 60.0];
let name = name.map(|n| format!("/Name /{n}")).unwrap_or_default();
objs.push(format!("<< /Type /Annot /Subtype /Stamp /Rect [{} {} {} {}] {name} /F 4 >>", rect[0], rect[1], rect[2], rect[3]));
expected.push((rect, *family));
}
let own = objs.len() + 2;
objs.push(format!("<< /Type /Annot /Subtype /Stamp /Rect [30 60 150 120] /Name /Draft /F 4 /AP << /N {own} 0 R >> >>"));
expected.push(([30.0, 60.0, 150.0, 120.0], 'm'));
objs.push("<< /Type /XObject /Subtype /Form /BBox [0 0 10 10] /Length 23 >>\nstream\n1 0 1 rg 0 0 10 10 re f\nendstream".into());
let annots: Vec<String> = (4..own).map(|n| format!("{n} 0 R")).collect();
objs[2] = format!("<< /Type /Page /Parent 2 0 R /Annots [{}] >>", annots.join(" "));
let mut bytes = b"%PDF-1.7\n".to_vec();
let mut offsets = Vec::new();
for (i, o) in objs.iter().enumerate() {
offsets.push(bytes.len());
bytes.extend_from_slice(format!("{} 0 obj\n{o}\nendobj\n", i + 1).as_bytes());
}
let xref = bytes.len();
bytes.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objs.len() + 1).as_bytes());
for o in offsets {
bytes.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes());
}
bytes.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objs.len() + 1).as_bytes());
(Arc::new(bytes), expected)
}
/// The colour family of an RGBA pixel that isn't white: `'r'`, `'g'` or `'b'` for the dominant
/// channel, `'n'` for a grey, `'m'` for magenta.
fn colour_family(p: &[u8]) -> Option<char> {
let (r, g, b) = (i32::from(p[0]), i32::from(p[1]), i32::from(p[2]));
if r.min(g).min(b) > 200 {
return None;
}
Some(if (r - g).abs() < 24 && (g - b).abs() < 24 {
'n'
} else if r > 200 && b > 200 && g < 80 {
'm'
} else if r > g && r > b {
'r'
} else if g > r && g > b {
'g'
} else {
'b'
})
}
/// Rubber stamps without an appearance are drawn from their `/Name` (ISO 32000-2 Table 184), in
/// the colour of the stamp they name; an unknown name gets a grey placeholder; a stamp's own
/// artwork is drawn as it is. Display only: Save writes the file without new appearances.
#[test]
fn stamps_without_appearances_draw_the_stamp_they_name() {
let (original, expected) = stamps_without_appearances();
let mut s = Session::new();
let id = s.open("stamps.pdf", None, original.clone(), None).expect("opens");
let p = shown(&s, id, 0);
for (i, (rect, family)) in expected.iter().enumerate() {
let mut counts = std::collections::HashMap::new();
for y in (792.0 - rect[3]) as u32..(792.0 - rect[1]) as u32 {
for x in rect[0] as u32..rect[2] as u32 {
let px = &p.rgba[((y * p.width + x) * 4) as usize..][..4];
if let Some(f) = colour_family(px) {
*counts.entry(f).or_insert(0) += 1;
}
}
}
let total: u32 = counts.values().sum();
let main = counts.iter().max_by_key(|(_, n)| **n).map(|(f, _)| *f);
assert!(total > 300, "stamp {i} draws ink inside its /Rect: {counts:?}");
assert_eq!(main, Some(*family), "stamp {i} is drawn in its colour: {counts:?}");
}
let saved = pdfcraft_cos::Document::open(s.save_bytes(id).unwrap()).unwrap();
for n in 4..20 {
assert!(saved.get(pdfcraft_cos::ObjRef::new(n, 0)).as_dict().is_some_and(|d| !d.contains(b"AP")), "{n} is saved without /AP");
}
}
/// A page with a FreeText comment that has no `/AP` stream: the smallest case behind #2371.
fn free_text_without_appearance() -> Arc<Vec<u8>> {
let objs: Vec<&[u8]> = vec![
@@ -6369,6 +7041,7 @@ fn content_edit_keeps_pages_annotations_fields_and_links() {
size: 12.0,
color: [0.0, 0.0, 0.0],
align: TextAlign::Left,
char_spacing: 0.0,
};
session.apply(id, Edit::AddText { page: 1, text }).unwrap();
let after = session.get(id).unwrap();
@@ -6408,6 +7081,7 @@ fn content_refresh_lists_match_the_storages_an_edit_touches() {
size: 12.0,
color: [0.0, 0.0, 0.0],
align: TextAlign::Left,
char_spacing: 0.0,
},
},
Edit::MoveObjects { page: 0, objects: vec![target(crate::ObjectKind::Added)], offset: [1.0, 0.0] },
@@ -6930,6 +7604,18 @@ fn text_blocks_stay_cached_after_an_edit_and_follow_undo_and_redo() {
assert!(Arc::ptr_eq(&redone, &blocks(&session)));
}
/// #4199, #3797: the spaces typed into a paragraph are all there after saving and reopening.
#[test]
fn edited_text_keeps_every_space_typed_through_save_and_reopen() {
let (mut s, id) = session_with(1);
let typed = " A b c";
s.apply(id, Edit::EditTextBlock { page: 0, block: 0, text: typed.into(), style: pdfcraft_edit::BlockStyle::default() }).unwrap();
let saved = s.save_bytes(id).unwrap();
let reopened = s.open("saved.pdf", None, saved, None).unwrap();
let blocks = s.get(reopened).unwrap().editor.as_ref().unwrap().text_blocks(0).unwrap();
assert_eq!(blocks[0].editor_text, typed);
}
/// A new document, or one restored from recovery, has never been written where it belongs: undo
/// back to the bytes it was opened from must not make it clean, or closing it would discard the
/// whole document without asking. Saving makes it clean; Revert of a saved one too.
@@ -7393,6 +8079,100 @@ fn exporting_office_keeps_dotted_leader_entries_as_paragraphs() {
assert!(positions.windows(2).all(|pair| pair[0] < pair[1]), "reading order: {html}");
}
/// A date typed in another of an XFA date field's edit patterns is kept in its first: yymmdd and
/// yyyymd are rewritten as yyyymmdd, a date none of them reads is refused, and the data holds the date.
#[test]
fn a_date_typed_by_another_of_an_xfa_fields_edit_patterns_is_kept_in_its_first() {
let mut s = Session::new();
let id = s
.open("dates.pdf", None, Arc::new(pdfcraft_xfa::fixtures::shell(&pdfcraft_xfa::fixtures::date_alternatives_template())), None)
.expect("opens");
let value = |s: &Session| s.get(id).unwrap().form.iter().find(|f| f.name == "leave").unwrap().value.clone();
s.apply(id, Edit::SetFieldValue { name: "leave".into(), value: FieldValue::Text("261018".into()) }).expect("yymmdd is one of its patterns");
assert_eq!(value(&s), ["20261018"]);
s.apply(id, Edit::SetFieldValue { name: "leave".into(), value: FieldValue::Text("2026118".into()) }).expect("so is yyyymd");
assert_eq!(value(&s), ["20261108"]);
let refused = s.apply(id, Edit::SetFieldValue { name: "leave".into(), value: FieldValue::Text("2618".into()) });
assert!(refused.is_err_and(|e| e.to_string().contains("yyyymmdd")), "none of its patterns reads it");
assert_eq!(value(&s), ["20261108"]);
// The data holds the date.
let cos = pdfcraft_cos::Document::open(s.save_bytes(id).unwrap()).unwrap();
let data = pdfcraft_xfa::parse_datasets(&pdfcraft_xfa::read_packets(&cos).unwrap().unwrap().xdp).expect("a datasets packet");
assert_eq!(data.text_at(&pdfcraft_xfa::som_to_path("form[0].leave[0]")), Some("2026-11-08"));
}
/// A date the field's own scripts refuse is not tried again in another of an XFA date field's
/// patterns: only a date its format refuses is, which happens before any script runs, so the
/// scripts run once. This validate script counts its runs in `name` and accepts on its second.
#[test]
fn a_date_its_validate_script_refuses_is_not_tried_again() {
let mut s = Session::new();
let id = s
.open("dates.pdf", None, Arc::new(pdfcraft_xfa::fixtures::shell(&pdfcraft_xfa::fixtures::date_alternatives_template())), None)
.expect("opens");
let script = Some("var n = Number(getField('name').value || 0) + 1; getField('name').value = String(n); event.rc = n >= 2;".to_string());
s.apply(id, Edit::SetFieldScript { name: "leave".into(), event: "validate".into(), script }).unwrap();
let value = |s: &Session, n: &str| s.get(id).unwrap().form.iter().find(|f| f.name == n).unwrap().value.clone();
// Its format reads 18OCT26, and so does its DDMMMYY pattern.
let refused = s.apply(id, Edit::SetFieldValue { name: "leave".into(), value: FieldValue::Text("18OCT26".into()) });
assert!(refused.is_err(), "the validate script refused it, once");
assert!(value(&s, "name").is_empty(), "nothing the refused run changed is kept: {:?}", value(&s, "name"));
}
/// An XFA button's click script may show the attachments panel; a text field's exit script
/// asking the same is noted on the console and ignored.
#[test]
fn an_xfa_button_may_show_a_side_panel_and_other_events_may_not() {
let xdp = r##"<?xml version="1.0" encoding="UTF-8"?>
<xdp:xdp xmlns:xdp="http://ns.adobe.com/xdp/">
<template xmlns="http://www.xfa.org/schema/xfa-template/3.3/">
<subform name="form" layout="tb">
<pageSet><pageArea name="front"><contentArea x="0.5in" y="0.5in" w="7.5in" h="10in"/><medium short="8.5in" long="11in"/></pageArea></pageSet>
<field name="files" w="2in" h="0.3in"><ui><button/></ui><caption><value><text>Attachments</text></value></caption>
<event activity="click"><script contentType="application/x-javascript">app.execMenuItem("ShowHideFileAttachment");</script></event></field>
<field name="note" w="2in" h="0.3in"><ui><textEdit/></ui>
<event activity="exit"><script contentType="application/x-javascript">app.execMenuItem("ShowHideFileAttachment");</script></event></field>
</subform>
</template>
</xdp:xdp>
"##;
let mut s = Session::new();
let id = s.open("files.pdf", None, Arc::new(pdfcraft_xfa::fixtures::shell(xdp)), None).expect("opens");
s.take_js_output(id);
s.apply(id, Edit::XfaEvent { som: "form[0].files[0]".into(), activity: "click".into() }).unwrap();
let out = s.take_js_output(id);
assert_eq!(out.requests, [pdfcraft_js::Request::ShowPanel(pdfcraft_js::Panel::Attachments)], "{out:?}");
s.apply(id, Edit::SetFieldValue { name: "note".into(), value: FieldValue::Text("x".into()) }).unwrap();
let out = s.take_js_output(id);
assert!(out.requests.is_empty(), "only a click shows a panel: {out:?}");
assert!(out.console.iter().any(|c| c.contains("show a side panel")), "{:?}", out.console);
}
/// A validate script that asks for Save As and a side panel gets neither, with a console note
/// for each; a button's script may still open Save As.
#[test]
fn a_fields_own_script_may_not_save_as_or_show_a_panel() {
let mut s = Session::new().with_clock(|| 1_700_000_000);
let id = s.open("order.pdf", None, Arc::new(scripted_form()), None).unwrap();
s.apply(
id,
Edit::SetFieldScript {
name: "qty".into(),
event: "validate".into(),
script: Some("app.execMenuItem('SaveAs'); app.execMenuItem('ShowHideFileAttachment');".into()),
},
)
.unwrap();
s.take_js_output(id);
s.apply(id, Edit::SetFieldValue { name: "qty".into(), value: FieldValue::Text("4".into()) }).unwrap();
let out = s.take_js_output(id);
assert!(out.requests.is_empty(), "a validate script runs unasked: {out:?}");
assert_eq!(out.console.iter().filter(|c| c.contains("only a button may")).count(), 2, "{:?}", out.console);
// A button's script may.
let o = s.run_javascript(id, "app.execMenuItem('SaveAs');", Some("go")).unwrap();
assert_eq!(o.requests, [js::Request::SaveAs]);
}
/// A page whose forms go past the reading limit and whose picture goes past the image budget is
/// listed once among the truncated pages.
#[test]
@@ -7438,3 +8218,109 @@ fn a_page_truncated_for_forms_and_pictures_is_listed_once() {
assert!(pages[0].images.is_empty(), "the picture is past the budget");
assert_eq!(truncated, [0]);
}
/// ISO 32000-2 Table 192, 12.7.5.2.3 and Table 228 (Comb): a check box, a push button, a comb
/// field the file leaves to the viewer. The page as displayed and printed as an image shows the
/// check box's caption symbol in its text colour, the button's grey face and the comb's cells in
/// the border colour, and saving writes the file as it was.
#[test]
fn buttons_and_combs_left_to_the_viewer_are_displayed() {
let pdf = b"%PDF-1.7\n\
1 0 obj << /Type /Catalog /Pages 2 0 R /AcroForm 4 0 R >> endobj\n\
2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj\n\
3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 400 200] /Annots [6 0 R 7 0 R 8 0 R] >> endobj\n\
4 0 obj << /Fields [6 0 R 7 0 R 8 0 R] /DA (/Helv 0 Tf 0 g) /DR << /Font << /Helv 5 0 R >> >> >> endobj\n\
5 0 obj << /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >> endobj\n\
6 0 obj << /Type /Annot /Subtype /Widget /FT /Btn /T (k) /V /Yes /AS /Yes /DA (/ZaDb 0 Tf 1 0 0 rg) /MK << /CA (8) /BC [0 0 0] >> /Rect [20 150 60 190] /F 4 /P 3 0 R >> endobj\n\
7 0 obj << /Type /Annot /Subtype /Widget /FT /Btn /Ff 65536 /T (o) /DA (/Helv 12 Tf 0 g) /MK << /CA (Press) /BG [0.8 0.8 0.8] /BC [0 0 0] >> /BS << /W 2 /S /B >> /Rect [100 150 220 190] /F 4 /P 3 0 R >> endobj\n\
8 0 obj << /Type /Annot /Subtype /Widget /FT /Tx /Ff 16777216 /MaxLen 4 /T (d) /V (AB) /DA (/Helv 12 Tf 0 g) /MK << /BC [0 0 1] >> /Rect [20 80 220 110] /F 4 /P 3 0 R >> endobj\n\
trailer << /Root 1 0 R >>\n%%EOF"
.to_vec();
let render = |bytes: Arc<Vec<u8>>| {
let mut r = pdfcraft_render::PageRenderer::new(bytes, pdfcraft_render::RenderConfig::default());
r.render(pdfcraft_render::RenderRequest { page: 0, scale: 1.0, ..Default::default() })
};
// Pixels of the page (drawn at scale 1, 400 x 200) in user-space box x0..x1, y0..y1 that `keep`.
let count = |page: &pdfcraft_render::RenderedPage, (x0, y0, x1, y1): (u32, u32, u32, u32), keep: &dyn Fn(&[u8; 4]) -> bool| {
let (px, _) = page.rgba.as_chunks::<4>();
(200 - y1..200 - y0)
.flat_map(|y| (x0..x1).map(move |x| (x, y)))
.filter(|&(x, y)| px.get((y * page.width + x) as usize).is_some_and(keep))
.count()
};
let red = |p: &[u8; 4]| p[0] > 200 && p[1] < 80 && p[2] < 80;
let grey = |p: &[u8; 4]| (180..=230).contains(&p[0]) && p[0] == p[1] && p[1] == p[2];
// Bluish: a 1 pt line on a pixel edge is half blue on each side.
let blue = |p: &[u8; 4]| p[2] > 200 && p[0] < 180 && p[1] < 180 && p[0] + 40 < p[2];
let mut s = Session::new();
let id = s.open("form.pdf", None, Arc::new(pdf), None).unwrap();
let shown = render(s.get(id).unwrap().display.clone());
assert!(count(&shown, (24, 154, 56, 186), &red) > 60, "the check box's red cross");
assert!(count(&shown, (104, 154, 216, 186), &grey) > 1000, "the push button's grey face");
// The comb's three inner lines at x = 70, 120 and 170, between its cells.
for x in [70, 120, 170] {
assert!(count(&shown, (x - 1, 84, x + 1, 106), &blue) >= 20, "a cell line at {x}");
}
assert_eq!(count(&shown, (95, 84, 97, 106), &blue), 0, "no line inside a cell");
// Print as Image: the page as a picture, at 72 dpi so it is the size of the page here.
let raster = pdfcraft_print::Raster { dpi: 72.0, grayscale: false };
let pictures = crate::print_raster::rasterize(s.get(id).unwrap(), &[0], &raster, pdfcraft_print::Content::Document).unwrap();
let printed = render(Arc::new(pictures));
assert!(count(&printed, (24, 154, 56, 186), &red) > 60, "the check box prints");
assert!(count(&printed, (104, 154, 216, 186), &grey) > 1000, "and the push button");
// The file is saved as it was: no widget has an appearance.
let saved = pdfcraft_cos::Document::open(s.save_bytes(id).unwrap()).unwrap();
for f in pdfcraft_forms::fields(&saved) {
assert!(saved.get(f.widgets[0].obj).as_dict().is_some_and(|d| !d.contains(b"AP")), "{} has no appearance", f.name);
}
}
/// ISO 32000-2 Tables 166 and 183, drawn on the page: a square without an appearance whose
/// `/Border [0 0 3 [6 3]]` names its width before a dash array is stroked 3 pt wide and dashed
/// (it was 1 pt and solid), and a caret with `/Sy /P` shows a ¶ to its right.
#[test]
fn legacy_border_dashes_and_the_caret_paragraph_symbol_are_drawn() {
let original = Arc::new(pdf_with_annots(&[
b"<< /Type /Annot /Subtype /Square /Rect [20 180 120 280] /Border [0 0 3 [6 3]] /C [1 0 0] >>",
b"<< /Type /Annot /Subtype /Caret /Rect [20 20 80 80] /Sy /P /C [0 0 1] >>",
]));
let mut s = Session::new().with_clock(|| 1_700_000_000);
let id = s.open("noap.pdf", None, original, None).expect("opens");
let p = shown(&s, id, 0);
let px = |x: u32, y: u32| p.rgba[((y * p.width + x) * 4) as usize..][..4].to_vec();
// y down: the bottom edge's stroke is centred 1.5 pt inside /Rect, on row 118.
let row: Vec<Vec<u8>> = (24..116).map(|x| px(x, 118)).collect();
let red = row.iter().filter(|c| c[0] > 200 && c[1] < 80).count();
let white = row.iter().filter(|c| c[1] > 200).count();
assert!(red > 40 && white > 15, "3 pt and dashed: {red} red, {white} white");
// The ¶ sits in the right part of the caret's /Rect, where the caret no longer reaches.
let blue = (250..270).flat_map(|y| (68..80).map(move |x| (x, y))).filter(|&(x, y)| {
let c = px(x, y);
c[2] > 150 && c[0] < 100
});
assert!(blue.count() > 20, "the pilcrow is drawn beside the caret");
}
/// A one-page 200 × 300 document whose page lists `annots` (objects 4, 5, …).
fn pdf_with_annots(annots: &[&[u8]]) -> Vec<u8> {
let list: String = (0..annots.len()).map(|i| format!("{} 0 R ", i + 4)).collect();
let page = format!("<< /Type /Page /Parent 2 0 R /Annots [{list}] >>");
let mut objs: Vec<&[u8]> =
vec![b"<< /Type /Catalog /Pages 2 0 R >>", b"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 200 300] >>", page.as_bytes()];
objs.extend_from_slice(annots);
let mut bytes = b"%PDF-1.7\n".to_vec();
let mut offsets = Vec::new();
for (i, o) in objs.iter().enumerate() {
offsets.push(bytes.len());
bytes.extend_from_slice(format!("{} 0 obj\n", i + 1).as_bytes());
bytes.extend_from_slice(o);
bytes.extend_from_slice(b"\nendobj\n");
}
let xref = bytes.len();
bytes.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objs.len() + 1).as_bytes());
for o in offsets {
bytes.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes());
}
bytes.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objs.len() + 1).as_bytes());
bytes
}
+1 -1
View File
@@ -74,5 +74,5 @@ pub fn discover(roots: &[PathBuf]) -> Vec<FontFile> {
files
}
fn font_extension(path: &Path) -> bool {
path.extension().and_then(|e| e.to_str()).is_some_and(|e| e.eq_ignore_ascii_case("ttf") || e.eq_ignore_ascii_case("otf"))
path.extension().and_then(std::ffi::OsStr::to_str).is_some_and(|e| e.eq_ignore_ascii_case("ttf") || e.eq_ignore_ascii_case("otf"))
}
+11 -5
View File
@@ -110,6 +110,16 @@ fn standard_role(doc: &pdfcraft_cos::Document, map: &Dict, role: &[u8]) -> Vec<u
role
}
/// Whether the page's resources hold a Form XObject, whose MCIDs are a separate namespace.
fn page_has_form_xobject(doc: &pdfcraft_cos::Document, page: &pdfcraft_cos::Dict) -> bool {
let resources = page.get(b"Resources").map(|o| doc.resolve(o));
let objects = resources.as_ref().and_then(|o| o.as_dict()).and_then(|d| d.get(b"XObject")).map(|o| doc.resolve(o));
objects
.as_ref()
.and_then(|o| o.as_dict())
.is_some_and(|d| d.iter().any(|(_, value)| matches!(&*doc.resolve(value), Object::Stream(s) if s.dict.name(b"Subtype") == Some(b"Form"))))
}
type Exclusions = HashMap<usize, HashSet<i32>>;
/// Resolve page-local MCIDs through the structure hierarchy, including inherited roles and
@@ -179,11 +189,7 @@ fn exclusions(source: &ExportSource, options: Options) -> Result<(Exclusions, bo
if !out.contains_key(&index) {
continue;
}
let resources = page.dict.get(b"Resources").map(|o| doc.resolve(o));
let objects = resources.as_ref().and_then(|o| o.as_dict()).and_then(|d| d.get(b"XObject")).map(|o| doc.resolve(o));
let has_form = objects.as_ref().and_then(|o| o.as_dict()).is_some_and(|d| {
d.iter().any(|(_, value)| matches!(&*doc.resolve(value), Object::Stream(s) if s.dict.name(b"Subtype") == Some(b"Form")))
});
let has_form = page_has_form_xobject(&doc, &page.dict);
if has_form {
out.remove(&index);
unclassified = true;
+25 -1
View File
@@ -53,6 +53,7 @@ fn click_only(e: &XfaEffect) -> Option<&'static str> {
XfaEffect::Print => Some("print"),
XfaEffect::SaveAs => Some("save"),
XfaEffect::LaunchUrl(_) => Some("open a link"),
XfaEffect::ShowPanel(_) => Some("show a side panel"),
XfaEffect::SetFocus(_) => Some("move the focus"),
_ => None,
}
@@ -532,7 +533,7 @@ impl<'a, 'b> Runner<'a, 'b> {
} else {
Some(by_som.iter().filter(|(som, _)| names.iter().any(|n| som_matches(som, n))).map(|(_, f)| f.clone()).collect())
};
if listed.as_ref().is_some_and(|l| l.is_empty()) {
if listed.as_ref().is_some_and(Vec::is_empty) {
return Ok(());
}
pdfcraft_forms::reset(self.doc, listed.as_deref()).map_err(|e| e.to_string())?;
@@ -628,6 +629,7 @@ impl<'a, 'b> Runner<'a, 'b> {
XfaEffect::Print => self.run.out.requests.push(Request::Print),
XfaEffect::SaveAs => self.run.out.requests.push(Request::SaveAs),
XfaEffect::LaunchUrl(u) => self.run.out.requests.push(Request::LaunchUrl(u.clone())),
XfaEffect::ShowPanel(p) => self.run.out.requests.push(Request::ShowPanel(*p)),
XfaEffect::SetFocus(som) => {
if let Some(name) = self.by_som().get(som).cloned() {
self.run.out.requests.push(Request::Focus(name));
@@ -858,6 +860,28 @@ pub(crate) fn on_data_replaced(doc: &mut pdfcraft_cos::Document, tpl: &Template,
r.finish().map(|_| ())
}
/// A text value typed into the laid-out XFA date field `name` by another of its edit picture's
/// patterns, written in the first ([`pdfcraft_xfa::typed_date`]); `None` for anything else.
/// `tpl` is the template the scripts use, when they run; otherwise it is read from `doc`.
pub(crate) fn typed_date(
doc: &pdfcraft_cos::Document,
tpl: Option<&Template>,
name: &str,
value: &pdfcraft_forms::FieldValue,
) -> Option<pdfcraft_forms::FieldValue> {
let pdfcraft_forms::FieldValue::Text(text) = value else { return None };
let som = pdfcraft_xfa::fields_by_som(doc).into_iter().find_map(|(som, n)| (n == name).then_some(som))?;
let read;
let tpl = match tpl {
Some(t) => t,
None => {
read = pdfcraft_xfa::template_of(doc).ok()?;
&read
}
};
pdfcraft_xfa::typed_date(tpl, &som, text).map(pdfcraft_forms::FieldValue::Text)
}
/// A button's click script (or any event, by SOM path and activity), then calculations.
pub(crate) fn on_event(doc: &mut pdfcraft_cos::Document, tpl: &Template, som: &str, activity: &str, run: &mut XfaRun) -> Result<(), String> {
let mut r = Runner::new(doc, tpl, run, EVENT_BUDGET_MS);
+80 -12
View File
@@ -246,7 +246,7 @@ pub(crate) fn tables(blocks: &[Block]) -> (Vec<Table>, Vec<bool>) {
used.sort_unstable();
used.dedup();
let mut edges: Vec<f64> = used.iter().filter_map(|&i| col_of.get(i).copied().flatten()).filter_map(|ci| cols.get(ci)).map(|c| c.0).collect();
edges.sort_by(|a, b| a.total_cmp(b));
edges.sort_by(f64::total_cmp);
edges.dedup_by(|a, b| (*a - *b).abs() <= COL_TOL);
let ncols = edges.len();
let ok = (ncols >= 3 || (ncols == 2 && run.len() >= 3)) && ncols <= MAX_COLS;
@@ -256,7 +256,7 @@ pub(crate) fn tables(blocks: &[Block]) -> (Vec<Table>, Vec<bool>) {
}
let right = used.iter().map(|&i| blocks[i].rect[2]).fold(f64::MIN, f64::max) + COL_TOL;
let mut rows_out = Vec::new();
let mut slots: Vec<Option<Cell>> = vec![None; ncols];
let mut slots: Vec<Option<(Cell, Vec<usize>)>> = vec![None; ncols];
for row in run.drain(..) {
for slot in slots.iter_mut() {
*slot = None;
@@ -266,20 +266,28 @@ pub(crate) fn tables(blocks: &[Block]) -> (Vec<Table>, Vec<bool>) {
let Some(slot) = edges.iter().position(|e| (*e - b.rect[0]).abs() <= COL_TOL) else { continue };
let span = edges[slot + 1..].iter().filter(|e| **e > b.rect[0] + COL_TOL && **e < b.rect[2] - COL_TOL).count() + 1;
let cell = Cell { text: b.text.trim().to_string(), size: b.size, bold: b.bold, italic: b.italic, color: b.color, span };
match &mut slots[slot] {
Some(c) => {
match slots.get_mut(slot) {
Some(Some((c, sources))) => {
c.text.push(' ');
c.text.push_str(&cell.text);
sources.push(bi);
}
None => slots[slot] = Some(cell),
Some(empty @ None) => *empty = Some((cell, vec![bi])),
None => continue,
}
consumed[bi] = true;
}
let mut materialized = Vec::with_capacity(ncols);
let mut column = 0;
while column < ncols {
match slots[column].take() {
Some(mut cell) => {
match slots.get_mut(column).and_then(Option::take) {
Some((mut cell, sources)) => {
// A spanning cell can skip later slots. Only consume source blocks
// when their text is emitted, leaving covered text in paragraph flow.
for bi in sources {
if let Some(taken) = consumed.get_mut(bi) {
*taken = true;
}
}
cell.span = cell.span.min(ncols - column).max(1);
column += cell.span;
materialized.push(cell);
@@ -313,7 +321,7 @@ pub(crate) fn tables(blocks: &[Block]) -> (Vec<Table>, Vec<bool>) {
let run_edges = |run: &[Vec<(usize, usize)>]| -> Vec<f64> {
let mut es: Vec<f64> =
run.iter().flatten().filter_map(|(_, i)| col_of.get(*i).copied().flatten()).filter_map(|ci| cols.get(ci)).map(|c| c.0).collect();
es.sort_by(|a, b| a.total_cmp(b));
es.sort_by(f64::total_cmp);
es.dedup_by(|a, b| (*a - *b).abs() <= COL_TOL);
es
};
@@ -517,17 +525,18 @@ fn docx_table(t: &Table) -> String {
s.push_str("</w:tblGrid>");
for row in &t.rows {
s.push_str("<w:tr>");
let mut column = 0usize;
for c in row {
let span = if c.span > 1 { format!("<w:gridSpan w:val=\"{}\"/>", c.span) } else { String::new() };
let w: i64 = widths.iter().take(c.span.min(widths.len())).sum();
let w: i64 = widths.iter().skip(column).take(c.span).sum();
s.push_str(&format!(
"<w:tc><w:tcPr><w:tcW w:w=\"{w}\" w:type=\"dxa\"/>{span}</w:tcPr><w:p>{}</w:p></w:tc>",
run_xml(&c.text, c.size, c.bold, c.italic, c.color)
));
column = column.saturating_add(c.span);
}
// Pad the grid so every row covers all columns (Word rejects short rows).
let used: usize = row.iter().map(|c| c.span).sum();
for _ in used..t.cols.len() {
for _ in column..t.cols.len() {
s.push_str("<w:tc><w:tcPr><w:tcW w:w=\"0\" w:type=\"auto\"/></w:tcPr><w:p/></w:tc>");
}
s.push_str("</w:tr>");
@@ -1040,6 +1049,27 @@ mod tests {
assert!(xml.contains("<w:insideH w:val=\"nil\"/>"));
}
#[test]
fn word_table_cell_widths_follow_the_columns_they_span() {
let cell = |text: &str, span| Cell { text: text.into(), size: 11.0, bold: false, italic: false, color: [0.0; 3], span };
let table = Table {
rect: [0.0, 0.0, 300.0, 100.0],
cols: vec![0.0, 50.0, 150.0],
rows: vec![
vec![cell("First", 1), cell("Second", 1), cell("Third", 1)],
vec![cell("First", 1), cell("Last two", 2)],
vec![cell("First two", 2), cell("Third", 1)],
vec![cell("All", 3)],
vec![cell("First", 1)],
],
};
let xml = docx_table(&table);
assert!(xml.contains("<w:gridCol w:w=\"1000\"/><w:gridCol w:w=\"2000\"/><w:gridCol w:w=\"3000\"/>"), "{xml}");
let widths: Vec<Vec<&str>> =
xml.split("<w:tr>").skip(1).map(|row| row.split("<w:tcW w:w=\"").skip(1).map(|cell| cell.split('"').next().unwrap()).collect()).collect();
assert_eq!(widths, vec![vec!["1000", "2000", "3000"], vec!["1000", "5000"], vec!["3000", "3000"], vec!["6000"], vec!["1000", "0", "0"]]);
}
#[test]
fn word_keeps_a_page_with_a_clear_image_and_big_title_in_flow() {
// page() has a picture between paragraphs and a 24 pt title over 11 pt body text, but
@@ -1392,6 +1422,40 @@ mod tests {
assert_eq!(h.matches("https://example.org/event").count(), 3, "{h}");
}
/// A continuation can drift into a grid column covered by the preceding cell's span.
/// It must remain available as paragraph text if that slot never becomes an output cell.
#[test]
fn table_spans_do_not_consume_text_they_do_not_emit() {
let mut blocks = vec![
Block { size: 12.0, ..block("ABCDEFGHIJK", 72.1, 697.0, 151.3, 710.8) },
Block { size: 12.0, color: [0.0, 0.0, 1.0], ..block("LOST", 150.4, 697.0, 179.2, 710.8) },
Block { size: 12.0, ..block("R0", 250.0, 697.0, 264.4, 710.8) },
];
for row in 1..=4 {
let y = 697.0 - f64::from(row) * 50.0;
for (text, left, right) in [(format!("L{row}"), 72.1, 86.5), (format!("M{row}"), 146.4, 160.8), (format!("R{row}"), 250.0, 264.4)] {
blocks.push(Block { size: 12.0, ..block(&text, left, y, right, y + 13.8) });
}
}
let p = Page { width: 612.0, height: 792.0, blocks, ..Page::default() };
let (tables, consumed) = tables(&p.blocks);
assert_eq!(tables.len(), 1);
assert_eq!(tables[0].rows[0][0].span, 2);
assert!(!consumed[1], "a covered slot did not emit its text");
assert!(consumed.iter().enumerate().all(|(index, used)| index == 1 || *used));
let outputs = [
html(std::slice::from_ref(&p), "Continuations"),
part(&docx(std::slice::from_ref(&p), "Continuations"), "word/document.xml"),
rtf(std::slice::from_ref(&p)),
part(&pptx(std::slice::from_ref(&p), "Continuations"), "ppt/slides/slide1.xml"),
];
for output in outputs {
for b in &p.blocks {
assert_eq!(output.matches(&b.text).count(), 1, "{} must survive exactly once", b.text);
}
}
}
/// #2806: a superscript right after a number ("1" "st") continues its cell; the prize table
/// around it stays a table.
#[test]
@@ -1407,6 +1471,10 @@ mod tests {
let h = html(std::slice::from_ref(&p), "Prizes");
assert!(h.contains("<table>"), "the prize table was lost: {h}");
assert!(h.contains("30,000") && h.contains("15,000"), "{h}");
let (tables, consumed) = tables(&p.blocks);
assert!(consumed.iter().all(|used| *used), "ordinary table continuations stay in their cells");
let cells: Vec<&str> = tables.iter().flat_map(|t| &t.rows).flatten().map(|c| c.text.as_str()).collect();
assert!(["st", "nd", "rd", "th"].iter().all(|suffix| cells.contains(suffix)));
}
#[test]
+59 -17
View File
@@ -2,7 +2,9 @@
//! The recipe is craft-fonts' `docs/integration.md`; unset, `CRAFT_FONTS` is empty. It only reads
//! the local checkout (no network). On wasm32 it embeds only the UI faces (BIZ UDPGothic Regular
//! and any `Arab`, `Telu`, `Hebr`, `Thai` or `Deva` face), to keep the web build within hosting
//! limits (Cloudflare Pages: 25 MiB per file).
//! limits (Cloudflare Pages: 25 MiB per file). Native builds also read the optional
//! `fonts/simplified-chinese-manifest.txt` (LXGW WenKai Lite); it is never embedded on wasm.
//! `CRAFT_FONTS_REQUIRED` makes both the checkout and that native manifest required.
use std::fmt::Write as _;
use std::path::PathBuf;
@@ -14,14 +16,15 @@ fn main() {
println!("cargo::rerun-if-env-changed=CRAFT_FONTS_DIR");
println!("cargo::rerun-if-env-changed=CRAFT_FONTS_REQUIRED");
let mut src = String::from("pub static CRAFT_FONTS: &[CraftFont] = &[\n");
let required = std::env::var_os("CRAFT_FONTS_REQUIRED").is_some();
if let Some(dir) = std::env::var_os("CRAFT_FONTS_DIR").map(PathBuf::from) {
match craft_fonts(&dir) {
match craft_fonts(&dir, required) {
Ok(entries) => src.push_str(&entries),
Err(e) if std::env::var_os("CRAFT_FONTS_REQUIRED").is_some() => {
println!("cargo::error=CRAFT_FONTS_DIR={}: {e}", dir.display());
}
Err(e) if required => println!("cargo::error=CRAFT_FONTS_DIR={}: {e}", dir.display()),
Err(e) => println!("cargo::warning=building without craft-fonts: CRAFT_FONTS_DIR={}: {e}", dir.display()),
}
} else if required {
println!("cargo::error=CRAFT_FONTS_REQUIRED is set but CRAFT_FONTS_DIR is missing");
}
src.push_str("];\n");
let out = PathBuf::from(std::env::var_os("OUT_DIR").unwrap_or_default()).join("craft_fonts.rs");
@@ -30,26 +33,62 @@ fn main() {
}
}
/// One `CraftFont { .. }` initialiser per manifest line.
fn craft_fonts(dir: &std::path::Path) -> Result<String, String> {
let manifest = dir.join("fonts/manifest.txt");
println!("cargo::rerun-if-changed={}", manifest.display());
let text = std::fs::read_to_string(&manifest).map_err(|e| format!("{}: {e}", manifest.display()))?;
/// The main manifest, plus the native-only Simplified Chinese manifest. The latter is optional
/// for ordinary builds and required when `CRAFT_FONTS_REQUIRED` is set, so a required build can
/// never pass the Chinese UI tests only by skipping them.
fn craft_fonts(dir: &std::path::Path, required: bool) -> Result<String, String> {
let wasm = std::env::var("CARGO_CFG_TARGET_ARCH").is_ok_and(|a| a == "wasm32");
let mut out = manifest(dir, &dir.join("fonts/manifest.txt"), wasm, false)?;
if !wasm {
let chinese = dir.join("fonts/simplified-chinese-manifest.txt");
println!("cargo::rerun-if-changed={}", chinese.display());
match chinese.try_exists() {
Ok(false) if required => {
return Err(format!("{}: CRAFT_FONTS_REQUIRED is set but the simplified-Chinese font manifest is missing", chinese.display()));
}
Ok(false) => {}
Ok(true) => match manifest(dir, &chinese, false, required) {
Ok(entries) => out.push_str(&entries),
// A broken optional addition must never discard the main Japanese/symbol/RTL faces.
Err(e) if required => return Err(e),
Err(e) => println!("cargo::warning=skipping optional Chinese fonts: {e}"),
},
Err(e) if required => return Err(format!("{}: {e}", chinese.display())),
Err(e) => println!("cargo::warning=skipping optional Chinese fonts: {}: {e}", chinese.display()),
}
}
Ok(out)
}
/// One `CraftFont { .. }` initialiser per manifest line.
///
/// `strict_cap` is set for the required native Simplified Chinese manifest: a face that does not
/// fit its cap must fail the build rather than be silently left out, so a required build cannot
/// pass without the Chinese face it promises.
fn manifest(dir: &std::path::Path, manifest: &std::path::Path, wasm: bool, strict_cap: bool) -> Result<String, String> {
println!("cargo::rerun-if-changed={}", manifest.display());
let text = std::fs::read_to_string(manifest).map_err(|e| format!("{}: {e}", manifest.display()))?;
let mut out = String::new();
for line in text.lines().map(str::trim).filter(|l| !l.is_empty() && !l.starts_with('#')) {
let f: Vec<&str> = line.split(" | ").map(str::trim).collect();
let [family, style, file, scripts, ..] = f.as_slice() else {
return Err(format!("malformed manifest line: {line}"));
};
// Whole CJK faces aren't embedded for size; interface CJK comes from cut faces once the app
// moves to craft-fonts-build (storytold/craft-libs#213).
// Keep the upstream general CJK size cap. The separately pinned native Chinese UI
// face has its own bound; web builds retain the smaller general limit. A required
// Chinese face over its cap fails the build instead of being silently omitted.
let cjk = scripts.split(',').any(cjk_scripts::is_cjk_script);
if cjk
&& !cjk_scripts::WHOLE_CJK_FAMILIES.contains(family)
&& std::fs::metadata(dir.join(file)).is_ok_and(|m| m.len() > cjk_scripts::MAX_OTHER_CJK_BYTES)
{
continue;
if cjk && let Ok(metadata) = std::fs::metadata(dir.join(file)) {
match cjk_scripts::cjk_size_decision(family, metadata.len(), wasm, strict_cap) {
cjk_scripts::CjkSizeDecision::Embed => {}
cjk_scripts::CjkSizeDecision::Skip => continue,
cjk_scripts::CjkSizeDecision::Reject => {
let cap = cjk_scripts::cjk_cap_bytes(family, wasm);
return Err(format!(
"{file}: the {family} face is larger than the {cap}-byte native Chinese UI cap; CRAFT_FONTS_REQUIRED cannot embed it"
));
}
}
}
// Arabic interface faces are small, so the web build keeps them too.
let arabic = scripts.split(',').any(|s| s.trim() == "Arab");
@@ -78,5 +117,8 @@ fn craft_fonts(dir: &std::path::Path) -> Result<String, String> {
path.display().to_string(),
);
}
if strict_cap && out.is_empty() {
return Err(format!("{}: CRAFT_FONTS_REQUIRED is set but no Chinese UI face fits the caps", manifest.display()));
}
Ok(out)
}
+58
View File
@@ -8,6 +8,11 @@ pub const WHOLE_CJK_FAMILIES: [&str; 3] = ["Shippori Mincho", "BIZ UDPGothic", "
/// Any other CJK face over this size is left out.
pub const MAX_OTHER_CJK_BYTES: u64 = 4 << 20;
/// Reviewed native-only UI fallback from the separate Chinese manifest.
/// It is never included in the browser payload. Other CJK families keep the 4 MiB cap.
pub const NATIVE_UI_CJK_FAMILIES: [&str; 1] = ["LXGW WenKai Lite"];
pub const MAX_NATIVE_UI_CJK_BYTES: u64 = 16 << 20;
/// ISO 15924 codes of the Han, Japanese and Korean scripts, Hangul on its own included.
const CJK_SCRIPTS: [&str; 6] = ["Hani", "Hans", "Hant", "Jpan", "Kore", "Hang"];
@@ -17,3 +22,56 @@ pub fn is_cjk_script(tag: &str) -> bool {
let code = tag.trim().split('-').next().unwrap_or_default();
CJK_SCRIPTS.contains(&code)
}
/// What `build.rs` does with one CJK face from a manifest.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CjkSizeDecision {
/// The face fits its cap (or is a Japanese family embedded whole).
Embed,
/// An optional face over its cap: leave it out and keep the rest.
Skip,
/// A required face over its cap: fail the build rather than silently omit it.
Reject,
}
/// The size cap that applies to `family` in this build.
pub fn cjk_cap_bytes(family: &str, wasm: bool) -> u64 {
if !wasm && NATIVE_UI_CJK_FAMILIES.contains(&family) { MAX_NATIVE_UI_CJK_BYTES } else { MAX_OTHER_CJK_BYTES }
}
/// Decide whether a CJK face is embedded, skipped, or rejected.
///
/// The Japanese document/UI families are embedded whole. Every other CJK family uses its cap;
/// `required` marks the native Simplified Chinese manifest of a `CRAFT_FONTS_REQUIRED` build,
/// where an over-cap face must fail instead of quietly disappearing.
pub fn cjk_size_decision(family: &str, bytes: u64, wasm: bool, required: bool) -> CjkSizeDecision {
if WHOLE_CJK_FAMILIES.contains(&family) {
return CjkSizeDecision::Embed;
}
if bytes <= cjk_cap_bytes(family, wasm) {
CjkSizeDecision::Embed
} else if required {
CjkSizeDecision::Reject
} else {
CjkSizeDecision::Skip
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_required_native_chinese_face_over_its_cap_is_rejected_not_skipped() {
let at_cap = MAX_NATIVE_UI_CJK_BYTES;
assert_eq!(cjk_size_decision("LXGW WenKai Lite", at_cap, false, true), CjkSizeDecision::Embed);
assert_eq!(cjk_size_decision("LXGW WenKai Lite", at_cap + 1, false, true), CjkSizeDecision::Reject);
assert_eq!(cjk_size_decision("LXGW WenKai Lite", at_cap + 1, false, false), CjkSizeDecision::Skip);
// The web build keeps the smaller general cap even for the native Chinese family.
assert_eq!(cjk_size_decision("LXGW WenKai Lite", MAX_OTHER_CJK_BYTES + 1, true, true), CjkSizeDecision::Reject);
// Japanese document/UI families are embedded whole.
assert_eq!(cjk_size_decision("BIZ UDPGothic", u64::MAX, false, true), CjkSizeDecision::Embed);
assert_eq!(cjk_cap_bytes("LXGW WenKai Lite", false), MAX_NATIVE_UI_CJK_BYTES);
assert_eq!(cjk_cap_bytes("LXGW WenKai Lite", true), MAX_OTHER_CJK_BYTES);
}
}
+7 -3
View File
@@ -315,12 +315,13 @@ mod tests {
}
/// `build.rs` embeds the Japanese CJK faces whole and any other CJK face only up to
/// `MAX_OTHER_CJK_BYTES`, so a checkout with a large Chinese or Korean face (craft-fonts has the
/// `MAX_OTHER_CJK_BYTES` (the explicitly pinned native-only LXGW UI fallback has a separate
/// 16 MiB cap), so a checkout with a large Chinese or Korean face (craft-fonts has the
/// 16.4 MB Noto Sans CJK SC) leaves it out. The four Japanese faces of the pinned craft-fonts
/// are 24.1 MB.
#[test]
fn cjk_faces_follow_the_size_rule() {
use crate::cjk_scripts::{MAX_OTHER_CJK_BYTES, WHOLE_CJK_FAMILIES, is_cjk_script};
use crate::cjk_scripts::{MAX_NATIVE_UI_CJK_BYTES, MAX_OTHER_CJK_BYTES, NATIVE_UI_CJK_FAMILIES, WHOLE_CJK_FAMILIES, is_cjk_script};
// A tag can carry a region after the code: craft-fonts tags Noto Sans HK UI `Hant-HK`.
assert!(["Hant-HK", "Hans", "Jpan", "Hang"].iter().all(|s| is_cjk_script(s)));
assert!(!["Latn", "Arab", "Hebr"].iter().any(|s| is_cjk_script(s)));
@@ -328,7 +329,10 @@ mod tests {
let (whole, other): (Vec<_>, Vec<_>) = cjk.partition(|f| WHOLE_CJK_FAMILIES.contains(&f.family));
for face in &other {
let len = face.bytes.len();
assert!(u64::try_from(len).is_ok_and(|n| n <= MAX_OTHER_CJK_BYTES), "{} is embedded at {len} bytes", face.name());
let native_ui = NATIVE_UI_CJK_FAMILIES.contains(&face.family);
assert!(!cfg!(target_arch = "wasm32") || !native_ui, "native UI face in web payload");
let cap = if native_ui { MAX_NATIVE_UI_CJK_BYTES } else { MAX_OTHER_CJK_BYTES };
assert!(u64::try_from(len).is_ok_and(|n| n <= cap), "{} is embedded at {len} bytes", face.name());
}
let bytes: usize = whole.iter().map(|f| f.bytes.len()).sum();
assert!(bytes < 25_000_000, "{bytes} bytes of Japanese faces");
+1 -1
View File
@@ -59,7 +59,7 @@ impl Std14 {
/// report that called it a standard-14 name would be telling the reader something untrue.
pub fn recognise(base: &str) -> Option<(Self, Match)> {
let base = base.rsplit('+').next().unwrap_or(base);
let flat: String = base.chars().filter(|c| c.is_ascii_alphanumeric()).map(|c| c.to_ascii_lowercase()).collect();
let flat: String = base.chars().filter(char::is_ascii_alphanumeric).map(|c| c.to_ascii_lowercase()).collect();
let has = |w: &str| flat.contains(w);
let (bold, italic) = (has("bold"), has("italic") || has("oblique"));
// Two bools index a four-element array, so the subscript is provably 0..=3.
+6 -3
View File
@@ -39,8 +39,9 @@ let cells: Vec<table::Cell> = grid.cells_for(names)?; // "Table1_1", "Table
- Inheritable attributes (`/FT`, `/Ff`, `/V`, `/DV`, `/DA`, `/Q`, `/MaxLen`) are resolved down the
field tree; the form's `/DA` and `/Q` are the last fallback.
- Text and choice fields get new appearance streams (`/Tx BMC … EMC`): auto-size (`0 Tf`), comb,
multiline wrapping, password masking, quadding, `/MK` background and border, list-box selection.
- Text and choice fields get new appearance streams (`/Tx BMC … EMC`): auto-size (`0 Tf`), comb
(cells parted in the border colour), multiline wrapping, password masking, quadding, `/MK`
background and border, list-box selection.
The `/DA` font is used when `/DR` has it as a simple font or a composite font with a predefined
Unicode CMap; otherwise Helvetica (WinAnsi). A value or button caption the font can't hold
(Chinese in a Helvetica field, a character beyond U+FFFF in a UCS-2 CMap) is kept, as Acrobat
@@ -55,7 +56,9 @@ let cells: Vec<table::Cell> = grid.cells_for(names)?; // "Table1_1", "Table
drawn from their values, as typing them would draw them; the engine shows and prints that copy
and saves the file as it was (#3470). `with_field_appearances_cached` keeps each widget's
drawing while the objects it was drawn from are the same (`FieldAppearanceCache`), so typing in
one field redraws that field, not the form.
one field redraws that field, not the form. Check boxes and radio buttons with no appearance for
their state are drawn from `/MK` (border, background, and when on the `/MK /CA` ZapfDingbats
symbol in the `/DA` colour), and push buttons with none from `/MK`, `/BS` and their caption.
- Check boxes and radio buttons switch `/V` and each widget's `/AS`. Widgets with no appearances
get PdfCraft's own (a drawn check mark or dot; no symbol font needed).
- Imported `/MaxLen 0` is treated as unlimited (also clearing an inherited limit), while the
+70 -1
View File
@@ -159,6 +159,60 @@ pub fn field_actions(doc: &Document, name: &str) -> Result<Vec<(Trigger, FieldAc
Ok(out)
}
/// Most chained actions [`field_action_chains`] walks per trigger.
const MAX_CHAIN: usize = 1000;
/// How many actions follow `action` through `/Next` (a dictionary or an array of them, each with
/// its own `/Next`), counting each object once.
fn chained(doc: &Document, action: &Object) -> usize {
let mut seen = std::collections::HashSet::new();
if let Object::Ref(r) = action {
seen.insert(*r);
}
let mut stack: Vec<Object> = doc.resolve(action).as_dict().and_then(|d| d.get(b"Next").cloned()).into_iter().collect();
let mut count = 0;
while let Some(o) = stack.pop() {
if count >= MAX_CHAIN {
break;
}
if let Object::Ref(r) = &o
&& !seen.insert(*r)
{
continue;
}
match &*doc.resolve(&o) {
Object::Array(items) => stack.extend(items.iter().cloned()),
Object::Dict(d) => {
count += 1;
stack.extend(d.get(b"Next").cloned());
}
_ => {}
}
}
count
}
/// For each trigger of field `name` (its first widget) whose action has others chained after it,
/// how many there are.
pub fn field_action_chains(doc: &Document, name: &str) -> Result<Vec<(Trigger, usize)>, FormError> {
let all = fields(doc);
let f = all.iter().find(|f| f.name == name).ok_or_else(|| FormError::NoSuchField(name.into()))?;
let Some(w) = f.widgets.first() else { return Ok(Vec::new()) };
let wd = doc.get(w.obj).as_dict().cloned().unwrap_or_default();
let aa = wd.get(b"AA").map(|a| doc.resolve(a)).and_then(|a| a.as_dict().cloned()).unwrap_or_default();
Ok(Trigger::ALL
.into_iter()
.filter_map(|t| {
let o = match t.key() {
None => wd.get(b"A").cloned().or_else(|| aa.get(b"U").cloned()),
Some(k) => aa.get(k).cloned(),
}?;
let n = chained(doc, &o);
(n > 0).then_some((t, n))
})
.collect())
}
fn write(doc: &mut Document, a: &FieldAction, pages: &[pdfcraft_cos::ObjRef]) -> Result<Option<Object>, FormError> {
let mut d = Dict::new();
d.set(b"Type".to_vec(), Object::name("Action"));
@@ -207,11 +261,13 @@ fn write(doc: &mut Document, a: &FieldAction, pages: &[pdfcraft_cos::ObjRef]) ->
}
/// Replace field `name`'s actions (on every widget) with `actions`; triggers not listed lose
/// theirs. `Other` actions are left as they are.
/// theirs. `Other` actions, and actions that read the same as before, are left as they are (with
/// their chain and the keys this module doesn't read); a replaced action keeps its chain.
pub fn set_field_actions(doc: &mut Document, name: &str, actions: &[(Trigger, FieldAction)]) -> Result<(), FormError> {
let all = fields(doc);
let f = all.iter().find(|f| f.name == name).ok_or_else(|| FormError::NoSuchField(name.into()))?.clone();
let pages = crate::page_refs(doc);
let mut scripts = crate::script_budget();
for w in &f.widgets {
let wd = doc.get(w.obj).as_dict().cloned().unwrap_or_default();
let mut aa = wd.get(b"AA").map(|a| doc.resolve(a)).and_then(|a| a.as_dict().cloned()).unwrap_or_default();
@@ -221,10 +277,23 @@ pub fn set_field_actions(doc: &mut Document, name: &str, actions: &[(Trigger, Fi
if matches!(new, Some(FieldAction::Other(_))) {
continue;
}
let old = match t.key() {
None => wd.get(b"A").cloned().or_else(|| aa.get(b"U").cloned()),
Some(k) => aa.get(k).cloned(),
};
let old_action = old.as_ref().and_then(|o| read(doc, o, &pages, &mut scripts));
if new.is_some() && new == old_action.as_ref() {
continue;
}
// The list shows a trigger's first action: replacing it keeps the ones chained after it.
let next = new.and(old).and_then(|o| doc.resolve(&o).as_dict().and_then(|d| d.get(b"Next").cloned()));
let obj = match new {
Some(a) => write(doc, a, &pages)?,
None => None,
};
if let (Some(Object::Ref(r)), Some(next)) = (&obj, next) {
doc.update_dict(*r, |d| d.set(b"Next".to_vec(), next))?;
}
match t.key() {
None => {
a_entry = obj;
+410 -14
View File
@@ -72,6 +72,134 @@ pub fn auto_text_size_by(width: f64, height: f64, multiline: bool, line_width: i
if tw.is_finite() && tw > width { (size * width / tw).max(4.0) } else { size }
}
/// How a text field's widget lays its value out in [`field_appearance_drawn`], for asking
/// whether a value fits it ([`TextBox::fits`]): what a field that doesn't scroll (`DoNotScroll`,
/// ISO 32000-2 Table 228) still takes. Built from the same pieces the appearance uses: the `/DA`
/// font from the form's `/DR` (Helvetica where that font can't show the text), the room inside
/// the border and the 2 pt padding, the `/DA` size (or the automatic size), and wrapping for a
/// multi-line field; the two must change together.
#[derive(Clone, Debug, PartialEq)]
pub struct TextBox {
/// The `/DA` font from `/DR`, when it is one the appearance can draw with.
font: Option<FontText>,
/// Width and height inside the border and padding.
inner_w: f64,
inner_h: f64,
/// The `/DA` size; `None` for an automatic (`0 Tf`) size, which shrinks to fit.
size: Option<f64>,
multiline: bool,
password: bool,
/// A comb field: its cells, not its width, bound it (`/MaxLen`).
comb: bool,
}
/// The [`TextBox`] widget `w` of text field `f` lays its value out in.
pub fn text_box(doc: &Document, f: &Field, w: &Widget) -> TextBox {
let wobj = doc.get(w.obj);
let wd = wobj.as_dict().cloned().unwrap_or_default();
let (page_w, page_h) = ((w.rect[2] - w.rect[0]).max(1.0), (w.rect[3] - w.rect[1]).max(1.0));
let place = placement(mk_rotation(doc, &wd), page_w, page_h);
let da = parse_da(wd.get(b"DA").and_then(|o| doc.resolve(o).as_string().map(|s| s.to_text())).as_deref().unwrap_or(&f.da));
let pad = 2.0 + border_width(doc, &wd);
let multiline = f.has(flags::MULTILINE);
TextBox {
font: dr_font(doc, &da.font).map(|(_, enc)| enc),
inner_w: (place.layout_w - 2.0 * pad).max(1.0),
inner_h: place.layout_h - 2.0 * pad,
size: (da.size > 0.0 && da.size.is_finite()).then_some(da.size),
multiline,
password: f.has(flags::PASSWORD),
comb: f.has(flags::COMB) && !multiline && !f.has(flags::PASSWORD) && f.max_len.is_some_and(|m| m > 0),
}
}
impl TextBox {
/// Whether `text` fits: on one line within the width, or, multi-line, wrapped within the
/// height, as the appearance draws it. An automatic size shrinks before text stops fitting,
/// so such a field is full only when the text no longer fits at its smallest size (4 pt). A
/// comb field always fits (its `/MaxLen` bounds it).
pub fn fits(&self, text: &str) -> bool {
if self.comb || text.is_empty() {
return true;
}
let shown: String = if self.password { "*".repeat(text.chars().count()) } else { text.to_string() };
// The font the appearance would choose for this text.
let can_show = |enc: &FontText| if self.multiline { shown.split(['\n', '\r']).all(|l| enc.can_encode(l)) } else { enc.can_encode(&shown) };
let font = self.font.as_ref().filter(|enc| can_show(enc)).unwrap_or(&FontText::WinAnsi);
let width_of = |t: &str, size: f64| font.width(t, size);
// The smallest an automatic size goes ([`auto_text_size_by`]).
let size = self.size.unwrap_or(4.0);
if self.multiline {
// As the appearance draws it: the first baseline is 0.85 em below the padded top and
// a line is drawn while its descent (0.207 em) stays inside the border, so the
// padding below the last line is not needed: `inner_h` plus 2 pt.
// Long words break by character, so a line is wider than the box only when it is a
// single character wider than the box, which the appearance still cuts at the sides.
let lines = wrap_with(&shown, size, self.inner_w, width_of);
let above = lines.len().saturating_sub(1) as f64;
above * size * 1.15 + 1.057 * size <= self.inner_h + 2.0 + 0.01 && lines.iter().all(|l| width_of(l, size) <= self.inner_w + 0.01)
} else {
// A line break in a single-line value is drawn as a space.
let line: String = shown.chars().map(|c| if matches!(c, '\n' | '\r') { ' ' } else { c }).collect();
width_of(&line, size) <= self.inner_w + 1e-6
}
}
/// An edit from `before` to `after` as a field that doesn't scroll takes it: all of it when
/// `after` fits, and otherwise as much of the text it inserted (typed or pasted) as still
/// fits, keeping what it removed removed. Returns the text and where the caret goes (in
/// characters, after what was kept of the insertion).
pub fn fitted_edit(&self, before: &str, after: &str) -> (String, usize) {
let (b, a): (Vec<char>, Vec<char>) = (before.chars().collect(), after.chars().collect());
// The edit replaced b[p..b.len() - q] with a[p..a.len() - q].
let p = b.iter().zip(&a).take_while(|(x, y)| x == y).count();
let most = b.len().min(a.len()).saturating_sub(p);
let q = b.iter().rev().zip(a.iter().rev()).take(most).take_while(|(x, y)| x == y).count();
// q <= a.len() - p, so these are in range; `get` keeps it so if that ever changes.
let end = a.len().saturating_sub(q);
let (prefix, inserted, suffix) = (a.get(..p).unwrap_or_default(), a.get(p..end).unwrap_or_default(), a.get(end..).unwrap_or_default());
let with = |k: usize| prefix.iter().chain(inserted.get(..k).unwrap_or_default()).chain(suffix).collect::<String>();
if self.fits(after) {
return (after.to_string(), p + inserted.len());
}
// The longest of the insertion's first `from..=to` characters that fits, halving: in one
// font a longer text is never narrower. `None` when even `from` doesn't fit.
let longest = |from: usize, to: usize| -> Option<usize> {
if from > to || !self.fits(&with(from)) {
return None;
}
let (mut lo, mut hi) = (from, to);
while lo < hi {
let mid = lo + (hi - lo).div_ceil(2);
if self.fits(&with(mid)) { lo = mid } else { hi = mid - 1 }
}
Some(lo)
};
// The font can change once, from the form's own to Helvetica, at the first inserted
// character the form's font can't show: each side of that point is searched on its own.
let n = inserted.len();
let kept = match self.font_switch(prefix, inserted, suffix) {
Some(t) => longest(0, t.saturating_sub(1)).into_iter().chain(longest(t, n)).max(),
None => longest(0, n),
}
.unwrap_or(0);
(with(kept), p + kept)
}
/// Where an insertion changes the font [`Self::fits`] measures in: how much of `inserted`
/// (between `prefix` and `suffix`) first includes a character the form's own font can't show,
/// when everything around it can be shown in that font. `None` when the font never changes.
fn font_switch(&self, prefix: &[char], inserted: &[char], suffix: &[char]) -> Option<usize> {
let enc = self.font.as_ref().filter(|_| !self.password)?;
// As `fits` decides: a multi-line value is checked line by line, its breaks aside.
let shows = |c: &char| (self.multiline && matches!(c, '\n' | '\r')) || enc.can_encode(&c.to_string());
if !prefix.iter().chain(suffix).all(shows) {
return None;
}
inserted.iter().position(|c| !shows(c)).map(|i| i + 1)
}
}
/// `/MK /R` as a quadrant, or 0 when it is missing or not a multiple of 90.
pub(crate) fn mk_rotation(doc: &Document, wd: &Dict) -> i64 {
let Some(raw) = wd.get(b"MK") else { return 0 };
@@ -277,10 +405,14 @@ fn stroke_op(fill: &str) -> String {
}
}
/// Background and border from `/MK` and `/BS`; returns (content, border width).
/// Background and border from `/MK` and `/BS`; returns (content, border width). A round XFA
/// check button's ([`is_round`]) are a circle inside the widget instead of its rectangle.
fn frame(doc: &Document, wd: &Dict, w: f64, h: f64) -> (String, f64) {
let mk = wd.get(b"MK").map(|m| doc.resolve(m)).and_then(|m| m.as_dict().cloned());
let mut c = String::new();
if is_round(doc, wd) {
return round_frame(doc, wd, mk.as_ref(), w, h);
}
if let Some(bg) = color_array(doc, mk.as_ref(), b"BG") {
c.push_str(&format!("{bg}\n0 0 {} {} re f\n", n(w), n(h)));
}
@@ -346,12 +478,89 @@ fn frame(doc: &Document, wd: &Dict, w: f64, h: f64) -> (String, f64) {
(c, 0.0)
}
/// Whether `wd` is a check box or radio button PdfCraft laid out for a round XFA check button
/// (`/PCXfaRound true`, written by the XFA layout).
fn is_round(doc: &Document, wd: &Dict) -> bool {
matches!(wd.get(b"PCXfaRound").map(|o| doc.resolve(o)).as_deref(), Some(Object::Bool(true)))
}
/// [`frame`] for a round check button: the `/MK /BG` background as a disc and the `/MK /BC`
/// border as a circle, both centred in the `w` × `h` box and as wide as its shorter side. A
/// dashed border stays dashed and an underline stays an underline; any other style is drawn
/// solid, and a border as wide as the circle fills it. Returns the border width.
fn round_frame(doc: &Document, wd: &Dict, mk: Option<&Dict>, w: f64, h: f64) -> (String, f64) {
let mut c = String::new();
let (cx, cy, r) = (w / 2.0, h / 2.0, w.min(h).max(0.0) / 2.0);
if let Some(bg) = color_array(doc, mk, b"BG") {
c.push_str(&format!("{bg}\n{}f\n", circle_path(cx, cy, r)));
}
let bs = wd.get(b"BS").map(|b| doc.resolve(b)).and_then(|b| b.as_dict().cloned());
let bw = bs.as_ref().and_then(|b| b.get(b"W")).and_then(|x| doc.resolve(x).as_f64()).unwrap_or(1.0).max(0.0);
let style = bs.as_ref().and_then(|b| b.name(b"S").map(<[u8]>::to_vec)).unwrap_or_default();
match color_array(doc, mk, b"BC") {
// An underline stays one: only the bottom edge, as for any widget.
Some(bc) if bw > 0.0 && style == b"U" => {
c.push_str(&format!("{}\n{} w\n0 {} m {} {} l S\n", stroke_op(&bc), n(bw), n(bw / 2.0), n(w), n(bw / 2.0)));
(c, bw)
}
// A border as wide as the circle fills it: a disc in the border's colour.
Some(bc) if bw > 0.0 && bw >= 2.0 * r => {
c.push_str(&format!("{bc}\n{}f\n", circle_path(cx, cy, r)));
(c, 2.0 * r)
}
Some(bc) if bw > 0.0 => {
let dashed = style == b"D";
// The stroke is centred on the path: inset by half its width, it stays inside.
let path = circle_path(cx, cy, r - bw / 2.0);
c.push_str(&format!("{}\n{} w\n{}{path}S\n[] 0 d\n", stroke_op(&bc), n(bw), if dashed { "[3] 0 d\n" } else { "" }));
(c, bw)
}
_ => (c, 0.0),
}
}
/// A closed circle of radius `r` around (`cx`, `cy`) as four Bézier arcs, ending with a space
/// so a paint operator can follow.
fn circle_path(cx: f64, cy: f64, r: f64) -> String {
// The control-point distance for a quarter circle.
let k = 0.5523 * r;
format!(
"{} {} m {} {} {} {} {} {} c {} {} {} {} {} {} c {} {} {} {} {} {} c {} {} {} {} {} {} c ",
n(cx + r),
n(cy),
n(cx + r),
n(cy + k),
n(cx + k),
n(cy + r),
n(cx),
n(cy + r),
n(cx - k),
n(cy + r),
n(cx - r),
n(cy + k),
n(cx - r),
n(cy),
n(cx - r),
n(cy - k),
n(cx - k),
n(cy - r),
n(cx),
n(cy - r),
n(cx + k),
n(cy - r),
n(cx + r),
n(cy - k),
n(cx + r),
n(cy)
)
}
/// The width [`frame`] insets the content by: the `/BS` border width when the widget has a
/// border colour, doubled for beveled and inset borders, and 0 without a border.
fn border_width(doc: &Document, wd: &Dict) -> f64 {
let mk = wd.get(b"MK").map(|m| doc.resolve(m)).and_then(|m| m.as_dict().cloned());
let bs = wd.get(b"BS").map(|b| doc.resolve(b)).and_then(|b| b.as_dict().cloned());
let bw = bs.as_ref().and_then(|b| b.get(b"W")).and_then(|x| doc.resolve(x).as_f64()).unwrap_or(1.0).max(0.0);
let bw = line_width(doc, wd);
if color_array(doc, mk.as_ref(), b"BC").is_none() || bw <= 0.0 {
return 0.0;
}
@@ -359,6 +568,37 @@ fn border_width(doc: &Document, wd: &Dict) -> f64 {
if style == b"B" || style == b"I" { 2.0 * bw } else { bw }
}
/// The widget's border line width, `/BS /W` (default 1, Table 168), as [`frame`] strokes it.
fn line_width(doc: &Document, wd: &Dict) -> f64 {
let bs = wd.get(b"BS").map(|b| doc.resolve(b)).and_then(|b| b.as_dict().cloned());
// `f64::max` turns NaN into 0, as it does a negative width.
bs.as_ref().and_then(|b| b.get(b"W")).and_then(|x| doc.resolve(x).as_f64()).unwrap_or(1.0).max(0.0)
}
/// Comb fields stop drawing their cells past this many; they would be a solid block anyway.
const MAX_COMB_DIVIDERS: usize = 500;
/// The lines between the `cells` positions of a comb field `w` × `h` (ISO 32000-2 Table 228,
/// Comb: the field is divided into `MaxLen` equally spaced positions), in the border's colour and
/// width, inside the border. None without a border, or past [`MAX_COMB_DIVIDERS`] cells.
fn comb_dividers(doc: &Document, wd: &Dict, w: f64, h: f64, cells: usize) -> String {
let mk = wd.get(b"MK").map(|m| doc.resolve(m)).and_then(|m| m.as_dict().cloned());
let inset = border_width(doc, wd);
let lw = line_width(doc, wd);
let Some(bc) = color_array(doc, mk.as_ref(), b"BC") else { return String::new() };
if !(inset > 0.0 && inset.is_finite() && lw > 0.0 && lw.is_finite()) || !(2..=MAX_COMB_DIVIDERS).contains(&cells) {
return String::new();
}
let cell = w / cells as f64;
let mut c = format!("{}\n{} w\n", stroke_op(&bc), n(lw));
for i in 1..cells {
let x = cell * i as f64;
c.push_str(&format!("{} {} m {} {} l\n", n(x), n(inset), n(x), n(h - inset)));
}
c.push_str("S\n");
c
}
/// Where a list box draws its options: one row per option from the top, starting with option
/// `top` (`/TI`, §12.7.4.4). The appearance PdfCraft writes and the viewer's in-place list share
/// it, so a click picks the option drawn under the pointer (#1524).
@@ -449,6 +689,45 @@ pub fn field_appearance_as(doc: &Document, f: &Field, w: &Widget, values: &[Stri
/// hold it: the form's font is a simple (WinAnsi) font, Helvetica stands in for one PdfCraft can't
/// write with (an embedded subset, `Identity-H`), or a UCS-2 CMap meets a character beyond U+FFFF.
pub fn field_appearance_drawn(doc: &Document, f: &Field, w: &Widget, values: &[String], format: bool) -> (Stream, Option<char>) {
let (stream, unencodable, _) = field_appearance_fit(doc, f, w, values, format);
(stream, unencodable)
}
/// A text value that its box cuts off at the field's font size (#4018).
#[derive(Clone, Debug, PartialEq)]
pub enum Overflow {
/// One line `width` points wide, with `room` for it, at `size` points.
Wide { width: f64, room: f64, size: f64 },
/// `lines` wrapped lines, of which the box shows `room`, at `size` points.
Tall { lines: usize, room: usize, size: f64 },
/// One line `height` points high (ascent to descent), with `room` for it, at `size` points.
High { height: f64, room: f64, size: f64 },
}
impl std::fmt::Display for Overflow {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Wide { width, room, size } => {
write!(f, "the value does not fit: {} pt wide at {} pt, room for {} pt", fmt(*width), fmt(*size), fmt(*room))
}
Self::Tall { lines, room, size } => write!(f, "the value does not fit: {lines} lines at {} pt, room for {room}", fmt(*size)),
Self::High { height, room, size } => {
write!(f, "the value does not fit: {} pt high at {} pt, room for {} pt", fmt(*height), fmt(*size), fmt(*room))
}
}
}
}
/// Whether the text field's value, drawn in widget `w`, is cut off by its box.
pub fn value_overflow(doc: &Document, f: &Field, w: &Widget) -> Option<Overflow> {
if f.kind != FieldKind::Text {
return None;
}
field_appearance_fit(doc, f, w, &f.value, true).2
}
/// [`field_appearance_drawn`], and whether the text drawn is cut off by the box.
fn field_appearance_fit(doc: &Document, f: &Field, w: &Widget, values: &[String], format: bool) -> (Stream, Option<char>, Option<Overflow>) {
// The Format event: what is shown, not what is stored.
let formatted: Vec<String>;
let values = if format
@@ -513,6 +792,7 @@ pub fn field_appearance_drawn(doc: &Document, f: &Field, w: &Widget, values: &[S
}
};
let mut size = da.size;
let mut overflow = None;
match f.kind {
FieldKind::List => {
// Every option, one per line from the top (from `/TI`); selected ones highlighted.
@@ -539,13 +819,25 @@ pub fn field_appearance_drawn(doc: &Document, f: &Field, w: &Widget, values: &[S
size = auto_text_size(&text, inner_w, height - 2.0 * pad, true, width_of);
}
let mut y = height - pad - size * 0.85;
for line in wrap_with(&text, size, inner_w, width_of) {
let lines = wrap_with(&text, size, inner_w, width_of);
// The lines whose descent stays inside the border; the rest are cut off.
let mut room = 0;
for line in &lines {
if y < -size {
break;
}
show(&mut body, x_for(&line, size), y, &line);
if y - 0.207 * size >= bw - 0.01 {
room += 1;
}
show(&mut body, x_for(line, size), y, line);
y -= size * 1.15;
}
if room < lines.len() {
overflow = Some(Overflow::Tall { lines: lines.len(), room, size });
} else if let Some(tw) = lines.iter().map(|l| width_of(l, size)).filter(|tw| *tw > inner_w + 0.01).reduce(f64::max) {
// A character wider than the box is a line of its own, still cut at the sides.
overflow = Some(Overflow::Wide { width: tw, room: inner_w, size });
}
} else {
if size == 0.0 {
// Comb cells hold one character each, so only the height limits them.
@@ -557,14 +849,24 @@ pub fn field_appearance_drawn(doc: &Document, f: &Field, w: &Widget, values: &[S
}
// Centre Helvetica's ascent (0.718) and descent (0.207) vertically.
let y = (height - 0.925 * size) / 2.0 + 0.207 * size;
// The clip box is inside the border; a line taller than it is cut at the top and bottom.
let room_h = height - 2.0 * bw;
if 0.925 * size > room_h + 0.01 {
overflow = Some(Overflow::High { height: 0.925 * size, room: room_h, size });
}
if comb {
let cells = f.max_len.unwrap_or(1).max(1);
let cell = width / cells as f64;
c.push_str(&comb_dividers(doc, &wd, width, height, cells));
for (i, ch) in text.chars().take(cells).enumerate() {
let s = ch.to_string();
show(&mut body, cell * i as f64 + (cell - width_of(&s, size)) / 2.0, y, &s);
}
} else {
let tw = width_of(&text.replace(['\n', '\r'], " "), size);
if overflow.is_none() && tw > inner_w + 0.01 {
overflow = Some(Overflow::Wide { width: tw, room: inner_w, size });
}
show(&mut body, x_for(&text, size), y, &text);
}
}
@@ -595,13 +897,17 @@ pub fn field_appearance_drawn(doc: &Document, f: &Field, w: &Widget, values: &[S
d.set(b"Subtype".to_vec(), Object::name("Form"));
set_form_box(&mut d, place);
d.set(b"Resources".to_vec(), Object::Dict(res));
(Stream::flate(d, &content), unencodable)
// Nothing drawn is nothing cut, however small the box.
let overflow = overflow.filter(|_| !text.is_empty());
(Stream::flate(d, &content), unencodable, overflow)
}
/// On/Off appearances for a check box or radio button that has none (a check mark or a dot,
/// drawn as paths, so no symbol font is needed).
/// The mark is drawn in the colour of the widget's `/DA`, else of `f_da` (the field's): the
/// Appearance tab's Text Color (#4261).
/// The streams are added to `doc` as indirect objects (streams can't be direct objects).
pub fn check_box_states(doc: &mut Document, w: &Widget, kind: FieldKind, on_name: &str) -> Dict {
pub fn check_box_states(doc: &mut Document, w: &Widget, kind: FieldKind, on_name: &str, f_da: &str) -> Dict {
let wobj = doc.get(w.obj);
let wd = wobj.as_dict().cloned().unwrap_or_default();
let (page_w, page_h) = ((w.rect[2] - w.rect[0]).max(1.0), (w.rect[3] - w.rect[1]).max(1.0));
@@ -609,6 +915,7 @@ pub fn check_box_states(doc: &mut Document, w: &Widget, kind: FieldKind, on_name
let (width, height) = (place.layout_w, place.layout_h);
let (frame_c, _) = frame(doc, &wd, width, height);
let style = crate::author::CheckStyle::of_widget(doc, &wd, kind);
let da = parse_da(wd.get(b"DA").and_then(|o| doc.resolve(o).as_string().map(|s| s.to_text())).as_deref().unwrap_or(f_da));
let mut form = |content: String| -> Object {
let mut d = Dict::new();
d.set(b"Type".to_vec(), Object::name("XObject"));
@@ -617,7 +924,7 @@ pub fn check_box_states(doc: &mut Document, w: &Widget, kind: FieldKind, on_name
Object::Ref(doc.add(Object::Stream(Stream::flate(d, content.as_bytes()))))
};
let s = width.min(height);
let mark = check_mark(style, width / 2.0, height / 2.0, s);
let mark = check_mark(style, width / 2.0, height / 2.0, s, &da.color);
let mut nd = Dict::new();
nd.set(crate::name_bytes(on_name), form(format!("{frame_c}{mark}")));
nd.set(b"Off".to_vec(), form(frame_c));
@@ -627,12 +934,13 @@ pub fn check_box_states(doc: &mut Document, w: &Widget, kind: FieldKind, on_name
}
/// The on-state mark for `style` (#94), centred on (`cx`, `cy`) in a box whose smaller side is
/// `s`, drawn in black.
fn check_mark(style: crate::author::CheckStyle, cx: f64, cy: f64, s: f64) -> String {
/// `s`, drawn in the fill colour operation `color` (`0 g`, `0 0 1 rg`).
fn check_mark(style: crate::author::CheckStyle, cx: f64, cy: f64, s: f64, color: &str) -> String {
use crate::author::CheckStyle;
let (fill, stroke) = (color, stroke_op(color));
// A filled polygon through `pts`.
let polygon = |pts: &[(f64, f64)]| {
let mut c = String::from("0 g\n");
let mut c = format!("{fill}\n");
for (i, (x, y)) in pts.iter().enumerate() {
c.push_str(&format!("{} {} {} ", n(*x), n(*y), if i == 0 { "m" } else { "l" }));
}
@@ -642,7 +950,7 @@ fn check_mark(style: crate::author::CheckStyle, cx: f64, cy: f64, s: f64) -> Str
let line = n((s * 0.1).max(1.0));
match style {
CheckStyle::Check => format!(
"0 G\n{line} w 1 J 1 j\n{} {} m {} {} l {} {} l S\n",
"{stroke}\n{line} w 1 J 1 j\n{} {} m {} {} l {} {} l S\n",
n(cx - s * 0.28),
n(cy),
n(cx - s * 0.08),
@@ -653,7 +961,7 @@ fn check_mark(style: crate::author::CheckStyle, cx: f64, cy: f64, s: f64) -> Str
CheckStyle::Cross => {
let d = s * 0.25;
format!(
"0 G\n{line} w 1 J\n{} {} m {} {} l S\n{} {} m {} {} l S\n",
"{stroke}\n{line} w 1 J\n{} {} m {} {} l S\n{} {} m {} {} l S\n",
n(cx - d),
n(cy - d),
n(cx + d),
@@ -666,7 +974,7 @@ fn check_mark(style: crate::author::CheckStyle, cx: f64, cy: f64, s: f64) -> Str
}
CheckStyle::Square => {
let d = s * 0.22;
format!("0 g\n{} {} {} {} re f\n", n(cx - d), n(cy - d), n(2.0 * d), n(2.0 * d))
format!("{fill}\n{} {} {} {} re f\n", n(cx - d), n(cy - d), n(2.0 * d), n(2.0 * d))
}
CheckStyle::Diamond => {
let d = s * 0.3;
@@ -688,7 +996,7 @@ fn check_mark(style: crate::author::CheckStyle, cx: f64, cy: f64, s: f64) -> Str
let r = s * 0.25;
let k = 0.5523 * r;
format!(
"0 g\n{} {} m {} {} {} {} {} {} c {} {} {} {} {} {} c {} {} {} {} {} {} c {} {} {} {} {} {} c f\n",
"{fill}\n{} {} m {} {} {} {} {} {} c {} {} {} {} {} {} c {} {} {} {} {} {} c {} {} {} {} {} {} c f\n",
n(cx + r),
n(cy),
n(cx + r),
@@ -720,6 +1028,94 @@ fn check_mark(style: crate::author::CheckStyle, cx: f64, cy: f64, s: f64) -> Str
}
}
/// How a check box or radio button widget `w` of field `f` looks in state on (`on`) or Off when
/// the file has no appearance for that state: its `/MK` background and border ([`frame`]), and
/// when on, its caption `/MK /CA` (ISO 32000-2 Table 192: the normal caption, which check boxes
/// and radio buttons may use too) as a ZapfDingbats character, as in the check box example of
/// 12.7.5.2.3: `4` (a check mark) by default, `l` (a dot) for a radio button. The character is
/// drawn in the `/DA` colour, at the `/DA` size or, for an automatic size (`0 Tf`), filling most
/// of the box. ZapfDingbats is one of the standard 14 fonts, so no font program is needed.
pub(crate) fn button_state_shown(doc: &Document, f: &Field, w: &Widget, on: bool) -> Stream {
let wobj = doc.get(w.obj);
let wd = wobj.as_dict().cloned().unwrap_or_default();
let (page_w, page_h) = ((w.rect[2] - w.rect[0]).max(1.0), (w.rect[3] - w.rect[1]).max(1.0));
let place = placement(mk_rotation(doc, &wd), page_w, page_h);
let (width, height) = (place.layout_w, place.layout_h);
let (frame_c, bw) = frame(doc, &wd, width, height);
let mut content = frame_c.into_bytes();
let mut res = Dict::new();
if on {
let mk = wd.get(b"MK").map(|m| doc.resolve(m)).and_then(|m| m.as_dict().cloned());
let caption = mk.as_ref().and_then(|mk| mk.get(b"CA")).and_then(|o| doc.resolve(o).as_string().map(|s| s.to_text()));
let dingbats = pdfcraft_fonts::Std14::ZapfDingbats;
// The caption's first character as a ZapfDingbats code, when the font has a glyph there.
let code = caption
.and_then(|s| s.chars().next())
.and_then(|ch| u8::try_from(u32::from(ch)).ok())
.filter(|&code| dingbats.width(code) > 0.0)
.unwrap_or(if f.kind == FieldKind::Radio { b'l' } else { b'4' });
let da = parse_da(wd.get(b"DA").and_then(|o| doc.resolve(o).as_string().map(|s| s.to_text())).as_deref().unwrap_or(&f.da));
// The glyph's advance and (about) its height, in ems.
let (advance, tall) = (dingbats.width(code) / 1000.0, 0.75);
let room = |side: f64| (side - 2.0 * bw - 2.0).max(1.0);
// An automatic size leaves a margin of a tenth of the room on each side.
let size = if da.size > 0.0 { da.size } else { (0.8 * room(width) / advance.max(0.1)).min(0.8 * room(height) / tall).clamp(1.0, 300.0) };
let (x, y) = ((width - advance * size) / 2.0, (height - tall * size) / 2.0 + 0.05 * size);
content.extend(format!("q\nBT\n/ZaDb {} Tf\n{}\n{} {} Td\n", n(size), da.color, n(x), n(y)).bytes());
content.extend(literal(&[code]));
content.extend_from_slice(b" Tj\nET\nQ\n");
let mut font = Dict::new();
font.set(b"Type".to_vec(), Object::name("Font"));
font.set(b"Subtype".to_vec(), Object::name("Type1"));
font.set(b"BaseFont".to_vec(), Object::name("ZapfDingbats"));
let mut fonts = Dict::new();
fonts.set(b"ZaDb".to_vec(), Object::Dict(font));
res.set(b"Font".to_vec(), Object::Dict(fonts));
}
let mut d = Dict::new();
d.set(b"Type".to_vec(), Object::name("XObject"));
d.set(b"Subtype".to_vec(), Object::name("Form"));
set_form_box(&mut d, place);
d.set(b"Resources".to_vec(), Object::Dict(res));
Stream::flate(d, &content)
}
/// How a push button widget `w` of field `f` with no normal appearance looks: its `/MK`
/// background and border, in the `/BS` width and style ([`frame`]: Table 168, `B` beveled, `I`
/// inset), with its caption `/MK /CA` (Table 192) centred in the `/DA` font, size and colour.
/// A button with an icon (`/MK /I`) is drawn as PdfCraft draws its own buttons, icon included.
pub(crate) fn push_button_shown(doc: &Document, f: &Field, w: &Widget) -> Stream {
let wobj = doc.get(w.obj);
let wd = wobj.as_dict().cloned().unwrap_or_default();
let mk = wd.get(b"MK").map(|m| doc.resolve(m)).and_then(|m| m.as_dict().cloned()).unwrap_or_default();
if mk.contains(b"I") {
return crate::author::button_appearance(doc, w, &f.da).0;
}
let (page_w, page_h) = ((w.rect[2] - w.rect[0]).max(1.0), (w.rect[3] - w.rect[1]).max(1.0));
let place = placement(mk_rotation(doc, &wd), page_w, page_h);
let (width, height) = (place.layout_w, place.layout_h);
let (frame_c, _) = frame(doc, &wd, width, height);
let mut content = frame_c.into_bytes();
let caption = mk.get(b"CA").and_then(|o| doc.resolve(o).as_string().map(|s| s.to_text())).unwrap_or_default();
let mut fonts = Dict::new();
if !caption.is_empty() && mk.get(b"TP").and_then(|t| doc.resolve(t).as_int()) != Some(1) {
let da = wd.get(b"DA").and_then(|o| doc.resolve(o).as_string().map(|s| s.to_text()));
// The automatic size PdfCraft's own buttons use.
let auto = ((height - 4.0) * 0.6).clamp(4.0, 14.0);
let (ops, name, font, _) = button_caption(doc, da.as_deref().unwrap_or(&f.da), &caption, width, height, auto);
content.extend(ops);
fonts.set(name.into_bytes(), font);
}
let mut res = Dict::new();
res.set(b"Font".to_vec(), Object::Dict(fonts));
let mut d = Dict::new();
d.set(b"Type".to_vec(), Object::name("XObject"));
d.set(b"Subtype".to_vec(), Object::name("Form"));
set_form_box(&mut d, place);
d.set(b"Resources".to_vec(), Object::Dict(res));
Stream::flate(d, &content)
}
#[cfg(test)]
mod tests {
use super::*;
+369 -66
View File
@@ -134,10 +134,9 @@ pub(crate) fn ensure_form(doc: &mut Document) -> Result<ObjRef, FormError> {
if !af.contains(b"DA") {
af.set(b"DA".to_vec(), PdfString::literal(b"/Helv 0 Tf 0 g".to_vec()));
}
let mut dr = af.get(b"DR").map(|o| doc.resolve(o)).and_then(|o| o.as_dict().cloned()).unwrap_or_default();
let mut fonts = dr.get(b"Font").map(|o| doc.resolve(o)).and_then(|o| o.as_dict().cloned()).unwrap_or_default();
let (dr, mut fonts) = form_fonts(doc, &af);
let mut added = inline_fonts_as_objects(doc, &mut fonts);
// Acrobat's resource names for the standard fonts its Appearance tab offers.
let mut added = false;
for (name, base) in [("Helv", "Helvetica"), ("TiRo", "Times-Roman"), ("Cour", "Courier")] {
if fonts.contains(name.as_bytes()) {
continue;
@@ -147,17 +146,105 @@ pub(crate) fn ensure_form(doc: &mut Document) -> Result<ObjRef, FormError> {
f.set(b"Subtype".to_vec(), Object::name("Type1"));
f.set(b"BaseFont".to_vec(), Object::name(base));
f.set(b"Encoding".to_vec(), Object::name("WinAnsiEncoding"));
fonts.set(name.as_bytes().to_vec(), Object::Dict(f));
let r = doc.add(Object::Dict(f));
fonts.set(name.as_bytes().to_vec(), Object::Ref(r));
added = true;
}
if added {
dr.set(b"Font".to_vec(), Object::Dict(fonts));
af.set(b"DR".to_vec(), Object::Dict(dr));
store_form_fonts(doc, &mut af, dr, fonts);
}
doc.set(r, Object::Dict(af));
Ok(r)
}
/// The form dictionary's `/DR` and its `/Font` dictionary, resolved (empty where missing).
fn form_fonts(doc: &Document, af: &Dict) -> (Dict, Dict) {
let dr = af.get(b"DR").map(|o| doc.resolve(o)).and_then(|o| o.as_dict().cloned()).unwrap_or_default();
let fonts = dr.get(b"Font").map(|o| doc.resolve(o)).and_then(|o| o.as_dict().cloned()).unwrap_or_default();
(dr, fonts)
}
/// Each /DR font its own object: Acrobat, redrawing a text field after it is typed in, shows
/// nothing when the font is a dictionary written inline in /DR (#3441). Fonts written inline
/// (by an earlier save, or another writer) become objects saying the same; a font that is an
/// object already, or an entry that isn't a dictionary, is left alone. Whether any changed.
fn inline_fonts_as_objects(doc: &mut Document, fonts: &mut Dict) -> bool {
let inline: Vec<(Vec<u8>, Dict)> = fonts.iter().filter_map(|(k, v)| Some((k.clone(), v.as_dict()?.clone()))).collect();
let changed = !inline.is_empty();
for (name, font) in inline {
let r = doc.add(Object::Dict(font));
fonts.set(name, Object::Ref(r));
}
changed
}
/// Write `fonts` back as the `/DR /Font` of the form dictionary `af`. An indirect `/DR` or
/// `/Font` stays the object it is.
fn store_form_fonts(doc: &mut Document, af: &mut Dict, mut dr: Dict, fonts: Dict) {
match dr.get(b"Font").and_then(Object::as_ref) {
Some(fr) => doc.set(fr, Object::Dict(fonts)),
None => dr.set(b"Font".to_vec(), Object::Dict(fonts)),
}
match af.get(b"DR").and_then(Object::as_ref) {
Some(dr_ref) => doc.set(dr_ref, Object::Dict(dr)),
None => af.set(b"DR".to_vec(), Object::Dict(dr)),
}
}
/// Filling a field: the form's inline `/DR` fonts become objects (see
/// [`inline_fonts_as_objects`]), so a form an earlier version of PdfCraft made works in Acrobat
/// once it has been filled here too (#3441). Only the font storage changes; nothing is added.
/// Not in a form a signature covers: there the file stays as the signer saw it, apart from the
/// value itself.
pub(crate) fn form_fonts_as_objects(doc: &mut Document, all: &[crate::Field]) -> Result<(), FormError> {
let signed = all.iter().any(|f| f.kind == crate::FieldKind::Signature && holds_value(doc, f.obj));
if signed {
return Ok(());
}
let Some(root) = doc.root() else { return Ok(()) };
let Some(entry) = doc.get(root).as_dict().and_then(|c| c.get(b"AcroForm").cloned()) else { return Ok(()) };
match entry {
Object::Ref(r) => {
let Some(mut af) = doc.get(r).as_dict().cloned() else { return Ok(()) };
let (dr, mut fonts) = form_fonts(doc, &af);
if inline_fonts_as_objects(doc, &mut fonts) {
store_form_fonts(doc, &mut af, dr, fonts);
doc.set(r, Object::Dict(af));
}
}
// A form dictionary written directly in the catalog (the catalog's /AcroForm need not be
// an indirect reference) is written back there.
Object::Dict(mut af) => {
let (dr, mut fonts) = form_fonts(doc, &af);
if inline_fonts_as_objects(doc, &mut fonts) {
store_form_fonts(doc, &mut af, dr, fonts);
doc.update_dict(root, |c| c.set(b"AcroForm".to_vec(), Object::Dict(af)))?;
}
}
_ => {}
}
Ok(())
}
/// Whether the field `r`, or the nearest ancestor that has one, holds a `/V` (the entry is
/// inheritable, ISO 32000-2 §12.7.4). The `/Parent` chain is followed at most 64 deep, as deep
/// as the field walk goes, so a cyclic chain ends.
fn holds_value(doc: &Document, r: ObjRef) -> bool {
let mut at = r;
for _ in 0..=64 {
let obj = doc.get(at);
let Some(d) = obj.as_dict() else { return false };
if d.contains(b"V") {
return true;
}
match d.reference(b"Parent") {
Some(p) => at = p,
None => return false,
}
}
false
}
/// The Appearance tab: borders, colours and text.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Look {
@@ -486,14 +573,228 @@ fn add_to_fields(doc: &mut Document, af: ObjRef, field: ObjRef) -> Result<(), Fo
Ok(())
}
/// The first free "<base>N" name.
fn free_name(existing: &[Field], base: &str) -> String {
/// The most parts a dotted field name may have ("a.b.c" has three).
const MAX_NAME_PARTS: usize = 32;
/// The field attributes a field inherits from its parents (ISO 32000-2 §12.7.4.1).
const INHERITED_KEYS: [&[u8]; 7] = [b"FT", b"Ff", b"V", b"DV", b"DA", b"Q", b"MaxLen"];
/// The parts of a full field name: `a.b` is the field `b` under the parent field `a`, since a
/// field's own (partial) name can't contain a period (ISO 32000-2 §12.7.4.2) (#2696).
fn name_parts(name: &str) -> Result<Vec<&str>, FormError> {
let parts: Vec<&str> = name.split('.').take(MAX_NAME_PARTS.saturating_add(1)).collect();
if parts.len() > MAX_NAME_PARTS {
return invalid(format!("field names can have at most {MAX_NAME_PARTS} parts"));
}
if parts.iter().any(|p| p.trim().is_empty()) {
return invalid("field names can't be empty, or have an empty part between periods");
}
Ok(parts)
}
/// Why the full name `name` can't be used beside the field named `other`, if it can't: the
/// same name, or one inside the other (a field that has a value can't also hold fields).
fn clash(name: &str, other: &str) -> Option<String> {
if name == other {
return Some(format!("a field named {name:?} already exists"));
}
let inside = |a: &str, b: &str| a.strip_prefix(b).is_some_and(|rest| rest.starts_with('.'));
(inside(name, other) || inside(other, name)).then(|| format!("{name:?} can't be used beside the field {other:?}"))
}
/// The array `key` of `holder` (`/Fields` of the form, `/Kids` of a field).
fn list_of(doc: &Document, holder: ObjRef, key: &[u8]) -> Vec<Object> {
let d = doc.get(holder).as_dict().cloned().unwrap_or_default();
d.get(key).map(|o| doc.resolve(o)).and_then(|o| o.as_array().cloned()).unwrap_or_default()
}
/// Add `field` to `parent`'s `/Kids`, or to the form's `/Fields` at the top.
fn link(doc: &mut Document, af: ObjRef, parent: Option<ObjRef>, field: ObjRef) -> Result<(), FormError> {
let Some(p) = parent else { return add_to_fields(doc, af, field) };
let mut kids = list_of(doc, p, b"Kids");
kids.push(Object::Ref(field));
doc.update_dict(p, |d| d.set(b"Kids".to_vec(), Object::Array(kids)))?;
Ok(())
}
/// The node named `name` (its own `/T`) directly under `parent`, or at the top of the form.
fn child_named(doc: &Document, af: ObjRef, parent: Option<ObjRef>, name: &str) -> Option<ObjRef> {
let list = match parent {
Some(p) => list_of(doc, p, b"Kids"),
None => list_of(doc, af, b"Fields"),
};
list.iter()
.filter_map(|o| o.as_ref())
.find(|r| doc.get(*r).as_dict().and_then(|d| d.get(b"T").cloned()).and_then(|t| crate::text_of(&doc.resolve(&t))).as_deref() == Some(name))
}
/// The values a parent field passes to the fields under it that can't be turned off by giving
/// the field a neutral one of its own, as `/Ff` and `/Q` can.
const PASSED_VALUES: [&[u8]; 3] = [b"V", b"DV", b"MaxLen"];
/// Whether `field` may go in the field tree under the full name `parts`, changing nothing. The
/// field list holds only terminal fields, so a parent left empty by a move isn't in it: a node
/// of the same name there is found here.
/// `inherited` is what the field will hold as its own before it moves (see [`inherited`]).
fn check_place(doc: &Document, af: ObjRef, field: ObjRef, parts: &[&str], inherited: &Dict) -> Result<(), FormError> {
let Some((own, parents)) = parts.split_last() else { return invalid("field names can't be empty") };
let mut owned = doc.get(field).as_dict().cloned().unwrap_or_default();
for (k, v) in inherited.iter() {
owned.set(k.to_vec(), v.clone());
}
let mut at: Option<ObjRef> = None;
let mut whole_path = true;
for part in parents {
let Some(r) = child_named(doc, af, at, part) else {
whole_path = false;
break;
};
// A value, reset value or length limit held by a parent would pass to this field.
let held = doc.get(r).as_dict().is_some_and(|d| PASSED_VALUES.iter().any(|k| d.contains(k) && !owned.contains(k)));
if held {
return invalid(format!("{part:?} holds a value for the fields under it, so {:?} can't be put there", parts.join(".")));
}
at = Some(r);
}
// A field being moved is still in the tree here, but under another full name (a move to its
// own name changes nothing and doesn't get here), so a node found is another.
if whole_path && child_named(doc, af, at, own).is_some() {
return invalid(format!("a field named {:?} already exists", parts.join(".")));
}
Ok(())
}
/// Put `field` in the field tree under the full name `parts`: its own `/T` is the last part,
/// and the parts before it name parent fields, reused where the tree has them and made where
/// not (Acrobat makes `a.b` a field `b` under a field `a`).
fn attach(doc: &mut Document, af: ObjRef, field: ObjRef, parts: &[&str]) -> Result<(), FormError> {
let Some((own, parents)) = parts.split_last() else { return invalid("field names can't be empty") };
check_place(doc, af, field, parts, &Dict::new())?;
let mut parent: Option<ObjRef> = None;
let mut inherits = false;
for part in parents {
let next = match child_named(doc, af, parent, part) {
Some(r) => {
inherits |= doc.get(r).as_dict().is_some_and(|d| d.contains(b"Ff") || d.contains(b"Q"));
r
}
None => {
let mut d = Dict::new();
d.set(b"T".to_vec(), PdfString::text(part));
d.set(b"Kids".to_vec(), Object::Array(Vec::new()));
if let Some(p) = parent {
d.set(b"Parent".to_vec(), Object::Ref(p));
}
let r = doc.add(Object::Dict(d));
link(doc, af, parent, r)?;
r
}
};
parent = Some(next);
}
doc.update_dict(field, |d| {
d.set(b"T".to_vec(), PdfString::text(own));
match parent {
Some(p) => d.set(b"Parent".to_vec(), Object::Ref(p)),
None => {
d.remove(b"Parent");
}
}
// An existing parent's flags and alignment would otherwise pass to this field.
if inherits {
for k in [&b"Ff"[..], b"Q"] {
if !d.contains(k) {
d.set(k.to_vec(), Object::Int(0));
}
}
}
})?;
link(doc, af, parent, field)
}
/// What `field` inherits from its parents and doesn't hold itself, changing nothing.
fn inherited(doc: &Document, field: ObjRef) -> Dict {
let own = doc.get(field).as_dict().cloned().unwrap_or_default();
let mut add = Dict::new();
let mut seen = std::collections::HashSet::new();
let mut parent = own.reference(b"Parent");
while let Some(p) = parent {
if seen.len() > 64 || !seen.insert(p) {
break;
}
let Some(d) = doc.get(p).as_dict().cloned() else { break };
for k in INHERITED_KEYS {
if let Some(v) = d.get(k).filter(|_| !own.contains(k) && !add.contains(k)) {
add.set(k.to_vec(), v.clone());
}
}
parent = d.reference(b"Parent");
}
add
}
/// Copy onto `field` what it inherits (`add`, from [`inherited`]), so it keeps it when it moves.
fn own_inherited(doc: &mut Document, field: ObjRef, add: &Dict) -> Result<(), FormError> {
if add.iter().next().is_some() {
doc.update_dict(field, |d| {
for (k, v) in add.iter() {
d.set(k.to_vec(), v.clone());
}
})?;
}
Ok(())
}
/// Take `field` out of the field tree: from its parent's `/Kids`, or from `/Fields`.
fn detach(doc: &mut Document, field: ObjRef) -> Result<(), FormError> {
let parent = doc.get(field).as_dict().and_then(|d| d.reference(b"Parent"));
let remove_from = |doc: &mut Document, holder: ObjRef, key: &[u8]| -> Result<(), FormError> {
let mut d = doc.get(holder).as_dict().cloned().unwrap_or_default();
let list = d.get(key).map(|o| doc.resolve(o)).and_then(|o| o.as_array().cloned()).unwrap_or_default();
let kept: Vec<Object> = list.into_iter().filter(|o| o.as_ref() != Some(field)).collect();
d.set(key.to_vec(), Object::Array(kept));
doc.set(holder, Object::Dict(d));
Ok(())
};
match parent {
Some(p) => remove_from(doc, p, b"Kids")?,
None => {
let root = doc.root().ok_or(FormError::NoForm)?;
match doc.get(root).as_dict().and_then(|d| d.get(b"AcroForm").cloned()) {
Some(Object::Ref(af)) => remove_from(doc, af, b"Fields")?,
// A form dictionary held directly in the catalog.
Some(Object::Dict(mut af)) => {
let list = af.get(b"Fields").map(|o| doc.resolve(o)).and_then(|o| o.as_array().cloned()).unwrap_or_default();
let kept: Vec<Object> = list.into_iter().filter(|o| o.as_ref() != Some(field)).collect();
af.set(b"Fields".to_vec(), Object::Array(kept));
doc.update_dict(root, |d| d.set(b"AcroForm".to_vec(), Object::Dict(af)))?;
}
_ => {}
}
}
}
Ok(())
}
/// The first free "<base>N" name: not a field's, and not held by a node at the top of the field
/// tree (`held`), such as a parent field left empty by a move, which isn't in `existing`.
fn free_name(existing: &[Field], held: &[String], base: &str) -> String {
(1..=u64::MAX)
.map(|n| format!("{base}{n}"))
.find(|c| !existing.iter().any(|f| f.name == *c || f.name.starts_with(&format!("{c}."))))
.find(|c| !held.contains(c) && !existing.iter().any(|f| f.name == *c || f.name.starts_with(&format!("{c}."))))
.unwrap_or_else(|| base.to_string())
}
/// The own names (`/T`) of the nodes in the form's `/Fields`, changing nothing.
fn top_names(doc: &Document) -> Vec<String> {
let Some(root) = doc.root() else { return Vec::new() };
let Some(af) = doc.get(root).as_dict().and_then(|d| d.get(b"AcroForm").map(|o| doc.resolve(o))).and_then(|o| o.as_dict().cloned()) else {
return Vec::new();
};
let list = af.get(b"Fields").map(|o| doc.resolve(o)).and_then(|o| o.as_array().cloned()).unwrap_or_default();
list.iter().filter_map(|o| doc.resolve(o).as_dict().and_then(|d| d.get(b"T").cloned())).filter_map(|t| crate::text_of(&doc.resolve(&t))).collect()
}
fn widget_dict(page: ObjRef, rect: [f64; 4]) -> Dict {
let mut d = Dict::new();
d.set(b"Type".to_vec(), Object::name("Annot"));
@@ -527,20 +828,18 @@ pub fn add_field(doc: &mut Document, page: usize, rect: [f64; 4], kind: &NewFiel
_ => name,
};
let name = match name.map(str::trim) {
Some(n) if !n.is_empty() => {
if n.contains('.') {
return invalid("field names can't contain a period");
}
n.to_string()
}
_ => free_name(&existing, kind.base_name()),
Some(n) if !n.is_empty() => n.to_string(),
_ => free_name(&existing, &top_names(doc), kind.base_name()),
};
let parts = name_parts(&name)?;
let radio_group = match kind {
NewField::Radio { group, .. } => existing.iter().find(|f| f.kind == FieldKind::Radio && Some(&f.name) == group.as_ref()).cloned(),
_ => None,
};
if radio_group.is_none() && existing.iter().any(|f| f.name == name) {
return invalid(format!("a field named {name:?} already exists"));
if radio_group.is_none()
&& let Some(why) = existing.iter().find_map(|f| clash(&name, &f.name))
{
return invalid(why);
}
let af = ensure_form(doc)?;
let mut w = widget_dict(page_ref, rect);
@@ -637,12 +936,11 @@ pub fn add_field(doc: &mut Document, page: usize, rect: [f64; 4], kind: &NewFiel
let mut g = Dict::new();
g.set(b"FT".to_vec(), Object::name("Btn"));
g.set(b"Ff".to_vec(), Object::Int((flags::RADIO | flags::NO_TOGGLE_TO_OFF) as i64));
g.set(b"T".to_vec(), PdfString::text(&field_name));
g.set(b"V".to_vec(), Object::name("Off"));
g.set(b"DA".to_vec(), PdfString::literal(b"/ZaDb 0 Tf 0 g".to_vec()));
g.set(b"Kids".to_vec(), Object::Array(Vec::new()));
let g = doc.add(Object::Dict(g));
add_to_fields(doc, af, g)?;
attach(doc, af, g, &parts)?;
g
}
};
@@ -666,13 +964,10 @@ pub fn add_field(doc: &mut Document, page: usize, rect: [f64; 4], kind: &NewFiel
caption: None,
list: None,
};
let ap = appearance::check_box_states(doc, &w, FieldKind::Radio, export);
let ap = appearance::check_box_states(doc, &w, FieldKind::Radio, export, "/ZaDb 0 Tf 0 g");
doc.update_dict(widget, |d| d.set(b"AP".to_vec(), Object::Dict(ap)))?;
}
_ => {
doc.update_dict(widget, |d| d.set(b"T".to_vec(), PdfString::text(&name)))?;
add_to_fields(doc, af, widget)?;
}
_ => attach(doc, af, widget, &parts)?,
}
add_to_page(doc, page_ref, widget)?;
redraw_field(doc, &field_name)?;
@@ -709,7 +1004,7 @@ fn redraw_widgets(doc: &mut Document, name: &str, only: Option<usize>) -> Result
}
FieldKind::CheckBox | FieldKind::Radio => {
let on = w.on_state.clone().unwrap_or_else(|| "Yes".into());
appearance::check_box_states(doc, w, f.kind, &on)
appearance::check_box_states(doc, w, f.kind, &on, &f.da)
}
FieldKind::PushButton => {
let (s, m) = button_appearance(doc, w, &f.da);
@@ -775,7 +1070,7 @@ fn form_stream(place: crate::appearance::Placement, content: Vec<u8>, resources:
/// color its `/DA` asks for (the widget's, else `field_da`, the field's own or inherited one).
/// Also returns the first caption character the font can't draw (drawn as `?`), for the caller to
/// mark and report.
fn button_appearance(doc: &Document, w: &Widget, field_da: &str) -> (Stream, Option<char>) {
pub(crate) fn button_appearance(doc: &Document, w: &Widget, field_da: &str) -> (Stream, Option<char>) {
let (mut c, place) = frame_only(doc, w);
let (width, height) = (place.layout_w, place.layout_h);
let wobj = doc.get(w.obj);
@@ -919,18 +1214,52 @@ pub fn set_props(doc: &mut Document, name: &str, props: &FieldProps) -> Result<S
}
let mut new_name = name.to_string();
if let Some(n) = props.name.as_deref().map(str::trim).filter(|n| *n != f.name) {
if n.is_empty() || n.contains('.') {
return invalid("field names can't be empty or contain a period");
// A full name under the same parents only renames the field's own part (the editor
// shows nested fields by their full name): it isn't moved, so it keeps its place and
// goes on inheriting from its parents.
let n = match (n.rsplit_once('.'), f.name.rsplit_once('.')) {
(Some((parents, own)), Some((current, _))) if parents == current => own,
_ => n,
};
if n.contains('.') {
// A full name: the field moves under the parent fields it names (#2696).
let parts = name_parts(n)?;
if let Some(why) = all.iter().filter(|x| x.obj != f.obj).find_map(|x| clash(n, &x.name)) {
return invalid(why);
}
let af = ensure_form(doc)?;
// Checked before anything changes, so a refused move leaves the field as it was.
let add = inherited(doc, f.obj);
check_place(doc, af, f.obj, &parts, &add)?;
// From here a failure (a write that `check_place` couldn't foresee) would leave the
// field half moved in `doc`. The engine runs every edit on a copy of the document and
// keeps it only when the edit succeeds (`Session::apply`), so the open document never
// sees that.
own_inherited(doc, f.obj, &add)?;
detach(doc, f.obj)?;
attach(doc, af, f.obj, &parts)?;
new_name = n.to_string();
} else {
if n.is_empty() {
return invalid("field names can't be empty");
}
// Rename the terminal part (the field's own /T). The parents' part stays, so the name
// that must be free is the full one: `MASTER.a` renamed to `b` takes `MASTER.b` (ISO
// 32000-2 §12.7.4.2). The field itself is no clash when it keeps its own name.
let prefix = f.name.rsplit_once('.').map(|(p, _)| format!("{p}.")).unwrap_or_default();
new_name = format!("{prefix}{n}");
if let Some(why) = all.iter().filter(|x| x.obj != f.obj).find_map(|x| clash(&new_name, &x.name)) {
return invalid(why);
}
// A node of that name beside it that isn't a terminal field, such as a parent
// field left empty by a move.
let af = ensure_form(doc)?;
let parent = doc.get(f.obj).as_dict().and_then(|d| d.reference(b"Parent"));
if child_named(doc, af, parent, n).is_some_and(|r| r != f.obj) {
return invalid(format!("a field named {new_name:?} already exists"));
}
doc.update_dict(f.obj, |d| d.set(b"T".to_vec(), PdfString::text(n)))?;
}
// Rename the terminal part (the field's own /T). The parents' part stays, so the name that
// must be free is the full one: `MASTER.a` renamed to `b` takes `MASTER.b` (ISO 32000-2
// §12.7.4.2). The field itself is no clash when it keeps its own name.
let prefix = f.name.rsplit_once('.').map(|(p, _)| format!("{p}.")).unwrap_or_default();
new_name = format!("{prefix}{n}");
if all.iter().any(|x| x.obj != f.obj && x.name == new_name) {
return invalid(format!("a field named {new_name:?} already exists"));
}
doc.update_dict(f.obj, |d| d.set(b"T".to_vec(), PdfString::text(n)))?;
// Calculations read the field by its new name, unless another field keeps the old one.
if all.iter().filter(|x| x.name == f.name).count() == 1 {
rename_in_calculations(doc, &all, &f.name, &new_name)?;
@@ -980,7 +1309,7 @@ pub fn set_props(doc: &mut Document, name: &str, props: &FieldProps) -> Result<S
{
return invalid("alignment is 0 (left), 1 (centre) or 2 (right)");
}
if props.options.as_ref().is_some_and(|o| o.is_empty()) && matches!(f.kind, FieldKind::Combo | FieldKind::List) {
if props.options.as_ref().is_some_and(Vec::is_empty) && matches!(f.kind, FieldKind::Combo | FieldKind::List) {
return invalid("a list needs at least one option");
}
if props.check_style.is_some() && !matches!(f.kind, FieldKind::CheckBox | FieldKind::Radio) {
@@ -1262,33 +1591,7 @@ fn delete_found_field(doc: &mut Document, f: Field) -> Result<(), FormError> {
}
}
}
// Out of the field tree: from its parent's /Kids, or from /Fields.
let parent = doc.get(f.obj).as_dict().and_then(|d| d.reference(b"Parent"));
let remove_from = |doc: &mut Document, holder: ObjRef, key: &[u8]| -> Result<(), FormError> {
let mut d = doc.get(holder).as_dict().cloned().unwrap_or_default();
let list = d.get(key).map(|o| doc.resolve(o)).and_then(|o| o.as_array().cloned()).unwrap_or_default();
let kept: Vec<Object> = list.into_iter().filter(|o| o.as_ref() != Some(f.obj)).collect();
d.set(key.to_vec(), Object::Array(kept));
doc.set(holder, Object::Dict(d));
Ok(())
};
match parent {
Some(p) => remove_from(doc, p, b"Kids")?,
None => {
let root = doc.root().ok_or(FormError::NoForm)?;
match doc.get(root).as_dict().and_then(|d| d.get(b"AcroForm").cloned()) {
Some(Object::Ref(af)) => remove_from(doc, af, b"Fields")?,
// A form dictionary held directly in the catalog.
Some(Object::Dict(mut af)) => {
let list = af.get(b"Fields").map(|o| doc.resolve(o)).and_then(|o| o.as_array().cloned()).unwrap_or_default();
let kept: Vec<Object> = list.into_iter().filter(|o| o.as_ref() != Some(f.obj)).collect();
af.set(b"Fields".to_vec(), Object::Array(kept));
doc.update_dict(root, |d| d.set(b"AcroForm".to_vec(), Object::Dict(af)))?;
}
_ => {}
}
}
}
detach(doc, f.obj)?;
// Out of the calculation order too: a `/CO` entry would keep the field, its value and its
// widgets reachable for a full save.
drop_from_calculation_order(doc, |r| r == f.obj || widgets.contains(&r))
+11 -7
View File
@@ -243,13 +243,7 @@ fn components(links: &[Vec<usize>]) -> Vec<usize> {
continue;
}
if low[v] == index[v] {
while let Some(w) = stack.pop() {
on_stack[w] = false;
component[w] = count;
if w == v {
break;
}
}
pop_component(&mut stack, &mut on_stack, &mut component, v, count);
count += 1;
}
if let Some(&(parent, _)) = work.last() {
@@ -260,6 +254,16 @@ fn components(links: &[Vec<usize>]) -> Vec<usize> {
component
}
fn pop_component(stack: &mut Vec<usize>, on_stack: &mut [bool], component: &mut [usize], v: usize, count: usize) {
while let Some(w) = stack.pop() {
on_stack[w] = false;
component[w] = count;
if w == v {
break;
}
}
}
/// Fix order: every node after the nodes it reads in other components, the earliest ready node
/// first, so an order that is already right stays as it is and otherwise only what must move
/// moves. Reads within a component (a loop) are left out: no order satisfies them.
+1 -1
View File
@@ -307,7 +307,7 @@ fn label_for(words: &[Word], rect: [f64; 4], right_of: bool) -> String {
.iter()
.filter(|w| w.rect[1] >= rect[3] - 1.0 && w.rect[1] - rect[3] < 24.0 && w.rect[0] < rect[2] && w.rect[2] > rect[0] - 4.0)
.collect();
let Some(line) = above.iter().map(|w| mid(w.rect)).min_by(|a, b| a.total_cmp(b)) else { return String::new() };
let Some(line) = above.iter().map(|w| mid(w.rect)).min_by(f64::total_cmp) else { return String::new() };
let mut on: Vec<&&Word> = above.iter().filter(|w| (mid(w.rect) - line).abs() < 3.0).collect();
on.sort_by(|a, b| a.rect[0].total_cmp(&b.rect[0]));
clean(&on.iter().map(|w| w.text.as_str()).collect::<Vec<_>>().join(" "))
+203 -14
View File
@@ -24,7 +24,7 @@ mod calc_order;
pub mod detect;
mod scripting;
pub mod table;
pub use actions::{FieldAction, Trigger, field_actions, set_field_actions};
pub use actions::{FieldAction, Trigger, field_action_chains, field_actions, set_field_actions};
pub use author::{
BorderStyle, CheckStyle, FieldFont, FieldProps, Look, LookPatch, MIN_FIELD_SIDE, NewField, add_field, check_style, delete_field,
delete_field_object, duplicate_field, look, redraw_field, set_button_icon, set_props,
@@ -48,6 +48,10 @@ pub enum FormError {
ReadOnly(String),
#[error("{0}")]
Invalid(String),
/// The value doesn't fit the field's format (its keystroke check refused it), which is
/// checked before any of the field's scripts run.
#[error("{0}")]
Format(String),
#[error("{0}")]
Cos(#[from] pdfcraft_cos::CosError),
}
@@ -932,6 +936,7 @@ pub fn set_value_with(doc: &mut Document, name: &str, value: &FieldValue, script
return Err(FormError::ReadOnly(name.into()));
}
write_value(doc, f, value, scripts)?;
author::form_fonts_as_objects(doc, &all)?;
// Fields with the same fully qualified name are one field (§12.7.3.1). Writers that repeat a
// name as separate field dictionaries, instead of widgets under one parent, get the value
// the first one took after its scripts, without running them again.
@@ -1049,7 +1054,7 @@ fn write_value(doc: &mut Document, f: &Field, value: &FieldValue, scripts: &mut
return invalid(format!("{:?} takes at most {max} characters", f.name));
}
// Keystroke (on commit) and Validate, as Acrobat runs them before accepting a value.
let t = &af::keystroke(&f.actions.format, &f.name, t).map_err(FormError::Invalid)?;
let t = &af::keystroke(&f.actions.format, &f.name, t).map_err(FormError::Format)?;
af::validate(&f.actions.validate, t).map_err(FormError::Invalid)?;
let t = &scripting::accept(doc, f, t, scripts)?;
doc.update_dict(f.obj, |d| {
@@ -1191,7 +1196,7 @@ fn set_states(doc: &mut Document, f: &Field, on: Option<&str>) -> Result<(), For
let has_ap = doc.get(w.obj).as_dict().and_then(|d| d.get(b"AP").cloned()).is_some();
if !has_ap {
let on_name = w.on_state.clone().unwrap_or_else(|| on.unwrap_or("Yes").to_string());
let ap = appearance::check_box_states(doc, w, f.kind, &on_name);
let ap = appearance::check_box_states(doc, w, f.kind, &on_name, &f.da);
doc.update_dict(w.obj, |d| d.set(b"AP".to_vec(), Object::Dict(ap)))?;
}
doc.update_dict(w.obj, |d| d.set(b"AS".to_vec(), name_obj(state)))?;
@@ -1293,16 +1298,158 @@ pub(crate) fn ask_viewers_to_redraw(doc: &mut Document) -> Result<(), FormError>
Ok(())
}
/// Text fields with the Password flag (inherited or their own) whose value (`/V`, inherited or
/// their own) is not empty and not their default value (`/DV`, which the form's author wrote and
/// a save restores), or one of whose separate widgets carries a `/V`.
fn password_fields(doc: &Document) -> Vec<Field> {
if !has_password_flag(doc) {
return Vec::new();
}
let on_widget = |f: &Field| f.widgets.iter().any(|w| w.obj != f.obj && doc.get(w.obj).as_dict().is_some_and(|d| d.get(b"V").is_some()));
let typed = |f: &Field| f.value.iter().any(|v| !v.is_empty()) && f.value.first() != f.default.first();
fields(doc).into_iter().filter(|f| f.kind == FieldKind::Text && f.has(flags::PASSWORD) && (typed(f) || on_widget(f))).collect()
}
/// Whether any field dictionary sets the Password flag (#3943 review). A field that inherits the
/// flag has an ancestor that sets it, so that ancestor is found instead; a kid clearing the flag
/// again only makes the answer cautious. It reads only `/Ff`, `/Kids` and `/Parent`, so a save
/// or recovery snapshot of a form without such a field doesn't build every [`Field`]. Like
/// [`fields`], it looks at the form's field tree and at the widgets on the pages, which may be
/// missing from `/Fields`. Each dictionary is visited once and at most 32 levels deep.
fn has_password_flag(doc: &Document) -> bool {
let sets_it = |r: ObjRef| doc.get(r).as_dict().and_then(|d| field_flags(doc, d)).is_some_and(|ff| ff & flags::PASSWORD != 0);
let top = acroform(doc).and_then(|af| af.get(b"Fields").map(|o| doc.resolve(o)).and_then(|o| o.as_array().cloned())).unwrap_or_default();
let mut stack: Vec<(Object, usize)> = top.into_iter().map(|o| (o, 0)).collect();
let mut seen = std::collections::HashSet::new();
while let Some((o, depth)) = stack.pop() {
let Object::Ref(r) = o else { continue };
if depth > 32 || !seen.insert(r) {
continue;
}
if sets_it(r) {
return true;
}
let kids = doc.get(r).as_dict().and_then(|d| d.get(b"Kids").map(|k| doc.resolve(k)).and_then(|k| k.as_array().cloned())).unwrap_or_default();
stack.extend(kids.into_iter().map(|k| (k, depth + 1)));
}
// Widgets on the pages, and the fields above them.
page_refs(doc).into_iter().any(|p| {
let annots =
doc.get(p).as_dict().and_then(|d| d.get(b"Annots").map(|a| doc.resolve(a)).and_then(|a| a.as_array().cloned())).unwrap_or_default();
annots.iter().filter_map(Object::as_ref).filter(|r| !seen.contains(r)).any(|r| field_chain(doc, r).into_iter().any(sets_it))
})
}
/// Whether any text field with the Password flag holds a value in `doc`.
pub fn has_password_values(doc: &Document) -> bool {
!password_fields(doc).is_empty()
}
/// The typed values of the text fields with the Password flag, as (name, text) pairs, for
/// [`restore_password_values`] after the document was rebased on a file written without them.
pub fn password_values(doc: &Document) -> Vec<(String, String)> {
password_fields(doc).into_iter().filter_map(|f| f.value.first().map(|v| (f.name.clone(), v.clone()))).collect()
}
/// Put values from [`password_values`] back into the open document, in memory only. A field
/// that is gone or read-only keeps what it has.
pub fn restore_password_values(doc: &mut Document, values: &[(String, String)]) -> Result<(), FormError> {
for (name, v) in values {
match set_value(doc, name, &FieldValue::Text(v.clone())) {
Ok(()) | Err(FormError::NoSuchField(_) | FormError::ReadOnly(_)) => {}
Err(e) => return Err(e),
}
}
Ok(())
}
/// `r` and its field ancestors (`/Parent`), nearest first, at most 32 deep and without repeats.
fn field_chain(doc: &Document, r: ObjRef) -> Vec<ObjRef> {
let mut chain = vec![r];
let mut cur = r;
while chain.len() < 32 {
let Some(Object::Ref(parent)) = doc.get(cur).as_dict().and_then(|d| d.get(b"Parent").cloned()) else { break };
if chain.contains(&parent) {
break;
}
chain.push(parent);
cur = parent;
}
chain
}
/// Remove the values of the text fields with the Password flag, for a copy of the document about
/// to be written to a file (#3926). ISO 32000-2 §12.7.5.3, Table 231, Password flag, note: "it is
/// imperative that PDF processors never store the value of the text field in the PDF file if
/// this flag is set". As Acrobat saves such a field (#3943 review, black-box test): a field with
/// a default value (`/DV`, which the form's author wrote) gets it back as its value, one without
/// is left empty, and its appearance is drawn again from that value, so the masking characters
/// no longer show how long the typed password was. `/DV` and the field's scripts stay.
///
/// A value can sit on the field, on one of its widgets, or on an ancestor it inherits from
/// (`/V` is inheritable). Each is removed; an ancestor's only when every field inheriting from it
/// is such a password field. Where an ancestor's value is shared with other fields and stays, the
/// password field gets an empty value of its own so it no longer inherits it. Returns how many
/// fields were cleared.
pub fn clear_password_values(doc: &mut Document) -> Result<usize, FormError> {
let targets = password_fields(doc);
if targets.is_empty() {
return Ok(0);
}
let is_password = |f: &Field| f.kind == FieldKind::Text && f.has(flags::PASSWORD);
// Each field's ancestors, found once: only values change below, never `/Parent` (#3943
// review: walking them again for every ancestor of every target was quadratic).
let chains: Vec<(bool, Vec<ObjRef>)> = fields(doc).iter().map(|g| (is_password(g), field_chain(doc, g.obj))).collect();
for f in &targets {
let chain = field_chain(doc, f.obj);
for w in &f.widgets {
if w.obj != f.obj {
doc.update_dict(w.obj, |d| {
d.remove(b"V");
})?;
}
}
doc.update_dict(f.obj, |d| {
d.remove(b"V");
})?;
let mut shared_value_kept = false;
for a in chain.iter().skip(1) {
if doc.get(*a).as_dict().is_none_or(|d| d.get(b"V").is_none()) {
continue;
}
let exclusive = chains.iter().filter(|(_, chain)| chain.contains(a)).all(|(password, _)| *password);
if exclusive {
doc.update_dict(*a, |d| {
d.remove(b"V");
})?;
} else {
shared_value_kept = true;
}
}
let restored: Vec<String> = f.default.first().cloned().into_iter().collect();
match restored.first() {
Some(dv) => doc.update_dict(f.obj, |d| d.set(b"V".to_vec(), PdfString::text(dv)))?,
None if shared_value_kept => doc.update_dict(f.obj, |d| d.set(b"V".to_vec(), PdfString::text("")))?,
None => {}
}
redraw(doc, f, &restored, &mut NoScripts)?;
}
Ok(targets.len())
}
/// Whether the form asks viewers to draw its fields' appearances themselves (`/NeedAppearances`).
pub fn need_appearances(doc: &Document) -> bool {
acroform(doc).is_some_and(|af| matches!(af.get(b"NeedAppearances").map(|o| doc.resolve(o)).as_deref(), Some(Object::Bool(true))))
}
/// A copy of `doc` in which text and choice fields are drawn from their values, for displaying
/// the document (`None` when no widget needs it): every such widget when the form sets
/// `/NeedAppearances` (ISO 32000-2 Table 224: the writer left the appearances to the viewer),
/// and otherwise each widget without a normal appearance (`/AP /N`). Drawn as typing the value
/// would draw it (#3470). `doc` is not changed: saving writes the file as it was.
/// A copy of `doc` in which form fields are drawn the way the file leaves to the viewer, for
/// displaying the document (`None` when no widget needs it). Text and choice fields are drawn from
/// their values: every one when the form sets `/NeedAppearances` (ISO 32000-2 Table 224: the
/// writer left the appearances to the viewer), and otherwise each widget without a normal
/// appearance (`/AP /N`), as typing the value would draw it (#3470). Check boxes and radio buttons
/// with no normal appearance for their state (`/AS`) are drawn from their `/MK` background, border
/// and caption, and push buttons with none from their `/MK` and `/BS` (Table 192). `doc` is not
/// changed: saving writes the file as it was.
pub fn with_field_appearances(doc: &Document) -> Option<Document> {
with_field_appearances_cached(doc, &mut FieldAppearanceCache::default())
}
@@ -1312,18 +1459,45 @@ pub fn with_field_appearances(doc: &Document) -> Option<Document> {
pub fn with_field_appearances_cached(doc: &Document, cache: &mut FieldAppearanceCache) -> Option<Document> {
let all = need_appearances(doc);
let mut copy: Option<Document> = None;
for f in fields(doc).iter().filter(|f| matches!(f.kind, FieldKind::Text | FieldKind::Combo | FieldKind::List)) {
for f in fields(doc) {
for w in &f.widgets {
let widget = doc.get(w.obj);
let drawn = widget.as_dict().and_then(|d| d.get(b"AP")).is_some_and(|ap| doc.resolve(ap).as_dict().is_some_and(|ap| ap.contains(b"N")));
if drawn && !all {
let normal = widget
.as_dict()
.and_then(|d| d.get(b"AP"))
.and_then(|ap| doc.resolve(ap).as_dict().and_then(|ap| ap.get(b"N").map(|n| doc.resolve(n))));
// A check box or radio button shows the appearance of its state (12.7.5.2.3): `/AS`,
// else a check box's value, else Off. An Off state may go without one (it shows
// nothing); an on state needs one.
let state = match f.kind {
FieldKind::CheckBox | FieldKind::Radio => {
let value = f.value.first().filter(|v| f.kind == FieldKind::CheckBox && !v.is_empty() && v.as_str() != "Off");
Some(w.state.clone().or_else(|| value.cloned()).unwrap_or_else(|| "Off".into()))
}
_ => None,
};
let missing = match f.kind {
FieldKind::Text | FieldKind::Combo | FieldKind::List => normal.is_none() || all,
FieldKind::PushButton => normal.is_none(),
FieldKind::CheckBox | FieldKind::Radio => match (normal.as_deref(), state.as_deref()) {
(None, _) => true,
(Some(Object::Dict(states)), Some(s)) => s != "Off" && !states.contains(&name_bytes(s)),
_ => false,
},
FieldKind::Signature => false,
};
if !missing {
continue;
}
let inputs = appearance_inputs(doc, w);
let stream = match cache.get(w.obj, &inputs) {
Some(stream) => stream,
None => {
let (stream, _) = appearance::field_appearance_drawn(doc, f, w, &f.value, true);
let stream = match f.kind {
FieldKind::CheckBox | FieldKind::Radio => appearance::button_state_shown(doc, &f, w, state.as_deref() != Some("Off")),
FieldKind::PushButton => appearance::push_button_shown(doc, &f, w),
_ => appearance::field_appearance_drawn(doc, &f, w, &f.value, true).0,
};
cache.insert(w.obj, inputs, &stream);
stream
}
@@ -1331,10 +1505,25 @@ pub fn with_field_appearances_cached(doc: &Document, cache: &mut FieldAppearance
let target = copy.get_or_insert_with(|| doc.clone());
let ap = target.add(Object::Stream(stream));
let mut fresh = Dict::new();
fresh.set(b"N".to_vec(), Object::Ref(ap));
match &state {
// The drawn look under its state's name, and that state as the widget's own.
Some(s) => {
let mut states = Dict::new();
states.set(name_bytes(s), Object::Ref(ap));
fresh.set(b"N".to_vec(), Object::Dict(states));
}
None => fresh.set(b"N".to_vec(), Object::Ref(ap)),
}
let apd = merged_appearance(target, w.obj, &fresh);
// Fails only when the widget isn't a dictionary; that widget then keeps its own look.
target.update_dict(w.obj, |d| d.set(b"AP".to_vec(), Object::Dict(apd))).ok();
target
.update_dict(w.obj, |d| {
d.set(b"AP".to_vec(), Object::Dict(apd));
if let Some(s) = &state {
d.set(b"AS".to_vec(), Object::Name(name_bytes(s)));
}
})
.ok();
}
}
copy
+8 -3
View File
@@ -269,23 +269,28 @@ pub fn cell_name(pattern: &str, row: usize, column: usize, seq: usize) -> String
if numbered {
return out;
}
substitute_isolated_n(&out, &row_number)
}
fn substitute_isolated_n(out: &str, row_number: &str) -> String {
if out == "N" || out == "n" {
return row_number;
return row_number.to_string();
}
let chars: Vec<char> = out.chars().collect();
let mut named = String::with_capacity(out.len() + row_number.len());
let mut numbered = false;
for (i, &ch) in chars.iter().enumerate() {
let after_separator = i.checked_sub(1).and_then(|p| chars.get(p)).is_some_and(|c| SEPARATORS.contains(c));
let before_separator = chars.get(i + 1).is_none_or(|c| SEPARATORS.contains(c));
if matches!(ch, 'N' | 'n') && after_separator && before_separator {
named.push_str(&row_number);
named.push_str(row_number);
numbered = true;
} else {
named.push(ch);
}
}
if !numbered {
named.push_str(&row_number);
named.push_str(row_number);
}
named
}
+1204 -1
View File
File diff suppressed because it is too large. Load diff
+5 -4
View File
@@ -123,7 +123,7 @@ fn lex(src: &str) -> Result<Vec<Token>, String> {
}
out.push(Token { tok: Tok::Str(s), line });
}
c if c.is_ascii_digit() || (c == '.' && chars.get(i + 1).is_some_and(|d| d.is_ascii_digit())) => {
c if c.is_ascii_digit() || (c == '.' && chars.get(i + 1).is_some_and(char::is_ascii_digit)) => {
let start = i;
while i < chars.len() && (chars[i].is_ascii_digit() || (chars[i] == '.' && chars.get(i + 1) != Some(&'.'))) {
i += 1;
@@ -760,7 +760,7 @@ fn parse_num(s: &str) -> Option<f64> {
}
fn is_numeric_text(s: &str) -> bool {
s.trim().parse::<f64>().is_ok_and(|v| v.is_finite())
s.trim().parse::<f64>().is_ok_and(f64::is_finite)
}
// ── the evaluator ───────────────────────────────────────────────────────────────────────────
@@ -1948,7 +1948,7 @@ fn parse_date(text: &str, picture: &str) -> Option<(i64, u32, u32)> {
}
/// Number of days in month `m` (1-12) of year `y`, leap years included.
fn days_in(y: i64, m: u32) -> u32 {
pub(crate) fn days_in(y: i64, m: u32) -> u32 {
// The length of the month from chrono (the first of the next month, less the first of this
// one). An invalid month keeps the old 31-day default.
// Month lengths repeat every 400 years, so the year within its cycle is enough (and always
@@ -2325,10 +2325,11 @@ impl Interp<'_> {
}
text = if frac.is_empty() { g } else { format!("{g}.{frac}") };
}
let nonzero = text.chars().any(|c| ('1'..='9').contains(&c));
if pic.contains('$') {
text = format!("${text}");
}
if num < 0.0 {
if num < 0.0 && nonzero {
text = format!("-{text}");
}
Val::Str(text)
+440 -11
View File
@@ -13,8 +13,8 @@
//! `required`, `display`, `hidden`, `numItems`, `getItemAt`, `currentValueIndices`,
//! `isBoxChecked`, `checkThisBox`, `exportValues`, `charLimit`, `textColor`, `fillColor`,
//! `setFocus`.
//! - `app` (`alert`, `beep`, `response`, `launchURL`, `viewerType`, `viewerVersion`,
//! `platform`, `setTimeOut`), `util` (`printf`, `printd`, `printx`), `console` (`println`,
//! - `app` (`alert`, `beep`, `response`, `launchURL`, `execMenuItem`, `viewerType`, `viewerVersion`,
//! `platform`, `setTimeOut`), `util` (`printf`, `printd`, `printx`, `scand`), `console` (`println`,
//! `show`, `clear`), `display` and `color`.
//!
//! The engine is a sandbox: no file, network or timer access exists, and loops and recursion
@@ -28,7 +28,7 @@ use std::collections::BTreeSet;
use std::sync::Arc;
use boa_engine::context::HostHooks;
use boa_engine::object::builtins::{JsArray, JsFunction};
use boa_engine::object::builtins::{JsArray, JsDate, JsFunction};
use boa_engine::object::{FunctionObjectBuilder, ObjectInitializer};
use boa_engine::property::Attribute;
use boa_engine::realm::Realm;
@@ -164,6 +164,36 @@ pub enum Request {
Beep,
/// `app.execMenuItem("SaveAs")` (XFA forms' Save buttons).
SaveAs,
/// `app.execMenuItem("ShowHide…")`: show the side panel, or hide it when it is showing.
ShowPanel(Panel),
}
/// A side panel a script can show or hide (`app.execMenuItem("ShowHideFileAttachment")`, …).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Panel {
/// The document's bookmarks (outline).
Bookmarks,
/// Page thumbnails.
Pages,
/// The files attached to the document.
Attachments,
/// The document's signatures and their validity.
Signatures,
/// The document's layers (optional content).
Layers,
}
impl Panel {
/// The panel's name in automation output, fixed whatever the variant is called.
pub fn id(self) -> &'static str {
match self {
Panel::Bookmarks => "bookmarks",
Panel::Pages => "pages",
Panel::Attachments => "attachments",
Panel::Signatures => "signatures",
Panel::Layers => "layers",
}
}
}
/// What running a script did.
@@ -181,6 +211,9 @@ pub struct Outcome {
pub requests: Vec<Request>,
/// The script's error (syntax error, exception, or a limit reached), if it failed.
pub error: Option<String>,
/// Errors in the document-level scripts that ran first. Each is a script of its own: one
/// that throws stops where it failed, and the others and the script itself still run (#3940).
pub doc_errors: Vec<String>,
/// The script's completion value (what the console prints), unless undefined.
pub result: Option<String>,
}
@@ -626,6 +659,8 @@ fn message(v: &JsValue, key: &str, ctx: &mut Context) -> JsResult<String> {
}
}
/// `app.alert(cMsg)`: records the message, given as a string or as an object with `cMsg`, and
/// returns 1 (the OK button).
fn alert(_: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> {
let m = message(&arg(args, 0), "cMsg", ctx)?;
host(ctx)?.borrow_mut().alert(m);
@@ -633,17 +668,49 @@ fn alert(_: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValue>
Ok(JsValue::from(1))
}
/// `app.beep()`: queues a request to beep.
fn beep(_: &JsValue, _: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> {
host(ctx)?.borrow_mut().request(Request::Beep);
Ok(JsValue::undefined())
}
/// `app.launchURL(cURL)`: queues a request to open the URL, given as a string or as an object
/// with `cURL`.
fn launch_url(_: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> {
let u = message(&arg(args, 0), "cURL", ctx)?;
host(ctx)?.borrow_mut().request(Request::LaunchUrl(u));
Ok(JsValue::undefined())
}
/// What `app.execMenuItem(name)` asks for, for the menu items forms use: the side panels, Print
/// and Save As. Other items do nothing.
pub(crate) fn menu_item(name: &str) -> Option<Request> {
Some(match name {
"ShowHideFileAttachment" => Request::ShowPanel(Panel::Attachments),
"ShowHideBookmarks" => Request::ShowPanel(Panel::Bookmarks),
"ShowHideThumbnails" => Request::ShowPanel(Panel::Pages),
"ShowHideSignatures" => Request::ShowPanel(Panel::Signatures),
"ShowHideOptCont" => Request::ShowPanel(Panel::Layers),
"Print" => Request::Print,
// Save opens Save As too, as it always has for XFA forms' buttons: a click on a form
// never overwrites the file unasked.
"SaveAs" | "Save" => Request::SaveAs,
_ => return None,
})
}
/// `app.execMenuItem(name)`: queues the request [`menu_item`] gives for the name (Save opens
/// Save As too); an unknown name does nothing.
fn exec_menu_item(_: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> {
let item = text(&arg(args, 0), ctx)?;
if let Some(r) = menu_item(&item) {
host(ctx)?.borrow_mut().request(r);
}
Ok(JsValue::undefined())
}
/// `app.response(…)`: always `null`, the answer for a canceled dialog, since no one is there to
/// type one.
fn response(_: &JsValue, _: &[JsValue], _: &mut Context) -> JsResult<JsValue> {
// No one to answer: as if the dialog was cancelled.
Ok(JsValue::null())
@@ -885,6 +952,324 @@ fn printd(_: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValue>
Ok(s(&out))
}
/// A field of a `util.scand` format.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum DateUnit {
/// `yyyy`: four digits.
Year,
/// `yy`: two digits, read as 1950–2049.
ShortYear,
Month,
/// `mmm`, `mmmm`: a month's name or its three-letter abbreviation.
MonthName,
Day,
/// `ddd`, `dddd`: a weekday's name, read and not checked.
Weekday,
Hour,
/// `h`, `hh`: 0–12, with `tt` for the afternoon.
Hour12,
Minute,
Second,
/// `t`, `tt`: am or pm.
AmPm,
}
impl DateUnit {
/// A year, month or day: a format needs one of these for `util.scand` to read anything.
fn is_date(self) -> bool {
matches!(self, Self::Year | Self::ShortYear | Self::Month | Self::MonthName | Self::Day)
}
/// Read from a run of digits, not from letters.
fn is_numeric(self) -> bool {
!matches!(self, Self::MonthName | Self::Weekday | Self::AmPm)
}
}
/// A piece of a `util.scand` format.
#[derive(Debug, PartialEq, Eq)]
enum ScanPart {
/// A field, the digits it takes when typed together with the next one (`width`), and whether
/// the next one follows it with nothing between them in the format (`joined`).
Field { unit: DateUnit, width: usize, joined: bool },
/// Letters the format writes as they are, which the text must have there.
Word(String),
}
/// The fields and literal words of a `util.scand` format, in order. A numeric field is marked
/// `joined` when another numeric field follows it directly; anything but letters and digits
/// outside a field is left out.
fn scan_parts(fmt: &str) -> Vec<ScanPart> {
let chars: Vec<char> = fmt.chars().collect();
let mut parts: Vec<ScanPart> = Vec::new();
// The last part is a field written right before this point, or letters still being collected.
let (mut after_field, mut in_word) = (false, false);
let mut i = 0;
while let Some(&c) = chars.get(i) {
// Counted for field letters only, so a long run of anything else is read once.
let run = if "ymdHhMst".contains(c) { chars.get(i..).unwrap_or_default().iter().take_while(|x| **x == c).count() } else { 1 };
let field = match (c, run) {
('y', 4..) => Some((DateUnit::Year, 4)),
('y', _) => Some((DateUnit::ShortYear, 2)),
('m', 3..) => Some((DateUnit::MonthName, 0)),
('m', n) => Some((DateUnit::Month, n)),
('d', 3..) => Some((DateUnit::Weekday, 0)),
('d', n) => Some((DateUnit::Day, n)),
('H', n) => Some((DateUnit::Hour, n.min(2))),
('h', n) => Some((DateUnit::Hour12, n.min(2))),
('M', n) => Some((DateUnit::Minute, n.min(2))),
('s', n) => Some((DateUnit::Second, n.min(2))),
('t', _) => Some((DateUnit::AmPm, 0)),
_ => None,
};
if let Some((unit, width)) = field {
if after_field
&& unit.is_numeric()
&& let Some(ScanPart::Field { unit: last, joined, .. }) = parts.last_mut()
&& last.is_numeric()
{
*joined = true;
}
parts.push(ScanPart::Field { unit, width, joined: false });
(after_field, in_word) = (true, false);
i += run;
continue;
}
// `\` writes the next character as it is.
let (literal, step) = if c == '\\' { (chars.get(i + 1).copied(), 2) } else { (Some(c), 1) };
i += step;
after_field = false;
match literal {
Some(l) if l.is_alphanumeric() => match parts.last_mut() {
Some(ScanPart::Word(w)) if in_word => w.push(l),
_ => {
parts.push(ScanPart::Word(l.to_string()));
in_word = true;
}
},
_ => in_word = false,
}
}
parts
}
/// A run of digits or of letters in the text `util.scand` reads.
enum ScanToken<'a> {
Digits(&'a str),
Letters(&'a str),
}
/// The text's runs of digits and of letters, in order; anything else only separates them, and
/// may not begin or end the text. `None` when it does.
fn scan_tokens(text: &str) -> Option<Vec<ScanToken<'_>>> {
// Some(true) for a digit, Some(false) for a letter, None for a separator.
let kind = |c: char| (c.is_ascii_digit() || c.is_alphabetic()).then_some(c.is_ascii_digit());
kind(text.chars().next()?)?;
kind(text.chars().next_back()?)?;
let mut out = Vec::new();
let mut start: Option<(usize, bool)> = None;
for (at, c) in text.char_indices().chain(std::iter::once((text.len(), ' '))) {
let k = kind(c);
if let Some((from, digits)) = start
&& k != Some(digits)
{
let piece = text.get(from..at)?;
out.push(if digits { ScanToken::Digits(piece) } else { ScanToken::Letters(piece) });
start = None;
}
if let Some(digits) = k
&& start.is_none()
{
start = Some((at, digits));
}
}
Some(out)
}
/// What `util.scand` reads.
#[derive(Debug, PartialEq, Eq)]
enum Scanned {
/// The text is empty: today, at noon.
Today,
/// A date and time: year, month (1–12), day, hours, minutes, seconds.
At(i32, u32, u32, u32, u32, u32),
}
/// The fields `util.scand` has read so far.
#[derive(Default)]
struct ScanValues {
y: Option<i32>,
mo: Option<u32>,
d: Option<u32>,
h: Option<u32>,
mi: Option<u32>,
sec: Option<u32>,
pm: Option<bool>,
/// The hour was read from `h` or `hh`.
twelve: bool,
}
impl ScanValues {
/// Records `v` as the value of `unit`: a `yy` year as 1950–2049, and an `h` or `hh` hour
/// marked as 12-hour. Month names, weekdays and am/pm are not read here.
fn set(&mut self, unit: DateUnit, v: u32) {
match unit {
DateUnit::Year => self.y = i32::try_from(v).ok(),
DateUnit::ShortYear => self.y = i32::try_from(v).ok().map(|v| if v < 50 { 2000 + v } else { 1900 + v }),
DateUnit::Month => self.mo = Some(v),
DateUnit::Day => self.d = Some(v),
DateUnit::Hour => self.h = Some(v),
DateUnit::Hour12 => {
self.h = Some(v);
self.twelve = true;
}
DateUnit::Minute => self.mi = Some(v),
DateUnit::Second => self.sec = Some(v),
DateUnit::MonthName | DateUnit::Weekday | DateUnit::AmPm => {}
}
}
}
/// Reads `text` by a `util.scand` format, as another viewer was observed to (black-box):
///
/// - Fields may be separated by anything but digits and letters, whether or not the format
/// separates them, but nothing may come before the first or after the last.
/// - Digits typed together fill the format's fields written together with exactly as many
/// digits as each has letters (`yyyymd`: 4, 1 and 1). A run of digits for one field alone may
/// have one or two, except a four-digit year.
/// - `yy` is 1950–2049; month names may be written in full or as three letters, in any case.
/// - Impossible dates are refused, but a month or day of 0 is read as 1.
/// - A format with no year, month or day reads nothing; an empty text is today, at noon.
///
/// Not observed: a year left out is `this_year`, and a month or day left out is 1.
fn scan_date(fmt: &str, text: &str, this_year: i32) -> Option<Scanned> {
let parts = scan_parts(fmt);
if !parts.iter().any(|p| matches!(p, ScanPart::Field { unit, .. } if unit.is_date())) {
return None;
}
if text.is_empty() {
return Some(Scanned::Today);
}
let tokens = scan_tokens(text)?;
let mut v = ScanValues::default();
let (mut p, mut t) = (0, 0);
while let Some(part) = parts.get(p) {
let token = tokens.get(t)?;
t += 1;
match (part, token) {
(ScanPart::Word(w), ScanToken::Letters(l) | ScanToken::Digits(l)) => {
if w.to_lowercase() != l.to_lowercase() {
return None;
}
p += 1;
}
(ScanPart::Field { unit: DateUnit::MonthName, .. }, ScanToken::Letters(l)) => {
v.mo = Some(named(&MONTHS, l)?.saturating_add(1));
p += 1;
}
(ScanPart::Field { unit: DateUnit::Weekday, .. }, ScanToken::Letters(l)) => {
named(&DAYS, l)?;
p += 1;
}
(ScanPart::Field { unit: DateUnit::AmPm, .. }, ScanToken::Letters(l)) => {
v.pm = Some(match l.to_lowercase().as_str() {
"am" | "a" => false,
"pm" | "p" => true,
_ => return None,
});
p += 1;
}
(ScanPart::Field { unit, width, joined }, ScanToken::Digits(run)) if unit.is_numeric() => {
// The fields written together from here, no more than the run's digits can fill,
// and the fewest of them the run fills.
let mut group = vec![(*unit, *width)];
let (mut more, mut widths) = (*joined, *width);
while more
&& widths < run.len()
&& let Some(ScanPart::Field { unit, width, joined }) = parts.get(p + group.len())
{
group.push((*unit, *width));
widths = widths.saturating_add(*width);
more = *joined;
}
let mut sum = 0;
let fills = group.iter().position(|(_, w)| {
sum += w;
sum == run.len()
});
if let Some(last) = fills {
let mut at = 0;
for (unit, w) in group.iter().take(last + 1) {
v.set(*unit, run.get(at..at + w)?.parse().ok()?);
at += w;
}
p += last + 1;
} else if *unit != DateUnit::Year && run.len() <= 2 {
v.set(*unit, run.parse().ok()?);
p += 1;
} else {
return None;
}
}
_ => return None,
}
}
if t != tokens.len() {
return None;
}
let y = v.y.unwrap_or(this_year);
let mo = v.mo.unwrap_or(1).max(1);
let d = v.d.unwrap_or(1).max(1);
if mo > 12 || i64::from(d) > i64::from(formcalc::days_in(i64::from(y), mo)) {
return None;
}
let mut h = v.h.unwrap_or(0);
if v.twelve && h > 12 {
return None;
}
match v.pm {
Some(true) if h < 12 => h += 12,
Some(false) if h == 12 => h = 0,
_ => {}
}
let (mi, sec) = (v.mi.unwrap_or(0), v.sec.unwrap_or(0));
(h <= 23 && mi <= 59 && sec <= 59).then_some(Scanned::At(y, mo, d, h, mi, sec))
}
/// The index of the name `word` is, in full or as its first three letters, in any case.
fn named(names: &[&str], word: &str) -> Option<u32> {
let word = word.to_lowercase();
let i = names.iter().position(|n| {
let n = n.to_lowercase();
word == n || n.get(..3) == Some(word.as_str())
})?;
u32::try_from(i).ok()
}
/// `util.scand(cFormat, cDate)`: the date `cDate` gives by a `util.printd` format, as a local
/// `Date`, or `null` when it doesn't read as one (see [`scan_date`]). Only text is read.
fn scand(_: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> {
let Some(typed) = arg(args, 1).as_string().map(|t| t.to_std_string_escaped()) else {
return Ok(JsValue::null());
};
let fmt = text(&arg(args, 0), ctx)?;
let date = JsDate::new(ctx);
let this_year = date.get_full_year(ctx)?.to_number(ctx)?;
let this_year = if this_year.is_finite() { this_year as i32 } else { 2000 };
match scan_date(&fmt, &typed, this_year) {
None => return Ok(JsValue::null()),
Some(Scanned::Today) => {
date.set_hours(&[12.into(), 0.into(), 0.into(), 0.into()], ctx)?;
}
Some(Scanned::At(y, mo, d, h, mi, sec)) => {
// setFullYear, not the constructor, so years 0–99 stay as they are.
date.set_full_year(&[y.into(), (mo.saturating_sub(1)).into(), d.into()], ctx)?;
date.set_hours(&[h.into(), mi.into(), sec.into(), 0.into()], ctx)?;
}
}
Ok(date.into())
}
/// `util.printx(cFormat, cSource)`: `?` any character, `X` letter or digit, `A` letter, `9`
/// digit, `*` the rest, `\` escape, `>` / `<` / `=` upper / lower / as is.
fn printx(_: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> {
@@ -950,6 +1335,8 @@ fn printx(_: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValue>
Ok(s(&out))
}
/// The `color` object: each named color (`transparent`, `black`, `red`, `cyan`, `gray`, …) as
/// an array of its color space (`T`, `G`, `RGB` or `CMYK`) followed by its components.
fn color_object(ctx: &mut Context) -> JsObject {
let mut entries: Vec<(&str, Vec<JsValue>)> = vec![
("transparent", vec![s("T")]),
@@ -976,8 +1363,10 @@ fn color_object(ctx: &mut Context) -> JsObject {
/// The XFA version scripts see as `xfa_version`.
const XFA_VERSION: f64 = 3.5;
/// Define the globals every script sees: the document's functions and properties (`getField`,
/// `numPages`, `info`, the XFA version), and `app`, `util`, `console`, `display` and `color`.
/// Defines the form object model's globals: the document's functions (`getField`, `resetForm`,
/// `print`, `submitForm` and others) and properties (`numFields`, `pageNum`, `numPages`,
/// `documentFileName`, `info`, the XFA version), and the `app`, `util`, `console`, `display` and
/// `color` objects.
fn install(ctx: &mut Context) -> JsResult<()> {
let globals: [(&str, usize, NativeFunction); 9] = [
("getField", 1, NativeFunction::from_fn_ptr(get_field)),
@@ -1025,6 +1414,7 @@ fn install(ctx: &mut Context) -> JsResult<()> {
.function(NativeFunction::from_fn_ptr(beep), js_string!("beep"), 0)
.function(NativeFunction::from_fn_ptr(response), js_string!("response"), 1)
.function(NativeFunction::from_fn_ptr(launch_url), js_string!("launchURL"), 2)
.function(NativeFunction::from_fn_ptr(exec_menu_item), js_string!("execMenuItem"), 1)
.function(NativeFunction::from_fn_ptr(timer), js_string!("setTimeOut"), 2)
.function(NativeFunction::from_fn_ptr(timer), js_string!("setInterval"), 2)
.function(NativeFunction::from_fn_ptr(noop), js_string!("clearTimeOut"), 1)
@@ -1041,6 +1431,7 @@ fn install(ctx: &mut Context) -> JsResult<()> {
.function(NativeFunction::from_fn_ptr(printf), js_string!("printf"), 1)
.function(NativeFunction::from_fn_ptr(printd), js_string!("printd"), 2)
.function(NativeFunction::from_fn_ptr(printx), js_string!("printx"), 2)
.function(NativeFunction::from_fn_ptr(scand), js_string!("scand"), 2)
.build();
ctx.register_global_property(js_string!("util"), util, rw)?;
let console = ObjectInitializer::new(ctx)
@@ -1204,16 +1595,31 @@ pub fn run(script: &str, event: &Event, doc: &DocInfo, fields: &[FieldState], do
/// script can observe uncommitted writes. Read-only calculations avoid copying the whole form.
pub fn run_shared(script: &str, event: &Event, doc: &DocInfo, fields: Arc<Vec<FieldState>>, doc_scripts: &[String], limits: Limits) -> Outcome {
let failed = |why: String| Outcome { rc: true, value: event.value.clone(), change: event.change.clone(), error: Some(why), ..Default::default() };
if let Some(why) = std::iter::once(script).chain(doc_scripts.iter().map(String::as_str)).find_map(refuse) {
if let Some(why) = refuse(script) {
return failed(why);
}
// A document script too long or too deeply nested to run safely is skipped and reported,
// as one that throws is; the others and the script still run (#3940).
let mut skipped = Vec::new();
let kept: Vec<(usize, &str)> = doc_scripts
.iter()
.enumerate()
.filter_map(|(i, d)| match refuse(d) {
Some(why) => {
skipped.push((i, why));
None
}
None => Some((i, d.as_str())),
})
.collect();
let (kept, skipped) = (&kept, &skipped);
#[cfg(not(target_arch = "wasm32"))]
{
std::thread::scope(|scope| {
let spawned = std::thread::Builder::new()
.name("pdfcraft-js".into())
.stack_size(SCRIPT_STACK)
.spawn_scoped(scope, || run_here(script, event, doc, fields, doc_scripts, limits));
.spawn_scoped(scope, || run_here(script, event, doc, fields, kept, skipped, limits));
match spawned {
Ok(thread) => thread.join().unwrap_or_else(|_| failed("the script stopped with an internal error".into())),
Err(e) => failed(format!("the script engine could not start: {e}")),
@@ -1221,7 +1627,7 @@ pub fn run_shared(script: &str, event: &Event, doc: &DocInfo, fields: Arc<Vec<Fi
})
}
#[cfg(target_arch = "wasm32")]
run_here(script, event, doc, fields, doc_scripts, limits)
run_here(script, event, doc, fields, kept, skipped, limits)
}
/// Host hooks that refuse to compile code from strings (`eval`, `Function` and its generator
@@ -1256,7 +1662,22 @@ impl HostHooks for CheckedCodeFromStrings {
}
}
fn run_here(script: &str, event: &Event, doc: &DocInfo, fields: Arc<Vec<FieldState>>, doc_scripts: &[String], limits: Limits) -> Outcome {
/// How [`Outcome::doc_errors`] names a failing document script: by its 1-based place.
fn doc_error(index: usize, error: &dyn std::fmt::Display) -> String {
format!("document script {}: {error}", index.saturating_add(1))
}
/// `doc_scripts` are the document scripts to run with their places among all of them;
/// `skipped` the ones refused before running, with the reason.
fn run_here(
script: &str,
event: &Event,
doc: &DocInfo,
fields: Arc<Vec<FieldState>>,
doc_scripts: &[(usize, &str)],
skipped: &[(usize, String)],
limits: Limits,
) -> Outcome {
let mut ctx = match Context::builder().host_hooks(std::rc::Rc::new(NoCodeFromStrings)).build() {
Ok(ctx) => ctx,
Err(e) => {
@@ -1277,12 +1698,18 @@ fn run_here(script: &str, event: &Event, doc: &DocInfo, fields: Arc<Vec<FieldSta
dropped: 0,
}));
let mut out = Outcome { rc: true, value: event.value.clone(), change: event.change.clone(), ..Default::default() };
let mut doc_errors: Vec<(usize, String)> = skipped.iter().map(|(i, why)| (*i, doc_error(*i, why))).collect();
let result = (|| -> JsResult<()> {
install(&mut ctx)?;
let ev = event_object(&mut ctx, event);
ctx.register_global_property(js_string!("event"), ev.clone(), Attribute::all())?;
for d in doc_scripts {
ctx.eval(Source::from_bytes(d))?;
// One document script that throws (calling a method PdfCraft lacks, say) must not keep
// every field script in the form from running: what it defined before the error, and
// the other scripts, stay available (#3940).
for &(i, d) in doc_scripts {
if let Err(e) = ctx.eval(Source::from_bytes(d)) {
doc_errors.push((i, doc_error(i, &e)));
}
}
let r = ctx.eval(Source::from_bytes(script))?;
if !r.is_undefined() {
@@ -1299,6 +1726,8 @@ fn run_here(script: &str, event: &Event, doc: &DocInfo, fields: Arc<Vec<FieldSta
if let Err(e) = result {
out.error = Some(e.to_string());
}
doc_errors.sort_by_key(|(i, _)| *i);
out.doc_errors = doc_errors.into_iter().map(|(_, e)| e).collect();
if let Some(h) = ctx.remove_data::<Shared>() {
let h = h.into_inner();
out.changed = h.changed.iter().map(|i| h.fields[*i].clone()).collect();
+327 -2
View File
@@ -254,6 +254,13 @@ fn kept_bytes(o: &Outcome) -> usize {
o.console.iter().chain(&o.alerts).map(String::len).sum::<usize>() + o.requests.iter().map(req).sum::<usize>()
}
#[test]
fn exec_menu_item_requests_are_capped_like_other_requests() {
let o = go("for (var i = 0; i < 12000; i++) app.execMenuItem('Print');", &Event::field("Mouse Up", "agree", ""));
assert_eq!(o.error, None);
assert_eq!(o.requests.len(), crate::xfa::MAX_EFFECTS);
}
#[test]
fn console_alerts_and_requests_are_capped_in_count_and_bytes() {
let o = go(
@@ -297,6 +304,61 @@ fn document_level_functions_are_available() {
assert_eq!(o.value, "8");
}
/// #3940: a document script that throws after defining a helper (here calling an Acrobat method
/// PdfCraft lacks) still leaves the helper, and the later scripts, to the field script.
#[test]
fn a_failing_document_script_does_not_stop_the_field_script() {
let docs = [
"function double(x) { return x * 2; }\nthis.getField('qty').buttonSetIcon(null);\nvar after = 1;".to_string(),
"function plus(x) { return x + 1; }".to_string(),
"this is not javascript".to_string(),
];
let o = run(
"event.value = plus(double(getField('qty').value));",
&Event::field("Calculate", "total", ""),
&doc(),
&fields(),
&docs,
Limits::default(),
);
assert_eq!((o.error.as_deref(), o.value.as_str()), (None, "9"));
assert_eq!(o.doc_errors.len(), 2, "{:?}", o.doc_errors);
assert!(o.doc_errors[0].starts_with("document script 1: TypeError"), "{:?}", o.doc_errors);
assert!(o.doc_errors[1].starts_with("document script 3: SyntaxError"), "{:?}", o.doc_errors);
// The failing script stopped where it failed.
let o = run("event.value = typeof after;", &Event::field("Calculate", "total", ""), &doc(), &fields(), &docs, Limits::default());
assert_eq!(o.value, "undefined");
// Working document scripts report nothing.
assert!(go("event.value = 1;", &Event::field("Calculate", "total", "")).doc_errors.is_empty());
}
/// A document script refused before running (too long, or nested too deeply to run safely) is
/// skipped like one that throws: never run, reported in its place, the rest still run.
#[test]
fn a_document_script_too_big_to_run_is_skipped_and_reported() {
let docs = [
"this.getField('qty').buttonSetIcon(null);".to_string(),
format!("var big = 1{};", "+1".repeat(MAX_SCRIPT_BYTES / 2)),
"function double(x) { return x * 2; }".to_string(),
format!("var deep = {}1{};", "(".repeat(10_000), ")".repeat(10_000)),
];
let o = run(
"event.value = double(getField('qty').value) + typeof big;",
&Event::field("Calculate", "total", ""),
&doc(),
&fields(),
&docs,
Limits::default(),
);
assert_eq!((o.error.as_deref(), o.value.as_str()), (None, "8undefined"));
let places: Vec<&str> = o.doc_errors.iter().map(|e| e.split(':').next().unwrap_or_default()).collect();
assert_eq!(places, ["document script 1", "document script 2", "document script 4"], "{:?}", o.doc_errors);
assert!(o.doc_errors[1].contains("too long") && o.doc_errors[2].contains("nested too deeply"), "{:?}", o.doc_errors);
// The field script's own limits still refuse it outright.
let o = run(&format!("1{}", "+1".repeat(MAX_SCRIPT_BYTES)), &Event::field("Calculate", "total", ""), &doc(), &fields(), &docs, Limits::default());
assert!(o.error.is_some_and(|e| e.contains("too long")) && o.doc_errors.is_empty());
}
#[test]
fn errors_and_runaway_scripts_are_contained() {
let o = go("event.value = nosuch.thing;", &Event::field("Calculate", "total", "keep"));
@@ -336,9 +398,11 @@ fn deeply_nested_scripts_fail_instead_of_crashing() {
let o = go(s, &Event::doc("Open"));
assert!(o.error.is_some(), "{}…", &s[..20]);
}
// A hostile document-level script is refused too, before the field script runs.
// A hostile document-level script is refused too: it never runs, and is reported, while
// the field script still does (#3940).
let o = run("event.value = 'ran';", &Event::field("Calculate", "a", ""), &doc(), &fields(), &[hostile[0].clone()], Limits::default());
assert!(o.error.is_some());
assert_eq!((o.error, o.value.as_str()), (None, "ran"));
assert!(o.doc_errors.len() == 1 && o.doc_errors[0].contains("nested too deeply"), "{:?}", o.doc_errors);
}
#[test]
@@ -805,6 +869,14 @@ mod formcalc {
o.result.unwrap_or_default()
}
/// A negative value that rounds to zero under the picture prints without a minus sign.
#[test]
fn format_does_not_print_negative_zero() {
assert_eq!(calc(r#"Format("9.9", -0.04)"#), "0.0");
assert_eq!(calc(r#"Format("99", -0.2)"#), "00");
assert_eq!(calc(r#"Format("9.9", -1.5)"#), "-1.5");
}
/// Assigning one long value to many fields at once stops at the run's byte budget and is
/// charged per copy, and a reset list names each field once.
#[test]
@@ -1328,6 +1400,8 @@ mod session {
use crate::xfa::*;
use crate::xfa_session::{Script, XfaSession};
/// A JavaScript or FormCalc script for `activity` on `target`, against the test form with
/// default limits and a 3 s timeout.
fn script(source: &str, formcalc: bool, target: &str, activity: &str) -> Script {
Script {
source: source.into(),
@@ -1339,6 +1413,9 @@ mod session {
}
}
/// JavaScript and FormCalc scripts run in turn in one session, each on the form the caller
/// sends: nothing an earlier script changed or defined leaks into the next, a failing script
/// doesn't end the session, and hundreds of scripts run on its one thread.
#[test]
fn scripts_of_one_event_run_on_one_thread_each_on_the_form_the_caller_sends() {
let mut s = XfaSession::new(XfaDoc { page_count: 3, ..Default::default() });
@@ -1378,6 +1455,8 @@ mod session {
assert!(started.elapsed() < std::time::Duration::from_secs(10), "{:?}", started.elapsed());
}
/// A JavaScript or FormCalc script whose engine takes longer to be ready than the script's
/// time limit still runs and returns its result, and the session stays alive.
#[test]
fn a_scripts_time_starts_when_its_context_is_ready() {
// The engine made slow to be ready (300 ms) under a 50 ms script limit: the script is
@@ -1398,6 +1477,9 @@ mod session {
assert_eq!(s.dead(), None);
}
/// An endless JavaScript loop past its 200 ms limit is abandoned within 2 s and leaves the
/// session dead, so nothing more runs in it; an endless FormCalc loop is abandoned or
/// reported as running too long.
#[test]
fn a_script_past_its_time_is_abandoned_and_the_session_is_dead_after_it() {
let mut s = XfaSession::new(XfaDoc::default());
@@ -1455,6 +1537,249 @@ fn shared_field_snapshots_isolate_writes_errors_and_script_globals() {
assert!(read.changed.is_empty());
}
mod scand {
use super::*;
use crate::xfa::{XfaDoc, XfaEvent, run_xfa};
/// Runs `util.scand(format, text)` for each case and checks the date it gives, written as
/// `yyyy-mm-dd HH:MM:ss`, or `null`.
fn assert_scand(cases: &[(&str, &str, &str)]) {
let list: Vec<String> = cases.iter().map(|(f, t, _)| format!("['{f}', '{t}']")).collect();
let script = format!(
"event.value = [{}].map(function (c) {{ var d = util.scand(c[0], c[1]); \
return d === null ? 'null' : util.printd('yyyy-mm-dd HH:MM:ss', d); }}).join('|');",
list.join(", ")
);
let o = go(&script, &Event::field("Calculate", "total", ""));
assert_eq!(o.error, None);
let got: Vec<&str> = o.value.split('|').collect();
assert_eq!(got.len(), cases.len());
for ((f, t, want), got) in cases.iter().zip(got) {
assert_eq!(got, *want, "util.scand('{f}', '{t}')");
}
}
// The cases below are another viewer's answers, observed black-box with a synthetic file.
/// Any separator may come between fields, whether the format has that one, another or none,
/// but a text with a space or a letter before or after the date reads nothing.
#[test]
fn scand_allows_separators_between_fields_but_nothing_before_or_after_them() {
assert_scand(&[
("yyyymmdd", "20261018", "2026-10-18 00:00:00"),
("yyyymmdd", "2026-10-18", "2026-10-18 00:00:00"),
("yyyymmdd", "2026 10 18", "2026-10-18 00:00:00"),
("mm/dd/yyyy", "10/18/2026", "2026-10-18 00:00:00"),
("mm/dd/yyyy", "10-18-2026", "2026-10-18 00:00:00"),
("yyyymmdd", " 20261018 ", "null"),
("yyyymmdd", "20261018x", "null"),
("yyyymmdd", "x20261018", "null"),
]);
}
/// Digits typed together fill the joined fields with exactly as many digits as each field has
/// letters, so a run of any other length reads nothing.
#[test]
fn scand_splits_digits_typed_together_by_the_formats_letter_counts() {
assert_scand(&[
("yyyymmdd", "261018", "null"),
("yyyymmdd", "2026118", "null"),
("yyyymmdd", "202610181", "null"),
("yymmdd", "20261018", "null"),
("yyyymdd", "2026118", "2026-01-18 00:00:00"),
("yyyymmd", "2026118", "2026-11-08 00:00:00"),
("yyyymd", "2026118", "null"),
("yyyymd", "202618", "2026-01-08 00:00:00"),
("yyyymd", "20261018", "null"),
("yymd", "2618", "2026-01-08 00:00:00"),
("yymd", "261018", "null"),
]);
}
/// A month past 12, a day past the month's end and February 29 outside a leap year are
/// refused, while a month or day of 0 is read as 1.
#[test]
fn scand_refuses_impossible_dates_and_reads_a_zero_month_or_day_as_1() {
assert_scand(&[
("yyyymmdd", "20261318", "null"),
("yyyymmdd", "20260230", "null"),
("yyyymmdd", "20260229", "null"),
("yyyymmdd", "20240229", "2024-02-29 00:00:00"),
("mm/dd/yyyy", "13/45/2026", "null"),
("yyyymmdd", "20260018", "2026-01-18 00:00:00"),
("yyyymmdd", "20261000", "2026-10-01 00:00:00"),
]);
}
/// A field typed by itself may have one or two digits, but a `yyyy` year needs four; `yy` reads
/// as 1950–2049; month names may be full or three letters in any case; weekday names are read.
#[test]
fn scand_reads_lone_fields_two_digit_years_and_month_and_weekday_names() {
assert_scand(&[
("mm/dd/yyyy", "1/5/2026", "2026-01-05 00:00:00"),
("m/d/yyyy", "1/5/2026", "2026-01-05 00:00:00"),
("m/d/yyyy", "01/05/2026", "2026-01-05 00:00:00"),
("m/d/yy", "1/5/26", "2026-01-05 00:00:00"),
("mm/dd/yyyy", "10/18/26", "null"),
("yyyy/mm/dd", "26/10/18", "null"),
("yymmdd", "261018", "2026-10-18 00:00:00"),
("yymmdd", "491018", "2049-10-18 00:00:00"),
("yymmdd", "501018", "1950-10-18 00:00:00"),
("mmm d, yyyy", "Oct 18, 2026", "2026-10-18 00:00:00"),
("mmm d, yyyy", "October 18, 2026", "2026-10-18 00:00:00"),
("mmm d, yyyy", "oct 18, 2026", "2026-10-18 00:00:00"),
("mmmm d, yyyy", "Oct 18, 2026", "2026-10-18 00:00:00"),
("mmmm d, yyyy", "October 18, 2026", "2026-10-18 00:00:00"),
("dd-mmm-yyyy", "18-Oct-2026", "2026-10-18 00:00:00"),
("dddd, mmmm d, yyyy", "Sunday, October 18, 2026", "2026-10-18 00:00:00"),
]);
}
/// A time is read along with a date, but a format with only time fields reads nothing.
#[test]
fn scand_reads_a_time_only_with_a_date() {
assert_scand(&[
("mm/dd/yyyy HH:MM:ss", "10/18/2026 21:07:05", "2026-10-18 21:07:05"),
("HH:MM", "09:07", "null"),
("HH:MM", "9:07", "null"),
("h:MM tt", "9:07 pm", "null"),
("h:MM tt", "9:07 am", "null"),
("h:MM tt", "12:07 am", "null"),
("h:MM tt", "9:07pm", "null"),
]);
}
/// An empty text reads as today at noon, and a text that is not a string (a number, or none
/// at all) reads nothing.
#[test]
fn scand_reads_only_text_and_an_empty_text_is_today_at_noon() {
let o = go(
"var d = util.scand('yyyymmdd', ''), n = new Date(); \
event.value = [d.toDateString() == n.toDateString(), d.getHours(), d.getMinutes(), d.getSeconds(), \
util.scand('yyyymmdd', 20261018), util.scand(), util.scand('yyyymmdd')].join('|');",
&Event::field("Calculate", "total", ""),
);
assert_eq!(o.error, None);
assert_eq!(o.value, "true|12|0|0|||");
}
// Not observed: the choices made where the other viewer wasn't asked.
/// A year left out is this year, `h:MM tt` reads a 12-hour time and refuses hours it cannot
/// have, and a letter the format writes must be typed there.
#[test]
fn scand_takes_this_year_when_none_is_given_and_reads_12_hour_times_and_written_letters() {
assert_scand(&[
("mm/dd/yyyy h:MM tt", "10/18/2026 9:07 pm", "2026-10-18 21:07:00"),
("mm/dd/yyyy h:MM tt", "10/18/2026 12:07 AM", "2026-10-18 00:07:00"),
("mm/dd/yyyy h:MM tt", "10/18/2026 13:07 pm", "null"),
("mm/dd/yyyy HH:MM", "10/18/2026 24:00", "null"),
("yyyy-mm-ddTHH:MM", "2026-10-18T21:07", "2026-10-18 21:07:00"),
("yyyy-mm-ddTHH:MM", "2026-10-18X21:07", "null"),
]);
let o = go(
"var d = util.scand('mm/dd', '10/18'); event.value = [d.getFullYear() == new Date().getFullYear(), d.getMonth(), d.getDate()].join('|');",
&Event::field("Calculate", "total", ""),
);
assert_eq!(o.error, None);
assert_eq!(o.value, "true|9|18");
}
/// A format of 50,000 literal letters and one of 100,000 fields, with texts to match, are read
/// in linear time. The limit is generous so a loaded runner passes (it also covers starting
/// the engine and building the strings); a quadratic scan of inputs this size takes minutes.
#[test]
fn scand_reads_long_formats_and_texts_in_linear_time() {
// Scripts can pass anything; native code isn't bounded by the loop limit.
let started = std::time::Instant::now();
let o = go(
"var x = new Array(50001).join('x'), md = new Array(50001).join('md'), ones = new Array(100000).join('1 ') + '1'; \
event.value = [util.scand(x + 'yyyy', x + '2026') !== null, util.scand('yyyy' + md, '2026 ' + ones) !== null].join('|');",
&Event::field("Calculate", "total", ""),
);
assert_eq!(o.error, None);
assert_eq!(o.value, "true|true");
assert!(started.elapsed() < std::time::Duration::from_secs(10), "{:?}", started.elapsed());
}
/// The check an XFA form runs on leaving a date field tries six formats with `util.scand` and
/// writes the first that reads the text back as `yyyymmdd`, or reports an invalid date.
#[test]
fn xfa_scripts_check_typed_dates_with_util_scand() {
// The check a form runs when a date field is left: the first of six formats that reads
// the typed text, written back as yyyymmdd; or an invalid date. Results as another viewer gives them.
let check = |typed: &str| {
let script = format!(
"var six = ['yyyymmdd', 'yymmdd', 'yyyymdd', 'yyyymmd', 'yyyymd', 'yymd'], out = 'invalid'; \
for (var i = 0; i < six.length; i++) {{ var d = util.scand(six[i], '{typed}'); \
if (d !== null) {{ out = util.printd('yyyymmdd', d); break; }} }} out"
);
let event = XfaEvent { activity: "exit".into(), target: "form1[0].page1[0].total[0]".into(), ..Default::default() };
run_xfa(&script, &event, &XfaDoc::default(), &super::xfa_model::form(), Limits::default())
};
for (typed, want) in [
("20261018", "20261018"),
("261018", "20261018"),
("2026118", "20260118"),
("202618", "20260108"),
("2618", "20260108"),
("2026-10-18", "20261018"),
("20261318", "invalid"),
("20260230", "invalid"),
] {
let o = check(typed);
assert_eq!(o.error, None, "{typed}: {o:?}");
assert_eq!(o.result.as_deref(), Some(want), "{typed}");
}
}
}
mod menu_items {
use super::*;
use crate::xfa::{XfaDoc, XfaEffect, XfaEvent, run_xfa};
/// Every side panel has a fixed id in automation output.
#[test]
fn each_panel_has_a_fixed_id_for_automation() {
let ids = [Panel::Bookmarks, Panel::Pages, Panel::Attachments, Panel::Signatures, Panel::Layers].map(Panel::id);
assert_eq!(ids, ["bookmarks", "pages", "attachments", "signatures", "layers"]);
}
/// Each side panel item, Print and SaveAs make their request, in order; an unknown item
/// makes none and is not an error.
#[test]
fn exec_menu_item_shows_side_panels_prints_and_saves() {
let o = go(
"app.execMenuItem('ShowHideFileAttachment'); app.execMenuItem('ShowHideBookmarks'); app.execMenuItem('ShowHideThumbnails'); \
app.execMenuItem('ShowHideSignatures'); app.execMenuItem('ShowHideOptCont'); app.execMenuItem('Print'); \
app.execMenuItem('SaveAs'); app.execMenuItem('NoSuchItem');",
&Event::field("Mouse Up", "total", ""),
);
assert_eq!(o.error, None);
assert_eq!(
o.requests,
[
Request::ShowPanel(Panel::Attachments),
Request::ShowPanel(Panel::Bookmarks),
Request::ShowPanel(Panel::Pages),
Request::ShowPanel(Panel::Signatures),
Request::ShowPanel(Panel::Layers),
Request::Print,
Request::SaveAs,
]
);
}
/// `app.execMenuItem` works in XFA scripts too: a click shows the attachments panel.
#[test]
fn xfa_scripts_show_the_attachments_panel() {
let event = XfaEvent { activity: "click".into(), target: "form1[0].page1[0].go[0]".into(), ..Default::default() };
let o = run_xfa("app.execMenuItem('ShowHideFileAttachment')", &event, &XfaDoc::default(), &super::xfa_model::form(), Limits::default());
assert_eq!(o.error, None, "{o:?}");
assert!(o.effects.contains(&XfaEffect::ShowPanel(Panel::Attachments)), "{:?}", o.effects);
}
}
/// The check XFA forms run on opening: without both globals, or with a version below 2.8, it
/// alerts that the viewer can't show the form.
const XFA_CHECK: &str = "if (typeof(xfa_installed) == 'undefined' || typeof(xfa_version) == 'undefined' || xfa_version < 2.8) app.alert('old viewer'); \
+26 -6
View File
@@ -15,7 +15,7 @@ use boa_engine::object::builtins::{JsArray, JsProxy};
use boa_engine::property::Attribute;
use boa_engine::{Context, JsObject, JsResult, JsString, JsValue, NativeFunction, Source, js_string};
use crate::{Limits, arg, as_number, error, function, platform, printd, printf, printx, refuse, s, text};
use crate::{Limits, arg, as_number, error, function, platform, printd, printf, printx, refuse, s, scand, text};
/// What kind of template object a node is.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -115,6 +115,8 @@ pub enum XfaEffect {
MessageBox(String),
/// `xfa.host.resetData()`: the named fields, or every field when empty.
ResetData(Vec<String>),
/// `app.execMenuItem("ShowHide…")`: show or hide a side panel.
ShowPanel(crate::Panel),
Print,
SaveAs,
LaunchUrl(String),
@@ -219,7 +221,7 @@ fn payload(e: &XfaEffect) -> usize {
XfaEffect::AddInstance { som } | XfaEffect::RemoveInstance { som } => som.len(),
XfaEffect::MessageBox(s) | XfaEffect::LaunchUrl(s) | XfaEffect::SetFocus(s) => s.len(),
XfaEffect::ResetData(names) => names.iter().fold(0usize, |n, s| n.saturating_add(s.len()).saturating_add(std::mem::size_of::<String>())),
XfaEffect::Print | XfaEffect::SaveAs | XfaEffect::Beep | XfaEffect::Recalculate | XfaEffect::Relayout => 0,
XfaEffect::Print | XfaEffect::SaveAs | XfaEffect::Beep | XfaEffect::Recalculate | XfaEffect::Relayout | XfaEffect::ShowPanel(_) => 0,
}
}
@@ -1131,39 +1133,50 @@ fn resolver(ctx: &mut Context, from: usize, many: bool) -> JsResult<JsValue> {
// ── xfa.host, xfa.layout, xfa.event, app, console ───────────────────────────────────────────
/// Records effect `e` on the host, as [`XHost::push`] does.
fn effect(ctx: &mut Context, e: XfaEffect) -> JsResult<()> {
host(ctx)?.borrow_mut().push(e);
Ok(())
}
/// `xfa.host.messageBox(message)`: records the message, cut to [`MAX_LINE`] characters, and
/// returns 1.
fn message_box(_: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> {
let m = clip(text(&arg(args, 0), ctx)?);
effect(ctx, XfaEffect::MessageBox(m))?;
Ok(JsValue::from(1.0))
}
/// `xfa.host.resetData(names)`: asks to reset the comma-separated fields, or every field when
/// the list is empty.
fn reset_data(_: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> {
let list = text(&arg(args, 0), ctx)?;
effect(ctx, XfaEffect::ResetData(reset_names(&list)))?;
Ok(JsValue::undefined())
}
/// `xfa.host.print(…)`: asks to print; its arguments are ignored.
fn print(_: &JsValue, _: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> {
effect(ctx, XfaEffect::Print)?;
Ok(JsValue::undefined())
}
/// `xfa.host.beep()`: asks to beep.
fn beep(_: &JsValue, _: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> {
effect(ctx, XfaEffect::Beep)?;
Ok(JsValue::undefined())
}
/// `xfa.host.gotoURL(url)`: asks to open the URL.
fn goto_url(_: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> {
let u = text(&arg(args, 0), ctx)?;
effect(ctx, XfaEffect::LaunchUrl(u))?;
Ok(JsValue::undefined())
}
/// `xfa.host.setFocus(target)`: asks to focus the node, given as a node object or as a SOM
/// expression resolved from the current node; an expression that names no node is passed on
/// as written.
fn set_focus(_: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> {
let target = arg(args, 0);
let som = match target.as_object() {
@@ -1182,11 +1195,14 @@ fn set_focus(_: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsVal
Ok(JsValue::undefined())
}
/// `app.execMenuItem(name)`: the effect for the request the shared menu table gives the name
/// (Save opens Save As too); an unknown name does nothing.
fn exec_menu_item(_: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> {
let item = text(&arg(args, 0), ctx)?;
match item.as_str() {
"SaveAs" | "Save" => effect(ctx, XfaEffect::SaveAs)?,
"Print" => effect(ctx, XfaEffect::Print)?,
match crate::menu_item(&item) {
Some(crate::Request::SaveAs) => effect(ctx, XfaEffect::SaveAs)?,
Some(crate::Request::Print) => effect(ctx, XfaEffect::Print)?,
Some(crate::Request::ShowPanel(p)) => effect(ctx, XfaEffect::ShowPanel(p))?,
_ => {}
}
Ok(JsValue::undefined())
@@ -1233,6 +1249,9 @@ fn xfa_resolve(ctx: &mut Context, many: bool) -> JsResult<JsValue> {
resolver(ctx, current, many)
}
/// Defines the globals for one script on node `current`: `xfa` (`form`, `host`, `layout`, `event`,
/// `resolveNode` and more), `event` as the same object as `xfa.event`, `app`, `console`, `util`,
/// and the nodes in scope by name, with `_name` for each repeatable one's instance manager.
fn install(ctx: &mut Context, event: &XfaEvent, doc: &XfaDoc, current: usize) -> JsResult<()> {
let rw = Attribute::CONFIGURABLE;
let form = node_object(ctx, 0)?;
@@ -1343,6 +1362,7 @@ fn install(ctx: &mut Context, event: &XfaEvent, doc: &XfaDoc, current: usize) ->
.function(NativeFunction::from_fn_ptr(printf), js_string!("printf"), 1)
.function(NativeFunction::from_fn_ptr(printd), js_string!("printd"), 2)
.function(NativeFunction::from_fn_ptr(printx), js_string!("printx"), 2)
.function(NativeFunction::from_fn_ptr(scand), js_string!("scand"), 2)
.build();
ctx.register_global_property(js_string!("util"), util, rw)?;
// Unqualified names: the current node's children, its siblings, then each ancestor's
@@ -1416,7 +1436,7 @@ fn install(ctx: &mut Context, event: &XfaEvent, doc: &XfaDoc, current: usize) ->
"DataView",
"Intl",
];
let mut defined: Vec<String> = RESERVED.iter().map(|s| s.to_string()).collect();
let mut defined: Vec<String> = RESERVED.iter().map(ToString::to_string).collect();
for scope in scopes {
let kids: Vec<(usize, String, bool)> = {
let h = host(ctx)?.borrow();
+3
View File
@@ -12,12 +12,15 @@ workspace = true
[dependencies]
pdfcraft-cos = { workspace = true }
pdfcraft-filters = { workspace = true }
pdfcraft-content = { workspace = true }
pdfcraft-model = { workspace = true }
pdfcraft-annot = { workspace = true }
thiserror.workspace = true
# JPEG decoding (zune-jpeg) and encoding, and bicubic resampling; already in the tree.
image = { version = "0.25", default-features = false, features = ["jpeg"] }
# The same JPEG decoder, used directly to read samples untransformed (/ColorTransform 0).
zune-jpeg = "0.5"
[dev-dependencies]
pdfcraft-render = { workspace = true }
+23 -5
View File
@@ -21,19 +21,37 @@ let report = optimize_with_progress(&mut doc, &settings, &mut |stage| keep_going
side-by-side tiles, rotated strips, masks. Content arrays use the shared space boundary
policy, so trailing comments, split operands and graphics state keep their meaning after merging.
- **Images:** the effective resolution of each image is measured where pages draw it (the CTM
through form XObjects, up to 12 deep; the smallest over all uses). If a use can't be
through form XObjects, up to 12 deep; the smallest over all uses).
Page-local `/UserUnit` scaling is included, so large-format pages are measured in physical inches.
If a use can't be
measured (forms nested deeper, or drawn too many times), no image is resampled. Colour and grayscale images above a
threshold are resampled with a bicubic (Catmull-Rom) filter to a target resolution and
stored as JPEG (Acrobat's quality steps) or ZIP; soft masks are resampled with their image.
An image is replaced only if the result is smaller. Left alone: CMYK and other colour spaces,
image masks, decode arrays, more than 8 bits, JPEG 2000, JBIG2 and CCITT.
image masks, decode arrays, more than 8 bits, JPEG 2000, JBIG2 and CCITT. A JPEG is read with
its colour transform (an Adobe marker's, else `/ColorTransform`, ISO 32000-2 §7.4.8), so one
stored untransformed keeps its colours; one whose marker and `/ColorTransform` disagree is left
alone, since readers differ on which wins.
- **Discard objects:** thumbnails, alternate images, document tags, print settings.
- **Clean up:** Flate for streams with no filter; for streams with an outer ASCII85 or ASCIIHex
layer, that layer is removed when the result is smaller (the inner filters keep their encoded
bytes). Streams with `/DecodeParms`, images and object streams are left alone.
bytes; streams with `/DecodeParms`, images and object streams keep their ASCII layer. LZW-compressed
streams, content and images alike, are decoded and stored with Flate instead (Acrobat's "In
streams that use LZW encoding, use Flate instead"): a predictor carries over to Flate without
`EarlyChange`, filters applied before the LZW one go with it and those after it keep their
bytes. A stream whose LZW data doesn't decode cleanly is left as it is. Not yet: inline images.
The engine runs Remove Hidden Information (`pdfcraft-redact`) for the user-data categories,
then this, then merges identical objects and writes a full, compressed save
(`pdfcraft_engine::optimizer::OptimizeJob`, which the UI runs on a worker thread with a
progress bar). JPEG decoding and
encoding and resampling come from the `image` crate.
progress bar). JPEG decoding comes from `zune-jpeg` (the decoder behind `image` and the
renderer), JPEG encoding and resampling from the `image` crate.
## Target PDF version: partial compatibility
The target selects the header version, clears the catalog `/Version`, controls object
streams (disabled for PDF 1.4), and checks encryption requirements. It does **not**
detect or convert content newer than the target: optional content, JPEG 2000 images,
16-bit images, OpenType fonts and PDF 2.0 features can remain. A PDF 1.4 header
therefore does not guarantee compatibility with PDF 1.4 readers or validators.
`optimize.compatibility-level` remains partial until content compatibility is checked.
+1 -1
View File
@@ -176,7 +176,7 @@ fn merge(doc: &Document, run: &[Fragment], n: usize) -> Option<(Vec<u8>, u32, u3
}
let obj = doc.get(f.image);
let Object::Stream(s) = &*obj else { return None };
let px = pixels(s, n)?;
let px = pixels(doc, s, n)?;
let px = if (f.width, f.height) == (width, r1 - r0) { px } else { resample(&px, n, f.width, f.height, width, r1 - r0)? };
out.get_mut(r0 as usize * row..r1 as usize * row)?.copy_from_slice(px.get(..(r1 - r0) as usize * row)?);
}
+157 -26
View File
@@ -158,15 +158,18 @@ pub fn effective_resolutions(doc: &Document, pages: &[ObjRef]) -> HashMap<ObjRef
out: HashMap::new(),
};
for p in pages {
let Some(d) = doc.get(*p).as_dict().cloned() else { continue };
let Some(contents) = d.get(b"Contents") else { continue };
let Some(dict) = doc.get(*p).as_dict().cloned() else { continue };
let page = pdfcraft_model::Page { obj: *p, dict };
let Some(contents) = page.dict.get(b"Contents") else { continue };
let res = page_resources(doc, *p).unwrap_or_default();
walk.budget = DecodeBudget::page();
let Some(data) = content_bytes(doc, contents, &mut walk.budget) else {
walk.complete = false;
continue;
};
walk.content(&data, &res, Matrix([1.0, 0.0, 0.0, 1.0, 0.0, 0.0]));
// Content coordinates are in page units; image resolution is in physical inches.
let unit = page.user_unit(doc);
walk.content(&data, &res, Matrix([unit, 0.0, 0.0, unit, 0.0, 0.0]));
}
if !walk.complete {
walk.out.values_mut().for_each(|v| *v = f64::INFINITY);
@@ -255,25 +258,21 @@ fn count_decoded(_n: u64) {
DECODED_PIXELS.with(|c| c.set(c.get().saturating_add(_n)));
}
/// 8-bit samples of an image (`n` components), decoded.
pub(crate) fn pixels(s: &Stream, n: usize) -> Option<Vec<u8>> {
/// 8-bit samples of an image (`n` components), decoded. `None` for a JPEG whose colour transform
/// readers may disagree about ([`ycc_encoded`]).
pub(crate) fn pixels(doc: &Document, s: &Stream, n: usize) -> Option<Vec<u8>> {
let (w, h) = (u32::try_from(s.dict.int(b"Width")?).ok()?, u32::try_from(s.dict.int(b"Height")?).ok()?);
if w == 0 || h == 0 || u64::from(w) * u64::from(h) > MAX_PIXELS {
return None;
}
let bytes = usize::try_from(w).ok()?.checked_mul(usize::try_from(h).ok()?)?.checked_mul(n)?;
if is_dct(s)? {
use image::ImageDecoder as _;
// The JPEG's own size is what gets decoded: one other than the dictionary's is refused from
// its header, before any pixels are.
let decoder = image::codecs::jpeg::JpegDecoder::new(std::io::Cursor::new(&s.raw[..])).ok()?;
if decoder.dimensions() != (w, h) {
return None;
}
let img = image::DynamicImage::from_decoder(decoder).ok()?;
count_decoded(u64::from(img.width()) * u64::from(img.height()));
// Adobe CMYK/YCCK JPEGs aren't handled (the colour space check excludes them).
let v = if n == 1 { img.into_luma8().into_raw() } else { img.into_rgb8().into_raw() };
// The colour transform matters to three components only (§7.4.8). CMYK and YCCK JPEGs
// never get here: the colour space check excludes them. The JPEG's own size must be the
// dictionary's: `jpeg_samples` refuses another from its header, before any pixels.
let ycc = n == 3 && ycc_encoded(doc, s)?;
let v = jpeg_samples(&s.raw, usize::try_from(w).ok()?, usize::try_from(h).ok()?, n, ycc)?;
count_decoded(u64::from(w) * u64::from(h));
(v.len() == bytes).then_some(v)
} else {
let v = s.decoded().ok()?;
@@ -281,6 +280,130 @@ pub(crate) fn pixels(s: &Stream, n: usize) -> Option<Vec<u8>> {
}
}
/// Whether the samples of a three-component JPEG are YCbCr, to be converted to RGB (ISO 32000-2
/// §7.4.8). An Adobe APP14 marker's transform flag says so, overriding the filter's
/// /ColorTransform; without a marker /ColorTransform does, 1 (YCbCr) by default.
///
/// `None`, so the image is left as it is, when readers may disagree: the marker and
/// /ColorTransform contradict each other (PdfCraft's renderer lets /ColorTransform 0 win where
/// the standard lets the marker win), either holds a value other than 0 or 1, or the parameters
/// or the JPEG's segments can't be read.
fn ycc_encoded(doc: &Document, s: &Stream) -> Option<bool> {
let entry = color_transform(doc, s)?;
match adobe_transform(&s.raw)? {
Some(t @ (0 | 1)) => entry.is_none_or(|c| c == i64::from(t)).then_some(t == 1),
Some(_) => None,
None => match entry {
None | Some(1) => Some(true),
Some(0) => Some(false),
Some(_) => None,
},
}
}
/// The /ColorTransform of a JPEG stream's filter parameters: `Some(None)` without one. `None`
/// if it isn't an integer, or the parameters aren't a dictionary paired with the filter as
/// §7.4 pairs them (a dictionary for a filter name, a one-element array for a one-filter array).
fn color_transform(doc: &Document, s: &Stream) -> Option<Option<i64>> {
let Some(parms) = s.dict.get(b"DecodeParms") else { return Some(None) };
let parms = doc.resolve(parms);
let parms = match (s.dict.get(b"Filter"), &*parms) {
(Some(Object::Array(_)), Object::Array(a)) if a.len() == 1 => doc.resolve(a.first()?),
(Some(Object::Name(_)), _) | (_, Object::Null) => parms.clone(),
_ => return None,
};
match &*parms {
Object::Null => Some(None),
Object::Dict(d) => match d.get(b"ColorTransform").map(|c| doc.resolve(c)).as_deref() {
None => Some(None),
Some(Object::Int(c)) => Some(Some(*c)),
Some(_) => None,
},
_ => None,
}
}
/// Markers and fill bytes [`adobe_transform`] reads before the first scan, at most. Encoders
/// write a few dozen segments.
const MAX_HEADER_STEPS: usize = 4096;
/// The transform flag of a JPEG's Adobe APP14 segment (0: samples stored as they are,
/// 1: YCbCr, 2: YCCK), the last one if there are several, as decoders read them; `Some(None)`
/// without one. `None` if the segments before the first scan can't be read, which includes a
/// stray byte between segments and a header of more than [`MAX_HEADER_STEPS`] steps.
///
/// Each step reads one marker or fill byte and jumps over its segment, so the work is bounded
/// by the step count, not by the size of the stream. That matters: Optimize asks again for every
/// group of fragments it tries, and the same image can be drawn many times.
fn adobe_transform(data: &[u8]) -> Option<Option<u8>> {
if data.get(..2)? != [0xFF, 0xD8] {
return None;
}
let mut flag = None;
let mut i = 2usize;
// Reading past the end returns.
for _ in 0..MAX_HEADER_STEPS {
// Decoders skip stray bytes between segments, but a stream can hold megabytes of them
// and each would be a step: the header counts as unreadable and the image is left as
// it is.
if *data.get(i)? != 0xFF {
return None;
}
let marker = *data.get(i.checked_add(1)?)?;
match marker {
// A fill byte before the marker.
0xFF => i = i.checked_add(1)?,
// The first scan (or the end): no header segments after it.
0xDA | 0xD9 => return Some(flag),
// Markers without a segment: TEM, RSTn, SOI.
0x01 | 0xD0..=0xD8 => i = i.checked_add(2)?,
_ => {
let len = usize::from(u16::from_be_bytes([*data.get(i.checked_add(2)?)?, *data.get(i.checked_add(3)?)?]));
// The length counts its own two bytes: anything shorter is malformed.
let end = i.checked_add(2)?.checked_add(len)?;
let segment = data.get(i.checked_add(4)?..end)?;
if marker == 0xEE
&& let Some(rest) = segment.strip_prefix(b"Adobe")
{
// Version, flags0 and flags1 (two bytes each), then the transform flag.
flag = Some(*rest.get(6)?);
}
i = end;
}
}
}
None
}
/// 8-bit samples of a JPEG `w` × `h` with `n` components (grey or RGB): YCbCr converted to RGB
/// if `ycc`, otherwise the samples as stored. `None` if the JPEG doesn't match (size or number
/// of components), is too large, or its decoder reads the samples otherwise (for example
/// components named R, G and B, which decoders take as stored, while `ycc` says YCbCr).
fn jpeg_samples(data: &[u8], w: usize, h: usize, n: usize, ycc: bool) -> Option<Vec<u8>> {
use zune_jpeg::zune_core::{bytestream::ZCursor, colorspace::ColorSpace, options::DecoderOptions};
if (w.checked_mul(h)? as u64) > MAX_PIXELS {
return None;
}
let options = DecoderOptions::default().set_strict_mode(false).set_max_width(usize::from(u16::MAX)).set_max_height(usize::from(u16::MAX));
let mut dec = zune_jpeg::JpegDecoder::new_with_options(ZCursor::new(data), options);
dec.decode_headers().ok()?;
if dec.dimensions()? != (w, h) || usize::from(dec.info()?.components) != n {
return None;
}
let out = match (n, ycc, dec.input_colorspace()?) {
(1, _, ColorSpace::Luma) => ColorSpace::Luma,
(3, true, ColorSpace::YCbCr) => ColorSpace::RGB,
// As stored: no conversion either way. The decoder reports an Adobe marker's 0 as CMYK
// until it decodes, and then reads three such components as RGB.
(3, false, ColorSpace::YCbCr) => ColorSpace::YCbCr,
(3, false, ColorSpace::RGB | ColorSpace::CMYK) => ColorSpace::RGB,
_ => return None,
};
dec.set_options(options.jpeg_set_out_colorspace(out));
let px = dec.decode().ok()?;
(px.len() == w.checked_mul(h)?.checked_mul(n)?).then_some(px)
}
pub(crate) fn resample(px: &[u8], n: usize, w: u32, h: u32, nw: u32, nh: u32) -> Option<Vec<u8>> {
use image::imageops::{FilterType, resize};
Some(match n {
@@ -297,11 +420,17 @@ fn jpeg(px: &[u8], n: usize, w: u32, h: u32, quality: u8) -> Option<Vec<u8>> {
Some(out)
}
/// Whether [`pixels`] reads `s` as it is drawn: a codec it decodes and no decode array that
/// changes anything. `None` when the colour space isn't grey or RGB.
/// Whether [`pixels`] reads `s` as it is drawn: a codec it decodes, no decode array that
/// changes anything, and for an RGB JPEG a colour transform readers agree on. `None` when the
/// colour space isn't grey or RGB.
pub(crate) fn decodable(doc: &Document, s: &Stream) -> Option<bool> {
let n = components(doc, s.dict.get(b"ColorSpace")?)?;
Some(is_dct(s).is_some() && s.dict.get(b"Decode").is_none_or(|d| is_identity_decode(doc, d, n)))
let dct = is_dct(s);
Some(
dct.is_some()
&& s.dict.get(b"Decode").is_none_or(|d| is_identity_decode(doc, d, n))
&& (n != 3 || dct == Some(false) || ycc_encoded(doc, s).is_some()),
)
}
/// Whether `decode` is the default decode array for `n` components ([0 1] each), which changes
@@ -313,7 +442,9 @@ fn is_identity_decode(doc: &Document, decode: &Object, n: usize) -> bool {
}
/// A new image stream from 8-bit samples: the original dictionary with the new size and filter.
/// A decode array is dropped: only images without one, or with the default one, get here.
/// A decode array is dropped: only images without one, or with the default one, get here. So are
/// the filter parameters: the samples are decoded, and a JPEG written here is plain YCbCr with no
/// Adobe marker, which is what a missing /ColorTransform means.
fn image_stream(old: &Dict, px: &[u8], n: usize, w: u32, h: u32, compression: Compression, was_dct: bool) -> Option<Stream> {
let mut d = old.clone();
for k in [&b"Filter"[..], b"DecodeParms", b"Decode", b"Length", b"DL"] {
@@ -374,7 +505,7 @@ fn process(doc: &Document, s: &Stream, ppi: f64, settings: &ImageSettings, n: us
} else {
(w, h)
};
let px = pixels(s, n)?;
let px = pixels(doc, s, n)?;
let px = if (nw, nh) != (w, h) { resample(&px, n, w, h, nw, nh)? } else { px };
let new = image_stream(d, &px, n, nw, nh, settings.compression, was_dct)?;
// A soft mask must keep the image's dimensions: resample it with the image (lossless).
@@ -387,7 +518,7 @@ fn process(doc: &Document, s: &Stream, ppi: f64, settings: &ImageSettings, n: us
return None;
}
let (mw, mh) = (u32::try_from(m.dict.int(b"Width")?).ok()?, u32::try_from(m.dict.int(b"Height")?).ok()?);
let mpx = pixels(m, 1)?;
let mpx = pixels(doc, m, 1)?;
let mpx = resample(&mpx, 1, mw, mh, nw, nh)?;
smask = Some((mr, image_stream(&m.dict, &mpx, 1, nw, nh, Compression::Flate, false)?));
}
@@ -460,13 +591,13 @@ mod dimension_tests {
dict.set(b"Width".to_vec(), Object::Int(width));
dict.set(b"Height".to_vec(), Object::Int(height));
let stream = Stream::from_raw(dict, vec![0; 4]);
assert!(pixels(&stream, channels).is_none(), "{width} x {height} x {channels}");
assert!(pixels(&Document::new_empty(), &stream, channels).is_none(), "{width} x {height} x {channels}");
}
let mut dict = Dict::new();
dict.set(b"Width".to_vec(), Object::Int(2));
dict.set(b"Height".to_vec(), Object::Int(2));
let stream = Stream::from_raw(dict, vec![1, 2, 3, 4, 5]);
assert_eq!(pixels(&stream, 1), Some(vec![1, 2, 3, 4]));
assert_eq!(pixels(&Document::new_empty(), &stream, 1), Some(vec![1, 2, 3, 4]));
}
/// A JPEG larger than its dictionary says is refused from its header, before its pixels are decoded.
@@ -481,9 +612,9 @@ mod dimension_tests {
Stream::from_raw(dict, data.clone())
};
DECODED_PIXELS.with(|c| c.set(0));
assert!(pixels(&stream(10, 10), 1).is_none());
assert!(pixels(&Document::new_empty(), &stream(10, 10), 1).is_none());
assert_eq!(DECODED_PIXELS.with(|c| c.get()), 0, "pixels decoded");
assert_eq!(pixels(&stream(1000, 1000), 1).map(|p| p.len()), Some(1000 * 1000));
assert_eq!(pixels(&Document::new_empty(), &stream(1000, 1000), 1).map(|p| p.len()), Some(1000 * 1000));
}
}
Loaded 100 of 342 files, more files were not shown because too many files have changed in this diff. Show more