mirror of
https://github.com/storytold/pdfcraft.git
synced 2026-11-11 00:41:21 +00:00
Merge upstream/main into feat/callout-reshape-1152
Keeps both the callout-parts test and main's ungroup tests in automation.rs. Carries the shared fix for main's rules.rs build break (content_streams now returns ContentStream; join via text::joined). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Pq7HyCHD1R3rywQBPCHXZA
This commit is contained in:
commit
699ee46ced
187 files changed
+16348
-1579
No files matched your search
@@ -0,0 +1,28 @@
|
||||
name: House rules
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
paths:
|
||||
- AGENTS.md
|
||||
- CLAUDE.md
|
||||
- .github/workflows/house-rules.yml
|
||||
pull_request:
|
||||
paths:
|
||||
- AGENTS.md
|
||||
- CLAUDE.md
|
||||
- .github/workflows/house-rules.yml
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: house-rules-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
house-rules:
|
||||
uses: storytold/craft-common-actions/.github/workflows/house-rules.yml@main
|
||||
with:
|
||||
rust: true
|
||||
@@ -19,7 +19,14 @@ concurrency:
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
# Regenerates contributors/contributors.json for the release commit; every build bundles it.
|
||||
credits:
|
||||
permissions:
|
||||
contents: read
|
||||
pull-requests: read
|
||||
uses: storytold/craft-common-actions/.github/workflows/refresh-contributors.yml@main
|
||||
release:
|
||||
needs: credits
|
||||
# Intentionally tracked at @main (not SHA-pinned) so org-wide CI improvements, security fixes, and build optimizations propagate without PR churn across all craftapp repos.
|
||||
uses: storytold/craft-common-actions/.github/workflows/release.yml@main
|
||||
with:
|
||||
@@ -27,6 +34,7 @@ jobs:
|
||||
app-title: PdfCraft
|
||||
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
|
||||
version: ${{ inputs.version }}
|
||||
contributors-artifact: ${{ needs.credits.outputs.artifact-name }}
|
||||
secrets:
|
||||
APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }}
|
||||
APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }}
|
||||
|
||||
@@ -1,6 +1,59 @@
|
||||
<!-- craft-house-rules:start core source=dde09ea31e2e457f5b4653a6e76f7cdf55944bdf sha256=540e6cea75d12d0710c3dca89658328e81e508ecef102446ca5bb95b7c0b92bb -->
|
||||
## House rules
|
||||
|
||||
These apply in every Craft repository. A later rule may be stricter, not weaker. The source is `standards/house-rules-core.md` in `storytold/craft-contrib`. Propose changes there, not in a copy.
|
||||
|
||||
1. **A person is accountable.** Whoever runs an agent answers for what it opens and for its review comments.
|
||||
2. **Check, then claim.** Before writing code, read the issue comments, search pull requests for `#N` and the keywords, and check recent commits on `main`. Comment on the issue first. Release a claim you will not finish.
|
||||
3. **Verify, don't guess.** Open a definition before using it. Confirm the cause in the code, even when someone names a location.
|
||||
4. **Keep fixes narrow and tested.** Fix what the issue describes, where the bug is. Add a test that fails without the fix.
|
||||
5. **Review the diff before opening a pull request.** Identifiers exist as used, the test fails without the fix, nothing unrelated changed, and the description is true.
|
||||
6. **Look for a better pull request.** If another fixes the same thing, close yours when it is better or equal, and say why.
|
||||
7. **Report only what ran.** Say what you tested and what you could not run. Without a local build or test, say so and rely on CI before marking ready.
|
||||
8. **`main` changes through a pull request.** Do not push to it. Branch protection enforces this. There is no exception.
|
||||
9. **Stop and ask only about** licensing outside the allowlist, publishing, releases, a new remote, secrets, spending money, destructive git, and anything else hard to undo. Otherwise keep working. `plan/` is a gitignored notebook, not rules. Without it, do not ask for it and do not stop.
|
||||
10. **Keep secrets and personal details out** of the repository, logs and requests.
|
||||
11. **CI stays shared.** Workflows call `storytold/craft-common-actions`. Do not change CI in a feature or fix pull request. If CI cannot cover a change, open an issue there.
|
||||
12. **Guards say why.** A check that looks removable says what it prevents. Read that before changing it.
|
||||
13. **Instructions must be readable by everyone.** No notes about one machine, and no links to files a reader cannot open. `craftrules` is retired. Do not link to it.
|
||||
14. **Keep pull requests moving.** Concurrent pull requests are fine; unanswered actionable feedback is not. Respond in 7 days, a reminder at 14, closure eligible at 30, from when an actionable request waits on the author. Suggestions and unconfirmed bot findings do not start the clock. A fix, explanation or agreed plan resets it; unrelated activity does not. Waiting on a reviewer or maintainer pauses it and does not count against the author. A maintainer decides closure; it is never automatic. Reuse search results, do not poll, and stop at a rate limit.
|
||||
15. **No agent attribution.** A pull request does not say an agent wrote it. A repository rule may not require that.
|
||||
<!-- craft-house-rules:end -->
|
||||
<!-- craft-house-rules:start rust source=dde09ea31e2e457f5b4653a6e76f7cdf55944bdf sha256=387e0ccb4b49e567f60951d7d6fff7305054c89f43ad812b9993dc7c38528013 -->
|
||||
## Rust Craft repositories
|
||||
|
||||
These apply to native Craft apps and to shared Rust libraries. Select them by repository type. A repository that merely contains some Rust does not take this block. Rules later in a repository's file may be stricter, but not weaker. The source is `standards/house-rules-rust.md` in [storytold/craft-contrib](https://github.com/storytold/craft-contrib).
|
||||
|
||||
1. **Never crash.** Non-test code does not panic and has no `unsafe`, except where the repository file names an exception. Return errors, treat input as hostile, and bound recursion and allocations. New production crate roots copy the `deny` attribute from an existing crate: `clippy::unwrap_used`, `clippy::expect_used`, `clippy::panic`, `clippy::unimplemented`, `clippy::todo`, `clippy::unreachable`. Every crash fix comes with a test that panicked before the fix.
|
||||
2. **Clean room.** Learn from observed behaviour and public specifications. Do not copy another product's code, assets, strings or artwork. Check a dependency's licence before adding it.
|
||||
3. **Assets and fonts.** Every asset is original or suitably licensed, and is recorded in `ATTRIBUTION.md` in the same change. Font files live in [storytold/craft-fonts](https://github.com/storytold/craft-fonts), not in the app repository.
|
||||
4. **Rust only for native Craft apps.** No handwritten JavaScript or TypeScript, and no Tauri, Electron or webview shell, in those apps. Shared tooling follows its documented technical scope and maintainer-approved exceptions. Craft PR Review's existing Tauri and TypeScript UI is one such exception. It does not relax this rule for native apps. Preserve any existing web build.
|
||||
5. **Time goes through `chrono`.** Do not hand-roll calendar conversion. For dates beyond what `chrono` can represent, follow [standards/time.md](https://github.com/storytold/craft-contrib/blob/main/standards/time.md).
|
||||
6. **Contributor credits.** Add or edit only your own person's entry in `contributors/people.toml`, and only after asking them. Never guess a name or hand-edit `contributors.json`.
|
||||
|
||||
## Licence allowlist
|
||||
|
||||
Dependencies and assets use SPDX identifiers. An expression is allowed when every identifier is in this list. A repository may name a shorter list. It may not add an identifier here by editing its own copy of these rules.
|
||||
|
||||
- `ISC`
|
||||
- `MIT`
|
||||
- `BSD-2-Clause`
|
||||
- `BSD-3-Clause`
|
||||
- `Apache-2.0`
|
||||
- `OFL-1.1`
|
||||
- `Ubuntu-font-1.0`
|
||||
- `Bitstream-Vera`
|
||||
- `CC0-1.0`
|
||||
- `CC-BY-4.0`
|
||||
- `CC-BY-SA-4.0`
|
||||
- `LicenseRef-Public-Domain`
|
||||
|
||||
`LicenseRef-Storyteller-Trademark` is not in this list. It covers Storyteller brand marks only, where a repository already says so.
|
||||
<!-- craft-house-rules:end -->
|
||||
|
||||
# AGENTS.md — rules for every agent and contributor
|
||||
|
||||
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.**
|
||||
These rules bind every AI agent and every human contributor working in this repository. They come before any task, instruction or deadline. Day-to-day working instructions are in this file; `CLAUDE.md` imports it.
|
||||
|
||||
---
|
||||
|
||||
@@ -85,7 +138,7 @@ If you find an asset that breaks these rules, stop and remove it from the reposi
|
||||
|
||||
---
|
||||
|
||||
## 2. Clean-room rules (summary; details in `CLAUDE.md` and `plan/adr/0001`)
|
||||
## 2. Clean-room rules (summary; `plan/adr/0001` is an optional local note)
|
||||
|
||||
- Never read, disassemble or copy anything inside the Acrobat bundle. Only names and listings are allowed, and **never** open `Contents/Resources/JavaScripts/`.
|
||||
- Behaviour comes only from public specifications (ISO 32000-2, the Arlington model), public documentation and black-box observation.
|
||||
@@ -106,7 +159,7 @@ If you find an asset that breaks these rules, stop and remove it from the reposi
|
||||
|
||||
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`).
|
||||
- **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 below).
|
||||
- **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.
|
||||
- **No `unsafe`.** The workspace sets `unsafe_code = "forbid"`. If a platform API needs it, use a maintained safe wrapper crate; a real exception needs the owner's sign-off.
|
||||
- **Treat every input-derived number as hostile.** Use `get()` instead of `[i]` or `[a..b]`. Slice strings only at char boundaries. Use checked/saturating arithmetic for lengths, offsets and counts. Guard against division by zero and NaN/inf casts, and never cast a negative value to `usize`. Cap allocations sized by the file.
|
||||
@@ -115,10 +168,18 @@ PdfCraft opens files from strangers, and people trust it with their work. A malf
|
||||
- **Prove it.** Every crash fix comes with a small synthetic regression test that panicked before the fix. Turn fuzzer findings (`cargo xtask fuzz`) into such tests before fixing them.
|
||||
- **Enforced by clippy.** Root `clippy.toml` lets tests use `unwrap`/`expect`/`panic!`. A crate that is clean carries `#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]`; new crates start with it.
|
||||
|
||||
## 5. Everything else
|
||||
## 5. Page interaction, fidelity and gates
|
||||
|
||||
|
||||
Follow `CLAUDE.md`. It covers quality gates, layering, commit rules and how to run and look at the app.
|
||||
- **Layering.** Nothing below L7 depends on egui/winit/eframe/rfd. `cos`, `filters`, `crypt` and `arlington` stay standalone.
|
||||
- **Page input.** Page modules read `PagePointer` (`crates/ui-egui/src/page_pointer.rs`), never egui's raw pointer state. `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`, `crates/ui-egui/src/canvas/page_cursor.rs`) and never set it themselves. `page_pointer::tests::page_modules_claim_the_cursor_and_never_set_it` enforces it.
|
||||
- **Page presses.** A page module decides what is under a point in one hit test (`Hit` in `crates/ui-egui/src/canvas/page_router.rs`) and acts on a press only through that router. Modules never read the router; they are told. `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.
|
||||
- **Fonts** are the optional build input `CRAFT_FONTS_DIR`. Code using `pdfcraft_fonts::CRAFT_FONTS` must work when it is empty.
|
||||
- **Quality gates** before every commit: `cargo fmt --check`, clippy with `-D warnings`, the tests, `cargo xtask layers`, `cargo xtask assets`, and the wasm check. New workspace crates include `workspace = true` under `[lints]`. Scope `cargo clippy -p <crate> --all-targets -- -D warnings` and `cargo test -p <crate>` to the crates you touched; the workspace sweep is CI's job.
|
||||
- **Review at four zooms** as you go: the clause, the function, the module, and the project (layering, wasm, undo, save fidelity, a matching automation tool, an honest `parity/` entry). Prove a test fails before the fix by reverting the fix once.
|
||||
- `plan/` is an optional gitignored notebook. Do not ask for it and do not stop when it is absent. Public status is [`ROADMAP.md`](ROADMAP.md), [`docs/gaps.md`](docs/gaps.md) and [`docs/roadmap.md`](docs/roadmap.md). "Shipped" in `parity/` means exists and tested, not parity with Acrobat.
|
||||
- `cargo run -p pdfcraft -- <file.pdf>` opens the app. `pdfcraft-cli run` drives the engine headlessly. `cargo xtask fuzz` findings stay in `fuzz-out/` and become synthetic tests. For UI work, look at a screenshot from `--control` or the `shot` example.
|
||||
|
||||
## Contributor credits (About window)
|
||||
|
||||
|
||||
+5
-5
@@ -45,7 +45,7 @@ Every asset PdfCraft includes, bundles or uses to build its published material,
|
||||
| `assets/icons/chevron-up.svg` | Lucide icon "chevron-up" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/chevron-up.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
|
||||
| `assets/icons/chevrons-left.svg` | Lucide icon "chevrons-left" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/chevrons-left.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
|
||||
| `assets/icons/chevrons-right.svg` | Lucide icon "chevrons-right" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/chevrons-right.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
|
||||
| `assets/icons/circle-check.svg` | Lucide icon "circle-check" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/circle-check.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
|
||||
| `assets/icons/circle-check.svg` | Lucide icon "circle-check" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/circle-check.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs; drawn as PDF path data by crates/sign/src/status_layers.rs into displayed signature status layers |
|
||||
| `assets/icons/circle-dashed.svg` | Lucide icon "circle-dashed" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/circle-dashed.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
|
||||
| `assets/icons/circle-dot.svg` | Lucide icon "circle-dot" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/circle-dot.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
|
||||
| `assets/icons/circle-help.svg` | Lucide icon "circle-help" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/circle-help.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
|
||||
@@ -174,7 +174,7 @@ Every asset PdfCraft includes, bundles or uses to build its published material,
|
||||
| `assets/icons/text-select.svg` | Lucide icon "text-select" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/text-select.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
|
||||
| `assets/icons/trash-2.svg` | Lucide icon "trash-2" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/trash-2.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
|
||||
| `assets/icons/trash.svg` | Lucide icon "trash" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/trash.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
|
||||
| `assets/icons/triangle-alert.svg` | Lucide icon "triangle-alert" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/triangle-alert.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
|
||||
| `assets/icons/triangle-alert.svg` | Lucide icon "triangle-alert" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/triangle-alert.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs; drawn as PDF path data by crates/sign/src/status_layers.rs into displayed signature status layers |
|
||||
| `assets/icons/type.svg` | Lucide icon "type" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/type.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
|
||||
| `assets/icons/underline.svg` | Lucide icon "underline" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/underline.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
|
||||
| `assets/icons/undo-2.svg` | Lucide icon "undo-2" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/undo-2.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
|
||||
@@ -184,7 +184,7 @@ Every asset PdfCraft includes, bundles or uses to build its published material,
|
||||
| `assets/icons/x.svg` | Lucide icon "x" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/x.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
|
||||
| `assets/icons/zoom-in.svg` | Lucide icon "zoom-in" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/zoom-in.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
|
||||
| `assets/icons/zoom-out.svg` | Lucide icon "zoom-out" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/zoom-out.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
|
||||
| `assets/fonts/Inter-Regular.ttf` | Inter Regular | The Inter Project Authors (Rasmus Andersson) | OFL-1.1 | https://github.com/rsms/inter | UI font, embedded in the app; demo PDF labels; slanted fallback glyphs in Fill & Sign typed signatures for characters Dancing Script lacks (Cyrillic, Greek), drawn as filled paths |
|
||||
| `assets/fonts/Inter-Regular.ttf` | Inter Regular | The Inter Project Authors (Rasmus Andersson) | OFL-1.1 | https://github.com/rsms/inter | UI font, embedded in the app; demo PDF labels; slanted fallback glyphs in Fill & Sign typed signatures for characters Dancing Script lacks (Cyrillic, Greek), drawn as filled paths; embedded into displayed signature status captions beyond WinAnsi by crates/sign/src/status_layers.rs |
|
||||
| `assets/fonts/Inter-Medium.ttf` | Inter Medium | The Inter Project Authors (Rasmus Andersson) | OFL-1.1 | https://github.com/rsms/inter | UI font, embedded in the app; demo PDF labels |
|
||||
| `assets/fonts/Inter-SemiBold.ttf` | Inter SemiBold | The Inter Project Authors (Rasmus Andersson) | OFL-1.1 | https://github.com/rsms/inter | UI font, embedded in the app; demo PDF labels |
|
||||
| `assets/fonts/JetBrainsMono-Regular.ttf` | JetBrains Mono Regular | The JetBrains Mono Project Authors | OFL-1.1 | https://github.com/JetBrains/JetBrainsMono | UI monospace font; demo PDF code |
|
||||
@@ -249,7 +249,7 @@ Every asset PdfCraft includes, bundles or uses to build its published material,
|
||||
| `assets/icons/thumbs-up.svg` | Lucide icon "thumbs-up" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/thumbs-up.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
|
||||
| `assets/icons/thumbs-down.svg` | Lucide icon "thumbs-down" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/thumbs-down.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
|
||||
| `assets/icons/message-square-plus.svg` | Lucide icon "message-square-plus" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/message-square-plus.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
|
||||
| `assets/icons/circle-x.svg` | Lucide icon "circle-x" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/circle-x.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
|
||||
| `assets/icons/circle-x.svg` | Lucide icon "circle-x" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/circle-x.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs; drawn as PDF path data by crates/sign/src/status_layers.rs into displayed signature status layers |
|
||||
| `crates/ui-egui/tests/data/form.pdf` | One-page AcroForm test fixture (text, check box, radio group, combo box) | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: hand-written PDF objects, no third-party content | Form-filling UI tests (crates/ui-egui/tests/it/forms.rs, commands.rs) |
|
||||
| `assets/icons/pentagon.svg` | Lucide icon "pentagon" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/pentagon.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
|
||||
| `assets/icons/message-square-quote.svg` | Lucide icon "message-square-quote" | Lucide Contributors (portions Cole Bemis, Feather) | ISC AND MIT | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/message-square-quote.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
|
||||
@@ -314,4 +314,4 @@ Not in this repository and never downloaded by it: compiled in only when the bui
|
||||
| Input | Option | Title | Author | Licence | Source | Attribution | Used for |
|
||||
|---|---|---|---|---|---|---|---|
|
||||
| `craft-i18n` | `CRAFT_I18N_DIR` | Interface translations: the craft-i18n catalogs (locales/<code>/common.tsv and pdfcraft.tsv) of the 34 languages PdfCraft offers besides English | The craft-i18n translators, including every translator of PdfCraft's former in-repo catalogs (crates/ui-egui/src/i18n/*.tsv, migrated at pdfcraft@ecdd1e6) | MIT OR Apache-2.0 | https://github.com/storytold/craft-i18n (pinned by commit in craft-i18n.rev, which CI, releases and the flatpak manifests read) | https://github.com/storytold/craft-i18n/blob/main/ATTRIBUTION.md | Interface text in languages other than English, embedded by crates/ui-egui/build.rs and looked up through craft-libs' craft-i18n crate; a build without CRAFT_I18N_DIR is English only. Clean-room translations from PdfCraft's English interface labels |
|
||||
| `craft-fonts` | `CRAFT_FONTS_DIR` | Japanese fonts: BIZ UDPGothic (Regular, Bold), Shippori Mincho, BIZ UDMincho; native Simplified Chinese font: LXGW WenKai Lite; Arabic font: Noto Sans Arabic | The BIZ UDGothic and BIZ UDMincho Project Authors (Morisawa Inc.), The Shippori Mincho Project Authors (FONTDASU), LXGW and the original Klee Project Authors / Fontworks (LXGW WenKai Lite), The Noto Project Authors (Noto Sans Arabic) | OFL-1.1 | https://github.com/storytold/craft-fonts (pinned by commit in .github/workflows/release.yml and .github/workflows/ci.yml); LXGW WenKai Lite from https://github.com/lxgw/LxgwWenKai-Lite/releases/tag/v1.530 (commit b712c83d98acf977bacfb7fb010207802808bda9) | https://github.com/storytold/craft-fonts/blob/main/ATTRIBUTION.md | Japanese fallback in the interface (BIZ UDPGothic first) and Japanese glyphs in edited PDF text (Shippori Mincho); Simplified Chinese interface fallback on native builds only (LXGW WenKai Lite Regular, font SHA-256 f799a538a3355877e597a0ae04050e897932c9ae7689eb9227c2953c5dd549ea, OFL SHA-256 0333a85fe077b6849f8e417acc44e8bd879442ceb681e271acf93e2d57fd4e2e, read from fonts/simplified-chinese-manifest.txt and never embedded on wasm); Arabic interface text, file names and document titles (Noto Sans Arabic); the web build embeds BIZ UDPGothic Regular and the pinned small Arabic, Hebrew, Thai and Devanagari faces; the selected craft-fonts revision contains no Telugu face. Other non-Japanese CJK faces retain the general 4 MiB cap; the reviewed native-only LXGW fallback has a separate 16 MiB cap. Open-source OFL releases are permitted under current AGENTS.md §1.1 |
|
||||
| `craft-fonts` | `CRAFT_FONTS_DIR` | Japanese fonts: BIZ UDPGothic (Regular, Bold), Shippori Mincho, BIZ UDMincho; native Simplified Chinese font: LXGW WenKai Lite; Arabic font: Noto Sans Arabic | The BIZ UDGothic and BIZ UDMincho Project Authors (Morisawa Inc.), The Shippori Mincho Project Authors (FONTDASU), LXGW and the original Klee Project Authors / Fontworks (LXGW WenKai Lite), The Noto Project Authors (Noto Sans Arabic) | OFL-1.1 | https://github.com/storytold/craft-fonts (pinned by commit in .github/workflows/release.yml and .github/workflows/ci.yml); LXGW WenKai Lite from https://github.com/lxgw/LxgwWenKai-Lite/releases/tag/v1.530 (commit b712c83d98acf977bacfb7fb010207802808bda9) | https://github.com/storytold/craft-fonts/blob/main/ATTRIBUTION.md | Japanese fallback in the interface (BIZ UDPGothic first) and Japanese glyphs in edited PDF text (Shippori Mincho); Simplified Chinese interface fallback on native builds only (LXGW WenKai Lite Regular, font SHA-256 f799a538a3355877e597a0ae04050e897932c9ae7689eb9227c2953c5dd549ea, OFL SHA-256 0333a85fe077b6849f8e417acc44e8bd879442ceb681e271acf93e2d57fd4e2e, read from fonts/simplified-chinese-manifest.txt and never embedded on wasm); Arabic interface text, file names and document titles (Noto Sans Arabic); status captions of named-layer signatures in Arabic, Japanese, Thai and Devanagari, drawn as filled outlines into the display copy by crates/sign/src/status_layers.rs; the web build embeds BIZ UDPGothic Regular and the pinned small Arabic, Hebrew, Thai and Devanagari faces; the selected craft-fonts revision contains no Telugu face. Other non-Japanese CJK faces retain the general 4 MiB cap; the reviewed native-only LXGW fallback has a separate 16 MiB cap. Open-source OFL releases are permitted under current AGENTS.md §1.1 |
|
||||
+5
-5
@@ -425,7 +425,7 @@ source = "https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icon
|
||||
licence = "ISC AND MIT"
|
||||
licence_file = "assets/icons/LICENSE-lucide.txt"
|
||||
kind = "icon"
|
||||
usage = "UI icon, embedded via crates/ui-egui/src/icon_data.rs"
|
||||
usage = "UI icon, embedded via crates/ui-egui/src/icon_data.rs; drawn as PDF path data by crates/sign/src/status_layers.rs into displayed signature status layers"
|
||||
sha256 = "201e790f3a05c65b2c4b0f952c9b9e1f35cd1c5b21698b3f4be131883fe90bc8"
|
||||
|
||||
[[asset]]
|
||||
@@ -1844,7 +1844,7 @@ source = "https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icon
|
||||
licence = "ISC AND MIT"
|
||||
licence_file = "assets/icons/LICENSE-lucide.txt"
|
||||
kind = "icon"
|
||||
usage = "UI icon, embedded via crates/ui-egui/src/icon_data.rs"
|
||||
usage = "UI icon, embedded via crates/ui-egui/src/icon_data.rs; drawn as PDF path data by crates/sign/src/status_layers.rs into displayed signature status layers"
|
||||
sha256 = "55aa37e0b73e7f8cd906952dbdeb96283c6595ca64aba240a17f3455cb989114"
|
||||
|
||||
[[asset]]
|
||||
@@ -1954,7 +1954,7 @@ source = "https://github.com/rsms/inter"
|
||||
licence = "OFL-1.1"
|
||||
licence_file = "assets/fonts/OFL-Inter.txt"
|
||||
kind = "font"
|
||||
usage = "UI font, embedded in the app; demo PDF labels; slanted fallback glyphs in Fill & Sign typed signatures for characters Dancing Script lacks (Cyrillic, Greek), drawn as filled paths"
|
||||
usage = "UI font, embedded in the app; demo PDF labels; slanted fallback glyphs in Fill & Sign typed signatures for characters Dancing Script lacks (Cyrillic, Greek), drawn as filled paths; embedded into displayed signature status captions beyond WinAnsi by crates/sign/src/status_layers.rs"
|
||||
sha256 = "40d692fce188e4471e2b3cba937be967878f631ad3ebbbdcd587687c7ebe0c82"
|
||||
|
||||
[[asset]]
|
||||
@@ -3004,7 +3004,7 @@ source = "https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icon
|
||||
licence = "ISC AND MIT"
|
||||
licence_file = "assets/icons/LICENSE-lucide.txt"
|
||||
kind = "icon"
|
||||
usage = "UI icon, embedded via crates/ui-egui/src/icon_data.rs"
|
||||
usage = "UI icon, embedded via crates/ui-egui/src/icon_data.rs; drawn as PDF path data by crates/sign/src/status_layers.rs into displayed signature status layers"
|
||||
sha256 = "ef1fec17d88794ba6c34c5cf63bdadbd234b3d4dffbcc3d55468b47e3f398472"
|
||||
|
||||
[[asset]]
|
||||
@@ -3142,7 +3142,7 @@ source = "https://github.com/storytold/craft-fonts (pinned by commit in .github/
|
||||
licence = "OFL-1.1"
|
||||
attribution = "https://github.com/storytold/craft-fonts/blob/main/ATTRIBUTION.md"
|
||||
kind = "font"
|
||||
usage = "Japanese fallback in the interface (BIZ UDPGothic first) and Japanese glyphs in edited PDF text (Shippori Mincho); Simplified Chinese interface fallback on native builds only (LXGW WenKai Lite Regular, font SHA-256 f799a538a3355877e597a0ae04050e897932c9ae7689eb9227c2953c5dd549ea, OFL SHA-256 0333a85fe077b6849f8e417acc44e8bd879442ceb681e271acf93e2d57fd4e2e, read from fonts/simplified-chinese-manifest.txt and never embedded on wasm); Arabic interface text, file names and document titles (Noto Sans Arabic); the web build embeds BIZ UDPGothic Regular and the pinned small Arabic, Hebrew, Thai and Devanagari faces; the selected craft-fonts revision contains no Telugu face. Other non-Japanese CJK faces retain the general 4 MiB cap; the reviewed native-only LXGW fallback has a separate 16 MiB cap. Open-source OFL releases are permitted under current AGENTS.md §1.1"
|
||||
usage = "Japanese fallback in the interface (BIZ UDPGothic first) and Japanese glyphs in edited PDF text (Shippori Mincho); Simplified Chinese interface fallback on native builds only (LXGW WenKai Lite Regular, font SHA-256 f799a538a3355877e597a0ae04050e897932c9ae7689eb9227c2953c5dd549ea, OFL SHA-256 0333a85fe077b6849f8e417acc44e8bd879442ceb681e271acf93e2d57fd4e2e, read from fonts/simplified-chinese-manifest.txt and never embedded on wasm); Arabic interface text, file names and document titles (Noto Sans Arabic); status captions of named-layer signatures in Arabic, Japanese, Thai and Devanagari, drawn as filled outlines into the display copy by crates/sign/src/status_layers.rs; the web build embeds BIZ UDPGothic Regular and the pinned small Arabic, Hebrew, Thai and Devanagari faces; the selected craft-fonts revision contains no Telugu face. Other non-Japanese CJK faces retain the general 4 MiB cap; the reviewed native-only LXGW fallback has a separate 16 MiB cap. Open-source OFL releases are permitted under current AGENTS.md §1.1"
|
||||
|
||||
[[asset]]
|
||||
path = "crates/sign/tests/data/x509-rsa-sha1.pdf"
|
||||
|
||||
@@ -1,65 +1 @@
|
||||
# PdfCraft — instructions for agents
|
||||
|
||||
PdfCraft is a clean-room, open-source, Rust-native PDF application targeting Adobe Acrobat Pro parity. It runs natively on macOS, Windows, Linux and FreeBSD, and on the web via WASM. It is the sibling of `../photocraft` (a Photoshop-class editor) and follows the same conventions.
|
||||
|
||||
## 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 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.
|
||||
|
||||
`plan/` is gitignored (local-only, like PhotoCraft). The machine-readable parity checklist lives in `parity/` (committed).
|
||||
|
||||
## 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). 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/`).
|
||||
- Never copy GPL/AGPL code. MuPDF, Ghostscript, Poppler, veraPDF and DSS run only as external oracle processes.
|
||||
- See `plan/README.md` §Clean-room and `plan/adr/0001`.
|
||||
- **Privacy.** When observing Acrobat, use synthetic fixtures only. Never capture the Home view, recent files or account info. Capture by window id (`plan/acrobat/tools/`). Never commit Acrobat outputs, corpus files or personal data.
|
||||
- **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 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.
|
||||
- No indexing or slicing with input-derived positions (use `get`, and slice strings only at char boundaries).
|
||||
- Use checked or saturating arithmetic on input-derived numbers, and guard against division by zero and NaN/inf casts.
|
||||
- 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.
|
||||
- **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.
|
||||
- Tests mirror the zooms: property → unit → crate integration → end-to-end.
|
||||
- **Prove a test fails before the fix by actually reverting the fix.** A test nobody has seen fail is not evidence. This has caught two worthless tests in this repo: one confinement test passed with path resolution switched off entirely, because the tools failed on a nonexistent document id before reaching the path.
|
||||
- **Rebasing is a review step, not a mechanical one.** Read every hunk you resolve, and the auto-merged hunks in the files you touched too — `main` moves fast enough that a file can change by hundreds of lines under a branch.
|
||||
- **External PRs are held to safety, security and completeness before style.** Provenance first (no Adobe-derived asset, no committed font, no copied GPL/AGPL code, behaviour from the spec and not from reading another implementation), then no new panic path or `unsafe`, then `--root` confinement on every path including ones reached by nested dispatch, opt-in-only MCP and control channel, no new outbound network, then a headless `automation` tool, tests at the right zoom and an honest `parity/` entry. Provenance is the part a contributor cannot be expected to know, and the only part that cannot be undone after merge.
|
||||
- **Quality gates** before every commit: `cargo fmt --check`, clippy with `-D warnings`, the tests, `cargo xtask layers`, `cargo xtask assets`, and the wasm check once `xtask ci` exists (M0).
|
||||
- New workspace crates must include `[lints] workspace = true` in `Cargo.toml` to inherit `[workspace.lints]`. Production crate roots must declare the required crate-level lint attributes before modules or other crate items; crate-level `//!` documentation may precede them.
|
||||
- **Scope builds and tests to the crates you touched** — `cargo clippy -p <crate> -j 2 --all-targets` and `cargo test -p <crate> -j 2`, under a `timeout`. A full `--workspace` build has locked up a development machine's CPU; it is CI's job and CI runs it on every PR. Run the workspace sweep locally only when you have a reason to and the machine is free.
|
||||
- **Check for existing work before starting a fix or feature.** Search the issues and PRs, open and closed, with `gh issue list -R storytold/pdfcraft --state all --search "<terms>"` and the same with `gh pr list` (try a few phrasings), and check whether a merged fix is already on `main` (`git merge-base --is-ancestor <commit> origin/main`). If one is, the report is likely from an older build: say so rather than fixing it again. If an open PR covers it, review or build on that PR instead of opening a competing one. If an issue exists, reference it in the PR (`Fixes #123`).
|
||||
- **Commits and PRs:** `main` is the only integration branch and is **never pushed to directly**. Branch from an up-to-date `main` as `<type>/<slug>` (`feat/`, `fix/`, `docs/`, `chore/`, `refactor/`), one task id per commit (e.g. `M1.4: xref stream reader`), commit only green states, and open a PR into `main` using `.github/pull_request_template.md`. Merge only when CI is green.
|
||||
- **`main` moves fast enough that PRs rot.** It took 396 commits in the three days to 2026-10-12, and most open PRs are conflicting at any given time. Rebase your own branch the same day `main` moves under it, and ask the author to rebase theirs — never rewrite a contributor's branch. Conflict risk tracks how *contested* the files are, not how large the change is: tooling, tests and docs are nearly free, while `crates/fonts`, `ui-egui` and the i18n catalogues are where several people collide at once.
|
||||
|
||||
## Running and looking at the app
|
||||
- `cargo run -p pdfcraft -- <file.pdf>` opens the desktop app.
|
||||
- `cargo run -p pdfcraft-cli -- run --script steps.json --root DIR` drives the engine headlessly through the automation tools (`pdfcraft-cli tools` lists them). Use it, together with `page_render`, to check engine changes. `pdfcraft-cli mcp` is the opt-in MCP server (AGENTS.md §3).
|
||||
- `cargo xtask fuzz --time 300` mutation-fuzzes open/render/edit/save in child processes. Findings land in `fuzz-out/findings/` (git-ignored; never commit corpus-derived files). Turn every real finding into a small synthetic regression test before fixing it.
|
||||
- `cargo xtask parity [--partial]` reports Acrobat-parity progress from `parity/acrobat-features.toml`. Update the entry when a feature ships.
|
||||
- `cargo xtask demo-pdf` builds `dist/demo/pdfcraft-showcase.pdf` (needs Chrome) for visual checks.
|
||||
- For UI work, **look at the result**. Either launch `pdfcraft --control FILE doc.pdf` and use `pdfcraft-cli ui --control FILE screenshot --out x.png` (plus `inspect`, `click`, `key`, `type`, `command`, `set`), or take a headless shot with `cargo run -p pdfcraft-ui-egui --example shot`. Compare against `plan/acrobat/02-ui-ux.md`. Control-channel tests use kittest (`crates/ui-egui/tests/control.rs`).
|
||||
- Parallel agents: use a separate `CARGO_TARGET_DIR` per agent and separate git worktrees.
|
||||
|
||||
## Current bootstrap debt (tracked in STATUS.md)
|
||||
- `pdfcraft-render` renders through the `hayro` crate directly and inspects documents through `lopdf`. Both get replaced by `cos` / `model` / the DisplayList device (M1–M2, ADR-0004).
|
||||
|
||||
## 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.
|
||||
- Don't add or change CI in a feature or fix PR. If the existing workflows can't build or test a change, link an existing craft-common-actions issue or PR, or open a new issue, or a PR only for a small fix that is safe for every app and does not increase CI time.
|
||||
- Some workflow files here still run their own jobs. Don't add to them. Moving a job into craft-common-actions is its own task, never part of another PR, and the job stays here until a shared workflow runs it.
|
||||
@AGENTS.md
|
||||
Generated
+40
-2
@@ -1312,10 +1312,21 @@ dependencies = [
|
||||
"zip",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-web-api"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=fd5e2feff6ea25bed371a99cc732b3968d621505#fd5e2feff6ea25bed371a99cc732b3968d621505"
|
||||
dependencies = [
|
||||
"js-sys",
|
||||
"serde_json",
|
||||
"wasm-bindgen",
|
||||
"wasm-bindgen-futures",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-web-host"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=2e2312ddaf21bc3d85cd3395d0955c7d239306f6#2e2312ddaf21bc3d85cd3395d0955c7d239306f6"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=fd5e2feff6ea25bed371a99cc732b3968d621505#fd5e2feff6ea25bed371a99cc732b3968d621505"
|
||||
dependencies = [
|
||||
"wasm-bindgen",
|
||||
"web-sys",
|
||||
@@ -4254,7 +4265,6 @@ version = "0.18.1"
|
||||
dependencies = [
|
||||
"pdfcraft-content",
|
||||
"pdfcraft-cos",
|
||||
"pdfcraft-filters",
|
||||
"pdfcraft-fonts",
|
||||
"pdfcraft-model",
|
||||
"thiserror 2.0.21",
|
||||
@@ -4631,6 +4641,7 @@ dependencies = [
|
||||
"pdfcraft-render",
|
||||
"pdfcraft-testkit",
|
||||
"pdfcraft-xfa",
|
||||
"regex",
|
||||
"sha2 0.11.1",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
@@ -4676,9 +4687,11 @@ dependencies = [
|
||||
"p521",
|
||||
"pbkdf2",
|
||||
"pdfcraft-annot",
|
||||
"pdfcraft-content",
|
||||
"pdfcraft-cos",
|
||||
"pdfcraft-fonts",
|
||||
"pdfcraft-model",
|
||||
"pdfcraft-testkit",
|
||||
"rc2",
|
||||
"ripemd",
|
||||
"rsa",
|
||||
@@ -4754,11 +4767,13 @@ dependencies = [
|
||||
name = "pdfcraft-web"
|
||||
version = "0.18.1"
|
||||
dependencies = [
|
||||
"craft-web-api",
|
||||
"craft-web-host",
|
||||
"eframe",
|
||||
"egui",
|
||||
"js-sys",
|
||||
"pdfcraft-ui-egui",
|
||||
"serde_json",
|
||||
"wasm-bindgen-futures",
|
||||
"web-sys",
|
||||
]
|
||||
@@ -5507,6 +5522,29 @@ dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "regex"
|
||||
version = "1.13.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d"
|
||||
dependencies = [
|
||||
"aho-corasick",
|
||||
"memchr",
|
||||
"regex-automata",
|
||||
"regex-syntax",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "regex-automata"
|
||||
version = "0.4.18"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2"
|
||||
dependencies = [
|
||||
"aho-corasick",
|
||||
"memchr",
|
||||
"regex-syntax",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "regex-syntax"
|
||||
version = "0.8.11"
|
||||
|
||||
+8
-1
@@ -70,7 +70,11 @@ pdfcraft-prc-render = { path = "crates/prc-render", version = "0.18.1" }
|
||||
hayro = "0.7.1"
|
||||
hayro-syntax = "0.7.2"
|
||||
lopdf = "0.45"
|
||||
flate2 = { version = "1.1", default-features = false, features = ["rust_backend"] }
|
||||
# zlib-rs: miniz_oxide took about 1.7 µs for every fixed-Huffman block, empty or not
|
||||
# (`pdfcraft_filters::FLATE_READ_WORK`). Other dependencies still build flate2's default
|
||||
# miniz_oxide backend; flate2 prefers zlib-rs when both are built, as the Windows build already did
|
||||
# through craft-update. `flate::tests::a_copy_from_before_the_start_is_damage` shows which runs.
|
||||
flate2 = { version = "1.1", default-features = false, features = ["zlib-rs"] }
|
||||
weezl = "0.2"
|
||||
# CCITT Group 4 encoding (pdfcraft-filters); already in the tree through tiff.
|
||||
fax = "0.2.7"
|
||||
@@ -80,6 +84,9 @@ hayro-jbig2 = "0.3"
|
||||
|
||||
# foundation
|
||||
thiserror = "2"
|
||||
# Linear-time matching (no backtracking) for caller-supplied redaction patterns. `perf-dfa` gives
|
||||
# the lazy-DFA cache that `RegexBuilder::dfa_size_limit` bounds (the limit is inert without it).
|
||||
regex = { version = "1", default-features = false, features = ["std", "unicode", "perf-dfa"] }
|
||||
serde = { version = "1", features = ["derive", "rc"] }
|
||||
serde_json = "1"
|
||||
log = "0.4"
|
||||
|
||||
+10
@@ -3,6 +3,8 @@
|
||||
> **Last reviewed:** 2026-11-03 | **Last updated:** 2026-11-03 | **Change:** patch (M5 #5850 review: indirect typewriter intent and composer edits preserve outer whitespace; movement regression commits by outside click; estimates unchanged)
|
||||
|
||||
> **Last reviewed:** 2026-11-03 | **Last updated:** 2026-11-03 | **Change:** patch (M5 #5850: Enter adds Fill & Sign line breaks; outside clicks commit, Escape cancels, and saved multiline appearances retain their text and height; estimates unchanged)
|
||||
> **Last reviewed:** 2026-10-31 | **Last updated:** 2026-10-31 | **Change:** minor (M3/M4, #5330: Crop pages is directly available in the document quick toolbar; estimates unchanged)
|
||||
|
||||
|
||||
> **Last reviewed:** 2026-11-01 | **Last updated:** 2026-11-01 | **Change:** patch (M7, PR #2155 further review: inherited drawing/text state, affine image gestures, paste/selection ownership, no-op scripts and menu permissions; estimates unchanged)
|
||||
|
||||
@@ -229,6 +231,7 @@ Ranked; detail and the full milestone table in [docs/roadmap.md](docs/roadmap.md
|
||||
| 8 | 1.0 polish: performance, right-to-left, missing languages, keyboard-only (M14) | 55–95 |
|
||||
|
||||
## Progress log
|
||||
- **2026-10-13 (M8, redact by regex):** `redact_mark` takes `regex` (caller expression, linear-time engine, length/size/nesting caps, empty-matching refused) with optional `validate` (luhn, mod97, iban). Headless only; issue #1886.
|
||||
|
||||
- **2026-10-28 (M10, #4119 partial):** Scan & OCR ▸ Enhance scanned file cleans scanned pages in place: background removal (level 0–100, as the camera clean-up), edge shadow removal (book gutters, copier borders) and despeckle. Each scan image is decoded, cleaned and written back into its own object at the same size and colour space (JPEG stays JPEG, others lossless, 1-bit stays 1-bit), so the OCR text layer, comments and links stay; one undo step, shared images once, unsupported images (CMYK, indexed, JPEG 2000, JBIG2, CCITT, broken data) reported. `page_enhance_scan` drives it headlessly. Not yet an option of Recognize text. Estimates unchanged.
|
||||
- **2026-11-03 (M11, shared JBIG2 dictionary):** With Monochrome Images set to JBIG2, Optimize has up to 16 JBIG2 images share one symbol dictionary (`/JBIG2Globals`), the letters found on more than one page stored once, when that is smaller (`pdfcraft_filters::encode_jbig2_shared`). Eight pages of 10 pt text rendered at 300 dpi take 41% less in Helvetica and 42% in Times than coded alone, 10% in Courier; groups of 16 save 45%, of 32 only 47%. Only images redaction can store again without the dictionary share one (image masks and DeviceGray named directly, at most 64 Mi pixels), and redacting one stores the rest of its group so, which the group bounds to 15.
|
||||
@@ -256,6 +259,7 @@ Ranked; detail and the full milestone table in [docs/roadmap.md](docs/roadmap.md
|
||||
|
||||
- 2026-11-01: PR #2155 review follow-up preserves editor crops through group moves and keeps arranged artwork outside added-item streams; unsafe nested-tag extraction is refused. Image handles and flips follow page orientation, added images accept general transforms, and clipboard/text/Home/font-discovery edge cases have focused regressions. Candidate only; estimates unchanged.
|
||||
- 2026-11-01: PR #2155 maintainer edits remove redundant image/text helpers and add regressions for crop ownership, arrange scope/state fidelity, clipboard precedence, crop-drag bounds, and font scanning. Transform and Unicode-script tools complete the headless paths.
|
||||
- **2026-10-31 (M3/M4, #5330):** The document quick toolbar offers Crop pages directly through the existing page.crop command, with the command’s assembly-permission check and an active-tool highlight. The existing crop, undo and headless page_set_box paths are unchanged. No toolbar customization or new shortcut. Estimates unchanged.
|
||||
|
||||
- **2026-10-18 (M3, #1354, local candidate):** Integrated --two-paged with current main, retaining upstream modal/picker ownership and single-tab reuse. Native launch/opening/password regressions, negative checks against the old wrapper, visual inspection, formatting, strict scoped Clippy, layers, assets, parity and scoped WASM compilation pass. Three existing socket tests are unavailable in this workspace; one existing network test remains ignored. No push or GitHub merge; estimates unchanged.
|
||||
- **2026-10-31 (M2, PR #4172 review):** Added same-machine pixel oracles for GBK Song, Hei, Kai and FangSong, including all four subset-prefixed Founder aliases. Reference PDFs use explicit Unicode mappings and independently selected installed faces; font data and rasters remain in memory. All eight cases ran; wrong-glyph and wrong-family production mutations each failed the new assertion and were restored. Validation: 422 renderer unit tests, renderer all-target Clippy with -D warnings, formatting, layers/assets/parity and renderer WASM checks passed; existing optional-patch/WASM warnings and parity notes remain. Estimates unchanged.
|
||||
@@ -315,6 +319,7 @@ Ranked; detail and the full milestone table in [docs/roadmap.md](docs/roadmap.md
|
||||
- **2026-10-22 (M14, macOS association recovery candidate):** Successful desktop open/save/sign can queue recovery of an existing per-file binding to the running PDFCraft bundle through NSWorkspace. Metadata-only watcher changes retain undo and avoid false overwrite prompts; real same-length/same-mtime edits remain protected. Rebased on 0.12.0 and reuses #3042's shared atomic metadata preservation; the bounded recovery parser does not narrow save limits. Prior native Preview TEST-signature and Finder workflows passed on macOS 27.0.1; other versions remain unqualified. Estimates unchanged.
|
||||
- **2026-10-13 (M7, free image rotation):** A selected page image has a rotate knob (Shift: 15 degree steps) and `image_edit` a `rotate_by` action; the angle is written as one undoable `cm`. Snapping to page edges while moving is in #1740; resize snapping is not done. Estimates unchanged.
|
||||
|
||||
- **2026-10-20 (M9 #79 review, M2, M8):** text extraction reads a marked-content /ActualText that marks no glyph where it paints (paths and images, cut to what is visible, along the direction they are drawn), so words drawn as outlines can be found, copied and exported; OCR and scan field detection still count such a page as having no text of its own. Redaction strips /ActualText, /Alt, /E and /T from inline marked content around paint it clips, as it already did around paint it removed, so a partly redacted outlined word leaves no name in the file. Named-layer recognition also needs the layer form to draw n1 and n3. Estimates unchanged.
|
||||
- **2026-10-20 (M4, initial view):** Window and interface options read indirect boolean ViewerPreferences values. Synthetic regressions cover true/false, direct/indirect preference dictionaries and save/reopen; malformed entries retain false defaults. Estimates unchanged.
|
||||
- **2026-10-20 (M3, #3535):** Escape with a menu open closes the menu and keeps the text selection; the next Escape clears it, as before. One keypress used to do both. A synthetic UI regression checks it. Estimates unchanged.
|
||||
- **2026-10-16 (M3, close prompt keyboard):** The "Save changes?" prompt opens with Save chosen (Enter saves, as before) and the arrow keys and Tab / Shift+Tab move the choice to Cancel or Don't save, shown with a focus ring; Enter or Space press the chosen button and Escape still cancels. Before, Enter always saved whatever was Tab-focused. Estimates unchanged.
|
||||
@@ -405,6 +410,8 @@ Ranked; detail and the full milestone table in [docs/roadmap.md](docs/roadmap.md
|
||||
- **2026-10-16 (M10, #1201 partial):** Lossless image export applies each component's Decode pair. Indexed values round and clip before palette lookup. Color-key masks keep raw samples. The existing 16-bit precision limit remains. JPEG and mask Decode, ICC transforms, and calibrated colors remain outside this fix. Estimates unchanged.
|
||||
- **2026-10-16 (M3, #2739):** Wrapped revision buttons stay above Binding in Document Properties. A synthetic regression checks control bounds and opens a saved revision at two viewport widths. Estimates unchanged.
|
||||
- **2026-10-19 (M7, tracked text):** Editable paragraphs and object labels distinguish repeated glyph tracking from word gaps in TJ arrays and separately positioned glyphs. Synthetic regressions cover character spacing, horizontal scaling, rotated baselines, larger word gaps, and rows of one-glyph words or cells (inferred tracking is capped at half an em, so `a b c` and digit or Y/N columns keep their spaces). Estimates unchanged.
|
||||
- **2026-10-16 (M9, #79):** a signature appearance that follows the named-layer convention (its /N draws one Form that holds and draws n1 and n3) shows the signature's real state: n1, n3 and n4 are redrawn in the display copy with the panel's icons and a caption in the interface language (Helvetica; else shaped in embedded Inter, or in a craft-fonts face for Arabic, Japanese and Telugu; else English, as Chinese always is). Exports, both print modes and the CLI's render show the redrawn state; saves never do. Every signature keeps its badge, since a document can clip or cover its own layers. Estimates unchanged.
|
||||
- **2026-10-16 (M9):** the page validation overlay moves to the widget's bottom-right corner as it lies on the page (so it turns with the page and the view) and takes a quarter of the widget's shorter side, at most 48 screen points, so it annotates the signer's artwork from a corner instead of covering the middle of it; a field too small for a legible mark keeps its outline, a rectangle the screen cannot place is not drawn at all, and the whole widget answers the pointer. Estimates unchanged.
|
||||
- **2026-10-16 (M5, #2669, item 5):** The Comments panel groups replies by name and counts all page roots once per frame. Estimates unchanged.
|
||||
- **2026-10-16 (M7, #2140):** Header & footer (and Bates numbering, which uses the same dialog) can shrink the page content so the header and footer don't cover it: the original content is scaled evenly into the band they leave free, centred across, also on rotated pages; Remove and Update take the scaling away, and margins that leave no room are refused. Dialog checkbox with a preview of the band, `shrink` on `doc_header_footer`, all catalogs. Annotations and added text and images are not moved yet. Estimates unchanged.
|
||||
- **2026-10-20 (M14, Spanish catalog gaps):** `es.tsv` gains the 143 `(context, English)` keys the other catalogs carried and it was missing, so Spanish covers the whole bundled key union like Lithuanian and Vietnamese: calendar months and weekdays, the `certificate` context, X.509 key usages, signature-revision and digital-ID lines, password validation, eight plural messages, the combine-from-folder strings, the rendering and stale-file notices and the shortcut-spelled tooltips. Counts in `localization-parity.md` re-measured against the current union (`vi` restated against it for the same reason). Status stays `partial`: no translated help, and OS details stay outside the catalog. Estimates unchanged.
|
||||
@@ -793,6 +800,7 @@ Newest first: the date, what moved, and the new overall estimate.
|
||||
| 2026-11-01 | patch | M7 #5657: header/footer, watermark and background operations commit all selected pages together; later-page errors preserve marks, content, shared/inherited resources and pending edits; estimates unchanged. |
|
||||
| 2026-10-28 | patch | M2, PR #4172: integrate main 5af10276 and retain both roadmap histories; viewer-only CJK and print/output font policies and estimates unchanged. |
|
||||
| 2026-10-27 | minor | M10: OCR stages SHA-256-verified ONNX models after the upstream RTEN URL brownout; discovery prefers a complete ONNX pair per directory, falls back to a complete RTEN pair, and never mixes formats or directories; language/web limits and estimates unchanged. |
|
||||
| 2026-10-20 | minor | M9 #79 review, M2, M8: /ActualText that marks no glyph extracts where it paints, as far as it is visible; redaction strips /ActualText around paint it clips; named-layer recognition needs the layer form to draw n1 and n3. Estimates unchanged. |
|
||||
| 2026-10-23 | minor | M8, #3205 follow-up: phone-pattern redaction includes the +39 country code on labelled Italian geographic numbers with a slash; dates, protocol identifiers and whole-run guards remain. Estimates unchanged. |
|
||||
| 2026-10-23 | minor | M11: image downsampling measures physical resolution after page-local UserUnit scaling, including shared nested forms; synthetic measurement and optimization regressions. Estimates unchanged. |
|
||||
| 2026-10-23 | minor | M10: Word table cells use the grid columns they span, including cells after a merged cell; synthetic export regression and CLI reproduction. Estimates unchanged. |
|
||||
@@ -807,6 +815,8 @@ Newest first: the date, what moved, and the new overall estimate.
|
||||
| 2026-10-18 | minor | M1, #1143: a live reference may match the xref generation or a same-number header at its indexed offset; neither-match and free slots remain null. Bounded repair diagnostics and synthetic cache, free-slot, edit and classic/packed save regressions; estimates unchanged. |
|
||||
| 2026-10-18 | minor | M5, PR #1971: nested source `/Page` and `/Pages` dictionaries export as null without traversing page content or the page tree. Synthetic saved/reopened three-page regression retains unrelated metadata and aliases. FDF import semantics, copied-graph limits and estimates unchanged. |
|
||||
| 2026-10-15 | minor | M5: budget retained FDF entries before cloning; discovery keeps lazy array owners and annotation positions, with alias/cache-eviction stress fixtures. Limits cover the copied graph; source parsing/page discovery retain existing COS/parser limits, with no total source-memory bound. FDF import semantics and estimates unchanged. |
|
||||
| 2026-10-16 | minor | M9 #79: named-layer signature appearances show the signature's real state in the display copy, exports and both print modes, never in saves; captions follow the interface language. Estimates unchanged. |
|
||||
| 2026-10-16 | minor | M9: the page validation overlay moves to the widget's bottom-right corner as it lies on the page and stops growing past 48 screen points, so it annotates the signer's artwork from a corner instead of covering the middle of it; a field under 32 screen points keeps its outline. Estimates unchanged. |
|
||||
| 2026-10-15 | minor | M7: the Edit text caret is as tall as the row it is on in a region with several sizes; estimates unchanged. |
|
||||
| 2026-10-18 | minor | M4, PR #1919 review: repeated page indices apply each rotation to the latest page-local value, preserving indirect/inherited angles. Synthetic adjacent/interleaved duplicates retain siblings and page contents through incremental and full saves. Estimates unchanged. |
|
||||
| 2026-10-18 | minor | M3, #3149: page replacement cancels render demand collected for the previous geometry; all viewer raster upload paths reject empty or oversized textures before cache eviction. Synthetic regressions reproduce the reported 1880×2350 upload at a 2048 limit, retain cached images and unsaved edits, and resume bounded backdrops and tiles. Estimates unchanged. |
|
||||
|
||||
@@ -366,8 +366,9 @@ pub(crate) fn render(args: &[String]) -> Result<(), CliError> {
|
||||
Some("pam") => None,
|
||||
_ => return Err(format!("render: --out {out}: use a .png, .jpg, .tif or .pam name").into()),
|
||||
};
|
||||
// The app renders a display copy that draws comments missing their /AP streams; the CLI
|
||||
// must agree with it (and with independent viewers), while keeping the file it reads intact.
|
||||
// The app renders a display copy that draws comments missing their /AP streams and the state
|
||||
// of named-layer signatures (here with no trusted certificates); the CLI must agree with it
|
||||
// (and with independent viewers), while keeping the file it reads intact.
|
||||
let bytes = read(path)?;
|
||||
let password = flag(args, "--password");
|
||||
// The renderer takes only the user password of R2–R4 files; `Session::open` and the display
|
||||
|
||||
@@ -12,9 +12,12 @@ workspace = true
|
||||
[dependencies]
|
||||
pdfcraft-ui-egui = { workspace = true }
|
||||
# The host messages (storytold/craft-libs): one contract and one bridge for the web builds.
|
||||
craft-web-host = { git = "https://github.com/storytold/craft-libs", rev = "2e2312ddaf21bc3d85cd3395d0955c7d239306f6", version = "0.1.0" }
|
||||
# The page command API (storytold/craft-libs#413): window.pdfcraft over the UI control channel.
|
||||
craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "fd5e2feff6ea25bed371a99cc732b3968d621505", version = "0.1.0" }
|
||||
craft-web-host = { git = "https://github.com/storytold/craft-libs", rev = "fd5e2feff6ea25bed371a99cc732b3968d621505", version = "0.1.0" }
|
||||
eframe = { workspace = true, features = ["default_fonts", "glow", "persistence", "accesskit"] }
|
||||
egui = { workspace = true, features = ["default_fonts", "monochrome_emoji_fonts"] }
|
||||
serde_json = { workspace = true }
|
||||
|
||||
[target.'cfg(target_arch = "wasm32")'.dependencies]
|
||||
wasm-bindgen-futures = "0.4"
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
//! `window.pdfcraft`: the page command API (`craft-web-api`, storytold/craft-libs#413) over the app's
|
||||
//! UI control channel (`pdfcraft_ui_egui::control`), opt-in with `?control`.
|
||||
//!
|
||||
//! The crate owns the JavaScript side (`request`, `execute`, `commands`, `docInspect`, `uiInspect`,
|
||||
//! `screenshot`, as promises with a timeout). This module is PdfCraft's part: a [`Request`] that
|
||||
//! sends each call through the app's [`ControlClient`] and waits for the reply, and the table that
|
||||
//! names PdfCraft's methods: its control channel drives the UI, so `commands` is `ui.commands`,
|
||||
//! `execute` runs a registry command with `ui.command`, `docInspect` is `ui.state` and `uiInspect`
|
||||
//! is `ui.inspect`.
|
||||
//!
|
||||
//! The channel keeps the accessibility tree of every frame, so it is off unless the page asks for it
|
||||
//! (`?control`), as FigCraft's is. PdfCraft's control requests cannot be withdrawn, so a call the page
|
||||
//! gave up on may still run (or be rejected) when the app reaches it, as it does for a desktop client that timed out.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
/// The reply of a control request as the protocol's `{ok, result}` / `{ok: false, error}` object.
|
||||
fn reply_object(reply: Result<Value, String>) -> Value {
|
||||
match reply {
|
||||
Ok(result) => json!({"ok": true, "result": result}),
|
||||
Err(error) => json!({"ok": false, "error": error}),
|
||||
}
|
||||
}
|
||||
|
||||
/// The params of `ui.command`. `execute(command, params)` sends `{command, params}`; `ui.command`
|
||||
/// takes `{id}` (and `params` for `ui.panel`). A request that already names an `id` is the page's own
|
||||
/// `request("ui.command", {id})` and goes through unchanged.
|
||||
fn command_params(params: Value) -> Value {
|
||||
match params.get("command").and_then(Value::as_str) {
|
||||
Some(command) if params.get("id").is_none() => json!({"id": command, "params": params.get("params").cloned().unwrap_or(Value::Null)}),
|
||||
_ => params,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
pub use web::install;
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
mod web {
|
||||
use std::rc::Rc;
|
||||
use std::sync::mpsc::{Receiver, TryRecvError};
|
||||
|
||||
use craft_web_api::methods::Methods;
|
||||
use craft_web_api::page::{PageApi, Request};
|
||||
use pdfcraft_ui_egui::control::{ControlClient, Reply};
|
||||
use serde_json::{Value, json};
|
||||
use wasm_bindgen_futures::JsFuture;
|
||||
|
||||
use super::{command_params, reply_object};
|
||||
|
||||
/// The app id in `window.<app>`.
|
||||
const APP: &str = "pdfcraft";
|
||||
|
||||
/// How often a waiting call looks for the app's reply, in milliseconds (about a frame).
|
||||
const POLL_MS: i32 = 16;
|
||||
|
||||
/// PdfCraft's control methods behind each function.
|
||||
fn methods() -> Methods {
|
||||
Methods {
|
||||
commands: Some("ui.commands"),
|
||||
execute: Some("ui.command"),
|
||||
doc_inspect: Some("ui.state"),
|
||||
ui_inspect: Some("ui.inspect"),
|
||||
screenshot: Some("ui.screenshot"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Put `window.pdfcraft` on the page, sending its calls through `client`. An existing
|
||||
/// `window.pdfcraft` keeps the functions it already has.
|
||||
pub fn install(client: ControlClient) {
|
||||
let request: Request = Rc::new(move |method, params| {
|
||||
let params = if method == "ui.command" { command_params(params) } else { params };
|
||||
Box::pin(wait(client.send(&method, params)))
|
||||
});
|
||||
if let Err(e) = Rc::new(PageApi::new(APP, methods(), request)).install() {
|
||||
eframe::web_sys::console::warn_1(&format!("PdfCraft: couldn't install window.{APP}: {e:?}").into());
|
||||
}
|
||||
}
|
||||
|
||||
/// The app's reply, polled about once a frame.
|
||||
async fn wait(reply: Receiver<Reply>) -> Value {
|
||||
loop {
|
||||
match reply.try_recv() {
|
||||
Ok(reply) => return reply_object(reply),
|
||||
Err(TryRecvError::Empty) => sleep(POLL_MS).await,
|
||||
Err(TryRecvError::Disconnected) => return json!({"ok": false, "error": "the app dropped the request"}),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn sleep(ms: i32) {
|
||||
let promise = js_sys::Promise::new(&mut |resolve, _| {
|
||||
if let Some(window) = web_sys::window() {
|
||||
let _ = window.set_timeout_with_callback_and_timeout_and_arguments_0(&resolve, ms);
|
||||
}
|
||||
});
|
||||
let _ = JsFuture::from(promise).await;
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use serde_json::json;
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn execute_becomes_a_ui_command_by_id() {
|
||||
assert_eq!(command_params(json!({"command": "file.word_count", "params": {"a": 1}})), json!({"id": "file.word_count", "params": {"a": 1}}));
|
||||
assert_eq!(command_params(json!({"command": "file.save", "params": {}})), json!({"id": "file.save", "params": {}}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_request_that_names_an_id_goes_through_unchanged() {
|
||||
let own = json!({"id": "file.save"});
|
||||
assert_eq!(command_params(own.clone()), own);
|
||||
let both = json!({"id": "ui.panel", "command": "x", "params": {"reset": true}});
|
||||
assert_eq!(command_params(both.clone()), both, "an id wins over a command");
|
||||
assert_eq!(command_params(json!({})), json!({}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn replies_become_the_protocols_objects() {
|
||||
assert_eq!(reply_object(Ok(json!({"n": 1}))), json!({"ok": true, "result": {"n": 1}}));
|
||||
assert_eq!(reply_object(Err("boom".to_string())), json!({"ok": false, "error": "boom"}));
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,9 @@
|
||||
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
|
||||
#[cfg(any(target_arch = "wasm32", test))]
|
||||
mod api;
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn main() {
|
||||
use pdfcraft_ui_egui::PdfCraftApp;
|
||||
@@ -68,6 +71,11 @@ fn main() {
|
||||
&"PdfCraft: ?host=parent needs a framing page on the same origin; saves download instead".into(),
|
||||
);
|
||||
}
|
||||
// `?control`: `window.pdfcraft`, the page's command API (`api`). Opt-in: the control
|
||||
// channel keeps the accessibility tree of every frame.
|
||||
if query_param("control").is_some() {
|
||||
api::install(app.attach_control(&cc.egui_ctx));
|
||||
}
|
||||
Ok(Box::new(app))
|
||||
}),
|
||||
)
|
||||
|
||||
@@ -333,7 +333,7 @@ fn native_options(integrated: bool, app_frame: bool, renderer: eframe::Renderer)
|
||||
let mut viewport = egui::ViewportBuilder::default()
|
||||
.with_title("PdfCraft")
|
||||
.with_inner_size([1440.0, 920.0])
|
||||
.with_min_inner_size([820.0, 520.0])
|
||||
.with_min_inner_size(pdfcraft_ui_egui::MIN_WINDOW_SIZE)
|
||||
.with_drag_and_drop(true)
|
||||
// Wayland app id: matches packaging/linux/ai.storyteller.pdfcraft.desktop.
|
||||
.with_app_id(APP_ID);
|
||||
|
||||
@@ -186,3 +186,8 @@ sync_github_name = true
|
||||
|
||||
[people.helenkwok]
|
||||
real_name = "Helen Kwok"
|
||||
|
||||
[people.vangel76]
|
||||
real_name = "Valentin Klein"
|
||||
display_name = "vangel76"
|
||||
sync_github_name = false
|
||||
@@ -14,6 +14,5 @@ workspace = true
|
||||
pdfcraft-cos = { workspace = true }
|
||||
pdfcraft-model = { workspace = true }
|
||||
pdfcraft-content = { workspace = true }
|
||||
pdfcraft-filters = { workspace = true }
|
||||
pdfcraft-fonts = { workspace = true }
|
||||
thiserror.workspace = true
|
||||
+74
-20
@@ -25,6 +25,8 @@ pub enum AltError {
|
||||
NotAFigure(u32),
|
||||
#[error("the page has more content than can be edited")]
|
||||
TooLarge,
|
||||
#[error("the figure's content may be in a damaged or unreadable content stream, or after the damage, so nothing was changed")]
|
||||
Damaged,
|
||||
#[error("{0}")]
|
||||
Cos(#[from] pdfcraft_cos::CosError),
|
||||
}
|
||||
@@ -52,6 +54,8 @@ pub enum ArtifactError {
|
||||
ParentTree(String),
|
||||
#[error("the page has more content than can be edited")]
|
||||
TooLarge,
|
||||
#[error("the tag's marked content may be in a damaged or unreadable content stream, or after the damage, so nothing was changed")]
|
||||
Damaged,
|
||||
#[error(transparent)]
|
||||
Cos(#[from] pdfcraft_cos::CosError),
|
||||
}
|
||||
@@ -372,7 +376,19 @@ fn content_entries(doc: &Document, page: &Dict) -> Vec<Object> {
|
||||
}
|
||||
}
|
||||
|
||||
type DecodedStream = (Object, Option<(Stream, Vec<u8>)>);
|
||||
/// How much of a content stream decoded.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
enum Read {
|
||||
Whole,
|
||||
/// Damaged partway: the data is what decoded before the damage. What follows it is unknown,
|
||||
/// the syntax the later streams start in too.
|
||||
Damaged,
|
||||
/// Not at all (a filter this reader lacks, say): the data is empty.
|
||||
Unread,
|
||||
}
|
||||
|
||||
/// A `/Contents` entry and, for a stream, the stream, its decoded data and how much of it decoded.
|
||||
type DecodedStream = (Object, Option<(Stream, Vec<u8>, Read)>);
|
||||
|
||||
/// Decode the page's content streams within the page decode budget. `None` when a stream is
|
||||
/// rejected because the budget is exhausted.
|
||||
@@ -383,14 +399,14 @@ fn decode_page_streams(doc: &Document, page: &Dict) -> Option<Vec<DecodedStream>
|
||||
for entry in entries {
|
||||
let decoded = match &*doc.resolve(&entry) {
|
||||
Object::Stream(s) => {
|
||||
let data = match budget.decode(s) {
|
||||
Ok(data) => data,
|
||||
let (data, read) = match budget.decode_with_damage(doc, s, usize::MAX) {
|
||||
Ok((data, damaged)) => (data, if damaged { Read::Damaged } else { Read::Whole }),
|
||||
// Content past the budget may hold more of the tag: editing the rest
|
||||
// would leave that part marked as a tag the tree no longer has.
|
||||
Err(_) if budget.exhausted() => return None,
|
||||
Err(_) => Vec::new(),
|
||||
Err(_) => (Vec::new(), Read::Unread),
|
||||
};
|
||||
Some((s.clone(), data))
|
||||
Some((s.clone(), data, read))
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
@@ -403,6 +419,18 @@ fn marked_id(doc: &Document, props: &Dict, op: &pdfcraft_content::Op, ids: &Hash
|
||||
(op.op == b"BDC").then(|| bdc_mcid(doc, props, op)).flatten().filter(|n| ids.contains(n))
|
||||
}
|
||||
|
||||
/// What [`artifact_marked_content`] did.
|
||||
#[derive(Debug, PartialEq)]
|
||||
enum Marked {
|
||||
/// The streams holding the content were rewritten.
|
||||
Done,
|
||||
/// None of the content is on the page, or with `require_all` not all of it: nothing changed.
|
||||
NotFound,
|
||||
/// Some of it is, or may be, in a stream damaged partway or one that doesn't decode, neither of
|
||||
/// which can be rewritten without losing what wasn't read, or after the damage: nothing changed.
|
||||
Damaged,
|
||||
}
|
||||
|
||||
/// Turn the tag's marked-content blocks into artifacts, rewriting only the streams that
|
||||
/// contain them. Other content streams, and unknown entries on a rewritten stream, stay.
|
||||
/// With `require_all`, every id in `ids` must appear on the page before any stream is rewritten.
|
||||
@@ -412,25 +440,45 @@ fn artifact_marked_content(
|
||||
streams: Vec<DecodedStream>,
|
||||
ids: &HashSet<i64>,
|
||||
require_all: bool,
|
||||
) -> Result<bool, pdfcraft_cos::CosError> {
|
||||
) -> Result<Marked, pdfcraft_cos::CosError> {
|
||||
let props = page_properties(doc, &page.dict);
|
||||
let decoded: Vec<&[u8]> = streams.iter().filter_map(|(_, s)| s.as_ref().map(|(_, bytes)| bytes.as_slice())).collect();
|
||||
// The pieces are the streams, in order.
|
||||
let decoded: Vec<&[u8]> = streams.iter().filter_map(|(_, s)| s.as_ref().map(|(_, bytes, _)| bytes.as_slice())).collect();
|
||||
let read: Vec<Read> = streams.iter().filter_map(|(_, s)| s.as_ref().map(|(_, _, read)| *read)).collect();
|
||||
let damage = read.iter().position(|r| *r == Read::Damaged);
|
||||
let pieces = pdfcraft_content::Pieces::join(&decoded);
|
||||
let mut found = HashSet::new();
|
||||
let mut edits = Vec::new();
|
||||
for op in pieces.parse().ops {
|
||||
if let Some(id) = marked_id(doc, &props, &op, ids) {
|
||||
// What follows the damage is unknown: a string or comment the damage left open runs
|
||||
// on into the next stream, so what reads as an operator after it may not be one. An
|
||||
// operator whose operands start before a stream not read whole and whose keyword comes
|
||||
// after it takes them from around what wasn't read: that stream may end them itself.
|
||||
let (first, last) = pieces.pieces_of(&op);
|
||||
if damage.is_some_and(|d| last > d) || read.get(first..last).is_some_and(|r| r.iter().any(|r| *r != Read::Whole)) {
|
||||
return Ok(Marked::Damaged);
|
||||
}
|
||||
found.insert(id);
|
||||
edits.push((op.span, b"/Artifact BMC".to_vec()));
|
||||
}
|
||||
}
|
||||
if if require_all { found != *ids } else { found.is_empty() } {
|
||||
return Ok(false);
|
||||
// Content not found may be past the damage, or in a stream that doesn't decode: whether it
|
||||
// is on the page isn't known.
|
||||
if found != *ids && read.iter().any(|r| *r != Read::Whole) {
|
||||
return Ok(Marked::Damaged);
|
||||
}
|
||||
let mut spliced = pieces.splice(edits).into_iter();
|
||||
if if require_all { found != *ids } else { found.is_empty() } {
|
||||
return Ok(Marked::NotFound);
|
||||
}
|
||||
let spliced = pieces.splice(edits);
|
||||
if read.iter().zip(&decoded).zip(&spliced).any(|((read, old), new)| *read != Read::Whole && *old != new.as_slice()) {
|
||||
return Ok(Marked::Damaged);
|
||||
}
|
||||
let mut spliced = spliced.into_iter();
|
||||
let mut next = Vec::with_capacity(streams.len());
|
||||
for (entry, stream) in streams {
|
||||
let Some((stream, old)) = stream else {
|
||||
let Some((stream, old, _)) = stream else {
|
||||
next.push(entry);
|
||||
continue;
|
||||
};
|
||||
@@ -456,7 +504,7 @@ fn artifact_marked_content(
|
||||
_ => Object::Array(next),
|
||||
};
|
||||
doc.update_dict(page.obj, |p| p.set(b"Contents".to_vec(), contents))?;
|
||||
Ok(true)
|
||||
Ok(Marked::Done)
|
||||
}
|
||||
|
||||
/// Decorative figure: its marked content on the page becomes an artifact, and the element
|
||||
@@ -468,11 +516,15 @@ pub fn mark_decorative(doc: &mut Document, obj: ObjRef) -> Result<(), AltError>
|
||||
let pg = d.get(b"Pg").and_then(Object::as_ref).or_else(|| elements(doc).into_iter().find(|e| e.object == obj).and_then(|e| e.page));
|
||||
if let Some(page) = pg.and_then(|p| pages.iter().find(|x| x.obj == p)).filter(|_| !ids.is_empty()) {
|
||||
let streams = decode_page_streams(doc, &page.dict).ok_or(AltError::TooLarge)?;
|
||||
// The parent tree no longer points those ids at the figure.
|
||||
if artifact_marked_content(doc, page, streams, &ids, false)?
|
||||
&& let Some(key) = page.dict.get(b"StructParents").and_then(Object::as_int)
|
||||
{
|
||||
clear_parent_tree(doc, key, obj)?;
|
||||
match artifact_marked_content(doc, page, streams, &ids, false)? {
|
||||
// The parent tree no longer points those ids at the figure.
|
||||
Marked::Done => {
|
||||
if let Some(key) = page.dict.get(b"StructParents").and_then(|o| doc.resolve(o).as_int()) {
|
||||
clear_parent_tree(doc, key, obj)?;
|
||||
}
|
||||
}
|
||||
Marked::NotFound => {}
|
||||
Marked::Damaged => return Err(AltError::Damaged),
|
||||
}
|
||||
}
|
||||
// Out of its parent's kids.
|
||||
@@ -513,10 +565,12 @@ pub fn mark_tag_artifact(doc: &mut Document, obj: ObjRef) -> Result<(), Artifact
|
||||
let parent = element.dict.get(b"P").and_then(Object::as_ref).ok_or(ArtifactError::NoParent)?;
|
||||
let replacement = replacement_kids(doc, parent, obj)?;
|
||||
let streams = decode_page_streams(doc, &page.dict).ok_or(ArtifactError::TooLarge)?;
|
||||
if !artifact_marked_content(doc, page, streams, &ids, true)? {
|
||||
return Err(ArtifactError::ContentNotFound);
|
||||
match artifact_marked_content(doc, page, streams, &ids, true)? {
|
||||
Marked::Done => {}
|
||||
Marked::NotFound => return Err(ArtifactError::ContentNotFound),
|
||||
Marked::Damaged => return Err(ArtifactError::Damaged),
|
||||
}
|
||||
if let Some(key) = page.dict.get(b"StructParents").and_then(Object::as_int) {
|
||||
if let Some(key) = page.dict.get(b"StructParents").and_then(|o| doc.resolve(o).as_int()) {
|
||||
clear_parent_tree(doc, key, obj).map_err(|e| ArtifactError::ParentTree(e.to_string()))?;
|
||||
}
|
||||
doc.update_dict(parent, |p| p.set(b"K".to_vec(), replacement))?;
|
||||
|
||||
+17
-11
@@ -4,7 +4,7 @@
|
||||
//! which can then be retagged with the existing tag-property tool after human review.
|
||||
|
||||
use pdfcraft_content::{Op, parse, serialize_ops};
|
||||
use pdfcraft_cos::{Dict, Document, ObjRef, Object, Stream};
|
||||
use pdfcraft_cos::{DecodeBudget, Dict, Document, ObjRef, Object, Stream};
|
||||
|
||||
const MAX_PAGES: usize = 1_000;
|
||||
const MAX_PAGE_BYTES: usize = 16 * 1024 * 1024;
|
||||
@@ -57,18 +57,24 @@ fn content_bytes(doc: &Document, page: &pdfcraft_model::Page, index: usize) -> R
|
||||
let Object::Stream(stream) = &*value else { return Err(unsupported(index, "contents include a non-stream object")) };
|
||||
let remaining = MAX_PAGE_BYTES.saturating_sub(all.len().saturating_add(1));
|
||||
if remaining == 0 {
|
||||
return Err(unsupported(index, "decoded content exceeds 16 MiB"));
|
||||
return Err(unsupported(index, "decoding the content takes more than 16 MiB"));
|
||||
}
|
||||
let chain = stream.filters();
|
||||
let decoded = if chain.is_empty() {
|
||||
if stream.raw.len() > remaining {
|
||||
return Err(unsupported(index, "decoded content exceeds 16 MiB"));
|
||||
// Strictly, and with `/DecodeParms` given by reference: the content is written back from it.
|
||||
let mut budget = DecodeBudget::new(remaining, 0);
|
||||
let decoded = budget.decode_strict(doc, stream).map_err(|e| {
|
||||
// The allowance counts what every filter stage decodes, as a page's does.
|
||||
if budget.remaining() == 0 {
|
||||
unsupported(index, "decoding the content takes more than 16 MiB")
|
||||
} else {
|
||||
// The decoder's own reason: `CosError::Filter`'s text would say again that the data
|
||||
// couldn't be decoded.
|
||||
let why = match e {
|
||||
pdfcraft_cos::CosError::Filter(why) => why,
|
||||
other => other.to_string(),
|
||||
};
|
||||
unsupported(index, format!("content cannot be decoded strictly: {why}"))
|
||||
}
|
||||
stream.raw.to_vec()
|
||||
} else {
|
||||
pdfcraft_filters::decode(&chain, &stream.raw, remaining)
|
||||
.map_err(|e| unsupported(index, format!("content cannot be decoded strictly: {e}")))?
|
||||
};
|
||||
})?;
|
||||
all.extend_from_slice(&decoded);
|
||||
all.push(b' ');
|
||||
}
|
||||
|
||||
@@ -79,6 +79,68 @@ fn autotag_text_writes_marked_content_and_parent_tree_across_pages() {
|
||||
assert_eq!(status(&check(&reopened, &Options::default()), Rule::TaggedContent), Status::Passed);
|
||||
}
|
||||
|
||||
/// Page content behind a predictor whose `/DecodeParms` are given by reference is read through
|
||||
/// them: autotagging writes the text back as it was, marked, not with the predictor's tag bytes in
|
||||
/// it (a `\0` every eight bytes, which split `24` into `2 4`).
|
||||
#[test]
|
||||
fn autotag_text_reads_content_with_parameters_given_by_reference() {
|
||||
use pdfcraft_cos::{Dict, ObjRef};
|
||||
let mut content = b"BT /F1 24 Tf 72 700 Td (Hello World) Tj ET".to_vec();
|
||||
content.resize(content.len().div_ceil(8) * 8, b' ');
|
||||
// PNG rows of eight bytes, each tagged 0 (no prediction).
|
||||
let rows: Vec<u8> = content.chunks(8).flat_map(|row| std::iter::once(0).chain(row.iter().copied())).collect();
|
||||
let mut doc = pdf(
|
||||
&[
|
||||
"<< /Type /Catalog /Pages 2 0 R >>".into(),
|
||||
"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".into(),
|
||||
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 600 800] /Contents 4 0 R /Resources << /Font << /F1 5 0 R >> >> >>".into(),
|
||||
stream(""),
|
||||
FONT.into(),
|
||||
],
|
||||
"",
|
||||
);
|
||||
let parms: Dict = [(b"Predictor".to_vec(), Object::Int(12)), (b"Columns".to_vec(), Object::Int(8))].into_iter().collect();
|
||||
let parms = doc.add(Object::Dict(parms));
|
||||
let mut predicted = pdfcraft_cos::Stream::flate(Dict::new(), &rows);
|
||||
predicted.dict.set(b"DecodeParms".to_vec(), Object::Ref(parms));
|
||||
doc.set(ObjRef::new(4, 0), predicted);
|
||||
assert_eq!(autotag_text(&mut doc).unwrap(), AutoTagResult { pages: 1, paragraphs: 1 });
|
||||
let page = &pdfcraft_model::pages(&doc)[0];
|
||||
let written = doc.resolve(page.dict.get(b"Contents").unwrap());
|
||||
let Object::Stream(written) = &*written else { panic!("page content") };
|
||||
let text = String::from_utf8_lossy(&written.decoded_strict().unwrap()).into_owned();
|
||||
assert!(text.contains("/F1 24 Tf") && text.contains("(Hello World) Tj"), "{text}");
|
||||
}
|
||||
|
||||
/// Autotagging refuses a page whose content it can't read whole, and says why: content past
|
||||
/// 16 MiB, or content that doesn't decode strictly, with the decoder's reason right after.
|
||||
#[test]
|
||||
fn autotag_text_says_why_it_cannot_read_a_page() {
|
||||
use pdfcraft_cos::{Dict, ObjRef, Stream};
|
||||
let reason = |content: Stream| {
|
||||
let mut doc = pdf(
|
||||
&[
|
||||
"<< /Type /Catalog /Pages 2 0 R >>".into(),
|
||||
"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".into(),
|
||||
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 600 800] /Contents 4 0 R /Resources << /Font << /F1 5 0 R >> >> >>".into(),
|
||||
stream(""),
|
||||
FONT.into(),
|
||||
],
|
||||
"",
|
||||
);
|
||||
doc.set(ObjRef::new(4, 0), content);
|
||||
match autotag_text(&mut doc) {
|
||||
Err(AutoTagError::Unsupported { reason, .. }) => reason,
|
||||
other => panic!("{other:?}"),
|
||||
}
|
||||
};
|
||||
assert_eq!(reason(Stream::from_raw(Dict::new(), vec![b' '; 17 << 20])), "decoding the content takes more than 16 MiB");
|
||||
let mut corrupt = Stream::from_raw(Dict::new(), b"not zlib data".to_vec());
|
||||
corrupt.dict.set(b"Filter".to_vec(), Object::name("FlateDecode"));
|
||||
let why = reason(corrupt);
|
||||
assert!(why.starts_with("content cannot be decoded strictly: FlateDecode: "), "{why}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn autotag_text_refuses_paint_and_does_not_modify_the_document() {
|
||||
let mut doc = pdf(
|
||||
@@ -1087,6 +1149,185 @@ fn mark_tag_artifact_validates_parent_and_all_mcids_before_mutating_document() {
|
||||
assert_eq!(*absent.get(ObjRef::new(9, 0)), before_pt);
|
||||
}
|
||||
|
||||
/// zlib data that reads as `readable` and is then damaged, with more of the stream after the
|
||||
/// damage: a stored block, then a block of the reserved type (RFC 1951 §3.2.3), then `rest`.
|
||||
fn damaged_flate(readable: &[u8], rest: &[u8]) -> pdfcraft_cos::Stream {
|
||||
let len = u16::try_from(readable.len()).unwrap();
|
||||
let mut raw = vec![0x78, 0x01, 0x00];
|
||||
raw.extend_from_slice(&len.to_le_bytes());
|
||||
raw.extend_from_slice(&(!len).to_le_bytes());
|
||||
raw.extend_from_slice(readable);
|
||||
raw.push(0x07);
|
||||
raw.extend_from_slice(rest);
|
||||
let mut dict = pdfcraft_cos::Dict::new();
|
||||
dict.set(b"Filter".to_vec(), pdfcraft_cos::Object::name("FlateDecode"));
|
||||
pdfcraft_cos::Stream::from_raw(dict, raw)
|
||||
}
|
||||
|
||||
/// A tag's content in a stream damaged partway stays tagged: rewriting the stream from what
|
||||
/// decoded would lose what follows the damage. Nothing changes, the structure tree and the stream
|
||||
/// included. Content in a whole stream before a damaged one is marked, and the damaged one kept
|
||||
/// as stored.
|
||||
#[test]
|
||||
fn a_tags_content_in_a_stream_damaged_partway_is_not_rewritten() {
|
||||
use pdfcraft_cos::{ObjRef, Object};
|
||||
let content = b"/Figure << /MCID 0 >> BDC q 40 0 0 20 10 150 cm /Im Do Q EMC /Photo << /MCID 1 >> BDC 100 100 50 30 re f EMC\n";
|
||||
let damaged = damaged_flate(content, b"0 0 1 rg 0 0 10 10 re f");
|
||||
let mut doc = figures_doc();
|
||||
doc.set(ObjRef::new(4, 0), damaged.clone());
|
||||
let contents = |doc: &Document| doc.get(ObjRef::new(3, 0)).as_dict().unwrap().get(b"Contents").cloned();
|
||||
let state = |doc: &Document| (contents(doc), doc.get(ObjRef::new(9, 0)), doc.get(ObjRef::new(6, 0)), doc.get(ObjRef::new(4, 0)));
|
||||
let before = state(&doc);
|
||||
assert_eq!(figures(&doc).len(), 2, "read up to the damage");
|
||||
assert_eq!(mark_tag_artifact(&mut doc, ObjRef::new(7, 0)), Err(ArtifactError::Damaged));
|
||||
assert_eq!(mark_decorative(&mut doc, ObjRef::new(7, 0)), Err(AltError::Damaged));
|
||||
assert_eq!(state(&doc), before);
|
||||
|
||||
let mut doc = figures_doc();
|
||||
let other = doc.add(damaged_flate(b"0 g\n", b"0 0 1 rg 0 0 10 10 re f"));
|
||||
doc.update_dict(ObjRef::new(3, 0), |p| p.set(b"Contents".to_vec(), Object::Array(vec![Object::Ref(ObjRef::new(4, 0)), Object::Ref(other)])))
|
||||
.unwrap();
|
||||
mark_tag_artifact(&mut doc, ObjRef::new(7, 0)).unwrap();
|
||||
let Some(Object::Array(list)) = contents(&doc) else { panic!("contents {:?}", contents(&doc)) };
|
||||
assert_ne!(list.first(), Some(&Object::Ref(ObjRef::new(4, 0))), "the tag's stream is rewritten");
|
||||
assert_eq!(list.get(1), Some(&Object::Ref(other)), "kept as stored");
|
||||
}
|
||||
|
||||
/// What follows the damage is unknown, the syntax the next stream starts in too, so a tag's
|
||||
/// content in a stream after a damaged one stays tagged. Here a comment the damage leaves open
|
||||
/// runs on into the next stream, up to its first end of line, and a string starting there reads
|
||||
/// as operators, among them what looks like the figure's content: rewritten, it would change the
|
||||
/// string. Nothing changes, the structure tree included.
|
||||
#[test]
|
||||
fn a_tags_content_after_a_damaged_stream_is_not_rewritten() {
|
||||
use pdfcraft_cos::{Dict, ObjRef, Object, Stream};
|
||||
let in_a_string = b"(a note\n/Figure << /MCID 0 >> BDC 0 g EMC\n) pop /Photo << /MCID 1 >> BDC 100 100 50 30 re f EMC";
|
||||
for (damaged, after) in [(b"0 g\n".as_slice(), None), (b"0 g % a comment".as_slice(), Some(in_a_string.as_slice()))] {
|
||||
let mut doc = figures_doc();
|
||||
if let Some(after) = after {
|
||||
doc.set(ObjRef::new(4, 0), Stream::from_raw(Dict::new(), after.to_vec()));
|
||||
}
|
||||
let first = doc.add(damaged_flate(damaged, b"\n0 0 1 rg 0 0 10 10 re f"));
|
||||
doc.update_dict(ObjRef::new(3, 0), |p| p.set(b"Contents".to_vec(), Object::Array(vec![Object::Ref(first), Object::Ref(ObjRef::new(4, 0))])))
|
||||
.unwrap();
|
||||
let state = |doc: &Document| {
|
||||
(doc.get(ObjRef::new(3, 0)).as_dict().unwrap().get(b"Contents").cloned(), doc.get(ObjRef::new(9, 0)), doc.get(ObjRef::new(6, 0)))
|
||||
};
|
||||
let before = state(&doc);
|
||||
assert_eq!(mark_tag_artifact(&mut doc, ObjRef::new(7, 0)), Err(ArtifactError::Damaged), "{damaged:?}");
|
||||
assert_eq!(mark_decorative(&mut doc, ObjRef::new(7, 0)), Err(AltError::Damaged), "{damaged:?}");
|
||||
assert_eq!(state(&doc), before, "{damaged:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A page may split its content between an operator's operands and its keyword. When the operands
|
||||
/// of the figure's `BDC` end the stream before one damaged from its start or one that doesn't
|
||||
/// decode, the `BDC` the page reads is in what wasn't read: joined without it, those operands and
|
||||
/// the next tag's read as one `BDC`, which reaches into the stream after it. Neither marking
|
||||
/// changes anything, the structure tree included.
|
||||
#[test]
|
||||
fn a_tags_operands_before_a_stream_not_read_whole_are_not_rewritten() {
|
||||
use pdfcraft_cos::{Dict, ObjRef, Object, Stream};
|
||||
let rest = b" BDC q 40 0 0 20 10 150 cm /Im Do Q EMC";
|
||||
for damaged in [true, false] {
|
||||
let mut doc = figures_doc();
|
||||
doc.set(ObjRef::new(4, 0), Stream::from_raw(Dict::new(), b"/Figure << /MCID 0 >>".to_vec()));
|
||||
let hidden = if damaged {
|
||||
damaged_flate(b"", rest)
|
||||
} else {
|
||||
let filter = doc.add(Object::name("FlateDecode"));
|
||||
let mut s = Stream::flate(Dict::new(), rest);
|
||||
s.dict.set(b"Filter".to_vec(), Object::Ref(filter));
|
||||
s
|
||||
};
|
||||
let hidden = doc.add(hidden);
|
||||
let after = doc.add(Object::Stream(Stream::from_raw(Dict::new(), b"/Photo << /MCID 1 >> BDC 100 100 50 30 re f EMC".to_vec())));
|
||||
let listed = Object::Array(vec![Object::Ref(ObjRef::new(4, 0)), Object::Ref(hidden), Object::Ref(after)]);
|
||||
doc.update_dict(ObjRef::new(3, 0), |p| p.set(b"Contents".to_vec(), listed)).unwrap();
|
||||
let state = |doc: &Document| {
|
||||
(doc.get(ObjRef::new(3, 0)).as_dict().unwrap().get(b"Contents").cloned(), doc.get(ObjRef::new(9, 0)), doc.get(ObjRef::new(6, 0)))
|
||||
};
|
||||
let before = state(&doc);
|
||||
assert_eq!(mark_tag_artifact(&mut doc, ObjRef::new(7, 0)), Err(ArtifactError::Damaged), "damaged: {damaged}");
|
||||
assert_eq!(mark_decorative(&mut doc, ObjRef::new(7, 0)), Err(AltError::Damaged), "damaged: {damaged}");
|
||||
assert_eq!(state(&doc), before, "damaged: {damaged}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A tag's content not found on the page may be in a stream that doesn't decode: it isn't known
|
||||
/// to be off the page, so neither marking changes anything, the structure tree included.
|
||||
#[test]
|
||||
fn a_tags_content_not_found_beside_a_stream_that_does_not_decode_is_not_taken_for_absent() {
|
||||
use pdfcraft_cos::{Dict, ObjRef, Object, Stream};
|
||||
let mut doc = figures_doc();
|
||||
doc.update_dict(ObjRef::new(7, 0), |d| d.set(b"K".to_vec(), Object::Int(2))).unwrap();
|
||||
let mut dict = Dict::new();
|
||||
dict.set(b"Filter".to_vec(), Object::name("NoSuchFilter"));
|
||||
let other = doc.add(Object::Stream(Stream::from_raw(dict, b"/Figure << /MCID 2 >> BDC 0 g EMC".to_vec())));
|
||||
doc.update_dict(ObjRef::new(3, 0), |p| p.set(b"Contents".to_vec(), Object::Array(vec![Object::Ref(other), Object::Ref(ObjRef::new(4, 0))])))
|
||||
.unwrap();
|
||||
let state = |doc: &Document| {
|
||||
(doc.get(ObjRef::new(3, 0)).as_dict().unwrap().get(b"Contents").cloned(), doc.get(ObjRef::new(9, 0)), doc.get(ObjRef::new(6, 0)))
|
||||
};
|
||||
let before = state(&doc);
|
||||
assert_eq!(mark_decorative(&mut doc, ObjRef::new(7, 0)), Err(AltError::Damaged));
|
||||
assert_eq!(mark_tag_artifact(&mut doc, ObjRef::new(7, 0)), Err(ArtifactError::Damaged));
|
||||
assert_eq!(state(&doc), before);
|
||||
}
|
||||
|
||||
/// A tag's content not found before the damage in a damaged stream may be past it: it isn't known
|
||||
/// to be off the page, so neither marking changes anything.
|
||||
#[test]
|
||||
fn a_tags_content_past_the_damage_is_not_taken_for_absent() {
|
||||
use pdfcraft_cos::ObjRef;
|
||||
let damaged =
|
||||
damaged_flate(b"/Photo << /MCID 1 >> BDC 100 100 50 30 re f EMC\n", b"/Figure << /MCID 0 >> BDC q 40 0 0 20 10 150 cm /Im Do Q EMC");
|
||||
let mut doc = figures_doc();
|
||||
doc.set(ObjRef::new(4, 0), damaged);
|
||||
let contents = |doc: &Document| doc.get(ObjRef::new(3, 0)).as_dict().unwrap().get(b"Contents").cloned();
|
||||
let before = (contents(&doc), doc.get(ObjRef::new(9, 0)), doc.get(ObjRef::new(6, 0)));
|
||||
assert_eq!(mark_decorative(&mut doc, ObjRef::new(7, 0)), Err(AltError::Damaged));
|
||||
assert_eq!(mark_tag_artifact(&mut doc, ObjRef::new(7, 0)), Err(ArtifactError::Damaged));
|
||||
assert_eq!((contents(&doc), doc.get(ObjRef::new(9, 0)), doc.get(ObjRef::new(6, 0))), before);
|
||||
}
|
||||
|
||||
/// A page's `/StructParents` given by reference is read through it: the parent tree no longer
|
||||
/// points the marked content at the tag.
|
||||
#[test]
|
||||
fn struct_parents_given_by_reference_are_read() {
|
||||
use pdfcraft_cos::{ObjRef, Object};
|
||||
let by_reference = || {
|
||||
let mut doc = figures_doc();
|
||||
let key = doc.add(Object::Int(0));
|
||||
doc.update_dict(ObjRef::new(3, 0), |p| p.set(b"StructParents".to_vec(), Object::Ref(key))).unwrap();
|
||||
doc
|
||||
};
|
||||
let nums = |doc: &Document| doc.get(ObjRef::new(9, 0)).as_dict().and_then(|d| d.get(b"Nums").cloned());
|
||||
let mut doc = by_reference();
|
||||
mark_decorative(&mut doc, ObjRef::new(7, 0)).unwrap();
|
||||
assert_eq!(nums(&doc), Some(Object::Array(vec![Object::Int(0), Object::Array(vec![Object::Null, Object::Ref(ObjRef::new(8, 0))])])));
|
||||
let mut doc = by_reference();
|
||||
mark_tag_artifact(&mut doc, ObjRef::new(8, 0)).unwrap();
|
||||
assert_eq!(nums(&doc), Some(Object::Array(vec![Object::Int(0), Object::Array(vec![Object::Ref(ObjRef::new(7, 0)), Object::Null])])));
|
||||
}
|
||||
|
||||
/// A content stream that doesn't decode at all is kept as stored, and a tag in the page's other
|
||||
/// streams is still marked: only running past the decode budget refuses.
|
||||
#[test]
|
||||
fn a_tag_beside_a_stream_that_does_not_decode_is_marked() {
|
||||
use pdfcraft_cos::{Dict, ObjRef, Object, Stream};
|
||||
let mut doc = figures_doc();
|
||||
let mut dict = Dict::new();
|
||||
dict.set(b"Filter".to_vec(), Object::name("NoSuchFilter"));
|
||||
let other = doc.add(Object::Stream(Stream::from_raw(dict, b"0 g".to_vec())));
|
||||
doc.update_dict(ObjRef::new(3, 0), |p| p.set(b"Contents".to_vec(), Object::Array(vec![Object::Ref(other), Object::Ref(ObjRef::new(4, 0))])))
|
||||
.unwrap();
|
||||
mark_tag_artifact(&mut doc, ObjRef::new(7, 0)).unwrap();
|
||||
let contents = doc.get(ObjRef::new(3, 0)).as_dict().unwrap().get(b"Contents").cloned();
|
||||
let Some(Object::Array(list)) = contents else { panic!("contents {contents:?}") };
|
||||
assert_eq!(list.first(), Some(&Object::Ref(other)), "kept as stored");
|
||||
}
|
||||
|
||||
fn ref_(n: u32) -> Option<pdfcraft_cos::ObjRef> {
|
||||
Some(pdfcraft_cos::ObjRef::new(n, 0))
|
||||
}
|
||||
|
||||
@@ -283,7 +283,7 @@ impl<'a> Walker<'a> {
|
||||
return Err(AuditError::TooManyForms);
|
||||
}
|
||||
// A form stream that cannot be decoded fails the audit: it might hide a cover.
|
||||
let data = self.budget.decode_strict(stream)?;
|
||||
let data = self.budget.decode_strict(self.doc, stream)?;
|
||||
// The XObject matrix maps form space into the user space active at `Do`.
|
||||
let mut sub_gs = gs.clone();
|
||||
sub_gs.ctm = matrix.then(&gs.ctm);
|
||||
@@ -326,7 +326,7 @@ pub fn filled_rects(doc: &Document, page: &Dict) -> Result<Vec<FilledRect>, Audi
|
||||
let mut streams = Vec::with_capacity(contents.len());
|
||||
for c in &contents {
|
||||
if let Object::Stream(s) = &*doc.resolve(c) {
|
||||
streams.push(budget.decode_strict(s)?);
|
||||
streams.push(budget.decode_strict(doc, s)?);
|
||||
}
|
||||
}
|
||||
let pieces = Pieces::join(&streams);
|
||||
|
||||
@@ -26,6 +26,11 @@ 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.
|
||||
|
||||
`page_add_text` and `content_update` take one of `color` (`#RRGGBB` or a name, painted in
|
||||
DeviceRGB), `gray` (0 black to 1 white, DeviceGray `g`) and `cmyk` (`[c, m, y, k]`, each 0 to 1,
|
||||
DeviceCMYK `k`), so text added to a print file can be 100 K black. `content_list` reports `gray` or
|
||||
`cmyk` for such text.
|
||||
|
||||
`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
|
||||
|
||||
@@ -185,6 +185,7 @@ impl Automation {
|
||||
let recipe = Recipe::parse(self, args)?;
|
||||
let recursive = args.opt_bool("recursive")?.unwrap_or(false);
|
||||
let stop = args.opt_bool("stop_on_error")?.unwrap_or(false);
|
||||
let dry_run = args.opt_bool("dry_run")?.unwrap_or(false);
|
||||
let paths = args.strs("paths")?;
|
||||
if paths.is_empty() || paths.len() > 1000 {
|
||||
return Err(Args::wrong("paths", "1 to 1000 files or folders"));
|
||||
@@ -211,11 +212,41 @@ impl Automation {
|
||||
let mut files = discovery.skipped;
|
||||
let (mut completed, mut failed_count) = (0, 0);
|
||||
let mut stopped = false;
|
||||
let mut planned_outputs: HashSet<PathBuf> = HashSet::new();
|
||||
for (path, relative) in discovery.files {
|
||||
if stopped || !recipe.accepts(&path) {
|
||||
files.push(json!({"path":path.to_string_lossy(),"status":"skipped","reason":if stopped {"stopped after error"} else {"unsupported input extension"}}));
|
||||
continue;
|
||||
}
|
||||
if dry_run {
|
||||
let planned: Result<PathBuf> = (|| {
|
||||
let target = out.join(&relative).with_extension("pdf");
|
||||
let target = self.resolve(target.to_str().ok_or_else(|| failed("output path is not UTF-8"))?, true)?;
|
||||
if !target.starts_with(&out) {
|
||||
return Err(failed("output path leaves out_dir"));
|
||||
}
|
||||
let dir = target.parent().ok_or_else(|| failed("output has no parent"))?;
|
||||
let stem = target.file_stem().ok_or_else(|| failed("output has no stem"))?.to_string_lossy().into_owned();
|
||||
for n in 1..=10_000 {
|
||||
let candidate = if n == 1 { target.clone() } else { dir.join(format!("{stem} ({n}).pdf")) };
|
||||
if candidate.symlink_metadata().is_ok() || planned_outputs.contains(&candidate) {
|
||||
continue;
|
||||
}
|
||||
planned_outputs.insert(candidate.clone());
|
||||
return Ok(candidate);
|
||||
}
|
||||
Err(failed("all 10000 output names are occupied"))
|
||||
})();
|
||||
match planned {
|
||||
Ok(target) => files.push(json!({"path":path.to_string_lossy(),"status":"planned","output":target.to_string_lossy().replace('\\', "/"),"steps":recipe.steps})),
|
||||
Err(e) => {
|
||||
failed_count += 1;
|
||||
files.push(json!({"path":path.to_string_lossy(),"status":"error","error":e.to_string()}));
|
||||
stopped = stop;
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
// Recheck confinement and links before reading a discovered file.
|
||||
let result: Result<_> = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
|
||||
let current = self.resolve(path.to_str().ok_or_else(|| failed("input path is not UTF-8"))?, false)?;
|
||||
@@ -244,8 +275,8 @@ impl Automation {
|
||||
}
|
||||
}
|
||||
}
|
||||
let skipped = files.len().saturating_sub(completed + failed_count);
|
||||
Ok(json!({"completed":completed,"failed":failed_count,"skipped":skipped,"stopped":stopped,"files":files}))
|
||||
let skipped = files.iter().filter(|file| file["status"] == "skipped").count();
|
||||
Ok(json!({"dry_run":dry_run,"completed":completed,"failed":failed_count,"skipped":skipped,"stopped":stopped,"files":files}))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -279,4 +310,20 @@ mod tests {
|
||||
discovery.visited = 0;
|
||||
assert!(discovery.walk(Path::new("absent"), Path::new(""), Path::new("output"), true, MAX_DEPTH + 1).unwrap_err().to_string().contains("64"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn doc_batch_dry_run_lists_outputs_without_writing() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
std::fs::create_dir(dir.path().join("input")).unwrap();
|
||||
let pdf = Session::new().create_from_text("Doc", "Hello").unwrap();
|
||||
std::fs::write(dir.path().join("input/a.pdf"), &*pdf).unwrap();
|
||||
let auto = Automation::new().with_root(dir.path()).unwrap();
|
||||
let report = auto.doc_batch(&Args(&json!({"paths":["input"],"steps":["optimize"],"out_dir":"out","dry_run":true}))).unwrap();
|
||||
assert_eq!(report["dry_run"], true, "{report}");
|
||||
assert_eq!(report["completed"], 0, "{report}");
|
||||
assert_eq!(report["failed"], 0, "{report}");
|
||||
assert_eq!(report["files"][0]["status"], "planned", "{report}");
|
||||
assert!(report["files"][0]["output"].as_str().unwrap().ends_with("out/a.pdf"), "{report}");
|
||||
assert!(!dir.path().join("out").exists());
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
//! move/resize/retype/restyle it, delete it. Geometry is in points from the top-left of the
|
||||
//! displayed page (y down), like every other tool.
|
||||
|
||||
use pdfcraft_engine::{ADDED_CHAR_SPACING_LIMIT, AddedContent, AddedText, Edit, FontFamily, TextAlign};
|
||||
use pdfcraft_engine::{ADDED_CHAR_SPACING_LIMIT, AddedContent, AddedText, Edit, FontFamily, TextAlign, TextInk};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::comments::parse_color;
|
||||
@@ -30,6 +30,27 @@ fn rect_arg(a: &Args, key: &str) -> Result<Option<[f64; 4]>> {
|
||||
.transpose()
|
||||
}
|
||||
|
||||
const INK_ARGS: &str = "give one of color (#RRGGBB or a name), gray (0 black to 1 white) and cmyk ([c, m, y, k], each 0 to 1)";
|
||||
|
||||
/// `gray` or `cmyk`: the text painted in DeviceGray or DeviceCMYK rather than RGB. At most one of
|
||||
/// them and `color`.
|
||||
fn ink_arg(a: &Args) -> Result<Option<TextInk>> {
|
||||
if ["color", "gray", "cmyk"].iter().filter(|k| a.get(k).is_some()).count() > 1 {
|
||||
return Err(bad(INK_ARGS));
|
||||
}
|
||||
let unit = |v: Option<f64>, key: &str| v.filter(|v| (0.0..=1.0).contains(v)).ok_or_else(|| bad(format!("{key} takes numbers from 0 to 1")));
|
||||
if let Some(g) = a.get("gray") {
|
||||
return Ok(Some(TextInk::Gray(unit(g.as_f64(), "gray")?)));
|
||||
}
|
||||
let Some(c) = a.get("cmyk") else { return Ok(None) };
|
||||
let parts = c.as_array().filter(|p| p.len() == 4).ok_or_else(|| bad("cmyk must be [c, m, y, k]"))?;
|
||||
let mut cmyk = [0.0; 4];
|
||||
for (out, v) in cmyk.iter_mut().zip(parts) {
|
||||
*out = unit(v.as_f64(), "cmyk")?;
|
||||
}
|
||||
Ok(Some(TextInk::Cmyk(cmyk)))
|
||||
}
|
||||
|
||||
/// Apply the style arguments to `t`.
|
||||
fn style(a: &Args, t: &mut AddedText) -> Result<()> {
|
||||
if let Some(s) = a.opt_num("size")? {
|
||||
@@ -49,8 +70,12 @@ fn style(a: &Args, t: &mut AddedText) -> Result<()> {
|
||||
if let Some(i) = a.opt_bool("italic")? {
|
||||
t.italic = i;
|
||||
}
|
||||
if let Some(c) = a.opt_str("color")? {
|
||||
t.color = parse_color(c)?;
|
||||
if let Some(ink) = ink_arg(a)? {
|
||||
t.set_ink(Some(ink));
|
||||
} else if let Some(c) = a.opt_str("color")? {
|
||||
// An RGB colour paints in RGB, even one that is the ink's look.
|
||||
t.set_ink(None);
|
||||
t.set_color(parse_color(c)?);
|
||||
}
|
||||
if let Some(al) = a.opt_str("align")? {
|
||||
t.align = parse_align(al)?;
|
||||
@@ -124,6 +149,12 @@ impl Automation {
|
||||
v["bold"] = json!(t.bold);
|
||||
v["italic"] = json!(t.italic);
|
||||
v["char_spacing"] = json!(t.char_spacing);
|
||||
// Text painted in a print colour space says so; RGB text has neither.
|
||||
match t.painted_ink() {
|
||||
Some(TextInk::Gray(g)) => v["gray"] = json!(g),
|
||||
Some(TextInk::Cmyk(c)) => v["cmyk"] = json!(c),
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
AddedContent::Image(_) => v["type"] = json!("image"),
|
||||
}
|
||||
@@ -205,8 +236,8 @@ impl Automation {
|
||||
if a.get("text").is_some() {
|
||||
return Err(bad("images have no text"));
|
||||
}
|
||||
if ["font", "size", "bold", "italic", "color", "align", "aligns", "char_spacing"].iter().any(|k| a.get(k).is_some()) {
|
||||
return Err(bad("font, size, bold, italic, color, align, aligns and char_spacing apply to text"));
|
||||
if ["font", "size", "bold", "italic", "color", "gray", "cmyk", "align", "aligns", "char_spacing"].iter().any(|k| a.get(k).is_some()) {
|
||||
return Err(bad("font, size, bold, italic, color, gray, cmyk, align, aligns and char_spacing apply to text"));
|
||||
}
|
||||
if let Some(deg) = a.opt_int("rotate")? {
|
||||
if deg.rem_euclid(90) != 0 {
|
||||
|
||||
@@ -467,6 +467,7 @@ impl Automation {
|
||||
"bring_forward" => ImageEdit::Arrange(pdfcraft_engine::ArrangeOrder::BringForward),
|
||||
"send_backward" => ImageEdit::Arrange(pdfcraft_engine::ArrangeOrder::SendBackward),
|
||||
"remove_crop" => ImageEdit::RemoveCrop,
|
||||
"ungroup" => ImageEdit::Ungroup,
|
||||
"replace" => {
|
||||
let path = self.resolve(a.str("path")?, false)?;
|
||||
let bytes = read_input(&path)?;
|
||||
|
||||
@@ -6,6 +6,10 @@ use super::{Arc, Automation, BlockKey, DocId, Document, Edit, Path, PathBuf, Tex
|
||||
/// How far a watermark may be moved from the page centre, in points (a page is at most 14,400).
|
||||
const WATERMARK_MAX_OFFSET: f64 = 20_000.0;
|
||||
|
||||
/// `doc_optimize` with `target_bytes`: (max target ppi, max JPEG quality) per extra attempt, mildest first.
|
||||
/// The quality applies only to images the caller left on JPEG; zip and retain keep their encoding.
|
||||
const TARGET_LADDER: [(f64, u8); 5] = [(110.0, 45), (96.0, 35), (72.0, 28), (54.0, 20), (36.0, 12)];
|
||||
|
||||
/// Bookmarks in one page of the bookmark list, by default and at most.
|
||||
const BOOKMARK_PAGE: usize = 100;
|
||||
|
||||
@@ -380,7 +384,45 @@ impl Automation {
|
||||
})
|
||||
.collect::<Result<_>>()?,
|
||||
};
|
||||
let (bytes, r) = self.session.optimized_bytes(id, &settings, &discard).map_err(failed)?;
|
||||
let target = match a.opt_int("target_bytes")? {
|
||||
None => None,
|
||||
Some(t) if t >= 1 => Some(usize::try_from(t).map_err(|_| ToolError::InvalidArgs(format!("target_bytes {t} is too large")))?),
|
||||
Some(t) => return Err(ToolError::InvalidArgs(format!("target_bytes must be at least 1, not {t}"))),
|
||||
};
|
||||
let (mut bytes, mut r) = self.session.optimized_bytes(id, &settings, &discard).map_err(failed)?;
|
||||
let mut attempts = 1;
|
||||
let mut step_used = 0;
|
||||
// Settings already optimized with; a rung that changes nothing is not run again.
|
||||
let mut tried = vec![settings.clone()];
|
||||
if let Some(t) = target {
|
||||
// Stronger image settings, one rung per attempt, until the copy fits. Every attempt
|
||||
// starts from the open document, so a failed one changes nothing; the number of
|
||||
// attempts is fixed. The smallest copy is kept if none fits.
|
||||
for (k, &(ppi, quality)) in TARGET_LADDER.iter().enumerate() {
|
||||
if bytes.len() <= t {
|
||||
break;
|
||||
}
|
||||
let mut s = settings.clone();
|
||||
for img in [&mut s.color, &mut s.gray] {
|
||||
img.downsample = true;
|
||||
img.target_ppi = img.target_ppi.min(ppi);
|
||||
img.above_ppi = img.above_ppi.min(ppi * 1.5).max(img.target_ppi);
|
||||
// Only a caller who chose JPEG gets a lower quality; zip and retain stay as asked.
|
||||
if let Compression::Jpeg(q) = img.compression {
|
||||
img.compression = Compression::Jpeg(q.min(quality));
|
||||
}
|
||||
}
|
||||
if tried.contains(&s) {
|
||||
continue;
|
||||
}
|
||||
let (b2, r2) = self.session.optimized_bytes(id, &s, &discard).map_err(failed)?;
|
||||
tried.push(s);
|
||||
attempts += 1;
|
||||
if b2.len() < bytes.len() {
|
||||
(bytes, r, step_used) = (b2, r2, k + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
write_atomic(&path, &bytes)?;
|
||||
fn valid_version(v: &[u8]) -> Option<&str> {
|
||||
if matches!(v, [b'1'..=b'9', b'.', b'0'..=b'9']) { std::str::from_utf8(v).ok() } else { None }
|
||||
@@ -400,7 +442,19 @@ impl Automation {
|
||||
// entry). Both are "d.d", so text order is version order.
|
||||
let pdf_version = catalog_version.as_deref().into_iter().chain(header_version).max();
|
||||
let o = &r.optimize;
|
||||
Ok(json!({
|
||||
let mut extra = json!({});
|
||||
if let Some(t) = target {
|
||||
let (ppi, quality) = step_used.checked_sub(1).and_then(|k| TARGET_LADDER.get(k)).copied().unzip();
|
||||
let lossy = matches!(settings.color.compression, Compression::Jpeg(_)) || matches!(settings.gray.compression, Compression::Jpeg(_));
|
||||
let quality = quality.filter(|_| lossy);
|
||||
extra = json!({
|
||||
"target_bytes": t,
|
||||
"target_reached": bytes.len() <= t,
|
||||
"attempts": attempts,
|
||||
"target_settings": { "step": step_used, "max_ppi": ppi, "max_jpeg_quality": quality },
|
||||
});
|
||||
}
|
||||
let mut out = json!({
|
||||
"path": path.to_string_lossy(),
|
||||
"pdf_version": pdf_version,
|
||||
"object_streams": settings.effective_object_streams(),
|
||||
@@ -425,7 +479,11 @@ impl Automation {
|
||||
"unused_xobjects": o.unused_xobjects,
|
||||
"merged_objects": r.merged,
|
||||
"discarded": r.discarded.iter().map(|(h, n)| json!({ "category": h.id(), "count": n })).collect::<Vec<_>>(),
|
||||
}))
|
||||
});
|
||||
if let (Some(o), Some(e)) = (out.as_object_mut(), extra.as_object()) {
|
||||
o.extend(e.iter().map(|(k, v)| (k.clone(), v.clone())));
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// A watermark or background picture: `file` (an image or a PDF) and `file_page` (1-based).
|
||||
|
||||
@@ -375,6 +375,9 @@ pub(crate) fn info(d: &Document) -> Value {
|
||||
})).collect::<Vec<_>>(),
|
||||
"warnings": i.warnings,
|
||||
"repairs": d.repair_log(),
|
||||
// Objects that could not be read (each reads as null): nothing was repaired, what they held is
|
||||
// lost. Last, so it includes what reading the fields above failed on.
|
||||
"unreadable_objects": d.unreadable_objects(),
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -20,6 +20,10 @@ pub(crate) const FIND_MAX_WARNINGS: usize = 100;
|
||||
|
||||
pub(crate) const FIND_MAX_WARNING_BYTES: usize = 1024;
|
||||
|
||||
/// HTML that one `text_extract` with `format: "html"` returns across all its pages; a page past
|
||||
/// it gets none. `html_truncated` covers this and any page whose own copy hit its caps.
|
||||
const MAX_EXTRACT_HTML_BYTES: usize = 32 << 20;
|
||||
|
||||
impl Automation {
|
||||
// ---- pages and text ----------------------------------------------------------------------
|
||||
|
||||
@@ -201,6 +205,16 @@ impl Automation {
|
||||
}
|
||||
|
||||
pub(crate) fn text_extract(&mut self, a: &Args) -> Result<Value> {
|
||||
self.text_extract_within(a, MAX_EXTRACT_HTML_BYTES)
|
||||
}
|
||||
|
||||
/// [`Self::text_extract`] with at most `html_budget` bytes of HTML across all pages.
|
||||
pub(crate) fn text_extract_within(&mut self, a: &Args, html_budget: usize) -> Result<Value> {
|
||||
let html = match a.opt_str("format")?.unwrap_or("text") {
|
||||
"text" => false,
|
||||
"html" => true,
|
||||
other => return Err(ToolError::InvalidArgs(format!("format must be \"text\" or \"html\", not {other:?}"))),
|
||||
};
|
||||
let doc = self.doc_to_copy(a)?;
|
||||
let id = doc.id;
|
||||
let pages = match a.opt_ints("pages")? {
|
||||
@@ -214,8 +228,42 @@ impl Automation {
|
||||
Some(r) => t.column_text(&t.glyphs_in(r)),
|
||||
None => t.plain_text(),
|
||||
};
|
||||
let out: Vec<Value> = pages.iter().zip(texts).map(|(p, t)| json!({ "page": p + 1, "text": text(&t) })).collect();
|
||||
Ok(json!({ "pages": out }))
|
||||
let doc = self.doc(a)?;
|
||||
let mut out = Vec::with_capacity(pages.len());
|
||||
// `spent`: the budget ran out, so later pages get no HTML. `cut`: some page's HTML is
|
||||
// missing part of its text, by the budget or by the copy's own caps.
|
||||
let (mut html_left, mut spent, mut cut) = (html_budget, false, false);
|
||||
for (&p, t) in pages.iter().zip(texts) {
|
||||
let mut page = json!({ "page": p + 1, "text": text(&t) });
|
||||
if html {
|
||||
// Copy with formatting: the same glyphs as an HTML fragment, within one budget for
|
||||
// the whole call; a page past it gets none and the call says so.
|
||||
let mut copy = pdfcraft_engine::RichCopy::default();
|
||||
if !spent {
|
||||
let glyphs: Vec<usize> = match rect {
|
||||
Some(r) => t.glyphs_in(r),
|
||||
None => (0..t.glyphs.len()).collect(),
|
||||
};
|
||||
copy = doc.rich_copy(p, &t, &glyphs).map_err(failed)?;
|
||||
match html_left.checked_sub(copy.html.len()) {
|
||||
Some(left) => html_left = left,
|
||||
None => {
|
||||
spent = true;
|
||||
copy = pdfcraft_engine::RichCopy::default();
|
||||
}
|
||||
}
|
||||
}
|
||||
cut |= spent || copy.truncated;
|
||||
page["html"] = json!(copy.html);
|
||||
page["styles_incomplete"] = json!(copy.styles_incomplete || spent);
|
||||
}
|
||||
out.push(page);
|
||||
}
|
||||
let mut result = json!({ "pages": out });
|
||||
if html {
|
||||
result["html_truncated"] = json!(cut);
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
/// Matches in document order, extracting page text in growing batches and stopping as soon as
|
||||
|
||||
@@ -2,8 +2,8 @@
|
||||
//! (removing what they cover for good) or clear them.
|
||||
|
||||
use pdfcraft_engine::{
|
||||
Edit, Hidden, NewAnnotation, REDACT_MAX_WORDS, REDACTION_CODE_SETS, RedactPattern, RedactionCodeSet, Shape, Style, find_pattern, rect_quad,
|
||||
redact_word_list,
|
||||
Edit, Hidden, NewAnnotation, REDACT_MAX_WORDS, REDACT_VALIDATORS, REDACTION_CODE_SETS, RedactPattern, RedactRegex, RedactValidator,
|
||||
RedactionCodeSet, Shape, Style, find_pattern, rect_quad, redact_word_list,
|
||||
};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
@@ -59,16 +59,20 @@ impl Automation {
|
||||
a.get("find").is_some(),
|
||||
a.get("words").is_some(),
|
||||
a.get("pattern").is_some(),
|
||||
a.get("regex").is_some(),
|
||||
a.opt_bool("whole_pages")?.unwrap_or(false),
|
||||
];
|
||||
if chosen.iter().filter(|c| **c).count() != 1 {
|
||||
return Err(ToolError::InvalidArgs("pass exactly one of rect (with page), find, words, pattern or whole_pages: true".into()));
|
||||
return Err(ToolError::InvalidArgs("pass exactly one of rect (with page), find, words, pattern, regex or whole_pages: true".into()));
|
||||
}
|
||||
let case_sensitive = a.opt_bool("case_sensitive")?.unwrap_or(false);
|
||||
let whole_words = a.opt_bool("whole_words")?.unwrap_or(false);
|
||||
if (case_sensitive || whole_words) && a.get("find").is_none() && a.get("words").is_none() {
|
||||
return Err(ToolError::InvalidArgs("case_sensitive and whole_words apply only to find or words".into()));
|
||||
}
|
||||
if a.get("validate").is_some() && a.get("regex").is_none() {
|
||||
return Err(ToolError::InvalidArgs("validate applies only to regex".into()));
|
||||
}
|
||||
// Per searched word or phrase: how many marks it made.
|
||||
let mut matched_words: Vec<(String, usize)> = Vec::new();
|
||||
if a.get("rect").is_some() {
|
||||
@@ -89,6 +93,19 @@ impl Automation {
|
||||
Some(p) => Some(RedactPattern::from_id(p).ok_or_else(|| ToolError::InvalidArgs(format!("unknown pattern {p:?}")))?),
|
||||
None => None,
|
||||
};
|
||||
let user_re = match a.opt_str("regex")? {
|
||||
Some(src) => {
|
||||
let validator = match a.opt_str("validate")? {
|
||||
Some(v) => Some(RedactValidator::from_id(v).ok_or_else(|| {
|
||||
let ids: Vec<_> = REDACT_VALIDATORS.iter().map(|v| v.id()).collect();
|
||||
ToolError::InvalidArgs(format!("unknown validate {v:?}; allowed: {}", ids.join(", ")))
|
||||
})?),
|
||||
None => None,
|
||||
};
|
||||
Some(RedactRegex::new(src, validator).map_err(|e| ToolError::InvalidArgs(e.to_string()))?)
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
let needles: Vec<String> = match (a.opt_str("find")?, a.get("words")) {
|
||||
(Some(f), _) => vec![f.to_owned()],
|
||||
(None, Some(_)) => {
|
||||
@@ -108,9 +125,27 @@ impl Automation {
|
||||
let texts = self.page_texts(id, &pages)?;
|
||||
let info = self.doc(a)?.info.clone();
|
||||
for (&p, text) in pages.iter().zip(&texts) {
|
||||
let hits: Vec<(Option<usize>, _)> = match pattern {
|
||||
Some(pat) => text.find_with(|chars| find_pattern(pat, chars)).into_iter().map(|h| (None, h)).collect(),
|
||||
None => needles
|
||||
let hits: Vec<(Option<usize>, _)> = match (&user_re, pattern) {
|
||||
(Some(re), _) => {
|
||||
// A page with too many matches fails the call: marking only the first ones
|
||||
// would leave the rest readable after redact_apply.
|
||||
let too_many = std::cell::Cell::new(false);
|
||||
let found = text.find_with(|chars| {
|
||||
re.find(chars).unwrap_or_else(|_| {
|
||||
too_many.set(true);
|
||||
Vec::new()
|
||||
})
|
||||
});
|
||||
if too_many.get() {
|
||||
return Err(ToolError::InvalidArgs(format!(
|
||||
"regex has more than 10000 matches on page {}; nothing was marked. Narrow the expression so that every match can be marked",
|
||||
p + 1
|
||||
)));
|
||||
}
|
||||
found.into_iter().map(|h| (None, h)).collect()
|
||||
}
|
||||
(None, Some(pat)) => text.find_with(|chars| find_pattern(pat, chars)).into_iter().map(|h| (None, h)).collect(),
|
||||
(None, None) => needles
|
||||
.iter()
|
||||
.enumerate()
|
||||
.flat_map(|(i, w)| text.find_opts(w, case_sensitive, whole_words).into_iter().map(move |h| (Some(i), h)))
|
||||
|
||||
@@ -119,6 +119,7 @@ impl Automation {
|
||||
"page": s.page.map(|p| p + 1),
|
||||
"rect": rect,
|
||||
"visible": s.visible,
|
||||
"verdict_shown": s.verdict_shown,
|
||||
"revision": s.revision,
|
||||
"sub_filter": s.sub_filter,
|
||||
"algorithm": s.algorithm,
|
||||
|
||||
@@ -550,3 +550,35 @@ fn tool_file_reads_refuse_inputs_exceeding_512_mib() {
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_extract_html_has_one_budget_across_pages() {
|
||||
let mut a = Automation::new();
|
||||
let id = search_document(&mut a, 3);
|
||||
let args = json!({ "doc": id.0, "format": "html" });
|
||||
let full = a.text_extract(&Args(&args)).unwrap();
|
||||
assert_eq!(full["html_truncated"], false);
|
||||
let sizes: Vec<usize> = full["pages"].as_array().unwrap().iter().map(|p| p["html"].as_str().unwrap().len()).collect();
|
||||
assert!(sizes.iter().all(|n| *n > 0), "{full}");
|
||||
// Room for two pages: the third gets no HTML, and the call says so.
|
||||
let capped = a.text_extract_within(&Args(&args), sizes[0] + sizes[1] + sizes[2] - 1).unwrap();
|
||||
let pages = capped["pages"].as_array().unwrap();
|
||||
assert_eq!(capped["html_truncated"], true);
|
||||
assert_eq!(pages[1]["html"], full["pages"][1]["html"]);
|
||||
assert_eq!(pages[2]["html"], "");
|
||||
assert_eq!(pages[2]["styles_incomplete"], true);
|
||||
assert_eq!(pages[2]["text"], "Page 3", "the plain text is not capped by the HTML budget");
|
||||
// Plain text alone says nothing about HTML.
|
||||
assert!(a.text_extract(&Args(&json!({ "doc": id.0 }))).unwrap().get("html_truncated").is_none());
|
||||
// A smaller page after the one that overflowed still gets none: "Page 1" fits what "Page 10"
|
||||
// did not.
|
||||
let id = search_document(&mut a, 10);
|
||||
let args = json!({ "doc": id.0, "pages": [10, 1], "format": "html" });
|
||||
let full = a.text_extract(&Args(&args)).unwrap();
|
||||
let (ten, one) = (full["pages"][0]["html"].as_str().unwrap().len(), full["pages"][1]["html"].as_str().unwrap().len());
|
||||
assert!(one < ten, "{full}");
|
||||
let capped = a.text_extract_within(&Args(&args), ten - 1).unwrap();
|
||||
assert_eq!(capped["pages"][0]["html"], "");
|
||||
assert_eq!(capped["pages"][1]["html"], "", "no HTML after the budget ran out: {capped}");
|
||||
assert_eq!(capped["pages"][1]["styles_incomplete"], true);
|
||||
}
|
||||
@@ -148,7 +148,7 @@ pub fn tools() -> Vec<ToolDef> {
|
||||
"paths": {"type":"array","items":{"type":"string"},"minItems":1,"maxItems":1000},
|
||||
"out_dir": {"type":"string"},
|
||||
"steps": {"type":"array","items":{"type":"string","enum":["convert","ocr","optimize"]},"minItems":1,"maxItems":3,"uniqueItems":true},
|
||||
"recursive": {"type":"boolean"}, "stop_on_error": {"type":"boolean"},
|
||||
"recursive": {"type":"boolean"}, "stop_on_error": {"type":"boolean"}, "dry_run": {"type":"boolean"},
|
||||
"ppi": {"type":"number","minimum":9,"maximum":1600},
|
||||
"quality": {"type":"integer","minimum":1,"maximum":100},
|
||||
"dpi": {"type":"number","minimum":72,"maximum":600},
|
||||
@@ -164,7 +164,7 @@ pub fn tools() -> Vec<ToolDef> {
|
||||
.cmd("file.open")
|
||||
.with(schema(json!({ "path": { "type": "string" }, "password": { "type": "string", "description": "User or owner password for encrypted files." } }), &["path"])),
|
||||
t("doc_list", "List open documents", "List the open documents with their ids, page counts and unsaved state.").ro().with(schema(json!({}), &[])),
|
||||
t("doc_info", "Inspect a document", "Metadata, page sizes and labels, bookmarks, annotations, form fields, links, layers, page transitions and display times, the destination it opens at, attachments, fonts, security and repair notes.")
|
||||
t("doc_info", "Inspect a document", "Metadata, page sizes and labels, bookmarks, annotations, form fields, links, layers, page transitions and display times, the destination it opens at, attachments, fonts, security, repair notes and the objects that could not be read.")
|
||||
.ro()
|
||||
.cmd("file.properties")
|
||||
.with(schema(json!({ "doc": doc() }), &["doc"])),
|
||||
@@ -216,13 +216,14 @@ pub fn tools() -> Vec<ToolDef> {
|
||||
.with(schema(json!({ "doc": doc(), "pages": pages("to count (default: all)"),
|
||||
"exclude_tables": { "type": "boolean" }, "exclude_code": { "type": "boolean" }, "exclude_images": { "type": "boolean" }
|
||||
}), &["doc"])),
|
||||
t("text_extract", "Extract text", "Extract the text of some or all pages, in reading order. With rect, only the text inside that rectangle on each page, as Column select takes it: one row per visual line, side-by-side pieces (table cells) separated by a tab.")
|
||||
t("text_extract", "Extract text", "Extract the text of some or all pages, in reading order. With rect, only the text inside that rectangle on each page, as Column select takes it: one row per visual line, side-by-side pieces (table cells) separated by a tab. With format \"html\", each page also carries html, the same text as Copy with formatting puts on the clipboard (paragraphs, bold, italic, size, colour and font family), and styles_incomplete when some styles had to be left out. With rect, the html is that text in line order, not split into the column's rows and cells. The HTML of one call is capped at 32 MiB in total; pages past the cap carry empty html with styles_incomplete. html_truncated is set when that cap is reached or when a page's own copy was cut at its span or size cap.")
|
||||
.ro()
|
||||
.cmd("edit.column_select")
|
||||
.with(schema(
|
||||
json!({
|
||||
"doc": doc(), "pages": pages("to extract (default: all)"),
|
||||
"rect": { "type": "array", "items": { "type": "number" }, "minItems": 4, "maxItems": 4, "description": "Column select: [x0, y0, x1, y1] in points from the top-left of the displayed page; a glyph counts when its centre is inside." }
|
||||
"rect": { "type": "array", "items": { "type": "number" }, "minItems": 4, "maxItems": 4, "description": "Column select: [x0, y0, x1, y1] in points from the top-left of the displayed page; a glyph counts when its centre is inside." },
|
||||
"format": { "type": "string", "enum": ["text", "html"], "description": "text (default) or html: also return each page's text as formatted HTML." }
|
||||
}),
|
||||
&["doc"],
|
||||
)),
|
||||
@@ -619,7 +620,7 @@ pub fn tools() -> Vec<ToolDef> {
|
||||
t(
|
||||
"redact_mark",
|
||||
"Mark for redaction",
|
||||
"Mark content for redaction (nothing is removed until redact_apply). One of: rect [x0, y0, x1, y1] (points from the top-left of the displayed page) with page; find (text, every match); words (a list of words or phrases, every match of each; the result's matched_words says how many marks each made); pattern (phone, email, credit-card, ssn, date, iban: every match, Acrobat's Search & Redact patterns); whole_pages: true. find and words accept case_sensitive and whole_words (both default false). Select one page with page or multiple with pages (default all); do not pass both. rect requires page. overlay: text shown on the box once applied, or code_set (foia: U.S. FOIA (b)(1)(A)…(b)(9); privacy-act: U.S. Privacy Act (d)(5), (j)(1)…(k)(7)) with codes, shown as \"(b)(6), (b)(7)(C)\"; fill: box colour (default black). Undoable.",
|
||||
"Mark content for redaction (nothing is removed until redact_apply). One of: rect [x0, y0, x1, y1] (points from the top-left of the displayed page) with page; find (text, every match); words (a list of words or phrases, every match of each; the result's matched_words says how many marks each made); pattern (phone, email, credit-card, ssn, date, iban: every match, Acrobat's Search & Redact patterns); regex (your own regular expression, every match, on the page text with words and lines separated by one space; Rust regex syntax: linear-time, no look-around or back-references, case-sensitive unless (?i), at most 1024 bytes, more than 10000 matches on one page fail the call, matches of the empty string are refused) with optional validate (luhn, mod97, iban: keep a match only if its checksum holds); whole_pages: true. find and words accept case_sensitive and whole_words (both default false). Select one page with page or multiple with pages (default all); do not pass both. rect requires page. overlay: text shown on the box once applied, or code_set (foia: U.S. FOIA (b)(1)(A)…(b)(9); privacy-act: U.S. Privacy Act (d)(5), (j)(1)…(k)(7)) with codes, shown as \"(b)(6), (b)(7)(C)\"; fill: box colour (default black). Undoable.",
|
||||
)
|
||||
.with(schema(
|
||||
json!({
|
||||
@@ -631,6 +632,8 @@ pub fn tools() -> Vec<ToolDef> {
|
||||
"case_sensitive": { "type": "boolean", "description": "Match letter case for find or words (default false)." },
|
||||
"whole_words": { "type": "boolean", "description": "Match whole words for find or words (default false)." },
|
||||
"pattern": pattern_enum(),
|
||||
"regex": { "type": "string", "minLength": 1, "maxLength": 1024, "description": "Regular expression (Rust regex syntax), at most 1024 bytes (maxLength counts characters, the limit is bytes); every match is marked." },
|
||||
"validate": { "type": "string", "enum": ["luhn", "mod97", "iban"], "description": "With regex: keep a match only if its checksum is valid (spaces and hyphens ignored)." },
|
||||
"whole_pages": { "type": "boolean" },
|
||||
"pages": pages("to search or mark (default: all); mutually exclusive with page, and not valid with rect"),
|
||||
"overlay": { "type": "string" },
|
||||
@@ -718,13 +721,13 @@ pub fn tools() -> Vec<ToolDef> {
|
||||
}),
|
||||
&["doc"],
|
||||
)),
|
||||
t("content_list", "List added content", "Text and images added with page_add_text/page_add_image (or Edit a PDF ▸ Add content), per page with a 1-based index, rect (points from the top-left of the page), and text style.")
|
||||
t("content_list", "List added content", "Text and images added with page_add_text/page_add_image (or Edit a PDF ▸ Add content), per page with a 1-based index, rect (points from the top-left of the page), and text style; text painted in gray or CMYK also has gray (its level) or cmyk ([c, m, y, k]).")
|
||||
.ro()
|
||||
.with(schema(json!({ "doc": doc() }), &["doc"])),
|
||||
t(
|
||||
"page_add_text",
|
||||
"Add text to a page",
|
||||
"Add text as page content (not a comment). Place it with at [x, y] (top-left, points from the top-left of the displayed page) and width (wrap width, default 200), or rect. Newlines start new lines; long lines wrap. Style: font helvetica/times/courier, size, bold, italic, color (#RRGGBB or a name), align left/center/right, char_spacing (points after each character). Text must be Western European (WinAnsi) characters, or Arabic, Hebrew or Thai when the build has their craft-fonts faces (drawn right to left where the text is); others are refused. It stays editable with content_update. Undoable.",
|
||||
"Add text as page content (not a comment). Place it with at [x, y] (top-left, points from the top-left of the displayed page) and width (wrap width, default 200), or rect. Newlines start new lines; long lines wrap. Style: font helvetica/times/courier, size, bold, italic, color (#RRGGBB or a name, painted in RGB) or, for print, gray (0 black to 1 white, painted in DeviceGray) or cmyk ([c, m, y, k], each 0 to 1, painted in DeviceCMYK; [0, 0, 0, 1] is 100 K black), one of the three, align left/center/right, char_spacing (points after each character). Text must be Western European (WinAnsi) characters, or Arabic, Hebrew or Thai when the build has their craft-fonts faces (drawn right to left where the text is); others are refused. It stays editable with content_update. Undoable.",
|
||||
)
|
||||
.cmd("edit.text")
|
||||
.with(schema(
|
||||
@@ -735,6 +738,8 @@ pub fn tools() -> Vec<ToolDef> {
|
||||
"rect": { "type": "array", "items": { "type": "number" }, "minItems": 4, "maxItems": 4 },
|
||||
"font": { "type": "string", "enum": ["helvetica", "times", "courier"] }, "size": { "type": "number", "minimum": 1, "maximum": 500 },
|
||||
"bold": { "type": "boolean" }, "italic": { "type": "boolean" }, "color": { "type": "string" },
|
||||
"gray": { "type": "number", "minimum": 0, "maximum": 1, "description": "DeviceGray level, 0 black to 1 white (instead of color)." },
|
||||
"cmyk": { "type": "array", "items": { "type": "number", "minimum": 0, "maximum": 1 }, "minItems": 4, "maxItems": 4, "description": "DeviceCMYK [c, m, y, k], each 0 to 1 (instead of color); [0, 0, 0, 1] is 100 K black." },
|
||||
"align": { "type": "string", "enum": ["left", "center", "right", "justify"] },
|
||||
"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." },
|
||||
@@ -751,13 +756,15 @@ pub fn tools() -> Vec<ToolDef> {
|
||||
json!({ "doc": doc(), "page": { "type": "integer", "minimum": 1 }, "path": { "type": "string" }, "rect": { "type": "array", "items": { "type": "number" }, "minItems": 4, "maxItems": 4 } }),
|
||||
&["doc", "page", "path"],
|
||||
)),
|
||||
t("content_update", "Edit added content", "Move/resize (rect), retype (text) or restyle (font, size, bold, italic, color, align, char_spacing in points) an added item (page, index from content_list). Images: rotate (degrees, multiple of 90, counter-clockwise), flip_h / flip_v (toggle), crop [left, bottom, right, top] as fractions trimmed, image (a file that replaces the picture). Undoable.")
|
||||
t("content_update", "Edit added content", "Move/resize (rect), retype (text) or restyle (font, size, bold, italic, color or gray or cmyk as page_add_text takes them, align, char_spacing in points) an added item (page, index from content_list). Images: rotate (degrees, multiple of 90, counter-clockwise), flip_h / flip_v (toggle), crop [left, bottom, right, top] as fractions trimmed, image (a file that replaces the picture). Undoable.")
|
||||
.with(schema(
|
||||
json!({
|
||||
"doc": doc(), "page": { "type": "integer", "minimum": 1 }, "index": { "type": "integer", "minimum": 1 },
|
||||
"rect": { "type": "array", "items": { "type": "number" }, "minItems": 4, "maxItems": 4 }, "text": { "type": "string" },
|
||||
"font": { "type": "string", "enum": ["helvetica", "times", "courier"] }, "size": { "type": "number", "minimum": 1, "maximum": 500 },
|
||||
"bold": { "type": "boolean" }, "italic": { "type": "boolean" }, "color": { "type": "string" },
|
||||
"gray": { "type": "number", "minimum": 0, "maximum": 1, "description": "DeviceGray level, 0 black to 1 white (instead of color)." },
|
||||
"cmyk": { "type": "array", "items": { "type": "number", "minimum": 0, "maximum": 1 }, "minItems": 4, "maxItems": 4, "description": "DeviceCMYK [c, m, y, k], each 0 to 1 (instead of color); [0, 0, 0, 1] is 100 K black." },
|
||||
"align": { "type": "string", "enum": ["left", "center", "right", "justify"] },
|
||||
"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." },
|
||||
@@ -891,7 +898,7 @@ pub fn tools() -> Vec<ToolDef> {
|
||||
comment_ref(json!({ "status": { "type": "string", "enum": ["none", "accepted", "rejected", "cancelled", "completed"] }, "author": { "type": "string" } })),
|
||||
&["doc", "status"],
|
||||
)),
|
||||
t("sign_list", "List and validate signatures", "Every signature field with its validation: status (valid, unknown = intact but the signer isn't trusted, invalid, unsigned), signer and certificate, date, reason, location, certification level, page and rect, the revision it covers and changes made after signing (none, allowed, disallowed), with Acrobat-style explanations.")
|
||||
t("sign_list", "List and validate signatures", "Every signature field with its validation: status (valid, unknown = intact but the signer isn't trusted, invalid, unsigned), signer and certificate, date, reason, location, certification level, page and rect, whether PdfCraft draws that state into the signature's own appearance as displayed (verdict_shown; never written to the file), the revision it covers and changes made after signing (none, allowed, disallowed), with Acrobat-style explanations.")
|
||||
.ro()
|
||||
.with(schema(json!({ "doc": doc() }), &["doc"])),
|
||||
t("sign_id_create", "Create a digital ID", "Create a self-signed digital ID and save it as a password-protected .p12 file (Acrobat: Configure a new digital ID ▸ Create a new digital ID ▸ Save to file). Default key: 2048-bit RSA, valid 5 years.").with(schema(
|
||||
@@ -1285,7 +1292,7 @@ pub fn tools() -> Vec<ToolDef> {
|
||||
"property": { "type": "string", "enum": ["type", "title", "actual_text", "alternate_text", "language", "summary", "scope"] },
|
||||
"value": { "type": "string" },
|
||||
}), &["doc", "object", "generation", "property"])),
|
||||
t("accessibility_mark_tag_artifact", "Mark tag content as artifact", "Mark a reachable leaf structure tag's direct marked content as an artifact and remove the tag from the reading structure. Use object and generation from accessibility_tags. Tags with child structure elements, no direct marked content, or content not found on its page are rejected. Undoable.")
|
||||
t("accessibility_mark_tag_artifact", "Mark tag content as artifact", "Mark a reachable leaf structure tag's direct marked content as an artifact and remove the tag from the reading structure. Use object and generation from accessibility_tags. Tags with child structure elements, no direct marked content, content not found on its page, or content that a damaged or undecodable content stream may hide or change are rejected. Undoable.")
|
||||
.with(schema(json!({
|
||||
"doc": doc(), "object": { "type": "integer", "minimum": 1 },
|
||||
"generation": { "type": "integer", "minimum": 0, "maximum": 65535 },
|
||||
@@ -1555,14 +1562,14 @@ 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), 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.")
|
||||
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, ungroup (Form artwork only: its content is drawn in place, so its text becomes editable with text_paragraphs/text_edit and its pictures separate; refused for knockout groups and for transparency groups that blend inside, are drawn translucent or blend in a colour space other than the page's, which would composite differently, and for forms whose /DefaultGray, /DefaultRGB or /DefaultCMYK the page doesn't share, which would stop remapping their colours), 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", "transform", "flip_horizontal", "flip_vertical", "replace", "delete", "bring_to_front", "send_to_back", "bring_forward", "send_backward", "remove_crop"] },
|
||||
"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", "ungroup"] },
|
||||
"rect": { "type": "array", "items": { "type": "number" }, "minItems": 4, "maxItems": 4 },
|
||||
"quarters": { "type": "integer" },
|
||||
"degrees": { "type": "number" },
|
||||
@@ -1628,7 +1635,7 @@ pub fn tools() -> Vec<ToolDef> {
|
||||
.with(schema(json!({ "doc": doc() }), &["doc"])),
|
||||
t("doc_open_revision", "Open a revision", "Open saved revision `revision` (1 = the oldest) of a document as a new, unsaved document, to see the file as it was then.")
|
||||
.with(schema(json!({ "doc": doc(), "revision": { "type": "integer", "minimum": 1 } }), &["doc", "revision"])),
|
||||
t("doc_optimize", "Optimize PDF", "Write an optimized copy to `path` (Acrobat's PDF Optimizer). preset: standard (default; Reduce File Size's choices) or mobile (images to 96 ppi above 144, JPEG high quality); the options below change it. compatibility: retain (default; keeps the document's version, or 1.5 when object streams are written), 1.4, 1.5, 1.6, 1.7 or 2.0. merge_fragments (default true) first puts a page picture drawn as many stacked image strips (as some PDF printers write it) back together into one image, so it can be resampled (merged_images, fragments_merged). color / gray: { downsample, ppi, above_ppi, compression: jpeg|zip|retain, quality 1–100 } (defaults: downsample to 150 ppi above 225, JPEG 60). mono: { downsample, ppi, above_ppi, compression: ccitt_g4|jbig2|retain } for black-and-white images and image masks (default: averaged down to 300 ppi above 450 ppi, counted in images_resampled; stored losslessly as CCITT Group 4 or JBIG2 (or 1-bit Flate, once resampled or packed from more bits) when that is smaller, up to 16 JBIG2 images sharing one symbol dictionary (/JBIG2Globals) where that is smaller still (image masks and DeviceGray images named directly, of at most 64 Mi pixels, which redaction can store again without it), Group 3 fax images, JBIG2 images, black-and-white RGB and indexed images using only palette entries 0 and 1 among them, counted in images_recompressed; retain resamples only, a CCITT image staying CCITT, a JBIG2 image JBIG2 and any other becoming Flate). Images past what one run may decode stay as they are, counted in images_refused; streams it only stores with Flate past that stay LZW, uncounted. Images are measured where pages draw them and replaced only when smaller. discard_*: thumbnails (default true), alternate_images (true), tags, print_settings; flate_unencoded (true); object_streams (default true; always off for 1.4); lzw_to_flate (true) decodes LZW streams and stores them with Flate instead, leaving any it cannot decode unchanged (lzw_streams counts the streams converted); remove_invalid_links and remove_unreferenced_dests (true); images and forms the pages list but never draw are always dropped (unused_xobjects). discard: Remove Hidden Information categories (metadata, attachments, comments, form-fields, hidden-text, hidden-layers, bookmarks, links-actions-scripts, private-data). Signed documents are refused. The open document is unchanged.")
|
||||
t("doc_optimize", "Optimize PDF", "Write an optimized copy to `path` (Acrobat's PDF Optimizer). preset: standard (default; Reduce File Size's choices) or mobile (images to 96 ppi above 144, JPEG high quality); the options below change it. compatibility: retain (default; keeps the document's version, or 1.5 when object streams are written), 1.4, 1.5, 1.6, 1.7 or 2.0. merge_fragments (default true) first puts a page picture drawn as many stacked image strips (as some PDF printers write it) back together into one image, so it can be resampled (merged_images, fragments_merged). color / gray: { downsample, ppi, above_ppi, compression: jpeg|zip|retain, quality 1–100 } (defaults: downsample to 150 ppi above 225, JPEG 60). mono: { downsample, ppi, above_ppi, compression: ccitt_g4|jbig2|retain } for black-and-white images and image masks (default: averaged down to 300 ppi above 450 ppi, counted in images_resampled; stored losslessly as CCITT Group 4 or JBIG2 (or 1-bit Flate, once resampled or packed from more bits) when that is smaller, up to 16 JBIG2 images sharing one symbol dictionary (/JBIG2Globals) where that is smaller still (image masks and DeviceGray images named directly, of at most 64 Mi pixels, which redaction can store again without it), Group 3 fax images, JBIG2 images, black-and-white RGB and indexed images using only palette entries 0 and 1 among them, counted in images_recompressed; retain resamples only, a CCITT image staying CCITT, a JBIG2 image JBIG2 and any other becoming Flate). Images past what one run may decode stay as they are, counted in images_refused; streams it only stores with Flate past that stay LZW, uncounted. Images are measured where pages draw them and replaced only when smaller. discard_*: thumbnails (default true), alternate_images (true), tags, print_settings; flate_unencoded (true); object_streams (default true; always off for 1.4); lzw_to_flate (true) decodes LZW streams and stores them with Flate instead, leaving any it cannot decode unchanged (lzw_streams counts the streams converted); remove_invalid_links and remove_unreferenced_dests (true); images and forms the pages list but never draw are always dropped (unused_xobjects). discard: Remove Hidden Information categories (metadata, attachments, comments, form-fields, hidden-text, hidden-layers, bookmarks, links-actions-scripts, private-data). Signed documents are refused. target_bytes (optional): if the copy is larger, retry with up to 5 progressively stronger image settings (downsample to at most 110, 96, 72, 54, 36 ppi, applied to colour and grey images; images set to JPEG also get JPEG quality at most 45, 35, 28, 20, 12, while zip and retain images keep their encoding and only get the lower ppi) and stop at the first copy that fits; reports target_reached, attempts and target_settings, and writes the smallest copy with target_reached false when none fits. Without it nothing changes. The open document is unchanged.")
|
||||
.cmd("optimize.advanced")
|
||||
.with(schema(
|
||||
json!({
|
||||
@@ -1640,6 +1647,7 @@ pub fn tools() -> Vec<ToolDef> {
|
||||
"color": { "type": "object" },
|
||||
"gray": { "type": "object" },
|
||||
"mono": { "type": "object" },
|
||||
"target_bytes": { "type": "integer", "minimum": 1 },
|
||||
"discard_thumbnails": { "type": "boolean" },
|
||||
"discard_alternate_images": { "type": "boolean" },
|
||||
"discard_tags": { "type": "boolean" },
|
||||
|
||||
@@ -2538,6 +2538,7 @@ fn protecting_through_tools() {
|
||||
// Copying wasn't allowed either (#568): no text or images come out, though search works.
|
||||
for (tool, args) in [
|
||||
("text_extract", json!({ "doc": re })),
|
||||
("text_extract", json!({ "doc": re, "format": "html" })),
|
||||
("text_word_count", json!({ "doc": re })),
|
||||
("text_paragraphs", json!({ "doc": re, "page": 1 })),
|
||||
("doc_export_text", json!({ "doc": re, "path": "out.txt" })),
|
||||
@@ -4817,6 +4818,34 @@ fn redacting_through_tools() {
|
||||
assert!(matches!(a.call("redact_mark", &json!({ "doc": doc })), Err(ToolError::InvalidArgs(_))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn redacting_with_a_caller_regex_through_tools() {
|
||||
let dir = workdir("redact-regex");
|
||||
std::fs::write(
|
||||
dir.join("ids.txt"),
|
||||
"Ref 1 85 05 78 006 084 36 end\nRef 2 91 12 34 567 890 12 end\nCard 4539 1488 0343 6467 and 4539 1488 0343 6468",
|
||||
)
|
||||
.unwrap();
|
||||
let mut a = auto(&dir);
|
||||
let doc = ok(&mut a, "doc_create", json!({ "from": "text", "path": "ids.txt" }))["doc"].as_u64().unwrap();
|
||||
let bad = |a: &mut Automation, args: Value| matches!(a.call("redact_mark", &args), Err(ToolError::InvalidArgs(_)));
|
||||
assert!(bad(&mut a, json!({ "doc": doc, "regex": "(unclosed" })));
|
||||
assert!(bad(&mut a, json!({ "doc": doc, "regex": "a*" })));
|
||||
assert!(bad(&mut a, json!({ "doc": doc, "regex": "x".repeat(2000) })));
|
||||
assert!(bad(&mut a, json!({ "doc": doc, "regex": "x", "pattern": "ssn" })));
|
||||
assert!(bad(&mut a, json!({ "doc": doc, "regex": "x", "validate": "crc" })));
|
||||
assert!(bad(&mut a, json!({ "doc": doc, "find": "x", "validate": "luhn" })));
|
||||
assert!(matches!(a.call("redact_mark", &json!({ "doc": doc, "regex": "Z{3}" })), Err(ToolError::Failed(_))));
|
||||
let r = ok(&mut a, "redact_mark", json!({ "doc": doc, "regex": r"\d \d\d \d\d \d\d \d{3} \d{3} \d\d" }));
|
||||
assert_eq!(r["marked"].as_u64(), Some(2));
|
||||
let r = ok(&mut a, "redact_mark", json!({ "doc": doc, "regex": r"\d{4}( \d{4}){3}", "validate": "luhn" }));
|
||||
assert_eq!(r["marked"].as_u64(), Some(1), "only the number with a valid checksum");
|
||||
ok(&mut a, "redact_apply", json!({ "doc": doc }));
|
||||
let text = page_text(&mut a, doc)[0].clone();
|
||||
assert!(!text.contains("85 05") && !text.contains("91 12") && !text.contains("6467"), "{text}");
|
||||
assert!(text.contains("6468"), "{text}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
/// Mark, apply and save remove the complete international number while retaining labels and controls.
|
||||
fn redacting_italian_international_slash_numbers_through_tools() {
|
||||
@@ -5214,6 +5243,83 @@ fn adding_content_through_tools() {
|
||||
assert!(matches!(a.call("content_delete", &json!({ "doc": doc, "page": 1, "index": 5 })), Err(ToolError::Failed(_))));
|
||||
}
|
||||
|
||||
/// #6440: `page_add_text` paints text in CMYK or gray for a print file, so its black is 100 K
|
||||
/// (`0 0 0 1 k`) rather than DeviceRGB; `content_update` restyles it either way.
|
||||
#[test]
|
||||
fn added_text_takes_a_cmyk_or_gray_ink_through_tools() {
|
||||
let dir = workdir("content-ink");
|
||||
let mut a = auto(&dir);
|
||||
let doc = ok(&mut a, "doc_open", json!({ "path": "a.pdf" }))["doc"].as_u64().unwrap();
|
||||
ok(&mut a, "page_add_text", json!({ "doc": doc, "page": 1, "text": "PROOF", "at": [20, 20], "cmyk": [0, 0, 0, 1] }));
|
||||
ok(&mut a, "page_add_text", json!({ "doc": doc, "page": 1, "text": "Note", "at": [20, 80], "gray": 0.5 }));
|
||||
let items = ok(&mut a, "content_list", json!({ "doc": doc }))["items"].clone();
|
||||
assert_eq!((&items[0]["cmyk"], &items[1]["gray"]), (&json!([0.0, 0.0, 0.0, 1.0]), &json!(0.5)));
|
||||
// The item streams of the saved file.
|
||||
let saved_items = |a: &mut Automation, name: &str| -> Vec<String> {
|
||||
ok(a, "doc_save", json!({ "doc": doc, "path": name }));
|
||||
let saved = pdfcraft_cos::Document::open(std::sync::Arc::new(std::fs::read(dir.join(name)).unwrap())).unwrap();
|
||||
let page = &pdfcraft_model::pages(&saved)[0];
|
||||
let list = saved.resolve(page.dict.get(b"Contents").unwrap()).as_array().cloned().unwrap();
|
||||
list.iter()
|
||||
.filter_map(|c| match &*saved.resolve(c) {
|
||||
pdfcraft_cos::Object::Stream(s) if s.dict.name(b"PCMark") == Some(&b"Added"[..]) => {
|
||||
Some(String::from_utf8_lossy(&s.decoded().unwrap()).into_owned())
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
let streams = saved_items(&mut a, "ink.pdf");
|
||||
assert!(streams[0].contains("0 0 0 1 k") && !streams[0].contains("rg"), "{}", streams[0]);
|
||||
assert!(streams[1].contains("0.5 g") && !streams[1].contains("rg"), "{}", streams[1]);
|
||||
// Restyled: to RGB with color, and back to CMYK.
|
||||
ok(&mut a, "content_update", json!({ "doc": doc, "page": 1, "index": 2, "color": "#000000" }));
|
||||
ok(&mut a, "content_update", json!({ "doc": doc, "page": 1, "index": 1, "cmyk": [1, 0, 0, 0] }));
|
||||
let items = ok(&mut a, "content_list", json!({ "doc": doc }))["items"].clone();
|
||||
assert_eq!((&items[0]["cmyk"], items[1].get("gray")), (&json!([1.0, 0.0, 0.0, 0.0]), None));
|
||||
let streams = saved_items(&mut a, "restyled.pdf");
|
||||
assert!(streams[0].contains("1 0 0 0 k") && streams[1].contains("0 0 0 rg"), "{streams:?}");
|
||||
// One colour at a time, four numbers from 0 to 1.
|
||||
for bad in [
|
||||
json!({ "color": "red", "cmyk": [0, 0, 0, 1] }),
|
||||
json!({ "gray": 0.5, "cmyk": [0, 0, 0, 1] }),
|
||||
json!({ "gray": 1.5 }),
|
||||
json!({ "cmyk": [0, 0, 1] }),
|
||||
json!({ "cmyk": [0, 0, 0, 1, 0] }),
|
||||
json!({ "cmyk": [0, "x", 0, 1] }),
|
||||
json!({ "cmyk": [0, 0, 0, -0.1] }),
|
||||
] {
|
||||
let mut args = json!({ "doc": doc, "page": 1, "text": "x", "at": [20, 200] });
|
||||
args.as_object_mut().unwrap().extend(bad.as_object().unwrap().clone());
|
||||
assert!(matches!(a.call("page_add_text", &args), Err(ToolError::InvalidArgs(_))), "{bad}");
|
||||
}
|
||||
assert_eq!(ok(&mut a, "content_list", json!({ "doc": doc }))["count"], 2, "nothing refused was added");
|
||||
// content_update refuses them too, an image takes no ink, and a refused update changes nothing.
|
||||
let mut png = Vec::new();
|
||||
{
|
||||
let mut enc = png::Encoder::new(&mut png, 40, 20);
|
||||
enc.set_color(png::ColorType::Rgb);
|
||||
let mut w = enc.write_header().unwrap();
|
||||
w.write_image_data(&[200u8; 2400]).unwrap();
|
||||
}
|
||||
std::fs::write(dir.join("logo.png"), png).unwrap();
|
||||
ok(&mut a, "page_add_image", json!({ "doc": doc, "page": 1, "path": "logo.png", "rect": [100, 200, 180, 240] }));
|
||||
let before = ok(&mut a, "content_list", json!({ "doc": doc }))["items"].clone();
|
||||
for (index, bad) in [
|
||||
(1, json!({ "gray": 0.5, "cmyk": [0, 0, 0, 1] })),
|
||||
(2, json!({ "color": "red", "gray": 0.5 })),
|
||||
(1, json!({ "size": 30, "cmyk": [0, 0, 0, 2] })),
|
||||
(2, json!({ "bold": true, "gray": -1 })),
|
||||
(3, json!({ "gray": 0.5 })),
|
||||
(3, json!({ "cmyk": [0, 0, 0, 1] })),
|
||||
] {
|
||||
let mut args = json!({ "doc": doc, "page": 1, "index": index });
|
||||
args.as_object_mut().unwrap().extend(bad.as_object().unwrap().clone());
|
||||
assert!(matches!(a.call("content_update", &args), Err(ToolError::InvalidArgs(_))), "{bad}");
|
||||
}
|
||||
assert_eq!(ok(&mut a, "content_list", json!({ "doc": doc }))["items"], before, "a refused update changed nothing");
|
||||
}
|
||||
|
||||
/// Edit ▸ Copy and Paste headlessly (#2636): an added text box or image, as it is, onto its own
|
||||
/// page beside it, onto a point, and into another document.
|
||||
#[test]
|
||||
@@ -6821,6 +6927,43 @@ fn a_dynamic_xfa_forms_signature_box_is_signed_under_its_som_path() {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn named_layer_verdicts_are_reported_and_rendered_through_tools() {
|
||||
use pdfcraft_cos::{Dict, Document, Lexer, ObjRef, Object, SaveOptions, Stream};
|
||||
let dir = workdir("named-layer-verdict");
|
||||
let mut cos = Document::open(std::sync::Arc::new(fixture(1))).unwrap();
|
||||
let dict = |text: &str| Lexer::new(text.as_bytes(), 0).object().unwrap().as_dict().unwrap().clone();
|
||||
let form = |resources: Dict, ops: &str| {
|
||||
let mut d = dict("<< /Type /XObject /Subtype /Form /BBox [0 0 100 100] >>");
|
||||
d.set(b"Resources".to_vec(), resources);
|
||||
Stream::from_raw(d, ops.as_bytes().to_vec())
|
||||
};
|
||||
let blank = cos.add(form(Dict::new(), ""));
|
||||
let layers = dict(&format!("<< /XObject << /n1 {blank} /n3 {blank} >> >>"));
|
||||
let layer_form = cos.add(form(layers, "/n1 Do /n3 Do"));
|
||||
let normal = cos.add(form(dict(&format!("<< /XObject << /FRM {layer_form} >> >>")), "/FRM Do"));
|
||||
// Deliberately malformed CMS: an invalid signature still gets the redrawn invalid state.
|
||||
let value = cos.add(dict("<< /Type /Sig /SubFilter /ETSI.CAdES.detached /ByteRange [0 0 0 0] /Contents <00> >>"));
|
||||
let widget = cos
|
||||
.add(dict(&format!("<< /FT /Sig /T (Signature1) /Subtype /Widget /F 4 /Rect [50 50 150 150] /P 4 0 R /V {value} /AP << /N {normal} >> >>")));
|
||||
cos.update_dict(ObjRef::new(4, 0), |p| p.set(b"Annots".to_vec(), vec![Object::Ref(widget)])).unwrap();
|
||||
cos.update_dict(cos.root().unwrap(), |root| root.set(b"AcroForm".to_vec(), dict(&format!("<< /Fields [{widget}] >>")))).unwrap();
|
||||
let original = pdfcraft_cos::write_full(&cos, &SaveOptions::default()).unwrap();
|
||||
std::fs::write(dir.join("named.pdf"), &original).unwrap();
|
||||
let mut a = auto(&dir);
|
||||
let doc = ok(&mut a, "doc_open", json!({"path": "named.pdf"}))["doc"].as_u64().unwrap();
|
||||
let list = ok(&mut a, "sign_list", json!({"doc": doc}));
|
||||
assert_eq!(list["signatures"][0]["status"], "invalid");
|
||||
assert_eq!(list["signatures"][0]["verdict_shown"], true);
|
||||
let rendered = a.call("page_render", &json!({"doc": doc, "page": 1, "dpi": 72})).unwrap();
|
||||
let Content::Png { data, .. } = &rendered[0] else { panic!("expected a PNG") };
|
||||
let pixels = image::load_from_memory_with_format(data, image::ImageFormat::Png).unwrap().to_rgba8();
|
||||
let red = pixels.pixels().filter(|p| p.0.iter().zip([0xD7, 0x37, 0x3F]).all(|(a, b)| a.abs_diff(b) < 30)).count();
|
||||
assert!(red > 100, "the invalid state is drawn: {red} red pixels");
|
||||
ok(&mut a, "doc_save", json!({"doc": doc, "path": "saved.pdf", "full": false}));
|
||||
assert_eq!(std::fs::read(dir.join("saved.pdf")).unwrap(), original, "the drawn state never enters saves");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn digital_ids_signing_and_validation_through_tools() {
|
||||
let dir = workdir("signing");
|
||||
@@ -6879,6 +7022,8 @@ fn sign_document_and_verify_trust(a: &mut Automation, dir: &Path) -> u64 {
|
||||
assert_eq!(t["trusted"].as_array().unwrap().len(), 1);
|
||||
let list = ok(a, "sign_list", json!({ "doc": doc }));
|
||||
assert_eq!((list["all_valid"].as_bool(), list["signatures"][0]["status"].as_str()), (Some(true), Some("valid")));
|
||||
// PdfCraft's own appearance has no status layers to draw into: only the page badge shows it.
|
||||
assert_eq!(list["signatures"][0]["verdict_shown"], false);
|
||||
ok(a, "comment_add", json!({ "doc": doc, "page": 1, "type": "note", "at": [20, 20], "contents": "ok" }));
|
||||
let s = &ok(a, "sign_list", json!({ "doc": doc }))["signatures"][0];
|
||||
assert_eq!((s["status"].as_str(), s["modification"].as_str()), (Some("valid"), Some("allowed")));
|
||||
@@ -7487,6 +7632,63 @@ fn a_page_printed_in_strips_gets_small_through_tools() {
|
||||
assert!(matches!(a.call("doc_optimize", &json!({ "doc": doc, "path": "x.pdf", "preset": "tiny" })), Err(ToolError::InvalidArgs(_))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn optimizing_to_a_target_size() {
|
||||
// Dropped at the end of the test, also when an assertion fails.
|
||||
let tmp = tempfile::TempDir::new().unwrap();
|
||||
let dir = tmp.path().to_path_buf();
|
||||
let (w, h) = (2400u32, 1600u32);
|
||||
let px: Vec<u8> = (0..w * h)
|
||||
.flat_map(|i| {
|
||||
let (x, y) = (i % w, i / w);
|
||||
[(x * 255 / w) as u8 ^ ((x * y) & 15) as u8, (y * 255 / h) as u8, ((x + y) & 255) as u8]
|
||||
})
|
||||
.collect();
|
||||
let mut jpeg = Vec::new();
|
||||
let mut enc = image::codecs::jpeg::JpegEncoder::new_with_quality(&mut jpeg, 95);
|
||||
enc.set_pixel_density(image::codecs::jpeg::PixelDensity::dpi(600));
|
||||
enc.encode(&px, w, h, image::ExtendedColorType::Rgb8).unwrap();
|
||||
std::fs::write(dir.join("photo.jpg"), &jpeg).unwrap();
|
||||
let mut a = auto(&dir);
|
||||
let doc = ok(&mut a, "doc_create", json!({ "from": "images", "paths": ["photo.jpg"] }))["doc"].as_u64().unwrap();
|
||||
// Without a target nothing changes: no target fields.
|
||||
let base = ok(&mut a, "doc_optimize", json!({ "doc": doc, "path": "base.pdf" }));
|
||||
assert!(base.get("target_reached").is_none(), "{base}");
|
||||
let base_len = base["bytes_after"].as_u64().unwrap();
|
||||
// A target below the default result is met by a stronger step.
|
||||
let r = ok(&mut a, "doc_optimize", json!({ "doc": doc, "path": "fit.pdf", "target_bytes": base_len - 1 }));
|
||||
assert_eq!(r["target_reached"], true, "{r}");
|
||||
assert!(r["bytes_after"].as_u64().unwrap() < base_len, "{r}");
|
||||
assert!(r["target_settings"]["step"].as_u64().unwrap() >= 1, "{r}");
|
||||
assert_eq!(std::fs::metadata(dir.join("fit.pdf")).unwrap().len(), r["bytes_after"].as_u64().unwrap());
|
||||
// A target already met by the first attempt tries nothing more.
|
||||
let r = ok(&mut a, "doc_optimize", json!({ "doc": doc, "path": "easy.pdf", "target_bytes": base_len }));
|
||||
assert_eq!((r["target_reached"].as_bool(), r["attempts"].as_u64()), (Some(true), Some(1)), "{r}");
|
||||
// An impossible target: bounded attempts, smallest copy written, said plainly.
|
||||
let r = ok(&mut a, "doc_optimize", json!({ "doc": doc, "path": "tiny.pdf", "target_bytes": 1 }));
|
||||
assert_eq!((r["target_reached"].as_bool(), r["attempts"].as_u64()), (Some(false), Some(6)), "{r}");
|
||||
assert!(r["bytes_after"].as_u64().unwrap() < base_len, "{r}");
|
||||
assert!(std::fs::metadata(dir.join("tiny.pdf")).is_ok());
|
||||
// The open document is untouched by the failed attempts, and bad targets are refused.
|
||||
let again = ok(&mut a, "doc_optimize", json!({ "doc": doc, "path": "again.pdf" }));
|
||||
assert_eq!(again["bytes_after"].as_u64().unwrap(), base_len);
|
||||
assert!(matches!(a.call("doc_optimize", &json!({ "doc": doc, "path": "x.pdf", "target_bytes": 0 })), Err(ToolError::InvalidArgs(_))));
|
||||
// A caller who asked for lossless images keeps them: retries only tighten the ppi, no JPEG quality.
|
||||
let lossless = json!({ "compression": "zip" });
|
||||
let r = ok(&mut a, "doc_optimize", json!({ "doc": doc, "path": "zip.pdf", "color": lossless, "gray": lossless, "target_bytes": 1 }));
|
||||
assert_eq!(r["attempts"].as_u64(), Some(6), "{r}");
|
||||
assert!(r["target_settings"]["max_ppi"].is_number() && r["target_settings"]["max_jpeg_quality"].is_null(), "{r}");
|
||||
// A JPEG caller gets the quality step.
|
||||
let r = ok(&mut a, "doc_optimize", json!({ "doc": doc, "path": "jpg.pdf", "target_bytes": 1 }));
|
||||
assert!(r["target_settings"]["max_jpeg_quality"].is_number(), "{r}");
|
||||
// Settings already at the ladder's floor leave every rung equal to the first run: no retries.
|
||||
let floor = json!({ "ppi": 9, "above_ppi": 9, "compression": "jpeg", "quality": 1 });
|
||||
let r = ok(&mut a, "doc_optimize", json!({ "doc": doc, "path": "floor.pdf", "color": floor, "gray": floor, "target_bytes": 1 }));
|
||||
assert_eq!((r["target_reached"].as_bool(), r["attempts"].as_u64()), (Some(false), Some(1)), "{r}");
|
||||
// Confinement still applies.
|
||||
assert!(a.call("doc_optimize", &json!({ "doc": doc, "path": "../out.pdf", "target_bytes": 1000 })).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn initial_view_through_tools() {
|
||||
let dir = workdir("initial-view");
|
||||
@@ -8209,6 +8411,52 @@ BT /F1 11 Tf 20 20 Td (Total due: 150.00) Tj ET";
|
||||
assert!(rendered.iter().any(|c| matches!(c, Content::Png { .. })));
|
||||
}
|
||||
|
||||
/// #5149: a two-column, two-row table drawn with ruled lines reaches Word as a table with its
|
||||
/// rules, not as four paragraphs one under another.
|
||||
#[test]
|
||||
fn exporting_a_ruled_two_by_two_table_to_word_keeps_the_table() {
|
||||
let dir = workdir("ruled-table-word");
|
||||
let content = "0.5 w 20 270 m 300 270 l S 20 245 m 300 245 l S 20 220 m 300 220 l S \
|
||||
20 220 m 20 270 l S 160 220 m 160 270 l S 300 220 m 300 270 l S \
|
||||
BT /F1 11 Tf 25 253 Td (Name) Tj 140 0 Td (Value) Tj -140 -25 Td (Alpha) Tj 140 0 Td (One) Tj ET \
|
||||
BT /F1 11 Tf 20 150 Td (A paragraph after the table.) Tj ET";
|
||||
let stream = format!("<< /Length {} >>\nstream\n{content}\nendstream", content.len());
|
||||
let objs = [
|
||||
"<< /Type /Catalog /Pages 2 0 R >>",
|
||||
"<< /Type /Pages /Kids [3 0 R] /Count 1 >>",
|
||||
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 320 300] /Contents 4 0 R /Resources << /Font << /F1 5 0 R >> >> >>",
|
||||
stream.as_str(),
|
||||
"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>",
|
||||
];
|
||||
std::fs::write(dir.join("table.pdf"), pdf_of(&objs)).unwrap();
|
||||
let mut a = auto(&dir);
|
||||
let doc = ok(&mut a, "doc_open", json!({ "path": "table.pdf" }))["doc"].as_u64().unwrap();
|
||||
ok(&mut a, "doc_export_office", json!({ "doc": doc, "path": "table.docx" }));
|
||||
let zip = std::fs::read(dir.join("table.docx")).unwrap();
|
||||
let mut at = 0;
|
||||
let mut xml = String::new();
|
||||
while zip[at..].starts_with(b"PK\x03\x04") {
|
||||
let size = u32::from_le_bytes(zip[at + 18..at + 22].try_into().unwrap()) as usize;
|
||||
let len = u16::from_le_bytes(zip[at + 26..at + 28].try_into().unwrap()) as usize;
|
||||
let data = at + 30 + len;
|
||||
if &zip[at + 30..data] == b"word/document.xml" {
|
||||
std::io::Read::read_to_string(&mut flate2::read::DeflateDecoder::new(&zip[data..data + size]), &mut xml).unwrap();
|
||||
break;
|
||||
}
|
||||
at = data + size;
|
||||
}
|
||||
assert_eq!(xml.matches("<w:tbl>").count(), 1, "the ruled grid is a table: {xml}");
|
||||
let table = xml.split_once("<w:tbl>").and_then(|(_, t)| t.split_once("</w:tbl>")).map(|(t, _)| t).unwrap();
|
||||
assert_eq!(table.matches("<w:tr>").count(), 2, "{table}");
|
||||
for word in ["Name", "Value", "Alpha", "One"] {
|
||||
assert_eq!(table.matches(&format!(">{word}</w:t>")).count(), 1, "{word} is a cell: {xml}");
|
||||
assert_eq!(xml.matches(&format!(">{word}</w:t>")).count(), 1, "{word} is written once");
|
||||
}
|
||||
assert!(table.contains("w:val=\"single\""), "the drawn rules become borders: {table}");
|
||||
assert!(!table.contains("A paragraph after the table."));
|
||||
assert_eq!(xml.matches(">A paragraph after the table.</w:t>").count(), 1);
|
||||
}
|
||||
|
||||
/// #4158: a word set in italic inside a sentence ("Before *Chevron* after.") reaches Word as an
|
||||
/// italic run of the sentence's paragraph, not as a paragraph of its own between two halves.
|
||||
#[test]
|
||||
@@ -9311,27 +9559,15 @@ fn a_deleted_image_is_not_kept_by_reduce_or_optimize() {
|
||||
/// page is turned with /Rotate 90.
|
||||
fn table_pdf() -> Vec<u8> {
|
||||
let body = "BT /F1 12 Tf 20 250 Td (Name) Tj 130 0 Td (Qty) Tj -130 -20 Td (Apple) Tj 130 0 Td (12) Tj -130 -20 Td (Pear) Tj 130 0 Td (7) Tj ET";
|
||||
let objs = [
|
||||
"<< /Type /Catalog /Pages 2 0 R >>".to_string(),
|
||||
"<< /Type /Pages /Kids [4 0 R 5 0 R] /Count 2 /MediaBox [0 0 300 300] >>".to_string(),
|
||||
"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>".to_string(),
|
||||
"<< /Type /Page /Parent 2 0 R /Contents 6 0 R /Resources << /Font << /F1 3 0 R >> >> >>".to_string(),
|
||||
"<< /Type /Page /Parent 2 0 R /Rotate 90 /Contents 6 0 R /Resources << /Font << /F1 3 0 R >> >> >>".to_string(),
|
||||
format!("<< /Length {} >>\nstream\n{body}\nendstream", body.len()),
|
||||
];
|
||||
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
|
||||
let stream = format!("<< /Length {} >>\nstream\n{body}\nendstream", body.len());
|
||||
pdf_of(&[
|
||||
"<< /Type /Catalog /Pages 2 0 R >>",
|
||||
"<< /Type /Pages /Kids [4 0 R 5 0 R] /Count 2 /MediaBox [0 0 300 300] >>",
|
||||
"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>",
|
||||
"<< /Type /Page /Parent 2 0 R /Contents 6 0 R /Resources << /Font << /F1 3 0 R >> >> >>",
|
||||
"<< /Type /Page /Parent 2 0 R /Rotate 90 /Contents 6 0 R /Resources << /Font << /F1 3 0 R >> >> >>",
|
||||
&stream,
|
||||
])
|
||||
}
|
||||
|
||||
/// Issue #740: `text_extract` with `rect` takes what Column select takes, in the displayed-page
|
||||
@@ -9372,6 +9608,56 @@ fn text_extract_with_a_rect_takes_one_column() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Copy with formatting, headless: `format: "html"` adds each page's text as the HTML fragment
|
||||
/// Copy puts on the clipboard, for the whole page or only what `rect` takes.
|
||||
#[test]
|
||||
fn text_extract_as_html_keeps_the_formatting() {
|
||||
let dir = workdir("rich-copy");
|
||||
std::fs::write(dir.join("table.pdf"), table_pdf()).unwrap();
|
||||
let mut a = auto(&dir);
|
||||
let doc = ok(&mut a, "doc_open", json!({ "path": "table.pdf" }))["doc"].as_u64().unwrap();
|
||||
let page = &ok(&mut a, "text_extract", json!({ "doc": doc, "pages": [1], "format": "html" }))["pages"][0];
|
||||
let html = page["html"].as_str().unwrap();
|
||||
assert!(html.starts_with("<p style=\"margin:0\"><span style=\"font-family:'Helvetica';font-size:12pt\">Name"), "{html}");
|
||||
assert!(html.contains("Pear") && html.contains("Qty"), "{html}");
|
||||
assert_eq!(page["text"], "Name\nApple\nPear\nQty\n12\n7", "the plain text is unchanged");
|
||||
assert_eq!(page["styles_incomplete"], false);
|
||||
// Plain text by default: no html key.
|
||||
assert!(ok(&mut a, "text_extract", json!({ "doc": doc, "pages": [1] }))["pages"][0].get("html").is_none());
|
||||
// Only what the rect takes; nothing inside gives empty HTML.
|
||||
let column = ok(&mut a, "text_extract", json!({ "doc": doc, "pages": [1], "rect": [120, 0, 300, 300], "format": "html" }));
|
||||
let html = column["pages"][0]["html"].as_str().unwrap();
|
||||
assert!(html.contains("Qty") && !html.contains("Name"), "{html}");
|
||||
let none = ok(&mut a, "text_extract", json!({ "doc": doc, "pages": [1], "rect": [0, 0, 5, 5], "format": "html" }));
|
||||
assert_eq!(none["pages"][0]["html"], "");
|
||||
// An unknown format is refused.
|
||||
for bad in [json!("rtf"), json!(1)] {
|
||||
let e = a.call("text_extract", &json!({ "doc": doc, "format": bad })).unwrap_err();
|
||||
assert!(matches!(e, ToolError::InvalidArgs(_)), "{bad}: {e}");
|
||||
}
|
||||
// Bold, italic, colour and size come through end to end.
|
||||
let body = "BT /F1 18 Tf 20 250 Td (Big) Tj ET BT /F2 12 Tf 20 200 Td (Strong) Tj ET \
|
||||
BT /F3 12 Tf 20 150 Td (Slanted) Tj ET BT 0 0 1 rg /F1 12 Tf 20 100 Td (Blue) Tj ET";
|
||||
let stream = format!("<< /Length {} >>\nstream\n{body}\nendstream", body.len());
|
||||
let styled = pdf_of(&[
|
||||
"<< /Type /Catalog /Pages 2 0 R >>",
|
||||
"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 300 300] >>",
|
||||
"<< /Type /Page /Parent 2 0 R /Contents 4 0 R /Resources << /Font << /F1 5 0 R /F2 6 0 R /F3 7 0 R >> >> >>",
|
||||
&stream,
|
||||
"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>",
|
||||
"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica-Bold >>",
|
||||
"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica-Oblique >>",
|
||||
]);
|
||||
std::fs::write(dir.join("styled.pdf"), styled).unwrap();
|
||||
let doc = ok(&mut a, "doc_open", json!({ "path": "styled.pdf" }))["doc"].as_u64().unwrap();
|
||||
let page = &ok(&mut a, "text_extract", json!({ "doc": doc, "format": "html" }))["pages"][0];
|
||||
let html = page["html"].as_str().unwrap();
|
||||
assert!(html.contains("font-size:18pt\">Big"), "{html}");
|
||||
assert!(html.contains("<strong>Strong</strong>"), "{html}");
|
||||
assert!(html.contains("<em>Slanted</em>"), "{html}");
|
||||
assert!(html.contains("color:#0000FF\">Blue"), "{html}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mixed_visual_region_edit_preview_save_reopen_and_undo_through_tools() {
|
||||
use pdfcraft_cos::{Dict, Document, Object, Stream, write_incremental};
|
||||
@@ -10928,6 +11214,154 @@ fn a_callouts_parts_are_listed_and_changed_through_the_tools() {
|
||||
assert!(near(&auto["points"][1], &[288.0, 220.0]), "{auto}");
|
||||
}
|
||||
|
||||
/// #3005: a table and a small signature drawn inside one transparency-group Form XObject (how
|
||||
/// HTML-to-PDF converters write a block with a translucent picture). Edit a PDF sees one piece
|
||||
/// of artwork and no text; `image_edit ungroup` draws it in place with the same pixels, its
|
||||
/// text becomes paragraphs that `text_edit` changes, and undo brings the form back.
|
||||
fn table_in_a_form_pdf() -> Vec<u8> {
|
||||
let table = b"BT /F1 12 Tf 1 0 0 1 20 120 Tm (Revenue) Tj 1 0 0 1 120 120 Tm (153,300.00) Tj 1 0 0 1 20 100 Tm (Costs) Tj 1 0 0 1 120 100 Tm (382,110.00) Tj ET 0.6 G 0.5 w 15 115 m 220 115 l S";
|
||||
// Two pictures with soft masks overlapping each other, the second also over the table's
|
||||
// last cell: a translucent wash, and a picture whose corner pixels are see-through.
|
||||
let inner = [&table[..], b" q 40 0 0 20 30 40 cm /Sig Do Q q 60 0 0 40 50 30 cm /Wash Do Q q 100 0 0 30 110 90 cm /Sig Do Q"].concat();
|
||||
let rgb: Vec<u8> = std::iter::repeat_n([20u8, 60, 220], 16).flatten().collect();
|
||||
let alpha: Vec<u8> = (0..16).map(|i| if i % 3 == 0 { 255 } else { 0 }).collect();
|
||||
let page = b"q /Fm1 Do Q";
|
||||
let stream = |dict: &str, data: &[u8]| [format!("{dict} /Length {} >>\nstream\n", data.len()).as_bytes(), data, b"\nendstream"].concat();
|
||||
let objs: Vec<Vec<u8>> = vec![
|
||||
b"<< /Type /Catalog /Pages 2 0 R >>".to_vec(),
|
||||
b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_vec(),
|
||||
b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 240 160] /Contents 4 0 R /Resources << /XObject << /Fm1 5 0 R >> >> >>".to_vec(),
|
||||
stream("<<", page),
|
||||
stream(
|
||||
"<< /Type /XObject /Subtype /Form /BBox [0 0 240 160] /Group << /S /Transparency /CS /DeviceRGB >> /Resources << /Font << /F1 6 0 R >> /XObject << /Sig 7 0 R /Wash 9 0 R >> >>",
|
||||
&inner,
|
||||
),
|
||||
b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>".to_vec(),
|
||||
stream("<< /Type /XObject /Subtype /Image /Width 4 /Height 4 /ColorSpace /DeviceRGB /BitsPerComponent 8 /SMask 8 0 R", &rgb),
|
||||
stream("<< /Type /XObject /Subtype /Image /Width 4 /Height 4 /ColorSpace /DeviceGray /BitsPerComponent 8", &alpha),
|
||||
stream(
|
||||
"<< /Type /XObject /Subtype /Image /Width 2 /Height 2 /ColorSpace /DeviceRGB /BitsPerComponent 8 /SMask 10 0 R",
|
||||
&[230, 40, 40].repeat(4),
|
||||
),
|
||||
stream("<< /Type /XObject /Subtype /Image /Width 2 /Height 2 /ColorSpace /DeviceGray /BitsPerComponent 8", &[128, 96, 160, 64]),
|
||||
];
|
||||
let mut out = b"%PDF-1.7\n".to_vec();
|
||||
let mut offsets = Vec::new();
|
||||
for (i, o) in objs.iter().enumerate() {
|
||||
offsets.push(out.len());
|
||||
out.extend_from_slice(format!("{} 0 obj\n", i + 1).as_bytes());
|
||||
out.extend_from_slice(o);
|
||||
out.extend_from_slice(b"\nendobj\n");
|
||||
}
|
||||
let xref = out.len();
|
||||
out.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objs.len() + 1).as_bytes());
|
||||
for o in offsets {
|
||||
out.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes());
|
||||
}
|
||||
out.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objs.len() + 1).as_bytes());
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ungrouping_a_table_drawn_in_a_form_makes_its_text_editable() {
|
||||
let dir = workdir("ungroup");
|
||||
std::fs::write(dir.join("table.pdf"), table_in_a_form_pdf()).unwrap();
|
||||
let mut a = auto(&dir);
|
||||
let doc = ok(&mut a, "doc_open", json!({ "path": "table.pdf" }))["doc"].as_u64().unwrap();
|
||||
let paragraphs = |a: &mut Automation| ok(a, "text_paragraphs", json!({ "doc": doc, "page": 1 }))["paragraphs"].as_array().unwrap().len();
|
||||
let objects = |a: &mut Automation| ok(a, "object_list", json!({ "doc": doc, "page": 1 }))["objects"].as_array().unwrap().len();
|
||||
assert_eq!((paragraphs(&mut a), objects(&mut a)), (0, 1), "one piece of artwork, no text");
|
||||
let (w, h, before) = a.render_pixels(doc, 1, 2.0).unwrap();
|
||||
|
||||
ok(&mut a, "image_edit", json!({ "doc": doc, "page": 1, "image": 1, "action": "ungroup" }));
|
||||
let (w2, h2, after) = a.render_pixels(doc, 1, 2.0).unwrap();
|
||||
assert_eq!((w, h), (w2, h2));
|
||||
let differing = before.as_ref().as_chunks::<4>().0.iter().zip(after.as_ref().as_chunks::<4>().0).filter(|(p, q)| p != q).count();
|
||||
assert_eq!(differing, 0, "ungrouping draws the same pixels");
|
||||
assert!(paragraphs(&mut a) >= 4, "the table's text is page text now");
|
||||
let images = ok(&mut a, "page_images", json!({ "doc": doc, "page": 1 }));
|
||||
let kinds: Vec<_> = images["images"].as_array().unwrap().iter().map(|i| i["kind"].clone()).collect();
|
||||
assert_eq!(kinds, vec![json!("image"); 3], "the pictures are separate pictures now: {images}");
|
||||
|
||||
let list = ok(&mut a, "text_paragraphs", json!({ "doc": doc, "page": 1 }));
|
||||
let target =
|
||||
list["paragraphs"].as_array().unwrap().iter().find(|p| p["text"].as_str().is_some_and(|t| t.contains("382,110.00"))).unwrap()["paragraph"]
|
||||
.clone();
|
||||
ok(&mut a, "text_edit", json!({ "doc": doc, "page": 1, "paragraph": target, "text": "400,000.00" }));
|
||||
let text = ok(&mut a, "text_extract", json!({ "doc": doc, "pages": [1] }));
|
||||
let s = text.to_string();
|
||||
assert!(s.contains("400,000.00") && !s.contains("382,110.00"), "{s}");
|
||||
|
||||
ok(&mut a, "edit_undo", json!({ "doc": doc }));
|
||||
ok(&mut a, "edit_undo", json!({ "doc": doc }));
|
||||
assert_eq!((paragraphs(&mut a), objects(&mut a)), (0, 1), "undo brings the form back");
|
||||
}
|
||||
|
||||
/// One 300 × 300 page that draws form `Fm1` with `page_do`; the form (with `matrix`) fills with
|
||||
/// pattern `/P1` (`pattern`) in `content`, and a red outline on the page marks where it lands.
|
||||
fn pattern_in_a_form_pdf(page_do: &str, matrix: &str, content: &str, pattern: &str) -> Vec<u8> {
|
||||
let objs = [
|
||||
"<< /Type /Catalog /Pages 2 0 R >>".to_string(),
|
||||
"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_string(),
|
||||
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 300] /Contents 4 0 R /Resources << /XObject << /Fm1 5 0 R >> >> >>".to_string(),
|
||||
stream_object("<<", &format!("{page_do} 1 0 0 RG 1 w 60 60 180 180 re S")),
|
||||
stream_object(&format!("<< /Type /XObject /Subtype /Form /BBox [0 0 300 300] {matrix} /Resources << /Pattern << /P1 6 0 R >> >>"), content),
|
||||
pattern.to_string(),
|
||||
];
|
||||
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
|
||||
}
|
||||
|
||||
/// #3067 review: a pattern's matrix maps pattern space to the default space of the stream that
|
||||
/// uses it (ISO 32000-2 §8.7.2), so a pattern filled inside a form moved by its `/Matrix` or by a
|
||||
/// `cm` before the `Do` must stay where it was when the form is drawn inline. Each case draws
|
||||
/// differently in Acrobat when the placement is lost (tiles out of phase or half size, the
|
||||
/// shading outside its box); ungrouped, every one paints the same pixels.
|
||||
#[test]
|
||||
fn ungrouping_keeps_patterns_where_the_forms_placement_put_them() {
|
||||
let tiling = stream_object(
|
||||
"<< /Type /Pattern /PatternType 1 /PaintType 1 /TilingType 1 /BBox [0 0 20 20] /XStep 20 /YStep 20 /Resources << >>",
|
||||
"0 0 0 rg 0 0 10 10 re f 10 10 10 10 re f",
|
||||
);
|
||||
let shading = "<< /Type /Pattern /PatternType 2 /Shading << /ShadingType 2 /ColorSpace /DeviceRGB /Coords [0 0 100 0] /Function << /FunctionType 2 /Domain [0 1] /C0 [1 0 0] /C1 [0 0 1] /N 1 >> /Extend [false false] >> >>";
|
||||
let cases = [
|
||||
("no placement", "q /Fm1 Do Q", "", "/Pattern cs /P1 scn 60 60 180 180 re f", tiling.as_str()),
|
||||
("form Matrix, half a tile", "q /Fm1 Do Q", "/Matrix [1 0 0 1 10 0]", "/Pattern cs /P1 scn 50 60 180 180 re f", tiling.as_str()),
|
||||
("cm doubling the form", "q 2 0 0 2 0 0 cm /Fm1 Do Q", "", "/Pattern cs /P1 scn 30 30 90 90 re f", tiling.as_str()),
|
||||
("shading moved by the form Matrix", "q /Fm1 Do Q", "/Matrix [1 0 0 1 100 100]", "/Pattern cs /P1 scn 0 0 100 100 re f", shading),
|
||||
];
|
||||
for (what, page_do, matrix, content, pattern) in cases {
|
||||
let dir = workdir("ungroup_patterns");
|
||||
std::fs::write(dir.join("p.pdf"), pattern_in_a_form_pdf(page_do, matrix, content, pattern)).unwrap();
|
||||
let mut a = auto(&dir);
|
||||
let doc = ok(&mut a, "doc_open", json!({ "path": "p.pdf" }))["doc"].as_u64().unwrap();
|
||||
let (w, h, before) = a.render_pixels(doc, 1, 1.0).unwrap();
|
||||
ok(&mut a, "image_edit", json!({ "doc": doc, "page": 1, "image": 1, "action": "ungroup" }));
|
||||
ok(&mut a, "doc_save", json!({ "doc": doc, "path": "out.pdf" }));
|
||||
let saved = ok(&mut a, "doc_open", json!({ "path": "out.pdf" }))["doc"].as_u64().unwrap();
|
||||
let (w2, h2, after) = a.render_pixels(saved, 1, 1.0).unwrap();
|
||||
assert_eq!((w, h), (w2, h2), "{what}");
|
||||
let differing = before.as_ref().as_chunks::<4>().0.iter().zip(after.as_ref().as_chunks::<4>().0).filter(|(p, q)| p != q).count();
|
||||
assert_eq!(differing, 0, "{what}: ungrouping draws the same pixels, saved and reopened");
|
||||
}
|
||||
}
|
||||
|
||||
/// An indirect stream object: `dict` (without its closing `>>`) and `data`.
|
||||
fn stream_object(dict: &str, data: &str) -> String {
|
||||
format!("{dict} /Length {} >>\nstream\n{data}\nendstream", data.len())
|
||||
}
|
||||
|
||||
/// Reviewing headlessly: corrections keep the boxes, a stale or foreign review is refused, and
|
||||
/// applying consumes the handle (the pages already accepted were applied once).
|
||||
#[test]
|
||||
|
||||
@@ -238,3 +238,61 @@ fn mcp_batch_errors_keep_the_structured_per_file_report() {
|
||||
assert_eq!(report["result"]["isError"], true, "{report}");
|
||||
assert_eq!(report["result"]["structuredContent"]["failed"], 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dry_run_planned_files_are_not_counted_as_skipped() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
std::fs::create_dir_all(dir.path().join("input/sub")).unwrap();
|
||||
std::fs::create_dir_all(dir.path().join("out")).unwrap();
|
||||
let original = pdf();
|
||||
std::fs::write(dir.path().join("input/a.pdf"), &original).unwrap();
|
||||
std::fs::write(dir.path().join("input/sub/a.pdf"), &original).unwrap();
|
||||
std::fs::write(dir.path().join("out/a.pdf"), b"precious").unwrap();
|
||||
let mut auto = Automation::new().with_root(dir.path()).unwrap();
|
||||
let report = result(&mut auto, json!({"paths":["input","input/sub"],"steps":["optimize"],"out_dir":"out","dry_run":true}));
|
||||
assert_eq!(report["dry_run"], true, "{report}");
|
||||
assert_eq!(report["completed"], 0, "{report}");
|
||||
assert_eq!(report["failed"], 0, "{report}");
|
||||
assert_eq!(report["skipped"], 0, "planned files are not skipped: {report}");
|
||||
let files = report["files"].as_array().unwrap();
|
||||
assert_eq!(files.len(), 2, "{report}");
|
||||
assert!(files.iter().all(|file| file["status"] == "planned"), "{report}");
|
||||
assert!(files.iter().all(|file| file["steps"] == json!(["optimize"])), "planned files list the ordered steps: {report}");
|
||||
assert!(files[0]["output"].as_str().unwrap().ends_with("out/a (2).pdf"), "existing output gets the publish collision name: {report}");
|
||||
assert!(files[1]["output"].as_str().unwrap().ends_with("out/a (3).pdf"), "later planned files reserve their names: {report}");
|
||||
assert_eq!(std::fs::read(dir.path().join("out/a.pdf")).unwrap(), b"precious");
|
||||
assert!(!dir.path().join("out/a (2).pdf").exists(), "dry run writes nothing: {report}");
|
||||
#[cfg(unix)]
|
||||
{
|
||||
// An output subfolder that resolves outside out_dir is a per-file error:
|
||||
// it counts as failed, honors stop_on_error, and later files are skipped.
|
||||
for outside_root in [false, true] {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let outside = tempfile::tempdir().unwrap();
|
||||
std::fs::create_dir_all(dir.path().join("input/sub")).unwrap();
|
||||
std::fs::create_dir_all(dir.path().join("out")).unwrap();
|
||||
std::fs::write(dir.path().join("input/a.pdf"), pdf()).unwrap();
|
||||
std::fs::write(dir.path().join("input/sub/page.pdf"), pdf()).unwrap();
|
||||
std::fs::write(dir.path().join("input/z.pdf"), pdf()).unwrap();
|
||||
let target = if outside_root { outside.path().to_path_buf() } else { dir.path().join("outside") };
|
||||
if !outside_root {
|
||||
std::fs::create_dir(&target).unwrap();
|
||||
}
|
||||
std::os::unix::fs::symlink(&target, dir.path().join("out/sub")).unwrap();
|
||||
let mut auto = Automation::new().with_root(dir.path()).unwrap();
|
||||
let report = result(
|
||||
&mut auto,
|
||||
json!({"paths":["input"],"steps":["optimize"],"out_dir":"out","recursive":true,"dry_run":true,"stop_on_error":true}),
|
||||
);
|
||||
assert_eq!(report["failed"], 1, "preview target failure is per-file: {report}");
|
||||
assert_eq!(report["stopped"], true, "{report}");
|
||||
assert_eq!(report["skipped"], 1, "only the unprocessed file is skipped: {report}");
|
||||
let files = report["files"].as_array().unwrap();
|
||||
assert_eq!(files.len(), 3, "{report}");
|
||||
assert_eq!(files[0]["status"], "planned", "{report}");
|
||||
assert_eq!(files[1]["status"], "error", "{report}");
|
||||
assert_eq!(files[2]["status"], "skipped", "stop_on_error leaves later files unplanned: {report}");
|
||||
assert!(!dir.path().join("out/a.pdf").exists(), "dry run writes nothing: {report}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -17,3 +17,4 @@ mod optimize_content_boundaries;
|
||||
mod redact_after_stray_q_form;
|
||||
mod redact_text_after_q;
|
||||
mod render_warnings;
|
||||
mod unreadable_objects;
|
||||
@@ -0,0 +1,64 @@
|
||||
//! `doc_info` lists the objects of a file that could not be read: each reads as null, so the file
|
||||
//! opens, but what it held is lost and nothing was repaired.
|
||||
|
||||
use pdfcraft_automation::{Automation, Content};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
/// A one-page PDF whose document information dictionary (object 4) is `info`.
|
||||
fn with_info(info: &str) -> Vec<u8> {
|
||||
let bodies = [
|
||||
"<< /Type /Catalog /Pages 2 0 R >>",
|
||||
"<< /Type /Pages /Kids [3 0 R] /Count 1 >>",
|
||||
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] >>",
|
||||
info,
|
||||
];
|
||||
let mut out = b"%PDF-1.7\n".to_vec();
|
||||
let mut offsets = Vec::new();
|
||||
for (i, body) in bodies.iter().enumerate() {
|
||||
offsets.push(out.len());
|
||||
out.extend_from_slice(format!("{} 0 obj\n{body}\nendobj\n", i + 1).as_bytes());
|
||||
}
|
||||
let xref = out.len();
|
||||
out.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", bodies.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 /Info 4 0 R >>\nstartxref\n{xref}\n%%EOF\n", bodies.len() + 1).as_bytes());
|
||||
out
|
||||
}
|
||||
|
||||
fn info_of(a: &mut Automation, path: &str) -> Value {
|
||||
let doc = match a.call("doc_open", &json!({ "path": path })).unwrap().remove(0) {
|
||||
Content::Json(v) => v["doc"].as_u64().unwrap(),
|
||||
other => panic!("expected JSON: {other:?}"),
|
||||
};
|
||||
match a.call("doc_info", &json!({ "doc": doc })).unwrap().remove(0) {
|
||||
Content::Json(v) => v,
|
||||
other => panic!("expected JSON: {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// An unparseable `/Info` is listed with its number and why, the rest of the file reads, and
|
||||
/// nothing is reported as repaired.
|
||||
#[test]
|
||||
fn doc_info_lists_an_object_that_could_not_be_read() {
|
||||
let dir = std::env::temp_dir().join(format!("pdfcraft-unreadable-objects-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
std::fs::write(dir.join("broken.pdf"), with_info("<< /Title (Report) /Author ) >>")).unwrap();
|
||||
std::fs::write(dir.join("sound.pdf"), with_info("<< /Title (Report) >>")).unwrap();
|
||||
let mut a = Automation::new().with_root(&dir).unwrap();
|
||||
|
||||
let info = info_of(&mut a, "broken.pdf");
|
||||
let lines = info["unreadable_objects"].as_array().unwrap();
|
||||
assert_eq!(lines.len(), 1, "{info}");
|
||||
let line = lines[0].as_str().unwrap();
|
||||
assert!(line.starts_with("object 4 0 could not be read: syntax error"), "{line}");
|
||||
assert_eq!(info["repairs"], json!([]), "nothing was repaired");
|
||||
assert_eq!(info["pages"].as_array().unwrap().len(), 1, "the rest of the file reads");
|
||||
|
||||
let info = info_of(&mut a, "sound.pdf");
|
||||
assert_eq!(info["unreadable_objects"], json!([]), "{info}");
|
||||
assert_eq!(info["title"], "Report");
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
+189
-36
@@ -11,7 +11,9 @@ use crate::{CosError, Document, ObjRef, Object, Stream};
|
||||
/// 16 ns, so this is 2 to 5 minutes, and about as long again for what an operation does with the
|
||||
/// pixels. A page scanned at 300 dpi takes about 17 million, 8.4 for its pixels and that again to
|
||||
/// decode them, so this alone reads about 1,000 of them. A byte into or out of a filter is a step
|
||||
/// too, and takes less: 3 ns at most, or up to 19 ns through a predictor on samples of a bit.
|
||||
/// too, and takes less: 3 ns at most, or up to 19 ns through a predictor on samples of a bit. A
|
||||
/// byte Flate reads is [`pdfcraft_filters::FLATE_READ_WORK`] steps besides, since inflating blocks
|
||||
/// that make nothing takes up to 21 ns a byte: about 7 ns a step.
|
||||
const IMAGE_WORK: u64 = 1 << 34;
|
||||
/// The steps each byte of the file adds to [`IMAGE_WORK`], so that a long scan is read whole: such a
|
||||
/// page pays for itself with about 2 KB of the file, about the smallest a page of text is stored
|
||||
@@ -38,9 +40,9 @@ const JPEG_WORK: u64 = 2;
|
||||
/// and images can share one, so reading it again for each has to count.
|
||||
const JPEG_READ_WORK: u64 = 4;
|
||||
|
||||
/// A stream decode within a byte bound, with the bytes its filter stages decoded: the data or
|
||||
/// the error, each with that count.
|
||||
type Decoder = fn(&Stream, usize) -> Result<(Vec<u8>, usize), (FilterError, usize)>;
|
||||
/// A stream decode within a byte bound, with the bytes its filter stages decoded: the data and
|
||||
/// whether it stopped at damage, or the error, each with that count.
|
||||
type Decoder = fn(&Stream, usize) -> Result<(Vec<u8>, bool, usize), (FilterError, usize)>;
|
||||
|
||||
/// What one operation over a document's images may still spend decoding them: exporting them,
|
||||
/// optimizing them, and storing LZW streams with Flate as it does, clearing them for redaction.
|
||||
@@ -263,45 +265,57 @@ impl DecodeBudget {
|
||||
}
|
||||
|
||||
/// `stream` decoded like [`Stream::decoded`], charged to the allowance. Fails, without
|
||||
/// decoding, once the allowance is spent.
|
||||
/// decoding, once the allowance is spent. A stream damaged partway gives what decoded before
|
||||
/// the damage, so code that writes the stream back reads it with
|
||||
/// [`DecodeBudget::decode_with_damage`] instead.
|
||||
pub fn decode(&mut self, stream: &Stream) -> Result<Vec<u8>, CosError> {
|
||||
self.charge(stream, usize::MAX, Stream::decoded_within_counted)
|
||||
self.charge(stream, usize::MAX, Stream::decoded_within_counted).map(|(data, _)| data)
|
||||
}
|
||||
|
||||
/// Like [`DecodeBudget::decode`], for a stream with a tighter bound of its own: decoding
|
||||
/// past `max` bytes is an error that charges `max`, the work it took to find out.
|
||||
pub fn decode_within(&mut self, stream: &Stream, max: usize) -> Result<Vec<u8>, CosError> {
|
||||
self.charge(stream, max, Stream::decoded_within_counted)
|
||||
self.charge(stream, max, Stream::decoded_within_counted).map(|(data, _)| data)
|
||||
}
|
||||
|
||||
/// [`DecodeBudget::decode_within`] (`usize::MAX` for no bound of its own), with the stream's
|
||||
/// `/DecodeParms` given by reference read in `doc`, also saying whether the stream is damaged:
|
||||
/// `true` when a filter stopped at corrupt data, so the bytes are only what decoded before it.
|
||||
/// A stream written back from them loses everything after the damage, which other readers may
|
||||
/// still read.
|
||||
pub fn decode_with_damage(&mut self, doc: &Document, stream: &Stream, max: usize) -> Result<(Vec<u8>, bool), CosError> {
|
||||
self.charge(&doc.decoding_view(stream), max, Stream::decoded_within_counted)
|
||||
}
|
||||
|
||||
/// `stream` decoded like [`Stream::decoded_strict`] (any corruption is an error), charged to
|
||||
/// the allowance.
|
||||
pub fn decode_strict(&mut self, stream: &Stream) -> Result<Vec<u8>, CosError> {
|
||||
self.charge(stream, usize::MAX, Stream::decoded_strict_within_counted)
|
||||
/// the allowance, with its `/DecodeParms` given by reference read in `doc`.
|
||||
pub fn decode_strict(&mut self, doc: &Document, stream: &Stream) -> Result<Vec<u8>, CosError> {
|
||||
let strict: Decoder = |s, max| s.decoded_strict_within_counted(max).map(|(data, spent)| (data, false, spent));
|
||||
self.charge(&doc.decoding_view(stream), usize::MAX, strict).map(|(data, _)| data)
|
||||
}
|
||||
|
||||
/// Decodes `stream` within `max` and the allowance, charging what every filter stage
|
||||
/// decoded: a stage's output counts even when a later stage shrinks it, and a corrupt stream
|
||||
/// pays for the bytes decoded before the error, so referencing a stream again and again
|
||||
/// spends the allowance by the work each decode does.
|
||||
fn charge(&mut self, stream: &Stream, max: usize, decode: Decoder) -> Result<Vec<u8>, CosError> {
|
||||
fn charge(&mut self, stream: &Stream, max: usize, decode: Decoder) -> Result<(Vec<u8>, bool), CosError> {
|
||||
if self.bytes == 0 && !stream.raw.is_empty() {
|
||||
return Err(CosError::Filter(FilterError::LimitExceeded(self.limit).to_string()));
|
||||
}
|
||||
if max < self.bytes {
|
||||
let result = decode(stream, max);
|
||||
let spent = match &result {
|
||||
Ok((_, spent)) => *spent,
|
||||
Ok((_, _, spent)) => *spent,
|
||||
Err((FilterError::LimitExceeded(_), _)) => max,
|
||||
Err((_, spent)) => *spent,
|
||||
};
|
||||
self.bytes = self.bytes.saturating_sub(spent);
|
||||
return result.map(|(data, _)| data).map_err(|(e, _)| CosError::Filter(e.to_string()));
|
||||
return result.map(|(data, damaged, _)| (data, damaged)).map_err(|(e, _)| CosError::Filter(e.to_string()));
|
||||
}
|
||||
match decode(stream, self.bytes) {
|
||||
Ok((data, spent)) => {
|
||||
Ok((data, damaged, spent)) => {
|
||||
self.bytes = self.bytes.saturating_sub(spent);
|
||||
Ok(data)
|
||||
Ok((data, damaged))
|
||||
}
|
||||
Err((FilterError::LimitExceeded(_), _)) => {
|
||||
self.bytes = 0;
|
||||
@@ -332,17 +346,24 @@ impl DecodeBudget {
|
||||
self.seen.insert(r)
|
||||
}
|
||||
|
||||
/// Each stream `contents` names, decoded against the allowance, in order. `contents` is a
|
||||
/// page's `/Contents`: one stream, or an array whose non-stream entries are left out.
|
||||
/// A stream that fails to decode, or arrives after the allowance is spent, is an `Err` in its
|
||||
/// place, so the caller chooses between skipping it and giving up.
|
||||
/// Each stream `contents` names, decoded against the allowance, in order, its `/DecodeParms`
|
||||
/// given by reference read in `doc`. `contents` is a page's `/Contents`: one stream, or an
|
||||
/// array whose non-stream entries are left out. A stream that fails to decode, or arrives
|
||||
/// after the allowance is spent, is an `Err` in its place, so the caller chooses between
|
||||
/// skipping it and giving up.
|
||||
pub fn decode_contents(&mut self, doc: &Document, contents: &Object) -> Vec<Result<Vec<u8>, CosError>> {
|
||||
self.decode_contents_with_damage(doc, contents).into_iter().map(|read| read.map(|(data, _)| data)).collect()
|
||||
}
|
||||
|
||||
/// [`DecodeBudget::decode_contents`], each stream also saying whether it is damaged partway
|
||||
/// ([`DecodeBudget::decode_with_damage`], which reads `/DecodeParms` given by reference).
|
||||
pub fn decode_contents_with_damage(&mut self, doc: &Document, contents: &Object) -> Vec<Result<(Vec<u8>, bool), CosError>> {
|
||||
match &*doc.resolve(contents) {
|
||||
Object::Stream(s) => vec![self.decode(s)],
|
||||
Object::Stream(s) => vec![self.decode_with_damage(doc, s, usize::MAX)],
|
||||
Object::Array(list) => list
|
||||
.iter()
|
||||
.filter_map(|entry| match &*doc.resolve(entry) {
|
||||
Object::Stream(s) => Some(self.decode(s)),
|
||||
Object::Stream(s) => Some(self.decode_with_damage(doc, s, usize::MAX)),
|
||||
_ => None,
|
||||
})
|
||||
.collect(),
|
||||
@@ -367,6 +388,11 @@ mod image_tests {
|
||||
Stream::from_raw(dict, pdfcraft_filters::encode_jbig2_generic(&[0xFF; 4], 16, 2).unwrap())
|
||||
}
|
||||
|
||||
/// What a Flate stage pays to read `n` bytes, besides what it makes.
|
||||
fn read(n: usize) -> u64 {
|
||||
pdfcraft_filters::FLATE_READ_WORK * n as u64
|
||||
}
|
||||
|
||||
/// Each image spends what it took from one allowance, and those past it are refused and
|
||||
/// counted, whatever their filters. What can't be decoded here costs nothing, and fails
|
||||
/// without being one of these.
|
||||
@@ -413,7 +439,7 @@ mod image_tests {
|
||||
let mut dict = Dict::new();
|
||||
dict.set(b"Filter".to_vec(), Object::Array(vec![Object::name("FlateDecode"), Object::name("FlateDecode")]));
|
||||
let bomb = Stream::from_raw(dict, pdfcraft_filters::encode_flate(&inner));
|
||||
let cost = (bomb.raw.len() + inner.len() + samples.len()) as u64;
|
||||
let cost = (bomb.raw.len() + inner.len() + samples.len()) as u64 + read(bomb.raw.len()) + read(inner.len());
|
||||
let mut budget = ImageBudget::with_work(2 * cost + 1);
|
||||
for left in [cost + 1, 1] {
|
||||
assert_eq!(budget.decode(&doc, &bomb, 1 << 20).unwrap(), samples);
|
||||
@@ -442,17 +468,17 @@ mod image_tests {
|
||||
let image = behind(pdfcraft_filters::encode_flate(&alone.raw));
|
||||
let mut budget = ImageBudget::with_work(u64::MAX);
|
||||
assert_eq!(budget.decode(&doc, &image, 1 << 20).unwrap(), samples);
|
||||
assert_eq!(u64::MAX - budget.work_left(), decoding + (image.raw.len() + alone.raw.len()) as u64);
|
||||
assert_eq!(u64::MAX - budget.work_left(), decoding + (image.raw.len() + alone.raw.len()) as u64 + read(image.raw.len()));
|
||||
|
||||
// Past this image's limit: an error, with what finding out took paid and the rest left.
|
||||
let bomb = behind(pdfcraft_filters::encode_flate(&vec![0; 1 << 16]));
|
||||
let mut budget = ImageBudget::with_work(u64::MAX);
|
||||
assert!(budget.decode(&doc, &bomb, 1000).is_err());
|
||||
assert_eq!(u64::MAX - budget.work_left(), bomb.raw.len() as u64 + 1000);
|
||||
assert_eq!(u64::MAX - budget.work_left(), bomb.raw.len() as u64 + read(bomb.raw.len()) + 1000);
|
||||
assert_eq!(budget.refused(), 0, "that image's limit isn't the run's");
|
||||
|
||||
// A small allowance is a limit too: it stops there, and the image is refused.
|
||||
let mut budget = ImageBudget::with_work(bomb.raw.len() as u64 + 10);
|
||||
let mut budget = ImageBudget::with_work(bomb.raw.len() as u64 + read(bomb.raw.len()) + 10);
|
||||
assert!(budget.decode(&doc, &bomb, 1 << 20).is_err());
|
||||
assert_eq!((budget.work_left(), budget.refused()), (0, 1));
|
||||
}
|
||||
@@ -492,7 +518,7 @@ mod image_tests {
|
||||
let doc = Document::open(std::sync::Arc::new(file)).unwrap();
|
||||
let image = doc.get(doc.root().unwrap()).as_dict().unwrap().reference(b"Image").unwrap();
|
||||
let s = stream(&doc, image);
|
||||
let filters = (raw.len() + skipped.len()) as u64;
|
||||
let filters = (raw.len() + skipped.len()) as u64 + read(raw.len());
|
||||
assert_eq!(spent(&doc, &s), first, "the first read undoes them");
|
||||
assert_eq!(spent(&doc, &s), first - filters, "kept");
|
||||
|
||||
@@ -507,7 +533,7 @@ mod image_tests {
|
||||
let image = jbig2(Some(Object::Dict(parms)));
|
||||
let mut budget = ImageBudget::with_work(u64::MAX);
|
||||
assert!(budget.decode(&doc, &image, 1 << 20).unwrap_err().to_string().contains("globals"));
|
||||
assert_eq!(u64::MAX - budget.work_left(), (over.len() + crate::MAX_JBIG2_GLOBALS) as u64);
|
||||
assert_eq!(u64::MAX - budget.work_left(), (over.len() + crate::MAX_JBIG2_GLOBALS) as u64 + read(over.len()));
|
||||
assert_eq!(budget.refused(), 0);
|
||||
}
|
||||
|
||||
@@ -528,7 +554,7 @@ mod image_tests {
|
||||
dict.set(b"DecodeParms".to_vec(), Object::Array(vec![Object::Null, Object::Dict(parms)]));
|
||||
let image = Stream::from_raw(dict, pdfcraft_filters::encode_flate(&coded));
|
||||
let pixels = u64::from(w) * u64::from(h);
|
||||
let cost = (image.raw.len() + coded.len() + 4 * coded.len() + 512 * h as usize) as u64 + pixels;
|
||||
let cost = (image.raw.len() + coded.len() + 4 * coded.len() + 512 * h as usize) as u64 + read(image.raw.len()) + pixels;
|
||||
let mut budget = ImageBudget::with_work(cost);
|
||||
assert_eq!(budget.decode(&doc, &image, 1 << 20).unwrap().len(), 512 * h as usize);
|
||||
assert_eq!(budget.work_left(), 0, "exactly that");
|
||||
@@ -553,7 +579,7 @@ mod image_tests {
|
||||
};
|
||||
let rows = vec![0xFFu8; 512 * 1024];
|
||||
let flate = blank(Some("FlateDecode"), pdfcraft_filters::encode_flate(&rows));
|
||||
let cost = (flate.raw.len() + rows.len()) as u64 + 4096 * 1024;
|
||||
let cost = (flate.raw.len() + rows.len()) as u64 + read(flate.raw.len()) + 4096 * 1024;
|
||||
let mut budget = ImageBudget::with_work(cost);
|
||||
assert_eq!(budget.decode(&doc, &flate, 1 << 24).unwrap(), rows);
|
||||
assert_eq!((budget.work_left(), budget.refused()), (0, 0), "exactly that");
|
||||
@@ -590,6 +616,36 @@ mod image_tests {
|
||||
assert_eq!((budget.work_left(), budget.refused()), (0, 1));
|
||||
}
|
||||
|
||||
/// What Flate reads is priced for blocks that make nothing, and an image an encoder made pays
|
||||
/// little for it: a scan-like picture stored in under half its size costs no more than half
|
||||
/// again its bytes, samples and pixels. Redaction decodes a picture once for each page that draws it, so
|
||||
/// a letterhead on hundreds of pages has to fit about as often as it did unpriced (here, at
|
||||
/// most half again the cost).
|
||||
#[test]
|
||||
fn an_image_an_encoder_made_pays_little_for_its_reading() {
|
||||
let doc = Document::new_empty();
|
||||
let mut seed = 0x2545_F491_4F6C_DD1Du64;
|
||||
let samples: Vec<u8> = (0..256 * 256usize)
|
||||
.map(|i| {
|
||||
seed ^= seed << 13;
|
||||
seed ^= seed >> 7;
|
||||
seed ^= seed << 17;
|
||||
((i % 256) as u8 / 16) ^ (seed as u8 & 3)
|
||||
})
|
||||
.collect();
|
||||
let mut dict = Dict::new();
|
||||
dict.set(b"Width".to_vec(), Object::Int(256));
|
||||
dict.set(b"Height".to_vec(), Object::Int(256));
|
||||
let image = Stream::flate(dict, &samples);
|
||||
assert!(image.raw.len() * 2 < samples.len(), "stored smaller: {}", image.raw.len());
|
||||
let unpriced = (image.raw.len() + samples.len()) as u64 + 256 * 256;
|
||||
let mut budget = ImageBudget::with_work(u64::MAX);
|
||||
budget.decode(&doc, &image, 1 << 20).unwrap();
|
||||
let paid = u64::MAX - budget.work_left();
|
||||
assert_eq!(paid, unpriced + read(image.raw.len()));
|
||||
assert!(2 * paid <= 3 * unpriced, "{paid} steps against {unpriced}");
|
||||
}
|
||||
|
||||
/// An image pays for the pixels its data holds, not those its size declares: one claiming
|
||||
/// 131072 by 131072 pixels with a few bytes of Flate costs what those bytes give, and the
|
||||
/// images after it are decoded as they would be without it.
|
||||
@@ -609,8 +665,8 @@ mod image_tests {
|
||||
budget.decode(&doc, s, 1 << 24).unwrap();
|
||||
u64::MAX - budget.work_left()
|
||||
};
|
||||
assert_eq!(cost(&claims), (claims.raw.len() + 16 + 16 * 8) as u64, "its bytes, and a pixel a bit of them");
|
||||
assert_eq!(cost(&image), (image.raw.len() + 64 * 64) as u64 + 64 * 64, "its bytes, and its pixels");
|
||||
assert_eq!(cost(&claims), (claims.raw.len() + 16 + 16 * 8) as u64 + read(claims.raw.len()), "its bytes, and a pixel a bit of them");
|
||||
assert_eq!(cost(&image), (image.raw.len() + 64 * 64) as u64 + read(image.raw.len()) + 64 * 64, "its bytes, and its pixels");
|
||||
for decode in [ImageBudget::decode, ImageBudget::decode_filters] {
|
||||
let mut budget = ImageBudget::with_work(cost(&claims) + cost(&image));
|
||||
assert_eq!(decode(&mut budget, &doc, &claims, 1 << 24).unwrap(), [0; 16]);
|
||||
@@ -627,7 +683,7 @@ mod image_tests {
|
||||
let samples = vec![7u8; 1000];
|
||||
let raw = pdfcraft_filters::encode_flate(&samples);
|
||||
let chain = [(Filter::Flate, Params::default())];
|
||||
let cost = (raw.len() + samples.len()) as u64;
|
||||
let cost = (raw.len() + samples.len()) as u64 + read(raw.len());
|
||||
let mut budget = ImageBudget::with_work(cost + 10);
|
||||
assert_eq!(budget.decode_chain(&chain, &raw, 1 << 20).unwrap(), samples);
|
||||
assert_eq!(budget.work_left(), 10);
|
||||
@@ -664,7 +720,7 @@ mod image_tests {
|
||||
assert_eq!(budget.decode_filters(&doc, &image, 1 << 20).unwrap(), rows);
|
||||
let cost = u64::MAX - budget.work_left();
|
||||
// The tag byte of each of its 100 rows counts, which the predictor takes off.
|
||||
assert_eq!(cost, (image.raw.len() + rows.len() + 100) as u64);
|
||||
assert_eq!(cost, (image.raw.len() + rows.len() + 100) as u64 + read(image.raw.len()));
|
||||
let mut budget = ImageBudget::with_work(cost - 1);
|
||||
assert!(budget.decode_filters(&doc, &image, 1 << 20).is_err());
|
||||
assert_eq!((budget.work_left(), budget.refused()), (0, 1));
|
||||
@@ -769,7 +825,7 @@ mod tests {
|
||||
assert_eq!(budget.remaining(), 0);
|
||||
let mut budget = DecodeBudget::new((1 << 20) - 1, 1);
|
||||
let Object::Stream(stream) = &*doc.get(bomb) else { panic!("not a stream") };
|
||||
assert!(budget.decode_strict(stream).is_err());
|
||||
assert!(budget.decode_strict(&doc, stream).is_err());
|
||||
assert_eq!(budget.remaining(), 0);
|
||||
|
||||
let mut budget = DecodeBudget::new(10 << 20, 1);
|
||||
@@ -793,14 +849,111 @@ mod tests {
|
||||
let corrupt = Stream::from_raw(whole.dict.clone(), whole.raw.get(..cut).unwrap_or_default().to_vec());
|
||||
let partial = corrupt.decoded().map(|d| d.len()).unwrap_or(0);
|
||||
assert!(partial > 0, "a cut flate stream decodes in part");
|
||||
let doc = Document::new_empty();
|
||||
let mut budget = DecodeBudget::new(10 << 20, 1);
|
||||
assert!(budget.decode_strict(&corrupt).is_err());
|
||||
assert!(budget.decode_strict(&doc, &corrupt).is_err());
|
||||
assert_eq!(budget.remaining(), (10 << 20) - partial);
|
||||
let mut budget = DecodeBudget::new(10 << 20, 1);
|
||||
assert!(budget.decode_within(&corrupt, 1 << 30).is_ok());
|
||||
assert_eq!(budget.remaining(), (10 << 20) - partial);
|
||||
}
|
||||
|
||||
/// A stream damaged partway decodes to what came before the damage, and says so, so that code
|
||||
/// writing it back can leave it as it is. What every reader takes is no damage: a missing
|
||||
/// checksum, no filter at all.
|
||||
#[test]
|
||||
fn a_stream_damaged_partway_says_so() {
|
||||
let doc = Document::new_empty();
|
||||
let read = |budget: &mut DecodeBudget, s: &Stream, max| budget.decode_with_damage(&doc, s, max).map(|(d, damaged)| (d.len(), damaged)).ok();
|
||||
let whole = Stream::flate(Dict::new(), &vec![b' '; 1 << 20]);
|
||||
let cut = Stream::from_raw(whole.dict.clone(), whole.raw.get(..whole.raw.len() / 2).unwrap_or_default().to_vec());
|
||||
let partial = cut.decoded().map(|d| d.len()).unwrap_or(0);
|
||||
assert!(partial > 0, "a cut flate stream decodes in part");
|
||||
let mut budget = DecodeBudget::new(10 << 20, 1);
|
||||
assert_eq!(read(&mut budget, &cut, usize::MAX), Some((partial, true)));
|
||||
assert_eq!(budget.remaining(), (10 << 20) - partial);
|
||||
// Within a bound of its own, under what is left.
|
||||
assert_eq!(read(&mut budget, &cut, 4 << 20), Some((partial, true)));
|
||||
assert_eq!(budget.decode(&cut).map(|d| d.len()).ok(), Some(partial));
|
||||
|
||||
let mut budget = DecodeBudget::new(10 << 20, 1);
|
||||
assert_eq!(read(&mut budget, &whole, usize::MAX), Some((1 << 20, false)));
|
||||
assert_eq!(read(&mut budget, &whole, 4 << 20), Some((1 << 20, false)));
|
||||
let unchecked = Stream::from_raw(whole.dict.clone(), whole.raw.get(..whole.raw.len() - 4).unwrap_or_default().to_vec());
|
||||
assert_eq!(read(&mut budget, &unchecked, usize::MAX), Some((1 << 20, false)));
|
||||
assert_eq!(read(&mut budget, &Stream::from_raw(Dict::new(), b"0 0 m".to_vec()), usize::MAX), Some((5, false)));
|
||||
// A later stage's damage is the stream's.
|
||||
let mut dict = Dict::new();
|
||||
dict.set(b"Filter".to_vec(), Object::Array(vec![Object::name("FlateDecode"), Object::name("ASCIIHexDecode")]));
|
||||
let hex = Stream::from_raw(dict, Stream::flate(Dict::new(), b"4142zz4344>").raw.to_vec());
|
||||
assert_eq!(budget.decode_with_damage(&doc, &hex, usize::MAX).ok(), Some((b"AB".to_vec(), true)));
|
||||
// So is an earlier stage's, though the stage after it reads all it was given: a stored
|
||||
// block of whole hex, then a block of the reserved type (RFC 1951 §3.2.3).
|
||||
let readable = b"4142>";
|
||||
let len = u16::try_from(readable.len()).unwrap_or_default();
|
||||
let mut raw = vec![0x78, 0x01, 0x00];
|
||||
raw.extend_from_slice(&len.to_le_bytes());
|
||||
raw.extend_from_slice(&(!len).to_le_bytes());
|
||||
raw.extend_from_slice(readable);
|
||||
raw.push(0x07);
|
||||
let flate_damaged = Stream::from_raw(hex.dict.clone(), raw);
|
||||
assert_eq!(budget.decode_with_damage(&doc, &flate_damaged, usize::MAX).ok(), Some((b"AB".to_vec(), true)));
|
||||
}
|
||||
|
||||
/// `/DecodeParms` given by reference, or a parameter given by reference in them, is read: a
|
||||
/// predicted stream decodes as with them direct. Of the stream, decoding copies no more than
|
||||
/// its filters and their parameters.
|
||||
#[test]
|
||||
fn parameters_given_by_reference_are_read() {
|
||||
let content = b"q 10 0 0 10 0 0 cm /Im Do Q";
|
||||
// PNG Up, one column: each byte a row of its own, tagged 2.
|
||||
let mut rows = Vec::new();
|
||||
let mut above = 0u8;
|
||||
for &b in content {
|
||||
rows.extend([2, b.wrapping_sub(above)]);
|
||||
above = b;
|
||||
}
|
||||
let raw = Stream::flate(Dict::new(), &rows).raw;
|
||||
let mut doc = Document::new_empty();
|
||||
let direct: Dict = [(b"Predictor".to_vec(), Object::Int(12))].into_iter().collect();
|
||||
let by_reference = Object::Ref(doc.add(Object::Dict(direct.clone())));
|
||||
let predictor = doc.add(Object::Int(12));
|
||||
let inner = Object::Dict([(b"Predictor".to_vec(), Object::Ref(predictor))].into_iter().collect());
|
||||
for parms in [Object::Dict(direct), by_reference, inner] {
|
||||
let mut dict = Dict::new();
|
||||
dict.set(b"Filter".to_vec(), Object::name("FlateDecode"));
|
||||
dict.set(b"DecodeParms".to_vec(), parms.clone());
|
||||
dict.set(b"Other".to_vec(), Object::Array(vec![Object::Int(0); 1000]));
|
||||
let s = Stream::from_raw(dict, raw.to_vec());
|
||||
assert_eq!(DecodeBudget::page().decode_with_damage(&doc, &s, usize::MAX).ok(), Some((content.to_vec(), false)), "{parms:?}");
|
||||
assert_eq!(DecodeBudget::page().decode_strict(&doc, &s).ok(), Some(content.to_vec()), "{parms:?}");
|
||||
let r = doc.add(Object::Stream(s.clone()));
|
||||
let read = DecodeBudget::page().decode_contents_with_damage(&doc, &Object::Array(vec![Object::Ref(r)]));
|
||||
assert_eq!(read, [Ok((content.to_vec(), false))], "{parms:?}");
|
||||
assert_eq!(DecodeBudget::page().decode_contents(&doc, &Object::Ref(r)), [Ok(content.to_vec())], "{parms:?}");
|
||||
let view = doc.decoding_view(&s);
|
||||
assert!(matches!(view, std::borrow::Cow::Borrowed(_)) || view.dict.len() == 2, "{:?}", view.dict);
|
||||
}
|
||||
}
|
||||
|
||||
/// A page's content streams each say whether they are damaged, in their places.
|
||||
#[test]
|
||||
fn a_pages_streams_each_say_whether_they_are_damaged() {
|
||||
let mut doc = Document::new_empty();
|
||||
let whole = doc.add(Object::Stream(Stream::flate(Dict::new(), b"0 0 m 1 1 l S")));
|
||||
let Object::Stream(s) = &*doc.get(whole) else { panic!("not a stream") };
|
||||
let cut = Stream::from_raw(s.dict.clone(), s.raw.get(..s.raw.len() - 6).unwrap_or_default().to_vec());
|
||||
let cut = doc.add(Object::Stream(cut));
|
||||
let contents = Object::Array(vec![Object::Ref(whole), Object::Null, Object::Ref(cut)]);
|
||||
let mut budget = DecodeBudget::page();
|
||||
let read: Vec<_> = budget.decode_contents_with_damage(&doc, &contents).into_iter().map(|r| r.map(|(_, damaged)| damaged).ok()).collect();
|
||||
assert_eq!(read, [Some(false), Some(true)]);
|
||||
let one: Vec<_> =
|
||||
budget.decode_contents_with_damage(&doc, &Object::Ref(cut)).into_iter().map(|r| r.map(|(_, damaged)| damaged).ok()).collect();
|
||||
assert_eq!(one, [Some(true)]);
|
||||
assert_eq!(budget.decode_contents(&doc, &contents).iter().filter(|r| r.is_ok()).count(), 2, "read up to the damage");
|
||||
}
|
||||
|
||||
/// A stream that fails its reading as zlib, and then as raw deflate after decoding all of it,
|
||||
/// gives nothing back, and each reference still pays for what it decoded.
|
||||
#[test]
|
||||
@@ -832,7 +985,7 @@ mod tests {
|
||||
assert_eq!(budget.remaining(), (10 << 20) - charged);
|
||||
assert!(budget.decode_within(&chained, 2 << 20).is_ok());
|
||||
assert_eq!(budget.remaining(), (10 << 20) - 2 * charged);
|
||||
assert!(budget.decode_strict(&chained).is_ok());
|
||||
assert!(budget.decode_strict(&Document::new_empty(), &chained).is_ok());
|
||||
assert_eq!(budget.remaining(), (10 << 20) - 3 * charged);
|
||||
}
|
||||
}
|
||||
@@ -24,11 +24,11 @@ pub(crate) use objects::Held;
|
||||
pub(crate) use reader::find;
|
||||
#[cfg(test)]
|
||||
use reader::rfind;
|
||||
pub(crate) use state::ObjectReader;
|
||||
use state::{ObjStm, Slot};
|
||||
use state::{ObjStm, Slot, Unreadable};
|
||||
pub(crate) use state::{ObjectReader, held_bytes};
|
||||
pub use state::{ReadState, SourceIdentity};
|
||||
#[cfg(test)]
|
||||
use state::{SECTION_READS, held_bytes, objstm_member};
|
||||
use state::{SECTION_READS, objstm_member};
|
||||
use xref::XrefIndex;
|
||||
pub use xref::{Revision, XrefEntry};
|
||||
|
||||
@@ -48,8 +48,14 @@ pub struct Document {
|
||||
/// `fill_xref_gaps`.
|
||||
located: Arc<BTreeMap<u32, (u64, u16)>>,
|
||||
repair_log: Arc<Vec<String>>,
|
||||
/// What loading each file object gave, a failure as well: a damaged object is otherwise
|
||||
/// loaded again on every read, and a member of an object stream that can't be decoded
|
||||
/// decodes the stream again (`Document::load`).
|
||||
cache: Arc<Mutex<state::ObjectCache>>,
|
||||
objstms: Arc<Mutex<HashMap<u32, Arc<ObjStm>>>>,
|
||||
/// See [`Self::unreadable_objects`]. Shared by clones, like the caches: it describes the
|
||||
/// source, and is reset wherever they are.
|
||||
unreadable: Arc<Mutex<Unreadable>>,
|
||||
/// 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>>>>>,
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
use std::collections::HashSet;
|
||||
|
||||
use super::reader::find;
|
||||
use super::state::{LENGTHS, LoadGuard, ObjStm, ObjectReader, ReadState, Slot, SourceIdentity, held_bytes, objstm_member};
|
||||
use super::state::{
|
||||
LENGTHS, LoadGuard, ObjStm, ObjectReader, ReadState, Slot, SourceIdentity, loaded_bytes, note_overlay_read, objstm_member, overlay_reads,
|
||||
};
|
||||
use super::xref::{Revision, XrefEntry, XrefIndex};
|
||||
use super::{
|
||||
Arc, CosError, Cow, Dict, Document, Lexer, MAX_DECODED, MAX_JBIG2_GLOBALS, ObjRef, Object, Stream, is_whitespace, parse_indirect_shared,
|
||||
@@ -88,6 +90,39 @@ impl Document {
|
||||
&self.repair_log
|
||||
}
|
||||
|
||||
/// Objects of the file that could not be read, lowest number first, as lines such as
|
||||
/// "object 11 0 could not be read: syntax error at byte 512: ...". [`Self::get`] reads each
|
||||
/// as null (ISO 32000-2 §7.3.10), so a document with one opens, but what it held is lost:
|
||||
/// unlike [`Self::repair_log`], nothing was repaired. Lists the objects read so far, by this
|
||||
/// document, its clones or a scan of it, that have not since been edited; past 100, a last
|
||||
/// line says there were more. Opening again, authenticating or rebuilding the index starts
|
||||
/// the list afresh, as it does the object cache.
|
||||
pub fn unreadable_objects(&self) -> Vec<String> {
|
||||
let Ok(unreadable) = self.unreadable.lock() else { return Vec::new() };
|
||||
unreadable.lines(|num| self.overlay.contains_key(&num))
|
||||
}
|
||||
|
||||
/// Record `num` as unreadable. `reason` is built only for an object not yet listed, so a file
|
||||
/// whose broken object is asked for again and again pays for it once.
|
||||
fn note_unreadable(&self, num: u32, reason: impl FnOnce() -> String) {
|
||||
// A poisoned lock only means the object goes unlisted; the read itself still fails.
|
||||
let Ok(mut unreadable) = self.unreadable.lock() else { return };
|
||||
let hidden = |n: u32| self.overlay.contains_key(&n);
|
||||
if unreadable.wants(num, hidden) {
|
||||
unreadable.note(num, self.generation(num), &reason(), hidden);
|
||||
}
|
||||
}
|
||||
|
||||
/// Why an object listed at `offset` could not be read: what parsing it there, without resolving
|
||||
/// an indirect `/Length`, found. A best account, not the only one: the reader also tried
|
||||
/// elsewhere.
|
||||
fn why_unreadable(&self, offset: usize) -> String {
|
||||
match parse_indirect_shared(&self.data, offset, &|_| None, &self.endstreams) {
|
||||
Err(e) => e.to_string(),
|
||||
Ok(_) => "no readable copy was found at its cross-reference offset or elsewhere in the file".into(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Add a line to [`Self::repair_log`]: a leniency applied while reading that the user should
|
||||
/// know about (fidelity: never silent).
|
||||
pub fn note_repair(&mut self, line: String) {
|
||||
@@ -288,7 +323,29 @@ impl Document {
|
||||
/// ([`pdfcraft_filters::MAX_CHAIN`]). Only small values are copied, so a file can't have a
|
||||
/// large object copied once for each key and filter.
|
||||
pub fn with_direct_parms<'s>(&self, s: &'s Stream) -> Cow<'s, Stream> {
|
||||
let Some(p) = s.dict.get(b"DecodeParms") else { return Cow::Borrowed(s) };
|
||||
let Some(made) = self.direct_parms(s) else { return Cow::Borrowed(s) };
|
||||
let mut s = s.clone();
|
||||
s.dict.set(b"DecodeParms".to_vec(), made);
|
||||
Cow::Owned(s)
|
||||
}
|
||||
|
||||
/// [`Document::with_direct_parms`] for decoding alone: where that copies `s`, this makes a
|
||||
/// stream of `s`'s data, shared, and a dictionary of its `/Filter` and the parameters made
|
||||
/// direct, all its filters read. A stream named again and again, as a page's `/Contents` may
|
||||
/// list one, isn't copied whole each time.
|
||||
pub(crate) fn decoding_view<'s>(&self, s: &'s Stream) -> Cow<'s, Stream> {
|
||||
let Some(made) = self.direct_parms(s) else { return Cow::Borrowed(s) };
|
||||
let mut dict = Dict::new();
|
||||
if let Some(f) = s.dict.get(b"Filter") {
|
||||
dict.set(b"Filter".to_vec(), f.clone());
|
||||
}
|
||||
dict.set(b"DecodeParms".to_vec(), made);
|
||||
Cow::Owned(Stream { dict, raw: s.raw.clone() })
|
||||
}
|
||||
|
||||
/// The `/DecodeParms` [`Document::with_direct_parms`] gives `s`, or `None` when it keeps `s`.
|
||||
fn direct_parms(&self, s: &Stream) -> Option<Object> {
|
||||
let p = s.dict.get(b"DecodeParms")?;
|
||||
let crypt = |f: &Object| matches!(f.as_name(), Some(b"Crypt"));
|
||||
let filters: Vec<bool> = match s.dict.get(b"Filter") {
|
||||
Some(Object::Array(a)) => a.iter().map(crypt).collect(),
|
||||
@@ -296,7 +353,7 @@ impl Document {
|
||||
None => Vec::new(),
|
||||
};
|
||||
if filters.iter().filter(|c| !**c).count() > pdfcraft_filters::MAX_CHAIN {
|
||||
return Cow::Borrowed(s);
|
||||
return None;
|
||||
}
|
||||
let mut changed = matches!(p, Object::Ref(_));
|
||||
// Its numbers and flags kept, resolved; anything else is no filter's parameters (null).
|
||||
@@ -323,12 +380,7 @@ impl Document {
|
||||
}
|
||||
_ => one(p, &mut changed),
|
||||
};
|
||||
if !changed {
|
||||
return Cow::Borrowed(s);
|
||||
}
|
||||
let mut s = s.clone();
|
||||
s.dict.set(b"DecodeParms".to_vec(), made);
|
||||
Cow::Owned(s)
|
||||
changed.then_some(made)
|
||||
}
|
||||
|
||||
/// `o`, or the object it refers to, without copying either.
|
||||
@@ -497,27 +549,38 @@ impl Document {
|
||||
}
|
||||
|
||||
pub fn try_get(&self, num: u32) -> Result<Arc<Object>, CosError> {
|
||||
match self.overlay.get(&num) {
|
||||
Some(Slot::Set(_, o) | Slot::RepairedSet(_, _, o)) => return Ok(o.clone()),
|
||||
Some(Slot::Freed(_)) => return Ok(Arc::new(Object::Null)),
|
||||
None => {}
|
||||
if let Some(slot) = self.overlay.get(&num) {
|
||||
note_overlay_read();
|
||||
return Ok(match slot {
|
||||
Slot::Set(_, o) | Slot::RepairedSet(_, _, o) => o.clone(),
|
||||
Slot::Freed(_) => Arc::new(Object::Null),
|
||||
});
|
||||
}
|
||||
if let Some(o) = self.cache.lock().map_err(|_| CosError::Poisoned)?.get(&num) {
|
||||
return Ok(o.clone());
|
||||
if let Some(loaded) = self.cache.lock().map_err(|_| CosError::Poisoned)?.get(&num) {
|
||||
return loaded.clone();
|
||||
}
|
||||
// Loading can re-enter (indirect stream `/Length`, object streams); damaged files make
|
||||
// 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.
|
||||
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)
|
||||
let edits_read = overlay_reads();
|
||||
let loaded = self.load(num, 0).map(Arc::new);
|
||||
if let Err(e) = &loaded
|
||||
&& !matches!(e, CosError::Poisoned)
|
||||
{
|
||||
self.note_unreadable(num, || e.to_string());
|
||||
}
|
||||
// A failure is kept like an object, or every read of a damaged object loads it again. A
|
||||
// poisoned lock says nothing about the object. Clones share the cache, so a load that read
|
||||
// this document's edits (an edited object stream or `/Length`) is not kept.
|
||||
if overlay_reads() == edits_read && !matches!(loaded, Err(CosError::Poisoned)) {
|
||||
// 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, loaded.clone(), loaded_bytes(&loaded, &self.data));
|
||||
self.evict_editor_cache_if_over_budget(num)?;
|
||||
}
|
||||
loaded
|
||||
}
|
||||
|
||||
/// Bounds for the editing cache: roomier than the scan reader's (128 objects / 8 MB)
|
||||
@@ -629,11 +692,20 @@ impl Document {
|
||||
None | Some(XrefEntry::Free { .. }) => Ok(Object::Null),
|
||||
Some(XrefEntry::InFile { offset, .. }) => {
|
||||
let resolve = |r: ObjRef| {
|
||||
if let Some(known) = LENGTHS.with(|m| m.borrow().get(&r).copied()) {
|
||||
if self.overlay.contains_key(&r.num) {
|
||||
note_overlay_read();
|
||||
}
|
||||
// A length resolved through this document's edits counts as an edit read
|
||||
// on every reuse.
|
||||
if let Some((known, edits)) = LENGTHS.with(|m| m.borrow().get(&r).copied()) {
|
||||
if edits {
|
||||
note_overlay_read();
|
||||
}
|
||||
return known;
|
||||
}
|
||||
let edits_read = overlay_reads();
|
||||
let length = self.try_get_reference(r).ok().and_then(|o| o.as_int());
|
||||
LENGTHS.with(|m| m.borrow_mut().insert(r, length));
|
||||
LENGTHS.with(|m| m.borrow_mut().insert(r, (length, overlay_reads() != edits_read)));
|
||||
length
|
||||
};
|
||||
let off = offset as usize;
|
||||
@@ -646,7 +718,10 @@ impl Document {
|
||||
.or_else(|| if self.header_offset == 0 { None } else { at(off.saturating_add(self.header_offset)) })
|
||||
.or_else(|| self.located.get(&num).and_then(|(o, _)| usize::try_from(*o).ok()).and_then(at))
|
||||
.or_else(|| self.scan_for(num).map(|(id, o)| self.decrypted(id, o)))
|
||||
.ok_or(CosError::MissingObject(num))
|
||||
.ok_or_else(|| {
|
||||
self.note_unreadable(num, || self.why_unreadable(off));
|
||||
CosError::MissingObject(num)
|
||||
})
|
||||
}
|
||||
Some(XrefEntry::InStream { stream, index }) => {
|
||||
let stm = self.objstm(stream)?;
|
||||
@@ -659,7 +734,9 @@ impl Document {
|
||||
}
|
||||
|
||||
pub(super) fn objstm(&self, num: u32) -> Result<Arc<ObjStm>, CosError> {
|
||||
if let Some(s) = self.objstms.lock().map_err(|_| CosError::Poisoned)?.get(&num) {
|
||||
// An edited or freed stream is this document's alone: clones share the parsed streams.
|
||||
let edited = self.overlay.contains_key(&num);
|
||||
if !edited && let Some(s) = self.objstms.lock().map_err(|_| CosError::Poisoned)?.get(&num) {
|
||||
return Ok(s.clone());
|
||||
}
|
||||
// A file entry that cannot place the stream (one that says it is itself compressed
|
||||
@@ -667,6 +744,7 @@ impl Document {
|
||||
// header, as a plain object with a wrong offset is. An edited or freed stream, in the
|
||||
// overlay or in a saved revision's table, is what that says it is: the file's copy
|
||||
// must not come back.
|
||||
let edits_read = overlay_reads();
|
||||
let loaded = match self.try_get(num) {
|
||||
Ok(o) if matches!(*o, Object::Stream(_)) => o,
|
||||
_ if self.overlay.contains_key(&num) || matches!(self.xref_entry(num), Some(XrefEntry::Free { .. })) => {
|
||||
@@ -674,6 +752,8 @@ impl Document {
|
||||
}
|
||||
_ => Arc::new(self.scan_for(num).map(|(id, o)| self.decrypted(id, o)).ok_or(CosError::MissingObject(num))?),
|
||||
};
|
||||
// A stream whose load read this document's edits (its `/Length`) is as much its own as an edited one.
|
||||
let own = edited || overlay_reads() != edits_read;
|
||||
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();
|
||||
@@ -681,6 +761,8 @@ impl Document {
|
||||
// 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));
|
||||
#[cfg(test)]
|
||||
super::tests::OBJSTM_DECODES.with(|decodes| decodes.set(decodes.get() + 1));
|
||||
let data = readable.decoded_within(self.stream_limit)?;
|
||||
let mut lx = Lexer::new(&data, 0);
|
||||
let mut index = Vec::with_capacity(n);
|
||||
@@ -689,6 +771,9 @@ impl Document {
|
||||
index.push(objstm_member(onum, off, first, data.len()));
|
||||
}
|
||||
let stm = Arc::new(ObjStm { index, data: Arc::new(data) });
|
||||
if own {
|
||||
return Ok(stm);
|
||||
}
|
||||
// Same bound as the object cache: decoded object streams can be megabytes each.
|
||||
// Insert first so the retained `num` is actually in the map.
|
||||
self.objstms.lock().map_err(|_| CosError::Poisoned)?.insert(num, stm.clone());
|
||||
@@ -745,6 +830,7 @@ impl Document {
|
||||
pub fn set(&mut self, r: ObjRef, obj: impl Into<Object>) {
|
||||
let obj = self.adopt(obj.into());
|
||||
self.overlay.insert(r.num, Slot::Set(r.generation, Arc::new(obj)));
|
||||
self.forget_member_failures(r.num);
|
||||
if r.num >= self.next_num {
|
||||
self.next_num = r.num.saturating_add(1);
|
||||
}
|
||||
@@ -804,6 +890,16 @@ impl Document {
|
||||
/// Delete an object (its number becomes free with the next generation).
|
||||
pub fn free(&mut self, r: ObjRef) {
|
||||
self.overlay.insert(r.num, Slot::Freed(r.generation.saturating_add(1)));
|
||||
self.forget_member_failures(r.num);
|
||||
}
|
||||
|
||||
/// Forget cached failures of the members `stream` held in the file: they were failures of
|
||||
/// the file's copy, and an edit of `stream` may read. Clones share the cache, so theirs are
|
||||
/// searched again too, which costs time only. A poisoned lock leaves the cache as it is.
|
||||
fn forget_member_failures(&self, stream: u32) {
|
||||
if let Ok(mut cache) = self.cache.lock() {
|
||||
cache.forget_failures(|n| matches!(self.entries.lookup(*n, &self.data), Some(XrefEntry::InStream { stream: s, .. }) if s == stream));
|
||||
}
|
||||
}
|
||||
|
||||
/// Free what was added since the file was read and nothing refers to any more: the objects
|
||||
|
||||
@@ -23,6 +23,7 @@ impl Document {
|
||||
repair_log: Arc::new(Vec::new()),
|
||||
cache: Arc::default(),
|
||||
objstms: Arc::default(),
|
||||
unreadable: Arc::default(),
|
||||
jbig2_globals: Arc::default(),
|
||||
stream_limit: crate::object::MAX_DECODED,
|
||||
overlay: BTreeMap::new(),
|
||||
@@ -110,6 +111,7 @@ impl Document {
|
||||
repair_log: Arc::new(Vec::new()),
|
||||
cache: Arc::default(),
|
||||
objstms: Arc::default(),
|
||||
unreadable: Arc::default(),
|
||||
jbig2_globals: Arc::default(),
|
||||
stream_limit: stream_limit.min(crate::object::MAX_DECODED),
|
||||
overlay: BTreeMap::new(),
|
||||
@@ -216,6 +218,7 @@ impl Document {
|
||||
// Objects read while locating the catalog were read before decryption was possible.
|
||||
self.cache = Arc::default();
|
||||
self.objstms = Arc::default();
|
||||
self.unreadable = Arc::default();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
#[cfg(test)]
|
||||
use super::state::SECTION_READS;
|
||||
use super::state::Unreadable;
|
||||
use super::xref::{
|
||||
MAX_COMPACT_XREF_BYTES, MAX_COMPACT_XREF_ROWS, Revision, XrefEntry, XrefIndex, XrefRange, XrefRevisionSection, XrefSection, XrefSectionData,
|
||||
};
|
||||
@@ -634,10 +635,20 @@ impl Document {
|
||||
// Offsets of objects that may be cross-reference streams: their dictionaries are the
|
||||
// trailers of files that have no `trailer` keyword (§7.5.8).
|
||||
let mut xref_streams = Vec::new();
|
||||
for (num, offset, generation, body) in object_headers(&data) {
|
||||
let headers = object_headers(&data);
|
||||
// Where `/XRef` occurs in the file, found in one pass.
|
||||
let mut xref_marks = Vec::new();
|
||||
let mut mark_from = 0;
|
||||
while let Some(p) = find(&data, b"/XRef", mark_from, data.len()) {
|
||||
xref_marks.push(p);
|
||||
mark_from = p + 1;
|
||||
}
|
||||
for &(num, offset, generation, body) in &headers {
|
||||
entries.insert(num, XrefEntry::InFile { offset, generation });
|
||||
objstms.push(num);
|
||||
if find(&data, b"/XRef", body, body.saturating_add(1024)).is_some()
|
||||
// `/XRef` within the 1024 bytes after the header (the first one that is there).
|
||||
let first = xref_marks.partition_point(|&p| p < body);
|
||||
if xref_marks.get(first).is_some_and(|&p| p + 5 <= body.saturating_add(1024).min(data.len()))
|
||||
&& let Ok(at) = usize::try_from(offset)
|
||||
{
|
||||
xref_streams.push(at);
|
||||
@@ -648,6 +659,7 @@ impl Document {
|
||||
}
|
||||
self.entries = Arc::new(XrefIndex::Materialized(Arc::new(entries.clone()), Arc::default()));
|
||||
self.cache.lock().map_err(|_| CosError::Poisoned)?.clear();
|
||||
*self.unreadable.lock().map_err(|_| CosError::Poisoned)? = Unreadable::default();
|
||||
// Objects inside object streams.
|
||||
for num in objstms {
|
||||
if let Ok(o) = self.try_get(num)
|
||||
@@ -664,6 +676,8 @@ impl Document {
|
||||
}
|
||||
let object_count = entries.len();
|
||||
self.entries = Arc::new(XrefIndex::Materialized(Arc::new(entries), Arc::default()));
|
||||
// Failures from the scan stand: the members added change no scanned entry, and a
|
||||
// `/Length` found only now cannot make a stream unreadable.
|
||||
self.cache.lock().map_err(|_| CosError::Poisoned)?.clear();
|
||||
// Trailer: the last `trailer` dictionary or cross-reference stream dictionary with a
|
||||
// usable /Root (last in the file, whichever kind), else the catalog itself. One whose
|
||||
@@ -823,7 +837,33 @@ pub(crate) fn find(hay: &[u8], needle: &[u8], from: usize, to: usize) -> Option<
|
||||
if from >= to || needle.is_empty() || to - from < needle.len() {
|
||||
return None;
|
||||
}
|
||||
hay[from..to].windows(needle.len()).position(|w| w == needle).map(|p| p + from)
|
||||
let hay = &hay[from..to];
|
||||
// Look for the needle's rarest byte first, a plain byte scan, and compare the rest only there.
|
||||
const COMMON: &[u8] = b" etaoinsrhldcumfpgwybvkxjqz";
|
||||
let (k, rare) =
|
||||
needle.iter().copied().enumerate().max_by_key(|&(_, b)| COMMON.iter().position(|&c| c == b).unwrap_or(COMMON.len())).unwrap_or((0, 0));
|
||||
let mut i = k;
|
||||
while let Some(p) = hay.get(i..).and_then(|rest| position_of(rest, rare)) {
|
||||
let start = i + p - k;
|
||||
if hay.get(start..start + needle.len()) == Some(needle) {
|
||||
return Some(start + from);
|
||||
}
|
||||
i += p + 1;
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// The first position of `byte` in `hay`. Whole 32-byte blocks are tested without branching, which
|
||||
/// the compiler turns into vector compares; only a block that holds the byte is searched.
|
||||
fn position_of(hay: &[u8], byte: u8) -> Option<usize> {
|
||||
const BLOCK: usize = 32;
|
||||
let (blocks, rest) = hay.as_chunks::<BLOCK>();
|
||||
for (i, block) in blocks.iter().enumerate() {
|
||||
if block.iter().fold(false, |any, &b| any | (b == byte)) {
|
||||
return block.iter().position(|&b| b == byte).map(|p| i * BLOCK + p);
|
||||
}
|
||||
}
|
||||
rest.iter().position(|&b| b == byte).map(|p| blocks.len() * BLOCK + p)
|
||||
}
|
||||
|
||||
pub(super) fn rfind(hay: &[u8], needle: &[u8], from: usize) -> Option<usize> {
|
||||
|
||||
@@ -6,8 +6,20 @@ thread_local! {
|
||||
static LOADING: std::cell::RefCell<Vec<u32>> = const { std::cell::RefCell::new(Vec::new()) };
|
||||
/// Indirect `/Length` values resolved during the current outermost load: a damaged file
|
||||
/// retries a parse several ways, and each retry would resolve the same lengths again
|
||||
/// (exponential in the chain of streams whose lengths point at further streams).
|
||||
pub(super) static LENGTHS: std::cell::RefCell<HashMap<ObjRef, Option<i64>>> = std::cell::RefCell::new(HashMap::new());
|
||||
/// (exponential in the chain of streams whose lengths point at further streams). Each is
|
||||
/// kept with whether resolving it read unsaved edits.
|
||||
pub(super) static LENGTHS: std::cell::RefCell<HashMap<ObjRef, (Option<i64>, bool)>> = std::cell::RefCell::new(HashMap::new());
|
||||
/// Unsaved edits read on this thread (`Document::try_get`, and a `/Length` in `Document::load`).
|
||||
static OVERLAY_READS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// Unsaved edits read so far on this thread: a load during which this changes depended on one.
|
||||
pub(super) fn overlay_reads() -> u64 {
|
||||
OVERLAY_READS.with(std::cell::Cell::get)
|
||||
}
|
||||
|
||||
pub(super) fn note_overlay_read() {
|
||||
OVERLAY_READS.with(|c| c.set(c.get().wrapping_add(1)));
|
||||
}
|
||||
|
||||
/// Marks an object as being loaded on this thread. Loading can re-enter (indirect stream
|
||||
@@ -30,6 +42,14 @@ impl LoadGuard {
|
||||
}
|
||||
}
|
||||
|
||||
/// What loading a file object gave, kept in the document's cache either way.
|
||||
pub(super) type Loaded = Result<Arc<Object>, CosError>;
|
||||
|
||||
/// The bytes a load result holds of its own ([`held_bytes`]); a failure holds none.
|
||||
pub(super) fn loaded_bytes(loaded: &Loaded, data: &Arc<Vec<u8>>) -> usize {
|
||||
loaded.as_ref().map_or(0, |o| held_bytes(o, data, 0))
|
||||
}
|
||||
|
||||
impl Drop for LoadGuard {
|
||||
fn drop(&mut self) {
|
||||
let outermost = LOADING.with(|l| {
|
||||
@@ -61,6 +81,60 @@ pub(super) fn objstm_member(num: i64, offset: i64, first: Option<usize>, len: us
|
||||
(start < len).then_some((num, start))
|
||||
}
|
||||
|
||||
/// Objects the reader could not read, each with the reason (see `Document::unreadable_objects`).
|
||||
/// Bounded: a document records past [`Unreadable::MAX`] of the objects it shows only the fact that
|
||||
/// there were more. Entries a clone has edited are hidden from it and do not count, so the whole
|
||||
/// list holds at most `MAX` plus the objects edited in clones.
|
||||
#[derive(Debug, Default)]
|
||||
pub(super) struct Unreadable {
|
||||
pub(super) objects: BTreeMap<u32, (u16, String)>,
|
||||
pub(super) more: bool,
|
||||
}
|
||||
|
||||
impl Unreadable {
|
||||
pub(super) const MAX: usize = 100;
|
||||
/// Characters of a reason kept: a parser's message can quote the bytes it stopped at.
|
||||
const REASON: usize = 160;
|
||||
|
||||
/// Whether `num` is to be recorded: not listed yet and there is room among the entries the
|
||||
/// asking document still shows (`hidden` are the ones it has edited, as in [`Self::lines`]),
|
||||
/// so a clone's edits never use up its own allowance. A full list notes that there were more,
|
||||
/// so a caller asks this before building the reason.
|
||||
pub(super) fn wants(&mut self, num: u32, hidden: impl Fn(u32) -> bool) -> bool {
|
||||
if self.objects.contains_key(&num) {
|
||||
return false;
|
||||
}
|
||||
if self.objects.keys().filter(|n| !hidden(**n)).count() >= Self::MAX {
|
||||
self.more = true;
|
||||
return false;
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// Record `num` once; the first reason given is kept.
|
||||
pub(super) fn note(&mut self, num: u32, generation: u16, reason: &str, hidden: impl Fn(u32) -> bool) {
|
||||
if self.wants(num, hidden) {
|
||||
self.objects.insert(num, (generation, reason.chars().take(Self::REASON).collect()));
|
||||
}
|
||||
}
|
||||
|
||||
/// One line per recorded object not `hidden`, then one saying there were more, if there were.
|
||||
pub(super) fn lines(&self, hidden: impl Fn(u32) -> bool) -> Vec<String> {
|
||||
// Clones share the list and each hides its own edits, so the list may hold more than
|
||||
// `MAX` entries in all; each document still shows at most `MAX`.
|
||||
let mut shown = self.objects.iter().filter(|(num, _)| !hidden(**num));
|
||||
let mut lines: Vec<String> = shown
|
||||
.by_ref()
|
||||
.take(Self::MAX)
|
||||
.map(|(num, (generation, reason))| format!("object {num} {generation} could not be read: {reason}"))
|
||||
.collect();
|
||||
if self.more || shown.next().is_some() {
|
||||
lines.push(format!("more objects could not be read; only the first {} are listed", Self::MAX));
|
||||
}
|
||||
lines
|
||||
}
|
||||
}
|
||||
|
||||
/// Where an overlay slot came from.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub(super) enum Slot {
|
||||
@@ -182,7 +256,7 @@ thread_local! {
|
||||
pub(super) static SECTION_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// Parsed objects by number, each with what it holds ([`held_bytes`]) measured once, when it goes
|
||||
/// What loading each object gave (a failure as well), 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
|
||||
@@ -191,12 +265,12 @@ thread_local! {
|
||||
/// (#5873).
|
||||
#[derive(Default)]
|
||||
pub(crate) struct ObjectCache {
|
||||
entries: HashMap<u32, (Arc<Object>, usize)>,
|
||||
entries: HashMap<u32, (Loaded, usize)>,
|
||||
owned: usize,
|
||||
}
|
||||
|
||||
impl ObjectCache {
|
||||
pub(crate) fn get(&self, num: &u32) -> Option<&Arc<Object>> {
|
||||
pub(crate) fn get(&self, num: &u32) -> Option<&Loaded> {
|
||||
self.entries.get(num).map(|(object, _)| object)
|
||||
}
|
||||
|
||||
@@ -205,8 +279,8 @@ impl ObjectCache {
|
||||
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) {
|
||||
/// Keep what loading `num` gave, which holds `owned` bytes ([`loaded_bytes`]).
|
||||
pub(crate) fn insert(&mut self, num: u32, object: Loaded, owned: usize) {
|
||||
if let Some((_, before)) = self.entries.insert(num, (object, owned)) {
|
||||
self.owned = self.owned.saturating_sub(before);
|
||||
}
|
||||
@@ -232,6 +306,11 @@ impl ObjectCache {
|
||||
self.owned = 0;
|
||||
}
|
||||
|
||||
/// Drop the cached failures `stale` picks. A failure holds no bytes, so the total stands.
|
||||
pub(crate) fn forget_failures(&mut self, mut stale: impl FnMut(&u32) -> bool) {
|
||||
self.entries.retain(|num, (loaded, _)| loaded.is_ok() || !stale(num));
|
||||
}
|
||||
|
||||
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));
|
||||
@@ -239,7 +318,7 @@ impl ObjectCache {
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn values(&self) -> impl Iterator<Item = &Arc<Object>> {
|
||||
self.entries.values().map(|(object, _)| object)
|
||||
self.entries.values().filter_map(|(object, _)| object.as_ref().ok())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -256,7 +335,7 @@ const OWNED_BYTES_DEPTH: usize = 256;
|
||||
/// InDesign's `/PieceInfo` -- thousands of small numeric arrays, parsed into tens of thousands of
|
||||
/// values -- weighed nothing, so the caches kept a thousand of them: a 35 MB file held 1.5 GB
|
||||
/// (#5873).
|
||||
pub(super) fn held_bytes(object: &Object, data: &Arc<Vec<u8>>, depth: usize) -> usize {
|
||||
pub(crate) fn held_bytes(object: &Object, data: &Arc<Vec<u8>>, depth: usize) -> usize {
|
||||
if depth > OWNED_BYTES_DEPTH {
|
||||
return usize::MAX;
|
||||
}
|
||||
|
||||
@@ -3,6 +3,8 @@ 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) };
|
||||
/// How many times `Document::objstm` decoded an object stream on this thread.
|
||||
pub(super) static OBJSTM_DECODES: 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
|
||||
@@ -730,6 +732,163 @@ fn an_entry_that_misses_its_object_is_found_by_searching_but_is_not_exact() {
|
||||
assert!(doc.xref_entry_is_exact(1) && doc.xref_entry_is_exact(2));
|
||||
}
|
||||
|
||||
/// An object that can't be read at its entry or anywhere else is searched for in the whole file
|
||||
/// once: every later read, in a clone too, gives the same error without searching again. An
|
||||
/// edit of that number still answers for it.
|
||||
#[test]
|
||||
fn an_unreadable_object_is_searched_for_once() {
|
||||
let bodies = ["<< /Type /Catalog /Pages 2 0 R >>", "<< /Type /Pages /Kids [] /Count 0 >>", "<< /Odd Key(x) >>"];
|
||||
let doc = Document::open(Arc::new(build(&bodies, "/Root 1 0 R /Info 3 0 R"))).unwrap();
|
||||
FILE_SCANS.with(|scans| scans.set(0));
|
||||
let first = doc.try_get(3);
|
||||
assert!(first.is_err(), "{first:?}");
|
||||
for _ in 0..10 {
|
||||
assert_eq!(doc.try_get(3), first);
|
||||
assert_eq!(*doc.get(ObjRef::new(3, 0)), Object::Null);
|
||||
}
|
||||
let mut edited = doc.clone();
|
||||
assert_eq!(edited.try_get(3), first);
|
||||
assert_eq!(FILE_SCANS.with(std::cell::Cell::get), 1, "searches for an object that isn't there");
|
||||
let report = doc.unreadable_objects();
|
||||
assert_eq!(report.len(), 1, "cached failures must stay listed exactly once: {report:?}");
|
||||
assert_eq!(edited.unreadable_objects(), report, "clones retain the cached failure diagnostic");
|
||||
edited.set(ObjRef::new(3, 0), Object::Int(7));
|
||||
assert_eq!(edited.try_get(3).as_deref(), Ok(&Object::Int(7)));
|
||||
assert_eq!(doc.try_get(3), first, "the edit is the clone's alone");
|
||||
edited.free(ObjRef::new(3, 0));
|
||||
assert_eq!(edited.try_get(3).as_deref(), Ok(&Object::Null));
|
||||
}
|
||||
|
||||
/// A member of an object stream that can't be decoded (here, one that decodes past the document's
|
||||
/// stream limit) is decoded once: every later read, in a clone too, gives the same error without
|
||||
/// decoding the stream again. The stream itself loads, so no search of the file is involved.
|
||||
#[test]
|
||||
fn a_member_of_an_undecodable_object_stream_is_decoded_once() {
|
||||
let file = object_stream_file("3 0 ", &format!("<< /Hidden ({}) >>", "x".repeat(4096)), 0);
|
||||
let doc = Document::open_with_stream_limit(Arc::new(file), None, 1024).unwrap();
|
||||
OBJSTM_DECODES.with(|decodes| decodes.set(0));
|
||||
let first = doc.try_get(3);
|
||||
assert!(matches!(first, Err(CosError::Filter(_))), "{first:?}");
|
||||
for _ in 0..10 {
|
||||
assert_eq!(doc.try_get(3), first);
|
||||
}
|
||||
assert_eq!(doc.clone().try_get(3), first);
|
||||
assert_eq!(OBJSTM_DECODES.with(std::cell::Cell::get), 1, "decodes an object stream that can't be decoded");
|
||||
}
|
||||
|
||||
/// Clones share the cache, and an edit is one clone's alone: a member of an object stream that
|
||||
/// one clone freed or replaced still reads, in the others, from the file's stream.
|
||||
#[test]
|
||||
fn an_edited_object_stream_leaves_other_clones_members_alone() {
|
||||
let file = Arc::new(object_stream_file("3 0 ", "<< /Hidden (yes) >>", 0));
|
||||
let doc = Document::open(file.clone()).unwrap();
|
||||
let mut freed = doc.clone();
|
||||
freed.free(ObjRef::new(4, 0));
|
||||
assert_eq!(freed.try_get(3), Err(CosError::MissingObject(4)));
|
||||
assert_eq!(text_of(&doc, 3, b"Hidden").as_deref(), Some("yes"), "the free reached another clone");
|
||||
let doc = Document::open(file).unwrap();
|
||||
let mut replaced = doc.clone();
|
||||
let mut dict = Dict::new();
|
||||
dict.set(b"Type".to_vec(), Object::name("ObjStm"));
|
||||
dict.set(b"N".to_vec(), Object::Int(1));
|
||||
dict.set(b"First".to_vec(), Object::Int(4));
|
||||
replaced.set(ObjRef::new(4, 0), crate::Stream::from_raw(dict, b"3 0 << /Hidden (no) >>".to_vec()));
|
||||
assert_eq!(text_of(&replaced, 3, b"Hidden").as_deref(), Some("no"));
|
||||
assert_eq!(text_of(&doc, 3, b"Hidden").as_deref(), Some("yes"), "the replacement reached another clone");
|
||||
}
|
||||
|
||||
/// A member that failed to load from the file's object stream is kept as a failure, but replacing
|
||||
/// or freeing that stream forgets it: the member then reads from the edit.
|
||||
#[test]
|
||||
fn an_edited_object_stream_forgets_its_members_failures() {
|
||||
let file = Arc::new(object_stream_file("3 0 ", ") broken", 0));
|
||||
let mut doc = Document::open(file.clone()).unwrap();
|
||||
assert!(doc.try_get(3).is_err(), "the file's member does not parse");
|
||||
let mut dict = Dict::new();
|
||||
dict.set(b"Type".to_vec(), Object::name("ObjStm"));
|
||||
dict.set(b"N".to_vec(), Object::Int(1));
|
||||
dict.set(b"First".to_vec(), Object::Int(4));
|
||||
doc.set(ObjRef::new(4, 0), crate::Stream::from_raw(dict, b"3 0 << /Hidden (fixed) >>".to_vec()));
|
||||
assert_eq!(text_of(&doc, 3, b"Hidden").as_deref(), Some("fixed"), "the cached failure outlived the edit");
|
||||
assert!(doc.try_get(3).is_ok());
|
||||
let mut doc = Document::open(file).unwrap();
|
||||
assert!(matches!(doc.try_get(3), Err(CosError::Syntax { .. })), "the file's member does not parse");
|
||||
doc.free(ObjRef::new(4, 0));
|
||||
assert_eq!(doc.try_get(3), Err(CosError::MissingObject(4)), "the freed stream's member");
|
||||
}
|
||||
|
||||
/// An object stream framed by one clone's edit of its indirect `/Length` is that clone's alone:
|
||||
/// the others still read its members within the file's length.
|
||||
#[test]
|
||||
fn an_edited_object_stream_length_leaves_other_clones_members_alone() {
|
||||
let file = Arc::new(object_stream_file_with("3 0 ", "<< /Hidden (cut endstream here) >>", 0, true));
|
||||
let doc = Document::open(file).unwrap();
|
||||
let mut edited = doc.clone();
|
||||
// Ends the stream at the `endstream` inside the member's string.
|
||||
let cut = "3 0 << /Hidden (cut".len();
|
||||
edited.set(ObjRef::new(6, 0), Object::Int(cut as i64));
|
||||
assert_ne!(text_of(&edited, 3, b"Hidden").as_deref(), Some("cut endstream here"), "the edited length was not used");
|
||||
assert_eq!(text_of(&doc, 3, b"Hidden").as_deref(), Some("cut endstream here"), "the edited length reached another clone");
|
||||
}
|
||||
|
||||
/// A `/Length` read through one clone's edits and reused within the same load still keeps that
|
||||
/// load to the clone. Here the file's offsets are header-relative behind junk, so object 10's
|
||||
/// offset first lands on object 12, whose length (object 8, in the edited object stream 9) is
|
||||
/// read; object 10's own length then loads object stream 4, framed by object 8 too.
|
||||
#[test]
|
||||
fn a_reused_edited_length_leaves_other_clones_members_alone() {
|
||||
let mut out = b"%PDF-1.5\n".to_vec();
|
||||
let mut offs = [0usize; 13];
|
||||
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");
|
||||
};
|
||||
let stream = |dict: &str, data: &str| format!("<< {dict} >>\nstream\n{data}\nendstream").into_bytes();
|
||||
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 inner = "11 0 3 2 5 << /Hidden (cut endstream here) >>";
|
||||
obj(&mut out, 4, &stream("/Type /ObjStm /N 2 /First 9 /Length 8 0 R", inner));
|
||||
let lengths = format!("8 0 {}", inner.len());
|
||||
obj(&mut out, 9, &stream(&format!("/Type /ObjStm /N 1 /First 4 /Length {}", lengths.len()), &lengths));
|
||||
obj(&mut out, 12, &stream("/Length 8 0 R", &"x".repeat(40)));
|
||||
obj(&mut out, 10, &stream("/Length 11 0 R", "PDATA"));
|
||||
// A cross-reference stream: a hybrid file's /XRefStm is not looked for behind junk.
|
||||
let compressed = [(3, 4, 1), (8, 9, 0), (11, 4, 0)];
|
||||
let mut data = Vec::new();
|
||||
for (n, off) in offs.iter().enumerate() {
|
||||
let row = match compressed.iter().find(|c| c.0 == n) {
|
||||
Some(&(_, stream, index)) => [2, 0, stream, index],
|
||||
None if *off == 0 => [0, 0, 0, 0],
|
||||
None => {
|
||||
let [.., hi, lo] = u32::try_from(*off).unwrap().to_be_bytes();
|
||||
[1, hi, lo, 0]
|
||||
}
|
||||
};
|
||||
data.extend_from_slice(&row);
|
||||
}
|
||||
let table = out.len();
|
||||
let dict = format!("<< /Type /XRef /Size 14 /W [1 2 1] /Index [0 13] /Root 1 0 R /Length {} >>", data.len());
|
||||
out.extend_from_slice(format!("13 0 obj\n{dict}\nstream\n").as_bytes());
|
||||
out.extend_from_slice(&data);
|
||||
out.extend_from_slice(format!("\nendstream\nendobj\nstartxref\n{table}\n%%EOF\n").as_bytes());
|
||||
let mut file = vec![b'J'; offs[10] - offs[12] - 1];
|
||||
file.push(b'\n');
|
||||
file.extend_from_slice(&out);
|
||||
let doc = Document::open(Arc::new(file)).unwrap();
|
||||
let mut edited = doc.clone();
|
||||
let cut = "11 0 3 2 5 << /Hidden (cut".len();
|
||||
let mut dict = Dict::new();
|
||||
dict.set(b"Type".to_vec(), Object::name("ObjStm"));
|
||||
dict.set(b"N".to_vec(), Object::Int(1));
|
||||
dict.set(b"First".to_vec(), Object::Int(4));
|
||||
edited.set(ObjRef::new(9, 0), crate::Stream::from_raw(dict, format!("8 0 {cut}").into_bytes()));
|
||||
assert!(matches!(&*edited.get(ObjRef::new(10, 0)), Object::Stream(s) if &s.raw[..] == b"PDATA"));
|
||||
assert_ne!(text_of(&edited, 3, b"Hidden").as_deref(), Some("cut endstream here"), "the edited length was not used");
|
||||
assert_eq!(text_of(&doc, 3, b"Hidden").as_deref(), Some("cut endstream here"), "the edited length reached another clone");
|
||||
}
|
||||
|
||||
/// A classic table with `/Size` rows and object 0's free entry first, its subsection numbered
|
||||
/// `1 n` instead of `0 n` (#2676): every row is one number off.
|
||||
fn misnumbered_table(start: u32) -> Vec<u8> {
|
||||
@@ -1255,7 +1414,7 @@ fn temporary_reader_keeps_file_views_and_evicts_data_of_its_own() {
|
||||
// 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]));
|
||||
let size = held_bytes(&owned, &reader.document.data, 0);
|
||||
reader.document.cache.lock().unwrap().insert(3, Arc::new(owned), size);
|
||||
reader.document.cache.lock().unwrap().insert(3, Ok(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");
|
||||
}
|
||||
@@ -1468,8 +1627,14 @@ fn hybrid_reference_files_read_the_xref_stream_too() {
|
||||
/// stream puts it at position `member` of object stream 4, which holds `header` (the number
|
||||
/// and offset pairs) and then `members`.
|
||||
fn object_stream_file(header: &str, members: &str, member: u8) -> Vec<u8> {
|
||||
object_stream_file_with(header, members, member, false)
|
||||
}
|
||||
|
||||
/// [`object_stream_file`], with the stream's `/Length` in object 6 when `indirect_length`.
|
||||
fn object_stream_file_with(header: &str, members: &str, member: u8, indirect_length: bool) -> Vec<u8> {
|
||||
let mut out = b"%PDF-1.5\n".to_vec();
|
||||
let mut offs = [0usize; 6];
|
||||
let size = if indirect_length { 7 } else { 6 };
|
||||
let mut offs = vec![0usize; size];
|
||||
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());
|
||||
@@ -1480,7 +1645,8 @@ fn object_stream_file(header: &str, members: &str, member: u8) -> Vec<u8> {
|
||||
obj(&mut out, 2, b"<< /Type /Pages /Kids [] /Count 0 /Extra 3 0 R >>");
|
||||
let count = header.split_whitespace().count() / 2;
|
||||
let inner = format!("{header}{members}");
|
||||
let mut stm = format!("<< /Type /ObjStm /N {count} /First {} /Length {} >>\nstream\n", header.len(), inner.len()).into_bytes();
|
||||
let length = if indirect_length { "6 0 R".to_string() } else { inner.len().to_string() };
|
||||
let mut stm = format!("<< /Type /ObjStm /N {count} /First {} /Length {length} >>\nstream\n", header.len()).into_bytes();
|
||||
stm.extend_from_slice(inner.as_bytes());
|
||||
stm.extend_from_slice(b"\nendstream");
|
||||
obj(&mut out, 4, &stm);
|
||||
@@ -1489,13 +1655,16 @@ fn object_stream_file(header: &str, members: &str, member: u8) -> Vec<u8> {
|
||||
xs.extend_from_slice(&data);
|
||||
xs.extend_from_slice(b"\nendstream");
|
||||
obj(&mut out, 5, &xs);
|
||||
if indirect_length {
|
||||
obj(&mut out, 6, inner.len().to_string().as_bytes());
|
||||
}
|
||||
let table = out.len();
|
||||
out.extend_from_slice(b"xref\n0 6\n0000000000 65535 f \n");
|
||||
out.extend_from_slice(format!("xref\n0 {size}\n0000000000 65535 f \n").as_bytes());
|
||||
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 6 /Root 1 0 R /XRefStm {} >>\nstartxref\n{table}\n%%EOF\n", offs[5]).as_bytes());
|
||||
out.extend_from_slice(format!("trailer << /Size {size} /Root 1 0 R /XRefStm {} >>\nstartxref\n{table}\n%%EOF\n", offs[5]).as_bytes());
|
||||
out
|
||||
}
|
||||
|
||||
@@ -1849,6 +2018,105 @@ 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");
|
||||
}
|
||||
|
||||
/// A file whose object 3 (its `/Info`) can't be parsed: the rest reads.
|
||||
fn with_unreadable_info() -> Vec<u8> {
|
||||
build(
|
||||
&["<< /Type /Catalog /Pages 2 0 R >>", "<< /Type /Pages /Kids [] /Count 0 >>", "<< /Title (Report) /Author ) >>"],
|
||||
"/Root 1 0 R /Info 3 0 R",
|
||||
)
|
||||
}
|
||||
|
||||
/// An object that can't be parsed reads as null and is listed once, by number and generation,
|
||||
/// with why. Clones and scans share the list, an edit takes the object off it (in that document
|
||||
/// only), and a sound file lists nothing.
|
||||
#[test]
|
||||
fn unreadable_objects_are_listed_with_the_reason() {
|
||||
let doc = Document::open(Arc::new(with_unreadable_info())).unwrap();
|
||||
assert!(doc.unreadable_objects().is_empty(), "nothing has read object 3 yet");
|
||||
assert_eq!(*doc.get(ObjRef::new(3, 0)), Object::Null);
|
||||
assert!(doc.try_get(3).is_err());
|
||||
let lines = doc.unreadable_objects();
|
||||
assert_eq!(lines.len(), 1, "read twice, listed once: {lines:?}");
|
||||
assert!(lines[0].starts_with("object 3 0 could not be read: syntax error"), "{lines:?}");
|
||||
let scanned = doc.clone();
|
||||
assert_eq!(scanned.scan_objects_checked().filter(|(_, o)| o.is_err()).count(), 1);
|
||||
assert_eq!(doc.unreadable_objects(), lines, "the scan found the same object");
|
||||
let unread = Document::open(Arc::new(with_unreadable_info())).unwrap();
|
||||
let scanned = unread.clone();
|
||||
assert_eq!(scanned.scan_objects_checked().filter(|(_, o)| o.is_err()).count(), 1);
|
||||
assert_eq!(unread.unreadable_objects(), lines, "a clone's scan reaches the original");
|
||||
let mut edited = doc.clone();
|
||||
edited.set(ObjRef::new(3, 0), Object::Dict(Dict::new()));
|
||||
assert!(edited.unreadable_objects().is_empty(), "the edit replaced it");
|
||||
assert_eq!(doc.unreadable_objects(), lines);
|
||||
let sound =
|
||||
build(&["<< /Type /Catalog /Pages 2 0 R >>", "<< /Type /Pages /Kids [] /Count 0 >>", "<< /Title (Report) >>"], "/Root 1 0 R /Info 3 0 R");
|
||||
let sound = Document::open(Arc::new(sound)).unwrap();
|
||||
assert_eq!(sound.scan_objects_checked().filter(|(_, o)| o.is_err()).count(), 0);
|
||||
assert!(sound.unreadable_objects().is_empty());
|
||||
}
|
||||
|
||||
/// A file rebuilt from its object headers still lists an object the scan could not read.
|
||||
#[test]
|
||||
fn a_rebuilt_file_lists_the_objects_its_scan_could_not_read() {
|
||||
let text = "%PDF-1.7\n1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n2 0 obj\n<< /Type /Pages /Kids [] /Count 0 >>\nendobj\n3 0 obj\n<< /A ) >>\nendobj\n%%EOF\n";
|
||||
let doc = Document::open(Arc::new(text.as_bytes().to_vec())).unwrap();
|
||||
assert!(doc.repair_log().iter().any(|l| l.starts_with("rebuilt cross-reference index")), "{:?}", doc.repair_log());
|
||||
let lines = doc.unreadable_objects();
|
||||
assert_eq!(lines.len(), 1, "{lines:?}");
|
||||
assert!(lines[0].starts_with("object 3 0 could not be read: syntax error"), "{lines:?}");
|
||||
}
|
||||
|
||||
/// The list keeps at most 100 objects and then says there were more; an object whose
|
||||
/// cross-reference offset holds no object is listed with that as its reason.
|
||||
#[test]
|
||||
fn the_unreadable_object_list_is_bounded() {
|
||||
let mut bodies = vec!["<< /Type /Catalog /Pages 2 0 R >>", "<< /Type /Pages /Kids [] /Count 0 >>"];
|
||||
bodies.extend(std::iter::repeat_n("<< /A ) >>", 120));
|
||||
let doc = Document::open(Arc::new(build(&bodies, "/Root 1 0 R"))).unwrap();
|
||||
assert_eq!(doc.scan_objects_checked().filter(|(_, o)| o.is_err()).count(), 120);
|
||||
let lines = doc.unreadable_objects();
|
||||
assert_eq!(lines.len(), 101, "{:?}", lines.last());
|
||||
assert!(lines[0].starts_with("object 3 0 could not be read"), "{}", lines[0]);
|
||||
assert_eq!(lines[100], "more objects could not be read; only the first 100 are listed");
|
||||
|
||||
let base = build(&["<< /Type /Catalog /Pages 2 0 R >>", "<< /Type /Pages /Kids [] /Count 0 >>", "(three)"], "/Root 1 0 R");
|
||||
let text = String::from_utf8_lossy(&base).into_owned();
|
||||
let gone = text.replacen("3 0 obj\n(three)", "9 0 obj\n(three)", 1);
|
||||
let doc = Document::open(Arc::new(gone.into_bytes())).unwrap();
|
||||
assert!(doc.try_get(3).is_err());
|
||||
assert_eq!(
|
||||
doc.unreadable_objects(),
|
||||
["object 3 0 could not be read: no readable copy was found at its cross-reference offset or elsewhere in the file"]
|
||||
);
|
||||
}
|
||||
|
||||
/// The unreadable list is shared by clones, and each hides what it has edited. A clone that edited
|
||||
/// every listed object still lists its own failures: hidden entries don't use up its allowance.
|
||||
#[test]
|
||||
fn objects_a_clone_edited_do_not_use_up_its_unreadable_allowance() {
|
||||
let mut bodies = vec!["<< /Type /Catalog /Pages 2 0 R >>", "<< /Type /Pages /Kids [] /Count 0 >>"];
|
||||
bodies.extend(std::iter::repeat_n("<< /A ) >>", 110));
|
||||
let doc = Document::open(Arc::new(build(&bodies, "/Root 1 0 R"))).unwrap();
|
||||
for num in 3..103 {
|
||||
assert!(doc.try_get(num).is_err());
|
||||
}
|
||||
assert_eq!(doc.unreadable_objects().len(), 100);
|
||||
let mut edited = doc.clone();
|
||||
for num in 3..103 {
|
||||
edited.set(ObjRef::new(num, 0), Object::Null);
|
||||
}
|
||||
for num in 103..113 {
|
||||
assert!(edited.try_get(num).is_err());
|
||||
}
|
||||
let lines = edited.unreadable_objects();
|
||||
assert_eq!(lines.len(), 10, "{lines:?}");
|
||||
assert!(lines[0].starts_with("object 103 0 could not be read"), "{}", lines[0]);
|
||||
let original = doc.unreadable_objects();
|
||||
assert_eq!(original.len(), 101, "the original still shows at most 100, then says there were more");
|
||||
assert_eq!(original[100], "more objects could not be read; only the first 100 are listed");
|
||||
}
|
||||
|
||||
#[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
|
||||
@@ -1884,10 +2152,10 @@ fn the_object_cache_keeps_its_total_as_objects_come_and_go() {
|
||||
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);
|
||||
cache.insert(1, Ok(one.clone()), a);
|
||||
cache.insert(2, Ok(two), b);
|
||||
assert_eq!(cache.owned(), a + b);
|
||||
cache.insert(2, one, a);
|
||||
cache.insert(2, Ok(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));
|
||||
@@ -1921,3 +2189,29 @@ fn the_editor_cache_charges_a_dictionary_for_the_values_it_holds() {
|
||||
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");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn find_agrees_with_a_plain_window_search() {
|
||||
let naive = |hay: &[u8], needle: &[u8], from: usize, to: usize| {
|
||||
if from >= to || needle.is_empty() || to - from < needle.len() {
|
||||
return None;
|
||||
}
|
||||
hay[from..to].windows(needle.len()).position(|w| w == needle).map(|p| p + from)
|
||||
};
|
||||
let mut seed = 0x9E37_79B9_7F4A_7C15u64;
|
||||
let mut next = move || {
|
||||
seed ^= seed << 13;
|
||||
seed ^= seed >> 7;
|
||||
seed ^= seed << 17;
|
||||
seed
|
||||
};
|
||||
let alphabet = b"/XRef t\n<>0";
|
||||
for _ in 0..20_000 {
|
||||
let hay: Vec<u8> = (0..next() % 200).map(|_| alphabet[(next() % alphabet.len() as u64) as usize]).collect();
|
||||
let needles: [&[u8]; 5] = [b"/XRef", b"trailer", b"R", b"ff", b"<<"];
|
||||
let needle = needles[(next() % 5) as usize];
|
||||
let from = (next() % (hay.len() as u64 + 1)) as usize;
|
||||
let to = from + (next() % (hay.len() as u64 + 1 - from as u64)) as usize;
|
||||
assert_eq!(find(&hay, needle, from, to), naive(&hay, needle, from, to), "{hay:?} {needle:?} {from} {to}");
|
||||
}
|
||||
}
|
||||
@@ -297,13 +297,18 @@ impl Stream {
|
||||
|
||||
/// [`Stream::decoded_within`] for a caller charging an allowance: the filter error is kept
|
||||
/// typed, so a caller can tell a spent limit from corrupt data, `max` bounds all filter
|
||||
/// stages together, and the result gives the bytes they decoded (the work done, on success
|
||||
/// and on failure).
|
||||
pub(crate) fn decoded_within_counted(&self, max: usize) -> Result<(Vec<u8>, usize), (pdfcraft_filters::FilterError, usize)> {
|
||||
/// stages together, and the result gives whether the data stopped at damage (it is then what
|
||||
/// decoded before it) and the bytes the stages decoded (the work done, on success and on
|
||||
/// failure).
|
||||
pub(crate) fn decoded_within_counted(&self, max: usize) -> Result<(Vec<u8>, bool, usize), (pdfcraft_filters::FilterError, usize)> {
|
||||
let mut damaged = false;
|
||||
let decode = |chain: &[(Filter, Params)], data: &[u8], max| {
|
||||
pdfcraft_filters::decode_tolerant_counted(chain, data, max).map(|(v, _, spent)| (v, spent))
|
||||
pdfcraft_filters::decode_tolerant_counted(chain, data, max).map(|(v, partial, spent)| {
|
||||
damaged = partial;
|
||||
(v, spent)
|
||||
})
|
||||
};
|
||||
self.decode_chain(max, decode)
|
||||
self.decode_chain(max, decode).map(|(v, spent)| (v, damaged, spent))
|
||||
}
|
||||
|
||||
/// [`Stream::decoded_within`] spending from `work`, what an operation may still do across a
|
||||
@@ -337,8 +342,14 @@ impl Stream {
|
||||
|
||||
/// Decoded data, bounded by [`MAX_DECODED`]; any corruption is an error.
|
||||
pub fn decoded_strict(&self) -> Result<Vec<u8>, CosError> {
|
||||
self.decoded_strict_within(MAX_DECODED)
|
||||
}
|
||||
|
||||
/// Like [`Stream::decoded_strict`], bounded by `max` (and [`MAX_DECODED`]): for data that
|
||||
/// will be copied elsewhere, where a damaged stream must not pass for a shorter one.
|
||||
pub fn decoded_strict_within(&self, max: usize) -> Result<Vec<u8>, CosError> {
|
||||
let decode = |chain: &[(Filter, Params)], data: &[u8], max| pdfcraft_filters::decode(chain, data, max).map(|v| (v, 0)).map_err(|e| (e, 0));
|
||||
self.decode_chain(MAX_DECODED, decode).map(|(v, _)| v).map_err(|(e, _)| CosError::Filter(e.to_string()))
|
||||
self.decode_chain(max, decode).map(|(v, _)| v).map_err(|(e, _)| CosError::Filter(e.to_string()))
|
||||
}
|
||||
|
||||
/// [`Stream::decoded_strict`] bounded by `max` and counted like
|
||||
|
||||
+129
-21
@@ -15,7 +15,7 @@ use std::io::Write;
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::CosError;
|
||||
use crate::document::{Document, ObjectReader, XrefEntry};
|
||||
use crate::document::{Document, ObjectReader, XrefEntry, held_bytes};
|
||||
use crate::object::{Dict, ObjRef, Object, PdfString, Stream};
|
||||
|
||||
/// Serialize one object. Deterministic: same object → same bytes.
|
||||
@@ -23,9 +23,7 @@ pub fn serialize(o: &Object, out: &mut Vec<u8>) {
|
||||
match o {
|
||||
Object::Null => out.extend_from_slice(b"null"),
|
||||
Object::Bool(b) => out.extend_from_slice(if *b { b"true" } else { b"false" }),
|
||||
Object::Int(i) => {
|
||||
let _ = write!(out, "{i}");
|
||||
}
|
||||
Object::Int(i) => write_int(*i, out),
|
||||
Object::Real(r) => write_real(*r, out),
|
||||
Object::String(s) => write_string(s, out),
|
||||
Object::Name(n) => write_name(n, out),
|
||||
@@ -42,11 +40,46 @@ pub fn serialize(o: &Object, out: &mut Vec<u8>) {
|
||||
Object::Dict(d) => write_dict(d, out),
|
||||
Object::Stream(s) => write_stream(s, out),
|
||||
Object::Ref(r) => {
|
||||
let _ = write!(out, "{} {} R", r.num, r.generation);
|
||||
write_digits(u64::from(r.num), out);
|
||||
out.push(b' ');
|
||||
write_digits(u64::from(r.generation), out);
|
||||
out.extend_from_slice(b" R");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Upper-case hexadecimal digits.
|
||||
const HEX: &[u8; 16] = b"0123456789ABCDEF";
|
||||
|
||||
/// The decimal digits of `v`, the same bytes `write!(out, "{v}")` gives, without the formatter.
|
||||
fn write_digits(mut v: u64, out: &mut Vec<u8>) {
|
||||
// `u64::MAX` has 20 digits, so `at` never goes below 0.
|
||||
let mut buf = [0u8; 20];
|
||||
let mut at = buf.len();
|
||||
loop {
|
||||
at -= 1;
|
||||
buf[at] = b'0' + (v % 10) as u8;
|
||||
v /= 10;
|
||||
if v == 0 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
out.extend_from_slice(&buf[at..]);
|
||||
}
|
||||
|
||||
/// A signed integer in decimal, as `write!(out, "{i}")` writes it.
|
||||
fn write_int(i: i64, out: &mut Vec<u8>) {
|
||||
if i < 0 {
|
||||
out.push(b'-');
|
||||
}
|
||||
write_digits(i.unsigned_abs(), out);
|
||||
}
|
||||
|
||||
/// `b` as two upper-case hexadecimal digits.
|
||||
fn hex_pair(b: u8) -> [u8; 2] {
|
||||
[HEX[usize::from(b >> 4)], HEX[usize::from(b & 15)]]
|
||||
}
|
||||
|
||||
fn write_real(r: f64, out: &mut Vec<u8>) {
|
||||
if !r.is_finite() {
|
||||
out.push(b'0');
|
||||
@@ -55,7 +88,7 @@ fn write_real(r: f64, out: &mut Vec<u8>) {
|
||||
// A whole number is written as an integer only within the integer range Annex C gives
|
||||
// (±2³¹−1), so `4e9` or `1e30` stays a real token for readers with 32-bit integers.
|
||||
if r.fract() == 0.0 && r.abs() <= f64::from(i32::MAX) {
|
||||
let _ = write!(out, "{}", r as i32);
|
||||
write_int(i64::from(r as i32), out);
|
||||
return;
|
||||
}
|
||||
// Plain decimal notation (§7.3.3 has no exponents). Rust's `Display` for f64 prints the
|
||||
@@ -76,7 +109,8 @@ fn write_name(n: &[u8], out: &mut Vec<u8>) {
|
||||
if regular {
|
||||
out.push(b);
|
||||
} else {
|
||||
let _ = write!(out, "#{b:02X}");
|
||||
out.push(b'#');
|
||||
out.extend_from_slice(&hex_pair(b));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -84,9 +118,10 @@ fn write_name(n: &[u8], out: &mut Vec<u8>) {
|
||||
fn write_string(s: &PdfString, out: &mut Vec<u8>) {
|
||||
let binary = s.bytes.iter().filter(|b| !(b' '..=b'~').contains(*b) && !matches!(b, b'\n' | b'\r' | b'\t')).count();
|
||||
if s.hex || binary * 4 > s.bytes.len().max(1) {
|
||||
out.reserve(s.bytes.len().saturating_mul(2).saturating_add(2));
|
||||
out.push(b'<');
|
||||
for b in &s.bytes {
|
||||
let _ = write!(out, "{b:02X}");
|
||||
for &b in &s.bytes {
|
||||
out.extend_from_slice(&hex_pair(b));
|
||||
}
|
||||
out.push(b'>');
|
||||
return;
|
||||
@@ -105,7 +140,7 @@ fn write_string(s: &PdfString, out: &mut Vec<u8>) {
|
||||
0x0C => out.extend_from_slice(b"\\f"),
|
||||
b' '..=b'~' => out.push(b),
|
||||
_ => {
|
||||
let _ = write!(out, "\\{b:03o}");
|
||||
out.extend_from_slice(&[b'\\', b'0' + (b >> 6), b'0' + ((b >> 3) & 7), b'0' + (b & 7)]);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -275,14 +310,22 @@ pub fn write_incremental(doc: &Document, opts: &SaveOptions) -> Result<Vec<u8>,
|
||||
|
||||
/// The objects [`write_full`] writes: everything reachable from the trailer's /Root, /Info and
|
||||
/// /Encrypt and from its unknown entries, breadth-first, with the new number each gets
|
||||
/// (aliases of one slot included) and, in visit order, whether it is a stream.
|
||||
type SaveOrder = (HashMap<ObjRef, u32>, Vec<(ObjRef, bool)>);
|
||||
/// (aliases of one slot included) and, in visit order, whether it is a stream and the parsed
|
||||
/// object where the budget allowed keeping it.
|
||||
type SaveOrder = (HashMap<ObjRef, u32>, Vec<(ObjRef, bool)>, Vec<Option<Arc<Object>>>);
|
||||
|
||||
fn full_save_order(reader: &mut ObjectReader, trailer_in: &Dict) -> Result<SaveOrder, CosError> {
|
||||
/// Number the objects reachable from the trailer. `retain` keeps parsed objects for the write
|
||||
/// pass, up to the budget. A caller that needs only the numbers passes `false`, so the traversal
|
||||
/// holds no parsed objects beyond the current one.
|
||||
fn full_save_order(reader: &mut ObjectReader, trailer_in: &Dict, retain: bool) -> Result<SaveOrder, CosError> {
|
||||
// Breadth-first walk from the trailer, assigning new numbers in visit order.
|
||||
let mut map: HashMap<ObjRef, u32> = HashMap::new();
|
||||
// Record the type while traversing so classifying packed objects needs no second parse.
|
||||
let mut order: Vec<(ObjRef, bool)> = Vec::new();
|
||||
// The parsed object of each entry in `order`, kept for the write pass while the budget
|
||||
// allows it. Past the budget the write pass reads the object again.
|
||||
let mut kept: Vec<Option<Arc<Object>>> = Vec::new();
|
||||
let mut kept_budget = KeptObjects::default();
|
||||
let mut queue: VecDeque<ObjRef> = VecDeque::new();
|
||||
let visit_refs = |o: &Object, queue: &mut VecDeque<ObjRef>| collect_refs(o, &mut |r| queue.push_back(r));
|
||||
for key in [&b"Root"[..], b"Info", b"Encrypt"] {
|
||||
@@ -321,8 +364,9 @@ fn full_save_order(reader: &mut ObjectReader, trailer_in: &Dict) -> Result<SaveO
|
||||
map.insert(canonical, num);
|
||||
order.push((canonical, matches!(*o, Object::Stream(_))));
|
||||
visit_refs(&o, &mut queue);
|
||||
kept.push((retain && kept_budget.admit(&o, reader.document.bytes())).then_some(o));
|
||||
}
|
||||
Ok((map, order))
|
||||
Ok((map, order, kept))
|
||||
}
|
||||
|
||||
/// The object numbers a full save of `doc` would write: exactly the objects [`write_full`]
|
||||
@@ -331,7 +375,7 @@ fn full_save_order(reader: &mut ObjectReader, trailer_in: &Dict) -> Result<SaveO
|
||||
pub fn reachable_objects(doc: &Document) -> Result<HashSet<u32>, CosError> {
|
||||
let mut reader = doc.object_reader();
|
||||
let trailer_in = reader.document.trailer().clone();
|
||||
let (_, order) = full_save_order(&mut reader, &trailer_in)?;
|
||||
let (_, order, _) = full_save_order(&mut reader, &trailer_in, false)?;
|
||||
Ok(order.into_iter().map(|(r, _)| r.num).collect())
|
||||
}
|
||||
|
||||
@@ -345,7 +389,7 @@ pub fn write_full(doc: &Document, opts: &SaveOptions) -> Result<Vec<u8>, CosErro
|
||||
let mut reader = doc.object_reader();
|
||||
stamp_mod_date(&mut reader.document, opts);
|
||||
let trailer_in = reader.document.trailer().clone();
|
||||
let (map, order) = full_save_order(&mut reader, &trailer_in)?;
|
||||
let (map, order, mut kept) = full_save_order(&mut reader, &trailer_in, true)?;
|
||||
let version = reader.document.version().chars().take(3).collect::<String>();
|
||||
let version = if opts.object_streams && version.as_str() < "1.5" { "1.5".to_string() } else { version };
|
||||
let mut out = Vec::new();
|
||||
@@ -375,14 +419,14 @@ pub fn write_full(doc: &Document, opts: &SaveOptions) -> Result<Vec<u8>, CosErro
|
||||
let mut rows: BTreeMap<u32, Row> = BTreeMap::new();
|
||||
// Keep only references, not renamed copies of the entire object graph. Standalone
|
||||
// objects still precede object streams, preserving the established output order.
|
||||
let mut packed: Vec<(u32, ObjRef)> = Vec::new();
|
||||
let mut packed: Vec<(u32, ObjRef, Option<Arc<Object>>)> = Vec::new();
|
||||
for (i, (r, is_stream)) in order.iter().enumerate() {
|
||||
let num = output_number(i)?;
|
||||
let in_stream = opts.object_streams && !is_stream && !encryption_objects.contains(&num) && root_outside != Some(num);
|
||||
if in_stream {
|
||||
packed.push((num, *r));
|
||||
packed.push((num, *r, kept[i].take()));
|
||||
} else {
|
||||
let o = reread(&mut reader, *r, *is_stream)?;
|
||||
let o = written_object(&mut reader, *r, *is_stream, kept[i].take())?;
|
||||
let o = renumber(&prepared(&reader.document, r.num, num, 0, &o), &map);
|
||||
rows.insert(num, Row::InFile(out.len() as u64, 0));
|
||||
write_indirect(num, 0, &o, &mut out);
|
||||
@@ -392,9 +436,9 @@ pub fn write_full(doc: &Document, opts: &SaveOptions) -> Result<Vec<u8>, CosErro
|
||||
// individually: the whole stream is (§7.5.7, §7.6.2).
|
||||
let mut next = output_number(order.len())?;
|
||||
let mut batch = ObjectStreamBatch::default();
|
||||
for (num, reference) in packed {
|
||||
for (num, reference, parsed) in packed {
|
||||
let mut encoded = Vec::new();
|
||||
serialize(&renumber(&*reread(&mut reader, reference, false)?, &map), &mut encoded);
|
||||
serialize(&renumber(&*written_object(&mut reader, reference, false, parsed)?, &map), &mut encoded);
|
||||
if batch.count > 0 && batch.body.len().saturating_add(encoded.len()).saturating_add(1) > OBJSTM_BYTES {
|
||||
batch.flush(&reader.document, &mut next, &mut rows, &mut out)?;
|
||||
}
|
||||
@@ -428,6 +472,38 @@ pub fn write_full(doc: &Document, opts: &SaveOptions) -> Result<Vec<u8>, CosErro
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// What `write_full` keeps of the objects it parsed while numbering them, measured with
|
||||
/// [`held_bytes`] (the parsed tree and any data that is not a view into the file). Beyond the
|
||||
/// budget objects are read again when written, which bounds the memory of a save of a huge
|
||||
/// document.
|
||||
#[derive(Default)]
|
||||
struct KeptObjects {
|
||||
bytes: usize,
|
||||
}
|
||||
|
||||
impl KeptObjects {
|
||||
const BYTES: usize = 64 * 1024 * 1024;
|
||||
|
||||
/// Whether `object` still fits the budget; if so it is counted against it.
|
||||
fn admit(&mut self, object: &Object, data: &Arc<Vec<u8>>) -> bool {
|
||||
let bytes = self.bytes.saturating_add(held_bytes(object, data, 0));
|
||||
if bytes > Self::BYTES {
|
||||
return false;
|
||||
}
|
||||
self.bytes = bytes;
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
/// The object to write for `r`: the one parsed while numbering when it was kept, else `r` read
|
||||
/// again.
|
||||
fn written_object(reader: &mut ObjectReader, r: ObjRef, is_stream: bool, kept: Option<Arc<Object>>) -> Result<Arc<Object>, CosError> {
|
||||
match kept {
|
||||
Some(o) => Ok(o),
|
||||
None => reread(reader, r, is_stream),
|
||||
}
|
||||
}
|
||||
|
||||
/// Assemble the full rewrite's trailer and apply its identifier policy.
|
||||
fn full_save_trailer(doc: &Document, trailer_in: &Dict, map: &HashMap<ObjRef, u32>, opts: &SaveOptions, out: &[u8]) -> Dict {
|
||||
let mut trailer = Dict::new();
|
||||
@@ -935,6 +1011,38 @@ mod tests {
|
||||
Lexer::new(&out, 0).object().expect("parses")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn kept_objects_stop_at_their_byte_budget() {
|
||||
let data = Arc::new(Vec::new());
|
||||
let string = Object::String(PdfString::literal(vec![b'x'; 1000]));
|
||||
let array = Object::Array(vec![Object::Int(1), Object::Null]);
|
||||
let mut kept = KeptObjects::default();
|
||||
assert!(kept.admit(&string, &data) && kept.admit(&array, &data));
|
||||
assert_eq!(kept.bytes, held_bytes(&string, &data, 0) + held_bytes(&array, &data, 0));
|
||||
let mut full = KeptObjects { bytes: KeptObjects::BYTES - held_bytes(&string, &data, 0) + 1 };
|
||||
let before = full.bytes;
|
||||
assert!(!full.admit(&string, &data), "one byte over the budget");
|
||||
assert_eq!(full.bytes, before, "a refused object is not counted");
|
||||
let mut deep = Object::Null;
|
||||
for _ in 0..300 {
|
||||
deep = Object::Array(vec![deep]);
|
||||
}
|
||||
assert!(!KeptObjects::default().admit(&deep, &data), "nesting past the limit is never kept");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn kept_objects_count_names_and_dictionary_keys() {
|
||||
let data = Arc::new(Vec::new());
|
||||
let name = Object::Name(vec![b'n'; KeptObjects::BYTES + 1]);
|
||||
let mut kept = KeptObjects::default();
|
||||
assert!(!kept.admit(&name, &data), "a name over the byte budget is not kept");
|
||||
assert_eq!(kept.bytes, 0);
|
||||
let mut dict = Dict::new();
|
||||
dict.set(vec![b'k'; KeptObjects::BYTES + 1], Object::Null);
|
||||
assert!(!kept.admit(&Object::Dict(dict), &data), "nor a dictionary key");
|
||||
assert_eq!(kept.bytes, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_second_read_that_differs_fails_the_save_instead_of_writing_null() {
|
||||
let mut doc = Document::new_empty();
|
||||
|
||||
@@ -5,5 +5,6 @@ mod corpus;
|
||||
mod encryption;
|
||||
mod generations;
|
||||
mod proptests;
|
||||
mod serialize_format;
|
||||
mod shared_streams;
|
||||
mod writer;
|
||||
@@ -0,0 +1,116 @@
|
||||
//! `serialize` writes integers, references, hexadecimal strings, octal escapes and `#xx` name
|
||||
//! escapes with its own digit loops. They must give the bytes the standard formatter gives.
|
||||
|
||||
use pdfcraft_cos::{ObjRef, Object, PdfString, serialize};
|
||||
use proptest::prelude::*;
|
||||
|
||||
fn bytes_of(o: &Object) -> Vec<u8> {
|
||||
let mut v = Vec::new();
|
||||
serialize(o, &mut v);
|
||||
v
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn integer_extremes_and_digit_boundaries() {
|
||||
let mut cases = vec![0i64, 1, -1, 9, 10, 99, 100, i64::MAX, i64::MIN, i64::MIN + 1, i64::from(i32::MAX), i64::from(i32::MIN)];
|
||||
let mut p = 1i64;
|
||||
while let Some(next) = p.checked_mul(10) {
|
||||
cases.extend([next - 1, next, next + 1, -next]);
|
||||
p = next;
|
||||
}
|
||||
for i in cases {
|
||||
assert_eq!(bytes_of(&Object::Int(i)), i.to_string().into_bytes(), "{i}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reference_extremes() {
|
||||
for (n, g) in [(0, 0), (1, 0), (u32::MAX, u16::MAX), (10, 65535), (4_000_000_000, 7)] {
|
||||
assert_eq!(bytes_of(&Object::Ref(ObjRef::new(n, g))), format!("{n} {g} R").into_bytes());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_byte_value_in_hex_strings_octal_escapes_and_names() {
|
||||
let all: Vec<u8> = (0..=255).collect();
|
||||
let hex: String = all.iter().map(|b| format!("{b:02X}")).collect();
|
||||
assert_eq!(bytes_of(&Object::String(PdfString { bytes: all.clone(), hex: true })), format!("<{hex}>").into_bytes());
|
||||
// A literal string with a few control bytes escapes them in octal.
|
||||
let lit = bytes_of(&Object::String(PdfString { bytes: b"abcdefghijkl\x01\x7f\xffz".to_vec(), hex: false }));
|
||||
assert_eq!(lit, b"(abcdefghijkl\\001\\177\\377z)");
|
||||
let name = bytes_of(&Object::Name(all.clone()));
|
||||
let mut want = b"/".to_vec();
|
||||
for &b in &all {
|
||||
let regular = (b'!'..=b'~').contains(&b) && !matches!(b, b'(' | b')' | b'<' | b'>' | b'[' | b']' | b'{' | b'}' | b'/' | b'%' | b'#');
|
||||
if regular {
|
||||
want.push(b);
|
||||
} else {
|
||||
want.extend_from_slice(format!("#{b:02X}").as_bytes());
|
||||
}
|
||||
}
|
||||
assert_eq!(name, want);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn whole_real_at_i32_min_stays_a_real_token() {
|
||||
// -2^31 is outside the Annex C integer range (±2^31-1), so it keeps its trailing point.
|
||||
assert_eq!(bytes_of(&Object::Real(f64::from(i32::MIN))), b"-2147483648.");
|
||||
}
|
||||
|
||||
proptest! {
|
||||
#[test]
|
||||
fn integers_match_the_formatter(i in any::<i64>()) {
|
||||
prop_assert_eq!(bytes_of(&Object::Int(i)), format!("{i}").into_bytes());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn whole_reals_match_the_formatter(i in -i32::MAX..=i32::MAX) {
|
||||
prop_assert_eq!(bytes_of(&Object::Real(f64::from(i))), format!("{i}").into_bytes());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn references_match_the_formatter(n in any::<u32>(), g in any::<u16>()) {
|
||||
prop_assert_eq!(bytes_of(&Object::Ref(ObjRef::new(n, g))), format!("{n} {g} R").into_bytes());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hex_strings_match_the_formatter(bytes in proptest::collection::vec(any::<u8>(), 0..300)) {
|
||||
let mut want = String::from("<");
|
||||
for b in &bytes {
|
||||
want.push_str(&format!("{b:02X}"));
|
||||
}
|
||||
want.push('>');
|
||||
prop_assert_eq!(bytes_of(&Object::String(PdfString { bytes, hex: true })), want.into_bytes());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn binary_literal_strings_match_the_formatter(bytes in proptest::collection::vec(any::<u8>(), 0..300)) {
|
||||
// Mostly-binary input is written as hex; mostly-text input with escapes is a literal.
|
||||
let got = bytes_of(&Object::String(PdfString { bytes: bytes.clone(), hex: false }));
|
||||
let binary = bytes.iter().filter(|b| !(b' '..=b'~').contains(*b) && !matches!(b, b'\n' | b'\r' | b'\t')).count();
|
||||
let mut want = Vec::new();
|
||||
if binary * 4 > bytes.len().max(1) {
|
||||
want.push(b'<');
|
||||
for b in &bytes {
|
||||
want.extend_from_slice(format!("{b:02X}").as_bytes());
|
||||
}
|
||||
want.push(b'>');
|
||||
} else {
|
||||
want.push(b'(');
|
||||
for &b in &bytes {
|
||||
match b {
|
||||
b'(' | b')' | b'\\' => want.extend_from_slice(&[b'\\', b]),
|
||||
b'\n' => want.extend_from_slice(b"\\n"),
|
||||
b'\r' => want.extend_from_slice(b"\\r"),
|
||||
b'\t' => want.extend_from_slice(b"\\t"),
|
||||
0x08 => want.extend_from_slice(b"\\b"),
|
||||
0x0C => want.extend_from_slice(b"\\f"),
|
||||
b' '..=b'~' => want.push(b),
|
||||
_ => want.extend_from_slice(format!("\\{b:03o}").as_bytes()),
|
||||
}
|
||||
}
|
||||
want.push(b')');
|
||||
}
|
||||
prop_assert_eq!(got, want);
|
||||
}
|
||||
}
|
||||
@@ -183,12 +183,17 @@ fn image(doc: &Document, s: &Stream, budget: &mut ImageBudget) -> Result<(&'stat
|
||||
.unwrap_or(false);
|
||||
// In a PDF a CMYK JPEG's samples are ink amounts unless /Decode inverts them, while image
|
||||
// viewers read a CMYK JPEG file as inverted (Adobe's convention): as is, it would show as
|
||||
// a negative.
|
||||
let as_is_negative = jpeg && !inverted && matches!(space(doc, s.dict.get(b"ColorSpace")), Ok(Space::Cmyk));
|
||||
// a negative. The space is read once: an indexed one's lookup table is paid for each time.
|
||||
let read = (jpeg && !inverted).then(|| space(doc, s.dict.get(b"ColorSpace"), budget));
|
||||
let as_is_negative = matches!(read, Some(Ok(Space::Cmyk)));
|
||||
if jpeg && alpha.is_none() && key.is_none() && !as_is_negative {
|
||||
return as_is();
|
||||
}
|
||||
let mut space = if mask { Space::Gray } else { space(doc, s.dict.get(b"ColorSpace"))? };
|
||||
let mut space = match read {
|
||||
_ if mask => Space::Gray,
|
||||
Some(read) => read?,
|
||||
None => space(doc, s.dict.get(b"ColorSpace"), budget)?,
|
||||
};
|
||||
let (samples, bpc) = if jpeg {
|
||||
if !budget.pay_jpeg((w as u64).saturating_mul(h as u64).saturating_mul(space.components() as u64), &s.raw) {
|
||||
return Err(FilterError::Spent.to_string());
|
||||
@@ -436,7 +441,10 @@ impl Space {
|
||||
/// A lookup table holds at most 256 entries of 4 bytes; decoding stops well past that.
|
||||
const MAX_LOOKUP: usize = 64 << 10;
|
||||
|
||||
fn space(doc: &Document, cs: Option<&Object>) -> Result<Space, String> {
|
||||
/// The colour space `cs` names; an indexed one's lookup table is read within `budget`, as the
|
||||
/// image's samples are, since each image reads it again and its filters can do work that makes
|
||||
/// nothing.
|
||||
fn space(doc: &Document, cs: Option<&Object>, budget: &mut ImageBudget) -> Result<Space, String> {
|
||||
let Some(cs) = cs else { return Err("the image has no colour space".into()) };
|
||||
let cs = doc.resolve(cs);
|
||||
let unsupported = |n: &[u8]| Err(format!("{} images can't be exported yet", String::from_utf8_lossy(n)));
|
||||
@@ -470,7 +478,7 @@ fn space(doc: &Document, cs: Option<&Object>) -> Result<Space, String> {
|
||||
if nested {
|
||||
return Err("nested indexed colour spaces aren't valid".into());
|
||||
}
|
||||
let base = space(doc, a.get(1))?;
|
||||
let base = space(doc, a.get(1), budget)?;
|
||||
let hival = match a.get(2).map(|value| doc.resolve(value)).as_deref() {
|
||||
Some(Object::Int(value)) if (0..=255).contains(value) => *value as u8,
|
||||
_ => return Err("an indexed colour space with an invalid hival".into()),
|
||||
@@ -478,10 +486,14 @@ fn space(doc: &Document, cs: Option<&Object>) -> Result<Space, String> {
|
||||
let table = match a.get(3).map(|t| doc.resolve(t)).as_deref() {
|
||||
Some(Object::String(s)) => s.bytes.clone(),
|
||||
// Through its parameters given by reference too, as the image's samples.
|
||||
Some(Object::Stream(t)) => doc
|
||||
.with_direct_parms(t)
|
||||
.decoded_within(MAX_LOOKUP)
|
||||
.map_err(|_| "an indexed colour space with an oversized or damaged lookup table".to_string())?,
|
||||
Some(Object::Stream(t)) => {
|
||||
let refused = budget.refused();
|
||||
match budget.decode_filters(doc, t, MAX_LOOKUP) {
|
||||
Ok(table) => table,
|
||||
Err(_) if budget.refused() > refused => return Err(FilterError::Spent.to_string()),
|
||||
Err(_) => return Err("an indexed colour space with an oversized or damaged lookup table".into()),
|
||||
}
|
||||
}
|
||||
_ => return Err("an indexed colour space without a lookup table".into()),
|
||||
};
|
||||
Ok(Space::Indexed(Box::new(base), hival, table))
|
||||
|
||||
+133
-1
@@ -516,6 +516,129 @@ fn decoded(name: &str, bytes: &[u8], format: image::ImageFormat) -> Result<Embed
|
||||
Ok(rgba_image(rgba.as_raw(), rgba.dimensions(), (72.0, 72.0)))
|
||||
}
|
||||
|
||||
fn le16(b: &[u8], at: usize) -> Option<u16> {
|
||||
b.get(at..at + 2).map(|x| u16::from_le_bytes([x[0], x[1]]))
|
||||
}
|
||||
|
||||
/// How a PCX image holds its pixels: bits per plane and planes.
|
||||
#[derive(Clone, Copy, PartialEq)]
|
||||
enum PcxLayout {
|
||||
/// One byte per pixel per colour: each scanline has a red, a green and a blue row.
|
||||
Rgb,
|
||||
/// One byte per pixel, an index into the palette after the image (grey without one).
|
||||
Indexed,
|
||||
/// One bit per pixel in each of 1 to 4 planes, an index into the header's palette.
|
||||
Bits(usize),
|
||||
}
|
||||
|
||||
impl PcxLayout {
|
||||
fn of(bits: u8, planes: usize) -> Option<PcxLayout> {
|
||||
match (bits, planes) {
|
||||
(8, 3) => Some(PcxLayout::Rgb),
|
||||
(8, 1) => Some(PcxLayout::Indexed),
|
||||
(1, 1..=4) => Some(PcxLayout::Bits(planes)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The palette of a PCX image, and where its run-length coded scanlines end. An 8-bit image ends
|
||||
/// with a 0x0C byte and 256 colours; a one-plane bit image is black and white whatever its header
|
||||
/// holds; other bit images use the 16 colours at byte 16.
|
||||
fn pcx_palette(bytes: &[u8], layout: PcxLayout) -> (Vec<u8>, usize) {
|
||||
match layout {
|
||||
PcxLayout::Rgb => (Vec::new(), bytes.len()),
|
||||
PcxLayout::Indexed => match bytes.len().checked_sub(769).filter(|at| *at >= 128 && bytes.get(*at) == Some(&0x0C)) {
|
||||
Some(at) => (bytes.get(at + 1..).unwrap_or_default().to_vec(), at),
|
||||
None => ((0..=255u8).flat_map(|v| [v, v, v]).collect(), bytes.len()),
|
||||
},
|
||||
PcxLayout::Bits(1) => (vec![0, 0, 0, 255, 255, 255], bytes.len()),
|
||||
PcxLayout::Bits(_) => (bytes.get(16..64).unwrap_or_default().to_vec(), bytes.len()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The `rows` scanlines of `line` bytes each, decoded. A run may cross from one plane's row into the
|
||||
/// next, but not out of its scanline.
|
||||
fn pcx_scanlines(mut body: &[u8], rows: usize, line: usize) -> Option<Vec<u8>> {
|
||||
let mut out = Vec::new();
|
||||
out.try_reserve_exact(rows.checked_mul(line)?).ok()?;
|
||||
for row in 1..=rows {
|
||||
let end = row * line;
|
||||
while out.len() < end {
|
||||
let (&c, rest) = body.split_first()?;
|
||||
body = rest;
|
||||
if c < 0xC0 {
|
||||
out.push(c);
|
||||
continue;
|
||||
}
|
||||
let (&value, rest) = body.split_first()?;
|
||||
body = rest;
|
||||
let count = usize::from(c & 0x3F);
|
||||
if count > end - out.len() {
|
||||
return None;
|
||||
}
|
||||
out.resize(out.len() + count, value);
|
||||
}
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// The RGB samples of the `w` pixels of scanline `row` (planes `stride` bytes apart).
|
||||
fn pcx_row(out: &mut Vec<u8>, row: &[u8], w: usize, stride: usize, layout: PcxLayout, palette: &[u8]) {
|
||||
let at = |i: usize| row.get(i).copied().unwrap_or(0);
|
||||
for x in 0..w {
|
||||
let index = match layout {
|
||||
PcxLayout::Rgb => {
|
||||
out.extend([at(x), at(stride + x), at(2 * stride + x)]);
|
||||
continue;
|
||||
}
|
||||
PcxLayout::Indexed => usize::from(at(x)),
|
||||
PcxLayout::Bits(planes) => (0..planes).fold(0, |index, k| index | (usize::from(at(k * stride + x / 8) >> (7 - x % 8) & 1) << k)),
|
||||
};
|
||||
out.extend((0..3).map(|c| palette.get(index * 3 + c).copied().unwrap_or(0)));
|
||||
}
|
||||
}
|
||||
|
||||
/// A PCX image: a 128-byte header (size at 4-11, resolution at 12 and 14, plane count at 65, bytes
|
||||
/// per plane row at 66), then run-length coded scanlines, each holding one row of every plane.
|
||||
fn pcx(name: &str, bytes: &[u8]) -> Result<Embedded, CreateError> {
|
||||
let bad = |m: &str| CreateError::Image(name.into(), m.into());
|
||||
let header = bytes.get(..128).ok_or_else(|| bad("a damaged PCX header"))?;
|
||||
let word = |at: usize| le16(header, at).unwrap_or(0);
|
||||
let byte = |at: usize| header.get(at).copied().unwrap_or(0);
|
||||
let (bits, planes, stride) = (byte(3), usize::from(byte(65)), usize::from(word(66)));
|
||||
let (Some(w), Some(h)) = (word(8).checked_sub(word(4)), word(10).checked_sub(word(6))) else {
|
||||
return Err(bad("a damaged PCX header"));
|
||||
};
|
||||
let (w, h) = (usize::from(w) + 1, usize::from(h) + 1);
|
||||
if planes == 0 || stride == 0 {
|
||||
return Err(bad("a damaged PCX header"));
|
||||
}
|
||||
let layout = PcxLayout::of(bits, planes).ok_or_else(|| bad("this PCX plane layout is not supported"))?;
|
||||
if stride < (w * usize::from(bits)).div_ceil(8) {
|
||||
return Err(bad("a damaged PCX header"));
|
||||
}
|
||||
let line = planes * stride;
|
||||
if line.saturating_mul(h) > MAX_DECODED_BYTES || w.saturating_mul(h).saturating_mul(3) > MAX_DECODED_BYTES {
|
||||
return Err(bad("unusual PCX image size"));
|
||||
}
|
||||
let (palette, end) = pcx_palette(bytes, layout);
|
||||
let body = bytes.get(128..end).unwrap_or_default();
|
||||
let scanlines = pcx_scanlines(body, h, line).ok_or_else(|| bad("a damaged PCX body"))?;
|
||||
let mut data = Vec::new();
|
||||
data.try_reserve_exact(w * h * 3).map_err(|_| bad("not enough memory for this image"))?;
|
||||
for row in scanlines.chunks_exact(line) {
|
||||
pcx_row(&mut data, row, w, stride, layout, &palette);
|
||||
}
|
||||
let dpi = (f64::from(word(12)), f64::from(word(14)));
|
||||
let dpi = if dpi.0 > 0.0 && dpi.1 > 0.0 { dpi } else { (72.0, 72.0) };
|
||||
let mut d = Dict::new();
|
||||
d.set(b"ColorSpace".to_vec(), Object::name("DeviceRGB"));
|
||||
d.set(b"BitsPerComponent".to_vec(), Object::Int(8));
|
||||
let px = (u32::try_from(w).unwrap_or(0), u32::try_from(h).unwrap_or(0));
|
||||
Ok(Embedded { dict: d, data, filtered: false, smask: None, icc: None, px, dpi })
|
||||
}
|
||||
|
||||
/// Largest GIF logical screen, in pixels (4096×4096).
|
||||
const MAX_GIF_PIXELS: u64 = 1 << 24;
|
||||
|
||||
@@ -623,7 +746,13 @@ pub enum SourceKind {
|
||||
}
|
||||
|
||||
/// File extensions Create converts to PDF (images and plain text).
|
||||
pub const CONVERTIBLE: [&str; 12] = ["png", "jpg", "jpeg", "tif", "tiff", "gif", "bmp", "jp2", "j2k", "jpx", "txt", "text"];
|
||||
pub const CONVERTIBLE: [&str; 13] = ["png", "jpg", "jpeg", "tif", "tiff", "gif", "bmp", "jp2", "j2k", "jpx", "pcx", "txt", "text"];
|
||||
|
||||
/// A PCX file: its manufacturer byte, a version (1 was never used), run-length coding and 1 or 8
|
||||
/// bits per plane. `pcx` says when the rest of the header isn't one it can read.
|
||||
fn is_pcx(bytes: &[u8]) -> bool {
|
||||
bytes.first() == Some(&0x0A) && matches!(bytes.get(1), Some(0 | 2..=5)) && bytes.get(2) == Some(&1) && matches!(bytes.get(3), Some(1 | 8))
|
||||
}
|
||||
|
||||
/// A classic TIFF or a BigTIFF (version 43), in either byte order.
|
||||
fn is_tiff(bytes: &[u8]) -> bool {
|
||||
@@ -640,6 +769,7 @@ fn is_image(bytes: &[u8]) -> bool {
|
||||
|| bytes.starts_with(b"\x89PNG\r\n\x1a\n")
|
||||
|| is_tiff(bytes)
|
||||
|| is_gif(bytes)
|
||||
|| is_pcx(bytes)
|
||||
// JPEG 2000: a JP2 file or a raw codestream.
|
||||
|| bytes.starts_with(JP2_SIGNATURE)
|
||||
|| bytes.starts_with(&[0xFF, 0x4F, 0xFF, 0x51])
|
||||
@@ -675,6 +805,8 @@ fn embed(name: &str, bytes: &[u8], wanted: usize) -> Result<Vec<Embedded>, Creat
|
||||
Ok(vec![decoded(name, &pdfcraft_xfa::image::bmp_with_pixel_offset(bytes), image::ImageFormat::Bmp)?])
|
||||
} else if is_gif(bytes) {
|
||||
Ok(vec![decoded(name, bytes, image::ImageFormat::Gif)?])
|
||||
} else if is_pcx(bytes) {
|
||||
Ok(vec![pcx(name, bytes)?])
|
||||
} else if bytes.starts_with(JP2_SIGNATURE) || bytes.starts_with(&[0xFF, 0x4F, 0xFF, 0x51]) {
|
||||
Ok(vec![jpx(name, bytes)?])
|
||||
} else {
|
||||
|
||||
@@ -485,6 +485,82 @@ fn bigtiff_images_become_pages() {
|
||||
assert_eq!(media(&pages(&doc)[0]), [0.0, 0.0, 2.0, 1.0], "4×2 px at 144 dpi");
|
||||
}
|
||||
|
||||
/// A PCX header for a `w` by `h` image at 72 dpi.
|
||||
fn pcx_header(version: u8, bits: u8, planes: u8, stride: u16, w: u16, h: u16) -> Vec<u8> {
|
||||
let mut pcx = vec![0u8; 128];
|
||||
pcx[..4].copy_from_slice(&[0x0A, version, 1, bits]);
|
||||
pcx[8..10].copy_from_slice(&(w - 1).to_le_bytes());
|
||||
pcx[10..12].copy_from_slice(&(h - 1).to_le_bytes());
|
||||
pcx[12..14].copy_from_slice(&72u16.to_le_bytes());
|
||||
pcx[14..16].copy_from_slice(&72u16.to_le_bytes());
|
||||
pcx[65] = planes;
|
||||
pcx[66..68].copy_from_slice(&stride.to_le_bytes());
|
||||
pcx
|
||||
}
|
||||
|
||||
/// A 24-bit PCX: each scanline holds a red, a green and a blue row.
|
||||
#[test]
|
||||
fn pcx_images_become_pages() {
|
||||
let mut pcx = pcx_header(5, 8, 3, 2, 2, 2);
|
||||
pcx.extend_from_slice(&[10, 11, 20, 21, 30, 31]);
|
||||
pcx.extend_from_slice(&[40, 41, 50, 51, 60, 61]);
|
||||
let embedded = super::pcx("a.pcx", &pcx).unwrap();
|
||||
assert_eq!(embedded.data, [10, 20, 30, 11, 21, 31, 40, 50, 60, 41, 51, 61]);
|
||||
let doc = reopen(&from_images(&[("a.pcx".into(), pcx)]).unwrap());
|
||||
assert_eq!(pages(&doc).len(), 1);
|
||||
assert_eq!(media(&pages(&doc)[0]), [0.0, 0.0, 2.0, 2.0]);
|
||||
assert_eq!(image_of(&doc, 0).name(b"ColorSpace"), Some(&b"DeviceRGB"[..]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pcx_run_may_cross_planes_but_not_scanlines() {
|
||||
// 0xC4 repeats 7 four times: the red row and half of the green one
|
||||
let mut pcx = pcx_header(5, 8, 3, 2, 2, 1);
|
||||
pcx.extend_from_slice(&[0xC4, 7, 8, 9]);
|
||||
assert_eq!(super::pcx("a.pcx", &pcx).unwrap().data[..], [7, 7, 8, 7, 7, 9]);
|
||||
let mut pcx = pcx_header(5, 8, 3, 2, 2, 2);
|
||||
pcx.extend_from_slice(&[0xC8, 7, 1, 2, 3, 4]);
|
||||
assert!(super::pcx("a.pcx", &pcx).is_err(), "eight bytes in a six-byte scanline");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_8_bit_pcx_uses_its_palette_and_is_grey_without_one() {
|
||||
let mut pcx = pcx_header(5, 8, 1, 2, 2, 1);
|
||||
pcx.extend_from_slice(&[1, 2]);
|
||||
assert_eq!(super::pcx("a.pcx", &pcx).unwrap().data[..], [1, 1, 1, 2, 2, 2], "no palette: grey");
|
||||
pcx.push(0x0C);
|
||||
let mut palette = vec![0u8; 768];
|
||||
palette[3..9].copy_from_slice(&[9, 8, 7, 6, 5, 4]);
|
||||
pcx.extend_from_slice(&palette);
|
||||
assert_eq!(super::pcx("a.pcx", &pcx).unwrap().data[..], [9, 8, 7, 6, 5, 4]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bit_plane_pcx_images_read_their_palette() {
|
||||
// version 2, one plane: black and white
|
||||
let mut pcx = pcx_header(2, 1, 1, 2, 2, 1);
|
||||
pcx.extend_from_slice(&[0b1000_0000, 0]);
|
||||
assert!(from_images(&[("a.pcx".into(), pcx.clone())]).is_ok(), "an old version is still a PCX");
|
||||
assert_eq!(super::pcx("a.pcx", &pcx).unwrap().data[..], [255, 255, 255, 0, 0, 0]);
|
||||
// two planes: colour 3 is at byte 16 + 9
|
||||
let mut pcx = pcx_header(5, 1, 2, 1, 1, 1);
|
||||
pcx[25..28].copy_from_slice(&[1, 2, 3]);
|
||||
pcx.extend_from_slice(&[0x80, 0x80]);
|
||||
assert_eq!(super::pcx("a.pcx", &pcx).unwrap().data[..], [1, 2, 3]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn damaged_pcx_headers_and_bodies_are_refused() {
|
||||
let no_planes = pcx_header(5, 8, 0, 2, 2, 1);
|
||||
let no_stride = pcx_header(5, 8, 3, 0, 2, 1);
|
||||
let short_stride = pcx_header(5, 8, 3, 1, 2, 1);
|
||||
let short_body = pcx_header(5, 8, 3, 2, 2, 1);
|
||||
for bytes in [no_planes, no_stride, short_stride, short_body] {
|
||||
assert!(super::pcx("a.pcx", &bytes).is_err());
|
||||
}
|
||||
assert!(super::pcx("a.pcx", &[0x0A, 5, 1, 8]).is_err(), "no header");
|
||||
}
|
||||
|
||||
/// A synthetic ICC profile: a 128-byte header (size, device class, colour space, `acsp`) and
|
||||
/// some payload. Only the header is read.
|
||||
fn icc_profile(space: &[u8; 4]) -> Vec<u8> {
|
||||
@@ -2333,6 +2409,98 @@ fn flate_images_past_the_exports_allowance_are_left_out_with_the_reason() {
|
||||
assert_eq!(budget.refused(), 1);
|
||||
}
|
||||
|
||||
/// An indexed image's lookup table, given as a stream, is read within the export's allowance as
|
||||
/// the image's samples are: each image reads it again, and its filters can do work that makes
|
||||
/// nothing (Flate over empty blocks). Past the allowance the image is left out with the reason.
|
||||
#[test]
|
||||
fn a_lookup_table_is_read_within_the_exports_allowance() {
|
||||
use pdfcraft_cos::{Dict, Document, ImageBudget, Object, PdfString, Stream};
|
||||
let table = [255, 0, 0, 0, 0, 255];
|
||||
let lookup = Stream::flate(Dict::new(), &table);
|
||||
let exported = |as_stream: bool, work: u64| {
|
||||
let mut doc = Document::new_empty();
|
||||
let table = if as_stream { Object::Ref(doc.add(Object::Stream(lookup.clone()))) } else { Object::String(PdfString::literal(table.to_vec())) };
|
||||
let mut dict = Dict::new();
|
||||
dict.set(b"Subtype".to_vec(), Object::name("Image"));
|
||||
dict.set(b"Width".to_vec(), Object::Int(2));
|
||||
dict.set(b"Height".to_vec(), Object::Int(1));
|
||||
dict.set(b"BitsPerComponent".to_vec(), Object::Int(8));
|
||||
dict.set(b"ColorSpace".to_vec(), Object::Array(vec![Object::name("Indexed"), Object::name("DeviceRGB"), Object::Int(1), table]));
|
||||
let image = doc.add(Object::Stream(Stream::flate(dict, &[0, 1])));
|
||||
let mut budget = ImageBudget::with_work(work);
|
||||
let file = crate::extract::image_file_within(&doc, image, &mut budget);
|
||||
(file, work - budget.work_left(), budget.refused())
|
||||
};
|
||||
let (direct, image_alone, _) = exported(false, u64::MAX);
|
||||
let (streamed, both, _) = exported(true, u64::MAX);
|
||||
assert_eq!(streamed.unwrap(), direct.unwrap(), "the same picture");
|
||||
let read = (lookup.raw.len() + table.len()) as u64 + pdfcraft_filters::FLATE_READ_WORK * lookup.raw.len() as u64;
|
||||
assert_eq!(both, image_alone + read, "the table is paid for as it is read");
|
||||
let (refused, _, count) = exported(true, image_alone);
|
||||
assert!(refused.unwrap_err().contains("more image decoding than"));
|
||||
assert_eq!(count, 1);
|
||||
}
|
||||
|
||||
/// A JPEG's colour space is read once for an export, its lookup table paid for once: whether it is
|
||||
/// CMYK (a negative as is) and what its samples are both come from that reading. An indexed JPEG
|
||||
/// isn't valid, and is written as it is, but its soft mask makes it go on past the first. With the
|
||||
/// mask, a table the allowance can't pay for leaves the image out, with the reason.
|
||||
#[test]
|
||||
fn a_jpegs_lookup_table_is_paid_for_once() {
|
||||
use pdfcraft_cos::{Dict, Document, ImageBudget, Object, PdfString, Stream};
|
||||
let table = [255, 0, 0, 0, 0, 255];
|
||||
let lookup = Stream::flate(Dict::new(), &table);
|
||||
let mut jpeg = Vec::new();
|
||||
image::GrayImage::from_pixel(2, 1, image::Luma([1])).write_to(&mut std::io::Cursor::new(&mut jpeg), image::ImageFormat::Jpeg).unwrap();
|
||||
// `given`: None leaves the colour space out, Some(true) gives the table as a stream.
|
||||
let exported = |given: Option<bool>, work: u64| {
|
||||
let mut doc = Document::new_empty();
|
||||
let table = given.map(|as_stream| {
|
||||
if as_stream { Object::Ref(doc.add(Object::Stream(lookup.clone()))) } else { Object::String(PdfString::literal(table.to_vec())) }
|
||||
});
|
||||
let mut mask = Dict::new();
|
||||
for (k, v) in
|
||||
[("Subtype", Object::name("Image")), ("Width", Object::Int(2)), ("Height", Object::Int(1)), ("BitsPerComponent", Object::Int(8))]
|
||||
{
|
||||
mask.set(k.as_bytes().to_vec(), v);
|
||||
}
|
||||
mask.set(b"ColorSpace".to_vec(), Object::name("DeviceGray"));
|
||||
let mask = doc.add(Object::Stream(Stream::flate(mask, &[255, 128])));
|
||||
let mut dict = Dict::new();
|
||||
for (k, v) in
|
||||
[("Subtype", Object::name("Image")), ("Width", Object::Int(2)), ("Height", Object::Int(1)), ("BitsPerComponent", Object::Int(8))]
|
||||
{
|
||||
dict.set(k.as_bytes().to_vec(), v);
|
||||
}
|
||||
if let Some(table) = table {
|
||||
dict.set(b"ColorSpace".to_vec(), Object::Array(vec![Object::name("Indexed"), Object::name("DeviceRGB"), Object::Int(1), table]));
|
||||
}
|
||||
dict.set(b"Filter".to_vec(), Object::name("DCTDecode"));
|
||||
dict.set(b"SMask".to_vec(), Object::Ref(mask));
|
||||
let image = doc.add(Object::Stream(Stream::from_raw(dict, jpeg.clone())));
|
||||
let mut budget = ImageBudget::with_work(work);
|
||||
let file = crate::extract::image_file_within(&doc, image, &mut budget);
|
||||
(file, work - budget.work_left(), budget.refused())
|
||||
};
|
||||
let (direct, direct_cost, _) = exported(Some(false), u64::MAX);
|
||||
let (streamed, streamed_cost, _) = exported(Some(true), u64::MAX);
|
||||
assert_eq!(direct, Ok(("jpg", jpeg.clone())), "written as it is");
|
||||
assert_eq!(streamed, direct);
|
||||
let read = (lookup.raw.len() + table.len()) as u64 + pdfcraft_filters::FLATE_READ_WORK * lookup.raw.len() as u64;
|
||||
assert_eq!(streamed_cost, direct_cost + read, "one reading of the table");
|
||||
|
||||
// Without a colour space nothing is read after the soft mask, so this is what the mask costs.
|
||||
let (none, mask, _) = exported(None, u64::MAX);
|
||||
assert_eq!(none.unwrap_err(), "the image has no colour space");
|
||||
// Read first, the table would be refused a step short of the mask too, and the mask after it.
|
||||
assert!(read >= mask, "the table costs at least what the mask does");
|
||||
assert_eq!(exported(Some(true), mask - 1).2, 1, "the mask is read first, and refused alone");
|
||||
let (refused, _, count) = exported(Some(true), mask + read - 1);
|
||||
let refused = refused.unwrap_err();
|
||||
assert!(refused.contains("more image decoding than"), "{refused}");
|
||||
assert_eq!(count, 1, "refused at the table, and nothing after it asks to be paid for");
|
||||
}
|
||||
|
||||
/// A JPEG is written as it is, at no cost, unless something means decoding it, here a mask: that
|
||||
/// pays for its samples, and past the allowance the image goes, with the reason, as it would come out without
|
||||
/// its transparency otherwise.
|
||||
|
||||
@@ -31,7 +31,7 @@ use layout::Piece;
|
||||
pub(crate) use layout::WRAP_CALLS;
|
||||
pub use layout::{PASTE_STEP, first_undrawable, lines, paste_place, paste_rect, text_rect, text_width};
|
||||
pub use store::{add_content, delete_content, isolate_content, list_added, scan_markers, update_content};
|
||||
pub use types::{Added, AddedImage, AddedText, Align, CHAR_SPACING_LIMIT, Family, MarkerScan};
|
||||
pub use types::{Added, AddedImage, AddedText, Align, CHAR_SPACING_LIMIT, Family, Ink, MarkerScan};
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum Content {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use super::layout::{
|
||||
Piece, arabic_error, hebrew_error, is_arabic, is_hebrew, is_thai, latin_width, norm, shaped_layout, text_rect, thai_error, wrapped,
|
||||
};
|
||||
use super::types::{AddedText, Align, Family};
|
||||
use super::types::{AddedText, Align, Family, Ink};
|
||||
use super::{
|
||||
Content, Dict, Document, EditError, GlyphError, GlyphOutline, HashMap, HashSet, ObjRef, Object, PdfString, ShapedCluster, ShapedScript, Stream,
|
||||
align_code, literal, matrix_number, n, shaped_glyph, win_ansi,
|
||||
@@ -105,8 +105,7 @@ pub(super) fn draw_laid_shaped(
|
||||
fonts.set(name.clone().into_bytes(), Object::Ref(font));
|
||||
names.push(name);
|
||||
}
|
||||
let [cr, cg, cb] = t.color.map(|v| v.clamp(0.0, 1.0));
|
||||
out.extend(format!("BT {} {} {} rg\n", n(cr), n(cg), n(cb)).bytes());
|
||||
out.extend(format!("BT {}\n", t.fill_op()).bytes());
|
||||
if t.char_spacing != 0.0 {
|
||||
out.extend(format!("{} Tc\n", n(t.char_spacing)).bytes());
|
||||
}
|
||||
@@ -293,8 +292,7 @@ pub(super) fn draw(doc: &mut Document, c: &Content, view: [f64; 6], taken: &Dict
|
||||
}
|
||||
res.set(b"Font".to_vec(), Object::Dict(fonts));
|
||||
let r = text_rect(t);
|
||||
let [cr, cg, cb] = t.color.map(|v| v.clamp(0.0, 1.0));
|
||||
out.extend(format!("BT /{name} {} Tf {} {} {} rg\n", n(t.size), n(cr), n(cg), n(cb)).bytes());
|
||||
out.extend(format!("BT /{name} {} Tf {}\n", n(t.size), t.fill_op()).bytes());
|
||||
if t.char_spacing != 0.0 {
|
||||
out.extend(format!("{} Tc\n", n(t.char_spacing)).bytes());
|
||||
}
|
||||
@@ -355,6 +353,12 @@ pub(super) fn params(c: &Content) -> Dict {
|
||||
d.set(b"Font".to_vec(), Object::name(t.family.base_font(t.bold, t.italic)));
|
||||
d.set(b"Size".to_vec(), Object::Real(t.size));
|
||||
d.set(b"Color".to_vec(), arr(&t.color));
|
||||
// The ink beside its RGB look, which a reader that knows no ink keeps showing.
|
||||
match t.painted_ink() {
|
||||
Some(Ink::Gray(g)) => d.set(b"Gray".to_vec(), Object::Real(g)),
|
||||
Some(Ink::Cmyk(c)) => d.set(b"CMYK".to_vec(), arr(&c)),
|
||||
None => {}
|
||||
}
|
||||
d.set(b"Align".to_vec(), Object::Int(align_code(t.align)));
|
||||
// Each paragraph's own alignment, or null where it follows /Align.
|
||||
let aligns = crate::paragraph_align::tidy(t.aligns.clone(), t.align);
|
||||
|
||||
@@ -1,8 +1,33 @@
|
||||
use super::draw::{draw, params};
|
||||
use super::layout::{first_undrawable, is_thai, nums, shaped_arabic, thai_error};
|
||||
use super::types::{Added, AddedImage, AddedText, CHAR_SPACING_LIMIT, Family, MarkerScan, TAG};
|
||||
use super::types::{Added, AddedImage, AddedText, CHAR_SPACING_LIMIT, Family, Ink, MarkerScan, TAG};
|
||||
use super::{Content, Dict, Document, EditError, GlyphError, MarkKind, ObjRef, Object, Stream, align_from, check, contents, page_list, place_tagged};
|
||||
|
||||
/// A text item's gray or CMYK ink. Items written before inks, and an ink out of range or not
|
||||
/// made only of numbers (a `/Gray` name, a `/CMYK` entry that isn't a number), have none: the
|
||||
/// text paints in its RGB `/Color`.
|
||||
fn ink(doc: &Document, d: &Dict) -> Option<Ink> {
|
||||
let ink = if let Some(g) = d.get(b"Gray") {
|
||||
Ink::Gray(read_value(doc, g, Object::as_f64)?)
|
||||
} else {
|
||||
// Four entries or none: a longer array is never copied or read through.
|
||||
read_value(doc, d.get(b"CMYK")?, |cmyk| {
|
||||
let [c, m, y, k] = cmyk.as_array()?.as_slice() else { return None };
|
||||
Some(Ink::Cmyk([c.as_f64()?, m.as_f64()?, y.as_f64()?, k.as_f64()?]))
|
||||
})?
|
||||
};
|
||||
Some(ink).filter(|i| i.valid())
|
||||
}
|
||||
|
||||
/// `f` of `o`, a reference followed. A direct value is read where it is, never copied, so a
|
||||
/// large one a file puts there costs nothing to look at.
|
||||
fn read_value<T>(doc: &Document, o: &Object, f: impl FnOnce(&Object) -> T) -> T {
|
||||
match o {
|
||||
Object::Ref(_) => f(&doc.resolve(o)),
|
||||
direct => f(direct),
|
||||
}
|
||||
}
|
||||
|
||||
fn parse(doc: &Document, d: &Dict) -> Option<Content> {
|
||||
let r = nums(doc, d.get(b"Rect"));
|
||||
let rect: [f64; 4] = r.try_into().ok()?;
|
||||
@@ -21,7 +46,7 @@ fn parse(doc: &Document, d: &Dict) -> Option<Content> {
|
||||
.map(|a| a.iter().take(crate::paragraph_align::count(&text)).map(|v| v.as_int().map(|c| align_from(Some(c)))).collect())
|
||||
})
|
||||
.unwrap_or_default();
|
||||
Some(Content::Text(AddedText {
|
||||
let mut t = AddedText {
|
||||
rect,
|
||||
text,
|
||||
family,
|
||||
@@ -29,11 +54,19 @@ fn parse(doc: &Document, d: &Dict) -> Option<Content> {
|
||||
italic,
|
||||
size: d.get(b"Size").and_then(Object::as_f64).unwrap_or(12.0),
|
||||
color: if c.len() == 3 { [c[0], c[1], c[2]] } else { [0.0; 3] },
|
||||
ink: ink(doc, d),
|
||||
align,
|
||||
aligns: crate::paragraph_align::tidy(aligns, align),
|
||||
// Items written before character spacing have none.
|
||||
char_spacing: d.get(b"CharSpacing").and_then(Object::as_f64).filter(|v| v.is_finite()).unwrap_or(0.0),
|
||||
}))
|
||||
};
|
||||
// An ink whose look isn't the stored colour (a file edited by hand) is none.
|
||||
t.drop_stale_ink();
|
||||
// One that stands is the ink as painted, finer digits dropped, and its look.
|
||||
if let Some(i) = t.ink {
|
||||
t.set_ink(Some(i));
|
||||
}
|
||||
Some(Content::Text(t))
|
||||
}
|
||||
b"Image" => {
|
||||
let crop = nums(doc, d.get(b"Crop"));
|
||||
@@ -138,6 +171,9 @@ fn validate(c: &Content) -> Result<(), EditError> {
|
||||
"the character spacing must be between -{CHAR_SPACING_LIMIT} and {CHAR_SPACING_LIMIT} points"
|
||||
)));
|
||||
}
|
||||
if t.ink.is_some_and(|i| !i.valid()) {
|
||||
return Err(EditError::Invalid("a gray level and each CMYK value must be from 0 to 1".into()));
|
||||
}
|
||||
if (r[2] - r[0]).abs() < 1.0 {
|
||||
return Err(EditError::Invalid("the text box is too narrow".into()));
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use super::layout::norm;
|
||||
use super::{Content, MarkKind, ObjRef, Std14};
|
||||
use super::{Content, MarkKind, ObjRef, Std14, n};
|
||||
|
||||
pub(super) const TAG: &str = "Added";
|
||||
|
||||
@@ -90,6 +90,60 @@ pub enum Align {
|
||||
Justify,
|
||||
}
|
||||
|
||||
/// A device colour added text is painted in instead of RGB, for print files: a text's black in
|
||||
/// CMYK stays 100 K rather than a DeviceRGB black the printer separates into rich black.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub enum Ink {
|
||||
/// A DeviceGray level, from 0 (black) to 1 (white): painted with `g`.
|
||||
Gray(f64),
|
||||
/// DeviceCMYK `[c, m, y, k]`, each from 0 to 1 (`[0, 0, 0, 1]` is 100 K): painted with `k`.
|
||||
Cmyk([f64; 4]),
|
||||
}
|
||||
|
||||
impl Ink {
|
||||
/// Whether every component is a number from 0 to 1.
|
||||
pub fn valid(self) -> bool {
|
||||
self.components().iter().all(|v| v.is_finite() && (0.0..=1.0).contains(v))
|
||||
}
|
||||
|
||||
/// The ink as its operator paints it: each component to the thousandth that `g` and `k` are
|
||||
/// written with (as RGB's `rg`), so the item, what it reads back as and the page agree.
|
||||
pub fn painted(self) -> Ink {
|
||||
let round = |v: f64| (v * 1000.0).round() / 1000.0;
|
||||
match self {
|
||||
Ink::Gray(g) => Ink::Gray(round(g)),
|
||||
Ink::Cmyk(c) => Ink::Cmyk(c.map(round)),
|
||||
}
|
||||
}
|
||||
|
||||
fn components(&self) -> &[f64] {
|
||||
match self {
|
||||
Ink::Gray(g) => std::slice::from_ref(g),
|
||||
Ink::Cmyk(c) => c,
|
||||
}
|
||||
}
|
||||
|
||||
/// How the ink looks on screen: gray is the same level in each of red, green and blue
|
||||
/// (ISO 32000-2 §10.4.2.2), CMYK takes each colour plus black from 1 (§10.4.2.5).
|
||||
pub fn rgb(self) -> [f64; 3] {
|
||||
match self {
|
||||
Ink::Gray(g) => [g.clamp(0.0, 1.0); 3],
|
||||
Ink::Cmyk([c, m, y, k]) => [c, m, y].map(|v| 1.0 - (v + k).clamp(0.0, 1.0)),
|
||||
}
|
||||
}
|
||||
|
||||
/// The operator that makes this ink the fill colour, without a line end.
|
||||
pub(super) fn fill_op(self) -> String {
|
||||
match self {
|
||||
Ink::Gray(g) => format!("{} g", n(g.clamp(0.0, 1.0))),
|
||||
Ink::Cmyk(c) => {
|
||||
let [c, m, y, k] = c.map(|v| v.clamp(0.0, 1.0));
|
||||
format!("{} {} {} {} k", n(c), n(m), n(y), n(k))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct AddedText {
|
||||
/// The text box in display space; its width wraps the text and its top is the first line's
|
||||
@@ -100,7 +154,14 @@ pub struct AddedText {
|
||||
pub bold: bool,
|
||||
pub italic: bool,
|
||||
pub size: f64,
|
||||
/// The RGB colour: what the text is painted in, unless it has an [`AddedText::ink`] this is
|
||||
/// the look of.
|
||||
pub color: [f64; 3],
|
||||
/// A gray or CMYK ink the text is painted in, with `color` its look ([`Ink::rgb`]). Set it
|
||||
/// with [`AddedText::set_ink`] and the colour with [`AddedText::set_color`], which drops an
|
||||
/// ink the colour no longer shows; one left behind by setting `color` directly paints nothing
|
||||
/// ([`AddedText::painted_ink`]) until [`AddedText::drop_stale_ink`] forgets it.
|
||||
pub ink: Option<Ink>,
|
||||
pub align: Align,
|
||||
/// Extra space after every character, in points: the PDF's character spacing (`Tc`).
|
||||
pub char_spacing: f64,
|
||||
@@ -114,6 +175,44 @@ impl AddedText {
|
||||
pub fn paragraph_align(&self, i: usize) -> Align {
|
||||
crate::paragraph_align::align_of(&self.aligns, i, self.align)
|
||||
}
|
||||
|
||||
/// Paint the text in `ink` (its look becomes [`AddedText::color`]), or in RGB with `None`. An
|
||||
/// ink in range is kept as painted ([`Ink::painted`]); one out of range stays as given, for
|
||||
/// saving to refuse.
|
||||
pub fn set_ink(&mut self, ink: Option<Ink>) {
|
||||
let ink = ink.map(|i| if i.valid() { i.painted() } else { i });
|
||||
if let Some(i) = ink {
|
||||
self.color = i.rgb();
|
||||
}
|
||||
self.ink = ink;
|
||||
}
|
||||
|
||||
/// Paint the text in RGB `rgb`. Its ink stays only when `rgb` is the ink's own look; once
|
||||
/// gone it stays gone, so picking that look again later paints in RGB.
|
||||
pub fn set_color(&mut self, rgb: [f64; 3]) {
|
||||
self.color = rgb;
|
||||
self.drop_stale_ink();
|
||||
}
|
||||
|
||||
/// Forget an ink `color` no longer shows, so two styles that paint the same compare equal.
|
||||
pub fn drop_stale_ink(&mut self) {
|
||||
self.ink = self.painted_ink();
|
||||
}
|
||||
|
||||
/// The ink the text is painted in, or `None` for RGB: the one it has while `color` is still
|
||||
/// its look.
|
||||
pub fn painted_ink(&self) -> Option<Ink> {
|
||||
// Within rounding: a look read back from a file, or from a colour picker, is the same.
|
||||
self.ink.filter(|i| i.rgb().iter().zip(self.color).all(|(a, b)| (a - b).abs() < 1e-6))
|
||||
}
|
||||
|
||||
/// The operator that sets the text's fill colour, without a line end.
|
||||
pub(super) fn fill_op(&self) -> String {
|
||||
match self.painted_ink() {
|
||||
Some(ink) => ink.fill_op(),
|
||||
None => crate::marks::rgb(self.color),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for AddedText {
|
||||
@@ -126,6 +225,7 @@ impl Default for AddedText {
|
||||
italic: false,
|
||||
size: 12.0,
|
||||
color: [0.0; 3],
|
||||
ink: None,
|
||||
align: Align::Left,
|
||||
aligns: Vec::new(),
|
||||
char_spacing: 0.0,
|
||||
|
||||
@@ -208,7 +208,7 @@ pub(crate) fn restore(doc: &mut Document, page: &pdfcraft_model::Page) -> Result
|
||||
let same = |w: &ObjRef| match &*doc.get(*w) {
|
||||
Object::Stream(s) => {
|
||||
[TAG, &b"PCMark"[..], b"Subtype"].iter().all(|k| s.dict.get(k).is_none())
|
||||
&& DecodeBudget::new(SCAN_BYTES, 0).decode_strict(s).ok().as_deref() == Some(bytes.as_slice())
|
||||
&& DecodeBudget::new(SCAN_BYTES, 0).decode_strict(doc, s).ok().as_deref() == Some(bytes.as_slice())
|
||||
}
|
||||
_ => false,
|
||||
};
|
||||
@@ -248,7 +248,7 @@ fn restored_copy(doc: &Document, page: &pdfcraft_model::Page, copy: ObjRef) -> O
|
||||
return None;
|
||||
}
|
||||
let hash = note.get(b"Before")?.as_string()?;
|
||||
let bytes = DecodeBudget::new(SCAN_BYTES, 0).decode_strict(s).ok()?;
|
||||
let bytes = DecodeBudget::new(SCAN_BYTES, 0).decode_strict(doc, s).ok()?;
|
||||
let parsed = pdfcraft_content::parse(head(&bytes));
|
||||
// The `n` standing in for the fill, after exactly the operators that came before it.
|
||||
let fill = parsed.ops.get(index)?;
|
||||
@@ -384,11 +384,11 @@ fn scan(doc: &Document, p: &pdfcraft_model::Page, swap: Option<(ObjRef, &[u8])>)
|
||||
if b.len() > SCAN_BYTES.saturating_sub(total) {
|
||||
return None;
|
||||
}
|
||||
budget.decode_strict(&Stream::from_raw(Dict::new(), b.to_vec())).ok()?
|
||||
budget.decode_strict(doc, &Stream::from_raw(Dict::new(), b.to_vec())).ok()?
|
||||
}
|
||||
// Tolerant decoding can return an empty or partial stream after corruption.
|
||||
// That cannot prove which paint preceded the candidate backdrop.
|
||||
_ => budget.decode_strict(s).ok()?,
|
||||
_ => budget.decode_strict(doc, s).ok()?,
|
||||
};
|
||||
if bytes.len() > SCAN_BYTES.saturating_sub(total).saturating_sub(1) {
|
||||
return None;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//! A page's background colour: the colour the page is painted with before anything else, as
|
||||
//! Edit a PDF ▸ Background and many producers do it, for exports that keep a page colour (#2992).
|
||||
|
||||
use pdfcraft_content::{Matrix, Op, Pieces};
|
||||
use pdfcraft_content::{Matrix, Op};
|
||||
use pdfcraft_cos::{Dict, Document};
|
||||
|
||||
use crate::{EditError, Rgb};
|
||||
@@ -51,7 +51,7 @@ pub fn page_background(doc: &Document, page: usize) -> Result<Option<Rgb>, EditE
|
||||
let resources = p.dict.get(b"Resources").map(|r| doc.resolve(r)).and_then(|r| r.as_dict().cloned()).unwrap_or_default();
|
||||
let gstates = resources.get(b"ExtGState").map(|g| doc.resolve(g)).and_then(|g| g.as_dict().cloned()).unwrap_or_default();
|
||||
let streams = crate::text::content_streams(doc, &p.dict)?;
|
||||
let pieces = Pieces::join(&streams.iter().map(|(_, d)| d.as_slice()).collect::<Vec<_>>());
|
||||
let pieces = crate::text::joined(&streams);
|
||||
let ops = pieces.parse().ops;
|
||||
|
||||
let mut st = State { ctm: Matrix::IDENTITY, space: Space::Gray, fill: Some([0.0; 3]), alpha: 1.0, plain: true, clip: Some(Vec::new()) };
|
||||
|
||||
+82
-47
@@ -1,15 +1,15 @@
|
||||
//! Edit a PDF ▸ edit existing images and grouped artwork (Image/Form XObjects painted by `Do`
|
||||
//! in its own content streams), and changing one: move/resize/rotate/flip (the `Do` is wrapped in
|
||||
//! `q … cm … Q` with the extra transform), replace (it draws another XObject in the same place),
|
||||
//! or delete. Only the stream that draws it is rewritten, as a new object.
|
||||
//! delete, or ungroup grouped artwork (its content drawn in place, see `ungroup`). Only the stream that draws it is rewritten, as a new object.
|
||||
|
||||
use kurbo::{BezPath, Point, Shape};
|
||||
use pdfcraft_content::{Matrix, Op, Pieces, parse, serialize_ops};
|
||||
use pdfcraft_content::{Matrix, Op, parse, serialize_ops};
|
||||
use pdfcraft_cos::{Dict, Document, ObjRef, Object};
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::EditError;
|
||||
use crate::text::content_streams;
|
||||
use crate::text::{ContentStream, content_streams, joined};
|
||||
|
||||
/// The identity of a soft mask (`/SMask`) in the PDF graphics state.
|
||||
#[derive(Clone, Debug)]
|
||||
@@ -47,7 +47,7 @@ pub struct PageImage {
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
/// The content stream its `Do` (its first token) is in, and the `Do`'s index among the
|
||||
/// operators of the page's streams joined ([`Pieces`]).
|
||||
/// operators of the page's streams joined ([`pdfcraft_content::Pieces`]).
|
||||
pub stream: usize,
|
||||
op: usize,
|
||||
/// CTM before `Do`, excluding a Form's own Matrix.
|
||||
@@ -103,11 +103,6 @@ fn too_many_images() -> EditError {
|
||||
EditError::Invalid(format!("the page draws more than {MAX_PAGE_IMAGES} images"))
|
||||
}
|
||||
|
||||
/// The page's streams joined into the one stream they are: an operator may span two of them.
|
||||
fn joined(streams: &[(Object, Vec<u8>)]) -> Pieces {
|
||||
Pieces::join(&streams.iter().map(|(_, data)| data.as_slice()).collect::<Vec<_>>())
|
||||
}
|
||||
|
||||
fn page_of(doc: &Document, page: usize) -> Result<pdfcraft_model::Page, EditError> {
|
||||
pdfcraft_model::pages(doc).into_iter().nth(page).ok_or(EditError::NoSuchPage(page))
|
||||
}
|
||||
@@ -470,6 +465,9 @@ pub enum ImageChange {
|
||||
Arrange(ArrangeOrder),
|
||||
/// Remove any private crop on the image.
|
||||
RemoveCrop,
|
||||
/// Grouped Form artwork only: draw the form's content in place of its `Do`, so its text and
|
||||
/// pictures become the page's own and can be edited one by one (#2964).
|
||||
Ungroup,
|
||||
}
|
||||
|
||||
/// The user-space transform that maps box `from` onto box `to` (move and resize).
|
||||
@@ -532,12 +530,17 @@ fn exclusive_clip(ops: &[Op], op: usize) -> Option<(usize, Matrix)> {
|
||||
/// The `q cm … Q` whose only content after its `cm` is `start..=end` (a `Do`, or a balanced
|
||||
/// `q … Q` scope), with the index and value of that `cm`. Another transform of the same
|
||||
/// placement is folded into it, so repeated moves and resizes don't nest one more `q` each.
|
||||
fn enclosing_transform(ops: &[Op], start: usize, end: usize) -> Option<(usize, Matrix)> {
|
||||
/// None when its `Q` is at or past `hidden` ([`crate::text::first_op_after_damage`]): a stream
|
||||
/// between that wasn't read may draw in that `cm` too.
|
||||
fn enclosing_transform(ops: &[Op], start: usize, end: usize, hidden: usize) -> Option<(usize, Matrix)> {
|
||||
let at = start.checked_sub(1)?;
|
||||
let cm = ops.get(at)?;
|
||||
if !ops.get(at.checked_sub(1)?)?.is("q") || !ops.get(end.checked_add(1)?)?.is("Q") || !cm.is("cm") || cm.operands.len() != 6 {
|
||||
return None;
|
||||
}
|
||||
if end.checked_add(1)? >= hidden {
|
||||
return None;
|
||||
}
|
||||
let m = Matrix(cm.nums::<6>()?);
|
||||
m.0.iter().all(|v| v.is_finite()).then_some((at, m))
|
||||
}
|
||||
@@ -1057,7 +1060,9 @@ fn determine_arrange_spans(
|
||||
has_other_paint: bool,
|
||||
marked_unit: bool,
|
||||
) -> Result<(std::ops::Range<usize>, usize, usize, usize), EditError> {
|
||||
let scope = image_scopes(ops, target, "arranged")
|
||||
// Nothing is hidden for Arrange: it takes out the scope it finds, so a scope that closes past a
|
||||
// stream not read whole changes a stream past it, which `rewritten_contents` refuses.
|
||||
let scope = image_scopes(ops, target, "arranged", ops.len())
|
||||
.ok()
|
||||
.and_then(|s| s.isolated)
|
||||
.filter(|&(start, end, _)| start >= target_unit.start && end < target_unit.end);
|
||||
@@ -1191,13 +1196,7 @@ fn build_relocated_unit_ops(
|
||||
}
|
||||
|
||||
/// Change the stacking order of `img`, drawn on page `p` by its content streams `all`.
|
||||
fn arrange_image(
|
||||
doc: &mut Document,
|
||||
p: &pdfcraft_model::Page,
|
||||
all: &[(Object, Vec<u8>)],
|
||||
img: &PageImage,
|
||||
order: ArrangeOrder,
|
||||
) -> Result<(), EditError> {
|
||||
fn arrange_image(doc: &mut Document, p: &pdfcraft_model::Page, all: &[ContentStream], img: &PageImage, order: ArrangeOrder) -> Result<(), EditError> {
|
||||
let pieces = joined(all);
|
||||
let ops = pieces.parse().ops;
|
||||
let target = img.op;
|
||||
@@ -1264,7 +1263,7 @@ fn arrange_image(
|
||||
ops.get(dest_unit.start).map(|op| pieces.piece_of(op.span.start))
|
||||
};
|
||||
let owned_destination = destination_piece
|
||||
.filter(|piece| all.get(*piece).is_some_and(|(obj, _)| doc.resolve(obj).as_dict().is_some_and(|d| d.get(b"PCAdded").is_some())));
|
||||
.filter(|piece| all.get(*piece).is_some_and(|s| doc.resolve(&s.entry).as_dict().is_some_and(|d| d.get(b"PCAdded").is_some())));
|
||||
if let Some(piece) = owned_destination {
|
||||
let whole_unit = ops.iter().enumerate().all(|(index, op)| {
|
||||
let (first, last) = pieces.pieces_of(op);
|
||||
@@ -1439,13 +1438,14 @@ fn arrange_image(
|
||||
};
|
||||
|
||||
if let Some(piece) = owned_destination {
|
||||
let insertion = piece.saturating_add(usize::from(insert_after));
|
||||
crate::text::drawn_before_damage(all, insertion)?;
|
||||
let changed = pieces.splice([(target_span, removal_replacement)]);
|
||||
let contents = crate::text::rewritten_contents(doc, all, changed);
|
||||
let contents = crate::text::rewritten_contents(doc, all, changed)?;
|
||||
let mut list = match contents {
|
||||
Object::Array(list) => list,
|
||||
one => vec![one],
|
||||
};
|
||||
let insertion = piece.saturating_add(usize::from(insert_after));
|
||||
if insertion > list.len() {
|
||||
return Err(EditError::Invalid("the destination content stream is missing".into()));
|
||||
}
|
||||
@@ -1467,7 +1467,7 @@ fn arrange_image(
|
||||
}
|
||||
|
||||
let changed = pieces.splice(edits);
|
||||
let contents = crate::text::rewritten_contents(doc, all, changed);
|
||||
let contents = crate::text::rewritten_contents(doc, all, changed)?;
|
||||
doc.update_dict(p.obj, |d| d.set(b"Contents".to_vec(), contents))?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -1501,8 +1501,10 @@ impl ImageScopes {
|
||||
}
|
||||
}
|
||||
|
||||
/// [`ImageScopes`] of the `Do` at `target`. An image inside a text object cannot be `done`.
|
||||
fn image_scopes(ops: &[Op], target: usize, done: &str) -> Result<ImageScopes, EditError> {
|
||||
/// [`ImageScopes`] of the `Do` at `target`. An image inside a text object cannot be `done`. A scope
|
||||
/// still open at op `hidden` ([`crate::text::first_op_after_damage`]) holds a stream that wasn't
|
||||
/// read, which may paint there: it counts as painting something else.
|
||||
fn image_scopes(ops: &[Op], target: usize, done: &str, hidden: usize) -> Result<ImageScopes, EditError> {
|
||||
struct Scope {
|
||||
start: usize,
|
||||
matrix: Matrix,
|
||||
@@ -1521,6 +1523,11 @@ fn image_scopes(ops: &[Op], target: usize, done: &str) -> Result<ImageScopes, Ed
|
||||
let mut isolated = None;
|
||||
let mut outermost = None;
|
||||
for (index, op) in ops.iter().enumerate() {
|
||||
if index == hidden {
|
||||
for scope in &mut stack {
|
||||
scope.other_paint = true;
|
||||
}
|
||||
}
|
||||
match op.op.as_slice() {
|
||||
b"q" => {
|
||||
if stack.len() >= 256 {
|
||||
@@ -1606,20 +1613,26 @@ fn app_crop_ranges(ops: &[Op], start: usize, target: usize) -> Vec<std::ops::Ran
|
||||
}
|
||||
|
||||
/// Remove only crops written by PdfCraft, preserving the document author's clipping paths.
|
||||
fn remove_image_crop(doc: &mut Document, p: &pdfcraft_model::Page, all: &[(Object, Vec<u8>)], img: &PageImage) -> Result<(), EditError> {
|
||||
fn remove_image_crop(doc: &mut Document, p: &pdfcraft_model::Page, all: &[ContentStream], img: &PageImage) -> Result<(), EditError> {
|
||||
let pieces = joined(all);
|
||||
let ops = pieces.parse().ops;
|
||||
let target = img.op;
|
||||
let scope = image_scopes(&ops, target, "cropped")?;
|
||||
let Some((start, _, _)) = scope.transform_scope(target) else {
|
||||
return Err(EditError::Invalid("the image has no PdfCraft crop to remove".into()));
|
||||
let crops = |hidden| -> Result<Vec<std::ops::Range<usize>>, EditError> {
|
||||
let scope = image_scopes(&ops, target, "cropped", hidden)?;
|
||||
Ok(scope.transform_scope(target).map(|(start, _, _)| app_crop_ranges(&ops, start, target)).unwrap_or_default())
|
||||
};
|
||||
let crops = app_crop_ranges(&ops, start, target);
|
||||
if crops.is_empty() {
|
||||
return Err(EditError::Invalid("the image has no PdfCraft crop to remove".into()));
|
||||
let crops_there = crops(crate::text::first_op_after_damage(all, &pieces, &ops))?;
|
||||
if crops_there.is_empty() {
|
||||
// A crop in a scope that closes past a stream not read whole may clip what that stream draws.
|
||||
return Err(EditError::Invalid(if crops(ops.len())?.is_empty() {
|
||||
"the image has no PdfCraft crop to remove".into()
|
||||
} else {
|
||||
"the image's crop may also clip what a content stream that is damaged or can't be decoded draws, so it isn't removed".into()
|
||||
}));
|
||||
}
|
||||
let crops = crops_there;
|
||||
let changed = crate::text::splice(&pieces, &ops, |index| (Vec::new(), !crops.iter().any(|r| r.contains(&index))));
|
||||
let contents = crate::text::rewritten_contents(doc, all, changed);
|
||||
let contents = crate::text::rewritten_contents(doc, all, changed)?;
|
||||
doc.update_dict(p.obj, |d| d.set(b"Contents".to_vec(), contents))?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -1650,6 +1663,25 @@ pub fn change_image(doc: &mut Document, page: usize, index: usize, change: &Imag
|
||||
ImageChange::Crop(keep) => {
|
||||
return crop_image_impl(doc, &p, &all, &img, *keep);
|
||||
}
|
||||
ImageChange::Ungroup => {
|
||||
if !img.is_form {
|
||||
return Err(EditError::Invalid("only grouped Form artwork can be ungrouped".into()));
|
||||
}
|
||||
let res = p.dict.get(b"Resources").map(|x| doc.resolve(x)).and_then(|x| x.as_dict().cloned()).unwrap_or_default();
|
||||
let translucent = crate::ungroup::translucent_at(doc, &res, &ops, img.op);
|
||||
let space = crate::ungroup::page_blend_space(doc, &p.dict);
|
||||
let (inline, mut merged, patterns) =
|
||||
crate::ungroup::ungroup_ops(doc, &res, img.name.as_bytes(), translucent, space.as_ref(), Matrix(img.matrix))?;
|
||||
if !patterns.is_empty() {
|
||||
let mut table = merged.get(b"Pattern").map(|x| doc.resolve(x)).and_then(|x| x.as_dict().cloned()).unwrap_or_default();
|
||||
for (name, copy) in patterns {
|
||||
table.set(name, Object::Ref(doc.add(copy)));
|
||||
}
|
||||
merged.set(b"Pattern".to_vec(), Object::Dict(table));
|
||||
}
|
||||
resources = Some(merged);
|
||||
inline
|
||||
}
|
||||
ImageChange::Replace(r) => {
|
||||
if img.is_form {
|
||||
return Err(EditError::Invalid(
|
||||
@@ -1666,7 +1698,7 @@ pub fn change_image(doc: &mut Document, page: usize, index: usize, change: &Imag
|
||||
}
|
||||
};
|
||||
let changed = crate::text::splice(&pieces, &ops, |index| if index == img.op { (replacement.clone(), false) } else { (Vec::new(), true) });
|
||||
let contents = crate::text::rewritten_contents(doc, &all, changed);
|
||||
let contents = crate::text::rewritten_contents(doc, &all, changed)?;
|
||||
doc.update_dict(p.obj, |d| {
|
||||
d.set(b"Contents".to_vec(), contents);
|
||||
if let Some(res) = resources {
|
||||
@@ -1687,7 +1719,7 @@ pub(crate) fn selectable_images(
|
||||
Ok(page_images(doc, page)?
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.filter(|(_, image)| !all.get(image.stream).and_then(|(o, _)| o.as_ref()).is_some_and(|r| excluded.contains(&r)))
|
||||
.filter(|(_, image)| !all.get(image.stream).and_then(|s| s.entry.as_ref()).is_some_and(|r| excluded.contains(&r)))
|
||||
.collect())
|
||||
}
|
||||
|
||||
@@ -1700,7 +1732,7 @@ pub(crate) fn painted_over(doc: &Document, page: usize, rect: [f64; 4], from: us
|
||||
fn transform_image(
|
||||
doc: &mut Document,
|
||||
page: &pdfcraft_model::Page,
|
||||
streams: &[(Object, Vec<u8>)],
|
||||
streams: &[ContentStream],
|
||||
image: &PageImage,
|
||||
transform: [f64; 6],
|
||||
) -> Result<(), EditError> {
|
||||
@@ -1715,8 +1747,9 @@ fn transform_image(
|
||||
}
|
||||
// A private path crop moves with its image regardless of intervening state operators.
|
||||
// Shared crops retain the existing fixed-clip behavior, preserving neighbouring paint.
|
||||
let hidden = crate::text::first_op_after_damage(streams, &pieces, &ops);
|
||||
let (start, end, placement) =
|
||||
image_scopes(&ops, target, "transformed")?.transform_scope(target).unwrap_or((target, target, Matrix(image.draw_matrix)));
|
||||
image_scopes(&ops, target, "transformed", hidden)?.transform_scope(target).unwrap_or((target, target, Matrix(image.draw_matrix)));
|
||||
let inverse = placement.invert().ok_or_else(|| EditError::Invalid("the image has no area".into()))?;
|
||||
let local = placement.then(&Matrix(transform)).then(&inverse);
|
||||
if !local.0.iter().all(|v| v.is_finite() && v.abs() <= 1e12) {
|
||||
@@ -1725,7 +1758,7 @@ fn transform_image(
|
||||
|
||||
// Already alone in a `q cm … Q` (its own placement, or the wrapper an earlier edit added):
|
||||
// change that `cm` in place. The CTM inside is `local · cm · outer` either way.
|
||||
if let Some((at, cm)) = enclosing_transform(&ops, start, end) {
|
||||
if let Some((at, cm)) = enclosing_transform(&ops, start, end, hidden) {
|
||||
let folded = local.then(&cm);
|
||||
if !folded.0.iter().all(|v| v.is_finite() && v.abs() <= 1e12) {
|
||||
return Err(EditError::Invalid("the image transform is too large".into()));
|
||||
@@ -1733,7 +1766,7 @@ fn transform_image(
|
||||
let changed = crate::text::splice(&pieces, &ops, |index| {
|
||||
if index == at { (vec![Op::new("cm", folded.0.map(Object::Real).to_vec())], false) } else { (Vec::new(), true) }
|
||||
});
|
||||
let contents = crate::text::rewritten_contents(doc, streams, changed);
|
||||
let contents = crate::text::rewritten_contents(doc, streams, changed)?;
|
||||
doc.update_dict(page.obj, |d| d.set(b"Contents".to_vec(), contents))?;
|
||||
return Ok(());
|
||||
}
|
||||
@@ -1754,7 +1787,7 @@ fn transform_image(
|
||||
(Vec::new(), true)
|
||||
}
|
||||
});
|
||||
let contents = crate::text::rewritten_contents(doc, streams, changed);
|
||||
let contents = crate::text::rewritten_contents(doc, streams, changed)?;
|
||||
doc.update_dict(page.obj, |d| d.set(b"Contents".to_vec(), contents))?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -1766,7 +1799,7 @@ fn transform_image(
|
||||
fn crop_image_impl(
|
||||
doc: &mut Document,
|
||||
page: &pdfcraft_model::Page,
|
||||
streams: &[(Object, Vec<u8>)],
|
||||
streams: &[ContentStream],
|
||||
image: &PageImage,
|
||||
keep: [f64; 4],
|
||||
) -> Result<(), EditError> {
|
||||
@@ -1790,8 +1823,9 @@ fn crop_image_impl(
|
||||
if !ops.get(target).is_some_and(|op| op.is("Do")) {
|
||||
return Err(EditError::Invalid("the image operation could not be located".into()));
|
||||
}
|
||||
let (start, end, placement) =
|
||||
image_scopes(&ops, target, "cropped")?.transform_scope(target).unwrap_or((target, target, Matrix(image.draw_matrix)));
|
||||
let (start, end, placement) = image_scopes(&ops, target, "cropped", crate::text::first_op_after_damage(streams, &pieces, &ops))?
|
||||
.transform_scope(target)
|
||||
.unwrap_or((target, target, Matrix(image.draw_matrix)));
|
||||
let inverse = placement.invert().ok_or_else(|| EditError::Invalid("the image has no area".into()))?;
|
||||
let corners = [(x0, y0), (x1, y0), (x1, y1), (x0, y1)].map(|(x, y)| inverse.apply(x, y));
|
||||
if !corners.iter().all(|(x, y)| x.is_finite() && y.is_finite() && x.abs() <= 1e12 && y.abs() <= 1e12) {
|
||||
@@ -1844,7 +1878,7 @@ fn crop_image_impl(
|
||||
(Vec::new(), true)
|
||||
}
|
||||
});
|
||||
let contents = crate::text::rewritten_contents(doc, streams, changed);
|
||||
let contents = crate::text::rewritten_contents(doc, streams, changed)?;
|
||||
doc.update_dict(page.obj, |d| d.set(b"Contents".to_vec(), contents))?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -1872,6 +1906,7 @@ pub(crate) fn translate_images(doc: &mut Document, page: usize, indexes: &[usize
|
||||
}
|
||||
let pieces = joined(&all);
|
||||
let ops = pieces.parse().ops;
|
||||
let hidden = crate::text::first_op_after_damage(&all, &pieces, &ops);
|
||||
let mut inside_text = false;
|
||||
for (index, op) in ops.iter().enumerate() {
|
||||
if op.is("BT") {
|
||||
@@ -1889,7 +1924,7 @@ pub(crate) fn translate_images(doc: &mut Document, page: usize, indexes: &[usize
|
||||
let mut folds = std::collections::BTreeMap::new();
|
||||
for image in images.iter().filter(|image| image.has_editor_crop()) {
|
||||
let Some(&(_, _, offset)) = plans.get(&image.op) else { continue };
|
||||
let Some((start, end, placement)) = image_scopes(&ops, image.op, "moved")?.transform_scope(image.op) else {
|
||||
let Some((start, end, placement)) = image_scopes(&ops, image.op, "moved", hidden)?.transform_scope(image.op) else {
|
||||
return Err(EditError::Invalid("the image crop cannot be moved independently".into()));
|
||||
};
|
||||
let inverse = placement.invert().ok_or_else(|| EditError::Invalid("a selected image has no area".into()))?;
|
||||
@@ -1906,7 +1941,7 @@ pub(crate) fn translate_images(doc: &mut Document, page: usize, indexes: &[usize
|
||||
};
|
||||
// An enclosing cm is before the captured placement; an inside-scope cm is after it.
|
||||
// Their multiplication orders differ when that cm scales or shears a translation.
|
||||
let folded = enclosing_transform(&ops, start, end)
|
||||
let folded = enclosing_transform(&ops, start, end, hidden)
|
||||
.map(|(at, cm)| (at, local.then(&cm)))
|
||||
.or_else(|| leading_transform().map(|(at, cm)| (at, cm.then(&local))));
|
||||
if let Some((at, folded)) = folded {
|
||||
@@ -1942,7 +1977,7 @@ pub(crate) fn translate_images(doc: &mut Document, page: usize, indexes: &[usize
|
||||
// An image already alone in `q cm Do Q` moves by changing that `cm`, not by nesting another.
|
||||
for index in 0..ops.len() {
|
||||
let Some(&(movement, _, _)) = plans.get(&index) else { continue };
|
||||
let Some((at, cm)) = enclosing_transform(&ops, index, index) else { continue };
|
||||
let Some((at, cm)) = enclosing_transform(&ops, index, index, hidden) else { continue };
|
||||
let folded = movement.then(&cm);
|
||||
if !folded.0.iter().all(|v| v.is_finite() && v.abs() <= 1e12) {
|
||||
return Err(EditError::Invalid("the image move is too large".into()));
|
||||
@@ -1977,7 +2012,7 @@ pub(crate) fn translate_images(doc: &mut Document, page: usize, indexes: &[usize
|
||||
out.push(Op::new("Q", vec![]));
|
||||
(out, false)
|
||||
});
|
||||
let contents = crate::text::rewritten_contents(doc, &all, data);
|
||||
let contents = crate::text::rewritten_contents(doc, &all, data)?;
|
||||
doc.update_dict(p.obj, |d| d.set(b"Contents".to_vec(), contents))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -43,12 +43,15 @@ pub use backdrop::{Backdrop, backdrops_left_off, page_backdrop, page_backdrops};
|
||||
pub use text::strip_subset_tag;
|
||||
mod background;
|
||||
pub use background::page_background;
|
||||
mod rules;
|
||||
pub use rules::page_rules;
|
||||
pub mod objects;
|
||||
pub use objects::{EditableObject, MAX_MOVE_OBJECTS, ObjectKind, ObjectTarget, editable_objects, move_objects};
|
||||
|
||||
mod flatten;
|
||||
pub use flatten::{flatten, flatten_fill_sign};
|
||||
pub mod images;
|
||||
mod ungroup;
|
||||
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;
|
||||
@@ -61,8 +64,8 @@ pub use text::{
|
||||
};
|
||||
pub mod added;
|
||||
pub use added::{
|
||||
Added, AddedImage, AddedText, Align, Content, Family, MarkerScan, add_content, delete_content, first_undrawable, isolate_content, list_added,
|
||||
scan_markers, update_content,
|
||||
Added, AddedImage, AddedText, Align, Content, Family, Ink, MarkerScan, add_content, delete_content, first_undrawable, isolate_content,
|
||||
list_added, scan_markers, update_content,
|
||||
};
|
||||
|
||||
mod apply;
|
||||
|
||||
@@ -4,8 +4,9 @@
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
use pdfcraft_content::{Matrix, Op, Pieces};
|
||||
use pdfcraft_cos::{Dict, Document, Object};
|
||||
use pdfcraft_cos::{DecodeBudget, Dict, Document, Object};
|
||||
|
||||
use crate::text::ContentStream;
|
||||
use crate::{Content, EditError};
|
||||
|
||||
pub const MAX_MOVE_OBJECTS: usize = 1_000;
|
||||
@@ -152,7 +153,7 @@ fn added_geometry(doc: &Document, page: usize) -> Result<(Pieces, Vec<AddedGeome
|
||||
return Ok((Pieces::default(), Vec::new()));
|
||||
}
|
||||
let streams = checked_streams(doc, page)?;
|
||||
let pieces = Pieces::join(&streams.iter().map(|(_, bytes)| bytes.as_slice()).collect::<Vec<_>>());
|
||||
let pieces = crate::text::joined(&streams);
|
||||
let ops = pieces.parse().ops;
|
||||
let owned: BTreeSet<_> = added.iter().map(|a| a.obj).collect();
|
||||
let mut geometry = BTreeMap::new();
|
||||
@@ -161,7 +162,7 @@ fn added_geometry(doc: &Document, page: usize) -> Result<(Pieces, Vec<AddedGeome
|
||||
let mut stack = Vec::new();
|
||||
for (index, op) in ops.iter().enumerate() {
|
||||
let (stream, end) = pieces.pieces_of(op);
|
||||
let object = streams.get(stream).and_then(|(r, _)| r.as_ref());
|
||||
let object = streams.get(stream).and_then(|s| s.entry.as_ref());
|
||||
if object.is_some_and(|r| owned.contains(&r)) {
|
||||
if let std::collections::btree_map::Entry::Vacant(entry) = first.entry(stream) {
|
||||
if stream != end || !op.is("q") {
|
||||
@@ -275,7 +276,7 @@ fn translate_added(doc: &mut Document, page: usize, indexes: &[usize], offset: [
|
||||
})
|
||||
.collect::<Result<Vec<_>, EditError>>()?;
|
||||
let data = pieces.splice(edits);
|
||||
let contents = crate::text::rewritten_contents(doc, &streams, data);
|
||||
let contents = crate::text::rewritten_contents(doc, &streams, data)?;
|
||||
let refs = match &contents {
|
||||
Object::Array(a) => a.clone(),
|
||||
one => vec![one.clone()],
|
||||
@@ -288,9 +289,9 @@ fn translate_added(doc: &mut Document, page: usize, indexes: &[usize], offset: [
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A missing or undecodable preceding stream can hide graphics state that affects every
|
||||
/// A missing, undecodable or damaged preceding stream can hide graphics state that affects every
|
||||
/// later item. Refuse group editing rather than inventing an inventory from partial data.
|
||||
fn checked_streams(doc: &Document, page: usize) -> Result<Vec<(Object, Vec<u8>)>, EditError> {
|
||||
fn checked_streams(doc: &Document, page: usize) -> Result<Vec<ContentStream>, EditError> {
|
||||
let p = pdfcraft_model::pages(doc).into_iter().nth(page).ok_or(EditError::NoSuchPage(page))?;
|
||||
let contents = match p.dict.get(b"Contents") {
|
||||
None => Vec::new(),
|
||||
@@ -305,6 +306,7 @@ fn checked_streams(doc: &Document, page: usize) -> Result<Vec<(Object, Vec<u8>)>
|
||||
},
|
||||
};
|
||||
let mut remaining = MAX_CONTENT_BYTES;
|
||||
let mut decode = DecodeBudget::new(usize::MAX, 0);
|
||||
let mut depth = 0usize;
|
||||
let mut operations = 0usize;
|
||||
let mut streams = Vec::with_capacity(contents.len());
|
||||
@@ -313,9 +315,12 @@ fn checked_streams(doc: &Document, page: usize) -> Result<Vec<(Object, Vec<u8>)>
|
||||
let Object::Stream(stream) = &*resolved else {
|
||||
return Err(EditError::Invalid("a page content stream is missing".into()));
|
||||
};
|
||||
let bytes = stream
|
||||
.decoded_within(remaining.min(64 * 1024 * 1024))
|
||||
let (bytes, damaged) = decode
|
||||
.decode_with_damage(doc, stream, remaining.min(64 * 1024 * 1024))
|
||||
.map_err(|_| EditError::Invalid("the page content cannot be decoded within its size limit".into()))?;
|
||||
if damaged {
|
||||
return Err(EditError::Invalid("a page content stream is damaged partway".into()));
|
||||
}
|
||||
remaining =
|
||||
remaining.checked_sub(bytes.len()).ok_or_else(|| EditError::Invalid("the page content is too large for group selection".into()))?;
|
||||
let parsed = pdfcraft_content::parse(&bytes);
|
||||
@@ -333,7 +338,7 @@ fn checked_streams(doc: &Document, page: usize) -> Result<Vec<(Object, Vec<u8>)>
|
||||
return Err(EditError::Invalid("the page graphics state is nested too deeply".into()));
|
||||
}
|
||||
}
|
||||
streams.push((object, bytes));
|
||||
streams.push(ContentStream { entry: object, data: bytes, read: crate::text::Read::Whole });
|
||||
}
|
||||
Ok(streams)
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
//! A page's ruled lines: the horizontal and vertical strokes (and thin filled bars) its content
|
||||
//! draws, so exports can tell a ruled table from text that merely lines up (#5149).
|
||||
|
||||
use pdfcraft_content::Matrix;
|
||||
use pdfcraft_cos::Document;
|
||||
|
||||
use crate::EditError;
|
||||
|
||||
/// How deep `q` may nest (deeper saves are not tracked).
|
||||
const MAX_SAVES: usize = 64;
|
||||
|
||||
/// At most this many rules are returned, and a path keeps at most this many segments, so a
|
||||
/// hostile page stays bounded.
|
||||
pub const MAX_RULES: usize = 4096;
|
||||
|
||||
/// A segment whose ends differ by at most this much across its run (points) is horizontal or
|
||||
/// vertical; a filled rectangle at most this thick is a bar drawn as a rule.
|
||||
const THIN: f64 = 2.0;
|
||||
|
||||
/// The page's ruled lines, each as its box `[x0, y0, x1, y1]` in default user space (`x0 <= x1`,
|
||||
/// `y0 <= y1`; a stroke has zero thickness): horizontal and vertical straight segments of stroked
|
||||
/// paths (rectangle edges included) and filled rectangles at most two points thick. Curves,
|
||||
/// slanted lines and paths that are only clipped are left out, and so are the contents of forms.
|
||||
/// At most [`MAX_RULES`] rules, in content order.
|
||||
pub fn page_rules(doc: &Document, page: usize) -> Result<Vec<[f64; 4]>, EditError> {
|
||||
let pages = pdfcraft_model::pages(doc);
|
||||
let p = pages.get(page).ok_or(EditError::NoSuchPage(page))?;
|
||||
let streams = crate::text::content_streams(doc, &p.dict)?;
|
||||
let pieces = crate::text::joined(&streams);
|
||||
let ops = pieces.parse().ops;
|
||||
|
||||
let mut out: Vec<[f64; 4]> = Vec::new();
|
||||
let mut ctm = Matrix::IDENTITY;
|
||||
let mut saved: Vec<Matrix> = Vec::new();
|
||||
let mut lost_saves = 0usize;
|
||||
// The current path in page space: its straight segments, its rectangles, the current point
|
||||
// and where the current subpath started.
|
||||
let mut segments: Vec<[(f64, f64); 2]> = Vec::new();
|
||||
let mut rects: Vec<[(f64, f64); 4]> = Vec::new();
|
||||
let mut at: Option<(f64, f64)> = None;
|
||||
let mut start: Option<(f64, f64)> = None;
|
||||
for op in &ops {
|
||||
if out.len() >= MAX_RULES {
|
||||
break;
|
||||
}
|
||||
match op.op.as_slice() {
|
||||
b"q" => {
|
||||
if saved.len() < MAX_SAVES {
|
||||
saved.push(ctm);
|
||||
} else {
|
||||
lost_saves = lost_saves.saturating_add(1);
|
||||
}
|
||||
}
|
||||
b"Q" => {
|
||||
if lost_saves > 0 {
|
||||
lost_saves -= 1;
|
||||
} else if let Some(m) = saved.pop() {
|
||||
ctm = m;
|
||||
}
|
||||
}
|
||||
b"cm" => {
|
||||
if let Some(m) = Matrix::from_operands(&op.operands) {
|
||||
ctm = m.then(&ctm);
|
||||
}
|
||||
}
|
||||
b"m" => {
|
||||
let p = op.nums::<2>().map(|[x, y]| ctm.apply(x, y));
|
||||
(at, start) = (p, p);
|
||||
}
|
||||
b"l" => {
|
||||
let p = op.nums::<2>().map(|[x, y]| ctm.apply(x, y));
|
||||
if let (Some(a), Some(b)) = (at, p)
|
||||
&& segments.len() < MAX_RULES
|
||||
{
|
||||
segments.push([a, b]);
|
||||
}
|
||||
at = p;
|
||||
}
|
||||
b"c" => at = op.nums::<6>().map(|[.., x, y]| ctm.apply(x, y)),
|
||||
b"v" | b"y" => at = op.nums::<4>().map(|[.., x, y]| ctm.apply(x, y)),
|
||||
b"h" => {
|
||||
if let (Some(a), Some(b)) = (at, start)
|
||||
&& segments.len() < MAX_RULES
|
||||
{
|
||||
segments.push([a, b]);
|
||||
}
|
||||
at = start;
|
||||
}
|
||||
b"re" => {
|
||||
if let Some([x, y, w, h]) = op.nums::<4>() {
|
||||
let q = [ctm.apply(x, y), ctm.apply(x + w, y), ctm.apply(x + w, y + h), ctm.apply(x, y + h)];
|
||||
if rects.len() < MAX_RULES {
|
||||
rects.push(q);
|
||||
}
|
||||
(at, start) = (Some(q[0]), Some(q[0]));
|
||||
}
|
||||
}
|
||||
b"S" | b"s" | b"B" | b"B*" | b"b" | b"b*" => {
|
||||
let closes = matches!(op.op.as_slice(), b"s" | b"b" | b"b*");
|
||||
if closes && let (Some(a), Some(b)) = (at, start) {
|
||||
segments.push([a, b]);
|
||||
}
|
||||
let edges = rects.iter().flat_map(|q| [[q[0], q[1]], [q[1], q[2]], [q[2], q[3]], [q[3], q[0]]]);
|
||||
out.extend(segments.iter().copied().chain(edges).filter_map(axis_aligned));
|
||||
(segments, rects, at, start) = (Vec::new(), Vec::new(), None, None);
|
||||
}
|
||||
b"f" | b"F" | b"f*" => {
|
||||
out.extend(rects.iter().filter_map(thin_bar));
|
||||
(segments, rects, at, start) = (Vec::new(), Vec::new(), None, None);
|
||||
}
|
||||
b"n" => (segments, rects, at, start) = (Vec::new(), Vec::new(), None, None),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
out.truncate(MAX_RULES);
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The box of a horizontal or vertical segment, or `None` for a slanted, tiny or non-finite one.
|
||||
fn axis_aligned([a, b]: [(f64, f64); 2]) -> Option<[f64; 4]> {
|
||||
let r = [a.0.min(b.0), a.1.min(b.1), a.0.max(b.0), a.1.max(b.1)];
|
||||
let (w, h) = (r[2] - r[0], r[3] - r[1]);
|
||||
(r.iter().all(|v| v.is_finite()) && w.min(h) <= THIN && w.max(h) > THIN).then_some(r)
|
||||
}
|
||||
|
||||
/// The box of a filled rectangle drawn as a rule: upright, at most [`THIN`] thick and longer than that.
|
||||
fn thin_bar(q: &[(f64, f64); 4]) -> Option<[f64; 4]> {
|
||||
let upright = |a: (f64, f64), b: (f64, f64)| (a.0 - b.0).abs() <= 0.01 || (a.1 - b.1).abs() <= 0.01;
|
||||
if !(upright(q[0], q[1]) && upright(q[1], q[2])) {
|
||||
return None;
|
||||
}
|
||||
let xs = q.map(|p| p.0);
|
||||
let ys = q.map(|p| p.1);
|
||||
let r = [
|
||||
xs.iter().copied().fold(f64::INFINITY, f64::min),
|
||||
ys.iter().copied().fold(f64::INFINITY, f64::min),
|
||||
xs.iter().copied().fold(f64::NEG_INFINITY, f64::max),
|
||||
ys.iter().copied().fold(f64::NEG_INFINITY, f64::max),
|
||||
];
|
||||
let (w, h) = (r[2] - r[0], r[3] - r[1]);
|
||||
(r.iter().all(|v| v.is_finite()) && w.min(h) <= THIN && w.max(h) > THIN).then_some(r)
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -55,7 +55,10 @@ use fallback::{add_type3_font, is_type3_fallback};
|
||||
pub(crate) use fallback::{glyph_path, type3_font_dict, unique_font_name};
|
||||
use interp::{Origin, Paint, union};
|
||||
use lines::page_dict;
|
||||
pub(crate) use lines::{FormBudget, content_streams, content_streams_within, dict_in_place, form_call, resource_dict, rewritten_contents, splice};
|
||||
pub(crate) use lines::{
|
||||
ContentStream, FormBudget, Read, content_streams, content_streams_within, dict_in_place, drawn_before_damage, first_op_after_damage, form_call,
|
||||
joined, resource_dict, rewritten_contents, splice,
|
||||
};
|
||||
pub use lines::{MAX_FORM_DEPTH, MAX_FORM_VISITS, glyph_text_lines, text_lines};
|
||||
pub use rewrite::{LineEdit, replace_line, rewrite_block};
|
||||
use rewrite::{coincident_ops, rewrite_block_from};
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use super::interp::{Carry, interpret};
|
||||
use super::lines::{content_streams, page_dict, reading_lines, rewritten_contents, splice, text_lines};
|
||||
use super::lines::{content_streams, joined, page_dict, reading_lines, rewritten_contents, splice, text_lines};
|
||||
use super::rewrite::{LineEdit, coincident_ops, rewrite_block};
|
||||
use super::{Document, EditError, HashMap, Object, Op, Pieces, TextLine, group_blocks, regions};
|
||||
use super::{Document, EditError, HashMap, Object, Op, TextLine, group_blocks, regions};
|
||||
|
||||
/// An editable text region: adjacent runs on visual rows, followed by aligned rows.
|
||||
/// A region may contain several source fonts, sizes, colours and weights.
|
||||
@@ -270,7 +270,7 @@ pub fn clear_block(doc: &mut Document, page: usize, block: usize) -> Result<(),
|
||||
let p = page_dict(doc, page)?;
|
||||
let res = p.dict.get(b"Resources").and_then(|r| doc.resolve(r).as_dict().cloned()).unwrap_or_default();
|
||||
let streams = content_streams(doc, &p.dict)?;
|
||||
let pieces = Pieces::join(&streams.iter().map(|(_, d)| d.as_slice()).collect::<Vec<_>>());
|
||||
let pieces = joined(&streams);
|
||||
let ops = pieces.parse().ops;
|
||||
let shown = interpret(doc, &ops, &res, &mut HashMap::new(), &mut Carry::new(), None, None)?;
|
||||
let mut patches = HashMap::new();
|
||||
@@ -297,7 +297,7 @@ pub fn clear_block(doc: &mut Document, page: usize, block: usize) -> Result<(),
|
||||
patches.insert(s.op, replacement);
|
||||
}
|
||||
let data = splice(&pieces, &ops, |i| patches.remove(&i).map_or((Vec::new(), true), |v| (v, false)));
|
||||
let contents = rewritten_contents(doc, &streams, data);
|
||||
let contents = rewritten_contents(doc, &streams, data)?;
|
||||
doc.update_dict(p.obj, |d| d.set(b"Contents".to_vec(), contents))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
+132
-23
@@ -61,16 +61,37 @@ impl TextLine {
|
||||
}
|
||||
}
|
||||
|
||||
/// The page's content streams as listed, each with its decoded data (empty when it doesn't
|
||||
/// decode), within one page's [`DecodeBudget`]. An error when the content runs past it: reading
|
||||
/// or rewriting a page from part of its content would lose the rest.
|
||||
pub(crate) fn content_streams(doc: &Document, page: &Dict) -> Result<Vec<(Object, Vec<u8>)>, EditError> {
|
||||
/// One entry of a page's `/Contents`, and what it decoded to.
|
||||
pub(crate) struct ContentStream {
|
||||
/// The entry as listed.
|
||||
pub(crate) entry: Object,
|
||||
/// Its decoded data, empty when it doesn't decode.
|
||||
pub(crate) data: Vec<u8>,
|
||||
/// How much of it decoded.
|
||||
pub(crate) read: Read,
|
||||
}
|
||||
|
||||
/// How much of a content stream decoded ([`rewritten_contents`] says what each allows).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum Read {
|
||||
Whole,
|
||||
/// Damaged partway: the data is what decoded before the damage. What follows it is unknown,
|
||||
/// the graphics state and syntax the later streams start in too.
|
||||
Damaged,
|
||||
/// Not at all (a filter this reader lacks, say): the data is empty.
|
||||
Unread,
|
||||
}
|
||||
|
||||
/// The page's content streams as listed, each with its decoded data, within one page's
|
||||
/// [`DecodeBudget`]. An error when the content runs past it: reading or rewriting a page from
|
||||
/// part of its content would lose the rest.
|
||||
pub(crate) fn content_streams(doc: &Document, page: &Dict) -> Result<Vec<ContentStream>, EditError> {
|
||||
content_streams_within(doc, page, &mut DecodeBudget::page())
|
||||
}
|
||||
|
||||
/// [`content_streams`], decoded against `budget`, which a walk of the page's forms then goes on
|
||||
/// spending.
|
||||
pub(crate) fn content_streams_within(doc: &Document, page: &Dict, budget: &mut DecodeBudget) -> Result<Vec<(Object, Vec<u8>)>, EditError> {
|
||||
pub(crate) fn content_streams_within(doc: &Document, page: &Dict, budget: &mut DecodeBudget) -> Result<Vec<ContentStream>, EditError> {
|
||||
let list: Vec<Object> = match page.get(b"Contents") {
|
||||
None => Vec::new(),
|
||||
Some(c) => match &*doc.resolve(c) {
|
||||
@@ -79,20 +100,26 @@ pub(crate) fn content_streams_within(doc: &Document, page: &Dict, budget: &mut D
|
||||
},
|
||||
};
|
||||
let mut out = Vec::with_capacity(list.len());
|
||||
for o in list {
|
||||
let data = match &*doc.resolve(&o) {
|
||||
Object::Stream(s) => match budget.decode(s) {
|
||||
Ok(data) => data,
|
||||
for entry in list {
|
||||
let (data, read) = match &*doc.resolve(&entry) {
|
||||
Object::Stream(s) => match budget.decode_with_damage(doc, s, usize::MAX) {
|
||||
Ok((data, damaged)) => (data, if damaged { Read::Damaged } else { Read::Whole }),
|
||||
Err(e) if budget.remaining() == 0 => return Err(EditError::Invalid(format!("the page content is too large to read: {e}"))),
|
||||
Err(_) => Vec::new(),
|
||||
Err(_) => (Vec::new(), Read::Unread),
|
||||
},
|
||||
_ => Vec::new(),
|
||||
// Nothing to lose: a null or missing entry draws nothing.
|
||||
_ => (Vec::new(), Read::Whole),
|
||||
};
|
||||
out.push((o, data));
|
||||
out.push(ContentStream { entry, data, read });
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The page's streams joined into the one stream they are: an operator may span two of them.
|
||||
pub(crate) fn joined(streams: &[ContentStream]) -> Pieces {
|
||||
Pieces::join(&streams.iter().map(|s| s.data.as_slice()).collect::<Vec<_>>())
|
||||
}
|
||||
|
||||
/// Rewrite a page's content (its streams joined, see [`Pieces`]): `edit(i)` gives the operators
|
||||
/// to insert before operator `i` of `ops` (parsed from the joined pieces) and whether to keep it.
|
||||
/// Everything else is copied byte for byte. A page's streams are one stream in pieces, split
|
||||
@@ -120,26 +147,108 @@ pub(crate) fn splice(pieces: &Pieces, ops: &[Op], mut edit: impl FnMut(usize) ->
|
||||
pieces.splice(edits)
|
||||
}
|
||||
|
||||
/// An error when content at `/Contents` index `at` (a stream there, or one inserted there) is drawn
|
||||
/// after a stream not read whole, damaged partway or not decoding at all: what wasn't read can
|
||||
/// change how it reads, the graphics state it draws in among it.
|
||||
pub(crate) fn drawn_before_damage(streams: &[ContentStream], at: usize) -> Result<(), EditError> {
|
||||
if at > first_damaged(streams) {
|
||||
return Err(EditError::Invalid(
|
||||
"this change comes after a content stream that is damaged or can't be decoded, and what wasn't read can change how the rest of the page reads"
|
||||
.into(),
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The index of the first stream not read whole, or the number of streams.
|
||||
fn first_damaged(streams: &[ContentStream]) -> usize {
|
||||
streams.iter().position(|s| s.read != Read::Whole).unwrap_or(streams.len())
|
||||
}
|
||||
|
||||
/// The index of the first of `ops`, parsed from `pieces` (the [`joined`] `streams`), drawn after a
|
||||
/// stream not read whole, or `ops.len()`. A `q … Q` still open there may hold what wasn't read,
|
||||
/// painting in the state it sets. An operator counts by its keyword: one whose operands start
|
||||
/// before such a stream takes them from around what wasn't read.
|
||||
pub(crate) fn first_op_after_damage(streams: &[ContentStream], pieces: &Pieces, ops: &[Op]) -> usize {
|
||||
let damaged = first_damaged(streams);
|
||||
ops.iter().position(|op| pieces.pieces_of(op).1 > damaged).unwrap_or(ops.len())
|
||||
}
|
||||
|
||||
/// Whether `new` changes a text object still open at the first stream not read whole. The text
|
||||
/// object goes on in it, and the text it shows there starts where this text ends: a change of this
|
||||
/// text moves it. A change before the text object doesn't.
|
||||
fn changes_text_open_into_damage(streams: &[ContentStream], new: &[Vec<u8>]) -> bool {
|
||||
let upto = first_damaged(streams).saturating_add(1);
|
||||
if upto > streams.len() {
|
||||
return false;
|
||||
}
|
||||
let before = Pieces::join(&streams.iter().take(upto).map(|s| s.data.as_slice()).collect::<Vec<_>>());
|
||||
let mut open = None;
|
||||
for op in before.parse().ops {
|
||||
match op.op.as_slice() {
|
||||
b"BT" => open = Some(op.span.start),
|
||||
b"ET" => open = None,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let Some(at) = open else { return false };
|
||||
let after = Pieces::join(&new.iter().take(upto).map(Vec::as_slice).collect::<Vec<_>>());
|
||||
// Unchanged from the text object's start to the stream not read whole: it ends the same.
|
||||
!before.data().get(at..).is_some_and(|text| after.data().ends_with(text))
|
||||
}
|
||||
|
||||
/// The page's `/Contents` after a [`splice`]: pieces whose bytes changed become new streams
|
||||
/// (keeping their dictionaries), the others stay as they were.
|
||||
pub(crate) fn rewritten_contents(doc: &mut Document, streams: &[(Object, Vec<u8>)], new: Vec<Vec<u8>>) -> Object {
|
||||
let mut contents: Vec<Object> = Vec::with_capacity(streams.len());
|
||||
for ((obj, old), data) in streams.iter().zip(new) {
|
||||
if *old == data {
|
||||
contents.push(obj.clone());
|
||||
/// (keeping their dictionaries), the others stay as they were. An error, before anything is
|
||||
/// added, when a piece that changed is a stream that didn't decode whole, or comes after one.
|
||||
/// Written from what decoded, a damaged stream would lose everything after the damage, and one
|
||||
/// that doesn't decode all of it. What follows the damage is unknown, so a later stream may not
|
||||
/// read as it seems: a string or comment the damage left open runs on into it, and operators the
|
||||
/// damage hides can change the graphics state it draws in. A stream that doesn't decode hides its
|
||||
/// operators all the same.
|
||||
pub(crate) fn rewritten_contents(doc: &mut Document, streams: &[ContentStream], new: Vec<Vec<u8>>) -> Result<Object, EditError> {
|
||||
// The last stream that changed: when it is drawn before the damage, so are the others.
|
||||
if let Some(i) = streams.iter().zip(&new).rposition(|(s, data)| s.data != *data) {
|
||||
drawn_before_damage(streams, i)?;
|
||||
}
|
||||
if changes_text_open_into_damage(streams, &new) {
|
||||
return Err(EditError::Invalid(
|
||||
"this change is in a text object that goes on in a content stream that is damaged or can't be decoded, whose text starts where this text ends"
|
||||
.into(),
|
||||
));
|
||||
}
|
||||
for (s, data) in streams.iter().zip(&new) {
|
||||
if s.data == *data {
|
||||
continue;
|
||||
}
|
||||
let mut dict = match &*doc.resolve(obj) {
|
||||
match s.read {
|
||||
Read::Whole => {}
|
||||
Read::Damaged => {
|
||||
return Err(EditError::Invalid(
|
||||
"this change is in a content stream that is damaged partway, and rewriting it would lose what follows the damage".into(),
|
||||
));
|
||||
}
|
||||
Read::Unread => {
|
||||
return Err(EditError::Invalid("this change is in a content stream that can't be decoded, and rewriting it would lose it".into()));
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut contents: Vec<Object> = Vec::with_capacity(streams.len());
|
||||
for (s, data) in streams.iter().zip(new) {
|
||||
if s.data == data {
|
||||
contents.push(s.entry.clone());
|
||||
continue;
|
||||
}
|
||||
let mut dict = match &*doc.resolve(&s.entry) {
|
||||
Object::Stream(s) => s.dict.clone(),
|
||||
_ => Dict::new(),
|
||||
};
|
||||
dict.remove(b"Length");
|
||||
contents.push(Object::Ref(doc.add(Object::Stream(Stream::flate(dict, &data)))));
|
||||
}
|
||||
match <[Object; 1]>::try_from(contents) {
|
||||
Ok(match <[Object; 1]>::try_from(contents) {
|
||||
Ok([one]) => one,
|
||||
Err(many) => Object::Array(many),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn page_dict(doc: &Document, page: usize) -> Result<pdfcraft_model::Page, EditError> {
|
||||
@@ -201,7 +310,7 @@ fn text_lines_in(doc: &Document, p: &pdfcraft_model::Page, actual_text: bool) ->
|
||||
let mut carry = Carry::new();
|
||||
// The streams are one stream in pieces (§7.8.2), split between any two tokens: parse them
|
||||
// joined, so an operator whose operands end one piece still has them.
|
||||
let pieces = Pieces::join(&content_streams(doc, &p.dict)?.into_iter().map(|(_, d)| d).collect::<Vec<_>>());
|
||||
let pieces = joined(&content_streams(doc, &p.dict)?);
|
||||
let ops = pieces.parse().ops;
|
||||
let properties = res.get(b"Properties").and_then(|o| doc.dict(o)).unwrap_or_default();
|
||||
let shown = interpret(doc, &ops, &res, &mut cache, &mut carry, None, actual_text.then_some(&properties))?;
|
||||
@@ -608,7 +717,7 @@ pub(super) fn reading_lines(doc: &Document, page: usize) -> Result<(Vec<TextLine
|
||||
// do: a comment, an operator's operands or a marked-content sequence (its /ActualText too)
|
||||
// can run on from one stream into the next. Text still counts as the stream its operator
|
||||
// starts in, which keeps lines from different streams apart.
|
||||
let pieces = Pieces::join(&streams.into_iter().map(|(_, data)| data).collect::<Vec<_>>());
|
||||
let pieces = joined(&streams);
|
||||
let ops = pieces.parse().ops;
|
||||
let stream_of = |i: usize| ops.get(i).map_or(0, |op| pieces.pieces_of(op).0);
|
||||
walk(&mut w, &ops, &res, &mut carry, &stream_of)?;
|
||||
|
||||
@@ -4,10 +4,10 @@ use super::fallback::{
|
||||
source_program_completes, source_show, source_space, source_width, type3_encode, type3_font,
|
||||
};
|
||||
use super::interp::{Carry, Origin, TextState, interpret};
|
||||
use super::lines::{content_streams, page_dict, rewritten_contents, splice, text_lines};
|
||||
use super::lines::{content_streams, joined, page_dict, rewritten_contents, splice, text_lines};
|
||||
use super::{
|
||||
Dict, Document, EditError, HashMap, Matrix, Metrics, Object, Op, PdfString, Pieces, TextLine, TextSession, alignment_frame, group_blocks,
|
||||
is_centred, parse, rewrite_styled_block,
|
||||
Dict, Document, EditError, HashMap, Matrix, Metrics, Object, Op, PdfString, TextLine, TextSession, alignment_frame, group_blocks, is_centred,
|
||||
parse, rewrite_styled_block,
|
||||
};
|
||||
|
||||
/// What replacing a line did.
|
||||
@@ -56,7 +56,7 @@ pub(crate) fn replace_line_with_limit(doc: &mut Document, page: usize, line: usi
|
||||
let mut res = p.dict.get(b"Resources").map(|r| doc.resolve(r)).and_then(|r| r.as_dict().cloned()).unwrap_or_default();
|
||||
let mut fonts_res = res.get(b"Font").map(|f| doc.resolve(f)).and_then(|f| f.as_dict().cloned()).unwrap_or_default();
|
||||
let streams = content_streams(doc, &p.dict)?;
|
||||
let pieces = Pieces::join(&streams.iter().map(|(_, d)| d.as_slice()).collect::<Vec<_>>());
|
||||
let pieces = joined(&streams);
|
||||
let ops = pieces.parse().ops;
|
||||
let first = target.ops.first().copied().filter(|i| *i < ops.len()).ok_or_else(|| EditError::Invalid("the page's content changed".into()))?;
|
||||
// The line's own font, when it can show every character.
|
||||
@@ -127,7 +127,7 @@ pub(crate) fn replace_line_with_limit(doc: &mut Document, page: usize, line: usi
|
||||
}
|
||||
// Rebuild: the line's first operator becomes the replacement, its others go.
|
||||
let new_data = splice(&pieces, &ops, |i| if i == first { (std::mem::take(&mut replacement), false) } else { (Vec::new(), !drops.contains(&i)) });
|
||||
let contents = rewritten_contents(doc, &streams, new_data);
|
||||
let contents = rewritten_contents(doc, &streams, new_data)?;
|
||||
let page_ref = p.obj;
|
||||
if substituted.is_some() {
|
||||
res.set(b"Font".to_vec(), Object::Dict(fonts_res));
|
||||
@@ -834,7 +834,7 @@ pub(crate) fn rewrite_block_from(
|
||||
}
|
||||
let upright = dispatch.upright;
|
||||
let streams = content_streams(doc, &p.dict)?;
|
||||
let pieces = Pieces::join(&streams.iter().map(|(_, d)| d.as_slice()).collect::<Vec<_>>());
|
||||
let pieces = joined(&streams);
|
||||
let ops = pieces.parse().ops;
|
||||
let text = paragraph_text(text.unwrap_or(&b.text));
|
||||
// The characters to show, for choosing fonts: the breaks are moves, not glyphs.
|
||||
@@ -970,7 +970,7 @@ pub(crate) fn rewrite_block_from(
|
||||
let insert = if i == at { std::mem::take(&mut block_ops) } else { Vec::new() };
|
||||
(insert, !dropped.contains(&i))
|
||||
});
|
||||
let contents = rewritten_contents(doc, &streams, new_data);
|
||||
let contents = rewritten_contents(doc, &streams, new_data)?;
|
||||
let new_font = !reuse;
|
||||
if new_font {
|
||||
res.set(b"Font".to_vec(), Object::Dict(fonts_res));
|
||||
@@ -1040,7 +1040,7 @@ pub(crate) fn selectable_blocks(
|
||||
!b.lines
|
||||
.iter()
|
||||
.filter_map(|i| lines.get(*i))
|
||||
.any(|l| streams.get(l.stream).and_then(|(o, _)| o.as_ref()).is_some_and(|r| excluded.contains(&r)))
|
||||
.any(|l| streams.get(l.stream).and_then(|s| s.entry.as_ref()).is_some_and(|r| excluded.contains(&r)))
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
@@ -1134,7 +1134,7 @@ pub(crate) fn translate_blocks(doc: &mut Document, page: usize, indexes: &[usize
|
||||
}
|
||||
let res = p.dict.get(b"Resources").map(|r| doc.resolve(r)).and_then(|r| r.as_dict().cloned()).unwrap_or_default();
|
||||
let fonts = res.get(b"Font").map(|r| doc.resolve(r)).and_then(|r| r.as_dict().cloned()).unwrap_or_default();
|
||||
let pieces = Pieces::join(&streams.iter().map(|(_, d)| d.as_slice()).collect::<Vec<_>>());
|
||||
let pieces = joined(&streams);
|
||||
let ops = pieces.parse().ops;
|
||||
let shown = interpret(doc, &ops, &res, &mut HashMap::new(), &mut Carry::new(), None, None)?;
|
||||
let mut patches = HashMap::new();
|
||||
@@ -1205,7 +1205,7 @@ pub(crate) fn translate_blocks(doc: &mut Document, page: usize, indexes: &[usize
|
||||
return Err(EditError::Invalid("a selected text operation cannot be moved".into()));
|
||||
}
|
||||
let data = splice(&pieces, &ops, |i| patches.remove(&i).map_or((Vec::new(), true), |v| (v, false)));
|
||||
let contents = rewritten_contents(doc, &streams, data);
|
||||
let contents = rewritten_contents(doc, &streams, data)?;
|
||||
doc.update_dict(p.obj, |d| d.set(b"Contents".to_vec(), contents))?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -962,7 +962,7 @@ pub(crate) fn rewrite_styled_block(
|
||||
};
|
||||
let (rows, row_ranges, row_lines, row_soft, row_gap) = wrap_styled_rows(&chars, width, measure)?;
|
||||
let streams = content_streams(doc, &p.dict)?;
|
||||
let pieces = Pieces::join(&streams.iter().map(|(_, d)| d.as_slice()).collect::<Vec<_>>());
|
||||
let pieces = crate::text::joined(&streams);
|
||||
let ops = pieces.parse().ops;
|
||||
// A row the edit doesn't reach keeps its source operators, so its kerning, TJ word gaps and
|
||||
// glyph widths stay exactly as they were instead of being rebuilt from the text state. A row
|
||||
@@ -1206,7 +1206,7 @@ pub(crate) fn rewrite_styled_block(
|
||||
// when the rewrite splits one, and a kept row's operators come later in the stream.
|
||||
let marker = if marked { None } else { paragraph_marker(block, lines, &ops) };
|
||||
let data = splice_with_marker(&pieces, &ops, marker, at, block_ops, &drop);
|
||||
let contents = rewritten_contents(doc, &streams, data);
|
||||
let contents = rewritten_contents(doc, &streams, data)?;
|
||||
res.set(b"Font".to_vec(), Object::Dict(fonts));
|
||||
doc.update_dict(p.obj, |d| {
|
||||
d.set(b"Contents".to_vec(), contents);
|
||||
|
||||
@@ -0,0 +1,590 @@
|
||||
//! Edit a PDF ▸ Ungroup: draw a Form XObject's content in place of its `Do` (#2964, #3005).
|
||||
//!
|
||||
//! Text inside grouped Form artwork can't be edited, because editing rewrites only the page's own
|
||||
//! content streams. Ungrouping copies the form's content into the page at the same place,
|
||||
//! wrapped as `q <Matrix> cm <BBox> re W n … Q`, with the form's resources merged into a copy of
|
||||
//! the page's under names that don't clash. Its text then edits like any other. The form object
|
||||
//! itself is left alone, so another page or placement that draws it is unchanged. Each resource
|
||||
//! name is read from the operand the renderer uses ([`resource_operand`]), so a surplus operand
|
||||
//! before it changes neither the renaming nor the checks below.
|
||||
//!
|
||||
//! Drawing a form inline paints the same pixels unless the form is a transparency group whose
|
||||
//! compositing differs from painting its parts one by one: a knockout group, a group that uses
|
||||
//! a blend mode other than Normal inside, or a group drawn translucent, blended or under a soft
|
||||
//! mask, or a group with a blending colour space (`/CS`) other than the page's: its contents
|
||||
//! composite in that space and are then converted (ISO 32000-2 §11.6.6), inline they would
|
||||
//! composite in the page's. Those are refused rather than changed, as is a form whose
|
||||
//! `/DefaultGray`, `/DefaultRGB` or `/DefaultCMYK` the page doesn't share (it remaps the form's
|
||||
//! device colours, §8.6.5.6, and inline the page's resources apply), tagged form content (its
|
||||
//! structure link would be lost) and content whose marked content or text objects don't balance
|
||||
//! (inlined, they would change the scope of the page's own). A form in a layer (`/OC`) keeps its membership as `/OC … BDC … EMC`.
|
||||
//!
|
||||
//! A pattern's matrix maps pattern space to the default space of the content stream that uses it
|
||||
//! (ISO 32000-2 §8.7.2): inside the form that is the form's space at the `Do`, on the page it is
|
||||
//! the page's. So each pattern the form selects with `scn`/`SCN` is drawn from a copy whose
|
||||
//! `/Matrix` also carries the form's placement; one that can't be copied that way is refused.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use pdfcraft_content::{Matrix, Op, parse};
|
||||
use pdfcraft_cos::{Dict, Document, Object};
|
||||
|
||||
use crate::EditError;
|
||||
|
||||
/// The largest form content ungrouped (decoded bytes): the page's own content cap is far above
|
||||
/// any real form, and a bomb must not be copied into the page.
|
||||
const MAX_FORM_BYTES: usize = 64 << 20;
|
||||
|
||||
/// Resource categories a content stream refers to by name (ISO 32000-2 §7.8.3, Table 34).
|
||||
const CATEGORIES: [&[u8]; 7] = [b"Font", b"XObject", b"ExtGState", b"ColorSpace", b"Pattern", b"Shading", b"Properties"];
|
||||
|
||||
/// The `/ColorSpace` entries that remap device colours painted with the resources they are in
|
||||
/// (ISO 32000-2 §8.6.5.6).
|
||||
const DEFAULT_SPACES: [&[u8]; 3] = [b"DefaultGray", b"DefaultRGB", b"DefaultCMYK"];
|
||||
|
||||
/// The most distinct patterns one ungrouped form may select; each becomes a new object.
|
||||
const MAX_MOVED_PATTERNS: usize = 256;
|
||||
|
||||
/// A name map for one resource category: form name → name in the page's resources.
|
||||
type Renames = Vec<(Vec<u8>, Vec<u8>)>;
|
||||
|
||||
/// What [`ungroup_ops`] gives back: the ops that draw the form inline, the page resources with
|
||||
/// the form's merged in, and the pattern copies to add to the document, each under the name in
|
||||
/// the merged `/Pattern` dictionary that the ops already use.
|
||||
pub(crate) type Ungrouped = (Vec<Op>, Dict, Vec<(Vec<u8>, Object)>);
|
||||
|
||||
/// Ungroup form `name` from the page's `resources`. `translucent` says whether the graphics state
|
||||
/// at the `Do` is translucent, blended or soft-masked, which a transparency group composites as a
|
||||
/// whole. `page_space` is the page group's blending colour space ([`page_blend_space`]).
|
||||
/// `placement` maps the form's space to the page's default space at the `Do` (its `/Matrix`,
|
||||
/// then the CTM there).
|
||||
pub(crate) fn ungroup_ops(
|
||||
doc: &Document,
|
||||
resources: &Dict,
|
||||
name: &[u8],
|
||||
translucent: bool,
|
||||
page_space: Option<&Object>,
|
||||
placement: Matrix,
|
||||
) -> Result<Ungrouped, EditError> {
|
||||
let refuse = |why: &str| EditError::Invalid(format!("this artwork can't be ungrouped: {why}"));
|
||||
let xobjects = resources.get(b"XObject").map(|x| doc.resolve(x)).and_then(|x| x.as_dict().cloned()).ok_or_else(|| refuse("it is missing"))?;
|
||||
let form = xobjects.get(name).ok_or_else(|| refuse("it is missing"))?;
|
||||
let Object::Stream(s) = &*doc.resolve(form) else { return Err(refuse("it is not a Form XObject")) };
|
||||
if !is_name(doc, &s.dict, b"Subtype", b"Form") {
|
||||
return Err(refuse("it is not a Form XObject"));
|
||||
}
|
||||
let numbers = |key: &[u8], n: usize| -> Option<Vec<f64>> {
|
||||
let a = s.dict.get(key).map(|o| doc.resolve(o))?;
|
||||
let v: Vec<f64> = a.as_array()?.iter().filter_map(|x| doc.resolve(x).as_f64()).collect();
|
||||
(v.len() == n && v.iter().all(|x| x.is_finite())).then_some(v)
|
||||
};
|
||||
let bbox = numbers(b"BBox", 4).ok_or_else(|| refuse("its bounding box is missing or unreadable"))?;
|
||||
let matrix = match s.dict.get(b"Matrix") {
|
||||
None => None,
|
||||
Some(_) => Some(Matrix(
|
||||
<[f64; 6]>::try_from(numbers(b"Matrix", 6).ok_or_else(|| refuse("its matrix is unreadable"))?)
|
||||
.map_err(|_| refuse("its matrix is unreadable"))?,
|
||||
)),
|
||||
};
|
||||
let own = s.dict.get(b"Resources").map(|r| doc.resolve(r)).and_then(|r| r.as_dict().cloned());
|
||||
// A form without its own resources uses the ones it is drawn with (PDF 1.1).
|
||||
let form_res = own.clone().unwrap_or_else(|| resources.clone());
|
||||
|
||||
// A tagged form's content is a structure element's: drawn inline it would lose that link.
|
||||
if s.dict.get(b"StructParent").is_some() || s.dict.get(b"StructParents").is_some() {
|
||||
return Err(refuse("it is tagged content (Tags panel); edit its text in a copy without tags"));
|
||||
}
|
||||
let group = s.dict.get(b"Group").map(|g| doc.resolve(g)).and_then(|g| g.as_dict().cloned()).filter(|g| is_name(doc, g, b"S", b"Transparency"));
|
||||
if let Some(group) = &group {
|
||||
if group.get(b"K").is_some_and(|k| matches!(*doc.resolve(k), Object::Bool(true))) {
|
||||
return Err(refuse("it is a knockout transparency group"));
|
||||
}
|
||||
if translucent {
|
||||
return Err(refuse("it is a transparency group drawn translucent, blended or under a soft mask"));
|
||||
}
|
||||
// Its contents composite in its own colour space (ISO 32000-2 §11.6.6, Table 145 /CS);
|
||||
// inline they would composite in the page's.
|
||||
if let Some(cs) = group.get(b"CS")
|
||||
&& !same_blend_space(doc, cs, page_space)
|
||||
{
|
||||
return Err(refuse("it is a transparency group that blends in a colour space of its own"));
|
||||
}
|
||||
}
|
||||
|
||||
// Strictly: damaged data must not be copied in as a shorter form.
|
||||
let data = s.decoded_strict_within(MAX_FORM_BYTES).map_err(|e| refuse(&format!("its content can't be read ({e})")))?;
|
||||
let parsed = parse(&data);
|
||||
if parsed.skipped > 0 {
|
||||
return Err(refuse("its content has parts that can't be read"));
|
||||
}
|
||||
let mut ops = parsed.ops;
|
||||
if group.is_some() {
|
||||
// The form itself is being read: drawing itself again counts as blending.
|
||||
let mut walk = BlendWalk { path: form.as_ref().into_iter().collect(), known: HashMap::new(), reads: 0 };
|
||||
if blends_inside(doc, &form_res, &ops, 0, &mut walk) {
|
||||
return Err(refuse("it is a transparency group with blend modes inside"));
|
||||
}
|
||||
}
|
||||
|
||||
// A form's default colour space remaps its device colours (ISO 32000-2 §8.6.5.6); inline,
|
||||
// the page's resources are the current ones (§7.8.3).
|
||||
if own.is_some()
|
||||
&& let Some(key) = unshared_default_space(doc, &form_res, resources)
|
||||
{
|
||||
let key = String::from_utf8_lossy(key);
|
||||
return Err(refuse(&format!("it remaps its device colours with a /{key} the page doesn't share")));
|
||||
}
|
||||
|
||||
// Merge the form's resources into a copy of the page's, renaming what clashes.
|
||||
let mut merged = resources.clone();
|
||||
let mut renames: Vec<(&[u8], Renames)> = Vec::new();
|
||||
if own.is_some() {
|
||||
for cat in CATEGORIES {
|
||||
let Some(theirs) = form_res.get(cat).map(|x| doc.resolve(x)).and_then(|x| x.as_dict().cloned()) else { continue };
|
||||
let mut mine = merged.get(cat).map(|x| doc.resolve(x)).and_then(|x| x.as_dict().cloned()).unwrap_or_default();
|
||||
let mut map = Renames::new();
|
||||
let mut n = 0u32;
|
||||
for (key, value) in theirs.iter() {
|
||||
// A default colour space checked above is the page's, which applies inline;
|
||||
// renamed, it would be an entry nothing uses.
|
||||
if mine.get(key) == Some(value) || (cat == b"ColorSpace" && DEFAULT_SPACES.contains(&&key[..])) {
|
||||
continue;
|
||||
}
|
||||
let fresh = loop {
|
||||
n = n.saturating_add(1);
|
||||
let candidate = format!("PCUg{n}").into_bytes();
|
||||
if mine.get(&candidate).is_none() && theirs.get(&candidate).is_none() {
|
||||
break candidate;
|
||||
}
|
||||
if n == u32::MAX {
|
||||
return Err(refuse("too many resources"));
|
||||
}
|
||||
};
|
||||
mine.set(fresh.clone(), value.clone());
|
||||
map.push((key.to_vec(), fresh));
|
||||
}
|
||||
merged.set(cat.to_vec(), Object::Dict(mine));
|
||||
if !map.is_empty() {
|
||||
renames.push((cat, map));
|
||||
}
|
||||
}
|
||||
}
|
||||
let renamed = |cat: &[u8], name: &[u8]| -> Option<Vec<u8>> {
|
||||
renames.iter().find(|(c, _)| *c == cat).and_then(|(_, m)| m.iter().find(|(from, _)| from == name)).map(|(_, to)| to.clone())
|
||||
};
|
||||
// A nested form, Type 3 font or tiling pattern without resources of its own looks its names
|
||||
// up in the form's (the renderer chains them to whatever draws it). Drawn from the page, it
|
||||
// would find the page's, which differ wherever a name was renamed (every form resource that
|
||||
// isn't already the page's, the nested item's own entry included).
|
||||
if !renames.is_empty() && ops.iter().any(|op| inherits_resources(doc, &form_res, op)) {
|
||||
return Err(refuse("it draws a nested form, Type 3 font or pattern that uses its resources"));
|
||||
}
|
||||
let mut depth = 0usize;
|
||||
// Marked content and text objects must balance within the form's own stream: an extra EMC
|
||||
// would close one the page opened, and one left open would take in the page's later content.
|
||||
let mut marked = 0usize;
|
||||
let mut in_text = false;
|
||||
for op in &mut ops {
|
||||
match op.op.as_slice() {
|
||||
b"BDC" | b"BMC" => marked = marked.saturating_add(1),
|
||||
b"EMC" => marked = marked.checked_sub(1).ok_or_else(|| refuse("its content ends marked content it didn't begin"))?,
|
||||
b"BT" if in_text => return Err(refuse("its content begins a text object inside another")),
|
||||
b"BT" => in_text = true,
|
||||
b"ET" if !in_text => return Err(refuse("its content ends a text object it didn't begin")),
|
||||
b"ET" => in_text = false,
|
||||
_ => {}
|
||||
}
|
||||
match op.op.as_slice() {
|
||||
b"q" => depth = depth.saturating_add(1),
|
||||
b"Q" => depth = depth.checked_sub(1).ok_or_else(|| refuse("its content restores more graphics states than it saves"))?,
|
||||
_ => {}
|
||||
}
|
||||
let slot = resource_operand(op).map_err(|Unreadable| refuse("its content selects a resource with operands that can't be read"))?;
|
||||
if let Some((cat, i)) = slot
|
||||
&& let Some(operand) = op.operands.get_mut(i)
|
||||
&& let Object::Name(n) = operand
|
||||
&& let Some(to) = renamed(cat, n)
|
||||
{
|
||||
*operand = Object::Name(to);
|
||||
}
|
||||
if let Some((dict, _)) = &mut op.inline {
|
||||
for key in [&b"CS"[..], b"ColorSpace"] {
|
||||
if let Some(Object::Name(n)) = dict.get(key)
|
||||
&& let Some(to) = renamed(b"ColorSpace", n)
|
||||
{
|
||||
dict.set(key.to_vec(), Object::Name(to));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if marked > 0 || in_text {
|
||||
return Err(refuse("its content leaves marked content or a text object open"));
|
||||
}
|
||||
|
||||
// Patterns keep their place relative to the shapes they fill: each one the form selects is
|
||||
// drawn from a copy that also carries the placement. Nested forms and patterns inside
|
||||
// patterns keep their own parents, so only this stream's selections change.
|
||||
let mut patterns: Vec<(Vec<u8>, Object)> = Vec::new();
|
||||
if placement != Matrix::IDENTITY {
|
||||
let mut table = merged.get(b"Pattern").map(|x| doc.resolve(x)).and_then(|x| x.as_dict().cloned()).unwrap_or_default();
|
||||
let mut moved: Renames = Vec::new();
|
||||
let mut n = 0u32;
|
||||
for op in &mut ops {
|
||||
let Ok(Some((b"Pattern", i))) = resource_operand(op) else { continue };
|
||||
let Some(Object::Name(from)) = op.operands.get(i) else { continue };
|
||||
// A name the resources don't have selects nothing, inline or not.
|
||||
let Some(entry) = table.get(from).cloned() else { continue };
|
||||
let to = match moved.iter().find(|(f, _)| f == from) {
|
||||
Some((_, to)) => to.clone(),
|
||||
None => {
|
||||
if moved.len() >= MAX_MOVED_PATTERNS {
|
||||
return Err(refuse("it paints with too many patterns"));
|
||||
}
|
||||
let copy =
|
||||
moved_pattern(doc, &entry, placement).ok_or_else(|| refuse("it paints with a pattern whose position can't be kept"))?;
|
||||
let fresh = loop {
|
||||
n = n.saturating_add(1);
|
||||
let candidate = format!("PCUgPat{n}").into_bytes();
|
||||
if table.get(&candidate).is_none() {
|
||||
break candidate;
|
||||
}
|
||||
if n == u32::MAX {
|
||||
return Err(refuse("too many resources"));
|
||||
}
|
||||
};
|
||||
// Reserved here; the caller replaces it with the copy's reference.
|
||||
table.set(fresh.clone(), Object::Null);
|
||||
patterns.push((fresh.clone(), copy));
|
||||
moved.push((from.clone(), fresh.clone()));
|
||||
fresh
|
||||
}
|
||||
};
|
||||
if let Some(operand) = op.operands.get_mut(i) {
|
||||
*operand = Object::Name(to);
|
||||
}
|
||||
}
|
||||
if !patterns.is_empty() {
|
||||
merged.set(b"Pattern".to_vec(), Object::Dict(table));
|
||||
}
|
||||
}
|
||||
|
||||
// A form in a layer (/OC) stays in it: its content is marked with the same membership.
|
||||
let layer = match s.dict.get(b"OC") {
|
||||
None => None,
|
||||
Some(oc) => {
|
||||
let mut props = merged.get(b"Properties").map(|x| doc.resolve(x)).and_then(|x| x.as_dict().cloned()).unwrap_or_default();
|
||||
let existing = props.iter().find(|(_, v)| *v == oc).map(|(k, _)| k.clone());
|
||||
let name = match existing {
|
||||
Some(k) => k,
|
||||
None => {
|
||||
let fresh = (1..=u32::MAX)
|
||||
.map(|n| format!("PCUgOC{n}").into_bytes())
|
||||
.find(|c| props.get(c).is_none())
|
||||
.ok_or_else(|| refuse("too many resources"))?;
|
||||
props.set(fresh.clone(), oc.clone());
|
||||
merged.set(b"Properties".to_vec(), Object::Dict(props));
|
||||
fresh
|
||||
}
|
||||
};
|
||||
Some(name)
|
||||
}
|
||||
};
|
||||
|
||||
let num = |v: f64| Object::Real(v);
|
||||
let mut out = Vec::new();
|
||||
if let Some(name) = &layer {
|
||||
out.push(Op::new("BDC", vec![Object::name("OC"), Object::Name(name.clone())]));
|
||||
}
|
||||
out.push(Op::new("q", Vec::new()));
|
||||
if let Some(m) = matrix {
|
||||
out.push(Op::new("cm", m.0.iter().copied().map(num).collect()));
|
||||
}
|
||||
let (x0, y0, x1, y1) = (bbox[0].min(bbox[2]), bbox[1].min(bbox[3]), bbox[0].max(bbox[2]), bbox[1].max(bbox[3]));
|
||||
out.push(Op::new("re", vec![num(x0), num(y0), num(x1 - x0), num(y1 - y0)]));
|
||||
out.push(Op::new("W", Vec::new()));
|
||||
out.push(Op::new("n", Vec::new()));
|
||||
out.extend(ops);
|
||||
// A form ends with the state it was drawn with (the Do saves and restores it).
|
||||
out.extend(std::iter::repeat_with(|| Op::new("Q", Vec::new())).take(depth));
|
||||
out.push(Op::new("Q", Vec::new()));
|
||||
if layer.is_some() {
|
||||
out.push(Op::new("EMC", Vec::new()));
|
||||
}
|
||||
Ok((out, merged, patterns))
|
||||
}
|
||||
|
||||
/// The first of `/DefaultGray`, `/DefaultRGB` and `/DefaultCMYK` in the form's `/ColorSpace`
|
||||
/// resources that the page's don't have with an equal value (the same object, or the same value
|
||||
/// resolved). A default colour space remaps the device colours painted with the resource
|
||||
/// dictionary it is in (ISO 32000-2 §8.6.5.6, §7.8.3), so inline only the page's would apply.
|
||||
fn unshared_default_space(doc: &Document, form: &Dict, page: &Dict) -> Option<&'static [u8]> {
|
||||
let spaces = |res: &Dict| res.get(b"ColorSpace").map(|x| doc.resolve(x)).and_then(|x| x.as_dict().cloned()).unwrap_or_default();
|
||||
let (theirs, mine) = (spaces(form), spaces(page));
|
||||
DEFAULT_SPACES.into_iter().find(|key| theirs.get(key).is_some_and(|v| !mine.get(key).is_some_and(|p| *doc.resolve(p) == *doc.resolve(v))))
|
||||
}
|
||||
|
||||
/// A copy of pattern `entry` whose `/Matrix` maps its space to the page's default space instead
|
||||
/// of the form's: its own matrix, then `placement`. `None` when it isn't a readable pattern, its
|
||||
/// matrix is unreadable, the result isn't finite or a tiling pattern is too large to copy.
|
||||
fn moved_pattern(doc: &Document, entry: &Object, placement: Matrix) -> Option<Object> {
|
||||
let resolved = doc.resolve(entry);
|
||||
let (mut dict, stream) = match &*resolved {
|
||||
Object::Stream(s) => (s.dict.clone(), Some(s)),
|
||||
Object::Dict(d) => (d.clone(), None),
|
||||
_ => return None,
|
||||
};
|
||||
let own = match dict.get(b"Matrix") {
|
||||
None => Matrix::IDENTITY,
|
||||
Some(m) => {
|
||||
let m = doc.resolve(m);
|
||||
let nums: Vec<Object> = m.as_array()?.iter().map(|x| doc.resolve(x).as_ref().clone()).collect();
|
||||
Matrix::from_operands(&nums)?
|
||||
}
|
||||
};
|
||||
let moved = own.then(&placement);
|
||||
if !moved.0.iter().all(|v| v.is_finite()) {
|
||||
return None;
|
||||
}
|
||||
dict.set(b"Matrix".to_vec(), Object::Array(moved.0.iter().map(|v| Object::Real(*v)).collect()));
|
||||
match stream {
|
||||
Some(s) if s.raw.len() > MAX_FORM_BYTES => None,
|
||||
Some(s) => Some(Object::Stream(pdfcraft_cos::Stream { dict, raw: s.raw.clone() })),
|
||||
None => Some(Object::Dict(dict)),
|
||||
}
|
||||
}
|
||||
|
||||
/// How deep [`blends_inside`] follows nested forms; deeper ones count as blending.
|
||||
const MAX_NESTING: usize = 8;
|
||||
|
||||
/// The most nested forms and tiling patterns [`blends_inside`] reads in all; past that the rest
|
||||
/// count as blending, so a file can't make the check run for ever.
|
||||
const MAX_NESTED_READS: usize = 1024;
|
||||
|
||||
/// What [`blends_inside`] carries through its nested reads: the forms on the current path (a
|
||||
/// form drawing itself), the answer for each form with resources of its own (its answer doesn't
|
||||
/// depend on who draws it), and how many reads it has made.
|
||||
struct BlendWalk {
|
||||
path: Vec<pdfcraft_cos::ObjRef>,
|
||||
known: HashMap<pdfcraft_cos::ObjRef, bool>,
|
||||
reads: usize,
|
||||
}
|
||||
|
||||
/// An operator whose operands the renderer can't read as it expects, so it skips the operator.
|
||||
struct Unreadable;
|
||||
|
||||
/// Which operand of `op` names a resource, and from which category, read as the renderer reads
|
||||
/// it: operands are taken from the end, so a surplus operand before them is ignored. `Do`, `gs`,
|
||||
/// `sh`, `cs` and `CS` take the last operand; `Tf` a name then a size; `BDC` and `DP` a tag then
|
||||
/// a name or an inline dictionary; `scn` and `SCN` numbers and the last name among them.
|
||||
/// `Ok(None)` when `op` names no resource; [`Unreadable`] when the renderer would skip it, which
|
||||
/// [`ungroup_ops`] refuses rather than guess at.
|
||||
fn resource_operand(op: &Op) -> Result<Option<(&'static [u8], usize)>, Unreadable> {
|
||||
let operands = &op.operands;
|
||||
let name_at = |i: Option<usize>| i.is_some_and(|i| matches!(operands.get(i), Some(Object::Name(_))));
|
||||
let last = operands.len().checked_sub(1);
|
||||
let (cat, at): (&'static [u8], Option<usize>) = match op.op.as_slice() {
|
||||
b"Do" => (b"XObject", last),
|
||||
b"gs" => (b"ExtGState", last),
|
||||
b"sh" => (b"Shading", last),
|
||||
b"cs" | b"CS" => (b"ColorSpace", last),
|
||||
b"Tf" => {
|
||||
if !last.is_some_and(|i| matches!(operands.get(i), Some(Object::Int(_) | Object::Real(_)))) {
|
||||
return Err(Unreadable);
|
||||
}
|
||||
(b"Font", operands.len().checked_sub(2))
|
||||
}
|
||||
b"BDC" | b"DP" => {
|
||||
if !name_at(operands.len().checked_sub(2)) {
|
||||
return Err(Unreadable);
|
||||
}
|
||||
match last.and_then(|i| operands.get(i)) {
|
||||
Some(Object::Name(_)) => (b"Properties", last),
|
||||
Some(Object::Dict(_)) => return Ok(None),
|
||||
_ => return Err(Unreadable),
|
||||
}
|
||||
}
|
||||
b"scn" | b"SCN" => {
|
||||
if !operands.iter().all(|o| matches!(o, Object::Int(_) | Object::Real(_) | Object::Name(_))) {
|
||||
return Err(Unreadable);
|
||||
}
|
||||
return Ok(operands.iter().rposition(|o| matches!(o, Object::Name(_))).map(|i| (&b"Pattern"[..], i)));
|
||||
}
|
||||
_ => return Ok(None),
|
||||
};
|
||||
match at {
|
||||
Some(i) if name_at(Some(i)) => Ok(Some((cat, i))),
|
||||
_ => Err(Unreadable),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `op` draws a Form XObject (`Do`), Type 3 font (`Tf`) or tiling pattern (`scn`/`SCN`) from
|
||||
/// `resources` that has no `/Resources` of its own, and so inherits the ones it is drawn with.
|
||||
fn inherits_resources(doc: &Document, resources: &Dict, op: &Op) -> bool {
|
||||
let Ok(Some((cat @ (b"XObject" | b"Font" | b"Pattern"), i))) = resource_operand(op) else { return false };
|
||||
let Some(Object::Name(name)) = op.operands.get(i) else { return false };
|
||||
let Some(entry) = resources.get(cat).map(|d| doc.resolve(d)).and_then(|d| d.as_dict().and_then(|d| d.get(name).cloned())) else {
|
||||
return false;
|
||||
};
|
||||
let dict = match &*doc.resolve(&entry) {
|
||||
Object::Stream(s) => s.dict.clone(),
|
||||
Object::Dict(d) => d.clone(),
|
||||
_ => return false,
|
||||
};
|
||||
let drawn = match cat {
|
||||
b"XObject" => is_name(doc, &dict, b"Subtype", b"Form"),
|
||||
b"Font" => is_name(doc, &dict, b"Subtype", b"Type3"),
|
||||
// A shading pattern has no content of its own.
|
||||
_ => int_of(doc, &dict, b"PatternType") == Some(1),
|
||||
};
|
||||
drawn && dict.get(b"Resources").is_none()
|
||||
}
|
||||
|
||||
/// Whether `ops` (drawn with `resources`) blend with something other than Normal: a `gs` they
|
||||
/// use, or one used by a form or pattern they draw, at any depth. A shading pattern blends through
|
||||
/// its own `/ExtGState`, a tiling pattern through its content. A nested form or pattern that can't
|
||||
/// be read, is nested too deep or draws itself counts as blending, so the caller refuses rather
|
||||
/// than guesses. An operator the renderer skips ([`Unreadable`]) draws nothing and is skipped.
|
||||
fn blends_inside(doc: &Document, resources: &Dict, ops: &[Op], depth: usize, walk: &mut BlendWalk) -> bool {
|
||||
let category = |cat: &[u8]| resources.get(cat).map(|x| doc.resolve(x)).and_then(|x| x.as_dict().cloned()).unwrap_or_default();
|
||||
let (states, xobjects, patterns) = (category(b"ExtGState"), category(b"XObject"), category(b"Pattern"));
|
||||
let state_blends = |g: Option<&Object>| g.map(|g| doc.resolve(g)).and_then(|g| g.as_dict().cloned()).is_some_and(|gs| blends(doc, &gs));
|
||||
for op in ops {
|
||||
let Ok(Some((cat, i))) = resource_operand(op) else { continue };
|
||||
let Some(name) = op.name(i) else { continue };
|
||||
let o = match cat {
|
||||
b"ExtGState" if state_blends(states.get(name)) => return true,
|
||||
b"XObject" => xobjects.get(name),
|
||||
b"Pattern" => patterns.get(name),
|
||||
_ => continue,
|
||||
};
|
||||
let Some(o) = o else { continue };
|
||||
let resolved = doc.resolve(o);
|
||||
let nested = match &*resolved {
|
||||
Object::Stream(st) if op.is("Do") && is_name(doc, &st.dict, b"Subtype", b"Form") => st,
|
||||
Object::Stream(st) if !op.is("Do") && int_of(doc, &st.dict, b"PatternType") == Some(1) => st,
|
||||
// A shading pattern.
|
||||
Object::Stream(st) if !op.is("Do") => {
|
||||
if state_blends(st.dict.get(b"ExtGState")) {
|
||||
return true;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
Object::Dict(d) if !op.is("Do") => {
|
||||
if state_blends(d.get(b"ExtGState")) {
|
||||
return true;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
_ => continue,
|
||||
};
|
||||
let r = o.as_ref();
|
||||
if let Some(known) = r.and_then(|r| walk.known.get(&r)) {
|
||||
if *known {
|
||||
return true;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if depth >= MAX_NESTING || r.is_some_and(|r| walk.path.contains(&r)) || walk.reads >= MAX_NESTED_READS {
|
||||
return true;
|
||||
}
|
||||
walk.reads += 1;
|
||||
let Ok(data) = nested.decoded_strict_within(MAX_FORM_BYTES) else { return true };
|
||||
let own_resources = nested.dict.get(b"Resources").map(|r| doc.resolve(r)).and_then(|r| r.as_dict().cloned());
|
||||
let has_own = own_resources.is_some();
|
||||
let own = own_resources.unwrap_or_else(|| resources.clone());
|
||||
let inner = parse(&data);
|
||||
if inner.skipped > 0 {
|
||||
return true;
|
||||
}
|
||||
if let Some(r) = r {
|
||||
walk.path.push(r);
|
||||
}
|
||||
let blends = blends_inside(doc, &own, &inner.ops, depth + 1, walk);
|
||||
if let Some(r) = r {
|
||||
walk.path.retain(|x| *x != r);
|
||||
if has_own {
|
||||
walk.known.insert(r, blends);
|
||||
}
|
||||
}
|
||||
if blends {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// The blending colour space of the page group (ISO 32000-2 §11.4.7): the page's transparency
|
||||
/// `/Group /CS`, resolved. `None` when the page names none, and the PDF processor chooses.
|
||||
pub(crate) fn page_blend_space(doc: &Document, page: &Dict) -> Option<Object> {
|
||||
let group = page.get(b"Group").map(|g| doc.resolve(g)).and_then(|g| g.as_dict().cloned()).filter(|g| is_name(doc, g, b"S", b"Transparency"))?;
|
||||
group.get(b"CS").map(|cs| (*doc.resolve(cs)).clone())
|
||||
}
|
||||
|
||||
/// Whether a group blending in `cs` composites as the page does: in the page group's own space
|
||||
/// when it names one, else in DeviceRGB, the space viewers composite a page in on screen.
|
||||
fn same_blend_space(doc: &Document, cs: &Object, page_space: Option<&Object>) -> bool {
|
||||
let cs = doc.resolve(cs);
|
||||
match page_space {
|
||||
Some(page) => *cs == *page,
|
||||
None => cs.as_name() == Some(b"DeviceRGB"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `d`'s `key` is the name `want`, directly or through an indirect object (any value may
|
||||
/// be one, ISO 32000-2 §7.3.10).
|
||||
fn is_name(doc: &Document, d: &Dict, key: &[u8], want: &[u8]) -> bool {
|
||||
d.get(key).is_some_and(|v| doc.resolve(v).as_name() == Some(want))
|
||||
}
|
||||
|
||||
/// `d`'s integer `key`, directly or through an indirect object.
|
||||
fn int_of(doc: &Document, d: &Dict, key: &[u8]) -> Option<i64> {
|
||||
d.get(key).and_then(|v| doc.resolve(v).as_int())
|
||||
}
|
||||
|
||||
/// Whether an ExtGState blends with something other than Normal.
|
||||
fn blends(doc: &Document, gs: &Dict) -> bool {
|
||||
let Some(bm) = gs.get(b"BM").map(|b| doc.resolve(b)) else { return false };
|
||||
let first = match &*bm {
|
||||
Object::Array(a) => a.first().map(|x| doc.resolve(x)),
|
||||
_ => Some(bm.clone()),
|
||||
};
|
||||
!first.is_some_and(|b| matches!(b.as_name(), Some(b"Normal" | b"Compatible")))
|
||||
}
|
||||
|
||||
/// Whether the graphics state is translucent, blended or soft-masked at op `at` of the page's
|
||||
/// streams parsed as one (the indexes `page_images` gives), following `q`/`Q` and `gs`. Each `gs`
|
||||
/// changes only the parameters it sets.
|
||||
pub(crate) fn translucent_at(doc: &Document, resources: &Dict, ops: &[Op], at: usize) -> bool {
|
||||
let states = resources.get(b"ExtGState").map(|x| doc.resolve(x)).and_then(|x| x.as_dict().cloned()).unwrap_or_default();
|
||||
// Fill alpha below one, stroke alpha below one, a soft mask, a blend mode other than Normal.
|
||||
let mut stack: Vec<[bool; 4]> = Vec::new();
|
||||
let mut now = [false; 4];
|
||||
for op in ops.iter().take(at) {
|
||||
match op.op.as_slice() {
|
||||
b"q" => stack.push(now),
|
||||
b"Q" => now = stack.pop().unwrap_or([false; 4]),
|
||||
b"gs" => {
|
||||
let Ok(Some((_, i))) = resource_operand(op) else { continue };
|
||||
let Some(gs) = op.name(i).and_then(|n| states.get(n)).map(|g| doc.resolve(g)).and_then(|g| g.as_dict().cloned()) else {
|
||||
continue;
|
||||
};
|
||||
let alpha = |key: &[u8]| gs.get(key).map(|v| doc.resolve(v)).and_then(|v| v.as_f64()).map(|a| a < 1.0);
|
||||
if let Some(v) = alpha(b"ca") {
|
||||
now[0] = v;
|
||||
}
|
||||
if let Some(v) = alpha(b"CA") {
|
||||
now[1] = v;
|
||||
}
|
||||
if let Some(m) = gs.get(b"SMask").map(|v| doc.resolve(v)) {
|
||||
now[2] = m.as_name() != Some(b"None");
|
||||
}
|
||||
if gs.get(b"BM").is_some() {
|
||||
now[3] = blends(doc, &gs);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
now.iter().any(|v| *v)
|
||||
}
|
||||
@@ -206,6 +206,20 @@ pub struct OfficeExport {
|
||||
/// `Err(false)`: it can't be encoded).
|
||||
type PreparedImage = Result<(&'static str, Arc<[u8]>), bool>;
|
||||
|
||||
/// Displayed points per user-space unit on `info`'s page (`/UserUnit`), 1 when the page has no
|
||||
/// usable size.
|
||||
pub(crate) fn display_unit(info: &pdfcraft_render::PageInfo) -> f64 {
|
||||
let crop_width = f64::from(info.crop[2] - info.crop[0]);
|
||||
let display_width = f64::from(if info.rotation.is_multiple_of(180) { info.width } else { info.height });
|
||||
if crop_width > 0.0 && crop_width.is_finite() && display_width.is_finite() { display_width / crop_width } else { 1.0 }
|
||||
}
|
||||
|
||||
/// Bold and italic as a font's name says them (`Arial-BoldItalicMT`).
|
||||
pub(crate) fn weight_and_slant(base_font: &str) -> (bool, bool) {
|
||||
let f = base_font.to_ascii_lowercase();
|
||||
(f.contains("bold") || f.contains("black") || f.contains("heavy"), f.contains("italic") || f.contains("oblique"))
|
||||
}
|
||||
|
||||
impl crate::Document {
|
||||
/// The pages as paragraphs and images (for Word, HTML and RTF export), including what
|
||||
/// form XObjects draw.
|
||||
@@ -247,9 +261,7 @@ impl crate::Document {
|
||||
let b = info.user_to_view(r[2] as f32, r[3] as f32);
|
||||
[a[0].min(b[0]) as f64, (info.height - a[1].max(b[1])) as f64, a[0].max(b[0]) as f64, (info.height - a[1].min(b[1])) as f64]
|
||||
};
|
||||
let crop_width = f64::from(info.crop[2] - info.crop[0]);
|
||||
let display_width = f64::from(if info.rotation % 180 == 0 { info.width } else { info.height });
|
||||
let unit = if crop_width > 0.0 && crop_width.is_finite() && display_width.is_finite() { display_width / crop_width } else { 1.0 };
|
||||
let unit = display_unit(info);
|
||||
let reading = pdfcraft_edit::reading_blocks_checked(cos, i).unwrap_or_default();
|
||||
let forms_unread = reading.truncated;
|
||||
let blocks = reading
|
||||
@@ -257,7 +269,7 @@ impl crate::Document {
|
||||
.into_iter()
|
||||
.filter(|b| !b.text.trim().is_empty())
|
||||
.map(|b| {
|
||||
let f = b.base_font.to_ascii_lowercase();
|
||||
let (bold, italic) = weight_and_slant(&b.base_font);
|
||||
// `text` is trimmed; the editor text keeps the source's own spaces.
|
||||
let space_around = [b.editor_text.starts_with(char::is_whitespace), b.editor_text.ends_with(char::is_whitespace)];
|
||||
pdfcraft_export::Block {
|
||||
@@ -265,8 +277,8 @@ impl crate::Document {
|
||||
text: b.text,
|
||||
rect: visible_rect(b.rect),
|
||||
size: b.size * unit,
|
||||
bold: f.contains("bold") || f.contains("black") || f.contains("heavy"),
|
||||
italic: f.contains("italic") || f.contains("oblique"),
|
||||
bold,
|
||||
italic,
|
||||
color: b.color,
|
||||
rotation: b.rotation - f64::from(info.rotation),
|
||||
}
|
||||
@@ -301,7 +313,9 @@ impl crate::Document {
|
||||
}
|
||||
// The page colour (Edit a PDF ▸ Background, a producer's page fill) for formats that keep one.
|
||||
let background = pdfcraft_edit::page_background(cos, i).ok().flatten();
|
||||
pdfcraft_export::Page { width: info.width as f64, height: info.height as f64, blocks, images, background }
|
||||
// The ruled lines tell a drawn table from text that merely lines up (#5149).
|
||||
let rules = pdfcraft_edit::page_rules(cos, i).unwrap_or_default().into_iter().map(visible_rect).collect();
|
||||
pdfcraft_export::Page { width: info.width as f64, height: info.height as f64, blocks, images, background, rules }
|
||||
})
|
||||
.collect();
|
||||
(pages, truncated)
|
||||
|
||||
@@ -26,6 +26,9 @@ pub enum ImageEdit {
|
||||
Arrange(ArrangeOrder),
|
||||
/// Remove any private crop on the image.
|
||||
RemoveCrop,
|
||||
/// Grouped Form artwork: draw its content in place, so its text and pictures can be edited
|
||||
/// one by one (#2964).
|
||||
Ungroup,
|
||||
}
|
||||
|
||||
/// Forms ▸ Merge data files into spreadsheet: the field values of each file (FDF, XFDF or a
|
||||
|
||||
+101
-20
@@ -8,7 +8,8 @@ use pdfcraft_render::{DocInfo, RenderConfig, RenderPool};
|
||||
use crate::history::Editor;
|
||||
use crate::{
|
||||
CalculationOrder, CheckStyle, DocId, Edit, EditError, EditableObject, FormFieldKind, Hidden, InitialView, Label, MarkKind, SecuritySummary,
|
||||
SignatureInfo, TabOrder, TrustStore, XfaLayout, a11y, form_appearance, guard, js, measure, optimize, renderer_password, unrestricted,
|
||||
SignatureInfo, StatusCaptions, TabOrder, TrustStore, XfaLayout, a11y, form_appearance, guard, js, measure, optimize, renderer_password,
|
||||
signatures_of, unrestricted,
|
||||
};
|
||||
#[cfg(test)]
|
||||
use crate::{record_link_scan, record_marker_scan};
|
||||
@@ -19,8 +20,9 @@ pub struct Document {
|
||||
pub path: Option<String>,
|
||||
/// The working file: what Save writes.
|
||||
pub bytes: Arc<Vec<u8>>,
|
||||
/// What is displayed (the page view, `page_render`, page images): `bytes`, plus appearances
|
||||
/// drawn for display only for comments that have none ([`display_bytes`]). Never saved.
|
||||
/// What is displayed (the page view, `page_render`, page images): `bytes`, plus what is drawn
|
||||
/// for display only ([`display_bytes`]): appearances for comments that have none, and the
|
||||
/// states of named-layer signatures. Never saved.
|
||||
pub display: Arc<Vec<u8>>,
|
||||
pub info: DocInfo,
|
||||
pub renderer: RenderPool,
|
||||
@@ -41,6 +43,9 @@ pub struct Document {
|
||||
/// Signature fields, validated against the session's trust store (Signatures panel).
|
||||
pub signatures: Arc<Vec<SignatureInfo>>,
|
||||
pub(crate) trust: Arc<TrustStore>,
|
||||
/// The words signature status layers are drawn with (the session's, see
|
||||
/// [`Session::set_signature_captions`](crate::Session::set_signature_captions)).
|
||||
pub(crate) captions: Arc<StatusCaptions>,
|
||||
pub(crate) sig_cache: Arc<pdfcraft_sign::DigestCache>,
|
||||
pub(crate) editor: Option<Editor>,
|
||||
pub(crate) config: RenderConfig,
|
||||
@@ -631,6 +636,12 @@ impl Document {
|
||||
pub fn repair_log(&self) -> Vec<String> {
|
||||
self.editor.as_ref().map(|e| e.cos.repair_log().to_vec()).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Objects of the file that could not be read and read as null, one line each (see
|
||||
/// [`pdfcraft_cos::Document::unreadable_objects`]): only those read so far.
|
||||
pub fn unreadable_objects(&self) -> Vec<String> {
|
||||
self.editor.as_ref().map(|e| e.cos.unreadable_objects()).unwrap_or_default()
|
||||
}
|
||||
}
|
||||
|
||||
/// A title that names no document: what a web browser writes when it saves a blank page or a
|
||||
@@ -643,25 +654,84 @@ pub(crate) fn is_placeholder_title(title: &str) -> bool {
|
||||
address || t == "untitled"
|
||||
}
|
||||
|
||||
/// The working file plus appearances for comments that have none, and for form fields the file
|
||||
/// leaves to the viewer (#3470). Signature artwork is preserved; validation badges belong to the
|
||||
/// viewer and never enter these bytes, which image/text exports and Print as Image also consume.
|
||||
pub(crate) fn display_bytes(editor: Option<&mut Editor>, bytes: &Arc<Vec<u8>>) -> Arc<Vec<u8>> {
|
||||
/// What is displayed: the working file plus, in memory only and never saved, the appearances
|
||||
/// PdfCraft draws for comments that have none ([`pdfcraft_annot::with_missing_appearances`]) and
|
||||
/// for form fields the file leaves to the viewer (#3470), and the signature states drawn into
|
||||
/// named-layer signature appearances ([`pdfcraft_sign::show_status_layers`]). The working file is
|
||||
/// unchanged, and so is everything that reads it (saving, signatures, …). Image and text exports
|
||||
/// and Print as Image read these bytes, so they show the page as displayed; validation badges
|
||||
/// belong to the viewer and never enter them.
|
||||
///
|
||||
/// `signatures` is input and output: each one whose state gets drawn comes back marked
|
||||
/// (`verdict_shown`). A mark describes the bytes returned, so every mark is cleared first and a
|
||||
/// copy that cannot be written takes its marks with it.
|
||||
pub(crate) fn display_bytes(
|
||||
editor: Option<&mut Editor>,
|
||||
bytes: &Arc<Vec<u8>>,
|
||||
signatures: &mut [SignatureInfo],
|
||||
captions: &StatusCaptions,
|
||||
) -> Arc<Vec<u8>> {
|
||||
for sig in signatures.iter_mut() {
|
||||
sig.verdict_shown = false;
|
||||
}
|
||||
let Some(e) = editor else { return bytes.clone() };
|
||||
let comments = pdfcraft_annot::with_missing_appearances_cached(&e.cos, &mut e.appearances);
|
||||
let fields = pdfcraft_forms::with_field_appearances_cached(comments.as_ref().unwrap_or(&e.cos), &mut e.field_appearances);
|
||||
let Some(display) = fields.or(comments) else {
|
||||
if let Some(mut display) = fields.or(comments) {
|
||||
// Written whether or not a signature changed: the copy exists for the comments and fields.
|
||||
let _ = pdfcraft_sign::show_status_layers(&mut display, signatures, captions);
|
||||
return write_display_copy(e, bytes, &display, signatures);
|
||||
}
|
||||
// No comment or field needed an appearance, so there is no copy yet: build one only when a
|
||||
// signature's state would change it.
|
||||
if !pdfcraft_sign::has_status_layers(&e.cos, signatures) {
|
||||
return bytes.clone();
|
||||
};
|
||||
match write_incremental(&display, &SaveOptions::default()) {
|
||||
}
|
||||
let mut display = e.cos.clone();
|
||||
if !pdfcraft_sign::show_status_layers(&mut display, signatures, captions) {
|
||||
return bytes.clone();
|
||||
}
|
||||
write_display_copy(e, bytes, &display, signatures)
|
||||
}
|
||||
|
||||
/// Write the display copy, or keep the working file when it cannot be written. The page then
|
||||
/// shows the file's own artwork, so the marks are cleared. Losing the copy is a repair, so it is
|
||||
/// logged, once however many refreshes lose it again.
|
||||
pub(crate) fn write_display_copy(
|
||||
e: &mut Editor,
|
||||
bytes: &Arc<Vec<u8>>,
|
||||
display: &pdfcraft_cos::Document,
|
||||
signatures: &mut [SignatureInfo],
|
||||
) -> Arc<Vec<u8>> {
|
||||
match write_incremental(display, &SaveOptions::default()) {
|
||||
Ok(written) => Arc::new(written),
|
||||
Err(err) => {
|
||||
e.cos.note_repair(format!("missing comment or field appearances could not be drawn ({err})"));
|
||||
for sig in signatures.iter_mut() {
|
||||
sig.verdict_shown = false;
|
||||
}
|
||||
let line = format!("the display copy could not be written, so pages show the file as stored ({err})");
|
||||
if !e.cos.repair_log().contains(&line) {
|
||||
e.cos.note_repair(line);
|
||||
}
|
||||
bytes.clone()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Carry the marks across a revalidation that leaves the display copy alone, when it may: only
|
||||
/// when every verdict is the one the copy was drawn with. Returns whether it did; otherwise the
|
||||
/// copy has to be drawn again.
|
||||
pub(crate) fn carry_verdict_marks(previous: &[SignatureInfo], next: &mut [SignatureInfo]) -> bool {
|
||||
let unchanged = previous.len() == next.len()
|
||||
&& previous.iter().zip(next.iter()).all(|(p, n)| p.field == n.field && p.revision == n.revision && p.status == n.status);
|
||||
if unchanged {
|
||||
for (p, n) in previous.iter().zip(next.iter_mut()) {
|
||||
n.verdict_shown = p.verdict_shown;
|
||||
}
|
||||
}
|
||||
unchanged
|
||||
}
|
||||
|
||||
/// `comments` (the display copy with comment appearances, if it needed any; else the document
|
||||
/// itself) with its form fields drawn from their values where the file leaves that to the viewer.
|
||||
fn with_field_appearances(comments: Option<pdfcraft_cos::Document>, doc: &pdfcraft_cos::Document) -> Option<pdfcraft_cos::Document> {
|
||||
@@ -688,17 +758,28 @@ pub(crate) fn info_fields<'a>(info: &'a mut DocInfo, cos: &pdfcraft_cos::Documen
|
||||
]
|
||||
}
|
||||
|
||||
/// The copy PDFCraft displays when opening `bytes`: with appearances drawn, in memory only, for
|
||||
/// comments that have none and form fields the file leaves to the viewer. Render paths outside the app, such as the CLI, use this so their page
|
||||
/// images agree with the app and independent viewers. It never changes the source document, and an
|
||||
/// unparseable file, a write failure or a parser panic falls back to the original bytes.
|
||||
/// The copy PDFCraft displays when opening `bytes` with no trusted certificates and English
|
||||
/// captions ([`display_bytes`]): appearances drawn, in memory only, for comments that have none
|
||||
/// and form fields the file leaves to the viewer, and the state of each named-layer signature.
|
||||
/// Render paths outside the app, such as the CLI, use this so their page images agree with the app
|
||||
/// and independent viewers. It never changes the source document: a file with nothing to draw, an
|
||||
/// unparseable file, a write failure or a parser panic gives back the original bytes.
|
||||
pub fn display_bytes_for(bytes: Arc<Vec<u8>>, password: Option<&str>) -> Arc<Vec<u8>> {
|
||||
guard(|| {
|
||||
pdfcraft_cos::Document::open_with_password(bytes.clone(), password)
|
||||
.ok()
|
||||
.and_then(|cos| with_field_appearances(pdfcraft_annot::with_missing_appearances(&cos), &cos))
|
||||
.and_then(|display| write_incremental(&display, &SaveOptions::default()).ok())
|
||||
.map(Arc::new)
|
||||
let cos = pdfcraft_cos::Document::open_with_password(bytes.clone(), password).ok()?;
|
||||
let mut signatures = signatures_of(&cos, &bytes, &TrustStore::default(), &pdfcraft_sign::DigestCache::default());
|
||||
let layered = pdfcraft_sign::has_status_layers(&cos, &signatures);
|
||||
let (mut display, added) = match with_field_appearances(pdfcraft_annot::with_missing_appearances(&cos), &cos) {
|
||||
Some(display) => (display, true),
|
||||
None if layered => (cos, false),
|
||||
None => return None,
|
||||
};
|
||||
// As in the app, a layer recognised but not drawn after all makes no copy.
|
||||
let drawn = layered && pdfcraft_sign::show_status_layers(&mut display, &mut signatures, &StatusCaptions::default());
|
||||
if !(added || drawn) {
|
||||
return None;
|
||||
}
|
||||
write_incremental(&display, &SaveOptions::default()).ok().map(Arc::new)
|
||||
})
|
||||
.ok()
|
||||
.flatten()
|
||||
|
||||
@@ -286,6 +286,7 @@ impl Edit {
|
||||
pdfcraft_edit::ArrangeOrder::SendToBack => "Send to back",
|
||||
},
|
||||
ImageEdit::RemoveCrop => "Remove crop",
|
||||
ImageEdit::Ungroup => "Ungroup artwork",
|
||||
}),
|
||||
Edit::AddHeaderFooter { replace: false, .. } => Label::of("Add header & footer"),
|
||||
Edit::AddHeaderFooter { .. } => Label::of("Update header & footer"),
|
||||
|
||||
@@ -306,6 +306,7 @@ fn run_edit_page_image(doc: &mut pdfcraft_cos::Document, page: usize, index: usi
|
||||
ImageEdit::Delete => pdfcraft_edit::ImageChange::Delete,
|
||||
ImageEdit::Arrange(order) => pdfcraft_edit::ImageChange::Arrange(*order),
|
||||
ImageEdit::RemoveCrop => pdfcraft_edit::ImageChange::RemoveCrop,
|
||||
ImageEdit::Ungroup => pdfcraft_edit::ImageChange::Ungroup,
|
||||
};
|
||||
let page_model = pdfcraft_model::pages(doc)
|
||||
.into_iter()
|
||||
@@ -411,7 +412,7 @@ fn run_edit_page_image(doc: &mut pdfcraft_cos::Document, page: usize, index: usi
|
||||
ai.image = new_image;
|
||||
pdfcraft_edit::update_content(doc, page, added_idx, &AddedContent::Image(ai))?;
|
||||
}
|
||||
ImageEdit::Crop(_) | ImageEdit::RemoveCrop | ImageEdit::RotateBy(_) | ImageEdit::Arrange(_) | ImageEdit::Delete => {
|
||||
ImageEdit::Crop(_) | ImageEdit::RemoveCrop | ImageEdit::RotateBy(_) | ImageEdit::Arrange(_) | ImageEdit::Delete | ImageEdit::Ungroup => {
|
||||
pdfcraft_edit::change_image(doc, page, index, &c)?;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
//! Export a PDF ▸ Image and Text (execution plan M10.3, the first formats).
|
||||
//!
|
||||
//! [`Exporter`] renders pages to PNG, JPEG or TIFF at a resolution and extracts reading-order
|
||||
//! text, from a
|
||||
//! document's working file (so unsaved edits and hidden layers are respected, as on screen).
|
||||
//! text, from the copy a document displays ([`Document::export_source`]): its working file, so
|
||||
//! unsaved edits and hidden layers are respected, with what is drawn for display only.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::panic::{AssertUnwindSafe, catch_unwind};
|
||||
@@ -67,9 +67,10 @@ pub struct ExportSource {
|
||||
|
||||
impl Document {
|
||||
/// What an export reads, for exporting on another thread. These are the displayed
|
||||
/// bytes, so they may carry missing comment appearances PdfCraft drew. Signature
|
||||
/// artwork stays original; viewer validation badges are not document content and
|
||||
/// do not enter image/text exports or Print as Image. Saving uses the working file.
|
||||
/// bytes, so they may carry appearances PdfCraft drew that the file itself does not hold:
|
||||
/// missing comment appearances, and the signature states of named-layer signature
|
||||
/// appearances. Exports and Print as Image follow the page as shown; the viewer's badges
|
||||
/// are not document content and never enter them. Saving uses the working file.
|
||||
pub fn export_source(&self) -> ExportSource {
|
||||
ExportSource {
|
||||
bytes: self.display.clone(),
|
||||
|
||||
@@ -429,12 +429,16 @@ impl Session {
|
||||
let mut out = Vec::new();
|
||||
for page in list {
|
||||
let Some(info) = doc.info.pages.get(page) else { continue };
|
||||
let res = r.render(pdfcraft_render::RenderRequest { page, kind: pdfcraft_render::RequestKind::Text, scale: 1.0, ..Default::default() });
|
||||
let shapes = pdfcraft_forms::detect::page_shapes(cos, page);
|
||||
let existing: Vec<[f64; 4]> = doc.form.iter().flat_map(|f| f.widgets.iter()).filter(|w| w.page == Some(page)).map(|w| w.rect).collect();
|
||||
let (found, turn) = if shapes.boxes.is_empty() && shapes.rules.is_empty() && crate::scan_fields::is_scan(doc, page, info) {
|
||||
self.detect_on_scan(id, &mut r, page, res.text.as_deref(), &existing, &taken)
|
||||
// Labels come from the page's own text. Words that only /ActualText names (a stamp
|
||||
// drawn as outlines) are no labels, and leave the scan to be read.
|
||||
let own = crate::ocr::own_text(&mut r, page).ok();
|
||||
self.detect_on_scan(id, &mut r, page, own.as_ref(), &existing, &taken)
|
||||
} else {
|
||||
let res =
|
||||
r.render(pdfcraft_render::RenderRequest { page, kind: pdfcraft_render::RequestKind::Text, scale: 1.0, ..Default::default() });
|
||||
let words = res.text.map(|t| detection_words(&t, info)).unwrap_or_default();
|
||||
(pdfcraft_forms::detect::detect(&words, &shapes, &existing, &taken), 0)
|
||||
};
|
||||
|
||||
@@ -44,6 +44,7 @@ mod pictures;
|
||||
pub mod print_raster;
|
||||
pub mod printcheck;
|
||||
mod protection;
|
||||
mod rich_copy;
|
||||
pub mod scan_clean;
|
||||
mod scan_colours;
|
||||
mod scan_fields;
|
||||
@@ -68,6 +69,7 @@ pub use links::{
|
||||
MAX_REMOTE_DOCUMENT_BYTES, RemoteDocumentPathError, read_remote_document, remote_document_path_is_absolute, resolve_remote_document_path,
|
||||
};
|
||||
pub use pdfcraft_edit::strip_subset_tag;
|
||||
pub use rich_copy::RichCopy;
|
||||
pub use signature_image::{ImageSignaturePreview, SignatureImage};
|
||||
pub use signature_scan::{PhotoRect, ScanError, SignaturePhoto, Turn};
|
||||
pub use stamp_preview::{CommentLayer, StampPreview};
|
||||
@@ -91,7 +93,8 @@ pub use pdfcraft_edit::added::{
|
||||
};
|
||||
pub use pdfcraft_edit::paragraph_align;
|
||||
pub use pdfcraft_edit::{
|
||||
Added, AddedImage, AddedText, Align as TextAlign, Background, Content as AddedContent, Family as FontFamily, HeaderFooter, MarkKind, Watermark,
|
||||
Added, AddedImage, AddedText, Align as TextAlign, Background, Content as AddedContent, Family as FontFamily, HeaderFooter, Ink as TextInk,
|
||||
MarkKind, Watermark,
|
||||
};
|
||||
pub use pdfcraft_forms::{
|
||||
BorderStyle, CalculatedField, CalculationIssue, CalculationOrder, CheckStyle, Field as FormField, FieldAction, FieldChange, FieldFont,
|
||||
@@ -127,8 +130,9 @@ pub use pdfcraft_redact::patterns::{
|
||||
MAX_WORDS as REDACT_MAX_WORDS, PATTERNS as REDACT_PATTERNS, Pattern as RedactPattern, find as find_pattern, word_list as redact_word_list,
|
||||
};
|
||||
pub use pdfcraft_redact::sanitize::{HIDDEN, Hidden};
|
||||
pub use pdfcraft_redact::user_regex::{UserRegex as RedactRegex, VALIDATORS as REDACT_VALIDATORS, Validator as RedactValidator};
|
||||
pub use pdfcraft_sign as sign;
|
||||
pub use pdfcraft_sign::{SignOptions, SignatureInfo, Status as SignatureStatus, TrustStore};
|
||||
pub use pdfcraft_sign::{SignOptions, SignatureInfo, Status as SignatureStatus, StatusCaptions, TrustStore};
|
||||
pub use pdfcraft_xfdf::Format as DataFormat;
|
||||
pub use pdfcraft_xfdf::{Outline as CommentOutline, comment_count, comment_outlines, comments_bounds, is_xfdf_comments};
|
||||
|
||||
@@ -139,7 +143,7 @@ pub use comments::{SummarySort, comment_kind, comment_summary, comment_type_name
|
||||
#[cfg(test)]
|
||||
use document::page_runs;
|
||||
pub use document::{Document, EditNotice, TextNotice, display_bytes_for, render_password_for};
|
||||
use document::{display_bytes, info_fields, recovered_render_password, same_pages, shown_under_redactions, undrawn_notices};
|
||||
use document::{carry_verdict_marks, display_bytes, info_fields, recovered_render_password, same_pages, shown_under_redactions, undrawn_notices};
|
||||
pub use edit::{BATCH_LABELS, EDIT_LABELS, Edit};
|
||||
pub use error::{EditError, SourceProblem};
|
||||
pub use fill_sign::{displayed_offset, text_box_at, typed_signature_graphic, typed_signature_shape};
|
||||
|
||||
@@ -11,6 +11,7 @@ use std::sync::{Arc, Mutex};
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use pdfcraft_render::text::TextFilter;
|
||||
use pdfcraft_render::{PageInfo, PageRenderer, RenderConfig, RenderRequest, RequestKind};
|
||||
|
||||
pub use pdfcraft_ocr::{
|
||||
@@ -161,6 +162,18 @@ const ALREADY_ON_PAGE: f32 = 0.5;
|
||||
/// is a resolution on paper this size or smaller.
|
||||
const SHEET: f32 = 842.0;
|
||||
|
||||
/// The text of `page`'s own: its glyphs, without the words drawn as outlines or pictures that only
|
||||
/// `/ActualText` names.
|
||||
pub(crate) fn own_text(r: &mut PageRenderer, page: usize) -> Result<pdfcraft_render::PageText, String> {
|
||||
r.filtered_text(page, TextFilter { painted: true, ..Default::default() })
|
||||
}
|
||||
|
||||
/// Whether `page` has text of its own ([`own_text`]). A stamp drawn as outlines on a scan still
|
||||
/// leaves the scan to read; its words are not read twice, since they count as already on the page.
|
||||
fn has_own_text(r: &mut PageRenderer, page: usize) -> bool {
|
||||
own_text(r, page).is_ok_and(|t| t.glyphs.iter().any(|g| !g.text.trim().is_empty()))
|
||||
}
|
||||
|
||||
/// How much of `word` the `text` boxes cover, from 0 to 1. Boxes are `[x0, y0, x1, y1]` in page
|
||||
/// view space. Overlaps between the text boxes are counted twice (glyphs rarely overlap), so the
|
||||
/// sum is capped at the whole word.
|
||||
@@ -702,13 +715,14 @@ impl OcrJob {
|
||||
}
|
||||
let Some(info) = self.infos.get(page) else { continue };
|
||||
let skip = |why: &str| OcrPage { page, words: Vec::new(), already_on_page: 0, skipped: Some(why.into()), notes: Vec::new() };
|
||||
// The boxes of the page's own text (an earlier OCR layer's included), in view space.
|
||||
// The boxes of all text on the page, in view space: an earlier OCR layer's, and words
|
||||
// only /ActualText names, so neither is read again.
|
||||
let existing: Vec<[f32; 4]> = r
|
||||
.render(RenderRequest { page, kind: RequestKind::Text, scale: 1.0, ..Default::default() })
|
||||
.text
|
||||
.map(|t| t.glyphs.iter().filter(|g| !g.text.trim().is_empty()).map(|g| g.rect).collect())
|
||||
.unwrap_or_default();
|
||||
if self.settings.skip_text_pages && !self.settings.force_ocr && !existing.is_empty() {
|
||||
if self.settings.skip_text_pages && !self.settings.force_ocr && !existing.is_empty() && has_own_text(&mut r, page) {
|
||||
out.push(skip("the page already contains text"));
|
||||
continue;
|
||||
}
|
||||
@@ -1118,6 +1132,34 @@ mod tests {
|
||||
use super::*;
|
||||
use crate::export;
|
||||
|
||||
/// One 300 × 300 page drawing `content`, with Helvetica as `/F1`.
|
||||
fn page(content: &str) -> Arc<Vec<u8>> {
|
||||
let pdf = format!(
|
||||
"%PDF-1.7\n1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj\n2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj\n\
|
||||
3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 300 300] /Contents 4 0 R /Resources << /Font << /F1 5 0 R >> >> >> endobj\n\
|
||||
4 0 obj << /Length {} >> stream\n{content}\nendstream endobj\n\
|
||||
5 0 obj << /Type /Font /Subtype /Type1 /BaseFont /Helvetica >> endobj\ntrailer << /Root 1 0 R >>\n%%EOF",
|
||||
content.len()
|
||||
);
|
||||
Arc::new(pdf.into_bytes())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stamp_drawn_as_outlines_leaves_a_scan_to_read() {
|
||||
let stamp = page("/Span <</ActualText (APPROVED)>> BDC 100 40 60 20 re f EMC");
|
||||
let mut r = PageRenderer::new(stamp, RenderConfig::default());
|
||||
assert!(!has_own_text(&mut r, 0), "words only /ActualText names are no text of the page's own");
|
||||
// They still count as on the page, so reading the scan doesn't add them twice.
|
||||
let text = r.render(RenderRequest { page: 0, kind: RequestKind::Text, scale: 1.0, ..Default::default() }).text.unwrap();
|
||||
assert_eq!(text.plain_text(), "APPROVED");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn printed_glyphs_count_as_own_text() {
|
||||
let mut r = PageRenderer::new(page("BT /F1 12 Tf 20 150 Td (Total) Tj ET"), RenderConfig::default());
|
||||
assert!(has_own_text(&mut r, 0));
|
||||
}
|
||||
|
||||
/// #1028: a recognised word over the page's own text is that text again; one in an empty
|
||||
/// part of the page (a picture) is new.
|
||||
#[test]
|
||||
|
||||
@@ -7,8 +7,8 @@ use pdfcraft_render::{DocInfo, OpenError, RenderConfig, RenderPool, inspect};
|
||||
|
||||
use crate::history::{Editor, Keys, TextBlocksCache};
|
||||
use crate::{
|
||||
AppearanceCache, DocId, Document, Session, TrustStore, XFA_SCRIPTS_OFF, XfaLayout, display_bytes, display_config, guard, info_fields, js,
|
||||
note_warnings, recovered_render_password, render_threads, same_pages, signatures_of, xfa, xfa_layout, xfa_values_from_datasets,
|
||||
AppearanceCache, DocId, Document, Session, StatusCaptions, TrustStore, XFA_SCRIPTS_OFF, XfaLayout, display_bytes, display_config, guard,
|
||||
info_fields, js, note_warnings, recovered_render_password, render_threads, same_pages, signatures_of, xfa, xfa_layout, xfa_values_from_datasets,
|
||||
};
|
||||
|
||||
/// Immutable session state needed while a document is prepared away from its owning thread.
|
||||
@@ -17,6 +17,7 @@ pub struct OpenContext {
|
||||
now: Option<i64>,
|
||||
js_off: bool,
|
||||
trust: Arc<TrustStore>,
|
||||
captions: Arc<StatusCaptions>,
|
||||
xfa_time_scale: u32,
|
||||
}
|
||||
|
||||
@@ -54,7 +55,13 @@ impl OpenContext {
|
||||
impl Session {
|
||||
/// Snapshot the session state that affects open-time scripts, dates and signature trust.
|
||||
pub fn open_context(&self) -> OpenContext {
|
||||
OpenContext { now: self.now(), js_off: self.js_off, trust: self.trust.clone(), xfa_time_scale: self.xfa_time_scale.unwrap_or(1) }
|
||||
OpenContext {
|
||||
now: self.now(),
|
||||
js_off: self.js_off,
|
||||
trust: self.trust.clone(),
|
||||
captions: self.captions.clone(),
|
||||
xfa_time_scale: self.xfa_time_scale.unwrap_or(1),
|
||||
}
|
||||
}
|
||||
|
||||
/// Prepare a document without adding it to this session.
|
||||
@@ -74,6 +81,14 @@ impl Session {
|
||||
let id = DocId(self.next_id);
|
||||
let mut document = prepared.document;
|
||||
document.id = id;
|
||||
// Trust or the interface language may have changed while it was prepared on another
|
||||
// thread.
|
||||
if !Arc::ptr_eq(&document.trust, &self.trust) {
|
||||
document.captions = self.captions.clone();
|
||||
Self::revalidate(&mut document, self.trust.clone());
|
||||
} else if *document.captions != *self.captions {
|
||||
Self::draw_captions(&mut document, self.captions.clone());
|
||||
}
|
||||
self.docs.push(document);
|
||||
id
|
||||
}
|
||||
@@ -253,7 +268,7 @@ impl Session {
|
||||
// XFA notes survive the document being re-read after edits.
|
||||
let xfa_warnings: Vec<String> = if info.xfa.is_some() { info.warnings.clone() } else { Vec::new() };
|
||||
let mut document =
|
||||
Self::build_document(&context.trust, DocumentOpenData { name, path, bytes, info, structure: cos, render_password, password, xfa });
|
||||
Self::build_document(context, DocumentOpenData { name, path, bytes, info, structure: cos, render_password, password, xfa });
|
||||
// A script that ran away on open turns the form's scripts off for this document.
|
||||
document.xfa_template = if ran_away { None } else { xfa_template };
|
||||
document.js_output.append(script_output);
|
||||
@@ -266,7 +281,7 @@ impl Session {
|
||||
}
|
||||
|
||||
/// The last step of opening: build the document record and register it.
|
||||
fn build_document(trust: &Arc<TrustStore>, data: DocumentOpenData<'_>) -> Document {
|
||||
fn build_document(context: &OpenContext, data: DocumentOpenData<'_>) -> Document {
|
||||
let DocumentOpenData { name, path, bytes, mut info, structure: cos, render_password, password, xfa } = data;
|
||||
let config = RenderConfig { password: render_password.as_deref().map(Arc::from), ..Default::default() };
|
||||
let (mut editor, read_only_reason) = match cos {
|
||||
@@ -293,7 +308,7 @@ impl Session {
|
||||
Err(_) => (None, Some("the document structure could not be read for editing".into())),
|
||||
};
|
||||
let sig_cache = Arc::new(pdfcraft_sign::DigestCache::default());
|
||||
let signatures = editor.as_ref().map(|e| signatures_of(&e.cos, &bytes, trust, &sig_cache)).unwrap_or_default();
|
||||
let mut signatures = editor.as_ref().map(|e| signatures_of(&e.cos, &bytes, &context.trust, &sig_cache)).unwrap_or_default();
|
||||
// The inspection reads only `/Info`; a file stating its title or author only in XMP still
|
||||
// shows them (#2373).
|
||||
if let Some(e) = &editor {
|
||||
@@ -303,7 +318,7 @@ impl Session {
|
||||
}
|
||||
}
|
||||
}
|
||||
let display = display_bytes(editor.as_mut(), &bytes);
|
||||
let display = display_bytes(editor.as_mut(), &bytes, &mut signatures, &context.captions);
|
||||
let renderer = RenderPool::new(display.clone(), render_threads(), display_config(&config));
|
||||
let (form, adopted) = editor
|
||||
.as_ref()
|
||||
@@ -341,7 +356,8 @@ impl Session {
|
||||
marker_scan: OnceLock::new(),
|
||||
links: OnceLock::new(),
|
||||
signatures: Arc::new(signatures),
|
||||
trust: trust.clone(),
|
||||
trust: context.trust.clone(),
|
||||
captions: context.captions.clone(),
|
||||
sig_cache,
|
||||
editor,
|
||||
config,
|
||||
|
||||
@@ -0,0 +1,389 @@
|
||||
//! Copy with formatting: the selected glyphs of a page as paragraphs of styled spans and an
|
||||
//! HTML fragment ([`pdfcraft_export::clip_html`]) for the clipboard, next to the plain text.
|
||||
//!
|
||||
//! Glyphs come from the text layer (view space); style comes from the page's reading blocks,
|
||||
//! which never mix styles, mapped into view space. A glyph takes the style of the block its
|
||||
//! centre lies in; a glyph in no block is copied unstyled.
|
||||
|
||||
use pdfcraft_export::{ClipBuilder, ClipStyle, ClipText, clip_html};
|
||||
use pdfcraft_render::{PageInfo, PageText};
|
||||
|
||||
use crate::EditError;
|
||||
use crate::compare::{display_unit, weight_and_slant};
|
||||
|
||||
/// Block tests spent matching glyphs to blocks for one copy; past it the rest is unstyled.
|
||||
const MAX_MATCH_STEPS: usize = 20_000_000;
|
||||
/// How far outside a block's box (points) a glyph centre still belongs to it.
|
||||
const SLACK: f32 = 0.5;
|
||||
|
||||
/// Selected text with its formatting.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct RichCopy {
|
||||
/// The paragraphs and spans.
|
||||
pub text: ClipText,
|
||||
/// The HTML fragment for the clipboard (empty when nothing was selected).
|
||||
pub html: String,
|
||||
/// Styles were left out: the document has no editor to read them, reading stopped at its
|
||||
/// limits on this page, or matching glyphs to blocks ran out of steps.
|
||||
pub styles_incomplete: bool,
|
||||
/// A cap left part of the selection out of `text` and `html`; the plain text has all of it.
|
||||
pub truncated: bool,
|
||||
}
|
||||
|
||||
struct StyledBlock {
|
||||
rect: [f32; 4],
|
||||
style: ClipStyle,
|
||||
}
|
||||
|
||||
impl crate::Document {
|
||||
/// Selected `glyphs` of `page` (indices into `text`, in copy order) with their formatting.
|
||||
/// Refused when the document does not allow copying.
|
||||
pub fn rich_copy(&self, page: usize, text: &PageText, glyphs: &[usize]) -> Result<RichCopy, EditError> {
|
||||
self.rich_copy_within(page, text, glyphs, MAX_MATCH_STEPS)
|
||||
}
|
||||
|
||||
/// [`Self::rich_copy`] with `steps` block tests to match glyphs to blocks.
|
||||
fn rich_copy_within(&self, page: usize, text: &PageText, glyphs: &[usize], mut steps: usize) -> Result<RichCopy, EditError> {
|
||||
self.check_copying()?;
|
||||
let (blocks, mut incomplete) = self.styled_blocks(page);
|
||||
let mut nested = vec![None; blocks.len()];
|
||||
let mut b = ClipBuilder::new();
|
||||
// The previous glyph's line, block and box, and whether it was a hyphen.
|
||||
let mut prev: Option<(usize, Option<usize>, [f32; 4], bool)> = None;
|
||||
for &i in glyphs {
|
||||
let (Some(g), Some(&line)) = (text.glyphs.get(i), text.line_of.get(i)) else { continue };
|
||||
let hint = prev.and_then(|(_, b, _, _)| b).filter(|&k| !holds_smaller(&blocks, &mut nested, k, &mut steps));
|
||||
let found = block_at(&blocks, g.rect, hint, &mut steps).unwrap_or_else(|| {
|
||||
incomplete = true;
|
||||
None
|
||||
});
|
||||
let line = usize::try_from(line).unwrap_or(usize::MAX);
|
||||
if let Some((prev_line, prev_block, prev_rect, hyphen)) = prev {
|
||||
if line != prev_line {
|
||||
let style = |k: Option<usize>| k.and_then(|k| blocks.get(k)).map(|s| &s.style);
|
||||
if found.is_none() && prev_block.is_none() {
|
||||
b.line_break();
|
||||
} else if found == prev_block || wraps(style(prev_block), style(found), prev_rect, g.rect) {
|
||||
// A paragraph wrapping: one space, none after a hyphen.
|
||||
if !hyphen {
|
||||
b.space();
|
||||
}
|
||||
} else {
|
||||
b.paragraph();
|
||||
}
|
||||
} else if text.space_before.get(i).copied().unwrap_or(false) {
|
||||
b.space();
|
||||
}
|
||||
}
|
||||
let style = found.and_then(|k| blocks.get(k)).map(|s| &s.style);
|
||||
if !b.push(&g.text, style.unwrap_or(&ClipStyle::default())) {
|
||||
break;
|
||||
}
|
||||
prev = Some((line, found, g.rect, g.text.ends_with('-')));
|
||||
}
|
||||
Ok(finish(b, incomplete))
|
||||
}
|
||||
|
||||
/// `page`'s reading blocks in view space with their style, and whether reading stopped at
|
||||
/// its limits.
|
||||
fn styled_blocks(&self, page: usize) -> (Vec<StyledBlock>, bool) {
|
||||
let Some(info) = self.info.pages.get(page) else { return (Vec::new(), false) };
|
||||
let Some(editor) = self.editor.as_ref() else { return (Vec::new(), true) };
|
||||
let Ok(reading) = pdfcraft_edit::reading_blocks_checked(&editor.cos, page) else { return (Vec::new(), true) };
|
||||
let unit = display_unit(info);
|
||||
let blocks = reading
|
||||
.blocks
|
||||
.into_iter()
|
||||
.filter(|b| !b.text.trim().is_empty())
|
||||
.map(|b| {
|
||||
let (bold, italic) = weight_and_slant(&b.base_font);
|
||||
let style = ClipStyle {
|
||||
families: pdfcraft_export::font_family(&b.base_font),
|
||||
size: b.size * unit,
|
||||
bold: b.bold || bold,
|
||||
italic: b.italic || italic,
|
||||
color: b.color,
|
||||
};
|
||||
StyledBlock { rect: view_rect(info, b.rect), style }
|
||||
})
|
||||
.collect();
|
||||
(blocks, reading.truncated)
|
||||
}
|
||||
}
|
||||
|
||||
/// A user-space box as a view-space box (points from the displayed page's top-left, y down).
|
||||
fn view_rect(info: &PageInfo, r: [f64; 4]) -> [f32; 4] {
|
||||
let a = info.user_to_view(r[0] as f32, r[1] as f32);
|
||||
let b = info.user_to_view(r[2] as f32, r[3] as f32);
|
||||
[a[0].min(b[0]), a[1].min(b[1]), a[0].max(b[0]), a[1].max(b[1])]
|
||||
}
|
||||
|
||||
/// The copy `b` collected, with its HTML; `truncated` when a cap cut the text or the HTML.
|
||||
fn finish(b: ClipBuilder, styles_incomplete: bool) -> RichCopy {
|
||||
let text = b.finish();
|
||||
let (html, cut) = clip_html(&text);
|
||||
RichCopy { html, truncated: text.truncated || cut, text, styles_incomplete }
|
||||
}
|
||||
|
||||
/// Whether the next line starts inside the same paragraph although its first glyph is in another
|
||||
/// block: blocks split where the style changes, so a style change at a line's end is still a
|
||||
/// wrap when the size stays and the lines sit no further apart than their own height allows.
|
||||
/// Two blocks of the same style, a change of size, or a gap of over half a line are paragraphs.
|
||||
fn wraps(prev: Option<&ClipStyle>, next: Option<&ClipStyle>, prev_rect: [f32; 4], rect: [f32; 4]) -> bool {
|
||||
let (Some(prev), Some(next)) = (prev, next) else { return false };
|
||||
let diff = (prev.size - next.size).abs();
|
||||
if prev == next || diff.is_nan() || diff > 0.01 {
|
||||
return false;
|
||||
}
|
||||
let height = (prev_rect[3] - prev_rect[1]).max(rect[3] - rect[1]);
|
||||
// The next line starts just below the last one; a line far above it is another column.
|
||||
let gap = rect[1] - prev_rect[3];
|
||||
height > 0.0 && gap.is_finite() && gap >= -height / 2.0 && gap <= height / 2.0
|
||||
}
|
||||
|
||||
/// Whether a block smaller than block `k` overlaps it, so a glyph inside `k` may belong to that
|
||||
/// one instead. Worked out once per block (`nested` keeps it), at a step per block tested; when
|
||||
/// the steps run out the answer is yes, so the full search decides.
|
||||
fn holds_smaller(blocks: &[StyledBlock], nested: &mut [Option<bool>], k: usize, steps: &mut usize) -> bool {
|
||||
if let Some(Some(known)) = nested.get(k) {
|
||||
return *known;
|
||||
}
|
||||
let Some(outer) = blocks.get(k) else { return true };
|
||||
let area = |r: &[f32; 4]| (r[2] - r[0]) * (r[3] - r[1]);
|
||||
let overlaps = |r: &[f32; 4]| r[0] < outer.rect[2] && r[2] > outer.rect[0] && r[1] < outer.rect[3] && r[3] > outer.rect[1];
|
||||
let mut found = false;
|
||||
for (j, b) in blocks.iter().enumerate() {
|
||||
if *steps == 0 {
|
||||
return true;
|
||||
}
|
||||
*steps -= 1;
|
||||
if j != k && overlaps(&b.rect) && area(&b.rect) < area(&outer.rect) {
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if let Some(slot) = nested.get_mut(k) {
|
||||
*slot = Some(found);
|
||||
}
|
||||
found
|
||||
}
|
||||
|
||||
/// The block whose box holds the centre of `glyph` (view space): `hint` first (a block no
|
||||
/// smaller one overlaps), then the smallest that holds it. Each block tested costs a step;
|
||||
/// `None` when the steps ran out first.
|
||||
fn block_at(blocks: &[StyledBlock], glyph: [f32; 4], hint: Option<usize>, steps: &mut usize) -> Option<Option<usize>> {
|
||||
let (x, y) = ((glyph[0] + glyph[2]) / 2.0, (glyph[1] + glyph[3]) / 2.0);
|
||||
let holds = |r: &[f32; 4]| x >= r[0] - SLACK && x <= r[2] + SLACK && y >= r[1] - SLACK && y <= r[3] + SLACK;
|
||||
let area = |r: &[f32; 4]| (r[2] - r[0]) * (r[3] - r[1]);
|
||||
if let Some(k) = hint
|
||||
&& *steps > 0
|
||||
{
|
||||
*steps -= 1;
|
||||
if blocks.get(k).is_some_and(|b| holds(&b.rect)) {
|
||||
return Some(Some(k));
|
||||
}
|
||||
}
|
||||
let mut best: Option<(usize, f32)> = None;
|
||||
for (k, b) in blocks.iter().enumerate() {
|
||||
if *steps == 0 {
|
||||
return None;
|
||||
}
|
||||
*steps -= 1;
|
||||
if holds(&b.rect) && best.is_none_or(|(_, a)| area(&b.rect) < a) {
|
||||
best = Some((k, area(&b.rect)));
|
||||
}
|
||||
}
|
||||
Some(best.map(|(k, _)| k))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::sync::Arc;
|
||||
|
||||
use pdfcraft_export::{ClipBuilder, ClipStyle};
|
||||
|
||||
use crate::Session;
|
||||
|
||||
/// A heading in bold, a body paragraph of two lines with HTML-special characters, and a red
|
||||
/// word on the body's first line.
|
||||
fn styled_page() -> Vec<u8> {
|
||||
let content = b"BT /F1 24 Tf 20 250 Td (Title) Tj ET \
|
||||
BT /F2 12 Tf 20 200 Td (Body text) Tj ET \
|
||||
BT 1 0 0 rg /F2 12 Tf 90 200 Td (red) Tj ET \
|
||||
BT /F2 12 Tf 20 186 Td (a<b & c) Tj ET";
|
||||
page_with(content)
|
||||
}
|
||||
|
||||
/// A one-page PDF drawing `content` with `/F1` Helvetica-Bold and `/F2` Helvetica.
|
||||
fn page_with(content: &[u8]) -> Vec<u8> {
|
||||
pdfcraft_testkit::Pdf::new()
|
||||
.obj("<< /Type /Catalog /Pages 2 0 R >>")
|
||||
.obj("<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 300 300] >>")
|
||||
.obj("<< /Type /Page /Parent 2 0 R /Contents 4 0 R /Resources << /Font << /F1 5 0 R /F2 6 0 R >> >> >>")
|
||||
.stream("", content)
|
||||
.obj("<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica-Bold >>")
|
||||
.obj("<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>")
|
||||
.build()
|
||||
}
|
||||
|
||||
fn page_text(s: &Session, id: crate::DocId) -> Arc<pdfcraft_render::PageText> {
|
||||
let doc = s.get(id).unwrap();
|
||||
let mut r = pdfcraft_render::PageRenderer::new(doc.bytes.clone(), Default::default());
|
||||
let request = pdfcraft_render::RenderRequest { page: 0, kind: pdfcraft_render::RequestKind::Text, scale: 1.0, ..Default::default() };
|
||||
r.render(request).text.unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn copy_keeps_headings_body_and_colour_as_html() {
|
||||
let mut s = Session::new();
|
||||
let id = s.open("styled.pdf", None, Arc::new(styled_page()), None).unwrap();
|
||||
let text = page_text(&s, id);
|
||||
let all: Vec<usize> = (0..text.glyphs.len()).collect();
|
||||
let copy = s.get(id).unwrap().rich_copy(0, &text, &all).unwrap();
|
||||
let html = ©.html;
|
||||
assert!(!copy.styles_incomplete);
|
||||
assert!(
|
||||
html.starts_with("<p style=\"margin:0\"><span style=\"font-family:'Helvetica';font-size:24pt\"><strong>Title</strong></span></p>\n"),
|
||||
"{html}"
|
||||
);
|
||||
assert!(html.contains("font-size:12pt\">Body text "), "{html}");
|
||||
assert!(html.contains("font-size:12pt;color:#FF0000\">red</span>"), "{html}");
|
||||
assert!(html.contains("a<b & c"), "{html}");
|
||||
assert!(!html.contains("<b &"), "{html}");
|
||||
assert_eq!(copy.text.paragraphs.len(), html.matches("<p ").count());
|
||||
assert!(copy.text.paragraphs.len() >= 2, "{html}");
|
||||
// The heading and the body are separate paragraphs; the red word shares the body's.
|
||||
let body = copy.text.paragraphs.iter().find(|p| p.iter().any(|s| s.text.contains("Body"))).unwrap();
|
||||
assert!(body.iter().any(|s| s.text == "red" && s.style.color == [1.0, 0.0, 0.0]), "{body:?}");
|
||||
|
||||
// A part of the selection: only those glyphs.
|
||||
let part = s.get(id).unwrap().rich_copy(0, &text, &all[..5]).unwrap();
|
||||
assert_eq!(part.text.paragraphs.len(), 1);
|
||||
assert!(part.html.contains("<strong>Title</strong>"), "{}", part.html);
|
||||
// Nothing selected, and indices past the text: an empty copy, not a panic.
|
||||
let none = s.get(id).unwrap().rich_copy(0, &text, &[]).unwrap();
|
||||
assert!(none.html.is_empty() && none.text.paragraphs.is_empty());
|
||||
let past = s.get(id).unwrap().rich_copy(7, &text, &[usize::MAX, text.glyphs.len()]).unwrap();
|
||||
assert!(past.html.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn running_out_of_match_steps_copies_the_rest_unstyled() {
|
||||
let mut s = Session::new();
|
||||
let id = s.open("styled.pdf", None, Arc::new(styled_page()), None).unwrap();
|
||||
let text = page_text(&s, id);
|
||||
let all: Vec<usize> = (0..text.glyphs.len()).collect();
|
||||
let doc = s.get(id).unwrap();
|
||||
let full = doc.rich_copy(0, &text, &all).unwrap();
|
||||
// Enough for the first glyphs only: the text is all there, the rest has no style.
|
||||
let short = doc.rich_copy_within(0, &text, &all, 8).unwrap();
|
||||
assert!(short.styles_incomplete);
|
||||
let plain = |c: &super::RichCopy| c.text.paragraphs.iter().flatten().map(|s| s.text.clone()).collect::<String>();
|
||||
assert_eq!(plain(&short).replace([' ', '\n'], ""), plain(&full).replace([' ', '\n'], ""));
|
||||
let last = short.text.paragraphs.last().and_then(|p| p.last()).unwrap();
|
||||
assert_eq!(last.style, pdfcraft_export::ClipStyle::default(), "{last:?}");
|
||||
assert!(short.html.starts_with("<p style=\"margin:0\"><span style=\"font-family:'Helvetica';font-size:24pt\"><strong>T"), "{}", short.html);
|
||||
// No steps at all: nothing styled, still no panic.
|
||||
let none = doc.rich_copy_within(0, &text, &all, 0).unwrap();
|
||||
assert!(none.styles_incomplete && !none.html.contains("font-size"), "{}", none.html);
|
||||
// A page without blocks to match needs no steps.
|
||||
let page_less = doc.rich_copy_within(5, &text, &all, 0).unwrap();
|
||||
assert!(!page_less.styles_incomplete);
|
||||
}
|
||||
|
||||
fn copy_all(s: &Session, id: crate::DocId) -> super::RichCopy {
|
||||
let text = page_text(s, id);
|
||||
let all: Vec<usize> = (0..text.glyphs.len()).collect();
|
||||
s.get(id).unwrap().rich_copy(0, &text, &all).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_style_change_at_a_line_end_stays_in_its_paragraph() {
|
||||
let content = b"BT /F2 12 Tf 20 200 Td (plain then) Tj ET \
|
||||
BT /F1 12 Tf 85 200 Td (bold) Tj ET \
|
||||
BT /F2 12 Tf 20 186 Td (continues here) Tj ET \
|
||||
BT /F2 12 Tf 20 120 Td (Another paragraph) Tj ET";
|
||||
let mut s = Session::new();
|
||||
let id = s.open("wrap.pdf", None, Arc::new(page_with(content)), None).unwrap();
|
||||
let copy = copy_all(&s, id);
|
||||
let text = |p: &Vec<pdfcraft_export::ClipSpan>| p.iter().map(|s| s.text.as_str()).collect::<String>();
|
||||
let paragraphs: Vec<String> = copy.text.paragraphs.iter().map(text).collect();
|
||||
assert!(paragraphs.iter().any(|p| p.contains("bold") && p.contains("continues")), "{paragraphs:?}");
|
||||
assert!(paragraphs.iter().any(|p| p.contains("Another") && !p.contains("continues")), "a wide gap is still a paragraph: {paragraphs:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_style_change_into_the_next_column_starts_a_paragraph() {
|
||||
let content = b"BT /F2 12 Tf 20 200 Td (left top) Tj ET \
|
||||
BT /F2 12 Tf 20 186 Td (left end) Tj ET \
|
||||
BT /F1 12 Tf 170 200 Td (Right head) Tj ET \
|
||||
BT /F2 12 Tf 170 186 Td (right body) Tj ET";
|
||||
let mut s = Session::new();
|
||||
let id = s.open("columns.pdf", None, Arc::new(page_with(content)), None).unwrap();
|
||||
let copy = copy_all(&s, id);
|
||||
let text = |p: &Vec<pdfcraft_export::ClipSpan>| p.iter().map(|s| s.text.as_str()).collect::<String>();
|
||||
let paragraphs: Vec<String> = copy.text.paragraphs.iter().map(text).collect();
|
||||
assert!(paragraphs.iter().any(|p| p.contains("Right")), "{paragraphs:?}");
|
||||
assert!(!paragraphs.iter().any(|p| p.contains("left end") && p.contains("Right")), "{paragraphs:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_styled_word_inside_a_paragraph_keeps_its_style() {
|
||||
let content = b"BT /F2 12 Tf 20 200 Td (first row of the text) Tj ET \
|
||||
BT /F2 12 Tf 20 186 Td (second) Tj ET \
|
||||
BT /F1 12 Tf 62 186 Td (bold) Tj ET \
|
||||
BT /F2 12 Tf 92 186 Td (row) Tj ET";
|
||||
let mut s = Session::new();
|
||||
let id = s.open("nested.pdf", None, Arc::new(page_with(content)), None).unwrap();
|
||||
let copy = copy_all(&s, id);
|
||||
let spans: Vec<_> = copy.text.paragraphs.iter().flatten().collect();
|
||||
assert!(spans.iter().any(|s| s.text.contains("bold") && s.style.bold), "{spans:?}");
|
||||
assert!(spans.iter().any(|s| s.text.contains("second") && !s.style.bold), "{spans:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_capped_copy_is_marked_truncated() {
|
||||
let (plain, bold) = (ClipStyle::default(), ClipStyle { bold: true, ..ClipStyle::default() });
|
||||
let mut b = ClipBuilder::new();
|
||||
for k in 0..=pdfcraft_export::MAX_CLIP_SPANS {
|
||||
b.push("x", if k % 2 == 0 { &plain } else { &bold });
|
||||
}
|
||||
let copy = super::finish(b, false);
|
||||
assert!(copy.truncated && copy.text.truncated);
|
||||
let mut b = ClipBuilder::new();
|
||||
b.push("x", &plain);
|
||||
assert!(!super::finish(b, false).truncated);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn without_an_editor_the_styles_are_incomplete() {
|
||||
let mut s = Session::new();
|
||||
let id = s.open("styled.pdf", None, Arc::new(styled_page()), None).unwrap();
|
||||
let text = page_text(&s, id);
|
||||
let all: Vec<usize> = (0..text.glyphs.len()).collect();
|
||||
s.doc_mut(id).unwrap().editor = None;
|
||||
let copy = s.get(id).unwrap().rich_copy(0, &text, &all).unwrap();
|
||||
assert!(copy.styles_incomplete && !copy.html.contains("font-size"), "{}", copy.html);
|
||||
assert!(!copy.truncated);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn copy_with_formatting_is_refused_when_copying_is_withheld() {
|
||||
let mut cos = pdfcraft_cos::Document::open(Arc::new(styled_page())).unwrap();
|
||||
cos.set_encryption(&pdfcraft_cos::NewEncryption {
|
||||
algorithm: pdfcraft_cos::Algorithm::Aes256,
|
||||
user_password: "",
|
||||
owner_password: "owner",
|
||||
permissions: 0b0100, // print only
|
||||
encrypt_metadata: true,
|
||||
seed: [7; 32],
|
||||
})
|
||||
.unwrap();
|
||||
let bytes = Arc::new(pdfcraft_cos::write_full(&cos, &Default::default()).unwrap());
|
||||
let mut s = Session::new();
|
||||
let id = s.open("locked.pdf", None, bytes, None).unwrap();
|
||||
let text = pdfcraft_render::PageText { glyphs: Vec::new(), line_of: Vec::new(), space_before: Vec::new() };
|
||||
let err = s.get(id).unwrap().rich_copy(0, &text, &[]).unwrap_err();
|
||||
assert!(matches!(err, crate::EditError::NotPermitted(_)), "{err:?}");
|
||||
}
|
||||
}
|
||||
@@ -11,11 +11,11 @@ use crate::edit::{EditCtx, check_permission, run_edit};
|
||||
use crate::history::{Keys, MAX_UNDO, Scope, keys_after, scope_of, uses_scripts};
|
||||
use crate::{
|
||||
BookmarkPage, BookmarkRow, CombineSource, Combined, DataFormat, DocId, Document, Edit, EditError, Hidden, ImageResolution,
|
||||
LOW_RESOLUTION_PRINT_DPI, Label, ObjectKind, OptimizeReport, RecoverySnapshot, SignOptions, SourceKind, SplitPart, SummarySort, TrustStore,
|
||||
XFA_REMOVED_PREFIX, XFA_SCRIPTS_OFF, apply_layer_state, comment_list, comment_summary, decode_text, display_bytes, display_config, guard,
|
||||
info_fields, js, local_utc_offset, note_warnings, open_source, open_source_with, optimize, outline_rows, parse_ymd, print, print_raster,
|
||||
render_threads, scan_colours, set_default_layer_state, shown_under_redactions, signatures_of, source_kind, sync_xfa_state, undrawn_notices,
|
||||
use_layer_choices, writable, xfa, xfa_sync_datasets,
|
||||
LOW_RESOLUTION_PRINT_DPI, Label, ObjectKind, OptimizeReport, RecoverySnapshot, SignOptions, SourceKind, SplitPart, StatusCaptions, SummarySort,
|
||||
TrustStore, XFA_REMOVED_PREFIX, XFA_SCRIPTS_OFF, apply_layer_state, carry_verdict_marks, comment_list, comment_summary, decode_text,
|
||||
display_bytes, display_config, guard, info_fields, js, local_utc_offset, note_warnings, open_source, open_source_with, optimize, outline_rows,
|
||||
parse_ymd, print, print_raster, render_threads, scan_colours, set_default_layer_state, shown_under_redactions, signatures_of, source_kind,
|
||||
sync_xfa_state, undrawn_notices, use_layer_choices, writable, xfa, xfa_sync_datasets,
|
||||
};
|
||||
|
||||
mod editing;
|
||||
@@ -36,6 +36,8 @@ pub struct Session {
|
||||
utc_offset: Option<fn() -> i64>,
|
||||
/// Certificates trusted for signing (Acrobat: Trusted Certificates).
|
||||
pub(crate) trust: Arc<TrustStore>,
|
||||
/// The words signature status layers are drawn with, in the interface language.
|
||||
pub(crate) captions: Arc<StatusCaptions>,
|
||||
/// Preferences ▸ JavaScript ▸ Enable Acrobat JavaScript, inverted (on by default).
|
||||
pub(crate) js_off: bool,
|
||||
/// Preferences ▸ Date format, when not the default (see [`dates`]).
|
||||
|
||||
@@ -2,9 +2,9 @@
|
||||
use super::check_refresh_panic;
|
||||
use super::{
|
||||
Arc, DocId, Document, Edit, EditCtx, EditError, Label, MAX_UNDO, ObjectKind, OnceLock, RenderPool, SaveOptions, Scope, Session,
|
||||
XFA_REMOVED_PREFIX, XFA_SCRIPTS_OFF, check_permission, comment_list, display_bytes, display_config, guard, info_fields, inspect, js, keys_after,
|
||||
note_warnings, render_threads, run_edit, scan_colours, scope_of, shown_under_redactions, signatures_of, sync_xfa_state, undrawn_notices,
|
||||
uses_scripts, write_incremental, xfa, xfa_sync_datasets,
|
||||
XFA_REMOVED_PREFIX, XFA_SCRIPTS_OFF, carry_verdict_marks, check_permission, comment_list, display_bytes, display_config, guard, info_fields,
|
||||
inspect, js, keys_after, note_warnings, render_threads, run_edit, scan_colours, scope_of, shown_under_redactions, signatures_of, sync_xfa_state,
|
||||
undrawn_notices, uses_scripts, write_incremental, xfa, xfa_sync_datasets,
|
||||
};
|
||||
use crate::{EditNotice, MarkKind};
|
||||
|
||||
@@ -342,7 +342,14 @@ impl Session {
|
||||
#[cfg(test)]
|
||||
check_refresh_panic();
|
||||
if !doc.signatures.is_empty() {
|
||||
let signatures = signatures_of(&editor.cos, &bytes, &doc.trust, &doc.sig_cache);
|
||||
let mut signatures = signatures_of(&editor.cos, &bytes, &doc.trust, &doc.sig_cache);
|
||||
// The display copy is kept for a metadata edit, and so are its marks, unless the
|
||||
// edit changed a verdict (a certification can forbid it): the page then draws the
|
||||
// new one.
|
||||
if !carry_verdict_marks(&doc.signatures, &mut signatures) {
|
||||
doc.display = display_bytes(Some(editor), &bytes, &mut signatures, &doc.captions);
|
||||
doc.renderer = RenderPool::new(doc.display.clone(), render_threads(), display_config(&doc.config));
|
||||
}
|
||||
doc.signatures = Arc::new(signatures);
|
||||
}
|
||||
doc.bytes = bytes;
|
||||
@@ -386,8 +393,8 @@ impl Session {
|
||||
}
|
||||
doc.info.file_size = bytes.len();
|
||||
doc.form = form;
|
||||
let signatures = if doc.signatures.is_empty() { Vec::new() } else { signatures_of(&editor.cos, &bytes, &doc.trust, &doc.sig_cache) };
|
||||
doc.display = display_bytes(Some(editor), &bytes);
|
||||
let mut signatures = if doc.signatures.is_empty() { Vec::new() } else { signatures_of(&editor.cos, &bytes, &doc.trust, &doc.sig_cache) };
|
||||
doc.display = display_bytes(Some(editor), &bytes, &mut signatures, &doc.captions);
|
||||
doc.signatures = Arc::new(signatures);
|
||||
doc.renderer = RenderPool::new(doc.display.clone(), render_threads(), display_config(&doc.config));
|
||||
doc.bytes = bytes;
|
||||
@@ -444,8 +451,8 @@ impl Session {
|
||||
doc.marker_scan = OnceLock::new();
|
||||
}
|
||||
doc.info.file_size = bytes.len();
|
||||
let signatures = if doc.signatures.is_empty() { Vec::new() } else { signatures_of(&editor.cos, &bytes, &doc.trust, &doc.sig_cache) };
|
||||
doc.display = display_bytes(Some(editor), &bytes);
|
||||
let mut signatures = if doc.signatures.is_empty() { Vec::new() } else { signatures_of(&editor.cos, &bytes, &doc.trust, &doc.sig_cache) };
|
||||
doc.display = display_bytes(Some(editor), &bytes, &mut signatures, &doc.captions);
|
||||
doc.signatures = Arc::new(signatures);
|
||||
doc.renderer = RenderPool::new(doc.display.clone(), render_threads(), display_config(&doc.config));
|
||||
doc.bytes = bytes;
|
||||
@@ -467,6 +474,13 @@ impl Session {
|
||||
doc.renderer = RenderPool::new_inline(Arc::new(Vec::new()), doc.config.clone());
|
||||
doc.display = original.clone();
|
||||
doc.bytes = original;
|
||||
// The page shows the original's own artwork again, so nothing counts as drawn, even if
|
||||
// the refresh that follows fails.
|
||||
if doc.signatures.iter().any(|s| s.verdict_shown) {
|
||||
for sig in Arc::make_mut(&mut doc.signatures) {
|
||||
sig.verdict_shown = false;
|
||||
}
|
||||
}
|
||||
#[cfg(test)]
|
||||
check_refresh_panic();
|
||||
}
|
||||
@@ -528,8 +542,8 @@ impl Session {
|
||||
if invalidate_links {
|
||||
doc.links = OnceLock::new();
|
||||
}
|
||||
let signatures = signatures_of(&editor.cos, &bytes, &doc.trust, &doc.sig_cache);
|
||||
doc.display = display_bytes(Some(editor), &bytes);
|
||||
let mut signatures = signatures_of(&editor.cos, &bytes, &doc.trust, &doc.sig_cache);
|
||||
doc.display = display_bytes(Some(editor), &bytes, &mut signatures, &doc.captions);
|
||||
doc.signatures = Arc::new(signatures);
|
||||
doc.renderer = RenderPool::new(doc.display.clone(), render_threads(), display_config(&doc.config));
|
||||
doc.bytes = bytes;
|
||||
|
||||
@@ -170,6 +170,11 @@ impl Session {
|
||||
if !doc.config.layers.is_empty() {
|
||||
set_default_layer_state(&mut cos, &doc.info.layers);
|
||||
}
|
||||
// Signature states as the screen shows them, so not when its display copy could not be
|
||||
// written. This copy is only printed, never saved.
|
||||
if doc.signatures.iter().any(|s| s.verdict_shown) {
|
||||
let _ = pdfcraft_sign::show_status_layers(&mut cos, &mut doc.signatures.to_vec(), &doc.captions);
|
||||
}
|
||||
pdfcraft_print::impose(&cos, settings).map_err(|e| EditError::Print(e.to_string()))
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use super::{
|
||||
Arc, DocId, EditError, Keys, OpenError, RecoverySnapshot, RenderPool, SaveOptions, Session, SignOptions, TrustStore, display_bytes,
|
||||
display_config, guard, render_threads, signatures_of, writable, write_full, write_incremental, xfa_sync_datasets,
|
||||
Arc, DocId, Document, EditError, Keys, OpenError, RecoverySnapshot, RenderPool, SaveOptions, Session, SignOptions, StatusCaptions, TrustStore,
|
||||
display_bytes, display_config, guard, render_threads, signatures_of, writable, write_full, write_incremental, xfa_sync_datasets,
|
||||
};
|
||||
|
||||
impl Session {
|
||||
@@ -242,17 +242,55 @@ impl Session {
|
||||
pub fn set_trusted_certificates(&mut self, certs: Vec<pdfcraft_sign::Certificate>) {
|
||||
self.trust = Arc::new(TrustStore { certs });
|
||||
for doc in &mut self.docs {
|
||||
doc.trust = self.trust.clone();
|
||||
let Some(editor) = doc.editor.as_mut() else { continue };
|
||||
// Keep verdict refresh and renderer refresh together. Viewer caches are
|
||||
// invalidated by the UI trust path; trust alone changes no document artwork.
|
||||
let signatures = if doc.signatures.is_empty() { Vec::new() } else { signatures_of(&editor.cos, &doc.bytes, &doc.trust, &doc.sig_cache) };
|
||||
doc.display = display_bytes(Some(editor), &doc.bytes);
|
||||
doc.signatures = Arc::new(signatures);
|
||||
doc.renderer = RenderPool::new(doc.display.clone(), render_threads(), display_config(&doc.config));
|
||||
Self::revalidate(doc, self.trust.clone());
|
||||
}
|
||||
}
|
||||
|
||||
/// Validate `doc`'s signatures against `trust`, and rebuild its display copy and renderer
|
||||
/// with them: the verdicts choose what the copy draws. An unsigned document has nothing to
|
||||
/// validate and keeps both. Viewer caches are invalidated by the UI trust path.
|
||||
pub(crate) fn revalidate(doc: &mut Document, trust: Arc<TrustStore>) {
|
||||
doc.trust = trust;
|
||||
if doc.signatures.is_empty() {
|
||||
return;
|
||||
}
|
||||
let Some(editor) = doc.editor.as_mut() else { return };
|
||||
let mut signatures = signatures_of(&editor.cos, &doc.bytes, &doc.trust, &doc.sig_cache);
|
||||
doc.display = display_bytes(Some(editor), &doc.bytes, &mut signatures, &doc.captions);
|
||||
doc.signatures = Arc::new(signatures);
|
||||
doc.renderer = RenderPool::new(doc.display.clone(), render_threads(), display_config(&doc.config));
|
||||
}
|
||||
|
||||
/// The words the caption of a named-layer signature appearance is drawn with
|
||||
/// ([`pdfcraft_sign::show_status_layers`]), in the interface language. When they change, every
|
||||
/// open document's display copy and renderer are rebuilt; like trust, this is not an edit.
|
||||
/// Returns whether they changed.
|
||||
pub fn set_signature_captions(&mut self, captions: StatusCaptions) -> bool {
|
||||
if *self.captions == captions {
|
||||
return false;
|
||||
}
|
||||
self.captions = Arc::new(captions);
|
||||
for doc in &mut self.docs {
|
||||
Self::draw_captions(doc, self.captions.clone());
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// Draw `doc`'s signature status layers with `captions`: the display copy and renderer are
|
||||
/// rebuilt when it draws a signature's state (working file, generation and dirty unchanged).
|
||||
/// Whether a state is drawn does not depend on the words: a caption that can't be drawn in
|
||||
/// them is drawn in English.
|
||||
pub(crate) fn draw_captions(doc: &mut Document, captions: Arc<StatusCaptions>) {
|
||||
doc.captions = captions;
|
||||
if !doc.signatures.iter().any(|s| s.verdict_shown) {
|
||||
return;
|
||||
}
|
||||
let Some(editor) = doc.editor.as_mut() else { return };
|
||||
let signatures = Arc::make_mut(&mut doc.signatures);
|
||||
doc.display = display_bytes(Some(editor), &doc.bytes, signatures, &doc.captions);
|
||||
doc.renderer = RenderPool::new(doc.display.clone(), render_threads(), display_config(&doc.config));
|
||||
}
|
||||
|
||||
/// The signing time as a PDF date in local time with its offset (`D:…+02'00'`).
|
||||
pub fn signing_date(&self) -> String {
|
||||
let offset = self.local_offset();
|
||||
@@ -276,7 +314,7 @@ impl Session {
|
||||
opts.date = self.signing_date();
|
||||
}
|
||||
// A typed Password-field value is not signed into the file (#3926), as it isn't saved.
|
||||
let cos = writable(&editor.cos)?;
|
||||
let cos = drawn_for_first_signature(writable(&editor.cos)?);
|
||||
Ok(Arc::new(pdfcraft_sign::sign(&cos, id, &opts)?))
|
||||
}
|
||||
|
||||
@@ -294,7 +332,7 @@ impl Session {
|
||||
if opts.date.is_empty() {
|
||||
opts.date = self.signing_date();
|
||||
}
|
||||
let cos = writable(&editor.cos)?;
|
||||
let cos = drawn_for_first_signature(writable(&editor.cos)?);
|
||||
let signed = Arc::new(pdfcraft_sign::sign_with_timestamp(&cos, id, &opts, tsa)?);
|
||||
// Checked like a save before anyone writes it (#2166).
|
||||
self.check_save(doc, &signed)?;
|
||||
@@ -336,3 +374,78 @@ impl Session {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// `cos` with its form fields drawn, when the signature about to be made is the document's first
|
||||
/// and the form sets `/NeedAppearances` (#5939). That signature removes the flag, after which
|
||||
/// viewers show each field's stored appearance; a filled field whose stored appearance draws no
|
||||
/// text (an empty placeholder such as `/Tx BMC EMC`, or a stale look) would go blank. So every
|
||||
/// text and choice field is drawn from its value first, as the document is displayed
|
||||
/// ([`pdfcraft_forms::with_field_appearances`]), and the signature covers that look.
|
||||
///
|
||||
/// One exception: where PdfCraft's drawing would show a character as `?` (the field's font can't
|
||||
/// hold it) and the field's own appearance draws text, the field keeps its own appearance, which
|
||||
/// the program that filled it drew with a font that has the character. A field whose own
|
||||
/// appearance draws no text gets PdfCraft's drawing, `?` and all. Later signatures change
|
||||
/// nothing here: redrawing would count as a change to the earlier signatures.
|
||||
fn drawn_for_first_signature(cos: std::borrow::Cow<'_, pdfcraft_cos::Document>) -> std::borrow::Cow<'_, pdfcraft_cos::Document> {
|
||||
use pdfcraft_forms::FieldKind;
|
||||
if !pdfcraft_forms::need_appearances(&cos) || pdfcraft_sign::has_signatures(&cos) {
|
||||
return cos;
|
||||
}
|
||||
let Some(mut drawn) = pdfcraft_forms::with_field_appearances(&cos) else { return cos };
|
||||
for f in pdfcraft_forms::fields(&cos) {
|
||||
if !matches!(f.kind, FieldKind::Text | FieldKind::Combo | FieldKind::List) {
|
||||
continue;
|
||||
}
|
||||
for w in &f.widgets {
|
||||
let own = cos.get(w.obj).as_dict().filter(|d| draws_text(&cos, d)).and_then(|d| d.get(b"AP").cloned());
|
||||
// `.1`: the first character the drawing showed as `?`.
|
||||
if let Some(ap) = own
|
||||
&& pdfcraft_forms::appearance::field_appearance_drawn(&cos, &f, w, &f.value, true).1.is_some()
|
||||
{
|
||||
drawn.update_dict(w.obj, |d| d.set(b"AP".to_vec(), ap)).ok();
|
||||
}
|
||||
}
|
||||
}
|
||||
std::borrow::Cow::Owned(drawn)
|
||||
}
|
||||
|
||||
/// Whether the widget's normal appearance stream (`/AP /N`) shows text, itself or through the
|
||||
/// form XObjects it paints (a background-only one doesn't count).
|
||||
fn draws_text(cos: &pdfcraft_cos::Document, widget: &pdfcraft_cos::Dict) -> bool {
|
||||
let ap = widget.get(b"AP").map(|ap| cos.resolve(ap));
|
||||
let normal = ap.as_deref().and_then(|ap| ap.as_dict()).and_then(|ap| ap.get(b"N")).map(|n| cos.resolve(n));
|
||||
let Some(pdfcraft_cos::Object::Stream(s)) = normal.as_deref() else { return false };
|
||||
stream_draws_text(cos, s, &mut 16)
|
||||
}
|
||||
|
||||
/// Whether the form stream `s` shows text, following `Do` into its form XObjects. `budget` caps
|
||||
/// the streams opened along the way; running out (deep nesting, a cycle, many XObjects) counts
|
||||
/// as text, so the field keeps its own appearance as it would without the look inside.
|
||||
fn stream_draws_text(cos: &pdfcraft_cos::Document, s: &pdfcraft_cos::Stream, budget: &mut u8) -> bool {
|
||||
let Ok(data) = s.decoded() else { return false };
|
||||
let resources = s.dict.get(b"Resources").map(|r| cos.resolve(r));
|
||||
let xobjects = resources.as_deref().and_then(|r| r.as_dict()).and_then(|r| r.get(b"XObject")).map(|x| cos.resolve(x));
|
||||
for op in pdfcraft_content::ops(&data) {
|
||||
match op.op.as_slice() {
|
||||
b"Tj" | b"TJ" | b"'" | b"\"" => return true,
|
||||
b"Do" => {
|
||||
let name = op.operands.first().and_then(|n| n.as_name());
|
||||
let x = name.and_then(|n| xobjects.as_deref().and_then(|x| x.as_dict()).and_then(|x| x.get(n))).map(|x| cos.resolve(x));
|
||||
let Some(pdfcraft_cos::Object::Stream(f)) = x.as_deref() else { continue };
|
||||
if f.dict.name(b"Subtype") != Some(b"Form") {
|
||||
continue;
|
||||
}
|
||||
if *budget == 0 {
|
||||
return true;
|
||||
}
|
||||
*budget -= 1;
|
||||
if stream_draws_text(cos, f, budget) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
+758
-1
@@ -1,6 +1,6 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use super::document::is_placeholder_title;
|
||||
use super::document::{is_placeholder_title, write_display_copy};
|
||||
use super::edit::{EditCtx, check_permission, run_edit};
|
||||
use super::*;
|
||||
use pdfcraft_render::{Layer, LayerOp, OpenError, ReadingColors};
|
||||
@@ -2699,6 +2699,126 @@ fn a_signed_file_carries_no_password_field_value() {
|
||||
assert!(!appears_in_pdf(&signed, "*******"), "nor the typed length");
|
||||
}
|
||||
|
||||
/// A form with `/NeedAppearances true` whose filled fields have stored appearances that draw no
|
||||
/// text: `name` an empty placeholder, `town` one too with a value Helvetica can't hold (`ň`),
|
||||
/// `city` such a value with its own appearance that draws it (#5939), `street` no appearance at
|
||||
/// all, `river` a value Helvetica can't hold (`ř`) with an appearance that paints only a
|
||||
/// background form XObject, and `lake` such a value drawn by a form XObject its appearance
|
||||
/// paints.
|
||||
fn need_appearances_form() -> Vec<u8> {
|
||||
let stream =
|
||||
|content: &str| format!("<< /Type /XObject /Subtype /Form /BBox [0 0 160 20] /Length {} >>\nstream\n{content}\nendstream", content.len());
|
||||
let objs = [
|
||||
"<< /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [4 0 R 5 0 R 6 0 R 11 0 R 12 0 R 15 0 R] /NeedAppearances true /DA (/Helv 0 Tf 0 g) /DR << /Font << /Helv 7 0 R >> >> >> >>".to_string(),
|
||||
"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 200 300] >>".into(),
|
||||
"<< /Type /Page /Parent 2 0 R /Annots [4 0 R 5 0 R 6 0 R 11 0 R 12 0 R 15 0 R] >>".into(),
|
||||
"<< /Type /Annot /Subtype /Widget /FT /Tx /T (name) /V (Ada Lovelace) /Rect [20 250 180 270] /P 3 0 R /AP << /N 8 0 R >> >>".into(),
|
||||
"<< /Type /Annot /Subtype /Widget /FT /Tx /T (town) /V <FEFF0050006C007A00650148> /Rect [20 200 180 220] /P 3 0 R /AP << /N 9 0 R >> >>".into(),
|
||||
"<< /Type /Annot /Subtype /Widget /FT /Tx /T (city) /V <FEFF00420072006E006F00200159> /Rect [20 150 180 170] /P 3 0 R /AP << /N 10 0 R >> >>".into(),
|
||||
"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>".into(),
|
||||
stream("/Tx BMC EMC"),
|
||||
stream("/Tx BMC EMC"),
|
||||
stream("/Tx BMC BT /Helv 10 Tf 2 5 Td (Brno r) Tj ET EMC"),
|
||||
"<< /Type /Annot /Subtype /Widget /FT /Tx /T (street) /V (Main Street) /Rect [20 100 180 120] /P 3 0 R >>".into(),
|
||||
"<< /Type /Annot /Subtype /Widget /FT /Tx /T (river) /V <FEFF004F0159006500630068> /Rect [20 50 180 70] /P 3 0 R /AP << /N 13 0 R >> >>".into(),
|
||||
"<< /Type /XObject /Subtype /Form /BBox [0 0 160 20] /Resources << /XObject << /Bg 14 0 R >> >> /Length 10 >>\nstream\nq /Bg Do Q\nendstream".into(),
|
||||
stream("0.9 g 0 0 160 20 re f"),
|
||||
"<< /Type /Annot /Subtype /Widget /FT /Tx /T (lake) /V <FEFF004F0159006500630068> /Rect [20 20 180 40] /P 3 0 R /AP << /N 16 0 R >> >>".into(),
|
||||
"<< /Type /XObject /Subtype /Form /BBox [0 0 160 20] /Resources << /XObject << /Fm 17 0 R >> >> /Length 10 >>\nstream\nq /Fm Do Q\nendstream".into(),
|
||||
stream("BT /Helv 10 Tf 2 5 Td (Orech) Tj ET"),
|
||||
];
|
||||
let mut out = b"%PDF-1.7\n".to_vec();
|
||||
let mut offsets = Vec::new();
|
||||
for (i, o) in objs.iter().enumerate() {
|
||||
offsets.push(out.len());
|
||||
out.extend_from_slice(format!("{} 0 obj\n{o}\nendobj\n", i + 1).as_bytes());
|
||||
}
|
||||
let xref = out.len();
|
||||
out.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objs.len() + 1).as_bytes());
|
||||
for o in offsets {
|
||||
out.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes());
|
||||
}
|
||||
out.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objs.len() + 1).as_bytes());
|
||||
out
|
||||
}
|
||||
|
||||
/// The decoded normal appearance of the widget `num` in `doc`.
|
||||
fn normal_appearance(doc: &pdfcraft_cos::Document, num: u32) -> String {
|
||||
let widget = doc.get(pdfcraft_cos::ObjRef::new(num, 0));
|
||||
let ap = doc.resolve(widget.as_dict().unwrap().get(b"AP").unwrap());
|
||||
let n = doc.resolve(ap.as_dict().unwrap().get(b"N").unwrap());
|
||||
let pdfcraft_cos::Object::Stream(s) = &*n else { panic!("{n:?}") };
|
||||
String::from_utf8_lossy(&s.decoded().unwrap()).into_owned()
|
||||
}
|
||||
|
||||
/// #5939 review: the first signature removes `/NeedAppearances`, so the fields are drawn from
|
||||
/// their values first; without that, `name` and `town` would show their empty placeholders. A
|
||||
/// field whose own appearance draws its value keeps it rather than get a `?` for `ř`.
|
||||
#[test]
|
||||
fn the_first_signature_draws_the_fields_need_appearances_left_to_the_viewer() {
|
||||
let p12 = std::fs::read(concat!(env!("CARGO_MANIFEST_DIR"), "/../sign/tests/data/ec-p256.p12")).unwrap();
|
||||
let digital_id = sign::pkcs12::open(&p12, "test").unwrap();
|
||||
// After the test certificate's start date (2026-10-02).
|
||||
let mut s = Session::new().with_clock(|| 1_800_000_000);
|
||||
let id = s.open("form.pdf", None, Arc::new(need_appearances_form()), None).unwrap();
|
||||
let signed = s.sign(id, &digital_id, SignOptions { rect: None, ..SignOptions::default() }).unwrap();
|
||||
let doc = pdfcraft_cos::Document::open(signed.clone()).unwrap();
|
||||
assert!(!pdfcraft_forms::need_appearances(&doc));
|
||||
assert!(normal_appearance(&doc, 4).contains("(Ada Lovelace) Tj"), "{}", normal_appearance(&doc, 4));
|
||||
assert!(normal_appearance(&doc, 5).contains("(Plze?) Tj"), "{}", normal_appearance(&doc, 5));
|
||||
assert!(normal_appearance(&doc, 6).contains("(Brno r) Tj"), "{}", normal_appearance(&doc, 6));
|
||||
assert!(normal_appearance(&doc, 11).contains("(Main Street) Tj"), "{}", normal_appearance(&doc, 11));
|
||||
// Its own appearance only paints a background, so `river` gets the drawing, `?` and all.
|
||||
assert!(normal_appearance(&doc, 12).contains("(O?ech) Tj"), "{}", normal_appearance(&doc, 12));
|
||||
let city = |d: &pdfcraft_cos::Document| d.get(pdfcraft_cos::ObjRef::new(6, 0)).as_dict().unwrap().get(b"AP").cloned();
|
||||
let original = pdfcraft_cos::Document::open(Arc::new(need_appearances_form())).unwrap();
|
||||
assert_eq!(city(&doc), city(&original), "city keeps its own appearance");
|
||||
let lake = |d: &pdfcraft_cos::Document| d.get(pdfcraft_cos::ObjRef::new(15, 0)).as_dict().unwrap().get(b"AP").cloned();
|
||||
assert_eq!(lake(&doc), lake(&original), "lake keeps the appearance its form XObject draws");
|
||||
s.mark_signed(id, signed, None).unwrap();
|
||||
s.set_trusted_certificates(vec![digital_id.certificate.clone()]);
|
||||
let sig = &s.get(id).unwrap().signatures[0];
|
||||
assert_eq!((sig.signed, sig.status, sig.modification.clone()), (true, SignatureStatus::Valid, sign::Modification::None));
|
||||
}
|
||||
|
||||
/// A later signature draws nothing and leaves the flag: either would be a change to what the
|
||||
/// first signature covers.
|
||||
#[test]
|
||||
fn a_later_signature_leaves_need_appearances_forms_alone() {
|
||||
let p12 = std::fs::read(concat!(env!("CARGO_MANIFEST_DIR"), "/../sign/tests/data/ec-p256.p12")).unwrap();
|
||||
let digital_id = sign::pkcs12::open(&p12, "test").unwrap();
|
||||
let mut s = Session::new().with_clock(|| 1_800_000_000);
|
||||
let id = s.open("form.pdf", None, Arc::new(need_appearances_form()), None).unwrap();
|
||||
let first = s.sign(id, &digital_id, SignOptions { rect: None, ..SignOptions::default() }).unwrap();
|
||||
// The flag set again after the first signature, and `name` back to its empty placeholder.
|
||||
let mut cos = pdfcraft_cos::Document::open(first).unwrap();
|
||||
let root = cos.root().unwrap();
|
||||
cos.update_dict(root, |c| {
|
||||
if let Some(pdfcraft_cos::Object::Dict(af)) = c.get_mut(b"AcroForm") {
|
||||
af.set(b"NeedAppearances".to_vec(), pdfcraft_cos::Object::Bool(true));
|
||||
}
|
||||
})
|
||||
.unwrap();
|
||||
let placeholder = cos.add(pdfcraft_cos::Object::Stream(pdfcraft_cos::Stream::from_raw(Default::default(), b"/Tx BMC EMC".to_vec())));
|
||||
cos.update_dict(pdfcraft_cos::ObjRef::new(4, 0), |w| {
|
||||
let mut ap = pdfcraft_cos::Dict::new();
|
||||
ap.set(b"N".to_vec(), pdfcraft_cos::Object::Ref(placeholder));
|
||||
w.set(b"AP".to_vec(), pdfcraft_cos::Object::Dict(ap));
|
||||
})
|
||||
.unwrap();
|
||||
let flagged =
|
||||
Arc::new(pdfcraft_cos::write_incremental(&cos, &pdfcraft_cos::SaveOptions { object_streams: false, ..Default::default() }).unwrap());
|
||||
let id = s.open("flagged.pdf", None, flagged.clone(), None).unwrap();
|
||||
let second = s.sign(id, &digital_id, SignOptions { rect: None, ..SignOptions::default() }).unwrap();
|
||||
let (before, after) = (pdfcraft_cos::Document::open(flagged).unwrap(), pdfcraft_cos::Document::open(second.clone()).unwrap());
|
||||
assert!(pdfcraft_forms::need_appearances(&after));
|
||||
let widget = |d: &pdfcraft_cos::Document| d.get(pdfcraft_cos::ObjRef::new(4, 0));
|
||||
assert_eq!(widget(&after), widget(&before));
|
||||
assert_eq!(normal_appearance(&after, 4), "/Tx BMC EMC");
|
||||
s.mark_signed(id, second, None).unwrap();
|
||||
assert_eq!(s.get(id).unwrap().signatures.iter().filter(|x| x.signed).count(), 2);
|
||||
}
|
||||
|
||||
/// #3944: a value typed into an XFA `<passwordEdit/>` field stays in the open document (both the
|
||||
/// widget and the live XFA datasets, even across multiple edits and across Save + `mark_saved`),
|
||||
/// but is written to no file — neither on the widget nor in the XFA datasets stream.
|
||||
@@ -3116,6 +3236,26 @@ fn a_word_in_a_font_set_by_an_extgstate_is_redacted() {
|
||||
);
|
||||
}
|
||||
|
||||
/// A word drawn as outlines reads through its /ActualText. A mark over part of it applies (the
|
||||
/// outlines are clipped), and the name that would still read the whole word is gone from the page
|
||||
/// and from the saved file.
|
||||
#[test]
|
||||
fn a_word_drawn_as_outlines_is_redacted_with_its_name() {
|
||||
let mut s = Session::new().with_clock(|| 1_700_000_000);
|
||||
let page = one_line_page("", "/Span <</ActualText (SECRET42)>> BDC 20 150 m 140 150 l 140 170 l 20 170 l h f EMC");
|
||||
let id = s.open("outlines.pdf", None, Arc::new(page), None).unwrap();
|
||||
assert_eq!(page_texts(&s, id), ["SECRET42"]);
|
||||
let shape =
|
||||
Shape::Redact { quads: vec![pdfcraft_annot::rect_quad([10.0, 140.0, 90.0, 180.0])], overlay: String::new(), look: Default::default() };
|
||||
let mark =
|
||||
Edit::AddAnnotation(NewAnnotation { page: 0, style: Style::default_for(&shape), shape, contents: String::new(), author: "Ada".into() });
|
||||
s.apply(id, mark).unwrap();
|
||||
s.apply(id, Edit::ApplyRedactions { pages: None }).unwrap();
|
||||
assert_eq!(page_texts(&s, id), [""]);
|
||||
let saved = s.save_bytes(id).unwrap();
|
||||
assert!(!saved.windows(b"SECRET42".len()).any(|w| w == b"SECRET42"), "the name is not left in the file");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn redaction_marks_apply_for_good_and_undo() {
|
||||
let (mut s, id) = session_with(2);
|
||||
@@ -4182,6 +4322,7 @@ fn pasted_added_content_keeps_its_style_and_picture() {
|
||||
italic: true,
|
||||
size: 12.0,
|
||||
color: [0.8, 0.1, 0.2],
|
||||
ink: None,
|
||||
align: TextAlign::Center,
|
||||
aligns: Vec::new(),
|
||||
char_spacing: 0.0,
|
||||
@@ -4854,6 +4995,17 @@ fn bytes_has(haystack: &[u8], needle: &[u8]) -> bool {
|
||||
/// ranges and embed a detached CMS over them. The signed bytes keep the
|
||||
/// prepared appearance, so they validate exactly like a product signer's file.
|
||||
fn sign_prepared(doc: &mut pdfcraft_cos::Document, id: &sign::pkcs12::DigitalId, date: &str) -> Vec<u8> {
|
||||
sign_prepared_with(doc, id, date, |_| {})
|
||||
}
|
||||
|
||||
/// [`sign_prepared`], with `value` adding to the signature dictionary first (a certification's
|
||||
/// `/Reference`, say).
|
||||
fn sign_prepared_with(
|
||||
doc: &mut pdfcraft_cos::Document,
|
||||
id: &sign::pkcs12::DigitalId,
|
||||
date: &str,
|
||||
value: impl FnOnce(&mut pdfcraft_cos::Dict),
|
||||
) -> Vec<u8> {
|
||||
use pdfcraft_cos::{Dict, Object, PdfString};
|
||||
let reserve = 8192 + id.certificate.raw.len() + id.chain.iter().map(|c| c.raw.len()).sum::<usize>();
|
||||
let mut v = Dict::new();
|
||||
@@ -4863,6 +5015,7 @@ fn sign_prepared(doc: &mut pdfcraft_cos::Document, id: &sign::pkcs12::DigitalId,
|
||||
v.set(b"ByteRange".to_vec(), Object::Array([0].iter().chain(LAYERED_BR_MARK.iter()).map(|n| Object::Int(*n)).collect()));
|
||||
v.set(b"Contents".to_vec(), Object::String(PdfString { bytes: vec![0; reserve], hex: true }));
|
||||
v.set(b"M".to_vec(), PdfString::literal(date.as_bytes().to_vec()));
|
||||
value(&mut v);
|
||||
let sig = doc.add(Object::Dict(v));
|
||||
// The field by name, never by number: a full save (encryption, repairs) is
|
||||
// free to renumber objects, and a hardcoded reference would stamp the value
|
||||
@@ -5103,6 +5256,442 @@ fn real_layered_signatures_round_trip_behind_a_user_password() {
|
||||
assert_eq!(t.get(tid).unwrap().signatures[0].status, SignatureStatus::Valid);
|
||||
}
|
||||
|
||||
/// A one-page file whose unsigned signature field carries a named-layer appearance, in the
|
||||
/// geometry of a real one scaled by 4 (every word and drawing synthetic): /N draws /FRM, which
|
||||
/// draws n0–n4; n1 a yellow question mark and n4 "Signature Not Verified". Object numbers:
|
||||
/// 1 catalog, 2 pages, 3 page (400×300), 4 field, 5 AcroForm, 6 /N, 7 /FRM, 8–12 n0–n4,
|
||||
/// 13 Helvetica, 14 page content. `sign_prepared` adds the value.
|
||||
fn named_layer_signable_fixture() -> Vec<u8> {
|
||||
named_layer_signable_fixture_with("[0 0 100 100]")
|
||||
}
|
||||
|
||||
/// [`named_layer_signable_fixture`] with `n1_bbox` as its n1 layer's `/BBox`.
|
||||
fn named_layer_signable_fixture_with(n1_bbox: &str) -> Vec<u8> {
|
||||
fn form(bbox: &str, resources: &str, ops: &str) -> String {
|
||||
format!("<< /Type /XObject /Subtype /Form /BBox {bbox} /Resources {resources} /Length {} >>\nstream\n{ops}\nendstream", ops.len())
|
||||
}
|
||||
let helv = "<< /Font << /F1 13 0 R >> >>";
|
||||
let glyph = "1.08 0 0 1.08 46 6 cm";
|
||||
let objs = [
|
||||
"<< /Type /Catalog /Pages 2 0 R /AcroForm 5 0 R >>".to_string(),
|
||||
"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_string(),
|
||||
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 400 300] /Contents 14 0 R /Resources << /Font << /F1 13 0 R >> >> /Annots [4 0 R] >>"
|
||||
.to_string(),
|
||||
"<< /FT /Sig /T (Signature1) /Type /Annot /Subtype /Widget /F 132 /Rect [100 100 300 220] /P 3 0 R /AP << /N 6 0 R >> >>".to_string(),
|
||||
"<< /Fields [4 0 R] /SigFlags 3 >>".to_string(),
|
||||
form("[0 0 200 120]", "<< /XObject << /FRM 7 0 R >> >>", "q 1 0 0 1 0 0 cm /FRM Do Q"),
|
||||
form(
|
||||
"[0 0 200 120]",
|
||||
"<< /XObject << /n0 8 0 R /n1 9 0 R /n2 10 0 R /n3 11 0 R /n4 12 0 R >> >>",
|
||||
&format!("q /n0 Do Q q {glyph} /n1 Do Q q /n2 Do Q q {glyph} /n3 Do Q q /n4 Do Q"),
|
||||
),
|
||||
form("[0 0 100 100]", "<< >>", "% DSBlank"),
|
||||
form(
|
||||
n1_bbox,
|
||||
"<< >>",
|
||||
"q 1 0.84 0.2 rg 0.55 0.4 0 RG 3 w 30 72 m 30 88 42 98 56 98 c 72 98 84 88 84 74 c 66 50 l 58 28 l 44 28 l 44 48 l h B 44 6 14 14 re B Q",
|
||||
),
|
||||
form("[0 0 200 120]", helv, "BT /F1 13.6 Tf 1 0 0 1 8 62.4 Tm (Digitally signed by) Tj 1 0 0 1 8 48.8 Tm (Test Signer) Tj ET"),
|
||||
form("[0 0 100 100]", "<< >>", "% DSBlank"),
|
||||
form("[0 84 200 120]", helv, "BT /F1 18.8 Tf 1 0 0 1 8 93.2 Tm (Signature Not Verified) Tj ET"),
|
||||
"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>".to_string(),
|
||||
"<< /Length 44 >>\nstream\nBT /F1 14 Tf 20 270 Td (Contract text) Tj ET\nendstream".to_string(),
|
||||
];
|
||||
let mut out = b"%PDF-1.7\n".to_vec();
|
||||
let mut offs = Vec::new();
|
||||
for (k, o) in objs.iter().enumerate() {
|
||||
offs.push(out.len());
|
||||
out.extend_from_slice(format!("{} 0 obj\n{o}\nendobj\n", k + 1).as_bytes());
|
||||
}
|
||||
let start = out.len();
|
||||
out.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objs.len() + 1).as_bytes());
|
||||
for o in &offs {
|
||||
out.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes());
|
||||
}
|
||||
out.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{start}\n%%EOF", objs.len() + 1).as_bytes());
|
||||
out
|
||||
}
|
||||
|
||||
/// The status colours as the regenerated icons draw them.
|
||||
const VALID_GREEN: [u8; 3] = [0x2D, 0x9D, 0x78];
|
||||
const UNKNOWN_AMBER: [u8; 3] = [0xE6, 0x86, 0x19];
|
||||
const INVALID_RED: [u8; 3] = [0xD7, 0x37, 0x3F];
|
||||
|
||||
/// How many pixels of `rgba` are within 40 of `rgb` on every channel. A regenerated icon's
|
||||
/// stroke covers thousands at 1 px/pt; the fixture holds none of these colours otherwise.
|
||||
fn pixels_near(rgba: &[u8], rgb: [u8; 3]) -> usize {
|
||||
rgba.as_chunks::<4>().0.iter().filter(|p| p.iter().zip(rgb).all(|(a, b)| a.abs_diff(b) <= 40)).count()
|
||||
}
|
||||
|
||||
/// The displayed page at 1 px/pt.
|
||||
fn displayed_pixels(s: &Session, id: DocId) -> Vec<u8> {
|
||||
let doc = s.get(id).unwrap();
|
||||
let mut renderer = pdfcraft_render::PageRenderer::new(doc.display.clone(), doc.config.clone());
|
||||
let r = renderer.render(pdfcraft_render::RenderRequest { page: 0, scale: 1.0, ..Default::default() });
|
||||
assert!(r.error.is_none(), "{:?}", r.error);
|
||||
r.rgba.to_vec()
|
||||
}
|
||||
|
||||
fn exported_text(s: &Session, id: DocId) -> String {
|
||||
export::Exporter::new(s.get(id).unwrap()).text_of(&[0]).unwrap()
|
||||
}
|
||||
|
||||
/// The test identity and the certificate that makes it trusted.
|
||||
fn test_identity() -> (sign::pkcs12::DigitalId, sign::x509::Certificate) {
|
||||
let p12 = std::fs::read(concat!(env!("CARGO_MANIFEST_DIR"), "/../sign/tests/data/ec-p256.p12")).unwrap();
|
||||
let id = sign::pkcs12::open(&p12, "test").unwrap();
|
||||
let anchor = id.chain.first().cloned().unwrap_or_else(|| id.certificate.clone());
|
||||
(id, anchor)
|
||||
}
|
||||
|
||||
/// A named-layer signature through `Session`: the unknown state drawn on opening, the valid one
|
||||
/// once trusted, the signed bytes saved unchanged and still valid on reopening.
|
||||
fn check_named_layer_states(signed: Arc<Vec<u8>>, password: Option<&str>, anchor: &sign::x509::Certificate) {
|
||||
let mut s = Session::new().with_clock(|| 1_800_000_000);
|
||||
let id = s.open("named.pdf", None, signed.clone(), password).unwrap();
|
||||
let sig = &s.get(id).unwrap().signatures[0];
|
||||
assert_eq!(sig.status, SignatureStatus::Unknown, "untrusted at first");
|
||||
assert!(sig.verdict_shown, "the appearance shows the unknown state");
|
||||
let text = exported_text(&s, id);
|
||||
assert!(text.contains("Validity unknown") && !text.contains("Not Verified"), "{text:?}");
|
||||
let amber = pixels_near(&displayed_pixels(&s, id), UNKNOWN_AMBER);
|
||||
assert!(amber > 500, "{amber} amber pixels");
|
||||
s.set_trusted_certificates(vec![anchor.clone()]);
|
||||
let doc = s.get(id).unwrap();
|
||||
assert_eq!(doc.signatures[0].status, SignatureStatus::Valid);
|
||||
assert!(doc.signatures[0].verdict_shown);
|
||||
assert!(!doc.dirty, "trust is not an edit");
|
||||
let exported = exported_text(&s, id);
|
||||
assert!(exported.contains("Signature valid"), "{exported}");
|
||||
let page = displayed_pixels(&s, id);
|
||||
assert!(pixels_near(&page, VALID_GREEN) > 500 && pixels_near(&page, UNKNOWN_AMBER) < 50, "the page redraws for the new state");
|
||||
// Saving writes the working file, which never held the drawn state.
|
||||
let saved = s.save_bytes(id).unwrap();
|
||||
assert!(saved == signed, "an unchanged save is the signed file exactly");
|
||||
let mut t = Session::new().with_clock(|| 1_800_000_000);
|
||||
t.set_trusted_certificates(vec![anchor.clone()]);
|
||||
let tid = t.open("named-saved.pdf", None, saved, password).unwrap();
|
||||
let sig = &t.get(tid).unwrap().signatures[0];
|
||||
assert!(sig.status == SignatureStatus::Valid && sig.verdict_shown);
|
||||
let exported = exported_text(&t, tid);
|
||||
assert!(exported.contains("Signature valid"), "{exported}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn named_layer_signatures_show_their_state_through_trust_save_and_reopen() {
|
||||
let (id, anchor) = test_identity();
|
||||
let mut doc = pdfcraft_cos::Document::open(Arc::new(named_layer_signable_fixture())).unwrap();
|
||||
let signed = Arc::new(sign_prepared(&mut doc, &id, "D:20261002120000+01'00'"));
|
||||
check_named_layer_states(signed, None, &anchor);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn named_layer_signatures_round_trip_behind_a_user_password() {
|
||||
let (id, anchor) = test_identity();
|
||||
let mut doc = pdfcraft_cos::Document::open(Arc::new(named_layer_signable_fixture())).unwrap();
|
||||
doc.set_encryption(&pdfcraft_cos::NewEncryption {
|
||||
algorithm: pdfcraft_cos::Algorithm::Aes128,
|
||||
user_password: "user",
|
||||
owner_password: "owner",
|
||||
permissions: -1,
|
||||
encrypt_metadata: true,
|
||||
seed: [7; 32],
|
||||
})
|
||||
.unwrap();
|
||||
let encrypted = Arc::new(pdfcraft_cos::write_full(&doc, &pdfcraft_cos::SaveOptions::default()).unwrap());
|
||||
let mut doc = pdfcraft_cos::Document::open_with_password(encrypted, Some("user")).unwrap();
|
||||
let signed = Arc::new(sign_prepared(&mut doc, &id, "D:20261002120000+01'00'"));
|
||||
check_named_layer_states(signed, Some("user"), &anchor);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_tampered_named_layer_signature_shows_the_invalid_state() {
|
||||
let (id, _) = test_identity();
|
||||
let mut doc = pdfcraft_cos::Document::open(Arc::new(named_layer_signable_fixture())).unwrap();
|
||||
let mut signed = sign_prepared(&mut doc, &id, "D:20261002120000+01'00'");
|
||||
let at = signed.windows(15).position(|w| w == b"(Contract text)").unwrap();
|
||||
signed[at + 10] = b'X';
|
||||
let mut s = Session::new().with_clock(|| 1_800_000_000);
|
||||
let id = s.open("tampered.pdf", None, Arc::new(signed), None).unwrap();
|
||||
let sig = &s.get(id).unwrap().signatures[0];
|
||||
assert!(sig.status == SignatureStatus::Invalid && sig.verdict_shown);
|
||||
let exported = exported_text(&s, id);
|
||||
assert!(exported.contains("Signature invalid"), "{exported}");
|
||||
let red = pixels_near(&displayed_pixels(&s, id), INVALID_RED);
|
||||
assert!(red > 500, "{red} red pixels");
|
||||
}
|
||||
|
||||
/// A trusted named-layer signature.
|
||||
fn trusted_named_layer_session() -> (Session, DocId) {
|
||||
let (id, anchor) = test_identity();
|
||||
let mut doc = pdfcraft_cos::Document::open(Arc::new(named_layer_signable_fixture())).unwrap();
|
||||
let signed = Arc::new(sign_prepared(&mut doc, &id, "D:20261002120000+01'00'"));
|
||||
let mut s = Session::new().with_clock(|| 1_800_000_000);
|
||||
let vid = s.open("named.pdf", None, signed, None).unwrap();
|
||||
s.set_trusted_certificates(vec![anchor]);
|
||||
assert_eq!(s.get(vid).unwrap().signatures[0].status, SignatureStatus::Valid);
|
||||
(s, vid)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn named_layer_states_reach_exports_and_both_print_modes() {
|
||||
// What is drawn on the page is what leaves it.
|
||||
let (s, id) = trusted_named_layer_session();
|
||||
let doc = s.get(id).unwrap();
|
||||
let source = doc.export_source();
|
||||
let mut file = export::Exporter::from_source(export::ExportSource { bytes: doc.bytes.clone(), ..source.clone() });
|
||||
let mut shown = export::Exporter::from_source(source);
|
||||
assert_ne!(shown.png(0, 72.0).unwrap(), file.png(0, 72.0).unwrap(), "image export follows the display copy");
|
||||
let text = shown.text_of(&[0]).unwrap();
|
||||
assert!(text.contains("Signature valid") && !text.contains("Not Verified"), "{text:?}");
|
||||
let mut settings = print::Settings { pages: vec![0], paper: (400.0, 300.0), ..Default::default() };
|
||||
let (_, _, vector) = printed_pixels(s.print_pdf(id, &settings).unwrap());
|
||||
settings.raster = Some(print::Raster { dpi: 72.0, grayscale: false });
|
||||
let (_, _, raster) = printed_pixels(s.print_pdf(id, &settings).unwrap());
|
||||
for (mode, pixels) in [("vector", &vector), ("raster", &raster)] {
|
||||
assert!(pixels_near(pixels, VALID_GREEN) > 500, "{mode} print draws the valid state");
|
||||
assert!(pixels_near(pixels, [255, 214, 51]) < 50, "{mode} print drops the stored question mark");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn named_layers_show_beside_comments_that_need_appearances() {
|
||||
// A comment without an appearance makes the display copy for its own sake; the signature's
|
||||
// state is drawn into that same copy.
|
||||
use pdfcraft_cos::{ObjRef, Object};
|
||||
let (signer, anchor) = test_identity();
|
||||
let mut cos = pdfcraft_cos::Document::open(Arc::new(named_layer_signable_fixture())).unwrap();
|
||||
let square = cos.add(pdfcraft_cos::Lexer::new(b"<< /Type /Annot /Subtype /Square /Rect [10 10 60 60] /C [1 0 0] >>", 0).object().unwrap());
|
||||
cos.update_dict(ObjRef::new(3, 0), |page| page.set(b"Annots".to_vec(), Object::Array(vec![Object::Ref(ObjRef::new(4, 0)), Object::Ref(square)])))
|
||||
.unwrap();
|
||||
let signed = Arc::new(sign_prepared(&mut cos, &signer, "D:20261002120000+01'00'"));
|
||||
let mut s = Session::new().with_clock(|| 1_800_000_000);
|
||||
let id = s.open("commented.pdf", None, signed, None).unwrap();
|
||||
s.set_trusted_certificates(vec![anchor]);
|
||||
let shown = pdfcraft_cos::Document::open(s.get(id).unwrap().display.clone()).unwrap();
|
||||
assert!(shown.get(square).as_dict().is_some_and(|d| d.contains(b"AP")), "the comment's appearance is in the same copy");
|
||||
assert!(s.get(id).unwrap().signatures[0].verdict_shown);
|
||||
let green = pixels_near(&displayed_pixels(&s, id), VALID_GREEN);
|
||||
assert!(green > 500, "{green} green pixels");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn named_layers_show_beside_fields_the_viewer_draws() {
|
||||
// A text field without an appearance makes the display copy for its own sake; the
|
||||
// signature's state is drawn into that same copy.
|
||||
use pdfcraft_cos::{Lexer, ObjRef, Object};
|
||||
let (signer, anchor) = test_identity();
|
||||
let mut cos = pdfcraft_cos::Document::open(Arc::new(named_layer_signable_fixture())).unwrap();
|
||||
let field = cos.add(
|
||||
Lexer::new(
|
||||
b"<< /Type /Annot /Subtype /Widget /FT /Tx /T (name) /V (Test Signer) /DA (/F1 12 Tf 0 g) /Rect [20 20 380 40] /F 4 /P 3 0 R >>",
|
||||
0,
|
||||
)
|
||||
.object()
|
||||
.unwrap(),
|
||||
);
|
||||
let both = Object::Array(vec![Object::Ref(ObjRef::new(4, 0)), Object::Ref(field)]);
|
||||
cos.update_dict(ObjRef::new(3, 0), |page| page.set(b"Annots".to_vec(), both.clone())).unwrap();
|
||||
let resources = Lexer::new(b"<< /Font << /F1 13 0 R >> >>", 0).object().unwrap();
|
||||
cos.update_dict(ObjRef::new(5, 0), |form| {
|
||||
form.set(b"Fields".to_vec(), both);
|
||||
form.set(b"DR".to_vec(), resources);
|
||||
})
|
||||
.unwrap();
|
||||
let signed = Arc::new(sign_prepared(&mut cos, &signer, "D:20261002120000+01'00'"));
|
||||
let mut s = Session::new().with_clock(|| 1_800_000_000);
|
||||
let id = s.open("filled.pdf", None, signed, None).unwrap();
|
||||
s.set_trusted_certificates(vec![anchor]);
|
||||
let shown = pdfcraft_cos::Document::open(s.get(id).unwrap().display.clone()).unwrap();
|
||||
assert!(shown.get(field).as_dict().is_some_and(|d| d.contains(b"AP")), "the field's appearance is in the same copy");
|
||||
assert!(s.get(id).unwrap().signatures[0].verdict_shown);
|
||||
let green = pixels_near(&displayed_pixels(&s, id), VALID_GREEN);
|
||||
assert!(green > 500, "{green} green pixels");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_metadata_edit_keeps_the_regenerated_state() {
|
||||
let (mut s, id) = trusted_named_layer_session();
|
||||
s.apply(id, Edit::SetInfo { key: "Title".into(), value: "Contract".into() }).unwrap();
|
||||
let doc = s.get(id).unwrap();
|
||||
assert!(doc.signatures[0].verdict_shown, "the page still draws the state");
|
||||
let exported = exported_text(&s, id);
|
||||
assert!(exported.contains("Signature valid"), "{exported}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_metadata_edit_that_changes_a_verdict_redraws_it() {
|
||||
// A certification that allows no changes: setting the title invalidates the signature, and
|
||||
// the page has to say so rather than keep the valid state it drew.
|
||||
let (signer, anchor) = test_identity();
|
||||
let mut cos = pdfcraft_cos::Document::open(Arc::new(named_layer_signable_fixture())).unwrap();
|
||||
let signed = sign_prepared_with(&mut cos, &signer, "D:20261002120000+01'00'", |v| {
|
||||
let reference =
|
||||
pdfcraft_cos::Lexer::new(b"[<< /Type /SigRef /TransformMethod /DocMDP /TransformParams << /Type /TransformParams /P 1 /V /1.2 >> >>]", 0)
|
||||
.object()
|
||||
.unwrap();
|
||||
v.set(b"Reference".to_vec(), reference);
|
||||
});
|
||||
let mut s = Session::new().with_clock(|| 1_800_000_000);
|
||||
let id = s.open("certified.pdf", None, Arc::new(signed), None).unwrap();
|
||||
s.set_trusted_certificates(vec![anchor]);
|
||||
assert_eq!(s.get(id).unwrap().signatures[0].status, SignatureStatus::Valid);
|
||||
s.apply(id, Edit::SetInfo { key: "Title".into(), value: "Changed".into() }).unwrap();
|
||||
let doc = s.get(id).unwrap();
|
||||
assert_eq!(doc.signatures[0].status, SignatureStatus::Invalid);
|
||||
assert!(doc.signatures[0].verdict_shown);
|
||||
let exported = exported_text(&s, id);
|
||||
assert!(exported.contains("Signature invalid"), "{exported}");
|
||||
let red = pixels_near(&displayed_pixels(&s, id), INVALID_RED);
|
||||
assert!(red > 500, "{red} red pixels");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn verdict_marks_carry_over_only_while_every_verdict_is_unchanged() {
|
||||
let (s, id) = trusted_named_layer_session();
|
||||
let previous = s.get(id).unwrap().signatures.to_vec();
|
||||
assert!(previous[0].verdict_shown);
|
||||
let mut same = previous.clone();
|
||||
same[0].verdict_shown = false;
|
||||
assert!(carry_verdict_marks(&previous, &mut same) && same[0].verdict_shown);
|
||||
let mut changed = previous.clone();
|
||||
(changed[0].verdict_shown, changed[0].status) = (false, SignatureStatus::Invalid);
|
||||
assert!(!carry_verdict_marks(&previous, &mut changed) && !changed[0].verdict_shown);
|
||||
let mut later = previous.clone();
|
||||
(later[0].verdict_shown, later[0].revision) = (false, previous[0].revision + 1);
|
||||
assert!(!carry_verdict_marks(&previous, &mut later) && !later[0].verdict_shown);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn releasing_the_working_file_drops_the_marks() {
|
||||
// The page shows the original's own artwork until the refresh finishes.
|
||||
let (mut s, id) = trusted_named_layer_session();
|
||||
let doc = s.docs.iter_mut().find(|d| d.id == id).unwrap();
|
||||
assert!(doc.signatures[0].verdict_shown);
|
||||
Session::release_working(doc);
|
||||
assert!(!doc.signatures[0].verdict_shown);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn background_open_uses_the_current_trust_at_commit() {
|
||||
let (signer, anchor) = test_identity();
|
||||
let mut cos = pdfcraft_cos::Document::open(Arc::new(named_layer_signable_fixture())).unwrap();
|
||||
let signed = Arc::new(sign_prepared(&mut cos, &signer, "D:20261002120000+01'00'"));
|
||||
let mut s = Session::new().with_clock(|| 1_800_000_000);
|
||||
let prepared = s.open_context().prepare_open("background.pdf", None, signed, None).unwrap();
|
||||
s.set_trusted_certificates(vec![anchor]);
|
||||
let id = s.commit_open(prepared);
|
||||
let sig = &s.get(id).unwrap().signatures[0];
|
||||
assert!(sig.status == SignatureStatus::Valid && sig.verdict_shown);
|
||||
let exported = exported_text(&s, id);
|
||||
assert!(exported.contains("Signature valid"), "{exported}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn background_open_uses_the_current_trust_and_language_at_commit() {
|
||||
// Both changed while the document was prepared: the state and its words are both the new ones.
|
||||
let (signer, anchor) = test_identity();
|
||||
let mut cos = pdfcraft_cos::Document::open(Arc::new(named_layer_signable_fixture())).unwrap();
|
||||
let signed = Arc::new(sign_prepared(&mut cos, &signer, "D:20261002120000+01'00'"));
|
||||
let mut s = Session::new().with_clock(|| 1_800_000_000);
|
||||
let prepared = s.open_context().prepare_open("background.pdf", None, signed, None).unwrap();
|
||||
s.set_trusted_certificates(vec![anchor]);
|
||||
s.set_signature_captions(StatusCaptions {
|
||||
valid: "Signatur gültig".into(),
|
||||
unknown: "Gültigkeit unbekannt".into(),
|
||||
invalid: "Signatur ungültig".into(),
|
||||
});
|
||||
let id = s.commit_open(prepared);
|
||||
assert_eq!(s.get(id).unwrap().signatures[0].status, SignatureStatus::Valid);
|
||||
let exported = exported_text(&s, id);
|
||||
assert!(exported.contains("Signatur gültig"), "{exported}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn printing_draws_signature_states_only_where_the_screen_does() {
|
||||
let (mut s, id) = trusted_named_layer_session();
|
||||
let settings = print::Settings { pages: vec![0], paper: (400.0, 300.0), ..Default::default() };
|
||||
// The screen falls back to the file's artwork when its display copy cannot be written, and
|
||||
// takes the marks with it; print follows.
|
||||
let doc = s.docs.iter_mut().find(|d| d.id == id).unwrap();
|
||||
let mut cleared = doc.signatures.to_vec();
|
||||
cleared[0].verdict_shown = false;
|
||||
doc.signatures = Arc::new(cleared);
|
||||
let (_, _, printed) = printed_pixels(s.print_pdf(id, &settings).unwrap());
|
||||
let green = pixels_near(&printed, VALID_GREEN);
|
||||
assert!(green < 50, "{green} green pixels");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_failed_display_write_drops_the_marks() {
|
||||
let (mut s, id) = trusted_named_layer_session();
|
||||
let doc = s.docs.iter_mut().find(|d| d.id == id).unwrap();
|
||||
let mut signatures = doc.signatures.to_vec();
|
||||
assert!(signatures[0].verdict_shown);
|
||||
// A stream-limited document is read-only: the writer refuses it.
|
||||
let unwritable = pdfcraft_cos::Document::open_with_stream_limit(doc.bytes.clone(), None, 1).unwrap();
|
||||
let editor = doc.editor.as_mut().unwrap();
|
||||
let shown = write_display_copy(editor, &doc.bytes, &unwritable, &mut signatures);
|
||||
assert!(Arc::ptr_eq(&shown, &doc.bytes), "the page falls back to the file's own artwork");
|
||||
assert!(!signatures[0].verdict_shown, "so nothing counts as drawn");
|
||||
// Logged once, however many refreshes lose the copy again.
|
||||
write_display_copy(editor, &doc.bytes, &unwritable, &mut signatures);
|
||||
let logged = editor.cos.repair_log().iter().filter(|l| l.contains("the display copy could not be written")).count();
|
||||
assert_eq!(logged, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn background_open_uses_the_current_caption_language_at_commit() {
|
||||
let (mut s, id) = trusted_named_layer_session();
|
||||
let bytes = s.get(id).unwrap().bytes.clone();
|
||||
let prepared = s.open_context().prepare_open("background.pdf", None, bytes, None).unwrap();
|
||||
s.set_signature_captions(StatusCaptions {
|
||||
valid: "Signatur gültig".into(),
|
||||
unknown: "Gültigkeit unbekannt".into(),
|
||||
invalid: "Signatur ungültig".into(),
|
||||
});
|
||||
let later = s.commit_open(prepared);
|
||||
let exported = exported_text(&s, later);
|
||||
assert!(exported.contains("Signatur gültig"), "{exported}");
|
||||
assert!(s.get(later).unwrap().signatures[0].verdict_shown);
|
||||
assert!(!s.get(later).unwrap().dirty);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn caption_language_follows_the_session_captions() {
|
||||
let (mut s, id) = trusted_named_layer_session();
|
||||
let generation = s.get(id).unwrap().generation;
|
||||
let german = StatusCaptions { valid: "Signatur gültig".into(), unknown: "Gültigkeit unbekannt".into(), invalid: "Signatur ungültig".into() };
|
||||
s.set_signature_captions(german);
|
||||
let doc = s.get(id).unwrap();
|
||||
assert!(!doc.dirty && doc.generation == generation, "captions are not an edit");
|
||||
assert!(doc.signatures[0].verdict_shown);
|
||||
let exported = exported_text(&s, id);
|
||||
assert!(exported.contains("Signatur gültig"), "{exported}");
|
||||
// Documents opened later draw with them too.
|
||||
let (signer, _) = test_identity();
|
||||
let mut cos = pdfcraft_cos::Document::open(Arc::new(named_layer_signable_fixture())).unwrap();
|
||||
let later = s.open("later.pdf", None, Arc::new(sign_prepared(&mut cos, &signer, "D:20261002120000+01'00'")), None).unwrap();
|
||||
let exported = exported_text(&s, later);
|
||||
assert!(exported.contains("Signatur gültig"), "{exported}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn non_win_ansi_captions_embed_inter_in_the_display_copy_only() {
|
||||
// Words WinAnsi cannot encode are drawn in Inter, embedded into the display copy only.
|
||||
let (mut s, id) = trusted_named_layer_session();
|
||||
let russian = StatusCaptions {
|
||||
valid: "Подпись действительна".into(),
|
||||
unknown: "Действительность неизвестна".into(),
|
||||
invalid: "Подпись недействительна".into(),
|
||||
};
|
||||
s.set_signature_captions(russian);
|
||||
let exported = exported_text(&s, id);
|
||||
assert!(exported.contains("Подпись действительна"), "{exported}");
|
||||
let doc = s.get(id).unwrap();
|
||||
assert!(bytes_has(&doc.display, b"/BaseFont /Inter") && !bytes_has(&doc.bytes, b"/BaseFont /Inter"), "Inter goes into the display copy only");
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "timing probe"]
|
||||
fn probe_edit_latency_on_a_large_signed_document() {
|
||||
@@ -7653,6 +8242,37 @@ fn free_text_without_appearance() -> Arc<Vec<u8>> {
|
||||
Arc::new(bytes)
|
||||
}
|
||||
|
||||
/// The CLI renders what the app shows with no trusted certificates: a named-layer signature in
|
||||
/// the state it has then (validity unknown), not the "not verified" its file stores. The source
|
||||
/// is not changed.
|
||||
#[test]
|
||||
fn cli_display_draws_signature_states_as_the_app_does_without_trust() {
|
||||
let (id, _) = test_identity();
|
||||
let mut doc = pdfcraft_cos::Document::open(Arc::new(named_layer_signable_fixture())).unwrap();
|
||||
let signed = Arc::new(sign_prepared(&mut doc, &id, "D:20261002120000+01'00'"));
|
||||
let display = display_bytes_for(signed.clone(), None);
|
||||
assert!(!Arc::ptr_eq(&display, &signed), "the state is drawn into a copy");
|
||||
let mut renderer = pdfcraft_render::PageRenderer::new(display, pdfcraft_render::RenderConfig::default());
|
||||
let page = renderer.render(pdfcraft_render::RenderRequest { page: 0, scale: 1.0, ..Default::default() });
|
||||
assert!(pixels_near(&page.rgba, UNKNOWN_AMBER) > 500, "the unknown state is drawn");
|
||||
assert!(pixels_near(&page.rgba, [255, 214, 51]) < 50, "the stored question mark is not");
|
||||
}
|
||||
|
||||
/// A layer recognised but too small to draw an icon in (a side so small the icon's scale rounds to
|
||||
/// zero) changes nothing, so the CLI renders the source, as the app does.
|
||||
#[test]
|
||||
fn cli_display_makes_no_copy_when_no_state_could_be_drawn() {
|
||||
let (id, _) = test_identity();
|
||||
let n1 = format!("[0 0 0.{}6 100]", "0".repeat(322));
|
||||
let mut doc = pdfcraft_cos::Document::open(Arc::new(named_layer_signable_fixture_with(&n1))).unwrap();
|
||||
let signed = Arc::new(sign_prepared(&mut doc, &id, "D:20261002120000+01'00'"));
|
||||
let cos = pdfcraft_cos::Document::open(signed.clone()).unwrap();
|
||||
let trust = pdfcraft_sign::TrustStore::default();
|
||||
let signatures = crate::doc_state::signatures_of(&cos, &signed, &trust, &pdfcraft_sign::DigestCache::default());
|
||||
assert!(pdfcraft_sign::has_status_layers(&cos, &signatures), "the layers are recognised");
|
||||
assert!(Arc::ptr_eq(&display_bytes_for(signed.clone(), None), &signed), "nothing was drawn, so there is no copy");
|
||||
}
|
||||
|
||||
/// #2371: a comment without an appearance stream is displayed by the app, so the CLI's page image
|
||||
/// must show it too. The helper's copy is for rendering only; documents that need no copy, and
|
||||
/// files it can't display, keep exactly the original source bytes.
|
||||
@@ -8112,6 +8732,7 @@ fn content_edit_keeps_pages_annotations_fields_and_links() {
|
||||
italic: false,
|
||||
size: 12.0,
|
||||
color: [0.0, 0.0, 0.0],
|
||||
ink: None,
|
||||
align: TextAlign::Left,
|
||||
aligns: Vec::new(),
|
||||
char_spacing: 0.0,
|
||||
@@ -8153,6 +8774,7 @@ fn content_refresh_lists_match_the_storages_an_edit_touches() {
|
||||
italic: false,
|
||||
size: 12.0,
|
||||
color: [0.0, 0.0, 0.0],
|
||||
ink: None,
|
||||
align: TextAlign::Left,
|
||||
aligns: Vec::new(),
|
||||
char_spacing: 0.0,
|
||||
@@ -8511,6 +9133,141 @@ fn a_signed_document_rebuilt_from_object_headers_refuses_edits() {
|
||||
assert!(!s.get(id).unwrap().dirty);
|
||||
}
|
||||
|
||||
/// A one-page document whose only signature field is signed and named with `len` bytes. The
|
||||
/// signature field walk reads names of up to 4096 bytes and passes longer ones over.
|
||||
fn signed_field_named(len: usize) -> Vec<u8> {
|
||||
pdf_of(&[
|
||||
"<< /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [4 0 R] >> >>".to_string(),
|
||||
"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".into(),
|
||||
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 300] /Annots [4 0 R] >>".into(),
|
||||
format!("<< /Type /Annot /Subtype /Widget /FT /Sig /T ({}) /V 5 0 R /Rect [20 20 180 60] /P 3 0 R >>", "a".repeat(len)),
|
||||
"<< /Type /Sig /Filter /Adobe.PPKLite /SubFilter /adbe.pkcs7.detached /ByteRange [0 1 2 1] /Contents <00> >>".into(),
|
||||
])
|
||||
}
|
||||
|
||||
/// A PDF of `objs`, numbered from 1, with a cross-reference table.
|
||||
fn pdf_of(objs: &[String]) -> Vec<u8> {
|
||||
let mut out = b"%PDF-1.7\n".to_vec();
|
||||
let mut offsets = Vec::new();
|
||||
for (i, o) in objs.iter().enumerate() {
|
||||
offsets.push(out.len());
|
||||
out.extend_from_slice(format!("{} 0 obj\n{o}\nendobj\n", i + 1).as_bytes());
|
||||
}
|
||||
let xref = out.len();
|
||||
out.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objs.len() + 1).as_bytes());
|
||||
for o in offsets {
|
||||
out.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes());
|
||||
}
|
||||
out.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objs.len() + 1).as_bytes());
|
||||
out
|
||||
}
|
||||
|
||||
fn open_signed_field_named(len: usize) -> (Session, DocId) {
|
||||
let mut s = Session::new();
|
||||
let id = s.open("form.pdf", None, Arc::new(signed_field_named(len)), None).expect("opens");
|
||||
(s, id)
|
||||
}
|
||||
|
||||
/// The cap's boundary as the engine meets it: a 4096-byte name is read, and its signature blocks a
|
||||
/// full rewrite.
|
||||
#[test]
|
||||
fn a_signature_named_at_the_cap_is_listed_and_blocks_a_full_rewrite() {
|
||||
let (s, id) = open_signed_field_named(4096);
|
||||
let doc = s.get(id).unwrap();
|
||||
let listed: Vec<_> = doc.signatures.iter().map(|r| (r.field.len(), r.signed)).collect();
|
||||
assert_eq!(listed, [(4096, true)], "the field is read, and no row stands for unread ones");
|
||||
assert_eq!(s.save_full_bytes(id).unwrap_err(), EditError::Signed);
|
||||
}
|
||||
|
||||
/// One byte past the cap the field goes unread: the list says so, and a full rewrite is still
|
||||
/// refused.
|
||||
#[test]
|
||||
fn a_signature_named_one_byte_past_the_cap_still_blocks_a_full_rewrite() {
|
||||
let (s, id) = open_signed_field_named(4097);
|
||||
let doc = s.get(id).unwrap();
|
||||
let unread = doc.signatures.iter().find(|r| r.field == "UnreadFields");
|
||||
let said = unread.map(|r| (r.signed, r.status, r.details.first().is_some_and(|d| d.message.starts_with("This form has too many fields"))));
|
||||
assert_eq!(said, Some((true, SignatureStatus::Unknown, true)), "{:?}", doc.signatures);
|
||||
assert_eq!(s.save_full_bytes(id).unwrap_err(), EditError::Signed);
|
||||
}
|
||||
|
||||
/// A signed field behind a kid with no /T: one merged with its widget under a named field that
|
||||
/// isn't a signature field (the walk can't list it, so its row is the unread one), and one under a
|
||||
/// node with no /T (listed by its full name). Either way the document is signed, and neither a full
|
||||
/// save nor Optimize may rewrite it.
|
||||
#[test]
|
||||
fn signed_fields_behind_kids_without_a_name_block_a_full_rewrite() {
|
||||
let page = |annot: u32| format!("<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 300] /Annots [{annot} 0 R] >>");
|
||||
let head = |annot: u32| {
|
||||
vec![
|
||||
"<< /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [4 0 R] >> >>".to_string(),
|
||||
"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".into(),
|
||||
page(annot),
|
||||
]
|
||||
};
|
||||
let sig = "<< /Type /Sig /SubFilter /ETSI.CAdES.detached /ByteRange [0 1 2 1] /Contents <00> >>".to_string();
|
||||
let mut merged = head(5);
|
||||
merged.extend([
|
||||
"<< /T (parent) /Kids [5 0 R] >>".to_string(),
|
||||
"<< /Type /Annot /Subtype /Widget /FT /Sig /V 6 0 R /Parent 4 0 R /Rect [20 20 180 60] /P 3 0 R >>".into(),
|
||||
sig.clone(),
|
||||
]);
|
||||
let mut nested = head(6);
|
||||
nested.extend([
|
||||
"<< /T (p) /Kids [5 0 R] >>".to_string(),
|
||||
"<< /Kids [6 0 R] /Parent 4 0 R >>".into(),
|
||||
"<< /Type /Annot /Subtype /Widget /FT /Sig /T (s) /V 7 0 R /Parent 5 0 R /Rect [20 20 180 60] /P 3 0 R >>".into(),
|
||||
sig,
|
||||
]);
|
||||
for (shape, objs, row) in [("merged", merged, "UnreadFields"), ("nested", nested, "p.s")] {
|
||||
let mut s = Session::new();
|
||||
let id = s.open("form.pdf", None, Arc::new(pdf_of(&objs)), None).expect("opens");
|
||||
let doc = s.get(id).unwrap();
|
||||
assert!(doc.is_signed() && doc.signatures.iter().any(|r| r.field == row), "{shape}: {:?}", doc.signatures);
|
||||
assert_eq!(s.save_full_bytes(id).unwrap_err(), EditError::Signed, "{shape}");
|
||||
assert!(matches!(s.optimize_job(id, &optimize::Settings::default(), &[]), Err(EditError::Signed)), "{shape}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The walk stops short of a signed field, so a signature may go unlisted; the document still
|
||||
/// counts as signed, and each guard against rewriting a signed document holds.
|
||||
#[test]
|
||||
fn a_signature_the_field_walk_passes_over_still_counts_as_signed() {
|
||||
let (s, id) = open_signed_field_named(64 << 10);
|
||||
let doc = s.get(id).unwrap();
|
||||
assert!(doc.is_signed(), "{:?}", doc.signatures);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_full_rewrite_is_refused_when_the_field_walk_passes_a_signature_over() {
|
||||
let (s, id) = open_signed_field_named(64 << 10);
|
||||
assert_eq!(s.save_full_bytes(id).unwrap_err(), EditError::Signed);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn optimizing_is_refused_when_the_field_walk_passes_a_signature_over() {
|
||||
let (s, id) = open_signed_field_named(64 << 10);
|
||||
assert!(matches!(s.optimize_job(id, &optimize::Settings::default(), &[]), Err(EditError::Signed)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rewriting_edit_is_refused_when_the_field_walk_passes_a_signature_over() {
|
||||
let (mut s, id) = open_signed_field_named(64 << 10);
|
||||
assert!(matches!(s.apply(id, Edit::Sanitize), Err(EditError::SignedRewrite(_))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_action_appends_to_a_file_whose_field_walk_passes_a_signature_over() {
|
||||
let bytes = Arc::new(signed_field_named(64 << 10));
|
||||
let steps = vec![actions::Step::from_id("set_title", "Checked").unwrap()];
|
||||
let title = actions::Action { name: "Title".into(), description: String::new(), steps, builtin: false };
|
||||
let r = actions::run_on(&title, "form.pdf", bytes.clone(), |_, _| {}).unwrap();
|
||||
assert!(r.bytes.starts_with(&bytes[..]), "the action rewrote the file instead of appending to it");
|
||||
let mut s = Session::new();
|
||||
let id = s.open("out.pdf", None, r.bytes, None).unwrap();
|
||||
assert_eq!(s.get(id).unwrap().info.title.as_deref(), Some("Checked"), "the title is in what was appended");
|
||||
}
|
||||
|
||||
/// #1324: marking a figure decorative rewrites that figure only. The header, added text and an
|
||||
/// unknown entry on the original stream stay attached to the page. This lives in the engine tests
|
||||
/// because edit and a11y are the same layer and cannot depend on each other.
|
||||
|
||||
@@ -78,6 +78,7 @@ fn count_inner(source: ExportSource, pages: &[usize], options: Options, mut prog
|
||||
tables: options.exclude_tables,
|
||||
code: options.exclude_code,
|
||||
images: options.exclude_images,
|
||||
painted: false,
|
||||
mcids: excluded.remove(&page).unwrap_or_default(),
|
||||
};
|
||||
let text = renderer.filtered_text(page, filter).map_err(|e| format!("page {}: {e}", page.saturating_add(1)))?.plain_text();
|
||||
|
||||
@@ -31,15 +31,20 @@ fn run_xml(text: &str, size: f64, bold: bool, italic: bool, color: [f64; 3]) ->
|
||||
format!("<w:r><w:rPr>{rpr}</w:rPr><w:t xml:space=\"preserve\">{}</w:t></w:r>", esc(text))
|
||||
}
|
||||
|
||||
/// One Word table: explicit absent borders (alignment alone cannot prove PDF rules), a grid sized
|
||||
/// from the detected column edges, `gridSpan` for spanning cells, empty cells for holes.
|
||||
/// One Word table: single borders when the page's rules draw its grid, explicit absent borders
|
||||
/// otherwise (alignment alone cannot prove PDF rules), a grid sized from the detected column
|
||||
/// edges, `gridSpan` for spanning cells, empty cells for holes.
|
||||
pub(crate) fn docx_table(t: &Table) -> String {
|
||||
let mut edges = t.cols.clone();
|
||||
edges.push(t.rect[2]);
|
||||
let widths: Vec<i64> = edges.windows(2).map(|w| ((w[1] - w[0]).max(20.0) * 20.0).round().clamp(60.0, 31680.0) as i64).collect();
|
||||
let mut s = String::from("<w:tbl><w:tblPr><w:tblW w:w=\"0\" w:type=\"auto\"/><w:tblBorders>");
|
||||
for edge in ["top", "left", "bottom", "right", "insideH", "insideV"] {
|
||||
s.push_str(&format!("<w:{edge} w:val=\"nil\"/>"));
|
||||
if t.ruled {
|
||||
s.push_str(&format!("<w:{edge} w:val=\"single\" w:sz=\"4\" w:space=\"0\" w:color=\"auto\"/>"));
|
||||
} else {
|
||||
s.push_str(&format!("<w:{edge} w:val=\"nil\"/>"));
|
||||
}
|
||||
}
|
||||
s.push_str("</w:tblBorders></w:tblPr><w:tblGrid>");
|
||||
for w in &widths {
|
||||
|
||||
@@ -0,0 +1,433 @@
|
||||
//! Copy with formatting: selected text as paragraphs of styled spans, written as an HTML
|
||||
//! fragment for the clipboard (inline styles, so a word processor keeps font, size, weight,
|
||||
//! slant and colour when it pastes).
|
||||
|
||||
use crate::as_html::allowed;
|
||||
use crate::{esc, hex};
|
||||
|
||||
/// Spans kept for one copy; text past it is left out and [`ClipText::truncated`] is set.
|
||||
pub const MAX_CLIP_SPANS: usize = 20_000;
|
||||
/// Text bytes kept for one copy (before escaping).
|
||||
pub const MAX_CLIP_TEXT_BYTES: usize = 2 << 20;
|
||||
/// The HTML written for one copy never passes this many bytes.
|
||||
pub const MAX_CLIP_HTML_BYTES: usize = 16 << 20;
|
||||
/// Font sizes are written within this range (points), so a hostile size stays a font size.
|
||||
const CLIP_SIZE_PT: std::ops::RangeInclusive<f64> = 1.0..=1000.0;
|
||||
/// A family name longer than this is not a family name.
|
||||
const MAX_FAMILY_CHARS: usize = 64;
|
||||
|
||||
/// How a span looks.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct ClipStyle {
|
||||
/// Family names to try in order ([`font_family`]); empty keeps the target's own.
|
||||
pub families: Vec<String>,
|
||||
/// Size in points; zero or not finite leaves the target's size, and any other is written
|
||||
/// within 1 to 1000.
|
||||
pub size: f64,
|
||||
pub bold: bool,
|
||||
pub italic: bool,
|
||||
/// Fill colour as RGB in 0..=1.
|
||||
pub color: [f64; 3],
|
||||
}
|
||||
|
||||
/// A run of text in one style.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct ClipSpan {
|
||||
pub text: String,
|
||||
pub style: ClipStyle,
|
||||
}
|
||||
|
||||
/// The copied text: paragraphs of spans, and whether a cap left some out.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct ClipText {
|
||||
pub paragraphs: Vec<Vec<ClipSpan>>,
|
||||
pub truncated: bool,
|
||||
}
|
||||
|
||||
/// Builds a [`ClipText`] piece by piece, merging pieces of equal style into one span and
|
||||
/// stopping at the caps.
|
||||
#[derive(Debug)]
|
||||
pub struct ClipBuilder {
|
||||
out: ClipText,
|
||||
/// The separator owed before the next piece in this paragraph (a space or a line break).
|
||||
pending: Option<char>,
|
||||
new_paragraph: bool,
|
||||
spans: usize,
|
||||
bytes: usize,
|
||||
}
|
||||
|
||||
impl Default for ClipBuilder {
|
||||
fn default() -> Self {
|
||||
Self { out: ClipText::default(), pending: None, new_paragraph: true, spans: 0, bytes: 0 }
|
||||
}
|
||||
}
|
||||
|
||||
impl ClipBuilder {
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
/// A word space before the next piece (dropped at the start of a paragraph).
|
||||
pub fn space(&mut self) {
|
||||
self.pending.get_or_insert(' ');
|
||||
}
|
||||
|
||||
/// A line break inside the paragraph before the next piece.
|
||||
pub fn line_break(&mut self) {
|
||||
self.pending = Some('\n');
|
||||
}
|
||||
|
||||
/// The next piece starts a new paragraph.
|
||||
pub fn paragraph(&mut self) {
|
||||
self.new_paragraph = true;
|
||||
self.pending = None;
|
||||
}
|
||||
|
||||
/// Append `text` in `style`. Returns `false` once a cap is reached; nothing more is kept.
|
||||
pub fn push(&mut self, text: &str, style: &ClipStyle) -> bool {
|
||||
if self.out.truncated {
|
||||
return false;
|
||||
}
|
||||
if text.is_empty() {
|
||||
return true;
|
||||
}
|
||||
let sep = if self.new_paragraph { None } else { self.pending };
|
||||
let need = text.len().saturating_add(sep.map_or(0, char::len_utf8));
|
||||
let Some(bytes) = self.bytes.checked_add(need).filter(|b| *b <= MAX_CLIP_TEXT_BYTES) else {
|
||||
self.out.truncated = true;
|
||||
return false;
|
||||
};
|
||||
let new_span = self.new_paragraph || self.out.paragraphs.last().and_then(|p| p.last()).is_none_or(|last| last.style != *style);
|
||||
if new_span && self.spans >= MAX_CLIP_SPANS {
|
||||
self.out.truncated = true;
|
||||
return false;
|
||||
}
|
||||
if self.new_paragraph {
|
||||
self.out.paragraphs.push(Vec::new());
|
||||
self.new_paragraph = false;
|
||||
}
|
||||
self.pending = None;
|
||||
let Some(spans) = self.out.paragraphs.last_mut() else { return false };
|
||||
match spans.last_mut() {
|
||||
Some(last) if last.style == *style => {
|
||||
last.text.extend(sep);
|
||||
last.text.push_str(text);
|
||||
}
|
||||
last => {
|
||||
// A separator belongs to the span before it, so a new style starts at its text.
|
||||
if let (Some(last), Some(sep)) = (last, sep) {
|
||||
last.text.push(sep);
|
||||
}
|
||||
spans.push(ClipSpan { text: text.to_owned(), style: style.clone() });
|
||||
self.spans += 1;
|
||||
}
|
||||
}
|
||||
self.bytes = bytes;
|
||||
true
|
||||
}
|
||||
|
||||
pub fn finish(self) -> ClipText {
|
||||
self.out
|
||||
}
|
||||
}
|
||||
|
||||
/// The family names to try for a font's `/BaseFont`, best first: subset tag and style suffix
|
||||
/// removed, `PSMT`/`MT`/`PS` dropped. The first has camel case and hyphens spaced
|
||||
/// (`ABCDEF+TimesNewRomanPSMT` → `Times New Roman`, `MS-Gothic` → `MS Gothic`); the second,
|
||||
/// when it differs, is the name as spelt (`SimSun`). A hyphen ends the family only before a
|
||||
/// style word (`Arial-BoldMT`). Only letters, digits, spaces, `-`, `_` and `.` are kept, so a
|
||||
/// name cannot leave its CSS string. Empty when nothing is left.
|
||||
pub fn font_family(base_font: &str) -> Vec<String> {
|
||||
let name = match base_font.split_once('+') {
|
||||
Some((tag, rest)) if tag.len() == 6 && tag.bytes().all(|b| b.is_ascii_uppercase()) => rest,
|
||||
_ => base_font,
|
||||
};
|
||||
let name = name.split_once(',').map_or(name, |(family, _)| family);
|
||||
let family = match name.rsplit_once('-') {
|
||||
Some((family, style)) if STYLE_WORDS.iter().any(|w| style.starts_with(w)) => family,
|
||||
_ => name,
|
||||
};
|
||||
let family = family.strip_suffix("PSMT").or_else(|| family.strip_suffix("MT")).or_else(|| family.strip_suffix("PS")).unwrap_or(family);
|
||||
let mut spaced = String::with_capacity(family.len().min(MAX_FAMILY_CHARS * 2));
|
||||
let mut prev_lower = false;
|
||||
for c in family.chars().take(MAX_FAMILY_CHARS) {
|
||||
if prev_lower && c.is_ascii_uppercase() {
|
||||
spaced.push(' ');
|
||||
}
|
||||
prev_lower = c.is_ascii_lowercase();
|
||||
spaced.push(if c == '-' { ' ' } else { c });
|
||||
}
|
||||
let spelt: String = family.chars().take(MAX_FAMILY_CHARS).collect();
|
||||
let mut out: Vec<String> = Vec::with_capacity(2);
|
||||
for f in [safe_family(&spaced), safe_family(&spelt)].into_iter().flatten() {
|
||||
if !out.contains(&f) {
|
||||
out.push(f);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// What may follow a hyphen in a `/BaseFont` when the rest names the style, not the family.
|
||||
const STYLE_WORDS: &[&str] = &[
|
||||
"Bold", "Italic", "Oblique", "Regular", "Roman", "Light", "Medium", "Semi", "Demi", "Black", "Heavy", "Thin", "Book", "Cond", "Extra", "Ultra",
|
||||
"Narrow", "Plain", "Normal", "It", "Bd", "Lt", "Md", "Blk", "MT", "PS",
|
||||
];
|
||||
|
||||
/// `family` with only letters, digits, spaces, `-`, `_` and `.`, so it cannot leave a CSS
|
||||
/// string; `None` when nothing is left.
|
||||
fn safe_family(family: &str) -> Option<String> {
|
||||
let kept: String = family.chars().filter(|c| c.is_alphanumeric() || matches!(c, ' ' | '-' | '_' | '.')).take(MAX_FAMILY_CHARS * 2).collect();
|
||||
let kept = kept.trim();
|
||||
(!kept.is_empty()).then(|| kept.to_owned())
|
||||
}
|
||||
|
||||
/// The copied text as an HTML fragment, and whether [`MAX_CLIP_HTML_BYTES`] cut it: one `<p>`
|
||||
/// per paragraph, a `<span>` per run with its families, size and colour inline, bold as
|
||||
/// `<strong>` and italic as `<em>` (so a target that drops style attributes still keeps them).
|
||||
/// Text is escaped; a line break is `<br>`, and a space HTML would collapse (after another
|
||||
/// space, at a paragraph's start or after a break, across runs too) is ` `. Never longer
|
||||
/// than the cap: a paragraph or run that would pass it ends the fragment.
|
||||
pub fn clip_html(text: &ClipText) -> (String, bool) {
|
||||
const OPEN: &str = "<p style=\"margin:0\">";
|
||||
const CLOSE: &str = "</p>\n";
|
||||
let fits = |len: usize, more: usize| len.saturating_add(more).saturating_add(CLOSE.len()) <= MAX_CLIP_HTML_BYTES;
|
||||
let mut out = String::new();
|
||||
for spans in &text.paragraphs {
|
||||
if !fits(out.len(), OPEN.len()) {
|
||||
return (out, true);
|
||||
}
|
||||
let mut p = String::from(OPEN);
|
||||
// A paragraph's first space would collapse.
|
||||
let mut space_before = true;
|
||||
for span in spans {
|
||||
let s = span_html(span, &mut space_before);
|
||||
if !fits(out.len().saturating_add(p.len()), s.len()) {
|
||||
if p.len() > OPEN.len() {
|
||||
out.push_str(&p);
|
||||
out.push_str(CLOSE);
|
||||
}
|
||||
return (out, true);
|
||||
}
|
||||
p.push_str(&s);
|
||||
}
|
||||
p.push_str(CLOSE);
|
||||
out.push_str(&p);
|
||||
}
|
||||
(out, false)
|
||||
}
|
||||
|
||||
/// One run as HTML. `space_before` says whether the text before it ended in a space or a break,
|
||||
/// and is left saying so for the next run.
|
||||
fn span_html(span: &ClipSpan, space_before: &mut bool) -> String {
|
||||
let st = &span.style;
|
||||
let mut css = Vec::new();
|
||||
let families: Vec<String> = st.families.iter().filter_map(|f| safe_family(f)).map(|f| format!("'{f}'")).collect();
|
||||
if !families.is_empty() {
|
||||
css.push(format!("font-family:{}", families.join(",")));
|
||||
}
|
||||
if st.size.is_finite() && st.size != 0.0 {
|
||||
css.push(format!("font-size:{}pt", num(st.size.clamp(*CLIP_SIZE_PT.start(), *CLIP_SIZE_PT.end()))));
|
||||
}
|
||||
if let Some(h) = hex(st.color) {
|
||||
css.push(format!("color:#{h}"));
|
||||
}
|
||||
let mut body = text_html(&span.text, space_before);
|
||||
if st.italic {
|
||||
body = format!("<em>{body}</em>");
|
||||
}
|
||||
if st.bold {
|
||||
body = format!("<strong>{body}</strong>");
|
||||
}
|
||||
if css.is_empty() { body } else { format!("<span style=\"{}\">{body}</span>", esc(&css.join(";"))) }
|
||||
}
|
||||
|
||||
/// Escape for HTML text in one pass; `\n` becomes `<br>`, and a space after a space or a break
|
||||
/// (`space_before` carries that in and out) is ` `, so a run of spaces keeps its width.
|
||||
/// Dropped: what [`esc`] drops (C0 controls), C1 controls, a carriage return
|
||||
/// and the bidirectional overrides and isolates, which would reorder the pasted text.
|
||||
fn text_html(text: &str, space_before: &mut bool) -> String {
|
||||
let mut out = String::with_capacity(text.len());
|
||||
for c in text.chars().filter(|c| clip_char(*c)) {
|
||||
match c {
|
||||
'\n' => out.push_str("<br>"),
|
||||
' ' if *space_before => out.push_str(" "),
|
||||
'&' => out.push_str("&"),
|
||||
'<' => out.push_str("<"),
|
||||
'>' => out.push_str(">"),
|
||||
'"' => out.push_str("""),
|
||||
c => out.push(c),
|
||||
}
|
||||
*space_before = matches!(c, ' ' | '\n');
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Whether `c` may go into the clipboard HTML's text.
|
||||
fn clip_char(c: char) -> bool {
|
||||
allowed(c) && !matches!(c, '\r' | '\u{80}'..='\u{9F}' | '\u{202A}'..='\u{202E}' | '\u{2066}'..='\u{2069}')
|
||||
}
|
||||
|
||||
/// A size with at most one decimal and no trailing `.0`.
|
||||
fn num(v: f64) -> String {
|
||||
let r = (v * 10.0).round() / 10.0;
|
||||
if r.fract() == 0.0 { format!("{r:.0}") } else { format!("{r:.1}") }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn style(size: f64, bold: bool, italic: bool, color: [f64; 3]) -> ClipStyle {
|
||||
ClipStyle { families: font_family("ABCDEF+Helvetica-Bold"), size, bold, italic, color }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn heading_body_and_coloured_span_keep_their_formatting() {
|
||||
let mut b = ClipBuilder::new();
|
||||
let heading = style(24.0, true, false, [0.0; 3]);
|
||||
let body = style(11.5, false, false, [0.0; 3]);
|
||||
let red = style(11.5, false, true, [1.0, 0.0, 0.0]);
|
||||
b.push("Title", &heading);
|
||||
b.paragraph();
|
||||
b.push("Body", &body);
|
||||
b.space();
|
||||
b.push("text", &body);
|
||||
b.space();
|
||||
b.push("red", &red);
|
||||
let clip = b.finish();
|
||||
assert_eq!(clip.paragraphs.len(), 2);
|
||||
assert_eq!(clip.paragraphs.get(1).map(Vec::len), Some(2), "{clip:?}");
|
||||
let (html, cut) = clip_html(&clip);
|
||||
assert!(!cut);
|
||||
assert_eq!(
|
||||
html,
|
||||
"<p style=\"margin:0\"><span style=\"font-family:'Helvetica';font-size:24pt\"><strong>Title</strong></span></p>\n\
|
||||
<p style=\"margin:0\"><span style=\"font-family:'Helvetica';font-size:11.5pt\">Body text </span>\
|
||||
<span style=\"font-family:'Helvetica';font-size:11.5pt;color:#FF0000\"><em>red</em></span></p>\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn special_characters_are_escaped_and_cannot_leave_the_style() {
|
||||
let st = ClipStyle { families: vec!["Evil';}</style><script>\\\n".into()], size: f64::NAN, ..ClipStyle::default() };
|
||||
let mut b = ClipBuilder::new();
|
||||
b.push("<a href=\"x\">&\u{0}\u{1b}</a> two\nline", &st);
|
||||
let (html, _) = clip_html(&b.finish());
|
||||
assert_eq!(
|
||||
html,
|
||||
"<p style=\"margin:0\"><span style=\"font-family:'Evilstylescript'\"><a href="x">&</a> two<br>line</span></p>\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invisible_controls_and_bidi_overrides_are_dropped() {
|
||||
let mut b = ClipBuilder::new();
|
||||
b.push("a\u{85}b\u{9F}c\rd\u{202E}e\u{2066}f\u{2069}g\u{202A}h\u{2067}i\tj", &ClipStyle::default());
|
||||
assert_eq!(clip_html(&b.finish()).0, "<p style=\"margin:0\">abcdefghi\tj</p>\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn font_sizes_stay_within_range() {
|
||||
for (size, want) in [(1e300, "1000"), (f64::MAX, "1000"), (2e306, "1000"), (0.2, "1"), (9.96, "10"), (-12.0, "1"), (f64::MIN, "1")] {
|
||||
let st = ClipStyle { size, ..ClipStyle::default() };
|
||||
let mut b = ClipBuilder::new();
|
||||
b.push("x", &st);
|
||||
let (html, _) = clip_html(&b.finish());
|
||||
assert_eq!(html, format!("<p style=\"margin:0\"><span style=\"font-size:{want}pt\">x</span></p>\n"), "{size}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn families_read_like_a_word_processor_names_them() {
|
||||
let f = |b: &str| font_family(b);
|
||||
assert_eq!(f("ABCDEF+TimesNewRomanPSMT"), ["Times New Roman", "TimesNewRoman"]);
|
||||
assert_eq!(f("Arial,BoldItalic"), ["Arial"]);
|
||||
assert_eq!(f("Arial-BoldMT"), ["Arial"]);
|
||||
assert_eq!(f("Helvetica-Oblique"), ["Helvetica"]);
|
||||
assert_eq!(f("MS-Gothic"), ["MS Gothic", "MS-Gothic"], "a hyphen before a family word stays in the name");
|
||||
assert_eq!(f("Segoe-UI-Bold"), ["Segoe UI", "Segoe-UI"], "the style is the last part");
|
||||
assert_eq!(f("SimSun"), ["Sim Sun", "SimSun"], "the name as spelt is tried too");
|
||||
assert_eq!(f("abcdef+Foo"), ["abcdefFoo"], "a lower-case prefix is not a subset tag");
|
||||
assert!(f("").is_empty());
|
||||
assert!(f("+'\"\\;").is_empty());
|
||||
assert!(f(&"Ab".repeat(10_000)).iter().all(|f| f.chars().count() <= MAX_FAMILY_CHARS * 2));
|
||||
let st = ClipStyle { families: f("SimSun"), ..ClipStyle::default() };
|
||||
let mut b = ClipBuilder::new();
|
||||
b.push("x", &st);
|
||||
assert_eq!(clip_html(&b.finish()).0, "<p style=\"margin:0\"><span style=\"font-family:'Sim Sun','SimSun'\">x</span></p>\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spaces_html_would_collapse_keep_their_width() {
|
||||
let (a, c) = (ClipStyle::default(), ClipStyle { bold: true, ..ClipStyle::default() });
|
||||
let mut b = ClipBuilder::new();
|
||||
b.push(" lead a ", &a);
|
||||
b.push(" b", &c);
|
||||
b.line_break();
|
||||
b.push(" c", &a);
|
||||
assert_eq!(
|
||||
clip_html(&b.finish()).0,
|
||||
"<p style=\"margin:0\"> lead a <strong> b<br></strong> c</p>\n",
|
||||
"at a paragraph's start, across runs and after a break"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_default_builder_starts_a_paragraph() {
|
||||
let mut b = ClipBuilder::default();
|
||||
assert!(b.push("x", &ClipStyle::default()));
|
||||
assert_eq!(b.finish().paragraphs.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_and_huge_selections_are_bounded() {
|
||||
let b = ClipBuilder::new();
|
||||
assert_eq!(clip_html(&b.finish()), (String::new(), false));
|
||||
let mut b = ClipBuilder::new();
|
||||
b.space();
|
||||
assert!(b.push("", &ClipStyle::default()));
|
||||
assert!(b.finish().paragraphs.is_empty(), "nothing pushed, nothing kept");
|
||||
|
||||
// Alternating styles: the span cap stops it.
|
||||
let (a, c) = (style(10.0, false, false, [0.0; 3]), style(10.0, true, false, [0.0; 3]));
|
||||
let mut b = ClipBuilder::new();
|
||||
let mut kept = 0usize;
|
||||
for i in 0..MAX_CLIP_SPANS + 10 {
|
||||
if b.push("x", if i % 2 == 0 { &a } else { &c }) {
|
||||
kept += 1;
|
||||
}
|
||||
}
|
||||
let clip = b.finish();
|
||||
assert!(clip.truncated);
|
||||
assert_eq!(kept, MAX_CLIP_SPANS);
|
||||
// Exactly at the cap, a new paragraph is refused before it is opened.
|
||||
let mut b = ClipBuilder::new();
|
||||
for i in 0..MAX_CLIP_SPANS {
|
||||
assert!(b.push("x", if i % 2 == 0 { &a } else { &c }));
|
||||
}
|
||||
b.paragraph();
|
||||
assert!(!b.push("x", &a));
|
||||
let clip = b.finish();
|
||||
assert!(clip.truncated);
|
||||
assert_eq!(clip.paragraphs.len(), 1, "no empty paragraph past the cap");
|
||||
// One style: the text cap stops it.
|
||||
let mut b = ClipBuilder::new();
|
||||
let chunk = "y".repeat(1 << 16);
|
||||
// Bounded, so the test fails rather than runs on when the cap is gone.
|
||||
let pushes = (0..MAX_CLIP_TEXT_BYTES / chunk.len() + 2).take_while(|_| b.push(&chunk, &a)).count();
|
||||
assert_eq!(pushes, MAX_CLIP_TEXT_BYTES / chunk.len(), "the cap stopped it");
|
||||
let clip = b.finish();
|
||||
assert!(clip.truncated);
|
||||
assert!(clip.paragraphs.iter().flatten().map(|s| s.text.len()).sum::<usize>() <= MAX_CLIP_TEXT_BYTES);
|
||||
// HTML: escaping grows text up to sixfold; the writer still stops at its cap.
|
||||
let big = ClipText { paragraphs: vec![vec![ClipSpan { text: "<".repeat(1 << 20), style: a.clone() }]; 8], truncated: false };
|
||||
let (html, cut) = clip_html(&big);
|
||||
assert!(cut, "the cut is reported");
|
||||
assert!(html.len() <= MAX_CLIP_HTML_BYTES && html.ends_with("</p>\n"), "{}", html.len());
|
||||
assert!(html.len() > MAX_CLIP_HTML_BYTES / 2);
|
||||
// Empty paragraphs count against the cap too.
|
||||
let empty = ClipText { paragraphs: vec![Vec::new(); MAX_CLIP_HTML_BYTES / 20], truncated: false };
|
||||
let (html, cut) = clip_html(&empty);
|
||||
assert!(cut && html.len() <= MAX_CLIP_HTML_BYTES, "{}", html.len());
|
||||
}
|
||||
}
|
||||
@@ -43,6 +43,9 @@ pub struct Page {
|
||||
/// The colour the whole page is painted before its content (a page background), as sRGB
|
||||
/// components in 0..=1; `None` for a page with no background of its own.
|
||||
pub background: Option<[f64; 3]>,
|
||||
/// The ruled lines the page draws (horizontal and vertical strokes, thin filled bars), each
|
||||
/// as its box [x0, y0, x1, y1] on the displayed page in points (y up).
|
||||
pub rules: Vec<[f64; 4]>,
|
||||
}
|
||||
|
||||
/// One cell of a detected table. `span` is how many grid columns the cell covers (a header
|
||||
@@ -65,6 +68,9 @@ pub struct Table {
|
||||
pub rect: [f64; 4],
|
||||
pub cols: Vec<f64>,
|
||||
pub rows: Vec<Vec<Cell>>,
|
||||
/// Whether the page's ruled lines separate every pair of neighbouring cells, so the writers
|
||||
/// can draw the table's borders.
|
||||
pub ruled: bool,
|
||||
}
|
||||
|
||||
/// What goes into the output, in order.
|
||||
@@ -248,10 +254,72 @@ fn is_cell_like(b: &Block) -> bool {
|
||||
(b.rect[3] - b.rect[1]) <= b.size * 5.0 && !b.text.trim().is_empty()
|
||||
}
|
||||
|
||||
/// A rule at most this thick (points) is a line, not a filled area.
|
||||
const RULE_THICK: f64 = 3.0;
|
||||
|
||||
/// Rule comparisons one page may spend deciding whether its tables are ruled; past it a table
|
||||
/// counts as unruled, so a hostile page of many rules and cells stays quick.
|
||||
const RULE_BUDGET: usize = 4_000_000;
|
||||
|
||||
/// Whether `rules` separate every pair of neighbouring cells of a table whose rows are `rows`
|
||||
/// (block indices, top to bottom) and whose columns start at `edges` and end at `right`: between
|
||||
/// two columns a vertical rule beside each row (unless a cell of that row spans across), and
|
||||
/// between two rows a horizontal rule under each column. Every check spends `budget`.
|
||||
fn ruled(blocks: &[Block], rules: &[[f64; 4]], rows: &[Vec<usize>], edges: &[f64], right: f64, budget: &mut usize) -> bool {
|
||||
let vertical: Vec<&[f64; 4]> = rules.iter().filter(|r| r[2] - r[0] <= RULE_THICK && r[3] - r[1] > RULE_THICK).collect();
|
||||
let horizontal: Vec<&[f64; 4]> = rules.iter().filter(|r| r[3] - r[1] <= RULE_THICK && r[2] - r[0] > RULE_THICK).collect();
|
||||
let mut find = |set: &[&[f64; 4]], hit: &dyn Fn(&[f64; 4]) -> bool| -> bool {
|
||||
set.iter().any(|r| {
|
||||
*budget = budget.saturating_sub(1);
|
||||
*budget > 0 && hit(r)
|
||||
})
|
||||
};
|
||||
// Each row's vertical span.
|
||||
let spans: Vec<[f64; 2]> = rows
|
||||
.iter()
|
||||
.map(|row| {
|
||||
let bs = || row.iter().filter_map(|&i| blocks.get(i));
|
||||
[bs().map(|b| b.rect[1]).fold(f64::INFINITY, f64::min), bs().map(|b| b.rect[3]).fold(f64::NEG_INFINITY, f64::max)]
|
||||
})
|
||||
.collect();
|
||||
for (row, span) in rows.iter().zip(&spans) {
|
||||
let mid = (span[0] + span[1]) / 2.0;
|
||||
for pair in edges.windows(2) {
|
||||
let (lo, hi) = (pair[0], pair[1]);
|
||||
let cells = || row.iter().filter_map(|&i| blocks.get(i));
|
||||
if cells().any(|b| b.rect[0] < hi - COL_TOL && b.rect[2] > hi + COL_TOL) {
|
||||
continue;
|
||||
}
|
||||
let clear = |x: f64| !cells().any(|b| b.rect[0] + COL_TOL < x && x < b.rect[2] - COL_TOL);
|
||||
if !find(&vertical, &|r| {
|
||||
let x = (r[0] + r[2]) / 2.0;
|
||||
lo + COL_TOL < x && x <= hi + COL_TOL && r[1] <= mid && mid <= r[3] && clear(x)
|
||||
}) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
let mids: Vec<f64> = edges.iter().zip(edges.iter().skip(1).chain(std::iter::once(&right))).map(|(a, b)| (a + b) / 2.0).collect();
|
||||
for pair in spans.windows(2) {
|
||||
let (below_top, above_bottom) = (pair[1][1], pair[0][0]);
|
||||
for &x in &mids {
|
||||
if !find(&horizontal, &|r| {
|
||||
let y = (r[1] + r[3]) / 2.0;
|
||||
below_top - COL_TOL <= y && y <= above_bottom + COL_TOL && r[0] <= x && x <= r[2]
|
||||
}) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// Detect tables in a page's blocks from their text layout: columns are left edges shared by
|
||||
/// several short blocks, rows are blocks whose vertical spans overlap. Returns the tables and,
|
||||
/// several short blocks, rows are blocks whose vertical spans overlap. Two columns of two rows
|
||||
/// are a table only when `rules` (the page's ruled lines) draw its grid. Returns the tables and,
|
||||
/// per block, whether a table consumed it (so `items` can drop it from the paragraph flow).
|
||||
pub(crate) fn tables(blocks: &[Block]) -> (Vec<Table>, Vec<bool>) {
|
||||
pub(crate) fn tables(blocks: &[Block], rules: &[[f64; 4]]) -> (Vec<Table>, Vec<bool>) {
|
||||
let mut budget = RULE_BUDGET;
|
||||
let mut consumed = vec![false; blocks.len()];
|
||||
// Candidate columns: cluster the left edges of cell-like blocks.
|
||||
let mut xs: Vec<(f64, usize)> = blocks.iter().enumerate().filter(|(_, b)| is_cell_like(b)).map(|(i, b)| (b.rect[0], i)).collect();
|
||||
@@ -313,7 +381,7 @@ pub(crate) fn tables(blocks: &[Block]) -> (Vec<Table>, Vec<bool>) {
|
||||
}
|
||||
// Runs of consecutive rows that have two or more distinct columns are tables.
|
||||
let mut out = Vec::new();
|
||||
let flush = |run: &mut Vec<Vec<(usize, usize)>>, out: &mut Vec<Table>, consumed: &mut Vec<bool>| {
|
||||
let flush = |run: &mut Vec<Vec<(usize, usize)>>, out: &mut Vec<Table>, consumed: &mut Vec<bool>, budget: &mut usize| {
|
||||
if run.len() < 2 {
|
||||
run.clear();
|
||||
return;
|
||||
@@ -325,12 +393,16 @@ pub(crate) fn tables(blocks: &[Block]) -> (Vec<Table>, Vec<bool>) {
|
||||
edges.sort_by(f64::total_cmp);
|
||||
edges.dedup_by(|a, b| (*a - *b).abs() <= COL_TOL);
|
||||
let ncols = edges.len();
|
||||
let ok = (ncols >= 3 || (ncols == 2 && run.len() >= 3)) && ncols <= MAX_COLS;
|
||||
let right = used.iter().map(|&i| blocks[i].rect[2]).fold(f64::MIN, f64::max) + COL_TOL;
|
||||
let is_ruled = (2..=MAX_COLS).contains(&ncols) && !rules.is_empty() && {
|
||||
let row_blocks: Vec<Vec<usize>> = run.iter().map(|row| row.iter().map(|(_, i)| *i).collect()).collect();
|
||||
ruled(blocks, rules, &row_blocks, &edges, right, budget)
|
||||
};
|
||||
let ok = (ncols >= 3 || (ncols == 2 && (run.len() >= 3 || is_ruled))) && ncols <= MAX_COLS;
|
||||
if !ok {
|
||||
run.clear();
|
||||
return;
|
||||
}
|
||||
let right = used.iter().map(|&i| blocks[i].rect[2]).fold(f64::MIN, f64::max) + COL_TOL;
|
||||
let mut rows_out = Vec::new();
|
||||
let mut slots: Vec<Option<(Cell, Vec<usize>)>> = vec![None; ncols];
|
||||
for row in run.drain(..) {
|
||||
@@ -385,7 +457,7 @@ pub(crate) fn tables(blocks: &[Block]) -> (Vec<Table>, Vec<bool>) {
|
||||
right,
|
||||
used.iter().map(|&i| blocks[i].rect[3]).fold(f64::MIN, f64::max),
|
||||
];
|
||||
out.push(Table { rect, cols: edges, rows: rows_out });
|
||||
out.push(Table { rect, cols: edges, rows: rows_out, ruled: is_ruled });
|
||||
};
|
||||
// Runs of consecutive multi-column rows are tables. Rows on either side of a run that
|
||||
// hold a single cell wide enough to span two columns (a header band, a totals row) join
|
||||
@@ -436,7 +508,7 @@ pub(crate) fn tables(blocks: &[Block]) -> (Vec<Table>, Vec<bool>) {
|
||||
if end < rows.len() && rows[end].len() == 1 && spans_run(&run_edges(&rows[start..end]), rows[end][0].1) {
|
||||
pieces.push(rows[end].clone());
|
||||
}
|
||||
flush(&mut pieces, &mut out, &mut consumed);
|
||||
flush(&mut pieces, &mut out, &mut consumed, &mut budget);
|
||||
}
|
||||
(out, consumed)
|
||||
}
|
||||
@@ -448,7 +520,7 @@ pub(crate) fn items(pages: &[Page]) -> Vec<Item<'_>> {
|
||||
if i > 0 {
|
||||
out.push(Item::PageBreak);
|
||||
}
|
||||
let (tables, consumed) = tables(&p.blocks);
|
||||
let (tables, consumed) = tables(&p.blocks, &p.rules);
|
||||
// Blocks and images by their top edge, top to bottom.
|
||||
// A paragraph sits where its first run does: its other runs follow along the same line.
|
||||
let mut parts: Vec<(f64, f64, Item)> = paragraphs(&p.blocks, &consumed)
|
||||
|
||||
@@ -20,6 +20,7 @@ mod as_docx;
|
||||
mod as_html;
|
||||
mod as_markdown;
|
||||
mod as_rtf;
|
||||
mod clip;
|
||||
mod layout;
|
||||
|
||||
pub use as_docx::docx;
|
||||
@@ -34,6 +35,7 @@ pub use as_markdown::markdown;
|
||||
#[cfg(test)]
|
||||
use as_markdown::{emphasis, paragraph};
|
||||
pub use as_rtf::rtf;
|
||||
pub use clip::{ClipBuilder, ClipSpan, ClipStyle, ClipText, MAX_CLIP_HTML_BYTES, MAX_CLIP_SPANS, MAX_CLIP_TEXT_BYTES, clip_html, font_family};
|
||||
pub use layout::{Block, Cell, Image, Page, Table};
|
||||
#[cfg(test)]
|
||||
use layout::{LOOKUP_STEPS, MAX_COLS, body_size};
|
||||
|
||||
@@ -127,7 +127,7 @@ pub fn pptx(pages: &[Page], title: &str) -> Vec<u8> {
|
||||
let mut slides: Vec<(String, String)> = Vec::new(); // (slide_xml, slide_rels)
|
||||
|
||||
for p in pages {
|
||||
let (tables, consumed) = crate::tables(&p.blocks);
|
||||
let (tables, consumed) = crate::tables(&p.blocks, &p.rules);
|
||||
let title_idx = p
|
||||
.blocks
|
||||
.iter()
|
||||
|
||||
@@ -46,6 +46,7 @@ fn sample_page() -> Page {
|
||||
rotation: 0.0,
|
||||
}],
|
||||
background: None,
|
||||
rules: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -174,6 +175,7 @@ fn pptx_package_parts_are_complete_and_consistent() {
|
||||
],
|
||||
images: Vec::new(),
|
||||
background: None,
|
||||
rules: Vec::new(),
|
||||
};
|
||||
let bytes = pptx(&[sample_page(), table_page], "Two");
|
||||
let parts = entries(&bytes);
|
||||
@@ -278,7 +280,7 @@ fn hostile_sizes_do_not_overflow_the_slide_position() {
|
||||
rotation: 0.0,
|
||||
})
|
||||
.collect();
|
||||
let p = Page { width: f64::MAX, height: f64::NAN, blocks, images, background: None };
|
||||
let p = Page { width: f64::MAX, height: f64::NAN, blocks, images, background: None, rules: Vec::new() };
|
||||
let bytes = pptx(&[p], "Hostile");
|
||||
let slide = part(&bytes, "ppt/slides/slide1.xml");
|
||||
assert!(slide.contains("Title") && slide.contains("<p:pic>"), "the slide is still written");
|
||||
@@ -360,6 +362,7 @@ fn pptx_table_cell_with_largest_font_stays_in_table_and_not_in_title() {
|
||||
],
|
||||
images: Vec::new(),
|
||||
background: None,
|
||||
rules: Vec::new(),
|
||||
};
|
||||
let bytes = pptx(&[p], "Table Check");
|
||||
let slide_xml = part(&bytes, "ppt/slides/slide1.xml");
|
||||
|
||||
+54
-14
@@ -14,7 +14,7 @@ fn varied_page(n: usize) -> Page {
|
||||
space_around: [false; 2],
|
||||
})
|
||||
.collect();
|
||||
Page { width: 612.0, height: 792.0, blocks, images: Vec::new(), background: None }
|
||||
Page { width: 612.0, height: 792.0, blocks, images: Vec::new(), background: None, rules: Vec::new() }
|
||||
}
|
||||
|
||||
fn lookup_steps(f: impl FnOnce()) -> usize {
|
||||
@@ -69,6 +69,7 @@ fn page() -> Page {
|
||||
rotation: 0.0,
|
||||
}],
|
||||
background: None,
|
||||
rules: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -136,6 +137,7 @@ fn word_table_cell_widths_follow_the_columns_they_span() {
|
||||
vec![cell("All", 3)],
|
||||
vec![cell("First", 1)],
|
||||
],
|
||||
ruled: false,
|
||||
};
|
||||
let xml = docx_table(&table);
|
||||
assert!(xml.contains("<w:gridCol w:w=\"1000\"/><w:gridCol w:w=\"2000\"/><w:gridCol w:w=\"3000\"/>"), "{xml}");
|
||||
@@ -360,6 +362,7 @@ fn table_page() -> Page {
|
||||
],
|
||||
images: Vec::new(),
|
||||
background: None,
|
||||
rules: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -376,7 +379,7 @@ fn grid_text_becomes_a_real_table_in_every_format() {
|
||||
let d = docx(std::slice::from_ref(&p), "Bill");
|
||||
assert!(d.starts_with(b"PK"));
|
||||
assert!(d.windows(b"word/document.xml".len()).any(|w| w == b"word/document.xml"));
|
||||
let (tables, _) = tables(&p.blocks);
|
||||
let (tables, _) = tables(&p.blocks, &p.rules);
|
||||
assert_eq!(tables.len(), 1);
|
||||
let table_xml = docx_table(&tables[0]);
|
||||
assert!(table_xml.contains("<w:tblGrid>"));
|
||||
@@ -421,7 +424,7 @@ fn a_staircase_of_blocks_is_not_a_huge_table() {
|
||||
})
|
||||
.collect();
|
||||
let started = std::time::Instant::now();
|
||||
let (tables, _) = tables(&blocks);
|
||||
let (tables, _) = tables(&blocks, &[]);
|
||||
assert!(tables.iter().all(|t| t.cols.len() <= MAX_COLS), "{} columns", tables.iter().map(|t| t.cols.len()).max().unwrap_or(0));
|
||||
assert!(started.elapsed() < std::time::Duration::from_secs(5), "took {:?}", started.elapsed());
|
||||
}
|
||||
@@ -451,6 +454,7 @@ fn word_opens_tables_up_to_its_column_limit() {
|
||||
.collect(),
|
||||
images: Vec::new(),
|
||||
background: None,
|
||||
rules: Vec::new(),
|
||||
};
|
||||
let grid_cols = |p: &Page| part(&docx(std::slice::from_ref(p), "Grid"), "word/document.xml").matches("<w:gridCol ").count();
|
||||
assert_eq!(grid_cols(&grid(63)), 63, "63 columns is still a table");
|
||||
@@ -486,6 +490,7 @@ fn a_link_inside_a_sentence_is_not_a_table_column() {
|
||||
],
|
||||
images: Vec::new(),
|
||||
background: None,
|
||||
rules: Vec::new(),
|
||||
};
|
||||
let h = html(std::slice::from_ref(&p), "Regulations");
|
||||
assert!(!h.contains("<table>"), "running text became a table: {h}");
|
||||
@@ -507,7 +512,7 @@ fn sentences_that_run_on_into_links_are_not_a_table() {
|
||||
blocks.push(block(lead, 72.0, y, 211.0, y + 12.0));
|
||||
blocks.push(blue("https://example.org/event", 212.5, y, 360.0, y + 12.0));
|
||||
}
|
||||
let p = Page { width: 612.0, height: 792.0, blocks, images: Vec::new(), background: None };
|
||||
let p = Page { width: 612.0, height: 792.0, blocks, images: Vec::new(), background: None, rules: Vec::new() };
|
||||
let h = html(std::slice::from_ref(&p), "Event");
|
||||
assert!(!h.contains("<table>"), "sentences became a table: {h}");
|
||||
assert_eq!(h.matches("https://example.org/event").count(), 3, "{h}");
|
||||
@@ -529,7 +534,7 @@ fn table_spans_do_not_consume_text_they_do_not_emit() {
|
||||
}
|
||||
}
|
||||
let p = Page { width: 612.0, height: 792.0, blocks, ..Page::default() };
|
||||
let (tables, consumed) = tables(&p.blocks);
|
||||
let (tables, consumed) = tables(&p.blocks, &p.rules);
|
||||
assert_eq!(tables.len(), 1);
|
||||
assert_eq!(tables[0].rows[0][0].span, 2);
|
||||
assert!(!consumed[1], "a covered slot did not emit its text");
|
||||
@@ -558,11 +563,11 @@ fn a_superscript_beside_a_number_keeps_its_table() {
|
||||
blocks.push(Block { size: 8.0, ..block(sup, 106.0, y + 5.0, 113.0, y + 13.0) });
|
||||
blocks.push(block(&format!("{},000", 30 - 5 * n), 300.0, y, 340.0, y + 12.0));
|
||||
}
|
||||
let p = Page { width: 612.0, height: 792.0, blocks, images: Vec::new(), background: None };
|
||||
let p = Page { width: 612.0, height: 792.0, blocks, images: Vec::new(), background: None, rules: Vec::new() };
|
||||
let h = html(std::slice::from_ref(&p), "Prizes");
|
||||
assert!(h.contains("<table>"), "the prize table was lost: {h}");
|
||||
assert!(h.contains("30,000") && h.contains("15,000"), "{h}");
|
||||
let (tables, consumed) = tables(&p.blocks);
|
||||
let (tables, consumed) = tables(&p.blocks, &p.rules);
|
||||
assert!(consumed.iter().all(|used| *used), "ordinary table continuations stay in their cells");
|
||||
let cells: Vec<&str> = tables.iter().flat_map(|t| &t.rows).flatten().map(|c| c.text.as_str()).collect();
|
||||
assert!(["st", "nd", "rd", "th"].iter().all(|suffix| cells.contains(suffix)));
|
||||
@@ -591,6 +596,7 @@ fn two_column_body_text_is_not_mistaken_for_a_table() {
|
||||
],
|
||||
images: Vec::new(),
|
||||
background: None,
|
||||
rules: Vec::new(),
|
||||
};
|
||||
let h = html(&[p], "Paper");
|
||||
assert!(!h.contains("<table>"), "tall two-column text must stay paragraphs: {h}");
|
||||
@@ -675,7 +681,7 @@ fn italic_sentence() -> Vec<Block> {
|
||||
fn an_italic_word_stays_in_its_sentence() {
|
||||
let mut blocks = italic_sentence();
|
||||
blocks.push(block("The next line is a paragraph of its own.", 72.0, 684.0, 300.0, 696.0));
|
||||
let p = Page { width: 612.0, height: 792.0, blocks, images: Vec::new(), background: None };
|
||||
let p = Page { width: 612.0, height: 792.0, blocks, images: Vec::new(), background: None, rules: Vec::new() };
|
||||
let xml = part(&docx(std::slice::from_ref(&p), "Opinion"), "word/document.xml");
|
||||
assert_eq!(
|
||||
word_paragraphs(&xml),
|
||||
@@ -700,7 +706,7 @@ fn an_italic_word_stays_in_its_sentence() {
|
||||
fn a_sentence_keeps_its_reading_order() {
|
||||
let mut blocks = vec![block("Then the next line.", 72.0, 684.0, 200.0, 696.0)];
|
||||
blocks.extend(italic_sentence().into_iter().rev());
|
||||
let p = Page { width: 612.0, height: 792.0, blocks, images: Vec::new(), background: None };
|
||||
let p = Page { width: 612.0, height: 792.0, blocks, images: Vec::new(), background: None, rules: Vec::new() };
|
||||
let xml = part(&docx(std::slice::from_ref(&p), "Opinion"), "word/document.xml");
|
||||
assert_eq!(
|
||||
word_paragraphs(&xml),
|
||||
@@ -721,7 +727,7 @@ fn runs_keep_the_spaces_the_source_had_between_them() {
|
||||
block("E = mc", 72.0, 660.0, 110.0, 672.0),
|
||||
Block { size: 8.0, ..block("2", 110.0, 665.0, 115.0, 673.0) },
|
||||
];
|
||||
let p = Page { width: 612.0, height: 792.0, blocks, images: Vec::new(), background: None };
|
||||
let p = Page { width: 612.0, height: 792.0, blocks, images: Vec::new(), background: None, rules: Vec::new() };
|
||||
let xml = part(&docx(std::slice::from_ref(&p), "Spaces"), "word/document.xml");
|
||||
assert_eq!(
|
||||
word_paragraphs(&xml),
|
||||
@@ -733,7 +739,7 @@ fn runs_keep_the_spaces_the_source_had_between_them() {
|
||||
#[test]
|
||||
fn turned_text_is_not_a_run_of_the_line_beside_it() {
|
||||
let blocks = vec![block("Before", 72.0, 700.0, 110.0, 712.0), Block { rotation: 90.0, ..block("SIDE", 111.0, 690.0, 123.0, 720.0) }];
|
||||
let p = Page { width: 612.0, height: 792.0, blocks, images: Vec::new(), background: None };
|
||||
let p = Page { width: 612.0, height: 792.0, blocks, images: Vec::new(), background: None, rules: Vec::new() };
|
||||
let h = html(std::slice::from_ref(&p), "Turned");
|
||||
assert!(h.contains("<p>Before</p>") && h.contains("<p>SIDE</p>"), "{h}");
|
||||
}
|
||||
@@ -744,7 +750,7 @@ fn a_block_on_the_next_line_starts_a_paragraph() {
|
||||
block("The first line ends here", 72.0, 700.0, 190.0, 712.0),
|
||||
Block { italic: true, ..block("and the next starts there.", 190.5, 690.0, 320.0, 702.0) },
|
||||
];
|
||||
let p = Page { width: 612.0, height: 792.0, blocks, images: Vec::new(), background: None };
|
||||
let p = Page { width: 612.0, height: 792.0, blocks, images: Vec::new(), background: None, rules: Vec::new() };
|
||||
let xml = part(&docx(std::slice::from_ref(&p), "Lines"), "word/document.xml");
|
||||
assert_eq!(word_paragraphs(&xml), vec![runs(&[("The first line ends here", false)]), runs(&[("and the next starts there.", true)])], "{xml}");
|
||||
}
|
||||
@@ -761,7 +767,7 @@ fn table_cells_are_not_runs_of_a_paragraph() {
|
||||
blocks.push(block(&format!("{},000", 30 - 5 * n), 300.0, y, 340.0, y + 12.0));
|
||||
}
|
||||
blocks.extend(italic_sentence().into_iter().map(|b| Block { rect: [b.rect[0], b.rect[1] - 200.0, b.rect[2], b.rect[3] - 200.0], ..b }));
|
||||
let p = Page { width: 612.0, height: 792.0, blocks, images: Vec::new(), background: None };
|
||||
let p = Page { width: 612.0, height: 792.0, blocks, images: Vec::new(), background: None, rules: Vec::new() };
|
||||
let xml = part(&docx(std::slice::from_ref(&p), "Prizes"), "word/document.xml");
|
||||
assert_eq!(xml.matches("<w:tbl>").count(), 1, "{xml}");
|
||||
for cell in ["st", "nd", "rd", "30,000"] {
|
||||
@@ -781,7 +787,7 @@ fn a_paragraph_is_a_heading_only_when_its_text_is() {
|
||||
Block { bold: true, ..block("Summary", 72.0, 700.0, 125.0, 712.0) },
|
||||
block("the year closed with more members than it opened with, and fewer debts.", 128.0, 700.0, 540.0, 712.0),
|
||||
];
|
||||
let p = Page { width: 612.0, height: 792.0, blocks, images: Vec::new(), background: None };
|
||||
let p = Page { width: 612.0, height: 792.0, blocks, images: Vec::new(), background: None, rules: Vec::new() };
|
||||
let xml = part(&docx(std::slice::from_ref(&p), "Report"), "word/document.xml");
|
||||
assert_eq!(xml.matches("<w:pStyle w:val=\"Heading1\"/>").count(), 1, "{xml}");
|
||||
assert!(!xml.contains("Heading2"), "the lead-in made its paragraph a heading: {xml}");
|
||||
@@ -830,6 +836,7 @@ fn markdown_escapes_markup_and_keeps_emphasis_and_tables() {
|
||||
],
|
||||
images: Vec::new(),
|
||||
background: None,
|
||||
rules: Vec::new(),
|
||||
};
|
||||
let md = markdown(&[p]);
|
||||
assert!(md.contains("\\- not a list item"), "{md}");
|
||||
@@ -859,3 +866,36 @@ fn markdown_escapes_markup_and_keeps_emphasis_and_tables() {
|
||||
assert!(rows.contains(&"| A1 | kWh | 37414.00 |"), "{md}");
|
||||
assert!(rows.iter().all(|r| r.matches(" | ").count() == 2), "every row has the header's three cells: {md}");
|
||||
}
|
||||
|
||||
/// #5149: two columns of two rows are a table when ruled lines draw its grid, and the docx keeps
|
||||
/// its borders; the same text without rules (or with rules that only underline it) stays paragraphs.
|
||||
#[test]
|
||||
fn a_ruled_two_by_two_grid_is_a_table() {
|
||||
let blocks = vec![
|
||||
block("Name", 25.0, 250.0, 55.0, 261.0),
|
||||
block("Value", 165.0, 250.0, 195.0, 261.0),
|
||||
block("Alpha", 25.0, 225.0, 55.0, 236.0),
|
||||
block("One", 165.0, 225.0, 185.0, 236.0),
|
||||
];
|
||||
let grid = vec![
|
||||
[20.0, 270.0, 300.0, 270.0],
|
||||
[20.0, 245.0, 300.0, 245.0],
|
||||
[20.0, 220.0, 300.0, 220.0],
|
||||
[20.0, 220.0, 20.0, 270.0],
|
||||
[160.0, 220.0, 160.0, 270.0],
|
||||
[300.0, 220.0, 300.0, 270.0],
|
||||
];
|
||||
let (found, consumed) = tables(&blocks, &grid);
|
||||
assert_eq!(found.len(), 1);
|
||||
assert!(found[0].ruled);
|
||||
assert_eq!(found[0].rows.len(), 2);
|
||||
assert!(consumed.iter().all(|used| *used));
|
||||
let p = Page { width: 320.0, height: 300.0, blocks: blocks.clone(), rules: grid, ..Page::default() };
|
||||
let xml = part(&docx(std::slice::from_ref(&p), "Grid"), "word/document.xml");
|
||||
assert_eq!(xml.matches("<w:tbl>").count(), 1, "{xml}");
|
||||
assert!(xml.contains("w:val=\"single\"") && !xml.contains("w:val=\"nil\""), "{xml}");
|
||||
|
||||
assert!(tables(&blocks, &[]).0.is_empty(), "alignment alone does not make two by two a table");
|
||||
let underlines = [[20.0, 245.0, 300.0, 245.0]];
|
||||
assert!(tables(&blocks, &underlines).0.is_empty(), "a rule between the rows alone is no grid");
|
||||
}
|
||||
@@ -3,7 +3,7 @@
|
||||
PDF stream filters: the decoders and encoders behind `/Filter` and `/DecodeParms`.
|
||||
|
||||
- **Layer:** L0, standalone. No dependency on any other PdfCraft crate. `cos` depends on it (architecture §3 rule 3).
|
||||
- **Licence:** MIT OR Apache-2.0. Clean-room: written from ISO 32000-2 §7.4, RFC 1950/1951 (through `flate2` with the pure-Rust `miniz_oxide` backend), TIFF 6.0 §14 (predictor 2) and RFC 2083 §6 (PNG filters). CCITT Group 4 encoding (ITU-T T.6) is the `fax` crate's (MIT, already in the tree through `tiff`), checked here by round trips through an independent decoder; CCITT decoding (T.4 and T.6) is the `hayro-ccitt` crate's, and JBIG2 decoding the `hayro-jbig2` crate's (both MIT OR Apache-2.0, already in the tree through hayro), bounded here. JBIG2 generic region encoding is written from the public ISO/IEC 14492 Final Committee Draft (WG1 N1359, 1999); Annex H.2 checks the arithmetic coder byte for byte.
|
||||
- **Licence:** MIT OR Apache-2.0. Clean-room: written from ISO 32000-2 §7.4, RFC 1950/1951 (through `flate2` with the pure-Rust `zlib-rs` backend), TIFF 6.0 §14 (predictor 2) and RFC 2083 §6 (PNG filters). CCITT Group 4 encoding (ITU-T T.6) is the `fax` crate's (MIT, already in the tree through `tiff`), checked here by round trips through an independent decoder; CCITT decoding (T.4 and T.6) is the `hayro-ccitt` crate's, and JBIG2 decoding the `hayro-jbig2` crate's (both MIT OR Apache-2.0, already in the tree through hayro), bounded here. JBIG2 generic region encoding is written from the public ISO/IEC 14492 Final Committee Draft (WG1 N1359, 1999); Annex H.2 checks the arithmetic coder byte for byte.
|
||||
|
||||
- `#![forbid(unsafe_code)]`. Builds for `wasm32-unknown-unknown`.
|
||||
|
||||
@@ -38,14 +38,14 @@ encode_jbig2_shared(&[(data, columns, rows)]) -> Result<Option<SharedJbig2>, Fil
|
||||
- Image codecs (DCT, JPX, JBIG2, CCITT), `Crypt` and unknown filters anywhere in a chain give `Unsupported`: callers keep such data encoded. So does a chain longer than `MAX_CHAIN` (8) filters, before any stage runs. Decryption belongs to `crypt`.
|
||||
- `max_output` bounds every intermediate buffer (including the pre-predictor buffer) and gives `LimitExceeded(max_output)`. This also holds when Flate retries raw deflate after a misleading zlib header, in both strict and tolerant decoding.
|
||||
- `decode_counted` and `decode_tolerant_counted` are for a caller charging a budget (`pdfcraft_cos::DecodeBudget`). `max_output` bounds all stages together (each stage gets what the earlier ones left), and they give the bytes every stage that ran decoded, on success and on failure. A stage's output counts as its decoder produced it, before a predictor or a later stage shrinks it, and a failed decode pays for what it decoded first.
|
||||
- `decode_tolerant_within` is for a run of images (`pdfcraft_cos::ImageBudget`), as `decode_within` (its strict form), `decode_jbig2_within` and `decode_ccitt_within` are, all spending from one `work`, in the JBIG2 decoder's steps. `max_output` bounds each stage, as in `decode_tolerant`, and no stage decodes past what `work` has left. It pays a step a byte of `data` first and a step a byte each stage decodes, so a chain that fails has paid for what it did: 0.2 to 3 ns a byte in or out, up to 19 ns through a predictor on samples of a bit, against the 6 to 16 ns of a JBIG2 step. What `work` can't pay for spends all of it, and gives `Spent`; with nothing left nothing is read. A chain that can't be decoded at all costs nothing and gives its usual error.
|
||||
- `decode_tolerant_within` is for a run of images (`pdfcraft_cos::ImageBudget`), as `decode_within` (its strict form), `decode_jbig2_within` and `decode_ccitt_within` are, all spending from one `work`, in the JBIG2 decoder's steps. `max_output` bounds each stage, as in `decode_tolerant`, and no stage decodes past what `work` has left. It pays a step a byte of `data` first and a step a byte each stage decodes, so a chain that fails has paid for what it did: 0.2 to 3 ns a byte in or out, up to 19 ns through a predictor on samples of a bit, against the 6 to 16 ns of a JBIG2 step. A Flate stage also pays `FLATE_READ_WORK` (2) steps a byte it reads, before it runs, and again if it reads them a second time as raw deflate: inflating does work for every block it reads, and a stream of empty dynamic blocks took 21 ns a byte to make nothing, about 7 ns a step at that price. flate2 inflates with its zlib-rs backend, which it prefers to miniz_oxide when other dependencies build that too; miniz_oxide, its backend here before, took 1.4 µs a byte on empty fixed blocks. What `work` can't pay for spends all of it, and gives `Spent`; with nothing left nothing is read. A chain that can't be decoded at all costs nothing and gives its usual error.
|
||||
- `decode_tolerant` turns `Corrupt` into "what was decoded so far" plus `partial = true`, then runs the rest of the chain on it (predictors are applied to partial output too). `LimitExceeded` and `Unsupported` are still errors.
|
||||
|
||||
## Behaviour
|
||||
|
||||
| Filter | Decode | Encode |
|
||||
|---|---|---|
|
||||
| FlateDecode | zlib header checked, then inflated raw: a missing or wrong Adler-32 is tolerated; no valid header → raw deflate; trailing bytes ignored; preset dictionary → Corrupt; truncated → Corrupt (partial in tolerant mode) | zlib level 6 |
|
||||
| FlateDecode | zlib header checked, then inflated raw: a missing or wrong Adler-32 is tolerated; no valid header → raw deflate; trailing bytes ignored; preset dictionary → Corrupt; truncated, a back-reference to before the start of the output, or a dynamic block without an end-of-block code → Corrupt (partial in tolerant mode) | zlib level 6 |
|
||||
| LZWDecode | 9–12-bit MSB-first codes, clear (256), EOD (257), `EarlyChange` 0/1; missing EOD/initial clear tolerated; a full table stops growing | greedy, leading clear, clear-table when the table fills, EOD |
|
||||
| Predictors (Flate/LZW) | 2 = TIFF (1/2/4/8/16 bpc), 10–15 = PNG with per-row tags 0–4; partial final rows decoded; bad params or tags → Corrupt | 2, 10 None, 11 Sub, 12 Up, 13 Average, 14 Paeth, 15 per-row optimum (min sum of signed residuals) |
|
||||
| ASCIIHexDecode | white space ignored, odd digit padded with 0, `>` EOD (optional), other characters → Corrupt | upper case, newline every 64 digits, `>` |
|
||||
|
||||
+145
-14
@@ -5,6 +5,11 @@
|
||||
//! deflate stream is inflated raw after the 2-byte zlib header;
|
||||
//! - streams without a valid zlib header are inflated as raw deflate;
|
||||
//! - data after the end of the deflate stream is ignored.
|
||||
//!
|
||||
//! A back-reference to before the start of the output points at nothing, and is damage, as zlib
|
||||
//! has it: read strictly the stream is refused, and read tolerantly what came before it is kept.
|
||||
//! (miniz_oxide, flate2's backend here before zlib-rs, copied zeros and went on.) So is a dynamic
|
||||
//! block whose code has no end-of-block symbol, and nothing of that block is kept.
|
||||
|
||||
use std::io::Write;
|
||||
|
||||
@@ -21,25 +26,48 @@ fn zlib_header(data: &[u8]) -> Option<(u8, u8)> {
|
||||
ok.then_some((cmf, flg))
|
||||
}
|
||||
|
||||
pub(crate) fn decode(data: &[u8], max: usize) -> Step {
|
||||
/// `data` inflated within `max`, and whether it was read twice: a zlib header that only looked
|
||||
/// valid is read again as raw deflate, within `again`, what a caller paying for what is read has
|
||||
/// left for it once it has paid for the second reading. `None`, that reading can't be paid for,
|
||||
/// and is [`FilterError::Spent`](crate::FilterError::Spent).
|
||||
pub(crate) fn decode(data: &[u8], max: usize, again: Option<usize>) -> (Step, bool) {
|
||||
match zlib_header(data) {
|
||||
Some((_, flg)) if flg & 0x20 != 0 => Err(Failure::corrupt(NAME, "zlib preset dictionary is not allowed in PDF", Vec::new())),
|
||||
Some((_, flg)) if flg & 0x20 != 0 => (Err(Failure::corrupt(NAME, "zlib preset dictionary is not allowed in PDF", Vec::new())), false),
|
||||
Some(_) => match inflate_raw(&data[2..], max) {
|
||||
// A header that only looked valid: retry the whole input as raw deflate.
|
||||
Err(f) if f.partial.is_empty() && matches!(f.error, crate::FilterError::Corrupt { .. }) => match inflate_raw(data, max) {
|
||||
// Keep the original corruption diagnostic only if the retry is corrupt
|
||||
// too. A limit error must remain fatal even for tolerant decoding. What the
|
||||
// retry decoded isn't kept, but a caller charging for work has to hear of it.
|
||||
Err(retry) if matches!(retry.error, crate::FilterError::Corrupt { .. }) => Err(Failure { discarded: retry.partial.len(), ..f }),
|
||||
retry => retry,
|
||||
},
|
||||
r => r,
|
||||
Err(f) if f.partial.is_empty() && matches!(f.error, crate::FilterError::Corrupt { .. }) => {
|
||||
let Some(again) = again else {
|
||||
return (Err(Failure { error: crate::FilterError::Spent, partial: Vec::new(), discarded: 0 }), false);
|
||||
};
|
||||
let step = match inflate_raw(data, again) {
|
||||
// Keep the original corruption diagnostic only if the retry is corrupt
|
||||
// too. A limit error must remain fatal even for tolerant decoding. What the
|
||||
// retry decoded isn't kept, but a caller charging for work has to hear of it.
|
||||
Err(retry) if matches!(retry.error, crate::FilterError::Corrupt { .. }) => Err(Failure { discarded: retry.partial.len(), ..f }),
|
||||
retry => retry,
|
||||
};
|
||||
(step, true)
|
||||
}
|
||||
r => (r, false),
|
||||
},
|
||||
None => inflate_raw(data, max),
|
||||
None => (inflate_raw(data, max), false),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// Bytes inflating gave back on this thread, its partial output included.
|
||||
pub(crate) static INFLATED: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
fn inflate_raw(input: &[u8], max: usize) -> Step {
|
||||
let step = inflate(input, max);
|
||||
#[cfg(test)]
|
||||
INFLATED.with(|c| c.set(c.get() + step.as_ref().map_or_else(|f| f.partial.len(), Vec::len)));
|
||||
step
|
||||
}
|
||||
|
||||
fn inflate(input: &[u8], max: usize) -> Step {
|
||||
let mut d = Decompress::new(false);
|
||||
let mut out: Vec<u8> = Vec::new();
|
||||
// One byte beyond the limit lets us tell "exactly max" from "more than max".
|
||||
@@ -87,7 +115,7 @@ mod tests {
|
||||
use crate::FilterError;
|
||||
|
||||
fn dec(d: &[u8]) -> Result<Vec<u8>, FilterError> {
|
||||
decode(d, 1 << 24).map_err(|f| f.error)
|
||||
decode(d, 1 << 24, Some(1 << 24)).0.map_err(|f| f.error)
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -144,7 +172,7 @@ mod tests {
|
||||
fn corrupt_and_truncated() {
|
||||
let data: Vec<u8> = (0..10_000u32).map(|i| (i % 13) as u8).collect();
|
||||
let z = encode(&data);
|
||||
match decode(&z[..z.len() / 2], 1 << 24) {
|
||||
match decode(&z[..z.len() / 2], 1 << 24, Some(1 << 24)).0 {
|
||||
Err(f) => {
|
||||
assert!(matches!(f.error, FilterError::Corrupt { .. }));
|
||||
assert_eq!(&data[..f.partial.len()], &f.partial[..]);
|
||||
@@ -155,6 +183,8 @@ mod tests {
|
||||
assert!(matches!(dec(&[0x78, 0x9c, 0x07, 0, 0, 0]), Err(FilterError::Corrupt { .. })));
|
||||
// Preset dictionary.
|
||||
assert!(matches!(dec(&[0x78, 0x20, 0, 0, 0, 0]), Err(FilterError::Corrupt { .. })));
|
||||
// One whose header is followed by data that inflates: refused all the same.
|
||||
assert!(matches!(dec(&[0x78, 0xBB, 0x4b, 0x04, 0x00]), Err(FilterError::Corrupt { .. })));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -168,6 +198,107 @@ mod tests {
|
||||
}
|
||||
|
||||
fn dec_limit(d: &[u8], max: usize) -> Result<Vec<u8>, FilterError> {
|
||||
decode(d, max).map_err(|f| f.error)
|
||||
decode(d, max, Some(max)).0.map_err(|f| f.error)
|
||||
}
|
||||
|
||||
/// Deflate's bits: header fields and extra bits least significant first, Huffman codes most
|
||||
/// significant first (RFC 1951 §3.1.1).
|
||||
#[derive(Default)]
|
||||
struct Bits {
|
||||
out: Vec<u8>,
|
||||
acc: u32,
|
||||
n: u32,
|
||||
}
|
||||
|
||||
impl Bits {
|
||||
fn put(&mut self, value: u32, len: u32) {
|
||||
for i in 0..len {
|
||||
self.acc |= ((value >> i) & 1) << self.n;
|
||||
self.n += 1;
|
||||
if self.n == 8 {
|
||||
self.out.push(self.acc as u8);
|
||||
(self.acc, self.n) = (0, 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn code(&mut self, code: u32, len: u32) {
|
||||
for i in (0..len).rev() {
|
||||
self.put((code >> i) & 1, 1);
|
||||
}
|
||||
}
|
||||
|
||||
fn finish(mut self) -> Vec<u8> {
|
||||
if self.n > 0 {
|
||||
self.out.push(self.acc as u8);
|
||||
}
|
||||
self.out
|
||||
}
|
||||
}
|
||||
|
||||
/// A dynamic block whose literal and length code has no end-of-block symbol can't end (RFC 1951
|
||||
/// §3.2.5): it is refused, and nothing of it is kept.
|
||||
#[test]
|
||||
fn a_dynamic_code_without_an_end_is_damage() {
|
||||
let mut bits = Bits::default();
|
||||
bits.put(1, 1); // the final block,
|
||||
bits.put(2, 2); // dynamic Huffman codes (§3.2.7)
|
||||
bits.put(0, 5); // 257 literal and length codes
|
||||
bits.put(0, 5); // 1 distance code
|
||||
bits.put(14, 4); // 18 code length codes, in their order up to the one for 1
|
||||
for symbol in [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1] {
|
||||
bits.put(u32::from(symbol == 18 || symbol == 1), 3);
|
||||
}
|
||||
// Code length codes: 1 is 0, 18 is 1. 'A' and 'B' get a bit each, 256 none.
|
||||
let zeros = |bits: &mut Bits, n: u32| {
|
||||
bits.code(1, 1);
|
||||
bits.put(n - 11, 7);
|
||||
};
|
||||
zeros(&mut bits, 65);
|
||||
bits.code(0, 1);
|
||||
bits.code(0, 1);
|
||||
zeros(&mut bits, 138);
|
||||
zeros(&mut bits, 52);
|
||||
bits.code(0, 1); // the distance code: a bit
|
||||
for _ in 0..4 {
|
||||
bits.code(0, 1); // 'A'
|
||||
}
|
||||
let data = bits.finish();
|
||||
assert!(zlib_header(&data).is_none(), "read as raw deflate");
|
||||
match decode(&data, 1 << 20, Some(1 << 20)).0 {
|
||||
Err(f) => {
|
||||
assert!(matches!(f.error, FilterError::Corrupt { .. }), "{}", f.error);
|
||||
assert_eq!(f.partial, b"");
|
||||
}
|
||||
Ok(out) => panic!("read as {out:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// A back-reference to before the start of the output points at nothing: read strictly the
|
||||
/// stream is refused, and what came before it is what a tolerant reading keeps. miniz_oxide,
|
||||
/// flate2's backend here before zlib-rs, copied zeros and went on, so this also shows which
|
||||
/// backend inflates (the price of reading Flate, `FLATE_READ_WORK`, is set for zlib-rs).
|
||||
#[test]
|
||||
fn a_copy_from_before_the_start_is_damage() {
|
||||
let literal = |bits: &mut Bits, b: u8| bits.code(0x30 + u32::from(b), 8);
|
||||
let mut bits = Bits::default();
|
||||
bits.put(1, 1); // the final block,
|
||||
bits.put(1, 2); // fixed Huffman codes (§3.2.6)
|
||||
literal(&mut bits, b'A');
|
||||
literal(&mut bits, b'B');
|
||||
bits.code(1, 7); // length 3
|
||||
bits.code(4, 5); // distance 5 (code 4 and an extra bit of 0), three bytes before the start
|
||||
bits.put(0, 1);
|
||||
literal(&mut bits, b'C');
|
||||
bits.code(0, 7); // end of block
|
||||
let data = bits.finish();
|
||||
assert!(zlib_header(&data).is_none(), "read as raw deflate");
|
||||
match decode(&data, 1 << 20, Some(1 << 20)).0 {
|
||||
Err(f) => {
|
||||
assert!(matches!(f.error, FilterError::Corrupt { .. }), "{}", f.error);
|
||||
assert_eq!(f.partial, b"AB");
|
||||
}
|
||||
Ok(out) => panic!("read as {out:?}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
+130
-32
@@ -189,7 +189,7 @@ pub(crate) fn pay(work: &mut u64, steps: u64) -> Result<(), FilterError> {
|
||||
/// [`FilterError::Unsupported`] (callers keep such data encoded), as does a chain longer than
|
||||
/// [`MAX_CHAIN`]. `max_output` bounds every intermediate buffer.
|
||||
pub fn decode(chain: &[(Filter, Params)], data: &[u8], max_output: usize) -> Result<Vec<u8>, FilterError> {
|
||||
run(chain, data, max_output, None, true).map(|(v, _, _)| v).map_err(|(e, _)| e)
|
||||
run(chain, data, max_output, None, true, false).map(|(v, _, _)| v).map_err(|(e, _)| e)
|
||||
}
|
||||
|
||||
/// Like [`decode`] for a caller charging an allowance: `max_output` bounds the bytes all stages
|
||||
@@ -197,27 +197,28 @@ pub fn decode(chain: &[(Filter, Params)], data: &[u8], max_output: usize) -> Res
|
||||
/// bytes, on success and on failure. A stage's output counts even when a later stage or its
|
||||
/// predictor shrinks it.
|
||||
pub fn decode_counted(chain: &[(Filter, Params)], data: &[u8], max_output: usize) -> Result<(Vec<u8>, usize), (FilterError, usize)> {
|
||||
run(chain, data, max_output, Some(max_output), true).map(|(v, _, spent)| (v, spent))
|
||||
run(chain, data, max_output, Some(max_output), true, false).map(|(v, _, spent)| (v, spent))
|
||||
}
|
||||
|
||||
/// Like [`decode`], but on corrupt data returns what was decoded before the error and
|
||||
/// reports `partial = true` (the behaviour viewers expect). The remaining filters of the
|
||||
/// chain still run on the partial data. Limit and unsupported errors are still errors.
|
||||
pub fn decode_tolerant(chain: &[(Filter, Params)], data: &[u8], max_output: usize) -> Result<(Vec<u8>, bool), FilterError> {
|
||||
run(chain, data, max_output, None, false).map(|(v, partial, _)| (v, partial)).map_err(|(e, _)| e)
|
||||
run(chain, data, max_output, None, false, false).map(|(v, partial, _)| (v, partial)).map_err(|(e, _)| e)
|
||||
}
|
||||
|
||||
/// [`decode_tolerant`] bounded and counted as [`decode_counted`] is.
|
||||
pub fn decode_tolerant_counted(chain: &[(Filter, Params)], data: &[u8], max_output: usize) -> Result<(Vec<u8>, bool, usize), (FilterError, usize)> {
|
||||
run(chain, data, max_output, Some(max_output), false)
|
||||
run(chain, data, max_output, Some(max_output), false, false)
|
||||
}
|
||||
|
||||
/// [`decode_tolerant`], spending from `work`, what decoding may still cost across a run of images:
|
||||
/// a step for each byte of `data`, paid before anything is decoded, and one for each byte a stage
|
||||
/// decodes, so a chain that fails, or a stage that goes past `max_output`, has paid for what it did.
|
||||
/// No stage decodes past what is left: a chain that `work` can't pay for spends all of it and stops
|
||||
/// there, so with nothing left nothing is read. A chain that can't be decoded at all costs nothing,
|
||||
/// whatever is left, so what an image's filters are is known from the error.
|
||||
/// a step for each byte of `data`, paid before anything is decoded, [`FLATE_READ_WORK`] for each
|
||||
/// byte a Flate stage reads, paid before it runs (again if it reads them twice), and one for each
|
||||
/// byte a stage decodes, so a chain that fails, or a stage that goes past `max_output`, has paid for
|
||||
/// what it did. No stage decodes past what is left: a chain that `work` can't pay for spends all of
|
||||
/// it and stops there, so with nothing left nothing is read. A chain that can't be decoded at all
|
||||
/// costs nothing, whatever is left, so what an image's filters are is known from the error.
|
||||
///
|
||||
/// Unlike [`decode_tolerant`], no filters at all gives `data` itself, within `max_output`.
|
||||
pub fn decode_tolerant_within(chain: &[(Filter, Params)], data: &[u8], max_output: usize, work: &mut u64) -> Result<Vec<u8>, FilterError> {
|
||||
@@ -237,14 +238,15 @@ fn spending(chain: &[(Filter, Params)], data: &[u8], max_output: usize, work: &m
|
||||
return if data.len() > max_output { Err(FilterError::LimitExceeded(max_output)) } else { Ok(data.to_vec()) };
|
||||
}
|
||||
let left = usize::try_from(*work).unwrap_or(usize::MAX);
|
||||
match run(chain, data, max_output, Some(left), strict) {
|
||||
match run(chain, data, max_output, Some(left), strict, true) {
|
||||
Ok((out, _, decoded)) => pay(work, decoded as u64).map(|()| out),
|
||||
// The stage stopped at the lower of the two, which took as much to find out.
|
||||
Err((FilterError::LimitExceeded(_), decoded)) if left.saturating_sub(decoded) > max_output => {
|
||||
pay(work, (decoded as u64).saturating_add(max_output as u64))?;
|
||||
Err(FilterError::LimitExceeded(max_output))
|
||||
}
|
||||
Err((FilterError::LimitExceeded(_), _)) => {
|
||||
// Past what is left, a stage stops, or a Flate stage doesn't start.
|
||||
Err((FilterError::LimitExceeded(_) | FilterError::Spent, _)) => {
|
||||
*work = 0;
|
||||
Err(FilterError::Spent)
|
||||
}
|
||||
@@ -256,6 +258,20 @@ fn spending(chain: &[(Filter, Params)], data: &[u8], max_output: usize, work: &m
|
||||
/// up to the output limit, so the chain length multiplies the work.
|
||||
pub const MAX_CHAIN: usize = 8;
|
||||
|
||||
/// The steps each byte Flate reads costs where decoding is paid for ([`decode_tolerant_within`],
|
||||
/// [`decode_within`]), besides the step it was paid as input and a step for each byte it makes.
|
||||
/// Inflating does work for every block it reads, whether or not the block makes anything: an empty
|
||||
/// fixed-Huffman block is ten bits (RFC 1951 §3.2.6). With flate2's zlib-rs backend (zlib-rs
|
||||
/// 0.6.8, release build) the slowest blocks measured, empty dynamic ones, took 21 ns a byte read
|
||||
/// to make nothing, empty fixed ones 9 and fixed ones of a literal each 6, so at this price the
|
||||
/// worst per byte read comes to about 7 ns a step, inside what a step of JBIG2 decoding takes.
|
||||
/// (miniz_oxide 0.9.1, flate2's backend here before, took about 1.7 µs for every fixed-Huffman
|
||||
/// block, empty or not: 1,383 ns a byte read on empty ones.) A stage's start isn't priced, about
|
||||
/// 0.25 µs: every way to repeat one takes bytes of the file, so what starts cost is bounded by the
|
||||
/// file's length. Data a real encoder makes took 0.2 to 2.3 ns a byte made, its reading included, so
|
||||
/// an image pays twice its stored length more than it would unpriced.
|
||||
pub const FLATE_READ_WORK: u64 = 2;
|
||||
|
||||
/// Whether a chain is one [`run`] takes, and if not, the error.
|
||||
fn decodable(chain: &[(Filter, Params)]) -> Result<(), FilterError> {
|
||||
if chain.len() > MAX_CHAIN {
|
||||
@@ -269,22 +285,39 @@ fn decodable(chain: &[(Filter, Params)]) -> Result<(), FilterError> {
|
||||
|
||||
/// The decoded data, whether it is partial and the bytes all stages decoded, or the error and
|
||||
/// the bytes decoded before it. `max` bounds each stage, and `total` all of them together.
|
||||
/// `priced`, the count is steps: each Flate stage also pays [`FLATE_READ_WORK`] for each byte it
|
||||
/// reads, before it runs, so a stage `total` can't pay for doesn't run
|
||||
/// ([`FilterError::Spent`]).
|
||||
fn run(
|
||||
chain: &[(Filter, Params)],
|
||||
data: &[u8],
|
||||
max: usize,
|
||||
total: Option<usize>,
|
||||
strict: bool,
|
||||
priced: bool,
|
||||
) -> Result<(Vec<u8>, bool, usize), (FilterError, usize)> {
|
||||
decodable(chain).map_err(|e| (e, 0))?;
|
||||
let mut cur: Cow<[u8]> = Cow::Borrowed(data);
|
||||
let mut partial = false;
|
||||
let mut spent = 0usize;
|
||||
let price = usize::try_from(FLATE_READ_WORK).unwrap_or(usize::MAX);
|
||||
for (filter, params) in chain {
|
||||
let read = if priced && matches!(filter, Filter::Flate) { price.saturating_mul(cur.len()) } else { 0 };
|
||||
let room = total.map_or(usize::MAX, |total| total.saturating_sub(spent));
|
||||
if read > room {
|
||||
return Err((FilterError::Spent, spent));
|
||||
}
|
||||
spent = spent.saturating_add(read);
|
||||
#[cfg(test)]
|
||||
STAGE_BYTES.with(|c| c.set(c.get() + cur.len()));
|
||||
let limit = total.map_or(max, |total| max.min(total.saturating_sub(spent)));
|
||||
let (step, work) = decode_one(filter, params, &cur, limit);
|
||||
// A second reading of the same bytes (Flate's raw retry) is paid for as the first was, and
|
||||
// makes no more than is left once it has been.
|
||||
let again = room.checked_sub(read.saturating_mul(2)).map(|left| max.min(left));
|
||||
let (step, work, again) = decode_one(filter, params, &cur, limit, again);
|
||||
if again {
|
||||
spent = spent.saturating_add(read);
|
||||
}
|
||||
spent = spent.saturating_add(work);
|
||||
cur = Cow::Owned(match step {
|
||||
Ok(v) => v,
|
||||
@@ -299,15 +332,21 @@ fn run(
|
||||
Ok((cur.into_owned(), partial, spent))
|
||||
}
|
||||
|
||||
/// One stage's result and the bytes its decoder produced (before any predictor).
|
||||
fn decode_one(filter: &Filter, params: &Params, data: &[u8], max: usize) -> (Step, usize) {
|
||||
/// One stage's result, the bytes its decoder produced (before any predictor), and whether it
|
||||
/// read its input twice, which it does only within `again` ([`flate::decode`]).
|
||||
fn decode_one(filter: &Filter, params: &Params, data: &[u8], max: usize, again: Option<usize>) -> (Step, usize, bool) {
|
||||
let once = |(step, n): (Step, usize)| (step, n, false);
|
||||
match filter {
|
||||
Filter::Flate => with_predictor(flate::decode(data, max), params, "FlateDecode"),
|
||||
Filter::Lzw => with_predictor(lzw::decode(data, params.early_change != 0, max), params, "LZWDecode"),
|
||||
Filter::AsciiHex => counted(asciihex::decode(data, max)),
|
||||
Filter::Ascii85 => counted(ascii85::decode(data, max)),
|
||||
Filter::RunLength => counted(runlength::decode(data, max)),
|
||||
other => (Err(Failure { error: FilterError::Unsupported(other.name().to_owned()), partial: Vec::new(), discarded: 0 }), 0),
|
||||
Filter::Flate => {
|
||||
let (step, twice) = flate::decode(data, max, again);
|
||||
let (step, n) = with_predictor(step, params, "FlateDecode");
|
||||
(step, n, twice)
|
||||
}
|
||||
Filter::Lzw => once(with_predictor(lzw::decode(data, params.early_change != 0, max), params, "LZWDecode")),
|
||||
Filter::AsciiHex => once(counted(asciihex::decode(data, max))),
|
||||
Filter::Ascii85 => once(counted(ascii85::decode(data, max))),
|
||||
Filter::RunLength => once(counted(runlength::decode(data, max))),
|
||||
other => (Err(Failure { error: FilterError::Unsupported(other.name().to_owned()), partial: Vec::new(), discarded: 0 }), 0, false),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -553,7 +592,7 @@ mod tests {
|
||||
let data = encode_flate(&hex);
|
||||
let chain = [(Filter::Flate, Params::default()), (Filter::AsciiHex, Params::default())];
|
||||
let whole = decode(&chain, &data, 1 << 20).unwrap();
|
||||
let cost = (data.len() + hex.len() + whole.len()) as u64;
|
||||
let cost = (data.len() + hex.len() + whole.len()) as u64 + FLATE_READ_WORK * data.len() as u64;
|
||||
let mut work = u64::MAX;
|
||||
assert_eq!(decode_tolerant_within(&chain, &data, 1 << 20, &mut work).unwrap(), whole);
|
||||
assert_eq!(u64::MAX - work, cost);
|
||||
@@ -585,8 +624,11 @@ mod tests {
|
||||
assert_eq!(work, 0);
|
||||
super::STAGE_BYTES.with(|c| c.get())
|
||||
};
|
||||
assert_eq!(read((bomb.len() + inner.len()) as u64 + 10), bomb.len() + inner.len(), "the second stage stops");
|
||||
assert_eq!(read(bomb.len() as u64 + 10), bomb.len(), "the first stops, and the second never runs");
|
||||
let paid = |n: usize| (1 + FLATE_READ_WORK) * n as u64;
|
||||
assert_eq!(read(paid(bomb.len()) + paid(inner.len()) + 10), bomb.len() + inner.len(), "the second stage stops");
|
||||
assert_eq!(read(paid(bomb.len()) + FLATE_READ_WORK * inner.len() as u64 - 1), bomb.len(), "the second can't pay to read");
|
||||
assert_eq!(read(paid(bomb.len()) + 10), bomb.len(), "the first stops, and the second never runs");
|
||||
assert_eq!(read(paid(bomb.len()) - 1), 0, "the first can't pay to read");
|
||||
assert_eq!(read(bomb.len() as u64 - 1), 0, "it can't pay to be read");
|
||||
}
|
||||
|
||||
@@ -598,18 +640,19 @@ mod tests {
|
||||
let chain = [(Filter::Flate, Params::default())];
|
||||
let mut work = u64::MAX;
|
||||
assert!(matches!(decode_tolerant_within(&chain, &data, 1000, &mut work), Err(FilterError::LimitExceeded(1000))));
|
||||
assert_eq!(u64::MAX - work, data.len() as u64 + 1000);
|
||||
let read = |n: usize| FLATE_READ_WORK * n as u64;
|
||||
assert_eq!(u64::MAX - work, data.len() as u64 + read(data.len()) + 1000);
|
||||
// The later stage of two, which pays for the first as well.
|
||||
let bomb = encode_flate(&data);
|
||||
let two = [(Filter::Flate, Params::default()), (Filter::Flate, Params::default())];
|
||||
let mut work = u64::MAX;
|
||||
assert!(matches!(decode_tolerant_within(&two, &bomb, data.len(), &mut work), Err(FilterError::LimitExceeded(_))));
|
||||
assert_eq!(u64::MAX - work, (bomb.len() + 2 * data.len()) as u64);
|
||||
assert_eq!(u64::MAX - work, (bomb.len() + 2 * data.len()) as u64 + read(bomb.len()) + read(data.len()));
|
||||
// Both limits at once: a run that can't go on is what a caller needs to hear.
|
||||
let mut work = data.len() as u64 + 1000;
|
||||
let mut work = data.len() as u64 + read(data.len()) + 1000;
|
||||
assert!(refused(&decode_tolerant_within(&chain, &data, 1000, &mut work).unwrap_err()));
|
||||
assert_eq!(work, 0);
|
||||
let mut work = data.len() as u64 + 1001;
|
||||
let mut work = data.len() as u64 + read(data.len()) + 1001;
|
||||
assert!(matches!(decode_tolerant_within(&chain, &data, 1000, &mut work), Err(FilterError::LimitExceeded(1000))));
|
||||
assert_eq!(work, 1, "the image's limit, with a step to spare");
|
||||
}
|
||||
@@ -625,21 +668,22 @@ mod tests {
|
||||
assert!(!partial.is_empty());
|
||||
let mut work = u64::MAX;
|
||||
assert_eq!(decode_tolerant_within(&chain, &cut, 1 << 20, &mut work).unwrap(), partial);
|
||||
assert_eq!(u64::MAX - work, (cut.len() + partial.len()) as u64);
|
||||
let read = |n: usize| FLATE_READ_WORK * n as u64;
|
||||
assert_eq!(u64::MAX - work, (cut.len() + partial.len()) as u64 + read(cut.len()));
|
||||
// Read strictly it is an error, for the same work.
|
||||
let mut work = u64::MAX;
|
||||
assert!(matches!(decode_within(&chain, &cut, 1 << 20, &mut work), Err(FilterError::Corrupt { .. })));
|
||||
assert_eq!(u64::MAX - work, (cut.len() + partial.len()) as u64);
|
||||
assert_eq!(u64::MAX - work, (cut.len() + partial.len()) as u64 + read(cut.len()));
|
||||
let whole = encode_flate(&data);
|
||||
let mut work = u64::MAX;
|
||||
assert_eq!(decode_within(&chain, &whole, 1 << 20, &mut work).unwrap(), data);
|
||||
assert_eq!(u64::MAX - work, (whole.len() + data.len()) as u64);
|
||||
assert_eq!(u64::MAX - work, (whole.len() + data.len()) as u64 + read(whole.len()));
|
||||
// A predictor that comes to nothing, after all of this was inflated for it.
|
||||
let p = Params { predictor: 99, ..Params::default() };
|
||||
let data = encode_flate(&vec![0; 1 << 16]);
|
||||
let mut work = u64::MAX;
|
||||
assert!(decode_tolerant_within(&[(Filter::Flate, p)], &data, 1 << 20, &mut work).unwrap().is_empty());
|
||||
assert_eq!(u64::MAX - work, data.len() as u64 + (1 << 16));
|
||||
assert_eq!(u64::MAX - work, data.len() as u64 + read(data.len()) + (1 << 16));
|
||||
}
|
||||
|
||||
/// A stream that reads as zlib only until it fails, and as raw deflate until that fails too,
|
||||
@@ -661,13 +705,67 @@ mod tests {
|
||||
assert_eq!(spent, 0x0601);
|
||||
let mut work = u64::MAX;
|
||||
assert!(decode_tolerant_within(&chain, &data, 1 << 20, &mut work).unwrap().is_empty());
|
||||
assert_eq!(u64::MAX - work, (data.len() + 0x0601) as u64);
|
||||
// Read twice: as zlib, then as raw deflate.
|
||||
assert_eq!(u64::MAX - work, (data.len() + 0x0601) as u64 + 2 * FLATE_READ_WORK * data.len() as u64);
|
||||
// Through a predictor, which would otherwise lose the count.
|
||||
let p = Params { predictor: 12, columns: 4, ..Params::default() };
|
||||
let (_, _, spent) = decode_tolerant_counted(&[(Filter::Flate, p)], &data, 1 << 20).unwrap();
|
||||
assert_eq!(spent, 0x0601);
|
||||
}
|
||||
|
||||
/// Inflating does work for every block it reads, whether or not the block makes anything: empty
|
||||
/// fixed-Huffman blocks, ten bits each, make nothing however many there are. Each byte of them
|
||||
/// is paid for at Flate's price before any is read.
|
||||
#[test]
|
||||
fn a_flate_stage_pays_for_what_it_reads() {
|
||||
// Four empty blocks in five bytes, as raw deflate, then an empty final block.
|
||||
let mut hollow = [0x02, 0x08, 0x20, 0x80, 0x00].repeat(1 << 12);
|
||||
hollow.extend([0x03, 0x00]);
|
||||
let chain = [(Filter::Flate, Params::default())];
|
||||
assert_eq!(decode(&chain, &hollow, 1 << 20).unwrap(), b"");
|
||||
let cost = (1 + FLATE_READ_WORK) * hollow.len() as u64;
|
||||
let mut work = u64::MAX;
|
||||
assert_eq!(decode_tolerant_within(&chain, &hollow, 1 << 20, &mut work).unwrap(), b"");
|
||||
assert_eq!(u64::MAX - work, cost);
|
||||
let mut work = cost;
|
||||
assert!(decode_tolerant_within(&chain, &hollow, 1 << 20, &mut work).is_ok(), "exactly enough");
|
||||
assert_eq!(work, 0);
|
||||
super::STAGE_BYTES.with(|c| c.set(0));
|
||||
let mut work = cost - 1;
|
||||
assert!(refused(&decode_tolerant_within(&chain, &hollow, 1 << 20, &mut work).unwrap_err()));
|
||||
assert_eq!((work, super::STAGE_BYTES.with(|c| c.get())), (0, 0), "nothing was inflated");
|
||||
// Counted for a byte allowance, as a page's content is, reading costs nothing.
|
||||
assert_eq!(decode_counted(&chain, &hollow, 1 << 20).unwrap(), (Vec::new(), 0));
|
||||
}
|
||||
|
||||
/// A zlib header that only looked valid is read again as raw deflate, and the second reading
|
||||
/// is paid for as the first was. One that can't be paid for is refused, not read as damaged.
|
||||
#[test]
|
||||
fn a_second_reading_is_paid_for() {
|
||||
// As zlib: a block of a reserved type at once. As raw deflate: a stored block of this many
|
||||
// zero bytes, then an empty final block.
|
||||
let mut data = vec![0x78, 0x01, 0x06, 0xFE, 0xF9];
|
||||
data.extend(vec![0u8; 0x0601]);
|
||||
data.extend([0x03, 0x00]);
|
||||
let chain = [(Filter::Flate, Params::default())];
|
||||
assert_eq!(decode(&chain, &data, 1 << 20).unwrap(), vec![0u8; 0x0601]);
|
||||
let read = FLATE_READ_WORK * data.len() as u64;
|
||||
let mut work = (data.len() + 0x0601) as u64 + 2 * read;
|
||||
assert_eq!(decode_tolerant_within(&chain, &data, 1 << 20, &mut work).unwrap(), vec![0u8; 0x0601]);
|
||||
assert_eq!(work, 0, "exactly enough");
|
||||
// Enough to read it once and not twice: it isn't read again.
|
||||
super::flate::INFLATED.with(|c| c.set(0));
|
||||
let mut work = data.len() as u64 + 2 * read - 1;
|
||||
assert!(refused(&decode_tolerant_within(&chain, &data, 1 << 20, &mut work).unwrap_err()));
|
||||
assert_eq!((work, super::flate::INFLATED.with(|c| c.get())), (0, 0));
|
||||
// Enough to read it twice, and a byte short of what it makes: the second reading makes no
|
||||
// more than is left once it has been paid for.
|
||||
super::flate::INFLATED.with(|c| c.set(0));
|
||||
let mut work = (data.len() + 0x0601) as u64 + 2 * read - 1;
|
||||
assert!(refused(&decode_tolerant_within(&chain, &data, 1 << 20, &mut work).unwrap_err()));
|
||||
assert!(super::flate::INFLATED.with(|c| c.get()) < 0x0601, "it stopped short");
|
||||
}
|
||||
|
||||
/// With nothing left nothing is read. What can't be decoded at all never costs anything, and
|
||||
/// says so whatever is left. Without filters, what is read is the data.
|
||||
#[test]
|
||||
|
||||
@@ -31,7 +31,7 @@ pub use script::{
|
||||
script_missing, script_outline,
|
||||
};
|
||||
pub use shaping::{
|
||||
ShapedCluster, ShapedScript, arabic_glyph, arabic_has, hebrew_has, shape_arabic, shape_hebrew, shape_thai, shaped_glyph, thai_has,
|
||||
ShapedCluster, ShapedScript, arabic_glyph, arabic_has, face_glyph, hebrew_has, shape_arabic, shape_hebrew, shape_thai, shaped_glyph, thai_has,
|
||||
};
|
||||
pub use std14::Std14;
|
||||
|
||||
|
||||
@@ -156,13 +156,13 @@ fn cids_with_outlines(doc: &Document, font: &Dict) -> Vec<u64> {
|
||||
let Some(program) = dict(doc, descendant.get(b"FontDescriptor")).and_then(|d| d.get(b"FontFile2").cloned()) else { return Vec::new() };
|
||||
let program = doc.resolve(&program);
|
||||
let Object::Stream(stream) = program.as_ref() else { return Vec::new() };
|
||||
let Ok(bytes) = stream.decoded_within(16 << 20) else { return Vec::new() };
|
||||
let Ok(bytes) = doc.with_direct_parms(stream).decoded_within(16 << 20) else { return Vec::new() };
|
||||
let Some(loca) = skrifa::FontRef::from_index(&bytes, 0).ok().and_then(|face| face.loca(None).ok()) else { return Vec::new() };
|
||||
let outlined = |gid: u32| loca.get_raw(gid as usize).zip(loca.get_raw(gid as usize + 1)).is_some_and(|(start, end)| end > start);
|
||||
match descendant.get(b"CIDToGIDMap").map(|o| doc.resolve(o)).as_deref() {
|
||||
None | Some(Object::Name(_)) => bit_set_below_64k((0..loca.len().min(0x1_0000) as u32).filter(|&gid| outlined(gid))),
|
||||
Some(Object::Stream(map)) => {
|
||||
let Ok(map) = map.decoded_within(1 << 17) else { return Vec::new() };
|
||||
let Ok(map) = doc.with_direct_parms(map).decoded_within(1 << 17) else { return Vec::new() };
|
||||
bit_set_below_64k(
|
||||
map.as_chunks::<2>()
|
||||
.0
|
||||
@@ -189,7 +189,7 @@ fn embedded_widths(doc: &Document, font: &Dict, m: &mut Metrics) {
|
||||
let Some(object) = descriptor.get(key) else { continue };
|
||||
let object = doc.resolve(object);
|
||||
let Object::Stream(stream) = object.as_ref() else { continue };
|
||||
let Ok(bytes) = stream.decoded_within(16 << 20) else { continue };
|
||||
let Ok(bytes) = doc.with_direct_parms(stream).decoded_within(16 << 20) else { continue };
|
||||
let Ok(face) = skrifa::FontRef::from_index(&bytes, 0) else { continue };
|
||||
let upem = f64::from(face.metrics(Size::unscaled(), LocationRef::default()).units_per_em);
|
||||
if upem == 0.0 {
|
||||
@@ -691,7 +691,7 @@ impl Metrics {
|
||||
m.codes = Codes::Two;
|
||||
if let Some(e) = font.get(b"Encoding").map(|e| doc.resolve(e))
|
||||
&& let Object::Stream(s) = &*e
|
||||
&& let Ok(data) = s.decoded_within(MAX_CMAP_BYTES)
|
||||
&& let Ok(data) = doc.with_direct_parms(s).decoded_within(MAX_CMAP_BYTES)
|
||||
{
|
||||
let (spaces, cids) = parse_cmap(&data);
|
||||
if !spaces.is_empty() {
|
||||
@@ -1293,7 +1293,10 @@ fn unicode_map(doc: &Document, font: &Dict, composite: bool) -> Unicode {
|
||||
}
|
||||
match font.get(b"ToUnicode").map(|t| doc.resolve(t)).as_deref() {
|
||||
Some(Object::Stream(s)) => {
|
||||
if let Ok(data) = s.decoded_within(MAX_CMAP_BYTES) {
|
||||
// With `/DecodeParms` given by reference, as every stream of the font is read here,
|
||||
// and as the redaction proof reads the map: the two must get the same text, or a copy
|
||||
// redaction rightly left counts as a survivor.
|
||||
if let Ok(data) = doc.with_direct_parms(s).decoded_within(MAX_CMAP_BYTES) {
|
||||
parse_to_unicode(&data, &mut out);
|
||||
}
|
||||
}
|
||||
|
||||
+115
-18
@@ -104,6 +104,18 @@ fn font(doc: &mut Document, entries: Vec<(&str, Object)>) -> Dict {
|
||||
d
|
||||
}
|
||||
|
||||
/// `data` behind Flate and a PNG predictor whose `/DecodeParms` is a reference: read without
|
||||
/// it, every row of four bytes keeps its tag byte.
|
||||
fn behind_parms_by_reference(doc: &mut Document, data: &[u8]) -> Object {
|
||||
let parms = doc.add(Object::Dict(Dict::from_iter([(b"Predictor".to_vec(), Object::Int(12)), (b"Columns".to_vec(), Object::Int(4))])));
|
||||
let mut data = data.to_vec();
|
||||
data.resize(data.len().next_multiple_of(4), 0);
|
||||
let rows: Vec<u8> = data.chunks(4).flat_map(|row| std::iter::once(0).chain(row.iter().copied())).collect();
|
||||
let mut stream = Stream::flate(Dict::new(), &rows);
|
||||
stream.dict.set(b"DecodeParms".to_vec(), Object::Ref(parms));
|
||||
Object::Ref(doc.add(Object::Stream(stream)))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn embedded_editor_fonts_are_validated_without_installing_or_exporting() {
|
||||
use pdfcraft_cos::Stream;
|
||||
@@ -124,34 +136,46 @@ fn embedded_editor_fonts_are_validated_without_installing_or_exporting() {
|
||||
}
|
||||
|
||||
/// #2130: with no `/Widths`, an embedded program's advances win over a guess from the name
|
||||
/// ("Mono" would mean Courier, 600 units for every glyph).
|
||||
/// ("Mono" would mean Courier, 600 units for every glyph), the program's `/DecodeParms` given
|
||||
/// directly or by reference.
|
||||
#[test]
|
||||
fn a_font_without_widths_measures_with_its_embedded_program() {
|
||||
use pdfcraft_cos::Stream;
|
||||
use skrifa::MetadataProvider as _;
|
||||
let mut doc = Document::new_empty();
|
||||
let bytes = include_bytes!("../../../../assets/fonts/Inter-Regular.ttf");
|
||||
let face = skrifa::FontRef::new(bytes).unwrap();
|
||||
let (size, location) = (skrifa::instance::Size::unscaled(), skrifa::instance::LocationRef::default());
|
||||
let upem = f64::from(face.metrics(size, location).units_per_em);
|
||||
let advance = |c: char| f64::from(face.glyph_metrics(size, location).advance_width(face.charmap().map(c).unwrap()).unwrap()) / upem;
|
||||
let program = doc.add(Object::Stream(Stream::flate(Dict::new(), bytes)));
|
||||
let mut descriptor = Dict::new();
|
||||
descriptor.set(b"FontFile2".to_vec(), Object::Ref(program));
|
||||
let f = font(
|
||||
&mut doc,
|
||||
vec![
|
||||
("Subtype", Object::name("TrueType")),
|
||||
("BaseFont", Object::name("HouseMono")),
|
||||
("Encoding", Object::name("WinAnsiEncoding")),
|
||||
("FontDescriptor", Object::Dict(descriptor)),
|
||||
],
|
||||
);
|
||||
let m = Metrics::from_dict(&doc, &f);
|
||||
for c in ['i', 'l', 'W', ' '] {
|
||||
assert!((m.width(u32::from(c)) - advance(c)).abs() < 1e-9, "{c}: {} vs {}", m.width(u32::from(c)), advance(c));
|
||||
for by_reference in [false, true] {
|
||||
let mut doc = Document::new_empty();
|
||||
let program = if by_reference {
|
||||
behind_parms_by_reference(&mut doc, bytes)
|
||||
} else {
|
||||
Object::Ref(doc.add(Object::Stream(Stream::flate(Dict::new(), bytes))))
|
||||
};
|
||||
let mut descriptor = Dict::new();
|
||||
descriptor.set(b"FontFile2".to_vec(), program);
|
||||
let f = font(
|
||||
&mut doc,
|
||||
vec![
|
||||
("Subtype", Object::name("TrueType")),
|
||||
("BaseFont", Object::name("HouseMono")),
|
||||
("Encoding", Object::name("WinAnsiEncoding")),
|
||||
("FontDescriptor", Object::Dict(descriptor)),
|
||||
],
|
||||
);
|
||||
let m = Metrics::from_dict(&doc, &f);
|
||||
for c in ['i', 'l', 'W', ' '] {
|
||||
assert!(
|
||||
(m.width(u32::from(c)) - advance(c)).abs() < 1e-9,
|
||||
"{c}, by reference {by_reference}: {} vs {}",
|
||||
m.width(u32::from(c)),
|
||||
advance(c)
|
||||
);
|
||||
}
|
||||
assert!(m.width(u32::from('i')) < 0.4, "not Courier's 0.6, by reference {by_reference}");
|
||||
}
|
||||
assert!(m.width(u32::from('i')) < 0.4, "not Courier's 0.6");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -342,6 +366,79 @@ fn cmap_streams_decode_within_a_size_cap() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cmap_streams_read_their_parameters_given_by_reference() {
|
||||
// Both maps behind a predictor whose `/DecodeParms` is a reference: read without it, every
|
||||
// row keeps its tag byte inside the map's tokens.
|
||||
let to_unicode = b"1 begincodespacerange <0000> <FFFF> endcodespacerange 1 beginbfrange <0024> <0026> <0041> endbfrange";
|
||||
let encoding = b"1 begincodespacerange <0000> <FFFF> endcodespacerange 1 begincidrange <0000> <FFFF> 0 endcidrange";
|
||||
let mut doc = Document::new_empty();
|
||||
let (tu, enc) = (behind_parms_by_reference(&mut doc, to_unicode), behind_parms_by_reference(&mut doc, encoding));
|
||||
let mut desc = Dict::new();
|
||||
desc.set(b"Subtype".to_vec(), Object::name("CIDFontType2"));
|
||||
let f = font(
|
||||
&mut doc,
|
||||
vec![("Subtype", Object::name("Type0")), ("Encoding", enc), ("DescendantFonts", Object::Array(vec![Object::Dict(desc)])), ("ToUnicode", tu)],
|
||||
);
|
||||
let m = Metrics::from_dict(&doc, &f);
|
||||
assert_eq!(m.decode(&[0, 0x24]), "A", "ToUnicode");
|
||||
assert!(matches!(m.codes, Codes::Ranges(_)), "Encoding");
|
||||
}
|
||||
|
||||
/// A Type 0 subset over Inter with `/DW` alone, whose CIDs 1 to 7 draw "A B C D" (ToUnicode
|
||||
/// gives CIDs 1 and 2), its program and its `/CIDToGIDMap` each behind a predictor whose
|
||||
/// `/DecodeParms` is a reference, or behind Flate alone.
|
||||
fn inter_subset(program_by_reference: bool, map_by_reference: bool) -> Metrics {
|
||||
use skrifa::MetadataProvider as _;
|
||||
let bytes = include_bytes!("../../../../assets/fonts/Inter-Regular.ttf");
|
||||
let face = skrifa::FontRef::new(bytes).unwrap();
|
||||
let gid = |c: char| u16::try_from(face.charmap().map(c).unwrap().to_u32()).unwrap();
|
||||
let gids: Vec<u8> = std::iter::once(0).chain("A B C D".chars().map(gid)).flat_map(u16::to_be_bytes).collect();
|
||||
let stream = |doc: &mut Document, data: &[u8], by_reference: bool| {
|
||||
if by_reference { behind_parms_by_reference(doc, data) } else { Object::Ref(doc.add(Object::Stream(Stream::flate(Dict::new(), data)))) }
|
||||
};
|
||||
let mut doc = Document::new_empty();
|
||||
let program = stream(&mut doc, bytes, program_by_reference);
|
||||
let map = stream(&mut doc, &gids, map_by_reference);
|
||||
let to_unicode = b"1 begincodespacerange <0000> <FFFF> endcodespacerange 2 beginbfchar <0001> <0041> <0002> <0020> endbfchar";
|
||||
let to_unicode = stream(&mut doc, to_unicode, false);
|
||||
let mut descriptor = Dict::new();
|
||||
descriptor.set(b"FontFile2".to_vec(), program);
|
||||
let mut desc = Dict::new();
|
||||
desc.set(b"Subtype".to_vec(), Object::name("CIDFontType2"));
|
||||
desc.set(b"DW".to_vec(), Object::Int(600));
|
||||
desc.set(b"FontDescriptor".to_vec(), Object::Dict(descriptor));
|
||||
desc.set(b"CIDToGIDMap".to_vec(), map);
|
||||
let f = font(
|
||||
&mut doc,
|
||||
vec![
|
||||
("Subtype", Object::name("Type0")),
|
||||
("BaseFont", Object::name("ABCDEF+Inter")),
|
||||
("Encoding", Object::name("Identity-H")),
|
||||
("DescendantFonts", Object::Array(vec![Object::Dict(desc)])),
|
||||
("ToUnicode", to_unicode),
|
||||
],
|
||||
);
|
||||
Metrics::from_dict(&doc, &f)
|
||||
}
|
||||
|
||||
/// A subset with `/DW` alone has a glyph for a CID when the program's glyph it maps to has an
|
||||
/// outline, so the space, Inter's empty glyph, is refused. Its program, or its `/CIDToGIDMap`,
|
||||
/// behind parameters given by reference says the same: read without them, no program says
|
||||
/// which glyphs are empty, or the map points the CIDs at other glyphs.
|
||||
#[test]
|
||||
fn a_subsets_program_and_cid_map_read_their_parameters_given_by_reference() {
|
||||
let direct = inter_subset(false, false);
|
||||
assert!(!direct.outlined_cids.is_empty());
|
||||
assert_eq!(direct.encode("A").as_deref(), Some(&[0, 1][..]));
|
||||
assert_eq!(direct.encode(" "), None, "the space's glyph is empty");
|
||||
for (program, map) in [(true, false), (false, true)] {
|
||||
let m = inter_subset(program, map);
|
||||
assert_eq!(m.outlined_cids, direct.outlined_cids, "program by reference: {program}, map: {map}");
|
||||
assert_eq!(m.encode(" "), None, "program by reference: {program}, map: {map}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn composite_fonts_use_to_unicode() {
|
||||
let mut doc = Document::new_empty();
|
||||
|
||||
@@ -147,6 +147,16 @@ pub fn arabic_glyph(id: u32) -> Result<GlyphOutline, GlyphError> {
|
||||
/// A bounded outline from the same face that produced the shaped glyph id.
|
||||
pub fn shaped_glyph(script: ShapedScript, id: u32) -> Result<GlyphOutline, GlyphError> {
|
||||
let (font, _) = face(script).ok_or(GlyphError::NoFont)?;
|
||||
glyph(font, id)
|
||||
}
|
||||
|
||||
/// Glyph `id` of the face in `bytes`, bounded like [`shaped_glyph`]: for text shaped with
|
||||
/// [`crate::source_shaping::shape`] in a face no [`ShapedScript`] names.
|
||||
pub fn face_glyph(bytes: &[u8], id: u32) -> Result<GlyphOutline, GlyphError> {
|
||||
glyph(&FontRef::new(bytes).map_err(|_| GlyphError::NoFont)?, id)
|
||||
}
|
||||
|
||||
fn glyph(font: &FontRef, id: u32) -> Result<GlyphOutline, GlyphError> {
|
||||
if font.maxp().map_or(true, |m| id >= u32::from(m.num_glyphs())) {
|
||||
return Err(GlyphError::Missing);
|
||||
}
|
||||
|
||||
@@ -22,11 +22,14 @@ let report = optimize_with_progress(&mut doc, &settings, &mut |stage| keep_going
|
||||
printed this way went from 4.3 MB to 231 KB (Standard) and 161 KB (Mobile). Not merged yet:
|
||||
side-by-side tiles, rotated strips, masks. Content arrays use the shared space boundary
|
||||
policy, so trailing comments, split operands and graphics state keep their meaning after merging.
|
||||
A page whose content doesn't decode, or is damaged partway, is left as it is: written again from
|
||||
what decoded, it would lose the rest.
|
||||
- **Images:** the effective resolution of each image is measured where pages draw it (the CTM
|
||||
through form XObjects, up to 12 deep; the smallest over all uses).
|
||||
Page-local `/UserUnit` scaling is included, so large-format pages are measured in physical inches.
|
||||
If a use can't be
|
||||
measured (forms nested deeper, or drawn too many times), no image is resampled. Colour and grayscale images above a
|
||||
measured (forms nested deeper or drawn too many times, or content that doesn't decode or is
|
||||
damaged partway, which may draw an image larger past the damage), no image is resampled. Colour and grayscale images above a
|
||||
threshold are resampled with a bicubic (Catmull-Rom) filter to a target resolution and
|
||||
stored as JPEG (Acrobat's quality steps) or ZIP; soft masks are resampled with their image. A
|
||||
stencil `/Mask` has its own resolution, so the picture changes under it and it stays as it is.
|
||||
|
||||
@@ -394,8 +394,8 @@ mod tests {
|
||||
let mut budget = ImageBudget::with_work(0);
|
||||
assert_eq!(merge_page(&mut doc.clone(), page, &mut Report::default(), &mut |_| true, &mut budget).unwrap(), 0);
|
||||
assert_eq!(budget.refused(), 1);
|
||||
// Reading each strip, and building the picture of 8 rows of 8 they make.
|
||||
let cost = raw + 8 * (8 + 8) + 8 * 8;
|
||||
// Reading each strip, inflating it, and building the picture of 8 rows of 8 they make.
|
||||
let cost = (1 + pdfcraft_filters::FLATE_READ_WORK) * raw + 8 * (8 + 8) + 8 * 8;
|
||||
let mut budget = ImageBudget::with_work(u64::MAX);
|
||||
assert_eq!(merge_page(&mut doc.clone(), page, &mut Report::default(), &mut |_| true, &mut budget).unwrap(), 8);
|
||||
assert_eq!(u64::MAX - budget.work_left(), cost);
|
||||
|
||||
@@ -32,9 +32,10 @@ fn held_page_resources(doc: &Document, page: ObjRef) -> Option<(Dict, ObjRef)> {
|
||||
}
|
||||
|
||||
/// The page content `contents` names, decoded against `budget` and joined. `None` when a stream
|
||||
/// doesn't decode or the budget runs out: the content is not all known.
|
||||
/// doesn't decode, is damaged partway or the budget runs out: the content is not all known.
|
||||
pub(crate) fn content_bytes(doc: &Document, contents: &Object, budget: &mut DecodeBudget) -> Option<Vec<u8>> {
|
||||
let pieces = budget.decode_contents(doc, contents).into_iter().collect::<Result<Vec<_>, _>>().ok()?;
|
||||
let reads = budget.decode_contents_with_damage(doc, contents);
|
||||
let pieces = reads.into_iter().map(|read| read.ok().filter(|(_, damaged)| !damaged).map(|(data, _)| data)).collect::<Option<Vec<_>>>()?;
|
||||
Some(Pieces::join(&pieces).data().to_vec())
|
||||
}
|
||||
|
||||
@@ -214,7 +215,7 @@ impl Walk<'_> {
|
||||
self.complete = false;
|
||||
return;
|
||||
}
|
||||
let Ok(data) = self.budget.decode(s) else {
|
||||
let Ok((data, false)) = self.budget.decode_with_damage(doc, s, usize::MAX) else {
|
||||
self.complete = false;
|
||||
return;
|
||||
};
|
||||
@@ -245,9 +246,9 @@ fn remaps_device_spaces(doc: &Document, resources: &Dict) -> bool {
|
||||
|
||||
/// The effective resolution (ppi) of every image drawn by `pages`: the smallest over its uses.
|
||||
///
|
||||
/// If forms nest too deeply, are drawn too many times, or a page's content doesn't decode within
|
||||
/// its budget, every image is given `INFINITY` (never resampled), since its largest use may be
|
||||
/// among those missed.
|
||||
/// If forms nest too deeply, are drawn too many times, or a page's or form's content doesn't
|
||||
/// decode within its budget or is damaged partway, every image is given `INFINITY` (never
|
||||
/// resampled), since its largest use may be among those missed.
|
||||
pub fn effective_resolutions(doc: &Document, pages: &[ObjRef]) -> HashMap<ObjRef, f64> {
|
||||
walk_pages(doc, pages).0
|
||||
}
|
||||
@@ -1699,7 +1700,7 @@ mod dimension_tests {
|
||||
dict.set(b"BitsPerComponent".to_vec(), Object::Int(8));
|
||||
dict.set(b"ColorSpace".to_vec(), Object::name("DeviceGray"));
|
||||
let image = Stream::flate(dict, &samples);
|
||||
let read = (image.raw.len() + samples.len()) as u64 + 256 * 256;
|
||||
let read = (image.raw.len() + samples.len()) as u64 + pdfcraft_filters::FLATE_READ_WORK * image.raw.len() as u64 + 256 * 256;
|
||||
let original = doc.add(Object::Stream(image.clone()));
|
||||
let mut xobjects = Dict::new();
|
||||
xobjects.set(b"I0".to_vec(), Object::Ref(original));
|
||||
@@ -1791,7 +1792,7 @@ mod dimension_tests {
|
||||
};
|
||||
let mut doc = Document::new_empty();
|
||||
let mask = image("DeviceGray");
|
||||
let cost = (mask.raw.len() + noise.len()) as u64 + 256 * 256;
|
||||
let cost = (mask.raw.len() + noise.len()) as u64 + pdfcraft_filters::FLATE_READ_WORK * mask.raw.len() as u64 + 256 * 256;
|
||||
let masked = doc.add(Object::Stream(mask));
|
||||
let mut with_mask = image("DeviceGray");
|
||||
with_mask.dict.set(b"SMask".to_vec(), Object::Ref(masked));
|
||||
|
||||
Loaded 100 of 187 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user