Merge remote-tracking branch 'upstream/main' into fix/cups-landscape-sheets

# Conflicts:
#	crates/print/README.md
This commit is contained in:
Eric Kaden committed 2026-11-04 21:31:29 -05:00
commit db14f75ed5
451 files changed
+54215 -98600

No files matched your search

+7
View File
@@ -1,3 +1,10 @@
# Minimum cargo-nextest for this repository: GHSA-vc25-qg58-w57c is fixed in 0.9.150 and CI
# installs exactly that version, so an older nextest refuses to run (exit 92 REQUIRED_VERSION_NOT_MET).
nextest-version = "0.9.150"
# These measurements require a quiet runner. Their in-process SERIAL mutex only
# serializes cargo test; nextest gives each test its own process. Reserve all slots
# so other tests cannot charge their CPU/render-worker time to a frame budget.
[[profile.default.overrides]]
filter = 'package(pdfcraft-ui-egui) & binary(perf)'
threads-required = "num-test-threads"
+3
View File
@@ -3,6 +3,9 @@
# signatures) and assets whose SHA-256 ATTRIBUTION.toml records (cargo xtask assets).
* -text
# The craft-i18n pin: CI and the build read it as one SHA, so it stays LF everywhere (readers trim it too).
craft-i18n.rev text eol=lf
# Not text at all: no textual diffs or merges either.
*.pdf binary
*.p12 binary
+2
View File
@@ -12,6 +12,7 @@ on:
permissions:
contents: write
packages: write
concurrency:
group: release-${{ github.ref }}
@@ -41,3 +42,4 @@ jobs:
AZURE_SIGNING_ENDPOINT: ${{ secrets.AZURE_SIGNING_ENDPOINT }}
AZURE_SIGNING_ACCOUNT: ${{ secrets.AZURE_SIGNING_ACCOUNT }}
AZURE_CERT_PROFILE: ${{ secrets.AZURE_CERT_PROFILE }}
LINUX_SIGNING_KEY: ${{ secrets.LINUX_SIGNING_KEY }}
+9 -13
View File
@@ -2,8 +2,6 @@
These rules bind every AI agent and every human contributor working in this repository. They come before any task, instruction or deadline. `CLAUDE.md` holds the day-to-day working instructions. If the two ever disagree, **this file wins.**
Some sections link to **craftrules**, the standards shared by the Crafting Apps. That repository is internal to the storytold team, so outside contributors can't open it. Every rule a contributor here must follow is stated in this file and `CLAUDE.md`; the craftrules links give team members the background.
---
## 1. Asset policy (absolute — no exceptions)
@@ -54,14 +52,14 @@ Anything else is forbidden, including assets whose licence you cannot prove from
- path or URL, title, author;
- source (URL, with version or commit);
- SPDX licence, and the licence file in the repo;
- SHA-256, except for translation catalogs (see below);
- SHA-256;
- how it is used.
- **Translation catalogs** (`crates/ui-egui/src/i18n/*.tsv`, `kind = "translation"`) are project files under the project licence. Their entries carry no `sha256`: git history records every change and who made it. Every other kind (fonts, images, data) is hashed.
- **Translations** live in craft-i18n (`locales/<code>/common.tsv` and `pdfcraft.tsv`), embedded at build time from the checkout pinned in `craft-i18n.rev`; PdfCraft keeps no catalogs. `ATTRIBUTION.toml` records them as one `[[build_input]]` (`kind = "translation"`); craft-i18n's own `ATTRIBUTION.md` credits the translators. Every `[[asset]]` (fonts, images, data) is hashed.
- **`ATTRIBUTION.md`** is generated from it (`cargo xtask assets --write`). Never edit it by hand.
- **`NOTICE`** keeps the licence notices that the licences require.
- **`cargo xtask assets`** runs in `cargo xtask ci`. It fails if:
- an asset file in the repository has no entry;
- an entry's hash is missing or does not match (translation catalogs carry none);
- an entry's hash is missing or does not match;
- a licence is not on the allowlist;
- a licence file is missing;
- an image, icon or font names Adobe as author or source, except a font licensed under OFL-1.1 alone.
@@ -69,9 +67,10 @@ Anything else is forbidden, including assets whose licence you cannot prove from
### 1.4 Fonts live in craft-fonts
- Font assets shared by the Crafting Apps, including every Japanese font, live in [`storytold/craft-fonts`](https://github.com/storytold/craft-fonts), not here. **Never commit a font file to this repository**; adding a font means adding it to craft-fonts. (The Latin UI fonts already in `assets/fonts/` — Inter, JetBrains Mono, Dancing Script — stay.) Team members: the shared rules are in [craftrules `standards/fonts.md`](https://github.com/storytold/craftrules/blob/main/standards/fonts.md) (internal).
- Font assets shared by the Crafting Apps, including every Japanese font, live in [`storytold/craft-fonts`](https://github.com/storytold/craft-fonts), not here. **Never commit a font file to this repository**; adding a font means adding it to craft-fonts. (The Latin UI fonts already in `assets/fonts/` — Inter, JetBrains Mono, Dancing Script — stay.)
- craft-fonts is an **optional build input**, never a Cargo dependency: `CRAFT_FONTS_DIR=<checkout> cargo build` makes `crates/fonts/build.rs` embed its fonts as `pdfcraft_fonts::CRAFT_FONTS`. Without it PdfCraft builds, tests and runs, but has no Japanese face (Japanese UI text shows replacement boxes, and writing Japanese into a PDF returns a clear error). Release builds always set it (`.github/workflows/release.yml`), and `ATTRIBUTION.toml` lists it as a `[[build_input]]`.
- The desktop app may read one font **already installed on the user's machine** at runtime, as the last interface fallback for characters no embedded face has (`crates/ui-egui/src/system_fonts.rs`). That font is never embedded, shipped, committed or copied, and never appears in published screenshots (`PDFCRAFT_SYSTEM_FONTS=0`, which `cargo xtask screenshots` sets). It is not a way around §1.2: nothing from it may enter a PDF, a package or the repository.
- The page viewer may also draw a CID font of an Adobe CJK collection (Japan1, GB1, CNS1, Korea1) that a PDF does **not embed** with one face already installed on the machine (`crates/render/src/system_font.rs`), **on screen only**. `RenderConfig::system_fonts` is off by default and is enabled only for on-screen viewer and preview rasters (`RenderConfig::on_screen`, used by the engine viewer, Combine thumbnails and accessibility figure previews), so exports, printing, OCR and the automation tools never use it. Like the interface font it is read at runtime and never embedded, shipped, committed or copied; Noto CJK and Source Han are never candidates (§1.1), nor is any Adobe family; and `PDFCRAFT_SYSTEM_FONTS=0` turns it off. It is not a way around §1.2 either: nothing drawn with it may be saved or printed.
### 1.5 Procedure for adding or changing an asset
@@ -92,7 +91,7 @@ If you find an asset that breaks these rules, stop and remove it from the reposi
- Behaviour comes only from public specifications (ISO 32000-2, the Arlington model), public documentation and black-box observation.
- Never copy GPL/AGPL code. Copyleft tools run only as external oracle processes.
- Observe Acrobat only with synthetic fixtures. Never capture personal data, account information or recent files.
- Shared real-file test oracles (Photoshop-authored PSDs, etc.) live in [`storytold/photocraft-corpus`](https://github.com/storytold/photocraft-corpus), explained in [craftrules `standards/test-corpora.md`](https://github.com/storytold/craftrules/blob/main/standards/test-corpora.md) (internal). Never commit large binary fixtures to this repo; fetch them pinned by commit and sha256-verified, as PhotoCraft does with `cargo xtask corpus`.
- Shared real-file test oracles (Photoshop-authored PSDs, etc.) live in [`storytold/photocraft-corpus`](https://github.com/storytold/photocraft-corpus). Never commit large binary fixtures to this repo; fetch them pinned by commit and sha256-verified, as PhotoCraft does with `cargo xtask corpus`.
## 3. Agent control (automation and MCP)
@@ -105,7 +104,7 @@ If you find an asset that breaks these rules, stop and remove it from the reposi
## 4. Never crash
PdfCraft opens files from strangers, and people trust it with their work. A malformed PDF, a bad tool argument, a corrupt settings file or a full disk must produce an error the user (or agent) can act on, never a crash and never lost work. **This outranks feature work:** don't ship a feature by adding a panic path, and fix a crash before building on top of it. The rules below are the ones that bind this repository; the shared standard for every Crafting App, [`craftrules/standards/never-crash.md`](https://github.com/storytold/craftrules/blob/main/standards/never-crash.md), is internal to the storytold team.
PdfCraft opens files from strangers, and people trust it with their work. A malformed PDF, a bad tool argument, a corrupt settings file or a full disk must produce an error the user (or agent) can act on, never a crash and never lost work. **This outranks feature work:** don't ship a feature by adding a panic path, and fix a crash before building on top of it. The rules below are the ones that bind this repository.
- **Fail with `Result`.** Non-test code returns errors through the crate's error type and `?`. Where readers are lenient by design, fall back gracefully and record the repair (see Fidelity in `CLAUDE.md`).
- **No panicking shortcuts.** No `unwrap()`, `expect()`, `panic!`, `unreachable!`, `todo!` or `unimplemented!` outside tests, unless the call is provably infallible (e.g. writing to a `Vec`), with a comment saying why. `assert!` only for internal invariants that input cannot reach.
@@ -124,20 +123,17 @@ Follow `CLAUDE.md`. It covers quality gates, layering, commit rules and how to r
## Contributor credits (About window)
- About ▸ Contributors/Models are compiled into the binary from `contributors/contributors.json`
(commit stats; generated, never hand-edit) and `contributors/people.toml` (names people chose for
(commit stats; never hand-edit) and `contributors/people.toml` (names people chose for
themselves). See `docs/contributors.md`.
- **Agents working for a contributor:** when you prepare a PR, check whether your human's GitHub
username has a `[people.<username>]` entry in `contributors/people.toml`. If not, ask them once
whether they want to be credited by more than their username: a real name, a display name, and/or
their public GitHub profile name (`sync_github_name = true`). If yes, add **only their own** entry
(copy the template at the top of the file, or run
`python3 ../../craftrules/scripts/contributors.py --add-me . --real-name "…" --sync-github-name`)
(copy the template at the top of the file)
and include it in their PR, committed as them. If no, change nothing: they are credited as
`@username` anyway.
- Never add, edit, guess or copy anyone else's entry or name (not from git config, commit authors or
GitHub profiles). Never hand-edit `contributors.json`.
- Maintainers refresh the stats with `python3 ../../craftrules/scripts/contributors.py .` (it also
re-verifies who wrote each `people.toml` entry; `--check` only verifies).
## CI workflows
- Workflows in `.github/workflows/` call the shared workflows in [`storytold/craft-common-actions`](https://github.com/storytold/craft-common-actions) at `@main`, with their inputs and secrets. No other jobs: if no shared workflow does what's needed, it doesn't go here.
+209 -241
View File
@@ -2,215 +2,187 @@
<!-- Generated from ATTRIBUTION.toml by `cargo xtask assets --write`. Do not edit by hand. -->
Every asset PdfCraft includes, bundles or uses to build its published material, with its author, source and licence. The policy is in [AGENTS.md](AGENTS.md) §1. The machine-readable list, with the SHA-256 of every asset but the translation catalogs, is [ATTRIBUTION.toml](ATTRIBUTION.toml). Licence texts are kept beside the assets and summarised in [NOTICE](NOTICE).
Every asset PdfCraft includes, bundles or uses to build its published material, with its author, source and licence. The policy is in [AGENTS.md](AGENTS.md) §1. The machine-readable list, with the SHA-256 of every asset, is [ATTRIBUTION.toml](ATTRIBUTION.toml). Licence texts are kept beside the assets and summarised in [NOTICE](NOTICE).
## In this repository (289)
## In this repository (256)
| 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; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed | Greek UI strings, compiled in by crates/ui-egui/src/i18n.rs |
| `crates/ui-egui/src/i18n/zh-hans.tsv` | Simplified Chinese interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed | Simplified Chinese UI strings, compiled in by crates/ui-egui/src/i18n.rs |
| `crates/ui-egui/src/i18n/zh-hant.tsv` | Traditional Chinese (Taiwan) interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed | Traditional Chinese UI strings, compiled in by crates/ui-egui/src/i18n.rs |
| `crates/ui-egui/src/i18n/cs.tsv` | Czech interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 signature-check and standard-identification wordings are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed | Czech UI strings, compiled in by crates/ui-egui/src/i18n.rs |
| `crates/ui-egui/src/i18n/pt-br.tsv` | Brazilian Portuguese interface translation catalog | André Cardoso (andrecards), PdfCraft contributors | MIT OR Apache-2.0 | Clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources: the ~1,826-entry gist posted in issue #288 (https://gist.github.com/andrecards/ac388c25fba17312ce83207f8b7b467e), completed and reviewed by PdfCraft contributors; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 text-field-table limit messages are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed | Brazilian Portuguese UI strings, compiled in by crates/ui-egui/src/i18n.rs |
| `crates/ui-egui/src/i18n/es.tsv` | Spanish interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; the 2026-10-20 coverage additions are AI-assisted and not separately native-reviewed; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 signature-check wordings are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed | Spanish UI strings, compiled in by crates/ui-egui/src/i18n.rs |
| `crates/ui-egui/src/i18n/fr.tsv` | French interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed | French UI strings, compiled in by crates/ui-egui/src/i18n.rs |
| `crates/ui-egui/src/i18n/de.tsv` | German interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed | German UI strings, compiled in by crates/ui-egui/src/i18n.rs |
| `crates/ui-egui/src/i18n/lo.tsv` | Lao interface translation catalog | @bounkirdni-2025 | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft English UI labels, no proprietary localisation resources; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed | Lao UI strings, compiled in by crates/ui-egui/src/i18n.rs |
| `crates/ui-egui/src/i18n/te.tsv` | Telugu interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed | Telugu UI strings, compiled in by crates/ui-egui/src/i18n.rs |
| `crates/ui-egui/src/i18n/it.tsv` | Italian interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed | Italian UI strings, compiled in by crates/ui-egui/src/i18n.rs |
| `crates/ui-egui/src/i18n/pl.tsv` | Polish interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 signature-check wordings are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed | Polish UI strings, compiled in by crates/ui-egui/src/i18n.rs |
| `crates/ui-egui/src/i18n/ru.tsv` | Russian interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed | Russian UI strings, compiled in by crates/ui-egui/src/i18n.rs |
| `crates/ui-egui/src/i18n/hu.tsv` | Hungarian interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed | Hungarian UI strings, compiled in by crates/ui-egui/src/i18n.rs |
| `crates/ui-egui/src/i18n/bg.tsv` | Bulgarian interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed | Bulgarian UI strings, compiled in by crates/ui-egui/src/i18n.rs |
| `crates/ui-egui/src/i18n/kk.tsv` | Kazakh interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of the English UI labels into Kazakh, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed | Kazakh UI strings, compiled in by crates/ui-egui/src/i18n.rs |
| `crates/ui-egui/src/i18n/ja.tsv` | Japanese interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed | Japanese UI strings, compiled in by crates/ui-egui/src/i18n.rs |
| `crates/ui-egui/src/i18n/uk.tsv` | Ukrainian interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed | Ukrainian UI strings, compiled in by crates/ui-egui/src/i18n.rs |
| `crates/ui-egui/src/i18n/ar.tsv` | Arabic interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed | Arabic UI strings, compiled in by crates/ui-egui/src/i18n.rs |
| `crates/ui-egui/src/i18n/ckb.tsv` | Central Kurdish (Sorani) interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed | Central Kurdish UI strings, compiled in by crates/ui-egui/src/i18n.rs |
| `crates/ui-egui/src/i18n/fa.tsv` | Persian (Farsi) 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-25 initial catalog covering the current 2,776-entry key union, AI-assisted translations from English, not separately native-reviewed | Persian UI strings, compiled in by crates/ui-egui/src/i18n.rs |
| `crates/ui-egui/src/i18n/tr.tsv` | Turkish interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed | Turkish UI strings, compiled in by crates/ui-egui/src/i18n.rs |
| `crates/ui-egui/src/i18n/lt.tsv` | Lithuanian interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels and user-facing messages; original catalog reviewed by a native Lithuanian-speaking contributor; 2026-10-15 coverage additions are AI-assisted and not separately native-reviewed; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed | Lithuanian UI strings, compiled in by crates/ui-egui/src/i18n.rs |
| `crates/ui-egui/src/i18n/hi.tsv` | Hindi interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 text-field-table labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed | Hindi UI strings, compiled in by crates/ui-egui/src/i18n.rs |
| `crates/ui-egui/src/i18n/id.tsv` | Indonesian interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 text-field-table labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed | Indonesian UI strings, compiled in by crates/ui-egui/src/i18n.rs |
| `crates/ui-egui/src/i18n/ko.tsv` | Korean interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 text-field-table labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed | Korean UI strings, compiled in by crates/ui-egui/src/i18n.rs |
| `crates/ui-egui/src/i18n/ro.tsv` | Romanian interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels and user-facing messages; AI-assisted and not yet reviewed line by line by a native Romanian speaker; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 text-field-table labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed | Romanian UI strings, compiled in by crates/ui-egui/src/i18n.rs |
| `crates/ui-egui/src/i18n/fi.tsv` | Finnish interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: AI-assisted (Claude Code) clean-room translations of PdfCraft's English UI labels and user-facing messages; not yet proofread by a native Finnish speaker; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 text-field-table labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 calculation-order, text-format, print, thumbnail, layer, comment-reshape and signature labels (previously English placeholders) are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed | Finnish UI strings, compiled in by crates/ui-egui/src/i18n.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 |
| `assets/icons/square-terminal.svg` | Lucide icon "square-terminal" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/square-terminal.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/file-code.svg` | Lucide icon "file-code" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/file-code.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/file-spreadsheet.svg` | Lucide icon "file-spreadsheet" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/file-spreadsheet.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/align-justify.svg` | Lucide icon "align-justify" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/align-justify.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/align-right.svg` | Lucide icon "align-right" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/align-right.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/columns-3.svg` | Lucide icon "columns-3" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/columns-3.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/rows-3.svg` | Lucide icon "rows-3" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/rows-3.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/flip-horizontal-2.svg` | Lucide icon "flip-horizontal-2" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/flip-horizontal-2.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/flip-vertical-2.svg` | Lucide icon "flip-vertical-2" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/flip-vertical-2.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/app-window.svg` | Lucide icon "app-window" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/app-window.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/arrow-left-right.svg` | Lucide icon "arrow-left-right" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/arrow-left-right.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/arrow-up-down.svg` | Lucide icon "arrow-up-down" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/arrow-up-down.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/arrow-up-right.svg` | Lucide icon "arrow-up-right" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/arrow-up-right.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/badge-check.svg` | Lucide icon "badge-check" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/badge-check.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/bandage.svg` | Lucide icon "bandage" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/bandage.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/bell.svg` | Lucide icon "bell" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/bell.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/blend.svg` | Lucide icon "blend" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/blend.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/bold.svg` | Lucide icon "bold" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/bold.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/book-open.svg` | Lucide icon "book-open" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/book-open.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/bookmark.svg` | Lucide icon "bookmark" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/bookmark.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/bookmark-plus.svg` | Lucide icon "bookmark-plus" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/bookmark-plus.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/braces.svg` | Lucide icon "braces" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/braces.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/brush-cleaning.svg` | Lucide icon "brush-cleaning" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/brush-cleaning.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/brush.svg` | Lucide icon "brush" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/brush.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/camera.svg` | Lucide icon "camera" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/camera.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/check-circle-2.svg` | Lucide icon "check-circle-2" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/check-circle-2.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/check.svg` | Lucide icon "check" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/check.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/chevron-down.svg` | Lucide icon "chevron-down" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/chevron-down.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/chevron-left.svg` | Lucide icon "chevron-left" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/chevron-left.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/chevron-right.svg` | Lucide icon "chevron-right" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/chevron-right.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/chevron-up.svg` | Lucide icon "chevron-up" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/chevron-up.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/chevrons-left.svg` | Lucide icon "chevrons-left" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/chevrons-left.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/chevrons-right.svg` | Lucide icon "chevrons-right" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/chevrons-right.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/circle-check.svg` | Lucide icon "circle-check" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/circle-check.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/circle-dashed.svg` | Lucide icon "circle-dashed" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/circle-dashed.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/circle-dot.svg` | Lucide icon "circle-dot" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/circle-dot.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/circle-help.svg` | Lucide icon "circle-help" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/circle-help.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/circle.svg` | Lucide icon "circle" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/circle.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/clock-3.svg` | Lucide icon "clock-3" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/clock-3.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/clock.svg` | Lucide icon "clock" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/clock.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/cloud-upload.svg` | Lucide icon "cloud-upload" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/cloud-upload.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/cloud.svg` | Lucide icon "cloud" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/cloud.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/code-xml.svg` | Lucide icon "code-xml" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/code-xml.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/columns-2.svg` | Lucide icon "columns-2" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/columns-2.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/compass.svg` | Lucide icon "compass" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/compass.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/contrast.svg` | Lucide icon "contrast" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/contrast.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/copy-plus.svg` | Lucide icon "copy-plus" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/copy-plus.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/copy.svg` | Lucide icon "copy" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/copy.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/crop.svg` | Lucide icon "crop" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/crop.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/droplet.svg` | Lucide icon "droplet" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/droplet.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/ellipsis-vertical.svg` | Lucide icon "ellipsis-vertical" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/ellipsis-vertical.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/ellipsis.svg` | Lucide icon "ellipsis" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/ellipsis.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/eraser.svg` | Lucide icon "eraser" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/eraser.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/external-link.svg` | Lucide icon "external-link" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/external-link.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/eye-off.svg` | Lucide icon "eye-off" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/eye-off.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/eye.svg` | Lucide icon "eye" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/eye.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/file-check.svg` | Lucide icon "file-check" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/file-check.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/file-down.svg` | Lucide icon "file-down" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/file-down.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/file-input.svg` | Lucide icon "file-input" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/file-input.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/file-lock-2.svg` | Lucide icon "file-lock-2" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/file-lock-2.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/file-minus.svg` | Lucide icon "file-minus" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/file-minus.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/file-output.svg` | Lucide icon "file-output" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/file-output.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/file-pen-line.svg` | Lucide icon "file-pen-line" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/file-pen-line.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/file-plus-2.svg` | Lucide icon "file-plus-2" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/file-plus-2.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/file-plus.svg` | Lucide icon "file-plus" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/file-plus.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/file-scan.svg` | Lucide icon "file-scan" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/file-scan.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/file-search.svg` | Lucide icon "file-search" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/file-search.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/file-symlink.svg` | Lucide icon "file-symlink" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/file-symlink.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/file-text.svg` | Lucide icon "file-text" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/file-text.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/file-x.svg` | Lucide icon "file-x" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/file-x.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/files.svg` | Lucide icon "files" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/files.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/film.svg` | Lucide icon "film" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/film.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/filter.svg` | Lucide icon "filter" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/filter.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/folder-open.svg` | Lucide icon "folder-open" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/folder-open.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/folder-plus.svg` | Lucide icon "folder-plus" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/folder-plus.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/folder.svg` | Lucide icon "folder" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/folder.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/gauge.svg` | Lucide icon "gauge" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/gauge.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/git-compare.svg` | Lucide icon "git-compare" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/git-compare.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/globe.svg` | Lucide icon "globe" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/globe.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/grid-3x3.svg` | Lucide icon "grid-3x3" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/grid-3x3.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/hand.svg` | Lucide icon "hand" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/hand.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/hash.svg` | Lucide icon "hash" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/hash.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/heading.svg` | Lucide icon "heading" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/heading.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/highlighter.svg` | Lucide icon "highlighter" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/highlighter.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/house.svg` | Lucide icon "house" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/house.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/image-plus.svg` | Lucide icon "image-plus" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/image-plus.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/image.svg` | Lucide icon "image" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/image.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/info.svg` | Lucide icon "info" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/info.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/italic.svg` | Lucide icon "italic" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/italic.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/languages.svg` | Lucide icon "languages" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/languages.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/lasso.svg` | Lucide icon "lasso" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/lasso.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/layers.svg` | Lucide icon "layers" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/layers.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/layout-grid.svg` | Lucide icon "layout-grid" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/layout-grid.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/link-2.svg` | Lucide icon "link-2" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/link-2.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/link.svg` | Lucide icon "link" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/link.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/list-checks.svg` | Lucide icon "list-checks" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/list-checks.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/list-ordered.svg` | Lucide icon "list-ordered" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/list-ordered.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/list.svg` | Lucide icon "list" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/list.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/lock-open.svg` | Lucide icon "lock-open" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/lock-open.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/lock.svg` | Lucide icon "lock" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/lock.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/maximize-2.svg` | Lucide icon "maximize-2" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/maximize-2.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/maximize.svg` | Lucide icon "maximize" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/maximize.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/message-circle-reply.svg` | Lucide icon "message-circle-reply" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/message-circle-reply.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/message-square-text.svg` | Lucide icon "message-square-text" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/message-square-text.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/message-square.svg` | Lucide icon "message-square" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/message-square.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/messages-square.svg` | Lucide icon "messages-square" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/messages-square.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/mic.svg` | Lucide icon "mic" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/mic.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/minimize.svg` | Lucide icon "minimize" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/minimize.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/minimize-2.svg` | Lucide icon "minimize-2" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/minimize-2.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/minus.svg` | Lucide icon "minus" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/minus.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/moon.svg` | Lucide icon "moon" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/moon.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/mouse-pointer-2.svg` | Lucide icon "mouse-pointer-2" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/mouse-pointer-2.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/move.svg` | Lucide icon "move" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/move.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/navigation.svg` | Lucide icon "navigation" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/navigation.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/paint-bucket.svg` | Lucide icon "paint-bucket" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/paint-bucket.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/palette.svg` | Lucide icon "palette" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/palette.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/panel-left.svg` | Lucide icon "panel-left" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/panel-left.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/panel-right.svg` | Lucide icon "panel-right" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/panel-right.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/panels-top-left.svg` | Lucide icon "panels-top-left" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/panels-top-left.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/paperclip.svg` | Lucide icon "paperclip" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/paperclip.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/pen-line.svg` | Lucide icon "pen-line" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/pen-line.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/pen-tool.svg` | Lucide icon "pen-tool" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/pen-tool.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/pencil.svg` | Lucide icon "pencil" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/pencil.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/pipette.svg` | Lucide icon "pipette" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/pipette.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/plus.svg` | Lucide icon "plus" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/plus.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/presentation.svg` | Lucide icon "presentation" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/presentation.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/printer.svg` | Lucide icon "printer" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/printer.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/rectangle-horizontal.svg` | Lucide icon "rectangle-horizontal" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/rectangle-horizontal.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/redo-2.svg` | Lucide icon "redo-2" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/redo-2.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/replace.svg` | Lucide icon "replace" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/replace.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/rotate-ccw.svg` | Lucide icon "rotate-ccw" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/rotate-ccw.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/rotate-cw.svg` | Lucide icon "rotate-cw" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/rotate-cw.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/ruler.svg` | Lucide icon "ruler" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/ruler.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/save.svg` | Lucide icon "save" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/save.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/scan-text.svg` | Lucide icon "scan-text" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/scan-text.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/scan.svg` | Lucide icon "scan" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/scan.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/scissors.svg` | Lucide icon "scissors" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/scissors.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/search.svg` | Lucide icon "search" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/search.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/send.svg` | Lucide icon "send" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/send.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/settings-2.svg` | Lucide icon "settings-2" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/settings-2.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/settings.svg` | Lucide icon "settings" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/settings.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/share-2.svg` | Lucide icon "share-2" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/share-2.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/shield-check.svg` | Lucide icon "shield-check" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/shield-check.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/signature.svg` | Lucide icon "signature" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/signature.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/sliders-horizontal.svg` | Lucide icon "sliders-horizontal" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/sliders-horizontal.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/sparkles.svg` | Lucide icon "sparkles" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/sparkles.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/spline.svg` | Lucide icon "spline" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/spline.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/square-dashed-mouse-pointer.svg` | Lucide icon "square-dashed-mouse-pointer" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/square-dashed-mouse-pointer.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/square-dashed.svg` | Lucide icon "square-dashed" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/square-dashed.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/square.svg` | Lucide icon "square" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/square.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/squares-subtract.svg` | Lucide icon "squares-subtract" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/squares-subtract.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/stamp.svg` | Lucide icon "stamp" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/stamp.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/star.svg` | Lucide icon "star" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/star.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/sticky-note.svg` | Lucide icon "sticky-note" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/sticky-note.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/strikethrough.svg` | Lucide icon "strikethrough" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/strikethrough.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/sun.svg` | Lucide icon "sun" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/sun.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/swatch-book.svg` | Lucide icon "swatch-book" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/swatch-book.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/tag.svg` | Lucide icon "tag" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/tag.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/text-cursor-input.svg` | Lucide icon "text-cursor-input" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/text-cursor-input.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/text-select.svg` | Lucide icon "text-select" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/text-select.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/trash-2.svg` | Lucide icon "trash-2" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/trash-2.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/trash.svg` | Lucide icon "trash" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/trash.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/triangle-alert.svg` | Lucide icon "triangle-alert" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/triangle-alert.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/type.svg` | Lucide icon "type" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/type.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/underline.svg` | Lucide icon "underline" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/underline.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/undo-2.svg` | Lucide icon "undo-2" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/undo-2.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/user-round.svg` | Lucide icon "user-round" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/user-round.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/wand-sparkles.svg` | Lucide icon "wand-sparkles" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/wand-sparkles.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/wrench.svg` | Lucide icon "wrench" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/wrench.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/x.svg` | Lucide icon "x" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/x.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/zoom-in.svg` | Lucide icon "zoom-in" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/zoom-in.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/zoom-out.svg` | Lucide icon "zoom-out" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/zoom-out.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/accessibility.svg` | Lucide icon "accessibility" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | 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 AND MIT | 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 AND MIT | 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 |
| `assets/icons/square-terminal.svg` | Lucide icon "square-terminal" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/square-terminal.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/file-code.svg` | Lucide icon "file-code" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/file-code.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/file-spreadsheet.svg` | Lucide icon "file-spreadsheet" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/file-spreadsheet.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/align-justify.svg` | Lucide icon "align-justify" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/align-justify.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/align-right.svg` | Lucide icon "align-right" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/align-right.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/columns-3.svg` | Lucide icon "columns-3" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/columns-3.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/rows-3.svg` | Lucide icon "rows-3" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/rows-3.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/flip-horizontal-2.svg` | Lucide icon "flip-horizontal-2" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/flip-horizontal-2.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/flip-vertical-2.svg` | Lucide icon "flip-vertical-2" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/flip-vertical-2.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/app-window.svg` | Lucide icon "app-window" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/app-window.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/arrow-left-right.svg` | Lucide icon "arrow-left-right" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/arrow-left-right.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/arrow-up-down.svg` | Lucide icon "arrow-up-down" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/arrow-up-down.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/arrow-up-right.svg` | Lucide icon "arrow-up-right" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/arrow-up-right.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/badge-check.svg` | Lucide icon "badge-check" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/badge-check.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/bandage.svg` | Lucide icon "bandage" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/bandage.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/bell.svg` | Lucide icon "bell" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/bell.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/blend.svg` | Lucide icon "blend" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/blend.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/bold.svg` | Lucide icon "bold" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/bold.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/book-open.svg` | Lucide icon "book-open" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/book-open.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/bookmark.svg` | Lucide icon "bookmark" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/bookmark.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/bookmark-plus.svg` | Lucide icon "bookmark-plus" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/bookmark-plus.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/braces.svg` | Lucide icon "braces" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/braces.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/brush-cleaning.svg` | Lucide icon "brush-cleaning" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/brush-cleaning.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/brush.svg` | Lucide icon "brush" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/brush.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/camera.svg` | Lucide icon "camera" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/camera.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/check-circle-2.svg` | Lucide icon "check-circle-2" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/check-circle-2.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/check.svg` | Lucide icon "check" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/check.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/chevron-down.svg` | Lucide icon "chevron-down" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/chevron-down.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/chevron-left.svg` | Lucide icon "chevron-left" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/chevron-left.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/chevron-right.svg` | Lucide icon "chevron-right" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/chevron-right.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/chevron-up.svg` | Lucide icon "chevron-up" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/chevron-up.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/chevrons-left.svg` | Lucide icon "chevrons-left" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/chevrons-left.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/chevrons-right.svg` | Lucide icon "chevrons-right" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/chevrons-right.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/circle-check.svg` | Lucide icon "circle-check" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/circle-check.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/circle-dashed.svg` | Lucide icon "circle-dashed" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/circle-dashed.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/circle-dot.svg` | Lucide icon "circle-dot" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/circle-dot.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/circle-help.svg` | Lucide icon "circle-help" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/circle-help.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/circle.svg` | Lucide icon "circle" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/circle.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/clock-3.svg` | Lucide icon "clock-3" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/clock-3.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/clock.svg` | Lucide icon "clock" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/clock.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/cloud-upload.svg` | Lucide icon "cloud-upload" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/cloud-upload.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/cloud.svg` | Lucide icon "cloud" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/cloud.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/code-xml.svg` | Lucide icon "code-xml" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/code-xml.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/columns-2.svg` | Lucide icon "columns-2" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/columns-2.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/compass.svg` | Lucide icon "compass" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/compass.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/contrast.svg` | Lucide icon "contrast" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/contrast.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/copy-plus.svg` | Lucide icon "copy-plus" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/copy-plus.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/copy.svg` | Lucide icon "copy" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/copy.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/crop.svg` | Lucide icon "crop" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/crop.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/droplet.svg` | Lucide icon "droplet" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/droplet.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/ellipsis-vertical.svg` | Lucide icon "ellipsis-vertical" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/ellipsis-vertical.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/ellipsis.svg` | Lucide icon "ellipsis" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/ellipsis.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/eraser.svg` | Lucide icon "eraser" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/eraser.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/external-link.svg` | Lucide icon "external-link" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/external-link.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/eye-off.svg` | Lucide icon "eye-off" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/eye-off.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/eye.svg` | Lucide icon "eye" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/eye.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/file-check.svg` | Lucide icon "file-check" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/file-check.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/file-down.svg` | Lucide icon "file-down" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/file-down.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/file-input.svg` | Lucide icon "file-input" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/file-input.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/file-lock-2.svg` | Lucide icon "file-lock-2" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/file-lock-2.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/file-minus.svg` | Lucide icon "file-minus" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/file-minus.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/file-output.svg` | Lucide icon "file-output" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/file-output.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/file-pen-line.svg` | Lucide icon "file-pen-line" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/file-pen-line.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/file-plus-2.svg` | Lucide icon "file-plus-2" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/file-plus-2.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/file-plus.svg` | Lucide icon "file-plus" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/file-plus.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/file-scan.svg` | Lucide icon "file-scan" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/file-scan.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/file-search.svg` | Lucide icon "file-search" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/file-search.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/file-symlink.svg` | Lucide icon "file-symlink" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/file-symlink.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/file-text.svg` | Lucide icon "file-text" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/file-text.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/file-x.svg` | Lucide icon "file-x" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/file-x.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/files.svg` | Lucide icon "files" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/files.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/film.svg` | Lucide icon "film" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/film.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/filter.svg` | Lucide icon "filter" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/filter.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/folder-open.svg` | Lucide icon "folder-open" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/folder-open.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/folder-plus.svg` | Lucide icon "folder-plus" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/folder-plus.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/folder.svg` | Lucide icon "folder" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/folder.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/gauge.svg` | Lucide icon "gauge" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/gauge.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/git-compare.svg` | Lucide icon "git-compare" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/git-compare.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/globe.svg` | Lucide icon "globe" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/globe.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/grid-3x3.svg` | Lucide icon "grid-3x3" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/grid-3x3.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/hand.svg` | Lucide icon "hand" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/hand.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/hash.svg` | Lucide icon "hash" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/hash.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/heading.svg` | Lucide icon "heading" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/heading.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/highlighter.svg` | Lucide icon "highlighter" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/highlighter.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/house.svg` | Lucide icon "house" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/house.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/image-plus.svg` | Lucide icon "image-plus" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/image-plus.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/image.svg` | Lucide icon "image" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/image.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/info.svg` | Lucide icon "info" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/info.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/italic.svg` | Lucide icon "italic" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/italic.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/languages.svg` | Lucide icon "languages" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/languages.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/lasso.svg` | Lucide icon "lasso" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/lasso.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/layers.svg` | Lucide icon "layers" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/layers.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/layout-grid.svg` | Lucide icon "layout-grid" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/layout-grid.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/link-2.svg` | Lucide icon "link-2" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/link-2.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/link.svg` | Lucide icon "link" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/link.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/list-checks.svg` | Lucide icon "list-checks" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/list-checks.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/list-ordered.svg` | Lucide icon "list-ordered" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/list-ordered.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/list.svg` | Lucide icon "list" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/list.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/lock-open.svg` | Lucide icon "lock-open" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/lock-open.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/lock.svg` | Lucide icon "lock" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/lock.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/maximize-2.svg` | Lucide icon "maximize-2" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/maximize-2.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/maximize.svg` | Lucide icon "maximize" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/maximize.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/message-circle-reply.svg` | Lucide icon "message-circle-reply" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/message-circle-reply.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/message-square-text.svg` | Lucide icon "message-square-text" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/message-square-text.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/message-square.svg` | Lucide icon "message-square" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/message-square.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/messages-square.svg` | Lucide icon "messages-square" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/messages-square.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/mic.svg` | Lucide icon "mic" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/mic.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/minimize.svg` | Lucide icon "minimize" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/minimize.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/minimize-2.svg` | Lucide icon "minimize-2" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/minimize-2.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/minus.svg` | Lucide icon "minus" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/minus.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/moon.svg` | Lucide icon "moon" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/moon.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/mouse-pointer-2.svg` | Lucide icon "mouse-pointer-2" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/mouse-pointer-2.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/move.svg` | Lucide icon "move" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/move.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/navigation.svg` | Lucide icon "navigation" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/navigation.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/paint-bucket.svg` | Lucide icon "paint-bucket" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/paint-bucket.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/palette.svg` | Lucide icon "palette" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/palette.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/panel-left.svg` | Lucide icon "panel-left" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/panel-left.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/panel-right.svg` | Lucide icon "panel-right" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/panel-right.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/panels-top-left.svg` | Lucide icon "panels-top-left" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/panels-top-left.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/paperclip.svg` | Lucide icon "paperclip" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/paperclip.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/pen-line.svg` | Lucide icon "pen-line" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/pen-line.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/pen-tool.svg` | Lucide icon "pen-tool" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/pen-tool.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/pencil.svg` | Lucide icon "pencil" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/pencil.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/pipette.svg` | Lucide icon "pipette" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/pipette.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/plus.svg` | Lucide icon "plus" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/plus.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/presentation.svg` | Lucide icon "presentation" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/presentation.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/printer.svg` | Lucide icon "printer" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/printer.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/rectangle-horizontal.svg` | Lucide icon "rectangle-horizontal" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/rectangle-horizontal.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/redo-2.svg` | Lucide icon "redo-2" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/redo-2.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/replace.svg` | Lucide icon "replace" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/replace.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/rotate-ccw.svg` | Lucide icon "rotate-ccw" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/rotate-ccw.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/rotate-cw.svg` | Lucide icon "rotate-cw" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/rotate-cw.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/ruler.svg` | Lucide icon "ruler" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/ruler.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/save.svg` | Lucide icon "save" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/save.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/scan-text.svg` | Lucide icon "scan-text" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/scan-text.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/scan.svg` | Lucide icon "scan" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/scan.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/scissors.svg` | Lucide icon "scissors" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/scissors.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/search.svg` | Lucide icon "search" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/search.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/send.svg` | Lucide icon "send" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/send.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/settings-2.svg` | Lucide icon "settings-2" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/settings-2.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/settings.svg` | Lucide icon "settings" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/settings.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/share-2.svg` | Lucide icon "share-2" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/share-2.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/shield-check.svg` | Lucide icon "shield-check" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/shield-check.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/signature.svg` | Lucide icon "signature" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/signature.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/sliders-horizontal.svg` | Lucide icon "sliders-horizontal" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/sliders-horizontal.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/sparkles.svg` | Lucide icon "sparkles" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/sparkles.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/spline.svg` | Lucide icon "spline" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/spline.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/square-dashed-mouse-pointer.svg` | Lucide icon "square-dashed-mouse-pointer" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/square-dashed-mouse-pointer.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/square-dashed.svg` | Lucide icon "square-dashed" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/square-dashed.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/square.svg` | Lucide icon "square" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/square.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/squares-subtract.svg` | Lucide icon "squares-subtract" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/squares-subtract.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/stamp.svg` | Lucide icon "stamp" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/stamp.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/star.svg` | Lucide icon "star" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/star.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/sticky-note.svg` | Lucide icon "sticky-note" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/sticky-note.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/strikethrough.svg` | Lucide icon "strikethrough" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/strikethrough.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/sun.svg` | Lucide icon "sun" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/sun.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/swatch-book.svg` | Lucide icon "swatch-book" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/swatch-book.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/tag.svg` | Lucide icon "tag" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/tag.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/text-cursor-input.svg` | Lucide icon "text-cursor-input" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/text-cursor-input.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/text-select.svg` | Lucide icon "text-select" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/text-select.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/trash-2.svg` | Lucide icon "trash-2" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/trash-2.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/trash.svg` | Lucide icon "trash" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/trash.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/triangle-alert.svg` | Lucide icon "triangle-alert" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/triangle-alert.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/type.svg` | Lucide icon "type" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/type.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/underline.svg` | Lucide icon "underline" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/underline.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/undo-2.svg` | Lucide icon "undo-2" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/undo-2.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/user-round.svg` | Lucide icon "user-round" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/user-round.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/wand-sparkles.svg` | Lucide icon "wand-sparkles" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/wand-sparkles.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/wrench.svg` | Lucide icon "wrench" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/wrench.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/x.svg` | Lucide icon "x" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/x.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/zoom-in.svg` | Lucide icon "zoom-in" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/zoom-in.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/zoom-out.svg` | Lucide icon "zoom-out" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/zoom-out.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/fonts/Inter-Regular.ttf` | Inter Regular | The Inter Project Authors (Rasmus Andersson) | OFL-1.1 | https://github.com/rsms/inter | UI font, embedded in the app; demo PDF labels; slanted fallback glyphs in Fill & Sign typed signatures for characters Dancing Script lacks (Cyrillic, Greek), drawn as filled paths |
| `assets/fonts/Inter-Medium.ttf` | Inter Medium | The Inter Project Authors (Rasmus Andersson) | OFL-1.1 | https://github.com/rsms/inter | UI font, embedded in the app; demo PDF labels |
| `assets/fonts/Inter-SemiBold.ttf` | Inter SemiBold | The Inter Project Authors (Rasmus Andersson) | OFL-1.1 | https://github.com/rsms/inter | UI font, embedded in the app; demo PDF labels |
@@ -231,6 +203,7 @@ Every asset PdfCraft includes, bundles or uses to build its published material,
| `vendor/hayro-interpret/assets/FoxitSymbol.pfb` | FoxitSymbol (standard-14 substitute font) | Foxit Software Inc. / PDFium Authors | BSD-3-Clause | https://pdfium.googlesource.com/pdfium (via hayro-interpret 0.7.0 assets/) | Renders non-embedded standard-14 fonts (vendored hayro-interpret) |
| `vendor/hayro-interpret/assets/CGATS001Compat-v2-micro.icc` | CGATS001Compat v2 micro ICC profile | Clinton Ingram (saucecontrol/Compact-ICC-Profiles) | CC0-1.0 | https://github.com/saucecontrol/Compact-ICC-Profiles | Default CMYK colour conversion (vendored hayro-interpret) |
| `crates/fonts/src/std14_metrics.rs` | Standard-14 font advance widths and encodings (as Rust tables) | Adobe (Core14 AFM metrics, PDF specification encodings); tables generated by the PdfCraft contributors | MIT OR Apache-2.0 | ISO 32000-2 Annex D and the Adobe Core14 AFM metrics. Generated by joining the published WinAnsi, Symbol and ZapfDingbats encodings (code to glyph name) with the per-glyph advance widths, then spot-checked against the specification by hand in the tests of crates/fonts/src/std14.rs. Data only: the code that reads these tables lives in std14.rs, so that ordinary edits do not churn this file's hash. | Advance widths for the fourteen standard fonts, which a PDF may name without embedding. Non-visual data, not a typeface: the item AGENTS.md 1.1 permits, held first-party so generated appearance streams and the renderer agree. |
| `crates/prc/src/acof/table.rs` | PRC Double prefix-code table (as a Rust table) | Kristof Ralovich (prc-rs); the code table itself is defined by the PRC format (ISO 14739-1, working draft clause 11.17.2) | MIT | Rows taken from prc-rs src/double.rs at commit 287b671bb5b31b05efb5ec1b98f7c359b9e4dd7d (https://github.com/ralovich/prc-rs), mechanically reformatted into (code length, code, entry) tuples; checked to be a complete prefix code by the tests in crates/prc/src/acof.rs. Data only: the code that reads the table lives in acof.rs. The MIT notice is kept in the file header. | Decodes every PRC Double (coordinates, transforms, colours) in 3D annotations' PRC streams. Non-visual data. |
| `vendor/hayro-cmap/assets/cmaps.brotli` | Adobe CMap resources (predefined CJK CMaps) | Adobe | BSD-3-Clause | https://github.com/adobe-type-tools/cmap-resources (via hayro-cmap 0.1.0 assets/) | Character-code mapping tables required to read CJK PDFs. Non-visual data, allowed by AGENTS.md §1.1 |
| `docs/brand/artcraft-logo-white.png` | ArtCraft brand: artcraft-logo-white | ArtCraft Team | LicenseRef-Storyteller-Trademark | ArtCraft Team brand assets (provided by the project owner, 2026-10-01; identical copies in storytold/photocraft) | ArtCraft branding next to the community links (About dialog, Help menu, home screen) and in docs. ArtCraft Team trademark, not open source; may be used only unmodified within PdfCraft; forks and modified versions must remove it. |
| `docs/brand/artcraft-logo-white.svg` | ArtCraft brand: artcraft-logo-white | ArtCraft Team | LicenseRef-Storyteller-Trademark | ArtCraft Team brand assets (provided by the project owner, 2026-10-01; identical copies in storytold/photocraft) | ArtCraft branding next to the community links (About dialog, Help menu, home screen) and in docs. ArtCraft Team trademark, not open source; may be used only unmodified within PdfCraft; forks and modified versions must remove it. |
@@ -240,22 +213,22 @@ Every asset PdfCraft includes, bundles or uses to build its published material,
| `docs/brand/artcraft-mark-black.svg` | ArtCraft brand: artcraft-mark-black | ArtCraft Team | LicenseRef-Storyteller-Trademark | ArtCraft Team brand assets (provided by the project owner, 2026-10-01; identical copies in storytold/photocraft) | ArtCraft branding next to the community links (About dialog, Help menu, home screen) and in docs. ArtCraft Team trademark, not open source; may be used only unmodified within PdfCraft; forks and modified versions must remove it. |
| `docs/brand/artcraft-mark.png` | ArtCraft brand: artcraft-mark | ArtCraft Team | LicenseRef-Storyteller-Trademark | ArtCraft Team brand assets (provided by the project owner, 2026-10-01; identical copies in storytold/photocraft) | ArtCraft branding next to the community links (About dialog, Help menu, home screen) and in docs. ArtCraft Team trademark, not open source; may be used only unmodified within PdfCraft; forks and modified versions must remove it. |
| `docs/brand/artcraft-mark.svg` | ArtCraft brand: artcraft-mark | ArtCraft Team | LicenseRef-Storyteller-Trademark | ArtCraft Team brand assets (provided by the project owner, 2026-10-01; identical copies in storytold/photocraft) | ArtCraft branding next to the community links (About dialog, Help menu, home screen) and in docs. ArtCraft Team trademark, not open source; may be used only unmodified within PdfCraft; forks and modified versions must remove it. |
| `assets/app-icon/pdfcraft.svg` | PdfCraft app icon (master vector) | PdfCraft contributors (drawn by the project owner in ArtCraft; vectorised with craftrules vectorize_tile.py) | MIT OR Apache-2.0 | Contributor-original (see assets/app-icon/README.md) | Master artwork; every other app-icon file is rendered from it (packaging/icons.sh) |
| `assets/app-icon/pdfcraft-small.svg` | PdfCraft app icon (light vector) | PdfCraft contributors (drawn by the project owner in ArtCraft; vectorised with craftrules vectorize_tile.py) | MIT OR Apache-2.0 | Contributor-original (see assets/app-icon/README.md) | README header and assets/app-icon/README.md |
| `assets/app-icon/pdfcraft-1024.png` | PdfCraft app icon, 1024 px on Apple's icon grid | PdfCraft contributors (drawn by the project owner in ArtCraft; vectorised with craftrules vectorize_tile.py) | MIT OR Apache-2.0 | Contributor-original (see assets/app-icon/README.md) | Runtime window/Dock icon on macOS (apps/pdfcraft/src/main.rs) |
| `assets/app-icon/pdfcraft.icns` | PdfCraft app icon (macOS .icns) | PdfCraft contributors (drawn by the project owner in ArtCraft; vectorised with craftrules vectorize_tile.py) | MIT OR Apache-2.0 | Contributor-original (see assets/app-icon/README.md) | macOS app bundle icon |
| `assets/app-icon/pdfcraft.ico` | PdfCraft app icon (Windows .ico, 16-256 px) | PdfCraft contributors (drawn by the project owner in ArtCraft; vectorised with craftrules vectorize_tile.py) | MIT OR Apache-2.0 | Contributor-original (see assets/app-icon/README.md) | Embedded in pdfcraft.exe by apps/pdfcraft/build.rs (Explorer, taskbar, Start menu, Alt-Tab) |
| `assets/app-icon/pdfcraft.svg` | PdfCraft app icon (master vector) | PdfCraft contributors (drawn by the project owner in ArtCraft) | MIT OR Apache-2.0 | Contributor-original (see assets/app-icon/README.md) | Master artwork; every other app-icon file is rendered from it (packaging/icons.sh) |
| `assets/app-icon/pdfcraft-small.svg` | PdfCraft app icon (light vector) | PdfCraft contributors (drawn by the project owner in ArtCraft) | MIT OR Apache-2.0 | Contributor-original (see assets/app-icon/README.md) | README header and assets/app-icon/README.md |
| `assets/app-icon/pdfcraft-1024.png` | PdfCraft app icon, 1024 px on Apple's icon grid | PdfCraft contributors (drawn by the project owner in ArtCraft) | MIT OR Apache-2.0 | Contributor-original (see assets/app-icon/README.md) | Runtime window/Dock icon on macOS (apps/pdfcraft/src/main.rs) |
| `assets/app-icon/pdfcraft.icns` | PdfCraft app icon (macOS .icns) | PdfCraft contributors (drawn by the project owner in ArtCraft) | MIT OR Apache-2.0 | Contributor-original (see assets/app-icon/README.md) | macOS app bundle icon |
| `assets/app-icon/pdfcraft.ico` | PdfCraft app icon (Windows .ico, 16-256 px) | PdfCraft contributors (drawn by the project owner in ArtCraft) | MIT OR Apache-2.0 | Contributor-original (see assets/app-icon/README.md) | Embedded in pdfcraft.exe by apps/pdfcraft/build.rs (Explorer, taskbar, Start menu, Alt-Tab) |
| `assets/app-icon/pdfcraft-document.svg` | PdfCraft PDF document icon (master vector) | Lucide Icons and Contributors (document outline); PdfCraft contributors (PDF badge, lettering and composition) | ISC AND (MIT OR Apache-2.0) | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/file-text.svg); contributor-original composition (assets/app-icon/README.md) | Master artwork for the Windows PDF file type icon; rendered by packaging/icons.sh, without fonts or external images |
| `assets/app-icon/pdfcraft-document.ico` | PdfCraft PDF document icon (Windows .ico, 16-256 px) | Lucide Icons and Contributors (document outline); PdfCraft contributors (PDF badge, lettering and composition) | ISC AND (MIT OR Apache-2.0) | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/file-text.svg); contributor-original composition (assets/app-icon/README.md) | Embedded in pdfcraft.exe as resource 2; the Windows installer uses it for PdfCraft.Document and Applications/pdfcraft.exe PDF file associations |
| `assets/app-icon/hicolor/16x16/apps/ai.storyteller.pdfcraft.png` | PdfCraft app icon, 16 px | PdfCraft contributors (drawn by the project owner in ArtCraft; vectorised with craftrules vectorize_tile.py) | MIT OR Apache-2.0 | Contributor-original (see assets/app-icon/README.md) | Linux hicolor theme icon (packaging/linux/ai.storyteller.pdfcraft.desktop) |
| `assets/app-icon/hicolor/24x24/apps/ai.storyteller.pdfcraft.png` | PdfCraft app icon, 24 px | PdfCraft contributors (drawn by the project owner in ArtCraft; vectorised with craftrules vectorize_tile.py) | MIT OR Apache-2.0 | Contributor-original (see assets/app-icon/README.md) | Linux hicolor theme icon (packaging/linux/ai.storyteller.pdfcraft.desktop) |
| `assets/app-icon/hicolor/32x32/apps/ai.storyteller.pdfcraft.png` | PdfCraft app icon, 32 px | PdfCraft contributors (drawn by the project owner in ArtCraft; vectorised with craftrules vectorize_tile.py) | MIT OR Apache-2.0 | Contributor-original (see assets/app-icon/README.md) | Linux hicolor theme icon (packaging/linux/ai.storyteller.pdfcraft.desktop) |
| `assets/app-icon/hicolor/48x48/apps/ai.storyteller.pdfcraft.png` | PdfCraft app icon, 48 px | PdfCraft contributors (drawn by the project owner in ArtCraft; vectorised with craftrules vectorize_tile.py) | MIT OR Apache-2.0 | Contributor-original (see assets/app-icon/README.md) | Linux hicolor theme icon (packaging/linux/ai.storyteller.pdfcraft.desktop) |
| `assets/app-icon/hicolor/64x64/apps/ai.storyteller.pdfcraft.png` | PdfCraft app icon, 64 px | PdfCraft contributors (drawn by the project owner in ArtCraft; vectorised with craftrules vectorize_tile.py) | MIT OR Apache-2.0 | Contributor-original (see assets/app-icon/README.md) | Linux hicolor theme icon (packaging/linux/ai.storyteller.pdfcraft.desktop) |
| `assets/app-icon/hicolor/128x128/apps/ai.storyteller.pdfcraft.png` | PdfCraft app icon, 128 px | PdfCraft contributors (drawn by the project owner in ArtCraft; vectorised with craftrules vectorize_tile.py) | MIT OR Apache-2.0 | Contributor-original (see assets/app-icon/README.md) | Linux hicolor theme icon (packaging/linux/ai.storyteller.pdfcraft.desktop) |
| `assets/app-icon/hicolor/256x256/apps/ai.storyteller.pdfcraft.png` | PdfCraft app icon, 256 px | PdfCraft contributors (drawn by the project owner in ArtCraft; vectorised with craftrules vectorize_tile.py) | MIT OR Apache-2.0 | Contributor-original (see assets/app-icon/README.md) | Linux hicolor theme icon (packaging/linux/ai.storyteller.pdfcraft.desktop); runtime window icon on Windows and Linux (apps/pdfcraft/src/main.rs) |
| `assets/app-icon/hicolor/512x512/apps/ai.storyteller.pdfcraft.png` | PdfCraft app icon, 512 px | PdfCraft contributors (drawn by the project owner in ArtCraft; vectorised with craftrules vectorize_tile.py) | MIT OR Apache-2.0 | Contributor-original (see assets/app-icon/README.md) | Linux hicolor theme icon (packaging/linux/ai.storyteller.pdfcraft.desktop) |
| `assets/app-icon/hicolor/scalable/apps/ai.storyteller.pdfcraft.svg` | PdfCraft app icon (Linux scalable) | PdfCraft contributors (drawn by the project owner in ArtCraft; vectorised with craftrules vectorize_tile.py) | MIT OR Apache-2.0 | Contributor-original (see assets/app-icon/README.md) | Linux hicolor theme icon (packaging/linux/ai.storyteller.pdfcraft.desktop) |
| `assets/app-icon/hicolor/16x16/apps/ai.storyteller.pdfcraft.png` | PdfCraft app icon, 16 px | PdfCraft contributors (drawn by the project owner in ArtCraft) | MIT OR Apache-2.0 | Contributor-original (see assets/app-icon/README.md) | Linux hicolor theme icon (packaging/linux/ai.storyteller.pdfcraft.desktop) |
| `assets/app-icon/hicolor/24x24/apps/ai.storyteller.pdfcraft.png` | PdfCraft app icon, 24 px | PdfCraft contributors (drawn by the project owner in ArtCraft) | MIT OR Apache-2.0 | Contributor-original (see assets/app-icon/README.md) | Linux hicolor theme icon (packaging/linux/ai.storyteller.pdfcraft.desktop) |
| `assets/app-icon/hicolor/32x32/apps/ai.storyteller.pdfcraft.png` | PdfCraft app icon, 32 px | PdfCraft contributors (drawn by the project owner in ArtCraft) | MIT OR Apache-2.0 | Contributor-original (see assets/app-icon/README.md) | Linux hicolor theme icon (packaging/linux/ai.storyteller.pdfcraft.desktop) |
| `assets/app-icon/hicolor/48x48/apps/ai.storyteller.pdfcraft.png` | PdfCraft app icon, 48 px | PdfCraft contributors (drawn by the project owner in ArtCraft) | MIT OR Apache-2.0 | Contributor-original (see assets/app-icon/README.md) | Linux hicolor theme icon (packaging/linux/ai.storyteller.pdfcraft.desktop) |
| `assets/app-icon/hicolor/64x64/apps/ai.storyteller.pdfcraft.png` | PdfCraft app icon, 64 px | PdfCraft contributors (drawn by the project owner in ArtCraft) | MIT OR Apache-2.0 | Contributor-original (see assets/app-icon/README.md) | Linux hicolor theme icon (packaging/linux/ai.storyteller.pdfcraft.desktop) |
| `assets/app-icon/hicolor/128x128/apps/ai.storyteller.pdfcraft.png` | PdfCraft app icon, 128 px | PdfCraft contributors (drawn by the project owner in ArtCraft) | MIT OR Apache-2.0 | Contributor-original (see assets/app-icon/README.md) | Linux hicolor theme icon (packaging/linux/ai.storyteller.pdfcraft.desktop) |
| `assets/app-icon/hicolor/256x256/apps/ai.storyteller.pdfcraft.png` | PdfCraft app icon, 256 px | PdfCraft contributors (drawn by the project owner in ArtCraft) | MIT OR Apache-2.0 | Contributor-original (see assets/app-icon/README.md) | Linux hicolor theme icon (packaging/linux/ai.storyteller.pdfcraft.desktop); runtime window icon on Windows and Linux (apps/pdfcraft/src/main.rs) |
| `assets/app-icon/hicolor/512x512/apps/ai.storyteller.pdfcraft.png` | PdfCraft app icon, 512 px | PdfCraft contributors (drawn by the project owner in ArtCraft) | MIT OR Apache-2.0 | Contributor-original (see assets/app-icon/README.md) | Linux hicolor theme icon (packaging/linux/ai.storyteller.pdfcraft.desktop) |
| `assets/app-icon/hicolor/scalable/apps/ai.storyteller.pdfcraft.svg` | PdfCraft app icon (Linux scalable) | PdfCraft contributors (drawn by the project owner in ArtCraft) | MIT OR Apache-2.0 | Contributor-original (see assets/app-icon/README.md) | Linux hicolor theme icon (packaging/linux/ai.storyteller.pdfcraft.desktop) |
| `docs/images/pdfcraft-bookmarks.png` | PdfCraft screenshot: Bookmarks | PdfCraft contributors (generated by `cargo xtask screenshots`) | MIT OR Apache-2.0 | this repository | README: navigation. Shows only PdfCraft UI, Lucide icons and the showcase PDF built from the [[fetched]] OFL fonts |
| `docs/images/pdfcraft-dark.png` | PdfCraft screenshot: Dark theme | PdfCraft contributors (generated by `cargo xtask screenshots`) | MIT OR Apache-2.0 | this repository | README: themes. Shows only PdfCraft UI, Lucide icons and the showcase PDF built from the [[fetched]] OFL fonts |
| `docs/images/pdfcraft-find.png` | PdfCraft screenshot: Find text | PdfCraft contributors (generated by `cargo xtask screenshots`) | MIT OR Apache-2.0 | this repository | README: search. Shows only PdfCraft UI, Lucide icons and the showcase PDF built from the [[fetched]] OFL fonts |
@@ -269,34 +242,28 @@ Every asset PdfCraft includes, bundles or uses to build its published material,
| `docs/images/pdfcraft-tools.png` | PdfCraft screenshot: All tools | PdfCraft contributors (generated by `cargo xtask screenshots`) | MIT OR Apache-2.0 | this repository | README: tool catalogue. Shows PdfCraft UI, Lucide icons, the showcase PDF built from the [[fetched]] OFL fonts, and the ArtCraft mark (Storyteller trademark from docs/brand/, not covered by this licence) |
| `docs/images/pdfcraft-twoup.png` | PdfCraft screenshot: Two-up reading | PdfCraft contributors (generated by `cargo xtask screenshots`) | MIT OR Apache-2.0 | this repository | README: layouts. Shows only PdfCraft UI, Lucide icons and the showcase PDF built from the [[fetched]] OFL fonts |
| `docs/images/pdfcraft-viewer.png` | PdfCraft screenshot: Viewer with comments | PdfCraft contributors (generated by `cargo xtask screenshots`) | MIT OR Apache-2.0 | this repository | README hero. Shows only PdfCraft UI, Lucide icons and the showcase PDF built from the [[fetched]] OFL fonts |
| `assets/icons/pin.svg` | Lucide icon "pin" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/pin.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/move-right.svg` | Lucide icon "move-right" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/move-right.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/reply.svg` | Lucide icon "reply" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/reply.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/thumbs-up.svg` | Lucide icon "thumbs-up" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/thumbs-up.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/thumbs-down.svg` | Lucide icon "thumbs-down" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/thumbs-down.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/message-square-plus.svg` | Lucide icon "message-square-plus" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/message-square-plus.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/circle-x.svg` | Lucide icon "circle-x" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/circle-x.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/pin.svg` | Lucide icon "pin" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/pin.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/move-right.svg` | Lucide icon "move-right" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/move-right.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/reply.svg` | Lucide icon "reply" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/reply.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/thumbs-up.svg` | Lucide icon "thumbs-up" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/thumbs-up.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/thumbs-down.svg` | Lucide icon "thumbs-down" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/thumbs-down.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/message-square-plus.svg` | Lucide icon "message-square-plus" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/message-square-plus.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/circle-x.svg` | Lucide icon "circle-x" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/circle-x.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `crates/ui-egui/tests/data/form.pdf` | One-page AcroForm test fixture (text, check box, radio group, combo box) | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: hand-written PDF objects, no third-party content | Form-filling UI tests (crates/ui-egui/tests/it/forms.rs, commands.rs) |
| `assets/icons/pentagon.svg` | Lucide icon "pentagon" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/pentagon.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/message-square-quote.svg` | Lucide icon "message-square-quote" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/message-square-quote.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/pentagon.svg` | Lucide icon "pentagon" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/pentagon.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/message-square-quote.svg` | Lucide icon "message-square-quote" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/message-square-quote.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `crates/sign/tests/data/openssl-signed.pdf` | One-page PDF signed with OpenSSL CMS (adbe.pkcs7.detached) by the RSA test key | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: hand-written PDF objects; signature made with `openssl cms -sign` over its byte ranges (see crates/sign/tests/data/README.md) | Signature validation tests (crates/sign/tests/it/pdf.rs): a signature PdfCraft did not make |
| `assets/icons/clipboard-paste.svg` | Lucide icon "clipboard-paste" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/clipboard-paste.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/clipboard-paste.svg` | Lucide icon "clipboard-paste" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/clipboard-paste.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/fonts/DancingScript.ttf` | Dancing Script (variable) | The Dancing Script Project Authors (Pablo Impallari) | OFL-1.1 | https://github.com/google/fonts/blob/9710da1eacb3be272583c3224dcb70f9da6eadbb/ofl/dancingscript/DancingScript%5Bwght%5D.ttf | Fill & Sign typed signatures and initials: the typed name's glyph outlines, drawn as filled paths (the font file itself is not embedded in PDFs) |
| `packaging/macos/dmg/background.svg` | PdfCraft macOS DMG window background | @XusBadia | MIT OR Apache-2.0 | Original work for this repository, derived from the PdfCraft app icon (assets/app-icon/pdfcraft.svg, referenced via an SVG image element, not copied) | Finder window of the macOS DMG; rendered to background.tiff by packaging/macos/dmg/generate.py |
| `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; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed | Vietnamese UI strings, compiled in by crates/ui-egui/src/i18n.rs |
| `crates/ui-egui/src/i18n/sl.tsv` | Slovene interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-18 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed | Slovene UI strings, compiled in by crates/ui-egui/src/i18n.rs |
| `assets/icons/monitor.svg` | Lucide icon "monitor" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | 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 |
| `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; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed | Norwegian Bokmål UI strings, compiled in by crates/ui-egui/src/i18n.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; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed | Albanian UI strings, compiled in by crates/ui-egui/src/i18n.rs |
| `crates/ui-egui/src/i18n/th.tsv` | Thai interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed | Thai UI strings, compiled in by crates/ui-egui/src/i18n.rs |
| `crates/ui-egui/src/i18n/ca.tsv` | Catalan interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, written from their meaning; no proprietary localisation resources; 2026-10-22 page-gap labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 text-field-table labels are contributor-original AI-assisted translations from English, not separately native-reviewed; 2026-10-22 secured-document notice labels are contributor-original AI-assisted translations from English, not separately native-reviewed; the 2026-10-22 reply-count label is an AI-assisted translation from English, not separately native-reviewed | Catalan UI strings, compiled in by crates/ui-egui/src/i18n.rs |
| `assets/icons/superscript.svg` | Lucide icon "superscript" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | 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 AND MIT | 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 AND MIT | 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 AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/move-horizontal.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
## Compiled in through dependencies (6)
@@ -338,10 +305,11 @@ Fonts are fetched by `cargo xtask demo-pdf` into `target/demo-fonts/`, OCR model
| `text-detection.onnx` | Ocrs text detection model | Robert Knight (ocrs-models; trained on HierText, CC-BY-SA-4.0) | CC-BY-SA-4.0 | https://github.com/robertknight/ocrs/blob/0c826441362a701c55560fefc17bf356b6d1037e/ocrs/examples/download-models.sh (author-published ONNX models; model card: https://huggingface.co/robertknight/ocrs/blob/df0edd170279ab971b53e094c627255a87e1a503/README.md, cc-by-sa-4.0) | Scan & OCR: finds words on page images (cargo xtask models) |
| `text-recognition.onnx` | Ocrs text recognition model | Robert Knight (ocrs-models; trained on HierText, CC-BY-SA-4.0) | CC-BY-SA-4.0 | https://github.com/robertknight/ocrs/blob/0c826441362a701c55560fefc17bf356b6d1037e/ocrs/examples/download-models.sh (author-published ONNX models; model card: https://huggingface.co/robertknight/ocrs/blob/df0edd170279ab971b53e094c627255a87e1a503/README.md, cc-by-sa-4.0) | Scan & OCR: reads the words it finds (cargo xtask models) |
## Optional build inputs (1)
## Optional build inputs (2)
Not in this repository and never downloaded by it: compiled in only when the build sets the option (official releases do). Each input attributes its own files.
| Input | Option | Title | Author | Licence | Source | Attribution | Used for |
|---|---|---|---|---|---|---|---|
| `craft-i18n` | `CRAFT_I18N_DIR` | Interface translations: the craft-i18n catalogs (locales/<code>/common.tsv and pdfcraft.tsv) of the 34 languages PdfCraft offers besides English | The craft-i18n translators, including every translator of PdfCraft's former in-repo catalogs (crates/ui-egui/src/i18n/*.tsv, migrated at pdfcraft@ecdd1e6) | MIT OR Apache-2.0 | https://github.com/storytold/craft-i18n (pinned by commit in craft-i18n.rev, which CI, releases and the flatpak manifests read) | https://github.com/storytold/craft-i18n/blob/main/ATTRIBUTION.md | Interface text in languages other than English, embedded by crates/ui-egui/build.rs and looked up through craft-libs' craft-i18n crate; a build without CRAFT_I18N_DIR is English only. Clean-room translations from PdfCraft's English interface labels |
| `craft-fonts` | `CRAFT_FONTS_DIR` | Japanese fonts: BIZ UDPGothic (Regular, Bold), Shippori Mincho, BIZ UDMincho; native Simplified Chinese font: LXGW WenKai Lite; Arabic font: Noto Sans Arabic | The BIZ UDGothic and BIZ UDMincho Project Authors (Morisawa Inc.), The Shippori Mincho Project Authors (FONTDASU), LXGW and the original Klee Project Authors / Fontworks (LXGW WenKai Lite), The Noto Project Authors (Noto Sans Arabic) | OFL-1.1 | https://github.com/storytold/craft-fonts (pinned by commit in .github/workflows/release.yml and .github/workflows/ci.yml); LXGW WenKai Lite from https://github.com/lxgw/LxgwWenKai-Lite/releases/tag/v1.530 (commit b712c83d98acf977bacfb7fb010207802808bda9) | https://github.com/storytold/craft-fonts/blob/main/ATTRIBUTION.md | Japanese fallback in the interface (BIZ UDPGothic first) and Japanese glyphs in edited PDF text (Shippori Mincho); Simplified Chinese interface fallback on native builds only (LXGW WenKai Lite Regular, font SHA-256 f799a538a3355877e597a0ae04050e897932c9ae7689eb9227c2953c5dd549ea, OFL SHA-256 0333a85fe077b6849f8e417acc44e8bd879442ceb681e271acf93e2d57fd4e2e, read from fonts/simplified-chinese-manifest.txt and never embedded on wasm); Arabic interface text, file names and document titles (Noto Sans Arabic); the web build embeds BIZ UDPGothic Regular and the pinned small Arabic, Hebrew, Thai and Devanagari faces; the selected craft-fonts revision contains no Telugu face. Other non-Japanese CJK faces retain the general 4 MiB cap; the reviewed native-only LXGW fallback has a separate 16 MiB cap. Open-source OFL releases are permitted under current AGENTS.md §1.1 |
+227 -545
View File
File diff suppressed because it is too large. Load diff
+4 -4
View File
@@ -4,7 +4,7 @@ PdfCraft is a clean-room, open-source, Rust-native PDF application targeting Ado
## Start every session here
1. Read `plan/STATUS.md`: the current milestone, the next unchecked task and any blockers. `ROADMAP.md` is the one-page summary (stage, numbers, progress log) and `docs/roadmap.md` the milestone table; at the end of every session update the milestone row and add a line to the ROADMAP.md progress log.
- Read `docs/gaps.md` (the ranked gaps: Acrobat interop, the open-issue backlog, the renderer and a fidelity harness, editing existing content, Pro workflows, 1.0 polish) and `docs/target-app-parity.md` (the numbers and how they are measured) before choosing work. Prefer the gaps over new P2/P3 features, and keep both documents true when things change (`docs/` progress docs follow craftrules `standards/progress-docs.md`: status line, revision history).
- Read `docs/gaps.md` (the ranked gaps: Acrobat interop, the open-issue backlog, the renderer and a fidelity harness, editing existing content, Pro workflows, 1.0 polish) and `docs/target-app-parity.md` (the numbers and how they are measured) before choosing work. Prefer the gaps over new P2/P3 features, and keep both documents true when things change (`docs/` progress docs carry a status line and a revision history).
- "Shipped" in `parity/` means "exists and tested", not "as good as Acrobat". Don't mark a feature shipped on a generic test, and say in its notes what is still missing.
2. Read that task in `plan/execution-plan.md` §3, the relevant section of `plan/architecture.md`, and the README of the crate you're touching.
3. Follow the **autonomous operation protocol** in `plan/execution-plan.md` §7 (orient → plan → implement + test → verify → record → commit). Don't stop to ask unless §7 lists the decision as the user's.
@@ -13,7 +13,7 @@ PdfCraft is a clean-room, open-source, Rust-native PDF application targeting Ado
## Non-negotiables
- **Assets: read `AGENTS.md` §1 before adding or showing any icon, image, font or document.** No assets from Adobe products, ever. Only openly licensed or contributor-original assets are allowed, each with an entry in `ATTRIBUTION.toml`. `cargo xtask assets` enforces this. `AGENTS.md` overrides this file.
- **Fonts live in [storytold/craft-fonts](https://github.com/storytold/craft-fonts).** Never commit font files here (`AGENTS.md` §1.4; team members: [craftrules `standards/fonts.md`](https://github.com/storytold/craftrules/blob/main/standards/fonts.md), internal). It is the optional build input `CRAFT_FONTS_DIR`: `git clone https://github.com/storytold/craft-fonts ../craft-fonts && CRAFT_FONTS_DIR=../craft-fonts cargo test --workspace` embeds the Japanese fonts (UI fallback, Japanese text in edited PDFs) and runs their tests, which otherwise skip. Code using `pdfcraft_fonts::CRAFT_FONTS` must work when it is empty.
- **Fonts live in [storytold/craft-fonts](https://github.com/storytold/craft-fonts).** Never commit font files here (`AGENTS.md` §1.4). It is the optional build input `CRAFT_FONTS_DIR`: `git clone https://github.com/storytold/craft-fonts ../craft-fonts && CRAFT_FONTS_DIR=../craft-fonts cargo test --workspace` embeds the Japanese fonts (UI fallback, Japanese text in edited PDFs) and runs their tests, which otherwise skip. Code using `pdfcraft_fonts::CRAFT_FONTS` must work when it is empty.
- **Clean-room.**
- Never read, disassemble or copy anything inside the Acrobat bundle (names and listings only). **Never open `Contents/Resources/JavaScripts/`.**
- Behaviour comes from public docs, specs (ISO 32000-2, the Arlington model) and black-box observation (`plan/acrobat/`).
@@ -23,7 +23,7 @@ PdfCraft is a clean-room, open-source, Rust-native PDF application targeting Ado
- **Layering.** Nothing below L7 depends on egui/winit/eframe/rfd (`plan/architecture.md` §3). `cos`/`filters`/`crypt`/`arlington` stay standalone.
- **Page input.** Page modules read `PagePointer` (`crates/ui-egui/src/page_pointer.rs`), never egui's raw pointer state (`hover_pos`, `interact_pos`, `latest_pos`, `press_origin`, button reads); `page_pointer::tests::page_modules_read_the_pointer_only_through_page_pointer` enforces it.
- **Page cursor.** Page modules claim the cursor for what is under the pointer (`view.cursor.claim(Layer::…, icon)`, `crates/ui-egui/src/canvas/page_cursor.rs`), never set it (`set_cursor_icon`, `cursor_icon =`, `on_hover_cursor`); `document_area` sets it once, from the claim on the highest layer the active tool reaches. `page_pointer::tests::page_modules_claim_the_cursor_and_never_set_it` enforces it.
- **Page presses.** A page module decides what of its own is under a point in one hit test, which returns a `Hit` (owner, layer, cursor, tip; `crates/ui-egui/src/canvas/page_router.rs`) and gives its cursor, its tip and its press. It acts on a press only when the router says the press is its own (`view.router.owner(page)`), never by testing the press point again or by asking another module whether it wants it. Escape cancels any press the pages hold (`cancel_on_escape`), and that press is ignored until the button is up. `page_modules_take_presses_from_the_router_without_repeating_hit_tests` guards the centralized hit calls and captured-owner handlers; runtime routing tests cover gesture behavior.
- **Page presses.** A page module decides what of its own is under a point in one hit test, which returns a `Hit` (owner, layer, cursor, tip; `crates/ui-egui/src/canvas/page_router.rs`) and gives its cursor, its tip and its press. It acts on a press only when the press is its own or, for the active tool, nobody's: the page view tells it which (`PagePress`: its own, nobody's, or another page's), and it never tests the press point again or asks another module whether it wants it. Escape cancels any press the pages hold (`cancel_on_escape`), and that press is ignored until the button is up. `page_pointer::tests::page_modules_act_on_a_press_only_through_the_router` enforces it.
- **Fidelity.** The PDF object graph is the model. Preserve unknown data. Saves are incremental unless a full rewrite is required. Never silently drop or repair data without recording it.
- **Never panic.** Every PDF, script, MCP call, settings file and keystroke is untrusted input, and none of it may crash the app or lose the user's work. This outranks feature work. Return `Result` (the crate's error enum) and propagate with `?`, or fall back leniently and record it. In non-test code:
- No `unwrap`/`expect`/`panic!`/`unreachable!`/`todo!` unless it is provably infallible, with a comment saying why.
@@ -32,7 +32,7 @@ PdfCraft is a clean-room, open-source, Rust-native PDF application targeting Ado
- Cap allocations sized by input, and bound recursion with depth limits or seen-sets.
- Handle lock poisoning.
- No `unsafe` (`unsafe_code = "forbid"`).
- Every crash fix gets a synthetic regression test. See `AGENTS.md` §4 (and, for team members, the internal `craftrules/standards/never-crash.md`).
- Every crash fix gets a synthetic regression test. See `AGENTS.md` §4.
- **Rust only** in the product and build (`xtask`). No handwritten JS/TS.
- **Time goes through `chrono`** (workspace dependency). Never hand-roll UTC/calendar conversion (days-to-date algorithms, leap-year math); a crate owns only its output format string. The one exception is range extension: past the years chrono can represent, shift the date by whole 400-year Gregorian cycles (146,097 days, after which the calendar repeats), let chrono compute the month and day, and add the cycles back to the year (splitting seconds into hours, minutes and seconds is plain arithmetic).
- **Review every update as you make it, at four zooms.** Not an end-of-task pass — a per-update habit, so a defect never gets built on. **Clause:** checked arithmetic, `get()` not `[i]`, char-boundary slicing, the right error through `?`, `<` against `<=`, the 1-based/0-based seam, capped allocations. **Function:** is it total — name an input that panics; walk empty, zero, max, malformed, cyclic; is the return type honest. **File/module:** two sources of truth, dead or duplicated code, is the public surface still smallest and the doc comment still true. **Project:** layering, wasm, undo/redo, save fidelity, encryption and permissions, a matching `automation` tool or registry entry, and whether a `parity/` status or note just became untrue. Scale the zoom to the change, and fix what a level turns up before widening.
Generated
+74 -47
View File
@@ -1178,17 +1178,17 @@ dependencies = [
[[package]]
name = "craft-docpath"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545#e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545"
source = "git+https://github.com/storytold/craft-libs?rev=787a7a0f972fd1d7a7618fdbeca3a5267a0407ff#787a7a0f972fd1d7a7618fdbeca3a5267a0407ff"
[[package]]
name = "craft-fonts-build"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545#e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545"
source = "git+https://github.com/storytold/craft-libs?rev=787a7a0f972fd1d7a7618fdbeca3a5267a0407ff#787a7a0f972fd1d7a7618fdbeca3a5267a0407ff"
[[package]]
name = "craft-i18n"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545#e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545"
source = "git+https://github.com/storytold/craft-libs?rev=787a7a0f972fd1d7a7618fdbeca3a5267a0407ff#787a7a0f972fd1d7a7618fdbeca3a5267a0407ff"
dependencies = [
"fixed_decimal",
"icu_decimal",
@@ -1211,7 +1211,7 @@ dependencies = [
[[package]]
name = "craft-keymap"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545#e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545"
source = "git+https://github.com/storytold/craft-libs?rev=787a7a0f972fd1d7a7618fdbeca3a5267a0407ff#787a7a0f972fd1d7a7618fdbeca3a5267a0407ff"
dependencies = [
"egui",
"serde",
@@ -1221,7 +1221,7 @@ dependencies = [
[[package]]
name = "craft-menu"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545#e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545"
source = "git+https://github.com/storytold/craft-libs?rev=787a7a0f972fd1d7a7618fdbeca3a5267a0407ff#787a7a0f972fd1d7a7618fdbeca3a5267a0407ff"
dependencies = [
"craft-keymap",
"craft-quit",
@@ -1234,9 +1234,10 @@ dependencies = [
[[package]]
name = "craft-print"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545#e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545"
source = "git+https://github.com/storytold/craft-libs?rev=787a7a0f972fd1d7a7618fdbeca3a5267a0407ff#787a7a0f972fd1d7a7618fdbeca3a5267a0407ff"
dependencies = [
"craft-winprint-gdi",
"log",
"miniz_oxide 0.9.1",
"roxmltree 0.21.2",
"tempfile",
@@ -1247,7 +1248,7 @@ dependencies = [
[[package]]
name = "craft-quit"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545#e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545"
source = "git+https://github.com/storytold/craft-libs?rev=787a7a0f972fd1d7a7618fdbeca3a5267a0407ff#787a7a0f972fd1d7a7618fdbeca3a5267a0407ff"
dependencies = [
"dispatch2",
"egui",
@@ -1258,7 +1259,7 @@ dependencies = [
[[package]]
name = "craft-ui"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545#e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545"
source = "git+https://github.com/storytold/craft-libs?rev=787a7a0f972fd1d7a7618fdbeca3a5267a0407ff#787a7a0f972fd1d7a7618fdbeca3a5267a0407ff"
dependencies = [
"craft-fonts-build",
"craft-i18n",
@@ -1279,7 +1280,7 @@ dependencies = [
[[package]]
name = "craft-update"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=04aa1703b32d299e54f78fcde4182f2b393a9116#04aa1703b32d299e54f78fcde4182f2b393a9116"
source = "git+https://github.com/storytold/craft-libs?rev=787a7a0f972fd1d7a7618fdbeca3a5267a0407ff#787a7a0f972fd1d7a7618fdbeca3a5267a0407ff"
dependencies = [
"chrono",
"dunce",
@@ -4207,7 +4208,7 @@ dependencies = [
[[package]]
name = "pdfcraft"
version = "0.15.0"
version = "0.18.1"
dependencies = [
"chrono",
"craft-update",
@@ -4231,7 +4232,7 @@ dependencies = [
[[package]]
name = "pdfcraft-a11y"
version = "0.15.0"
version = "0.18.1"
dependencies = [
"pdfcraft-content",
"pdfcraft-cos",
@@ -4243,7 +4244,7 @@ dependencies = [
[[package]]
name = "pdfcraft-annot"
version = "0.15.0"
version = "0.18.1"
dependencies = [
"hayro-syntax",
"pdfcraft-cos",
@@ -4254,7 +4255,7 @@ dependencies = [
[[package]]
name = "pdfcraft-audit"
version = "0.15.0"
version = "0.18.1"
dependencies = [
"pdfcraft-content",
"pdfcraft-cos",
@@ -4265,7 +4266,7 @@ dependencies = [
[[package]]
name = "pdfcraft-automation"
version = "0.15.0"
version = "0.18.1"
dependencies = [
"base64 0.23.1",
"flate2",
@@ -4276,6 +4277,8 @@ dependencies = [
"pdfcraft-model",
"pdfcraft-organize",
"pdfcraft-platform",
"pdfcraft-prc",
"pdfcraft-prc-render",
"pdfcraft-render",
"pdfcraft-xfa",
"png 0.18.1",
@@ -4287,7 +4290,7 @@ dependencies = [
[[package]]
name = "pdfcraft-cli"
version = "0.15.0"
version = "0.18.1"
dependencies = [
"base64 0.23.1",
"pdfcraft-audit",
@@ -4305,11 +4308,11 @@ dependencies = [
[[package]]
name = "pdfcraft-compare"
version = "0.15.0"
version = "0.18.1"
[[package]]
name = "pdfcraft-content"
version = "0.15.0"
version = "0.18.1"
dependencies = [
"hayro-syntax",
"pdfcraft-cos",
@@ -4317,7 +4320,7 @@ dependencies = [
[[package]]
name = "pdfcraft-cos"
version = "0.15.0"
version = "0.18.1"
dependencies = [
"chrono",
"hayro-syntax",
@@ -4332,11 +4335,10 @@ dependencies = [
[[package]]
name = "pdfcraft-create"
version = "0.15.0"
version = "0.18.1"
dependencies = [
"encoding_rs",
"hayro-ccitt",
"hayro-jbig2",
"hayro-syntax",
"image",
"pdfcraft-cos",
@@ -4352,7 +4354,7 @@ dependencies = [
[[package]]
name = "pdfcraft-crypt"
version = "0.15.0"
version = "0.18.1"
dependencies = [
"aes",
"md-5",
@@ -4364,7 +4366,7 @@ dependencies = [
[[package]]
name = "pdfcraft-edit"
version = "0.15.0"
version = "0.18.1"
dependencies = [
"hayro-syntax",
"kurbo 0.13.1",
@@ -4373,6 +4375,8 @@ dependencies = [
"pdfcraft-cos",
"pdfcraft-fonts",
"pdfcraft-model",
"pdfcraft-render",
"proptest",
"sha2 0.11.1",
"thiserror 2.0.21",
"unicode-bidi",
@@ -4380,7 +4384,7 @@ dependencies = [
[[package]]
name = "pdfcraft-engine"
version = "0.15.0"
version = "0.18.1"
dependencies = [
"chrono",
"craft-docpath",
@@ -4392,10 +4396,12 @@ dependencies = [
"pdfcraft-annot",
"pdfcraft-audit",
"pdfcraft-compare",
"pdfcraft-content",
"pdfcraft-cos",
"pdfcraft-create",
"pdfcraft-edit",
"pdfcraft-export",
"pdfcraft-filters",
"pdfcraft-fonts",
"pdfcraft-forms",
"pdfcraft-geom",
@@ -4422,14 +4428,14 @@ dependencies = [
[[package]]
name = "pdfcraft-export"
version = "0.15.0"
version = "0.18.1"
dependencies = [
"flate2",
]
[[package]]
name = "pdfcraft-filters"
version = "0.15.0"
version = "0.18.1"
dependencies = [
"fax",
"flate2",
@@ -4442,7 +4448,7 @@ dependencies = [
[[package]]
name = "pdfcraft-fonts"
version = "0.15.0"
version = "0.18.1"
dependencies = [
"harfrust",
"pdfcraft-cos",
@@ -4452,7 +4458,7 @@ dependencies = [
[[package]]
name = "pdfcraft-forms"
version = "0.15.0"
version = "0.18.1"
dependencies = [
"hayro-syntax",
"pdfcraft-content",
@@ -4465,11 +4471,11 @@ dependencies = [
[[package]]
name = "pdfcraft-geom"
version = "0.15.0"
version = "0.18.1"
[[package]]
name = "pdfcraft-js"
version = "0.15.0"
version = "0.18.1"
dependencies = [
"boa_engine",
"chrono",
@@ -4477,7 +4483,7 @@ dependencies = [
[[package]]
name = "pdfcraft-measure"
version = "0.15.0"
version = "0.18.1"
dependencies = [
"pdfcraft-annot",
"pdfcraft-content",
@@ -4490,14 +4496,14 @@ dependencies = [
[[package]]
name = "pdfcraft-model"
version = "0.15.0"
version = "0.18.1"
dependencies = [
"pdfcraft-cos",
]
[[package]]
name = "pdfcraft-ocr"
version = "0.15.0"
version = "0.18.1"
dependencies = [
"ocrs",
"pdfcraft-fonts",
@@ -4508,7 +4514,7 @@ dependencies = [
[[package]]
name = "pdfcraft-optimize"
version = "0.15.0"
version = "0.18.1"
dependencies = [
"image",
"pdfcraft-annot",
@@ -4524,11 +4530,11 @@ dependencies = [
[[package]]
name = "pdfcraft-oracle"
version = "0.15.0"
version = "0.18.1"
[[package]]
name = "pdfcraft-organize"
version = "0.15.0"
version = "0.18.1"
dependencies = [
"hayro-syntax",
"pdfcraft-content",
@@ -4539,7 +4545,7 @@ dependencies = [
[[package]]
name = "pdfcraft-platform"
version = "0.15.0"
version = "0.18.1"
dependencies = [
"async-channel",
"futures-lite",
@@ -4547,9 +4553,27 @@ dependencies = [
"zbus",
]
[[package]]
name = "pdfcraft-prc"
version = "0.18.1"
dependencies = [
"flate2",
"proptest",
"thiserror 2.0.21",
]
[[package]]
name = "pdfcraft-prc-render"
version = "0.18.1"
dependencies = [
"flate2",
"pdfcraft-prc",
"thiserror 2.0.21",
]
[[package]]
name = "pdfcraft-preflight"
version = "0.15.0"
version = "0.18.1"
dependencies = [
"flate2",
"pdfcraft-content",
@@ -4560,7 +4584,7 @@ dependencies = [
[[package]]
name = "pdfcraft-print"
version = "0.15.0"
version = "0.18.1"
dependencies = [
"craft-print",
"pdfcraft-content",
@@ -4572,7 +4596,7 @@ dependencies = [
[[package]]
name = "pdfcraft-redact"
version = "0.15.0"
version = "0.18.1"
dependencies = [
"pdfcraft-annot",
"pdfcraft-content",
@@ -4589,7 +4613,7 @@ dependencies = [
[[package]]
name = "pdfcraft-render"
version = "0.15.0"
version = "0.18.1"
dependencies = [
"bytemuck",
"flate2",
@@ -4608,7 +4632,7 @@ dependencies = [
[[package]]
name = "pdfcraft-sign"
version = "0.15.0"
version = "0.18.1"
dependencies = [
"aes",
"aws-lc-rs",
@@ -4644,17 +4668,18 @@ dependencies = [
[[package]]
name = "pdfcraft-testkit"
version = "0.15.0"
version = "0.18.1"
[[package]]
name = "pdfcraft-ui-egui"
version = "0.15.0"
version = "0.18.1"
dependencies = [
"arboard",
"base64 0.23.1",
"block2 0.6.2",
"bytemuck",
"chrono",
"craft-i18n",
"craft-keymap",
"craft-menu",
"craft-quit",
@@ -4672,6 +4697,7 @@ dependencies = [
"objc2 0.6.5",
"objc2-app-kit 0.3.2",
"objc2-foundation 0.3.2",
"pdfcraft-content",
"pdfcraft-cos",
"pdfcraft-engine",
"pdfcraft-fonts",
@@ -4682,6 +4708,7 @@ dependencies = [
"plist",
"png 0.18.1",
"pollster 1.0.1",
"proptest",
"rfd",
"rustix 1.1.5",
"serde",
@@ -4700,7 +4727,7 @@ dependencies = [
[[package]]
name = "pdfcraft-web"
version = "0.15.0"
version = "0.18.1"
dependencies = [
"eframe",
"egui",
@@ -4712,7 +4739,7 @@ dependencies = [
[[package]]
name = "pdfcraft-xfa"
version = "0.15.0"
version = "0.18.1"
dependencies = [
"base64 0.23.1",
"image",
@@ -4726,7 +4753,7 @@ dependencies = [
[[package]]
name = "pdfcraft-xfdf"
version = "0.15.0"
version = "0.18.1"
dependencies = [
"pdfcraft-annot",
"pdfcraft-cos",
@@ -6765,7 +6792,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"
dependencies = [
"fastrand",
"getrandom 0.3.4",
"getrandom 0.4.3",
"once_cell",
"rustix 1.1.5",
"windows-sys 0.61.2",
+47 -41
View File
@@ -5,7 +5,7 @@ exclude = ["vendor"]
default-members = ["crates/*", "apps/pdfcraft", "apps/pdfcraft-cli", "xtask"]
[workspace.package]
version = "0.15.0"
version = "0.18.1"
edition = "2024"
license = "MIT OR Apache-2.0"
rust-version = "1.95"
@@ -13,52 +13,58 @@ 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 = "e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545", features = ["serde"] }
craft-ui = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "787a7a0f972fd1d7a7618fdbeca3a5267a0407ff", 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 = "e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545" }
craft-quit = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "787a7a0f972fd1d7a7618fdbeca3a5267a0407ff" }
# One menu definition for the native macOS menu bar and the in-window bar elsewhere.
craft-menu = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545" }
craft-keymap = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545", default-features = false }
craft-menu = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "787a7a0f972fd1d7a7618fdbeca3a5267a0407ff" }
craft-keymap = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "787a7a0f972fd1d7a7618fdbeca3a5267a0407ff", default-features = false }
# Interface translations: lookup, fallback, CLDR plurals and language names over the craft-i18n
# catalogs that `crates/ui-egui/build.rs` embeds from `CRAFT_I18N_DIR` (storytold/craft-i18n, at
# the commit in `craft-i18n.rev`). Already in the tree through craft-ui.
craft-i18n = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "787a7a0f972fd1d7a7618fdbeca3a5267a0407ff" }
# Shared system spooler; document composition remains in pdfcraft-print.
craft-print = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545" }
craft-print = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "787a7a0f972fd1d7a7618fdbeca3a5267a0407ff" }
# 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 = "e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545" }
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "787a7a0f972fd1d7a7618fdbeca3a5267a0407ff" }
# craft-update: app-specific pretend versions apply to startup and manual checks.
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "04aa1703b32d299e54f78fcde4182f2b393a9116", features = ["egui"] }
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "787a7a0f972fd1d7a7618fdbeca3a5267a0407ff", features = ["egui"] }
# internal
pdfcraft-geom = { path = "crates/geom", version = "0.15.0" }
pdfcraft-filters = { path = "crates/filters", version = "0.15.0" }
pdfcraft-cos = { path = "crates/cos", version = "0.15.0" }
pdfcraft-crypt = { path = "crates/crypt", version = "0.15.0" }
pdfcraft-organize = { path = "crates/organize", version = "0.15.0" }
pdfcraft-measure = { path = "crates/measure", version = "0.15.0" }
pdfcraft-annot = { path = "crates/annot", version = "0.15.0" }
pdfcraft-audit = { path = "crates/audit", version = "0.15.0" }
pdfcraft-fonts = { path = "crates/fonts", version = "0.15.0" }
pdfcraft-model = { path = "crates/model", version = "0.15.0" }
pdfcraft-content = { path = "crates/content", version = "0.15.0" }
pdfcraft-redact = { path = "crates/redact", version = "0.15.0" }
pdfcraft-print = { path = "crates/print", version = "0.15.0" }
pdfcraft-xfdf = { path = "crates/xfdf", version = "0.15.0" }
pdfcraft-sign = { path = "crates/sign", version = "0.15.0" }
pdfcraft-optimize = { path = "crates/optimize", version = "0.15.0" }
pdfcraft-a11y = { path = "crates/a11y", version = "0.15.0" }
pdfcraft-oracle = { path = "crates/oracle", version = "0.15.0" }
pdfcraft-testkit = { path = "crates/testkit", version = "0.15.0" }
pdfcraft-ocr = { path = "crates/ocr", version = "0.15.0" }
pdfcraft-js = { path = "crates/js", version = "0.15.0" }
pdfcraft-compare = { path = "crates/compare", version = "0.15.0" }
pdfcraft-preflight = { path = "crates/preflight", version = "0.15.0" }
pdfcraft-export = { path = "crates/export", version = "0.15.0" }
pdfcraft-edit = { path = "crates/edit", version = "0.15.0" }
pdfcraft-create = { path = "crates/create", version = "0.15.0" }
pdfcraft-forms = { path = "crates/forms", version = "0.15.0" }
pdfcraft-xfa = { path = "crates/xfa", version = "0.15.0" }
pdfcraft-render = { path = "crates/render", version = "0.15.0" }
pdfcraft-engine = { path = "crates/engine", version = "0.15.0" }
pdfcraft-platform = { path = "crates/platform", version = "0.15.0" }
pdfcraft-ui-egui = { path = "crates/ui-egui", version = "0.15.0" }
pdfcraft-automation = { path = "crates/automation", version = "0.15.0", default-features = false }
pdfcraft-geom = { path = "crates/geom", version = "0.18.1" }
pdfcraft-filters = { path = "crates/filters", version = "0.18.1" }
pdfcraft-cos = { path = "crates/cos", version = "0.18.1" }
pdfcraft-crypt = { path = "crates/crypt", version = "0.18.1" }
pdfcraft-organize = { path = "crates/organize", version = "0.18.1" }
pdfcraft-measure = { path = "crates/measure", version = "0.18.1" }
pdfcraft-annot = { path = "crates/annot", version = "0.18.1" }
pdfcraft-audit = { path = "crates/audit", version = "0.18.1" }
pdfcraft-fonts = { path = "crates/fonts", version = "0.18.1" }
pdfcraft-model = { path = "crates/model", version = "0.18.1" }
pdfcraft-content = { path = "crates/content", version = "0.18.1" }
pdfcraft-redact = { path = "crates/redact", version = "0.18.1" }
pdfcraft-print = { path = "crates/print", version = "0.18.1" }
pdfcraft-xfdf = { path = "crates/xfdf", version = "0.18.1" }
pdfcraft-sign = { path = "crates/sign", version = "0.18.1" }
pdfcraft-optimize = { path = "crates/optimize", version = "0.18.1" }
pdfcraft-a11y = { path = "crates/a11y", version = "0.18.1" }
pdfcraft-oracle = { path = "crates/oracle", version = "0.18.1" }
pdfcraft-testkit = { path = "crates/testkit", version = "0.18.1" }
pdfcraft-ocr = { path = "crates/ocr", version = "0.18.1" }
pdfcraft-js = { path = "crates/js", version = "0.18.1" }
pdfcraft-compare = { path = "crates/compare", version = "0.18.1" }
pdfcraft-preflight = { path = "crates/preflight", version = "0.18.1" }
pdfcraft-export = { path = "crates/export", version = "0.18.1" }
pdfcraft-edit = { path = "crates/edit", version = "0.18.1" }
pdfcraft-create = { path = "crates/create", version = "0.18.1" }
pdfcraft-forms = { path = "crates/forms", version = "0.18.1" }
pdfcraft-xfa = { path = "crates/xfa", version = "0.18.1" }
pdfcraft-render = { path = "crates/render", version = "0.18.1" }
pdfcraft-engine = { path = "crates/engine", version = "0.18.1" }
pdfcraft-platform = { path = "crates/platform", version = "0.18.1" }
pdfcraft-ui-egui = { path = "crates/ui-egui", version = "0.18.1" }
pdfcraft-automation = { path = "crates/automation", version = "0.18.1", default-features = false }
pdfcraft-prc = { path = "crates/prc", version = "0.18.1" }
pdfcraft-prc-render = { path = "crates/prc-render", version = "0.18.1" }
# pdf
hayro = "0.7.1"
+166
View File
@@ -0,0 +1,166 @@
# Stage 1 source documents only. Destinations are logical names, not packaging instructions.
# licences lists audited full-text identifiers; omission grants no bundle applicability.
[[document]]
source = "LICENSE-APACHE"
licences = ["Apache-2.0"]
destination = "LICENSE-APACHE"
sha256 = "0d542e0c8804e39aa7f37eb00da5a762149dc682d7829451287e11b938e94594"
[[document]]
source = "LICENSE-MIT"
licences = ["MIT"]
destination = "LICENSE-MIT"
sha256 = "cd7032ea33b71427f188e34ffb4aee9d6868a57fd196037c5c8b2be03a2a0352"
[[document]]
source = "NOTICE"
destination = "NOTICE"
sha256 = "9f854f730719af962cd840529324d089e05e68a30bd245c50e33f96e009b4314"
[[document]]
source = "assets/app-icon/LICENSE-document.txt"
destination = "assets/app-icon/LICENSE-document.txt"
sha256 = "64a3137e3d5cc41e5b78d2ad8dd9ddddd6588283f9f7b3128aa6a8a50852fb9a"
[[document]]
source = "assets/app-icon/LICENSE.txt"
destination = "assets/app-icon/LICENSE.txt"
sha256 = "b768acafe6cbad8247eedf86b5b5381feefcd4ee0f8c7808b86811bc687cf37b"
[[document]]
source = "assets/fonts/OFL-DancingScript.txt"
destination = "assets/fonts/OFL-DancingScript.txt"
sha256 = "6f090277c00af96651ce6dbcc38ff1591047a3bffef486e80b6a32e8276a8201"
[[document]]
source = "assets/fonts/OFL-Inter.txt"
destination = "assets/fonts/OFL-Inter.txt"
sha256 = "262481e844521b326f5ecd053e59b98c8b2da78c8ee1bdbb6e8174305e54935a"
[[document]]
source = "assets/fonts/OFL-JetBrainsMono.txt"
destination = "assets/fonts/OFL-JetBrainsMono.txt"
sha256 = "a76abf002c49097d146e86740a3105a5d00450b1592e820a1109a8c5680cd697"
[[document]]
source = "assets/icons/LICENSE-lucide.txt"
destination = "assets/icons/LICENSE-lucide.txt"
sha256 = "b495047bd93a9b06913511076f504daba17d5bbeb3e0650f3bb53a4220329c57"
[[document]]
source = "docs/brand/LICENSE-brand.txt"
destination = "docs/brand/LICENSE-brand.txt"
sha256 = "0f33f48e7a96cd359d4e4e5b11424b13cebeb59cc70c77928186695e4173585c"
[[document]]
source = "licenses/CMap-LICENSE.txt"
licences = ["BSD-3-Clause"]
destination = "licenses/CMap-LICENSE.txt"
sha256 = "742665db9c8e1bc72603c6d319ca3e90b83bd6d95202f0cd4ef11068a07a9c29"
origin = "https://static.crates.io/crates/hayro-cmap/hayro-cmap-0.1.0.crate#assets/LICENSE.txt"
[[document]]
source = "licenses/egui-Hack-Regular.txt"
licences = ["MIT", "Bitstream-Vera"]
destination = "licenses/egui-Hack-Regular.txt"
sha256 = "47c0cccbeec7e8614548cc485588b28149e7874188df5f41b36efebcee285c87"
origin = "https://raw.githubusercontent.com/emilk/egui/0.36.2/crates/epaint_default_fonts/fonts/Hack-Regular.txt"
[[document]]
source = "licenses/egui-OFL.txt"
licences = ["OFL-1.1"]
destination = "licenses/egui-OFL.txt"
sha256 = "6a73f9541c2de74158c0e7cf6b0a58ef774f5a780bf191f2d7ec9cc53efe2bf2"
origin = "https://raw.githubusercontent.com/emilk/egui/0.36.2/crates/epaint_default_fonts/fonts/OFL.txt"
[[document]]
source = "licenses/egui-UFL.txt"
licences = ["Ubuntu-font-1.0"]
destination = "licenses/egui-UFL.txt"
sha256 = "2f0015108d68627bd788d313f529c21ff4da2c2c42a5e1f3883acc83480f9002"
origin = "https://raw.githubusercontent.com/emilk/egui/0.36.2/crates/epaint_default_fonts/fonts/UFL.txt"
[[document]]
source = "licenses/egui-emoji-icon-font-mit-license.txt"
licences = ["MIT"]
destination = "licenses/egui-emoji-icon-font-mit-license.txt"
sha256 = "b9d2c1d909aa149996fd4c91dcb92b2362a04431640c1d200959da94caf8cde1"
origin = "https://raw.githubusercontent.com/emilk/egui/0.36.2/crates/epaint_default_fonts/fonts/emoji-icon-font-mit-license.txt"
[[document]]
source = "licenses/prc-rs-LICENSE.txt"
licences = ["MIT"]
destination = "licenses/prc-rs-LICENSE.txt"
sha256 = "ddb846513d92153d8fa16b18ed3e7c86953a582f0d2f49f02b29f1bd569dac58"
origin = "https://raw.githubusercontent.com/ralovich/prc-rs/287b671bb5b31b05efb5ec1b98f7c359b9e4dd7d/LICENSE"
[[document]]
source = "vendor/hayro-interpret/LICENSE-APACHE"
licences = ["Apache-2.0"]
destination = "vendor/hayro-interpret/LICENSE-APACHE"
sha256 = "0cec06e0e55fbc3dc5cee4fca9b607f66cb8f4e4dbcf3b3c013594dd156732e9"
[[document]]
source = "vendor/hayro-interpret/LICENSE-MIT"
licences = ["MIT"]
destination = "vendor/hayro-interpret/LICENSE-MIT"
sha256 = "51b50e6120c344dcc146bbd6375ca1c78e079d97c8bea76e67a53d6ff0efebac"
[[document]]
source = "vendor/hayro-interpret/assets/CGATS_LICENSE.txt"
destination = "vendor/hayro-interpret/assets/CGATS_LICENSE.txt"
sha256 = "469d87b5fa48f8aaf69e25f4fcac3a309c97dbb7d561b917638abdb640e004d9"
[[document]]
source = "vendor/hayro-interpret/assets/LICENSE_FOXIT"
destination = "vendor/hayro-interpret/assets/LICENSE_FOXIT"
sha256 = "b578cdd2345840ada550bd12519533812320d5f1d21cf4c1c7e1b1b0a31c98b7"
[[document]]
source = "vendor/hayro-cmap/assets/LICENSE.txt"
licences = ["BSD-3-Clause"]
destination = "vendor/hayro-cmap/assets/LICENSE.txt"
sha256 = "742665db9c8e1bc72603c6d319ca3e90b83bd6d95202f0cd4ef11068a07a9c29"
[[document]]
source = "vendor/vello_common/LICENSE-MIT"
licences = ["MIT"]
destination = "vendor/vello_common/LICENSE-MIT"
sha256 = "adf157330f722fe7cfd5964a2a6974eff851b718228c6735724a11706e6f4dec"
[[bundled]]
crate = "epaint_default_fonts"
path = "fonts/Ubuntu-Light.ttf"
licence = "Ubuntu-font-1.0"
documents = ["licenses/egui-UFL.txt"]
[[bundled]]
crate = "epaint_default_fonts"
path = "fonts/Hack-Regular.ttf"
licence = "MIT AND Bitstream-Vera"
documents = ["licenses/egui-Hack-Regular.txt"]
[[bundled]]
crate = "epaint_default_fonts"
path = "fonts/NotoEmoji-Regular.ttf"
licence = "OFL-1.1"
documents = ["licenses/egui-OFL.txt"]
[[bundled]]
crate = "epaint_default_fonts"
path = "fonts/emoji-icon-font.ttf"
licence = "MIT"
documents = ["licenses/egui-emoji-icon-font-mit-license.txt"]
[[bundled]]
crate = "epaint_default_fonts"
path = "fonts/egui-icons.ttf"
licence = "MIT"
documents = ["licenses/egui-emoji-icon-font-mit-license.txt"]
[[bundled]]
crate = "hayro-interpret"
path = "src/font/generated/metrics.rs"
licence = "MIT OR Apache-2.0"
documents = ["vendor/hayro-interpret/LICENSE-MIT", "vendor/hayro-interpret/LICENSE-APACHE"]
+1 -1
View File
@@ -12,7 +12,7 @@ Third-party material
This product bundles third-party material under its own licenses, listed below. The per-file
list (author, source, license) is in ATTRIBUTION.md.
- Lucide icons (assets/icons/*.svg) — ISC License. See assets/icons/LICENSE-lucide.txt.
- Lucide icons (assets/icons/*.svg) — ISC and MIT licences (Feather-derived icons). See assets/icons/LICENSE-lucide.txt.
The Windows PDF file icon (assets/app-icon/pdfcraft-document.svg and .ico) adapts Lucide's
file-text outline and combines it with contributor-original artwork. See
assets/app-icon/LICENSE-document.txt (ISC AND (MIT OR Apache-2.0)), packaged as
+12 -1
View File
@@ -140,6 +140,8 @@ Search the whole document as you type, step through matches with <kbd>⌘G</kbd>
## Navigate long documents
Launch with `pdfcraft --two-paged file.pdf` (or `pdfcraft file.pdf --two-paged`) to open each command-line PDF in noncontinuous two-page view. This optional launch override does not change saved default-layout preferences or PDFs restored from the previous session. An explicit `--layout` option takes precedence on the active document regardless of argument order; `--default-layout` retains its existing behavior for subsequently opened documents.
Right-click a PDF tab to close it, reopen the last closed file-backed tab, or reveal its file. Closing still asks about unsaved changes. Reopening reads the saved file from disk; it does not restore discarded edits. Reveal selects the file in Explorer or Finder. On Linux and FreeBSD it requests `org.freedesktop.FileManager1.ShowItems`, falling back to opening the containing directory with `xdg-open` when that service is unavailable. Reopen and Reveal are unavailable on the web; Reveal is also unavailable for pathless documents.
Bookmarks, page thumbnails and the document's own page labels (i, ii, 1, 2…) keep you oriented in long documents. Search bookmark titles in the Bookmarks panel to find nested entries even when their parents are collapsed. Matches keep their ancestors for context; Clear restores the unfiltered tree without changing its expansion state.
@@ -545,9 +547,18 @@ stand on its own.
| <img src="https://raw.githubusercontent.com/storytold/vectorcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.vectorcraft.png" alt="" width="32" height="32"> | **VectorCraft** | Vector illustration | [GitHub](https://github.com/storytold/vectorcraft) | [Website](https://getartcraft.com/apps/vectorcraft) |
| <img src="https://raw.githubusercontent.com/storytold/filmcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.filmcraft.png" alt="" width="32" height="32"> | **FilmCraft** | Video editing, color and sound | [GitHub](https://github.com/storytold/filmcraft) | [Website](https://getartcraft.com/apps/filmcraft) |
| <img src="https://raw.githubusercontent.com/storytold/lightcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.lightcraft.png" alt="" width="32" height="32"> | **LightCraft** | Photo library and raw development | [GitHub](https://github.com/storytold/lightcraft) | [Website](https://getartcraft.com/apps/lightcraft) |
| <img src="https://raw.githubusercontent.com/storytold/pdfcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.pdfcraft.png" alt="" width="32" height="32"> | **PdfCraft** | **Reading, organizing and protecting PDFs · you are here** | [GitHub](https://github.com/storytold/pdfcraft) | [Website](https://getartcraft.com/apps/pdfcraft) |
| <img src="https://raw.githubusercontent.com/storytold/pdfcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.pdfcraft.png" alt="" width="32" height="32"> | **PdfCraft** | Reading, organizing and protecting PDFs | [GitHub](https://github.com/storytold/pdfcraft) | [Website](https://getartcraft.com/apps/pdfcraft) |
| <img src="https://raw.githubusercontent.com/storytold/effectcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.effectcraft.png" alt="" width="32" height="32"> | **EffectCraft** | Motion graphics and visual effects | [GitHub](https://github.com/storytold/effectcraft) | [Website](https://getartcraft.com/apps/effectcraft) |
| <img src="https://raw.githubusercontent.com/storytold/designcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.designcraft.png" alt="" width="32" height="32"> | **DesignCraft** | Page layout and publishing | [GitHub](https://github.com/storytold/designcraft) | [Website](https://getartcraft.com/apps/designcraft) |
| <img src="https://raw.githubusercontent.com/storytold/figcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.figcraft.png" alt="" width="32" height="32"> | **FigCraft** | Interface design and prototyping | [GitHub](https://github.com/storytold/figcraft) | [Website](https://getartcraft.com/apps/figcraft) |
| <img src="https://raw.githubusercontent.com/storytold/wordcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.wordcraft.png" alt="" width="32" height="32"> | **WordCraft** | Word processing and documents | [GitHub](https://github.com/storytold/wordcraft) | [Website](https://getartcraft.com/apps/wordcraft) |
| <img src="https://raw.githubusercontent.com/storytold/soundcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.soundcraft.png" alt="" width="32" height="32"> | **SoundCraft** | Audio recording and editing | [GitHub](https://github.com/storytold/soundcraft) | [Website](https://getartcraft.com/apps/soundcraft) |
| <img src="https://raw.githubusercontent.com/storytold/deckcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.deckcraft.png" alt="" width="32" height="32"> | **DeckCraft** | Presentations and slide decks | [GitHub](https://github.com/storytold/deckcraft) | [Website](https://getartcraft.com/apps/deckcraft) |
| <img src="https://raw.githubusercontent.com/storytold/cadcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.cadcraft.png" alt="" width="32" height="32"> | **CADCraft** | Computer-aided design | [GitHub](https://github.com/storytold/cadcraft) | [Website](https://getartcraft.com/apps/cadcraft) |
| <img src="https://raw.githubusercontent.com/storytold/gridcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.gridcraft.png" alt="" width="32" height="32"> | **GridCraft** | Spreadsheets and data | [GitHub](https://github.com/storytold/gridcraft) | [Website](https://getartcraft.com/apps/gridcraft) |
| <img src="https://raw.githubusercontent.com/storytold/texturecraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.texturecraft.png" alt="" width="32" height="32"> | **TextureCraft** | 3D texture painting | [GitHub](https://github.com/storytold/texturecraft) | [Website](https://getartcraft.com/apps/texturecraft) |
| <img src="https://raw.githubusercontent.com/storytold/craft-anything/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.craft-anything.png" alt="" width="32" height="32"> | **Craft Anything** | See how any software works, then build your own | [GitHub](https://github.com/storytold/craft-anything) | [Website](https://getartcraft.com/apps/craft-anything) |
| <img src="https://raw.githubusercontent.com/tangency-labs/solidcraft/main/assets/icons/app/linux/exports/hicolor/64x64/apps/io.tangencylabs.solidcraft.png" alt="" width="32" height="32"> | **SolidCraft** | Parametric 3D CAD by Tangency Labs (community app) | [GitHub](https://github.com/tangency-labs/solidcraft) | |
And [**ArtCraft**](https://getartcraft.com/) itself, our AI image and video studio for artists who want real control.
+78 -6
View File
@@ -1,5 +1,24 @@
# PdfCraft roadmap
> **Last reviewed:** 2026-11-03 | **Last updated:** 2026-11-03 | **Change:** patch (M5 #5850 review: indirect typewriter intent and composer edits preserve outer whitespace; movement regression commits by outside click; estimates unchanged)
> **Last reviewed:** 2026-11-03 | **Last updated:** 2026-11-03 | **Change:** patch (M5 #5850: Enter adds Fill & Sign line breaks; outside clicks commit, Escape cancels, and saved multiline appearances retain their text and height; estimates unchanged)
> **Last reviewed:** 2026-11-01 | **Last updated:** 2026-11-01 | **Change:** patch (M7, PR #2155 further review: inherited drawing/text state, affine image gestures, paste/selection ownership, no-op scripts and menu permissions; estimates unchanged)
> **Last reviewed:** 2026-11-01 | **Last updated:** 2026-11-01 | **Change:** patch (M7, PR #2155 latest comments: explicit image-paste events, mixed-size field refresh, and documented mixed-script normalization with Undo; estimates unchanged)
> **Last reviewed:** 2026-11-01 | **Last updated:** 2026-11-01 | **Change:** patch (M7, PR #2155 review follow-up: preserve image crop/tag/stream ownership, resize in page orientation, harden clipboard and text formatting, and reload installed fonts; estimates unchanged)
> **Last reviewed:** 2026-10-31 | **Last updated:** 2026-10-31 | **Change:** patch (M2, PR #4172: GBK rasters compared with explicit Unicode and independently selected installed faces; wrong-glyph and wrong-family negative controls fail; estimates unchanged)
> **Last reviewed:** 2026-10-31 | **Last updated:** 2026-10-31 | **Change:** patch (M2, PR #4172: integrate main fa5f9f8c; retain CJK viewer and upstream raster regressions, restore explicit display_config imports; estimates unchanged)
> **Last reviewed:** 2026-10-28 · **Last updated:** 2026-10-28 · **Change:** patch (M2, PR #4172: integrate main 5af10276; retain both roadmap histories and viewer-only CJK font policy; estimates unchanged)
> **Last reviewed:** 2026-10-27 · **Last updated:** 2026-10-27 · **Change:** patch (M2, PR #4172: integrate main 1dd2737b; preserve viewer-only CJK fallback and regression coverage across engine, renderer and Combine module splits; estimates unchanged)
> **Last reviewed:** 2026-10-27 · **Last updated:** 2026-10-27 · **Change:** patch (M2, PR #4172: integrate main 9a9813bf and preserve viewer-only CJK fallback through the engine module split; estimates unchanged)
> **Last reviewed:** 2026-10-26 · **Last updated:** 2026-10-26 · **Change:** patch (M2, PR #4172: document installed-font resolution helpers and regression contracts; behavior and estimates unchanged)
> **Last reviewed:** 2026-10-26 · **Last updated:** 2026-10-26 · **Change:** patch (M2, PR #4172: print preview excludes installed CJK fonts and isolates its font cache from the viewer; estimates unchanged)
> **Last reviewed:** 2026-10-26 · **Last updated:** 2026-10-26 · **Change:** patch (M2, PR #4172: reconcile current main while retaining display-only CJK fallback and upstream Japanese font selection; estimates unchanged)
> **Last reviewed:** 2026-10-23 · **Last updated:** 2026-10-23 · **Change:** minor (M2, PR #4172: extend on-screen CJK fallback to Combine thumbnails and figure previews; recognise FangSong and subset-prefixed Founder names; estimates unchanged)
> **Last reviewed:** 2026-10-15 · **Last updated:** 2026-10-15 · **Change:** minor (typed small Edit font sizes and Fill & Sign text/date colour, #2444/#2496; estimates unchanged)
**Stage: alpha** · next: beta, ~25% (ready for real work 50% → 75%) and ~400–700 h away
@@ -204,9 +223,45 @@ Ranked; detail and the full milestone table in [docs/roadmap.md](docs/roadmap.md
## Progress log
- **2026-11-03 (M11, shared JBIG2 dictionary):** With Monochrome Images set to JBIG2, Optimize has up to 16 JBIG2 images share one symbol dictionary (`/JBIG2Globals`), the letters found on more than one page stored once, when that is smaller (`pdfcraft_filters::encode_jbig2_shared`). Eight pages of 10 pt text rendered at 300 dpi take 41% less in Helvetica and 42% in Times than coded alone, 10% in Courier; groups of 16 save 45%, of 32 only 47%. Only images redaction can store again without the dictionary share one (image masks and DeviceGray named directly, at most 64 Mi pixels), and redacting one stores the rest of its group so, which the group bounds to 15.
- **2026-11-03 (M5, #5850 review):** Resolve indirect IT when recognizing typewriter contents and Fill & Sign marks. Comment listing and property lookup retain their existing direct-Subtype behavior. A real double-click Edit composer preserves the typewriter’s text as written; ordinary comment edits keep trimming. Regressions cover direct Subtype with indirect intent, save/reopen, raw posted contents and same-index comments on different pages. The existing live-movement test now commits its setup with an outside click rather than Enter. Estimates unchanged.
- **2026-11-03 (M5, #5850):** Fill & Sign Enter inserts a line break in a growing editor; clicking outside commits and Escape cancels. Nonempty text keeps leading, internal and trailing line breaks. The headless fill_sign_add path sizes its typewriter box for the same wrapped lines so saved appearances show every row. Production-order keyboard and engine save/reopen/render regressions exercise the UI and headless callers. Estimates unchanged.
- **2026-11-03 (M7, #5835):** In image crop mode, a right-click on the image, its crop box or its handles keeps the crop and opens no menu, so the menu no longer switches as the pointer moves. A right-click elsewhere clears the selection and opens the page menu. UI tests cover all four page rotations, overlapping images, a 45° image, and a check that the Done/Cancel/Remove Crop pills at a page edge still keep the crop.
- **2026-11-02 (M12, #1297):** `model_add` embeds a U3D or PRC file, recognised by its header, as a 3D annotation with a chosen activation and a poster (an image or PDF page fitted in the box, or a labelled frame); an older file's catalog `/Version` is raised to what the model needs. Views, a rendered poster and a UI command are later steps. Estimates unchanged.
- **2026-11-02 (M10, #5743):** macOS print jobs name their title and owner (`com.apple.print.JobInfo.PMJobName`, `PMJobOwner`), as the system print dialog does, because a Kyocera filter crashes on a job without them. Checked by a test and through `doc_print` against a stand-in `lp`; not yet on a physical printer.
- **2026-11-01 (M7, #5657):** Header/footer, watermark and background additions and replacements stage the complete call before committing. Synthetic later-page failures preserve exact incremental bytes, object count, dirty state and allocation cursor; success controls retain other marks and shared/inherited resources. Estimates unchanged.
- **2026-11-01 (M14, #5572):** Preferences ▸ Documents and view sets how many recent files to keep, from 0 to 50 with 12 by default. At 0 Home has no Recent section and File ▸ Open Recent is disabled. The list is cut when Preferences closes, so the number can pass through 0 on its way to another.
- **2026-11-01 (M5/M14, customizable hotbar, freehand highlight, and moveable navigation rail):** Added Freehand-Highlight (`/Subtype /Ink`, `/IT /FreehandHighlight`, Multiply blending, 100 pt max line width) inside the standard Highlight flyout and headless `comment_add`; added a customizable floating or side-docked hotbar with a full-side chrome strip mode, settings gear icon anchored at the bar end, and 24–64 px sizing; and added Left/Right docking for the navigation rail (`rail_side`). Focused unit and integration tests pass across `annot`, `automation`, and `ui-egui`. Estimates unchanged.
- 2026-11-01: PR #2155 further review preserves inherited Form text state and soft-mask chronology during Arrange, composes crop-group moves in the proper scope, and uses affine/press-relative image resize plus a shared rotation pivot. No-op script buttons preserve hidden source text; paste coordinates, visible selection ownership, and Snapshot/Export permissions have dedicated regressions. Candidate only; estimates unchanged.
- 2026-11-01: PR #2155 latest follow-up handles explicit image-paste events without release-time guesses, refreshes the font-size field when a selection becomes mixed, and specifies mixed-script normalization with exact Undo restoration. Candidate only; estimates unchanged.
- 2026-11-01: PR #2155 review follow-up preserves editor crops through group moves and keeps arranged artwork outside added-item streams; unsafe nested-tag extraction is refused. Image handles and flips follow page orientation, added images accept general transforms, and clipboard/text/Home/font-discovery edge cases have focused regressions. Candidate only; estimates unchanged.
- 2026-11-01: PR #2155 maintainer edits remove redundant image/text helpers and add regressions for crop ownership, arrange scope/state fidelity, clipboard precedence, crop-drag bounds, and font scanning. Transform and Unicode-script tools complete the headless paths.
- **2026-10-18 (M3, #1354, local candidate):** Integrated --two-paged with current main, retaining upstream modal/picker ownership and single-tab reuse. Native launch/opening/password regressions, negative checks against the old wrapper, visual inspection, formatting, strict scoped Clippy, layers, assets, parity and scoped WASM compilation pass. Three existing socket tests are unavailable in this workspace; one existing network test remains ignored. No push or GitHub merge; estimates unchanged.
- **2026-10-31 (M2, PR #4172 review):** Added same-machine pixel oracles for GBK Song, Hei, Kai and FangSong, including all four subset-prefixed Founder aliases. Reference PDFs use explicit Unicode mappings and independently selected installed faces; font data and rasters remain in memory. All eight cases ran; wrong-glyph and wrong-family production mutations each failed the new assertion and were restored. Validation: 422 renderer unit tests, renderer all-target Clippy with -D warnings, formatting, layers/assets/parity and renderer WASM checks passed; existing optional-patch/WASM warnings and parity notes remain. Estimates unchanged.
- **2026-10-31 (M2, PR #4172):** Integrated main fa5f9f8c, retaining both roadmap histories and raster regression groups. Restored display_config and thumbnail_config imports after the upstream explicit-import migration. Validation: 422 renderer unit tests, engine/UI all-target checks, scoped all-target Clippy with -D warnings, formatting, layers, assets, parity and renderer/engine WASM checks passed. Existing optional-patch/WASM warnings and parity notes remain; no full engine/UI runtime test rerun. Display-only font policy and estimates unchanged.
- **2026-10-28 (M2, PR #4172):** Integrated main 5af10276, preserving both roadmap histories and reviewing auto-merged export tests and accessibility UI changes. Validation: 488 scoped tests passed (18 engine, 412 renderer unit, 43 renderer integration, 15 Combine; one existing renderer integration test ignored); scoped all-target Clippy with -D warnings, formatting, layers, assets, parity and renderer/engine WASM checks passed. Viewer-only CJK fallback and print/output font policy remain unchanged; estimates unchanged.
- **2026-10-27 (M2, PR #4172 module-split conflicts):** Integrated main 1dd2737b, retaining viewer-only CJK fallback in split session modules and Combine thumbnail workers, and moving renderer regressions to the new test module. Validation: 798 scoped tests passed (371 engine, 412 renderer, 15 Combine; two existing engine tests ignored); scoped all-target Clippy with -D warnings, formatting, layers, assets, parity and renderer/engine WASM checks passed. Estimates unchanged.
- **2026-10-27 (M10, OCR models):** Model staging downloads and verifies the ONNX pair after the upstream RTEN URL brownout; runtime discovery prefers complete ONNX pairs per directory, retains complete RTEN fallback and preserves directory precedence.
- **2026-10-26 (M2, PR #4172):** Reconciled current main, preserving its Japanese serif/weight selection and both branches' progress records. Installed CJK viewer and preview fallback remains display-only; estimates unchanged.
- **2026-10-29 (M7, #2517):** Widening a paragraph rejoins a wrap with the number of spaces that wrap consumed, including a typed run and none for a Chinese or Japanese word split. The count survives an incremental save and a full rewrite, and a width-only `text_edit` uses it. Estimates unchanged.
- **2026-10-26 (M11, JBIG2 symbols):** Lossless JBIG2 now stores each distinct mark of a black-and-white image once, as a symbol, and places its exact copies, when that is smaller than the generic region: on six pages of rendered 300 dpi text 28% of the generic region's size and 17% of Group 4's, and the same bits back through two independent decoders (hayro-jbig2 and Poppler). Scans, whose letters are seldom identical, gain little until refinement coding; a dictionary shared between pages (`/JBIG2Globals`) is next. Estimates unchanged.
- **2026-10-27 (M10, OCR models):** Model staging downloads and verifies the ONNX pair after the upstream RTEN URL brownout; runtime discovery prefers complete ONNX pairs per directory, retains complete RTEN fallback and preserves directory precedence.
- **2026-10-25 (M5, comment replies):** One reply can be deleted from the Comments panel without its thread. On the selected card each reply has its own "…" menu (Edit, Copy text, Delete); Delete takes that reply with its pop-up and the replies to it, as `comment_delete` already did headlessly, and the comment and its other replies stay. The card stays selected, and the panel's editor stays open, on what they were on though the delete moved it in `/Annots`. Undo and Redo close the editor, since either can move what it was open on. A locked reply can't be deleted. Estimates unchanged.
- **2026-10-24 (M10, #4158 partial):** Word, HTML, RTF and PowerPoint export keep a block that continues another on its line (an italic case name, a link, a superscript) as a run in its own style inside that paragraph, with the source's word space, instead of a paragraph of its own. Style changes that wrap onto the next line still split paragraphs (the reading blocks keep style boundaries). Estimates unchanged.
- **2026-10-24 (M3, window move on Wayland, #3970 follow-up):** After a move or resize by PdfCraft's own title bar or edges, the button release given back to egui goes before the pointer leaving the window, so hover no longer sticks at the old place until the pointer moves. Found by CodeRabbit in review of #3970; a unit test covers it. Estimates unchanged.
@@ -238,6 +293,8 @@ Ranked; detail and the full milestone table in [docs/roadmap.md](docs/roadmap.md
- **2026-10-24 (M5, move preview):** A comment being moved is drawn where it goes while it is dragged (a rectangle or oval showed only its blue frame): the comment is rendered alone once as the drag starts and laid over the page, which shows it where it was until the move is applied. Engine `Document::comment_layer`; synthetic engine and UI regressions. 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-23 (M2, #234, continuation of #1567):** Reconciled installed CJK viewer fallback with current rendering changes; Windows preserves installed Song/Hei/Kai families and bounds font reads. GBK-EUC-H CIDFontType2 regression coverage includes text extraction; viewer fallback also survives reload with retained preferences. System fonts remain display-only. No overall readiness estimate changed.
- **2026-10-22 (M14, macOS association recovery candidate):** Successful desktop open/save/sign can queue recovery of an existing per-file binding to the running PDFCraft bundle through NSWorkspace. Metadata-only watcher changes retain undo and avoid false overwrite prompts; real same-length/same-mtime edits remain protected. Rebased on 0.12.0 and reuses #3042's shared atomic metadata preservation; the bounded recovery parser does not narrow save limits. Prior native Preview TEST-signature and Finder workflows passed on macOS 27.0.1; other versions remain unqualified. Estimates unchanged.
- **2026-10-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.
@@ -357,6 +414,8 @@ Ranked; detail and the full milestone table in [docs/roadmap.md](docs/roadmap.md
- **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-12 (M2, installed CJK fonts):** A CID font of an Adobe CJK collection (Japan1, GB1, CNS1, Korea1) that a PDF doesn't embed, such as the Kozuka Gothic of an Acrobat text box or the SongtiTC of a Pages export, drew nothing unless craft-fonts had a Japanese face. After craft-fonts, it now draws with a face already installed on the machine (PingFang, Heiti, Microsoft JhengHei / YaHei, Malgun and the like; read at runtime, never bundled, and used only for the on-screen viewer, never for exports, printing or OCR; Noto CJK and Source Han excluded; `PDFCRAFT_SYSTEM_FONTS=0` turns it off). The face of a collection with several regions (PingFang SC, TC) is chosen by region. Checked on macOS with a synthetic Traditional Chinese, Simplified Chinese and Korean page; the Windows and Linux font lists are untested, and a machine with none of the listed faces still draws nothing.
- **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.
@@ -529,10 +588,10 @@ Newest first: the date, what moved, and the new overall estimate.
- **2026-10-10 (L Print, #756):** Windows prints. The Print dialog lists the system's printers and its default from `Win32_Printer` (through PowerShell's CIM; `wmic` is gone from Windows 11), and Print spools the print-ready PDF: the in-box Windows.Data.Pdf renders each sheet at the printer's own resolution and System.Drawing.Printing carries copies, collation, duplex and colour as the job's settings — both reached through `powershell`, so the Rust code touches no Win32 API and the machine needs no PDF reader. This closes #756 and the "printer not showing" duplicates #160, #244, #293, #465 and #644, using the CIM approach community-tested in #452; the tests render the job's sheets through the whole WinRT path on CI (dry run, no printer needed) and, where a printer can be added, catch a real job in its paused queue. Web printing is still missing; milestone and effort estimates are unchanged.
- **2026-10-10 (M3, #740):** Column select, as in Acrobat: holding Alt (Option on macOS) when a drag starts selects only the text inside the rectangle, with the Select tool, the text markup tools and Redact; Edit ▸ Column select does it with a plain drag, for Linux desktops whose window manager takes Alt-drag (Xfce, Cinnamon, MATE, KDE Plasma 5 by default). Copy gives rows top to bottom with tab-separated cells (right to left in right-to-left rows, reading order for vertical text); `text_extract` takes the same rectangle as `rect`. The new label is in all 15 catalogs. Also repaired `parity/acrobat-features.toml`, which #650 had left unparseable (duplicate keys on `form.field-list`). Still missing: column selection across pages and ⇧-click extension. Estimates unchanged.
- **2026-10-10 (progress docs, hours per audience):** Each readiness number gets its own hours to ≈ 95%: full ≈ 49% / 780–1,400 h, mainstream ≈ 55% / 500–900 h, essentials ≈ 66% / 180–330 h. The full number is now the standard's additive weighted sum over the dimensions (written weights), 47% → 49%: method aligned with the standard, no new evidence. Beta ≈ 26 points, ≈ 400–700 h.
- **2026-10-10 (progress docs, hours per audience):** Each readiness number gets its own hours to ≈ 95%: full ≈ 49% / 780–1,400 h, mainstream ≈ 55% / 500–900 h, essentials ≈ 66% / 180–330 h. The full number is now the additive weighted sum over the dimensions (written weights), 47% → 49%; no new evidence. Beta ≈ 26 points, ≈ 400–700 h.
- **2026-10-10 (progress docs, gate consistency check):** Re-judged the convert-and-share row with the rule applied across all Crafting Apps (a workflow blocks only when it can't be completed at all; lossy exchange and missing sub-cases are beta items, as for FilmCraft's .prproj or VectorCraft's .ai). Unencrypted sharing works, encryption interop (#774) and Office→PDF are sub-cases, Word export is lossy rather than absent: partial, not blocking. **Stage pre-alpha → alpha**; numbers unchanged (47%, mainstream 55%; beta ≈ 400–700 h). Added an essentials-user score: ≈ 66% for someone who only opens, reads, comments, fills, signs, prints and rearranges pages.
- **2026-10-10 (progress docs, second look and alpha gate):** At the owner's request, after practitioners praised PdfCraft, re-examined the numbers. User sentiment: 7,595 stars, 177k + 39k downloads of 0.4.0/0.5.0, 23 user issues with explicit praise and switching reports (#179, #232, #273), issue themes concentrated in core paths (launch/GPU, rendering, editing, CJK, signing, printing). The checklist is not niche-dominated (497 mainstream vs 311 specialist rows; P0 95% / 91%). The first pass's 9-point cross-cutting deduction double-counted Windows printing, interop and glyphs: **ready for real work 40% → 47%**, and **≈ 55% for the mainstream practitioner** (new). The new core-workflow gate (craftrules progress-docs) fails on convert and share (#774, no Office import, #773): **stage alpha → pre-alpha**, ≈ 40–70 h from alpha; beta still ≈ 400–700 h.
- **2026-10-10 (progress docs, full re-measure):** Re-measured against Acrobat Pro 26.002.21931 (installed bundle inspected: document types, localizations, plug-in and framework names). Checklist: 423 shipped + 74 partial of 808 (56.9%; P0 94.2%), ≈ 67% tier-weighted. Ready for real work ≈ 40%; stage **alpha**; ≈ 400–700 h to beta, ≈ 780–1,400 h to full parity (up from 600–1,100 h: the first public releases surfaced Acrobat interop of encrypted output, Windows printing, Chinese UI glyphs, Word-export layout and a 245-issue backlog). This file restructured to the craftrules progress-docs standard; the honest assessment moved to `docs/target-app-parity.md`, the gap list to `docs/gaps.md`, the milestones (duplicated rows merged) to `docs/roadmap.md`; new `docs/architecture.md`, `docs/localization-parity.md`, `docs/file-format-parity.md`, `docs/pdf-spec-parity.md`, `docs/ui-parity.md`, `docs/hardware-parity.md`.
- **2026-10-10 (progress docs, second look and alpha gate):** At the owner's request, after practitioners praised PdfCraft, re-examined the numbers. User sentiment: 7,595 stars, 177k + 39k downloads of 0.4.0/0.5.0, 23 user issues with explicit praise and switching reports (#179, #232, #273), issue themes concentrated in core paths (launch/GPU, rendering, editing, CJK, signing, printing). The checklist is not niche-dominated (497 mainstream vs 311 specialist rows; P0 95% / 91%). The first pass's 9-point cross-cutting deduction double-counted Windows printing, interop and glyphs: **ready for real work 40% → 47%**, and **≈ 55% for the mainstream practitioner** (new). The new core-workflow gate fails on convert and share (#774, no Office import, #773): **stage alpha → pre-alpha**, ≈ 40–70 h from alpha; beta still ≈ 400–700 h.
- **2026-10-10 (progress docs, full re-measure):** Re-measured against Acrobat Pro 26.002.21931 (installed bundle inspected: document types, localizations, plug-in and framework names). Checklist: 423 shipped + 74 partial of 808 (56.9%; P0 94.2%), ≈ 67% tier-weighted. Ready for real work ≈ 40%; stage **alpha**; ≈ 400–700 h to beta, ≈ 780–1,400 h to full parity (up from 600–1,100 h: the first public releases surfaced Acrobat interop of encrypted output, Windows printing, Chinese UI glyphs, Word-export layout and a 245-issue backlog). This file restructured; the honest assessment moved to `docs/target-app-parity.md`, the gap list to `docs/gaps.md`, the milestones (duplicated rows merged) to `docs/roadmap.md`; new `docs/architecture.md`, `docs/localization-parity.md`, `docs/file-format-parity.md`, `docs/pdf-spec-parity.md`, `docs/ui-parity.md`, `docs/hardware-parity.md`.
- **2026-10-10 (M8, redact word lists):** Find text and redact gains "Multiple words or phrases": a list with one word or phrase per line, typed or imported from a `.txt` file, whose every match is marked in one undo step. Lists are trimmed, deduplicated and bounded (1,000 entries of 256 characters, files up to 1 MB). `redact_mark` takes `words` and reports how many marks each made, so an agent sees which found nothing. Tests cover the list parsing, the tool end to end (mark, undo, apply, invalid lists) and the dialog with an imported list; the new labels are translated in all 13 UI catalogs. `protect.redact-word-lists` is shipped; whole-word and case-sensitive matching and exporting the list are still missing. Estimates unchanged (about 30–35%).
- **2026-10-10 (M4, bookmarks from structure):** Bookmark options ▸ New bookmarks from structure (command `bookmark.from_structure`, tool `bookmark_from_structure`) turns a tagged document's headings into bookmarks: H1–H6 through the role map, a plain H by its section nesting, nested by level under a new first "Untitled" bookmark as in Acrobat, each linked to its structure element (/SE). Titles come from /ActualText, the marked text on the page (decoded through the font's ToUnicode or encoding), /Alt or /T. The walk is bounded (depth, visits, heading and title caps, cycle-safe), an untagged document gets a clear error, and the edit is one undo step. Tests cover role maps, nesting, ToUnicode text, a self-referencing heading, the tool, undo and the panel. Still missing: Acrobat's element-type choice and destinations at the heading's position. The M4 row no longer lists Replace pages as missing (it shipped earlier). Overall estimate unchanged (about 30–35%).
- **2026-10-10 (M9, signing encrypted documents):** Digital signatures, certification and document timestamps work on password-protected PDFs instead of failing with "not supported: signing encrypted documents". `pdfcraft-cos` no longer encrypts or decrypts a signature dictionary's `/Contents` (§7.6.2; by `/Type /Sig|/DocTimeStamp` or `/Contents` + `/ByteRange`), so the placeholder is patched after hashing as in a plain file and existing signatures in encrypted files read their real CMS (which also fixes their DSS `/VRI` keys and keeps them intact in a full rewrite). Opened with the user password, the signer applies the document's permissions (fill-forms for existing fields and timestamps, annotate + modify for new fields, modify for certifying) and names the permissions password when it refuses. Synthetic tests cover all four algorithms, counter-signing, tampering, permissions and the automation tools. Overall estimate unchanged (about 30–35%).
@@ -702,6 +761,10 @@ Newest first: the date, what moved, and the new overall estimate.
| Date | Change | Summary |
|---|---|---|
| 2026-11-03 | patch | M5 #5850 review: indirect typewriter intent and composer edits preserve outer whitespace; movement regression commits by outside click; estimates unchanged. |
| 2026-11-03 | patch | M5 #5850: Enter adds Fill & Sign line breaks; outside clicks commit, Escape cancels, and saved multiline appearances retain their text and height; estimates unchanged. |
| 2026-11-01 | patch | M7 #5657: header/footer, watermark and background operations commit all selected pages together; later-page errors preserve marks, content, shared/inherited resources and pending edits; estimates unchanged. |
| 2026-10-28 | patch | M2, PR #4172: integrate main 5af10276 and retain both roadmap histories; viewer-only CJK and print/output font policies and estimates unchanged. |
| 2026-10-27 | minor | M10: OCR stages SHA-256-verified ONNX models after the upstream RTEN URL brownout; discovery prefers a complete ONNX pair per directory, falls back to a complete RTEN pair, and never mixes formats or directories; language/web limits and estimates unchanged. |
| 2026-10-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. |
@@ -740,11 +803,11 @@ Newest first: the date, what moved, and the new overall estimate.
| 2026-10-11 | minor | M7: #594 paragraph-drag candidate and source regressions prepared; subsequent Linux validation passed all eight CI gates. Estimates unchanged. |
| 2026-10-10 | minor | Recorded the remaining System appearance repair after #881; estimates unchanged |
| 2026-10-11 | minor | Contributor fork: document-font selection and subset completion, CFF, style ranges, contextual/bidi save/reopen and all-page Chinese keyboard acceptance; curve/hole hit testing (shared clips stay fixed, as on main). Scope remains bounded; percentages unchanged |
| 2026-10-10 | minor | Readiness table with hours per audience; full number restated as the additive weighted sum over dimensions (47% → 49%; method aligned with the standard, no new evidence) |
| 2026-10-10 | minor | Readiness table with hours per audience; full number restated as the additive weighted sum over dimensions (47% → 49%; no new evidence) |
| 2026-10-10 | minor | Essentials-user score added (≈ 66%) |
| 2026-10-10 | minor | Gate consistency check: convert and share re-judged partial, not blocking; stage pre-alpha → alpha |
| 2026-10-10 | minor | Second look: ready 40% → 47% (cross-cutting double count removed), mainstream-practitioner numbers and user sentiment added; core-workflow alpha gate applied, stage alpha → pre-alpha |
| 2026-10-10 | major | Restructured to the progress-docs standard (stage, two numbers, dimensions, features, languages, upcoming, log); full re-measure; assessment, gaps and milestones moved to `docs/`; log sorted newest first and a stray merged entry dated |
| 2026-10-10 | major | Progress docs restructured (stage, two numbers, dimensions, features, languages, upcoming, log); full re-measure; assessment, gaps and milestones moved to `docs/`; log sorted newest first and a stray merged entry dated |
| 2026-10-07 | minor | 806 tracked features, 51.0% shipped, effort-weighted ≈ 30–35%, 600–1,100 h |
| 2026-10-05 | major | Honest assessment and "Where we're lacking" added |
| 2026-10-12 | minor | M8: cleanup removes replacement descriptions only from changed marked-content spans, preserving surviving accessibility text. Estimates unchanged. |
@@ -767,9 +830,18 @@ Newest first: the date, what moved, and the new overall estimate.
- **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.
- **2026-10-23 (M2, PR #4172):** Combine thumbnails and accessibility figure previews use the viewer's display-only CJK fallback. Windows family matching includes FangSong and subset-prefixed Founder names. Export, print, OCR and automation remain off by default; estimates unchanged.
- **2026-10-26 (M2, PR #4172 print-preview review):** Print-preview requests disable installed CJK fallback and use an isolated cache so preview font availability matches output. Viewer fallback survives switching in either direction. Synthetic GBK regressions cover inline and single-worker rendering, full pages and tiles; estimates unchanged.
- **2026-10-26 (M2, PR #4172 documentation review):** Added function documentation for installed-font script selection, bounded candidate reads, platform paths, resolver precedence and regression contracts. No runtime behavior or estimate change.
- **2026-10-27 (M2, PR #4172 conflict resolution):** Integrated main `9a9813bf` and its engine module split. Opening, layer changes and session renderer rebuilds retain display-only CJK fallback; output configuration and print-preview cache isolation are preserved. Validation passed: 16 scoped engine regressions, 412 renderer unit tests, 43 renderer integration tests (one existing corpus case ignored), 15 Combine tests, scoped Clippy, formatting, layers/assets/parity and renderer/engine WASM checks. Estimates unchanged.
## Pages sidebar keyboard refresh (2026-10-30)
PR #2133 retains document-local Pages sidebar focus for Ctrl/Cmd+A and Escape after the UI module split. The selection does not navigate. The focused regression is in `crates/ui-egui/tests/it/view.rs`; current-head hosted validation is pending. Feature counts and estimates are unchanged.
## Button export-value refresh (2026-10-30)
PR #1952 retains per-widget checkbox/radio export-value editing in the split form-authoring and Prepare modules. Caption editing remains supported. Tests cover preserved appearances and selection, invalid/locked refusals, data-format round trips, and Apply/Cancel/Undo. Current-head hosted validation is pending; feature estimates are unchanged.
- **2026-10-31 (#1577):** Reconciled the page-shadow preference with split viewer, organizer, settings and control modules, preserving upstream page-gap shadow suppression. CI validation pending.
+21 -29
View File
@@ -1,6 +1,8 @@
//! PdfCraft desktop app.
//!
//! Usage: `pdfcraft [options] [files…]` (`-h` / `--help` prints a short version of this, [`USAGE`]).
//! `--two-paged` opens each command-line PDF in noncontinuous two-page view, without changing defaults.
//! An explicit `--layout` takes precedence for the active document, regardless of argument order.
//! `--create-images [images…]` stages the images in one PDF and asks for the page DPI.
//!
//! View options (applied after the files open; also the seed of the UI control channel):
@@ -8,7 +10,7 @@
//! --theme light|dark|system --language auto|<code> --mode all|read|edit|convert|sign --tool <catalogue id> --left open|closed
//! --organize on --fields on --dialog properties|shortcuts|about --palette <query> --home on
//! --cover on|off --default-layout single|continuous|two-up|two-page --default-continuous on|off --default-zoom fit-width|fit-page|<percent> --always-default-view on|off
//! --page-gaps on|off --default-page-gaps on|off
//! --page-gaps on|off --default-page-gaps on|off --recent-files 0..50
//! --combine-view grid|list --combine-zoom 60..200`
//!
//! `--new-window` opens a window of its own. Without it, on Windows, a launch that only names files
@@ -40,6 +42,7 @@ mod motion;
mod reopen;
mod settings;
mod single_instance;
mod startup;
mod text_scale;
#[cfg(test)]
#[path = "windows_manifest.rs"]
@@ -63,6 +66,7 @@ Usage: pdfcraft [options] [files…]
Opens the files in the PdfCraft desktop app.
Options:
--two-paged open command-line PDFs in noncontinuous two-page view
--new-window open a window of its own instead of passing the files to a running PdfCraft
--create-images [images…] put the images in one PDF and ask for the page DPI
--control <file> enable the UI control channel (pdfcraft-cli ui --control <file> …)
@@ -218,28 +222,16 @@ fn main() -> eframe::Result {
let _ = std::io::Write::write_fmt(&mut std::io::stderr(), format_args!("pdfcraft: {report}\n"));
}
}));
let mut files = Vec::new();
let mut options: Vec<(String, String)> = Vec::new();
let mut control_file: Option<String> = None;
let mut create_images = false;
let mut new_window = false;
let mut args = std::env::args().skip(1);
while let Some(a) = args.next() {
match a.as_str() {
"--version" => return print_and_exit(&format!("pdfcraft {}", pdfcraft_engine::build_info::version())),
// Before any window or log file, so a scripted call returns (#4076).
"-h" | "--help" => return print_and_exit(USAGE),
"--control" => control_file = args.next(),
"--create-images" => create_images = true,
"--new-window" => new_window = true,
flag if flag.starts_with("--") => {
let value = args.next().unwrap_or_default();
options.push((flag.trim_start_matches("--").to_string(), value));
}
_ => files.push(path_from_arg(a)),
}
let mut startup = startup::Arguments::parse(std::env::args().skip(1));
if startup.version {
return print_and_exit(&format!("pdfcraft {}", pdfcraft_engine::build_info::version()));
}
let files = rejoin_split_paths(files, |p| std::path::Path::new(p).is_file());
if startup.help {
return print_and_exit(USAGE);
}
startup.files = rejoin_split_paths(startup.files, |p| std::path::Path::new(p).is_file());
let may_hand_off = startup.may_hand_off();
let startup::Arguments { files, options, control_file, create_images, two_paged, .. } = startup;
let integrated = cfg!(target_os = "macos");
// GNOME on Wayland leaves the window frame to the app (src/decorations.rs).
let window_controls = if cfg!(any(target_os = "macos", target_os = "windows")) { None } else { decorations::app_drawn() };
@@ -260,7 +252,6 @@ fn main() -> eframe::Result {
// Explorer double-click, a file manager or `xdg-open`) hands them to the PdfCraft already
// running and exits (#282, #317, #1726). Any option means the caller wants this launch's own
// window.
let may_hand_off = !new_window && !files.is_empty() && options.is_empty() && control_file.is_none() && !create_images;
// Absolute for this instance too: links relative to a document resolve against its folder,
// never the working directory.
let files = single_instance::absolute(&files);
@@ -270,7 +261,7 @@ fn main() -> eframe::Result {
single_instance::Claim::Alone => None,
};
let choice = renderer_choice(std::env::var("PDFCRAFT_RENDERER").ok().as_deref());
let launch = Launch { files, options, control_file, create_images, integrated, window_controls };
let launch = Launch { files, options, control_file, create_images, integrated, window_controls, two_paged };
// Finder, Open With and the Dock deliver files as Apple events, not arguments; catch the one
// that launched us as well as later ones. Lives until the event loop returns.
#[cfg(target_os = "macos")]
@@ -380,6 +371,7 @@ struct Launch {
integrated: bool,
/// The window buttons the app draws, when the desktop leaves the frame to it.
window_controls: Option<pdfcraft_ui_egui::window_controls::Layout>,
two_paged: bool,
}
/// Whether the window is a native Wayland one (not X11 or XWayland).
@@ -400,7 +392,7 @@ fn app_creator<'a>(
instance: Option<&'a single_instance::Server>,
#[cfg(target_os = "macos")] apple_events: &'a apple_events::AppleEvents,
) -> eframe::AppCreator<'a> {
let Launch { files, options, control_file, create_images, integrated, window_controls } = launch;
let Launch { files, options, control_file, create_images, integrated, window_controls, two_paged } = launch;
Box::new(move |cc| {
started.set(true);
let mut app = PdfCraftApp::new();
@@ -467,6 +459,7 @@ fn app_creator<'a>(
&[("folder", &w.folder.display().to_string()), ("error", &w.error)],
);
}
let defer_layout = two_paged && !files.is_empty() && !create_images;
if create_images {
if let Err(e) = app.begin_image_import_paths(&files) {
app.notify(e);
@@ -475,12 +468,11 @@ fn app_creator<'a>(
// With the preference on, last session's files come back first; files named on
// the command line open after them, in front (#442).
app.reopen_last_files(&files);
for f in files {
app.open_path(&f);
}
startup::open_files(&mut app, &files, two_paged);
}
for (k, v) in options {
if let Err(e) = app.set_option(&k, &v) {
let result = if defer_layout && k == "layout" { app.set_launch_layout(&v) } else { app.set_option(&k, &v) };
if let Err(e) = result {
log::warn!("--{k} {v}: {e}");
}
}
+244
View File
@@ -0,0 +1,244 @@
//! Native launch arguments and per-file view overrides (#1354).
use pdfcraft_ui_egui::PdfCraftApp;
#[derive(Default)]
pub(super) struct Arguments {
pub files: Vec<String>,
pub options: Vec<(String, String)>,
pub control_file: Option<String>,
pub create_images: bool,
pub new_window: bool,
pub two_paged: bool,
pub version: bool,
pub help: bool,
}
impl Arguments {
pub fn may_hand_off(&self) -> bool {
!self.new_window && !self.files.is_empty() && self.options.is_empty() && self.control_file.is_none() && !self.create_images && !self.two_paged
}
pub fn parse(args: impl IntoIterator<Item = String>) -> Self {
let mut parsed = Self::default();
let mut args = args.into_iter();
while let Some(a) = args.next() {
match a.as_str() {
"--version" => {
parsed.version = true;
break;
}
"-h" | "--help" => {
parsed.help = true;
break;
}
"--control" => parsed.control_file = args.next(),
"--create-images" => parsed.create_images = true,
"--new-window" => parsed.new_window = true,
"--two-paged" => parsed.two_paged = true,
flag if flag.starts_with("--two-paged=") => {
// It has no value: do not consume the following filename on malformed use.
log::warn!("{flag}: use --two-paged without a value");
}
flag if flag.starts_with("--") => {
let value = args.next().unwrap_or_default();
parsed.options.push((flag.trim_start_matches("--").to_string(), value));
}
_ => parsed.files.push(super::path_from_arg(a)),
}
}
parsed
}
}
pub(super) fn open_files(app: &mut PdfCraftApp, files: &[String], two_paged: bool) {
for path in files {
if two_paged {
// The per-file override wins over initial view without changing saved defaults.
app.open_path_with_display(path, pdfcraft_ui_egui::canvas::PageLayout::TwoUp, false);
} else {
app.open_path(path);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn parse(args: &[&str]) -> Arguments {
Arguments::parse(args.iter().map(|s| s.to_string()))
}
#[test]
fn standalone_flag_keeps_files_in_either_position() {
for args in
[["--two-paged", "first.pdf", "second.pdf"], ["first.pdf", "--two-paged", "second.pdf"], ["first.pdf", "second.pdf", "--two-paged"]]
{
let parsed = parse(&args);
assert!(parsed.two_paged);
assert_eq!(parsed.files, ["first.pdf", "second.pdf"]);
assert!(parsed.options.is_empty());
assert!(!parsed.may_hand_off());
}
let empty = parse(&["--two-paged"]);
assert!(empty.two_paged && empty.files.is_empty());
let normal = parse(&["first.pdf", "second.pdf"]);
assert!(!normal.two_paged);
assert!(normal.may_hand_off());
for args in [
&["--new-window", "first.pdf"][..],
&["--layout", "two-page", "first.pdf"],
&["--control", "control.json", "first.pdf"],
&["--create-images", "first.png"],
] {
assert!(!parse(args).may_hand_off());
}
}
#[test]
fn existing_layout_options_are_preserved_in_either_order() {
for args in [["--two-paged", "--layout", "single", "file.pdf"], ["--layout", "single", "--two-paged", "file.pdf"]] {
let parsed = parse(&args);
assert!(parsed.two_paged);
assert_eq!(parsed.files, ["file.pdf"]);
assert_eq!(parsed.options, [("layout".into(), "single".into())]);
}
let parsed = parse(&["--two-paged", "--default-layout", "two-up", "file.pdf"]);
assert_eq!(parsed.options, [("default-layout".into(), "two-up".into())]);
}
#[test]
fn newer_options_and_version_are_preserved() {
let parsed = parse(&["--two-paged", "--new-window", "--grid-zoom", "150", "--default-mode", "read", "file:///tmp/a%20b.pdf"]);
assert!(parsed.two_paged && parsed.new_window);
assert_eq!(parsed.files, ["/tmp/a b.pdf"]);
assert_eq!(parsed.options, [("grid-zoom".into(), "150".into()), ("default-mode".into(), "read".into())]);
assert!(!parsed.may_hand_off());
let version = parse(&["--two-paged", "--version", "ignored.pdf"]);
assert!(version.version && version.files.is_empty());
}
#[test]
fn help_keeps_the_headless_early_exit() {
for flag in ["-h", "--help"] {
let args = parse(&["--two-paged", flag, "ignored.pdf"]);
assert!(args.help && args.files.is_empty());
}
}
#[test]
fn malformed_boolean_does_not_eat_a_file_or_option() {
let args = parse(&["--two-paged=false", "first.pdf", "--layout", "single", "second.pdf"]);
assert!(!args.two_paged);
assert_eq!(args.files, ["first.pdf", "second.pdf"]);
assert_eq!(args.options, [("layout".into(), "single".into())]);
}
#[test]
fn startup_override_is_per_file_and_does_not_persist() {
use std::io::Write as _;
let nonce = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos();
let path = std::env::temp_dir().join(format!("pdfcraft-two-paged-{}-{nonce}.pdf", std::process::id()));
let mut file = std::fs::OpenOptions::new().create_new(true).write(true).open(&path).unwrap();
file.write_all(include_bytes!("../../../crates/ui-egui/tests/data/form.pdf")).unwrap();
drop(file);
let second_path = path.with_extension("second.pdf");
std::fs::copy(&path, &second_path).unwrap();
let text = path.to_str().unwrap();
let second = second_path.to_str().unwrap();
for enabled in [false, true] {
let mut app = PdfCraftApp::new();
app.set_option("default-layout", "single").unwrap();
app.open_bytes("restored.pdf", None, include_bytes!("../../../crates/ui-egui/tests/data/form.pdf").to_vec()).unwrap();
let restored = app.views[0].id;
open_files(&mut app, &[text.into(), second.into()], enabled);
assert_eq!(app.views.len(), 3);
assert_eq!(app.views[0].id, restored);
assert_eq!(app.views[0].layout, pdfcraft_ui_egui::canvas::PageLayout::Single);
for view in app.views.iter().skip(1) {
assert_eq!(
view.layout,
if enabled { pdfcraft_ui_egui::canvas::PageLayout::TwoUp } else { pdfcraft_ui_egui::canvas::PageLayout::Single }
);
assert!(!view.continuous());
}
let persisted: serde_json::Value = serde_json::from_str(&app.persist()).unwrap();
assert_eq!(persisted["default_layout"], "single");
assert!(persisted.get("two_paged").is_none());
// Existing --layout applies after the flag to the active document only.
if enabled {
app.set_launch_layout("continuous").unwrap();
} else {
app.set_option("layout", "continuous").unwrap();
}
assert_eq!(app.views[2].layout, pdfcraft_ui_egui::canvas::PageLayout::Single);
assert!(app.views[2].continuous());
app.set_option("default-layout", "two-up").unwrap();
assert_eq!(app.view_defaults.layout, pdfcraft_ui_egui::canvas::PageLayout::TwoUp);
assert!(app.view_defaults.continuous);
open_files(&mut app, &[], enabled);
assert_eq!(app.views.len(), 3);
}
std::fs::remove_file(path).unwrap();
std::fs::remove_file(second_path).unwrap();
}
#[test]
fn explicit_launch_layout_preserves_argument_order_and_active_file() {
use pdfcraft_ui_egui::canvas::PageLayout;
let path = std::env::temp_dir().join(format!("pdfcraft-explicit-layout-{}.pdf", std::process::id()));
std::fs::write(&path, include_bytes!("../../../crates/ui-egui/tests/data/form.pdf")).unwrap();
let second_path = path.with_extension("second.pdf");
std::fs::copy(&path, &second_path).unwrap();
let names = [path.to_str().unwrap(), second_path.to_str().unwrap()];
for prefix in [["--two-paged", "--layout", "single"], ["--layout", "single", "--two-paged"]] {
for count in [1, 2] {
let args = Arguments::parse(prefix.into_iter().chain(names.iter().take(count).copied()).map(str::to_owned));
let mut app = PdfCraftApp::new();
app.set_option("default-layout", "continuous").unwrap();
app.open_bytes("restored.pdf", None, include_bytes!("../../../crates/ui-egui/tests/data/form.pdf").to_vec()).unwrap();
open_files(&mut app, &args.files, args.two_paged);
for (key, value) in args.options {
assert_eq!(key, "layout");
app.set_launch_layout(&value).unwrap();
}
assert_eq!(app.active, Some(count));
assert!(app.views[0].continuous());
for view in app.views.iter().skip(1).take(count - 1) {
assert_eq!(view.layout, PageLayout::TwoUp);
}
assert_eq!(app.views[count].layout, PageLayout::Single);
assert!(!app.views[count].continuous());
assert!(app.view_defaults.continuous);
}
}
std::fs::remove_file(path).unwrap();
std::fs::remove_file(second_path).unwrap();
}
}
#[cfg(test)]
mod repeated_file_tests {
use super::*;
#[test]
fn a_repeated_file_reuses_its_tab_and_receives_the_launch_override() {
use pdfcraft_ui_egui::canvas::PageLayout;
let path = std::env::temp_dir().join(format!("pdfcraft-repeated-startup-{}.pdf", std::process::id()));
std::fs::write(&path, include_bytes!("../../../crates/ui-egui/tests/data/form.pdf")).unwrap();
let name = path.to_str().unwrap().to_string();
let mut app = PdfCraftApp::new();
app.set_option("default-layout", "continuous").unwrap();
app.open_path(&name);
let original = app.views[0].id;
open_files(&mut app, &[name.clone(), name], true);
assert_eq!(app.views.len(), 1);
assert_eq!(app.views[0].id, original);
assert_eq!(app.views[0].layout, PageLayout::TwoUp);
assert!(!app.views[0].continuous());
app.set_launch_layout("single").unwrap();
assert_eq!(app.views[0].layout, PageLayout::Single);
assert!(app.view_defaults.continuous);
std::fs::remove_file(path).unwrap();
}
}
+23
View File
@@ -663,6 +663,29 @@ fn the_desktop_entry_names_the_window_class() {
assert_eq!(class, Some(super::APP_ID));
}
/// Both flatpak manifests build with the craft-i18n commit `craft-i18n.rev` pins: CI and
/// releases read the file, and the manifests have to name the commit themselves. The pin may
/// have a trailing newline or CRLF (a Windows checkout), so it is trimmed, as every reader does.
#[test]
fn the_flatpak_manifests_pin_the_craft_i18n_rev() {
let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../..");
let rev = std::fs::read_to_string(root.join("craft-i18n.rev")).unwrap();
let rev = rev.trim();
assert!(rev.len() == 40 && rev.bytes().all(|b| b.is_ascii_hexdigit()), "craft-i18n.rev holds one full SHA: {rev:?}");
for manifest in ["ai.storyteller.pdfcraft.yml", "ai.storyteller.pdfcraft.bundle.yml"] {
let text = std::fs::read_to_string(root.join("packaging/linux/flatpak").join(manifest)).unwrap();
let source =
text.split("url: https://github.com/storytold/craft-i18n").nth(1).unwrap_or_else(|| panic!("{manifest}: a craft-i18n git source"));
let source = source.split("- type:").next().unwrap_or(source);
let commit = source
.lines()
.find_map(|l| l.trim().strip_prefix("commit:"))
.unwrap_or_else(|| panic!("{manifest}: the craft-i18n source pins a commit"));
assert_eq!(commit.trim().trim_matches(['\'', '"']), rev, "{manifest}");
assert!(text.contains("CRAFT_I18N_DIR: /run/build/pdfcraft/craft-i18n"), "{manifest}: the build names the catalogs");
}
}
// Regression test for #246: `eprintln!` panics when standard error is a broken pipe (a GUI
// launch on Windows), and a panic inside the panic hook aborts the process. The start-up
// path and the hook must write to standard error without it.
+1 -2
View File
@@ -20,8 +20,7 @@ icons use the full-bleed tile. macOS icons put it on Apple's grid (an 824 px bod
1024 px canvas).
**Provenance:** the project owner's original drawing, made in ArtCraft (2880 px, keyed to the palette), then
vectorised with craftrules `assets/logo-options/_tools/vectorize_tile.py` (potrace; no filtering or
warping). The source drawing is kept in craftrules at `assets/app-icons/pdfcraft/source.png`, not here.
vectorised (potrace; no filtering or warping).
Licence: [LICENSE.txt](LICENSE.txt) (`MIT OR Apache-2.0`, like the repo).
## Files
+5 -5
View File
@@ -1,13 +1,10 @@
# Contributor names for the About window (craftrules standards/contributors.md).
# Contributor names for the About window.
#
# Everyone who contributes is credited by GitHub username automatically. Anything more is up to
# you: add YOUR OWN entry below, in your own PR (commit it yourself). Never add someone else; a
# maintainer may add a person only when that person asked, recording where in consent_source.
#
# Easiest: python3 ../../craftrules/scripts/contributors.py --add-me . \
# [--real-name "Ada Lovelace"] [--display-name "Ada"] [--sync-github-name]
#
# Or copy this block, replacing your-github-username (every field is optional):
# Copy this block, replacing your-github-username (every field is optional):
#
# [people.your-github-username]
# real_name = "Your Name" # shown when the viewer picks "Real name"
@@ -183,3 +180,6 @@ sync_github_name = true
[people.dylanmtaylor]
sync_github_name = true
[people.Combiler01]
sync_github_name = true
+1
View File
@@ -0,0 +1 @@
575cfdef63227b14daf173b8cc87928bfdfa325e
+78 -92
View File
@@ -125,9 +125,9 @@ pub(crate) fn elements(doc: &Document) -> Vec<Element> {
}
/// The marked-content ids an element owns directly.
fn mcids(d: &Dict) -> Vec<i64> {
fn mcids(doc: &Document, d: &Dict) -> Vec<i64> {
let mut out = Vec::new();
let mut push = |o: &Object| match o {
let mut push = |o: &Object| match &*doc.resolve(o) {
Object::Int(n) => out.push(*n),
Object::Dict(m) if m.name(b"Type") == Some(b"MCR") => {
if let Some(n) = m.get(b"MCID").and_then(Object::as_int) {
@@ -323,7 +323,7 @@ pub fn figures(doc: &Document) -> Vec<Figure> {
let mut wanted: HashMap<usize, HashSet<i64>> = HashMap::new();
for (e, page) in &figures {
if let Some(p) = page {
wanted.entry(*p).or_default().extend(mcids(&e.dict));
wanted.entry(*p).or_default().extend(mcids(doc, &e.dict));
}
}
let bounds: HashMap<usize, HashMap<i64, [f64; 4]>> =
@@ -333,7 +333,7 @@ pub fn figures(doc: &Document) -> Vec<Figure> {
.map(|(e, page)| {
let alt = e.dict.get(b"Alt").map(|o| doc.resolve(o)).and_then(|o| o.as_string().map(|s| s.to_text()));
let on_page = page.and_then(|p| bounds.get(&p));
let bbox = on_page.and_then(|b| mcids(&e.dict).iter().filter_map(|id| b.get(id)).fold(None, |acc, b| Some(union(acc, *b))));
let bbox = on_page.and_then(|b| mcids(doc, &e.dict).iter().filter_map(|id| b.get(id)).fold(None, |acc, b| Some(union(acc, *b))));
Figure { obj: e.object, page, alt, bbox }
})
.collect()
@@ -363,52 +363,73 @@ pub fn set_alt(doc: &mut Document, obj: ObjRef, alt: Option<&str>) -> Result<(),
}
/// The page's content entries: one stream, or the elements of a contents array.
fn content_entries(doc: &Document, page: &Dict) -> Option<Vec<Object>> {
let c = page.get(b"Contents")?;
Some(match &*doc.resolve(c) {
fn content_entries(doc: &Document, page: &Dict) -> Vec<Object> {
let Some(c) = page.get(b"Contents") else { return Vec::new() };
match &*doc.resolve(c) {
Object::Array(a) => a.clone(),
Object::Stream(_) => vec![c.clone()],
_ => return None,
})
_ => Vec::new(),
}
}
fn marked(doc: &Document, props: &Dict, op: &pdfcraft_content::Op, ids: &HashSet<i64>) -> bool {
op.op == b"BDC" && bdc_mcid(doc, props, op).is_some_and(|n| ids.contains(&n))
}
type DecodedStream = (Object, Option<(Stream, Vec<u8>)>);
/// Turn the figure's marked-content blocks into artifacts, rewriting only the streams that
/// contain them. Other content streams, and unknown entries on a rewritten stream, stay.
fn artifact_marked_content(doc: &mut Document, page: &pdfcraft_model::Page, ids: &HashSet<i64>) -> Result<bool, AltError> {
let Some(entries) = content_entries(doc, &page.dict) else { return Ok(false) };
let props = page_properties(doc, &page.dict);
let mut streams: Vec<Option<(Stream, Vec<u8>)>> = Vec::with_capacity(entries.len());
/// Decode the page's content streams within the page decode budget. `None` when a stream is
/// rejected because the budget is exhausted.
fn decode_page_streams(doc: &Document, page: &Dict) -> Option<Vec<DecodedStream>> {
let entries = content_entries(doc, page);
let mut streams = Vec::with_capacity(entries.len());
let mut budget = DecodeBudget::page();
for entry in &entries {
match &*doc.resolve(entry) {
for entry in entries {
let decoded = match &*doc.resolve(&entry) {
Object::Stream(s) => {
let data = match budget.decode(s) {
Ok(data) => data,
// Content past the budget may hold more of the figure: editing the rest
// would leave that part marked as a figure the tree no longer has.
Err(_) if budget.exhausted() => return Err(AltError::TooLarge),
// Content past the budget may hold more of the tag: editing the rest
// would leave that part marked as a tag the tree no longer has.
Err(_) if budget.exhausted() => return None,
Err(_) => Vec::new(),
};
streams.push(Some((s.clone(), data)));
Some((s.clone(), data))
}
_ => streams.push(None),
_ => None,
};
streams.push((entry, decoded));
}
Some(streams)
}
fn marked_id(doc: &Document, props: &Dict, op: &pdfcraft_content::Op, ids: &HashSet<i64>) -> Option<i64> {
(op.op == b"BDC").then(|| bdc_mcid(doc, props, op)).flatten().filter(|n| ids.contains(n))
}
/// Turn the tag's marked-content blocks into artifacts, rewriting only the streams that
/// contain them. Other content streams, and unknown entries on a rewritten stream, stay.
/// With `require_all`, every id in `ids` must appear on the page before any stream is rewritten.
fn artifact_marked_content(
doc: &mut Document,
page: &pdfcraft_model::Page,
streams: Vec<DecodedStream>,
ids: &HashSet<i64>,
require_all: bool,
) -> Result<bool, pdfcraft_cos::CosError> {
let props = page_properties(doc, &page.dict);
let decoded: Vec<&[u8]> = streams.iter().filter_map(|(_, s)| s.as_ref().map(|(_, bytes)| bytes.as_slice())).collect();
let pieces = pdfcraft_content::Pieces::join(&decoded);
let mut found = HashSet::new();
let mut edits = Vec::new();
for op in pieces.parse().ops {
if let Some(id) = marked_id(doc, &props, &op, ids) {
found.insert(id);
edits.push((op.span, b"/Artifact BMC".to_vec()));
}
}
let decoded: Vec<&[u8]> = streams.iter().flatten().map(|(_, bytes)| bytes.as_slice()).collect();
let pieces = pdfcraft_content::Pieces::join(&decoded);
let edits: Vec<_> =
pieces.parse().ops.into_iter().filter(|op| marked(doc, &props, op, ids)).map(|op| (op.span, b"/Artifact BMC".to_vec())).collect();
if edits.is_empty() {
if if require_all { found != *ids } else { found.is_empty() } {
return Ok(false);
}
let mut spliced = pieces.splice(edits).into_iter();
let mut next = Vec::with_capacity(entries.len());
let mut changed = false;
for (entry, stream) in entries.into_iter().zip(streams) {
let mut next = Vec::with_capacity(streams.len());
for (entry, stream) in streams {
let Some((stream, old)) = stream else {
next.push(entry);
continue;
@@ -421,7 +442,6 @@ fn artifact_marked_content(doc: &mut Document, page: &pdfcraft_model::Page, ids:
next.push(entry);
continue;
}
changed = true;
let mut dict = stream.dict;
dict.remove(b"Length");
dict.remove(b"Filter");
@@ -431,28 +451,27 @@ fn artifact_marked_content(doc: &mut Document, page: &pdfcraft_model::Page, ids:
// appear elsewhere in this array or on another page, where it must stay unchanged.
next.push(Object::Ref(doc.add(stream)));
}
if changed {
let contents = match next.as_slice() {
[one] => one.clone(),
_ => Object::Array(next),
};
doc.update_dict(page.obj, |p| p.set(b"Contents".to_vec(), contents))?;
}
Ok(changed)
let contents = match next.as_slice() {
[one] => one.clone(),
_ => Object::Array(next),
};
doc.update_dict(page.obj, |p| p.set(b"Contents".to_vec(), contents))?;
Ok(true)
}
/// Decorative figure: its marked content on the page becomes an artifact, and the element
/// leaves the structure tree (and the parent tree).
pub fn mark_decorative(doc: &mut Document, obj: ObjRef) -> Result<(), AltError> {
let d = check_figure(doc, obj)?;
let ids: HashSet<i64> = mcids(&d).into_iter().collect();
let ids: HashSet<i64> = mcids(doc, &d).into_iter().collect();
let pages = pdfcraft_model::pages(doc);
let pg = d.get(b"Pg").and_then(Object::as_ref).or_else(|| elements(doc).into_iter().find(|e| e.object == obj).and_then(|e| e.page));
if let Some(page) = pg.and_then(|p| pages.iter().find(|x| x.obj == p)).filter(|_| !ids.is_empty())
&& artifact_marked_content(doc, page, &ids)?
{
if let Some(page) = pg.and_then(|p| pages.iter().find(|x| x.obj == p)).filter(|_| !ids.is_empty()) {
let streams = decode_page_streams(doc, &page.dict).ok_or(AltError::TooLarge)?;
// The parent tree no longer points those ids at the figure.
if let Some(key) = page.dict.get(b"StructParents").and_then(Object::as_int) {
if artifact_marked_content(doc, page, streams, &ids, false)?
&& let Some(key) = page.dict.get(b"StructParents").and_then(Object::as_int)
{
clear_parent_tree(doc, key, obj)?;
}
}
@@ -484,54 +503,23 @@ pub fn mark_tag_artifact(doc: &mut Document, obj: ObjRef) -> Result<(), Artifact
if has_child_structure(doc, &element.dict) {
return Err(ArtifactError::HasChildren);
}
let ids: HashSet<i64> = mcids(&element.dict).into_iter().collect();
let ids: HashSet<i64> = mcids(doc, &element.dict).into_iter().collect();
if ids.is_empty() {
return Err(ArtifactError::NoMarkedContent);
}
let pages = pdfcraft_model::pages(doc);
let page_ref = element.page.ok_or(ArtifactError::NoPage)?;
let page = pages.iter().find(|page| page.obj == page_ref).ok_or(ArtifactError::NoPage)?;
let mut content = Vec::new();
if let Some(c) = page.dict.get(b"Contents") {
let mut budget = DecodeBudget::page();
for data in budget.decode_contents(doc, c) {
match data {
Ok(data) => {
content.extend_from_slice(&data);
content.push(b' ');
}
// The page's /Contents is replaced with what was decoded: content past the
// budget would be dropped from the page.
Err(_) if budget.exhausted() => return Err(ArtifactError::TooLarge),
Err(_) => {}
}
}
}
let mut ops = pdfcraft_content::parse(&content).ops;
let mut found = HashSet::new();
for op in &mut ops {
let id = (op.op == b"BDC")
.then(|| match op.operands.get(1) {
Some(Object::Dict(mark)) => mark.get(b"MCID").and_then(Object::as_int),
_ => None,
})
.flatten()
.filter(|id| ids.contains(id));
if let Some(id) = id {
*op = pdfcraft_content::Op::new("BMC", vec![Object::name("Artifact")]);
found.insert(id);
}
}
if found != ids {
let parent = element.dict.get(b"P").and_then(Object::as_ref).ok_or(ArtifactError::NoParent)?;
let replacement = replacement_kids(doc, parent, obj)?;
let streams = decode_page_streams(doc, &page.dict).ok_or(ArtifactError::TooLarge)?;
if !artifact_marked_content(doc, page, streams, &ids, true)? {
return Err(ArtifactError::ContentNotFound);
}
let stream = doc.add(Object::Stream(Stream::flate(Dict::new(), &pdfcraft_content::serialize_ops(&ops))));
doc.update_dict(page.obj, |p| p.set(b"Contents".to_vec(), Object::Ref(stream)))?;
if let Some(key) = page.dict.get(b"StructParents").and_then(Object::as_int) {
clear_parent_tree(doc, key, obj).map_err(|e| ArtifactError::ParentTree(e.to_string()))?;
}
let parent = element.dict.get(b"P").and_then(Object::as_ref).ok_or(ArtifactError::NoParent)?;
remove_from_parent(doc, parent, obj)?;
doc.update_dict(parent, |p| p.set(b"K".to_vec(), replacement))?;
// Keep the retired object valid if another object holds an out-of-tree reference to it.
doc.update_dict(obj, |d| {
d.remove(b"P");
@@ -551,20 +539,18 @@ fn has_child_structure(doc: &Document, tag: &Dict) -> bool {
tag.get(b"K").is_some_and(|items| child(doc, items))
}
fn remove_from_parent(doc: &mut Document, parent: ObjRef, obj: ObjRef) -> Result<(), ArtifactError> {
fn replacement_kids(doc: &Document, parent: ObjRef, obj: ObjRef) -> Result<Object, ArtifactError> {
let kids = doc.get(parent).as_dict().and_then(|p| p.get(b"K").cloned()).ok_or(ArtifactError::NoParent)?;
let replacement = match kids {
match kids {
Object::Array(items) => {
if items.iter().filter(|item| item.as_ref() == Some(obj)).count() != 1 {
return Err(ArtifactError::AmbiguousParent);
}
Object::Array(items.into_iter().filter(|item| item.as_ref() != Some(obj)).collect())
Ok(Object::Array(items.into_iter().filter(|item| item.as_ref() != Some(obj)).collect()))
}
Object::Ref(r) if r == obj => Object::Array(Vec::new()),
_ => return Err(ArtifactError::NoParent),
};
doc.update_dict(parent, |p| p.set(b"K".to_vec(), replacement))?;
Ok(())
Object::Ref(r) if r == obj => Ok(Object::Array(Vec::new())),
_ => Err(ArtifactError::NoParent),
}
}
/// Replace `obj` by null in the page's parent-tree array (`key`), in a flat /Nums tree.
+70
View File
@@ -1017,6 +1017,76 @@ fn named_property_lists_are_found_and_marked_decorative_like_inline_ones() {
assert!(props.contains(b"P0") && props.contains(b"P1") && props.contains(b"Other"), "resources are left as they were");
}
#[test]
fn mark_tag_artifact_finds_named_property_lists_and_indirect_mcrs() {
use pdfcraft_cos::{Dict, ObjRef, Object};
let mut doc = named_figures_doc();
let mcr = doc.add(Object::Dict([(b"Type".to_vec(), Object::name("MCR")), (b"MCID".to_vec(), Object::Int(0))].into_iter().collect::<Dict>()));
doc.update_dict(ObjRef::new(7, 0), |d| d.set(b"K".to_vec(), Object::Ref(mcr))).unwrap();
assert_eq!(figures(&doc)[0].bbox, Some([10.0, 150.0, 50.0, 170.0]), "indirect MCR is resolved for figure bounds");
for (tag, gone) in [(ObjRef::new(7, 0), "/P0"), (ObjRef::new(8, 0), "/P1")] {
mark_tag_artifact(&mut doc, tag).unwrap();
let pages = pdfcraft_model::pages(&doc);
let c = doc.resolve(pages[0].dict.get(b"Contents").unwrap());
let Object::Stream(c) = &*c else { panic!("one content stream") };
let text = String::from_utf8(c.decoded().unwrap()).unwrap();
assert!(text.contains("/Artifact BMC") && !text.contains(gone), "{text}");
}
assert_eq!(tags(&doc).into_iter().map(|t| t.object.num).collect::<Vec<_>>(), [6]);
let nums = doc.get(ObjRef::new(9, 0)).as_dict().and_then(|d| d.get(b"Nums").cloned());
assert_eq!(nums, Some(Object::Array(vec![Object::Int(0), Object::Array(vec![Object::Null, Object::Null])])));
let r = check(&doc, &Options { rules: [Rule::FiguresAltText, Rule::TaggedContent].into(), pages: None });
assert_eq!(failed(&r), Vec::<Rule>::new(), "{:?}", r.results);
}
#[test]
fn mark_tag_artifact_validates_parent_and_all_mcids_before_mutating_document() {
use pdfcraft_cos::{ObjRef, Object};
// Missing /P on the tag must fail before touching /Contents or /ParentTree.
let mut no_parent = figures_doc();
let before_contents = no_parent.get(ObjRef::new(3, 0)).as_dict().unwrap().get(b"Contents").cloned();
let before_pt = no_parent.get(ObjRef::new(9, 0)).as_ref().clone();
no_parent
.update_dict(ObjRef::new(7, 0), |d| {
d.remove(b"P");
})
.unwrap();
assert_eq!(mark_tag_artifact(&mut no_parent, ObjRef::new(7, 0)), Err(ArtifactError::NoParent));
assert_eq!(no_parent.get(ObjRef::new(3, 0)).as_dict().unwrap().get(b"Contents").cloned(), before_contents);
assert_eq!(*no_parent.get(ObjRef::new(9, 0)), before_pt);
// Duplicate entry in parent's /K must fail with AmbiguousParent before touching /Contents or /ParentTree.
let mut dup_parent = figures_doc();
dup_parent
.update_dict(ObjRef::new(6, 0), |d| {
d.set(b"K".to_vec(), Object::Array(vec![Object::Ref(ObjRef::new(7, 0)), Object::Ref(ObjRef::new(8, 0)), Object::Ref(ObjRef::new(7, 0))]));
})
.unwrap();
assert_eq!(mark_tag_artifact(&mut dup_parent, ObjRef::new(7, 0)), Err(ArtifactError::AmbiguousParent));
assert_eq!(dup_parent.get(ObjRef::new(3, 0)).as_dict().unwrap().get(b"Contents").cloned(), before_contents);
assert_eq!(*dup_parent.get(ObjRef::new(9, 0)), before_pt);
// Partial MCID match (MCID 0 present, MCID 99 absent) must fail with ContentNotFound in
// mark_tag_artifact without mutating /Contents, while mark_decorative still converts MCID 0.
let mut partial = figures_doc();
partial.update_dict(ObjRef::new(7, 0), |d| d.set(b"K".to_vec(), Object::Array(vec![Object::Int(0), Object::Int(99)]))).unwrap();
assert_eq!(mark_tag_artifact(&mut partial, ObjRef::new(7, 0)), Err(ArtifactError::ContentNotFound));
assert_eq!(partial.get(ObjRef::new(3, 0)).as_dict().unwrap().get(b"Contents").cloned(), before_contents);
assert_eq!(*partial.get(ObjRef::new(9, 0)), before_pt);
mark_decorative(&mut partial, ObjRef::new(7, 0)).unwrap();
assert_ne!(partial.get(ObjRef::new(3, 0)).as_dict().unwrap().get(b"Contents").cloned(), before_contents);
assert_ne!(*partial.get(ObjRef::new(9, 0)), before_pt);
// When none of a figure's MCIDs appear on the page, mark_decorative leaves /Contents and /ParentTree untouched.
let mut absent = figures_doc();
absent.update_dict(ObjRef::new(7, 0), |d| d.set(b"K".to_vec(), Object::Int(99))).unwrap();
mark_decorative(&mut absent, ObjRef::new(7, 0)).unwrap();
assert_eq!(absent.get(ObjRef::new(3, 0)).as_dict().unwrap().get(b"Contents").cloned(), before_contents);
assert_eq!(*absent.get(ObjRef::new(9, 0)), before_pt);
}
fn ref_(n: u32) -> Option<pdfcraft_cos::ObjRef> {
Some(pdfcraft_cos::ObjRef::new(n, 0))
}
+14 -8
View File
@@ -99,14 +99,20 @@ fn shown_strings(ops: &[Op]) -> Vec<String> {
#[test]
fn mark_decorative_leaves_the_other_stream_untouched() {
let mut doc = tagged_figure_two_streams("0 0 1 rg 300 600 100 50 re f", "BT /F1 12 Tf 72 500 Td (After) Tj ET");
let before = doc.get(ObjRef::new(11, 0)).clone();
mark_decorative(&mut doc, ObjRef::new(8, 0)).expect("mark decorative succeeds");
assert!(figures(&doc).is_empty());
assert_eq!(*doc.get(ObjRef::new(11, 0)), *before, "the second stream holds no figure and keeps its object");
let page = doc.get(ObjRef::new(3, 0));
let contents = page.as_dict().unwrap().get(b"Contents").unwrap().as_array().unwrap();
assert_eq!(contents[1].as_ref(), Some(ObjRef::new(11, 0)), "the untouched stream must not be replaced by a re-encoded copy");
for use_artifact in [false, true] {
let mut doc = tagged_figure_two_streams("0 0 1 rg 300 600 100 50 re f", "BT /F1 12 Tf 72 500 Td (After) Tj ET");
let before = doc.get(ObjRef::new(11, 0)).clone();
if use_artifact {
mark_tag_artifact(&mut doc, ObjRef::new(8, 0)).expect("mark tag artifact succeeds");
} else {
mark_decorative(&mut doc, ObjRef::new(8, 0)).expect("mark decorative succeeds");
}
assert!(figures(&doc).is_empty());
assert_eq!(*doc.get(ObjRef::new(11, 0)), *before, "the second stream holds no figure and keeps its object");
let page = doc.get(ObjRef::new(3, 0));
let contents = page.as_dict().unwrap().get(b"Contents").unwrap().as_array().unwrap();
assert_eq!(contents[1].as_ref(), Some(ObjRef::new(11, 0)), "the untouched stream must not be replaced by a re-encoded copy");
}
}
/// A and B supply different operands to R's BDC. Reusing R must not let the first
+24 -11
View File
@@ -278,7 +278,7 @@ fn ext_gstate(opacity: f64, multiply: bool) -> Option<Dict> {
Some(res)
}
fn form(bbox: [f64; 4], content: &[u8], resources: Dict) -> Stream {
pub(crate) fn form(bbox: [f64; 4], content: &[u8], resources: Dict) -> Stream {
let mut d = Dict::new();
d.set(b"Type".to_vec(), Object::name("XObject"));
d.set(b"Subtype".to_vec(), Object::name("Form"));
@@ -288,6 +288,18 @@ fn form(bbox: [f64; 4], content: &[u8], resources: Dict) -> Stream {
Stream::flate(d, content)
}
/// The `cm` that draws a picture into `at`: an image (its unit square) or a form XObject whose
/// `/Matrix` maps it to `size` points (`None`, or a side that is not positive, draws nothing).
pub(crate) fn picture_place(at: [f64; 4], image: bool, size: Option<(f64, f64)>) -> Option<String> {
let [x0, y0, x1, y1] = at;
let (w, h) = (x1 - x0, y1 - y0);
if image {
return Some(format!("{} 0 0 {} {} {} cm", n(w), n(h), n(x0), n(y0)));
}
let (sw, sh) = size.filter(|(sw, sh)| *sw > 0.0 && *sh > 0.0)?;
Some(format!("{} 0 0 {} {} {} cm", n(w / sw), n(h / sh), n(x0), n(y0)))
}
/// The page `/Rotate` an image signature's picture is turned back by (`/PCPictureRotate`, written
/// when the signature is added to a turned page): 0, 90, 180 or 270.
pub(crate) fn picture_turn(d: &Dict) -> i64 {
@@ -325,7 +337,7 @@ pub fn undrawable_text(d: &Dict) -> Option<(&'static str, char)> {
}
/// `/Font` resources naming `/Helv`: standard Helvetica with WinAnsiEncoding.
fn helvetica_resource() -> Object {
pub(crate) 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"));
@@ -392,9 +404,13 @@ struct AppearanceDrawing {
}
impl AppearanceDrawing {
/// Initialize an appearance drawing buffer and configure its graphics state for opacity and blend mode.
fn new(context: &AppearanceContext<'_>) -> Self {
let mut drawing = Self::default();
if let Some(gs) = ext_gstate(context.opacity, context.subtype == b"Highlight") {
if let Some(gs) = ext_gstate(
context.opacity,
context.subtype == b"Highlight" || (context.subtype == b"Ink" && context.dict.name(b"IT") == Some(b"FreehandHighlight")),
) {
drawing.resources.set(b"ExtGState".to_vec(), Object::Dict(gs));
drawing.content.push_str("/GS0 gs\n");
}
@@ -782,15 +798,12 @@ fn draw_stamp(context: &AppearanceContext<'_>, mut drawing: AppearanceDrawing) -
// the standard counter-rotation as its form `/Matrix`: viewers fit the turned
// bounding box to `/Rect` (ISO 32000-2 §12.5.5), so it reads upright as displayed.
if let Some(pic) = d.get(b"PCPicture").and_then(Object::as_ref) {
let [x0, y0, x1, y1] = rect;
let (w, h) = (x1 - x0, y1 - y0);
let image = matches!(d.get(b"PCPictureImage"), Some(Object::Bool(true)));
let place = if image {
format!("{} 0 0 {} {} {} cm", n(w), n(h), n(x0), n(y0))
} else {
let size = nums(d, b"PCPictureSize").filter(|s| s.len() == 2 && s[0] > 0.0 && s[1] > 0.0)?;
format!("{} 0 0 {} {} {} cm", n(w / size[0]), n(h / size[1]), n(x0), n(y0))
};
let size = nums(d, b"PCPictureSize").and_then(|s| match s.as_slice() {
[w, h] if *w > 0.0 && *h > 0.0 => Some((*w, *h)),
_ => None,
});
let place = picture_place(rect, image, size)?;
c.push_str(&format!("q {place} /Pic Do Q\n"));
let mut xo = Dict::new();
xo.set(b"Pic".to_vec(), Object::Ref(pic));
+17 -9
View File
@@ -33,6 +33,16 @@ pub(crate) fn grow(r: [f64; 4], by: f64) -> [f64; 4] {
[r[0] - by, r[1] - by, r[2] + by, r[3] + by]
}
/// Tight bounding box of ink strokes, including Bezier control points for strokes with three or
/// more points (matching [`appearance::smooth_segments`]).
pub(crate) fn ink_bounds(strokes: &[Vec<[f64; 2]>]) -> Option<[f64; 4]> {
let controls = strokes.iter().filter(|s| s.len() > 2).flat_map(|s| {
let pts: Vec<(f64, f64)> = s.iter().map(|p| (p[0], p[1])).collect();
appearance::smooth_segments(&pts).into_iter().flat_map(|[a, b, _]| [[a.0, a.1], [b.0, b.1]])
});
bounds(strokes.iter().flatten().copied().chain(controls))
}
pub(crate) fn ending_draws(ending: LineEnding) -> bool {
ending != LineEnding::None
}
@@ -87,17 +97,11 @@ pub(crate) fn rect_for(shape: &Shape, style: &Style) -> Result<[f64; 4], AnnotEr
let pad = half + if ending_draws(*start) || ending_draws(*end) { appearance::arrow_size(style.width) } else { 0.0 };
grow(bounds([*from, *to].into_iter()).unwrap_or_default(), pad + 1.0)
}
Shape::Ink { strokes } | Shape::Signature { strokes } => {
Shape::Ink { strokes } | Shape::FreehandHighlight { strokes } | Shape::Signature { strokes } => {
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
// points and control points.
let controls = strokes.iter().filter(|s| s.len() > 2).flat_map(|s| {
let pts: Vec<(f64, f64)> = s.iter().map(|p| (p[0], p[1])).collect();
appearance::smooth_segments(&pts).into_iter().flat_map(|[a, b, _]| [[a.0, a.1], [b.0, b.1]])
});
grow(bounds(strokes.iter().flatten().copied().chain(controls)).unwrap_or_default(), half + 1.0)
grow(ink_bounds(strokes).unwrap_or_default(), half + 1.0)
}
Shape::Polygon { vertices, cloud } => {
let b = bounds(vertices.iter().copied())
@@ -164,6 +168,7 @@ fn subject(shape: &Shape) -> &'static str {
Shape::Oval { .. } => "Oval",
Shape::Line { start: LineEnding::None, end: LineEnding::OpenArrow, .. } => "Arrow",
Shape::Line { .. } => "Line",
Shape::FreehandHighlight { .. } => "Freehand Highlight",
Shape::Ink { .. } => "Pencil",
Shape::TextBox { .. } => "Text Box",
Shape::Typewriter { .. } => "Typewriter",
@@ -292,10 +297,13 @@ pub fn add_annotation(doc: &mut Document, new: &NewAnnotation, meta: &Meta) -> R
}
}
}
Shape::Ink { strokes } | Shape::Signature { strokes } => {
Shape::Ink { strokes } | Shape::FreehandHighlight { strokes } | Shape::Signature { strokes } => {
d.set(b"C".to_vec(), rgb(style.color));
let list = strokes.iter().filter(|s| !s.is_empty()).map(|s| num_array(&s.concat())).collect();
d.set(b"InkList".to_vec(), Object::Array(list));
if matches!(&new.shape, Shape::FreehandHighlight { .. }) {
d.set(b"IT".to_vec(), Object::name("FreehandHighlight"));
}
border(&mut d);
}
Shape::Polygon { vertices, cloud } => {
+6 -2
View File
@@ -47,8 +47,12 @@ pub(crate) fn text_value(doc: &Document, d: &Dict, key: &[u8]) -> Option<String>
Object::Name(n) => String::from_utf8_lossy(n).into_owned(),
_ => return None,
};
let s = s.trim_matches('\0').trim().to_string();
(!s.is_empty()).then_some(s)
let s = s.trim_matches('\0');
// Typewriter outer whitespace belongs to the text (keep in step with render's inspector).
let name_is = |key: &[u8], expected: &[u8]| d.get(key).is_some_and(|o| doc.resolve(o).as_name() == Some(expected));
let keep_breaks = key == b"Contents" && name_is(b"Subtype", b"FreeText") && name_is(b"IT", b"FreeTextTypeWriter");
let s = if keep_breaks { s } else { s.trim() };
(!s.trim().is_empty()).then(|| s.to_owned())
}
/// Whether an annotation subtype is a comment. Links, form widgets, pop-ups and the non-markup
+10
View File
@@ -22,7 +22,9 @@ mod create;
mod draw;
mod info;
mod lookup;
mod model3d;
mod modify;
mod threed;
mod types;
#[cfg(test)]
@@ -36,11 +38,13 @@ use lookup::{annots, page_ref};
pub use lookup::{
has_visible_fill_sign, is_fill_sign, isolate_annotation, isolate_annotations, page_refs, picture_rotation, set_annots, signature_image,
};
pub use model3d::{Model3d, Model3dKind, model_3d, model_3d_annotations};
pub(crate) use modify::n;
pub use modify::{
add_reply, add_text_replacement, deletable, delete_annotation, erase_ink, fillable, goes_with, lift_annotation, move_annotation, set_contents,
set_fill, set_font_size, set_locked, set_marked, set_points, set_rect, set_review_state, set_style, with_replies_and_popups,
};
pub use threed::{Activation as Activation3d, MAX_MODEL_BYTES, ModelFormat, NewModel3d, PosterPicture, add_3d_model, check_model};
pub use types::{
AttachIcon, FillMark, LineEnding, Markup, Meta, NOTE_SIZE, NewAnnotation, NoteIcon, OverlayFont, OverlayLook, ReviewState, Rgb, Shape,
StampGroup, StampKind, Style, StyleChange, TextReplacement, rect_quad,
@@ -70,6 +74,12 @@ pub enum AnnotError {
/// with a font that has those characters. The message names the character.
#[error("{0}")]
Undrawable(String),
/// A 3D model file that is neither U3D (starts with `U3D` and a zero byte) nor PRC (starts `PRC`).
#[error("not a 3D model: the file must be U3D (ECMA-363) or PRC (ISO 14739-1)")]
NotAModel,
/// A 3D model larger than `MAX_MODEL_BYTES`.
#[error("the 3D model is {size} bytes; the largest accepted is {max}")]
ModelTooLarge { size: usize, max: usize },
#[error("{0}")]
Cos(#[from] pdfcraft_cos::CosError),
}
+4 -4
View File
@@ -137,11 +137,11 @@ pub fn is_fill_sign(doc: &Document, d: &Dict) -> bool {
if matches!(d.get(b"PCFillSign").map(|o| doc.resolve(o)).as_deref(), Some(Object::Bool(true))) {
return true;
}
let subtype = d.name(b"Subtype").unwrap_or_default();
if subtype == b"FreeText" && d.name(b"IT") == Some(b"FreeTextTypeWriter") {
let name_is = |key: &[u8], expected: &[u8]| d.get(key).is_some_and(|o| doc.resolve(o).as_name() == Some(expected));
if name_is(b"Subtype", b"FreeText") && name_is(b"IT", b"FreeTextTypeWriter") {
return true;
}
if subtype == b"Stamp" {
if name_is(b"Subtype", b"Stamp") {
if matches!(d.name(b"Name"), Some(b"PCCheck" | b"PCCross" | b"PCDot" | b"PCLine" | b"PCTypedSignature")) {
return true;
}
@@ -151,7 +151,7 @@ pub fn is_fill_sign(doc: &Document, d: &Dict) -> bool {
return true;
}
}
subtype == b"Ink" && text_value(doc, d, b"Subj").as_deref() == Some("Signature")
name_is(b"Subtype", b"Ink") && text_value(doc, d, b"Subj").as_deref() == Some("Signature")
}
pub(crate) fn annotation_flags(doc: &Document, d: &Dict) -> i64 {
+77
View File
@@ -0,0 +1,77 @@
//! Reading the model a 3D annotation shows (ISO 32000-2 §13.6.3 and §13.6.4): its `/3DD` is a
//! 3D stream, or a 3D reference dictionary naming the stream another annotation shares.
use super::lookup::{annots, page_ref};
use super::threed::MAX_MODEL_BYTES;
use super::{AnnotError, Dict, Document, Object};
/// The format of a 3D stream, from its `/Subtype`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Model3dKind {
/// Product Representation Compact (ISO 14739-1).
Prc,
/// Universal 3D (ECMA-363).
U3d,
}
/// A 3D annotation's model: its format and the decoded stream.
#[derive(Debug, Clone, PartialEq)]
pub struct Model3d {
pub kind: Model3dKind,
pub data: Vec<u8>,
}
/// The `/Annots` positions of the 3D annotations on 0-based `page`, in order.
///
/// # Errors
/// [`AnnotError::NoPageTree`] or [`AnnotError::NoSuchPage`].
pub fn model_3d_annotations(doc: &Document, page: usize) -> Result<Vec<usize>, AnnotError> {
let list = annots(doc, page_ref(doc, page)?);
Ok(list.iter().enumerate().filter(|(_, a)| doc.dict(a).is_some_and(|d| d.name(b"Subtype") == Some(b"3D"))).map(|(i, _)| i).collect())
}
/// The model of the 3D annotation at `/Annots` position `index` on 0-based `page`, decoded.
///
/// # Errors
/// [`AnnotError::NoSuchAnnotation`] when there is no annotation there; [`AnnotError::Invalid`]
/// when it is not a 3D annotation, has no readable 3D stream, names a format other than PRC or
/// U3D, or decodes past [`MAX_MODEL_BYTES`].
pub fn model_3d(doc: &Document, page: usize, index: usize) -> Result<Model3d, AnnotError> {
let list = annots(doc, page_ref(doc, page)?);
let entry = list.get(index).ok_or(AnnotError::NoSuchAnnotation { page, index })?;
let annot = doc.dict(entry).ok_or(AnnotError::NoSuchAnnotation { page, index })?;
let at = || format!("annotation {} on page {}", index.saturating_add(1), page.saturating_add(1));
if annot.name(b"Subtype") != Some(b"3D") {
return Err(AnnotError::Invalid(format!("{} is not a 3D annotation", at())));
}
let stream = stream_of(doc, &annot).ok_or_else(|| AnnotError::Invalid(format!("{} has no 3D stream", at())))?;
let Object::Stream(s) = stream.as_ref() else {
return Err(AnnotError::Invalid(format!("{} has no 3D stream", at())));
};
let kind = match s.dict.name(b"Subtype") {
Some(b"PRC") => Model3dKind::Prc,
Some(b"U3D") => Model3dKind::U3d,
other => {
let name = other.map_or_else(|| "none".to_owned(), |n| String::from_utf8_lossy(n).into_owned());
return Err(AnnotError::Invalid(format!("{}'s 3D stream is of an unknown format ({name})", at())));
}
};
let data = doc
.with_direct_parms(s)
.decoded_within(MAX_MODEL_BYTES)
.map_err(|e| AnnotError::Invalid(format!("{}'s 3D stream could not be decoded: {e}", at())))?;
Ok(Model3d { kind, data })
}
/// What an annotation's `/3DD` names: the 3D stream itself, or the `/3D` entry of a 3D reference
/// dictionary. A reference is followed once; the caller refuses anything that is not a stream.
fn stream_of(doc: &Document, annot: &Dict) -> Option<std::sync::Arc<Object>> {
let obj = doc.resolve(annot.get(b"3DD")?);
match obj.as_ref() {
Object::Dict(d) if d.name(b"Type") == Some(b"3DRef") => Some(doc.resolve(d.get(b"3D")?)),
_ => Some(obj),
}
}
#[cfg(test)]
mod tests;
+88
View File
@@ -0,0 +1,88 @@
use std::sync::Arc;
use super::*;
/// A one-page document whose page has `annots` as its `/Annots`, plus `extra` objects from 4 on.
fn doc(annots: &str, extra: &[Vec<u8>]) -> Document {
let mut objs: Vec<Vec<u8>> = vec![
b"<< /Type /Catalog /Pages 2 0 R >>".to_vec(),
b"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 612 792] >>".to_vec(),
format!("<< /Type /Page /Parent 2 0 R /Annots {annots} >>").into_bytes(),
];
objs.extend(extra.iter().cloned());
let mut out = b"%PDF-1.7\n".to_vec();
let mut offsets = Vec::new();
for (i, o) in objs.iter().enumerate() {
offsets.push(out.len());
out.extend_from_slice(format!("{} 0 obj\n", i + 1).as_bytes());
out.extend_from_slice(o);
out.extend_from_slice(b"\nendobj\n");
}
let xref = out.len();
out.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objs.len() + 1).as_bytes());
for o in offsets {
out.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes());
}
out.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objs.len() + 1).as_bytes());
Document::open(Arc::new(out)).expect("opens")
}
fn stream(dict: &str, body: &[u8]) -> Vec<u8> {
let mut s = format!("<< {dict} /Length {} >>\nstream\n", body.len()).into_bytes();
s.extend_from_slice(body);
s.extend_from_slice(b"\nendstream");
s
}
fn annot(dd: &str) -> Vec<u8> {
format!("<< /Type /Annot /Subtype /3D /Rect [0 0 100 100] /3DD {dd} >>").into_bytes()
}
#[test]
fn a_plain_3d_stream_is_read_through_its_filters() {
let d = doc("[4 0 R]", &[annot("5 0 R"), stream("/Type /3D /Subtype /PRC /Filter /ASCIIHexDecode", b"505243>")]);
assert_eq!(model_3d(&d, 0, 0), Ok(Model3d { kind: Model3dKind::Prc, data: b"PRC".to_vec() }));
}
#[test]
fn a_3dref_leads_to_the_stream_it_names() {
let d = doc("[4 0 R]", &[annot("<< /Type /3DRef /3D 5 0 R >>"), stream("/Type /3D /Subtype /PRC", b"PRC")]);
assert_eq!(model_3d(&d, 0, 0).map(|m| m.data), Ok(b"PRC".to_vec()));
}
#[test]
fn a_u3d_stream_is_read_and_says_so() {
let d = doc("[4 0 R]", &[annot("5 0 R"), stream("/Type /3D /Subtype /U3D", b"U3D")]);
assert_eq!(model_3d(&d, 0, 0).map(|m| m.kind), Ok(Model3dKind::U3d));
}
#[test]
fn a_3d_annotation_without_a_stream_is_invalid() {
let d = doc("[<< /Type /Annot /Subtype /3D /Rect [0 0 1 1] >>]", &[]);
assert!(matches!(model_3d(&d, 0, 0), Err(AnnotError::Invalid(m)) if m.contains("no 3D stream")));
}
#[test]
fn an_unknown_format_is_invalid() {
let d = doc("[4 0 R]", &[annot("5 0 R"), stream("/Type /3D /Subtype /STL", b"x")]);
assert!(matches!(model_3d(&d, 0, 0), Err(AnnotError::Invalid(m)) if m.contains("unknown format (STL)")));
}
#[test]
fn a_3dref_is_followed_once_and_only_to_a_stream() {
// A reference naming another reference, or one that names itself, is damage: no stream.
let d = doc("[4 0 R]", &[annot("5 0 R"), b"<< /Type /3DRef /3D 6 0 R >>".to_vec(), b"<< /Type /3DRef /3D 5 0 R >>".to_vec()]);
assert!(matches!(model_3d(&d, 0, 0), Err(AnnotError::Invalid(m)) if m.contains("no 3D stream")));
// The stream is under `/3D`; a `/3DD` inside the reference is not the standard's key.
let d = doc("[4 0 R]", &[annot("<< /Type /3DRef /3DD 5 0 R >>"), stream("/Type /3D /Subtype /PRC", b"PRC")]);
assert!(matches!(model_3d(&d, 0, 0), Err(AnnotError::Invalid(m)) if m.contains("no 3D stream")));
}
#[test]
fn another_annotation_is_not_a_3d_one() {
let d = doc("[<< /Type /Annot /Subtype /Square /Rect [0 0 1 1] >> 4 0 R]", &[annot("5 0 R"), stream("/Subtype /PRC", b"PRC")]);
assert!(matches!(model_3d(&d, 0, 0), Err(AnnotError::Invalid(m)) if m.contains("not a 3D annotation")));
assert_eq!(model_3d(&d, 0, 2), Err(AnnotError::NoSuchAnnotation { page: 0, index: 2 }));
assert_eq!(model_3d_annotations(&d, 0), Ok(vec![1]));
assert_eq!(model_3d_annotations(&d, 1), Err(AnnotError::NoSuchPage(1)));
}
+36 -3
View File
@@ -1,5 +1,5 @@
use super::create::{
add_annotation, base_dict, bounds, callout_attach, ending_draws, ending_pair, finite, grow, normalize, num_array, rect_for, rgb,
add_annotation, base_dict, bounds, callout_attach, ending_draws, ending_pair, finite, grow, ink_bounds, normalize, num_array, rect_for, rgb,
};
use super::draw::{draw_appearance, redraw_or_restore, set_appearance};
use super::info::{line_endings_of, text_value};
@@ -529,7 +529,33 @@ fn apply_text_box(doc: &mut Document, r: ObjRef, rect: [f64; 4], meta: &Meta, ne
}
fn border_width_of(d: &Dict) -> f64 {
d.get(b"BS").and_then(|b| b.as_dict()).and_then(|b| b.get(b"W")).and_then(|w| w.as_f64()).unwrap_or(1.0).max(0.0)
appearance::border_width(d)
}
/// Recompute `/Rect` for an `Ink` annotation when its stroke width changes from `old_w` to `w`.
/// Preserves any baseline margin beyond `old_w / 2.0` (at least `1.0` pt) without accumulating
/// padding across repeated width increases and decreases.
fn ink_rect_for_width(d: &Dict, old_w: f64, w: f64) -> Option<[f64; 4]> {
let list = d.get(b"InkList")?.as_array()?;
let mut strokes: Vec<Vec<[f64; 2]>> = Vec::with_capacity(list.len());
for s in list {
let pts: Vec<f64> = s.as_array()?.iter().map(Object::as_f64).collect::<Option<_>>()?;
strokes.push(pts.as_chunks::<2>().0.iter().map(|p| [p[0], p[1]]).collect());
}
let inner = ink_bounds(&strokes)?;
let vals: Vec<f64> = d.get(b"Rect").and_then(Object::as_array).map(|a| a.iter().filter_map(Object::as_f64).collect()).unwrap_or_default();
let Some(old_rect) = four(&vals).map(normalize) else {
return Some(grow(inner, w / 2.0 + 1.0));
};
let old_half = old_w / 2.0;
let new_half = w / 2.0;
let base = [
(inner[0] - old_rect[0] - old_half).max(1.0),
(inner[1] - old_rect[1] - old_half).max(1.0),
(old_rect[2] - inner[2] - old_half).max(1.0),
(old_rect[3] - inner[3] - old_half).max(1.0),
];
Some([inner[0] - base[0] - new_half, inner[1] - base[1] - new_half, inner[2] + base[2] + new_half, inner[3] + base[3] + new_half])
}
/// Change a comment's colour, opacity, line width and/or line endings, and redraw it.
@@ -576,10 +602,17 @@ pub fn set_style(doc: &mut Document, page: usize, index: usize, change: StyleCha
}
}
if let Some(w) = width {
let old_w = border_width_of(d);
let w = w.max(0.0);
let mut bs = d.get(b"BS").and_then(|b| b.as_dict()).cloned().unwrap_or_default();
bs.set(b"W".to_vec(), Object::Real(w.max(0.0)));
bs.set(b"W".to_vec(), Object::Real(w));
d.set(b"BS".to_vec(), Object::Dict(bs));
d.remove(b"Border");
if d.name(b"Subtype") == Some(b"Ink")
&& let Some(rect) = ink_rect_for_width(d, old_w, w)
{
d.set(b"Rect".to_vec(), num_array(&rect));
}
}
if let Some(ends) = endings {
if ends.len() == 1 {
+215
View File
@@ -2194,3 +2194,218 @@ fn degenerate_and_absurd_leader_and_caption_values_do_not_panic() {
assert!(long.contains(&format!("({}) Tj", "w".repeat(256))), "cut to 256");
assert!(!long.contains(&"w".repeat(257)));
}
#[test]
fn freehand_highlight_is_compatible_ink_with_marker_blending() {
let shape = Shape::FreehandHighlight { strokes: vec![vec![[20.0, 100.0], [120.0, 100.0]]] };
let mut annotation = new(0, shape.clone());
annotation.style = Style::default_for(&shape);
let mut doc = fixture();
let index = add_annotation(&mut doc, &annotation, &meta("marker")).unwrap();
let doc = reopen(&doc);
let ink = &list(&doc, 0)[index];
assert_eq!(ink.name(b"Subtype"), Some(&b"Ink"[..]));
assert_eq!(ink.name(b"IT"), Some(&b"FreehandHighlight"[..]));
assert_eq!(ink.get(b"CA").and_then(Object::as_f64), Some(0.35));
let ap = ink.get(b"AP").unwrap().as_dict().unwrap().reference(b"N").unwrap();
let resources = doc.get(ap).as_dict().unwrap().get(b"Resources").cloned().unwrap();
let blend = resources.as_dict().unwrap().get(b"ExtGState").unwrap().as_dict().unwrap().get(b"GS0").unwrap().as_dict().unwrap();
assert_eq!(blend.name(b"BM"), Some(&b"Multiply"[..]));
let mut doc = doc;
let rect_of = |doc: &Document, idx: usize| -> Vec<f64> {
list(doc, 0)[idx].get(b"Rect").unwrap().as_array().unwrap().iter().filter_map(Object::as_f64).collect()
};
let rect_before = rect_of(&doc, index);
set_style(&mut doc, 0, index, StyleChange { color: None, opacity: None, width: Some(34.0), endings: None }, &meta("wider")).unwrap();
let rect_after = rect_of(&doc, index);
assert!((rect_after[0] - (rect_before[0] - 10.0)).abs() < 1e-4);
assert!((rect_after[2] - (rect_before[2] + 10.0)).abs() < 1e-4);
// Repeated increase/decrease cycles must keep bounds stable and never accumulate padding.
set_style(&mut doc, 0, index, StyleChange { color: None, opacity: None, width: Some(14.0), endings: None }, &meta("narrower")).unwrap();
let rect_restored = rect_of(&doc, index);
for (a, b) in rect_restored.iter().zip(rect_before.iter()) {
assert!((a - b).abs() < 1e-4, "expected {rect_before:?}, got {rect_restored:?}");
}
set_style(&mut doc, 0, index, StyleChange { color: None, opacity: None, width: Some(34.0), endings: None }, &meta("wider-again")).unwrap();
let rect_second_wide = rect_of(&doc, index);
for (a, b) in rect_second_wide.iter().zip(rect_after.iter()) {
assert!((a - b).abs() < 1e-4, "expected {rect_after:?}, got {rect_second_wide:?}");
}
// Imported ink whose width is specified only by `/Border [0 0 20]` must use 20 pt as its
// previous width (shrinking by 5 pt on a decrease to 10 pt rather than expanding as if 1 pt).
let (_, r) = lookup::annot_ref(&mut doc, 0, index).unwrap();
doc.update_dict(r, |d| {
d.remove(b"BS");
d.set(b"Border".to_vec(), Object::Array(vec![Object::Real(0.0), Object::Real(0.0), Object::Real(20.0)]));
d.set(b"Rect".to_vec(), create::num_array(&[5.0, 85.0, 135.0, 115.0]));
})
.unwrap();
set_style(&mut doc, 0, index, StyleChange { color: None, opacity: None, width: Some(10.0), endings: None }, &meta("border-shrink")).unwrap();
let rect_from_border = rect_of(&doc, index);
for (a, b) in rect_from_border.iter().zip([10.0, 90.0, 130.0, 110.0]) {
assert!((a - b).abs() < 1e-4, "expected [10, 90, 130, 110], got {rect_from_border:?}");
}
}
/// A 3D annotation is PDF 1.6 and a PRC model 1.7 (ISO 32000-2 §13.6): an older document's
/// catalog says so, and a newer one is left as it is.
#[test]
fn a_3d_model_raises_an_older_document_to_its_version() {
let catalog_version = |doc: &Document| {
let root = doc.root().unwrap();
doc.get(root).as_dict().unwrap().name(b"Version").map(<[u8]>::to_vec)
};
let add = |doc: &mut Document, model: &[u8]| {
let new = NewModel3d { page: 0, rect: [100.0, 100.0, 300.0, 300.0], model, activation: Activation3d::default(), poster: None, contents: "" };
add_3d_model(doc, &new, &meta("m")).unwrap();
};
let mut doc = fixture();
add(&mut doc, b"U3D\0rest");
assert_eq!(catalog_version(&reopen(&doc)), None, "a 1.7 file needs nothing for U3D");
for (model, version) in [(&b"U3D\0rest"[..], &b"1.6"[..]), (b"PRC rest", b"1.7")] {
let mut doc = fixture();
doc.set_version("1.4");
add(&mut doc, model);
assert_eq!(catalog_version(&reopen(&doc)).as_deref(), Some(version));
}
let mut doc = fixture();
doc.set_version("2.0");
add(&mut doc, b"PRC rest");
assert_eq!(catalog_version(&reopen(&doc)), None, "a 2.0 file takes PRC as it is");
}
/// Before 2.0, PRC is an Adobe extension to PDF 1.7 (§7.12): a PRC model declares it, keeping
/// other extensions and a later ADBE level; U3D and a 2.0 file need nothing.
#[test]
fn a_prc_model_declares_the_adobe_extension_before_pdf_2() {
let adbe = |doc: &Document| {
let root = doc.root().unwrap();
let ext = doc.get(root).as_dict().unwrap().get(b"Extensions").map(|e| doc.resolve(e).as_dict().unwrap().clone());
ext.map(|e| {
let adbe = e.get(b"ADBE").map(|a| a.as_dict().unwrap().clone());
(e.get(b"XYZ").is_some(), adbe.map(|a| (a.name(b"BaseVersion").map(<[u8]>::to_vec), a.get(b"ExtensionLevel").and_then(Object::as_int))))
})
};
let add = |doc: &mut Document, model: &[u8]| {
let new = NewModel3d { page: 0, rect: [100.0, 100.0, 300.0, 300.0], model, activation: Activation3d::default(), poster: None, contents: "" };
add_3d_model(doc, &new, &meta("m")).unwrap();
};
let mut doc = fixture();
add(&mut doc, b"PRC rest");
assert_eq!(adbe(&reopen(&doc)), Some((false, Some((Some(b"1.7".to_vec()), Some(1))))));
let mut doc = fixture();
add(&mut doc, b"U3Drest");
assert_eq!(adbe(&reopen(&doc)), None, "U3D is in ISO 32000-1");
let mut doc = fixture();
doc.set_version("2.0");
add(&mut doc, b"PRC rest");
assert_eq!(adbe(&reopen(&doc)), None, "PRC is in ISO 32000-2");
let mut doc = fixture();
let root = doc.root().unwrap();
let mut level3 = Dict::new();
level3.set(b"BaseVersion".to_vec(), Object::name("1.7"));
level3.set(b"ExtensionLevel".to_vec(), Object::Int(3));
let mut ext = Dict::new();
ext.set(b"ADBE".to_vec(), Object::Dict(level3));
ext.set(b"XYZ".to_vec(), Object::Dict(Dict::new()));
doc.update_dict(root, |c| c.set(b"Extensions".to_vec(), Object::Dict(ext.clone()))).unwrap();
add(&mut doc, b"PRC rest");
assert_eq!(adbe(&reopen(&doc)), Some((true, Some((Some(b"1.7".to_vec()), Some(3))))), "a later level is kept");
ext.remove(b"ADBE");
let mut doc = fixture();
doc.update_dict(root, |c| c.set(b"Extensions".to_vec(), Object::Dict(ext))).unwrap();
add(&mut doc, b"PRC rest");
assert_eq!(adbe(&reopen(&doc)), Some((true, Some((Some(b"1.7".to_vec()), Some(1))))), "other extensions are kept");
let mut doc = fixture();
let mut ext = Dict::new();
ext.set(b"ADBE".to_vec(), Object::Array(vec![Object::Dict(Dict::new())]));
let ext = doc.add(Object::Dict(ext));
doc.update_dict(root, |c| c.set(b"Extensions".to_vec(), Object::Ref(ext))).unwrap();
add(&mut doc, b"PRC rest");
let doc = reopen(&doc);
let ext = doc.resolve(doc.get(doc.root().unwrap()).as_dict().unwrap().get(b"Extensions").unwrap());
assert!(ext.as_dict().unwrap().get(b"ADBE").unwrap().as_array().is_some(), "an array of ADBE extensions is left alone");
}
#[test]
fn a_picture_is_placed_by_its_box_and_a_form_needs_a_positive_size() {
let at = [10.0, 20.0, 110.0, 70.0];
assert_eq!(appearance::picture_place(at, true, None).as_deref(), Some("100 0 0 50 10 20 cm"), "an image fills its unit square");
assert_eq!(appearance::picture_place(at, false, Some((200.0, 25.0))).as_deref(), Some("0.5 0 0 2 10 20 cm"));
for size in [None, Some((0.0, 25.0)), Some((200.0, -1.0))] {
assert_eq!(appearance::picture_place(at, false, size), None, "{size:?}");
}
}
/// The poster's box must lie in the rectangle, and a form poster needs a size to scale by.
#[test]
fn a_3d_poster_outside_its_rectangle_or_without_a_size_is_refused() {
let picture = |at: [f64; 4], size: (f64, f64)| PosterPicture { xobject: ObjRef { num: 6, generation: 0 }, image: false, size, at };
for (poster, why) in [
(picture([50.0, 100.0, 250.0, 300.0], (10.0, 10.0)), "starts left of the rectangle"),
(picture([100.0, 100.0, 300.0, 301.0], (10.0, 10.0)), "ends above it"),
(picture([100.0, 100.0, 300.0, 300.0], (0.0, 10.0)), "has no width"),
(picture([100.0 - 2e-7, 150.0, 100.0 - 1e-7, 200.0], (10.0, 10.0)), "lies outside within the rounding slack"),
] {
let mut doc = fixture();
let new = NewModel3d {
page: 0,
rect: [100.0, 100.0, 300.0, 300.0],
model: b"PRC rest",
activation: Activation3d::default(),
poster: Some(poster),
contents: "",
};
assert!(matches!(add_3d_model(&mut doc, &new, &meta("m")), Err(AnnotError::Invalid(_))), "{why}");
assert_eq!(list(&doc, 0).len(), 1, "{why}: nothing added");
}
}
/// A poster box fitted to the rectangle in floating point ends an ulp outside it: a 7×3 picture
/// centred in [0 100 3.6 110.8] spans -2.2e-16 to 3.6000000000000005. It is taken, inside the
/// rectangle.
#[test]
fn a_3d_poster_fitted_to_its_rectangle_with_rounding_is_taken() {
let mut doc = fixture();
let at = [-2.220446049250313e-16, 104.62857142857143, 3.6000000000000005, 106.17142857142858];
let poster = PosterPicture { xobject: ObjRef { num: 6, generation: 0 }, image: false, size: (7.0, 3.0), at };
let new = NewModel3d {
page: 0,
rect: [0.0, 100.0, 3.6, 110.8],
model: b"PRC rest",
activation: Activation3d::default(),
poster: Some(poster),
contents: "",
};
assert_eq!(add_3d_model(&mut doc, &new, &meta("m")), Ok(1));
}
#[test]
fn indirect_typewriter_names_keep_outer_whitespace_in_summaries() {
let mut doc = fixture();
let intent = Object::Ref(doc.add(Object::name("FreeTextTypeWriter")));
let page = page_refs(&doc).unwrap()[0];
let mut entries = annots(&doc, page);
let Object::Dict(annotation) = &mut entries[0] else { panic!("fixture annotation is inline") };
annotation.set(b"Subtype".to_vec(), Object::name("FreeText"));
annotation.set(b"IT".to_vec(), intent);
let contents = " \nAda\n\nLovelace\n\n ";
annotation.set(b"Contents".to_vec(), PdfString::text(contents));
set_annots(&mut doc, page, entries).unwrap();
let check = |doc: &Document| {
let list = summaries(doc);
let summary = list.iter().find(|a| a.page == 0 && a.index == 0).expect("direct Subtype is listed");
assert_eq!(summary.contents.as_deref(), Some(contents), "indirect typewriter intent preserves outer whitespace");
assert_eq!(summary.subtype, "FreeText");
assert_eq!(summary.intent.as_deref(), Some("FreeTextTypeWriter"));
assert!(summary.fill_sign, "indirect intent still identifies a Fill & Sign mark");
};
check(&doc);
check(&reopen(&doc));
}
+292
View File
@@ -0,0 +1,292 @@
//! 3D annotations (ISO 32000-2 §13.6.2): a U3D or PRC model shown in a rectangle on a page,
//! with a poster (`/AP /N`) for printing, for readers without 3D, and until it is activated.
use super::create::{finite, normalize, num_array};
use super::lookup::{annots, page_ref, set_annots};
use super::types::{FLAG_PRINT, Meta};
use super::{AnnotError, Dict, Document, ObjRef, Object, PdfString, Stream, appearance, n};
/// The largest model accepted, in bytes: well past real U3D/PRC files, and bounded because the
/// model is held and compressed in memory.
pub const MAX_MODEL_BYTES: usize = 256 << 20;
/// What the poster says when there is no picture.
const PLACEHOLDER_LABEL: &str = "3D model";
/// A 3D stream's data format (§13.6.3): ECMA-363 U3D or ISO 14739-1 PRC.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ModelFormat {
U3d,
Prc,
}
impl ModelFormat {
/// The format a model file's first bytes declare: U3D files start `U3D\0` (ECMA-363 file
/// header block type), PRC files start `PRC`.
///
/// # Errors
///
/// [`AnnotError::NotAModel`] for anything else.
pub fn detect(bytes: &[u8]) -> Result<Self, AnnotError> {
if bytes.starts_with(b"U3D\0") {
Ok(Self::U3d)
} else if bytes.starts_with(b"PRC") {
Ok(Self::Prc)
} else {
Err(AnnotError::NotAModel)
}
}
/// The 3D stream's `/Subtype`.
pub fn subtype(self) -> &'static str {
match self {
Self::U3d => "U3D",
Self::Prc => "PRC",
}
}
/// The PDF version a document holding it needs (§13.6): a 3D annotation is 1.6, a PRC stream
/// 1.7 under Adobe's extension, declared by [`add_3d_model`] (PDF 2.0 takes PRC as standard).
pub fn version(self) -> &'static str {
match self {
Self::U3d => "1.6",
Self::Prc => "1.7",
}
}
}
/// When a reader turns the poster into the live model (§13.6.2, the activation dictionary's
/// `/A`). The standard's default is [`Self::Click`].
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Activation {
/// `/XA`: when the user clicks it; it prints as its poster.
#[default]
Click,
/// `/PO`: when the page opens.
PageOpen,
/// `/PV`: when the page becomes visible.
PageVisible,
}
impl Activation {
/// Every activation, with the word a tool argument names it by.
pub const ALL: [(Self, &'static str); 3] = [(Self::Click, "click"), (Self::PageOpen, "page_open"), (Self::PageVisible, "page_visible")];
/// The `/A` name.
pub fn name(self) -> &'static str {
match self {
Self::Click => "XA",
Self::PageOpen => "PO",
Self::PageVisible => "PV",
}
}
}
/// A picture already in the document (an image XObject, or a form XObject whose `/Matrix` maps it
/// to `size` points) drawn into `at`, a box inside the annotation's rectangle.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct PosterPicture {
pub xobject: ObjRef,
pub image: bool,
pub size: (f64, f64),
pub at: [f64; 4],
}
/// A 3D model to add on `page` (0-based) in `rect` (user space).
#[derive(Clone, Debug, PartialEq)]
pub struct NewModel3d<'a> {
pub page: usize,
pub rect: [f64; 4],
pub model: &'a [u8],
pub activation: Activation,
/// The poster's picture; `None` draws a labelled frame.
pub poster: Option<PosterPicture>,
/// `/Contents`: the annotation's alternate description (§12.5.2).
pub contents: &'a str,
}
/// Check a model before anything is added: its size and its format.
///
/// # Errors
///
/// [`AnnotError::ModelTooLarge`] past [`MAX_MODEL_BYTES`], else as [`ModelFormat::detect`].
pub fn check_model(model: &[u8]) -> Result<ModelFormat, AnnotError> {
check_model_size(model, MAX_MODEL_BYTES)?;
ModelFormat::detect(model)
}
fn check_model_size(model: &[u8], max: usize) -> Result<(), AnnotError> {
if model.len() > max {
return Err(AnnotError::ModelTooLarge { size: model.len(), max });
}
Ok(())
}
/// Add a 3D annotation: the model in a Flate-compressed 3D stream referenced from `/3DD` (so the
/// annotation has its own instance, §13.6.2), `/3DA` stating only `/A`, and the poster as `/AP /N`.
/// No view (`/3DV`, `/VA`) is written: readers open on the model's own default view. A document
/// older than [`ModelFormat::version`] is raised to it. Returns its index in the page's `/Annots`.
///
/// # Errors
///
/// As [`check_model`]; [`AnnotError::NoSuchPage`]; [`AnnotError::Invalid`] for a rectangle with no
/// area or a poster box outside it.
pub fn add_3d_model(doc: &mut Document, new: &NewModel3d<'_>, meta: &Meta) -> Result<usize, AnnotError> {
let format = check_model(new.model)?;
let page = page_ref(doc, new.page)?;
let rect = normalize(new.rect);
if !finite(&new.rect) || rect[2] - rect[0] < 1.0 || rect[3] - rect[1] < 1.0 {
return Err(AnnotError::Invalid("invalid rectangle for the 3D model (each side at least 1 pt)".into()));
}
let poster = match &new.poster {
Some(p) => picture_poster(rect, p)?,
None => placeholder_poster(rect),
};
let mut stream = Dict::new();
stream.set(b"Type".to_vec(), Object::name("3D"));
stream.set(b"Subtype".to_vec(), Object::name(format.subtype()));
let stream = doc.add(Object::Stream(Stream::flate(stream, new.model)));
let poster = doc.add(Object::Stream(poster));
let d = annotation_dict(new, rect, page, stream, poster, meta);
let r = doc.add(Object::Dict(d));
let mut list = annots(doc, page);
let index = list.len();
list.push(Object::Ref(r));
set_annots(doc, page, list)?;
at_least_version(doc, format.version())?;
if format == ModelFormat::Prc && !at_least(doc, "2.0") {
declare_prc_extension(doc)?;
}
Ok(index)
}
/// Whether the header or the catalog `/Version` says `min` or later (§7.7.2).
fn at_least(doc: &Document, min: &str) -> bool {
let reached = |v: &[u8]| v.len() >= 3 && v >= min.as_bytes();
let catalog = doc.root().and_then(|root| doc.get(root).as_dict().and_then(|c| c.get(b"Version").cloned()));
let catalog = catalog.and_then(|v| doc.resolve(&v).as_name().map(<[u8]>::to_vec));
reached(doc.version().as_bytes()) || catalog.as_deref().is_some_and(reached)
}
/// PRC came before PDF 2.0 as an Adobe extension to 1.7: such a file declares
/// `/Extensions /ADBE` with ExtensionLevel 1 or later (§7.12). Other extensions and an ADBE entry
/// that already has a level are kept; one that is not a dictionary (an array of them) is left alone.
fn declare_prc_extension(doc: &mut Document) -> Result<(), AnnotError> {
let Some(root) = doc.root() else { return Ok(()) };
let catalog = doc.get(root);
// `None` when present but not a dictionary; an empty one when absent.
let dict_or_new = |o: Option<&Object>| match o.map(|o| doc.resolve(o)) {
None => Some(Dict::new()),
Some(o) => o.as_dict().cloned(),
};
let Some(mut extensions) = dict_or_new(catalog.as_dict().and_then(|c| c.get(b"Extensions"))) else { return Ok(()) };
let Some(mut adbe) = dict_or_new(extensions.get(b"ADBE")) else { return Ok(()) };
if adbe.get(b"ExtensionLevel").map(|l| doc.resolve(l)).and_then(|l| l.as_int()).is_some_and(|l| l >= 1) {
return Ok(());
}
adbe.set(b"BaseVersion".to_vec(), Object::name("1.7"));
adbe.set(b"ExtensionLevel".to_vec(), Object::Int(1));
extensions.set(b"ADBE".to_vec(), Object::Dict(adbe));
doc.update_dict(root, |c| c.set(b"Extensions".to_vec(), Object::Dict(extensions)))?;
Ok(())
}
/// A document whose header and catalog `/Version` both say less than `min` gets `/Version min` in
/// its catalog (§7.7.2: the later of the two applies).
fn at_least_version(doc: &mut Document, min: &str) -> Result<(), AnnotError> {
let Some(root) = doc.root() else { return Ok(()) };
if !at_least(doc, min) {
doc.update_dict(root, |c| c.set(b"Version".to_vec(), Object::name(min)))?;
}
Ok(())
}
fn annotation_dict(new: &NewModel3d<'_>, rect: [f64; 4], page: ObjRef, stream: ObjRef, poster: ObjRef, meta: &Meta) -> Dict {
let mut d = Dict::new();
d.set(b"Type".to_vec(), Object::name("Annot"));
d.set(b"Subtype".to_vec(), Object::name("3D"));
d.set(b"Rect".to_vec(), num_array(&rect));
d.set(b"P".to_vec(), Object::Ref(page));
d.set(b"F".to_vec(), Object::Int(FLAG_PRINT));
if !new.contents.is_empty() {
d.set(b"Contents".to_vec(), PdfString::text(new.contents));
}
if !meta.id.is_empty() {
d.set(b"NM".to_vec(), PdfString::text(&meta.id));
}
if let Some(date) = &meta.date {
d.set(b"M".to_vec(), PdfString::literal(date.as_bytes().to_vec()));
}
d.set(b"3DD".to_vec(), Object::Ref(stream));
let mut activation = Dict::new();
activation.set(b"A".to_vec(), Object::name(new.activation.name()));
d.set(b"3DA".to_vec(), Object::Dict(activation));
let mut ap = Dict::new();
ap.set(b"N".to_vec(), Object::Ref(poster));
d.set(b"AP".to_vec(), Object::Dict(ap));
d
}
/// The poster drawing `p` into its box, which must lie within `rect`.
fn picture_poster(rect: [f64; 4], p: &PosterPicture) -> Result<Stream, AnnotError> {
let at = normalize(p.at);
// A box fitted to `rect` in floating point can end a few ulps outside it: allow that, then clamp.
let slack = rect.iter().fold(1.0_f64, |m, v| m.max(v.abs())) * 1e-9;
let near = finite(&p.at) && at[0] >= rect[0] - slack && at[1] >= rect[1] - slack && at[2] <= rect[2] + slack && at[3] <= rect[3] + slack;
let at = [at[0].max(rect[0]), at[1].max(rect[1]), at[2].min(rect[2]), at[3].min(rect[3])];
if !(near && at[2] > at[0] && at[3] > at[1]) {
return Err(AnnotError::Invalid("the poster must fit inside the 3D model's rectangle".into()));
}
let place = appearance::picture_place(at, p.image, Some(p.size)).ok_or_else(|| AnnotError::Invalid("the poster picture has no size".into()))?;
let mut xobjects = Dict::new();
xobjects.set(b"Pic".to_vec(), Object::Ref(p.xobject));
let mut resources = Dict::new();
resources.set(b"XObject".to_vec(), Object::Dict(xobjects));
Ok(appearance::form(rect, format!("q {place} /Pic Do Q\n").as_bytes(), resources))
}
/// A light frame with "3D model" centred in it, shrunk to fit (left out when even 2 pt won't).
fn placeholder_poster(rect: [f64; 4]) -> Stream {
let [x0, y0, x1, y1] = rect;
let (w, h) = (x1 - x0, y1 - y0);
let mut c =
format!("0.94 g {} {} {} {} re f\n0.45 G 1 w {} {} {} {} re S\n", n(x0), n(y0), n(w), n(h), n(x0 + 0.5), n(y0 + 0.5), n(w - 1.0), n(h - 1.0));
let mut resources = Dict::new();
let unit = appearance::text_width(PLACEHOLDER_LABEL, 1.0);
let size = if unit > 0.0 { (w * 0.8 / unit).min(h * 0.4).min(14.0) } else { 0.0 };
if size >= 2.0 {
let (tx, ty) = (x0 + (w - unit * size) / 2.0, y0 + (h - size * 0.7) / 2.0);
c.push_str(&format!("BT 0.3 g /Helv {} Tf {} {} Td ({PLACEHOLDER_LABEL}) Tj ET\n", n(size), n(tx), n(ty)));
resources.set(b"Font".to_vec(), appearance::helvetica_resource());
}
appearance::form(rect, c.as_bytes(), resources)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn model_size_is_capped() {
assert_eq!(check_model_size(&[0; 8], 8), Ok(()));
assert_eq!(check_model_size(&[0; 9], 8), Err(AnnotError::ModelTooLarge { size: 9, max: 8 }));
}
#[test]
fn the_format_is_read_from_the_header() {
assert_eq!(ModelFormat::detect(b"U3D\0rest"), Ok(ModelFormat::U3d));
assert_eq!(ModelFormat::detect(b"PRC8800"), Ok(ModelFormat::Prc));
for junk in [&b""[..], b"U3D", b"U3DX", b"PR", b"%PDF-1.7", b"prc"] {
assert_eq!(ModelFormat::detect(junk), Err(AnnotError::NotAModel), "{junk:?}");
}
}
#[test]
fn the_placeholder_label_shrinks_to_fit_and_is_dropped_when_it_cannot() {
let wide = String::from_utf8(placeholder_poster([0.0, 0.0, 300.0, 200.0]).decoded().unwrap().to_vec()).unwrap();
assert!(wide.contains("/Helv 14 Tf") && wide.contains("(3D model) Tj"), "{wide}");
let tiny = placeholder_poster([0.0, 0.0, 4.0, 4.0]);
assert!(!String::from_utf8(tiny.decoded().unwrap().to_vec()).unwrap().contains("Tj"));
assert!(tiny.dict.get(b"Resources").and_then(Object::as_dict).is_none_or(|r| r.get(b"Font").is_none()));
}
}
+7 -1
View File
@@ -355,6 +355,10 @@ pub enum Shape {
start: LineEnding,
end: LineEnding,
},
/// Translucent freehand highlighting, stored as ink with a distinct intent.
FreehandHighlight {
strokes: Vec<Vec<[f64; 2]>>,
},
/// Freehand strokes (Draw tool).
Ink {
strokes: Vec<Vec<[f64; 2]>>,
@@ -474,6 +478,7 @@ pub fn rect_quad(r: [f64; 4]) -> [f64; 8] {
}
impl Shape {
/// Return the PDF `/Subtype` name for this annotation shape.
pub fn subtype(&self) -> &'static str {
match self {
Shape::Note { .. } => "Text",
@@ -481,7 +486,7 @@ impl Shape {
Shape::Rectangle { .. } => "Square",
Shape::Oval { .. } => "Circle",
Shape::Line { .. } => "Line",
Shape::Ink { .. } | Shape::Signature { .. } => "Ink",
Shape::Ink { .. } | Shape::FreehandHighlight { .. } | Shape::Signature { .. } => "Ink",
Shape::TextBox { .. } | Shape::Typewriter { .. } | Shape::Callout { .. } => "FreeText",
Shape::Mark { .. } | Shape::Stamp { .. } | Shape::CustomStamp { .. } | Shape::TypedSignature { .. } => "Stamp",
Shape::Redact { .. } => "Redact",
@@ -610,6 +615,7 @@ impl Style {
}
Shape::Callout { .. } => ([0.0, 0.0, 0.0], 1.0),
Shape::Caret { .. } | Shape::Attachment { .. } => ([0.0, 0.47, 0.84], 1.0),
Shape::FreehandHighlight { .. } => return Self { color: [1.0, 0.94, 0.0], opacity: 0.35, width: 14.0, fill: None },
Shape::Ink { .. } => ([0.0, 0.4, 0.87], 2.0),
Shape::TextBox { .. } | Shape::Typewriter { .. } => ([0.0, 0.0, 0.0], 0.0),
Shape::Mark { .. } => ([0.0, 0.0, 0.0], 1.5),
+19 -18
View File
@@ -15,7 +15,7 @@
//! the joined stream)`; rectangles inside a form XObject carry the `Do` operator's position.
//! Positions compare lexicographically in paint order.
use pdfcraft_content::{Matrix, Op, Pieces, parse};
use pdfcraft_content::{Matrix, Op, Pieces, ops};
use pdfcraft_cos::{DecodeBudget, Dict, Document, Object};
use crate::AuditError;
@@ -123,12 +123,13 @@ impl<'a> Walker<'a> {
Ok(())
}
/// Walk one operator slice with the given graphics state. `at_do` is the `Do` position to
/// Walk one stream's operators, read one at a time (a stream of millions of short operators
/// is never held whole), with the given graphics state. `at_do` is the `Do` position to
/// stamp on rectangles found inside a form XObject, or `None` at page level (where each
/// fill operator's own position is used).
fn walk_ops(
&mut self,
ops: &[Op],
ops: impl Iterator<Item = Op>,
gs: &mut Gs,
stack: &mut Vec<Gs>,
resources: &Dict,
@@ -136,8 +137,9 @@ impl<'a> Walker<'a> {
at_do: Option<(usize, usize)>,
) -> Result<(), AuditError> {
let mut path = Path::Empty;
for (i, op) in ops.iter().enumerate() {
for (i, op) in ops.enumerate() {
self.bump()?;
let op = &op;
// Paint position of this operator: its own `(piece, joined index)` at page level,
// the enclosing `Do`'s position inside a form XObject.
let pos = match at_do {
@@ -257,8 +259,9 @@ impl<'a> Walker<'a> {
/// changes inside never leak out; every rectangle found is stamped with the `Do`
/// position `pos`.
fn walk_xobject(&mut self, name: &[u8], gs: &Gs, resources: &Dict, depth: usize, pos: (usize, usize)) -> Result<(), AuditError> {
let xobjects = resources.get(b"XObject").map(|o| self.doc.resolve(o)).and_then(|o| o.as_dict().cloned()).unwrap_or_default();
let Some(entry) = xobjects.get(name) else { return Ok(()) };
// Borrowed, not copied: a `Do` must not cost the size of the whole XObject table.
let xobjects = resources.get(b"XObject").map(|o| self.doc.resolve(o));
let Some(entry) = xobjects.as_deref().and_then(Object::as_dict).and_then(|d| d.get(name)) else { return Ok(()) };
let resolved = self.doc.resolve(entry);
let Object::Stream(stream) = &*resolved else { return Ok(()) };
let dict = &stream.dict;
@@ -274,18 +277,18 @@ impl<'a> Walker<'a> {
(v.len() == 6 && v.iter().all(|x| x.is_finite())).then(|| Matrix([v[0], v[1], v[2], v[3], v[4], v[5]]))
})
.unwrap_or(Matrix::IDENTITY);
let sub_resources = dict.get(b"Resources").map(|o| self.doc.resolve(o)).and_then(|o| o.as_dict().cloned()).unwrap_or_default();
let (sub_resources, empty) = (dict.get(b"Resources").map(|o| self.doc.resolve(o)), Dict::new());
let sub_resources = sub_resources.as_deref().and_then(Object::as_dict).unwrap_or(&empty);
if !self.budget.enter_form() {
return Err(AuditError::TooManyForms);
}
// A form stream that cannot be decoded fails the audit: it might hide a cover.
let data = self.budget.decode_strict(stream)?;
let ops = parse(&data).ops;
// The XObject matrix maps form space into the user space active at `Do`.
let mut sub_gs = gs.clone();
sub_gs.ctm = matrix.then(&gs.ctm);
let mut sub_stack = Vec::new();
self.walk_ops(&ops, &mut sub_gs, &mut sub_stack, &sub_resources, depth + 1, Some(pos))
self.walk_ops(ops(&data), &mut sub_gs, &mut sub_stack, sub_resources, depth + 1, Some(pos))
}
}
@@ -298,13 +301,10 @@ fn user_point(gs: &Gs, op: &Op) -> Option<[f64; 2]> {
/// The non-stroking alpha (`/ca`) of a named ExtGState, defaulting to opaque.
fn ext_alpha(doc: &Document, resources: &Dict, name: &[u8]) -> f64 {
let alpha = resources
.get(b"ExtGState")
.map(|o| doc.resolve(o))
.and_then(|o| o.as_dict().cloned())
.and_then(|d| d.get(name).map(|o| doc.resolve(o)))
.and_then(|o| o.as_dict().cloned())
.and_then(|d| d.get(b"ca").map(|o| doc.resolve(o)).and_then(|o| o.as_f64()));
// Borrowed, not copied: a `gs` must not cost the size of the whole ExtGState table.
let states = resources.get(b"ExtGState").map(|o| doc.resolve(o));
let state = states.as_deref().and_then(Object::as_dict).and_then(|d| d.get(name)).map(|o| doc.resolve(o));
let alpha = state.as_deref().and_then(Object::as_dict).and_then(|d| d.get(b"ca").map(|o| doc.resolve(o)).and_then(|o| o.as_f64()));
alpha.filter(|a| a.is_finite()).map(|a| a.clamp(0.0, 1.0)).unwrap_or(1.0)
}
@@ -330,10 +330,11 @@ pub fn filled_rects(doc: &Document, page: &Dict) -> Result<Vec<FilledRect>, Audi
}
}
let pieces = Pieces::join(&streams);
let parsed = pieces.parse();
let mut w = Walker { doc, pieces: &pieces, out: Vec::new(), ops_seen: 0, budget };
let mut gs = Gs::default();
let mut stack = Vec::new();
w.walk_ops(&parsed.ops, &mut gs, &mut stack, &resources, 0, None)?;
// Read one operator at a time: the joined stream can hold millions of them within the
// decode budget, and the walk only ever needs the current one.
w.walk_ops(ops(pieces.data()), &mut gs, &mut stack, &resources, 0, None)?;
Ok(w.out)
}
+38 -19
View File
@@ -99,6 +99,9 @@ const COVER_FRACTION: f64 = 0.4;
const WORD_FRACTION: f64 = 0.5;
/// WCAG contrast ratio below which the text is unreadable against the cover.
const COVER_CONTRAST: f64 = 3.0;
/// Bytes of a hidden line's text read (copied or trimmed) that cost one comparison: a byte scan
/// is far cheaper than a box comparison, but a long padded line under many covers adds up.
const TEXT_BYTES_PER_COMPARISON: usize = 16;
/// Audit every page for faux redactions and unapplied redaction marks. Fails closed: any
/// content that cannot be decoded, or that needs more work or report than the audit's bounds, is
@@ -157,15 +160,24 @@ impl Budget {
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);
}
self.spend(self.page_cost)?;
if !copying {
return Ok(lines.iter().any(|line| hides(line) && !line.text.trim().is_empty()).then(String::new));
let mut hidden = false;
for line in lines.iter().filter(|l| hides(l)) {
// Trimming walks the line's text (padding and all): it costs its bytes.
self.spend(line.text.len() / TEXT_BYTES_PER_COMPARISON)?;
if !line.text.trim().is_empty() {
hidden = true;
break;
}
}
return Ok(hidden.then(String::new));
}
let mut covered = String::new();
for line in lines.iter().filter(|l| hides(l)) {
// Copying and trimming the line walks its text once per cover: a long padded
// line under many covers would otherwise be read far more than its runs suggest.
self.spend(line.text.len() / TEXT_BYTES_PER_COMPARISON)?;
if !covered.is_empty() {
covered.push(' ');
}
@@ -174,11 +186,21 @@ impl Budget {
Ok((!covered.trim().is_empty()).then_some(covered))
}
/// `n` units of work done against the comparison bound.
fn spend(&mut self, n: usize) -> Result<(), AuditError> {
self.comparisons = self.comparisons.saturating_add(n);
if self.comparisons > self.limits.comparisons {
return Err(AuditError::TooManyComparisons);
}
Ok(())
}
/// The text a finding reports for `covered`: none when copying is withheld. Charges what it
/// reports against the output bound.
/// reports, and the finding's own record, against the output bound: a finding with no text
/// (copying withheld, or a shared annotation list on many pages) still takes memory.
fn report_text(&mut self, covered: String, copying: bool) -> Result<String, AuditError> {
let reported = if copying { covered } else { String::new() };
self.covered_text = self.covered_text.saturating_add(reported.len());
self.covered_text = self.covered_text.saturating_add(reported.len()).saturating_add(std::mem::size_of::<AuditFinding>());
if self.covered_text > self.limits.covered_text {
return Err(AuditError::TooMuchOutput);
}
@@ -321,17 +343,14 @@ enum AnnotationCover {
fn annots(doc: &Document, page: &Dict) -> Result<Vec<AnnotationCover>, AuditError> {
let Some(a) = page.get(b"Annots") else { return Ok(Vec::new()) };
let resolved = doc.resolve(a);
let items: Vec<pdfcraft_cos::Object> = match &*resolved {
pdfcraft_cos::Object::Array(items) => items.clone(),
// A missing /Annots means no marks; a malformed one fails the audit.
_ => return Err(AuditError::BadAnnots),
};
// A missing /Annots means no marks; a malformed one fails the audit.
let Some(items) = resolved.as_array() else { return Err(AuditError::BadAnnots) };
let mut out = Vec::new();
for a in &items {
let dict = match &*doc.resolve(a) {
pdfcraft_cos::Object::Dict(d) => d.clone(),
_ => continue,
};
for a in items {
// Borrowed from the resolved object: one large dictionary listed many times is not
// copied once per listing.
let resolved = doc.resolve(a);
let Some(dict) = resolved.as_dict() else { continue };
let v: Vec<f64> = match dict.get(b"Rect") {
None => continue,
Some(r) => doc.resolve(r).as_array().map(|arr| arr.iter().filter_map(|o| doc.resolve(o).as_f64()).collect()).unwrap_or_default(),
@@ -340,7 +359,7 @@ fn annots(doc: &Document, page: &Dict) -> Result<Vec<AnnotationCover>, AuditErro
continue;
}
let rect = [v[0].min(v[2]), v[1].min(v[3]), v[0].max(v[2]), v[1].max(v[3])];
match subtype(doc, &dict)?.as_deref() {
match subtype(doc, dict)?.as_deref() {
Some(b"Redact") => out.push(AnnotationCover::Redact(rect)),
Some(b"Square") => {
let flags = dict.get(b"F").and_then(|f| doc.resolve(f).as_int()).unwrap_or(0);
@@ -349,7 +368,7 @@ fn annots(doc: &Document, page: &Dict) -> Result<Vec<AnnotationCover>, AuditErro
}
let alpha = dict.get(b"CA").map(|o| doc.resolve(o)).and_then(|o| o.as_f64()).unwrap_or(1.0);
if alpha >= 1.0
&& let Some(rgb) = annotation_color(doc, &dict, b"IC")
&& let Some(rgb) = annotation_color(doc, dict, b"IC")
{
out.push(AnnotationCover::Square { rect, rgb });
}
+60 -5
View File
@@ -720,9 +720,11 @@ fn runs_without_words_count_against_the_comparison_bound() {
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 };
// Plus the hidden line's text, read once to copy it.
let text = lines[0].text.len() / crate::TEXT_BYTES_PER_COMPARISON;
let limits = crate::Limits { comparisons: 50 + text, covered_text: usize::MAX };
assert!(matches!(crate::audit(&doc, limits), Err(crate::AuditError::TooManyComparisons)));
let limits = crate::Limits { comparisons: 51, covered_text: usize::MAX };
let limits = crate::Limits { comparisons: 51 + text, covered_text: usize::MAX };
assert_eq!(crate::audit(&doc, limits).expect("within the budget").len(), 1);
}
@@ -746,14 +748,18 @@ fn copy_restricted_documents_withhold_covered_text() {
let findings = audit_redactions(&user).expect("audit must run");
assert_eq!(findings.len(), 1, "the cover is still reported: {findings:?}");
assert_eq!(findings[0].covered_text, "");
// The output bound counts the text reported, so withheld text costs nothing.
let nothing = crate::Limits { comparisons: usize::MAX, covered_text: 0 };
// The output bound counts the text reported and the finding's record, so withheld text
// costs only the record.
let record = std::mem::size_of::<AuditFinding>();
let nothing = crate::Limits { comparisons: usize::MAX, covered_text: record };
assert_eq!(crate::audit(&user, nothing).expect("withheld text is not output").len(), 1);
let none = crate::Limits { covered_text: record - 1, ..nothing };
assert!(matches!(crate::audit(&user, none), Err(crate::AuditError::TooMuchOutput)));
let owner = Document::open_with_password(bytes, Some("owner")).expect("open");
let findings = audit_redactions(&owner).expect("audit must run");
assert_eq!(findings.len(), 1, "{findings:?}");
assert_eq!(findings[0].covered_text, "SECRET DATA 123");
let exact = crate::Limits { comparisons: usize::MAX, covered_text: "SECRET DATA 123".len() };
let exact = crate::Limits { comparisons: usize::MAX, covered_text: "SECRET DATA 123".len() + record };
assert!(crate::audit(&owner, exact).is_ok());
let short = crate::Limits { covered_text: exact.covered_text - 1, ..exact };
assert!(matches!(crate::audit(&owner, short), Err(crate::AuditError::TooMuchOutput)));
@@ -820,3 +826,52 @@ fn form_entries_past_the_page_allowance_fail_the_audit() {
let page: Dict = [(b"Contents".to_vec(), Object::Ref(draws)), (b"Resources".to_vec(), Object::Dict(resources))].into_iter().collect();
assert!(matches!(crate::cover::filled_rects(&doc, &page), Err(crate::AuditError::TooManyForms)));
}
/// Copying a covered line's text walks all of it, padding included, so a long padded line under
/// many covers costs its bytes once per cover, not one run per cover (CodeRabbit).
#[test]
fn covered_text_bytes_count_against_the_comparison_bound() {
// One run: 20 KiB of spaces around a word, which trims to the word alone.
let mut content = b"BT /F1 24 Tf 100 700 Td (".to_vec();
content.extend_from_slice(&[b' '; 10_000]);
content.extend_from_slice(b"SECRET");
content.extend_from_slice(&[b' '; 10_000]);
content.extend_from_slice(b") Tj ET\n0 g\n");
for _ in 0..10 {
content.extend_from_slice(b"-1 688 1000000 32 re f\n");
}
let doc = open(one_page(&content, ""));
let lines = pdfcraft_edit::glyph_text_lines(&doc, &pdfcraft_model::pages(&doc)[0]).expect("text");
assert_eq!(lines.len(), 1);
let bytes = lines[0].text.len();
assert!(bytes > 20_000, "{bytes} bytes of text");
// Each cover: one comparison for the line, plus its bytes when it is hidden.
let exact = crate::Limits { comparisons: 10 * (1 + bytes / crate::TEXT_BYTES_PER_COMPARISON), covered_text: usize::MAX };
let findings = crate::audit(&doc, exact).expect("within the budget");
assert_eq!(findings.len(), 10, "{findings:?}");
assert!(findings.iter().all(|f| f.covered_text == "SECRET"), "{findings:?}");
let short = crate::Limits { comparisons: exact.comparisons - 1, ..exact };
assert!(matches!(crate::audit(&doc, short), Err(crate::AuditError::TooManyComparisons)));
}
/// One annotation list shared by many pages makes a finding on each: every finding's record
/// counts against the output bound, text or no text (CodeRabbit).
#[test]
fn every_finding_record_counts_against_the_output_bound() {
let content = b"BT /F1 24 Tf 100 700 Td (SECRET) Tj ET\n";
let mut b = Builder::new();
b.add("<< /Type /Catalog /Pages 2 0 R >>");
b.add("<< /Type /Pages /Kids [3 0 R 7 0 R 8 0 R] /Count 3 >>");
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(content);
b.add(FONT);
b.add("[<< /Type /Annot /Subtype /Redact /Rect [95 685 200 725] >>]");
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("<< /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 >>");
let doc = open(b.build());
let one = "SECRET".len() + std::mem::size_of::<AuditFinding>();
let exact = crate::Limits { comparisons: usize::MAX, covered_text: 3 * one };
assert_eq!(crate::audit(&doc, exact).expect("within the budget").len(), 3);
let short = crate::Limits { covered_text: 3 * one - 1, ..exact };
assert!(matches!(crate::audit(&doc, short), Err(crate::AuditError::TooMuchOutput)));
}
+2
View File
@@ -14,6 +14,8 @@ pdfcraft-cos = { workspace = true }
pdfcraft-render = { workspace = true }
pdfcraft-organize = { workspace = true }
pdfcraft-platform = { workspace = true }
pdfcraft-prc = { workspace = true }
pdfcraft-prc-render = { workspace = true }
serde_json = { workspace = true }
sha2 = "0.11"
tempfile = "3.27"
+27
View File
@@ -5,6 +5,8 @@ Agent control for PdfCraft: a headless tool table over the engine, and an opt-in
- **Layer:** L7 (architecture §13), but headless. It depends on `engine`, `render` and `organize`, never on a UI toolkit.
- **Status:** over a hundred tools; `pdfcraft-cli tools` lists the current set with their schemas (the count isn't repeated here, so it can't go stale). They cover inspection, rendering, text, page edits and organizing, page labels, bookmarks, comments and their review, form filling and authoring (fields, properties, scripts, data exchange, detection), redaction and sanitizing, password protection and signatures, calibrated 2D measurements and CSV export, adding text, images, links and stamps, optimizing, OCR, printing, export, metadata, undo/redo, save, combine, extract and split. Comment tools take geometry in the same top-left-origin points as everything else, and `comment_add` can mark text by searching for it (`find`). The MCP server also serves the open documents as resources, page images included. The running app's UI is driven separately, through the `ui.*` control channel in `pdfcraft-ui-egui`.
`fill_sign_add` text accepts line breaks, including blank lines. Its typewriter box grows to hold all wrapped rows, and saving/reopening preserves the contents and appearance.
## API
```rust
@@ -21,6 +23,9 @@ them with the image's current orientation. Full turns retain its appearance, rec
and flips. Angles that are not multiples of 90 are refused without changing the document or
its undo/redo history.
`page_add_text`, `content_update` and `text_edit` take per-line `aligns`. An `"inherit"` entry
follows the box-level `align`; legacy `null` entries remain accepted with the same meaning.
`Content` is `Json(Value)` or `Png { data, width, height }`. Errors are `UnknownTool`, `InvalidArgs` (the call didn't match the schema) or `Failed` (a readable message for the agent).
## Conventions
@@ -199,6 +204,19 @@ undoable and survive saving/reopening. `image_hit` shares the UI's curve and hol
The bounds, limits and font requirements are in [existing-text editing](../../docs/editing-existing-text.md)
and [image editing](../../docs/editing-images.md).
### Superscript and subscript normalization
`text_script` changes characters to their Unicode superscript or subscript forms; it does not
change the font size or baseline. For characters that have such forms, uniformly plain text
toggles to the requested script, and uniformly scripted text toggles back to plain text.
Characters without a matching form stay unchanged and do not determine the selection's state.
A selection mixing plain and target-script characters normalizes to the requested script.
For example, subscript changes `H₂2` to `H₂₂`, then to `H22` on the next call; superscript
changes `Q²2` to `Q²²`, then to `Q22`. A second toggle does not reconstruct the original
mixture. Each call is one undoable text edit: `edit_undo` restores the exact prior text,
including its original mixture. Save/reopen preserves the resulting normalized characters.
## Opening local GoToR links
`link_open {doc, page, index, password?}` follows a local PDF link using `link_list`
@@ -232,6 +250,15 @@ choices and values over 4096 UTF-8 bytes return an error.
Example: `form_set_props doc=1 field=agree export_value=Accepted widget=1`.
## Rendering a 3D model
`model_render` draws a page's 3D model (a 3D annotation's PRC stream, directly or through a 3D
reference) to a PNG, without the viewer. `model` picks the page's Nth 3D model (default 1);
`width` and `height` are 1 to 4096 (default 512); `direction` is the view direction from the eye
(default `[-1, 1, -1]`, with Z up unless the view looks along Z); `perspective` defaults to true.
The model is framed to fill the image and shaded by a headlight on white. U3D models are refused
with an error, and the annotation's own views, lighting and render modes are not applied yet.
## Viewer navigation history
A running PdfCraft instance launched with `--control FILE` exposes its per-tab history through
+8 -1
View File
@@ -6,6 +6,13 @@ impl Automation {
let ext = path.extension().map(|e| e.to_string_lossy().into_owned()).unwrap_or_default();
let format = pdfcraft_engine::compare::OfficeFormat::from_extension(&ext)
.ok_or_else(|| ToolError::InvalidArgs(format!("unsupported extension {ext:?} (docx, pptx, html, rtf or md)")))?;
let html_mode = a.opt_str("html_mode")?.unwrap_or("rich");
let format = match (format, html_mode) {
(pdfcraft_engine::compare::OfficeFormat::Html, "rich") => pdfcraft_engine::compare::OfficeFormat::Html,
(pdfcraft_engine::compare::OfficeFormat::Html, "simple") => pdfcraft_engine::compare::OfficeFormat::HtmlSimple,
(_, "rich") => format,
(_, _) => return Err(ToolError::InvalidArgs("html_mode is only available for HTML exports (rich or simple)".into())),
};
let export = self.doc_to_copy(a)?.export_office_checked(format);
write_atomic(&path, &export.bytes)?;
// Text left out to keep a hostile page bounded is said, not silent (#3120).
@@ -15,7 +22,7 @@ impl Automation {
if !export.truncated_pages.is_empty() {
use pdfcraft_engine::compare::{MAX_FORM_DEPTH, MAX_FORM_VISITS};
out["warnings"] = json!([format!(
"forms nested more than {MAX_FORM_DEPTH} deep, or past the first {MAX_FORM_VISITS} forms of a page (forms the page draws itself count too), were left out on the pages in truncated_pages: their text and images are missing from the export, although the viewer may still show them"
"pictures past what one export may hold or decode, or forms nested more than {MAX_FORM_DEPTH} deep, or past the first {MAX_FORM_VISITS} forms of a page (forms the page draws itself count too), were left out on the pages in truncated_pages: their text and images are missing from the export, although the viewer may still show them"
)]);
}
Ok(out)
+214
View File
@@ -0,0 +1,214 @@
use std::io::Write;
use pdfcraft_engine::{Edit, HeaderFooter};
use serde_json::{Value, json};
use super::error::{Result, ToolError, failed};
use super::json::Args;
use super::paths::read_input;
use super::{Arc, Automation, Path, PathBuf};
struct FilePlan {
input: String,
source: PathBuf,
password: Option<String>,
output: PathBuf,
pages: usize,
first: u64,
last: u64,
}
impl Automation {
pub(crate) fn doc_bates_multi(&mut self, args: &Args) -> Result<Value> {
let files = args.0.get("files").and_then(Value::as_array).ok_or_else(|| ToolError::InvalidArgs("files must be an array".into()))?;
if files.is_empty() || files.len() > 1000 {
return Err(ToolError::InvalidArgs("files must contain 1 to 1000 entries".into()));
}
let start = match args.0.get("start_number") {
None | Some(Value::Null) => 1,
Some(value) => value
.as_u64()
.filter(|n| *n >= 1)
.ok_or_else(|| ToolError::InvalidArgs("start_number must be a whole number of at least 1".into()))?,
};
let digits = args.opt_int("digits")?.unwrap_or(6);
let digits =
u8::try_from(digits).ok().filter(|d| (1..=12).contains(d)).ok_or_else(|| ToolError::InvalidArgs("digits must be from 1 to 12".into()))?;
let prefix = args.opt_str("prefix")?.unwrap_or("");
let suffix = args.opt_str("suffix")?.unwrap_or("");
// `#` separates the token's fields and `>>` ends it: either would cut the token short.
if prefix.len() > 128 || suffix.len() > 128 || [prefix, suffix].iter().any(|s| s.contains('#') || s.contains(">>")) {
return Err(ToolError::InvalidArgs("prefix and suffix must be at most 128 bytes and cannot contain # or >>".into()));
}
let dry_run = args.opt_bool("dry_run")?.unwrap_or(false);
// Resolve and reserve the complete path list before opening or writing anything.
let mut sources = Vec::with_capacity(files.len());
let mut targets = Vec::with_capacity(files.len());
let mut passwords = Vec::with_capacity(files.len());
for entry in files {
let input = entry
.get("input")
.and_then(Value::as_str)
.filter(|s| !s.is_empty())
.ok_or_else(|| ToolError::InvalidArgs("each file needs a non-empty input path".into()))?;
let output = entry
.get("output")
.and_then(Value::as_str)
.filter(|s| !s.is_empty())
.ok_or_else(|| ToolError::InvalidArgs("each file needs a non-empty output path".into()))?;
let source = self.resolve(input, false)?;
let target = self.resolve(output, true)?;
if target.exists() {
return Err(failed(format!("output already exists; refusing to replace it: {output}")));
}
let parent = target.parent().ok_or_else(|| failed(format!("output has no parent directory: {output}")))?;
if !parent.is_dir() {
return Err(failed(format!("output directory does not exist: {}", parent.display())));
}
sources.push((input.to_string(), source));
targets.push((output.to_string(), target));
passwords.push(entry.get("password").and_then(Value::as_str).map(str::to_owned));
}
let input_paths: std::collections::HashSet<_> = sources.iter().map(|(_, path)| path.clone()).collect();
let mut output_paths = std::collections::HashSet::new();
for (name, path) in &targets {
if input_paths.contains(path) {
return Err(failed(format!("output {name} names an input file; choose a separate output path")));
}
if !output_paths.insert(path.clone()) {
return Err(failed(format!("two files use the same output path: {name}")));
}
}
let mut plans = Vec::with_capacity(files.len());
let mut next = start;
let mut input_bytes = 0u64;
for (index, ((input_name, input_path), (_, output_path))) in sources.iter().zip(&targets).enumerate() {
let size = std::fs::metadata(input_path).map_err(failed)?.len();
input_bytes = input_bytes
.checked_add(size)
.filter(|total| *total <= 512 * 1024 * 1024)
.ok_or_else(|| failed("combined Bates input exceeds the 512 MiB safety limit"))?;
let bytes = read_input(input_path)?;
input_bytes = input_bytes
.saturating_sub(size)
.checked_add(u64::try_from(bytes.len()).unwrap_or(u64::MAX))
.filter(|total| *total <= 512 * 1024 * 1024)
.ok_or_else(|| failed("combined Bates input exceeds the 512 MiB safety limit"))?;
let display_name = input_path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
let password = passwords.get(index).and_then(Option::as_deref);
let id = self.session.open(display_name, Some(input_path.to_string_lossy().into_owned()), Arc::new(bytes), password).map_err(failed)?;
let pages =
self.session.get(id).map(|doc| doc.info.pages.len()).ok_or_else(|| failed("opened document disappeared during Bates preflight"))?;
self.session.close(id);
if pages == 0 {
return Err(failed(format!("{input_name} has no pages to number")));
}
let count = u64::try_from(pages).map_err(|_| failed(format!("page count is too large for {input_name}")))?;
let last = next.checked_add(count.saturating_sub(1)).ok_or_else(|| failed(format!("Bates number range overflows for {input_name}")))?;
plans.push(FilePlan {
input: input_name.clone(),
source: input_path.clone(),
password: passwords.get(index).cloned().flatten(),
output: output_path.clone(),
pages,
first: next,
last,
});
if index + 1 < sources.len() {
next = last.checked_add(1).ok_or_else(|| failed(format!("Bates sequence overflows after {input_name}")))?;
}
}
let intervals: Vec<Value> = plans
.iter()
.zip(&targets)
.map(|(p, (name, _))| json!({"input":p.input,"output":name,"pages":p.pages,"first":p.first,"last":p.last}))
.collect();
if dry_run {
return Ok(json!({"dry_run":true,"files":intervals}));
}
let mut staged = Vec::with_capacity(plans.len());
let mut results = Vec::with_capacity(plans.len());
let mut output_bytes = 0u64;
for plan in &plans {
let source_bytes = match read_input(&plan.source) {
Ok(bytes) => bytes,
Err(error) => {
results.push(json!({"input":plan.input,"output":plan.output,"status":"error","pages":plan.pages,"first":plan.first,"last":plan.last,"error":error.to_string()}));
continue;
}
};
let name = plan.source.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
let id = match self.session.open(name, Some(plan.source.to_string_lossy().into_owned()), Arc::new(source_bytes), plan.password.as_deref())
{
Ok(id) => id,
Err(error) => {
results.push(json!({"input":plan.input,"output":plan.output,"status":"error","pages":plan.pages,"first":plan.first,"last":plan.last,"error":error.to_string()}));
continue;
}
};
if self.session.get(id).is_none_or(|doc| doc.info.pages.len() != plan.pages) {
self.session.close(id);
results.push(json!({"input":plan.input,"output":plan.output,"status":"error","pages":plan.pages,"first":plan.first,"last":plan.last,"error":"input changed after preflight; page count differs"}));
continue;
}
let template = format!("<<Bates Number#{digits}#{}#{prefix}#{suffix}>>", plan.first);
let mut settings = HeaderFooter::default();
settings.text[4] = template;
let pages: Vec<usize> = (0..plan.pages).collect();
let applied = self.session.apply(id, Edit::AddHeaderFooter { pages, settings, replace: false });
let result = applied.and_then(|()| self.session.save_full_bytes(id));
match result {
Ok(bytes) => {
let total = output_bytes.saturating_add(u64::try_from(bytes.len()).unwrap_or(u64::MAX));
if total > 512 * 1024 * 1024 {
results.push(json!({"input":plan.input,"output":plan.output,"status":"error","pages":plan.pages,"first":plan.first,"last":plan.last,"error":"combined Bates output exceeds the 512 MiB safety limit"}));
} else {
output_bytes = total;
staged.push((plan.output.clone(), bytes));
}
}
Err(error) => results.push(json!({"input":plan.input,"output":plan.output,"status":"error","pages":plan.pages,"first":plan.first,"last":plan.last,"error":error.to_string()})),
}
self.session.close(id);
}
for (path, bytes) in staged {
match publish_new(&path, &bytes) {
Ok(()) => {
let plan = plans.iter().find(|p| p.output == path);
if let Some(plan) = plan {
results.push(json!({"input":plan.input,"output":path,"status":"ok","first":plan.first,"last":plan.last,"pages":plan.pages}));
}
}
Err(error) => {
let plan = plans.iter().find(|p| p.output == path);
if let Some(plan) = plan {
results.push(json!({"input":plan.input,"output":path,"status":"error","pages":plan.pages,"first":plan.first,"last":plan.last,"error":error.to_string()}));
}
}
}
}
results.sort_by_key(|result| plans.iter().position(|plan| result["output"] == json!(plan.output)).unwrap_or(usize::MAX));
let completed = results.iter().filter(|r| r["status"] == "ok").count();
let failed_count = results.len().saturating_sub(completed);
Ok(json!({"dry_run":false,"completed":completed,"failed":failed_count,"files":results}))
}
}
/// Publish a PDF atomically while refusing a target created by another process after preflight.
fn publish_new(path: &Path, bytes: &[u8]) -> Result<()> {
let parent = path.parent().ok_or_else(|| failed("output has no parent directory"))?;
let mut temp = tempfile::NamedTempFile::new_in(parent).map_err(failed)?;
temp.write_all(bytes).map_err(failed)?;
temp.as_file().sync_all().map_err(failed)?;
temp.persist_noclobber(path).map(|_| ()).map_err(|error| {
if error.error.kind() == std::io::ErrorKind::AlreadyExists {
failed(format!("output appeared after preflight; refusing to replace it: {}", path.display()))
} else {
failed(error.error)
}
})
}
+209
View File
@@ -0,0 +1,209 @@
//! Bookmark trees in and out of documents: `bookmark_export`, `bookmark_import`, `bookmark_copy`.
//!
//! The portable form is JSON: `{"bookmarks": [node, …]}`, where a node is `title`, `page`
//! (1-based, or `null` for one that goes nowhere), `view` (`{"type", "values"}`: a destination
//! type and its values in PDF user space, as the file stores them), `color`, `bold`, `italic`,
//! `open` and `children`. What export writes, import takes back unchanged. A file also carries
//! `"truncated": true` when the export left out bookmarks nested past the listing limit.
use crate::{Args, Automation, Result, ToolError, failed};
use pdfcraft_engine::{DocId, Edit, OutlineNode};
use serde_json::{Value, json};
/// Deepest nesting a bookmark tree may have (the listing reaches 33 levels).
const MAX_DEPTH: usize = 33;
/// The keys a node may have: the ones [`node_json`] writes.
const NODE_KEYS: [&str; 8] = ["title", "page", "view", "color", "bold", "italic", "open", "children"];
impl Automation {
pub(crate) fn bookmark_export(&self, a: &Args) -> Result<Value> {
let id = self.doc(a)?.id;
let path = a.opt_path("path")?.unwrap_or_default();
let tree = self.outline_of(id, &path)?;
let mut out = json!({ "bookmarks": tree.nodes.iter().map(node_json).collect::<Vec<_>>(), "truncated": tree.truncated });
if let Some(file) = a.opt_str("out")? {
let target = self.resolve(file, true)?;
let mut saved = json!({ "bookmarks": out["bookmarks"] });
if tree.truncated {
saved["truncated"] = json!(true);
}
let text = serde_json::to_vec_pretty(&saved).map_err(failed)?;
crate::write_atomic(&target, &text)?;
out["path"] = json!(target);
}
Ok(out)
}
pub(crate) fn bookmark_import(&mut self, a: &Args) -> Result<Value> {
let (nodes, truncated) = match (a.get("bookmarks"), a.opt_str("file")?) {
(Some(list), None) => (nodes_of(list)?, false),
(None, Some(file)) => {
let path = self.resolve(file, false)?;
let value: Value = serde_json::from_slice(&crate::read_input(&path)?).map_err(|e| failed(format!("not a bookmark file: {e}")))?;
let list = value.get("bookmarks").ok_or_else(|| failed("not a bookmark file: it has no \"bookmarks\" list"))?;
(nodes_of(list)?, value.get("truncated") == Some(&Value::Bool(true)))
}
_ => return Err(ToolError::InvalidArgs("give either bookmarks or file".into())),
};
let mut out = self.write_tree(a, nodes)?;
out["truncated"] = json!(truncated);
Ok(out)
}
pub(crate) fn bookmark_copy(&mut self, a: &Args) -> Result<Value> {
let from = a.int("from")?;
let from = DocId(u64::try_from(from).map_err(|_| ToolError::InvalidArgs("from must be positive".into()))?);
let path = a.opt_path("path")?.unwrap_or_default();
let tree = self.outline_of(from, &path)?;
let mut out = self.write_tree(a, tree.nodes)?;
out["truncated"] = json!(tree.truncated);
Ok(out)
}
fn outline_of(&self, id: DocId, path: &[usize]) -> Result<pdfcraft_engine::OutlineTree> {
match self.session.outline_tree(id, path) {
// The engine names the path 0-based; the caller gave it 1-based.
Some(tree) => tree.map_err(|e| match e {
pdfcraft_organize::OutlineError::NoSuchBookmark(_) => failed(format!("there is no bookmark at {:?}", one_based(path))),
e => failed(e),
}),
None => Err(failed(format!("document {} is not open, or its bookmarks can't be read for editing", id.0))),
}
}
/// Write `nodes` into `doc` under `parent` at `position` (or in place of the outline with
/// `replace`), and say which of them went nowhere because the document lacks their page.
fn write_tree(&mut self, a: &Args, bookmarks: Vec<OutlineNode>) -> Result<Value> {
let parent = a.opt_path("parent")?.unwrap_or_default();
let index = a.opt_int("position")?.map_or(usize::MAX, |p| usize::try_from(p.max(1) - 1).unwrap_or(usize::MAX));
let replace = a.opt_bool("replace")?.unwrap_or(false);
let count = self.doc(a)?.info.pages.len();
let unmapped = pdfcraft_engine::outline_unmapped(&bookmarks, count);
let mut out = self.apply(a, Edit::ImportBookmarks { parent, index, bookmarks, replace })?;
out["unmapped"] = json!(unmapped.iter().map(|p| one_based(p)).collect::<Vec<_>>());
Ok(out)
}
}
fn one_based(path: &[usize]) -> Vec<usize> {
path.iter().map(|i| i.saturating_add(1)).collect()
}
/// A node as JSON, leaving out what is at its default (no view, black, regular, no children).
fn node_json(n: &OutlineNode) -> Value {
let mut v = json!({ "title": n.title, "page": n.page.map(|p| p.saturating_add(1)), "open": n.open });
if let Some((kind, values)) = &n.view {
v["view"] = json!({ "type": String::from_utf8_lossy(kind), "values": values });
}
if let Some(c) = n.color {
v["color"] = json!(c);
}
if n.bold {
v["bold"] = json!(true);
}
if n.italic {
v["italic"] = json!(true);
}
if !n.children.is_empty() {
v["children"] = json!(n.children.iter().map(node_json).collect::<Vec<_>>());
}
v
}
fn nodes_of(list: &Value) -> Result<Vec<OutlineNode>> {
let mut count = 0;
list_of(list, &[], &mut count)
}
/// The nodes of one level; `at` is the 1-based path of their parent, for messages.
fn list_of(list: &Value, at: &[usize], count: &mut usize) -> Result<Vec<OutlineNode>> {
let items = list.as_array().ok_or_else(|| bad(at, "children must be a list of bookmarks"))?;
if at.len() >= MAX_DEPTH && !items.is_empty() {
return Err(bad(at, &format!("bookmarks may nest at most {MAX_DEPTH} levels deep")));
}
*count = count.saturating_add(items.len());
if *count > pdfcraft_engine::MAX_IMPORT_BOOKMARKS {
return Err(ToolError::InvalidArgs(format!("at most {} bookmarks can be imported at once", pdfcraft_engine::MAX_IMPORT_BOOKMARKS)));
}
let mut out = Vec::with_capacity(items.len());
for (i, item) in items.iter().enumerate() {
let mut path = at.to_vec();
path.push(i.saturating_add(1));
out.push(node_of(item, &path, count)?);
}
Ok(out)
}
/// One node and, through [`list_of`], its children (recursion bounded by `MAX_DEPTH`).
fn node_of(v: &Value, at: &[usize], count: &mut usize) -> Result<OutlineNode> {
let o = v.as_object().ok_or_else(|| bad(at, "must be an object"))?;
if let Some(k) = o.keys().find(|k| !NODE_KEYS.contains(&k.as_str())) {
return Err(bad(at, &format!("unknown key {k:?} (a bookmark has {})", NODE_KEYS.join(", "))));
}
let field = |k: &str| o.get(k).filter(|x| !x.is_null());
// An empty title is kept: files have them, and export writes them as "".
let title = field("title").and_then(Value::as_str).ok_or_else(|| bad(at, "needs a title"))?.to_string();
let page = match field("page") {
None => None,
Some(p) => Some(p.as_u64().filter(|p| *p >= 1).and_then(|p| usize::try_from(p - 1).ok()).ok_or_else(|| bad(at, "page must be 1 or more"))?),
};
let flag = |k: &str| field(k).map_or(Ok(None), |x| x.as_bool().map(Some).ok_or_else(|| bad(at, &format!("{k} must be true or false"))));
let color = match field("color") {
None => None,
Some(c) => {
let rgb: Option<Vec<f32>> = c.as_array().and_then(|c| c.iter().map(|x| x.as_f64().map(|x| x as f32)).collect());
match rgb.as_deref() {
Some(&[r, g, b]) if [r, g, b].iter().all(|c| (0.0..=1.0).contains(c)) => Some([r, g, b]),
_ => return Err(bad(at, "color must be [r, g, b], each from 0 to 1")),
}
}
};
let children = match field("children") {
None => Vec::new(),
Some(list) => list_of(list, at, count)?,
};
Ok(OutlineNode {
title,
page,
view: field("view").map(|x| view_of(x, at)).transpose()?,
color,
italic: flag("italic")?.unwrap_or(false),
bold: flag("bold")?.unwrap_or(false),
open: flag("open")?.unwrap_or(true),
children,
})
}
/// `{"type": "XYZ", "values": [left, top, zoom]}`: a destination type with exactly its values.
fn view_of(v: &Value, at: &[usize]) -> Result<(Vec<u8>, Vec<Option<f64>>)> {
let kind = v.get("type").and_then(Value::as_str).ok_or_else(|| bad(at, "view needs a type such as XYZ or Fit"))?;
let values = match v.get("values").filter(|x| !x.is_null()) {
None => Vec::new(),
Some(list) => {
let list = list.as_array().filter(|l| l.len() <= 4).ok_or_else(|| bad(at, "view values must be a list of at most 4 numbers or nulls"))?;
list.iter()
.map(|x| match x {
Value::Null => Ok(None),
x => x.as_f64().map(Some).ok_or_else(|| bad(at, "view values must be numbers or null")),
})
.collect::<Result<_>>()?
}
};
let arity = pdfcraft_engine::outline_view_arity(kind.as_bytes()).ok_or_else(|| bad(at, VIEW_TYPES))?;
if values.len() != arity {
return Err(bad(at, &format!("a {kind} view takes {arity} values (numbers, or null to keep the reader's)")));
}
if kind == "FitR" && values.iter().any(Option::is_none) {
return Err(bad(at, "a FitR view needs all four values: left, bottom, right, top"));
}
Ok((kind.as_bytes().to_vec(), values))
}
const VIEW_TYPES: &str = "view type must be XYZ (3 values: left, top, zoom), Fit, FitB (none), FitH, FitV, FitBH, FitBV (1) or FitR (4)";
fn bad(at: &[usize], what: &str) -> ToolError {
if at.is_empty() {
return ToolError::InvalidArgs(format!("bookmarks: {what}"));
}
ToolError::InvalidArgs(format!("bookmark {at:?}: {what}"))
}
+8 -5
View File
@@ -75,7 +75,7 @@ fn to_user(p: &PageInfo, x: f64, y: f64) -> [f64; 2] {
[ux as f64, uy as f64]
}
fn rect_to_user(p: &PageInfo, r: [f64; 4]) -> [f64; 4] {
pub(crate) fn rect_to_user(p: &PageInfo, r: [f64; 4]) -> [f64; 4] {
let (a, b) = (to_user(p, r[0], r[1]), to_user(p, r[2], r[3]));
[a[0].min(b[0]), a[1].min(b[1]), a[0].max(b[0]), a[1].max(b[1])]
}
@@ -183,6 +183,7 @@ impl Automation {
"page": c.page + 1,
"index": c.index + 1,
"type": c.subtype,
"intent": c.intent,
"author": c.author,
"contents": c.contents,
"modified": c.modified,
@@ -328,7 +329,7 @@ impl Automation {
let [start, end] = ending_pair(kind, endings.as_deref())?;
Shape::Line { from: to_user(&info, f[0], f[1]), to: to_user(&info, t[0], t[1]), start, end }
}
"ink" => {
"ink" | "freehand_highlight" => {
let wrong = || ToolError::InvalidArgs("strokes must be an array of arrays of [x, y] points".into());
let strokes = a.get("strokes").ok_or_else(|| ToolError::InvalidArgs("ink needs `strokes`".into()))?;
let strokes = strokes
@@ -346,7 +347,7 @@ impl Automation {
.collect::<Result<Vec<_>>>()
})
.collect::<Result<Vec<_>>>()?;
Shape::Ink { strokes }
if kind == "freehand_highlight" { Shape::FreehandHighlight { strokes } } else { Shape::Ink { strokes } }
}
"polygon" | "cloud" | "polyline" => {
let wrong = || ToolError::InvalidArgs(format!("{kind} needs `points`: an array of [x, y] points"));
@@ -538,8 +539,10 @@ impl Automation {
return self.apply(a, edit);
}
let text_at = |t: &str| {
let w = (pdfcraft_engine::annot_text::text_width(t, size) + 8.0).clamp(20.0, 600.0);
let h = size * 1.2 + 6.0;
let longest = t.lines().map(|line| pdfcraft_engine::annot_text::text_width(line, size)).fold(0.0, f64::max);
let w = (longest + 8.0).clamp(20.0, 600.0);
let rows = pdfcraft_engine::annot_text::wrap(t, size, w - 4.0).len().max(1);
let h = rows as f64 * size * 1.2 + 6.0;
let rect = pdfcraft_engine::text_box_at(i64::from(info.rotation), at, w, h).unwrap_or([at[0], at[1] - h, at[0] + w, at[1]]);
Shape::Typewriter { rect, font_size: size }
};
+4 -3
View File
@@ -83,10 +83,10 @@ pub(crate) fn parse_align(al: &str) -> Result<TextAlign> {
/// Most entries `aligns` takes: one per paragraph, and no text has this many.
const MAX_ALIGNS: usize = 4096;
/// `aligns`: each paragraph's (line's) own alignment, or null where it follows `align`.
/// `aligns`: each paragraph's (line's) own alignment, or inherit/null where it follows `align`.
pub(crate) fn opt_aligns(a: &Args) -> Result<Option<Vec<Option<TextAlign>>>> {
let Some(v) = a.get("aligns") else { return Ok(None) };
let items = v.as_array().ok_or_else(|| bad("aligns must be an array of left, center, right, justify or null"))?;
let items = v.as_array().ok_or_else(|| bad("aligns must be an array of left, center, right, justify, inherit or null"))?;
if items.len() > MAX_ALIGNS {
return Err(bad(format!("aligns takes at most {MAX_ALIGNS} entries")));
}
@@ -94,8 +94,9 @@ pub(crate) fn opt_aligns(a: &Args) -> Result<Option<Vec<Option<TextAlign>>>> {
.iter()
.map(|v| match v {
Value::Null => Ok(None),
Value::String(s) if s == "inherit" => Ok(None),
Value::String(s) => parse_align(s).map(Some),
_ => Err(bad("each entry of aligns is left, center, right, justify or null")),
_ => Err(bad("each entry of aligns is left, center, right, justify, inherit or null")),
})
.collect::<Result<Vec<_>>>()
.map(Some)
+108 -5
View File
@@ -12,6 +12,35 @@ pub enum Content {
Png { data: Vec<u8>, width: u32, height: u32 },
}
/// `image_edit` `transform`: a matrix `[a b c d e f]` acting on top-left-origin points (a point
/// moves to `(a·x + c·y + e, b·x + d·y + f)`) → the same motion in PDF user space, which is
/// what `ImageEdit::Transform` applies after the image's placement. Both spaces are related by
/// an affine map, so three corners of the crop box pin the result down.
fn view_transform_to_user(info: &pdfcraft_render::PageInfo, m: [f64; 6]) -> Result<[f64; 6]> {
let [a, b, c, d, e, f] = m;
let det = a * d - b * c;
if !m.iter().all(|v| v.is_finite()) || !det.is_finite() || det.abs() < 1e-9 {
return Err(ToolError::InvalidArgs("transform needs a finite matrix that keeps an area (a·d − b·c must not be 0)".into()));
}
let moved = |x: f32, y: f32| {
let [vx, vy] = info.user_to_view(x, y).map(f64::from);
info.view_to_user((a * vx + c * vy + e) as f32, (b * vx + d * vy + f) as f32).map(f64::from)
};
let [x0, y0, x1, y1] = info.crop;
let (w, h) = (f64::from(x1 - x0), f64::from(y1 - y0));
if w.abs() < 1e-3 || h.abs() < 1e-3 {
return Err(ToolError::InvalidArgs("the page has no area to transform in".into()));
}
let (o, px, py) = (moved(x0, y0), moved(x1, y0), moved(x0, y1));
let (ua, ub, uc, ud) = ((px[0] - o[0]) / w, (px[1] - o[1]) / w, (py[0] - o[0]) / h, (py[1] - o[1]) / h);
let (x0, y0) = (f64::from(x0), f64::from(y0));
let user = [ua, ub, uc, ud, o[0] - ua * x0 - uc * y0, o[1] - ub * x0 - ud * y0];
if !user.iter().all(|v| v.is_finite()) {
return Err(ToolError::InvalidArgs("the transform moves the image too far".into()));
}
Ok(user)
}
impl Automation {
/// Run the tool `name` with JSON `args` (an object; `null` means no arguments).
pub fn call(&mut self, name: &str, args: &Value) -> Result<Vec<Content>> {
@@ -24,6 +53,7 @@ impl Automation {
tools::check_args(def, args)?;
let a = Args(args);
let out = match name {
"doc_bates_multi" => self.doc_bates_multi(&a)?,
"doc_open" => self.doc_open(&a)?,
"doc_batch" => self.doc_batch(&a)?,
"doc_list" => json!({ "documents": self.session.docs().iter().map(summary).collect::<Vec<_>>() }),
@@ -39,6 +69,7 @@ impl Automation {
self.apply(&a, edit)?
}
"page_render" => return self.page_render(&a),
"model_render" => return self.model_render(&a),
"comment_image_preview" => return self.comment_image_preview(&a),
"text_extract" => self.text_extract(&a)?,
"text_word_count" => self.text_word_count(&a)?,
@@ -166,6 +197,9 @@ impl Automation {
out
}
"bookmark_list" => self.bookmark_listing(&a)?,
"bookmark_export" => self.bookmark_export(&a)?,
"bookmark_import" => self.bookmark_import(&a)?,
"bookmark_copy" => self.bookmark_copy(&a)?,
"bookmark_add" => {
let page = self.page(&a)?;
let parent = a.opt_path("parent")?.unwrap_or_default();
@@ -294,13 +328,13 @@ impl Automation {
let id = self.doc(&a)?.id;
let before = self.doc(&a)?.bytes.len();
let path = self.resolve(a.str("path")?, true)?;
let (bytes, merged) = self.session.reduced_bytes(id).map_err(failed)?;
let (bytes, merged, images_refused) = self.session.reduced_bytes(id).map_err(failed)?;
// As in the app, a copy that isn't smaller is not written (#490).
let written = bytes.len() < before;
if written {
write_atomic(&path, &bytes)?;
}
json!({ "path": path.to_string_lossy(), "written": written, "bytes_before": before, "bytes_after": bytes.len(), "merged_objects": merged })
json!({ "path": path.to_string_lossy(), "written": written, "bytes_before": before, "bytes_after": bytes.len(), "merged_objects": merged, "images_refused": images_refused })
}
"doc_optimize" => self.doc_optimize(&a)?,
"doc_initial_view" => self.doc_initial_view(&a)?,
@@ -357,7 +391,7 @@ impl Automation {
let (u, v) = (info.user_to_view(rect[0] as f32, rect[1] as f32), info.user_to_view(rect[2] as f32, rect[3] as f32));
[r(u[0].min(v[0])), r(u[1].min(v[1])), r(u[0].max(v[0])), r(u[1].max(v[1]))]
});
json!({ "visible_rect": visible, "image": i + 1, "rect": [r(u[0].min(v[0])), r(u[1].min(v[1])), r(u[0].max(v[0])), r(u[1].max(v[1]))], "pixels": [im.width, im.height], "name": im.name, "kind": if im.is_form { "form" } else { "image" } })
json!({ "visible_rect": visible, "has_editor_crop": im.has_editor_crop(), "image": i + 1, "rect": [r(u[0].min(v[0])), r(u[1].min(v[1])), r(u[0].max(v[0])), r(u[1].max(v[1]))], "pixels": [im.width, im.height], "name": im.name, "kind": if im.is_form { "form" } else { "image" } })
})
.collect();
json!({ "page": page + 1, "count": list.len(), "images": list })
@@ -395,6 +429,16 @@ impl Automation {
let (u0, u1) = (info.view_to_user(r[0] as f32, r[1] as f32), info.view_to_user(r[2] as f32, r[3] as f32));
ImageEdit::Move([u0[0].min(u1[0]) as f64, u0[1].min(u1[1]) as f64, u0[0].max(u1[0]) as f64, u0[1].max(u1[1]) as f64])
}
"transform" => {
let m: Vec<f64> = a
.get("matrix")
.and_then(Value::as_array)
.and_then(|x| x.iter().map(Value::as_f64).collect())
.ok_or_else(|| ToolError::InvalidArgs("transform needs matrix: 6 numbers [a, b, c, d, e, f]".into()))?;
let m = <[f64; 6]>::try_from(m)
.map_err(|_| ToolError::InvalidArgs("transform needs matrix: 6 numbers [a, b, c, d, e, f]".into()))?;
ImageEdit::Transform(view_transform_to_user(&self.doc(&a)?.info.pages[page], m)?)
}
"rotate_by" => ImageEdit::RotateBy(
a.get("degrees")
.and_then(Value::as_f64)
@@ -410,9 +454,18 @@ impl Automation {
let (u0, u1) = (info.view_to_user(r[0] as f32, r[1] as f32), info.view_to_user(r[2] as f32, r[3] as f32));
ImageEdit::Crop([u0[0].min(u1[0]) as f64, u0[1].min(u1[1]) as f64, u0[0].max(u1[0]) as f64, u0[1].max(u1[1]) as f64])
}
"flip_horizontal" => ImageEdit::Flip { horizontal: true },
"flip_vertical" => ImageEdit::Flip { horizontal: false },
action @ ("flip_horizontal" | "flip_vertical") => {
let horizontal = action == "flip_horizontal";
let info = self.doc(&a)?.info.pages.get(page).ok_or_else(|| ToolError::InvalidArgs("the page does not exist".into()))?;
// The tool names displayed axes; the engine names PDF user-space axes.
ImageEdit::Flip { horizontal: horizontal ^ (info.rotation % 180 == 90) }
}
"delete" => ImageEdit::Delete,
"bring_to_front" => ImageEdit::Arrange(pdfcraft_engine::ArrangeOrder::BringToFront),
"send_to_back" => ImageEdit::Arrange(pdfcraft_engine::ArrangeOrder::SendToBack),
"bring_forward" => ImageEdit::Arrange(pdfcraft_engine::ArrangeOrder::BringForward),
"send_backward" => ImageEdit::Arrange(pdfcraft_engine::ArrangeOrder::SendBackward),
"remove_crop" => ImageEdit::RemoveCrop,
"replace" => {
let path = self.resolve(a.str("path")?, false)?;
let bytes = read_input(&path)?;
@@ -624,6 +677,7 @@ impl Automation {
}
out
}
"text_script" => self.text_script(&a)?,
"doc_audit_space" => {
let rows: Vec<Value> = self
.doc(&a)?
@@ -719,6 +773,7 @@ impl Automation {
"comment_list" => self.comment_list(&a)?,
"comment_add" => self.comment_add(&a)?,
"stamp_custom" => self.stamp_custom(&a)?,
"model_add" => self.model_add(&a)?,
"comment_reply" => self.comment_reply(&a)?,
"comment_set_status" => self.comment_set_status(&a)?,
"sign_list" => self.sign_list(&a)?,
@@ -815,4 +870,52 @@ impl Automation {
};
Ok(vec![Content::Json(out)])
}
/// `text_script`: Format text ▸ Superscript or Subscript on a paragraph, or on a byte range
/// of its editor text, written as `text_edit` writes the paragraph.
fn text_script(&mut self, a: &Args) -> Result<Value> {
use pdfcraft_engine::text_script::{Script, toggle};
let name = a.str("script")?;
let script = match name {
"superscript" => Script::Super,
"subscript" => Script::Sub,
other => return Err(ToolError::InvalidArgs(format!("unknown script {other:?} (superscript, subscript)"))),
};
let page = self.page(a)?;
let k = a.int("paragraph")?;
let text = {
let doc = self.doc(a)?;
let blocks = doc.text_blocks(page);
let index = self.paragraph_index(doc.id, page, k, &blocks)?;
blocks.get(index).map(|b| b.editor_text.clone()).ok_or_else(|| ToolError::InvalidArgs(format!("paragraph {k} is out of range")))?
};
let range = match a.opt_ints("range")? {
None => None,
Some(r) => {
let bounds = match r.as_slice() {
[start, end] => usize::try_from(*start).ok().zip(usize::try_from(*end).ok()),
_ => None,
};
let range = bounds
.map(|(start, end)| start..end)
.filter(|r| r.start < r.end && r.end <= text.len() && text.is_char_boundary(r.start) && text.is_char_boundary(r.end));
let Some(range) = range else {
return Err(ToolError::InvalidArgs(format!(
"range must be [start, end]: UTF-8 byte offsets of the paragraph's editor_text (from text_paragraphs) with start < end <= {}, on character boundaries",
text.len()
)));
};
Some(range)
}
};
let (toggled, _) = toggle(&text, range.as_ref(), script)
.ok_or_else(|| ToolError::InvalidArgs(format!("nothing to change: no character of the text has a {name} form")))?;
let args = json!({ "doc": a.get("doc"), "page": a.get("page"), "paragraph": k, "text": toggled });
let mut out = match self.call("text_edit", &args)?.into_iter().next() {
Some(Content::Json(out)) => out,
_ => json!({}),
};
out["script"] = json!(name);
Ok(out)
}
}
+1
View File
@@ -410,6 +410,7 @@ impl Automation {
"images": o.images,
"images_resampled": o.images_resampled,
"images_recompressed": o.images_recompressed,
"images_refused": o.images_refused,
"image_bytes_before": o.image_bytes_before,
"image_bytes_after": o.image_bytes_after,
"thumbnails": o.thumbnails,
+12 -2
View File
@@ -394,8 +394,18 @@ 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_input", "read_input_bytes", "read_review_sidecar", "process", "linked", "walk", "publish"];
const RESOLVED_BY_CALLER: &[&str] = &[
"write_atomic",
"write_atomic_with",
"read_input",
"read_input_bytes",
"read_model",
"read_review_sidecar",
"process",
"linked",
"walk",
"publish",
];
let mut dirs = vec![Path::new(env!("CARGO_MANIFEST_DIR")).join("src")];
let mut files = vec![];
while let Some(dir) = dirs.pop() {
+4
View File
@@ -16,6 +16,7 @@
mod a11y;
mod batch;
mod bates;
mod comments;
mod content;
mod conventions;
@@ -26,6 +27,8 @@ mod links;
#[cfg(feature = "mcp")]
pub mod mcp;
mod measure;
mod model3d;
mod model_render;
mod printing;
mod reading;
mod redact;
@@ -49,6 +52,7 @@ use file_access::foreign_share;
use text_cache::TextCache;
mod assemble;
mod bookmark_io;
mod dispatch;
mod documents;
mod error;
+1 -1
View File
@@ -557,7 +557,7 @@ fn tool_json(t: &crate::ToolDef) -> Value {
"title": t.title,
"description": t.description,
"inputSchema": t.input_schema,
"annotations": { "title": t.title, "readOnlyHint": t.read_only, "destructiveHint": t.destructive, "idempotentHint": t.read_only || matches!(t.name, "doc_save" | "doc_optimize" | "doc_export_data" | "measure_export" | "doc_export_images" | "doc_export_office" | "doc_export_all_images" | "doc_export_text" | "image_save"), "openWorldHint": false },
"annotations": { "title": t.title, "readOnlyHint": t.read_only, "destructiveHint": t.destructive, "idempotentHint": t.read_only || matches!(t.name, "doc_save" | "doc_optimize" | "doc_export_data" | "measure_export" | "doc_export_images" | "doc_export_office" | "doc_export_all_images" | "doc_export_text" | "image_save" | "bookmark_export"), "openWorldHint": false },
})
}
+114
View File
@@ -0,0 +1,114 @@
//! 3D model tools (Acrobat: Rich Media ▸ Add 3D, AGENTS.md §3).
use std::path::Path;
use pdfcraft_engine::{Activation3d, Edit, MAX_3D_MODEL_BYTES, MarkFile, Model3dFormat};
use serde_json::Value;
use crate::comments::rect_to_user;
use crate::{Args, Automation, Result, ToolError, failed};
/// The largest side of a 3D model's box, in points: the largest page PDF allows (ISO 32000-2 Annex C).
const MAX_MODEL_SIDE: f64 = 14_400.0;
impl Automation {
/// A U3D or PRC model in `rect` on `page`, its poster the picture at `poster` (a PDF page or an
/// image) fitted inside the box, or a labelled frame.
pub(crate) fn model_add(&mut self, a: &Args) -> Result<Value> {
let page = self.page(a)?;
let info = self.doc(a)?.info.pages.get(page).cloned().ok_or_else(|| ToolError::InvalidArgs(format!("page {} does not exist", page + 1)))?;
let r = a.nums::<4>("rect")?.ok_or_else(|| ToolError::InvalidArgs("missing argument rect".into()))?;
let (w, h) = ((r[2] - r[0]).abs(), (r[3] - r[1]).abs());
if !((1.0..=MAX_MODEL_SIDE).contains(&w) && (1.0..=MAX_MODEL_SIDE).contains(&h)) {
return Err(ToolError::InvalidArgs(format!(
"rect must be [x0, y0, x1, y1] with each side at least 1 pt and at most {MAX_MODEL_SIDE} pt"
)));
}
let activation = match a.opt_str("activation")? {
None => Activation3d::default(),
Some(word) => Activation3d::ALL
.iter()
.find(|(_, w)| *w == word)
.map(|(act, _)| *act)
.ok_or_else(|| ToolError::InvalidArgs(format!("activation must be one of: {}", Activation3d::ALL.map(|(_, w)| w).join(", "))))?,
};
let path = self.resolve(a.str("path")?, false)?;
let model = read_model(&path, MAX_3D_MODEL_BYTES)?;
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 poster = match a.opt_str("poster")? {
None => None,
Some(p) => {
let path = self.resolve(p, false)?;
let bytes = crate::read_input(&path)?;
let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
let page = usize::try_from(a.opt_int("poster_page")?.unwrap_or(1).max(1)).unwrap_or(1).saturating_sub(1);
Some(MarkFile { name, bytes: std::sync::Arc::new(bytes), page })
}
};
let edit = Edit::AddModel3d { page, rect: rect_to_user(&info, r), model: std::sync::Arc::new(model), poster, activation, name };
self.apply(a, edit)
}
}
/// Read a resolved model file of at most `max` bytes. Its size (from the file system) and its first
/// bytes are checked before the rest is read, so a large file that is not a model is never loaded.
fn read_model(path: &Path, max: usize) -> Result<Vec<u8>> {
use std::io::Read as _;
let io = |e: std::io::Error| failed(format!("{}: {e}", path.display()));
let too_large = |size: u64| failed(format!("the 3D model is {size} bytes; the largest accepted is {max}"));
let cap = u64::try_from(max).unwrap_or(u64::MAX);
let mut file = std::fs::File::open(path).map_err(io)?;
if let Ok(meta) = file.metadata()
&& meta.is_file()
&& meta.len() > cap
{
return Err(too_large(meta.len()));
}
let mut bytes = Vec::new();
(&mut file).take(4).read_to_end(&mut bytes).map_err(io)?;
Model3dFormat::detect(&bytes).map_err(failed)?;
let rest = cap.saturating_add(1).saturating_sub(bytes.len() as u64);
file.take(rest).read_to_end(&mut bytes).map_err(io)?;
if bytes.len() > max {
return Err(failed(format!("the 3D model is more than {max} bytes, the largest accepted")));
}
Ok(bytes)
}
#[cfg(test)]
mod tests {
use super::*;
fn file(dir: &Path, name: &str, bytes: &[u8]) -> std::path::PathBuf {
let path = dir.join(name);
std::fs::write(&path, bytes).unwrap();
path
}
#[test]
fn a_model_is_read_whole_when_it_fits() {
let dir = tempfile::tempdir().unwrap();
let mut prc = b"PRC".to_vec();
prc.extend_from_slice(&[7; 40]);
assert_eq!(read_model(&file(dir.path(), "m.prc", &prc), 64).unwrap(), prc);
assert_eq!(read_model(&file(dir.path(), "m.u3d", b"U3D\0x"), 6).unwrap(), b"U3D\0x");
}
#[test]
fn a_model_past_the_cap_is_refused_by_its_size_before_it_is_read() {
let dir = tempfile::tempdir().unwrap();
let path = file(dir.path(), "big.prc", &[b'P', b'R', b'C', 0, 0, 0, 0, 0, 0, 0]);
let err = read_model(&path, 4).unwrap_err().to_string();
assert!(err.contains("is 10 bytes") && err.contains("largest accepted is 4"), "the file's own size, from the file system: {err}");
}
#[test]
fn a_file_that_is_not_a_model_is_refused_by_its_header() {
let dir = tempfile::tempdir().unwrap();
for junk in [&b"%PDF-1.7 a page"[..], b"PR", b"", b"U3DX and more"] {
let err = read_model(&file(dir.path(), "junk.bin", junk), 64).unwrap_err().to_string();
assert!(err.contains("not a 3D model"), "{junk:?}: {err}");
}
}
}
+104
View File
@@ -0,0 +1,104 @@
//! `model_render`: a page's 3D model (ISO 32000-2 §13.6) drawn to a PNG, without a viewer.
use pdfcraft_engine::model3d::Model3dKind;
use pdfcraft_prc::PrcFile;
use pdfcraft_prc_render::{Camera, RenderOptions, assemble, render};
use super::Automation;
use super::dispatch::Content;
use super::error::{Result, ToolError, failed};
use super::json::Args;
use super::pages::encode_png;
/// Default and largest side of the image, in pixels.
pub(crate) const DEFAULT_SIDE: u32 = 512;
pub(crate) const MAX_SIDE: u32 = 4096;
/// The default view: from the front, right and above, as an isometric view looks.
const DEFAULT_DIRECTION: [f64; 3] = [-1.0, 1.0, -1.0];
impl Automation {
pub(crate) fn model_render(&mut self, a: &Args) -> Result<Vec<Content>> {
let page = self.page(a)?;
let width = side(a, "width")?;
let height = side(a, "height")?;
let direction = direction(a)?;
let perspective = a.opt_bool("perspective")?.unwrap_or(true);
let doc = self.doc(a)?;
let found = doc.model_3d_annotations(page).map_err(failed)?;
let index = match a.opt_int("model")? {
None => *found.first().ok_or_else(|| failed(format!("page {} has no 3D model", page.saturating_add(1))))?,
Some(n) => {
let pos = usize::try_from(n).ok().and_then(|n| n.checked_sub(1)).ok_or_else(|| Args::wrong("model", "a positive integer"))?;
*found
.get(pos)
.ok_or_else(|| ToolError::InvalidArgs(format!("page {} has {} 3D models, not {n}", page.saturating_add(1), found.len())))?
}
};
let model = doc.model_3d(page, index).map_err(failed)?;
if model.kind == Model3dKind::U3d {
return Err(failed("this 3D model is in U3D, which can't be drawn yet; only PRC models can"));
}
let prc = PrcFile::parse(&model.data).map_err(|e| failed(format!("the 3D model could not be read: {e}")))?;
let meshes = assemble(&prc).map_err(failed)?;
let aspect = f64::from(width) / f64::from(height);
let camera = Camera::fit_meshes(&meshes, direction, up_for(direction), perspective, aspect).map_err(failed)?;
let image = render(&meshes, &camera, &RenderOptions { width, height, ..RenderOptions::default() }).map_err(failed)?;
let data = encode_png(image.width, image.height, &premultiplied(image.rgba))?;
Ok(vec![Content::Png { data, width: image.width, height: image.height }])
}
}
fn side(a: &Args, key: &str) -> Result<u32> {
match a.opt_int(key)? {
None => Ok(DEFAULT_SIDE),
Some(n) => u32::try_from(n).ok().filter(|n| (1..=MAX_SIDE).contains(n)).ok_or_else(|| Args::wrong(key, &format!("between 1 and {MAX_SIDE}"))),
}
}
/// `direction`: three finite numbers, not all zero, from the eye towards the model.
fn direction(a: &Args) -> Result<[f64; 3]> {
let Some(v) = a.get("direction") else { return Ok(DEFAULT_DIRECTION) };
let wrong = || Args::wrong("direction", "three numbers [x, y, z], not all zero");
let items = v.as_array().filter(|x| x.len() == 3).ok_or_else(wrong)?;
let mut out = [0.0; 3];
for (o, x) in out.iter_mut().zip(items) {
*o = x.as_f64().filter(|f| f.is_finite()).ok_or_else(wrong)?;
}
if out.iter().all(|c| *c == 0.0) {
return Err(wrong());
}
Ok(out)
}
/// Z is up, as CAD models are drawn, unless the view looks along it.
fn up_for([x, y, z]: [f64; 3]) -> [f64; 3] {
if x.hypot(y) <= z.abs() * 1e-6 { [0.0, 1.0, 0.0] } else { [0.0, 0.0, 1.0] }
}
/// Straight RGBA to the premultiplied RGBA `encode_png` takes.
fn premultiplied(mut rgba: Vec<u8>) -> Vec<u8> {
for [r, g, b, alpha] in rgba.as_chunks_mut::<4>().0 {
let a = u16::from(*alpha);
for c in [r, g, b] {
*c = u8::try_from((u16::from(*c) * a + 127) / 255).unwrap_or(u8::MAX);
}
}
rgba
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn premultiplying_scales_colour_by_alpha() {
assert_eq!(premultiplied(vec![200, 100, 0, 255, 200, 100, 0, 128, 9, 9, 9, 0]), vec![200, 100, 0, 255, 100, 50, 0, 128, 0, 0, 0, 0]);
}
#[test]
fn a_view_along_z_keeps_y_up() {
assert_eq!(up_for([0.0, 0.0, -1.0]), [0.0, 1.0, 0.0]);
assert_eq!(up_for(DEFAULT_DIRECTION), [0.0, 0.0, 1.0]);
}
}
+17 -3
View File
@@ -201,8 +201,8 @@ impl Automation {
}
pub(crate) fn doc_remove_hidden(&mut self, a: &Args) -> Result<Value> {
let edit = match a.get("categories") {
None => Edit::Sanitize,
let which = match a.get("categories") {
None => None,
Some(_) => {
let which = a
.strs("categories")?
@@ -212,10 +212,24 @@ impl Automation {
if which.is_empty() {
return Err(ToolError::InvalidArgs("categories is empty".into()));
}
Some(which)
}
};
// One scan, for this check and for what was removed. The removal refuses when it counts
// every listed category as 0 (an AcroForm with no fields counts 1), with an error about
// redaction marks; this reads the same scan, so it refuses exactly then. A document that
// can't be edited has no scan: `apply` says why.
let info = self.doc(a)?.hidden_info();
let edit = match which {
None => Edit::Sanitize,
Some(which) => {
if !info.is_empty() && which.iter().all(|h| info.iter().find(|c| c.0 == *h).is_none_or(|c| c.1 == 0)) {
return Err(failed("nothing to remove: the listed categories hold nothing (see doc_hidden_info)"));
}
Edit::RemoveHidden { which }
}
};
let before: usize = self.doc(a)?.hidden_info().iter().map(|c| c.1).sum();
let before: usize = info.iter().map(|c| c.1).sum();
let mut out = self.apply(a, edit)?;
let after: usize = self.doc(a)?.hidden_info().iter().map(|c| c.1).sum();
out["removed"] = json!(before.saturating_sub(after));
+95 -13
View File
@@ -121,6 +121,14 @@ pub fn tools() -> Vec<ToolDef> {
let save_out = json!({ "type": "string", "description": "File to write. Omit to open the result as a new unsaved document instead." });
let open = json!({ "type": "boolean", "description": "Also open the result as a new document (default: only when out is omitted)." });
vec![
t("doc_bates_multi", "Add Bates numbering across files", "Apply one consecutive Bates sequence to an ordered list of PDFs. Each file entry has input and output paths and an optional open or permissions password. The operation first validates every input/output and computes inclusive numeric intervals; dry_run returns that allocation without writing. Existing output files are never replaced. On application, files that cannot be edited or saved are reported individually and later files continue.")
.destructive()
.with(schema(json!({
"files": {"type":"array","minItems":1,"maxItems":1000,"description":"PDFs in Bates sequence order.","items":{"type":"object","properties":{"input":{"type":"string","minLength":1,"description":"Input PDF path."},"output":{"type":"string","minLength":1,"description":"New output PDF path; must not exist."},"password":{"type":"string","description":"Open or permissions password, if needed."}},"required":["input","output"],"additionalProperties":false}},
"start_number": {"type":"integer","minimum":1,"description":"First number in the sequence (default 1)."}, "digits": {"type":"integer","minimum":1,"maximum":12,"description":"Zero-padded number width (default 6)."},
"prefix": {"type":"string","maxLength":128,"description":"Text before the number: at most 128 UTF-8 bytes, without # or >>."}, "suffix": {"type":"string","maxLength":128,"description":"Text after the number: at most 128 UTF-8 bytes, without # or >>."},
"dry_run": {"type":"boolean","description":"Return each file's inclusive number interval without writing (default false)."}
}), &["files"])),
t("doc_batch", "Process files and folders", "Run convert, ocr and/or optimize over files and folders, one file at a time. recursive defaults to false. Preserve paths relative to each selected folder inside out_dir; duplicate inputs run once. Skip unsupported files, links and the output subtree. Existing outputs receive numbered names and are never replaced. Continue after per-file errors unless stop_on_error is true. Return completed/failed/skipped counts and per-file results. Discovery is bounded to 10000 entries and 64 folder levels. Convert must be first; each step can appear once. OCR uses installed models. Optimize uses Reduce File Size settings, optionally overriding target ppi (threshold 1.5 times ppi; black-and-white images go to the larger of ppi and 300) and JPEG quality; a larger candidate keeps the original bytes. Sources and open documents are unchanged.")
.with(schema(json!({
"paths": {"type":"array","items":{"type":"string"},"minItems":1,"maxItems":1000},
@@ -173,9 +181,16 @@ pub fn tools() -> Vec<ToolDef> {
"hide_text_block": { "type": "integer", "minimum": 1, "description": "Render an inline editor background without this paragraph (number from text_paragraphs, resolved as text_edit does: refused once an edit merged that paragraph into a neighbour). Does not modify the document." },
"hide_added_text": { "type": "integer", "minimum": 1, "description": "Render a retyping background without this added text item (added index from object_list). Mutually exclusive with hide_text_block. Does not modify the document." }
}), &["doc", "page"])),
t("model_render", "Render a 3D model", "Draw a page's 3D model (a 3D annotation's PRC stream) to a PNG, framed to fill the image, with headlight shading on a white background. model is its 1-based position among the page's 3D models (default 1). direction is the view direction [x, y, z] from the eye towards the model (default [-1, 1, -1]); Z is up unless the view looks along Z. perspective defaults to true. U3D models can't be drawn yet and give an error. Does not modify the document.")
.ro()
.with(schema(json!({ "doc": doc(), "page": { "type": "integer", "minimum": 1 }, "model": { "type": "integer", "minimum": 1 },
"width": { "type": "integer", "minimum": 1, "maximum": 4096 }, "height": { "type": "integer", "minimum": 1, "maximum": 4096 },
"direction": { "type": "array", "items": { "type": "number" }, "minItems": 3, "maxItems": 3 },
"perspective": { "type": "boolean" }
}), &["doc", "page"])),
t("object_list", "List editable objects", "List existing paragraphs, Image/Form artwork and added content once, with source kind/index references, displayed rectangles and document generation. Indexes change when content changes; use generation in object_move to reject stale references.")
.ro().with(schema(json!({"doc":doc(),"page":{"type":"integer","minimum":1}}), &["doc","page"])),
t("object_move", "Move objects together", "Atomically translate 1–1000 mixed references from object_list by [dx, dy] in displayed points (right/down). Preserves glyph codes, fonts, image data and relative spacing; success is one undo step. Clipping and vertical text are refused. A bad/stale reference refuses the entire move.")
t("object_move", "Move objects together", "Atomically translate 1–1000 mixed references from object_list by [dx, dy] in displayed points (right/down). Preserves glyph codes, fonts, image data and relative spacing; success is one undo step. Text used as a clipping path and vertical text are refused. A bad/stale reference refuses the entire move.")
.with(schema(json!({"doc":doc(),"page":{"type":"integer","minimum":1},
"objects":{"type":"array","minItems":1,"maxItems":1000,"uniqueItems":true,"items":{
"type":"object","properties":{"kind":{"type":"string","enum":["added","text","image"]},"index":{"type":"integer","minimum":1}},"required":["kind","index"],"additionalProperties":false}},
@@ -315,6 +330,50 @@ pub fn tools() -> Vec<ToolDef> {
}),
&["doc", "title", "page"],
)),
t(
"bookmark_export",
"Export bookmarks",
"The bookmark tree, or the subtree at path, as a list of nodes bookmark_import takes back unchanged. A node has title, page (1-based, null when it goes nowhere), open, and when set view ({type, values}: a destination type from ISO 32000-2 §12.3.2.2 Table 149 and its values in PDF user space, as the file stores them), color ([r, g, b], 0-1), bold, italic and children. truncated is true when bookmarks nested deeper than 33 levels were left out. With out, the tree is also written there as a JSON file {\"bookmarks\": [...]}, with \"truncated\": true when that is so; out is overwritten.",
)
.destructive()
.with(schema(
json!({ "doc": doc(), "path": path("The bookmark whose subtree to export (omit for the whole outline)"), "out": path_arg() }),
&["doc"],
)),
t(
"bookmark_import",
"Import bookmarks",
"Add a tree of bookmarks, as bookmark_export gives it (bookmarks) or as a JSON file it wrote (file), under a parent bookmark (or at the top level) at a position, or with replace in place of the whole outline. A bookmark whose page this document lacks is kept without a destination and listed in unmapped (1-based paths into the given tree). A view takes exactly its type's values (XYZ 3, FitR 4, FitH/FitV/FitBH/FitBV 1, Fit/FitB none). Give exactly one of bookmarks and file. A title may be empty but not missing; a key a node does not have is refused. Every node is checked before anything is written: at most 100000 bookmarks, nested at most 33 levels counting the parent's. truncated is true when the file says its export left bookmarks out. Undoable.",
)
.destructive()
.with(schema(
json!({
"doc": doc(),
"bookmarks": { "type": "array", "items": { "type": "object" }, "minItems": 1, "description": "Nodes as bookmark_export returns them." },
"file": path_arg(),
"parent": path("Parent bookmark (omit for the top level)"),
"position": { "type": "integer", "minimum": 1, "description": "1-based position among the parent's children (default: last)." },
"replace": { "type": "boolean", "description": "Replace the document's bookmarks instead of adding to them (default false; leave parent out)." }
}),
&["doc"],
)),
t(
"bookmark_copy",
"Copy bookmarks from another document",
"Copy the bookmarks of document from (or the subtree at path) into doc, by page number: under a parent bookmark (or at the top level) at a position, or with replace in place of doc's outline. A bookmark whose page doc lacks is kept without a destination and listed in unmapped (1-based paths into the copied tree). truncated is true when bookmarks nested deeper than 33 levels were left out of the copy. Undoable.",
)
.destructive()
.with(schema(
json!({
"doc": doc(),
"from": { "type": "integer", "minimum": 1, "description": "Id of the document to copy from." },
"path": path("The bookmark whose subtree to copy (omit for the whole outline)"),
"parent": path("Parent bookmark in doc (omit for the top level)"),
"position": { "type": "integer", "minimum": 1, "description": "1-based position among the parent's children (default: last)." },
"replace": { "type": "boolean", "description": "Replace doc's bookmarks instead of adding to them (default false; leave parent out)." }
}),
&["doc", "from"],
)),
t("bookmark_rename", "Rename a bookmark", "Change a bookmark's title. Undoable.")
.with(schema(json!({ "doc": doc(), "path": path("The bookmark"), "title": { "type": "string", "minLength": 1 } }), &["doc", "path", "title"])),
t("bookmark_delete", "Delete a bookmark", "Delete a bookmark and the bookmarks under it. Undoable.")
@@ -461,6 +520,20 @@ pub fn tools() -> Vec<ToolDef> {
}),
&["doc", "page", "path"],
)),
t("model_add", "Add a 3D model", "Add a 3D model (Acrobat: Rich Media ▸ Add 3D): the U3D or PRC file at path, recognised by its first bytes, as a 3D annotation in rect [x0, y0, x1, y1] (points from the top-left of the displayed page; each side 1–14400 pt; at most 256 MiB). Its poster, what prints and what readers show until the model is activated, is the picture at poster (a PDF page, poster_page default 1, or an image) fitted inside rect keeping its shape and centred; without poster, a frame labelled \"3D model\". activation: click (default), page_open or page_visible. name is its description (default: the file name). No views are added: readers open the model on its own default view. Undoable.")
.with(schema(
json!({
"doc": doc(),
"page": { "type": "integer", "minimum": 1 },
"path": { "type": "string" },
"rect": { "type": "array", "items": { "type": "number" }, "minItems": 4, "maxItems": 4 },
"poster": { "type": "string" },
"poster_page": { "type": "integer", "minimum": 1 },
"activation": { "type": "string", "enum": ["click", "page_open", "page_visible"] },
"name": { "type": "string" },
}),
&["doc", "page", "path", "rect"],
)),
t("form_set_image", "Set an image field's picture", "Show an image file (PNG, JPEG, TIFF, GIF or BMP) in an image field or button, scaled to fit and centred (what clicking an image field does). On an XFA form the picture is kept in its data too (base64, as Designer saves it) and the form shows it from there. Undoable.")
.with(schema(json!({ "doc": doc(), "field": { "type": "string" }, "path": { "type": "string" } }), &["doc", "field", "path"])),
t(
@@ -562,7 +635,7 @@ pub fn tools() -> Vec<ToolDef> {
t(
"doc_remove_hidden",
"Remove hidden information / Sanitize",
"Remove the listed categories (see doc_hidden_info), or every category when none are listed (Sanitize Document). Form fields are flattened so their values stay visible. The next save rewrites the whole file. Undoable until saved.",
"Remove the listed categories (see doc_hidden_info), or every category when none are listed (Sanitize Document). Fails when the listed categories hold nothing. Form fields are flattened so their values stay visible. The next save rewrites the whole file. Undoable until saved.",
)
.destructive()
.with(schema(
@@ -637,7 +710,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"] },
"aligns": { "type": "array", "maxItems": 4096, "items": { "enum": ["left", "center", "right", "justify", null] }, "description": "Each paragraph's (line's) own alignment, by index; null follows align." },
"aligns": { "type": "array", "maxItems": 4096, "items": { "type": "string", "enum": ["left", "center", "right", "justify", "inherit"] }, "description": "Each paragraph's (line's) own alignment, by index; inherit (or legacy null) follows align." },
"char_spacing": { "type": "number", "minimum": -500, "maximum": 500, "description": "Points after each character." },
}),
&["doc", "page", "text"],
@@ -660,7 +733,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"] },
"aligns": { "type": "array", "maxItems": 4096, "items": { "enum": ["left", "center", "right", "justify", null] }, "description": "Each paragraph's (line's) own alignment, by index; null follows align." },
"aligns": { "type": "array", "maxItems": 4096, "items": { "type": "string", "enum": ["left", "center", "right", "justify", "inherit"] }, "description": "Each paragraph's (line's) own alignment, by index; inherit (or legacy null) follows align." },
"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.95 }, "minItems": 4, "maxItems": 4, "description": "Fractions trimmed: left, bottom, right, top. Left and right together, and bottom and top together, trim at most 0.95." },
@@ -754,7 +827,7 @@ pub fn tools() -> Vec<ToolDef> {
json!({
"doc": doc(),
"page": { "type": "integer", "minimum": 1 },
"type": { "type": "string", "enum": ["note", "highlight", "underline", "strikeout", "squiggly", "replace", "rectangle", "oval", "line", "arrow", "ink", "textbox", "stamp", "polygon", "cloud", "polyline", "callout", "caret", "attachment"] },
"type": { "type": "string", "enum": ["note", "highlight", "underline", "strikeout", "squiggly", "replace", "rectangle", "oval", "line", "arrow", "ink", "freehand_highlight", "textbox", "stamp", "polygon", "cloud", "polyline", "callout", "caret", "attachment"] },
"path": { "type": "string", "description": "attachment: the file to attach." },
"points": { "type": "array", "items": point(), "minItems": 2 },
"knee": point(),
@@ -1194,9 +1267,9 @@ pub fn tools() -> Vec<ToolDef> {
json!({ "doc": doc(), "field": { "type": "string" }, "event": { "type": "string", "enum": ["keystroke", "format", "validate", "calculate", "mouse_up"] }, "script": { "type": "string" } }),
&["doc", "field", "event"],
)),
t("doc_export_office", "Export to Word, PowerPoint, HTML, RTF or Markdown", "Export a PDF ▸ Word (.docx), PowerPoint (.pptx, one slide per page), HTML (.html, one file with images inline), RTF (.rtf) or Markdown (.md or .markdown: pipe tables, images left out), chosen by path's extension: text, headings, bold and italic. Word uses borderless inferred tables and positioned editable shapes on pages with artwork, rotated or large text; each source page retains its size. Font matching and vector graphics remain limited. Export reads forms 50 deep and up to 50 000 a page, counting forms the page draws itself. Pages that go past either limit are listed in truncated_pages, with a warning; the text and images of the forms left out are missing.")
t("doc_export_office", "Export to Word, PowerPoint, HTML, RTF or Markdown", "Export a PDF ▸ Word (.docx), PowerPoint (.pptx, one slide per page), HTML (.html, one file with images inline), RTF (.rtf) or Markdown (.md or .markdown: pipe tables, images left out), chosen by path's extension: text, headings, bold and italic. HTML uses rich styling by default; set html_mode to simple for CSS-free headings, paragraphs, emphasis and tables. Simple HTML keeps text and inline images but omits colour and layout styling. Word uses borderless inferred tables and positioned editable shapes on pages with artwork, rotated or large text; each source page retains its size. Font matching and vector graphics remain limited. Export reads forms 50 deep and up to 50 000 a page, counting forms the page draws itself. Pages that go past either limit, or that have pictures past what one export may hold or decode, are listed in truncated_pages, with a warning; what was left out is missing.")
.cmd("export.docx")
.with(schema(json!({ "doc": doc(), "path": { "type": "string" } }), &["doc", "path"])),
.with(schema(json!({ "doc": doc(), "path": { "type": "string" }, "html_mode": { "type": "string", "enum": ["rich", "simple"], "default": "rich" } }), &["doc", "path"])),
t("pdfa_verify", "Verify PDF/A", "Standards ▸ Verify PDF/A compliance: the PDF/A-2b or 3b rules the document breaks (ISO 19005 clause, message, page, whether Save as PDF/A can fix it), plus what it declares.")
.ro()
.cmd("standards.pdfa")
@@ -1281,7 +1354,7 @@ pub fn tools() -> Vec<ToolDef> {
.ro()
.cmd("ocr.recognize")
.with(schema(json!({}), &[])),
t("doc_export_all_images", "Export all images", "Write the images that pages use into a folder (`<name>_Page_<n>_Image_<k>.jpg|png`, n zero-padded to the page count's digits), each once: JPEG images unchanged, others as PNG with their soft mask as alpha. min_size skips images with fewer pixels on their shorter side. Images that can't be decoded yet (JPEG 2000, JBIG2 inside other filters, separations) are listed under skipped. Includes unsaved edits.")
t("doc_export_all_images", "Export all images", "Write the images that pages use into a folder (`<name>_Page_<n>_Image_<k>.jpg|png`, n zero-padded to the page count's digits), each once: JPEG images unchanged, others as PNG with their soft mask as alpha. min_size skips images with fewer pixels on their shorter side. Images that can't be decoded yet (JPEG 2000, separations), or past what one export may decode or hold, are listed under skipped, with the reason. Includes unsaved edits.")
.cmd("export.all_images")
.with(schema(
json!({
@@ -1340,7 +1413,7 @@ pub fn tools() -> Vec<ToolDef> {
}),
&["from"],
)),
t("doc_reduce", "Reduce file size", "Write a smaller copy of the document to `path` with Acrobat's Reduce File Size choices: colour and grey images above 225 ppi downsampled to 150 ppi and JPEG-compressed (medium quality), black-and-white images averaged down to 300 ppi above 450 ppi and each stored as CCITT Group 4 (or 1-bit Flate, once resampled or packed from more bits) whenever that is smaller, thumbnails dropped, identical fonts and images merged, unused objects dropped, compressed object streams. If the copy wouldn't be smaller, nothing is written and `written` is false. The open document is unchanged.")
t("doc_reduce", "Reduce file size", "Write a smaller copy of the document to `path` with Acrobat's Reduce File Size choices: colour and grey images above 225 ppi downsampled to 150 ppi and JPEG-compressed (medium quality), black-and-white images averaged down to 300 ppi above 450 ppi and each stored as CCITT Group 4 (or 1-bit Flate, once resampled or packed from more bits) whenever that is smaller, thumbnails dropped, identical fonts and images merged, unused objects dropped, compressed object streams. If the copy wouldn't be smaller, nothing is written and `written` is false. Images past what one run may decode stay as they are, counted in images_refused; streams it only stores with Flate past that stay LZW, uncounted. The open document is unchanged.")
.cmd("optimize.reduce")
.with(schema(json!({ "doc": doc(), "path": { "type": "string" } }), &["doc", "path"])),
t("doc_initial_view", "Initial view", "Read or change how the document opens (Document Properties ▸ Initial View) and its reading options: navigation (page, bookmarks, pages, attachments, layers), layout (default, single, continuous, two_up, two_up_continuous, two_up_cover, two_up_continuous_cover), magnification (default, actual, fit_page, fit_width, fit_height, fit_visible, or a percentage), page, window options (fit_window, center_window, full_screen, display_title), interface options (hide_menubar, hide_toolbar, hide_window_ui), language and binding (left, right). Only the given ones change; returns the result. Undoable.").with(schema(
@@ -1378,17 +1451,18 @@ pub fn tools() -> Vec<ToolDef> {
.ro()
.cmd("edit.edit_text")
.with(schema(json!({ "doc": doc(), "page": { "type": "integer", "minimum": 1 } }), &["doc", "page"])),
t("image_edit", "Edit an image", "Change one of a page's images (number from page_images): action move (rect: new full placement box in top-left-origin points, based on page_images.rect), crop (rect: the part to keep, top-left-origin points; the pixels stay in place and page_images.visible_rect shows the result; a later move carries the crop along), rotate (quarters clockwise, default 1), rotate_by (degrees: any angle clockwise about the visible centre; the box in page_images then becomes the turned image's bounding box), flip_horizontal, flip_vertical, replace (path: an image file, drawn in the same place) or delete. Undoable. The selected image crop transforms with its pixels, isolating shared path scopes while retaining neighboring painting. Text-outline clips return a clear error. Rotation/flip use the visible centre. Form artwork supports move/resize/rotate/flip/delete as a group; replace and image_save only support raster images.")
t("image_edit", "Edit an image", "Change one of a page's images (number from page_images): action move (rect: new full placement box in top-left-origin points, based on page_images.rect), crop (rect: the part to keep, top-left-origin points; the pixels stay in place and page_images.visible_rect shows the result; a later move carries the crop along), remove_crop (remove a crop created by PdfCraft while preserving clipping paths from the original document), rotate (quarters clockwise, default 1), rotate_by (degrees: any angle clockwise about the visible centre; the box in page_images then becomes the turned image's bounding box), transform (matrix: 6 numbers [a, b, c, d, e, f] in top-left-origin points, applied after the current placement so a point (x, y) of the image moves to (a·x + c·y + e, b·x + d·y + f); finite, with a·d − b·c not 0; the box in page_images becomes the transformed image's bounding box), flip_horizontal (reflect left/right on the displayed page), flip_vertical (reflect top/bottom on the displayed page; both flip actions follow the page rotation), replace (path: an image file, drawn in the same place), delete, or arrange: bring_to_front, send_to_back, bring_forward, send_backward (reorder stacking order among content on the page; errors when the image is already at the requested limit; arranging an added image converts it into an ordinary page image). Undoable. The selected image crop transforms with its pixels, isolating shared path scopes while retaining neighboring painting. Text-outline clips return a clear error. Rotation/flip use the visible centre. Form artwork supports move/resize/rotate/flip/delete as a group; replace and image_save only support raster images.")
.cmd("edit.edit_text")
.with(schema(
json!({
"doc": doc(),
"page": { "type": "integer", "minimum": 1 },
"image": { "type": "integer", "minimum": 1 },
"action": { "type": "string", "enum": ["move", "crop", "rotate", "rotate_by", "flip_horizontal", "flip_vertical", "replace", "delete"] },
"action": { "type": "string", "enum": ["move", "crop", "rotate", "rotate_by", "transform", "flip_horizontal", "flip_vertical", "replace", "delete", "bring_to_front", "send_to_back", "bring_forward", "send_backward", "remove_crop"] },
"rect": { "type": "array", "items": { "type": "number" }, "minItems": 4, "maxItems": 4 },
"quarters": { "type": "integer" },
"degrees": { "type": "number" },
"matrix": { "type": "array", "items": { "type": "number" }, "minItems": 6, "maxItems": 6 },
"path": { "type": "string" },
}),
&["doc", "page", "image", "action"],
@@ -1428,7 +1502,7 @@ pub fn tools() -> Vec<ToolDef> {
"size": { "type": "number", "exclusiveMinimum": 0 },
"color": { "type": "string", "description": "#rrggbb" },
"align": { "type": "string", "enum": ["left", "center", "right", "justify"] },
"aligns": { "type": "array", "maxItems": 4096, "items": { "enum": ["left", "center", "right", "justify", null] }, "description": "Each paragraph's (line's) own alignment, by index; null follows align." },
"aligns": { "type": "array", "maxItems": 4096, "items": { "type": "string", "enum": ["left", "center", "right", "justify", "inherit"] }, "description": "Each paragraph's (line's) own alignment, by index; inherit (or legacy null) follows align." },
"underline": { "type": "boolean" },
"line_spacing": { "type": "number", "description": "Multiple of the font size (1.2 is ordinary)." },
"dx": { "type": "number", "description": "Paragraph only: move right by this many points (negative: left)." },
@@ -1438,11 +1512,19 @@ pub fn tools() -> Vec<ToolDef> {
"scale": { "type": "number", "description": "Horizontal scale in percent." } }),
&["doc", "page"],
)),
t("text_script", "Superscript or subscript", "Format text ▸ Superscript or Subscript on one paragraph (paragraph, from text_paragraphs), or on range [start, end): UTF-8 byte offsets of its editor_text. The characters take the Unicode superscript or subscript forms (2 → ², 2 → ₂; the font must have those glyphs, and extracted text contains them); text already in that script goes back to plain characters. Characters Unicode has no such form for (q, a space) stay unchanged and do not determine the selection's script state. Mixed plain and target-script characters normalize to that script, then to plain text on the next call (H₂2 → H₂₂ → H22); a second toggle does not reconstruct the original mixture. Use Undo to restore the exact prior text. The paragraph is then rewritten as text_edit rewrites it, with the same result fields. Refused when no character would change. Undoable. Mathematical minus U+2212 has its own script mapping; ASCII hyphen-minus stays unchanged.")
.cmd("edit.edit_text")
.with(schema(
json!({ "doc": doc(), "page": { "type": "integer", "minimum": 1 }, "paragraph": { "type": "integer", "minimum": 1 },
"script": { "type": "string", "enum": ["superscript", "subscript"] },
"range": { "type": "array", "items": { "type": "integer", "minimum": 0 }, "minItems": 2, "maxItems": 2, "description": "UTF-8 byte offsets [start, end) of the paragraph's editor_text; the whole paragraph when omitted." } }),
&["doc", "page", "paragraph", "script"],
)),
t("doc_revisions", "List revisions", "List the document's saved revisions (oldest first): each incremental update is one. Returns revision number, where it ends in the file and its size, and which signatures sign exactly that revision.")
.with(schema(json!({ "doc": doc() }), &["doc"])),
t("doc_open_revision", "Open a revision", "Open saved revision `revision` (1 = the oldest) of a document as a new, unsaved document, to see the file as it was then.")
.with(schema(json!({ "doc": doc(), "revision": { "type": "integer", "minimum": 1 } }), &["doc", "revision"])),
t("doc_optimize", "Optimize PDF", "Write an optimized copy to `path` (Acrobat's PDF Optimizer). preset: standard (default; Reduce File Size's choices) or mobile (images to 96 ppi above 144, JPEG high quality); the options below change it. compatibility: retain (default; keeps the document's version, or 1.5 when object streams are written), 1.4, 1.5, 1.6, 1.7 or 2.0. merge_fragments (default true) first puts a page picture drawn as many stacked image strips (as some PDF printers write it) back together into one image, so it can be resampled (merged_images, fragments_merged). color / gray: { downsample, ppi, above_ppi, compression: jpeg|zip|retain, quality 1–100 } (defaults: downsample to 150 ppi above 225, JPEG 60). mono: { downsample, ppi, above_ppi, compression: ccitt_g4|jbig2|retain } for black-and-white images and image masks (default: averaged down to 300 ppi above 450 ppi, counted in images_resampled; stored losslessly as CCITT Group 4 or JBIG2 (or 1-bit Flate, once resampled or packed from more bits) when that is smaller, Group 3 fax images, black-and-white RGB and indexed images using only palette entries 0 and 1 among them, counted in images_recompressed; retain resamples only, a CCITT image staying CCITT and any other becoming Flate). Images are measured where pages draw them and replaced only when smaller. discard_*: thumbnails (default true), alternate_images (true), tags, print_settings; flate_unencoded (true); object_streams (default true; always off for 1.4); lzw_to_flate (true) decodes LZW streams and stores them with Flate instead, leaving any it cannot decode unchanged (lzw_streams counts the streams converted); remove_invalid_links and remove_unreferenced_dests (true); images and forms the pages list but never draw are always dropped (unused_xobjects). discard: Remove Hidden Information categories (metadata, attachments, comments, form-fields, hidden-text, hidden-layers, bookmarks, links-actions-scripts, private-data). Signed documents are refused. The open document is unchanged.")
t("doc_optimize", "Optimize PDF", "Write an optimized copy to `path` (Acrobat's PDF Optimizer). preset: standard (default; Reduce File Size's choices) or mobile (images to 96 ppi above 144, JPEG high quality); the options below change it. compatibility: retain (default; keeps the document's version, or 1.5 when object streams are written), 1.4, 1.5, 1.6, 1.7 or 2.0. merge_fragments (default true) first puts a page picture drawn as many stacked image strips (as some PDF printers write it) back together into one image, so it can be resampled (merged_images, fragments_merged). color / gray: { downsample, ppi, above_ppi, compression: jpeg|zip|retain, quality 1–100 } (defaults: downsample to 150 ppi above 225, JPEG 60). mono: { downsample, ppi, above_ppi, compression: ccitt_g4|jbig2|retain } for black-and-white images and image masks (default: averaged down to 300 ppi above 450 ppi, counted in images_resampled; stored losslessly as CCITT Group 4 or JBIG2 (or 1-bit Flate, once resampled or packed from more bits) when that is smaller, up to 16 JBIG2 images sharing one symbol dictionary (/JBIG2Globals) where that is smaller still (image masks and DeviceGray images named directly, of at most 64 Mi pixels, which redaction can store again without it), Group 3 fax images, JBIG2 images, black-and-white RGB and indexed images using only palette entries 0 and 1 among them, counted in images_recompressed; retain resamples only, a CCITT image staying CCITT, a JBIG2 image JBIG2 and any other becoming Flate). Images past what one run may decode stay as they are, counted in images_refused; streams it only stores with Flate past that stay LZW, uncounted. Images are measured where pages draw them and replaced only when smaller. discard_*: thumbnails (default true), alternate_images (true), tags, print_settings; flate_unencoded (true); object_streams (default true; always off for 1.4); lzw_to_flate (true) decodes LZW streams and stores them with Flate instead, leaving any it cannot decode unchanged (lzw_streams counts the streams converted); remove_invalid_links and remove_unreferenced_dests (true); images and forms the pages list but never draw are always dropped (unused_xobjects). discard: Remove Hidden Information categories (metadata, attachments, comments, form-fields, hidden-text, hidden-layers, bookmarks, links-actions-scripts, private-data). Signed documents are refused. The open document is unchanged.")
.cmd("optimize.advanced")
.with(schema(
json!({
+643 -1
View File
@@ -664,6 +664,44 @@ fn tool_table_is_well_formed() {
}
}
fn assert_homogeneous_enums(schema: &Value, path: &str) {
fn json_kind(value: &Value) -> &'static str {
match value {
Value::Null => "null",
Value::Bool(_) => "boolean",
Value::Number(_) => "number",
Value::String(_) => "string",
Value::Array(_) => "array",
Value::Object(_) => "object",
}
}
if let Some(values) = schema.get("enum").and_then(Value::as_array) {
let first = values.first().map(json_kind);
assert!(values.iter().map(json_kind).all(|kind| Some(kind) == first), "mixed enum types at {path}: {values:?}");
}
match schema {
Value::Object(object) => {
for (key, child) in object {
assert_homogeneous_enums(child, &format!("{path}.{key}"));
}
}
Value::Array(array) => {
for (index, child) in array.iter().enumerate() {
assert_homogeneous_enums(child, &format!("{path}[{index}]"));
}
}
_ => {}
}
}
#[test]
fn tool_schema_enums_have_one_json_type() {
for tool in tools() {
assert_homogeneous_enums(&tool.input_schema, tool.name);
}
}
#[test]
fn explicit_font_and_disjoint_ranges_save_reopen_through_tools() {
let dir = workdir("font-ranges");
@@ -2111,6 +2149,27 @@ fn comments_through_tools() {
save_and_reopen_comments(&dir, &mut a, doc);
}
#[test]
fn freehand_highlight_through_tools() {
let dir = workdir("freehand-highlight");
let mut a = auto(&dir);
let doc = ok(&mut a, "doc_open", json!({ "path": "a.pdf" }))["doc"].as_u64().unwrap();
ok(
&mut a,
"comment_add",
json!({ "doc": doc, "page": 1, "type": "freehand_highlight", "width": 100,
"strokes": [[[20, 100], [120, 100]]] }),
);
let list = ok(&mut a, "comment_list", json!({ "doc": doc }));
assert_eq!(list["count"], 1);
assert_eq!(list["comments"][0]["type"], "Ink");
assert_eq!(list["comments"][0]["intent"], "FreehandHighlight");
assert_eq!(list["comments"][0]["color"], "#FFF000");
let undone = ok(&mut a, "edit_undo", json!({ "doc": doc }));
assert_eq!(undone["undone"], "Add freehand highlight");
assert_eq!(ok(&mut a, "comment_list", json!({ "doc": doc }))["count"], 0);
}
fn add_comment_examples(a: &mut Automation, doc: u64) -> String {
// "Page 2" sits at y = 150 (user space) = 150 from the top of the 300 pt page.
let hl = ok(a, "comment_add", json!({ "doc": doc, "page": 2, "type": "highlight", "find": "page 2", "contents": "check", "author": "Ada" }));
@@ -2773,6 +2832,74 @@ fn headers_watermarks_and_backgrounds_through_tools() {
assert!(matches!(refused, Err(ToolError::InvalidArgs(e)) if e.contains("Courier")));
}
#[test]
fn bates_numbers_continue_across_files_and_report_preflight_and_permission_failures() {
let dir = workdir("bates-multi");
let files = json!([
{"input":"b.pdf","output":"b-numbered.pdf"},
{"input":"a.pdf","output":"a-numbered.pdf"}
]);
let mut a = auto(&dir);
let allocation = ok(&mut a, "doc_bates_multi", json!({"files":files,"start_number":50,"dry_run":true}));
assert_eq!(allocation["files"][0]["first"], 50);
assert_eq!(allocation["files"][0]["last"], 51);
assert_eq!(allocation["files"][1]["first"], 52);
assert_eq!(allocation["files"][1]["last"], 54);
assert!(!dir.join("a-numbered.pdf").exists());
let applied = ok(&mut a, "doc_bates_multi", json!({"files":files,"start_number":17,"prefix":"CASE-"}));
assert_eq!(applied["completed"], 2);
let mut out = auto(&dir);
let first = ok(&mut out, "doc_open", json!({"path":"a-numbered.pdf"}))["doc"].as_u64().unwrap();
let second = ok(&mut out, "doc_open", json!({"path":"b-numbered.pdf"}))["doc"].as_u64().unwrap();
assert!(page_text(&mut out, second)[0].contains("CASE-000017"));
assert!(page_text(&mut out, first)[0].contains("CASE-000019"));
let overflow = err(&mut a, "doc_bates_multi", json!({"files":[{"input":"b.pdf","output":"overflow.pdf"}],"start_number":u64::MAX}));
assert!(overflow.to_string().contains("overflows"));
assert!(!dir.join("overflow.pdf").exists());
// A range may end at u64::MAX itself.
let at_max = ok(&mut a, "doc_bates_multi", json!({"files":[{"input":"b.pdf","output":"max.pdf"}],"start_number":u64::MAX - 1,"dry_run":true}));
assert_eq!(at_max["files"][0]["last"], u64::MAX);
for bad in
[json!({"start_number":-3}), json!({"start_number":2.5}), json!({"start_number":"7"}), json!({"prefix":"CASE>>"}), json!({"suffix":"A>>B"})]
{
let mut args = json!({"files":[{"input":"b.pdf","output":"bad.pdf"}],"dry_run":true});
args.as_object_mut().unwrap().extend(bad.as_object().unwrap().clone());
assert!(a.call("doc_bates_multi", &args).is_err(), "{bad}");
}
use pdfcraft_engine::{Changes, Edit, Protection, Session};
let mut session = Session::new();
let id = session.open("locked.pdf", None, std::sync::Arc::new(fixture(1)), None).unwrap();
session
.apply(
id,
Edit::Protect(Protection {
open_password: Some("open".into()),
permissions_password: Some("owner".into()),
changes: Changes::None,
..Default::default()
}),
)
.unwrap();
std::fs::write(dir.join("locked.pdf"), session.save_bytes(id).unwrap().as_ref()).unwrap();
let result = ok(
&mut a,
"doc_bates_multi",
json!({"files":[
{"input":"b.pdf","output":"partial-numbered.pdf"},
{"input":"locked.pdf","output":"locked-numbered.pdf","password":"open"}
]}),
);
assert_eq!(result["completed"], 1);
assert_eq!(result["failed"], 1);
assert_eq!(result["files"][1]["first"], 3);
assert!(result["files"][1]["error"].as_str().unwrap().contains("owner password"), "{result}");
assert!(dir.join("partial-numbered.pdf").exists());
assert!(!dir.join("locked-numbered.pdf").exists());
}
#[test]
fn a_shrinking_header_and_footer_moves_the_page_content_out_of_their_way_through_tools() {
let dir = workdir("hf-shrink");
@@ -3286,6 +3413,39 @@ fn editing_existing_text_through_tools() {
assert_eq!(p["lines"].as_array().map(Vec::len), Some(2), "{p}");
}
/// Format text ▸ Superscript and Subscript without the GUI: a range, then back again over a space
/// (which has no superscript form), each one undo step; refusals change nothing.
#[test]
fn superscript_and_subscript_through_tools() {
let dir = workdir("text-script");
let mut a = auto(&dir);
let doc = ok(&mut a, "doc_open", json!({ "path": "a.pdf" }))["doc"].as_u64().unwrap();
let paragraph =
|a: &mut Automation| ok(a, "text_paragraphs", json!({ "doc": doc, "page": 2 }))["paragraphs"][0]["text"].as_str().unwrap().to_string();
let script = |script: &str, range: Value| json!({ "doc": doc, "page": 2, "paragraph": 1, "script": script, "range": range });
// "Page 2": the 2 is byte 5.
let r = ok(&mut a, "text_script", script("superscript", json!([5, 6])));
assert_eq!((r["script"].as_str(), r["paragraph"]["text"].as_str()), (Some("superscript"), Some("Page ²")), "{r}");
assert_eq!(page_text(&mut a, doc)[1], "Page ²");
// " ²": the space has no superscript form, and the range still toggles back.
ok(&mut a, "text_script", script("superscript", json!([4, 7])));
assert_eq!(paragraph(&mut a), "Page 2");
assert_eq!(ok(&mut a, "edit_undo", json!({ "doc": doc }))["undone"], "Edit text");
assert_eq!(paragraph(&mut a), "Page ²");
// Refused, changing nothing: a range that splits ², one past the end, an empty one, a range
// with nothing that has a subscript form, an unknown script.
for (name, range) in [
("superscript", json!([5, 6])),
("superscript", json!([0, 99])),
("superscript", json!([3, 3])),
("subscript", json!([4, 5])),
("italic", json!([0, 1])),
] {
assert!(matches!(a.call("text_script", &script(name, range.clone())), Err(ToolError::InvalidArgs(_))), "{name} {range}");
}
assert_eq!(paragraph(&mut a), "Page ²");
}
#[test]
fn styled_cyrillic_fallback_is_batched_through_tools_and_reopen() {
if pdfcraft_fonts::document_japanese_font().is_none() {
@@ -3453,6 +3613,13 @@ fn editing_page_images_through_tools() {
assert_eq!(cropped["visible_rect"], json!([10.0, 10.0, 25.0, 30.0]));
ok(&mut a, "image_edit", json!({ "doc": made, "page": 1, "image": 1, "action": "rotate" }));
ok(&mut a, "image_edit", json!({ "doc": made, "page": 1, "image": 1, "action": "flip_horizontal" }));
// A single image is already in front and at the back; no-op arrange is refused without dirtying undo.
assert!(a.call("image_edit", &json!({ "doc": made, "page": 1, "image": 1, "action": "bring_to_front" })).is_err());
assert!(a.call("image_edit", &json!({ "doc": made, "page": 1, "image": 1, "action": "send_to_back" })).is_err());
assert!(a.call("image_edit", &json!({ "doc": made, "page": 1, "image": 1, "action": "bring_forward" })).is_err());
assert!(a.call("image_edit", &json!({ "doc": made, "page": 1, "image": 1, "action": "send_backward" })).is_err());
let r = ok(&mut a, "image_edit", json!({ "doc": made, "page": 1, "image": 1, "action": "remove_crop" }));
assert_eq!(r["undo"], "Remove crop");
// Any angle: the box grows to the turned picture's bounds, and it undoes like a quarter turn.
let before = ok(&mut a, "page_images", json!({ "doc": made, "page": 1 }))["images"][0]["rect"].clone();
let r = ok(&mut a, "image_edit", json!({ "doc": made, "page": 1, "image": 1, "action": "rotate_by", "degrees": 30.5 }));
@@ -3472,6 +3639,80 @@ fn editing_page_images_through_tools() {
assert!(matches!(a.call("image_edit", &json!({ "doc": made, "page": 1, "image": 1, "action": "delete" })), Err(ToolError::InvalidArgs(_))));
}
#[test]
fn arranging_page_images_through_tools() {
let dir = workdir("arrange-page-images");
let mut a = auto(&dir);
let doc = ok(&mut a, "doc_open", json!({ "path": "a.pdf" }))["doc"].as_u64().unwrap();
ok(&mut a, "doc_export_images", json!({ "doc": doc, "folder": "src", "dpi": 18, "pages": [1, 2] }));
let made = ok(&mut a, "doc_create", json!({ "from": "images", "paths": ["src/a_page_1.png"] }))["doc"].as_u64().unwrap();
ok(&mut a, "page_add_image", json!({ "doc": made, "page": 1, "path": "src/a_page_2.png", "rect": [50, 50, 100, 100] }));
assert_eq!(ok(&mut a, "page_images", json!({ "doc": made, "page": 1 }))["count"], 2);
let r = ok(&mut a, "image_edit", json!({ "doc": made, "page": 1, "image": 1, "action": "bring_to_front" }));
assert_eq!(r["undo"], "Bring to front");
let r = ok(&mut a, "image_edit", json!({ "doc": made, "page": 1, "image": 2, "action": "send_to_back" }));
assert_eq!(r["undo"], "Send to back");
ok(&mut a, "doc_save", json!({ "doc": made, "path": "arranged.pdf" }));
let reopened = ok(&mut a, "doc_open", json!({ "path": "arranged.pdf" }))["doc"].as_u64().unwrap();
let after_reopen = ok(&mut a, "page_images", json!({ "doc": reopened, "page": 1 }));
assert_eq!(after_reopen["count"], 2);
assert_eq!(after_reopen["images"][0]["rect"], json!([0.0, 0.0, 50.0, 75.0]));
assert_eq!(after_reopen["images"][1]["rect"], json!([50.0, 50.0, 100.0, 100.0]));
}
/// The transform a rotated-image resize sends (`ImageEdit::Transform`) is reachable headlessly,
/// in the same top-left-origin points as the other image tools, also on a turned page.
#[test]
fn transforming_page_images_through_tools() {
let dir = workdir("transform-page-images");
let mut a = auto(&dir);
let doc = ok(&mut a, "doc_open", json!({ "path": "a.pdf" }))["doc"].as_u64().unwrap();
ok(&mut a, "doc_export_images", json!({ "doc": doc, "folder": "src", "dpi": 18, "pages": [1] }));
let made = ok(&mut a, "doc_create", json!({ "from": "images", "paths": ["src/a_page_1.png"] }))["doc"].as_u64().unwrap();
let rect = |a: &mut Automation| ok(a, "page_images", json!({ "doc": made, "page": 1 }))["images"][0]["rect"].clone();
let transform =
|a: &mut Automation, m: Value| ok(a, "image_edit", json!({ "doc": made, "page": 1, "image": 1, "action": "transform", "matrix": m }));
ok(&mut a, "image_edit", json!({ "doc": made, "page": 1, "image": 1, "action": "move", "rect": [5, 5, 25, 35] }));
// Right 10, down 20.
assert_eq!(transform(&mut a, json!([1, 0, 0, 1, 10, 20]))["undo"], "Transform image");
assert_eq!(rect(&mut a), json!([15.0, 25.0, 35.0, 55.0]));
// Twice the size about the top-left corner of the page.
transform(&mut a, json!([2, 0, 0, 2, 0, 0]));
assert_eq!(rect(&mut a), json!([30.0, 50.0, 70.0, 110.0]));
// A quarter turn, (x, y) → (200 − y, x): the box turns with it, and it undoes in one step.
transform(&mut a, json!([0, 1, -1, 0, 200, 0]));
assert_eq!(rect(&mut a), json!([90.0, 30.0, 150.0, 70.0]));
ok(&mut a, "edit_undo", json!({ "doc": made }));
assert_eq!(rect(&mut a), json!([30.0, 50.0, 70.0, 110.0]));
// On a turned page "right" is still right on screen.
ok(&mut a, "page_rotate", json!({ "doc": made, "pages": [1], "degrees": 90 }));
let numbers = |v: Value| [0, 1, 2, 3].map(|i| v[i].as_f64().unwrap());
let [x0, y0, x1, y1] = numbers(rect(&mut a));
transform(&mut a, json!([1, 0, 0, 1, 10, 0]));
let after = numbers(rect(&mut a));
for (got, want) in after.into_iter().zip([x0 + 10.0, y0, x1 + 10.0, y1]) {
assert!((got - want).abs() < 0.015, "{after:?} is not ({x0}, {y0}, {x1}, {y1}) moved right by 10");
}
// Flat, non-finite, short and missing matrices are refused before anything changes.
let before = rect(&mut a);
for bad in [
json!([1, 2, 2, 4, 0, 0]),
json!([0, 0, 0, 0, 0, 0]),
json!([1e300, 0, 0, 1e300, 0, 0]),
json!([1, 0, 0, 1]),
json!([1, 0, "invalid", 0, 1, 10, 0]),
json!([1, 0, null, 0, 1, 10, 0]),
] {
let r = a.call("image_edit", &json!({ "doc": made, "page": 1, "image": 1, "action": "transform", "matrix": bad }));
assert!(matches!(r, Err(ToolError::InvalidArgs(_))), "{bad}: {r:?}");
}
assert!(matches!(a.call("image_edit", &json!({ "doc": made, "page": 1, "image": 1, "action": "transform" })), Err(ToolError::InvalidArgs(_))));
assert_eq!(rect(&mut a), before);
}
#[test]
fn enhance_camera_image_through_tools() {
let dir = workdir("enhance-camera");
@@ -4497,12 +4738,23 @@ fn removing_hidden_information_through_tools() {
assert_eq!(r["undo"], "Remove hidden information");
assert_eq!(ok(&mut a, "comment_list", json!({ "doc": doc }))["count"], 0);
assert!(count(&ok(&mut a, "doc_hidden_info", json!({ "doc": doc })), "metadata") >= 1, "only comments went");
// With none left, removing them again says so, and Optimize discarding them still runs.
let again = a.call("doc_remove_hidden", &json!({ "doc": doc, "categories": ["comments"] }));
assert!(matches!(&again, Err(ToolError::Failed(m)) if m.starts_with("nothing to remove")), "{again:?}");
let optimized = ok(&mut a, "doc_optimize", json!({ "doc": doc, "path": "optimized.pdf", "discard": ["comments", "bookmarks"] }));
assert_eq!(optimized["discarded"], json!([]), "{optimized}");
let r = ok(&mut a, "doc_remove_hidden", json!({ "doc": doc }));
assert_eq!(r["undo"], "Sanitize document");
ok(&mut a, "doc_save", json!({ "doc": doc, "path": "clean.pdf" }));
let bytes = std::fs::read(dir.join("clean.pdf")).unwrap();
assert!(!bytes.windows(11).any(|w| w == b"Secret plan"), "the old revision is gone");
assert!(matches!(a.call("doc_remove_hidden", &json!({ "doc": doc, "categories": ["nonsense"] })), Err(ToolError::InvalidArgs(_))));
// A document that can't be edited has no scan: the refusal says why, not that nothing is there.
let junk = [vec![b'x'; 5000], std::fs::read(dir.join("a.pdf")).unwrap()].concat();
std::fs::write(dir.join("junk.pdf"), junk).unwrap();
let read_only = ok(&mut a, "doc_open", json!({ "path": "junk.pdf" }))["doc"].as_u64().unwrap();
let refused = a.call("doc_remove_hidden", &json!({ "doc": read_only, "categories": ["comments"] }));
assert!(matches!(&refused, Err(ToolError::Failed(m)) if m.contains("can't be edited")), "{refused:?}");
}
/// A one-page PDF whose text "TOP SECRET" sits under an opaque black rectangle.
@@ -6478,10 +6730,12 @@ fn optimizing_through_tools() {
let reduced = ok(&mut a, "doc_reduce", json!({ "doc": doc, "path": "reduced.pdf" }));
assert!(reduced["bytes_after"].as_u64().unwrap() < reduced["bytes_before"].as_u64().unwrap());
assert_eq!(reduced["written"], true);
assert_eq!(reduced["images_refused"], 0);
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["images_refused"], 0);
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"));
@@ -7429,6 +7683,17 @@ fn exporting_to_word_html_and_rtf() {
}
let html = std::fs::read_to_string(dir.join("a.html")).unwrap();
assert!(html.contains("Page 1") && html.contains("Page 3") && html.matches("<hr>").count() == 2, "{html}");
ok(&mut a, "doc_export_office", json!({ "doc": doc, "path": "simple.html", "html_mode": "simple" }));
let simple_html = std::fs::read_to_string(dir.join("simple.html")).unwrap();
assert!(
simple_html.contains("Page 1")
&& !simple_html.contains("<style")
&& !simple_html.contains("style=")
&& !simple_html.contains("<span")
&& !simple_html.contains("<div")
);
assert!(a.call("doc_export_office", &json!({ "doc": doc, "path": "bad.html", "html_mode": "compact" })).is_err());
assert!(a.call("doc_export_office", &json!({ "doc": doc, "path": "bad.docx", "html_mode": "simple" })).is_err());
assert!(std::fs::read(dir.join("a.docx")).unwrap().starts_with(b"PK"));
assert!(std::fs::read(dir.join("a.pptx")).unwrap().starts_with(b"PK"));
assert!(std::fs::read_to_string(dir.join("a.rtf")).unwrap().contains("Page 2"));
@@ -9764,7 +10029,11 @@ fn added_text_lines_take_their_own_alignments() {
let dir = workdir("paragraph-aligns");
let mut a = auto(&dir);
let id = ok(&mut a, "doc_create", json!({"from":"blank","width":600,"height":400}))["doc"].as_u64().unwrap();
ok(&mut a, "page_add_text", json!({"doc":id,"page":1,"text":"Left line\nRight line","at":[40,50],"width":500,"size":12,"aligns":[null,"right"]}));
ok(
&mut a,
"page_add_text",
json!({"doc":id,"page":1,"text":"Left line\nRight line\nInherited line","at":[40,50],"width":500,"size":12,"aligns":[null,"right","inherit"]}),
);
let rect = |a: &mut Automation, text: &str| -> Vec<f64> {
let lines = ok(a, "text_lines", json!({"doc":id,"page":1}));
let line = lines["lines"].as_array().unwrap().iter().find(|l| l["text"] == text).cloned().unwrap();
@@ -9772,10 +10041,13 @@ fn added_text_lines_take_their_own_alignments() {
};
assert!((rect(&mut a, "Left line")[0] - 40.0).abs() < 1.0);
assert!((rect(&mut a, "Right line")[2] - 540.0).abs() < 1.0, "{:?}", rect(&mut a, "Right line"));
assert!((rect(&mut a, "Inherited line")[0] - 40.0).abs() < 1.0);
// The whole box centred: the right-aligned line goes with it.
ok(&mut a, "content_update", json!({"doc":id,"page":1,"index":1,"align":"center"}));
let right = rect(&mut a, "Right line");
assert!(((right[0] + right[2]) / 2.0 - 290.0).abs() < 1.0, "{right:?}");
let inherited = rect(&mut a, "Inherited line");
assert!(((inherited[0] + inherited[2]) / 2.0 - 290.0).abs() < 1.0, "{inherited:?}");
assert!(a.call("content_update", &json!({"doc":id,"page":1,"index":1,"aligns":["sideways"]})).is_err());
assert!(a.call("content_update", &json!({"doc":id,"page":1,"index":1,"aligns":"right"})).is_err());
}
@@ -9922,6 +10194,31 @@ fn changing_a_lists_options_through_tools_keeps_its_saved_selection_on_the_same_
assert_eq!(saved_selection_indices(&dir.join("letters.pdf"), "letters"), Some(vec![0, 1]), "B and C are now items 0 and 1");
}
/// Clearing a field's length limit through `form_set_props` (`"max_length": 0`) leaves it with
/// none, even when its parent field has one it would otherwise inherit.
#[test]
fn clearing_a_kids_length_limit_through_tools_does_not_bring_back_its_parents() {
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 [6 0 R] >>",
"<< /Fields [5 0 R] /DA (/Helv 12 Tf 0 g) /DR << /Font << /Helv 7 0 R >> >> >>",
"<< /T (address) /FT /Tx /MaxLen 3 /Kids [6 0 R] >>",
"<< /Type /Annot /Subtype /Widget /T (city) /Parent 5 0 R /MaxLen 8 /Rect [10 250 150 268] /P 3 0 R >>",
"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>",
];
let dir = workdir("kid-max-len");
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();
ok(&mut a, "form_set_props", json!({ "doc": doc, "field": "address.city", "max_length": 0 }));
ok(&mut a, "form_fill", json!({ "doc": doc, "values": { "address.city": "Absalom" } }));
let fields = ok(&mut a, "form_fields", json!({ "doc": doc }));
let city = fields["fields"].as_array().unwrap().iter().find(|f| f["name"] == "address.city").unwrap().clone();
assert!(city.get("max_length").is_none(), "no limit, not the parent's 3: {city}");
assert_eq!(city["value"], "Absalom", "the value is not cut to the parent's 3 characters");
}
/// Clearing a field's default through `form_set_props` (`"default": ""`) leaves it with none,
/// even when its parent field has one it would otherwise inherit.
#[test]
@@ -10190,3 +10487,348 @@ fn simple_rule_scan_drawn(content: &[u8]) -> Vec<u8> {
}
write_full(&doc, &SaveOptions::default()).unwrap()
}
#[test]
fn editor_crop_group_move_and_arrange_survive_added_item_deletion_through_tools() {
let dir = workdir("editor-crop-group-arrange");
let mut a = auto(&dir);
let source = ok(&mut a, "doc_open", json!({"path":"a.pdf"}))["doc"].as_u64().unwrap();
ok(&mut a, "doc_export_images", json!({"doc":source,"folder":"src","dpi":18,"pages":[1]}));
let doc = ok(&mut a, "doc_create", json!({"from":"images","paths":["src/a_page_1.png"]}))["doc"].as_u64().unwrap();
ok(&mut a, "image_edit", json!({"doc":doc,"page":1,"image":1,"action":"move","rect":[5,5,25,35]}));
ok(&mut a, "image_edit", json!({"doc":doc,"page":1,"image":1,"action":"crop","rect":[10,10,20,30]}));
ok(&mut a, "page_add_text", json!({"doc":doc,"page":1,"text":"Movable label","rect":[2,40,45,55],"size":6}));
let inventory = ok(&mut a, "object_list", json!({"doc":doc,"page":1}));
let objects: Vec<_> = inventory["objects"].as_array().unwrap().iter().map(|o| json!({"kind":o["kind"],"index":o["index"]})).collect();
assert_eq!(objects.len(), 2);
let moved = ok(&mut a, "object_move", json!({"doc":doc,"page":1,"objects":objects,"offset":[3,4]}));
assert_eq!(moved["moved"], 2);
let picture = ok(&mut a, "page_images", json!({"doc":doc,"page":1}))["images"][0].clone();
assert_eq!(picture["rect"], json!([8.0, 9.0, 28.0, 39.0]));
assert_eq!(picture["visible_rect"], json!([13.0, 14.0, 23.0, 34.0]));
assert!(page_text(&mut a, doc)[0].contains("Movable label"));
ok(&mut a, "edit_undo", json!({"doc":doc}));
assert_eq!(ok(&mut a, "page_images", json!({"doc":doc,"page":1}))["images"][0]["visible_rect"], json!([10.0, 10.0, 20.0, 30.0]));
ok(&mut a, "edit_redo", json!({"doc":doc}));
ok(&mut a, "doc_save", json!({"doc":doc,"path":"grouped.pdf"}));
let reopened = ok(&mut a, "doc_open", json!({"path":"grouped.pdf"}))["doc"].as_u64().unwrap();
assert_eq!(ok(&mut a, "page_images", json!({"doc":reopened,"page":1}))["images"][0]["visible_rect"], picture["visible_rect"]);
ok(&mut a, "image_edit", json!({"doc":reopened,"page":1,"image":1,"action":"bring_to_front"}));
assert_eq!(ok(&mut a, "content_list", json!({"doc":reopened}))["count"], 1);
ok(&mut a, "content_delete", json!({"doc":reopened,"page":1,"index":1}));
ok(&mut a, "doc_save", json!({"doc":reopened,"path":"independent.pdf"}));
let saved = ok(&mut a, "doc_open", json!({"path":"independent.pdf"}))["doc"].as_u64().unwrap();
let after = ok(&mut a, "page_images", json!({"doc":saved,"page":1}));
assert_eq!(after["count"], 1);
assert_eq!(after["images"][0]["rect"], picture["rect"]);
assert_eq!(after["images"][0]["visible_rect"], picture["visible_rect"]);
let rendered = a.call("page_render", &json!({"doc":saved,"page":1,"dpi":72})).unwrap();
assert!(rendered.iter().any(|c| matches!(c, Content::Png {data,width,height} if !data.is_empty() && *width > 0 && *height > 0)));
}
#[test]
fn image_flip_tools_follow_displayed_axes_on_every_page_rotation() {
fn corners(a: &Automation, id: u64) -> [[f64; 2]; 4] {
let doc = a.session().get(pdfcraft_engine::DocId(id)).unwrap();
let [aa, b, c, d, e, f] = doc.page_images(0)[0].matrix;
[(0.0, 0.0), (1.0, 0.0), (0.0, 1.0), (1.0, 1.0)]
.map(|(x, y)| doc.info.pages[0].user_to_view((aa * x + c * y + e) as f32, (b * x + d * y + f) as f32).map(f64::from))
}
fn raster(a: &mut Automation, id: u64) -> (usize, usize, Vec<u8>) {
let rendered = a.call("page_render", &json!({"doc":id,"page":1,"dpi":72})).unwrap();
let Content::Png { data, .. } = &rendered[0] else { panic!("expected PNG") };
let mut reader = png::Decoder::new(std::io::Cursor::new(data)).read_info().unwrap();
let mut bytes = vec![0; reader.output_buffer_size().unwrap()];
let frame = reader.next_frame(&mut bytes).unwrap();
bytes.truncate(frame.buffer_size());
if frame.color_type == png::ColorType::Rgb {
bytes = bytes.as_chunks::<3>().0.iter().flat_map(|&[r, g, b]| [r, g, b, 255]).collect();
} else {
assert_eq!(frame.color_type, png::ColorType::Rgba);
}
(frame.width as usize, frame.height as usize, bytes)
}
let dir = workdir("displayed-image-flip");
let mut png_bytes = Vec::new();
{
let mut encoder = png::Encoder::new(&mut png_bytes, 8, 4);
encoder.set_color(png::ColorType::Rgb);
let colors = [[240, 20, 30], [20, 230, 40], [30, 40, 220], [220, 210, 20]];
let pixels: Vec<u8> = (0..4).flat_map(|y| (0..8).flat_map(move |x| colors[usize::from(x >= 4) + 2 * usize::from(y >= 2)])).collect();
encoder.write_header().unwrap().write_image_data(&pixels).unwrap();
}
std::fs::write(dir.join("quadrants.png"), png_bytes).unwrap();
let mut a = auto(&dir);
let mut failures = Vec::new();
for rotation in [0, 90, 180, 270] {
let doc = ok(&mut a, "doc_create", json!({"from":"images","paths":["quadrants.png"]}))["doc"].as_u64().unwrap();
if rotation != 0 {
ok(&mut a, "page_rotate", json!({"doc":doc,"pages":[1],"degrees":rotation}));
}
let before = corners(&a, doc);
let (width, height, pixels) = raster(&mut a, doc);
let xmin = before.iter().map(|p| p[0]).fold(f64::INFINITY, f64::min);
let xmax = before.iter().map(|p| p[0]).fold(f64::NEG_INFINITY, f64::max);
let ymin = before.iter().map(|p| p[1]).fold(f64::INFINITY, f64::min);
let ymax = before.iter().map(|p| p[1]).fold(f64::NEG_INFINITY, f64::max);
for (action, horizontal) in [("flip_horizontal", true), ("flip_vertical", false)] {
ok(&mut a, "image_edit", json!({"doc":doc,"page":1,"image":1,"action":action}));
let after = corners(&a, doc);
for (old, new) in before.into_iter().zip(after) {
let expected = if horizontal { [xmin + xmax - old[0], old[1]] } else { [old[0], ymin + ymax - old[1]] };
if new.into_iter().zip(expected).any(|(actual, want)| (actual - want).abs() > 0.001) {
failures.push(format!("rotation {rotation} {action}: corner {old:?} became {new:?}, expected {expected:?}"));
break;
}
}
let (new_width, new_height, actual_pixels) = raster(&mut a, doc);
assert_eq!((new_width, new_height), (width, height));
let mut expected_pixels = Vec::new();
for y in 0..height {
for x in 0..width {
let source = if horizontal { (y * width + width - 1 - x) * 4 } else { ((height - 1 - y) * width + x) * 4 };
expected_pixels.extend_from_slice(&pixels[source..source + 4]);
}
}
if actual_pixels.iter().zip(&expected_pixels).any(|(actual, want)| actual.abs_diff(*want) > 1) {
failures.push(format!("rotation {rotation} {action}: raster flipped the wrong displayed axis"));
}
assert_ne!(actual_pixels, pixels, "the asymmetric image makes both flip axes observable");
ok(&mut a, "edit_undo", json!({"doc":doc}));
assert_eq!(corners(&a, doc), before, "one undo restores the original placement");
}
}
assert!(failures.is_empty(), "{}", failures.join("\n"));
}
#[test]
fn mixed_script_tools_normalize_but_undo_restores_the_exact_mixture() {
let dir = workdir("mixed-script-policy");
let mut a = auto(&dir);
for (script, mixed, uniform, plain) in [("superscript", "Q²2", "Q²²", "Q22"), ("subscript", "H₂2", "H₂₂", "H22")] {
let doc = ok(&mut a, "doc_open", json!({"path":"a.pdf"}))["doc"].as_u64().unwrap();
ok(&mut a, "text_edit", json!({"doc":doc,"page":1,"paragraph":1,"text":mixed,"size":14,"width":160}));
let paragraph =
|a: &mut Automation| ok(a, "text_paragraphs", json!({"doc":doc,"page":1}))["paragraphs"][0]["editor_text"].as_str().unwrap().to_owned();
assert_eq!(paragraph(&mut a), mixed);
let before = a.session().get(pdfcraft_engine::DocId(doc)).unwrap().bytes.clone();
let args = json!({"doc":doc,"page":1,"paragraph":1,"script":script});
let once = ok(&mut a, "text_script", args.clone());
assert_eq!(once["paragraph"]["text"], uniform);
assert_eq!(paragraph(&mut a), uniform);
ok(&mut a, "text_script", args);
assert_eq!(paragraph(&mut a), plain);
assert_ne!(plain, mixed, "normalization does not promise to recreate the original mixture");
ok(&mut a, "edit_undo", json!({"doc":doc}));
assert_eq!(paragraph(&mut a), uniform, "one Undo restores the preceding scripted text");
ok(&mut a, "edit_undo", json!({"doc":doc}));
assert_eq!(paragraph(&mut a), mixed, "Undo restores the exact initial Unicode mixture");
assert_eq!(
a.session().get(pdfcraft_engine::DocId(doc)).unwrap().bytes.as_ref(),
before.as_ref(),
"Undo also restores the exact prior document bytes"
);
ok(&mut a, "edit_redo", json!({"doc":doc}));
assert_eq!(paragraph(&mut a), uniform);
ok(&mut a, "edit_redo", json!({"doc":doc}));
assert_eq!(paragraph(&mut a), plain);
let path = format!("mixed-{script}.pdf");
ok(&mut a, "doc_save", json!({"doc":doc,"path":path}));
let reopened = ok(&mut a, "doc_open", json!({"path":path}))["doc"].as_u64().unwrap();
assert_eq!(page_text(&mut a, reopened)[0], plain);
}
}
#[test]
fn multiline_fill_sign_engine_round_trip_preserves_lines_and_appearance() {
let dir = workdir("fill-sign-multiline");
let mut a = auto(&dir);
let doc = ok(&mut a, "doc_open", json!({"path":"a.pdf"}))["doc"].as_u64().unwrap();
let text = "\nAda\n\nLovelace\n";
ok(&mut a, "fill_sign_add", json!({"doc":doc,"page":1,"type":"text","at":[20,20],"text":text}));
let id = pdfcraft_engine::DocId(doc);
let annot = &a.session().get(id).unwrap().info.annotations[0];
assert_eq!(annot.contents.as_deref(), Some(text), "typewriter contents keep outer line breaks");
assert!(annot.rect[3] - annot.rect[1] >= 66.0, "five text lines need their full height, including blank lines: {:?}", annot.rect);
let pixels = a.render_pixels(doc, 1, 1.0).unwrap();
// The fixture's page text is at y=150; only the typewriter draws at y=65..80.
assert!(
(65..80).any(|y| (20..80).any(|x| {
let i = (y * pixels.0 as usize + x) * 4;
pixels.2[i..i + 3].iter().all(|v| *v < 100)
})),
"the lower nonempty line appears inside its box"
);
let rendered = a.call("page_render", &json!({"doc":doc,"page":1,"dpi":72})).unwrap();
ok(&mut a, "doc_save", json!({"doc":doc,"path":"multiline.pdf"}));
let mut re = auto(&dir);
let reopened = ok(&mut re, "doc_open", json!({"path":"multiline.pdf"}))["doc"].as_u64().unwrap();
assert_eq!(re.session().get(pdfcraft_engine::DocId(reopened)).unwrap().info.annotations[0].contents.as_deref(), Some(text));
assert_eq!(rendered, re.call("page_render", &json!({"doc":reopened,"page":1,"dpi":72})).unwrap(), "saved appearances are identical");
std::fs::remove_dir_all(dir).unwrap();
}
/// Export, then import into another document and copy between open documents: the tree comes
/// back unchanged, a page the target lacks is reported, and the import undoes in one step.
#[test]
fn bookmarks_export_import_and_copy_between_documents() {
let dir = workdir("bookmark-io");
let mut a = auto(&dir);
let src = ok(&mut a, "doc_open", json!({ "path": "a.pdf" }))["doc"].as_u64().unwrap();
ok(&mut a, "bookmark_add", json!({ "doc": src, "title": "Intro", "page": 1 }));
ok(&mut a, "bookmark_add", json!({ "doc": src, "title": "Detail", "page": 3, "parent": [1] }));
ok(&mut a, "bookmark_add", json!({ "doc": src, "title": "End", "page": 2 }));
ok(&mut a, "bookmark_set_style", json!({ "doc": src, "path": [1], "color": [1, 0, 0], "bold": true }));
let exported = ok(&mut a, "bookmark_export", json!({ "doc": src, "out": "marks.json" }));
assert_eq!(exported["truncated"], false);
let tree = exported["bookmarks"].clone();
assert_eq!((tree[0]["title"].clone(), tree[0]["color"].clone(), tree[0]["bold"].clone()), (json!("Intro"), json!([1.0, 0.0, 0.0]), json!(true)));
assert_eq!((tree[0]["children"][0]["title"].clone(), tree[0]["children"][0]["page"].clone()), (json!("Detail"), json!(3)));
assert_eq!(tree[0]["view"]["type"], "XYZ");
let subtree = ok(&mut a, "bookmark_export", json!({ "doc": src, "path": [1, 1] }))["bookmarks"].clone();
assert_eq!(subtree, json!([tree[0]["children"][0]]));
// b.pdf has two pages: Detail goes to the third, so it arrives without a destination.
let dst = ok(&mut a, "doc_open", json!({ "path": "b.pdf" }))["doc"].as_u64().unwrap();
let imported = ok(&mut a, "bookmark_import", json!({ "doc": dst, "file": "marks.json" }));
assert_eq!(imported["unmapped"], json!([[1, 1]]));
let back = ok(&mut a, "bookmark_export", json!({ "doc": dst }))["bookmarks"].clone();
assert_eq!(back[0]["children"][0]["page"], json!(null));
assert_eq!((back[0]["title"].clone(), back[1].clone()), (tree[0]["title"].clone(), tree[1].clone()));
ok(&mut a, "edit_undo", json!({ "doc": dst }));
assert_eq!(ok(&mut a, "bookmark_list", json!({ "doc": dst }))["bookmarks"], json!([]));
// Into a document with every page, the tree is unchanged, wherever it is copied from.
let same = ok(&mut a, "doc_open", json!({ "path": "a.pdf" }))["doc"].as_u64().unwrap();
ok(&mut a, "bookmark_add", json!({ "doc": same, "title": "Old", "page": 1 }));
let copied = ok(&mut a, "bookmark_copy", json!({ "doc": same, "from": src, "replace": true }));
assert_eq!(copied["unmapped"], json!([]));
assert_eq!(ok(&mut a, "bookmark_export", json!({ "doc": same }))["bookmarks"], tree);
ok(&mut a, "bookmark_import", json!({ "doc": same, "bookmarks": subtree, "parent": [2], "position": 1 }));
assert_eq!(ok(&mut a, "bookmark_list", json!({ "doc": same }))["bookmarks"][1]["children"][0]["title"], "Detail");
}
/// A one-page document whose outline has an untitled item, a /FitR destination with three of
/// its four numbers, and a chain nested `deep` levels below them.
fn odd_outline(deep: usize) -> Vec<u8> {
let first_deep = 7;
let mut objs = vec![
"<< /Type /Catalog /Pages 2 0 R /Outlines 4 0 R >>".to_string(),
"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 200 300] >>".into(),
"<< /Type /Page /Parent 2 0 R >>".into(),
"<< /Type /Outlines /First 5 0 R /Last 6 0 R >>".into(),
"<< /Title () /Parent 4 0 R /Next 6 0 R /Dest [3 0 R /Fit] >>".into(),
format!(
"<< /Title (Short) /Parent 4 0 R /Prev 5 0 R /Dest [3 0 R /FitR 0 0 10]{} >>",
if deep > 0 { format!(" /First {first_deep} 0 R /Last {first_deep} 0 R") } else { String::new() }
),
];
for i in 0..deep {
let (me, parent) = (first_deep + i, if i == 0 { 6 } else { first_deep + i - 1 });
let child = if i + 1 < deep { format!(" /First {0} 0 R /Last {0} 0 R", me + 1) } else { String::new() };
objs.push(format!("<< /Title (Level) /Parent {parent} 0 R /Dest [3 0 R /Fit]{child} >>"));
}
pdf_of(&objs.iter().map(String::as_str).collect::<Vec<_>>())
}
/// What a real file holds and the JSON form can't say exactly still copies and round-trips: an
/// empty title stays empty, a short /FitR keeps its page and drops the view, and bookmarks past
/// the listing depth are reported as left out at every step.
#[test]
fn odd_bookmarks_round_trip_and_a_cut_tree_says_so() {
let dir = workdir("bookmark-io-odd");
std::fs::write(dir.join("odd.pdf"), odd_outline(0)).unwrap();
std::fs::write(dir.join("deep.pdf"), odd_outline(40)).unwrap();
let mut a = auto(&dir);
let src = ok(&mut a, "doc_open", json!({ "path": "odd.pdf" }))["doc"].as_u64().unwrap();
let tree = ok(&mut a, "bookmark_export", json!({ "doc": src, "out": "odd.json" }))["bookmarks"].clone();
assert_eq!((tree[0]["title"].clone(), tree[1]["page"].clone(), tree[1].get("view")), (json!(""), json!(1), None));
let dst = ok(&mut a, "doc_open", json!({ "path": "b.pdf" }))["doc"].as_u64().unwrap();
assert_eq!(ok(&mut a, "bookmark_import", json!({ "doc": dst, "file": "odd.json", "replace": true }))["truncated"], false);
// A destination with no view is written as XYZ with nulls: the same page, the reader's view.
let back = ok(&mut a, "bookmark_export", json!({ "doc": dst }))["bookmarks"].clone();
assert_eq!((back[0].clone(), back[1]["title"].clone(), back[1]["page"].clone()), (tree[0].clone(), json!("Short"), json!(1)));
assert_eq!(back[1]["view"], json!({ "type": "XYZ", "values": [null, null, null] }));
let copied = ok(&mut a, "bookmark_copy", json!({ "doc": dst, "from": src, "replace": true }));
assert_eq!((copied["unmapped"].clone(), copied["truncated"].clone()), (json!([]), json!(false)));
match a.call("bookmark_export", &json!({ "doc": src, "path": [3] })) {
Err(ToolError::Failed(m)) => assert!(m.contains("no bookmark at [3]"), "{m}"),
other => panic!("expected no bookmark, got {other:?}"),
}
let deep = ok(&mut a, "doc_open", json!({ "path": "deep.pdf" }))["doc"].as_u64().unwrap();
assert_eq!(ok(&mut a, "bookmark_export", json!({ "doc": deep, "out": "deep.json" }))["truncated"], true);
let saved: Value = serde_json::from_slice(&std::fs::read(dir.join("deep.json")).unwrap()).unwrap();
assert_eq!(saved["truncated"], true);
assert_eq!(ok(&mut a, "bookmark_import", json!({ "doc": dst, "file": "deep.json", "replace": true }))["truncated"], true);
assert_eq!(ok(&mut a, "bookmark_copy", json!({ "doc": dst, "from": deep, "replace": true }))["truncated"], true);
let export = tools().into_iter().find(|t| t.name == "bookmark_export").unwrap();
assert!(export.destructive && !export.read_only, "bookmark_export overwrites out");
std::fs::remove_dir_all(dir).unwrap();
}
#[test]
fn a_misspelt_bookmark_key_is_refused_not_dropped() {
let dir = workdir("bookmark-io-key");
let mut a = auto(&dir);
let doc = ok(&mut a, "doc_open", json!({ "path": "a.pdf" }))["doc"].as_u64().unwrap();
let tree = json!([{ "title": "Parent", "children": [{ "title": "Red", "page": 1, "colour": [1, 0, 0] }] }]);
match a.call("bookmark_import", &json!({ "doc": doc, "bookmarks": tree })) {
Err(ToolError::InvalidArgs(m)) => assert!(m.contains("[1, 1]") && m.contains("\"colour\""), "{m}"),
other => panic!("expected InvalidArgs, got {other:?}"),
}
assert_eq!(ok(&mut a, "bookmark_list", json!({ "doc": doc }))["bookmarks"], json!([]));
std::fs::remove_dir_all(dir).unwrap();
}
#[test]
fn a_bad_bookmark_tree_is_refused_whole_and_names_the_node() {
let dir = workdir("bookmark-io-bad");
let mut a = auto(&dir);
let doc = ok(&mut a, "doc_open", json!({ "path": "a.pdf" }))["doc"].as_u64().unwrap();
let refused = |a: &mut Automation, bookmarks: Value| match a.call("bookmark_import", &json!({ "doc": doc, "bookmarks": bookmarks })) {
Err(ToolError::InvalidArgs(m)) => m,
other => panic!("expected InvalidArgs, got {other:?}"),
};
let fine = json!({ "title": "Fine", "page": 1 });
let m = refused(&mut a, json!([fine, { "title": "Parent", "children": [{ "page": 1 }] }]));
assert!(m.contains("[2, 1]") && m.contains("title"), "{m}");
let m = refused(&mut a, json!([{ "title": 5 }]));
assert!(m.contains("[1]") && m.contains("title"), "{m}");
let m = refused(&mut a, json!([fine, { "title": "Bad", "page": 0 }]));
assert!(m.contains("[2]") && m.contains("page"), "{m}");
let m = refused(&mut a, json!([{ "title": "Bad", "color": [2, 0, 0] }]));
assert!(m.contains("color"), "{m}");
let m = refused(&mut a, json!([{ "title": "Bad", "view": { "type": "XYZ", "values": [1, 2, 3, 4, 5] } }]));
assert!(m.contains("view"), "{m}");
let mut deep = json!({ "title": "Leaf" });
for _ in 0..40 {
deep = json!({ "title": "Level", "children": [deep] });
}
assert!(refused(&mut a, json!([deep])).contains("33 levels"));
let m = refused(&mut a, json!([fine, { "title": "Z", "page": 1, "view": { "type": "Zoom" } }]));
assert!(m.contains("[2]") && m.contains("XYZ (3 values"), "{m}");
let m = refused(&mut a, json!([fine, { "title": "Z", "page": 1, "view": { "type": "FitH", "values": [1, 2] } }]));
assert!(m.contains("[2]") && m.contains("FitH view takes 1"), "{m}");
let m = refused(&mut a, json!([{ "title": "R", "view": { "type": "FitR", "values": [0, null, 1, 1] } }]));
assert!(m.contains("all four"), "{m}");
assert!(matches!(a.call("bookmark_import", &json!({ "doc": doc })), Err(ToolError::InvalidArgs(_))));
assert!(matches!(a.call("bookmark_import", &json!({ "doc": doc, "bookmarks": [fine], "file": "x.json" })), Err(ToolError::InvalidArgs(_))));
// A real bookmark file outside the root is refused for being outside, not for being missing.
let outside = dir.with_extension("outside.json");
std::fs::write(&outside, br#"{"bookmarks": [{"title": "Outside", "page": 1}]}"#).unwrap();
let name = format!("../{}", outside.file_name().unwrap().to_string_lossy());
match a.call("bookmark_import", &json!({ "doc": doc, "file": name })) {
Err(ToolError::Failed(m)) => assert!(m.contains("outside the allowed directory"), "{m}"),
other => panic!("expected the root to refuse it, got {other:?}"),
}
let _ = std::fs::remove_file(&outside);
let out = dir.with_extension("out.json");
let name = format!("../{}", out.file_name().unwrap().to_string_lossy());
match a.call("bookmark_export", &json!({ "doc": doc, "out": name })) {
Err(ToolError::Failed(m)) => assert!(m.contains("outside the allowed directory"), "{m}"),
other => panic!("expected the root to refuse it, got {other:?}"),
}
assert!(!out.exists());
assert_eq!(ok(&mut a, "bookmark_list", json!({ "doc": doc }))["bookmarks"], json!([]));
}
@@ -145,6 +145,8 @@ fn tools_that_read_a_path_are_held_to_the_read_root() {
ok(&mut server, "doc_open", json!({"path": s(&base.join("in/a.pdf"))}));
let (secret, pic, gone) = (s(&base.join("outside/secret.pdf")), s(&base.join("outside/pic.png")), s(&base.join("outside/gone.bin")));
let out = s(&base.join("out/result.pdf"));
std::fs::write(base.join("in/m.prc"), b"PRC model").unwrap();
let model = s(&base.join("in/m.prc"));
for (tool, args) in [
("page_insert_file", json!({"doc": 1, "path": secret, "at": 1})),
("page_replace", json!({"doc": 1, "pages": [1], "path": secret})),
@@ -153,6 +155,8 @@ fn tools_that_read_a_path_are_held_to_the_read_root() {
("doc_create", json!({"from": "images", "paths": [pic]})),
("stamp_custom", json!({"doc": 1, "page": 1, "path": secret, "at": [10, 10]})),
("stamp_custom", json!({"doc": 1, "page": 1, "path": secret, "rect": [10, 10, 493, 300]})),
("model_add", json!({"doc": 1, "page": 1, "path": secret, "rect": [10, 10, 100, 100]})),
("model_add", json!({"doc": 1, "page": 1, "path": model, "rect": [10, 10, 100, 100], "poster": pic})),
("page_add_image", json!({"doc": 1, "page": 1, "path": pic})),
("image_edit", json!({"doc": 1, "page": 1, "image": 1, "action": "replace", "path": pic})),
("comment_add", json!({"doc": 1, "page": 1, "type": "attachment", "at": [10, 10], "path": secret})),
+2
View File
@@ -8,6 +8,8 @@ mod batch;
mod button_caption;
mod form_bulk;
mod hostile_args;
mod model_3d;
mod model_render;
mod optimize_content_boundaries;
mod redact_after_stray_q_form;
mod redact_text_after_q;
+120
View File
@@ -0,0 +1,120 @@
//! `model_add` embeds a U3D or PRC model as a 3D annotation (ISO 32000-2 §13.6.2) with a poster,
//! end to end: the tool, the saved file, undo, and the refusals.
use pdfcraft_automation::{Automation, Content, ToolError};
use pdfcraft_cos::{Dict, Document, Object, Stream};
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:?}"),
}
}
fn png(w: u32, h: u32) -> Vec<u8> {
let mut out = Vec::new();
let mut encoder = png::Encoder::new(&mut out, w, h);
encoder.set_color(png::ColorType::Rgb);
encoder.set_depth(png::BitDepth::Eight);
encoder.write_header().unwrap().write_image_data(&vec![90; (w * h * 3) as usize]).unwrap();
out
}
fn stream(doc: &Document, obj: &Object) -> Stream {
match doc.resolve(obj).as_ref() {
Object::Stream(s) => s.clone(),
other => panic!("expected a stream: {other:?}"),
}
}
/// The 3D annotations on the first page of the saved file.
fn saved_3d(dir: &std::path::Path) -> (Document, Vec<Dict>) {
let doc = Document::open(std::sync::Arc::new(std::fs::read(dir.join("out.pdf")).unwrap())).unwrap();
let page = &pdfcraft_model::pages(&doc)[0];
let list = page.dict.get(b"Annots").map(|a| doc.resolve(a).as_array().cloned().unwrap()).unwrap_or_default();
let found = list.iter().map(|o| doc.resolve(o).as_dict().unwrap().clone()).filter(|d| d.name(b"Subtype") == Some(&b"3D"[..])).collect();
(doc, found)
}
#[test]
fn model_add_embeds_the_model_with_a_fitted_poster() {
let dir = tempfile::tempdir().unwrap();
let mut prc = b"PRC".to_vec();
prc.extend_from_slice(&[7; 200]);
std::fs::write(dir.path().join("bracket.prc"), &prc).unwrap();
std::fs::write(dir.path().join("poster.png"), png(80, 40)).unwrap();
let mut a = Automation::new().with_root(dir.path()).unwrap();
let doc = tool(&mut a, "doc_create", json!({ "from": "blank", "width": 600, "height": 800 }))["doc"].as_u64().unwrap();
// A 300 × 300 box from the top-left of the page: user space [100, 400, 400, 700].
let call =
json!({ "doc": doc, "page": 1, "path": "bracket.prc", "rect": [100, 100, 400, 400], "poster": "poster.png", "activation": "page_open" });
tool(&mut a, "model_add", call);
tool(&mut a, "doc_save", json!({ "doc": doc, "path": "out.pdf" }));
let (saved, found) = saved_3d(dir.path());
let [annot] = found.as_slice() else { panic!("one 3D annotation: {found:?}") };
let rect: Vec<f64> = annot.get(b"Rect").unwrap().as_array().unwrap().iter().filter_map(Object::as_f64).collect();
assert_eq!(rect, [100.0, 400.0, 400.0, 700.0]);
assert_eq!(annot.get(b"Contents").and_then(Object::as_string).map(|s| s.to_text()).as_deref(), Some("bracket"));
let model = stream(&saved, annot.get(b"3DD").unwrap());
assert_eq!(model.dict.name(b"Type"), Some(&b"3D"[..]));
assert_eq!(model.dict.name(b"Subtype"), Some(&b"PRC"[..]));
assert_eq!(model.dict.name(b"Filter"), Some(&b"FlateDecode"[..]));
assert_eq!(model.decoded().unwrap().to_vec(), prc, "the model is stored unchanged");
let activation = saved.resolve(annot.get(b"3DA").unwrap()).as_dict().unwrap().clone();
assert_eq!(activation.name(b"A"), Some(&b"PO"[..]));
// The 80 × 40 picture fitted in the 300 × 300 box: 300 × 150, centred top to bottom.
let ap = saved.resolve(annot.get(b"AP").unwrap()).as_dict().unwrap().clone();
let poster = stream(&saved, ap.get(b"N").unwrap());
let content = String::from_utf8(poster.decoded().unwrap().to_vec()).unwrap();
assert!(content.contains("300 0 0 150 100 475 cm /Pic Do"), "{content}");
assert_eq!(tool(&mut a, "edit_undo", json!({ "doc": doc }))["undone"], "Add 3D model");
tool(&mut a, "doc_save", json!({ "doc": doc, "path": "out.pdf" }));
assert!(saved_3d(dir.path()).1.is_empty(), "undo removes it");
}
#[test]
fn model_add_without_a_poster_draws_a_labelled_frame_and_activates_on_click() {
let dir = tempfile::tempdir().unwrap();
let mut u3d = b"U3D\0".to_vec();
u3d.extend_from_slice(&[0; 60]);
std::fs::write(dir.path().join("part.u3d"), &u3d).unwrap();
let mut a = Automation::new().with_root(dir.path()).unwrap();
let doc = tool(&mut a, "doc_create", json!({ "from": "blank", "width": 600, "height": 800 }))["doc"].as_u64().unwrap();
tool(&mut a, "model_add", json!({ "doc": doc, "page": 1, "path": "part.u3d", "rect": [50, 50, 250, 200], "name": "Part" }));
tool(&mut a, "doc_save", json!({ "doc": doc, "path": "out.pdf" }));
let (saved, found) = saved_3d(dir.path());
let [annot] = found.as_slice() else { panic!("one 3D annotation: {found:?}") };
assert_eq!(stream(&saved, annot.get(b"3DD").unwrap()).dict.name(b"Subtype"), Some(&b"U3D"[..]));
let activation = saved.resolve(annot.get(b"3DA").unwrap()).as_dict().unwrap().clone();
assert_eq!(activation.name(b"A"), Some(&b"XA"[..]), "the standard's default, stated");
let ap = saved.resolve(annot.get(b"AP").unwrap()).as_dict().unwrap().clone();
let content = String::from_utf8(stream(&saved, ap.get(b"N").unwrap()).decoded().unwrap().to_vec()).unwrap();
assert!(content.contains("re S") && content.contains("(3D model) Tj"), "{content}");
}
#[test]
fn model_add_refuses_what_is_not_a_model_and_adds_nothing() {
let dir = tempfile::tempdir().unwrap();
std::fs::write(dir.path().join("notes.txt"), b"PR not a model").unwrap();
std::fs::write(dir.path().join("part.prc"), b"PRC....").unwrap();
let mut a = Automation::new().with_root(dir.path()).unwrap();
let doc = tool(&mut a, "doc_create", json!({ "from": "blank", "width": 600, "height": 800 }))["doc"].as_u64().unwrap();
let not_a_model = a.call("model_add", &json!({ "doc": doc, "page": 1, "path": "notes.txt", "rect": [10, 10, 100, 100] }));
assert!(matches!(&not_a_model, Err(ToolError::Failed(m)) if m.contains("U3D") && m.contains("PRC")), "{not_a_model:?}");
for (args, why) in [
(json!({ "rect": [10, 10, 10, 100] }), "zero width"),
(json!({ "rect": [0, 0, 20000, 100] }), "wider than a PDF page can be"),
(json!({}), "no rect"),
(json!({ "rect": [10, 10, 100, 100], "activation": "now" }), "an unknown activation"),
] {
let mut call = json!({ "doc": doc, "page": 1, "path": "part.prc" });
call.as_object_mut().unwrap().extend(args.as_object().unwrap().clone());
assert!(matches!(a.call("model_add", &call), Err(ToolError::InvalidArgs(_))), "{why}");
}
tool(&mut a, "doc_save", json!({ "doc": doc, "path": "out.pdf" }));
assert!(saved_3d(dir.path()).1.is_empty());
}
+112
View File
@@ -0,0 +1,112 @@
//! `model_render` draws a page's 3D model headlessly: a synthetic PDF holding a synthetic PRC.
use std::path::PathBuf;
use pdfcraft_automation::{Automation, Content};
use serde_json::{Value, json};
/// One triangle at z = 0 facing +z, with corners (-1,-1), (1,-1) and (0,1), as a PRC file of one
/// file structure with no product tree, in hexadecimal for the stream's `/ASCIIHexDecode`.
const TRIANGLE_PRC_HEX: &str = "505243c91f0000c91f00000100000002000000030000000400000000000000000000000000000000000000010000000500000006000000070000000800000000000000060000006b0000009a000000a3000000ab000000cd000000d5000000dd000000e500000000000000505243c91f0000c91f0000050000000600000007000000080000000000000000000000000000000000000000000000789c63000000010001789c030000000001789c9b71c087758da2422b43084fe3140e038713464cd759381a162800006ed70828789c030000000001789c030000000001789c030000000001";
/// A one-page PDF whose page holds a 3D annotation over a stream of `/Subtype /{subtype}`.
fn pdf(subtype: &str, hex: &str) -> Vec<u8> {
let stream = format!("<< /Type /3D /Subtype /{subtype} /Filter /ASCIIHexDecode /Length {} >>\nstream\n{hex}>\nendstream", hex.len() + 1);
let objs: Vec<String> = vec![
"<< /Type /Catalog /Pages 2 0 R >>".into(),
"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 200 200] >>".into(),
"<< /Type /Page /Parent 2 0 R /Annots [<< /Type /Annot /Subtype /Square /Rect [0 0 10 10] >> 4 0 R] >>".into(),
"<< /Type /Annot /Subtype /3D /Rect [20 20 180 180] /3DD 5 0 R >>".into(),
stream,
];
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
}
/// A fresh folder with `prc.pdf` and `u3d.pdf` in `in`, `outside.pdf` beside it, and an
/// automation rooted at `in`.
fn setup(test: &str) -> (PathBuf, Automation) {
let dir = std::env::temp_dir().join(format!("pdfcraft-model3d-{test}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(dir.join("in")).unwrap();
std::fs::write(dir.join("in/prc.pdf"), pdf("PRC", TRIANGLE_PRC_HEX)).unwrap();
std::fs::write(dir.join("in/u3d.pdf"), pdf("U3D", "553344")).unwrap();
std::fs::write(dir.join("outside.pdf"), pdf("PRC", TRIANGLE_PRC_HEX)).unwrap();
let a = Automation::new().with_root(dir.join("in")).unwrap();
(dir, a)
}
fn open(a: &mut Automation, path: &str) -> u64 {
match a.call("doc_open", &json!({ "path": path })).unwrap().remove(0) {
Content::Json(v) => v["doc"].as_u64().unwrap(),
other => panic!("expected JSON: {other:?}"),
}
}
/// The RGB of pixel (x, y) of a PNG.
fn rgb(data: &[u8], x: usize, y: usize) -> [u8; 3] {
let mut reader = png::Decoder::new(std::io::Cursor::new(data)).read_info().unwrap();
let mut pixels = vec![0; reader.output_buffer_size().unwrap()];
let info = reader.next_frame(&mut pixels).unwrap();
let channels = info.line_size / info.width as usize;
let at = y * info.line_size + x * channels;
[pixels[at], pixels[at + 1], pixels[at + 2]]
}
#[test]
fn a_prc_model_is_drawn_over_the_background() {
let (_dir, mut a) = setup("prc");
let doc = open(&mut a, "prc.pdf");
let args = json!({ "doc": doc, "page": 1, "width": 64, "height": 48, "direction": [0, 0, -1], "perspective": false });
let out = a.call("model_render", &args).unwrap();
let Content::Png { data, width, height } = &out[0] else { panic!("expected a PNG") };
assert_eq!((*width, *height), (64, 48));
assert_eq!(rgb(data, 0, 0), [255, 255, 255], "the corner is background");
assert_eq!(rgb(data, 32, 24), [190, 192, 200], "the centre is the triangle, lit head on");
// In perspective the headlight meets the face at a slight angle, so only not-background holds.
let out = a.call("model_render", &json!({ "doc": doc, "page": 1, "width": 64, "height": 48, "direction": [0, 0, -1] })).unwrap();
let Content::Png { data, .. } = &out[0] else { panic!("expected a PNG") };
assert_ne!(rgb(data, 32, 24), [255, 255, 255], "the centre is drawn in perspective too");
// The same model named explicitly, and the default isometric view, both draw.
assert!(a.call("model_render", &json!({ "doc": doc, "page": 1, "model": 1 })).is_ok());
}
#[test]
fn a_u3d_model_or_a_missing_one_is_a_clear_error() {
let (_dir, mut a) = setup("u3d");
let doc = open(&mut a, "u3d.pdf");
let err = a.call("model_render", &json!({ "doc": doc, "page": 1 })).unwrap_err().to_string();
assert!(err.contains("U3D"), "{err}");
let doc = open(&mut a, "prc.pdf");
let err = a.call("model_render", &json!({ "doc": doc, "page": 1, "model": 2 })).unwrap_err().to_string();
assert!(err.contains("has 1 3D models, not 2"), "{err}");
for bad in [json!({ "direction": [0, 0, 0] }), json!({ "direction": [1, 2] }), json!({ "width": 0 }), json!({ "height": 5000 })] {
let mut args = json!({ "doc": doc, "page": 1 });
args.as_object_mut().unwrap().extend(bad.as_object().unwrap().clone());
assert!(a.call("model_render", &args).is_err(), "{bad}");
}
}
#[test]
fn a_model_outside_the_root_is_never_opened_to_be_drawn() {
let (dir, mut a) = setup("root");
let outside = dir.join("outside.pdf");
for path in [Value::from("../outside.pdf"), Value::from(outside.to_string_lossy().into_owned())] {
assert!(a.call("doc_open", &json!({ "path": path })).is_err(), "{path} lies outside the root");
}
// The tool takes no path of its own: only a document opened inside the root reaches it.
assert!(a.call("model_render", &json!({ "doc": 1, "page": 1 })).is_err());
let doc = open(&mut a, "prc.pdf");
assert!(a.call("model_render", &json!({ "doc": doc, "page": 1 })).is_ok());
}
+5 -2
View File
@@ -730,11 +730,14 @@ impl Matrix {
pub fn invert(&self) -> Option<Matrix> {
let [a, b, c, d, e, f] = self.0;
let det = a * d - b * c;
if det.abs() < 1e-12 || !det.is_finite() {
if det == 0.0 || !det.is_finite() || det.abs() <= 1e-12 * ((a * d).abs() + (b * c).abs()) {
return None;
}
let (ia, ib, ic, id) = (d / det, -b / det, -c / det, a / det);
Some(Matrix([ia, ib, ic, id, -(e * ia + f * ic), -(e * ib + f * id)]))
let inverse = [ia, ib, ic, id, -(e * ia + f * ic), -(e * ib + f * id)];
// A determinant that underflows toward zero can still pass the relative check above,
// and dividing by it overflows: such a matrix has no usable inverse.
inverse.iter().all(|v| v.is_finite()).then_some(Matrix(inverse))
}
/// The bounding box of a rectangle `[x0 y0 x1 y1]` after this transform.
+14
View File
@@ -552,3 +552,17 @@ fn inline_images_end_where_the_renderer_ends_them() {
assert_eq!((parsed.skipped, parsed.ambiguous_images), (0, 0), "{}", String::from_utf8_lossy(data));
}
}
#[test]
fn invert_accepts_small_scale_and_rejects_singular() {
let m = Matrix([1e-7, 0., 0., 1e-7, 0., 0.]);
let inv = m.invert().expect("a uniform 1e-7 scale is invertible");
let id = m.then(&inv).0;
for (got, want) in id.iter().zip(Matrix::IDENTITY.0) {
assert!((got - want).abs() < 1e-9, "{id:?}");
}
assert!(Matrix([1., 2., 2., 4., 0., 0.]).invert().is_none());
assert!(Matrix([f64::NAN, 0., 0., 1., 0., 0.]).invert().is_none());
// A subnormal scale passes the relative check but its inverse overflows (CodeRabbit on #5703).
assert!(Matrix([1e-310, 0., 0., 1., 0., 0.]).invert().is_none());
}
+8 -3
View File
@@ -90,6 +90,11 @@ recognisable in a diff and byte-stable when re-serialized.
- Linearized output, Fast Web View (`core.linearization`, M11).
- Structural validation against the Arlington model (`core.arlington-validation`), which will live
in the reserved `arlington` crate.
- Image codecs. `pdfcraft-filters` carries the non-image filters and CCITT fax decoding
(`Document::decoded_image`); DCT, JPX and JBIG2 are still decoded through the bootstrap renderer
(`core.image-filters`, M2.6).
- Image codecs. `pdfcraft-filters` carries the non-image filters and CCITT fax and JBIG2 decoding
(`Document::decoded_image`, a JBIG2 image's `/JBIG2Globals` within `MAX_JBIG2_GLOBALS`, 32 MiB,
their filters undone once a document for the images that share them, up to 64 MiB kept, while
their segments are decoded for every image, and `ImageBudget` for an operation over many images,
which share one allowance of decoding, filters, decoders and pixels alike, and are refused past
it: `IMAGE_WORK`, 2^34 steps, or 2 to 5 minutes of JBIG2 and about 1,000 pages scanned at
300 dpi, plus `IMAGE_WORK_PER_BYTE`, 2^13 steps for each byte of the file);
DCT and JPX are still decoded through the bootstrap renderer (`core.image-filters`, M2.6).
+618
View File
@@ -6,16 +6,224 @@ use pdfcraft_filters::FilterError;
use crate::{CosError, Document, ObjRef, Object, Stream};
/// The steps of decoding an operation over a document's images may take whatever the file's size.
/// A step of JBIG2 decoding ([`hayro_jbig2::Image::decode_within`]) is about a pixel, and takes 6 to
/// 16 ns, so this is 2 to 5 minutes, and about as long again for what an operation does with the
/// pixels. A page scanned at 300 dpi takes about 17 million, 8.4 for its pixels and that again to
/// decode them, so this alone reads about 1,000 of them. A byte into or out of a filter is a step
/// too, and takes less: 3 ns at most, or up to 19 ns through a predictor on samples of a bit.
const IMAGE_WORK: u64 = 1 << 34;
/// The steps each byte of the file adds to [`IMAGE_WORK`], so that a long scan is read whole: such a
/// page pays for itself with about 2 KB of the file, about the smallest a page of text is stored
/// in, and a stream of any filter this reads can be decoded about 8 times at Flate's best, 1,032 to
/// one. So what a hostile file can ask for grows with its length, by about 14 minutes for 10 MB.
const IMAGE_WORK_PER_BYTE: u64 = 1 << 13;
/// Decoded bytes one page's content walk may produce in all: its `/Contents` streams and every
/// form XObject it enters, each occurrence counted again.
pub const MAX_PAGE_DECODED: usize = 256 << 20;
/// Form XObjects one page's content walk may enter, each entry counted again.
pub const MAX_PAGE_FORMS: usize = 50_000;
/// The most pixels an image redaction decodes, to clear the ones under a mark or to store again
/// without the `/JBIG2Globals` it shares with a redacted image (`pdfcraft_redact`). Optimize has
/// JBIG2 images share a dictionary only within it (`pdfcraft_optimize`), so that redaction can
/// store each of them again: one it couldn't would refuse the redaction.
pub const MAX_REDACTED_IMAGE_PIXELS: u64 = 64 << 20;
/// The steps a sample of a JPEG costs: a few bytes can hold a page of one grey, and decoding,
/// resampling and storing it took about 20 to 45 ns a sample.
const JPEG_WORK: u64 = 2;
/// The steps a byte of a JPEG costs to read: its tables took 24 ns a byte before a size was known,
/// and images can share one, so reading it again for each has to count.
const JPEG_READ_WORK: u64 = 4;
/// A stream decode within a byte bound, with the bytes its filter stages decoded: the data or
/// the error, each with that count.
type Decoder = fn(&Stream, usize) -> Result<(Vec<u8>, usize), (FilterError, usize)>;
/// What one operation over a document's images may still spend decoding them: exporting them,
/// optimizing them, and storing LZW streams with Flate as it does, clearing them for redaction.
///
/// An image has its own limit, which doesn't bound a file of thousands of images made to reach it:
/// a few hundred bytes of JBIG2 can ask for seconds of decoding, 4 KB of Flate inside Flate for a
/// gigabyte, and an image that shares `/JBIG2Globals` decodes them again. So images share this
/// allowance, whatever they do with what they decode and whether or not it works, and past it they
/// aren't decoded. A caller then treats them as it does an image it can't read, and
/// [`ImageBudget::refused`] says how many there were.
///
/// An image also pays for its pixels once decoded, as what reads it goes through them one by one
/// however few bytes coded them: blank rows of fax or Flate take almost none. It pays for no more
/// than its data holds, a bit a pixel at least, so an image declaring a size its data doesn't fill
/// costs what a smaller one would, not the run's allowance. A JPEG pays for its samples when
/// it is decoded ([`ImageBudget::pay_jpeg`]), and is otherwise not charged, as JPEG 2000 isn't:
/// their decoders don't run here.
#[derive(Debug)]
pub struct ImageBudget {
work: u64,
refused: usize,
}
impl ImageBudget {
/// The allowance for an operation on `doc`, which a longer file makes larger. The streams made
/// or changed since it was opened count as the file's bytes do, so a document built in memory
/// (combined, created, or given pages of scans) gets what it would once saved and opened again.
pub fn new(doc: &Document) -> Self {
let length = |n: usize| u64::try_from(n).unwrap_or(u64::MAX);
let edited = doc
.scan_objects_subset(doc.modified_objects())
.filter_map(|(_, object)| match &*object.ok()? {
Object::Stream(s) => Some(length(s.raw.len())),
_ => None,
})
.fold(0u64, u64::saturating_add);
let bytes = length(doc.bytes().len()).saturating_add(edited);
Self::with_work(IMAGE_WORK.saturating_add(bytes.saturating_mul(IMAGE_WORK_PER_BYTE)))
}
/// An allowance of `work` steps of decoding.
pub fn with_work(work: u64) -> Self {
Self { work, refused: 0 }
}
/// The samples of image `s`, decoded and charged to the allowance: the one way to decode an
/// image outside the renderer, so that an operation over many images can't decode them without
/// one.
///
/// They go through its filters ([`Stream::decoded`]), or, for a CCITT fax or JBIG2 image (its
/// last filter), through the filters before it and then [`pdfcraft_filters::decode_ccitt_within`]
/// with its [`Document::fax_params`], or [`pdfcraft_filters::decode_jbig2_within`] with its
/// `/JBIG2Globals`, as `CCITTFaxDecode` and `JBIG2Decode` give them (ISO 32000-2 §7.4.6,
/// §7.4.7). Parameters given by reference count, for every filter
/// ([`Document::with_direct_parms`]). A fax image's `/Columns` has to be its `/Width`, and a
/// JBIG2 image's page its `/Width` × `/Height`: PdfCraft's renderer draws the whole page into
/// the image. Up to its `/Height` rows are decoded, whatever a fax image's `/Rows` says; damaged
/// fax data gives fewer, so a caller checks it has the rows it needs. Damaged JBIG2 data, and
/// globals that can't be read (within [`MAX_JBIG2_GLOBALS`](crate::MAX_JBIG2_GLOBALS)), are an
/// error.
///
/// No stage, the filters before a fax or JBIG2 decoder included, may produce more than `max`
/// bytes, nor more than [`MAX_DECODED`](crate::MAX_DECODED). A JBIG2 image's `/JBIG2Globals`
/// are another stream, shared between images, and are decoded within `MAX_JBIG2_GLOBALS`
/// whatever `max` is. Each filter as it runs, the globals when they have to be read, and the fax
/// or JBIG2 decoder spend from the allowance, and the image then pays for its pixels; with
/// nothing left an image is refused before anything is read, its globals included.
///
/// ```
/// # let doc = pdfcraft_cos::Document::new_empty();
/// # let s = pdfcraft_cos::Stream::from_raw(pdfcraft_cos::Dict::new(), Vec::new());
/// let samples = pdfcraft_cos::ImageBudget::new(&doc).decode(&doc, &s, 1 << 20);
/// assert_eq!(samples.unwrap(), b"");
/// ```
///
/// `Document` has no way of its own to decode an image:
///
/// ```compile_fail
/// # let doc = pdfcraft_cos::Document::new_empty();
/// # let s = pdfcraft_cos::Stream::from_raw(pdfcraft_cos::Dict::new(), Vec::new());
/// let _ = doc.decoded_image(&s);
/// ```
///
/// ```compile_fail
/// # let doc = pdfcraft_cos::Document::new_empty();
/// # let s = pdfcraft_cos::Stream::from_raw(pdfcraft_cos::Dict::new(), Vec::new());
/// let _ = doc.decoded_image_within(&s, 1 << 20);
/// ```
pub fn decode(&mut self, doc: &Document, s: &Stream, max: usize) -> Result<Vec<u8>, CosError> {
let decoded = doc.decoded_image_spending(s, max, &mut self.work);
self.count_refused(s, &decoded);
self.pay_size(s, decoded?)
}
/// Image `s` through its filters alone, charged to the allowance: [`Stream::decoded_within`]
/// with its `/DecodeParms` given by reference read too ([`Document::with_direct_parms`]), for an
/// image that has no fax or JBIG2 decoder to go through.
pub fn decode_filters(&mut self, doc: &Document, s: &Stream, max: usize) -> Result<Vec<u8>, CosError> {
let decoded = doc.with_direct_parms(s).decoded_spending(max, &mut self.work);
self.count_refused(s, &decoded);
let decoded = decoded?;
if s.filters().iter().all(|(f, _)| f.is_decodable()) { self.pay_size(s, decoded) } else { Ok(decoded) }
}
/// `data` through `chain`, any corruption being an error ([`pdfcraft_filters::decode_within`]),
/// for a stream a run rewrites rather than an image it reads, charged to the allowance.
pub fn decode_chain(
&mut self,
chain: &[(pdfcraft_filters::Filter, pdfcraft_filters::Params)],
data: &[u8],
max: usize,
) -> Result<Vec<u8>, FilterError> {
pdfcraft_filters::decode_within(chain, data, max, &mut self.work)
}
/// Pays `steps` of other work on decoded data, or spends all there is and says so.
pub fn spend(&mut self, steps: u64) -> bool {
let left = self.work.checked_sub(steps);
self.work = left.unwrap_or(0);
left.is_some()
}
/// Pays for `pixels` a decode goes on to work through, or spends all there is, and the image
/// is refused.
pub fn pay_pixels(&mut self, pixels: u64) -> bool {
let paid = self.spend(pixels);
self.refused += usize::from(!paid);
paid
}
/// Pays for reading JPEG `data` and decoding its `samples`, as [`ImageBudget::pay_pixels`] does.
/// A caller pays before its tables are parsed, which can be most of the file.
pub fn pay_jpeg(&mut self, samples: u64, data: &[u8]) -> bool {
let reading = (data.len() as u64).saturating_mul(JPEG_READ_WORK);
self.pay_pixels(samples.saturating_mul(JPEG_WORK).saturating_add(reading))
}
/// Pays for the pixels of image `s` that its `decoded` data holds, those of its `/Width` and
/// `/Height` but no more than a bit of the data each, unless it is JBIG2, whose decoder pays for
/// its page, or isn't decoded here. What can't be paid for refuses the image.
fn pay_size(&mut self, s: &Stream, decoded: Vec<u8>) -> Result<Vec<u8>, CosError> {
if !charged(s) || matches!(s.filters().last(), Some((pdfcraft_filters::Filter::Jbig2, _))) {
return Ok(decoded);
}
let side = |key: &[u8]| s.dict.int(key).and_then(|v| u64::try_from(v).ok()).unwrap_or(0);
let held = u64::try_from(decoded.len()).unwrap_or(u64::MAX).saturating_mul(8);
if self.pay_pixels(side(b"Width").saturating_mul(side(b"Height")).min(held)) {
Ok(decoded)
} else {
Err(CosError::Filter(FilterError::Spent.to_string()))
}
}
/// An image that failed with nothing left was refused, unless it has a filter that costs
/// nothing here, which fails whatever is left.
fn count_refused(&mut self, s: &Stream, decoded: &Result<Vec<u8>, CosError>) {
if decoded.is_err() && self.work == 0 && charged(s) {
self.refused += 1;
}
}
/// The decodes refused for lack of allowance: an image read twice over is counted twice.
pub fn refused(&self) -> usize {
self.refused
}
/// The steps of decoding still allowed.
pub fn work_left(&self) -> u64 {
self.work
}
}
/// Whether `s` can be decoded here and so charged: general filters, a fax or JBIG2 decoder last at
/// most. Those decoders anywhere else can't run.
fn charged(s: &Stream) -> bool {
use pdfcraft_filters::Filter;
s.readable_filters().is_ok_and(|chain| {
chain.split_last().is_none_or(|((last, _), before)| {
(last.is_decodable() || matches!(last, Filter::Jbig2 | Filter::CcittFax)) && before.iter().all(|(f, _)| f.is_decodable())
})
})
}
/// What one operation may still decode and enter across all the streams it reads.
///
/// [`MAX_DECODED`](crate::MAX_DECODED) bounds one decode. It does not bound a page whose
@@ -143,6 +351,401 @@ impl DecodeBudget {
}
}
#[cfg(test)]
mod image_tests {
use super::*;
use crate::Dict;
fn jbig2(parms: Option<Object>) -> Stream {
let mut dict = Dict::new();
dict.set(b"Width".to_vec(), Object::Int(16));
dict.set(b"Height".to_vec(), Object::Int(2));
dict.set(b"Filter".to_vec(), Object::name("JBIG2Decode"));
if let Some(parms) = parms {
dict.set(b"DecodeParms".to_vec(), parms);
}
Stream::from_raw(dict, pdfcraft_filters::encode_jbig2_generic(&[0xFF; 4], 16, 2).unwrap())
}
/// Each image spends what it took from one allowance, and those past it are refused and
/// counted, whatever their filters. What can't be decoded here costs nothing, and fails
/// without being one of these.
#[test]
fn the_images_of_an_operation_share_its_allowance() {
let doc = Document::new_empty();
let image = jbig2(None);
let mut budget = ImageBudget::with_work(u64::MAX);
let samples = budget.decode(&doc, &image, 1 << 20).unwrap();
let cost = u64::MAX - budget.work_left();
assert!(cost > 0);
let mut budget = ImageBudget::with_work(3 * cost);
for left in [2, 1, 0] {
assert_eq!(budget.decode(&doc, &image, 1 << 20).unwrap(), samples);
assert_eq!(budget.work_left(), left * cost);
}
assert_eq!(budget.refused(), 0, "the allowance held exactly three");
for refused in [1, 2] {
assert!(budget.decode(&doc, &image, 1 << 20).is_err());
assert_eq!(budget.refused(), refused);
}
assert!(budget.decode(&doc, &Stream::flate(Dict::new(), b"samples"), 1 << 20).is_err());
assert!(budget.decode(&doc, &Stream::from_raw(Dict::new(), b"samples".to_vec()), 1 << 20).is_err());
assert_eq!(budget.refused(), 4, "other images share it");
for name in ["NoSuchFilter", "DCTDecode", "JPXDecode"] {
let mut dict = Dict::new();
dict.set(b"Filter".to_vec(), Object::name(name));
assert!(budget.decode(&doc, &Stream::from_raw(dict, b"data".to_vec()), 1 << 20).is_err());
assert_eq!(budget.refused(), 4, "{name} isn't one of these");
}
let mut dict = Dict::new();
dict.set(b"Filter".to_vec(), Object::Int(5));
assert!(budget.decode(&doc, &Stream::from_raw(dict, b"data".to_vec()), 1 << 20).is_err());
assert_eq!(budget.refused(), 4, "a /Filter that can't be read isn't either");
}
/// What a file of images each inflating a megabyte asks for: 4 KB of Flate inside Flate can ask
/// for a gigabyte, and these aren't JBIG2, so without the allowance nothing would stop them.
#[test]
fn filter_bombs_stop_at_the_allowance() {
let doc = Document::new_empty();
let samples = vec![0; 1 << 20];
let inner = pdfcraft_filters::encode_flate(&samples);
let mut dict = Dict::new();
dict.set(b"Filter".to_vec(), Object::Array(vec![Object::name("FlateDecode"), Object::name("FlateDecode")]));
let bomb = Stream::from_raw(dict, pdfcraft_filters::encode_flate(&inner));
let cost = (bomb.raw.len() + inner.len() + samples.len()) as u64;
let mut budget = ImageBudget::with_work(2 * cost + 1);
for left in [cost + 1, 1] {
assert_eq!(budget.decode(&doc, &bomb, 1 << 20).unwrap(), samples);
assert_eq!(budget.work_left(), left);
}
assert!(budget.decode(&doc, &bomb, 1 << 20).is_err());
assert_eq!((budget.work_left(), budget.refused()), (0, 1), "the first it can't pay for ends it");
}
/// Filters in front of a JBIG2 decoder pay as they run, on top of what the decoder takes, and
/// one that fails has still paid: nothing about the JBIG2 data is known by then, and each image
/// of a file can do this.
#[test]
fn filters_in_front_of_jbig2_pay_whether_or_not_they_work() {
let doc = Document::new_empty();
let alone = jbig2(None);
let mut budget = ImageBudget::with_work(u64::MAX);
let samples = budget.decode(&doc, &alone, 1 << 20).unwrap();
let decoding = u64::MAX - budget.work_left();
let behind = |raw: Vec<u8>| {
let mut dict = alone.dict.clone();
dict.set(b"Filter".to_vec(), Object::Array(vec![Object::name("FlateDecode"), Object::name("JBIG2Decode")]));
Stream::from_raw(dict, raw)
};
let image = behind(pdfcraft_filters::encode_flate(&alone.raw));
let mut budget = ImageBudget::with_work(u64::MAX);
assert_eq!(budget.decode(&doc, &image, 1 << 20).unwrap(), samples);
assert_eq!(u64::MAX - budget.work_left(), decoding + (image.raw.len() + alone.raw.len()) as u64);
// Past this image's limit: an error, with what finding out took paid and the rest left.
let bomb = behind(pdfcraft_filters::encode_flate(&vec![0; 1 << 16]));
let mut budget = ImageBudget::with_work(u64::MAX);
assert!(budget.decode(&doc, &bomb, 1000).is_err());
assert_eq!(u64::MAX - budget.work_left(), bomb.raw.len() as u64 + 1000);
assert_eq!(budget.refused(), 0, "that image's limit isn't the run's");
// A small allowance is a limit too: it stops there, and the image is refused.
let mut budget = ImageBudget::with_work(bomb.raw.len() as u64 + 10);
assert!(budget.decode(&doc, &bomb, 1 << 20).is_err());
assert_eq!((budget.work_left(), budget.refused()), (0, 1));
}
/// Globals that are read again for every image pay every time, and fail having paid. Kept
/// ones have no filters left to undo, so they pay for being read and nothing more.
#[test]
fn globals_pay_for_their_filters_each_time_they_are_decoded() {
let skipped = [0, 0, 0, 0, 0x3E, 0, 0, 0, 0, 0, 4, 0, 0, 0, 1];
let raw = pdfcraft_filters::encode_flate(&skipped);
let stream = |doc: &Document, r: ObjRef| match &*doc.get(r) {
Object::Stream(s) => s.clone(),
_ => panic!("not a stream"),
};
let spent = |doc: &Document, s: &Stream| {
let mut budget = ImageBudget::with_work(u64::MAX);
budget.decode(doc, s, 1 << 20).unwrap();
u64::MAX - budget.work_left()
};
let mut doc = Document::new_empty();
let mut dict = Dict::new();
dict.set(b"Filter".to_vec(), Object::name("FlateDecode"));
let globals = doc.add(Object::Stream(Stream::from_raw(dict, raw.clone())));
let mut parms = Dict::new();
parms.set(b"JBIG2Globals".to_vec(), Object::Ref(globals));
let image = doc.add(Object::Stream(jbig2(Some(Object::Dict(parms)))));
let root = doc.root().unwrap();
doc.update_dict(root, |c| c.set(b"Image".to_vec(), Object::Ref(image))).unwrap();
// Added in memory, so not kept: the filters are undone for each read.
let s = stream(&doc, image);
let first = spent(&doc, &s);
assert_eq!(spent(&doc, &s), first, "not kept, so paid for again");
// Read from a file, so kept: the second read has no filters to undo.
let file = crate::write_full(&doc, &crate::SaveOptions::default()).unwrap();
let doc = Document::open(std::sync::Arc::new(file)).unwrap();
let image = doc.get(doc.root().unwrap()).as_dict().unwrap().reference(b"Image").unwrap();
let s = stream(&doc, image);
let filters = (raw.len() + skipped.len()) as u64;
assert_eq!(spent(&doc, &s), first, "the first read undoes them");
assert_eq!(spent(&doc, &s), first - filters, "kept");
// Globals that fail pay too, with the image not refused: these go past their own limit.
let over = pdfcraft_filters::encode_flate(&vec![0; crate::MAX_JBIG2_GLOBALS + 1]);
let mut doc = Document::new_empty();
let mut dict = Dict::new();
dict.set(b"Filter".to_vec(), Object::name("FlateDecode"));
let globals = doc.add(Object::Stream(Stream::from_raw(dict, over.clone())));
let mut parms = Dict::new();
parms.set(b"JBIG2Globals".to_vec(), Object::Ref(globals));
let image = jbig2(Some(Object::Dict(parms)));
let mut budget = ImageBudget::with_work(u64::MAX);
assert!(budget.decode(&doc, &image, 1 << 20).unwrap_err().to_string().contains("globals"));
assert_eq!(u64::MAX - budget.work_left(), (over.len() + crate::MAX_JBIG2_GLOBALS) as u64);
assert_eq!(budget.refused(), 0);
}
/// A fax image pays for what comes before its decoder and for the rows it asks for, and past
/// the allowance it is refused like any other.
#[test]
fn fax_images_share_the_allowance() {
let doc = Document::new_empty();
let (w, h) = (4096u32, 64u32);
let coded = pdfcraft_filters::encode_g4(&vec![0xFF; 512 * h as usize], w, h).unwrap();
let mut parms = Dict::new();
parms.set(b"K".to_vec(), Object::Int(-1));
parms.set(b"Columns".to_vec(), Object::Int(i64::from(w)));
let mut dict = Dict::new();
dict.set(b"Width".to_vec(), Object::Int(i64::from(w)));
dict.set(b"Height".to_vec(), Object::Int(i64::from(h)));
dict.set(b"Filter".to_vec(), Object::Array(vec![Object::name("FlateDecode"), Object::name("CCITTFaxDecode")]));
dict.set(b"DecodeParms".to_vec(), Object::Array(vec![Object::Null, Object::Dict(parms)]));
let image = Stream::from_raw(dict, pdfcraft_filters::encode_flate(&coded));
let pixels = u64::from(w) * u64::from(h);
let cost = (image.raw.len() + coded.len() + 4 * coded.len() + 512 * h as usize) as u64 + pixels;
let mut budget = ImageBudget::with_work(cost);
assert_eq!(budget.decode(&doc, &image, 1 << 20).unwrap().len(), 512 * h as usize);
assert_eq!(budget.work_left(), 0, "exactly that");
assert!(budget.decode(&doc, &image, 1 << 20).is_err());
assert_eq!(budget.refused(), 1);
}
/// An image pays for its pixels however few bytes hold them, or a blank page of fax or Flate
/// would cost a run a second for a few bytes' worth of allowance; a JBIG2 image doesn't pay
/// twice, and one this doesn't decode pays nothing. Past what is left it isn't read.
#[test]
fn an_image_pays_for_its_pixels() {
let doc = Document::new_empty();
let blank = |filter: Option<&str>, data: Vec<u8>| {
let mut dict = Dict::new();
dict.set(b"Width".to_vec(), Object::Int(4096));
dict.set(b"Height".to_vec(), Object::Int(1024));
if let Some(filter) = filter {
dict.set(b"Filter".to_vec(), Object::name(filter));
}
Stream::from_raw(dict, data)
};
let rows = vec![0xFFu8; 512 * 1024];
let flate = blank(Some("FlateDecode"), pdfcraft_filters::encode_flate(&rows));
let cost = (flate.raw.len() + rows.len()) as u64 + 4096 * 1024;
let mut budget = ImageBudget::with_work(cost);
assert_eq!(budget.decode(&doc, &flate, 1 << 24).unwrap(), rows);
assert_eq!((budget.work_left(), budget.refused()), (0, 0), "exactly that");
// Its filters alone pay the same.
let mut budget = ImageBudget::with_work(cost);
assert_eq!(budget.decode_filters(&doc, &flate, 1 << 24).unwrap(), rows);
assert_eq!(budget.work_left(), 0);
// Short of its pixels it is refused, having paid for its filters.
let mut budget = ImageBudget::with_work(4096 * 1024 - 1);
assert!(budget.decode(&doc, &flate, 1 << 24).unwrap_err().to_string().contains("more image decoding than"));
assert_eq!((budget.work_left(), budget.refused()), (0, 1));
let mut budget = ImageBudget::with_work(4096 * 1024 - 1);
assert!(budget.decode_filters(&doc, &flate, 1 << 24).is_err());
assert_eq!((budget.work_left(), budget.refused()), (0, 1));
// What isn't decoded here pays for nothing, and fails as it would.
let mut budget = ImageBudget::with_work(10);
assert!(budget.decode(&doc, &blank(Some("DCTDecode"), b"data".to_vec()), 1 << 24).is_err());
assert_eq!((budget.work_left(), budget.refused()), (10, 0));
// Unfiltered data pays too, and a size that isn't one is no size.
let mut budget = ImageBudget::with_work(u64::MAX);
budget.decode(&doc, &blank(None, rows.clone()), 1 << 24).unwrap();
assert_eq!(u64::MAX - budget.work_left(), rows.len() as u64 + 4096 * 1024);
let mut odd = Dict::new();
odd.set(b"Width".to_vec(), Object::Int(-4));
odd.set(b"Height".to_vec(), Object::Int(9));
let mut budget = ImageBudget::with_work(u64::MAX);
budget.decode(&doc, &Stream::from_raw(odd, vec![1, 2]), 1 << 24).unwrap();
assert_eq!(u64::MAX - budget.work_left(), 2);
// A JPEG pays twice over for each sample, and four times for each byte it is read from.
let mut budget = ImageBudget::with_work(30);
assert!(budget.pay_jpeg(9, b"ab"));
assert_eq!((budget.work_left(), budget.refused()), (4, 0));
assert!(!budget.pay_jpeg(0, b"ab"));
assert_eq!((budget.work_left(), budget.refused()), (0, 1));
}
/// An image pays for the pixels its data holds, not those its size declares: one claiming
/// 131072 by 131072 pixels with a few bytes of Flate costs what those bytes give, and the
/// images after it are decoded as they would be without it.
#[test]
fn an_image_pays_for_no_more_pixels_than_its_data_holds() {
let doc = Document::new_empty();
let sized = |side: i64, data: &[u8]| {
let mut dict = Dict::new();
dict.set(b"Width".to_vec(), Object::Int(side));
dict.set(b"Height".to_vec(), Object::Int(side));
Stream::flate(dict, data)
};
let claims = sized(131_072, &[0; 16]);
let image = sized(64, &[7; 64 * 64]);
let cost = |s: &Stream| {
let mut budget = ImageBudget::with_work(u64::MAX);
budget.decode(&doc, s, 1 << 24).unwrap();
u64::MAX - budget.work_left()
};
assert_eq!(cost(&claims), (claims.raw.len() + 16 + 16 * 8) as u64, "its bytes, and a pixel a bit of them");
assert_eq!(cost(&image), (image.raw.len() + 64 * 64) as u64 + 64 * 64, "its bytes, and its pixels");
for decode in [ImageBudget::decode, ImageBudget::decode_filters] {
let mut budget = ImageBudget::with_work(cost(&claims) + cost(&image));
assert_eq!(decode(&mut budget, &doc, &claims, 1 << 24).unwrap(), [0; 16]);
assert_eq!(decode(&mut budget, &doc, &image, 1 << 24).unwrap(), [7; 64 * 64], "the image after it is decoded");
assert_eq!((budget.work_left(), budget.refused()), (0, 0));
}
}
/// A stream a run rewrites is read strictly and charged, and what the caller does with it after
/// comes out of the same allowance: what can't be paid for spends all of it.
#[test]
fn a_rewritten_stream_shares_the_allowance() {
use pdfcraft_filters::{Filter, FilterError, Params};
let samples = vec![7u8; 1000];
let raw = pdfcraft_filters::encode_flate(&samples);
let chain = [(Filter::Flate, Params::default())];
let cost = (raw.len() + samples.len()) as u64;
let mut budget = ImageBudget::with_work(cost + 10);
assert_eq!(budget.decode_chain(&chain, &raw, 1 << 20).unwrap(), samples);
assert_eq!(budget.work_left(), 10);
assert!(budget.spend(4));
assert_eq!(budget.work_left(), 6);
assert!(budget.spend(6), "exactly what is left");
assert_eq!(budget.work_left(), 0);
assert!(budget.spend(0));
let mut budget = ImageBudget::with_work(5);
assert!(!budget.spend(6));
assert_eq!(budget.work_left(), 0, "spends all of it");
assert!(matches!(budget.decode_chain(&chain, &raw, 1 << 20), Err(FilterError::Spent)));
let cut = raw.get(..raw.len() / 2).unwrap();
assert!(matches!(ImageBudget::with_work(u64::MAX).decode_chain(&chain, cut, 1 << 20), Err(FilterError::Corrupt { .. })), "strictly");
}
/// An image read through its filters alone reads parameters given by reference, is charged, and
/// is refused like the others. It isn't given to a decoder.
#[test]
fn filters_alone_are_charged_too() {
let mut doc = Document::new_empty();
let p = pdfcraft_filters::Params { predictor: 12, columns: 4, ..pdfcraft_filters::Params::default() };
let rows = vec![7u8; 400];
let mut parms = Dict::new();
parms.set(b"Predictor".to_vec(), Object::Int(12));
parms.set(b"Columns".to_vec(), Object::Int(4));
let parms = doc.add(Object::Dict(parms));
let mut dict = Dict::new();
dict.set(b"Filter".to_vec(), Object::name("FlateDecode"));
dict.set(b"DecodeParms".to_vec(), Object::Ref(parms));
let raw = pdfcraft_filters::encode(&pdfcraft_filters::Filter::Flate, &p, &rows).unwrap();
let image = Stream::from_raw(dict, raw);
let mut budget = ImageBudget::with_work(u64::MAX);
assert_eq!(budget.decode_filters(&doc, &image, 1 << 20).unwrap(), rows);
let cost = u64::MAX - budget.work_left();
// The tag byte of each of its 100 rows counts, which the predictor takes off.
assert_eq!(cost, (image.raw.len() + rows.len() + 100) as u64);
let mut budget = ImageBudget::with_work(cost - 1);
assert!(budget.decode_filters(&doc, &image, 1 << 20).is_err());
assert_eq!((budget.work_left(), budget.refused()), (0, 1));
let mut budget = ImageBudget::with_work(u64::MAX);
assert!(budget.decode_filters(&doc, &jbig2(None), 1 << 20).is_err());
assert_eq!(budget.work_left(), u64::MAX, "no decoder here, so nothing was read");
// Nor for a fax image, nor for a decoder that isn't last, however large they say they are.
for chain in [vec!["CCITTFaxDecode"], vec!["CCITTFaxDecode", "FlateDecode"], vec!["JBIG2Decode", "FlateDecode"]] {
let mut dict = Dict::new();
dict.set(b"Width".to_vec(), Object::Int(1000));
dict.set(b"Height".to_vec(), Object::Int(1000));
dict.set(b"Filter".to_vec(), Object::Array(chain.iter().map(|f| Object::name(f)).collect()));
let image = Stream::from_raw(dict, b"data".to_vec());
let mut budget = ImageBudget::with_work(u64::MAX);
assert!(budget.decode_filters(&doc, &image, 1 << 20).is_err());
assert_eq!(budget.work_left(), u64::MAX, "{chain:?}");
}
// Through `decode` a decoder that isn't last pays nothing either; one that is does.
let mut dict = Dict::new();
dict.set(b"Width".to_vec(), Object::Int(1000));
dict.set(b"Height".to_vec(), Object::Int(1000));
dict.set(b"Filter".to_vec(), Object::Array(vec![Object::name("JBIG2Decode"), Object::name("FlateDecode")]));
let mut budget = ImageBudget::with_work(u64::MAX);
assert!(budget.decode(&doc, &Stream::from_raw(dict, b"data".to_vec()), 1 << 20).is_err());
assert_eq!(budget.work_left(), u64::MAX);
}
/// The images of a file share its globals, so an image refused doesn't read them: this one's
/// can't be read, which is how to tell.
#[test]
fn an_image_past_the_allowance_does_not_read_its_globals() {
let mut doc = Document::new_empty();
let mut unreadable = Dict::new();
unreadable.set(b"Filter".to_vec(), Object::name("NoSuchFilter"));
let globals = doc.add(Object::Stream(Stream::from_raw(unreadable, b"data".to_vec())));
let mut parms = Dict::new();
parms.set(b"JBIG2Globals".to_vec(), Object::Ref(globals));
let image = jbig2(Some(Object::Dict(parms)));
let read = ImageBudget::with_work(u64::MAX).decode(&doc, &image, 1 << 20).unwrap_err().to_string();
assert!(read.contains("globals"), "{read}");
let refused = ImageBudget::with_work(0).decode(&doc, &image, 1 << 20).unwrap_err().to_string();
assert!(refused.contains("more image decoding than"), "{refused}");
}
/// A longer file gets more, by its length, and an empty one the fixed part.
#[test]
fn a_longer_file_allows_more_decoding() {
assert_eq!(ImageBudget::new(&Document::new_empty()).work_left(), IMAGE_WORK);
let pdf = b"%PDF-1.7\n1 0 obj << /Type /Catalog >> endobj\ntrailer << /Root 1 0 R >>\n%%EOF".to_vec();
let len = pdf.len() as u64;
let doc = Document::open(std::sync::Arc::new(pdf)).unwrap();
assert_eq!(ImageBudget::new(&doc).work_left(), IMAGE_WORK + len * IMAGE_WORK_PER_BYTE);
}
/// A document made in memory, as Combine, Create and inserted scans make one, gets for the
/// streams it was given what it would get for them once saved: what isn't a stream adds nothing.
#[test]
fn streams_made_in_memory_allow_more_decoding_too() {
let mut doc = Document::new_empty();
doc.add(Object::Stream(Stream::from_raw(Dict::new(), vec![0; 3000])));
doc.add(Object::Dict(Dict::new()));
doc.add(Object::Stream(Stream::flate(Dict::new(), &[1; 100])));
let flate = pdfcraft_filters::encode_flate(&[1; 100]).len() as u64;
assert_eq!(ImageBudget::new(&doc).work_left(), IMAGE_WORK + (3000 + flate) * IMAGE_WORK_PER_BYTE);
// A stream of an opened file changed in memory counts with the file.
let pdf = b"%PDF-1.7\n1 0 obj << /Type /Catalog >> endobj\ntrailer << /Root 1 0 R >>\n%%EOF".to_vec();
let len = pdf.len() as u64;
let mut doc = Document::open(std::sync::Arc::new(pdf)).unwrap();
doc.add(Object::Stream(Stream::from_raw(Dict::new(), vec![0; 500])));
assert_eq!(ImageBudget::new(&doc).work_left(), IMAGE_WORK + (len + 500) * IMAGE_WORK_PER_BYTE);
}
// What the constants' comments promise, for a page scanned at 300 dpi: about 1,000 of them
// whatever the file's size, and a page paying for itself with 2 KB of the file.
const PAGE: u64 = 17_000_000;
const _: () = assert!(IMAGE_WORK >= 1_000 * PAGE);
const _: () = assert!(IMAGE_WORK_PER_BYTE * 2_100 >= PAGE);
// And that a stream can be decoded about 8 times at Flate's best, 1,032 to one, and the byte in.
const _: () = assert!(IMAGE_WORK_PER_BYTE >= 7 * 1_033);
}
#[cfg(test)]
mod tests {
use super::*;
@@ -198,6 +801,21 @@ mod tests {
assert_eq!(budget.remaining(), (10 << 20) - partial);
}
/// A stream that fails its reading as zlib, and then as raw deflate after decoding all of it,
/// gives nothing back, and each reference still pays for what it decoded.
#[test]
fn a_decode_that_gives_nothing_back_still_pays() {
let mut data = vec![0x78, 0x01, 0x06, 0xFE, 0xF9];
data.extend(vec![0u8; 0x0601]);
data.push(0x07);
let mut dict = Dict::new();
dict.set(b"Filter".to_vec(), Object::name("FlateDecode"));
let stream = Stream::from_raw(dict, data);
let mut budget = DecodeBudget::new(10 * 0x0601, 1);
assert!(budget.decode(&stream).unwrap().is_empty());
assert_eq!(budget.remaining(), 9 * 0x0601);
}
/// A chain whose later stage shrinks the data pays for every stage's output: a Flate stage
/// that inflates to hex text, which ASCIIHex then halves, charges both.
#[test]
+11 -3
View File
@@ -10,7 +10,7 @@ use std::collections::{BTreeMap, HashMap, HashSet};
use std::sync::{Arc, Mutex, Weak};
use crate::CosError;
use crate::object::{Dict, MAX_DECODED, ObjRef, Object, Stream};
use crate::object::{Dict, MAX_DECODED, MAX_JBIG2_GLOBALS, ObjRef, Object, Stream};
use crate::parser::{EndstreamIndex, Lexer, is_whitespace, parse_indirect, parse_indirect_shared};
mod objects;
@@ -19,6 +19,7 @@ mod reader;
mod state;
mod xref;
pub(crate) use objects::Held;
#[cfg(test)]
pub(crate) use reader::find;
#[cfg(test)]
@@ -27,7 +28,7 @@ pub(crate) use state::ObjectReader;
use state::{ObjStm, Slot};
pub use state::{ReadState, SourceIdentity};
#[cfg(test)]
use state::{SECTION_READS, objstm_member, owned_bytes};
use state::{SECTION_READS, held_bytes, objstm_member};
use xref::XrefIndex;
pub use xref::{Revision, XrefEntry};
@@ -47,8 +48,11 @@ pub struct Document {
/// `fill_xref_gaps`.
located: Arc<BTreeMap<u32, (u64, u16)>>,
repair_log: Arc<Vec<String>>,
cache: Arc<Mutex<HashMap<u32, Arc<Object>>>>,
cache: Arc<Mutex<state::ObjectCache>>,
objstms: Arc<Mutex<HashMap<u32, Arc<ObjStm>>>>,
/// What `/JBIG2Globals` streams of the file decode to, by object number: the images of a scan
/// share them, and each would otherwise decode them again (see `Document::jbig2_globals`).
jbig2_globals: Arc<Mutex<HashMap<u32, Arc<Vec<u8>>>>>,
stream_limit: usize,
overlay: BTreeMap<u32, Slot>,
next_num: u32,
@@ -59,6 +63,10 @@ pub struct Document {
security: Option<Arc<pdfcraft_crypt::SecurityHandler>>,
/// Object number of the `/Encrypt` dictionary (never encrypted itself).
encrypt_num: Option<u32>,
/// What that dictionary and `/ID` refer to, which the key comes from, and so is as stored.
encrypt_members: Arc<HashSet<u32>>,
/// Object numbers a scan of the file didn't find: the file doesn't change, so it never will.
unfound: Arc<Mutex<HashSet<u32>>>,
/// Encryption was added, changed or removed since opening: only a full save can apply it.
encryption_changed: bool,
/// Set by edits that must not leave earlier revisions in the file (redaction).
+182 -82
View File
@@ -1,7 +1,13 @@
use super::reader::find;
use super::state::{LENGTHS, LoadGuard, ObjStm, ObjectReader, ReadState, Slot, SourceIdentity, objstm_member, owned_bytes};
use super::state::{LENGTHS, LoadGuard, ObjStm, ObjectReader, ReadState, Slot, SourceIdentity, held_bytes, objstm_member};
use super::xref::{Revision, XrefEntry};
use super::{Arc, CosError, Cow, Dict, Document, Lexer, MAX_DECODED, ObjRef, Object, Stream, is_whitespace, parse_indirect_shared};
use super::{
Arc, CosError, Cow, Dict, Document, Lexer, MAX_DECODED, MAX_JBIG2_GLOBALS, ObjRef, Object, Stream, is_whitespace, parse_indirect_shared,
};
/// The most decoded `/JBIG2Globals` a document keeps for its images to share (see
/// `Document::jbig2_globals`): two streams at [`MAX_JBIG2_GLOBALS`].
const JBIG2_GLOBALS_HELD: usize = 2 * MAX_JBIG2_GLOBALS;
impl Document {
pub fn bytes(&self) -> &Arc<Vec<u8>> {
@@ -150,12 +156,16 @@ impl Document {
self.try_get(r.num).unwrap_or_else(|_| Arc::new(Object::Null))
}
/// Follow a reference if `o` is one; otherwise return `o` itself.
/// Follow a reference if `o` is one; otherwise return `o` itself. An object can be nothing but
/// a reference to another, which is followed too, up to [`MAX_REFERENCE_HOPS`] of them.
pub fn resolve(&self, o: &Object) -> Arc<Object> {
match o {
Object::Ref(r) => self.get(*r),
other => Arc::new(other.clone()),
let Object::Ref(r) = o else { return Arc::new(o.clone()) };
let mut held = self.get(*r);
for _ in 0..MAX_REFERENCE_HOPS {
let Object::Ref(r) = &*held else { break };
held = self.get(*r);
}
held
}
/// `s` with the `/DecodeParms` its filters use made direct, so [`Stream::decoded`] reads them:
@@ -212,7 +222,7 @@ impl Document {
}
/// `o`, or the object it refers to, without copying either.
fn held<'o>(&self, o: &'o Object) -> Held<'o> {
pub(crate) fn held<'o>(&self, o: &'o Object) -> Held<'o> {
match o {
Object::Ref(_) => Held::Resolved(self.resolve(o)),
o => Held::Direct(o),
@@ -233,18 +243,7 @@ impl Document {
if !matches!(chain.last(), Some((pdfcraft_filters::Filter::CcittFax, _))) {
return None;
}
// Its place in /Filter, /Crypt included, pairs it with its /DecodeParms entry (§7.4.1): the
// last filter but a /Crypt, which `filters` leaves out wherever it stands.
let index = match s.dict.get(b"Filter") {
Some(Object::Array(a)) => a.iter().rposition(|f| f.as_name() != Some(b"Crypt".as_slice())).unwrap_or(0),
_ => 0,
};
let parms = match s.dict.get(b"DecodeParms").map(|p| self.resolve(p)).as_deref() {
Some(Object::Array(a)) => a.get(index).and_then(|p| self.dict(p)),
Some(p) if index == 0 => p.as_dict().cloned(),
_ => None,
}
.unwrap_or_default();
let parms = self.last_filter_parms(s);
let int = |key: &[u8], default: i64| parms.get(key).and_then(|v| self.resolve(v).as_int()).unwrap_or(default);
let flag = |key: &[u8], default: bool| match parms.get(key).map(|v| self.resolve(v)).as_deref() {
Some(Object::Bool(b)) => *b,
@@ -262,42 +261,129 @@ impl Document {
})
}
/// The samples of image `s`, decoded: through its filters ([`Stream::decoded`]), or, for a
/// CCITT fax image (its last filter), through the filters before it and then
/// [`pdfcraft_filters::decode_ccitt`] with its [`Document::fax_params`], as `CCITTFaxDecode`
/// gives them (ISO 32000-2 §7.4.6). Parameters given by reference count, for every filter
/// ([`Document::with_direct_parms`]). A fax image's `/Columns` has to be its `/Width`. Up to
/// its `/Height` rows are decoded, whatever `/Rows` says, within [`MAX_DECODED`] bytes; damaged
/// data gives fewer, so a caller checks it has the rows it needs.
pub fn decoded_image(&self, s: &Stream) -> Result<Vec<u8>, CosError> {
/// The `/DecodeParms` dictionary of stream `s`'s last filter, resolved: that of a lone filter,
/// or its entry in an array. Empty when there is none.
fn last_filter_parms(&self, s: &Stream) -> Dict {
// Its place in /Filter, /Crypt included, pairs it with its /DecodeParms entry (§7.4.1): the
// last filter but a /Crypt, which `filters` leaves out wherever it stands.
let index = match s.dict.get(b"Filter") {
Some(Object::Array(a)) => a.iter().rposition(|f| f.as_name() != Some(b"Crypt".as_slice())).unwrap_or(0),
_ => 0,
};
match s.dict.get(b"DecodeParms").map(|p| self.resolve(p)).as_deref() {
Some(Object::Array(a)) => a.get(index).and_then(|p| self.dict(p)),
Some(p) if index == 0 => p.as_dict().cloned(),
_ => None,
}
.unwrap_or_default()
}
/// [`Document::decoded_image_spending`] with no limit on the work, for tests of what an image
/// decodes to: everything else decodes images through an [`ImageBudget`](crate::ImageBudget).
#[cfg(test)]
pub(crate) fn decoded_image(&self, s: &Stream) -> Result<Vec<u8>, CosError> {
self.decoded_image_within(s, MAX_DECODED)
}
/// [`Document::decoded_image`] for an image whose decoding has a tighter bound than
/// [`MAX_DECODED`]: no stage, the filters before a fax decoder included, may produce more than
/// `max` bytes.
pub fn decoded_image_within(&self, s: &Stream, max: usize) -> Result<Vec<u8>, CosError> {
/// [`Document::decoded_image`] within `max` bytes.
#[cfg(test)]
pub(crate) fn decoded_image_within(&self, s: &Stream, max: usize) -> Result<Vec<u8>, CosError> {
let mut unbounded = u64::MAX;
self.decoded_image_spending(s, max, &mut unbounded)
}
/// The samples of image `s`, decoded within `max` bytes ([`MAX_DECODED`] at most), spending from
/// `work`: see [`ImageBudget::decode`](crate::ImageBudget::decode), the way in from outside this
/// crate, which says what this decodes and how.
pub(crate) fn decoded_image_spending(&self, s: &Stream, max: usize, work: &mut u64) -> Result<Vec<u8>, CosError> {
let max = max.min(MAX_DECODED);
let s = &*self.with_direct_parms(s);
let Some(p) = self.fax_params(s) else { return s.decoded_within(max) };
let filter = |e: pdfcraft_filters::FilterError| CosError::Filter(e.to_string());
let chain = s.readable_filters().map_err(filter)?;
// The filters before the image codec, such as ASCII85Decode, are undone first.
let undo = |before: &[(pdfcraft_filters::Filter, pdfcraft_filters::Params)], work: &mut u64| match before {
[] => Ok(Cow::Borrowed(&s.raw[..])),
_ => pdfcraft_filters::decode_tolerant_within(before, &s.raw, max, work).map(Cow::Owned).map_err(filter),
};
// `/Width` and `/Height` are read as given directly, as every caller reads them first: one
// given by reference has the image refused there, before it gets here.
let height = s.dict.int(b"Height").and_then(|h| u32::try_from(h).ok());
if let Some(((pdfcraft_filters::Filter::Jbig2, _), before)) = chain.split_last() {
let (Some(columns), Some(height)) = (s.dict.int(b"Width").and_then(|w| u32::try_from(w).ok()), height) else {
return Err(CosError::Filter("a JBIG2 image's /Width or /Height isn't a size".into()));
};
// Nothing to read for what can't be decoded: the images of a file share its globals.
let globals = if *work == 0 { None } else { self.jbig2_globals(s, work)? };
let data = if *work == 0 { Cow::Borrowed(&[][..]) } else { undo(before, work)? };
return pdfcraft_filters::decode_jbig2_within(&data, globals.as_deref().map(Vec::as_slice), columns, height, max, work).map_err(filter);
}
let Some(p) = self.fax_params(s) else { return s.decoded_spending(max, work) };
// As many rows as the image has: a /Rows below /Height would cut the picture short, and
// rows past /Height aren't drawn.
let p = pdfcraft_filters::CcittParams { rows: 0, ..p };
if s.dict.int(b"Width") != Some(p.columns) {
return Err(CosError::Filter("a fax image's /Columns aren't its /Width".into()));
}
let height = s.dict.int(b"Height").and_then(|h| u32::try_from(h).ok()).unwrap_or(0);
let stride = usize::try_from(p.columns).unwrap_or(usize::MAX).div_ceil(8).max(1);
let rows = u32::try_from(max / stride).unwrap_or(u32::MAX).min(height);
// The filters before it, such as ASCII85Decode, are undone first.
let chain = s.readable_filters().map_err(|e| CosError::Filter(e.to_string()))?;
let data = match chain.split_last() {
Some((_, before)) if !before.is_empty() => {
Cow::Owned(pdfcraft_filters::decode_tolerant(before, &s.raw, max).map_err(|e| CosError::Filter(e.to_string()))?.0)
}
_ => Cow::Borrowed(&s.raw[..]),
let rows = u32::try_from(max / stride).unwrap_or(u32::MAX).min(height.unwrap_or(0));
let data = undo(chain.split_last().map_or(&[][..], |(_, before)| before), work)?;
pdfcraft_filters::decode_ccitt_within(&data, &p, rows, work).map_err(filter)
}
/// The `/JBIG2Globals` stream a JBIG2 image `s` names by reference in its last filter's
/// `/DecodeParms`: `None` for a stream whose last filter isn't `JBIG2Decode`, or one without
/// globals. Redaction finds with it the other images that share a redacted image's globals.
pub fn jbig2_globals_ref(&self, s: &Stream) -> Option<ObjRef> {
let chain = s.readable_filters().ok()?;
if !matches!(chain.last(), Some((pdfcraft_filters::Filter::Jbig2, _))) {
return None;
}
self.last_filter_parms(s).get(b"JBIG2Globals").and_then(Object::as_ref)
}
/// What the `/JBIG2Globals` stream of JBIG2 image `s` (in its last filter's `/DecodeParms`)
/// decodes to, within [`MAX_JBIG2_GLOBALS`]; `None` without one (a reference to no object is
/// one to null, ISO 32000-2 §7.3.10, which is an absent entry, §7.3.7). The image is then read
/// without them, as the renderer draws it, so an image that needed them mostly fails to decode
/// and can decode to other pixels. A stream that is there and can't be read is an error, rather
/// than the image decoded without it.
///
/// The images of a scan share one globals stream, so a stream of the file, not edited since
/// it was read (the same in every clone) and with its `/DecodeParms` direct (by reference they
/// are another object, which can change while this one doesn't), has its filters undone once a
/// document and is kept, up to [`JBIG2_GLOBALS_HELD`] in all; others are read each time. That
/// saves the filters only: the segments it holds are decoded again for every image. Undoing
/// the filters spends from `work`, so globals read for every image pay every time.
fn jbig2_globals(&self, s: &Stream, work: &mut u64) -> Result<Option<Arc<Vec<u8>>>, CosError> {
let Some(entry) = self.last_filter_parms(s).get(b"JBIG2Globals").cloned() else { return Ok(None) };
let held = match entry {
Object::Ref(r) if !self.overlay.contains_key(&r.num) => Some(r.num),
_ => None,
};
pdfcraft_filters::decode_ccitt(&data, &p, rows).map_err(|e| CosError::Filter(e.to_string()))
if let Some(hit) = held.and_then(|num| self.jbig2_globals.lock().ok()?.get(&num).cloned()) {
return Ok(Some(hit));
}
let Object::Stream(g) = &*self.resolve(&entry) else { return Ok(None) };
let readable = self.with_direct_parms(g);
let held = held.filter(|_| matches!(readable, Cow::Borrowed(_)));
let mut data = readable.decoded_spending(MAX_JBIG2_GLOBALS, work).map_err(|e| {
let detail = match e {
CosError::Filter(detail) => detail,
e => e.to_string(),
};
CosError::Filter(format!("the JBIG2 globals can't be read: {detail}"))
})?;
// What is kept counts by its length, so that's all it may hold on to.
data.shrink_to_fit();
let data = Arc::new(data);
// A poisoned lock only means nothing is kept.
if let (Some(num), Ok(mut kept)) = (held, self.jbig2_globals.lock()) {
let total = kept.values().map(|g| g.len()).fold(data.len(), usize::saturating_add);
if total <= JBIG2_GLOBALS_HELD {
kept.insert(num, data.clone());
}
}
Ok(Some(data))
}
pub fn try_get(&self, num: u32) -> Result<Arc<Object>, CosError> {
@@ -313,12 +399,14 @@ impl Document {
// cycles such as `6 0 obj << /Length 6 0 R >>`. Bound the nesting on every path.
let _guard =
LoadGuard::enter(num).ok_or_else(|| CosError::Syntax { offset: 0, detail: format!("reference cycle while loading object {num}") })?;
let _scope = crate::security::FollowScope::enter();
let obj = self.load(num, 0)?;
let obj = Arc::new(obj);
// The editing cache is bounded like the scan reader's: re-parsing a file-backed view
// is cheap, and returned objects outlive eviction.
self.cache.lock().map_err(|_| CosError::Poisoned)?.insert(num, obj.clone());
self.evict_editor_cache_if_over_budget(num, &obj)?;
let owned = held_bytes(&obj, &self.data, 0);
self.cache.lock().map_err(|_| CosError::Poisoned)?.insert(num, obj.clone(), owned);
self.evict_editor_cache_if_over_budget(num)?;
Ok(obj)
}
@@ -327,10 +415,10 @@ impl Document {
/// document cannot pin its whole object graph. Only owned (decrypted/copied) bytes
/// count; file-backed views re-parse for free.
///
/// Worst case per document: input bytes + up to `EDITOR_CACHE_OBJECTS` ×
/// `EDITOR_LARGE_OBJECT` (1024 × 256 KB = 256 MB) of small objects between full
/// accounting passes + `EDITOR_OBJSTM_BYTES` (32 MB) + unsaved `overlay` edits.
/// The count cap always holds; byte accounting between passes is approximate.
/// Worst case per document: input bytes + `EDITOR_CACHE_BYTES` (32 MB) of owned object
/// data + `EDITOR_OBJSTM_BYTES` (32 MB) + unsaved `overlay` edits. Each object is measured
/// once, as it is cached ([`ObjectCache`](super::state::ObjectCache)), so both caps hold
/// after every insertion.
/// Clones share these caches, so one clone's eviction drops another's hot set;
/// that only costs re-parsing, never correctness. Eviction keeps just the newcomer:
/// file-backed views re-parse cheaply and editor working sets stay far below 1024.
@@ -343,37 +431,13 @@ impl Document {
const EDITOR_OBJSTM_BYTES: usize = 32 * 1024 * 1024;
/// Newcomers above this force a full accounting pass even below the count cap:
/// `EDITOR_CACHE_BYTES / 128`, so 128 large newcomers always trigger a pass before the
/// byte budget can double.
const EDITOR_LARGE_OBJECT: usize = 256 * 1024;
fn evict_editor_cache_if_over_budget(&self, fresh_num: u32, fresh: &Object) -> Result<(), CosError> {
// Fast path: the full fold is O(cache) per insert, so skip it for a small newcomer
// below the count cap. `len` is copied out first; nothing here holds the lock.
let len = self.cache.lock().map_err(|_| CosError::Poisoned)?.len();
if len <= Self::EDITOR_CACHE_OBJECTS && owned_bytes(fresh, &self.data, 0) <= Self::EDITOR_LARGE_OBJECT {
return Ok(());
}
// Walk a snapshot off-lock; re-lock only to evict.
let live: Vec<(u32, Arc<Object>)> = self.cache.lock().map_err(|_| CosError::Poisoned)?.iter().map(|(n, o)| (*n, o.clone())).collect();
let data = &self.data;
let owned: usize = live.iter().fold(0usize, |n, (_, o)| n.saturating_add(owned_bytes(o, data, 0)));
if live.len() <= Self::EDITOR_CACHE_OBJECTS && owned <= Self::EDITOR_CACHE_BYTES {
return Ok(());
}
// Re-check under the final lock: another thread may have inserted or evicted since
// the snapshot. Keep its newcomers, and skip the eviction if back within budget.
let snapshot: std::collections::HashSet<u32> = live.into_iter().map(|(n, _)| n).collect();
fn evict_editor_cache_if_over_budget(&self, fresh_num: u32) -> Result<(), CosError> {
let mut cache = self.cache.lock().map_err(|_| CosError::Poisoned)?;
if cache.len() <= Self::EDITOR_CACHE_OBJECTS {
let data = &self.data;
let owned: usize = cache.values().fold(0usize, |n, o| n.saturating_add(owned_bytes(o, data, 0)));
if owned <= Self::EDITOR_CACHE_BYTES {
return Ok(());
}
if cache.len() <= Self::EDITOR_CACHE_OBJECTS && cache.owned() <= Self::EDITOR_CACHE_BYTES {
return Ok(());
}
cache.retain(|n, _| *n == fresh_num || !snapshot.contains(n));
// Eviction keeps just the newcomer: file-backed views re-parse cheaply.
cache.retain(|n| *n == fresh_num);
Ok(())
}
@@ -503,7 +567,11 @@ impl Document {
let Object::Stream(s) = &*loaded else { return Err(CosError::MissingObject(num)) };
let n = s.dict.int(b"N").unwrap_or(0).clamp(0, 1_000_000) as usize;
let first = usize::try_from(s.dict.int(b"First").unwrap_or(0).max(0)).ok();
let data = s.decoded_within(self.stream_limit)?;
// Its parameters can be given by reference, and can sit in another object stream. A scan of
// the file's object streams comes here without a read around it.
let _scope = crate::security::FollowScope::enter();
let readable = crate::security::following(Cow::Borrowed(s), || self.with_direct_parms(s));
let data = readable.decoded_within(self.stream_limit)?;
let mut lx = Lexer::new(&data, 0);
let mut index = Vec::with_capacity(n);
for _ in 0..n {
@@ -518,8 +586,14 @@ impl Document {
Ok(stm)
}
/// Last-resort lookup: scan the file for `num G obj`.
/// Last-resort lookup: scan the file for `num G obj`. What isn't there is remembered: each miss
/// reads the whole file, and a file can refer to such an object from everywhere.
fn scan_for(&self, num: u32) -> Option<(ObjRef, Object)> {
if self.unfound.lock().is_ok_and(|unfound| unfound.contains(&num)) {
return None;
}
#[cfg(test)]
super::tests::FILE_SCANS.with(|scans| scans.set(scans.get() + 1));
let needle = format!("{num} ");
let data = &self.data;
let mut found = None;
@@ -535,6 +609,11 @@ impl Document {
found = Some((id, o)); // keep the last (newest) definition
}
}
if found.is_none()
&& let Ok(mut unfound) = self.unfound.lock()
{
unfound.insert(num);
}
found
}
@@ -600,8 +679,9 @@ impl Document {
///
/// Used when the working snapshot was restored from an earlier revision and the next
/// incremental save must still append to this file (the last saved revision). Objects
/// that already match are left untouched. Reads go through private readers so neither
/// document's editing cache is filled.
/// that already match are left untouched, except members of an object stream of this file
/// whose stream number `current` frees or reuses: those are written again on their own.
/// Reads go through private readers so neither document's editing cache is filled.
pub fn overlay_changes_from(&mut self, current: &Document) -> Result<(), CosError> {
let saved_nums = self.object_numbers();
let current_nums = current.object_numbers();
@@ -625,6 +705,22 @@ impl Document {
}
}
}
// An object stream of this file that is freed or replaced takes its members with it, so
// a member that is otherwise unchanged is written again on its own.
let gone = |n: u32| freed.binary_search(&n).is_ok() || changed.binary_search(&n).is_ok();
let orphaned: Vec<u32> = current_nums
.iter()
.copied()
.filter(|&num| changed.binary_search(&num).is_err())
.filter(|&num| {
let packed_in = match self.xref_entry(num) {
Some(XrefEntry::InStream { stream, .. }) => Some(stream),
_ => None,
};
packed_in.is_some_and(gone)
})
.collect();
changed.extend(orphaned);
for num in freed {
let generation = self.generation(num);
self.free(ObjRef::new(num, generation));
@@ -727,9 +823,13 @@ const DECODE_PARMS_KEYS: [&[u8]; 13] = [
b"ColorTransform",
];
/// How many references in a row [`Document::resolve`] follows: enough for any file, and it ends a
/// cycle of them.
const MAX_REFERENCE_HOPS: usize = 32;
/// An object read in place, or the object a reference names as the document holds it: either way
/// nothing is copied ([`Document::held`]).
enum Held<'o> {
pub(crate) enum Held<'o> {
Direct(&'o Object),
Resolved(Arc<Object>),
}
+55 -7
View File
@@ -1,7 +1,11 @@
use super::reader::find;
use super::state::Credentials;
use super::xref::XrefIndex;
use super::{Arc, BTreeMap, CosError, Dict, Document, ObjRef, Object};
use super::{Arc, BTreeMap, CosError, Dict, Document, HashSet, ObjRef, Object};
/// More objects than `/Encrypt` and `/ID` refer to in any file, so that one which refers to the page
/// tree, say, doesn't have a whole document read to open it.
const MAX_ENCRYPT_MEMBERS: usize = 64;
impl Document {
/// A new document with an empty page tree (for split / extract / combine). It has no
@@ -19,6 +23,7 @@ impl Document {
repair_log: Arc::new(Vec::new()),
cache: Arc::default(),
objstms: Arc::default(),
jbig2_globals: Arc::default(),
stream_limit: crate::object::MAX_DECODED,
overlay: BTreeMap::new(),
next_num: 1,
@@ -26,6 +31,8 @@ impl Document {
version: "1.7".into(),
security: None,
encrypt_num: None,
encrypt_members: Arc::default(),
unfound: Arc::default(),
encryption_changed: false,
full_save: false,
out_security: None,
@@ -102,6 +109,7 @@ impl Document {
repair_log: Arc::new(Vec::new()),
cache: Arc::default(),
objstms: Arc::default(),
jbig2_globals: Arc::default(),
stream_limit: stream_limit.min(crate::object::MAX_DECODED),
overlay: BTreeMap::new(),
next_num: 1,
@@ -109,6 +117,8 @@ impl Document {
version,
security: None,
encrypt_num: None,
encrypt_members: Arc::default(),
unfound: Arc::default(),
encryption_changed: false,
full_save: false,
out_security: None,
@@ -183,6 +193,8 @@ impl Document {
};
let params = crate::security::encrypt_dict(self, &dict);
let id0 = self.first_id();
// Read here, while nothing is decrypted yet.
let members = self.encryption_members(enc);
let handler = match credentials {
Credentials::Password(password) => Arc::new(pdfcraft_crypt::SecurityHandler::open(params, &id0, *password).map_err(|e| match e {
pdfcraft_crypt::CryptError::WrongPassword if password.is_none() => CosError::NeedsPassword,
@@ -195,6 +207,7 @@ impl Document {
};
self.security = Some(handler);
self.encrypt_num = num;
self.encrypt_members = Arc::new(members);
// Objects read while locating the catalog were read before decryption was possible.
self.cache = Arc::default();
self.objstms = Arc::default();
@@ -203,10 +216,42 @@ impl Document {
/// The first file identifier, part of the encryption key (empty when there is none).
fn first_id(&self) -> Vec<u8> {
match self.trailer.get(b"ID") {
Some(Object::Array(a)) => a.first().and_then(|s| s.as_string()).map(|s| s.bytes.clone()).unwrap_or_default(),
_ => Vec::new(),
let id = self.trailer.get(b"ID").map(|id| self.resolve(id));
let first = id.as_deref().and_then(Object::as_array).and_then(|a| a.first()).map(|s| self.resolve(s));
first.as_deref().and_then(Object::as_string).map(|s| s.bytes.clone()).unwrap_or_default()
}
/// The objects `/Encrypt`, given as `enc`, and `/ID` refer to, the ones they refer to, and so
/// on, up to [`MAX_ENCRYPT_MEMBERS`]. Their strings aren't encrypted (ISO 32000-2 §7.6.2): the
/// key is made from them, so they have to read as stored, and stay so. A number with no object
/// behind it, and a stream, which those dictionaries never hold, isn't one: an object added
/// under that number later, or a page's content a hostile `/Encrypt` names, is encrypted.
fn encryption_members(&self, enc: &Object) -> HashSet<u32> {
let mut pending = Vec::new();
crate::writer::collect_refs(enc, &mut |r| pending.push(r));
if let Some(id) = self.trailer.get(b"ID") {
crate::writer::collect_refs(id, &mut |r| pending.push(r));
}
let mut members = HashSet::new();
while let Some(r) = pending.pop() {
if members.len() >= MAX_ENCRYPT_MEMBERS || members.contains(&r.num) {
continue;
}
let held = self.get(r);
if matches!(&*held, Object::Null | Object::Stream(_)) {
continue;
}
members.insert(r.num);
crate::writer::collect_refs(&held, &mut |x| pending.push(x));
}
members
}
/// Whether object `num` is written as it is held, being one of [`Document::encryption_members`],
/// unedited, and the save writing the same `/Encrypt`. What was edited or added is encrypted
/// whatever its number.
pub(crate) fn stored_as_is(&self, num: u32) -> bool {
!self.encryption_changed && !self.is_edited(num) && self.encrypt_members.contains(&num)
}
/// Lift the restrictions of a document opened with its user password by entering the
@@ -268,8 +313,9 @@ impl Document {
/// always a full rewrite. Returns the handler (authenticated as owner).
pub fn set_encryption(&mut self, params: &pdfcraft_crypt::NewEncryption) -> Result<(), CosError> {
// The file identifier is part of the key; make sure it exists and keep it.
let id0 = match self.trailer.get(b"ID") {
Some(Object::Array(a)) if a.len() == 2 => a[0].as_string().map(|s| s.bytes.clone()).unwrap_or_default(),
let id = self.trailer.get(b"ID").map(|id| self.resolve(id));
let id0 = match id.as_deref() {
Some(Object::Array(a)) if a.len() == 2 => self.first_id(),
_ => {
let id = pdfcraft_crypt::file_id(&params.seed);
let s = Object::String(crate::PdfString { bytes: id.clone(), hex: true });
@@ -336,7 +382,9 @@ impl Document {
/// Decrypt a freshly parsed indirect object if the document is encrypted.
pub(super) fn decrypted(&self, id: ObjRef, o: Object) -> Object {
match &self.security {
Some(h) if Some(id.num) != self.encrypt_num => crate::security::transform(h, &o, id.num, id.generation, crate::security::Pass::Decrypt),
Some(h) if Some(id.num) != self.encrypt_num && !self.encrypt_members.contains(&id.num) => {
crate::security::transform(self, h, &o, id.num, id.generation, crate::security::Pass::Decrypt)
}
_ => o,
}
}
+87 -18
View File
@@ -163,11 +163,10 @@ impl ObjectReader {
// input bytes, which the document keeps anyway, so they don't count; decrypted
// streams and strings do. Checked after failed loads too: resolving a /Length may
// have cached large objects.
if let Ok(mut cache) = self.document.cache.lock() {
let data = &self.document.data;
if cache.len() >= Self::OBJECTS || cache.values().fold(0usize, |n, o| n.saturating_add(owned_bytes(o, data, 0))) > Self::STREAM_BYTES {
cache.clear();
}
if let Ok(mut cache) = self.document.cache.lock()
&& (cache.len() >= Self::OBJECTS || cache.owned() > Self::STREAM_BYTES)
{
cache.clear();
}
object
}
@@ -179,26 +178,96 @@ thread_local! {
pub(super) static SECTION_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
/// Nesting [`owned_bytes`] walks: past the parser's own nesting limit, so every parsed object
/// Parsed objects by number, each with what it holds ([`held_bytes`]) measured once, when it goes
/// in, and their sum kept beside them.
///
/// Both caches are bounded by those bytes. Summing them on every read walked every cached object
/// whole each time: a file whose page dictionaries carry kilobytes of private data (InDesign's
/// `/PieceInfo`) took seconds to open, almost all of it re-measuring objects already measured
/// (#5873).
#[derive(Default)]
pub(crate) struct ObjectCache {
entries: HashMap<u32, (Arc<Object>, usize)>,
owned: usize,
}
impl ObjectCache {
pub(crate) fn get(&self, num: &u32) -> Option<&Arc<Object>> {
self.entries.get(num).map(|(object, _)| object)
}
#[cfg(test)]
pub(crate) fn contains_key(&self, num: &u32) -> bool {
self.entries.contains_key(num)
}
/// Keep `object` as `num`, which holds `owned` bytes (what [`held_bytes`] says of it).
pub(crate) fn insert(&mut self, num: u32, object: Arc<Object>, owned: usize) {
if let Some((_, before)) = self.entries.insert(num, (object, owned)) {
self.owned = self.owned.saturating_sub(before);
}
self.owned = self.owned.saturating_add(owned);
}
pub(crate) fn len(&self) -> usize {
self.entries.len()
}
#[cfg(test)]
pub(crate) fn is_empty(&self) -> bool {
self.entries.is_empty()
}
/// The bytes the cached objects hold between them.
pub(crate) fn owned(&self) -> usize {
self.owned
}
pub(crate) fn clear(&mut self) {
self.entries.clear();
self.owned = 0;
}
pub(crate) fn retain(&mut self, mut keep: impl FnMut(&u32) -> bool) {
self.entries.retain(|num, _| keep(num));
self.owned = self.entries.values().fold(0usize, |n, (_, owned)| n.saturating_add(*owned));
}
#[cfg(test)]
pub(crate) fn values(&self) -> impl Iterator<Item = &Arc<Object>> {
self.entries.values().map(|(object, _)| object)
}
}
/// Nesting [`held_bytes`] walks: past the parser's own nesting limit, so every parsed object
/// is measured in full.
const OWNED_BYTES_DEPTH: usize = 256;
/// Bytes `object` holds of its own: string and stream data that is not a view into `data`
/// (the input file). An object nested deeper than [`OWNED_BYTES_DEPTH`] cannot be measured
/// and counts as too large to keep.
pub(super) fn owned_bytes(object: &Object, data: &Arc<Vec<u8>>, depth: usize) -> usize {
/// What keeping `object` parsed costs: string and stream data that is not a view into `data`
/// (the input file), and the parsed tree around it -- an [`Object`] per value and a key per
/// dictionary entry. An object nested deeper than [`OWNED_BYTES_DEPTH`] cannot be measured and
/// counts as too large to keep.
///
/// The tree counts. Measured by its strings and streams alone, a page dictionary carrying
/// InDesign's `/PieceInfo` -- thousands of small numeric arrays, parsed into tens of thousands of
/// values -- weighed nothing, so the caches kept a thousand of them: a 35 MB file held 1.5 GB
/// (#5873).
pub(super) fn held_bytes(object: &Object, data: &Arc<Vec<u8>>, depth: usize) -> usize {
if depth > OWNED_BYTES_DEPTH {
return usize::MAX;
}
let node = std::mem::size_of::<Object>();
// A key, its slot beside the value, and room in the index a large dictionary keeps.
let entry = |key: &[u8]| key.len().saturating_add(std::mem::size_of::<(crate::Name, Object)>()).saturating_add(16);
let dict =
|d: &crate::Dict, start: usize| d.iter().fold(start, |n, (k, v)| n.saturating_add(entry(k)).saturating_add(held_bytes(v, data, depth + 1)));
match object {
Object::String(s) => s.bytes.len(),
Object::Stream(s) => {
let own = if s.raw.shares(data) { 0 } else { s.raw.len() };
s.dict.iter().fold(own, |n, (_, v)| n.saturating_add(owned_bytes(v, data, depth + 1)))
}
Object::Array(a) => a.iter().fold(0usize, |n, v| n.saturating_add(owned_bytes(v, data, depth + 1))),
Object::Dict(d) => d.iter().fold(0usize, |n, (_, v)| n.saturating_add(owned_bytes(v, data, depth + 1))),
_ => 0,
Object::String(s) => node.saturating_add(s.bytes.len()),
Object::Name(n) => node.saturating_add(n.len()),
Object::Stream(s) => dict(&s.dict, node.saturating_add(if s.raw.shares(data) { 0 } else { s.raw.len() })),
Object::Array(a) => a.iter().fold(node, |n, v| n.saturating_add(held_bytes(v, data, depth + 1))),
Object::Dict(d) => dict(d, node),
_ => node,
}
}
+433 -5
View File
@@ -1,5 +1,147 @@
use super::*;
std::thread_local! {
/// How many times `Document::scan_for` read the file on this thread.
pub(super) static FILE_SCANS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
/// A scan that doesn't find an object isn't made again: each reads the whole file, and a file can
/// refer to such an object from every object it has.
#[test]
fn what_a_scan_of_the_file_did_not_find_is_remembered() {
let body = b"%PDF-1.7\n1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj\n2 0 obj << /Type /Pages /Kids [] /Count 0 >> endobj\n";
let mut out = body.to_vec();
let xref = out.len();
out.extend_from_slice(b"xref\n0 4\n0000000000 65535 f \n");
out.extend_from_slice(format!("{:010} 00000 n \n", 9).as_bytes());
out.extend_from_slice(format!("{:010} 00000 n \n", body.iter().position(|b| *b == b'\n').unwrap() + 49).as_bytes());
out.extend_from_slice(b"0000000001 00000 n \n");
out.extend_from_slice(format!("trailer << /Size 4 /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n").as_bytes());
let doc = Document::open(Arc::new(out)).unwrap();
FILE_SCANS.with(|scans| scans.set(0));
for _ in 0..5 {
assert!(doc.try_get(3).is_err());
}
assert_eq!(FILE_SCANS.with(std::cell::Cell::get), 1);
let clone = doc.clone();
assert!(clone.try_get(3).is_err());
assert_eq!(FILE_SCANS.with(std::cell::Cell::get), 1, "a clone has the same file");
}
/// An object can be nothing but a reference to another. A chain of them is followed, and one that
/// goes round ends in what isn't a dictionary or a name, without hanging.
#[test]
fn references_to_references_are_followed() {
let mut doc = Document::new_empty();
let name = doc.add(Object::name("Target"));
let one = doc.add(Object::Ref(name));
let two = doc.add(Object::Ref(one));
assert_eq!(doc.resolve(&Object::Ref(two)).as_name(), Some(b"Target".as_slice()));
let a = doc.add(Object::Null);
let b = doc.add(Object::Ref(a));
doc.set(a, Object::Ref(b));
assert_eq!(doc.resolve(&Object::Ref(a)).as_name(), None);
}
/// An object stream's `/DecodeParms` can be given by reference: without them a predictor isn't
/// undone, so its members were lost.
#[test]
fn an_object_stream_with_parameters_by_reference_is_read() {
let members = b"3 0 << /Hidden (yes) >>";
// PNG Sub, one row.
let mut rows = vec![1u8];
let mut before = 0u8;
for b in members {
rows.push(b.wrapping_sub(before));
before = *b;
}
let coded = pdfcraft_filters::encode_flate(&rows);
let mut out = b"%PDF-1.5\n".to_vec();
let mut offs = [0usize; 7];
let mut obj = |out: &mut Vec<u8>, n: usize, body: &[u8]| {
offs[n] = out.len();
out.extend_from_slice(format!("{n} 0 obj\n").as_bytes());
out.extend_from_slice(body);
out.extend_from_slice(b"\nendobj\n");
};
obj(&mut out, 1, b"<< /Type /Catalog /Pages 2 0 R >>");
obj(&mut out, 2, b"<< /Type /Pages /Kids [] /Count 0 /Extra 3 0 R >>");
let mut stm = format!("<< /Type /ObjStm /N 1 /First 4 /Filter /FlateDecode /DecodeParms 6 0 R /Length {} >>\nstream\n", coded.len()).into_bytes();
stm.extend_from_slice(&coded);
stm.extend_from_slice(b"\nendstream");
obj(&mut out, 4, &stm);
let data = [2u8, 0, 4, 0];
let mut xs = format!("<< /Type /XRef /Size 7 /W [1 2 1] /Index [3 1] /Length {} >>\nstream\n", data.len()).into_bytes();
xs.extend_from_slice(&data);
xs.extend_from_slice(b"\nendstream");
obj(&mut out, 5, &xs);
obj(&mut out, 6, format!("<< /Predictor 11 /Columns {} >>", members.len()).as_bytes());
let table = out.len();
out.extend_from_slice(b"xref\n0 7\n0000000000 65535 f \n");
for (n, off) in offs.iter().enumerate().skip(1) {
let line = if n == 3 { "0000000000 65535 f \n".to_string() } else { format!("{off:010} 00000 n \n") };
out.extend_from_slice(line.as_bytes());
}
out.extend_from_slice(format!("trailer << /Size 7 /Root 1 0 R /XRefStm {} >>\nstartxref\n{table}\n%%EOF\n", offs[5]).as_bytes());
let doc = Document::open(Arc::new(out)).unwrap();
let hidden = doc.get(ObjRef::new(3, 0));
assert_eq!(hidden.as_dict().and_then(|d| d.get(b"Hidden")).and_then(Object::as_string).map(|s| s.bytes.clone()), Some(b"yes".to_vec()));
}
/// Each entry of an `/Encrypt` dictionary, and of a crypt filter in it, reads the same by reference.
/// Read as absent, `/StmF` or `/CFM` was `/Identity`, so a whole file's streams stayed ciphertext.
#[test]
fn encrypt_dictionary_entries_read_the_same_by_reference() {
let string = |s: &str| Object::String(crate::PdfString::text(s));
let mut filter = Dict::new();
filter.set(b"CFM".to_vec(), Object::name("AESV2"));
filter.set(b"Length".to_vec(), Object::Int(5));
let cf = |filter: Dict| {
let mut cf = Dict::new();
cf.set(b"StdCF".to_vec(), Object::Dict(filter));
cf.set(b"Other".to_vec(), Object::Dict(Dict::new()));
Object::Dict(cf)
};
let mut d = Dict::new();
let entries = [
("Filter", Object::name("Standard")),
("V", Object::Int(4)),
("R", Object::Int(4)),
("Length", Object::Int(128)),
("P", Object::Int(-44)),
("O", string("owner")),
("U", string("user")),
("EncryptMetadata", Object::Bool(false)),
("CF", cf(filter.clone())),
("StmF", Object::name("StdCF")),
("StrF", Object::name("Other")),
("EFF", Object::name("StdCF")),
];
for (key, value) in &entries {
d.set(key.as_bytes().to_vec(), value.clone());
}
let mut doc = Document::new_empty();
let direct = crate::security::encrypt_dict(&doc, &d);
assert_eq!((direct.stm_f.as_slice(), direct.str_f.as_slice(), direct.ef_f.as_slice()), (&b"StdCF"[..], &b"Other"[..], &b"StdCF"[..]));
assert_eq!(direct.length_bits, 40, "the filter's own length, in bytes");
assert!(!direct.encrypt_metadata);
assert_eq!(direct.crypt_filters.iter().filter(|(_, m)| *m == pdfcraft_crypt::Method::Aes128).count(), 1);
for (key, value) in &entries {
let mut one = d.clone();
let r = doc.add(value.clone());
one.set(key.as_bytes().to_vec(), Object::Ref(r));
assert_eq!(crate::security::encrypt_dict(&doc, &one), direct, "/{key}");
}
for key in ["CFM", "Length"] {
let mut by_reference = filter.clone();
let r = doc.add(filter.get(key.as_bytes()).unwrap().clone());
by_reference.set(key.as_bytes().to_vec(), Object::Ref(r));
let mut one = d.clone();
one.set(b"CF".to_vec(), cf(by_reference));
assert_eq!(crate::security::encrypt_dict(&doc, &one), direct, "/{key} in the filter");
}
}
/// /DecodeParms given by reference, whole, as array entries or as the numbers inside, are read
/// once made direct: here a Flate predictor, which the stream alone doesn't see. Only the entries the filters use are
/// resolved, and nothing is for a chain longer than a decoder takes.
@@ -173,6 +315,217 @@ fn fax_images_decode_with_their_parameters() {
assert!(behind(&[Object::Int(5), fax], &[null, own], coded.clone()).is_err(), "a /Filter entry that isn't a name");
}
/// Images that share a `/JBIG2Globals` stream of the file decode it once a document: it is kept
/// for the next, in every clone. A globals stream edited since is read afresh (the kept one is the
/// file's), and objects added in memory aren't kept.
#[test]
fn shared_jbig2_globals_are_read_once() {
let bits = [0b1111_1000, 0, 0b1111_1000, 0, 0b1111_1000, 0];
let coded = pdfcraft_filters::encode_jbig2_generic(&bits, 10, 3).unwrap();
let mut doc = Document::new_empty();
let mut d = Dict::new();
d.set(b"Filter".to_vec(), Object::name("FlateDecode"));
let skipped = [0, 0, 0, 0, 0x3E, 0, 0, 0, 0, 0, 4, 0, 0, 0, 1];
let globals = doc.add(Object::Stream(Stream::from_raw(d, pdfcraft_filters::encode_flate(&skipped))));
let image = |doc: &mut Document| {
let mut d = Dict::new();
d.set(b"Width".to_vec(), Object::Int(10));
d.set(b"Height".to_vec(), Object::Int(3));
d.set(b"Filter".to_vec(), Object::name("JBIG2Decode"));
let mut parms = Dict::new();
parms.set(b"JBIG2Globals".to_vec(), Object::Ref(globals));
d.set(b"DecodeParms".to_vec(), Object::Dict(parms));
doc.add(Object::Stream(Stream::from_raw(d, coded.clone())))
};
let (a, b) = (image(&mut doc), image(&mut doc));
let stream = |doc: &Document, r: ObjRef| match &*doc.get(r) {
Object::Stream(s) => s.clone(),
_ => panic!("not a stream"),
};
assert_eq!(doc.decoded_image(&stream(&doc, a)).unwrap(), bits);
assert!(doc.jbig2_globals.lock().unwrap().is_empty(), "an object added in memory isn't kept");
// The same objects read from a file, the catalog holding on to the images (a full save may
// number them anew).
let root = doc.root().unwrap();
doc.update_dict(root, |c| c.set(b"Images".to_vec(), Object::Array(vec![Object::Ref(a), Object::Ref(b)]))).unwrap();
let file = crate::write_full(&doc, &crate::SaveOptions::default()).unwrap();
let mut doc = Document::open(Arc::new(file)).unwrap();
let images = doc.get(doc.root().unwrap()).as_dict().unwrap().get(b"Images").unwrap().as_array().unwrap().clone();
let (a, b) = (images[0].as_ref().unwrap(), images[1].as_ref().unwrap());
let parms = stream(&doc, a).dict.get(b"DecodeParms").unwrap().as_dict().unwrap().clone();
let globals = parms.reference(b"JBIG2Globals").unwrap();
let clone = doc.clone();
assert_eq!(doc.decoded_image(&stream(&doc, a)).unwrap(), bits);
assert_eq!(doc.jbig2_globals.lock().unwrap().len(), 1, "kept");
let kept = doc.jbig2_globals.lock().unwrap()[&globals.num].clone();
assert_eq!(clone.decoded_image(&stream(&clone, b)).unwrap(), bits, "the clone's other image");
let shared = clone.jbig2_globals.lock().unwrap()[&globals.num].clone();
assert!(Arc::ptr_eq(&kept, &shared), "the clone uses the one kept, not a second decode");
doc.set(globals, Object::Stream(Stream::from_raw(Dict::new(), b"not JBIG2".to_vec())));
assert!(doc.decoded_image(&stream(&doc, b)).is_err(), "the edited globals are read afresh");
assert_eq!(clone.decoded_image(&stream(&clone, b)).unwrap(), bits, "the clone keeps the file's");
}
/// A JBIG2 image's size is read as given directly, as every caller reads it first, and an image
/// with neither is an error, not an image of no rows.
#[test]
fn a_jbig2_image_needs_its_size_given_directly() {
let coded = pdfcraft_filters::encode_jbig2_generic(&[0xFF, 0xFF], 8, 2).unwrap();
let mut doc = Document::new_empty();
let size = doc.add(Object::Int(2));
let image = |width: Object, height: Object| {
let mut d = Dict::new();
d.set(b"Width".to_vec(), width);
d.set(b"Height".to_vec(), height);
d.set(b"Filter".to_vec(), Object::name("JBIG2Decode"));
doc.decoded_image(&Stream::from_raw(d, coded.clone()))
};
assert!(image(Object::Int(8), Object::Int(2)).is_ok());
assert!(image(Object::Ref(size), Object::Int(2)).is_err(), "/Width by reference");
assert!(image(Object::Int(8), Object::Ref(size)).is_err(), "/Height by reference");
}
/// A document that kept globals of 64 MiB keeps no more, and the images past that still read:
/// three streams of 22 MiB, shared by three images, are two kept and one decoded each time.
#[test]
fn kept_jbig2_globals_are_bounded_in_total() {
let bits = [0b1111_1000, 0, 0b1111_1000, 0, 0b1111_1000, 0];
let coded = pdfcraft_filters::encode_jbig2_generic(&bits, 10, 3).unwrap();
let length = 22 * 1024 * 1024;
let mut skipped = vec![0, 0, 0, 0, 0x3E, 0, 0];
skipped.extend_from_slice(&u32::try_from(4 + length).unwrap().to_be_bytes());
skipped.extend_from_slice(&[0, 0, 0, 1]);
skipped.resize(skipped.len() + length, 0);
let mut doc = Document::new_empty();
let mut images = Vec::new();
for _ in 0..3 {
let mut d = Dict::new();
d.set(b"Filter".to_vec(), Object::name("FlateDecode"));
let globals = doc.add(Object::Stream(Stream::from_raw(d, pdfcraft_filters::encode_flate(&skipped))));
let mut d = Dict::new();
d.set(b"Width".to_vec(), Object::Int(10));
d.set(b"Height".to_vec(), Object::Int(3));
d.set(b"Filter".to_vec(), Object::name("JBIG2Decode"));
let mut parms = Dict::new();
parms.set(b"JBIG2Globals".to_vec(), Object::Ref(globals));
d.set(b"DecodeParms".to_vec(), Object::Dict(parms));
images.push(Object::Ref(doc.add(Object::Stream(Stream::from_raw(d, coded.clone())))));
}
let root = doc.root().unwrap();
doc.update_dict(root, |c| c.set(b"Images".to_vec(), Object::Array(images))).unwrap();
let doc = Document::open(Arc::new(crate::write_full(&doc, &crate::SaveOptions::default()).unwrap())).unwrap();
let images = doc.get(doc.root().unwrap()).as_dict().unwrap().get(b"Images").unwrap().as_array().unwrap().clone();
for image in &images {
let Object::Stream(s) = &*doc.get(image.as_ref().unwrap()) else { panic!("not a stream") };
assert_eq!(doc.decoded_image(s).unwrap(), bits, "every image reads");
}
let kept = doc.jbig2_globals.lock().unwrap();
assert_eq!(kept.len(), 2, "two fit in 64 MiB, a third doesn't");
assert!(kept.values().all(|g| g.capacity() == g.len()), "what is kept holds no more than it counts");
}
/// Globals whose `/DecodeParms` are given by reference aren't kept: that's another object, so
/// editing it changes what they decode to while the stream itself, the key kept by, stays the same.
#[test]
fn jbig2_globals_with_parameters_by_reference_are_read_afresh() {
let bits = [0b1111_1000, 0, 0b1111_1000, 0, 0b1111_1000, 0];
let coded = pdfcraft_filters::encode_jbig2_generic(&bits, 10, 3).unwrap();
let skipped = [0, 0, 0, 0, 0x3E, 0, 0, 0, 0, 0, 4, 0, 0, 0, 1];
let params = pdfcraft_filters::Params { predictor: 12, colors: 1, bits_per_component: 8, columns: 15, early_change: 1 };
let mut doc = Document::new_empty();
let mut parms = Dict::new();
parms.set(b"Predictor".to_vec(), Object::Int(12));
parms.set(b"Columns".to_vec(), Object::Int(15));
let parms = doc.add(Object::Dict(parms));
let mut d = Dict::new();
d.set(b"Filter".to_vec(), Object::name("FlateDecode"));
d.set(b"DecodeParms".to_vec(), Object::Ref(parms));
let predicted = pdfcraft_filters::encode(&pdfcraft_filters::Filter::Flate, &params, &skipped).unwrap();
let globals = doc.add(Object::Stream(Stream::from_raw(d, predicted)));
let mut d = Dict::new();
d.set(b"Width".to_vec(), Object::Int(10));
d.set(b"Height".to_vec(), Object::Int(3));
d.set(b"Filter".to_vec(), Object::name("JBIG2Decode"));
let mut image_parms = Dict::new();
image_parms.set(b"JBIG2Globals".to_vec(), Object::Ref(globals));
d.set(b"DecodeParms".to_vec(), Object::Dict(image_parms));
let image = doc.add(Object::Stream(Stream::from_raw(d, coded)));
let root = doc.root().unwrap();
doc.update_dict(root, |c| c.set(b"Image".to_vec(), Object::Ref(image))).unwrap();
let mut doc = Document::open(Arc::new(crate::write_full(&doc, &crate::SaveOptions::default()).unwrap())).unwrap();
let image = doc.get(doc.root().unwrap()).as_dict().unwrap().reference(b"Image").unwrap();
let stream = |doc: &Document| match &*doc.get(image) {
Object::Stream(s) => s.clone(),
_ => panic!("not a stream"),
};
assert_eq!(doc.decoded_image(&stream(&doc)).unwrap(), bits);
assert!(doc.jbig2_globals.lock().unwrap().is_empty(), "not kept");
let globals = stream(&doc).dict.get(b"DecodeParms").unwrap().as_dict().unwrap().reference(b"JBIG2Globals").unwrap();
let Object::Stream(g) = &*doc.get(globals) else { panic!("not a stream") };
let parms = g.dict.reference(b"DecodeParms").unwrap();
doc.set(parms, Object::Dict(Dict::new()));
assert!(doc.decoded_image(&stream(&doc)).is_err(), "without the predictor they read otherwise");
}
/// A JBIG2 image reads through its decoder, behind other filters too, with the `/JBIG2Globals` of
/// its own `/DecodeParms` (a dictionary or its place in an array, /Crypt counting, by reference
/// too): globals that can't be read are an error, and ones at another filter's place aren't its
/// own, nor are those of a lone dictionary when other filters come first. Its page has to be its
/// /Width × /Height, and fit the bound.
#[test]
fn jbig2_images_decode_with_their_globals() {
// 10 × 3: the first five samples of each row white, the rest black.
let bits = [0b1111_1000, 0, 0b1111_1000, 0, 0b1111_1000, 0];
let coded = pdfcraft_filters::encode_jbig2_generic(&bits, 10, 3).unwrap();
let hex = coded.iter().map(|b| format!("{b:02x}")).chain([">".to_string()]).collect::<String>().into_bytes();
let mut doc = Document::new_empty();
// An extension segment (ISO/IEC 14492 7.4.14), which a decoder skips, Flate-encoded; and data
// that isn't JBIG2.
let globals = |doc: &mut Document, data: &[u8]| {
let mut d = Dict::new();
d.set(b"Filter".to_vec(), Object::name("FlateDecode"));
let globals = doc.add(Object::Stream(Stream::from_raw(d, pdfcraft_filters::encode_flate(data))));
let mut parms = Dict::new();
parms.set(b"JBIG2Globals".to_vec(), Object::Ref(globals));
Object::Dict(parms)
};
let (good, bad) = (globals(&mut doc, &[0, 0, 0, 0, 0x3E, 0, 0, 0, 0, 0, 4, 0, 0, 0, 1]), globals(&mut doc, b"not JBIG2"));
let indirect = Object::Ref(doc.add(bad.clone()));
let image = |filters: &[&str], parms: Option<Object>, data: &[u8], (width, height): (i64, i64), max: usize| {
let mut d = Dict::new();
d.set(b"Width".to_vec(), Object::Int(width));
d.set(b"Height".to_vec(), Object::Int(height));
d.set(b"Filter".to_vec(), Object::Array(filters.iter().map(|f| Object::name(f)).collect()));
if let Some(p) = parms {
d.set(b"DecodeParms".to_vec(), p);
}
doc.decoded_image_within(&Stream::from_raw(d, data.to_vec()), max)
};
let jbig2 = ["JBIG2Decode"];
let full = (10, 3);
assert_eq!(image(&jbig2, None, &coded, full, MAX_DECODED).unwrap(), bits);
assert_eq!(image(&jbig2, Some(good.clone()), &coded, full, MAX_DECODED).unwrap(), bits, "globals it skips");
for parms in [bad.clone(), Object::Array(vec![bad.clone()]), indirect.clone(), Object::Array(vec![indirect])] {
let e = image(&jbig2, Some(parms.clone()), &coded, full, MAX_DECODED).unwrap_err();
assert!(e.to_string().contains("JBIG2"), "{parms:?}: {e}");
}
let behind = ["ASCIIHexDecode", "JBIG2Decode"];
assert_eq!(image(&behind, None, &hex, full, MAX_DECODED).unwrap(), bits, "behind ASCIIHexDecode");
assert!(image(&behind, Some(Object::Array(vec![Object::Null, bad.clone()])), &hex, full, MAX_DECODED).is_err(), "its own globals");
assert_eq!(image(&behind, Some(Object::Array(vec![bad.clone(), Object::Null])), &hex, full, MAX_DECODED).unwrap(), bits, "another's");
assert_eq!(image(&behind, Some(bad.clone()), &hex, full, MAX_DECODED).unwrap(), bits, "a lone dictionary, the first filter's");
let after_crypt = ["Crypt", "JBIG2Decode"];
assert!(image(&after_crypt, Some(Object::Array(vec![Object::Null, bad.clone()])), &coded, full, MAX_DECODED).is_err(), "after /Crypt");
assert_eq!(image(&after_crypt, Some(Object::Array(vec![bad, Object::Null])), &coded, full, MAX_DECODED).unwrap(), bits, "/Crypt's");
for size in [(11, 3), (9, 3), (10, 2), (10, 4)] {
assert!(image(&jbig2, None, &coded, size, MAX_DECODED).is_err(), "a page other than {size:?}");
}
assert_eq!(image(&jbig2, None, &coded, full, 6).unwrap(), bits, "the page within the bound");
assert!(image(&jbig2, None, &coded, full, 5).is_err(), "the page past the bound");
}
#[test]
fn a_missing_file_id_is_derived_from_the_encryption_seed() {
let mut doc = Document::new_empty();
@@ -898,7 +1251,8 @@ fn temporary_reader_keeps_file_views_and_evicts_data_of_its_own() {
// Data of its own (decrypted streams, strings) counts: past the budget the cache is
// cleared after the next read, including a failed one.
let owned = Object::Stream(crate::Stream::from_raw(Dict::new(), vec![b'y'; ObjectReader::STREAM_BYTES + 1]));
reader.document.cache.lock().unwrap().insert(3, Arc::new(owned));
let size = held_bytes(&owned, &reader.document.data, 0);
reader.document.cache.lock().unwrap().insert(3, Arc::new(owned), size);
assert_eq!(*reader.get(ObjRef::new(99, 0)), Object::Null);
assert!(reader.document.cache.lock().unwrap().is_empty(), "owned data over budget is evicted");
}
@@ -981,13 +1335,14 @@ fn editor_cache_counts_deeply_nested_strings() {
source.update_dict(source.root().unwrap(), |d| d.set(b"Extension".to_vec(), Object::Array(objects))).unwrap();
let bytes = Arc::new(crate::write_full(&source, &crate::SaveOptions::default()).unwrap());
let doc = Document::open(bytes).unwrap();
assert_eq!(owned_bytes(&nested, &doc.data, 0), 1 << 20);
let held = held_bytes(&nested, &doc.data, 0);
assert!((1 << 20..(1 << 20) + 4096).contains(&held), "the string and a little tree: {held}");
let root = doc.get(doc.root().unwrap());
for reference in root.as_dict().unwrap().get(b"Extension").unwrap().as_array().unwrap() {
let Object::Ref(reference) = reference else { panic!("indirect object") };
drop(doc.get(*reference));
let cache = doc.cache.lock().unwrap();
let owned = cache.values().fold(0usize, |n, o| n.saturating_add(owned_bytes(o, &doc.data, 0)));
let owned = cache.values().fold(0usize, |n, o| n.saturating_add(held_bytes(o, &doc.data, 0)));
let strings = cache.values().filter(|o| o.as_array().is_some()).count();
assert!(strings << 20 <= Document::EDITOR_CACHE_BYTES + (1 << 20), "{strings} MiB strings cached, {owned} bytes counted");
}
@@ -1029,8 +1384,8 @@ fn editor_cache_stays_bounded() {
#[test]
fn editor_cache_byte_bound_fires() {
// 40 × 1 MB strings: far below the count cap, above the 32 MB byte budget. Each
// newcomer exceeds EDITOR_LARGE_OBJECT, so every insert takes a full accounting pass.
// 40 × 1 MB strings: far below the count cap, above the 32 MB byte budget, which is
// checked after every insertion.
let mut source = Document::new_empty();
let objects: Vec<_> = (0..40)
.map(|i| {
@@ -1490,3 +1845,76 @@ fn a_stream_whose_length_is_itself_and_never_ends_loads_quickly() {
});
rx.recv_timeout(std::time::Duration::from_secs(20)).expect("loading must not retry exponentially");
}
#[test]
fn a_restored_revision_keeps_what_the_saved_file_held_in_object_streams() {
// The earlier revision: an empty document read back from a file whose catalog and pages
// sit in an object stream.
let earlier = Document::open(Arc::new(crate::write_full(&Document::new_empty(), &crate::SaveOptions::default()).unwrap())).unwrap();
// The saved revision adds an object the catalog links to, so a full save numbers its objects
// anew; an undo then returns to the earlier graph.
let mut later = earlier.clone();
let extra = later.add(Object::Int(7));
let root = later.root().unwrap();
later.update_dict(root, |c| c.set(b"Extra".to_vec(), Object::Ref(extra))).unwrap();
let saved = crate::write_full(&later, &crate::SaveOptions::default()).unwrap();
let mut base = Document::open(Arc::new(saved)).unwrap();
assert!(
base.object_numbers().iter().any(|&n| matches!(base.xref_entry(n), Some(XrefEntry::InStream { .. }))),
"the saved file holds objects in a stream"
);
base.overlay_changes_from(&earlier).unwrap();
let file = crate::write_incremental(&base, &crate::SaveOptions::default()).unwrap();
let reread = Document::open(Arc::new(file)).unwrap();
let catalog = reread.get(reread.root().unwrap()).as_dict().unwrap().clone();
assert!(catalog.get(b"Extra").is_none(), "the restored catalog");
let pages = reread.resolve(catalog.get(b"Pages").unwrap());
assert_eq!(pages.as_dict().and_then(|d| d.name(b"Type")), Some(&b"Pages"[..]), "the pages survive: {pages:?}");
}
/// The cache keeps the sum of what its objects hold as they come and go, so neither reader has
/// to measure the cache again on every read (#5873).
#[test]
fn the_object_cache_keeps_its_total_as_objects_come_and_go() {
let data = Arc::new(Vec::new());
let one = Arc::new(Object::String(crate::PdfString::literal(vec![b'x'; 100])));
let two = Arc::new(Object::Array(vec![Object::Int(1); 10]));
let (a, b) = (held_bytes(&one, &data, 0), held_bytes(&two, &data, 0));
let mut cache = super::state::ObjectCache::default();
cache.insert(1, one.clone(), a);
cache.insert(2, two, b);
assert_eq!(cache.owned(), a + b);
cache.insert(2, one, a);
assert_eq!(cache.owned(), a + a, "a replaced object no longer counts");
cache.retain(|n| *n == 1);
assert_eq!((cache.len(), cache.owned()), (1, a));
cache.clear();
assert_eq!((cache.len(), cache.owned()), (0, 0));
}
/// A dictionary of numbers owns no string or stream bytes, but parsed it is tens of thousands
/// of values: InDesign's per-page `/PieceInfo`. Counting only strings and streams, the editing
/// cache kept a thousand such pages and a 35 MB book held 1.5 GB (#5873). What the parsed tree
/// holds counts now, so the byte budget bounds them.
#[test]
fn the_editor_cache_charges_a_dictionary_for_the_values_it_holds() {
let entries: String = (0..2000).map(|i| format!("/{i}[{i} 141 3 116.22 -375.993 1.0]")).collect();
let dict = format!("<< /PieceInfo << /InDesign << /Map << {entries} >> >> >> >>");
let count = 300;
let refs: String = (0..count).map(|i| format!("{} 0 R ", i + 2)).collect();
let mut bodies = vec![format!("<< /Type /Catalog /Extension [{refs}] >>")];
bodies.extend((0..count).map(|_| dict.clone()));
let bodies: Vec<&str> = bodies.iter().map(String::as_str).collect();
let doc = Document::open(Arc::new(build(&bodies, "/Root 1 0 R"))).unwrap();
let one = doc.get(crate::ObjRef::new(2, 0));
let held = held_bytes(&one, &doc.data, 0);
assert!(held > 2000 * std::mem::size_of::<Object>(), "the parsed tree counts: {held} bytes");
for i in 0..count {
drop(doc.get(crate::ObjRef::new(i as u32 + 2, 0)));
}
let cache = doc.cache.lock().unwrap();
assert!(cache.owned() <= Document::EDITOR_CACHE_BYTES, "{} bytes held", cache.owned());
assert!(cache.len() < count, "the byte budget evicted some, below the count cap: {} kept", cache.len());
let sum = cache.values().fold(0usize, |n, o| n.saturating_add(held_bytes(o, &doc.data, 0)));
assert_eq!(cache.owned(), sum, "the kept total is the cache's own");
}
+2 -2
View File
@@ -22,10 +22,10 @@ mod parser;
mod security;
mod writer;
pub use budget::{DecodeBudget, MAX_PAGE_DECODED, MAX_PAGE_FORMS};
pub use budget::{DecodeBudget, ImageBudget, MAX_PAGE_DECODED, MAX_PAGE_FORMS, MAX_REDACTED_IMAGE_PIXELS};
pub use bytes::Bytes;
pub use document::{Document, ReadState, Revision, SourceIdentity, XrefEntry};
pub use object::{Dict, MAX_DECODED, Name, ObjRef, Object, PdfString, Stream};
pub use object::{Dict, MAX_DECODED, MAX_JBIG2_GLOBALS, Name, ObjRef, Object, PdfString, Stream};
pub use parser::{Lexer, is_whitespace, parse_indirect};
pub use pdfcraft_crypt::{
Algorithm, Auth, Method as CryptMethod, NewEncryption, Permissions, SecurityHandler, effective_password, pdfdoc_byte, pdfdoc_char,
+14
View File
@@ -213,6 +213,12 @@ pub struct Stream {
/// Upper bound for a single decoded stream (decompression-bomb defence).
pub const MAX_DECODED: usize = 1 << 30;
/// The most an image's `/JBIG2Globals` stream may decode to: the symbol and pattern dictionaries an
/// encoder shares between pages, themselves coded, so far less than any stream may decode to
/// ([`MAX_DECODED`]). They are decoded before the image's JBIG2 page is read, so the page's size
/// can't bound them: they have a limit of their own.
pub const MAX_JBIG2_GLOBALS: usize = 32 << 20;
impl Stream {
/// A new stream from already-encoded bytes (`/Length` is set at write time).
pub fn from_raw(dict: Dict, raw: Vec<u8>) -> Self {
@@ -300,6 +306,14 @@ impl Stream {
self.decode_chain(max, decode)
}
/// [`Stream::decoded_within`] spending from `work`, what an operation may still do across a
/// document's images ([`pdfcraft_filters::decode_tolerant_within`]).
pub(crate) fn decoded_spending(&self, max: usize, work: &mut u64) -> Result<Vec<u8>, CosError> {
let filter = |e: pdfcraft_filters::FilterError| CosError::Filter(e.to_string());
let chain = self.readable_filters().map_err(filter)?;
pdfcraft_filters::decode_tolerant_within(&chain, &self.raw, max.min(MAX_DECODED), work).map_err(filter)
}
/// The stream decoded through its filters by `decode`, or copied when it has none, within
/// `max` and [`MAX_DECODED`].
fn decode_chain(
+14 -1
View File
@@ -341,7 +341,11 @@ impl<'a> Lexer<'a> {
let s = std::str::from_utf8(tok).map_err(|_| self.err("bad number"))?;
if s.contains('.') {
// Tolerate forms like "--5", "5-" or "1.2.3" by parsing the longest valid prefix.
let cleaned: String = s.trim_start_matches('+').replacen("--", "-", 1);
// Only a doubled sign needs a cleaned copy: a page of InDesign `/PieceInfo` is
// thousands of plain reals, and building a copy and a substring search for each
// was a large part of reading one (#5873).
let t = s.trim_start_matches('+');
let cleaned = if t.as_bytes().windows(2).any(|w| w == b"--") { std::borrow::Cow::Owned(t.replacen("--", "-", 1)) } else { t.into() };
let v = cleaned.get(..real_prefix_len(cleaned.as_bytes())).and_then(|p| parse_counted::<f64>(p).ok());
return Ok(Object::Real(v.unwrap_or(0.0)));
}
@@ -707,4 +711,13 @@ mod tests {
let mut lx = Lexer::new(two.as_bytes(), 0);
assert!(lx.object().is_ok() && lx.object().is_ok());
}
/// A plain real is read without a cleaned copy of its token; the forms that need one read
/// as they did (#5873).
#[test]
fn reals_read_the_same_with_and_without_a_doubled_sign() {
for (token, want) in [("1.5", 1.5), ("-375.993", -375.993), ("+2.25", 2.25), ("--5.5", -5.5), ("1.2.3", 1.2), ("-.5", -0.5), ("0.0", 0.0)] {
assert_eq!(Lexer::new(token.as_bytes(), 0).object().unwrap(), Object::Real(want), "{token}");
}
}
}
+214 -80
View File
@@ -7,10 +7,69 @@
//! false. Streams naming a crypt filter (`/Crypt` in `/Filter`) use that filter; embedded files
//! use `/EFF`.
use pdfcraft_crypt::{EncryptDict, Method, SecurityHandler, StreamKind};
use std::cell::Cell;
use pdfcraft_crypt::{EncryptDict, Method, SecurityHandler, StreamKind};
use pdfcraft_filters::MAX_CHAIN;
use crate::document::Held;
use crate::{Dict, Document, Object, PdfString, Stream};
/// How many references one read or write of an object may follow, with all that it loads on the
/// way. How an object is treated can be given by reference, and what that loads can do the same: a
/// file could make one read a tree of them, each object read again once the cache has let it go.
/// An object takes a few of these, and two dozen if every part of it is given by reference; past
/// this they read as absent. The parameters of an object stream, read together, count as one.
const MAX_FOLLOWED: u32 = 32;
std::thread_local! {
/// How many [`FollowScope`]s this thread is inside.
static SCOPES: Cell<u32> = const { Cell::new(0) };
/// The references followed in the outermost of them.
static FOLLOWED: Cell<u32> = const { Cell::new(0) };
/// The references refused in the outermost of them, past [`MAX_FOLLOWED`].
static REFUSED: Cell<u32> = const { Cell::new(0) };
}
/// One read or write of an object, with everything it loads on the way: what [`MAX_FOLLOWED`] counts.
pub(crate) struct FollowScope;
impl FollowScope {
pub(crate) fn enter() -> Self {
if SCOPES.replace(SCOPES.get().saturating_add(1)) == 0 {
FOLLOWED.set(0);
REFUSED.set(0);
}
FollowScope
}
}
impl Drop for FollowScope {
fn drop(&mut self) {
SCOPES.set(SCOPES.get().saturating_sub(1));
}
}
/// What `f` gives, counted against [`MAX_FOLLOWED`], or `spent` past it. Called inside a
/// [`FollowScope`], which is what starts the count again.
pub(crate) fn following<T>(spent: T, f: impl FnOnce() -> T) -> T {
if FOLLOWED.get() >= MAX_FOLLOWED {
REFUSED.set(REFUSED.get().saturating_add(1));
return spent;
}
FOLLOWED.set(FOLLOWED.get() + 1);
f()
}
/// `o`, or the object it refers to, for what decides how a stream or dictionary is treated. Past
/// [`MAX_FOLLOWED`] a reference reads as absent.
fn followed<'o>(doc: &Document, o: &'o Object) -> Held<'o> {
match o {
Object::Ref(_) => following(Held::Direct(&Object::Null), || doc.held(o)),
o => Held::Direct(o),
}
}
fn bytes_of(doc: &Document, d: &Dict, key: &[u8]) -> Vec<u8> {
d.get(key).map(|v| doc.resolve(v)).and_then(|v| v.as_string().map(|s| s.bytes.clone())).unwrap_or_default()
}
@@ -18,12 +77,12 @@ fn bytes_of(doc: &Document, d: &Dict, key: &[u8]) -> Vec<u8> {
/// Read the handler parameters from an `/Encrypt` dictionary.
pub(crate) fn encrypt_dict(doc: &Document, d: &Dict) -> EncryptDict {
let int = |k: &[u8], default: i64| d.get(k).map(|v| doc.resolve(v)).and_then(|v| v.as_int()).unwrap_or(default);
let name = |k: &[u8]| d.get(k).and_then(|v| v.as_name()).map(|n| n.to_vec()).unwrap_or_else(|| b"Identity".to_vec());
let name = |d: &Dict, k: &[u8]| d.get(k).and_then(|v| doc.resolve(v).as_name().map(<[u8]>::to_vec));
let mut crypt_filters = Vec::new();
if let Some(cf) = d.get(b"CF").map(|c| doc.resolve(c)).and_then(|c| c.as_dict().cloned()) {
for (k, v) in cf.iter() {
let Some(f) = doc.resolve(v).as_dict().cloned() else { continue };
let method = match f.name(b"CFM") {
let method = match name(&f, b"CFM").as_deref() {
Some(b"V2") => Method::Rc4,
Some(b"AESV2") => Method::Aes128,
Some(b"AESV3") => Method::Aes256,
@@ -40,7 +99,8 @@ pub(crate) fn encrypt_dict(doc: &Document, d: &Dict) -> EncryptDict {
.get(b"CF")
.map(|c| doc.resolve(c))
.and_then(|c| c.as_dict().and_then(|c| c.get(b"StdCF").map(|f| doc.resolve(f))))
.and_then(|f| f.as_dict().and_then(|f| f.int(b"Length")))
.and_then(|f| f.as_dict().and_then(|f| f.get(b"Length").map(|n| doc.resolve(n))))
.and_then(|n| n.as_int())
.filter(|n| *n > 0);
let length_bits = match (v, cf_len) {
(5.., _) => 256,
@@ -50,7 +110,7 @@ pub(crate) fn encrypt_dict(doc: &Document, d: &Dict) -> EncryptDict {
_ => int(b"Length", 40),
};
EncryptDict {
filter: d.name(b"Filter").map(|n| n.to_vec()).unwrap_or_default(),
filter: name(d, b"Filter").unwrap_or_default(),
v,
r: int(b"R", 0),
length_bits,
@@ -60,28 +120,46 @@ pub(crate) fn encrypt_dict(doc: &Document, d: &Dict) -> EncryptDict {
ue: bytes_of(doc, d, b"UE"),
perms: bytes_of(doc, d, b"Perms"),
p: int(b"P", -1) as i32,
encrypt_metadata: !matches!(d.get(b"EncryptMetadata"), Some(Object::Bool(false))),
encrypt_metadata: !matches!(d.get(b"EncryptMetadata").map(|v| doc.resolve(v)).as_deref(), Some(Object::Bool(false))),
crypt_filters,
stm_f: name(b"StmF"),
str_f: name(b"StrF"),
ef_f: d.get(b"EFF").and_then(|v| v.as_name()).map(|n| n.to_vec()).unwrap_or_default(),
stm_f: name(d, b"StmF").unwrap_or_else(|| b"Identity".to_vec()),
str_f: name(d, b"StrF").unwrap_or_else(|| b"Identity".to_vec()),
ef_f: name(d, b"EFF").unwrap_or_default(),
}
}
/// The crypt filter a stream names in its `/Filter` chain (`/Crypt` + `/DecodeParms /Name`).
fn named_crypt_filter(dict: &Dict) -> Option<Vec<u8>> {
let names: Vec<&[u8]> = match dict.get(b"Filter") {
Some(Object::Name(n)) => vec![n],
Some(Object::Array(a)) => a.iter().filter_map(Object::as_name).collect(),
/// Whether `f`, an entry of a `/Filter` chain or its only filter, is `/Crypt`.
fn is_crypt(doc: &Document, f: &Object) -> bool {
followed(doc, f).as_name() == Some(b"Crypt")
}
/// The crypt filter a stream names in its `/Filter` chain (`/Crypt` + `/DecodeParms /Name`), each
/// given directly or by reference, in an array or not. A chain longer than any decoder takes names
/// none: nothing can read that stream anyway, and every stream of a file can share one long array.
/// A `/Name` that reads as absent means `/Identity`, unless a reference on the way to it was refused
/// (see [`MAX_FOLLOWED`]): that says nothing about the stream, so it names none, and the document's
/// own filter is used.
fn named_crypt_filter(doc: &Document, dict: &Dict) -> Option<Vec<u8>> {
let refused = REFUSED.get();
let filter = followed(doc, dict.get(b"Filter")?);
let i = match &*filter {
Object::Array(a) if a.len() <= MAX_CHAIN + 1 => a.iter().position(|f| is_crypt(doc, f))?,
f if is_crypt(doc, f) => 0,
_ => return None,
};
let i = names.iter().position(|n| *n == b"Crypt")?;
let parms = match dict.get(b"DecodeParms") {
Some(Object::Dict(d)) if i == 0 => Some(d.clone()),
Some(Object::Array(a)) => a.get(i).and_then(|p| p.as_dict().cloned()),
let parms = dict.get(b"DecodeParms").map(|p| followed(doc, p));
let entry = match parms.as_deref() {
Some(Object::Array(a)) => a.get(i).map(|p| followed(doc, p)),
Some(p) if i == 0 => Some(Held::Direct(p)),
_ => None,
};
Some(parms.and_then(|p| p.name(b"Name").map(|n| n.to_vec())).unwrap_or_else(|| b"Identity".to_vec()))
let name = entry.as_deref().and_then(Object::as_dict).and_then(|p| p.get(b"Name")).map(|n| followed(doc, n));
match name.as_deref().and_then(Object::as_name) {
Some(name) => Some(name.to_vec()),
// /Identity here would read ciphertext as data, and write the stream in the clear.
None if REFUSED.get() > refused => None,
None => Some(b"Identity".to_vec()),
}
}
/// A signature dictionary (field signature, document timestamp or usage-rights signature),
@@ -91,42 +169,67 @@ fn named_crypt_filter(dict: &Dict) -> Option<Vec<u8>> {
/// `/Contents` alongside an array `/ByteRange` (`/Type` is optional). A signature dictionary
/// has no `/Subtype`; a dictionary with one (an annotation, whose `/Contents` is the comment
/// text) or with another `/Type` is never exempt, whatever else it carries.
fn is_signature_dict(d: &Dict) -> bool {
if d.get(b"Subtype").is_some() {
/// With `doc` its entries are read through references; a dictionary nested in another object
/// has none (see [`transform`]).
fn is_signature_dict(doc: Option<&Document>, d: &Dict) -> bool {
// All this decides is what happens to such a /Contents.
if !matches!(d.get(b"Contents"), Some(Object::String(_))) {
return false;
}
match d.get(b"Type") {
Some(_) => matches!(d.name(b"Type"), Some(b"Sig" | b"DocTimeStamp")),
None => matches!(d.get(b"Contents"), Some(Object::String(_))) && matches!(d.get(b"ByteRange"), Some(Object::Array(_))),
// A null entry, or one that refers to nothing, is an absent one (ISO 32000-2 §7.3.7, §7.3.10).
let entry = |key: &[u8]| {
let value = d.get(key)?;
let held = doc.map_or(Held::Direct(value), |doc| followed(doc, value));
(!matches!(*held, Object::Null)).then_some(held)
};
if entry(b"Subtype").is_some() {
return false;
}
match entry(b"Type") {
Some(t) => matches!(t.as_name(), Some(b"Sig" | b"DocTimeStamp")),
None => matches!(entry(b"ByteRange").as_deref(), Some(Object::Array(_))),
}
}
/// Remove the `/Crypt` entry from a stream's filter chain, with its decode parameters.
fn drop_crypt_filter(dict: &mut Dict) {
let i = match dict.get(b"Filter") {
Some(Object::Array(a)) => a.iter().position(|n| n.as_name() == Some(b"Crypt")),
Some(Object::Name(n)) if n.as_slice() == b"Crypt" => Some(0),
_ => None,
/// Longer than any filter's name. A name can be of any length, and a chain every stream shares can
/// hold a long one.
const MAX_FILTER_NAME: usize = 127;
/// The dictionary of `source` without the `/Crypt` entries of its filter chain and their decode
/// parameters. The two come out direct when given by reference, which every stream of a file can
/// share, so of what was shared only small values are copied: filter names, and the parameters
/// decoders read ([`Document::with_direct_parms`]). The chain is short, as [`named_crypt_filter`]
/// found a filter in it.
fn drop_crypt_filter(doc: &Document, source: &Stream) -> Dict {
let entry = |f: &Object| match f {
f if is_crypt(doc, f) => Object::name("Crypt"),
Object::Name(n) if n.len() <= MAX_FILTER_NAME => f.clone(),
Object::Ref(_) => f.clone(),
_ => Object::Null,
};
let Some(i) = i else { return };
let mut filters = match dict.get(b"Filter") {
Some(Object::Array(a)) => a.clone(),
_ => Vec::new(),
let filter = source.dict.get(b"Filter").map(|f| followed(doc, f));
let chain: Vec<Object> = match filter.as_deref() {
Some(Object::Array(a)) => a.iter().map(entry).collect(),
Some(f) => vec![entry(f)],
None => Vec::new(),
};
if i < filters.len() {
filters.remove(i);
}
let crypt: Vec<bool> = chain.iter().map(|f| f.as_name() == Some(b"Crypt")).collect();
let mut chained = Stream::from_raw(source.dict.clone(), Vec::new());
chained.dict.set(b"Filter".to_vec(), Object::Array(chain.clone()));
// A lone parameter dictionary belongs to the first filter (as `named_crypt_filter` reads it).
match dict.get(b"DecodeParms").cloned() {
Some(Object::Array(mut parms)) if i < parms.len() => {
parms.remove(i);
dict.set(b"DecodeParms".to_vec(), Object::Array(parms));
}
Some(Object::Dict(_)) if i == 0 => {
let parms = match doc.with_direct_parms(&chained).dict.get(b"DecodeParms") {
Some(Object::Array(p)) => Some(Object::Array(p.iter().zip(&crypt).filter(|(_, c)| !**c).map(|(p, _)| p.clone()).collect())),
Some(Object::Dict(_)) if crypt.first() == Some(&true) => None,
_ => source.dict.get(b"DecodeParms").cloned(),
};
let mut dict = source.dict.clone();
match parms {
Some(p) => dict.set(b"DecodeParms".to_vec(), p),
None => {
dict.remove(b"DecodeParms");
}
_ => {}
}
let filters: Vec<Object> = chain.into_iter().zip(&crypt).filter(|(_, c)| !**c).map(|(f, _)| f).collect();
if filters.is_empty() {
dict.remove(b"Filter");
if matches!(dict.get(b"DecodeParms"), Some(Object::Array(p)) if p.is_empty()) {
@@ -135,6 +238,7 @@ fn drop_crypt_filter(dict: &mut Dict) {
} else {
dict.set(b"Filter".to_vec(), Object::Array(filters));
}
dict
}
/// What [`transform`] does to an object.
@@ -152,51 +256,81 @@ pub(crate) enum Pass {
/// Decrypt or encrypt every string and stream in an indirect object, except a signature
/// dictionary's `/Contents` (see [`is_signature_dict`]).
pub(crate) fn transform(h: &SecurityHandler, o: &Object, num: u32, generation: u16, pass: Pass) -> Object {
///
/// `o` is as `doc` holds it: what a stream's dictionary gives by reference is read from `doc`, so
/// its references have to be the document's, not a save's renumbered ones.
pub(crate) fn transform(doc: &Document, h: &SecurityHandler, o: &Object, num: u32, generation: u16, pass: Pass) -> Object {
let _scope = FollowScope::enter();
let decrypt = pass == Pass::Decrypt;
let strings = |s: &PdfString| {
let bytes = if decrypt { h.decrypt_string(num, generation, &s.bytes) } else { h.encrypt_string(num, generation, &s.bytes) };
PdfString { bytes, hex: s.hex || !decrypt }
};
walk(o, &strings, h, num, generation, pass)
// References are followed here only, for the object itself, never for what is nested in it.
// `walk` goes deep, and a load from down there adds that depth again for each object loaded,
// which overflowed the stack on a 10 KB file. A stream can't be nested, and a dictionary that
// is reads as it says directly.
match o {
Object::Stream(s) => stream(doc, s, &strings, h, num, generation, pass),
Object::Dict(d) if is_signature_dict(Some(doc), d) => signature_dict(d, &strings),
o => walk(o, &strings),
}
}
fn walk(o: &Object, strings: &dyn Fn(&PdfString) -> PdfString, h: &SecurityHandler, num: u32, generation: u16, pass: Pass) -> Object {
let decrypt = pass == Pass::Decrypt;
/// `d`, a signature dictionary, with the strings of everything but its `/Contents` transformed.
fn signature_dict(d: &Dict, strings: &dyn Fn(&PdfString) -> PdfString) -> Object {
Object::Dict(
d.iter()
.map(|(k, v)| match (k.as_slice(), v) {
(b"Contents", Object::String(_)) => (k.clone(), v.clone()),
_ => (k.clone(), walk(v, strings)),
})
.collect(),
)
}
fn walk(o: &Object, strings: &dyn Fn(&PdfString) -> PdfString) -> Object {
match o {
Object::String(s) => Object::String(strings(s)),
Object::Array(a) => Object::Array(a.iter().map(|x| walk(x, strings, h, num, generation, pass)).collect()),
Object::Dict(d) if is_signature_dict(d) => Object::Dict(
d.iter()
.map(|(k, v)| match (k.as_slice(), v) {
(b"Contents", Object::String(_)) => (k.clone(), v.clone()),
_ => (k.clone(), walk(v, strings, h, num, generation, pass)),
})
.collect(),
),
Object::Dict(d) => Object::Dict(d.iter().map(|(k, v)| (k.clone(), walk(v, strings, h, num, generation, pass))).collect()),
Object::Stream(s) => {
let mut dict: Dict = s.dict.iter().map(|(k, v)| (k.clone(), walk(v, strings, h, num, generation, pass))).collect();
let ty = s.dict.name(b"Type");
// Cross-reference streams are never encrypted (§7.5.8), but only reading may trust the
// label: a stream a producer calls /XRef stays plaintext if writing believes it, and the
// writer builds its own cross-reference streams outside this transform.
if (decrypt && ty == Some(b"XRef")) || (ty == Some(b"Metadata") && !h.encrypts_metadata()) {
return Object::Stream(Stream { dict, raw: s.raw.clone() });
}
let mut named = named_crypt_filter(&s.dict);
if pass == Pass::EncryptReplacing && named.as_deref().is_some_and(|n| !h.dict().crypt_filters.iter().any(|(f, _)| f == n)) {
drop_crypt_filter(&mut dict);
named = None;
}
let kind = match (&named, ty) {
(Some(n), _) => StreamKind::Named(n),
(None, Some(b"EmbeddedFile")) => StreamKind::EmbeddedFile,
_ => StreamKind::Normal,
};
let raw = if decrypt { h.decrypt_stream(num, generation, &s.raw, kind) } else { h.encrypt_stream(num, generation, &s.raw, kind) };
Object::Stream(Stream { dict, raw: raw.into() })
}
Object::Array(a) => Object::Array(a.iter().map(|x| walk(x, strings)).collect()),
Object::Dict(d) if is_signature_dict(None, d) => signature_dict(d, strings),
Object::Dict(d) => Object::Dict(d.iter().map(|(k, v)| (k.clone(), walk(v, strings))).collect()),
other => other.clone(),
}
}
fn stream(
doc: &Document,
s: &Stream,
strings: &dyn Fn(&PdfString) -> PdfString,
h: &SecurityHandler,
num: u32,
generation: u16,
pass: Pass,
) -> Object {
let decrypt = pass == Pass::Decrypt;
let walked = |d: &Dict| -> Dict { d.iter().map(|(k, v)| (k.clone(), walk(v, strings))).collect() };
let ty = s.dict.get(b"Type").map(|t| followed(doc, t));
let ty = ty.as_deref().and_then(Object::as_name);
// Cross-reference streams are never encrypted (§7.5.8), but only reading may trust the
// label: a stream a producer calls /XRef stays plaintext if writing believes it, and the
// writer builds its own cross-reference streams outside this transform.
if (decrypt && ty == Some(b"XRef")) || (ty == Some(b"Metadata") && !h.encrypts_metadata()) {
return Object::Stream(Stream { dict: walked(&s.dict), raw: s.raw.clone() });
}
let mut named = named_crypt_filter(doc, &s.dict);
// Before the walk, which then encrypts what is in the dictionary this leaves.
let foreign = pass == Pass::EncryptReplacing && named.as_deref().is_some_and(|n| !h.dict().crypt_filters.iter().any(|(f, _)| f == n));
let dropped = foreign.then(|| drop_crypt_filter(doc, s));
if dropped.is_some() {
named = None;
}
let dict = walked(dropped.as_ref().unwrap_or(&s.dict));
let kind = match (&named, ty) {
(Some(n), _) => StreamKind::Named(n),
(None, Some(b"EmbeddedFile")) => StreamKind::EmbeddedFile,
_ => StreamKind::Normal,
};
let raw = if decrypt { h.decrypt_stream(num, generation, &s.raw, kind) } else { h.encrypt_stream(num, generation, &s.raw, kind) };
Object::Stream(Stream { dict, raw: raw.into() })
}
+44 -10
View File
@@ -133,11 +133,12 @@ fn write_stream(s: &Stream, out: &mut Vec<u8>) {
/// The object as written: encrypted with its (output) number when the document is encrypted,
/// except the `/Encrypt` dictionary itself (`source_num` is its number in the source document).
/// `o` has the document's numbers in its references ([`crate::security::transform`]).
fn prepared<'a>(doc: &Document, source_num: u32, num: u32, generation: u16, o: &'a Object) -> Cow<'a, Object> {
match doc.output_security() {
(Some(h), encrypt_num) if Some(source_num) != encrypt_num => {
(Some(h), encrypt_num) if Some(source_num) != encrypt_num && !doc.stored_as_is(source_num) => {
let pass = if doc.encryption_changed() { crate::security::Pass::EncryptReplacing } else { crate::security::Pass::Encrypt };
Cow::Owned(crate::security::transform(h, o, num, generation, pass))
Cow::Owned(crate::security::transform(doc, h, o, num, generation, pass))
}
_ => Cow::Borrowed(o),
}
@@ -245,7 +246,7 @@ pub fn write_incremental(doc: &Document, opts: &SaveOptions) -> Result<Vec<u8>,
if let Some(p) = prev {
trailer.set(b"Prev".to_vec(), Object::Int(p as i64));
}
let size = doc.next_num().max(trailer.int(b"Size").unwrap_or(0) as u32);
let size = doc.next_num().max(trailer.int(b"Size").map_or(0, |n| n.clamp(0, i64::from(u32::MAX)) as u32));
if as_stream {
let rows = offsets.iter().map(|(n, (o, g, used))| (*n, if *used { Row::InFile(*o, *g) } else { Row::Free(*g) })).collect();
write_xref_stream(&mut out, base, &mut trailer, rows, size);
@@ -287,6 +288,10 @@ pub fn write_full(doc: &Document, opts: &SaveOptions) -> Result<Vec<u8>, CosErro
queue.push_back(r);
}
}
// A direct /Encrypt can refer to objects, /CF or /StmF, say.
if let Some(encrypt @ Object::Dict(_)) = trailer_in.get(b"Encrypt") {
visit_refs(encrypt, &mut queue);
}
// Unknown trailer entries are document data. Objects they alone reference must be written
// too, or a full rewrite would keep the key and drop its value.
for (key, value) in trailer_in.iter() {
@@ -315,7 +320,10 @@ pub fn write_full(doc: &Document, opts: &SaveOptions) -> Result<Vec<u8>, CosErro
// The /Encrypt dictionary and everything it references (e.g. indirect /CF crypt-filter
// dictionaries) are needed before anything can be decrypted: never inside object streams.
let mut encryption_objects: std::collections::HashSet<ObjRef> = std::collections::HashSet::new();
let mut pending: Vec<ObjRef> = trailer_in.reference(b"Encrypt").into_iter().collect();
let mut pending: Vec<ObjRef> = Vec::new();
if let Some(encrypt) = trailer_in.get(b"Encrypt") {
collect_refs(encrypt, &mut |r| pending.push(r));
}
while let Some(r) = pending.pop() {
if encryption_objects.insert(r) {
collect_refs(&reader.get(r), &mut |x| pending.push(x));
@@ -336,9 +344,10 @@ pub fn write_full(doc: &Document, opts: &SaveOptions) -> Result<Vec<u8>, CosErro
if in_stream {
packed.push((num, *r));
} else {
let o = renumber(&*reread(&mut reader, *r, *is_stream)?, &map);
let o = reread(&mut reader, *r, *is_stream)?;
let o = renumber(&prepared(&reader.document, r.num, num, 0, &o), &map);
rows.insert(num, Row::InFile(out.len() as u64, 0));
write_indirect(num, 0, &prepared(&reader.document, r.num, num, 0, &o), &mut out);
write_indirect(num, 0, &o, &mut out);
}
}
// Object streams take the numbers after the last object. Their contents are not encrypted
@@ -368,11 +377,11 @@ pub fn write_full(doc: &Document, opts: &SaveOptions) -> Result<Vec<u8>, CosErro
trailer.set(key.to_vec(), Object::Ref(ObjRef::new(*r, 0)));
}
}
if let Some(Object::Dict(d)) = trailer_in.get(b"Encrypt") {
trailer.set(b"Encrypt".to_vec(), Object::Dict(d.clone()));
if let Some(encrypt @ Object::Dict(_)) = trailer_in.get(b"Encrypt") {
trailer.set(b"Encrypt".to_vec(), renumber(encrypt, &map));
}
if let Some(id) = trailer_in.get(b"ID") {
trailer.set(b"ID".to_vec(), id.clone());
trailer.set(b"ID".to_vec(), direct_id(&reader.document, id));
}
for (key, value) in trailer_in.iter() {
if !trailer_key_rewritten(key) {
@@ -442,6 +451,22 @@ impl ObjectStreamBatch {
}
}
/// `/ID` for the trailer, direct, as it has to be with `/Encrypt`: nothing else in the file holds
/// what it refers to now. Given by reference it is two entries at most, however many references a
/// file gave, so that one large string isn't copied for each. An entry that isn't a string stays in
/// its place as an empty one, which is how the key read it.
fn direct_id(doc: &Document, id: &Object) -> Object {
if matches!(id, Object::Array(a) if !a.iter().any(|s| matches!(s, Object::Ref(_)))) {
return id.clone();
}
let entry = |s: &Object| match &*doc.resolve(s) {
s @ Object::String(_) => s.clone(),
_ => Object::String(crate::PdfString { bytes: Vec::new(), hex: true }),
};
let held = doc.resolve(id);
Object::Array(held.as_array().into_iter().flatten().take(2).map(entry).collect())
}
/// Trailer keys a full rewrite generates itself. Everything else is copied, with references
/// renumbered, so a save does not drop metadata the reader accepted.
fn trailer_key_rewritten(key: &[u8]) -> bool {
@@ -486,7 +511,7 @@ pub(crate) fn unlinked_additions(doc: &Document) -> HashSet<u32> {
pending.into_keys().collect()
}
fn collect_refs(o: &Object, f: &mut impl FnMut(ObjRef)) {
pub(crate) fn collect_refs(o: &Object, f: &mut impl FnMut(ObjRef)) {
match o {
Object::Ref(r) => f(*r),
Object::Array(a) => a.iter().for_each(|x| collect_refs(x, f)),
@@ -663,6 +688,15 @@ fn civil_from_days(days: i64) -> (i64, u32, u32) {
#[cfg(test)]
mod tests {
/// `/ID` by reference comes out direct, each entry where it was: the key is made from the first.
#[test]
fn a_file_identifier_keeps_its_entries_in_their_places() {
let doc = Document::new_empty();
let string = |bytes: &[u8]| Object::String(crate::PdfString { bytes: bytes.to_vec(), hex: true });
let nowhere = Object::Ref(ObjRef::new(9_999, 0));
assert_eq!(super::direct_id(&doc, &Object::Array(vec![nowhere, string(b"ab")])), Object::Array(vec![string(b""), string(b"ab")]));
}
use proptest::prelude::*;
use super::*;
+823
View File
@@ -494,3 +494,826 @@ fn a_stream_labelled_xref_is_encrypted_when_saved() {
let bytes = write_full(&doc, &SaveOptions { object_streams: false, ..SaveOptions::default() }).unwrap();
assert!(!bytes.windows(SECRET.len()).any(|w| w == SECRET.as_bytes()), "the labelled stream was written in the clear");
}
/// The content stream's reference.
fn contents_of(doc: &Document) -> ObjRef {
let catalog = doc.get(doc.root().unwrap()).as_dict().cloned().unwrap();
let pages = doc.get(catalog.reference(b"Pages").unwrap()).as_dict().cloned().unwrap();
let page = doc.resolve(&pages.get(b"Kids").unwrap().as_array().unwrap()[0]).as_dict().cloned().unwrap();
page.reference(b"Contents").unwrap()
}
/// The content stream's data as loaded, whatever its filters say.
fn raw_content(doc: &Document) -> String {
match &*doc.get(contents_of(doc)) {
Object::Stream(s) => String::from_utf8_lossy(&s.raw).trim().to_string(),
_ => panic!("no content stream"),
}
}
/// Gives the content stream the `/Filter` and `/DecodeParms` of `selector`.
fn select(doc: &mut Document, (filter, parms): (Object, Object)) {
let contents = contents_of(doc);
let Object::Stream(mut s) = doc.get(contents).as_ref().clone() else { panic!("no content stream") };
s.dict.set(b"Filter".to_vec(), filter);
s.dict.set(b"DecodeParms".to_vec(), parms);
doc.set(contents, Object::Stream(s));
}
/// `/Crypt` naming `name`, in the `form`th spelling: all direct, then each part by reference.
/// `None` past the last.
fn selector(doc: &mut Document, form: usize, name: &str) -> Option<(Object, Object)> {
let crypt = Object::name("Crypt");
let parms = |n: Object| {
let mut d = pdfcraft_cos::Dict::new();
d.set(b"Name".to_vec(), n);
Object::Dict(d)
};
let named = parms(Object::name(name));
Some(match form {
0 => (crypt, named),
1 => (crypt, Object::Ref(doc.add(named))),
2 => (Object::Array(vec![crypt]), Object::Array(vec![Object::Ref(doc.add(named))])),
3 => (Object::Array(vec![crypt]), Object::Ref(doc.add(Object::Array(vec![named])))),
4 => (crypt, parms(Object::Ref(doc.add(Object::name(name))))),
5 => (Object::Ref(doc.add(crypt)), named),
6 => (Object::Ref(doc.add(Object::Array(vec![crypt]))), Object::Array(vec![named])),
7 => (Object::Array(vec![Object::Ref(doc.add(crypt))]), Object::Array(vec![named])),
// Behind a filter given by reference: places in the two arrays pair up all the same.
8 => (Object::Array(vec![Object::Ref(doc.add(Object::name("ASCIIHexDecode"))), crypt]), Object::Array(vec![Object::Null, named])),
// The two entries in different forms, which is how a lone filter is usually spelled.
9 => (Object::Array(vec![crypt]), named),
10 => (crypt, Object::Array(vec![named])),
// The filter twice, which names the first's.
11 => (Object::Array(vec![crypt.clone(), crypt]), Object::Array(vec![named.clone(), named])),
// A reference to a reference.
12 => {
let name = doc.add(Object::name(name));
let hop = doc.add(Object::Ref(name));
(crypt, parms(Object::Ref(hop)))
}
_ => return None,
})
}
fn holds(bytes: &[u8], text: &str) -> bool {
String::from_utf8_lossy(bytes).contains(text)
}
/// An object `/Encrypt` names is written as stored only while it is as stored. A file whose
/// `/Encrypt` names its `/Info` reads that dictionary as stored; once the title is edited, both
/// saves encrypt it rather than writing the new title in the clear.
#[test]
fn an_edited_object_that_encrypt_names_is_encrypted() {
let mut doc = Document::open(Arc::new(fixture())).unwrap();
doc.set_encryption(&NewEncryption {
algorithm: Algorithm::Aes128,
user_password: "",
owner_password: "owner",
permissions: -1,
encrypt_metadata: true,
seed: [9; 32],
})
.unwrap();
let info = doc.trailer().reference(b"Info").unwrap();
let mut dict = doc.get(doc.trailer().reference(b"Encrypt").unwrap()).as_dict().cloned().unwrap();
dict.set(b"Junk".to_vec(), Object::Ref(info));
doc.trailer_mut().set(b"Encrypt".to_vec(), Object::Dict(dict));
let bytes = write_full(&doc, &SaveOptions::default()).unwrap();
let mut doc = Document::open(Arc::new(bytes)).unwrap();
let info = doc.trailer().reference(b"Info").unwrap();
doc.update_dict(info, |d| d.set(b"Title".to_vec(), PdfString::text("Merger plan"))).unwrap();
for (save, saved) in [("incremental", write_incremental(&doc, &SaveOptions::default())), ("full", write_full(&doc, &SaveOptions::default()))] {
assert!(!holds(&saved.unwrap(), "Merger plan"), "{save}: the edited title was written in the clear");
}
}
/// A stream can select its crypt filter by reference at every step: the chain, an entry of it, the
/// parameters, an entry of those, the name (ISO 32000-2 §7.3.10, §7.4.10). Read as absent, the
/// filter was `/Identity`, so such a stream was saved in the clear and, in a file from elsewhere,
/// its ciphertext read as data. A full save renumbers: what it follows has the document's numbers.
#[test]
fn a_crypt_filter_selected_by_reference_is_used() {
for alg in [Algorithm::Aes128, Algorithm::Aes256] {
for form in 0.. {
let mut doc = Document::open(Arc::new(protect(alg, "", "owner", -1))).unwrap();
let Some(selected) = selector(&mut doc, form, "StdCF") else { break };
select(&mut doc, selected);
let saved = write_incremental(&doc, &SaveOptions::default()).unwrap();
assert!(!holds(&saved, "Secret page"), "{alg:?} form {form}: saved encrypted");
let back = Document::open(Arc::new(saved)).unwrap();
assert_eq!(raw_content(&back), SECRET, "{alg:?} form {form}: read back");
let full = write_full(&back, &SaveOptions::default()).unwrap();
assert!(!holds(&full, "Secret page"), "{alg:?} form {form}: renumbered, encrypted");
assert_eq!(raw_content(&Document::open(Arc::new(full)).unwrap()), SECRET, "{alg:?} form {form}: renumbered");
}
}
}
/// A reference to a stream that takes `follows` references to read cold, this one included: its
/// nine filters are all read, the last leading to the next stream.
fn spends(doc: &mut Document, follows: usize) -> Object {
let left = follows - 1;
let mut filters: Vec<Object> = (0..left.min(8)).map(|i| Object::Ref(doc.add(Object::Int(i as i64)))).collect();
if left > 8 {
filters.push(spends(doc, left - 8));
}
let mut dict = pdfcraft_cos::Dict::new();
dict.set(b"Filter".to_vec(), Object::Array(filters));
Object::Ref(doc.add(Object::Stream(pdfcraft_cos::Stream::from_raw(dict, Vec::new()))))
}
/// Gives the content stream a `/Type` that takes `follows` references to read, ahead of its filter.
fn spend_first(doc: &mut Document, follows: usize) {
let spent = spends(doc, follows);
let contents = contents_of(doc);
let Object::Stream(mut s) = doc.get(contents).as_ref().clone() else { panic!("no content stream") };
s.dict.set(b"Type".to_vec(), spent);
doc.set(contents, Object::Stream(s));
}
/// Past what one read may follow a reference reads as absent, and a crypt filter with no `/Name` is
/// `/Identity`. Together those would read this stream's ciphertext as data, so what can't be told
/// is the document's own filter, as a `/Filter` that can't be read is.
#[test]
fn a_crypt_filter_past_what_a_read_may_follow_is_the_documents_own() {
let mut doc = Document::open(Arc::new(protect(Algorithm::Aes128, "", "owner", -1))).unwrap();
let selected = selector(&mut doc, 1, "StdCF").unwrap();
select(&mut doc, selected);
spend_first(&mut doc, 40);
let saved = write_incremental(&doc, &SaveOptions::default()).unwrap();
assert!(!holds(&saved, "Secret page"), "saved encrypted");
let back = Document::open(Arc::new(saved)).unwrap();
assert_eq!(raw_content(&back), SECRET);
let full = write_full(&back, &SaveOptions::default()).unwrap();
assert!(!holds(&full, "Secret page"), "renumbered, encrypted");
assert_eq!(raw_content(&Document::open(Arc::new(full)).unwrap()), SECRET, "renumbered");
}
/// A read that takes all it may follow has refused nothing: a crypt filter with no `/Name` after it
/// is still `/Identity`, and the stream is in the clear.
#[test]
fn a_crypt_filter_with_no_name_after_all_a_read_may_follow_is_identity() {
let mut doc = Document::open(Arc::new(protect(Algorithm::Aes128, "", "owner", -1))).unwrap();
select(&mut doc, (Object::name("Crypt"), Object::Dict(pdfcraft_cos::Dict::new())));
spend_first(&mut doc, 32);
let saved = write_incremental(&doc, &SaveOptions::default()).unwrap();
assert!(holds(&saved, "Secret page"), "written as the stream asks");
assert_eq!(raw_content(&Document::open(Arc::new(saved)).unwrap()), SECRET);
}
/// `/Identity` selected by reference keeps a stream in the clear in a document that encrypts the
/// rest, in every spelling, on both saves.
#[test]
fn an_identity_crypt_filter_selected_by_reference_leaves_a_stream_alone() {
for form in 0.. {
let mut doc = Document::open(Arc::new(protect(Algorithm::Aes128, "", "owner", -1))).unwrap();
let Some(selected) = selector(&mut doc, form, "Identity") else { break };
select(&mut doc, selected);
let saved = write_incremental(&doc, &SaveOptions::default()).unwrap();
assert!(holds(&saved, "Secret page"), "form {form}: written as the stream asks");
let back = Document::open(Arc::new(saved)).unwrap();
assert_eq!(raw_content(&back), SECRET, "form {form}");
let full = write_full(&back, &SaveOptions::default()).unwrap();
assert!(holds(&full, "Secret page"), "form {form}: renumbered");
assert_eq!(raw_content(&Document::open(Arc::new(full)).unwrap()), SECRET, "form {form}: renumbered");
}
}
/// New protection drops a crypt filter it doesn't define, whichever way the stream selected it. The
/// chain comes out direct. Parameters in the stream's own dictionary stay, encrypted with it; of an
/// array in an object of its own, which every stream can share, only what decoders read is copied.
#[test]
fn protecting_drops_a_crypt_filter_selected_by_reference() {
let protected = |doc: &mut Document| {
doc.set_encryption(&NewEncryption {
algorithm: Algorithm::Aes256,
user_password: "",
owner_password: "owner",
permissions: -1,
encrypt_metadata: true,
seed: [7; 32],
})
.unwrap();
write_full(doc, &SaveOptions::default()).unwrap()
};
for form in 0.. {
let mut doc = Document::open(Arc::new(fixture())).unwrap();
let Some(selected) = selector(&mut doc, form, "MyCF") else { break };
select(&mut doc, selected);
let bytes = protected(&mut doc);
assert!(!holds(&bytes, "Secret page"), "form {form}: encrypted");
assert!(!holds(&bytes, "MyCF"), "form {form}: no selector left in the stream");
let back = Document::open(Arc::new(bytes.clone())).unwrap();
assert_eq!(raw_content(&back), SECRET, "form {form}");
let contents = back.get(contents_of(&back));
let filter = contents.as_dict().unwrap().get(b"Filter");
match form {
8 => assert!(
matches!(filter, Some(Object::Array(a)) if matches!(a.as_slice(), [Object::Ref(_)])),
"form 8: the other filter stays: {filter:?}"
),
_ => assert_eq!(filter, None, "form {form}"),
}
assert!(hayro_syntax::Pdf::new(bytes).is_ok(), "form {form}");
}
for shared in [false, true] {
let mut doc = Document::open(Arc::new(fixture())).unwrap();
let mut named = pdfcraft_cos::Dict::new();
named.set(b"Name".to_vec(), Object::name("MyCF"));
let mut other = pdfcraft_cos::Dict::new();
other.set(b"Note".to_vec(), Object::String(PdfString::text("Private note")));
other.set(b"Predictor".to_vec(), Object::Int(1));
let parms = Object::Array(vec![Object::Dict(named), Object::Dict(other)]);
let parms = if shared { Object::Ref(doc.add(parms)) } else { parms };
select(&mut doc, (Object::Array(vec![Object::name("Crypt"), Object::name("ASCIIHexDecode")]), parms));
let bytes = protected(&mut doc);
assert!(!holds(&bytes, "Private note"), "shared: {shared}");
let back = Document::open(Arc::new(bytes)).unwrap();
let contents = back.get(contents_of(&back));
let kept = contents.as_dict().unwrap().get(b"DecodeParms").unwrap().as_array().unwrap();
assert_eq!(kept.len(), 1, "one filter left, one entry");
let kept = kept[0].as_dict().unwrap();
assert_eq!(kept.get(b"Predictor"), Some(&Object::Int(1)), "shared: {shared}");
assert_eq!(kept.get(b"Note").is_some(), !shared, "shared: {shared}");
}
}
/// Every stream of a file can share one large object as its `/DecodeParms` or `/Filter`, which
/// costs nothing until new protection drops a crypt filter from each. Copied whole, a 1 MB file
/// came out at 1 GB.
#[test]
fn protecting_copies_no_large_object_into_every_stream() {
let pad = Object::Array(vec![Object::Int(1); 100_000]);
let mut doc = Document::open(Arc::new(fixture())).unwrap();
let mut large = pdfcraft_cos::Dict::new();
large.set(b"Pad".to_vec(), pad.clone());
let parms = doc.add(Object::Array(vec![Object::Null, Object::Dict(large)]));
let filter = doc.add(Object::Array(vec![Object::name("Crypt"), Object::Name(vec![b'A'; 100_000]), pad]));
let mut streams = Vec::new();
for _ in 0..200 {
let mut by_parms = pdfcraft_cos::Dict::new();
by_parms.set(b"Filter".to_vec(), Object::Array(vec![Object::name("Crypt"), Object::name("ASCIIHexDecode")]));
by_parms.set(b"DecodeParms".to_vec(), Object::Ref(parms));
streams.push(Object::Ref(doc.add(Object::Stream(pdfcraft_cos::Stream::from_raw(by_parms, b"41>".to_vec())))));
let mut by_filter = pdfcraft_cos::Dict::new();
by_filter.set(b"Filter".to_vec(), Object::Ref(filter));
streams.push(Object::Ref(doc.add(Object::Stream(pdfcraft_cos::Stream::from_raw(by_filter, b"41>".to_vec())))));
}
doc.update_dict(doc.root().unwrap(), |c| c.set(b"Test".to_vec(), Object::Array(streams))).unwrap();
doc.set_encryption(&NewEncryption {
algorithm: Algorithm::Aes256,
user_password: "",
owner_password: "owner",
permissions: -1,
encrypt_metadata: true,
seed: [7; 32],
})
.unwrap();
let bytes = write_full(&doc, &SaveOptions { object_streams: false, ..SaveOptions::default() }).unwrap();
assert!(bytes.len() < 1 << 20, "{} bytes", bytes.len());
}
/// A file can name one large string thousands of times in `/ID`, which holds two. An encrypted file
/// keeps its `/ID`, so each copy would be in the file a save writes.
#[test]
fn a_file_identifier_of_many_references_is_two_strings() {
let mut doc = Document::open(Arc::new(fixture())).unwrap();
doc.set_encryption(&NewEncryption {
algorithm: Algorithm::Aes128,
user_password: "",
owner_password: "owner",
permissions: -1,
encrypt_metadata: true,
seed: [9; 32],
})
.unwrap();
let large = doc.add(Object::String(PdfString { bytes: vec![0xAB; 100_000], hex: true }));
doc.trailer_mut().set(b"ID".to_vec(), Object::Array(vec![Object::Ref(large); 500]));
let bytes = write_full(&doc, &SaveOptions { object_streams: false, ..SaveOptions::default() }).unwrap();
assert!(bytes.len() < 1 << 20, "{} bytes", bytes.len());
}
/// What a file can do with those references: point a stream's selector at the stream itself, or at
/// nothing. They read as absent, so a stream with `/Crypt` is `/Identity` (ISO 32000-2 §7.4.10),
/// and one that names no filter follows the document's. Loading ends either way.
#[test]
fn a_crypt_filter_reference_to_itself_or_nothing_reads_as_absent() {
let named = |n: Object| {
let mut d = pdfcraft_cos::Dict::new();
d.set(b"Name".to_vec(), n);
Object::Dict(d)
};
for (what, encrypted) in [
("/Filter to itself", true),
("/Filter nowhere", true),
("/DecodeParms to itself", false),
("/DecodeParms nowhere", false),
("/Name to itself", false),
("/Name nowhere", false),
] {
let mut doc = Document::open(Arc::new(protect(Algorithm::Aes128, "", "owner", -1))).unwrap();
let me = Object::Ref(contents_of(&doc));
let nowhere = Object::Ref(ObjRef::new(9_999, 0));
let crypt = Object::name("Crypt");
select(
&mut doc,
match what {
"/Filter to itself" => (me, Object::Null),
"/Filter nowhere" => (nowhere, Object::Null),
"/DecodeParms to itself" => (crypt, me),
"/DecodeParms nowhere" => (crypt, nowhere),
"/Name to itself" => (crypt, named(me)),
_ => (crypt, named(nowhere)),
},
);
let saved = write_incremental(&doc, &SaveOptions::default()).unwrap();
assert_eq!(!holds(&saved, "Secret page"), encrypted, "{what}");
assert_eq!(raw_content(&Document::open(Arc::new(saved)).unwrap()), SECRET, "{what}");
}
}
/// A lone parameter dictionary belongs to the first filter, so `/Crypt` behind another filter has
/// none of its own and is `/Identity` (ISO 32000-2 §7.4.1), whatever that dictionary says.
#[test]
fn a_lone_parameter_dictionary_is_the_first_filters() {
let mut doc = Document::open(Arc::new(protect(Algorithm::Aes128, "", "owner", -1))).unwrap();
let mut parms = pdfcraft_cos::Dict::new();
parms.set(b"Name".to_vec(), Object::name("StdCF"));
let first = Object::Array(vec![Object::name("Crypt"), Object::name("ASCIIHexDecode")]);
let second = Object::Array(vec![Object::name("ASCIIHexDecode"), Object::name("Crypt")]);
select(&mut doc, (first, Object::Dict(parms.clone())));
assert!(!holds(&write_incremental(&doc, &SaveOptions::default()).unwrap(), "Secret page"), "first: it names StdCF");
select(&mut doc, (second, Object::Dict(parms)));
assert!(holds(&write_incremental(&doc, &SaveOptions::default()).unwrap(), "Secret page"), "second: it names nothing");
}
/// A lone parameter dictionary is the first filter's, so dropping a `/Crypt` behind that filter
/// leaves it, and dropping one in front of it takes it away.
#[test]
fn protecting_keeps_the_parameters_of_the_filter_before_a_crypt_filter() {
let protected = |filters: Vec<Object>| {
let mut doc = Document::open(Arc::new(fixture())).unwrap();
let mut parms = pdfcraft_cos::Dict::new();
parms.set(b"Name".to_vec(), Object::name("MyCF"));
select(&mut doc, (Object::Array(filters), Object::Dict(parms)));
doc.set_encryption(&NewEncryption {
algorithm: Algorithm::Aes256,
user_password: "",
owner_password: "owner",
permissions: -1,
encrypt_metadata: true,
seed: [7; 32],
})
.unwrap();
let back = Document::open(Arc::new(write_full(&doc, &SaveOptions::default()).unwrap())).unwrap();
back.get(contents_of(&back)).as_dict().unwrap().contains(b"DecodeParms")
};
let (hex, crypt) = (Object::name("ASCIIHexDecode"), Object::name("Crypt"));
assert!(protected(vec![hex.clone(), crypt.clone()]), "the first filter's, which stays");
assert!(!protected(vec![crypt, hex]), "/Crypt's, which goes");
}
/// Dropping `/Crypt` takes its entry out of `/DecodeParms`, and an array too short to have one is
/// left as it is, given directly or by reference.
#[test]
fn protecting_leaves_a_parameter_array_too_short_for_the_crypt_filter() {
for by_reference in [false, true] {
let mut doc = Document::open(Arc::new(fixture())).unwrap();
let short = Object::Array(vec![Object::Null]);
let parms = if by_reference { Object::Ref(doc.add(short)) } else { short };
select(&mut doc, (Object::Array(vec![Object::name("ASCIIHexDecode"), Object::name("Crypt")]), parms));
doc.set_encryption(&NewEncryption {
algorithm: Algorithm::Aes256,
user_password: "",
owner_password: "owner",
permissions: -1,
encrypt_metadata: true,
seed: [7; 32],
})
.unwrap();
let bytes = write_full(&doc, &SaveOptions::default()).unwrap();
assert!(!holds(&bytes, "Secret page"), "by reference: {by_reference}");
let back = Document::open(Arc::new(bytes)).unwrap();
assert_eq!(raw_content(&back), SECRET, "by reference: {by_reference}");
let contents = back.get(contents_of(&back));
let filter = contents.as_dict().unwrap().get(b"Filter").unwrap().as_array().unwrap();
assert_eq!(filter.len(), 1, "only /Crypt goes");
assert_eq!(filter[0].as_name(), Some(b"ASCIIHexDecode".as_slice()), "the other filter stays as it was");
}
}
/// A chain of up to [`pdfcraft_filters::MAX_CHAIN`] filters and `/Crypt` is read; a longer one
/// names no crypt filter, so its entries aren't followed for every stream sharing it.
#[test]
fn a_chain_longer_than_any_decoder_takes_names_no_crypt_filter() {
let chain = |others: usize| {
let mut doc = Document::open(Arc::new(protect(Algorithm::Aes128, "", "owner", -1))).unwrap();
let mut filters = vec![Object::name("ASCIIHexDecode"); others];
filters.push(Object::name("Crypt"));
let array = doc.add(Object::Array(filters));
select(&mut doc, (Object::Ref(array), Object::Null));
holds(&write_incremental(&doc, &SaveOptions::default()).unwrap(), "Secret page")
};
assert!(chain(pdfcraft_filters::MAX_CHAIN), "the longest chain read: /Identity, in the clear");
assert!(!chain(pdfcraft_filters::MAX_CHAIN + 1), "one more: the document's filter");
}
/// A stream's `/Type` by reference picks its handling like one given directly: metadata left
/// readable under `/EncryptMetadata false`, an embedded file under `/EFF`.
#[test]
fn a_stream_type_given_by_reference_picks_its_crypt_filter() {
let mut doc = Document::open(Arc::new(fixture())).unwrap();
let catalog = doc.get(doc.root().unwrap()).as_dict().cloned().unwrap();
let meta = catalog.reference(b"Metadata").unwrap();
let ty = doc.add(Object::name("Metadata"));
let Object::Stream(mut s) = doc.get(meta).as_ref().clone() else { panic!("no metadata stream") };
s.dict.set(b"Type".to_vec(), Object::Ref(ty));
doc.set(meta, Object::Stream(s));
doc.set_encryption(&NewEncryption {
algorithm: Algorithm::Aes256,
user_password: "",
owner_password: "o",
permissions: -1,
encrypt_metadata: false,
seed: [5; 32],
})
.unwrap();
let bytes = write_full(&doc, &SaveOptions::default()).unwrap();
assert!(holds(&bytes, "<x:xmpmeta>meta</x:xmpmeta>"), "search engines can read XMP");
let mut doc = Document::open(Arc::new(protect(Algorithm::Aes128, "", "owner", -1))).unwrap();
let encrypt = doc.trailer().reference(b"Encrypt").unwrap();
doc.update_dict(encrypt, |e| e.set(b"EFF".to_vec(), Object::name("Identity"))).unwrap();
let mut doc = Document::open(Arc::new(write_incremental(&doc, &SaveOptions::default()).unwrap())).unwrap();
let contents = contents_of(&doc);
let ty = doc.add(Object::name("EmbeddedFile"));
let Object::Stream(mut s) = doc.get(contents).as_ref().clone() else { panic!("no content stream") };
s.dict.set(b"Type".to_vec(), Object::Ref(ty));
doc.set(contents, Object::Stream(s));
assert!(holds(&write_incremental(&doc, &SaveOptions::default()).unwrap(), "Secret page"), "/EFF /Identity leaves it alone");
}
/// What makes a dictionary a signature's can be given by reference, and what is null or refers to
/// nothing is absent: `/Contents` stays as written in each of these.
#[test]
fn a_signature_dictionary_is_known_in_every_form() {
let mut doc = Document::open(Arc::new(fixture())).unwrap();
let ty = doc.add(Object::name("Sig"));
let range = Object::Array([0, 10, 20, 30].into_iter().map(Object::Int).collect());
let by_reference = doc.add(range.clone());
let nowhere = Object::Ref(ObjRef::new(9_999, 0));
let forms: [(Vec<(&str, Object)>, &str); 5] = [
(vec![("Type", Object::Ref(ty))], "DEAD"),
(vec![("ByteRange", Object::Ref(by_reference))], "BEEF"),
(vec![("Type", Object::Null), ("ByteRange", range.clone())], "CAFE"),
(vec![("Type", nowhere.clone()), ("ByteRange", range.clone())], "F00D"),
(vec![("Subtype", nowhere), ("ByteRange", range)], "D00D"),
];
let mut signatures = Vec::new();
for (entries, contents) in forms {
let mut sig = pdfcraft_cos::Dict::new();
for (key, value) in entries {
sig.set(key.as_bytes().to_vec(), value);
}
let bytes = (0..contents.len()).step_by(2).map(|i| u8::from_str_radix(&contents[i..i + 2], 16).unwrap()).collect();
sig.set(b"Contents".to_vec(), Object::String(PdfString { bytes, hex: true }));
signatures.push(Object::Ref(doc.add(Object::Dict(sig))));
}
// Nested in another object, it follows nothing, but known directly it is one all the same.
let mut nested = pdfcraft_cos::Dict::new();
nested.set(b"Type".to_vec(), Object::name("Sig"));
nested.set(b"Contents".to_vec(), Object::String(PdfString { bytes: vec![0xAB, 0xBA], hex: true }));
let mut field = pdfcraft_cos::Dict::new();
field.set(b"V".to_vec(), Object::Dict(nested));
signatures.push(Object::Ref(doc.add(Object::Dict(field))));
// Neither of what makes one: a string /Contents alone is anybody's, so it's encrypted.
let mut other = pdfcraft_cos::Dict::new();
other.set(b"Contents".to_vec(), Object::String(PdfString { bytes: vec![0xAB, 0xCD], hex: true }));
signatures.push(Object::Ref(doc.add(Object::Dict(other))));
doc.update_dict(doc.root().unwrap(), |c| c.set(b"Test".to_vec(), Object::Array(signatures))).unwrap();
doc.set_encryption(&NewEncryption {
algorithm: Algorithm::Aes256,
user_password: "",
owner_password: "owner",
permissions: -1,
encrypt_metadata: true,
seed: [3; 32],
})
.unwrap();
let bytes = write_full(&doc, &SaveOptions { object_streams: false, ..SaveOptions::default() }).unwrap();
for contents in ["DEAD", "BEEF", "CAFE", "F00D", "D00D", "ABBA"] {
assert!(holds(&bytes, &format!("<{contents}>")), "{contents}: written as is");
}
assert!(!holds(&bytes, "<ABCD>"), "without a /ByteRange it is no signature");
}
/// What a test needs to write an update of a classic file protected with AES-128.
struct Classic {
bytes: Vec<u8>,
root: ObjRef,
pages: ObjRef,
info: ObjRef,
encrypt: ObjRef,
id: Vec<u8>,
dict: pdfcraft_cos::Dict,
}
fn classic_file() -> Classic {
let mut doc = Document::open(Arc::new(fixture())).unwrap();
doc.set_encryption(&NewEncryption {
algorithm: Algorithm::Aes128,
user_password: "",
owner_password: "owner",
permissions: -1,
encrypt_metadata: true,
seed: [9; 32],
})
.unwrap();
let bytes = write_full(&doc, &SaveOptions { object_streams: false, ..SaveOptions::default() }).unwrap();
let doc = Document::open(Arc::new(bytes.clone())).unwrap();
let encrypt = doc.trailer().reference(b"Encrypt").unwrap();
let id = doc.trailer().get(b"ID").unwrap().as_array().unwrap()[0].as_string().unwrap().bytes.clone();
let dict = doc.get(encrypt).as_dict().cloned().unwrap();
let pages = doc.get(doc.root().unwrap()).as_dict().unwrap().reference(b"Pages").unwrap();
Classic { root: doc.root().unwrap(), pages, info: doc.trailer().reference(b"Info").unwrap(), bytes, encrypt, id, dict }
}
fn hex(bytes: &[u8]) -> String {
bytes.iter().map(|b| format!("{b:02X}")).collect()
}
/// `bytes` with an update appended: `objects`, and a trailer of `trailer` entries, in which `@n`
/// stands for the offset of object `n`. An object with nothing in it gets an entry of the
/// cross-reference table that points at nothing.
fn updated(bytes: &[u8], objects: &[(u32, Vec<u8>)], trailer: &str) -> Vec<u8> {
let at = bytes.windows(9).rposition(|w| w == b"startxref").unwrap();
let prev: usize = String::from_utf8_lossy(&bytes[at + 9..]).split_whitespace().next().unwrap().parse().unwrap();
let mut out = bytes.to_vec();
let mut table = String::from("xref\n");
let mut trailer = trailer.to_string();
for (num, body) in objects {
if body.is_empty() {
table.push_str(&format!("{num} 1\n0000000010 00000 n \n"));
continue;
}
trailer = trailer.replace(&format!("@{num}"), &out.len().to_string());
table.push_str(&format!("{num} 1\n{:010} 00000 n \n", out.len()));
out.extend_from_slice(format!("{num} 0 obj\n").as_bytes());
out.extend_from_slice(body);
out.extend_from_slice(b"\nendobj\n");
}
let xref = out.len();
out.extend_from_slice(table.as_bytes());
out.extend_from_slice(format!("trailer\n<< {trailer} /Size 2000 /Prev {prev} >>\nstartxref\n{xref}\n%%EOF\n").as_bytes());
out
}
/// The `/Encrypt` dictionary of `file`, with `/O`, `/StmF` and `/StrF` as given.
fn encrypt_with(file: &Classic, o: &str, filter: &str) -> Vec<u8> {
let string = |key: &[u8]| hex(&file.dict.get(key).unwrap().as_string().unwrap().bytes);
format!(
"<< /Filter /Standard /V 4 /R 4 /Length 128 /P {} /O {o} /U <{}> /CF << /StdCF << /CFM /AESV2 /Length 16 /AuthEvent /DocOpen >> >> /StmF /{filter} /StrF /{filter} >>",
file.dict.int(b"P").unwrap(),
string(b"U")
)
.into_bytes()
}
/// An object stream can have its parameters by reference, and a stream's crypt filter can be
/// selected by a member of it: legal together, though each is rare. What reads the stream first
/// goes through the object stream, and members must come out of it as they do read directly. They
/// didn't, while a read made for a selector wasn't allowed to follow its own: the object stream was
/// kept undecoded, its members lost for good, and a full save wrote nulls without saying so.
#[test]
fn an_object_stream_reached_from_a_selector_keeps_its_members() {
let file = classic_file();
let parms = "[<< /Name /Identity >> null]";
let header = format!("902 0 903 {} ", parms.len() + 1);
let members = format!("{header}{parms} << /Keep (yes) >>");
let (mut rows, mut before) = (vec![1u8], 0u8);
for b in members.bytes() {
rows.push(b.wrapping_sub(before));
before = b;
}
let coded = pdfcraft_cos::Stream::flate(pdfcraft_cos::Dict::new(), &rows).raw;
let mut object_stream =
format!("<< /Type /ObjStm /N 2 /First {} /Filter /FlateDecode /DecodeParms 911 0 R /Length {} >>\nstream\n", header.len(), coded.len())
.into_bytes();
object_stream.extend_from_slice(&coded);
object_stream.extend_from_slice(b"\nendstream");
let data = [2u8, 0x03, 0x8E, 0, 2, 0x03, 0x8E, 1];
let mut xref = format!("<< /Type /XRef /Size 2000 /W [1 2 1] /Index [902 2] /Length {} >>\nstream\n", data.len()).into_bytes();
xref.extend_from_slice(&data);
xref.extend_from_slice(b"\nendstream");
let string = |key: &[u8]| format!("<{}>", hex(&file.dict.get(key).unwrap().as_string().unwrap().bytes));
let objects = [
(file.root.num, format!("<< /Type /Catalog /Pages {} 0 R /A 900 0 R /B 903 0 R >>", file.pages.num).into_bytes()),
(file.encrypt.num, encrypt_with(&file, &string(b"O"), "Identity")),
(900, b"<< /Filter [/Crypt /ASCIIHexDecode] /DecodeParms 902 0 R /Length 1 >>\nstream\n>\nendstream".to_vec()),
(910, object_stream),
(911, format!("<< /Predictor 11 /Columns {} >>", members.len()).into_bytes()),
(912, xref),
];
let trailer = format!("/Root {} 0 R /Encrypt {} 0 R /ID [<{id}> <{id}>] /XRefStm @912", file.root.num, file.encrypt.num, id = hex(&file.id));
let bytes = updated(&file.bytes, &objects, &trailer);
let keep =
|doc: &Document, r: &Object| doc.resolve(r).as_dict().and_then(|d| d.get(b"Keep")).and_then(Object::as_string).map(|s| s.bytes.clone());
let member = Object::Ref(ObjRef::new(903, 0));
let doc = Document::open(Arc::new(bytes.clone())).unwrap();
assert_eq!(keep(&doc, &member).as_deref(), Some(b"yes".as_slice()), "read first");
let doc = Document::open(Arc::new(bytes.clone())).unwrap();
let _ = doc.get(ObjRef::new(900, 0));
assert_eq!(keep(&doc, &member).as_deref(), Some(b"yes".as_slice()), "read after the stream selecting from it");
let saved = write_full(&Document::open(Arc::new(bytes)).unwrap(), &SaveOptions::default()).unwrap();
let back = Document::open(Arc::new(saved)).unwrap();
let catalog = back.get(back.root().unwrap());
assert_eq!(keep(&back, catalog.as_dict().unwrap().get(b"B").unwrap()).as_deref(), Some(b"yes".as_slice()), "after a full save");
}
/// `walk` goes as deep as an object nests, so following a reference from down there adds that depth
/// again for each object it loads: this file, under 10 KB, overflowed a 2 MiB stack and took the
/// process with it. Only the object itself follows references, and it does so in very little stack.
#[test]
fn nested_dictionaries_load_nothing_on_a_small_stack() {
let file = classic_file();
let first = 960u32;
let objects: Vec<(u32, Vec<u8>)> = (first..first + 40)
.map(|num| {
let open = "[".repeat(120);
let close = "]".repeat(120);
(num, format!("{open}<< /Contents () /Type {} 0 R >>{close}", num + 1).into_bytes())
})
.collect();
let trailer = format!("/Root {} 0 R /Encrypt {} 0 R /ID [<{id}> <{id}>]", file.root.num, file.encrypt.num, id = hex(&file.id));
let bytes = updated(&file.bytes, &objects, &trailer);
let reading = std::thread::Builder::new().stack_size(1 << 20).spawn(move || {
let doc = Document::open(Arc::new(bytes)).unwrap();
doc.get(ObjRef::new(first, 0)).as_array().is_some()
});
assert_eq!(reading.unwrap().join().ok(), Some(true));
}
/// The object itself can follow references, a ladder of them as long as loading may nest, and that
/// fits a small stack too.
#[test]
fn a_ladder_of_signature_checks_fits_a_small_stack() {
let file = classic_file();
let first = 960u32;
let objects: Vec<(u32, Vec<u8>)> =
(first..first + 40).map(|num| (num, format!("<< /Contents () /Type {} 0 R >>", num + 1).into_bytes())).collect();
let trailer = format!("/Root {} 0 R /Encrypt {} 0 R /ID [<{id}> <{id}>]", file.root.num, file.encrypt.num, id = hex(&file.id));
let bytes = updated(&file.bytes, &objects, &trailer);
let reading = std::thread::Builder::new().stack_size(1 << 20).spawn(move || {
let doc = Document::open(Arc::new(bytes)).unwrap();
doc.get(ObjRef::new(first, 0)).as_dict().is_some()
});
assert_eq!(reading.unwrap().join().ok(), Some(true));
}
/// The strings of `/Encrypt` are never encrypted (ISO 32000-2 §7.6.2), and can be objects of their
/// own. Read as ordinary strings they were decrypted, and a full save encrypted them again under
/// another number, so the file it wrote no longer opened with its own password.
#[test]
fn encrypt_strings_given_by_reference_stay_as_stored() {
let file = classic_file();
let string = |key: &[u8]| hex(&file.dict.get(key).unwrap().as_string().unwrap().bytes);
let replaced = format!(
"<< /Filter /Standard /V 4 /R 4 /Length 128 /P {} /O 900 0 R /U 901 0 R /CF << /StdCF << /CFM /AESV2 /Length 16 /AuthEvent /DocOpen >> >> /StmF /StdCF /StrF /StdCF >>",
file.dict.int(b"P").unwrap()
);
let objects = [
(file.encrypt.num, replaced.into_bytes()),
(900, format!("<{}>", string(b"O")).into_bytes()),
(901, format!("<{}>", string(b"U")).into_bytes()),
];
let trailer =
format!("/Root {} 0 R /Info {} 0 R /Encrypt {} 0 R /ID [<{id}> <{id}>]", file.root.num, file.info.num, file.encrypt.num, id = hex(&file.id));
let source = Document::open(Arc::new(updated(&file.bytes, &objects, &trailer))).unwrap();
assert_eq!(content(&source), SECRET, "the file reads");
assert_eq!(title(&source).as_deref(), Some("Quarterly numbers"));
for object_streams in [false, true] {
let saved = write_full(&source, &SaveOptions { object_streams, ..SaveOptions::default() }).unwrap();
let back = Document::open(Arc::new(saved)).unwrap();
assert_eq!(content(&back), SECRET, "object streams: {object_streams}");
assert_eq!(title(&back).as_deref(), Some("Quarterly numbers"), "object streams: {object_streams}");
}
}
/// A save keeps what a file is protected with: its `/Encrypt`, which holds the handler and the
/// permissions, its `/ID`, and so its file key, under every algorithm and by either kind of save.
#[test]
fn a_save_keeps_the_handler_the_key_and_the_permissions() {
for alg in ALL {
let doc = Document::open_with_password(Arc::new(protect(alg, "user", "owner", -1 ^ 0b1_0000)), Some("user")).unwrap();
let held = |d: &Document| {
let encrypt = d.resolve(d.trailer().get(b"Encrypt").unwrap()).as_dict().unwrap().clone();
(encrypt, d.trailer().get(b"ID").cloned(), d.security().unwrap().file_key().to_vec(), format!("{:?}", d.permissions()))
};
let before = held(&doc);
let mut edited = doc.clone();
let _ = edited.add(Object::Int(1));
for (save, saved) in [
("incremental", write_incremental(&edited, &SaveOptions::default()).unwrap()),
("full", write_full(&doc, &SaveOptions::default()).unwrap()),
] {
let back = Document::open_with_password(Arc::new(saved), Some("user")).unwrap();
assert!(held(&back) == before, "{alg:?}: a {save} save");
assert_eq!(content(&back), SECRET, "{alg:?}: a {save} save");
}
}
}
/// `/ID` has to be direct in an encrypted file, but one that isn't has its key made from the same
/// bytes. A full save writes it direct, and an incremental one leaves it as it was.
#[test]
fn a_file_identifier_given_by_reference_is_read() {
let file = classic_file();
let id = hex(&file.id);
let reference = |entries: &str, objects: &[(u32, Vec<u8>)]| {
let trailer = format!("/Root {} 0 R /Encrypt {} 0 R /ID {entries}", file.root.num, file.encrypt.num);
updated(&file.bytes, objects, &trailer)
};
let whole = reference("900 0 R", &[(900, format!("[<{id}> <{id}>]").into_bytes())]);
let entries = reference("[900 0 R 901 0 R]", &[(900, format!("<{id}>").into_bytes()), (901, format!("<{id}>").into_bytes())]);
for file in [whole, entries] {
let source = Document::open(Arc::new(file)).unwrap();
assert_eq!(content(&source), SECRET);
let back = Document::open(Arc::new(write_full(&source, &SaveOptions::default()).unwrap())).unwrap();
assert_eq!(content(&back), SECRET);
assert!(matches!(back.trailer().get(b"ID"), Some(Object::Array(_))), "written direct");
let mut edited = source.clone();
let _ = edited.add(Object::Int(1));
let back = Document::open(Arc::new(write_incremental(&edited, &SaveOptions::default()).unwrap())).unwrap();
assert_eq!(content(&back), SECRET, "an incremental save");
assert_eq!(back.trailer().get(b"ID"), edited.trailer().get(b"ID"), "and leaves it as it was");
}
}
/// A direct `/Encrypt` can refer to objects. A full save dropped those it found only there, and kept
/// its references as they were under the old numbers, so nothing in the file read afterwards.
#[test]
fn a_direct_encrypt_dictionary_keeps_what_it_refers_to() {
for object_streams in [false, true] {
let mut doc = Document::open(Arc::new(fixture())).unwrap();
doc.set_encryption(&NewEncryption {
algorithm: Algorithm::Aes128,
user_password: "",
owner_password: "owner",
permissions: -1,
encrypt_metadata: true,
seed: [9; 32],
})
.unwrap();
let mut dict = doc.get(doc.trailer().reference(b"Encrypt").unwrap()).as_dict().cloned().unwrap();
let filter = doc.add(Object::name("StdCF"));
let filters = doc.add(dict.get(b"CF").unwrap().clone());
dict.set(b"StmF".to_vec(), Object::Ref(filter));
dict.set(b"CF".to_vec(), Object::Ref(filters));
doc.trailer_mut().set(b"Encrypt".to_vec(), Object::Dict(dict));
let options = SaveOptions { object_streams, ..SaveOptions::default() };
let saved = write_full(&doc, &options).unwrap();
let back = Document::open(Arc::new(saved)).unwrap();
assert_eq!(content(&back), SECRET, "object streams: {object_streams}");
let again = write_full(&back, &options).unwrap();
assert_eq!(content(&Document::open(Arc::new(again)).unwrap()), SECRET, "object streams: {object_streams}, saved again");
}
}
/// How a stream is treated can be given by reference, and what that loads can be a stream too. A
/// file can make a ladder of those, where each rung reads the rung below, then two trees wider than
/// the object cache, which push that rung out of it, then the rung below again. Each rung would
/// take twice what the one below does, if one read could follow any number of references.
#[test]
fn selectors_that_lead_to_selectors_load_at_once() {
let mut doc = Document::open(Arc::new(protect(Algorithm::Aes128, "", "owner", -1))).unwrap();
let stream_of = |doc: &mut Document, filters: Vec<Object>| {
let mut dict = pdfcraft_cos::Dict::new();
dict.set(b"Filter".to_vec(), Object::Array(filters));
doc.add(Object::Stream(pdfcraft_cos::Stream::from_raw(dict, Vec::new())))
};
let tree = |doc: &mut Document| {
let mut level: Vec<ObjRef> = (0..6_561).map(|i| doc.add(Object::Int(i))).collect();
while level.len() > 1 {
let chunks: Vec<Vec<Object>> = level.chunks(9).map(|c| c.iter().map(|r| Object::Ref(*r)).collect()).collect();
level = chunks.into_iter().map(|c| stream_of(doc, c)).collect();
}
Object::Ref(level[0])
};
let (first, second) = (tree(&mut doc), tree(&mut doc));
let mut top = doc.add(Object::Int(0));
// Twelve rungs of two, and the trees' five levels, stay inside the 32 that loading may nest.
for _ in 0..12 {
let (a, b) = (stream_of(&mut doc, vec![Object::Ref(top)]), stream_of(&mut doc, vec![Object::Ref(top)]));
top = stream_of(&mut doc, vec![Object::Ref(a), first.clone(), second.clone(), Object::Ref(b)]);
}
let saved = write_incremental(&doc, &SaveOptions::default()).unwrap();
let (done, finished) = std::sync::mpsc::channel();
std::thread::spawn(move || {
let doc = Document::open(Arc::new(saved)).unwrap();
let _ = done.send(doc.get(top).as_dict().is_some());
});
// With the budget it takes milliseconds, and without it longer than anyone would wait, so a
// margin this wide can't fail on a busy machine.
assert_eq!(finished.recv_timeout(std::time::Duration::from_secs(120)), Ok(true), "loading must not fan out");
}
+10
View File
@@ -228,6 +228,16 @@ fn incremental_save_keeps_a_trailer_only_edit() {
assert_qpdf_clean(&saved);
}
#[test]
fn incremental_save_ignores_a_negative_trailer_size() {
let mut doc = Document::open(Arc::new(classic_table())).unwrap();
doc.trailer_mut().set(b"Size".to_vec(), Object::Int(-1));
let next = doc.add(Object::Int(5)).num + 1;
let saved = write_incremental(&doc, &SaveOptions::default()).unwrap();
let back = Document::open(Arc::new(saved)).unwrap();
assert_eq!(back.trailer().int(b"Size"), Some(i64::from(next)));
}
/// What one edit added and a later one unlinked (a deleted comment, a cleared redaction mark) is
/// not written: the file never held it, and writing it would keep what was removed. Additions the
/// update still refers to, from the trailer or a changed object and through other additions, are.
-2
View File
@@ -15,8 +15,6 @@ pdfcraft-model = { workspace = true }
pdfcraft-fonts = { workspace = true }
# For `image::bmp_with_pixel_offset`, shared with XFA pictures.
pdfcraft-xfa = { workspace = true }
# Already in the graph through hayro: decodes JBIG2 images for Export ▸ Images.
hayro-jbig2.workspace = true
png = "0.18"
tiff = "0.11"
image = { version = "0.25", default-features = false, features = ["bmp", "gif", "jpeg"] }
+9 -6
View File
@@ -27,11 +27,14 @@ Layer L4. Create a PDF (Acrobat's Create a PDF tool), execution plan M10.2:
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.
JBIG2 images and masks (JBIG2 as their only filter) are decoded with `hayro-jbig2`, their `/JBIG2Globals` included,
as `JBIG2Decode` gives them: black as 0. An image whose JBIG2 page has another width than the image, or more
pixels than an exported image may have, or whose globals decode to more than 32 MiB (they are decoded before the
page's size is known, so they have a limit of their own), is skipped; such a mask is left out and the image
exported opaque, as JPX and CCITT masks are.
JBIG2 images and masks are decoded through `pdfcraft_cos::ImageBudget` (`pdfcraft_filters::decode_jbig2_within`), behind
other filters too, with the `/JBIG2Globals` of their own `/DecodeParms` entry, as `JBIG2Decode` gives them: black as 0. An image
whose JBIG2 page isn't its size (PdfCraft's renderer draws the whole page into the image; the page is refused before it is decoded),
or whose globals can't be read or decode to more than 32 MiB (they are decoded before the page's size is known, so they have a
limit of their own), is skipped, and such a mask is left out and the image exported opaque, as JPX and CCITT masks are.
Past what one export may decode, which its images share, filters, decoders and pixels alike (`ImageBudget`; a JPEG when it has to be
decoded, as a mask, to apply one, or to undo a CMYK file's inversion, and not when it is written as it is), an image is skipped, and so is one whose mask is past it, which would otherwise come out showing what the mask hides. An export also stops at 2 GiB of files held, or twice the document if that
is more, since they stay in memory until it ends.
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.
Soft-mask Decode intervals map samples to opacity before the mask is resized, including reversed ranges and indirect entries.
@@ -43,4 +46,4 @@ CCITT fax images (Group 3 and 4) are decoded for export through `pdfcraft_cos::D
`ASCII85Decode` too. Byte-aligned Group 3 rows are read by their end-of-line codes, whether the fill starts each code on a byte or
ends it on one, when the data starts with one (T.4 sends one before the first row), and on bytes otherwise, whatever `/EndOfLine`
says; data that comes up short is reported. Data with codes but none before the first row is read on bytes, and is reported or,
at `/K 0`, may come out wrong. JPEG 2000 and JBIG2 images are still reported, not exported.
at `/K 0`, may come out wrong. JPEG 2000 images are still reported, not exported.
+114 -130
View File
@@ -6,7 +6,8 @@
use std::collections::HashSet;
use pdfcraft_cos::{Dict, Document, ObjRef, Object, Stream};
use pdfcraft_cos::{Dict, Document, ImageBudget, MAX_DECODED, ObjRef, Object, Stream};
use pdfcraft_filters::FilterError;
/// One image, ready to write.
#[derive(Clone, Debug, PartialEq)]
@@ -31,12 +32,29 @@ pub struct ImageExport {
/// Images larger than this many pixels are skipped (memory).
const MAX_PIXELS: u64 = 100_000_000;
/// What one export may hold of the files it makes: they are all in memory until it ends, and a file
/// of a few KB can make gigabytes of PNG. Images past it are left out, with the reason.
const MAX_EXPORT_BYTES: usize = 2 << 30;
/// What an export of a file of `file_bytes` may hold: twice the file if that is more than
/// [`MAX_EXPORT_BYTES`], so that a file of large images is exported whole.
pub(crate) fn export_bytes(file_bytes: usize) -> usize {
MAX_EXPORT_BYTES.max(file_bytes.saturating_mul(2))
}
/// The images of `pages` (0-based; each image once, on the first page using it), skipping
/// those with fewer than `min_side` pixels on their shorter side.
pub fn extract_images(doc: &Document, pages: &[usize], min_side: u32) -> ImageExport {
extract_images_within(doc, pages, min_side, &mut ImageBudget::new(doc), export_bytes(doc.bytes().len()))
}
/// [`extract_images`] within `budget`, and holding `max_bytes` of files. An image past either is
/// left out, with the reason.
pub(crate) fn extract_images_within(doc: &Document, pages: &[usize], min_side: u32, budget: &mut ImageBudget, max_bytes: usize) -> ImageExport {
let all = pdfcraft_model::pages(doc);
let mut out = ImageExport::default();
let mut seen = HashSet::new();
let mut held = 0usize;
for &p in pages {
let Some(page) = all.get(p) else { continue };
let mut refs = Vec::new();
@@ -53,8 +71,15 @@ pub fn extract_images(doc: &Document, pages: &[usize], min_side: u32) -> ImageEx
if w <= 0 || h <= 0 || (w.min(h) as u64) < min_side as u64 {
continue;
}
match image(doc, s) {
Ok((extension, data)) => out.images.push(ExtractedImage { page: p, object: r, width: w as u32, height: h as u32, extension, data }),
if held >= max_bytes {
out.skipped.push((p, r, "more images than one export can hold".into()));
continue;
}
match image(doc, s, budget) {
Ok((extension, data)) => {
held = held.saturating_add(data.len());
out.images.push(ExtractedImage { page: p, object: r, width: w as u32, height: h as u32, extension, data });
}
Err(why) => out.skipped.push((p, r, why)),
}
}
@@ -64,8 +89,13 @@ pub fn extract_images(doc: &Document, pages: &[usize], min_side: u32) -> ImageEx
/// One image XObject as a file: JPEG as is, else PNG ("Save image as").
pub fn image_file(doc: &Document, image: ObjRef) -> Result<(&'static str, Vec<u8>), String> {
image_file_within(doc, image, &mut ImageBudget::new(doc))
}
/// [`image_file`] within `budget`, for a caller making a file of many images.
pub fn image_file_within(doc: &Document, image: ObjRef, budget: &mut ImageBudget) -> Result<(&'static str, Vec<u8>), String> {
match &*doc.get(image) {
Object::Stream(s) if s.dict.name(b"Subtype") == Some(b"Image") => self::image(doc, s),
Object::Stream(s) if s.dict.name(b"Subtype") == Some(b"Image") => self::image(doc, s, budget),
_ => Err("not an image".into()),
}
}
@@ -100,125 +130,24 @@ fn filters(s: &Stream) -> Vec<Vec<u8>> {
}
}
/// The samples of image `s`, decoded: through its filters, with a `/DecodeParms` dictionary given
/// by reference, or as an array's entry, or with numbers inside by reference, read too (a predictor
/// given so would otherwise be lost), or, for a JBIG2 image
/// (its only filter), through a JBIG2 decoder with its `/JBIG2Globals`, as rows of one-bit samples
/// each starting on a byte, with black as 0, as `JBIG2Decode` gives them (ISO 32000-2 §7.4.7).
fn decoded(doc: &Document, s: &Stream) -> Result<Vec<u8>, String> {
match filters(s).as_slice() {
[f] if f == b"JBIG2Decode" => jbig2(doc, s),
_ => doc.decoded_image(s).map_err(|e| e.to_string()),
}
}
/// The `/DecodeParms` of a stream with one filter: a dictionary, or the one in an array (7.4.2).
fn decode_parms(doc: &Document, s: &Stream) -> Dict {
let Some(p) = s.dict.get(b"DecodeParms").map(|p| doc.resolve(p)) else { return Dict::default() };
let p = match &*p {
Object::Array(a) => match a.first() {
Some(first) => doc.resolve(first),
None => return Dict::default(),
},
_ => p,
};
p.as_dict().cloned().unwrap_or_default()
}
/// The most an image's `/JBIG2Globals` decode to: the symbol and pattern dictionaries an encoder
/// shares between pages, themselves coded, so far less than any stream may decode to
/// ([`pdfcraft_cos::MAX_DECODED`], 1 GiB). Globals past it refuse the image.
const MAX_GLOBALS: usize = 32 << 20;
/// [`decoded`] for a JBIG2 image. Its JBIG2 page has to be the image's width, which the caller
/// checked against the export's size limit, and within that limit itself: the decoder decodes the
/// whole page, rows past the image's height too, so a small `/Height` over a far taller page
/// would cost more than the limit allows. Rows past the image's height are dropped, and too few
/// rows are refused by the caller. Globals that can't be read refuse the image, rather than
/// decoding it without them. They are decoded before the page's size is known, so the page's
/// limit can't bound them; they have [`MAX_GLOBALS`] of their own.
fn jbig2(doc: &Document, s: &Stream) -> Result<Vec<u8>, String> {
let globals = match decode_parms(doc, s).get(b"JBIG2Globals").map(|g| doc.resolve(g)).as_deref() {
Some(Object::Stream(g)) => {
Some(doc.with_direct_parms(g).decoded_within(MAX_GLOBALS).map_err(|e| format!("the JBIG2 globals can't be read: {e}"))?)
}
_ => None,
};
let image = hayro_jbig2::Image::new_embedded(&s.raw, globals.as_deref()).map_err(|e| format!("the JBIG2 image can't be read: {e}"))?;
if s.dict.int(b"Width") != Some(i64::from(image.width())) {
return Err("the JBIG2 image's width isn't the image's width".into());
}
if u64::from(image.width()).saturating_mul(u64::from(image.height())) > MAX_PIXELS {
return Err(format!("the JBIG2 page, {} × {}, is too large to export", image.width(), image.height()));
}
let height = s.dict.int(b"Height").and_then(|h| usize::try_from(h).ok()).unwrap_or(0);
let mut rows = Rows::new(image.width() as usize, height);
image.decode(&mut rows).map_err(|e| format!("the JBIG2 image can't be decoded: {e}"))?;
Ok(rows.out)
}
/// Rows of one-bit samples, each starting on a byte, filled from a decoder's pixels: `columns`
/// a row and at most `rows` rows. Pixels past a row's end and rows past the last are dropped, so
/// the output is bounded by the size the caller gave.
struct Rows {
out: Vec<u8>,
row: Vec<u8>,
x: usize,
columns: usize,
rows: usize,
done: usize,
}
impl Rows {
fn new(columns: usize, rows: usize) -> Self {
Rows { out: Vec::new(), row: vec![0; columns.div_ceil(8)], x: 0, columns, rows, done: 0 }
}
/// `count` pixels, as 1 samples when `one`.
fn push(&mut self, one: bool, count: usize) {
let end = self.x.saturating_add(count);
if one {
for x in self.x..end.min(self.columns) {
if let Some(b) = self.row.get_mut(x / 8) {
*b |= 0x80 >> (x % 8);
}
}
}
self.x = end;
}
fn end_row(&mut self) {
if self.done < self.rows {
self.out.extend_from_slice(&self.row);
self.done += 1;
}
self.row.fill(0);
self.x = 0;
}
}
/// JBIG2 codes black as 1, which `JBIG2Decode` gives as 0.
impl hayro_jbig2::Decoder for Rows {
fn push_pixel(&mut self, black: bool) {
self.push(!black, 1);
}
fn push_pixel_chunk(&mut self, black: bool, chunks: u32) {
self.push(!black, (chunks as usize).saturating_mul(8));
}
fn next_line(&mut self) {
self.end_row();
}
/// The samples of image `s`, decoded ([`ImageBudget::decode`]): through its filters, with a
/// `/DecodeParms` dictionary given by reference, or as an array's entry, or with numbers inside by
/// reference, read too (a predictor given so would otherwise be lost); a CCITT fax or JBIG2 image
/// through its decoder too, behind other filters as well, a JBIG2 image with its `/JBIG2Globals`.
/// A JBIG2 page has to be the image's size, which the caller checked against the export's limit,
/// before the page is decoded.
fn decoded(doc: &Document, s: &Stream, budget: &mut ImageBudget) -> Result<Vec<u8>, String> {
budget.decode(doc, s, MAX_DECODED).map_err(|e| e.to_string())
}
/// The file for one image: its JPEG data as is, or a PNG. An image with transparency (a soft
/// mask, a stencil `/Mask` or a colour-key `/Mask`) is always a PNG with that transparency as
/// alpha, JPEG images included, so cut-out images keep their transparent background.
fn image(doc: &Document, s: &Stream) -> Result<(&'static str, Vec<u8>), String> {
fn image(doc: &Document, s: &Stream, budget: &mut ImageBudget) -> Result<(&'static str, Vec<u8>), String> {
let f = filters(s);
let jpeg = matches!(f.last().map(Vec::as_slice), Some(b"DCTDecode" | b"DCT")) && f.len() == 1;
match f.last().map(Vec::as_slice) {
Some(b"JPXDecode") => return Err("JPEG 2000 images can't be exported yet".into()),
Some(b"JBIG2Decode") if f.len() > 1 => return Err("JBIG2 images inside other filters can't be exported yet".into()),
Some(b"DCTDecode" | b"DCT") if !jpeg => return Err("JPEG images inside other filters can't be exported yet".into()),
_ => {}
}
@@ -233,14 +162,24 @@ fn image(doc: &Document, s: &Stream) -> Result<(&'static str, Vec<u8>), String>
};
let mask = s.dict.get(b"ImageMask").is_some_and(|m| matches!(&*doc.resolve(m), Object::Bool(true)));
// A stencil mask (`ImageMask true`) has no /SMask or /Mask of its own (8.9.6.2).
let mut alpha = if mask { None } else { soft_mask(doc, s, w, h).or_else(|| stencil_mask(doc, s, w, h)) };
let refused = budget.refused();
let mut alpha = if mask { None } else { soft_mask(doc, s, w, h, budget).or_else(|| stencil_mask(doc, s, w, h, budget)) };
// Without its mask the image would come out opaque, showing what the mask hides.
if budget.refused() > refused {
return Err(FilterError::Spent.to_string());
}
let key = if mask { None } else { colour_key(doc, s) };
// Keep the existing JPEG and stencil-mask Decode handling separate from lossless colour images.
let endpoint = |value: Option<&Object>| value.map(|v| doc.resolve(v)).and_then(|v| v.as_f64()).filter(|v| v.is_finite());
let inverted = (jpeg || mask)
&& s.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)))
// Both ends have to be finite numbers, as for lossless images, or the default mapping stands.
.and_then(|d| {
let a = d.as_array()?;
Some(endpoint(a.first())? > endpoint(a.get(1))?)
})
.unwrap_or(false);
// In a PDF a CMYK JPEG's samples are ink amounts unless /Decode inverts them, while image
// viewers read a CMYK JPEG file as inverted (Adobe's convention): as is, it would show as
@@ -251,13 +190,16 @@ fn image(doc: &Document, s: &Stream) -> Result<(&'static str, Vec<u8>), String>
}
let mut space = if mask { Space::Gray } else { space(doc, s.dict.get(b"ColorSpace"))? };
let (samples, bpc) = if jpeg {
if !budget.pay_jpeg((w as u64).saturating_mul(h as u64).saturating_mul(space.components() as u64), &s.raw) {
return Err(FilterError::Spent.to_string());
}
// Grey, RGB or CMYK samples (YCCK is converted); a JPEG that doesn't decode, or an
// indexed one (not valid), is written as is, without its transparency.
let Some((samples, decoded)) = jpeg_samples(&s.raw, &space, w, h) else { return as_is() };
space = decoded;
(samples, 8)
} else {
let data = decoded(doc, s)?;
let data = decoded(doc, s, budget)?;
let bpc = if mask { 1 } else { s.dict.int(b"BitsPerComponent").unwrap_or(8) };
let bpc = match bpc {
1 => 1,
@@ -348,6 +290,32 @@ fn size(w: i64, h: i64) -> Option<(usize, usize)> {
(w > 0 && h > 0 && pixels <= MAX_PIXELS).then_some((w, h))
}
#[cfg(test)]
thread_local! {
/// JPEGs decoded whole, for the tests that keep one from being decoded for nothing.
pub(crate) static JPEGS_DECODED: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
/// The size a JPEG's header gives, which is what decoding it goes by, whatever its dictionary
/// says: an image of one pixel can hold a header of 500 megapixels.
fn jpeg_size(data: &[u8]) -> Option<(usize, usize)> {
use zune_jpeg::zune_core::{bytestream::ZCursor, options::DecoderOptions};
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()?;
dec.dimensions()
}
/// JPEG `data`, decoded, if its header says it is `w` × `h`.
fn jpeg_of_size(data: &[u8], w: usize, h: usize) -> Option<image::DynamicImage> {
if jpeg_size(data)? != (w, h) {
return None;
}
#[cfg(test)]
JPEGS_DECODED.with(|n| n.set(n.get() + 1));
image::load_from_memory_with_format(data, image::ImageFormat::Jpeg).ok()
}
/// A JPEG's samples (8 bits): grey for a grey image, CMYK as stored for a CMYK one, else RGB,
/// with the space they are in.
fn jpeg_samples(data: &[u8], space: &Space, w: usize, h: usize) -> Option<(Vec<u8>, Space)> {
@@ -356,10 +324,7 @@ fn jpeg_samples(data: &[u8], space: &Space, w: usize, h: usize) -> Option<(Vec<u
Space::Cmyk => return cmyk_jpeg_samples(data, w, h).map(|px| (px, Space::Cmyk)),
_ => {}
}
let img = image::load_from_memory_with_format(data, image::ImageFormat::Jpeg).ok()?;
if img.width() as usize != w || img.height() as usize != h {
return None;
}
let img = jpeg_of_size(data, w, h)?;
Some(match space {
Space::Gray => (img.into_luma8().into_raw(), Space::Gray),
_ => (img.into_rgb8().into_raw(), Space::Rgb),
@@ -560,32 +525,35 @@ fn cmyk(c: u8, m: u8, y: u8, k: u8) -> [u8; 3] {
}
/// The soft mask (`/SMask`) as 8-bit alpha, scaled to the image's size when it has another.
fn soft_mask(doc: &Document, s: &Stream, w: usize, h: usize) -> Option<Vec<u8>> {
fn soft_mask(doc: &Document, s: &Stream, w: usize, h: usize, budget: &mut ImageBudget) -> Option<Vec<u8>> {
let r = s.dict.get(b"SMask")?.as_ref()?;
let obj = doc.get(r);
let Object::Stream(m) = &*obj else { return None };
gray_plane(doc, m, w, h)
gray_plane(doc, m, w, h, budget)
}
/// A stencil `/Mask` (an image mask stream, 8.9.6.3) as 8-bit alpha: its 1 samples (0 with
/// `/Decode [1 0]`) hide the image.
fn stencil_mask(doc: &Document, s: &Stream, w: usize, h: usize) -> Option<Vec<u8>> {
fn stencil_mask(doc: &Document, s: &Stream, w: usize, h: usize, budget: &mut ImageBudget) -> Option<Vec<u8>> {
let r = s.dict.get(b"Mask")?.as_ref()?;
let obj = doc.get(r);
let Object::Stream(m) = &*obj else { return None };
Some(gray_plane(doc, m, w, h)?.into_iter().map(|v| 255 - v).collect())
Some(gray_plane(doc, m, w, h, budget)?.into_iter().map(|v| 255 - v).collect())
}
/// 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 masks).
fn gray_plane(doc: &Document, m: &Stream, w: usize, h: usize) -> Option<Vec<u8>> {
fn gray_plane(doc: &Document, m: &Stream, w: usize, h: usize, budget: &mut ImageBudget) -> Option<Vec<u8>> {
let (mw, mh) = size(m.dict.int(b"Width")?, m.dict.int(b"Height")?)?;
let stencil = m.dict.get(b"ImageMask").is_some_and(|v| matches!(&*doc.resolve(v), Object::Bool(true)));
let f = filters(m);
let mut px = match f.last().map(Vec::as_slice) {
Some(b"DCTDecode" | b"DCT") if f.len() == 1 => {
let img = image::load_from_memory_with_format(&m.raw, image::ImageFormat::Jpeg).ok()?.into_luma8();
(img.width() as usize == mw && img.height() as usize == mh).then(|| img.into_raw())?
// Past the allowance the image goes too: `image` sees this one refused.
if !budget.pay_jpeg((mw as u64).saturating_mul(mh as u64), &m.raw) {
return None;
}
jpeg_of_size(&m.raw, mw, mh)?.into_luma8().into_raw()
}
Some(b"DCTDecode" | b"DCT" | b"JPXDecode") => return None,
_ => {
@@ -599,7 +567,7 @@ fn gray_plane(doc: &Document, m: &Stream, w: usize, h: usize) -> Option<Vec<u8>>
_ => return None,
};
let max = (1u32 << bpc.min(8)) - 1;
unpack(&decoded(doc, m).ok()?, mw, mh, 1, bpc)?.into_iter().map(|v| (v as u32 * 255 / max) as u8).collect()
unpack(&decoded(doc, m, budget).ok()?, mw, mh, 1, bpc)?.into_iter().map(|v| (v as u32 * 255 / max) as u8).collect()
}
};
if let Some([lo, hi]) = decode(doc, m, 1).and_then(|pairs| pairs.first().copied()) {
@@ -612,7 +580,23 @@ fn gray_plane(doc: &Document, m: &Stream, w: usize, h: usize) -> Option<Vec<u8>>
return Some(px);
}
let img = image::GrayImage::from_raw(mw as u32, mh as u32, px)?;
Some(image::imageops::resize(&img, w as u32, h as u32, image::imageops::FilterType::Triangle).into_raw())
Some(scaled(&img, w as u32, h as u32).into_raw())
}
/// `img` scaled to `w` × `h`. Scaling goes down first, through a buffer of `img`'s width by `h` at
/// 16 bytes a pixel, which a mask of other proportions than its image can make larger than any
/// machine: 100,000 × 1 on an image of 1 × 100,000 asks for 160 GB, and that aborts the process.
/// Such a mask is scaled across first, which holds no more pixels than one of the two has. Past a
/// quarter over the larger of them, so that rounding leaves a mask of its image's shape as it was.
pub(crate) fn scaled(img: &image::GrayImage, w: u32, h: u32) -> image::GrayImage {
use image::imageops::{FilterType, resize};
let (mw, mh) = (u64::from(img.width()), u64::from(img.height()));
let largest = (mw * mh).max(u64::from(w) * u64::from(h));
if (mw * u64::from(h)).saturating_mul(4) > largest.saturating_mul(5) {
resize(&resize(img, w, img.height(), FilterType::Triangle), w, h, FilterType::Triangle)
} else {
resize(img, w, h, FilterType::Triangle)
}
}
fn png(w: u32, h: u32, rgb: &[u8], alpha: Option<&[u8]>) -> Result<Vec<u8>, String> {
+51 -26
View File
@@ -6,7 +6,7 @@ use pdfcraft_cos::{Dict, Document, ObjRef, Object, PdfString, Stream, serialize}
mod extract;
mod upright_image;
pub use extract::{ExtractedImage, ImageExport, extract_images, image_file};
pub use extract::{ExtractedImage, ImageExport, extract_images, image_file, image_file_within};
use pdfcraft_fonts::{literal, win_ansi, wrap};
#[derive(Debug, thiserror::Error, PartialEq)]
@@ -23,29 +23,48 @@ pub const LETTER: (f64, f64) = (612.0, 792.0);
/// The largest page side PDF allows (ISO 32000-2 Annex C: 14 400 units).
const MAX_SIDE: f64 = 14_400.0;
fn add_page(doc: &mut Document, w: f64, h: f64, resources: Dict, content: Option<Vec<u8>>) -> Result<ObjRef, CreateError> {
// `Document::new_empty` always has a page tree.
let pages = doc
.root()
.and_then(|r| doc.get(r).as_dict().and_then(|d| d.reference(b"Pages")))
.ok_or_else(|| CreateError::Invalid("the new document has no page tree".into()))?;
let mut page = Dict::new();
page.set(b"Type".to_vec(), Object::name("Page"));
page.set(b"Parent".to_vec(), Object::Ref(pages));
page.set(b"MediaBox".to_vec(), Object::Array(vec![0.into(), 0.into(), Object::Real(w), Object::Real(h)]));
page.set(b"Resources".to_vec(), Object::Dict(resources));
if let Some(c) = content {
let s = doc.add(Object::Stream(Stream::flate(Dict::new(), &c)));
page.set(b"Contents".to_vec(), Object::Ref(s));
/// The page tree of a document being made, with the pages added to it so far: its `/Kids` are
/// written once, by [`Pages::finish`]. Adding each page to the tree in the document would copy every
/// page before it, which a text of a million form feeds makes quadratic.
struct Pages {
tree: ObjRef,
kids: Vec<Object>,
}
impl Pages {
/// The page tree of `doc`, with the pages it has.
fn of(doc: &Document) -> Result<Self, CreateError> {
// `Document::new_empty` always has a page tree.
let tree = doc
.root()
.and_then(|r| doc.get(r).as_dict().and_then(|d| d.reference(b"Pages")))
.ok_or_else(|| CreateError::Invalid("the new document has no page tree".into()))?;
let kids = doc.get(tree).as_dict().and_then(|d| d.get(b"Kids")).and_then(|k| k.as_array().cloned()).unwrap_or_default();
Ok(Self { tree, kids })
}
fn add(&mut self, doc: &mut Document, w: f64, h: f64, resources: Dict, content: Option<Vec<u8>>) {
let mut page = Dict::new();
page.set(b"Type".to_vec(), Object::name("Page"));
page.set(b"Parent".to_vec(), Object::Ref(self.tree));
page.set(b"MediaBox".to_vec(), Object::Array(vec![0.into(), 0.into(), Object::Real(w), Object::Real(h)]));
page.set(b"Resources".to_vec(), Object::Dict(resources));
if let Some(c) = content {
let s = doc.add(Object::Stream(Stream::flate(Dict::new(), &c)));
page.set(b"Contents".to_vec(), Object::Ref(s));
}
self.kids.push(Object::Ref(doc.add(page)));
}
/// Writes the pages added into the tree.
fn finish(self, doc: &mut Document) -> Result<(), CreateError> {
let count = i64::try_from(self.kids.len()).map_err(|_| CreateError::Invalid("too many pages".into()))?;
doc.update_dict(self.tree, |d| {
d.set(b"Count".to_vec(), Object::Int(count));
d.set(b"Kids".to_vec(), Object::Array(self.kids));
})
.map_err(|e| CreateError::Invalid(e.to_string()))
}
let r = doc.add(page);
let _ = doc.update_dict(pages, |d| {
let mut kids = d.get(b"Kids").and_then(|k| k.as_array().cloned()).unwrap_or_default();
kids.push(Object::Ref(r));
d.set(b"Count".to_vec(), Object::Int(kids.len() as i64));
d.set(b"Kids".to_vec(), Object::Array(kids));
});
Ok(r)
}
fn set_title(doc: &mut Document, title: &str) {
@@ -65,9 +84,11 @@ pub fn blank(width: f64, height: f64, pages: usize) -> Result<Document, CreateEr
return Err(CreateError::Invalid("invalid page size or count".into()));
}
let mut doc = Document::new_empty();
let mut tree = Pages::of(&doc)?;
for _ in 0..pages {
add_page(&mut doc, width, height, Dict::new(), None)?;
tree.add(&mut doc, width, height, Dict::new(), None);
}
tree.finish(&mut doc)?;
Ok(doc)
}
@@ -675,6 +696,7 @@ pub fn from_images_with_resolution(images: &[(String, Vec<u8>)], resolution: Ima
return Err(CreateError::Invalid("no images".into()));
}
let mut doc = Document::new_empty();
let mut tree = Pages::of(&doc)?;
let mut profiles = Vec::new();
for img in images.iter().map(|(name, bytes)| embed(name, bytes, usize::MAX)).collect::<Result<Vec<_>, _>>()?.into_iter().flatten() {
let dpi = match resolution {
@@ -692,8 +714,9 @@ pub fn from_images_with_resolution(images: &[(String, Vec<u8>)], resolution: Ima
let mut res = Dict::new();
res.set(b"XObject".to_vec(), Object::Dict(xobj));
let content = format!("q {w:.3} 0 0 {h:.3} 0 0 cm /Im0 Do Q\n").into_bytes();
add_page(&mut doc, w, h, res, Some(content))?;
tree.add(&mut doc, w, h, res, Some(content));
}
tree.finish(&mut doc)?;
if let Some((name, _)) = images.first() {
set_title(&mut doc, name.rsplit_once('.').map_or(name.as_str(), |(s, _)| s));
}
@@ -787,6 +810,7 @@ fn set_text(title: &str, text: &str, page: (f64, f64), font_size: f64) -> Result
font.set(b"BaseFont".to_vec(), Object::name("Helvetica"));
font.set(b"Encoding".to_vec(), Object::name("WinAnsiEncoding"));
let fr = doc.add(font);
let mut tree = Pages::of(&doc)?;
let mut page_lines: Vec<Vec<String>> = vec![Vec::new()];
for l in lines.iter().take(lines.len().saturating_sub(1)) {
if l == "\u{c}" || page_lines.last().is_some_and(|p| p.len() >= per_page) {
@@ -810,8 +834,9 @@ fn set_text(title: &str, text: &str, page: (f64, f64), font_size: f64) -> Result
fonts.set(b"F1".to_vec(), Object::Ref(fr));
let mut res = Dict::new();
res.set(b"Font".to_vec(), Object::Dict(fonts));
add_page(&mut doc, w, h, res, Some(c))?;
tree.add(&mut doc, w, h, res, Some(c));
}
tree.finish(&mut doc)?;
set_title(&mut doc, title);
Ok(doc)
}
+432 -21
View File
@@ -124,6 +124,27 @@ fn text_is_wrapped_and_paginated() {
assert!(content(p.last().unwrap()).contains("(After a form feed) Tj"), "a form feed starts a page");
}
#[test]
fn text_of_many_form_feeds_makes_its_pages_in_linear_time() {
// Each form feed starts a page: adding each to the page tree copied all the pages before it,
// which made forty thousand of them take over a minute in a debug build, against about two
// seconds when the tree is written once.
let text = "x\u{c}".repeat(40_000);
let start = std::time::Instant::now();
let doc = from_text("many", &text, LETTER, 11.0).unwrap();
let took = start.elapsed();
let tree = doc.get(doc.get(doc.root().unwrap()).as_dict().unwrap().reference(b"Pages").unwrap());
let tree = tree.as_dict().unwrap();
assert_eq!(tree.get(b"Kids").and_then(|k| k.as_array()).map(|a| a.len()), Some(40_001));
assert_eq!(tree.int(b"Count"), Some(40_001));
assert!(took < std::time::Duration::from_secs(30), "{took:?}");
// Blank documents and pages made from images keep their pages, in order.
let doc = reopen(&blank(200.0, 300.0, 3).unwrap());
assert_eq!(pages(&doc).len(), 3);
let doc = reopen(&from_images(&[("a.png".into(), png_bytes(false)), ("b.png".into(), png_bytes(true))]).unwrap());
assert_eq!(pages(&doc).len(), 2);
}
#[test]
fn text_keeps_leading_spaces_and_tabs() {
let doc = reopen(&from_text("t", " indented\n\ttabbed\nplain", LETTER, 11.0).unwrap());
@@ -2054,10 +2075,10 @@ fn symbol_coded_jbig2_images_export_as_their_picture() {
/// Export ▸ Images reads JBIG2 images (ISO 32000-2 §7.4.7), JBIG2 black as 0: as the image, and as
/// a stencil `/Mask` of another. Their `/JBIG2Globals` are read, from a dictionary or the one in
/// an array, so globals that can't be read skip the image rather than being ignored. Rows past the
/// image's height are left out; a JBIG2 page of another width, or with fewer rows than the image,
/// or larger than an exported image may be (however small the image's `/Height`), or data that
/// isn't JBIG2, skips the image.
/// an array, so globals that can't be read skip the image rather than being ignored. A JBIG2 page
/// of another size than the image (a taller one too: PdfCraft's renderer draws the whole page into
/// the image), refused before it is decoded however large, or data that isn't JBIG2, skips the
/// image.
#[test]
fn jbig2_images_export_as_their_picture() {
let (w, h) = (203i64, 41i64);
@@ -2118,33 +2139,24 @@ fn jbig2_images_export_as_their_picture() {
for in_array in [false, true] {
assert!(skipped(&page(w, h, &jbig2, Some((&b"not JBIG2"[..], in_array)), false)), "unreadable globals, in an array: {in_array}");
}
assert_eq!(exported_rgba(&page(w, h - 5, &jbig2, None, false)).1, picture(h - 5), "rows past the height");
for (width, height, data) in [(w + 8, h, &jbig2[..]), (w - 1, h, &jbig2[..]), (w, h + 1, &jbig2[..]), (w, h, &b"not JBIG2"[..])] {
for (width, height, data) in
[(w + 8, h, &jbig2[..]), (w - 1, h, &jbig2[..]), (w, h + 1, &jbig2[..]), (w, h - 5, &jbig2[..]), (w, h, &b"not JBIG2"[..])]
{
assert!(skipped(&page(width, height, data, None, false)), "{width} × {height}, {} bytes", data.len());
}
// The same stream with its page information (the first segment's data, after its 11-byte
// header: width, then height) claiming a 20,000 × 10,000 page: 200 million pixels, over the
// export's 100 million, behind an image of 20,000 × 4. The decoder would decode the whole page
// (it takes pages of up to about 2^28 pixels), so it is refused first.
// header: width, then height) claiming a 20,000 × 10,000 page, behind an image of 20,000 × 4:
// the decoder would decode the whole page, so it is refused first.
let mut large = jbig2.clone();
large[11..15].copy_from_slice(&20_000u32.to_be_bytes());
large[15..19].copy_from_slice(&10_000u32.to_be_bytes());
assert!(skipped(&page(20_000, 4, &large, None, false)), "a page over the export's size");
assert!(skipped(&page(20_000, 4, &large, None, false)), "a page far taller than the image");
// Refused the same ways as a stencil /Mask, it is left out: the image exports opaque.
for (width, height, mask) in [(w + 8, h, &jbig2), (20_000, 4, &large)] {
let rgba = exported_rgba(&page(width, height, mask, None, true)).1;
assert_eq!(rgba.len() as i64, width * height * 4, "a {width}-wide mask");
assert!(alphas(&rgba).iter().all(|a| *a == 255), "a refused {width}-wide mask is left out");
}
// A page of exactly the budget, 20,000 × 5,000, is decoded; one row more is refused.
for (rows, refused) in [(5_000u32, false), (5_001, true)] {
large[15..19].copy_from_slice(&rows.to_be_bytes());
let doc = page(20_000, 4, &large, None, false);
assert_eq!(skipped(&doc), refused, "a page of 20,000 × {rows}");
if !refused {
assert_eq!(exported_rgba(&doc).1.len(), 20_000 * 4 * 4);
}
}
// Damaged data never panics.
for end in [0, 1, 10, 20, 30, jbig2.len() / 2] {
let _ = extract_images(&page(w, h, &jbig2[..end], None, false), &[0], 0);
@@ -2155,6 +2167,38 @@ fn jbig2_images_export_as_their_picture() {
assert_eq!(alphas(&exported_rgba(&page(w, h, &jbig2, None, true)).1), alpha);
}
/// A JBIG2 image behind another filter (ASCIIHexDecode) exports as its picture, as a fax image does,
/// with the `/JBIG2Globals` at its own place in a `/DecodeParms` array: globals that can't be read
/// there skip the image, and ones at the other filter's place aren't the image's.
#[test]
fn jbig2_images_behind_another_filter_export_as_their_picture() {
let bits = [0xF0u8, 0x0F, 0xAA, 0x55];
let jbig2 = pdfcraft_filters::encode_jbig2_generic(&bits, 16, 2).unwrap();
let hex: Vec<u8> = jbig2.iter().flat_map(|b| format!("{b:02x}").into_bytes()).chain(*b">").collect();
let picture: Vec<u8> = (0..32).flat_map(|i| if bits[i / 8] & (0x80 >> (i % 8)) != 0 { [255; 4] } else { [0, 0, 0, 255] }).collect();
// With unreadable globals at place `at` of its /DecodeParms.
let page = |at: Option<usize>| {
let mut doc = from_images(&[("flat.png".into(), png_bytes(false))]).unwrap();
with_image(&mut doc, |doc| {
let mut d = image_dict(16, 2, "DeviceGray", 1);
d.set(b"Filter".to_vec(), Object::Array(vec![Object::name("ASCIIHexDecode"), Object::name("JBIG2Decode")]));
if let Some(at) = at {
let mut parms = Dict::new();
parms.set(b"JBIG2Globals".to_vec(), Object::Ref(doc.add(Object::Stream(Stream::from_raw(Dict::new(), b"not JBIG2".to_vec())))));
let mut entries = vec![Object::Null, Object::Null];
entries[at] = Object::Dict(parms);
d.set(b"DecodeParms".to_vec(), Object::Array(entries));
}
Stream::from_raw(d, hex.clone())
});
doc
};
assert_eq!(exported_rgba(&page(None)), ("png", picture.clone()));
assert_eq!(exported_rgba(&page(Some(0))).1, picture, "globals at ASCIIHexDecode's place");
let out = extract_images(&page(Some(1)), &[0], 0);
assert!(out.images.is_empty() && out.skipped.len() == 1, "unreadable globals at its own place");
}
/// A JBIG2 image's `/JBIG2Globals` are decoded before its JBIG2 page's size is known, so they have
/// a limit of their own, 32 MiB, far below the 1 GiB of any stream: globals that Flate-decode to
/// one byte more skip the image, with the limit in the reason, though they take a few kilobytes
@@ -2162,7 +2206,8 @@ fn jbig2_images_export_as_their_picture() {
/// indirect `/DecodeParms`, in an array or not.
#[test]
fn jbig2_globals_are_decoded_within_a_limit_of_their_own() {
const LIMIT: usize = 32 << 20;
const LIMIT: usize = pdfcraft_cos::MAX_JBIG2_GLOBALS;
assert_eq!(LIMIT, 32 << 20);
let bits = [0xF0u8, 0x0F, 0xAA, 0x55];
let jbig2 = pdfcraft_filters::encode_jbig2_generic(&bits, 16, 2).unwrap();
let picture: Vec<u8> = (0..32).flat_map(|i| if bits[i / 8] & (0x80 >> (i % 8)) != 0 { [255; 4] } else { [0, 0, 0, 255] }).collect();
@@ -2206,6 +2251,372 @@ fn jbig2_globals_are_decoded_within_a_limit_of_their_own() {
let out = extract_images(&page(&over, form), &[0], 0);
assert!(out.images.is_empty(), "globals over the limit, form {form}");
let why = &out.skipped.first().expect("the image is skipped").2;
assert!(why.starts_with("the JBIG2 globals can't be read") && why.contains(&format!("limit of {LIMIT} bytes")), "{why}");
assert!(why.contains("the JBIG2 globals can't be read") && why.contains(&format!("limit of {LIMIT} bytes")), "{why}");
}
}
/// One allowance for all the images of an export: an image past it is left out, saying so.
#[test]
fn jbig2_images_past_the_exports_allowance_are_left_out_with_the_reason() {
use pdfcraft_cos::{Dict, Document, ImageBudget, Object, Stream};
let mut dict = Dict::new();
dict.set(b"Subtype".to_vec(), Object::name("Image"));
dict.set(b"Width".to_vec(), Object::Int(16));
dict.set(b"Height".to_vec(), Object::Int(2));
dict.set(b"BitsPerComponent".to_vec(), Object::Int(1));
dict.set(b"ColorSpace".to_vec(), Object::name("DeviceGray"));
dict.set(b"Filter".to_vec(), Object::name("JBIG2Decode"));
let image = Stream::from_raw(dict, pdfcraft_filters::encode_jbig2_generic(&[0xFF; 4], 16, 2).unwrap());
let mut cost = ImageBudget::with_work(u64::MAX);
cost.decode(&Document::new_empty(), &image, 1 << 20).unwrap();
let cost = u64::MAX - cost.work_left();
let pdf = b"%PDF-1.7\n1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj\n2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj\n3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 100 100] >> endobj\ntrailer << /Root 1 0 R >>\n%%EOF".to_vec();
let mut doc = Document::open(std::sync::Arc::new(pdf)).unwrap();
let (a, b) = (doc.add(Object::Stream(image.clone())), doc.add(Object::Stream(image)));
let mut xobjects = Dict::new();
xobjects.set(b"A".to_vec(), Object::Ref(a));
xobjects.set(b"B".to_vec(), Object::Ref(b));
let mut resources = Dict::new();
resources.set(b"XObject".to_vec(), Object::Dict(xobjects));
let page = pdfcraft_model::pages(&doc).swap_remove(0).obj;
doc.update_dict(page, |p| p.set(b"Resources".to_vec(), Object::Dict(resources))).unwrap();
let export = crate::extract::extract_images_within(&doc, &[0], 1, &mut ImageBudget::with_work(cost), usize::MAX);
assert_eq!(export.images.len(), 1);
assert_eq!(export.skipped.len(), 1);
assert!(export.skipped[0].2.contains("more image decoding than"), "{:?}", export.skipped);
// What an export holds is bounded too: the files are all in memory until it ends.
let export = crate::extract::extract_images_within(&doc, &[0], 1, &mut ImageBudget::with_work(u64::MAX), 1);
assert_eq!(export.images.len(), 1, "the first goes past it");
assert_eq!(export.skipped.len(), 1);
assert!(export.skipped[0].2.contains("than one export can hold"), "{:?}", export.skipped);
// A file of many images shares one allowance too, image by image.
let mut budget = ImageBudget::with_work(cost);
assert!(crate::extract::image_file_within(&doc, a, &mut budget).is_ok());
assert!(crate::extract::image_file_within(&doc, b, &mut budget).is_err());
}
/// An image that isn't JBIG2 shares the allowance too: a file of filter bombs would hold an export
/// as long as one of JBIG2. What isn't decoded here, a JPEG, is still exported.
#[test]
fn flate_images_past_the_exports_allowance_are_left_out_with_the_reason() {
use pdfcraft_cos::{Dict, Document, ImageBudget, Object, Stream};
let image = |filter: &str, raw: Vec<u8>| {
let mut dict = Dict::new();
dict.set(b"Subtype".to_vec(), Object::name("Image"));
dict.set(b"Width".to_vec(), Object::Int(2));
dict.set(b"Height".to_vec(), Object::Int(2));
dict.set(b"BitsPerComponent".to_vec(), Object::Int(8));
dict.set(b"ColorSpace".to_vec(), Object::name("DeviceGray"));
dict.set(b"Filter".to_vec(), Object::name(filter));
Stream::from_raw(dict, raw)
};
let flate = image("FlateDecode", pdfcraft_filters::encode_flate(&[0x80; 4]));
let mut cost = ImageBudget::with_work(u64::MAX);
cost.decode(&Document::new_empty(), &flate, 1 << 20).unwrap();
let cost = u64::MAX - cost.work_left();
let mut doc = Document::new_empty();
let (a, b) = (doc.add(Object::Stream(flate.clone())), doc.add(Object::Stream(flate)));
let mut budget = ImageBudget::with_work(cost);
assert!(crate::extract::image_file_within(&doc, a, &mut budget).is_ok());
let refused = crate::extract::image_file_within(&doc, b, &mut budget).unwrap_err();
assert!(refused.contains("more image decoding than"), "{refused}");
assert_eq!(budget.refused(), 1);
let jpeg = image::RgbImage::from_pixel(2, 2, image::Rgb([9, 9, 9]));
let mut bytes = Vec::new();
jpeg.write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Jpeg).unwrap();
let jpeg = doc.add(Object::Stream(image("DCTDecode", bytes)));
assert!(crate::extract::image_file_within(&doc, jpeg, &mut budget).is_ok(), "nothing charged");
assert_eq!(budget.refused(), 1);
}
/// A JPEG is written as it is, at no cost, unless something means decoding it, here a mask: that
/// pays for its samples, and past the allowance the image goes, with the reason, as it would come out without
/// its transparency otherwise.
#[test]
fn a_jpeg_that_has_to_be_decoded_shares_the_allowance() {
use pdfcraft_cos::{Dict, Document, ImageBudget, Object, Stream};
let mut jpeg = Vec::new();
image::RgbImage::from_pixel(4, 4, image::Rgb([9, 9, 9])).write_to(&mut std::io::Cursor::new(&mut jpeg), image::ImageFormat::Jpeg).unwrap();
let image_dict = |extra: Option<(&[u8], Object)>| {
let mut d = Dict::new();
d.set(b"Subtype".to_vec(), Object::name("Image"));
d.set(b"Width".to_vec(), Object::Int(4));
d.set(b"Height".to_vec(), Object::Int(4));
d.set(b"BitsPerComponent".to_vec(), Object::Int(8));
d.set(b"ColorSpace".to_vec(), Object::name("DeviceRGB"));
d.set(b"Filter".to_vec(), Object::name("DCTDecode"));
if let Some((key, value)) = extra {
d.set(key.to_vec(), value);
}
d
};
let mut doc = Document::new_empty();
let mut mask = Dict::new();
mask.set(b"Subtype".to_vec(), Object::name("Image"));
mask.set(b"Width".to_vec(), Object::Int(4));
mask.set(b"Height".to_vec(), Object::Int(4));
mask.set(b"BitsPerComponent".to_vec(), Object::Int(8));
mask.set(b"ColorSpace".to_vec(), Object::name("DeviceGray"));
let mask = doc.add(Object::Stream(Stream::from_raw(mask, vec![0x80; 16])));
let doc_jpeg_len = jpeg.len();
let masked = doc.add(Object::Stream(Stream::from_raw(image_dict(Some((b"SMask", Object::Ref(mask)))), jpeg.clone())));
let plain = doc.add(Object::Stream(Stream::from_raw(image_dict(None), jpeg)));
let mut budget = ImageBudget::with_work(0);
assert!(crate::extract::image_file_within(&doc, plain, &mut budget).is_ok(), "written as it is");
assert_eq!(budget.refused(), 0);
let mut budget = ImageBudget::with_work(u64::MAX);
assert!(crate::extract::image_file_within(&doc, masked, &mut budget).is_ok());
let cost = u64::MAX - budget.work_left();
let read = 4 * doc_jpeg_len as u64;
assert_eq!(cost, 16 + 16 + 2 * 4 * 4 * 3 + read, "the mask's bytes and pixels, the JPEG's samples twice and its reading");
let mut budget = ImageBudget::with_work(cost - 1);
let refused = crate::extract::image_file_within(&doc, masked, &mut budget).unwrap_err();
assert!(refused.contains("more image decoding than"), "{refused}");
assert_eq!(budget.refused(), 1);
}
/// A JPEG that is itself a mask pays for its samples, each time an image reads it: images can
/// share one, and only the images are ever seen once.
#[test]
fn a_jpeg_mask_pays_for_its_samples() {
use pdfcraft_cos::{Dict, Document, ImageBudget, Object, Stream};
let mut jpeg = Vec::new();
image::GrayImage::from_pixel(4, 4, image::Luma([90])).write_to(&mut std::io::Cursor::new(&mut jpeg), image::ImageFormat::Jpeg).unwrap();
let mut mask = Dict::new();
mask.set(b"Subtype".to_vec(), Object::name("Image"));
mask.set(b"Width".to_vec(), Object::Int(4));
mask.set(b"Height".to_vec(), Object::Int(4));
mask.set(b"BitsPerComponent".to_vec(), Object::Int(8));
mask.set(b"ColorSpace".to_vec(), Object::name("DeviceGray"));
mask.set(b"Filter".to_vec(), Object::name("DCTDecode"));
let mut doc = Document::new_empty();
let read = 4 * jpeg.len() as u64;
let mask = doc.add(Object::Stream(Stream::from_raw(mask, jpeg)));
let mut image = Dict::new();
image.set(b"Subtype".to_vec(), Object::name("Image"));
image.set(b"Width".to_vec(), Object::Int(1));
image.set(b"Height".to_vec(), Object::Int(1));
image.set(b"BitsPerComponent".to_vec(), Object::Int(8));
image.set(b"ColorSpace".to_vec(), Object::name("DeviceGray"));
image.set(b"SMask".to_vec(), Object::Ref(mask));
let image = doc.add(Object::Stream(Stream::from_raw(image, vec![0x80])));
let mut budget = ImageBudget::with_work(u64::MAX);
assert!(crate::extract::image_file_within(&doc, image, &mut budget).is_ok());
assert_eq!(u64::MAX - budget.work_left(), 2 * 4 * 4 + read + 2, "its samples twice, its reading, and the image's byte and pixel");
// Just short of what the mask costs: it isn't decoded, and takes the image with it.
let mut budget = ImageBudget::with_work(2 * 4 * 4 + read - 1);
let refused = crate::extract::image_file_within(&doc, image, &mut budget).unwrap_err();
assert!(refused.contains("more image decoding than"), "{refused}");
assert_eq!((budget.work_left(), budget.refused()), (0, 1));
}
/// What decoding a JPEG takes goes by its header, so that is what has to agree with the
/// dictionary before it is decoded: one image of a pixel can hold a page of 500 megapixels. The
/// file comes out as it is either way, so what shows is whether it was decoded.
#[test]
fn a_jpeg_larger_than_its_dictionary_says_isnt_decoded() {
use pdfcraft_cos::{Dict, Document, ImageBudget, Object, Stream};
let mut jpeg = Vec::new();
image::RgbImage::from_pixel(4, 4, image::Rgb([9, 9, 9])).write_to(&mut std::io::Cursor::new(&mut jpeg), image::ImageFormat::Jpeg).unwrap();
// A colour key means decoding it, to find the pixels it hides.
let keyed = |side: i64| {
let mut d = Dict::new();
d.set(b"Subtype".to_vec(), Object::name("Image"));
d.set(b"Width".to_vec(), Object::Int(side));
d.set(b"Height".to_vec(), Object::Int(side));
d.set(b"BitsPerComponent".to_vec(), Object::Int(8));
d.set(b"ColorSpace".to_vec(), Object::name("DeviceRGB"));
d.set(b"Filter".to_vec(), Object::name("DCTDecode"));
d.set(b"Mask".to_vec(), Object::Array(vec![Object::Int(0); 6]));
Stream::from_raw(d, jpeg.clone())
};
let decodes = |doc: &Document, image: pdfcraft_cos::ObjRef| {
crate::extract::JPEGS_DECODED.with(|n| n.set(0));
assert!(crate::extract::image_file_within(doc, image, &mut ImageBudget::with_work(u64::MAX)).is_ok());
crate::extract::JPEGS_DECODED.with(std::cell::Cell::get)
};
let mut doc = Document::new_empty();
let (honest, lying) = (doc.add(Object::Stream(keyed(4))), doc.add(Object::Stream(keyed(1))));
assert_eq!(decodes(&doc, honest), 1);
assert_eq!(decodes(&doc, lying), 0);
// The same as a mask: read as none, without being decoded.
let mut mask = keyed(1);
mask.dict.remove(b"Mask");
let mask = doc.add(Object::Stream(mask));
let mut image = Dict::new();
image.set(b"Subtype".to_vec(), Object::name("Image"));
image.set(b"Width".to_vec(), Object::Int(1));
image.set(b"Height".to_vec(), Object::Int(1));
image.set(b"BitsPerComponent".to_vec(), Object::Int(8));
image.set(b"ColorSpace".to_vec(), Object::name("DeviceGray"));
image.set(b"SMask".to_vec(), Object::Ref(mask));
let image = doc.add(Object::Stream(Stream::from_raw(image, vec![0x80])));
assert_eq!(decodes(&doc, image), 0);
// Reading the header to find that out is paid for: a mask can be mostly tables, shared by
// every image of a file, and with nothing left it isn't read.
let mut budget = ImageBudget::with_work(u64::MAX);
assert!(crate::extract::image_file_within(&doc, image, &mut budget).is_ok());
assert_eq!(u64::MAX - budget.work_left(), 2 + 4 * jpeg.len() as u64 + 2, "its one declared sample twice, its bytes, the image's byte and pixel");
let mut budget = ImageBudget::with_work(0);
assert!(crate::extract::image_file_within(&doc, image, &mut budget).is_err());
assert_eq!(budget.refused(), 1, "the image goes, with its mask unread");
}
/// A mask past the allowance can't be left out as an unreadable one is, or the image comes out
/// opaque, showing what the mask hides: the image goes, with the reason.
#[test]
fn an_image_whose_jbig2_mask_is_past_the_allowance_is_left_out() {
use pdfcraft_cos::{Dict, Document, ImageBudget, Object, Stream};
let mut mask = Dict::new();
mask.set(b"Subtype".to_vec(), Object::name("Image"));
mask.set(b"Width".to_vec(), Object::Int(16));
mask.set(b"Height".to_vec(), Object::Int(2));
mask.set(b"BitsPerComponent".to_vec(), Object::Int(1));
mask.set(b"ColorSpace".to_vec(), Object::name("DeviceGray"));
mask.set(b"Filter".to_vec(), Object::name("JBIG2Decode"));
let mut doc = Document::new_empty();
let mask = doc.add(Object::Stream(Stream::from_raw(mask, pdfcraft_filters::encode_jbig2_generic(&[0xFF; 4], 16, 2).unwrap())));
// A JPEG, read for nothing until its mask is, so only the mask can be what stops it.
let mut jpeg = Vec::new();
image::RgbImage::from_pixel(1, 1, image::Rgb([9, 9, 9])).write_to(&mut std::io::Cursor::new(&mut jpeg), image::ImageFormat::Jpeg).unwrap();
let mut image = Dict::new();
image.set(b"Subtype".to_vec(), Object::name("Image"));
image.set(b"Width".to_vec(), Object::Int(1));
image.set(b"Height".to_vec(), Object::Int(1));
image.set(b"BitsPerComponent".to_vec(), Object::Int(8));
image.set(b"ColorSpace".to_vec(), Object::name("DeviceRGB"));
image.set(b"Filter".to_vec(), Object::name("DCTDecode"));
image.set(b"SMask".to_vec(), Object::Ref(mask));
let image = doc.add(Object::Stream(Stream::from_raw(image, jpeg)));
assert!(crate::extract::image_file_within(&doc, image, &mut ImageBudget::with_work(u64::MAX)).is_ok());
let refused = crate::extract::image_file_within(&doc, image, &mut ImageBudget::with_work(0)).unwrap_err();
assert!(refused.contains("more image decoding than"), "{refused}");
}
/// A large honest file keeps its images: what an export may hold grows with the file past the fixed
/// part, and a file too long to double doesn't wrap round to nothing.
#[test]
fn an_export_may_hold_twice_a_large_file() {
let fixed = crate::extract::export_bytes(0);
assert_eq!(fixed, 2 << 30);
assert_eq!(crate::extract::export_bytes(fixed / 2), fixed);
assert_eq!(crate::extract::export_bytes(fixed / 2 + 1), fixed + 2);
assert_eq!(crate::extract::export_bytes(usize::MAX), usize::MAX);
}
/// `/Decode` says which way round a stencil mask is, and its numbers can be given by reference. Read
/// as absent, they gave the wrong answer, so the file came out a negative of what the page draws.
#[test]
fn a_stencil_masks_decode_array_can_hold_references() {
use pdfcraft_cos::Document;
let export = |decode: &str| {
let pdf = format!(
"%PDF-1.7\n1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj\n\
2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj\n\
3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 100 100] /Resources << /XObject << /Im 4 0 R >> >> >> endobj\n\
4 0 obj << /Subtype /Image /ImageMask true /Width 8 /Height 1 /BitsPerComponent 1 /Decode {decode} /Filter /ASCIIHexDecode /Length 3 >> stream\nF0>\nendstream endobj\n\
5 0 obj 1 endobj\n6 0 obj 0 endobj\n7 0 obj 7 0 R endobj\n8 0 obj 9 0 R endobj\n9 0 obj 8 0 R endobj\n\
trailer << /Root 1 0 R >>\n%%EOF"
);
let doc = Document::open(std::sync::Arc::new(pdf.into_bytes())).unwrap();
let mut export = crate::extract::extract_images(&doc, &[0], 1);
assert_eq!(export.images.len(), 1, "{decode}: {:?}", export.skipped);
export.images.remove(0).data
};
let (inverted, identity) = (export("[1 0]"), export("[0 1]"));
assert_ne!(inverted, identity, "the two ways round differ");
for decode in ["[5 0 R 0]", "[1 6 0 R]", "[5 0 R 6 0 R]"] {
assert_eq!(export(decode), inverted, "{decode}");
}
for decode in ["[0 5 0 R]", "[6 0 R 1]", "[6 0 R 5 0 R]"] {
assert_eq!(export(decode), identity, "{decode}");
}
// A reference that only leads back to itself holds no number, and an end that is missing or isn't
// a number leaves the default mapping, whichever end it is.
for decode in ["[7 0 R 0]", "[1 7 0 R]", "[8 0 R 0]", "[1 8 0 R]", "[7 0 R 8 0 R]", "[1]", "[1 /Name]", "[/Name 0]"] {
assert_eq!(export(decode), identity, "{decode}");
}
// Equal ends aren't the two ways round either, and a number too long to hold reads as infinite.
assert_eq!(export("[1 1]"), identity);
assert_eq!(export(&format!("[{} 0]", "9".repeat(400))), identity);
}
/// A mask of other proportions than its image is scaled to it, however far apart they are: the
/// first two shapes asked for 160 GB on the way, in a file of a kilobyte, and that aborted the
/// process. The third would ask for 10 GB if it went across first, which is why the way round
/// depends on the shapes. The value comes through, and masks of ordinary proportions, of the
/// image's size and larger than it, are scaled as they always were.
#[test]
fn a_mask_of_other_proportions_than_its_image_is_scaled_without_the_memory_of_both() {
use pdfcraft_cos::{Dict, Document, Object, Stream};
let gray = |w: i64, h: i64, data: &[u8]| {
let mut d = Dict::new();
d.set(b"Subtype".to_vec(), Object::name("Image"));
d.set(b"Width".to_vec(), Object::Int(w));
d.set(b"Height".to_vec(), Object::Int(h));
d.set(b"BitsPerComponent".to_vec(), Object::Int(8));
d.set(b"ColorSpace".to_vec(), Object::name("DeviceGray"));
d.set(b"Filter".to_vec(), Object::name("FlateDecode"));
Stream::from_raw(d, pdfcraft_filters::encode_flate(data))
};
let shapes = [
(100_000usize, 1usize, 1usize, 100_000usize),
(100_000, 64, 64, 100_000),
(1, 100_000, 100_000, 1),
(64, 1, 1, 64),
(3, 2, 6, 4),
(3, 2, 3, 2),
(6, 4, 3, 2),
];
for (mask_w, mask_h, w, h) in shapes {
let mut doc = Document::new_empty();
let mask = doc.add(Object::Stream(gray(mask_w as i64, mask_h as i64, &vec![0x80; mask_w * mask_h])));
let mut image = gray(w as i64, h as i64, &vec![0x40; w * h]);
image.dict.set(b"SMask".to_vec(), Object::Ref(mask));
let image = doc.add(Object::Stream(image));
let (name, png) = crate::image_file(&doc, image).unwrap_or_else(|e| panic!("{mask_w} × {mask_h} on {w} × {h}: {e}"));
assert_eq!(name, "png");
let mut reader = ::png::Decoder::new(std::io::Cursor::new(&png)).read_info().unwrap();
let mut rgba = vec![0; reader.output_buffer_size().unwrap()];
let info = reader.next_frame(&mut rgba).unwrap();
assert_eq!((info.width as usize, info.height as usize, info.color_type), (w, h, ::png::ColorType::Rgba));
assert!(rgba.as_chunks::<4>().0.iter().all(|p| p[3].abs_diff(0x80) <= 1), "{mask_w} × {mask_h} on {w} × {h}");
}
}
/// The long way round is for proportions far apart: up to a quarter over the larger image the
/// buffer is no danger, and such a mask scales as it always did, to the byte. Noise, as a flat mask comes
/// out the same either way.
#[test]
fn proportions_up_to_the_limit_scale_as_they_did() {
let noise = |w: u32, h: u32| {
let mut seed = 0x2545_F491_4F6C_DD1Du64;
let px = (0..w * h)
.map(|_| {
seed ^= seed << 13;
seed ^= seed >> 7;
seed ^= seed << 17;
seed as u8
})
.collect();
image::GrayImage::from_raw(w, h, px).unwrap()
};
// Each exactly a quarter over the larger: the source's size, then the target's.
for (mw, mh, w, h) in [(25, 16, 10, 20), (20, 5, 16, 25)] {
let mask = noise(mw, mh);
let direct = image::imageops::resize(&mask, w, h, image::imageops::FilterType::Triangle);
assert_eq!(crate::extract::scaled(&mask, w, h), direct, "{mw} × {mh} to {w} × {h}");
}
// A step past it goes the long way, which is how to tell.
let mask = noise(25, 15);
let direct = image::imageops::resize(&mask, 10, 20, image::imageops::FilterType::Triangle);
assert_ne!(crate::extract::scaled(&mask, 10, 20), direct);
// A mask of its image's size comes through as it is.
let mask = noise(20, 10);
assert_eq!(crate::extract::scaled(&mask, 20, 10), mask);
}
+2
View File
@@ -24,3 +24,5 @@ unicode-bidi = "0.3"
[dev-dependencies]
hayro-syntax = { workspace = true }
pdfcraft-render = { workspace = true }
proptest = { workspace = true }
+29 -3
View File
@@ -7,9 +7,25 @@ use super::place::{
};
use super::{Document, EditError, Object, added, backdrop, helvetica_width};
/// Commit one complete mark operation only after every selected page succeeds. The snapshot
/// shares original bytes, cross-references, caches and unchanged objects; only the overlay table
/// and document metadata are copied. Dropping a failed stage also drops removed marks, changed
/// page/resources/backdrop dictionaries and new objects, including the allocation cursor.
fn apply_mark_transaction(doc: &mut Document, apply: impl FnOnce(&mut Document) -> Result<(), EditError>) -> Result<(), EditError> {
let mut staged = doc.clone();
apply(&mut staged)?;
*doc = staged;
Ok(())
}
/// Add a header and footer to `pages` (0-based). With `replace`, existing headers and footers on
/// those pages are removed first (Acrobat's Replace Existing).
/// those pages are removed first (Acrobat's Replace Existing). The whole call is atomic:
/// on error, the document (including earlier selected pages) is unchanged.
pub fn add_header_footer(doc: &mut Document, pages: &[usize], hf: &HeaderFooter, replace: bool, cx: &Context) -> Result<(), EditError> {
apply_mark_transaction(doc, |staged| add_header_footer_in_place(staged, pages, hf, replace, cx))
}
fn add_header_footer_in_place(doc: &mut Document, pages: &[usize], hf: &HeaderFooter, replace: bool, cx: &Context) -> Result<(), EditError> {
let all = page_list(doc);
check(pages, all.len())?;
if hf.text.iter().all(|t| t.trim().is_empty()) {
@@ -121,8 +137,13 @@ pub fn add_header_footer(doc: &mut Document, pages: &[usize], hf: &HeaderFooter,
Ok(())
}
/// Add a text watermark to `pages`.
/// Add a text or picture watermark to `pages`. All selected pages, including mark replacement,
/// form one transaction; on error, the document is unchanged.
pub fn add_watermark(doc: &mut Document, pages: &[usize], wm: &Watermark, replace: bool) -> Result<(), EditError> {
apply_mark_transaction(doc, |staged| add_watermark_in_place(staged, pages, wm, replace))
}
fn add_watermark_in_place(doc: &mut Document, pages: &[usize], wm: &Watermark, replace: bool) -> Result<(), EditError> {
let all = page_list(doc);
check(pages, all.len())?;
let text = wm.text.trim();
@@ -201,8 +222,13 @@ pub fn add_watermark(doc: &mut Document, pages: &[usize], wm: &Watermark, replac
/// Add a solid-colour background behind the content of `pages`. With `bg.replace_backdrop`, a
/// white backdrop a page paints itself is replaced first, so the background shows (see
/// [`backdrop`]); a picture backdrop (a scan) still hides it.
/// [`backdrop`]); a picture backdrop (a scan) still hides it. All selected pages, including
/// replacement and backdrop edits, form one transaction; on error, the document is unchanged.
pub fn add_background(doc: &mut Document, pages: &[usize], bg: &Background, replace: bool) -> Result<(), EditError> {
apply_mark_transaction(doc, |staged| add_background_in_place(staged, pages, bg, replace))
}
fn add_background_in_place(doc: &mut Document, pages: &[usize], bg: &Background, replace: bool) -> Result<(), EditError> {
let all = page_list(doc);
check(pages, all.len())?;
if replace {
+7 -2
View File
@@ -98,8 +98,13 @@ pub fn page_background(doc: &Document, page: usize) -> Result<Option<Rgb>, EditE
}
b"sc" | b"scn" => st.fill = colour(st.space, op),
b"gs" => {
if let Some(g) = op.name(0).and_then(|n| gstates.get(n)).map(|g| doc.resolve(g)).and_then(|g| g.as_dict().cloned()) {
apply_gstate(doc, &g, &mut st);
let mut held = None;
let gstate = match op.name(0).and_then(|n| gstates.get(n)) {
Some(g) => crate::text::dict_in_place(doc, g, &mut held),
None => None,
};
if let Some(g) = gstate {
apply_gstate(doc, g, &mut st);
}
}
b"re" => match op.nums::<4>() {
+1331 -150
View File
File diff suppressed because it is too large. Load diff
+8 -2
View File
@@ -1,6 +1,11 @@
//! pdfcraft-edit — page content editing (L4). Today: page marks, Acrobat's Header & footer,
//! Watermark, Background and Bates numbering (execution plan M7.6).
//!
//! **Atomic page-mark operations.** Adding or replacing headers/footers, watermarks and backgrounds
//! stages the whole call on a document snapshot and commits only after every selected page succeeds.
//! An error preserves existing marks, content, resources, pending edits and allocated objects. The
//! snapshot shares original PDF bytes and unchanged objects; it copies the overlay table and metadata.
//!
//! **How marks are stored.** Each mark is one content stream appended to (or, for content behind
//! the page, inserted after the backgrounds at the start of) the page's `/Contents`, drawn in
//! display space (after `/Rotate`) and wrapped in a marked-content artifact (§14.8.2.2) so
@@ -35,6 +40,7 @@ pub type Rgb = [f64; 3];
pub mod backdrop;
pub use backdrop::{Backdrop, backdrops_left_off, page_backdrop, page_backdrops};
pub use text::strip_subset_tag;
mod background;
pub use background::page_background;
pub mod objects;
@@ -43,7 +49,7 @@ pub use objects::{EditableObject, MAX_MOVE_OBJECTS, ObjectKind, ObjectTarget, ed
mod flatten;
pub use flatten::{flatten, flatten_fill_sign};
pub mod images;
pub use images::{ImageChange, PageImage, change_image, page_images, reading_images, rect_to_rect, turn_about_centre, turn_by_degrees};
pub use images::{ArrangeOrder, ImageChange, PageImage, change_image, page_images, reading_images, rect_to_rect, turn_about_centre, turn_by_degrees};
pub mod bidi;
pub mod indic;
mod linebreak;
@@ -71,7 +77,7 @@ use marks::{matrix_number, n};
pub(crate) use place::undrawable;
#[cfg(test)]
use place::{ISOLATION_MAX_DEPTH, OLD_WRAP_CLOSE, WRAP_CLOSE, WRAP_OPEN, is_wrap_close, page_fonts, stream_bytes, stream_tag, tagged, wrapper_role};
use place::{check, check_on_top, contents, page_list, place_tagged};
use place::{Reach, check, check_on_top, contents, draw_on_top, lift_on_top, page_list, place_tagged, revealed_under_paint};
pub use place::{stamp, undrawable_message};
#[cfg(test)]
+211
View File
@@ -0,0 +1,211 @@
//! The public mark APIs either commit the complete operation or leave the document untouched.
use super::{cx, fixture, reopen, streams};
use crate::place::MARK_PLACEMENT_FAILURE;
use crate::*;
use pdfcraft_cos::{ObjRef, SaveOptions, write_incremental};
const SELECTED: &[usize] = &[0, 1, 2];
struct PlacementFailure;
impl PlacementFailure {
fn after_two_pages(kind: MarkKind) -> Self {
MARK_PLACEMENT_FAILURE.with(|failure| {
assert!(failure.get().is_none());
failure.set(Some((kind, 2, 0)));
});
Self
}
fn completed(&self) -> usize {
MARK_PLACEMENT_FAILURE.with(|failure| failure.get().unwrap().2)
}
}
impl Drop for PlacementFailure {
fn drop(&mut self) {
MARK_PLACEMENT_FAILURE.with(|failure| failure.set(None));
}
}
/// Four pages share an original stream and resources, both inherited and directly referenced.
/// All have all three existing marks, including a picture background with a replaced white fill.
fn marked_document() -> (Document, MarkSource) {
let mut doc = fixture();
let parent = ObjRef::new(2, 0);
let extra = doc.add(Object::Dict(Dict::from_iter([
(b"Type".to_vec(), Object::name("Page")),
(b"Parent".to_vec(), Object::Ref(parent)),
(b"Contents".to_vec(), Object::Ref(ObjRef::new(7, 0))),
])));
doc.update_dict(parent, |d| {
d.set(b"Kids".to_vec(), Object::Array([3, 4, 5].map(|n| Object::Ref(ObjRef::new(n, 0))).into_iter().chain([Object::Ref(extra)]).collect()));
d.set(b"Count".to_vec(), Object::Int(4));
})
.unwrap();
doc.set(ObjRef::new(7, 0), Object::Stream(Stream::from_raw(Dict::new(), b"1 g 0 0 600 800 re f 0 g BT /F1 9 Tf (Original page) Tj ET".to_vec())));
let picture = |doc: &mut Document, gray| {
let image = doc.add(Object::Stream(Stream::from_raw(
Dict::from_iter([
(b"Type".to_vec(), Object::name("XObject")),
(b"Subtype".to_vec(), Object::name("Image")),
(b"Width".to_vec(), Object::Int(1)),
(b"Height".to_vec(), Object::Int(1)),
(b"ColorSpace".to_vec(), Object::name("DeviceGray")),
(b"BitsPerComponent".to_vec(), Object::Int(8)),
]),
vec![gray],
)));
MarkSource { xobject: image, size: (1.0, 1.0), image: true }
};
let old_picture = picture(&mut doc, 170);
let replacement_picture = picture(&mut doc, 80);
let all = [0, 1, 2, 3];
let hf = HeaderFooter {
text: ["Old header".into(), String::new(), String::new(), String::new(), String::new(), String::new()],
font: added::Family::Times,
..Default::default()
};
add_header_footer(&mut doc, &all, &hf, false, &cx()).unwrap();
add_watermark(&mut doc, &all, &Watermark { text: "Old watermark".into(), opacity: 0.45, ..Default::default() }, false).unwrap();
add_background(&mut doc, &all, &Background { source: Some(old_picture), opacity: 0.6, replace_backdrop: true, ..Default::default() }, false)
.unwrap();
let pages = page_list(&doc);
let shared = ObjRef::new(6, 0);
let resources = (*doc.resolve(pages[0].dict.get(b"Resources").unwrap())).clone();
doc.set(shared, resources);
for (i, page) in pages.iter().enumerate() {
doc.update_dict(page.obj, |d| {
if i % 2 == 0 {
d.set(b"Resources".to_vec(), Object::Ref(shared));
} else {
d.remove(b"Resources");
}
})
.unwrap();
}
let doc = reopen(&doc);
assert!(!doc.is_modified());
let pages = page_list(&doc);
assert_eq!(pages.len(), 4);
assert!(doc.get(pages[1].obj).as_dict().unwrap().get(b"Resources").is_none(), "a selected page inherits its resources");
assert_eq!(pages[0].dict.get(b"Resources").and_then(Object::as_ref), Some(shared));
assert_eq!(pages[2].dict.get(b"Resources").and_then(Object::as_ref), Some(shared));
for i in 0..4 {
for kind in [MarkKind::HeaderFooter, MarkKind::Watermark, MarkKind::Background] {
assert_eq!(mark_streams(&doc, i, kind).len(), 1, "page {i} has existing {kind:?}");
}
}
(doc, replacement_picture)
}
fn mark_streams(doc: &Document, page: usize, kind: MarkKind) -> Vec<String> {
streams(doc, page).into_iter().filter(|s| s.contains(&format!("/PCMark /{}", kind.tag()))).collect()
}
fn apply_replacement(doc: &mut Document, kind: MarkKind, source: MarkSource, replace: bool) -> Result<(), EditError> {
match kind {
MarkKind::HeaderFooter => add_header_footer(
doc,
SELECTED,
&HeaderFooter {
text: ["New header".into(), String::new(), String::new(), String::new(), String::new(), String::new()],
font: added::Family::Courier,
shrink: true,
..Default::default()
},
replace,
&cx(),
),
MarkKind::Watermark => add_watermark(doc, SELECTED, &Watermark { source: Some(source), opacity: 0.25, ..Default::default() }, replace),
MarkKind::Background => {
add_background(doc, SELECTED, &Background { color: [0.1, 0.3, 0.7], replace_backdrop: true, ..Default::default() }, replace)
}
}
}
fn unchanged_after_later_page_failure(kind: MarkKind) {
// Replacement and addition share the same operation boundary; exercise replacement first.
for (replace, pending_edit) in [(true, false), (true, true), (false, false), (false, true)] {
let (mut doc, source) = marked_document();
if pending_edit {
let pending = doc.add(Object::String(pdfcraft_cos::PdfString::literal(b"unsaved caller edit".to_vec())));
doc.update_dict(page_list(&doc)[0].obj, |d| d.set(b"CallerEdit".to_vec(), Object::Ref(pending))).unwrap();
}
let modified = doc.is_modified();
let before = write_incremental(&doc, &SaveOptions::default()).unwrap();
let objects = doc.object_numbers().len();
let mut allocation_probe = doc.clone();
let next_object = allocation_probe.add(Object::Null);
let failure = PlacementFailure::after_two_pages(kind);
let result = apply_replacement(&mut doc, kind, source, replace);
assert_eq!(result, Err(EditError::Invalid("injected mark placement failure".into())));
assert_eq!(failure.completed(), 2, "the error followed two real page placements");
assert_eq!(doc.object_numbers().len(), objects, "{kind:?}, replace={replace}: no allocated objects remain");
assert_eq!(doc.is_modified(), modified, "{kind:?}, replace={replace}: the dirty state is preserved");
assert!(write_incremental(&doc, &SaveOptions::default()).unwrap() == before, "{kind:?}, replace={replace}: every byte stays unchanged");
assert_eq!(doc.add(Object::Null), next_object, "the allocation cursor is unchanged too");
}
}
#[test]
fn header_footer_changes_are_atomic_after_a_later_page_failure() {
unchanged_after_later_page_failure(MarkKind::HeaderFooter);
}
#[test]
fn watermark_changes_are_atomic_after_a_later_page_failure() {
unchanged_after_later_page_failure(MarkKind::Watermark);
}
#[test]
fn background_changes_are_atomic_after_a_later_page_failure() {
unchanged_after_later_page_failure(MarkKind::Background);
}
#[test]
fn replacements_commit_all_selected_pages_and_preserve_other_marks_and_shared_resources() {
for kind in [MarkKind::HeaderFooter, MarkKind::Watermark, MarkKind::Background] {
let (mut doc, source) = marked_document();
let before = doc.clone();
let expected = match kind {
MarkKind::HeaderFooter => "(New header)".to_string(),
MarkKind::Watermark => format!("/PCPic{} Do", source.xobject.num),
MarkKind::Background => "0.1 0.3 0.7 rg".to_string(),
};
apply_replacement(&mut doc, kind, source, true).unwrap();
let doc = reopen(&doc);
assert_eq!(streams(&doc, 3), streams(&before, 3), "the unselected page keeps its content");
let unselected = page_list(&before)[3].obj;
assert_eq!(doc.get(unselected), before.get(unselected), "the unselected page keeps its resources and entries");
for reference in [ObjRef::new(6, 0), ObjRef::new(7, 0)] {
assert_eq!(
format!("{:?}", doc.get(reference)),
format!("{:?}", before.get(reference)),
"shared resources and original content stay unchanged"
);
}
for page in SELECTED {
let marks = mark_streams(&doc, *page, kind);
assert_eq!(marks.len(), 1, "one replacement on selected page {page}");
assert!(marks[0].contains(&expected), "the new mark is present: {}", marks[0]);
let old_page = &page_list(&before)[*page];
let new_page = &page_list(&doc)[*page];
let old_resources = before.resolve(old_page.dict.get(b"Resources").unwrap());
let new_resources = doc.resolve(new_page.dict.get(b"Resources").unwrap());
for category in [&b"Font"[..], &b"ExtGState"[..], &b"XObject"[..]] {
let old = before.resolve(old_resources.as_dict().unwrap().get(category).unwrap());
let new = doc.resolve(new_resources.as_dict().unwrap().get(category).unwrap());
for (name, value) in old.as_dict().unwrap().iter() {
assert_eq!(new.as_dict().unwrap().get(name), Some(value), "old resources remain usable on page {page}");
assert_eq!(doc.resolve(value), before.resolve(value), "referenced resource contents are unchanged on page {page}");
}
}
for other in [MarkKind::HeaderFooter, MarkKind::Watermark, MarkKind::Background] {
if other != kind {
assert_eq!(mark_streams(&doc, *page, other), mark_streams(&before, *page, other), "unrelated {other:?} on page {page}");
}
}
}
}
}
+19 -1
View File
@@ -286,7 +286,12 @@ pub fn expand(template: &str, page_number: u32, count: usize, bates: u64, cx: &C
let digits = parts.get(1).and_then(|d| d.parse::<usize>().ok()).unwrap_or(6).clamp(1, 15);
format!("{}{:0digits$}{}", parts.get(3).unwrap_or(&""), bates, parts.get(4).unwrap_or(&""))
}
_ => format!("<<{token}>>"),
_ => {
// Not a token: emit one `<` and retry, so a later token is still found.
out.push('<');
rest = &rest[start + 1..];
continue;
}
};
out.push_str(&value);
rest = &after[end + 2..];
@@ -302,3 +307,16 @@ pub(crate) fn bates_start(template: &str) -> Option<u64> {
let t = &t[..t.find(">>")?];
t.split('#').nth(2).and_then(|s| s.parse().ok()).or(Some(1))
}
#[cfg(test)]
mod expand_tests {
use super::*;
#[test]
fn expand_token_after_extra_angle_brackets() {
let cx = Context::default();
assert_eq!(expand("<<<1>>>", 3, 9, 1, &cx), "<3>");
assert_eq!(expand("<< <<1>>", 3, 9, 1, &cx), "<< 3");
assert_eq!(expand("<<x>> <<1>>", 3, 9, 1, &cx), "<<x>> 3");
}
}
+96 -1
View File
@@ -294,7 +294,32 @@ pub(crate) fn isolation(doc: &Document, list: &[Object]) -> Isolation {
/// Put a mark's content on a page: behind (with the behind-marks at the start) or on top
/// (appended, after wrapping the original content in q/Q).
pub(crate) fn place(doc: &mut Document, page: &pdfcraft_model::Page, kind: MarkKind, content: Vec<u8>, behind: bool) -> Result<(), EditError> {
place_tagged(doc, page, kind.tag(), content, behind).map(drop)
place_tagged(doc, page, kind.tag(), content, behind)?;
#[cfg(test)]
fail_after_mark_placement(kind)?;
Ok(())
}
#[cfg(test)]
thread_local! {
/// Force an error after N completed placements of one kind, on this test thread only.
pub(crate) static MARK_PLACEMENT_FAILURE: std::cell::Cell<Option<(MarkKind, usize, usize)>> = const { std::cell::Cell::new(None) };
}
#[cfg(test)]
fn fail_after_mark_placement(kind: MarkKind) -> Result<(), EditError> {
MARK_PLACEMENT_FAILURE.with(|failure| {
if let Some((target, after, completed)) = failure.get()
&& target == kind
{
let completed = completed.saturating_add(1);
failure.set(Some((target, after, completed)));
if completed == after {
return Err(EditError::Invalid("injected mark placement failure".into()));
}
}
Ok(())
})
}
/// Put content on a page, tagged `tag` (see [`place`]). On top, whatever graphics state the
@@ -346,6 +371,76 @@ pub(crate) fn place_tagged(doc: &mut Document, page: &pdfcraft_model::Page, tag:
Ok(mark_ref)
}
/// Draw `ops`, written for the space whose CTM is `ctm`, on top of everything on `page`, tagged
/// `Edited`. A rewritten invisible paragraph goes here when [`revealed_under_paint`]: an OCR
/// layer written before the scan image it lies under would keep the revealed text hidden (#3973).
pub(crate) fn draw_on_top(doc: &mut Document, page: &pdfcraft_model::Page, ctm: [f64; 6], ops: &[pdfcraft_content::Op]) -> Result<(), EditError> {
if ops.is_empty() {
return Ok(());
}
use pdfcraft_content::Op;
let mut all = vec![Op::new("q", vec![]), Op::new("cm", ctm.iter().map(|v| pdfcraft_content::num(*v)).collect())];
all.extend_from_slice(ops);
all.push(Op::new("Q", vec![]));
place_tagged(doc, page, "Edited", pdfcraft_content::serialize_ops(&all), false).map(drop)
}
/// Where a rewritten paragraph can be drawn, in user space ([`revealed_under_paint`]).
pub(crate) struct Reach {
/// The paragraph's old box, where its cover goes.
pub rect: [f64; 4],
/// The move asked for (`BlockStyle::offset`).
pub offset: [f64; 2],
/// The widest line the rewrite may draw, how many lines it has, and how far apart they are.
pub width: f64,
pub rows: usize,
pub pitch: f64,
pub upright: bool,
}
impl Reach {
/// The old box and the moved one, grown to `width` either way (alignment may grow a line left
/// or right), down to `rows` lines and up one `pitch` above its top (a larger size on the first line, however many lines the old box had); turned text grows by the lines' diagonal every way.
/// Unbounded when a number is not finite.
pub(crate) fn bounds(&self) -> [f64; 4] {
const UNBOUNDED: [f64; 4] = [f64::NEG_INFINITY, f64::NEG_INFINITY, f64::INFINITY, f64::INFINITY];
let ([dx, dy], r) = (self.offset, self.rect);
if !r.iter().chain(&self.offset).chain([&self.width, &self.pitch]).all(|v| v.is_finite()) {
return UNBOUNDED;
}
let moved = [r[0] + dx, r[1] + dy, r[2] + dx, r[3] + dy];
let rows = f64::from(u32::try_from(self.rows).unwrap_or(u32::MAX));
let (width, height) = (self.width.abs(), self.pitch.abs() * rows);
let grown = if self.upright {
[moved[0].min(moved[2] - width), moved[1].min(moved[3] - height), moved[2].max(moved[0] + width), moved[3] + self.pitch.abs()]
} else {
let d = width.hypot(height);
[moved[0] - d, moved[1] - d, moved[2] + d, moved[3] + d]
};
let b = [r[0].min(grown[0]), r[1].min(grown[1]), r[2].max(grown[2]), r[3].max(grown[3])];
if b.iter().all(|v| v.is_finite()) { b } else { UNBOUNDED }
}
}
/// Whether a rewritten paragraph that was `invisible` goes on top of page `page`: something after
/// operator `at` of the page's joined `ops` paints over `reach` (user space, [`Reach::bounds`]), as the scan image
/// does over an OCR layer written before it (#3973). XObjects count where they are drawn; an inline
/// image or a shading after it counts anywhere, and so does any XObject when the page's images
/// cannot be listed.
pub(crate) fn revealed_under_paint(doc: &Document, page: usize, invisible: bool, reach: [f64; 4], ops: &[pdfcraft_content::Op], at: usize) -> bool {
let later = ops.get(at..).unwrap_or_default();
if !invisible || later.iter().any(|op| op.is("BI") || op.is("sh")) {
return invisible;
}
later.iter().any(|op| op.is("Do")) && crate::images::painted_over(doc, page, reach, at).unwrap_or(true)
}
/// The operators to draw on top of the page ([`draw_on_top`]): all of `paragraph` when `over`,
/// none otherwise. The page was checked to take them ([`check_on_top`]) before the edit began.
pub(crate) fn lift_on_top(over: bool, paragraph: &mut Vec<pdfcraft_content::Op>) -> Vec<pdfcraft_content::Op> {
if over { std::mem::take(paragraph) } else { Vec::new() }
}
fn too_deep_on_top() -> EditError {
EditError::Invalid("the page's marked content is nested too deeply to add anything on top of it".into())
}
+2013 -1
View File
File diff suppressed because it is too large. Load diff
+3 -2
View File
@@ -24,6 +24,7 @@ use crate::EditError;
mod regions;
#[path = "text_session.rs"]
mod session;
pub use fallback::strip_subset_tag;
use regions::{alignment_frame, group_blocks, is_centred, rewrite_styled_block};
pub use session::TextSession;
@@ -47,13 +48,13 @@ pub use editor::{TextEditLayout, TextEditorFont, register_text_font, text_edit_l
pub(crate) use fallback::SOURCE_SPACE_CALLS;
use fallback::{
MAX_TYPE3_GLYPHS, Type3Glyph, fallback_face, needs_type3, no_fallback_font, no_glyph_for, same_base_font, same_font, source_encodes,
source_family, source_program, source_show, source_space, source_width, strip_subset_tag, type3_faces, type3_glyph, write_type3_glyphs,
source_family, source_program, source_show, source_space, source_width, type3_faces, type3_glyph, write_type3_glyphs,
};
#[cfg(test)]
use fallback::{add_type3_font, is_type3_fallback};
use interp::{Origin, Paint, union};
use lines::page_dict;
pub(crate) use lines::{FormBudget, content_streams, content_streams_within, form_call, rewritten_contents, splice};
pub(crate) use lines::{FormBudget, content_streams, content_streams_within, dict_in_place, form_call, resource_dict, rewritten_contents, splice};
pub use lines::{MAX_FORM_DEPTH, MAX_FORM_VISITS, glyph_text_lines, text_lines};
pub use rewrite::{LineEdit, replace_line, rewrite_block};
use rewrite::{coincident_ops, rewrite_block_from};
+2 -1
View File
@@ -31,7 +31,8 @@ pub struct TextBlock {
/// Byte ranges in `editor_text` and their source line indexes.
pub spans: Vec<(std::ops::Range<usize>, usize)>,
/// Every line is invisible text (rendering mode 3): an OCR layer over a scanned image, whose
/// pixels show the words. A rewrite draws the new text visibly (see [`BlockStyle::cover`]).
/// pixels show the words. A rewrite draws the new text visibly, on top of the page when
/// the scan is drawn after it (see [`BlockStyle::cover`]).
pub invisible: bool,
}
+1 -1
View File
@@ -163,7 +163,7 @@ pub(crate) fn same_base_font(a: &str, b: &str) -> bool {
}
/// `ABCDEF+Arial` → `Arial`. A name without a subset tag is returned unchanged.
pub(crate) fn strip_subset_tag(name: &str) -> &str {
pub fn strip_subset_tag(name: &str) -> &str {
let bytes = name.as_bytes();
let is_tag = bytes.get(6) == Some(&b'+') && bytes.get(..6).is_some_and(|tag| tag.iter().all(u8::is_ascii_uppercase));
if is_tag { name.get(7..).unwrap_or(name) } else { name }
+69 -13
View File
@@ -18,13 +18,33 @@ pub(super) struct TextState {
/// graphics state the text was painted with that [`TextState::ops`] doesn't restate.
pub(super) stroke: Vec<Op>,
pub(super) line_width: Option<f64>,
ext_gstate: Vec<Vec<u8>>,
ext_gstate: Vec<GsSelection>,
/// The dash pattern and line cap in force (see [`Ts`]): compared, not restated.
pub(super) dash: Dash,
pub(super) line_cap: i64,
}
impl TextState {
/// The state a page's content starts in (ISO 32000-2 §8.4.1, §9.3.1): what is in force on
/// top of the page, after its content wrapped in `q`/`Q`.
pub(crate) fn initial() -> Self {
TextState {
font: None,
char_spacing: 0.0,
word_spacing: 0.0,
scale: 1.0,
leading: 0.0,
rise: 0.0,
fill: Vec::new(),
render_mode: 0,
stroke: Vec::new(),
line_width: None,
ext_gstate: Vec::new(),
dash: (Vec::new(), 0.0),
line_cap: 0,
}
}
pub(super) fn of(ts: &Ts) -> Self {
TextState {
font: ts.font.as_ref().map(|(n, _)| (String::from_utf8_lossy(n).into_owned(), ts.size)),
@@ -54,13 +74,17 @@ impl TextState {
///
/// 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.
pub(crate) fn paint_ops(&self, current: &TextState) -> Vec<Op> {
///
/// `ctm` is the CTM where they run. A soft mask is placed by the CTM its `gs` ran at
/// (ISO 32000-2 §11.6.5.2), so one selected at another CTM is selected there and the CTM
/// set back.
pub(crate) fn paint_ops(&self, current: &TextState, ctm: [f64; 6]) -> 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())]));
for sel in self.ext_gstate.iter().skip(shared) {
sel.push_ops(&mut v, ctm);
}
// A reselected ExtGState may set `/LW`, so the width (already the effective one) follows it.
let reselected = !v.is_empty();
@@ -222,7 +246,7 @@ pub(super) struct Ts {
/// The line width a `w` or an ExtGState's `/LW` set (`None`: the initial 1.0).
pub(super) line_width: Option<f64>,
/// The ExtGState resources selected with `gs`, oldest first (see [`select_gs`]).
pub(super) ext_gstate: Vec<Vec<u8>>,
pub(super) ext_gstate: Vec<GsSelection>,
/// The dash pattern a `d` or an ExtGState's `/D` set (initially solid: `[] 0`).
pub(super) dash: Dash,
/// The line cap a `J` or an ExtGState's `/LC` set (initially 0, butt).
@@ -255,12 +279,38 @@ 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);
fn select_gs(list: &mut Vec<GsSelection>, name: &[u8], anchor: Option<[f64; 6]>) {
list.retain(|s| s.name != name);
if list.len() >= MAX_GS {
list.remove(0);
}
list.push(name.to_vec());
list.push(GsSelection { name: name.to_vec(), anchor });
}
/// One `gs` selection: the ExtGState's resource name, and the CTM it ran at when the dictionary
/// has a soft mask, which that CTM places (ISO 32000-2 §11.6.5.2).
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct GsSelection {
name: Vec<u8>,
anchor: Option<[f64; 6]>,
}
impl GsSelection {
/// Select this ExtGState from where the CTM is `ctm`: at its anchor, then back to `ctm`. Both
/// moves need an invertible matrix; without one it is selected where it runs.
fn push_ops(&self, v: &mut Vec<Op>, ctm: [f64; 6]) {
let gs = Op::new("gs", vec![Object::Name(self.name.clone())]);
let moves = self.anchor.filter(|a| *a != ctm).and_then(|a| {
let (anchor, here) = (Matrix(a), Matrix(ctm));
Some((anchor.then(&here.invert()?), here.then(&anchor.invert()?)))
});
let Some((to, back)) = moves else {
v.push(gs);
return;
};
let cm = |m: Matrix| Op::new("cm", m.0.iter().map(|x| pdfcraft_content::num(*x)).collect());
v.extend([cm(to), gs, cm(back)]);
}
}
/// The text-showing operators of one stream with their text, font, box and baseline.
@@ -773,8 +823,9 @@ pub(super) fn interpret(
// `Some(properties)`: read `/ActualText`, looking named property lists up in `properties`.
logical_text: Option<&Dict>,
) -> Result<Vec<Shown>, EditError> {
let fonts_res = resources.get(b"Font").map(|f| doc.resolve(f)).and_then(|f| f.as_dict().cloned()).unwrap_or_default();
let states = resources.get(b"ExtGState").map(|g| doc.resolve(g)).and_then(|g| g.as_dict().cloned()).unwrap_or_default();
let (mut held_fonts, mut held_states, none) = (None, None, Dict::new());
let fonts_res = super::resource_dict(doc, resources, b"Font", &mut held_fonts).unwrap_or(&none);
let states = super::resource_dict(doc, resources, b"ExtGState", &mut held_states).unwrap_or(&none);
let mut out: Vec<Shown> = Vec::new();
let mut ts = carry.ts.clone();
let mut at_bt = (0usize, ts.clone());
@@ -878,11 +929,16 @@ pub(super) 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" => {
let mut held = None;
let params = match op.name(0).and_then(|name| states.get(name)) {
Some(p) => super::dict_in_place(doc, p, &mut held),
None => None,
};
if let Some(name) = op.name(0) {
select_gs(&mut ts.ext_gstate, name);
let masked = params.and_then(|p| p.get(b"SMask")).is_some_and(|m| doc.resolve(m).as_dict().is_some());
select_gs(&mut ts.ext_gstate, name, masked.then_some(ts.ctm.0));
}
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) {
if let Some(params) = params {
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());
+46 -11
View File
@@ -1,3 +1,5 @@
use std::sync::Arc;
use super::fallback::{same_font, same_paint};
use super::interp::{Carry, Origin, Pen, Shown, TextState, Ts, direction, interpret, to_frame, union};
use super::{DecodeBudget, Dict, Document, EditError, HashMap, Matrix, Object, Op, Pieces, Stream, TextLine, parse, serialize_ops};
@@ -452,10 +454,41 @@ impl FormBudget {
pub(crate) struct FormCall {
pub(crate) obj: Option<pdfcraft_cos::ObjRef>,
pub(crate) data: Vec<u8>,
pub(crate) resources: Dict,
/// The form, and its `/Resources` when they are an object of their own, which is what
/// [`FormCall::resources`] reads.
form: Arc<Object>,
own: Option<Arc<Object>>,
pub(crate) ctm: Matrix,
}
impl FormCall {
/// The resources its content is read with: its own, or if it has none, `drawn_with`, the ones
/// it was drawn with (PDF 1.1 files). Read in place, as a page can draw a form thousands of times:
/// a copy for each took time in the square of them.
pub(crate) fn resources<'a>(&'a self, drawn_with: &'a Dict) -> &'a Dict {
let direct = || match &*self.form {
Object::Stream(s) => s.dict.get(b"Resources").and_then(Object::as_dict),
_ => None,
};
self.own.as_deref().and_then(Object::as_dict).or_else(direct).unwrap_or(drawn_with)
}
}
/// `o` as a dictionary, read in place for the same reason as [`FormCall::resources`]. `held` keeps it
/// when it is an object of its own. Nothing else is one, and [`Document::resolve`] would copy it.
pub(crate) fn dict_in_place<'a>(doc: &Document, o: &'a Object, held: &'a mut Option<Arc<Object>>) -> Option<&'a Dict> {
match o {
Object::Dict(dict) => Some(dict),
Object::Ref(_) => held.insert(doc.resolve(o)).as_dict(),
_ => None,
}
}
/// The dictionary at `key` of `resources`, `/XObject` or `/Font`, say, as each form reads these.
pub(crate) fn resource_dict<'a>(doc: &Document, resources: &'a Dict, key: &[u8], held: &'a mut Option<Arc<Object>>) -> Option<&'a Dict> {
dict_in_place(doc, resources.get(key)?, held)
}
/// The form XObject `name` in `resources`, drawn with `ctm`. `None` for images, missing names
/// and forms already being read (`path`), and for forms nested too deep or past the page's
/// budget, which `budget` records as truncated; each form entered counts one visit.
@@ -472,13 +505,15 @@ pub(crate) fn form_call(
if limited && budget.truncated {
return None;
}
let xobjects = resources.get(b"XObject").map(|x| doc.resolve(x)).and_then(|x| x.as_dict().cloned())?;
let o = xobjects.get(name)?;
let obj = o.as_ref();
let mut held = None;
let o = resource_dict(doc, resources, b"XObject", &mut held)?.get(name)?;
// Only a reference can name a stream, so nothing else needs reading, or copying.
let obj = Some(o.as_ref()?);
if obj.is_some_and(|r| path.contains(&r)) {
return None;
}
let Object::Stream(s) = &*doc.resolve(o) else { return None };
let form = doc.resolve(o);
let Object::Stream(s) = &*form else { return None };
if s.dict.name(b"Subtype") != Some(b"Form") {
return None;
}
@@ -492,8 +527,7 @@ pub(crate) fn form_call(
let v: Vec<f64> = a.iter().filter_map(|x| doc.resolve(x).as_f64()).collect();
<[f64; 6]>::try_from(v).ok().filter(|v| v.iter().all(|x| x.is_finite()))
});
// A form without its own resources uses the ones it was drawn with (PDF 1.1 files).
let own = s.dict.get(b"Resources").map(|r| doc.resolve(r)).and_then(|r| r.as_dict().cloned());
let own = s.dict.get(b"Resources").filter(|r| matches!(r, Object::Ref(_))).map(|r| doc.resolve(r));
let data = match budget.decode.decode(s) {
Ok(data) => data,
Err(_) if budget.decode.remaining() == 0 => {
@@ -503,7 +537,7 @@ pub(crate) fn form_call(
Err(_) => Vec::new(),
};
budget.visits = budget.visits.saturating_add(1);
Some(FormCall { obj, data, resources: own.unwrap_or_else(|| resources.clone()), ctm: m.map_or(ctm, |m| Matrix(m).then(&ctm)) })
Some(FormCall { obj, data, form, own, ctm: m.map_or(ctm, |m| Matrix(m).then(&ctm)) })
}
/// The lines a page shows as it reads, including text drawn by form XObjects (which
@@ -522,8 +556,9 @@ pub(super) fn reading_lines(doc: &Document, page: usize) -> Result<(Vec<TextLine
fn walk(w: &mut Walk, ops: &[Op], resources: &Dict, carry: &mut Carry, stream: &dyn Fn(usize) -> usize) -> Result<(), EditError> {
let mut cache = HashMap::new();
let mut invoked = Vec::new();
let properties = resources.get(b"Properties").and_then(|o| w.doc.dict(o)).unwrap_or_default();
let shown = interpret(w.doc, ops, resources, &mut cache, carry, Some(&mut invoked), Some(&properties))?;
let (mut held, none) = (None, Dict::new());
let properties = resource_dict(w.doc, resources, b"Properties", &mut held).unwrap_or(&none);
let shown = interpret(w.doc, ops, resources, &mut cache, carry, Some(&mut invoked), Some(properties))?;
let mut last = None;
let mut last_stream = None;
let mut forms = invoked.into_iter().peekable();
@@ -556,7 +591,7 @@ pub(super) fn reading_lines(doc: &Document, page: usize) -> Result<(Vec<TextLine
if let Some(r) = form.obj {
w.path.push(r);
}
walk(w, &ops, &form.resources, &mut carry, &|_| stream)?;
walk(w, &ops, form.resources(resources), &mut carry, &|_| stream)?;
*text_left = carry.text_left;
if form.obj.is_some() {
w.path.pop();
+32 -5
View File
@@ -702,11 +702,13 @@ fn block_ops(plan: &BlockPlan<'_>, writer: &LineWriter<'_>, wrapped: &[(String,
let mut ops = vec![Op::new("q", vec![])];
ops.extend(reveal_ops(plan.block, plan.lines, plan.style, plan.emit.ctm)?);
// Moved: a translation inside that state.
let mut ctm = Matrix(plan.emit.ctm);
if let Some((ax, ay)) = plan.movement {
ops.push(Op::new("cm", vec![n(1.0), n(0.0), n(0.0), n(1.0), n(ax), n(ay)]));
ctm = Matrix([1.0, 0.0, 0.0, 1.0, ax, ay]).then(&ctm);
}
// Painted as the paragraph was, including what its text object set before the first show.
ops.extend(plan.state.paint_ops(plan.after));
ops.extend(plan.state.paint_ops(plan.after, ctm.0));
ops.push(Op::new("BT", vec![]));
let mut state = plan.state.clone();
state.word_spacing = 0.0;
@@ -816,6 +818,11 @@ pub(crate) fn rewrite_block_from(
let first = members.first().copied().ok_or_else(|| EditError::Invalid("the paragraph has no source runs".into()))?;
members.iter().try_for_each(|line| line.ensure_editable())?;
let p = page_dict(doc, page)?;
// Revealed OCR text may go on top of the page (see `revealed_under_paint`): a page that can't
// take that is refused here, before either rewrite path changes anything.
if b.invisible {
crate::check_on_top(doc, &p)?;
}
let mut res = p.dict.get(b"Resources").map(|r| doc.resolve(r)).and_then(|r| r.as_dict().cloned()).unwrap_or_default();
let mut fonts_res = res.get(b"Font").map(|f| doc.resolve(f)).and_then(|f| f.as_dict().cloned()).unwrap_or_default();
let dispatch = choose_rewrite_path(doc, &fonts_res, &b, &members, first, text, style)?;
@@ -930,9 +937,28 @@ pub(crate) fn rewrite_block_from(
char_spacing: o_state.char_spacing,
lead,
};
let plan =
BlockPlan { block: &b, lines: &lines, style, emit, after, movement, state: o_state, tm, size, underline: style.underline == Some(true) };
let at = if split { start } else { emit.bt_op };
// Revealed OCR text that something is painted over goes on top of the page, where it starts
// from the initial state.
let widest = wrapped.iter().map(|(l, _, _)| advance.of(l)).fold(width, f64::max);
let reach = crate::Reach { rect: b.rect, offset: [dx, dy], width: widest, rows: wrapped.len(), pitch: lead * k, upright };
let over = crate::revealed_under_paint(doc, page, b.invisible, reach.bounds(), &ops, at);
let initial = TextState::initial();
let drawn_from = if over { &initial } else { after };
let plan = BlockPlan {
block: &b,
lines: &lines,
style,
emit,
after: drawn_from,
movement,
state: o_state,
tm,
size,
underline: style.underline == Some(true),
};
let mut block_ops = block_ops(&plan, &writer, &wrapped, font.show_font.clone())?;
let on_top = crate::lift_on_top(over, &mut block_ops);
let n = pdfcraft_content::num;
block_ops.extend(after.ops().into_iter().filter(|op| !op.is("Tf") || after.font.is_some()));
if split {
@@ -940,7 +966,6 @@ pub(crate) fn rewrite_block_from(
block_ops.push(Op::new("BT", vec![]));
block_ops.push(Op::new("Tm", emit.tlm.iter().map(|v| n(*v)).collect()));
}
let at = if split { start } else { emit.bt_op };
let new_data = splice(&pieces, &ops, |i| {
let insert = if i == at { std::mem::take(&mut block_ops) } else { Vec::new() };
(insert, !dropped.contains(&i))
@@ -957,12 +982,14 @@ pub(crate) fn rewrite_block_from(
d.set(b"Resources".to_vec(), Object::Dict(res));
}
})?;
crate::draw_on_top(doc, &p, emit.ctm, &on_top)?;
Ok(LineEdit { substituted: font.substituted })
}
/// The cover (when [`BlockStyle::cover`] asks for one) and visible rendering that start a
/// rewritten invisible paragraph, drawn in the space whose CTM is `ctm`. Nothing for visible text.
/// The paragraph's `q`/`Q` restores the rendering mode for the invisible text after it.
/// The paragraph's `q`/`Q` restores the rendering mode for the invisible text after it; one
/// painted over where it was is drawn on top of the page instead ([`crate::draw_on_top`]).
pub(crate) fn reveal_ops(block: &TextBlock, lines: &[TextLine], style: &BlockStyle, ctm: [f64; 6]) -> Result<Vec<Op>, EditError> {
if !block.invisible {
return Ok(Vec::new());
+30 -7
View File
@@ -1,3 +1,4 @@
use super::super::interp::TextState;
use super::grouping::{across, is_centred, row_rect};
use super::{
BlockStyle, CraftFont, Dict, Document, EditError, HashMap, LineEdit, MAX_TYPE3_GLYPHS, Matrix, Metrics, Object, Op, PdfString, Pieces,
@@ -401,6 +402,16 @@ fn paragraph_geometry(doc: &Document, page: &pdfcraft_model::Page, block: &TextB
Ok((dx, dy, style.width.unwrap_or(natural).clamp(1.0, 14_400.0)))
}
/// How far below a row of `size` the next one is written: the source's leading unless a size
/// or line spacing is chosen.
fn row_step(style: &BlockStyle, size: f64, source_leading: f64) -> f64 {
if style.line_spacing.is_none() && style.size.is_none() {
source_leading
} else {
style.line_spacing.unwrap_or(1.5).clamp(0.5, 5.0) * style.size.unwrap_or(size)
}
}
type WrappedStyledRows = (StyledRows, RowRanges, Vec<usize>, Vec<bool>, Vec<usize>);
fn wrap_styled_rows(
@@ -976,6 +987,7 @@ pub(crate) fn rewrite_styled_block(
let o = &lead.origin;
// 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 };
let at = if split { start } else { o.bt_op };
validate_contextual_rows(&rows, &kept)?;
let measured: Vec<_> = rows.iter().map(|row| measure(row)).collect::<Result<_, _>>()?;
let shaped = prepare_shaped_rows(doc, &fonts, &rows, &kept, advance)?;
@@ -989,6 +1001,7 @@ pub(crate) fn rewrite_styled_block(
.ok_or_else(|| EditError::Invalid("the paragraph is drawn in a space it cannot be edited in".into()))?;
let (tx, ty) = back.apply(dx, dy);
block_ops.push(Op::new("cm", vec![n(1.0), n(0.0), n(0.0), n(1.0), n(tx), n(ty)]));
let run_ctm = Matrix([1.0, 0.0, 0.0, 1.0, tx, ty]).then(&Matrix(o.ctm)).0;
// A new row can land one leading above the next paragraph and look like the same
// paragraph. When every row is in this rewrite, a paragraph marker keeps them in one
// scope so the neighbour stays out (#2517). A row left in the source stream cannot share
@@ -1007,6 +1020,19 @@ pub(crate) fn rewrite_styled_block(
})
.rfind(|v| *v > 0.0)
.unwrap_or(first.size * 1.5);
// Revealed OCR text that something is painted over goes on top of the page, where it starts
// from the initial state.
let largest =
block.lines.iter().filter_map(|i| lines.get(*i)).map(|l| l.size).chain(style.ranges.iter().filter_map(|r| r.size)).fold(first.size, f64::max);
// At least one line of the largest glyphs, so a larger range reaches up as far as it draws.
const LINE_EM: f64 = 1.2;
let pitch = source_leading.max(row_step(style, largest, source_leading)).max(largest * LINE_EM);
let widest = measured.iter().copied().fold(width, f64::max);
// This path lays rows out along user-space baselines, so the paragraph is upright here.
let reach = crate::Reach { rect: block.rect, offset: [dx, dy], width: widest, rows: rows.len(), pitch, upright: true };
let over = crate::revealed_under_paint(doc, page, block.invisible, reach.bounds(), &ops, at);
let initial = TextState::initial();
let drawn_from = if over { &initial } else { after };
let mut baseline = first.origin.baseline;
for (row_index, row) in rows.iter().enumerate() {
let anchor = block.rows.get(row_index).and_then(|r| r.first()).and_then(|i| lines.get(*i));
@@ -1073,7 +1099,7 @@ pub(crate) fn rewrite_styled_block(
// 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));
block_ops.extend(state.paint_ops(drawn_from, run_ctm));
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();
@@ -1164,21 +1190,17 @@ pub(crate) fn rewrite_styled_block(
x += segment_width;
pos = end;
}
baseline -= if style.line_spacing.is_none() && style.size.is_none() {
source_leading
} else {
style.line_spacing.unwrap_or(1.5).clamp(0.5, 5.0) * style.size.unwrap_or(anchor.size)
};
baseline -= row_step(style, anchor.size, source_leading);
}
push_whole_paragraph_marker(&mut block_ops, marked, "EMC");
block_ops.push(Op::new("Q", vec![]));
let on_top = crate::lift_on_top(over, &mut block_ops);
block_ops.extend(after.ops());
if split {
block_ops.insert(0, Op::new("ET", vec![]));
block_ops.push(Op::new("BT", vec![]));
block_ops.push(Op::new("Tm", o.tlm.iter().map(|v| n(*v)).collect()));
}
let at = if split { start } else { o.bt_op };
// A kept source row sits outside `block_ops`. Bound the whole paragraph when a marker is
// safe. The close is not part of `block_ops`: that vector can end inside a text object
// when the rewrite splits one, and a kept row's operators come later in the stream.
@@ -1190,5 +1212,6 @@ pub(crate) fn rewrite_styled_block(
d.set(b"Contents".to_vec(), contents);
d.set(b"Resources".to_vec(), Object::Dict(res));
})?;
crate::draw_on_top(doc, &p, o.ctm, &on_top)?;
Ok(LineEdit { substituted })
}
+3
View File
@@ -19,6 +19,7 @@ pdfcraft-annot = { workspace = true }
pdfcraft-forms = { workspace = true }
pdfcraft-xfa = { workspace = true }
pdfcraft-edit = { workspace = true }
pdfcraft-content = { workspace = true }
pdfcraft-audit = { workspace = true }
pdfcraft-redact = { workspace = true }
pdfcraft-print = { workspace = true }
@@ -58,3 +59,5 @@ getrandom = { version = "0.4", features = ["wasm_js"] }
[dev-dependencies]
pdfcraft-testkit = { workspace = true }
# JBIG2 fixtures (`encode_jbig2_generic`).
pdfcraft-filters = { workspace = true }
+20 -1
View File
@@ -146,6 +146,11 @@ pub struct FileResult {
pub log: Vec<String>,
}
/// What an action's log says of the images a Reduce File Size step left, if there are any.
fn images_refused_note(images: usize) -> Option<String> {
(images > 0).then(|| format!("Reduce file size: {images} image(s) stayed as they were, past what one run may decode"))
}
fn apply_step(s: &mut Session, id: DocId, step: &Step, log: &mut Vec<String>) -> Result<Option<DocId>, EditError> {
let pages = s.get(id).map_or(0, |d| d.info.pages.len());
let all: Vec<usize> = (0..pages).collect();
@@ -156,9 +161,10 @@ fn apply_step(s: &mut Session, id: DocId, step: &Step, log: &mut Vec<String>) ->
return Ok(None);
}
Step::ReduceFileSize => {
let (bytes, _) = s.optimized_bytes(id, &crate::optimize::Settings::default(), &[])?;
let (bytes, report) = s.optimized_bytes(id, &crate::optimize::Settings::default(), &[])?;
let before = s.get(id).map_or(0, |d| d.bytes.len());
log.push(format!("Reduce file size: {} → {} bytes", before, bytes.len()));
log.extend(images_refused_note(report.optimize.images_refused));
let name = s.get(id).map(|d| d.name.clone()).unwrap_or_default();
s.close(id);
let new = s.open(name, None, bytes, None).map_err(|e| EditError::Reopen(e.to_string()))?;
@@ -222,3 +228,16 @@ pub fn run_on(action: &Action, name: &str, bytes: Arc<Vec<u8>>, mut progress: im
let bytes = if d.is_signed() { s.save_bytes(id) } else { s.save_full_bytes(id) }.map_err(|e| e.to_string())?;
Ok(FileResult { name: name.to_string(), bytes, log })
}
#[cfg(test)]
mod tests {
use super::images_refused_note;
/// A log line only for images that stayed, saying how many.
#[test]
fn the_log_says_when_images_stayed_as_they_were() {
assert_eq!(images_refused_note(0), None);
assert!(images_refused_note(1).is_some_and(|note| note.contains("1 image(s)")));
assert!(images_refused_note(3).is_some_and(|note| note.contains("3 image(s)")));
}
}
+3
View File
@@ -163,6 +163,8 @@ const HELP: Option<&str> = Some("Help");
/// Every command, in menu order.
pub const COMMANDS: &[CommandSpec] = &[
c("view.select_tool", "Select", None, None, Document, "mouse-pointer-2"),
c("view.hand_tool", "Hand", None, None, Document, "hand"),
c("file.open", "Open…", FILE, Some(Shortcut::cmd("O")), Nothing, "folder-open"),
c("file.open_recent", "Open Recent", FILE, None, Nothing, "clock"),
// Shown at the foot of File ▸ Open Recent and on Home, not as its own File menu item.
@@ -259,6 +261,7 @@ pub const COMMANDS: &[CommandSpec] = &[
c("comment.underline", "Underline text", None, None, Annotate, "underline"),
c("comment.strikeout", "Strikethrough text", None, None, Annotate, "strikethrough"),
c("comment.squiggly", "Squiggly underline text", None, None, Annotate, "spline"),
c("comment.freehand_highlight", "Freehand-Highlight", None, None, Annotate, "highlighter"),
c("comment.ink", "Draw freehand", None, None, Annotate, "pencil"),
c("comment.line", "Draw a line", None, None, Annotate, "minus"),
c("comment.arrow", "Draw an arrow", None, None, Annotate, "move-right"),
+1
View File
@@ -82,6 +82,7 @@ pub fn comment_type_name(subtype: &str) -> &str {
/// [`comment_type_name`], telling callouts, clouds and typewriter text apart by `/IT`.
pub fn comment_kind(a: &pdfcraft_render::Annotation) -> &str {
match a.intent.as_deref() {
Some("FreehandHighlight") if a.subtype == "Ink" => "Freehand Highlight",
Some("FreeTextCallout") => "Callout",
Some("PolygonCloud") => "Cloud",
Some("FreeTextTypeWriter") => "Typewriter",
+23 -4
View File
@@ -140,6 +140,8 @@ pub enum OfficeFormat {
Docx,
Pptx,
Html,
/// CSS-free HTML that preserves text and inline images but drops colours and layout styling.
HtmlSimple,
Rtf,
Markdown,
}
@@ -150,6 +152,7 @@ impl OfficeFormat {
OfficeFormat::Docx => "docx",
OfficeFormat::Pptx => "pptx",
OfficeFormat::Html => "html",
OfficeFormat::HtmlSimple => "html",
OfficeFormat::Rtf => "rtf",
OfficeFormat::Markdown => "md",
}
@@ -173,14 +176,15 @@ pub struct OfficeExport {
/// The exported file.
pub bytes: Vec<u8>,
/// Pages (0-based) that draw forms nested deeper than [`MAX_FORM_DEPTH`] or more of them
/// than [`MAX_FORM_VISITS`], or pictures past [`MAX_EXPORT_IMAGE_BYTES`]: export stops
/// reading there to stay bounded on hostile files, so the text and images of those forms, or
/// than [`MAX_FORM_VISITS`], or pictures past [`MAX_EXPORT_IMAGE_BYTES`] or past what one export
/// may decode: export stops reading there to stay bounded on hostile files, so the text and images of those forms, or
/// those pictures, are missing from `bytes`.
pub truncated_pages: Vec<usize>,
}
/// An image object prepared for Office export: its file extension and encoded bytes, or why it is
/// left out (`Err(true)`: past [`MAX_EXPORT_IMAGE_BYTES`]; `Err(false)`: it can't be encoded).
/// left out (`Err(true)`: past [`MAX_EXPORT_IMAGE_BYTES`], or what the export may decode;
/// `Err(false)`: it can't be encoded).
type PreparedImage = Result<(&'static str, Arc<[u8]>), bool>;
impl crate::Document {
@@ -194,6 +198,18 @@ impl crate::Document {
/// pictures went past `image_budget` bytes ([`OfficeExport::truncated_pages`]). Without
/// `images` no picture is prepared.
pub(crate) fn export_pages_checked(&self, images: bool, image_budget: usize) -> (Vec<pdfcraft_export::Page>, Vec<usize>) {
let Some(editor) = self.editor.as_ref() else { return (Vec::new(), Vec::new()) };
self.export_pages_within(images, image_budget, &mut pdfcraft_cos::ImageBudget::new(&editor.cos))
}
/// [`Self::export_pages_checked`], its pictures decoded within `image_work`, which is shared
/// by the whole export: a picture past it is left out like one past `image_budget`.
pub(crate) fn export_pages_within(
&self,
images: bool,
image_budget: usize,
image_work: &mut pdfcraft_cos::ImageBudget,
) -> (Vec<pdfcraft_export::Page>, Vec<usize>) {
let Some(cos) = self.editor.as_ref().map(|e| &e.cos) else { return (Vec::new(), Vec::new()) };
let mut truncated = Vec::new();
// Each image object is encoded once and shared by every place that draws it.
@@ -244,7 +260,9 @@ impl crate::Document {
.filter_map(|im| {
let object = im.object?;
let prepared = encoded.entry(object).or_insert_with(|| {
let (ext, bytes) = pdfcraft_create::image_file(cos, object).map_err(|_| false)?;
let refused = image_work.refused();
let (ext, bytes) =
pdfcraft_create::image_file_within(cos, object, &mut *image_work).map_err(|_| image_work.refused() > refused)?;
image_bytes = image_bytes.checked_sub(bytes.len()).ok_or(true)?;
Ok((if ext == "jpg" { "jpg" } else { "png" }, Arc::from(bytes)))
});
@@ -286,6 +304,7 @@ impl crate::Document {
OfficeFormat::Docx => pdfcraft_export::docx(&pages, &title),
OfficeFormat::Pptx => pdfcraft_export::pptx(&pages, &title),
OfficeFormat::Html => pdfcraft_export::html(&pages, &title).into_bytes(),
OfficeFormat::HtmlSimple => pdfcraft_export::html_simple(&pages, &title).into_bytes(),
OfficeFormat::Rtf => pdfcraft_export::rtf(&pages).into_bytes(),
OfficeFormat::Markdown => pdfcraft_export::markdown(&pages).into_bytes(),
};
+1 -2
View File
@@ -18,9 +18,8 @@ impl Document {
/// [`Document::page_images`]: a raster image, or Form artwork that holds one.
pub fn page_image_at(&self, page: usize, at: [f64; 2]) -> Option<usize> {
let editor = self.editor.as_ref()?;
let inside = |r: &[f64; 4]| (r[0]..=r[2]).contains(&at[0]) && (r[1]..=r[3]).contains(&at[1]);
self.page_images(page).iter().rposition(|i| {
inside(&i.rect)
i.contains(at)
&& match (i.is_form, i.object) {
(false, Some(_)) => true,
(true, Some(form)) => picture_in_form(&editor.cos, form).is_some(),
Loaded 100 of 451 files, more files were not shown because too many files have changed in this diff. Show more