M2: merge main and resolve CJK viewer integration conflicts
No files matched your search
@@ -27,7 +27,8 @@ permissions:
|
||||
|
||||
jobs:
|
||||
windows-arm64:
|
||||
uses: storytold/craft-common-actions/.github/workflows/windows-arm64.yml@8bb4e5ab95443171104ad88113fe1ef9b0e5ce3f
|
||||
# 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/windows-arm64.yml@main
|
||||
with:
|
||||
app-name: pdfcraft
|
||||
app-dir: PdfCraft
|
||||
|
||||
@@ -9,3 +9,4 @@ plan/
|
||||
/assets/models
|
||||
# A craft-fonts checkout used as the optional CRAFT_FONTS_DIR build input (CI and releases put it here).
|
||||
/craft-fonts
|
||||
.claude/
|
||||
@@ -139,3 +139,8 @@ Follow `CLAUDE.md`. It covers quality gates, layering, commit rules and how to r
|
||||
GitHub profiles). Never hand-edit `contributors.json`.
|
||||
- Maintainers refresh the stats with `python3 ../../craftrules/scripts/contributors.py .` (it also
|
||||
re-verifies who wrote each `people.toml` entry; `--check` only verifies).
|
||||
|
||||
## CI workflows
|
||||
- Workflows in `.github/workflows/` call the shared workflows in [`storytold/craft-common-actions`](https://github.com/storytold/craft-common-actions) at `@main`, with their inputs and secrets. No other jobs: if no shared workflow does what's needed, it doesn't go here.
|
||||
- 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.
|
||||
@@ -2879,7 +2879,7 @@ licence = "MIT OR Apache-2.0"
|
||||
licence_file = "assets/app-icon/LICENSE.txt"
|
||||
kind = "icon"
|
||||
usage = "Master artwork; every other app-icon file is rendered from it (packaging/icons.sh)"
|
||||
sha256 = "52b384a10a2a7fdd3145d9822972cfd568ef0cb7312549bd4399addd89d45a6d"
|
||||
sha256 = "27745c021830f82c033b0f15f2d8d9f8e099138743297887ff7e2c9e7ed069da"
|
||||
|
||||
[[asset]]
|
||||
path = "assets/app-icon/pdfcraft-small.svg"
|
||||
@@ -2890,7 +2890,7 @@ licence = "MIT OR Apache-2.0"
|
||||
licence_file = "assets/app-icon/LICENSE.txt"
|
||||
kind = "icon"
|
||||
usage = "README header and assets/app-icon/README.md"
|
||||
sha256 = "b036304c11ef5dcad36636d06ca0bf331b51e47650d25d3c916a0e1eabf544c7"
|
||||
sha256 = "b524df1a583f8034a5a23836955e4fb423e0149429d695e80d95e5056f408678"
|
||||
|
||||
[[asset]]
|
||||
path = "assets/app-icon/pdfcraft-1024.png"
|
||||
@@ -2901,7 +2901,7 @@ licence = "MIT OR Apache-2.0"
|
||||
licence_file = "assets/app-icon/LICENSE.txt"
|
||||
kind = "icon"
|
||||
usage = "Runtime window/Dock icon on macOS (apps/pdfcraft/src/main.rs)"
|
||||
sha256 = "da577d3f21fbcf5c739067787a9e683be2b064d76813b5d5fec9074a7a106538"
|
||||
sha256 = "68ac6730b8990d07503351d32eacea81e9ec171a7a6f09daf52d6555d8245c8a"
|
||||
|
||||
[[asset]]
|
||||
path = "assets/app-icon/pdfcraft.icns"
|
||||
@@ -2912,7 +2912,7 @@ licence = "MIT OR Apache-2.0"
|
||||
licence_file = "assets/app-icon/LICENSE.txt"
|
||||
kind = "icon"
|
||||
usage = "macOS app bundle icon"
|
||||
sha256 = "2425148222873de241d267aba667a8b234ecdd0149f2ca8bb6e79443b743b1e8"
|
||||
sha256 = "fca7e7a0e34cc5c5ecae5bca97ee896aac68c4a34b088bc3a0b3271484f23974"
|
||||
|
||||
[[asset]]
|
||||
path = "assets/app-icon/pdfcraft.ico"
|
||||
@@ -2923,7 +2923,7 @@ licence = "MIT OR Apache-2.0"
|
||||
licence_file = "assets/app-icon/LICENSE.txt"
|
||||
kind = "icon"
|
||||
usage = "Embedded in pdfcraft.exe by apps/pdfcraft/build.rs (Explorer, taskbar, Start menu, Alt-Tab)"
|
||||
sha256 = "56daaaae9ae5389794909570885809adf5e1d9183bef2d9669ed2f9bba3ed6f5"
|
||||
sha256 = "709271d66e07710a3f785ea21b0c85c5228eaf8bebe5058bc0f71f9ef20749eb"
|
||||
|
||||
[[asset]]
|
||||
path = "assets/app-icon/pdfcraft-document.svg"
|
||||
@@ -2934,7 +2934,7 @@ licence = "ISC AND (MIT OR Apache-2.0)"
|
||||
licence_file = "assets/app-icon/LICENSE-document.txt"
|
||||
kind = "icon"
|
||||
usage = "Master artwork for the Windows PDF file type icon; rendered by packaging/icons.sh, without fonts or external images"
|
||||
sha256 = "8da8278c2b89362be0a960879d453ff879d7544d6d58e47d5389574e8dfff77b"
|
||||
sha256 = "c129f1b538ce16e3c3fa0d89d3301038c51249ba5d61bfd98c46e69cfdf5c316"
|
||||
|
||||
[[asset]]
|
||||
path = "assets/app-icon/pdfcraft-document.ico"
|
||||
@@ -2945,7 +2945,7 @@ licence = "ISC AND (MIT OR Apache-2.0)"
|
||||
licence_file = "assets/app-icon/LICENSE-document.txt"
|
||||
kind = "icon"
|
||||
usage = "Embedded in pdfcraft.exe as resource 2; the Windows installer uses it for PdfCraft.Document and Applications/pdfcraft.exe PDF file associations"
|
||||
sha256 = "ba3f9128b368fc6d17d376cf62dbdbc22455451c5c8c4779210d7a2a7409b9e6"
|
||||
sha256 = "910be5e0ecdc94ce00368077ca1bef449bd5d62a75516feeb37884296c6fac4d"
|
||||
|
||||
[[asset]]
|
||||
path = "assets/app-icon/hicolor/16x16/apps/ai.storyteller.pdfcraft.png"
|
||||
@@ -2956,7 +2956,7 @@ licence = "MIT OR Apache-2.0"
|
||||
licence_file = "assets/app-icon/LICENSE.txt"
|
||||
kind = "icon"
|
||||
usage = "Linux hicolor theme icon (packaging/linux/ai.storyteller.pdfcraft.desktop)"
|
||||
sha256 = "9b77095cbe75dcba6b74a1fdcd4064812850efaf7a12edebefc9ded5eabb49da"
|
||||
sha256 = "660d2aace45ec1a28bc7e3708eab71ffee5cb1203f57a6256f7bd7c727193567"
|
||||
|
||||
[[asset]]
|
||||
path = "assets/app-icon/hicolor/24x24/apps/ai.storyteller.pdfcraft.png"
|
||||
@@ -2967,7 +2967,7 @@ licence = "MIT OR Apache-2.0"
|
||||
licence_file = "assets/app-icon/LICENSE.txt"
|
||||
kind = "icon"
|
||||
usage = "Linux hicolor theme icon (packaging/linux/ai.storyteller.pdfcraft.desktop)"
|
||||
sha256 = "a4cd466687f6c5cb59eef3fc564bdba1c8f0d9e324754eeebab82f18823efae7"
|
||||
sha256 = "1989441bdcc8d1df0d73cfe7eb836e9211abaa0fd7fd6ec7e4634bfcd472995d"
|
||||
|
||||
[[asset]]
|
||||
path = "assets/app-icon/hicolor/32x32/apps/ai.storyteller.pdfcraft.png"
|
||||
@@ -2978,7 +2978,7 @@ licence = "MIT OR Apache-2.0"
|
||||
licence_file = "assets/app-icon/LICENSE.txt"
|
||||
kind = "icon"
|
||||
usage = "Linux hicolor theme icon (packaging/linux/ai.storyteller.pdfcraft.desktop)"
|
||||
sha256 = "e22279013a5ed5c02571e1e4e9bc4cef9aa0847fcb733a285b2916fabd16bf78"
|
||||
sha256 = "7fd1ac555f7f6b13ef3fba2696dfb86900cfcb7f7b669aece38590bf2306cf2e"
|
||||
|
||||
[[asset]]
|
||||
path = "assets/app-icon/hicolor/48x48/apps/ai.storyteller.pdfcraft.png"
|
||||
@@ -2989,7 +2989,7 @@ licence = "MIT OR Apache-2.0"
|
||||
licence_file = "assets/app-icon/LICENSE.txt"
|
||||
kind = "icon"
|
||||
usage = "Linux hicolor theme icon (packaging/linux/ai.storyteller.pdfcraft.desktop)"
|
||||
sha256 = "55daf2d5575f6c4e4c4975c9f1c74231178f1801963a8b19f68dfa9bc50cb22f"
|
||||
sha256 = "784ef3bd9f9e479cb2df22a0aee259a441a9c358390e646639c3a0ed79d41288"
|
||||
|
||||
[[asset]]
|
||||
path = "assets/app-icon/hicolor/64x64/apps/ai.storyteller.pdfcraft.png"
|
||||
@@ -3000,7 +3000,7 @@ licence = "MIT OR Apache-2.0"
|
||||
licence_file = "assets/app-icon/LICENSE.txt"
|
||||
kind = "icon"
|
||||
usage = "Linux hicolor theme icon (packaging/linux/ai.storyteller.pdfcraft.desktop)"
|
||||
sha256 = "2975c200f341e247b5fa18f568fb27d390e3fa01e9b2ad37acb48d0e1cc8a124"
|
||||
sha256 = "deb1a9f849549d3f0652fb6d3c30b6eb6ea54498eaea8c1007d901bbafe7067c"
|
||||
|
||||
[[asset]]
|
||||
path = "assets/app-icon/hicolor/128x128/apps/ai.storyteller.pdfcraft.png"
|
||||
@@ -3011,7 +3011,7 @@ licence = "MIT OR Apache-2.0"
|
||||
licence_file = "assets/app-icon/LICENSE.txt"
|
||||
kind = "icon"
|
||||
usage = "Linux hicolor theme icon (packaging/linux/ai.storyteller.pdfcraft.desktop)"
|
||||
sha256 = "6ef927ca252b40bc9b5d8843d84137334362f8aa1acbb1bf8c15a02affd25b2b"
|
||||
sha256 = "1933bbeaea290497facd328e917dafcc433d0c0caa9f1e207aa45ac1e430898c"
|
||||
|
||||
[[asset]]
|
||||
path = "assets/app-icon/hicolor/256x256/apps/ai.storyteller.pdfcraft.png"
|
||||
@@ -3022,7 +3022,7 @@ licence = "MIT OR Apache-2.0"
|
||||
licence_file = "assets/app-icon/LICENSE.txt"
|
||||
kind = "icon"
|
||||
usage = "Linux hicolor theme icon (packaging/linux/ai.storyteller.pdfcraft.desktop); runtime window icon on Windows and Linux (apps/pdfcraft/src/main.rs)"
|
||||
sha256 = "cde7ee8c5ee38f9fc40a429fd9e6d99a035bcd321701fce331bb13bac126614d"
|
||||
sha256 = "47094c09fb77eb35d465eee46445626a4d78c7ef50629cc7d04a602de3e144e9"
|
||||
|
||||
[[asset]]
|
||||
path = "assets/app-icon/hicolor/512x512/apps/ai.storyteller.pdfcraft.png"
|
||||
@@ -3033,7 +3033,7 @@ licence = "MIT OR Apache-2.0"
|
||||
licence_file = "assets/app-icon/LICENSE.txt"
|
||||
kind = "icon"
|
||||
usage = "Linux hicolor theme icon (packaging/linux/ai.storyteller.pdfcraft.desktop)"
|
||||
sha256 = "5ede733e93b96f4eb8d94299232cf2f9605fa19b0d913f95fe9828c316a2d066"
|
||||
sha256 = "dea8010a8b41011aba054d3bfb8b790da57bc958c60869f508e1bbd288d3f280"
|
||||
|
||||
[[asset]]
|
||||
path = "assets/app-icon/hicolor/scalable/apps/ai.storyteller.pdfcraft.svg"
|
||||
@@ -3044,7 +3044,7 @@ licence = "MIT OR Apache-2.0"
|
||||
licence_file = "assets/app-icon/LICENSE.txt"
|
||||
kind = "icon"
|
||||
usage = "Linux hicolor theme icon (packaging/linux/ai.storyteller.pdfcraft.desktop)"
|
||||
sha256 = "52b384a10a2a7fdd3145d9822972cfd568ef0cb7312549bd4399addd89d45a6d"
|
||||
sha256 = "27745c021830f82c033b0f15f2d8d9f8e099138743297887ff7e2c9e7ed069da"
|
||||
|
||||
[[asset]]
|
||||
path = "docs/images/pdfcraft-bookmarks.png"
|
||||
@@ -3341,7 +3341,7 @@ licence = "MIT OR Apache-2.0"
|
||||
licence_file = "assets/app-icon/LICENSE.txt"
|
||||
kind = "image"
|
||||
usage = "Finder window of the macOS DMG; rendered to background.tiff by packaging/macos/dmg/generate.py"
|
||||
sha256 = "e8b9ea9d5e64b7b741c977543c1693825e77d5c4c579eeb674bf5dcd3764cd8a"
|
||||
sha256 = "182663e4d1c4fabbb7ab2e1f0d4e991a8e0859b4a8dee6934d3e25d77ea020af"
|
||||
|
||||
|
||||
[[asset]]
|
||||
@@ -3353,7 +3353,7 @@ licence = "MIT OR Apache-2.0"
|
||||
licence_file = "assets/app-icon/LICENSE.txt"
|
||||
kind = "image"
|
||||
usage = "1x + 2x HiDPI 16-colour palette TIFF copied into the macOS DMG by packaging/macos/package.sh; includes the app icon and the free LittleCMS built-in sRGB profile"
|
||||
sha256 = "f46881724a6621f3686a612a79dbdce4f7dbe9e2025610e44c9a094341334c2c"
|
||||
sha256 = "bedf1b23707b9e34157440e83f65464ff314fa9f6b1d39c7a8930d1645c2f8be"
|
||||
|
||||
[[fetched]]
|
||||
file = "text-detection.onnx"
|
||||
|
||||
@@ -22,6 +22,8 @@ PdfCraft is a clean-room, open-source, Rust-native PDF application targeting Ado
|
||||
- **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 router says the press is its own (`view.router.owner(page)`), never by testing the press point again or by asking another module whether it wants it. Escape cancels any press the pages hold (`cancel_on_escape`), and that press is ignored until the button is up. `page_modules_take_presses_from_the_router_without_repeating_hit_tests` guards the centralized hit calls and captured-owner handlers; runtime routing tests cover gesture behavior.
|
||||
- **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.
|
||||
@@ -39,6 +41,7 @@ PdfCraft is a clean-room, open-source, Rust-native PDF application targeting Ado
|
||||
- **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.
|
||||
@@ -55,3 +58,8 @@ PdfCraft is a clean-room, open-source, Rust-native PDF application targeting Ado
|
||||
|
||||
## 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.
|
||||
@@ -229,7 +229,7 @@ dependencies = [
|
||||
"objc2-foundation 0.3.2",
|
||||
"parking_lot",
|
||||
"percent-encoding",
|
||||
"windows-sys 0.59.0",
|
||||
"windows-sys 0.61.2",
|
||||
"wl-clipboard-rs",
|
||||
"x11rb",
|
||||
]
|
||||
@@ -1178,17 +1178,17 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-docpath"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545#e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545"
|
||||
|
||||
[[package]]
|
||||
name = "craft-fonts-build"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545#e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545"
|
||||
|
||||
[[package]]
|
||||
name = "craft-i18n"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545#e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545"
|
||||
dependencies = [
|
||||
"fixed_decimal",
|
||||
"icu_decimal",
|
||||
@@ -1211,7 +1211,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-keymap"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545#e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545"
|
||||
dependencies = [
|
||||
"egui",
|
||||
"serde",
|
||||
@@ -1221,7 +1221,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-menu"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545#e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545"
|
||||
dependencies = [
|
||||
"craft-keymap",
|
||||
"craft-quit",
|
||||
@@ -1234,7 +1234,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-print"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545#e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545"
|
||||
dependencies = [
|
||||
"craft-winprint-gdi",
|
||||
"miniz_oxide 0.9.1",
|
||||
@@ -1247,7 +1247,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-quit"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545#e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545"
|
||||
dependencies = [
|
||||
"dispatch2",
|
||||
"egui",
|
||||
@@ -1258,7 +1258,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545#e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545"
|
||||
dependencies = [
|
||||
"craft-fonts-build",
|
||||
"craft-i18n",
|
||||
@@ -1279,13 +1279,14 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-update"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=04aa1703b32d299e54f78fcde4182f2b393a9116#04aa1703b32d299e54f78fcde4182f2b393a9116"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"dunce",
|
||||
"egui",
|
||||
"flate2",
|
||||
"getrandom 0.3.4",
|
||||
"image",
|
||||
"log",
|
||||
"plist",
|
||||
"semver",
|
||||
@@ -2015,7 +2016,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"windows-sys 0.59.0",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2731,6 +2732,7 @@ version = "0.3.0"
|
||||
dependencies = [
|
||||
"fearless_simd",
|
||||
"hayro-ccitt",
|
||||
"image",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -4114,7 +4116,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"windows-sys 0.59.0",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -4205,7 +4207,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "pdfcraft"
|
||||
version = "0.14.0"
|
||||
version = "0.15.0"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"craft-update",
|
||||
@@ -4229,7 +4231,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "pdfcraft-a11y"
|
||||
version = "0.14.0"
|
||||
version = "0.15.0"
|
||||
dependencies = [
|
||||
"pdfcraft-content",
|
||||
"pdfcraft-cos",
|
||||
@@ -4241,7 +4243,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "pdfcraft-annot"
|
||||
version = "0.14.0"
|
||||
version = "0.15.0"
|
||||
dependencies = [
|
||||
"hayro-syntax",
|
||||
"pdfcraft-cos",
|
||||
@@ -4252,7 +4254,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "pdfcraft-audit"
|
||||
version = "0.14.0"
|
||||
version = "0.15.0"
|
||||
dependencies = [
|
||||
"pdfcraft-content",
|
||||
"pdfcraft-cos",
|
||||
@@ -4263,7 +4265,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "pdfcraft-automation"
|
||||
version = "0.14.0"
|
||||
version = "0.15.0"
|
||||
dependencies = [
|
||||
"base64 0.23.1",
|
||||
"flate2",
|
||||
@@ -4285,7 +4287,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "pdfcraft-cli"
|
||||
version = "0.14.0"
|
||||
version = "0.15.0"
|
||||
dependencies = [
|
||||
"base64 0.23.1",
|
||||
"pdfcraft-audit",
|
||||
@@ -4303,11 +4305,11 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "pdfcraft-compare"
|
||||
version = "0.14.0"
|
||||
version = "0.15.0"
|
||||
|
||||
[[package]]
|
||||
name = "pdfcraft-content"
|
||||
version = "0.14.0"
|
||||
version = "0.15.0"
|
||||
dependencies = [
|
||||
"hayro-syntax",
|
||||
"pdfcraft-cos",
|
||||
@@ -4315,7 +4317,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "pdfcraft-cos"
|
||||
version = "0.14.0"
|
||||
version = "0.15.0"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"hayro-syntax",
|
||||
@@ -4330,14 +4332,18 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "pdfcraft-create"
|
||||
version = "0.14.0"
|
||||
version = "0.15.0"
|
||||
dependencies = [
|
||||
"encoding_rs",
|
||||
"hayro-ccitt",
|
||||
"hayro-jbig2",
|
||||
"hayro-syntax",
|
||||
"image",
|
||||
"pdfcraft-cos",
|
||||
"pdfcraft-filters",
|
||||
"pdfcraft-fonts",
|
||||
"pdfcraft-model",
|
||||
"pdfcraft-xfa",
|
||||
"png 0.18.1",
|
||||
"thiserror 2.0.21",
|
||||
"tiff",
|
||||
@@ -4346,7 +4352,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "pdfcraft-crypt"
|
||||
version = "0.14.0"
|
||||
version = "0.15.0"
|
||||
dependencies = [
|
||||
"aes",
|
||||
"md-5",
|
||||
@@ -4358,7 +4364,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "pdfcraft-edit"
|
||||
version = "0.14.0"
|
||||
version = "0.15.0"
|
||||
dependencies = [
|
||||
"hayro-syntax",
|
||||
"kurbo 0.13.1",
|
||||
@@ -4367,16 +4373,18 @@ dependencies = [
|
||||
"pdfcraft-cos",
|
||||
"pdfcraft-fonts",
|
||||
"pdfcraft-model",
|
||||
"sha2 0.11.1",
|
||||
"thiserror 2.0.21",
|
||||
"unicode-bidi",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pdfcraft-engine"
|
||||
version = "0.14.0"
|
||||
version = "0.15.0"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"craft-docpath",
|
||||
"getrandom 0.4.3",
|
||||
"icu_properties",
|
||||
"idna",
|
||||
"image",
|
||||
@@ -4414,16 +4422,19 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "pdfcraft-export"
|
||||
version = "0.14.0"
|
||||
version = "0.15.0"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pdfcraft-filters"
|
||||
version = "0.14.0"
|
||||
version = "0.15.0"
|
||||
dependencies = [
|
||||
"fax",
|
||||
"flate2",
|
||||
"hayro-ccitt",
|
||||
"hayro-jbig2",
|
||||
"proptest",
|
||||
"thiserror 2.0.21",
|
||||
"weezl 0.2.1",
|
||||
@@ -4431,7 +4442,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "pdfcraft-fonts"
|
||||
version = "0.14.0"
|
||||
version = "0.15.0"
|
||||
dependencies = [
|
||||
"harfrust",
|
||||
"pdfcraft-cos",
|
||||
@@ -4441,7 +4452,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "pdfcraft-forms"
|
||||
version = "0.14.0"
|
||||
version = "0.15.0"
|
||||
dependencies = [
|
||||
"hayro-syntax",
|
||||
"pdfcraft-content",
|
||||
@@ -4454,11 +4465,11 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "pdfcraft-geom"
|
||||
version = "0.14.0"
|
||||
version = "0.15.0"
|
||||
|
||||
[[package]]
|
||||
name = "pdfcraft-js"
|
||||
version = "0.14.0"
|
||||
version = "0.15.0"
|
||||
dependencies = [
|
||||
"boa_engine",
|
||||
"chrono",
|
||||
@@ -4466,7 +4477,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "pdfcraft-measure"
|
||||
version = "0.14.0"
|
||||
version = "0.15.0"
|
||||
dependencies = [
|
||||
"pdfcraft-annot",
|
||||
"pdfcraft-content",
|
||||
@@ -4479,14 +4490,14 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "pdfcraft-model"
|
||||
version = "0.14.0"
|
||||
version = "0.15.0"
|
||||
dependencies = [
|
||||
"pdfcraft-cos",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pdfcraft-ocr"
|
||||
version = "0.14.0"
|
||||
version = "0.15.0"
|
||||
dependencies = [
|
||||
"ocrs",
|
||||
"pdfcraft-fonts",
|
||||
@@ -4497,7 +4508,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "pdfcraft-optimize"
|
||||
version = "0.14.0"
|
||||
version = "0.15.0"
|
||||
dependencies = [
|
||||
"image",
|
||||
"pdfcraft-annot",
|
||||
@@ -4506,17 +4517,18 @@ dependencies = [
|
||||
"pdfcraft-filters",
|
||||
"pdfcraft-model",
|
||||
"pdfcraft-render",
|
||||
"proptest",
|
||||
"thiserror 2.0.21",
|
||||
"zune-jpeg",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pdfcraft-oracle"
|
||||
version = "0.14.0"
|
||||
version = "0.15.0"
|
||||
|
||||
[[package]]
|
||||
name = "pdfcraft-organize"
|
||||
version = "0.14.0"
|
||||
version = "0.15.0"
|
||||
dependencies = [
|
||||
"hayro-syntax",
|
||||
"pdfcraft-content",
|
||||
@@ -4527,7 +4539,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "pdfcraft-platform"
|
||||
version = "0.14.0"
|
||||
version = "0.15.0"
|
||||
dependencies = [
|
||||
"async-channel",
|
||||
"futures-lite",
|
||||
@@ -4537,18 +4549,18 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "pdfcraft-preflight"
|
||||
version = "0.14.0"
|
||||
version = "0.15.0"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"pdfcraft-content",
|
||||
"pdfcraft-cos",
|
||||
"pdfcraft-model",
|
||||
"roxmltree 0.20.0",
|
||||
"roxmltree 0.21.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pdfcraft-print"
|
||||
version = "0.14.0"
|
||||
version = "0.15.0"
|
||||
dependencies = [
|
||||
"craft-print",
|
||||
"pdfcraft-content",
|
||||
@@ -4560,12 +4572,13 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "pdfcraft-redact"
|
||||
version = "0.14.0"
|
||||
version = "0.15.0"
|
||||
dependencies = [
|
||||
"pdfcraft-annot",
|
||||
"pdfcraft-content",
|
||||
"pdfcraft-cos",
|
||||
"pdfcraft-edit",
|
||||
"pdfcraft-filters",
|
||||
"pdfcraft-fonts",
|
||||
"pdfcraft-forms",
|
||||
"pdfcraft-model",
|
||||
@@ -4576,7 +4589,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "pdfcraft-render"
|
||||
version = "0.14.0"
|
||||
version = "0.15.0"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"flate2",
|
||||
@@ -4595,7 +4608,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "pdfcraft-sign"
|
||||
version = "0.14.0"
|
||||
version = "0.15.0"
|
||||
dependencies = [
|
||||
"aes",
|
||||
"aws-lc-rs",
|
||||
@@ -4631,11 +4644,11 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "pdfcraft-testkit"
|
||||
version = "0.14.0"
|
||||
version = "0.15.0"
|
||||
|
||||
[[package]]
|
||||
name = "pdfcraft-ui-egui"
|
||||
version = "0.14.0"
|
||||
version = "0.15.0"
|
||||
dependencies = [
|
||||
"arboard",
|
||||
"base64 0.23.1",
|
||||
@@ -4687,7 +4700,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "pdfcraft-web"
|
||||
version = "0.14.0"
|
||||
version = "0.15.0"
|
||||
dependencies = [
|
||||
"eframe",
|
||||
"egui",
|
||||
@@ -4699,27 +4712,27 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "pdfcraft-xfa"
|
||||
version = "0.14.0"
|
||||
version = "0.15.0"
|
||||
dependencies = [
|
||||
"base64 0.23.1",
|
||||
"image",
|
||||
"pdfcraft-cos",
|
||||
"pdfcraft-fonts",
|
||||
"png 0.18.1",
|
||||
"roxmltree 0.20.0",
|
||||
"roxmltree 0.21.2",
|
||||
"sha2 0.11.1",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pdfcraft-xfdf"
|
||||
version = "0.14.0"
|
||||
version = "0.15.0"
|
||||
dependencies = [
|
||||
"pdfcraft-annot",
|
||||
"pdfcraft-cos",
|
||||
"pdfcraft-forms",
|
||||
"pdfcraft-model",
|
||||
"roxmltree 0.20.0",
|
||||
"roxmltree 0.21.2",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
@@ -5258,7 +5271,7 @@ dependencies = [
|
||||
"once_cell",
|
||||
"socket2",
|
||||
"tracing",
|
||||
"windows-sys 0.59.0",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -5795,7 +5808,7 @@ dependencies = [
|
||||
"errno",
|
||||
"libc",
|
||||
"linux-raw-sys 0.12.1",
|
||||
"windows-sys 0.59.0",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -5865,7 +5878,7 @@ dependencies = [
|
||||
"security-framework",
|
||||
"security-framework-sys",
|
||||
"webpki-root-certs",
|
||||
"windows-sys 0.59.0",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -6752,10 +6765,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"
|
||||
dependencies = [
|
||||
"fastrand",
|
||||
"getrandom 0.4.3",
|
||||
"getrandom 0.3.4",
|
||||
"once_cell",
|
||||
"rustix 1.1.5",
|
||||
"windows-sys 0.59.0",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -7350,8 +7363,6 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "vello_cpu"
|
||||
version = "0.0.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6d8ded630e8316bb94a55881256506d1f3b9947b5f66db8a7d32ca7ba02decd0"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"glifo 0.1.1",
|
||||
@@ -7868,7 +7879,7 @@ version = "0.1.11"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
|
||||
dependencies = [
|
||||
"windows-sys 0.59.0",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -8595,9 +8606,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "zip"
|
||||
version = "9.1.0"
|
||||
version = "9.1.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2886b00003a72c4ccee3f42cfc34908d33b2508a74d827dc2a4244706475c704"
|
||||
checksum = "1156b39d142a34b999c2310a50455e0cb3760bf7efad0122f796d813bee26ccb"
|
||||
dependencies = [
|
||||
"crc32fast",
|
||||
"flate2",
|
||||
|
||||
@@ -5,7 +5,7 @@ exclude = ["vendor"]
|
||||
default-members = ["crates/*", "apps/pdfcraft", "apps/pdfcraft-cli", "xtask"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.14.0"
|
||||
version = "0.15.0"
|
||||
edition = "2024"
|
||||
license = "MIT OR Apache-2.0"
|
||||
rust-version = "1.95"
|
||||
@@ -13,51 +13,52 @@ repository = "https://github.com/storytold/pdfcraft"
|
||||
|
||||
[workspace.dependencies]
|
||||
# Shared frontend components; engines remain independent of egui.
|
||||
craft-ui = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0", features = ["serde"] }
|
||||
craft-ui = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545", features = ["serde"] }
|
||||
# Quit the macOS way (#1136): ⌘Q asks about unsaved changes, and closing quits through `terminate:`.
|
||||
craft-quit = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0" }
|
||||
craft-quit = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545" }
|
||||
# One menu definition for the native macOS menu bar and the in-window bar elsewhere.
|
||||
craft-menu = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0" }
|
||||
craft-keymap = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0", default-features = false }
|
||||
craft-menu = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545" }
|
||||
craft-keymap = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545", default-features = false }
|
||||
# Shared system spooler; document composition remains in pdfcraft-print.
|
||||
craft-print = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0" }
|
||||
craft-print = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545" }
|
||||
# Whether a path stored in a document may be opened (GoToR link targets).
|
||||
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0" }
|
||||
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0", features = ["egui"] }
|
||||
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "e11f9d9aebea5f6b8e74643c1ea1ed172ba5f545" }
|
||||
# craft-update: app-specific pretend versions apply to startup and manual checks.
|
||||
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "04aa1703b32d299e54f78fcde4182f2b393a9116", features = ["egui"] }
|
||||
# internal
|
||||
pdfcraft-geom = { path = "crates/geom", version = "0.14.0" }
|
||||
pdfcraft-filters = { path = "crates/filters", version = "0.14.0" }
|
||||
pdfcraft-cos = { path = "crates/cos", version = "0.14.0" }
|
||||
pdfcraft-crypt = { path = "crates/crypt", version = "0.14.0" }
|
||||
pdfcraft-organize = { path = "crates/organize", version = "0.14.0" }
|
||||
pdfcraft-measure = { path = "crates/measure", version = "0.14.0" }
|
||||
pdfcraft-annot = { path = "crates/annot", version = "0.14.0" }
|
||||
pdfcraft-audit = { path = "crates/audit", version = "0.14.0" }
|
||||
pdfcraft-fonts = { path = "crates/fonts", version = "0.14.0" }
|
||||
pdfcraft-model = { path = "crates/model", version = "0.14.0" }
|
||||
pdfcraft-content = { path = "crates/content", version = "0.14.0" }
|
||||
pdfcraft-redact = { path = "crates/redact", version = "0.14.0" }
|
||||
pdfcraft-print = { path = "crates/print", version = "0.14.0" }
|
||||
pdfcraft-xfdf = { path = "crates/xfdf", version = "0.14.0" }
|
||||
pdfcraft-sign = { path = "crates/sign", version = "0.14.0" }
|
||||
pdfcraft-optimize = { path = "crates/optimize", version = "0.14.0" }
|
||||
pdfcraft-a11y = { path = "crates/a11y", version = "0.14.0" }
|
||||
pdfcraft-oracle = { path = "crates/oracle", version = "0.14.0" }
|
||||
pdfcraft-testkit = { path = "crates/testkit", version = "0.14.0" }
|
||||
pdfcraft-ocr = { path = "crates/ocr", version = "0.14.0" }
|
||||
pdfcraft-js = { path = "crates/js", version = "0.14.0" }
|
||||
pdfcraft-compare = { path = "crates/compare", version = "0.14.0" }
|
||||
pdfcraft-preflight = { path = "crates/preflight", version = "0.14.0" }
|
||||
pdfcraft-export = { path = "crates/export", version = "0.14.0" }
|
||||
pdfcraft-edit = { path = "crates/edit", version = "0.14.0" }
|
||||
pdfcraft-create = { path = "crates/create", version = "0.14.0" }
|
||||
pdfcraft-forms = { path = "crates/forms", version = "0.14.0" }
|
||||
pdfcraft-xfa = { path = "crates/xfa", version = "0.14.0" }
|
||||
pdfcraft-render = { path = "crates/render", version = "0.14.0" }
|
||||
pdfcraft-engine = { path = "crates/engine", version = "0.14.0" }
|
||||
pdfcraft-platform = { path = "crates/platform", version = "0.14.0" }
|
||||
pdfcraft-ui-egui = { path = "crates/ui-egui", version = "0.14.0" }
|
||||
pdfcraft-automation = { path = "crates/automation", version = "0.14.0", default-features = false }
|
||||
pdfcraft-geom = { path = "crates/geom", version = "0.15.0" }
|
||||
pdfcraft-filters = { path = "crates/filters", version = "0.15.0" }
|
||||
pdfcraft-cos = { path = "crates/cos", version = "0.15.0" }
|
||||
pdfcraft-crypt = { path = "crates/crypt", version = "0.15.0" }
|
||||
pdfcraft-organize = { path = "crates/organize", version = "0.15.0" }
|
||||
pdfcraft-measure = { path = "crates/measure", version = "0.15.0" }
|
||||
pdfcraft-annot = { path = "crates/annot", version = "0.15.0" }
|
||||
pdfcraft-audit = { path = "crates/audit", version = "0.15.0" }
|
||||
pdfcraft-fonts = { path = "crates/fonts", version = "0.15.0" }
|
||||
pdfcraft-model = { path = "crates/model", version = "0.15.0" }
|
||||
pdfcraft-content = { path = "crates/content", version = "0.15.0" }
|
||||
pdfcraft-redact = { path = "crates/redact", version = "0.15.0" }
|
||||
pdfcraft-print = { path = "crates/print", version = "0.15.0" }
|
||||
pdfcraft-xfdf = { path = "crates/xfdf", version = "0.15.0" }
|
||||
pdfcraft-sign = { path = "crates/sign", version = "0.15.0" }
|
||||
pdfcraft-optimize = { path = "crates/optimize", version = "0.15.0" }
|
||||
pdfcraft-a11y = { path = "crates/a11y", version = "0.15.0" }
|
||||
pdfcraft-oracle = { path = "crates/oracle", version = "0.15.0" }
|
||||
pdfcraft-testkit = { path = "crates/testkit", version = "0.15.0" }
|
||||
pdfcraft-ocr = { path = "crates/ocr", version = "0.15.0" }
|
||||
pdfcraft-js = { path = "crates/js", version = "0.15.0" }
|
||||
pdfcraft-compare = { path = "crates/compare", version = "0.15.0" }
|
||||
pdfcraft-preflight = { path = "crates/preflight", version = "0.15.0" }
|
||||
pdfcraft-export = { path = "crates/export", version = "0.15.0" }
|
||||
pdfcraft-edit = { path = "crates/edit", version = "0.15.0" }
|
||||
pdfcraft-create = { path = "crates/create", version = "0.15.0" }
|
||||
pdfcraft-forms = { path = "crates/forms", version = "0.15.0" }
|
||||
pdfcraft-xfa = { path = "crates/xfa", version = "0.15.0" }
|
||||
pdfcraft-render = { path = "crates/render", version = "0.15.0" }
|
||||
pdfcraft-engine = { path = "crates/engine", version = "0.15.0" }
|
||||
pdfcraft-platform = { path = "crates/platform", version = "0.15.0" }
|
||||
pdfcraft-ui-egui = { path = "crates/ui-egui", version = "0.15.0" }
|
||||
pdfcraft-automation = { path = "crates/automation", version = "0.15.0", default-features = false }
|
||||
|
||||
# pdf
|
||||
hayro = "0.7.1"
|
||||
@@ -65,6 +66,11 @@ hayro-syntax = "0.7.2"
|
||||
lopdf = "0.45"
|
||||
flate2 = { version = "1.1", default-features = false, features = ["rust_backend"] }
|
||||
weezl = "0.2"
|
||||
# CCITT Group 4 encoding (pdfcraft-filters); already in the tree through tiff.
|
||||
fax = "0.2.7"
|
||||
# Independent CCITT and JBIG2 codecs, already in the tree through hayro.
|
||||
hayro-ccitt = "0.3"
|
||||
hayro-jbig2 = "0.3"
|
||||
|
||||
# foundation
|
||||
thiserror = "2"
|
||||
@@ -91,6 +97,9 @@ web-time = "1.1"
|
||||
unsafe_code = "forbid"
|
||||
|
||||
[workspace.lints.clippy]
|
||||
cognitive_complexity = "deny"
|
||||
too_many_arguments = "deny"
|
||||
wildcard_imports = "deny"
|
||||
dbg_macro = "warn"
|
||||
todo = "warn"
|
||||
|
||||
@@ -125,6 +134,7 @@ hayro-postscript = { path = "vendor/hayro-postscript" }
|
||||
hayro-jbig2 = { path = "vendor/hayro-jbig2" }
|
||||
lopdf = { path = "vendor/lopdf" }
|
||||
vello_common = { path = "vendor/vello_common" }
|
||||
vello_cpu = { path = "vendor/vello_cpu" }
|
||||
# The egui and winit crates below are pinned to immutable storytold git revisions (egui
|
||||
# 6d518fc799681571963842f95b55a6b68431b15a, winit a517b3846ee8457d84ee4975110bfda6797c44dc).
|
||||
# Only the retained `vendor/winit` and `vendor/egui-wgpu` copies are provenance for the app's
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
|
||||
|
||||
<p align="center">
|
||||
<img src="assets/app-icon/hicolor/256x256/apps/ai.storyteller.pdfcraft.png" width="128" height="128" alt="PdfCraft icon: an engraved lion on a teal tile">
|
||||
<img src="assets/app-icon/hicolor/256x256/apps/ai.storyteller.pdfcraft.png" width="128" height="128" alt="PdfCraft icon: an engraved lion on a red tile">
|
||||
</p>
|
||||
|
||||
<h1 align="center">PdfCraft</h1>
|
||||
@@ -21,10 +21,10 @@
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<img alt="License: MIT OR Apache-2.0" src="https://img.shields.io/badge/license-MIT%20OR%20Apache--2.0-12a58a?style=flat-square">
|
||||
<img alt="Written in Rust" src="https://img.shields.io/badge/written%20in-Rust-0a7563?style=flat-square">
|
||||
<img alt="Platforms: macOS, Windows, Linux, FreeBSD, web" src="https://img.shields.io/badge/runs%20on-macOS%20%C2%B7%20Windows%20%C2%B7%20Linux%20%C2%B7%20FreeBSD%20%C2%B7%20web-12a58a?style=flat-square">
|
||||
<img alt="No account, no telemetry" src="https://img.shields.io/badge/no%20account-no%20telemetry-0a7563?style=flat-square">
|
||||
<img alt="License: MIT OR Apache-2.0" src="https://img.shields.io/badge/license-MIT%20OR%20Apache--2.0-b70228?style=flat-square">
|
||||
<img alt="Written in Rust" src="https://img.shields.io/badge/written%20in-Rust-8a011e?style=flat-square">
|
||||
<img alt="Platforms: macOS, Windows, Linux, FreeBSD, web" src="https://img.shields.io/badge/runs%20on-macOS%20%C2%B7%20Windows%20%C2%B7%20Linux%20%C2%B7%20FreeBSD%20%C2%B7%20web-b70228?style=flat-square">
|
||||
<img alt="No account, no telemetry" src="https://img.shields.io/badge/no%20account-no%20telemetry-8a011e?style=flat-square">
|
||||
<br>
|
||||
<a href="https://sonarcloud.io/project/overview?id=storytold_pdfcraft"><img alt="Scanned by SonarCloud" src="https://img.shields.io/badge/Scanned_by-SonarCloud-4b9fd5?style=flat-square&logo=sonarqubecloud&logoColor=white"></a>
|
||||
<a href="https://coderabbit.ai"><img alt="Reviewed by CodeRabbit" src="https://img.shields.io/coderabbit/prs/github/storytold/pdfcraft?style=flat-square&label=Reviewed%20by%20CodeRabbit&logo=coderabbit"></a>
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
# PdfCraft roadmap
|
||||
|
||||
> **Last reviewed:** 2026-10-31 | **Last updated:** 2026-10-31 | **Change:** patch (M2, PR #4172: integrate main fa5f9f8c; retain CJK viewer and upstream raster regressions, restore explicit display_config imports; estimates unchanged)
|
||||
> **Last reviewed:** 2026-10-28 · **Last updated:** 2026-10-28 · **Change:** patch (M2, PR #4172: integrate main 5af10276; retain both roadmap histories and viewer-only CJK font policy; estimates unchanged)
|
||||
> **Last reviewed:** 2026-10-27 · **Last updated:** 2026-10-27 · **Change:** patch (M2, PR #4172: integrate main 1dd2737b; preserve viewer-only CJK fallback and regression coverage across engine, renderer and Combine module splits; estimates unchanged)
|
||||
> **Last reviewed:** 2026-10-27 · **Last updated:** 2026-10-27 · **Change:** patch (M2, PR #4172: integrate main 9a9813bf and preserve viewer-only CJK fallback through the engine module split; estimates unchanged)
|
||||
@@ -7,9 +8,11 @@
|
||||
> **Last reviewed:** 2026-10-26 · **Last updated:** 2026-10-26 · **Change:** patch (M2, PR #4172: print preview excludes installed CJK fonts and isolates its font cache from the viewer; estimates unchanged)
|
||||
> **Last reviewed:** 2026-10-26 · **Last updated:** 2026-10-26 · **Change:** patch (M2, PR #4172: reconcile current main while retaining display-only CJK fallback and upstream Japanese font selection; estimates unchanged)
|
||||
> **Last reviewed:** 2026-10-23 · **Last updated:** 2026-10-23 · **Change:** minor (M2, PR #4172: extend on-screen CJK fallback to Combine thumbnails and figure previews; recognise FangSong and subset-prefixed Founder names; estimates unchanged)
|
||||
> **Last reviewed:** 2026-10-15 · **Last updated:** 2026-10-15 · **Change:** minor (typed small Edit font sizes and Fill & Sign text/date colour, #2444/#2496; estimates unchanged)
|
||||
|
||||
**Stage: alpha** · next: beta, ~25% (ready for real work 50% → 75%) and ~400–700 h away
|
||||
|
||||
> **Last reviewed:** 2026-10-29 | **Last updated:** 2026-10-29 | **Change:** minor (M7 #2517: a narrowed then widened paragraph keeps the typed spaces the wrap consumed, after save and reopen; estimates unchanged)
|
||||
> **Last reviewed:** 2026-10-27 | **Last updated:** 2026-10-27 | **Change:** minor (M10: OCR model downloads use verified ONNX pairs with legacy discovery fallback; estimates unchanged)
|
||||
> **Last reviewed:** 2026-10-25 | **Last updated:** 2026-10-25 | **Change:** minor (M14 localization current state: Arabic logical catalog, explicit RTL label direction and mirrored stock chrome; native/browser RTL workflows unqualified. Native release Hans face via LXGW WenKai Lite; estimates unchanged)
|
||||
> **Last reviewed:** 2026-10-23 · **Last updated:** 2026-10-23 · **Change:** minor (M7, #2636 partial: pasting added text boxes and images in the engine and through `content_copy`; estimates unchanged)
|
||||
@@ -29,6 +32,7 @@
|
||||
> **Last reviewed:** 2026-10-20 | **Last updated:** 2026-10-20 | **Change:** minor (M2, #3574: named form properties retain page origin and own dictionary boundaries; estimates unchanged)
|
||||
> **Last reviewed:** 2026-10-20 · **Last updated:** 2026-10-20 · **Change:** minor (M4: initial-view options resolve indirect boolean preferences; estimates unchanged)
|
||||
> **Last reviewed:** 2026-10-16; **Last updated:** 2026-10-16; **Change:** minor (M5 #2669, item 5: reply groups and page root counts per frame; estimates unchanged)
|
||||
> **Last reviewed:** 2026-10-18 · **Last updated:** 2026-10-18 · **Change:** minor (M7 #2517: a partial rewrite keeps its marker around a kept row, and off the next marked region; estimates unchanged) · **Target:** Adobe Acrobat Pro (Acrobat DC, continuous track 26.002.21931, macOS)
|
||||
> **Last reviewed:** 2026-10-15 · **Last updated:** 2026-10-15 · **Change:** minor (M7: the Edit text caret is as tall as the row it is on; estimates unchanged) · **Target:** Adobe Acrobat Pro (Acrobat DC, continuous track 26.002.21931, macOS)
|
||||
> **Last reviewed:** 2026-10-15 · **Last updated:** 2026-10-15 · **Change:** minor (M6: CSV tab-containing headers; estimates unchanged)
|
||||
> **Last reviewed:** 2026-10-18 · **Last updated:** 2026-10-18 · **Change:** minor (M3, #3149: discard render demand after page geometry changes and check the GPU texture limit before upload; estimates unchanged)
|
||||
@@ -103,8 +107,8 @@ and add a line to the [progress log](#progress-log); when a gap closes, remove i
|
||||
|
||||
| | Value | Kind |
|
||||
|---|---|---|
|
||||
| **Feature breadth** | **≈ 67%** tier-weighted (56.9% unweighted: 423 shipped + 74 partial of 808; P0 94.2%) | measured, `parity/acrobat-features.toml` |
|
||||
| Feature breadth, mainstream practitioner | ≈ 70% tier-weighted (63.2% unweighted; P0 95.3%) | measured ([split](docs/target-app-parity.md#mainstream-practitioner-vs-full-acrobat-pro)) |
|
||||
| **Feature breadth** | **≈ 67%** tier-weighted (57.0% unweighted: 423 shipped + 75 partial of 808; P0 94.2%) | measured, `parity/acrobat-features.toml` |
|
||||
| Feature breadth, mainstream practitioner | ≈ 70% tier-weighted (63.3% unweighted; P0 95.3%) | measured ([split](docs/target-app-parity.md#mainstream-practitioner-vs-full-acrobat-pro)) |
|
||||
| **Ready for real work**, full Acrobat Pro | **≈ 50%** (45–53%) | estimated, weighted sum over [dimensions](#by-dimension) |
|
||||
| **Ready for real work**, mainstream practitioner | **≈ 55%** (50–60%) | estimated ([split](docs/target-app-parity.md#mainstream-practitioner-vs-full-acrobat-pro)) |
|
||||
| **Ready for real work**, essentials user | **≈ 66%** (60–70%) | estimated ([method](docs/target-app-parity.md#essentials-user)) |
|
||||
@@ -159,7 +163,7 @@ Hours are calibrated as in [Effort and calibration](docs/target-app-parity.md#ef
|
||||
| H Digital signatures | 62.2% | 45% | 40–70 |
|
||||
| I Scan and OCR | 23.1% | 15% | 40–75 |
|
||||
| J Create and export | 39.7% | 25% | 55–100 |
|
||||
| K Optimize and standards | 34.5% | 20% | 65–115 |
|
||||
| K Optimize and standards | 35.3% | 20% | 65–115 |
|
||||
| L Print | 39.7% | 35% | 30–55 |
|
||||
| M Accessibility | 63.1% | 30% | 40–70 |
|
||||
| N Automation, preferences, misc | 30.0% | 35% | 25–45 |
|
||||
@@ -208,6 +212,8 @@ Ranked; detail and the full milestone table in [docs/roadmap.md](docs/roadmap.md
|
||||
|
||||
## Progress log
|
||||
|
||||
- **2026-10-31 (M2, PR #4172):** Integrated main fa5f9f8c, retaining both roadmap histories and raster regression groups. Restored display_config and thumbnail_config imports after the upstream explicit-import migration. Validation: 422 renderer unit tests, engine/UI all-target checks, scoped all-target Clippy with -D warnings, formatting, layers, assets, parity and renderer/engine WASM checks passed. Existing optional-patch/WASM warnings and parity notes remain; no full engine/UI runtime test rerun. Display-only font policy and estimates unchanged.
|
||||
|
||||
- **2026-10-28 (M2, PR #4172):** Integrated main 5af10276, preserving both roadmap histories and reviewing auto-merged export tests and accessibility UI changes. Validation: 488 scoped tests passed (18 engine, 412 renderer unit, 43 renderer integration, 15 Combine; one existing renderer integration test ignored); scoped all-target Clippy with -D warnings, formatting, layers, assets, parity and renderer/engine WASM checks passed. Viewer-only CJK fallback and print/output font policy remain unchanged; estimates unchanged.
|
||||
|
||||
- **2026-10-27 (M2, PR #4172 module-split conflicts):** Integrated main 1dd2737b, retaining viewer-only CJK fallback in split session modules and Combine thumbnail workers, and moving renderer regressions to the new test module. Validation: 798 scoped tests passed (371 engine, 412 renderer, 15 Combine; two existing engine tests ignored); scoped all-target Clippy with -D warnings, formatting, layers, assets, parity and renderer/engine WASM checks passed. Estimates unchanged.
|
||||
@@ -216,10 +222,21 @@ Ranked; detail and the full milestone table in [docs/roadmap.md](docs/roadmap.md
|
||||
|
||||
- **2026-10-26 (M2, PR #4172):** Reconciled current main, preserving its Japanese serif/weight selection and both branches' progress records. Installed CJK viewer and preview fallback remains display-only; estimates unchanged.
|
||||
|
||||
- **2026-10-29 (M7, #2517):** Widening a paragraph rejoins a wrap with the number of spaces that wrap consumed, including a typed run and none for a Chinese or Japanese word split. The count survives an incremental save and a full rewrite, and a width-only `text_edit` uses it. Estimates unchanged.
|
||||
- **2026-10-26 (M11, JBIG2 symbols):** Lossless JBIG2 now stores each distinct mark of a black-and-white image once, as a symbol, and places its exact copies, when that is smaller than the generic region: on six pages of rendered 300 dpi text 28% of the generic region's size and 17% of Group 4's, and the same bits back through two independent decoders (hayro-jbig2 and Poppler). Scans, whose letters are seldom identical, gain little until refinement coding; a dictionary shared between pages (`/JBIG2Globals`) is next. Estimates unchanged.
|
||||
- **2026-10-25 (M5, comment replies):** One reply can be deleted from the Comments panel without its thread. On the selected card each reply has its own "…" menu (Edit, Copy text, Delete); Delete takes that reply with its pop-up and the replies to it, as `comment_delete` already did headlessly, and the comment and its other replies stay. The card stays selected, and the panel's editor stays open, on what they were on though the delete moved it in `/Annots`. Undo and Redo close the editor, since either can move what it was open on. A locked reply can't be deleted. Estimates unchanged.
|
||||
- **2026-10-24 (M10, #4158 partial):** Word, HTML, RTF and PowerPoint export keep a block that continues another on its line (an italic case name, a link, a superscript) as a run in its own style inside that paragraph, with the source's word space, instead of a paragraph of its own. Style changes that wrap onto the next line still split paragraphs (the reading blocks keep style boundaries). Estimates unchanged.
|
||||
- **2026-10-24 (M3, window move on Wayland, #3970 follow-up):** After a move or resize by PdfCraft's own title bar or edges, the button release given back to egui goes before the pointer leaving the window, so hover no longer sticks at the old place until the pointer moves. Found by CodeRabbit in review of #3970; a unit test covers it. Estimates unchanged.
|
||||
- **2026-10-24 (M14, #4253):** The annotation quick bar remembers Keep tool selected across restarts, including unpinning. Old and malformed settings keep safe defaults; the opt-in UI control channel reads and changes the same preference. Estimates unchanged.
|
||||
- **2026-10-22 (M7, #2517):** A partial rewrite of the last paragraph closes its marker after that paragraph's last `ET`, so a row left in the source stays in the paragraph. When the next paragraph shares the text object, the marker closes before that neighbour instead of after the shared `ET`. The extra marker is not added across two marked-content regions. Estimates unchanged.
|
||||
- **2026-10-15 (M7, #2517):** A blank line between paragraphs stays a paragraph break. An explicit `TL` is the measured baseline gap. Without one, three or more rows at a repeated step stay one paragraph, and a single wider gap stays a break. Adding a row, even when an earlier row is left in the source, does not absorb the next paragraph on a later edit. Estimates unchanged.
|
||||
|
||||
- **2026-10-24 (M11, more black-and-white images):** The optimizer re-stores Group 3 fax images as Group 4 when that is smaller, instead of leaving any CCITT image it doesn't resample as it is. Black-and-white images stored as eight-bit RGB (as some phone and scanner apps write them) become one-bit grey, and indexed images that use only their first two palette entries become one bit with their palette, so Monochrome Images compresses and downsamples them too.
|
||||
- **2026-10-24 (M11, monochrome downsampling):** The PDF Optimizer and Reduce File Size average black-and-white images above 450 ppi down to 300 ppi (Monochrome Images ▸ Downsample to), Group 4 scans included, so a 600 ppi text page goes from 79 KB to 40 KB. CCITT decoding moved into `pdfcraft-filters` (`decode_ccitt`), shared by Export ▸ Images and the optimizer through `Document::decoded_image`.
|
||||
- **2026-10-24 (M11, black-and-white pictures):** A scan saved as a 1-bit PNG became an eight-bit grey image when made into a PDF, larger than the PNG; Create PDF now stores pictures of only black and white at one bit (Group 4 when smaller), the optimizer packs eight-bit black-and-white grey images to one bit unless the grey settings make them smaller, as they can a dithered scan, soft mask counted, and Export ▸ Images reads CCITT fax images.
|
||||
- **2026-10-23 (M11, JBIG2):** The PDF Optimizer can store black-and-white images as lossless JBIG2 (a generic region, written from the JBIG2 draft standard and checked against its arithmetic-coder test sequence), about a third smaller than Group 4 on 300 dpi text, and Export ▸ Images reads JBIG2 images. JBIG2 symbol coding, where its largest gains on text are, is next.
|
||||
- **2026-10-23 (M11, monochrome compression):** The PDF Optimizer and Reduce File Size store black-and-white images (scans, image masks) losslessly as CCITT Group 4 when that is smaller, with a Monochrome Images setting in the Optimizer and `doc_optimize` `mono`. JBIG2 and monochrome downsampling are next.
|
||||
- **2026-10-23 (M6, calculation checks):** The calculation order now flags a formula that reads a field the form doesn't have (a field deleted from under a sum, a typo in notation, a script's `getField`) and a script that builds the names it reads at run time. Prepare a form ▸ Calculation order marks both on the row and in a card that names the broken formulas, in place of its all-clear. `form_calculation_order` gives each field's formula, and `form_fields` shows a custom Calculate script.
|
||||
- **2026-10-23 (M7, #4280):** Edit text names each standard stand-in font after its face (`PCEdTimesBold`, ...) instead of one shared `PCEdHelv`. Rewriting a bold paragraph whose subset lacks an accent no longer repoints the paragraphs set earlier in a regular stand-in at Times-Bold, and the editor's frame stays on the paragraph being edited. Pages saved by older builds keep their shared name and are not repaired. Estimates unchanged.
|
||||
- **2026-10-23 (M8, #3205 follow-up):** Phone-pattern redaction matches complete labelled Italian geographic numbers such as `Tel. +39 0426/123456`, with synthetic matcher and mark/apply/save/reopen coverage; unlabelled international slash numbers remain unsupported.
|
||||
- **2026-10-23 (M7, #2636 partial):** A new `PasteContent` edit pastes an added text box or image copied in the same document or another, keeping its style, picture, turns, flips and crop, as one undo step; `content_copy` drives it headlessly. A paste lands beside earlier copies (18 pt steps) and stays on the page. A pasted image reuses its picture object in its own document and after the first paste into another; there a colour profile is dropped and CMYK colours stored losslessly are turned to RGB. The desktop keys and menus follow in separate PRs. Estimates unchanged.
|
||||
@@ -235,6 +252,7 @@ Ranked; detail and the full milestone table in [docs/roadmap.md](docs/roadmap.md
|
||||
The regression checks two distinct appearances, inherited resources, print/reopen pixels and unchanged source data.
|
||||
Estimates unchanged.
|
||||
- **2026-10-21 (M3, window resize and move on Wayland):** With PdfCraft's own title bar on GNOME/Wayland, a second resize by a window edge, or a second move by the empty tab strip, works straight after the first; it waited for a click inside the window, because the compositor keeps the button's release from egui. A unit test covers the release given back; checked by hand in a test build. Estimates unchanged.
|
||||
- **2026-10-24 (M5, move preview):** A comment being moved is drawn where it goes while it is dragged (a rectangle or oval showed only its blue frame): the comment is rendered alone once as the drag starts and laid over the page, which shows it where it was until the move is applied. Engine `Document::comment_layer`; synthetic engine and UI regressions. Estimates unchanged.
|
||||
- **2026-10-22 (M4, #3916 partial):** Document edits and Undo/Redo cancel an Organize page drag. Pointer-release regressions check exact page order and save/reopen.
|
||||
- **2026-10-22 (M10, #3752 paper):** CUPS jobs ask for the chosen paper in every size. The 13 sizes the Print dialog sent no paper for (A6, A0–A2, ARCH, ANSI C–E) use PWG 5101.1 names, checked against a synthetic PPD with `cupsfilter`, and `doc_print` to a printer sends the paper too. The macOS tray half (Auto Select instead of the PPD's default tray) is a craft-print change that needs a pin bump here. Estimates unchanged.
|
||||
|
||||
@@ -317,6 +335,7 @@ Ranked; detail and the full milestone table in [docs/roadmap.md](docs/roadmap.md
|
||||
- **2026-10-19 (M3, #3360):** Switching between Read and the docking workspace retains the current document’s scroll position at fixed zoom, including within-page position; separate tabs retain their own offsets. Estimates unchanged.
|
||||
- **2026-10-18 (M8, #1350):** Integrated current main while preserving content-stream comment boundaries. Hidden-text cleanup retires unused named replacement descriptions on rewritten pages and forms, including inherited/shared resource holders, without removing descriptions still used by surviving content. Synthetic saved-byte and preservation regressions cover the cleanup. Estimates unchanged.
|
||||
- **2026-10-17 (M4, #2997):** Dragging page thumbnails in the Organize grid with Ctrl held (Option on macOS) drops copies at the gap instead of moving the pages: a "+" badge sits by the pointer, the copies land at the gap selected, and one undo step ("Duplicate pages") takes them out again. `page_duplicate` takes `at` (1-based, where the first copy goes; left out, after the last of them) so agents can drive the same thing, and the UI control channel's `ui.drag` modifiers now reach gestures that read the input state. Estimates unchanged.
|
||||
- **2026-10-16 (M7, Add Background):** A background added behind a page that paints its own opaque white backdrop (browsers' Save as PDF, print drivers) was hidden completely, so the tool looked broken. The dialog now detects such pages and offers to replace the backdrop (on by default): the one fill becomes `n` in a per-page copy of its stream, and Remove background turns the fill back on, after edits and redactions too, unless the operators before it changed or it would no longer be painted first; then it says which pages keep it off. The copy's tag holds no reference to the original stream, which had kept text a redaction or Remove Hidden Information removed in the saved file. Scanned pages are warned about, not touched. New `doc_backdrops` tool; `doc_background` takes `replace_backdrop`. The default colour is a visible light yellow and the preview shows text over it. Acrobat's own behaviour on such pages is unobserved. Estimates unchanged.
|
||||
- **2026-10-15 (M6, AcroForm XML text):** Plain AcroForm XML imports retain all direct text around comments and processing instructions, including CDATA and character references. Synthetic regressions verify exact values and unknown catalog data after incremental and full save/reopen. Nested-element and XFA interpretation are unchanged. Estimates unchanged.
|
||||
- **2026-10-15 (M6, #1917 refresh):** Integrated upstream `99941daa` while retaining the XML/XFDF attribute whitespace correction and all upstream progress. Only independent documentation conflicts required resolution; focused production and test files are unchanged from the previously green CI head. Estimates unchanged.
|
||||
- **2026-10-15 (M1, #2267 refresh):** Integrated upstream `99941daa` while retaining the raw-deflate fallback correction and all upstream progress. Only independent documentation conflicts required resolution; focused production and test files are unchanged from the previously green CI head. Estimates unchanged.
|
||||
@@ -468,6 +487,7 @@ Ranked; detail and the full milestone table in [docs/roadmap.md](docs/roadmap.md
|
||||
|
||||
Newest first: the date, what moved, and the new overall estimate.
|
||||
|
||||
- **2026-10-28 (M10, #1595):** Export to Markdown: `doc_export_office` with a `.md` or `.markdown` path writes CommonMark with GitHub pipe tables (headings, paragraphs with bold and italic, tables with their first row as the header, a rule between pages); text that Markdown would read as markup is escaped. Images, lists and links are not in the export's layout model and are left out. No menu item yet. Estimates unchanged.
|
||||
- **2026-10-12 (M3, GNOME title bar, #553):** On GNOME's Wayland session, whose compositor draws no window frames (it offers no `zxdg_decoration_manager_v1`), PdfCraft no longer shows winit's fallback title bar: it turns the frame off and the tab strip becomes the header bar, as in GNOME's own apps. Minimize, maximize/restore and close are drawn in Adwaita's style, in the order and on the side GNOME's `button-layout` names (Fedora's default shows only close); the window's edges and corners resize it, and a hairline outlines it while it isn't maximized. Preferences ▸ Use system title bar (shown only there) gives the window back winit's frame at once, without a restart (part of #1001), and `PDFCRAFT_TITLEBAR=app|system` overrides the choice. KDE, Sway, Hyprland, COSMIC and X11 keep the frame their desktop draws. Not done: right-clicking the header bar doesn't open GNOME's window menu (egui can't ask for it), the window has no shadow or rounded corners, the resize edges lie just inside the window rather than outside it, and Windows still uses its system frame (the rest of #1001). Estimates unchanged.
|
||||
- **2026-10-12 (M0, build label):** A local or patched build can carry a label, set at compile time with `PDFCRAFT_BUILD_LABEL`: `pdfcraft --version`, `pdfcraft-cli --version`, About and the log show `0.7.1 (titlebar)`, and `packaging/linux/package.sh` names the files `pdfcraft-0.7.1-titlebar-…` and makes the .rpm/.deb release `1.titlebar`, which upgrades over the release of the same version (and the next release over it). The version itself is unchanged, so the update check still compares it with published releases. Unlabelled builds are as before. Estimates unchanged.
|
||||
- **2026-10-11 (M6, #1208):** Dropdown and list-box Field Properties expose the existing Left/Center/Right alignment picker. Existing alignment stays intact until changed; cancel, undo/redo and save/reopen are covered through the real UI without changing options, values or flags. Estimates unchanged.
|
||||
@@ -776,3 +796,9 @@ Newest first: the date, what moved, and the new overall estimate.
|
||||
- **2026-10-26 (M2, PR #4172 documentation review):** Added function documentation for installed-font script selection, bounded candidate reads, platform paths, resolver precedence and regression contracts. No runtime behavior or estimate change.
|
||||
|
||||
- **2026-10-27 (M2, PR #4172 conflict resolution):** Integrated main `9a9813bf` and its engine module split. Opening, layer changes and session renderer rebuilds retain display-only CJK fallback; output configuration and print-preview cache isolation are preserved. Validation passed: 16 scoped engine regressions, 412 renderer unit tests, 43 renderer integration tests (one existing corpus case ignored), 15 Combine tests, scoped Clippy, formatting, layers/assets/parity and renderer/engine WASM checks. Estimates unchanged.
|
||||
## Pages sidebar keyboard refresh (2026-10-30)
|
||||
|
||||
PR #2133 retains document-local Pages sidebar focus for Ctrl/Cmd+A and Escape after the UI module split. The selection does not navigate. The focused regression is in `crates/ui-egui/tests/it/view.rs`; current-head hosted validation is pending. Feature counts and estimates are unchanged.
|
||||
## Button export-value refresh (2026-10-30)
|
||||
|
||||
PR #1952 retains per-widget checkbox/radio export-value editing in the split form-authoring and Prepare modules. Caption editing remains supported. Tests cover preserved appearances and selection, invalid/locked refusals, data-format round trips, and Apply/Cancel/Undo. Current-head hosted validation is pending; feature estimates are unchanged.
|
||||
@@ -1,6 +1,8 @@
|
||||
use super::commands::{parse_dpi, read};
|
||||
use super::options::{AUDIT_OPTIONS, CHECK_ONE_OPTIONS, CHECK_OPTIONS, flag, positional, validate_options};
|
||||
use super::*;
|
||||
use super::{
|
||||
Arc, CliError, Command, Duration, Instant, PageRenderer, Path, PathBuf, RenderConfig, RenderRequest, RequestKind, Stdio, inspect, stdout_line,
|
||||
};
|
||||
|
||||
/// Audit a document for faux redactions. Prints the findings as JSON; fails when any are
|
||||
/// found so scripts and CI can gate on it, and when the audit itself cannot run.
|
||||
|
||||
@@ -2,7 +2,7 @@ use super::options::{
|
||||
COMBINE_OPTIONS, EXTRACT_OPTIONS, INFO_OPTIONS, RENDER_OPTIONS, SPLIT_OPTIONS, TEXT_OPTIONS, can_be_path_value, flag, needs_value, positional,
|
||||
validate_options,
|
||||
};
|
||||
use super::*;
|
||||
use super::{Arc, CliError, ImageFormat, PageRenderer, Path, PathBuf, RenderConfig, RenderRequest, RequestKind, Write, inspect, stdout_line};
|
||||
|
||||
pub(crate) fn read(path: &str) -> Result<Arc<Vec<u8>>, String> {
|
||||
std::fs::read(path).map(Arc::new).map_err(|e| format!("{path}: {e}"))
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use super::*;
|
||||
use super::CliError;
|
||||
|
||||
pub(crate) fn flag<'a>(args: &'a [String], name: &str) -> Option<&'a str> {
|
||||
args.iter().position(|a| a == name).and_then(|i| args.get(i + 1)).map(String::as_str)
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
#[cfg(feature = "mcp")]
|
||||
use super::options::MCP_OPTIONS;
|
||||
use super::options::{RUN_OPTIONS, flag, positional, validate_options};
|
||||
use super::*;
|
||||
#[cfg(feature = "mcp")]
|
||||
use super::{Arc, Path, Write, automation_args};
|
||||
use super::{CliError, stdout_line};
|
||||
|
||||
// ---- automation --------------------------------------------------------------------------------
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use super::options::{UI_OPTIONS, flag, positional, validate_options};
|
||||
use super::*;
|
||||
use super::{CliError, Duration, stdout_line};
|
||||
|
||||
// ---- UI control channel client -----------------------------------------------------------------
|
||||
|
||||
|
||||
@@ -243,4 +243,40 @@ mod page_argument_tests {
|
||||
assert_eq!(std::fs::read(&source).unwrap(), bytes);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_clips_glyphs_outside_the_crop_box() {
|
||||
let dir = PageDir::new();
|
||||
let path = dir.0.join("cropped.pdf");
|
||||
let body = "BT /F1 12 Tf 20 260 Td (Outside header) Tj 0 -110 Td (Visible body) Tj 0 -120 Td (Outside footer) Tj ET";
|
||||
let objs: Vec<Vec<u8>> = vec![
|
||||
b"<< /Type /Catalog /Pages 2 0 R >>".to_vec(),
|
||||
b"<< /Type /Pages /Kids [4 0 R] /Count 1 /MediaBox [0 0 200 300] >>".to_vec(),
|
||||
b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>".to_vec(),
|
||||
b"<< /Type /Page /Parent 2 0 R /CropBox [0 100 200 200] /Contents 5 0 R /Resources << /Font << /F1 3 0 R >> >> >>".to_vec(),
|
||||
format!("<< /Length {} >>\nstream\n{body}\nendstream", body.len()).into_bytes(),
|
||||
];
|
||||
let mut pdf = b"%PDF-1.7\n".to_vec();
|
||||
let mut offsets = Vec::new();
|
||||
for (i, o) in objs.iter().enumerate() {
|
||||
offsets.push(pdf.len());
|
||||
pdf.extend_from_slice(format!("{} 0 obj\n", i + 1).as_bytes());
|
||||
pdf.extend_from_slice(o);
|
||||
pdf.extend_from_slice(b"\nendobj\n");
|
||||
}
|
||||
let xref = pdf.len();
|
||||
pdf.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objs.len() + 1).as_bytes());
|
||||
for o in offsets {
|
||||
pdf.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes());
|
||||
}
|
||||
pdf.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objs.len() + 1).as_bytes());
|
||||
std::fs::write(&path, pdf).unwrap();
|
||||
|
||||
for args in [vec![], vec!["--page", "1"]] {
|
||||
let out = Command::new(BIN).arg("text").arg(&path).args(&args).output().unwrap();
|
||||
assert!(out.status.success(), "{args:?}: {out:?}");
|
||||
assert!(out.stderr.is_empty(), "{args:?}: {}", String::from_utf8_lossy(&out.stderr));
|
||||
assert_eq!(String::from_utf8(out.stdout).unwrap().trim(), "Visible body", "{args:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -196,7 +196,7 @@ fn rejoin_split_paths(args: Vec<String>, exists: impl Fn(&str) -> bool) -> Vec<S
|
||||
fn main() -> eframe::Result {
|
||||
// Windows: the update helper is a copy of this program started with `--finish-update`.
|
||||
#[cfg(windows)]
|
||||
if let Some(result) = craft_update::self_update::finish(&craft_update::suite::PDFCRAFT, &std::env::args_os().skip(1).collect::<Vec<_>>()) {
|
||||
if let Some(result) = craft_update::self_update::finish(&pdfcraft_ui_egui::UPDATE_APP, &std::env::args_os().skip(1).collect::<Vec<_>>()) {
|
||||
std::process::exit(i32::from(result.is_err()));
|
||||
}
|
||||
// First, so the panic hook and every start-up warning are recorded (`logging`).
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# PdfCraft app icon
|
||||
|
||||
<img src="pdfcraft-small.svg" alt="PdfCraft app icon: an engraved lion's head on green" width="128">
|
||||
<img src="pdfcraft-small.svg" alt="PdfCraft app icon: an engraved lion's head on red" width="128">
|
||||
|
||||
**Creature:** a lion, in a frontal head-and-shoulders portrait, mane running off the bottom of the tile.
|
||||
|
||||
@@ -13,7 +13,7 @@ a full-bleed colour field, no frame or roundel, the animal looking at the viewer
|
||||
|---|---|---|
|
||||
| Ink | `#0b0b0c` | line work and the figure's contour |
|
||||
| Paper | `#efe9dc` | the figure (the lion's silhouette) |
|
||||
| PdfCraft green (app colour) | `#12a58a` | the full-bleed field |
|
||||
| PdfCraft red (app colour) | `#b70228` | the full-bleed field |
|
||||
|
||||
**Tile:** `viewBox="0 0 512 512"`, a rounded square with `rx=112` that clips everything. Windows and Linux
|
||||
icons use the full-bleed tile. macOS icons put it on Apple's grid (an 824 px body centred on a transparent
|
||||
@@ -33,7 +33,7 @@ Licence: [LICENSE.txt](LICENSE.txt) (`MIT OR Apache-2.0`, like the repo).
|
||||
| `pdfcraft-1024.png` | 1024 px on Apple's grid; also the runtime Dock icon on macOS |
|
||||
| `pdfcraft.icns` | macOS icon (16–1024 px) |
|
||||
| `pdfcraft.ico` | Windows icon (16–256 px), embedded in `pdfcraft.exe` by `apps/pdfcraft/build.rs` |
|
||||
| `pdfcraft-document.svg` | Windows PDF file icon master: a Lucide document outline, green badge and outlined PDF lettering; no font dependency |
|
||||
| `pdfcraft-document.svg` | Windows PDF file icon master: a Lucide document outline, red badge and outlined PDF lettering; no font dependency |
|
||||
| `pdfcraft-document.ico` | Windows PDF file icon (16–256 px), embedded as resource 2 in `pdfcraft.exe` |
|
||||
| `hicolor/<n>x<n>/apps/ai.storyteller.pdfcraft.png` | Linux hicolor theme, 16–512 px; the 256 px one is the runtime icon on Windows and Linux |
|
||||
| `hicolor/scalable/apps/ai.storyteller.pdfcraft.svg` | Linux scalable icon (copy of the master) |
|
||||
|
||||
|
Before Width: | Height: | Size: 17 KiB After Width: | Height: | Size: 17 KiB |
|
Before Width: | Height: | Size: 695 B After Width: | Height: | Size: 723 B |
|
Before Width: | Height: | Size: 1.2 KiB After Width: | Height: | Size: 1.2 KiB |
|
Before Width: | Height: | Size: 51 KiB After Width: | Height: | Size: 52 KiB |
|
Before Width: | Height: | Size: 1.9 KiB After Width: | Height: | Size: 1.9 KiB |
|
Before Width: | Height: | Size: 3.5 KiB After Width: | Height: | Size: 3.6 KiB |
|
Before Width: | Height: | Size: 141 KiB After Width: | Height: | Size: 141 KiB |
|
Before Width: | Height: | Size: 5.3 KiB After Width: | Height: | Size: 5.4 KiB |
@@ -1 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><defs><clipPath id="t"><rect width="512" height="512" rx="112"/></clipPath></defs><g clip-path="url(#t)"><rect width="512" height="512" fill="#12a58a"/><path fill="#efe9dc" fill-rule="evenodd" d="M101.8 505.4C68.7 502.1 39.1 483.6 21.7 455.2C13.3 441.6 8.2 426.1 6.6 409.8C6.1 404.5 6.1 340 6.6 339.6C6.7 339.5 7.3 339.2 7.9 339C9.3 338.5 10.9 337.4 11.7 336.3C12.9 334.6 13.9 333.7 16.2 332.1C19.5 330 20 329.8 25.2 328.1C29.9 326.7 31.9 325.9 33.5 324.8C34 324.5 35.3 323.9 36.4 323.5C38.5 322.7 44.3 319.3 45.5 318.1C46.3 317.4 46.7 315.8 46.7 314.1C46.7 313 47.2 310.8 47.8 308.8C48 308.3 49 306.6 50.2 305C53.3 300.9 54.3 299.4 55.6 296.8C56.3 295.4 57.3 293.7 57.9 292.8C59.5 290.5 59.3 289.5 57 288.4C55 287.4 54.2 284.9 54.7 281.7C55 280.2 55 279.8 54.6 278.8C54.2 277.8 54.1 276.8 54.1 272.6C54.1 266.9 54.1 266.7 52.2 266.2C51.6 266.1 51.1 265.7 50.8 265.3C49.9 263.8 47.8 261.7 46.6 260.8C44 259.2 43.9 257.7 45.8 255C46.5 254 47.4 252.7 47.6 252.2C48.3 250.9 49.3 250.1 51.1 249.2C52.9 248.4 53.4 247.8 53.6 246.1C53.7 245.1 53.9 244.7 54.7 244C55.3 243.5 56.5 242.4 57.5 241.5C59.8 239.5 60.4 239.2 66.4 237.9C74.1 236.1 76 235.2 76 233.4C76 233 76.1 232.5 76.2 232.4C76.3 232.2 77 231 77.8 229.6C79.1 227.1 79.1 227 78.6 226.5C77.5 225.2 78.8 221.8 81.8 218.6C84.2 216 85.5 214.1 85.5 213.2C85.5 212.8 85.7 211.9 86 211.2C86.4 210.1 86.5 209.3 86.4 207.1C86.4 204.4 86.4 204.4 85.8 204.4C85.5 204.5 85.2 204.3 85.1 204.1C84.9 203.5 84.6 203.7 84 204.6C82.3 207.5 82.6 201.7 84.5 195.5C84.9 194.1 85.4 192.2 85.5 191.3C85.7 190.4 85.9 189.4 86.2 188.9C86.4 188.4 86.6 187.3 86.7 185.7C86.8 182.5 87.9 180 90.4 177.7C93.3 174.8 94.5 173 94.4 171.9C94.4 170.9 94.3 170.9 93.4 170.8C91.2 170.5 92.2 168.7 95.1 167.6C96.2 167.2 98.2 165.7 98.2 165.2C98.2 165.1 97.7 165 97.1 165L95.9 164.9 95.9 162.9C95.9 161.1 96 160.7 96.6 159.7C96.9 159.1 97.2 158.4 97.2 158.2C97.3 158 97.7 157.3 98.2 156.6C99.5 154.9 101.1 151.9 101.7 150.2C102.2 148.8 104 146.3 105.4 145C106.9 143.5 107.9 139.9 107.1 138.6C106.7 138 106.5 138 105.5 138C104.2 138.1 104.2 138.3 105.1 135C106.2 131.1 106.1 130.5 104.3 131.1C103.5 131.4 103.6 130.9 105 127.9C106.5 124.7 108.3 121.7 110 119.4C110.7 118.4 111.5 117.1 111.7 116.4C112.8 113.4 114.7 110.7 117.2 108.6C118.5 107.5 119 107 119.4 106C119.9 104.7 121.3 103 121.9 103C122 103 122.7 102.3 123.4 101.4C124.6 100 124.7 99.7 124.8 98.1C125.1 95.8 127 93.3 130.1 91.2C130.5 90.9 131 90.3 131.3 89.9C131.9 88.8 132.9 88.2 135.1 87.5C137.1 86.9 137.7 86.4 138.9 84.6C139.4 83.8 139.9 83.2 140.1 83.2C140.6 83.2 142.8 81.3 142.8 80.9C142.8 80.5 144.1 79.3 144.6 79.2C145.3 79.2 147.8 76.9 149.4 74.8C151.2 72.4 152 71.7 154.4 71.1C155.4 70.9 156.1 70.5 157 69.7C158.9 67.8 160.9 67 164 66.6C165.5 66.5 166 66.2 166 65.5C166 64.6 167.1 63.8 168.9 63.3C169.8 63 172.1 62.2 173.8 61.4C175.6 60.6 177.8 59.8 178.7 59.7C179.9 59.5 180.2 59.3 180.2 59C180.2 58 182.7 57.5 186.9 57.5C191.1 57.6 191.8 57.3 193.5 54.9C194.7 53.2 197.3 52.2 200.9 52.1C203.3 52 203.8 51.9 204.1 51.5C204.4 51.2 204.9 51 205.5 51C206.2 51 206.6 50.8 207 50.3C207.4 50 208.2 49.3 208.9 48.8C209.6 48.4 210.4 47.7 210.7 47.3L211.2 46.5 214 46.7L216.7 46.8 217.4 46C217.7 45.6 218 45.1 218 45C218 44.8 218.4 44.5 218.8 44.3C219.2 44 219.7 43.5 219.9 43.2C220.1 42.8 220.3 42.6 220.8 42.7C223.4 43 223.8 43 224.2 42.7C224.5 42.4 225 42.3 225.6 42.3C226.5 42.4 226.6 42.3 227 41.6C227.4 40.7 227.6 38.4 227.3 38.1C226.3 37.5 227.5 36 228.9 36C230.6 36 236.5 38.5 239.6 40.4C241.5 41.6 243.2 42.3 243.6 42C244.5 41.4 246.2 41 248.7 41C250.2 40.9 251.6 40.8 251.8 40.7C252 40.6 253.4 40.4 254.9 40.2C259.3 39.6 260.9 38.6 260.6 36.8C260.3 34.8 261.6 33.7 264.4 33.6C265.9 33.5 266.3 33.6 266.8 34C267.4 34.5 267.4 34.5 267.9 34C268.3 33.6 268.8 33.4 270.3 33.4C272.1 33.4 272.3 33.4 275.1 34.8C276.7 35.6 278.3 36.5 278.7 36.8C279.2 37.3 279.6 37.4 280 37.3C280.6 37.2 280.9 37.5 282.4 39.1C284.2 41.1 284.7 41.3 285.3 40.5C285.5 40.1 285.8 40 286.1 40.1C286.7 40.3 287.9 42.6 288.7 44.9C289.6 47.7 289.6 47.7 291.6 46.2C295.5 43.1 298.8 42.1 298.8 44C298.8 45.4 299.6 45.5 302.3 44.4C306.9 42.5 308.3 42.3 308.8 43.4C309 43.9 309.1 44 310.3 44C312.1 44 311.9 44.6 309.7 45.8C308.7 46.2 307.8 46.9 307.6 47.2C307.4 47.5 306.6 48.1 305.9 48.6C304.5 49.6 302.7 51.5 302.9 51.8C303 51.9 303.4 51.9 303.8 51.7C304.3 51.6 305.5 51.4 306.7 51.3C308.7 51.2 308.7 51.2 309.1 51.8C309.7 52.7 310.3 52.7 312 51.9C312.8 51.5 314.7 50.7 316.4 50C318 49.3 320.4 48.4 321.5 47.9C324.6 46.7 325.8 46.7 324.9 48.1C324.4 49 324.4 49 325.7 48.9C327.9 48.8 327.4 49.7 323.4 53C322 54.2 321.8 54.5 321.8 55.2C321.7 56.4 322.3 56.7 323.6 56.1C324.9 55.6 329 55.3 330.7 55.7C333.1 56.2 335.5 57.5 336 58.5C336.6 59.8 337.6 60.1 340.4 59.7C343.1 59.4 344.5 59.6 345.2 60.4C345.9 61.1 345.7 61.5 344.5 62.4C343.1 63.4 343.3 63.8 345.2 64C347.1 64.2 349.1 65.2 349.2 65.9C349.3 66.6 350.1 67.3 350.9 67.3C351.8 67.2 353.2 67.9 353.4 68.4C353.5 68.6 353.3 69 353 Line truncated
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><defs><clipPath id="t"><rect width="512" height="512" rx="112"/></clipPath></defs><g clip-path="url(#t)"><rect width="512" height="512" fill="#b70228"/><path fill="#efe9dc" fill-rule="evenodd" d="M101.8 505.4C68.7 502.1 39.1 483.6 21.7 455.2C13.3 441.6 8.2 426.1 6.6 409.8C6.1 404.5 6.1 340 6.6 339.6C6.7 339.5 7.3 339.2 7.9 339C9.3 338.5 10.9 337.4 11.7 336.3C12.9 334.6 13.9 333.7 16.2 332.1C19.5 330 20 329.8 25.2 328.1C29.9 326.7 31.9 325.9 33.5 324.8C34 324.5 35.3 323.9 36.4 323.5C38.5 322.7 44.3 319.3 45.5 318.1C46.3 317.4 46.7 315.8 46.7 314.1C46.7 313 47.2 310.8 47.8 308.8C48 308.3 49 306.6 50.2 305C53.3 300.9 54.3 299.4 55.6 296.8C56.3 295.4 57.3 293.7 57.9 292.8C59.5 290.5 59.3 289.5 57 288.4C55 287.4 54.2 284.9 54.7 281.7C55 280.2 55 279.8 54.6 278.8C54.2 277.8 54.1 276.8 54.1 272.6C54.1 266.9 54.1 266.7 52.2 266.2C51.6 266.1 51.1 265.7 50.8 265.3C49.9 263.8 47.8 261.7 46.6 260.8C44 259.2 43.9 257.7 45.8 255C46.5 254 47.4 252.7 47.6 252.2C48.3 250.9 49.3 250.1 51.1 249.2C52.9 248.4 53.4 247.8 53.6 246.1C53.7 245.1 53.9 244.7 54.7 244C55.3 243.5 56.5 242.4 57.5 241.5C59.8 239.5 60.4 239.2 66.4 237.9C74.1 236.1 76 235.2 76 233.4C76 233 76.1 232.5 76.2 232.4C76.3 232.2 77 231 77.8 229.6C79.1 227.1 79.1 227 78.6 226.5C77.5 225.2 78.8 221.8 81.8 218.6C84.2 216 85.5 214.1 85.5 213.2C85.5 212.8 85.7 211.9 86 211.2C86.4 210.1 86.5 209.3 86.4 207.1C86.4 204.4 86.4 204.4 85.8 204.4C85.5 204.5 85.2 204.3 85.1 204.1C84.9 203.5 84.6 203.7 84 204.6C82.3 207.5 82.6 201.7 84.5 195.5C84.9 194.1 85.4 192.2 85.5 191.3C85.7 190.4 85.9 189.4 86.2 188.9C86.4 188.4 86.6 187.3 86.7 185.7C86.8 182.5 87.9 180 90.4 177.7C93.3 174.8 94.5 173 94.4 171.9C94.4 170.9 94.3 170.9 93.4 170.8C91.2 170.5 92.2 168.7 95.1 167.6C96.2 167.2 98.2 165.7 98.2 165.2C98.2 165.1 97.7 165 97.1 165L95.9 164.9 95.9 162.9C95.9 161.1 96 160.7 96.6 159.7C96.9 159.1 97.2 158.4 97.2 158.2C97.3 158 97.7 157.3 98.2 156.6C99.5 154.9 101.1 151.9 101.7 150.2C102.2 148.8 104 146.3 105.4 145C106.9 143.5 107.9 139.9 107.1 138.6C106.7 138 106.5 138 105.5 138C104.2 138.1 104.2 138.3 105.1 135C106.2 131.1 106.1 130.5 104.3 131.1C103.5 131.4 103.6 130.9 105 127.9C106.5 124.7 108.3 121.7 110 119.4C110.7 118.4 111.5 117.1 111.7 116.4C112.8 113.4 114.7 110.7 117.2 108.6C118.5 107.5 119 107 119.4 106C119.9 104.7 121.3 103 121.9 103C122 103 122.7 102.3 123.4 101.4C124.6 100 124.7 99.7 124.8 98.1C125.1 95.8 127 93.3 130.1 91.2C130.5 90.9 131 90.3 131.3 89.9C131.9 88.8 132.9 88.2 135.1 87.5C137.1 86.9 137.7 86.4 138.9 84.6C139.4 83.8 139.9 83.2 140.1 83.2C140.6 83.2 142.8 81.3 142.8 80.9C142.8 80.5 144.1 79.3 144.6 79.2C145.3 79.2 147.8 76.9 149.4 74.8C151.2 72.4 152 71.7 154.4 71.1C155.4 70.9 156.1 70.5 157 69.7C158.9 67.8 160.9 67 164 66.6C165.5 66.5 166 66.2 166 65.5C166 64.6 167.1 63.8 168.9 63.3C169.8 63 172.1 62.2 173.8 61.4C175.6 60.6 177.8 59.8 178.7 59.7C179.9 59.5 180.2 59.3 180.2 59C180.2 58 182.7 57.5 186.9 57.5C191.1 57.6 191.8 57.3 193.5 54.9C194.7 53.2 197.3 52.2 200.9 52.1C203.3 52 203.8 51.9 204.1 51.5C204.4 51.2 204.9 51 205.5 51C206.2 51 206.6 50.8 207 50.3C207.4 50 208.2 49.3 208.9 48.8C209.6 48.4 210.4 47.7 210.7 47.3L211.2 46.5 214 46.7L216.7 46.8 217.4 46C217.7 45.6 218 45.1 218 45C218 44.8 218.4 44.5 218.8 44.3C219.2 44 219.7 43.5 219.9 43.2C220.1 42.8 220.3 42.6 220.8 42.7C223.4 43 223.8 43 224.2 42.7C224.5 42.4 225 42.3 225.6 42.3C226.5 42.4 226.6 42.3 227 41.6C227.4 40.7 227.6 38.4 227.3 38.1C226.3 37.5 227.5 36 228.9 36C230.6 36 236.5 38.5 239.6 40.4C241.5 41.6 243.2 42.3 243.6 42C244.5 41.4 246.2 41 248.7 41C250.2 40.9 251.6 40.8 251.8 40.7C252 40.6 253.4 40.4 254.9 40.2C259.3 39.6 260.9 38.6 260.6 36.8C260.3 34.8 261.6 33.7 264.4 33.6C265.9 33.5 266.3 33.6 266.8 34C267.4 34.5 267.4 34.5 267.9 34C268.3 33.6 268.8 33.4 270.3 33.4C272.1 33.4 272.3 33.4 275.1 34.8C276.7 35.6 278.3 36.5 278.7 36.8C279.2 37.3 279.6 37.4 280 37.3C280.6 37.2 280.9 37.5 282.4 39.1C284.2 41.1 284.7 41.3 285.3 40.5C285.5 40.1 285.8 40 286.1 40.1C286.7 40.3 287.9 42.6 288.7 44.9C289.6 47.7 289.6 47.7 291.6 46.2C295.5 43.1 298.8 42.1 298.8 44C298.8 45.4 299.6 45.5 302.3 44.4C306.9 42.5 308.3 42.3 308.8 43.4C309 43.9 309.1 44 310.3 44C312.1 44 311.9 44.6 309.7 45.8C308.7 46.2 307.8 46.9 307.6 47.2C307.4 47.5 306.6 48.1 305.9 48.6C304.5 49.6 302.7 51.5 302.9 51.8C303 51.9 303.4 51.9 303.8 51.7C304.3 51.6 305.5 51.4 306.7 51.3C308.7 51.2 308.7 51.2 309.1 51.8C309.7 52.7 310.3 52.7 312 51.9C312.8 51.5 314.7 50.7 316.4 50C318 49.3 320.4 48.4 321.5 47.9C324.6 46.7 325.8 46.7 324.9 48.1C324.4 49 324.4 49 325.7 48.9C327.9 48.8 327.4 49.7 323.4 53C322 54.2 321.8 54.5 321.8 55.2C321.7 56.4 322.3 56.7 323.6 56.1C324.9 55.6 329 55.3 330.7 55.7C333.1 56.2 335.5 57.5 336 58.5C336.6 59.8 337.6 60.1 340.4 59.7C343.1 59.4 344.5 59.6 345.2 60.4C345.9 61.1 345.7 61.5 344.5 62.4C343.1 63.4 343.3 63.8 345.2 64C347.1 64.2 349.1 65.2 349.2 65.9C349.3 66.6 350.1 67.3 350.9 67.3C351.8 67.2 353.2 67.9 353.4 68.4C353.5 68.6 353.3 69 353 Line truncated
|
||||
|
Before Width: | Height: | Size: 451 KiB After Width: | Height: | Size: 451 KiB |
|
Before Width: | Height: | Size: 265 KiB After Width: | Height: | Size: 265 KiB |
|
Before Width: | Height: | Size: 35 KiB After Width: | Height: | Size: 14 KiB |
@@ -4,10 +4,10 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" viewBox="0 0 64 64">
|
||||
<g transform="translate(-2 -2) scale(2.8)" stroke="#0b0b0c" stroke-width="1" stroke-linecap="round" stroke-linejoin="round">
|
||||
<path fill="#efe9dc" d="M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z" />
|
||||
<path fill="#c8ece4" d="M14 2v5a1 1 0 0 0 1 1h5" />
|
||||
<path fill="none" stroke="#12a58a" d="M8 12h8M8 15h5" />
|
||||
<path fill="#f3cfd6" d="M14 2v5a1 1 0 0 0 1 1h5" />
|
||||
<path fill="none" stroke="#b70228" d="M8 12h8M8 15h5" />
|
||||
</g>
|
||||
<rect x="3" y="34" width="56" height="23" rx="4" fill="#087f6b" />
|
||||
<rect x="3" y="34" width="56" height="23" rx="4" fill="#8a011e" />
|
||||
<g fill="none" stroke="#fff" stroke-width="2.8" stroke-linecap="round" stroke-linejoin="round">
|
||||
<path d="M13 50V41h5a3 3 0 0 1 0 6h-5" />
|
||||
<path d="M27 41v9h3a4.5 4.5 0 0 0 0-9z" />
|
||||
|
||||
|
Before Width: | Height: | Size: 1023 B After Width: | Height: | Size: 1023 B |
@@ -1 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><defs><clipPath id="t"><rect width="512" height="512" rx="112"/></clipPath></defs><g clip-path="url(#t)"><rect width="512" height="512" fill="#12a58a"/><path fill="#efe9dc" fill-rule="evenodd" d="M103 505C57 502 18 468 8 421L7 415 7 377L6 340 8 339C9 339 11 337 13 335C16 332 19 330 26 328C31 326 43 321 45 319C46 317 46 317 47 313C48 309 48 308 51 304C53 302 55 298 56 297C56 295 58 293 58 293C59 291 59 290 58 289C55 287 55 287 54 273C54 268 54 267 53 267C51 266 44 259 45 258C45 256 49 251 51 249C53 249 53 248 53 247C54 243 59 240 64 238C73 236 76 235 76 234C76 233 77 232 77 230C79 228 79 227 79 225C78 223 79 221 83 217C86 214 86 213 86 208C86 205 85 202 84 204C84 206 83 205 83 203C83 202 84 198 86 190C86 189 87 187 87 185C87 182 88 180 91 177C95 173 95 172 93 171C92 170 92 169 96 167C98 166 98 165 97 165C95 164 96 159 99 156C99 155 101 153 101 151C102 150 103 147 105 146C108 142 108 138 105 138C104 138 104 138 105 135C106 132 106 130 105 131C103 131 106 124 110 120C111 119 112 117 112 115C113 114 114 112 116 110C118 108 120 106 120 106C120 105 121 104 122 103C124 101 125 100 125 98C125 95 132 88 135 88C136 88 138 86 140 84C142 81 145 79 146 79C147 78 148 76 149 75C151 73 152 72 154 71C155 71 157 70 158 69C159 68 160 67 162 67C164 67 166 66 166 65C167 64 169 63 177 60C179 60 180 59 181 58C181 58 183 58 187 58L192 57 193 55C195 53 198 52 201 52C203 52 204 52 204 51C204 51 205 51 205 51C206 51 210 48 211 47C211 47 212 47 214 46C217 46 217 46 218 45C220 43 220 43 223 43C227 43 228 42 227 38L227 36 229 36C231 36 233 37 237 39C241 41 243 42 244 42C244 42 247 41 249 41C258 40 261 39 261 37C260 34 265 32 267 34C267 34 267 34 268 34C270 33 277 35 279 37C279 37 279 37 280 37C280 37 282 38 283 39C284 41 285 41 285 41C286 39 288 42 289 45C289 48 290 48 291 46C294 44 298 42 299 44C299 45 300 45 304 44C307 43 308 43 308 43C309 44 310 44 310 44C311 44 311 45 310 46C304 49 302 52 306 51C307 51 308 51 309 52C310 53 310 53 318 49C324 47 325 47 325 48C325 49 325 49 326 49C328 49 327 50 324 52C321 55 321 57 324 56C328 55 334 56 336 59C337 60 338 60 341 60C345 59 346 60 345 62C343 64 344 64 346 64C346 64 348 65 349 65C350 66 351 67 352 67C353 68 353 68 353 69C353 71 353 71 359 70C364 70 365 71 362 73C358 74 360 75 364 74C367 73 367 73 367 75C367 77 368 78 370 78C371 79 372 80 372 82C372 83 373 84 373 85C375 86 377 87 377 86C378 86 378 86 378 87C378 88 378 89 379 89C383 90 384 91 386 94L387 96 392 96C397 95 397 95 398 97C399 98 399 98 402 98C406 97 407 98 408 100C408 101 408 102 410 102C414 103 418 107 418 110C418 111 419 113 420 115C422 119 422 120 422 122C422 123 422 124 422 124C422 124 423 126 423 128C423 130 424 132 425 133C427 136 427 145 425 151C424 152 424 154 423 155C423 157 422 158 421 159C420 160 419 161 419 162C419 165 415 169 412 171C411 172 410 173 410 173C410 174 409 175 408 176C407 177 407 177 407 180C407 181 406 183 406 183C405 185 405 186 407 188C409 191 410 192 410 194C410 196 410 197 413 200C417 205 420 211 421 218C423 222 422 224 421 222C419 219 419 221 420 225C422 228 421 230 420 227C417 223 417 226 420 236C423 243 423 245 425 247C426 248 427 250 427 251C428 254 427 259 426 257C424 254 424 259 425 262C427 266 427 270 425 274C422 282 424 289 434 300C438 305 439 308 439 309C439 310 439 311 440 313C441 315 441 317 440 318C440 318 440 320 442 324C444 330 446 334 446 337C446 340 446 340 444 339C442 338 442 338 442 342C442 343 443 346 443 348C443 351 444 352 446 357C449 361 449 362 449 364C449 365 449 366 450 367C451 369 450 370 449 369C446 366 446 369 449 372C451 375 453 381 453 383C453 384 454 385 456 387C460 391 465 403 464 403C464 403 463 403 463 403C463 403 462 405 462 407C461 412 460 413 459 412C458 411 458 411 457 412C457 413 457 416 457 419C456 425 457 425 458 428C458 429 458 431 458 432C458 432 458 434 459 435C459 436 460 437 459 438C459 440 459 440 461 441C464 444 465 449 463 448C461 448 460 450 460 451C460 451 460 452 460 453C459 454 460 455 462 457C465 461 466 465 466 470C466 473 467 476 467 478L468 481 466 483C453 494 429 504 408 505C400 506 110 506 103 505Z"/><path fill="#0b0b0c" fill-rule="evenodd" d="M107 505C107 504 108 499 109 498C109 497 110 498 109 502C108 505 108 507 107 505ZM110 504C110 503 111 502 111 502C112 500 112 503 111 505L110 506 110 504ZM118 505C118 504 119 501 120 499C121 496 122 494 122 493C122 491 122 492 121 495C120 498 119 499 119 497C119 496 119 496 118 499C117 501 117 502 116 502C116 503 116 497 117 493C118 489 118 484 117 485C117 485 116 487 116 488C114 498 113 498 114 488C114 481 114 480 113 482C113 487 112 487 112 482L112 477 111 481C111 486 110 488 110 482C111 478 110 477 109 480C109 484 108 482 108 478C109 477 109 475 109 474L108 472 108 474L107 476 107 473C108 469 107 469 106 472C105 475 104 474 105 470C106 469 106 466 106 466L106 464 106 466C104 471 103 465 104 458C104 457 104 456 104 456C104 455 104 456 101 462C100 465 100 463 101 458C101 455 102 452 102 450C102 446 101 448 100 453C100 458 98 461 98 458C98 4Line truncated
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><defs><clipPath id="t"><rect width="512" height="512" rx="112"/></clipPath></defs><g clip-path="url(#t)"><rect width="512" height="512" fill="#b70228"/><path fill="#efe9dc" fill-rule="evenodd" d="M103 505C57 502 18 468 8 421L7 415 7 377L6 340 8 339C9 339 11 337 13 335C16 332 19 330 26 328C31 326 43 321 45 319C46 317 46 317 47 313C48 309 48 308 51 304C53 302 55 298 56 297C56 295 58 293 58 293C59 291 59 290 58 289C55 287 55 287 54 273C54 268 54 267 53 267C51 266 44 259 45 258C45 256 49 251 51 249C53 249 53 248 53 247C54 243 59 240 64 238C73 236 76 235 76 234C76 233 77 232 77 230C79 228 79 227 79 225C78 223 79 221 83 217C86 214 86 213 86 208C86 205 85 202 84 204C84 206 83 205 83 203C83 202 84 198 86 190C86 189 87 187 87 185C87 182 88 180 91 177C95 173 95 172 93 171C92 170 92 169 96 167C98 166 98 165 97 165C95 164 96 159 99 156C99 155 101 153 101 151C102 150 103 147 105 146C108 142 108 138 105 138C104 138 104 138 105 135C106 132 106 130 105 131C103 131 106 124 110 120C111 119 112 117 112 115C113 114 114 112 116 110C118 108 120 106 120 106C120 105 121 104 122 103C124 101 125 100 125 98C125 95 132 88 135 88C136 88 138 86 140 84C142 81 145 79 146 79C147 78 148 76 149 75C151 73 152 72 154 71C155 71 157 70 158 69C159 68 160 67 162 67C164 67 166 66 166 65C167 64 169 63 177 60C179 60 180 59 181 58C181 58 183 58 187 58L192 57 193 55C195 53 198 52 201 52C203 52 204 52 204 51C204 51 205 51 205 51C206 51 210 48 211 47C211 47 212 47 214 46C217 46 217 46 218 45C220 43 220 43 223 43C227 43 228 42 227 38L227 36 229 36C231 36 233 37 237 39C241 41 243 42 244 42C244 42 247 41 249 41C258 40 261 39 261 37C260 34 265 32 267 34C267 34 267 34 268 34C270 33 277 35 279 37C279 37 279 37 280 37C280 37 282 38 283 39C284 41 285 41 285 41C286 39 288 42 289 45C289 48 290 48 291 46C294 44 298 42 299 44C299 45 300 45 304 44C307 43 308 43 308 43C309 44 310 44 310 44C311 44 311 45 310 46C304 49 302 52 306 51C307 51 308 51 309 52C310 53 310 53 318 49C324 47 325 47 325 48C325 49 325 49 326 49C328 49 327 50 324 52C321 55 321 57 324 56C328 55 334 56 336 59C337 60 338 60 341 60C345 59 346 60 345 62C343 64 344 64 346 64C346 64 348 65 349 65C350 66 351 67 352 67C353 68 353 68 353 69C353 71 353 71 359 70C364 70 365 71 362 73C358 74 360 75 364 74C367 73 367 73 367 75C367 77 368 78 370 78C371 79 372 80 372 82C372 83 373 84 373 85C375 86 377 87 377 86C378 86 378 86 378 87C378 88 378 89 379 89C383 90 384 91 386 94L387 96 392 96C397 95 397 95 398 97C399 98 399 98 402 98C406 97 407 98 408 100C408 101 408 102 410 102C414 103 418 107 418 110C418 111 419 113 420 115C422 119 422 120 422 122C422 123 422 124 422 124C422 124 423 126 423 128C423 130 424 132 425 133C427 136 427 145 425 151C424 152 424 154 423 155C423 157 422 158 421 159C420 160 419 161 419 162C419 165 415 169 412 171C411 172 410 173 410 173C410 174 409 175 408 176C407 177 407 177 407 180C407 181 406 183 406 183C405 185 405 186 407 188C409 191 410 192 410 194C410 196 410 197 413 200C417 205 420 211 421 218C423 222 422 224 421 222C419 219 419 221 420 225C422 228 421 230 420 227C417 223 417 226 420 236C423 243 423 245 425 247C426 248 427 250 427 251C428 254 427 259 426 257C424 254 424 259 425 262C427 266 427 270 425 274C422 282 424 289 434 300C438 305 439 308 439 309C439 310 439 311 440 313C441 315 441 317 440 318C440 318 440 320 442 324C444 330 446 334 446 337C446 340 446 340 444 339C442 338 442 338 442 342C442 343 443 346 443 348C443 351 444 352 446 357C449 361 449 362 449 364C449 365 449 366 450 367C451 369 450 370 449 369C446 366 446 369 449 372C451 375 453 381 453 383C453 384 454 385 456 387C460 391 465 403 464 403C464 403 463 403 463 403C463 403 462 405 462 407C461 412 460 413 459 412C458 411 458 411 457 412C457 413 457 416 457 419C456 425 457 425 458 428C458 429 458 431 458 432C458 432 458 434 459 435C459 436 460 437 459 438C459 440 459 440 461 441C464 444 465 449 463 448C461 448 460 450 460 451C460 451 460 452 460 453C459 454 460 455 462 457C465 461 466 465 466 470C466 473 467 476 467 478L468 481 466 483C453 494 429 504 408 505C400 506 110 506 103 505Z"/><path fill="#0b0b0c" fill-rule="evenodd" d="M107 505C107 504 108 499 109 498C109 497 110 498 109 502C108 505 108 507 107 505ZM110 504C110 503 111 502 111 502C112 500 112 503 111 505L110 506 110 504ZM118 505C118 504 119 501 120 499C121 496 122 494 122 493C122 491 122 492 121 495C120 498 119 499 119 497C119 496 119 496 118 499C117 501 117 502 116 502C116 503 116 497 117 493C118 489 118 484 117 485C117 485 116 487 116 488C114 498 113 498 114 488C114 481 114 480 113 482C113 487 112 487 112 482L112 477 111 481C111 486 110 488 110 482C111 478 110 477 109 480C109 484 108 482 108 478C109 477 109 475 109 474L108 472 108 474L107 476 107 473C108 469 107 469 106 472C105 475 104 474 105 470C106 469 106 466 106 466L106 464 106 466C104 471 103 465 104 458C104 457 104 456 104 456C104 455 104 456 101 462C100 465 100 463 101 458C101 455 102 452 102 450C102 446 101 448 100 453C100 458 98 461 98 458C98 4Line truncated
|
||||
|
Before Width: | Height: | Size: 238 KiB After Width: | Height: | Size: 238 KiB |
|
Before Width: | Height: | Size: 85 KiB After Width: | Height: | Size: 85 KiB |
@@ -1 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><defs><clipPath id="t"><rect width="512" height="512" rx="112"/></clipPath></defs><g clip-path="url(#t)"><rect width="512" height="512" fill="#12a58a"/><path fill="#efe9dc" fill-rule="evenodd" d="M101.8 505.4C68.7 502.1 39.1 483.6 21.7 455.2C13.3 441.6 8.2 426.1 6.6 409.8C6.1 404.5 6.1 340 6.6 339.6C6.7 339.5 7.3 339.2 7.9 339C9.3 338.5 10.9 337.4 11.7 336.3C12.9 334.6 13.9 333.7 16.2 332.1C19.5 330 20 329.8 25.2 328.1C29.9 326.7 31.9 325.9 33.5 324.8C34 324.5 35.3 323.9 36.4 323.5C38.5 322.7 44.3 319.3 45.5 318.1C46.3 317.4 46.7 315.8 46.7 314.1C46.7 313 47.2 310.8 47.8 308.8C48 308.3 49 306.6 50.2 305C53.3 300.9 54.3 299.4 55.6 296.8C56.3 295.4 57.3 293.7 57.9 292.8C59.5 290.5 59.3 289.5 57 288.4C55 287.4 54.2 284.9 54.7 281.7C55 280.2 55 279.8 54.6 278.8C54.2 277.8 54.1 276.8 54.1 272.6C54.1 266.9 54.1 266.7 52.2 266.2C51.6 266.1 51.1 265.7 50.8 265.3C49.9 263.8 47.8 261.7 46.6 260.8C44 259.2 43.9 257.7 45.8 255C46.5 254 47.4 252.7 47.6 252.2C48.3 250.9 49.3 250.1 51.1 249.2C52.9 248.4 53.4 247.8 53.6 246.1C53.7 245.1 53.9 244.7 54.7 244C55.3 243.5 56.5 242.4 57.5 241.5C59.8 239.5 60.4 239.2 66.4 237.9C74.1 236.1 76 235.2 76 233.4C76 233 76.1 232.5 76.2 232.4C76.3 232.2 77 231 77.8 229.6C79.1 227.1 79.1 227 78.6 226.5C77.5 225.2 78.8 221.8 81.8 218.6C84.2 216 85.5 214.1 85.5 213.2C85.5 212.8 85.7 211.9 86 211.2C86.4 210.1 86.5 209.3 86.4 207.1C86.4 204.4 86.4 204.4 85.8 204.4C85.5 204.5 85.2 204.3 85.1 204.1C84.9 203.5 84.6 203.7 84 204.6C82.3 207.5 82.6 201.7 84.5 195.5C84.9 194.1 85.4 192.2 85.5 191.3C85.7 190.4 85.9 189.4 86.2 188.9C86.4 188.4 86.6 187.3 86.7 185.7C86.8 182.5 87.9 180 90.4 177.7C93.3 174.8 94.5 173 94.4 171.9C94.4 170.9 94.3 170.9 93.4 170.8C91.2 170.5 92.2 168.7 95.1 167.6C96.2 167.2 98.2 165.7 98.2 165.2C98.2 165.1 97.7 165 97.1 165L95.9 164.9 95.9 162.9C95.9 161.1 96 160.7 96.6 159.7C96.9 159.1 97.2 158.4 97.2 158.2C97.3 158 97.7 157.3 98.2 156.6C99.5 154.9 101.1 151.9 101.7 150.2C102.2 148.8 104 146.3 105.4 145C106.9 143.5 107.9 139.9 107.1 138.6C106.7 138 106.5 138 105.5 138C104.2 138.1 104.2 138.3 105.1 135C106.2 131.1 106.1 130.5 104.3 131.1C103.5 131.4 103.6 130.9 105 127.9C106.5 124.7 108.3 121.7 110 119.4C110.7 118.4 111.5 117.1 111.7 116.4C112.8 113.4 114.7 110.7 117.2 108.6C118.5 107.5 119 107 119.4 106C119.9 104.7 121.3 103 121.9 103C122 103 122.7 102.3 123.4 101.4C124.6 100 124.7 99.7 124.8 98.1C125.1 95.8 127 93.3 130.1 91.2C130.5 90.9 131 90.3 131.3 89.9C131.9 88.8 132.9 88.2 135.1 87.5C137.1 86.9 137.7 86.4 138.9 84.6C139.4 83.8 139.9 83.2 140.1 83.2C140.6 83.2 142.8 81.3 142.8 80.9C142.8 80.5 144.1 79.3 144.6 79.2C145.3 79.2 147.8 76.9 149.4 74.8C151.2 72.4 152 71.7 154.4 71.1C155.4 70.9 156.1 70.5 157 69.7C158.9 67.8 160.9 67 164 66.6C165.5 66.5 166 66.2 166 65.5C166 64.6 167.1 63.8 168.9 63.3C169.8 63 172.1 62.2 173.8 61.4C175.6 60.6 177.8 59.8 178.7 59.7C179.9 59.5 180.2 59.3 180.2 59C180.2 58 182.7 57.5 186.9 57.5C191.1 57.6 191.8 57.3 193.5 54.9C194.7 53.2 197.3 52.2 200.9 52.1C203.3 52 203.8 51.9 204.1 51.5C204.4 51.2 204.9 51 205.5 51C206.2 51 206.6 50.8 207 50.3C207.4 50 208.2 49.3 208.9 48.8C209.6 48.4 210.4 47.7 210.7 47.3L211.2 46.5 214 46.7L216.7 46.8 217.4 46C217.7 45.6 218 45.1 218 45C218 44.8 218.4 44.5 218.8 44.3C219.2 44 219.7 43.5 219.9 43.2C220.1 42.8 220.3 42.6 220.8 42.7C223.4 43 223.8 43 224.2 42.7C224.5 42.4 225 42.3 225.6 42.3C226.5 42.4 226.6 42.3 227 41.6C227.4 40.7 227.6 38.4 227.3 38.1C226.3 37.5 227.5 36 228.9 36C230.6 36 236.5 38.5 239.6 40.4C241.5 41.6 243.2 42.3 243.6 42C244.5 41.4 246.2 41 248.7 41C250.2 40.9 251.6 40.8 251.8 40.7C252 40.6 253.4 40.4 254.9 40.2C259.3 39.6 260.9 38.6 260.6 36.8C260.3 34.8 261.6 33.7 264.4 33.6C265.9 33.5 266.3 33.6 266.8 34C267.4 34.5 267.4 34.5 267.9 34C268.3 33.6 268.8 33.4 270.3 33.4C272.1 33.4 272.3 33.4 275.1 34.8C276.7 35.6 278.3 36.5 278.7 36.8C279.2 37.3 279.6 37.4 280 37.3C280.6 37.2 280.9 37.5 282.4 39.1C284.2 41.1 284.7 41.3 285.3 40.5C285.5 40.1 285.8 40 286.1 40.1C286.7 40.3 287.9 42.6 288.7 44.9C289.6 47.7 289.6 47.7 291.6 46.2C295.5 43.1 298.8 42.1 298.8 44C298.8 45.4 299.6 45.5 302.3 44.4C306.9 42.5 308.3 42.3 308.8 43.4C309 43.9 309.1 44 310.3 44C312.1 44 311.9 44.6 309.7 45.8C308.7 46.2 307.8 46.9 307.6 47.2C307.4 47.5 306.6 48.1 305.9 48.6C304.5 49.6 302.7 51.5 302.9 51.8C303 51.9 303.4 51.9 303.8 51.7C304.3 51.6 305.5 51.4 306.7 51.3C308.7 51.2 308.7 51.2 309.1 51.8C309.7 52.7 310.3 52.7 312 51.9C312.8 51.5 314.7 50.7 316.4 50C318 49.3 320.4 48.4 321.5 47.9C324.6 46.7 325.8 46.7 324.9 48.1C324.4 49 324.4 49 325.7 48.9C327.9 48.8 327.4 49.7 323.4 53C322 54.2 321.8 54.5 321.8 55.2C321.7 56.4 322.3 56.7 323.6 56.1C324.9 55.6 329 55.3 330.7 55.7C333.1 56.2 335.5 57.5 336 58.5C336.6 59.8 337.6 60.1 340.4 59.7C343.1 59.4 344.5 59.6 345.2 60.4C345.9 61.1 345.7 61.5 344.5 62.4C343.1 63.4 343.3 63.8 345.2 64C347.1 64.2 349.1 65.2 349.2 65.9C349.3 66.6 350.1 67.3 350.9 67.3C351.8 67.2 353.2 67.9 353.4 68.4C353.5 68.6 353.3 69 353 Line truncated
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><defs><clipPath id="t"><rect width="512" height="512" rx="112"/></clipPath></defs><g clip-path="url(#t)"><rect width="512" height="512" fill="#b70228"/><path fill="#efe9dc" fill-rule="evenodd" d="M101.8 505.4C68.7 502.1 39.1 483.6 21.7 455.2C13.3 441.6 8.2 426.1 6.6 409.8C6.1 404.5 6.1 340 6.6 339.6C6.7 339.5 7.3 339.2 7.9 339C9.3 338.5 10.9 337.4 11.7 336.3C12.9 334.6 13.9 333.7 16.2 332.1C19.5 330 20 329.8 25.2 328.1C29.9 326.7 31.9 325.9 33.5 324.8C34 324.5 35.3 323.9 36.4 323.5C38.5 322.7 44.3 319.3 45.5 318.1C46.3 317.4 46.7 315.8 46.7 314.1C46.7 313 47.2 310.8 47.8 308.8C48 308.3 49 306.6 50.2 305C53.3 300.9 54.3 299.4 55.6 296.8C56.3 295.4 57.3 293.7 57.9 292.8C59.5 290.5 59.3 289.5 57 288.4C55 287.4 54.2 284.9 54.7 281.7C55 280.2 55 279.8 54.6 278.8C54.2 277.8 54.1 276.8 54.1 272.6C54.1 266.9 54.1 266.7 52.2 266.2C51.6 266.1 51.1 265.7 50.8 265.3C49.9 263.8 47.8 261.7 46.6 260.8C44 259.2 43.9 257.7 45.8 255C46.5 254 47.4 252.7 47.6 252.2C48.3 250.9 49.3 250.1 51.1 249.2C52.9 248.4 53.4 247.8 53.6 246.1C53.7 245.1 53.9 244.7 54.7 244C55.3 243.5 56.5 242.4 57.5 241.5C59.8 239.5 60.4 239.2 66.4 237.9C74.1 236.1 76 235.2 76 233.4C76 233 76.1 232.5 76.2 232.4C76.3 232.2 77 231 77.8 229.6C79.1 227.1 79.1 227 78.6 226.5C77.5 225.2 78.8 221.8 81.8 218.6C84.2 216 85.5 214.1 85.5 213.2C85.5 212.8 85.7 211.9 86 211.2C86.4 210.1 86.5 209.3 86.4 207.1C86.4 204.4 86.4 204.4 85.8 204.4C85.5 204.5 85.2 204.3 85.1 204.1C84.9 203.5 84.6 203.7 84 204.6C82.3 207.5 82.6 201.7 84.5 195.5C84.9 194.1 85.4 192.2 85.5 191.3C85.7 190.4 85.9 189.4 86.2 188.9C86.4 188.4 86.6 187.3 86.7 185.7C86.8 182.5 87.9 180 90.4 177.7C93.3 174.8 94.5 173 94.4 171.9C94.4 170.9 94.3 170.9 93.4 170.8C91.2 170.5 92.2 168.7 95.1 167.6C96.2 167.2 98.2 165.7 98.2 165.2C98.2 165.1 97.7 165 97.1 165L95.9 164.9 95.9 162.9C95.9 161.1 96 160.7 96.6 159.7C96.9 159.1 97.2 158.4 97.2 158.2C97.3 158 97.7 157.3 98.2 156.6C99.5 154.9 101.1 151.9 101.7 150.2C102.2 148.8 104 146.3 105.4 145C106.9 143.5 107.9 139.9 107.1 138.6C106.7 138 106.5 138 105.5 138C104.2 138.1 104.2 138.3 105.1 135C106.2 131.1 106.1 130.5 104.3 131.1C103.5 131.4 103.6 130.9 105 127.9C106.5 124.7 108.3 121.7 110 119.4C110.7 118.4 111.5 117.1 111.7 116.4C112.8 113.4 114.7 110.7 117.2 108.6C118.5 107.5 119 107 119.4 106C119.9 104.7 121.3 103 121.9 103C122 103 122.7 102.3 123.4 101.4C124.6 100 124.7 99.7 124.8 98.1C125.1 95.8 127 93.3 130.1 91.2C130.5 90.9 131 90.3 131.3 89.9C131.9 88.8 132.9 88.2 135.1 87.5C137.1 86.9 137.7 86.4 138.9 84.6C139.4 83.8 139.9 83.2 140.1 83.2C140.6 83.2 142.8 81.3 142.8 80.9C142.8 80.5 144.1 79.3 144.6 79.2C145.3 79.2 147.8 76.9 149.4 74.8C151.2 72.4 152 71.7 154.4 71.1C155.4 70.9 156.1 70.5 157 69.7C158.9 67.8 160.9 67 164 66.6C165.5 66.5 166 66.2 166 65.5C166 64.6 167.1 63.8 168.9 63.3C169.8 63 172.1 62.2 173.8 61.4C175.6 60.6 177.8 59.8 178.7 59.7C179.9 59.5 180.2 59.3 180.2 59C180.2 58 182.7 57.5 186.9 57.5C191.1 57.6 191.8 57.3 193.5 54.9C194.7 53.2 197.3 52.2 200.9 52.1C203.3 52 203.8 51.9 204.1 51.5C204.4 51.2 204.9 51 205.5 51C206.2 51 206.6 50.8 207 50.3C207.4 50 208.2 49.3 208.9 48.8C209.6 48.4 210.4 47.7 210.7 47.3L211.2 46.5 214 46.7L216.7 46.8 217.4 46C217.7 45.6 218 45.1 218 45C218 44.8 218.4 44.5 218.8 44.3C219.2 44 219.7 43.5 219.9 43.2C220.1 42.8 220.3 42.6 220.8 42.7C223.4 43 223.8 43 224.2 42.7C224.5 42.4 225 42.3 225.6 42.3C226.5 42.4 226.6 42.3 227 41.6C227.4 40.7 227.6 38.4 227.3 38.1C226.3 37.5 227.5 36 228.9 36C230.6 36 236.5 38.5 239.6 40.4C241.5 41.6 243.2 42.3 243.6 42C244.5 41.4 246.2 41 248.7 41C250.2 40.9 251.6 40.8 251.8 40.7C252 40.6 253.4 40.4 254.9 40.2C259.3 39.6 260.9 38.6 260.6 36.8C260.3 34.8 261.6 33.7 264.4 33.6C265.9 33.5 266.3 33.6 266.8 34C267.4 34.5 267.4 34.5 267.9 34C268.3 33.6 268.8 33.4 270.3 33.4C272.1 33.4 272.3 33.4 275.1 34.8C276.7 35.6 278.3 36.5 278.7 36.8C279.2 37.3 279.6 37.4 280 37.3C280.6 37.2 280.9 37.5 282.4 39.1C284.2 41.1 284.7 41.3 285.3 40.5C285.5 40.1 285.8 40 286.1 40.1C286.7 40.3 287.9 42.6 288.7 44.9C289.6 47.7 289.6 47.7 291.6 46.2C295.5 43.1 298.8 42.1 298.8 44C298.8 45.4 299.6 45.5 302.3 44.4C306.9 42.5 308.3 42.3 308.8 43.4C309 43.9 309.1 44 310.3 44C312.1 44 311.9 44.6 309.7 45.8C308.7 46.2 307.8 46.9 307.6 47.2C307.4 47.5 306.6 48.1 305.9 48.6C304.5 49.6 302.7 51.5 302.9 51.8C303 51.9 303.4 51.9 303.8 51.7C304.3 51.6 305.5 51.4 306.7 51.3C308.7 51.2 308.7 51.2 309.1 51.8C309.7 52.7 310.3 52.7 312 51.9C312.8 51.5 314.7 50.7 316.4 50C318 49.3 320.4 48.4 321.5 47.9C324.6 46.7 325.8 46.7 324.9 48.1C324.4 49 324.4 49 325.7 48.9C327.9 48.8 327.4 49.7 323.4 53C322 54.2 321.8 54.5 321.8 55.2C321.7 56.4 322.3 56.7 323.6 56.1C324.9 55.6 329 55.3 330.7 55.7C333.1 56.2 335.5 57.5 336 58.5C336.6 59.8 337.6 60.1 340.4 59.7C343.1 59.4 344.5 59.6 345.2 60.4C345.9 61.1 345.7 61.5 344.5 62.4C343.1 63.4 343.3 63.8 345.2 64C347.1 64.2 349.1 65.2 349.2 65.9C349.3 66.6 350.1 67.3 350.9 67.3C351.8 67.2 353.2 67.9 353.4 68.4C353.5 68.6 353.3 69 353 Line truncated
|
||||
|
Before Width: | Height: | Size: 451 KiB After Width: | Height: | Size: 451 KiB |
@@ -13,6 +13,7 @@ disallowed-methods = [
|
||||
{ path = "egui::Ui::radio_value", reason = "use radio_value from crates/ui-egui/src/widgets.rs, which is outlined and filled" },
|
||||
{ path = "egui::RadioButton::new", reason = "use radio from crates/ui-egui/src/widgets.rs, which is outlined and filled" },
|
||||
]
|
||||
cognitive-complexity-threshold = 30
|
||||
|
||||
disallowed-types = [
|
||||
{ path = "egui::ComboBox", reason = "use craft_ui::ComboBox: egui's combo box menu can't grow back while open (egui#5225)" },
|
||||
|
||||
@@ -180,3 +180,6 @@ sync_github_name = true
|
||||
[people.dotCooCoo]
|
||||
real_name = "Robert Lee"
|
||||
sync_github_name = true
|
||||
|
||||
[people.dylanmtaylor]
|
||||
sync_github_name = true
|
||||
@@ -188,7 +188,10 @@ pub(crate) fn mcid_texts(doc: &Document, page: &Dict) -> HashMap<i64, String> {
|
||||
// Where each id's last glyph ended, in user space.
|
||||
let mut ends: HashMap<i64, (f64, f64)> = HashMap::new();
|
||||
let mut gs = TextState::default();
|
||||
let mut saved: Vec<TextState> = Vec::new();
|
||||
// With each saved state, the text and text line matrices: inside a text object `q`/`Q`
|
||||
// save and restore them too (ISO 32000-2 §9.4.1, as corrected by the PDF Association's
|
||||
// errata, issue 368), as the renderer does.
|
||||
let mut saved: Vec<(TextState, Matrix, Matrix)> = Vec::new();
|
||||
let mut unsaved = 0usize;
|
||||
let (mut tm, mut tlm) = (Matrix::IDENTITY, Matrix::IDENTITY);
|
||||
for op in pdfcraft_content::parse(&page_content(doc, page)).ops {
|
||||
@@ -209,12 +212,12 @@ pub(crate) fn mcid_texts(doc: &Document, page: &Dict) -> HashMap<i64, String> {
|
||||
b"EMC" => {
|
||||
stack.pop();
|
||||
}
|
||||
b"q" if saved.len() < MAX_SAVED => saved.push(gs.clone()),
|
||||
b"q" if saved.len() < MAX_SAVED => saved.push((gs.clone(), tm, tlm)),
|
||||
b"q" => unsaved += 1,
|
||||
b"Q" if unsaved > 0 => unsaved -= 1,
|
||||
b"Q" => {
|
||||
if let Some(saved) = saved.pop() {
|
||||
gs = saved;
|
||||
(gs, tm, tlm) = saved;
|
||||
}
|
||||
}
|
||||
b"cm" => {
|
||||
|
||||
@@ -1235,6 +1235,19 @@ fn headings_drawn_glyph_by_glyph_keep_their_words() {
|
||||
);
|
||||
}
|
||||
|
||||
/// Inside a text object `q`/`Q` save and restore the text matrices (ISO 32000-2 §9.4.1, as
|
||||
/// corrected by the PDF Association's errata, issue 368), as the renderer does: a word whose
|
||||
/// glyphs continue after a `Q` stays one word.
|
||||
#[test]
|
||||
fn q_inside_a_text_object_restores_the_text_matrices() {
|
||||
let doc = heading_page(&[
|
||||
"BT /F1 20 Tf 72 700 Td (Chap) Tj q 0 -100 Td Q (ter One) Tj ET".into(),
|
||||
"BT /F1 20 Tf 72 650 Td (Chap) Tj q 1 0 0 1 300 300 Tm Q (ter Two) Tj ET".into(),
|
||||
]);
|
||||
let titles: Vec<String> = headings(&doc).into_iter().map(|h| h.title).collect();
|
||||
assert_eq!(titles, ["Chapter One", "Chapter Two"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_untagged_document_has_no_headings() {
|
||||
let mut objs = headings_doc();
|
||||
|
||||
@@ -30,7 +30,7 @@ let index = add_annotation(&mut doc, &NewAnnotation { page, shape, style, conten
|
||||
add_reply(&mut doc, page, index, "Agreed", "Ada", &meta)?;
|
||||
set_review_state(&mut doc, page, index, ReviewState::Accepted, "Ada", &meta)?;
|
||||
move_annotation(&mut doc, page, index, dx, dy, &meta)?;
|
||||
set_style(&mut doc, page, index, Some(rgb), Some(0.5), Some(2.0), &meta)?;
|
||||
set_style(&mut doc, page, index, StyleChange::new(Some(rgb), Some(0.5), Some(2.0), None), &meta)?;
|
||||
delete_annotation(&mut doc, page, index)?;
|
||||
signature_image(&doc, page, index)?; // embedded image XObject of Fill & Sign signature/initials
|
||||
```
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use super::*;
|
||||
use super::{Dict, Object, PdfString, Rgb, Stream, color, ext_gstate, form, literal, n, nums, rg, rg_stroke, text_width, win_ansi};
|
||||
|
||||
/// The label and colour of a standard rubber stamp name (ISO 32000-2 Table 184), for a stamp
|
||||
/// another program wrote without an appearance. Names are matched byte for byte, as PDF names
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
use super::draw::draw_appearance;
|
||||
use super::lookup::{annot_dict, annot_ref, annots, fill_sign_shape, page_ref, set_annots};
|
||||
use super::modify::{n, rich_text};
|
||||
use super::types::{FLAG_NO_ROTATE, FLAG_NO_ZOOM, FLAG_PRINT, LineEnding, Markup, Meta, NOTE_SIZE, NewAnnotation, Rgb, Shape, StampGroup, Style};
|
||||
use super::*;
|
||||
use super::types::{
|
||||
FLAG_NO_ROTATE, FLAG_NO_ZOOM, FLAG_PRINT, LineEnding, Markup, Meta, NOTE_SIZE, NewAnnotation, OverlayLook, Rgb, Shape, StampGroup, Style,
|
||||
};
|
||||
use super::{AnnotError, Dict, Document, ObjRef, Object, PdfString, appearance};
|
||||
|
||||
pub(crate) fn num_array(v: &[f64]) -> Object {
|
||||
Object::Array(v.iter().map(|x| Object::Real(*x)).collect())
|
||||
@@ -203,16 +205,12 @@ pub fn callout_attach(rect: [f64; 4], knee: [f64; 2]) -> [f64; 2] {
|
||||
pub fn add_annotation(doc: &mut Document, new: &NewAnnotation, meta: &Meta) -> Result<usize, AnnotError> {
|
||||
let page = page_ref(doc, new.page)?;
|
||||
let style = &new.style;
|
||||
if !finite(&style.color) || !style.opacity.is_finite() || !style.width.is_finite() {
|
||||
return Err(AnnotError::Invalid("invalid style".into()));
|
||||
}
|
||||
validate_style(style)?;
|
||||
let rect = rect_for(&new.shape, style)?;
|
||||
let mut d = base_dict(new.shape.subtype(), rect, page, &new.contents, &new.author, meta);
|
||||
d.set(b"Subj".to_vec(), PdfString::text(subject(&new.shape)));
|
||||
let opacity = style.opacity.clamp(0.0, 1.0);
|
||||
if opacity < 1.0 {
|
||||
d.set(b"CA".to_vec(), Object::Real(opacity));
|
||||
}
|
||||
set_non_opaque_style(&mut d, opacity);
|
||||
let border = |d: &mut Dict| {
|
||||
let mut bs = Dict::new();
|
||||
bs.set(b"W".to_vec(), Object::Real(style.width.max(0.0)));
|
||||
@@ -232,24 +230,7 @@ pub fn add_annotation(doc: &mut Document, new: &NewAnnotation, meta: &Meta) -> R
|
||||
d.set(b"C".to_vec(), rgb(style.color));
|
||||
d.set(b"QuadPoints".to_vec(), num_array(&quads.concat()));
|
||||
}
|
||||
Shape::Redact { quads, overlay, look } => {
|
||||
d.set(b"C".to_vec(), rgb(style.color));
|
||||
d.set(b"IC".to_vec(), rgb(style.fill.unwrap_or([0.0, 0.0, 0.0])));
|
||||
d.set(b"QuadPoints".to_vec(), num_array(&quads.concat()));
|
||||
if !overlay.is_empty() {
|
||||
d.set(b"OverlayText".to_vec(), PdfString::text(overlay));
|
||||
let [r, g, b] = look.color.map(|x| x.clamp(0.0, 1.0));
|
||||
let size = if look.size > 0.0 { look.size.min(400.0) } else { 0.0 };
|
||||
d.set(
|
||||
b"DA".to_vec(),
|
||||
PdfString::literal(format!("{} {} {} rg /{} {} Tf", n(r), n(g), n(b), look.font.resource(), n(size)).into_bytes()),
|
||||
);
|
||||
d.set(b"Q".to_vec(), Object::Int(look.align.min(2) as i64));
|
||||
if look.repeat {
|
||||
d.set(b"Repeat".to_vec(), Object::Bool(true));
|
||||
}
|
||||
}
|
||||
}
|
||||
Shape::Redact { quads, overlay, look } => set_redaction_properties(&mut d, style, quads, overlay, look),
|
||||
Shape::Rectangle { .. } | Shape::Oval { .. } => {
|
||||
d.set(b"C".to_vec(), rgb(style.color));
|
||||
if let Some(f) = style.fill {
|
||||
@@ -426,22 +407,55 @@ pub fn add_annotation(doc: &mut Document, new: &NewAnnotation, meta: &Meta) -> R
|
||||
let mut list = annots(doc, page);
|
||||
let index = list.len();
|
||||
list.push(Object::Ref(r));
|
||||
if let Some(pr) = popup {
|
||||
let mut p = Dict::new();
|
||||
p.set(b"Type".to_vec(), Object::name("Annot"));
|
||||
p.set(b"Subtype".to_vec(), Object::name("Popup"));
|
||||
p.set(b"Rect".to_vec(), num_array(&pr));
|
||||
p.set(b"Parent".to_vec(), Object::Ref(r));
|
||||
p.set(b"Open".to_vec(), Object::Bool(false));
|
||||
p.set(b"F".to_vec(), Object::Int(FLAG_PRINT | FLAG_NO_ZOOM | FLAG_NO_ROTATE));
|
||||
let pref = doc.add(Object::Dict(p));
|
||||
doc.update_dict(r, |d| d.set(b"Popup".to_vec(), Object::Ref(pref)))?;
|
||||
list.push(Object::Ref(pref));
|
||||
}
|
||||
add_popup(doc, r, popup, &mut list)?;
|
||||
set_annots(doc, page, list)?;
|
||||
Ok(index)
|
||||
}
|
||||
|
||||
fn validate_style(style: &Style) -> Result<(), AnnotError> {
|
||||
if !finite(&style.color) || !style.opacity.is_finite() || !style.width.is_finite() {
|
||||
return Err(AnnotError::Invalid("invalid style".into()));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn set_redaction_properties(dict: &mut Dict, style: &Style, quads: &[[f64; 8]], overlay: &str, look: &OverlayLook) {
|
||||
dict.set(b"C".to_vec(), rgb(style.color));
|
||||
dict.set(b"IC".to_vec(), rgb(style.fill.unwrap_or([0.0, 0.0, 0.0])));
|
||||
dict.set(b"QuadPoints".to_vec(), num_array(&quads.concat()));
|
||||
if !overlay.is_empty() {
|
||||
dict.set(b"OverlayText".to_vec(), PdfString::text(overlay));
|
||||
let [r, g, b] = look.color.map(|x| x.clamp(0.0, 1.0));
|
||||
let size = if look.size > 0.0 { look.size.min(400.0) } else { 0.0 };
|
||||
dict.set(b"DA".to_vec(), PdfString::literal(format!("{} {} {} rg /{} {} Tf", n(r), n(g), n(b), look.font.resource(), n(size)).into_bytes()));
|
||||
dict.set(b"Q".to_vec(), Object::Int(look.align.min(2) as i64));
|
||||
if look.repeat {
|
||||
dict.set(b"Repeat".to_vec(), Object::Bool(true));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn set_non_opaque_style(dict: &mut Dict, opacity: f64) {
|
||||
if opacity < 1.0 {
|
||||
dict.set(b"CA".to_vec(), Object::Real(opacity));
|
||||
}
|
||||
}
|
||||
|
||||
fn add_popup(doc: &mut Document, parent: ObjRef, rect: Option<[f64; 4]>, annots: &mut Vec<Object>) -> Result<(), AnnotError> {
|
||||
let Some(rect) = rect else { return Ok(()) };
|
||||
let mut popup = Dict::new();
|
||||
popup.set(b"Type".to_vec(), Object::name("Annot"));
|
||||
popup.set(b"Subtype".to_vec(), Object::name("Popup"));
|
||||
popup.set(b"Rect".to_vec(), num_array(&rect));
|
||||
popup.set(b"Parent".to_vec(), Object::Ref(parent));
|
||||
popup.set(b"Open".to_vec(), Object::Bool(false));
|
||||
popup.set(b"F".to_vec(), Object::Int(FLAG_PRINT | FLAG_NO_ZOOM | FLAG_NO_ROTATE));
|
||||
let popup_ref = doc.add(Object::Dict(popup));
|
||||
doc.update_dict(parent, |dict| dict.set(b"Popup".to_vec(), Object::Ref(popup_ref)))?;
|
||||
annots.push(Object::Ref(popup_ref));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Counterrotate a newly placed picture stamp's appearance into displayed-page axes.
|
||||
/// The picture may be an image or a PDF page. The normal appearance's transformed bounding
|
||||
/// box is fitted to `/Rect` by PDF viewers.
|
||||
|
||||
@@ -2,7 +2,7 @@ use super::create::{finite, num_array};
|
||||
use super::lookup::{annot_dict, annots, page_refs};
|
||||
use super::modify::refuse_foreign_text;
|
||||
use super::types::NOTE_SIZE;
|
||||
use super::*;
|
||||
use super::{AnnotError, Dict, Document, ObjRef, Object, Stream, appearance};
|
||||
|
||||
/// (Re)generate `/AP /N` for the annotation `r` from its dictionary, for an edit that keeps its
|
||||
/// text (a restyle, a new size or colour).
|
||||
|
||||
@@ -3,7 +3,7 @@ use super::draw::set_appearance;
|
||||
use super::lookup::{annot_dict, annot_ref, annotation_flags, annots, drawn_upright, is_fill_sign, page_ref, page_refs};
|
||||
use super::modify::{fillable, touch, unlocked};
|
||||
use super::types::{FLAG_LOCKED, LineEnding, Meta, NoteIcon, Rgb};
|
||||
use super::*;
|
||||
use super::{AnnotError, Dict, Document, ObjRef, Object, PdfString, appearance};
|
||||
|
||||
// ── reading ─────────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
@@ -33,15 +33,17 @@ pub use info::{Props, Summary, is_comment_subtype, props, set_info, summaries};
|
||||
#[cfg(test)]
|
||||
use lookup::{ANNOTS_ENTRIES_COPIED, PageWalk, annot_dict, annot_ref};
|
||||
use lookup::{annots, page_ref};
|
||||
pub use lookup::{has_visible_fill_sign, is_fill_sign, isolate_annotation, page_refs, picture_rotation, set_annots, signature_image};
|
||||
pub use lookup::{
|
||||
has_visible_fill_sign, is_fill_sign, isolate_annotation, isolate_annotations, page_refs, picture_rotation, set_annots, signature_image,
|
||||
};
|
||||
pub(crate) use modify::n;
|
||||
pub use modify::{
|
||||
add_reply, add_text_replacement, delete_annotation, erase_ink, fillable, goes_with, move_annotation, set_contents, set_fill, set_font_size,
|
||||
set_locked, set_marked, set_points, set_rect, set_review_state, set_style, with_replies_and_popups,
|
||||
add_reply, add_text_replacement, deletable, delete_annotation, erase_ink, fillable, goes_with, lift_annotation, move_annotation, set_contents,
|
||||
set_fill, set_font_size, set_locked, set_marked, set_points, set_rect, set_review_state, set_style, with_replies_and_popups,
|
||||
};
|
||||
pub use types::{
|
||||
AttachIcon, FillMark, LineEnding, Markup, Meta, NOTE_SIZE, NewAnnotation, NoteIcon, OverlayFont, OverlayLook, ReviewState, Rgb, Shape,
|
||||
StampGroup, StampKind, Style, rect_quad,
|
||||
StampGroup, StampKind, Style, StyleChange, TextReplacement, rect_quad,
|
||||
};
|
||||
|
||||
pub mod appearance;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use super::info::text_value;
|
||||
use super::types::{FLAG_HIDDEN, FLAG_NO_ROTATE, FLAG_NO_VIEW, Shape};
|
||||
use super::*;
|
||||
use super::{AnnotError, Dict, Document, ObjRef, Object, appearance};
|
||||
|
||||
// ── pages and /Annots ───────────────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -226,16 +226,33 @@ pub fn picture_rotation(doc: &Document, page: usize, index: usize) -> Result<i64
|
||||
/// over the page while it is dragged. `false`, with `doc` unchanged, when the annotation has no
|
||||
/// normal appearance (`/AP /N`) for that render to draw.
|
||||
pub fn isolate_annotation(doc: &mut Document, page: usize, index: usize) -> Result<bool, AnnotError> {
|
||||
isolate_annotations(doc, page, &[index])
|
||||
}
|
||||
|
||||
/// [`isolate_annotation`] for several annotations of one page: those of them with a normal
|
||||
/// appearance stay, in their order on the page. `false`, with `doc` unchanged, when none has one.
|
||||
/// An index that isn't one of the page's annotations is an error even when the others are, and
|
||||
/// leaves `doc` unchanged too.
|
||||
pub fn isolate_annotations(doc: &mut Document, page: usize, indices: &[usize]) -> Result<bool, AnnotError> {
|
||||
let p = page_ref(doc, page)?;
|
||||
let entry = annots(doc, p).get(index).cloned().ok_or(AnnotError::NoSuchAnnotation { page, index })?;
|
||||
let has_normal = {
|
||||
let obj = doc.resolve(&entry);
|
||||
obj.as_dict().and_then(|d| d.get(b"AP")).is_some_and(|ap| doc.resolve(ap).as_dict().is_some_and(|ap| ap.contains(b"N")))
|
||||
};
|
||||
if !has_normal {
|
||||
let list = annots(doc, p);
|
||||
let mut kept = Vec::new();
|
||||
for (index, entry) in list.iter().enumerate() {
|
||||
if !indices.contains(&index) {
|
||||
continue;
|
||||
}
|
||||
let obj = doc.resolve(entry);
|
||||
if obj.as_dict().and_then(|d| d.get(b"AP")).is_some_and(|ap| doc.resolve(ap).as_dict().is_some_and(|ap| ap.contains(b"N"))) {
|
||||
kept.push(entry.clone());
|
||||
}
|
||||
}
|
||||
if let Some(&index) = indices.iter().find(|&&i| i >= list.len()) {
|
||||
return Err(AnnotError::NoSuchAnnotation { page, index });
|
||||
}
|
||||
if kept.is_empty() {
|
||||
return Ok(false);
|
||||
}
|
||||
set_annots(doc, p, vec![entry])?;
|
||||
set_annots(doc, p, kept)?;
|
||||
doc.update_dict(p, |d| {
|
||||
d.remove(b"Contents");
|
||||
})?;
|
||||
|
||||
@@ -6,8 +6,9 @@ use super::info::{line_endings_of, text_value};
|
||||
use super::lookup::{annot_dict, annot_ref, annotation_flags, annots, page_ref, set_annots};
|
||||
use super::types::{
|
||||
FLAG_HIDDEN, FLAG_LOCKED, FLAG_NO_ROTATE, FLAG_NO_ZOOM, FLAG_PRINT, LineEnding, Markup, Meta, NewAnnotation, ReviewState, Rgb, Shape, Style,
|
||||
StyleChange, TextReplacement,
|
||||
};
|
||||
use super::*;
|
||||
use super::{AnnotError, Dict, Document, HashMap, HashSet, ObjRef, Object, PdfString, appearance};
|
||||
|
||||
/// A comment another program drew, whose text the standard fonts can't draw. Redrawing it would
|
||||
/// replace those characters with `?`, so the edit is refused before the dictionary changes.
|
||||
@@ -69,20 +70,53 @@ pub(crate) fn touch(d: &mut Dict, meta: &Meta) {
|
||||
}
|
||||
|
||||
/// Delete a comment together with its pop-up and its replies (and theirs), as Acrobat does.
|
||||
/// Refused while it, or a reply that would go with it, is locked.
|
||||
pub fn delete_annotation(doc: &mut Document, page: usize, index: usize) -> Result<(), AnnotError> {
|
||||
let p = page_ref(doc, page)?;
|
||||
let list = annots(doc, p);
|
||||
let target = list.get(index).cloned().ok_or(AnnotError::NoSuchAnnotation { page, index })?;
|
||||
deletable(doc, page, index)?;
|
||||
lift_annotation(doc, page, index)
|
||||
}
|
||||
|
||||
/// Whether [`delete_annotation`] deletes the annotation at `(page, index)`, or why not, without
|
||||
/// changing anything: what a Delete command asks before it is offered. It is refused while the
|
||||
/// annotation is locked, or a reply that would go with it is.
|
||||
pub fn deletable(doc: &Document, page: usize, index: usize) -> Result<(), AnnotError> {
|
||||
let list = annots(doc, page_ref(doc, page)?);
|
||||
let target = list.get(index).ok_or(AnnotError::NoSuchAnnotation { page, index })?;
|
||||
if let Some(r) = target.as_ref() {
|
||||
unlocked(doc, r)?;
|
||||
}
|
||||
// An inline comment has no reference to collect; the pop-up it names still goes.
|
||||
let seed = target.as_ref().or_else(|| target.as_dict().and_then(|d| d.reference(b"Popup")));
|
||||
let doomed = with_replies_and_popups(doc, &list, seed);
|
||||
let kept: Vec<Object> = list.into_iter().enumerate().filter(|(i, e)| *i != index && !goes_with(e, &doomed)).map(|(_, e)| e).collect();
|
||||
let doomed = with_replies_and_popups(doc, &list, seed(target));
|
||||
// A locked reply can't be deleted on its own, so it doesn't go with the comment or reply it
|
||||
// answers either. Pop-ups follow their comment.
|
||||
for (_, e) in list.iter().enumerate().filter(|(i, e)| *i != index && goes_with(e, &doomed)) {
|
||||
let obj = doc.resolve(e);
|
||||
if let Some(d) = obj.as_dict().filter(|d| d.name(b"Subtype") != Some(b"Popup".as_slice()))
|
||||
&& annotation_flags(doc, d) & FLAG_LOCKED != 0
|
||||
{
|
||||
return Err(AnnotError::Invalid("a reply to it is locked".into()));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Take the annotation at `(page, index)` out of its page with its pop-up and replies, as
|
||||
/// [`delete_annotation`] does but whatever their locks: for drawing the page beneath it on a
|
||||
/// copy of the document (a stamp or signature being dragged), which changes nothing.
|
||||
pub fn lift_annotation(doc: &mut Document, page: usize, index: usize) -> Result<(), AnnotError> {
|
||||
let p = page_ref(doc, page)?;
|
||||
let list = annots(doc, p);
|
||||
let target = list.get(index).ok_or(AnnotError::NoSuchAnnotation { page, index })?;
|
||||
let doomed = with_replies_and_popups(doc, &list, seed(target));
|
||||
let kept: Vec<Object> = list.iter().enumerate().filter(|(i, e)| *i != index && !goes_with(e, &doomed)).map(|(_, e)| e.clone()).collect();
|
||||
Ok(set_annots(doc, p, kept)?)
|
||||
}
|
||||
|
||||
/// What deleting the `/Annots` entry `target` starts from: its reference, or for an inline
|
||||
/// comment (which has none to collect) the pop-up it names, which still goes.
|
||||
fn seed(target: &Object) -> Option<ObjRef> {
|
||||
target.as_ref().or_else(|| target.as_dict().and_then(|d| d.reference(b"Popup")))
|
||||
}
|
||||
|
||||
/// Whether the `/Annots` entry `entry` goes with `going` (from [`with_replies_and_popups`]): it is
|
||||
/// one of them, or it is written inline (a file can, though the standard asks for references) and
|
||||
/// replies to (`/IRT`) or pops up for (`/Parent`) one of them. An inline entry has no reference
|
||||
@@ -499,17 +533,8 @@ fn border_width_of(d: &Dict) -> f64 {
|
||||
}
|
||||
|
||||
/// Change a comment's colour, opacity, line width and/or line endings, and redraw it.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn set_style(
|
||||
doc: &mut Document,
|
||||
page: usize,
|
||||
index: usize,
|
||||
color: Option<Rgb>,
|
||||
opacity: Option<f64>,
|
||||
width: Option<f64>,
|
||||
endings: Option<&[LineEnding]>,
|
||||
meta: &Meta,
|
||||
) -> Result<(), AnnotError> {
|
||||
pub fn set_style(doc: &mut Document, page: usize, index: usize, change: StyleChange, meta: &Meta) -> Result<(), AnnotError> {
|
||||
let StyleChange { color, opacity, width, endings } = change;
|
||||
let (_, r) = annot_ref(doc, page, index)?;
|
||||
unlocked(doc, r)?;
|
||||
let d = annot_dict(doc, r);
|
||||
@@ -521,7 +546,7 @@ pub fn set_style(
|
||||
if color.is_some_and(|c| !finite(&c)) || opacity.is_some_and(|o| !o.is_finite()) || width.is_some_and(|w| !w.is_finite()) {
|
||||
return Err(AnnotError::Invalid("invalid style".into()));
|
||||
}
|
||||
if let Some(ends) = endings {
|
||||
if let Some(ends) = &endings {
|
||||
let callout = subtype == "FreeText" && d.contains(b"CL");
|
||||
let pair = matches!(subtype.as_str(), "Line" | "PolyLine");
|
||||
if (callout && ends.len() != 1) || (pair && ends.len() != 2) || (!callout && !pair) {
|
||||
@@ -691,18 +716,8 @@ fn pair_points(d: &Dict, key: &[u8]) -> Option<Vec<[f64; 2]>> {
|
||||
/// to, so one id for both writes `inreplyto` equal to the caret's own `name`, and a reader that
|
||||
/// resolves names (Acrobat, and our own importer) loses the pair. `caret_meta` is a second id
|
||||
/// from the caller, so the edit stays deterministic.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn add_text_replacement(
|
||||
doc: &mut Document,
|
||||
page: usize,
|
||||
quads: &[[f64; 8]],
|
||||
replacement: &str,
|
||||
author: &str,
|
||||
strike: &Style,
|
||||
caret: &Style,
|
||||
meta: &Meta,
|
||||
caret_meta: &Meta,
|
||||
) -> Result<usize, AnnotError> {
|
||||
pub fn add_text_replacement(doc: &mut Document, replacement: TextReplacement<'_>) -> Result<usize, AnnotError> {
|
||||
let TextReplacement { page, quads, replacement, author, strike, caret, strike_meta: meta, caret_meta } = replacement;
|
||||
let last = *quads.last().ok_or_else(|| AnnotError::Invalid("select the text to replace first".into()))?;
|
||||
let s = add_annotation(
|
||||
doc,
|
||||
|
||||
@@ -229,6 +229,34 @@ fn delete_takes_popup_and_reply_chain() {
|
||||
assert_eq!(delete_annotation(&mut doc, 0, 9), Err(AnnotError::NoSuchAnnotation { page: 0, index: 9 }));
|
||||
}
|
||||
|
||||
/// A locked reply can't be deleted, so it doesn't go with what it answers either: deleting the
|
||||
/// reply above it, or the comment, is refused and changes nothing; once it is unlocked they go.
|
||||
#[test]
|
||||
fn a_locked_reply_keeps_what_it_answers() {
|
||||
let mut doc = fixture();
|
||||
let note = add_annotation(&mut doc, &new(0, Shape::Note { at: [100.0, 100.0], icon: NoteIcon::Comment }), &meta("n")).unwrap();
|
||||
let reply = add_reply(&mut doc, 0, note, "first", "Bob", &meta("r1")).unwrap();
|
||||
let answer = add_reply(&mut doc, 0, reply, "locked answer", "Ada", &meta("r2")).unwrap();
|
||||
set_locked(&mut doc, 0, answer, true).unwrap();
|
||||
let before = list(&doc, 0).len();
|
||||
assert_eq!(delete_annotation(&mut doc, 0, reply), Err(AnnotError::Invalid("a reply to it is locked".into())));
|
||||
assert_eq!(delete_annotation(&mut doc, 0, note), Err(AnnotError::Invalid("a reply to it is locked".into())));
|
||||
assert_eq!(list(&doc, 0).len(), before, "nothing went");
|
||||
// Asked first, read-only, as a Delete command does: the same answer, and the answer's own
|
||||
// lock is its own.
|
||||
assert_eq!(deletable(&doc, 0, note), Err(AnnotError::Invalid("a reply to it is locked".into())));
|
||||
assert_eq!(deletable(&doc, 0, answer), Err(AnnotError::Invalid("the comment is locked".into())));
|
||||
// Lifted on a copy, to draw the page beneath, the locks don't count.
|
||||
let mut copy = doc.clone();
|
||||
lift_annotation(&mut copy, 0, note).unwrap();
|
||||
assert!(list(©, 0).len() < before, "the thread is lifted off the copy");
|
||||
set_locked(&mut doc, 0, answer, false).unwrap();
|
||||
assert_eq!(deletable(&doc, 0, reply), Ok(()));
|
||||
delete_annotation(&mut doc, 0, reply).unwrap();
|
||||
let left: Vec<String> = list(&doc, 0).iter().map(|d| text(d, b"Contents")).collect();
|
||||
assert!(!left.iter().any(|t| t == "first" || t == "locked answer"), "the reply and its answer went: {left:?}");
|
||||
}
|
||||
|
||||
/// A reply or pop-up written inline in `/Annots` (a file can, though the standard asks for
|
||||
/// references) goes with the comment it points at, and so does a pop-up an inline reply or an
|
||||
/// inline comment names. An unrelated inline comment stays until it is deleted itself.
|
||||
@@ -303,7 +331,7 @@ fn move_shifts_all_geometry_and_the_popup() {
|
||||
fn restyle_and_resize_redraw_the_appearance() {
|
||||
let mut doc = fixture();
|
||||
let r = add_annotation(&mut doc, &new(0, Shape::Rectangle { rect: [10.0, 10.0, 110.0, 60.0] }), &meta("r")).unwrap();
|
||||
set_style(&mut doc, 0, r, Some([1.0, 0.0, 0.0]), Some(0.5), Some(4.0), None, &meta("")).unwrap();
|
||||
set_style(&mut doc, 0, r, StyleChange::new(Some([1.0, 0.0, 0.0]), Some(0.5), Some(4.0), None), &meta("")).unwrap();
|
||||
set_rect(&mut doc, 0, r, [0.0, 0.0, 200.0, 100.0], &meta("")).unwrap();
|
||||
let doc2 = reopen(&doc);
|
||||
let d = &list(&doc2, 0)[r];
|
||||
@@ -313,7 +341,10 @@ fn restyle_and_resize_redraw_the_appearance() {
|
||||
assert_eq!(d.get(b"CA").and_then(|o| o.as_f64()), Some(0.5));
|
||||
// A stamp's appearance can't be regenerated, so restyling it changes nothing.
|
||||
let before = list(&doc, 1)[0].clone();
|
||||
assert_eq!(set_style(&mut doc, 1, 0, Some([0.0; 3]), None, None, None, &meta("")), Err(AnnotError::Unsupported("Stamp".into())));
|
||||
assert_eq!(
|
||||
set_style(&mut doc, 1, 0, StyleChange::new(Some([0.0; 3]), None, None, None), &meta("")),
|
||||
Err(AnnotError::Unsupported("Stamp".into()))
|
||||
);
|
||||
assert_eq!(list(&doc, 1)[0], before);
|
||||
// Lines can't be resized as rectangles.
|
||||
let l = add_annotation(
|
||||
@@ -374,7 +405,7 @@ fn text_box_text_and_colour_changes_are_drawn() {
|
||||
let mut doc = fixture();
|
||||
let t = add_annotation(&mut doc, &new(0, Shape::TextBox { rect: [0.0, 0.0, 300.0, 100.0], font_size: 12.0 }), &meta("t")).unwrap();
|
||||
set_contents(&mut doc, 0, t, "Caf\u{e9} (draft) \u{2014} 100%", &meta("")).unwrap();
|
||||
set_style(&mut doc, 0, t, Some([1.0, 0.0, 0.0]), None, None, None, &meta("")).unwrap();
|
||||
set_style(&mut doc, 0, t, StyleChange::new(Some([1.0, 0.0, 0.0]), None, None, None), &meta("")).unwrap();
|
||||
let doc = reopen(&doc);
|
||||
let d = &list(&doc, 0)[t];
|
||||
assert_eq!(text(d, b"Contents"), "Caf\u{e9} (draft) \u{2014} 100%");
|
||||
@@ -556,8 +587,8 @@ fn fill_and_sign_items_are_drawn() {
|
||||
assert_eq!(text(&all[s], b"Subj"), "Signature");
|
||||
// Other stamps still can't be restyled; ours can.
|
||||
let mut doc = doc;
|
||||
set_style(&mut doc, 1, marks[0], Some([0.0, 0.0, 1.0]), None, None, None, &meta("")).unwrap();
|
||||
assert!(set_style(&mut doc, 1, 0, Some([0.0; 3]), None, None, None, &meta("")).is_err());
|
||||
set_style(&mut doc, 1, marks[0], StyleChange::new(Some([0.0, 0.0, 1.0]), None, None, None), &meta("")).unwrap();
|
||||
assert!(set_style(&mut doc, 1, 0, StyleChange::new(Some([0.0; 3]), None, None, None), &meta("")).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -844,7 +875,20 @@ fn replace_text_groups_a_strikeout_and_a_caret() {
|
||||
let quads = [[100.0, 720.0, 200.0, 720.0, 100.0, 706.0, 200.0, 706.0]];
|
||||
let red = Style { color: [0.89, 0.13, 0.13], opacity: 1.0, width: 1.0, fill: None };
|
||||
let blue = Style { color: [0.0, 0.47, 0.84], opacity: 1.0, width: 1.0, fill: None };
|
||||
let i = add_text_replacement(&mut doc, 0, &quads, "new words", "Ada", &red, &blue, &meta("r"), &meta("r-caret")).unwrap();
|
||||
let i = add_text_replacement(
|
||||
&mut doc,
|
||||
TextReplacement {
|
||||
page: 0,
|
||||
quads: &quads,
|
||||
replacement: "new words",
|
||||
author: "Ada",
|
||||
strike: &red,
|
||||
caret: &blue,
|
||||
strike_meta: &meta("r"),
|
||||
caret_meta: &meta("r-caret"),
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
let doc = reopen(&doc);
|
||||
let a = list(&doc, 0);
|
||||
let strike = &a[i];
|
||||
@@ -866,7 +910,22 @@ fn replace_text_groups_a_strikeout_and_a_caret() {
|
||||
let mut doc = doc;
|
||||
delete_annotation(&mut doc, 0, i).unwrap();
|
||||
assert!(!list(&doc, 0).iter().any(|d| d.name(b"Subtype") == Some(b"Caret")));
|
||||
assert!(add_text_replacement(&mut doc, 0, &[], "x", "Ada", &red, &blue, &meta("r"), &meta("r-caret")).is_err());
|
||||
assert!(
|
||||
add_text_replacement(
|
||||
&mut doc,
|
||||
TextReplacement {
|
||||
page: 0,
|
||||
quads: &[],
|
||||
replacement: "x",
|
||||
author: "Ada",
|
||||
strike: &red,
|
||||
caret: &blue,
|
||||
strike_meta: &meta("r"),
|
||||
caret_meta: &meta("r-caret")
|
||||
}
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1177,7 +1236,7 @@ fn every_line_ending_is_drawn() {
|
||||
)
|
||||
.unwrap();
|
||||
let before = rect(&list(&doc, 0).into_iter().find(|d| d.name(b"Subtype") == Some(b"Line")).expect("line"));
|
||||
set_style(&mut doc, 0, index, None, None, None, Some(&[LineEnding::None, LineEnding::Square]), &meta("style")).unwrap();
|
||||
set_style(&mut doc, 0, index, StyleChange::new(None, None, None, Some(vec![LineEnding::None, LineEnding::Square])), &meta("style")).unwrap();
|
||||
let mut doc = reopen(&doc);
|
||||
let line = list(&doc, 0).into_iter().find(|d| d.name(b"Subtype") == Some(b"Line")).expect("line");
|
||||
let after = rect(&line);
|
||||
@@ -1245,7 +1304,7 @@ fn redraw_keeps_shared_annotation_appearances_and_drops_stale_alternates() {
|
||||
let other_dict = list(&doc, 0)[other].clone();
|
||||
let source = other_dict.get(b"AP").unwrap();
|
||||
let before = doc.resolve(source);
|
||||
set_style(&mut doc, 0, first, Some([1.0, 0.0, 0.0]), None, None, None, &meta("")).unwrap();
|
||||
set_style(&mut doc, 0, first, StyleChange::new(Some([1.0, 0.0, 0.0]), None, None, None), &meta("")).unwrap();
|
||||
assert_eq!(doc.resolve(source), before, "a shared AP must not change");
|
||||
for full in [false, true] {
|
||||
let bytes = if full {
|
||||
@@ -1367,7 +1426,7 @@ fn comment_text_the_standard_fonts_cannot_draw_is_kept_and_marked() {
|
||||
.unwrap();
|
||||
assert_eq!(mark(&doc, s), Some('张'));
|
||||
// Our own `?` appearance is redrawn on a restyle; Western European text clears the mark.
|
||||
set_style(&mut doc, 0, t, Some([1.0, 0.0, 0.0]), None, None, None, &meta("")).unwrap();
|
||||
set_style(&mut doc, 0, t, StyleChange::new(Some([1.0, 0.0, 0.0]), None, None, None), &meta("")).unwrap();
|
||||
assert_eq!(mark(&doc, t), Some('签'));
|
||||
set_contents(&mut doc, 0, t, "Zürich —\nGenève", &meta("")).unwrap();
|
||||
assert_eq!(mark(&doc, t), None);
|
||||
@@ -1395,7 +1454,7 @@ fn comment_text_the_standard_fonts_cannot_draw_is_kept_and_marked() {
|
||||
set_annots(&mut doc, page, on_page).unwrap();
|
||||
let k = list(&doc, 0).len() - 1;
|
||||
let before = list(&doc, 0)[k].clone();
|
||||
let err = set_style(&mut doc, 0, k, Some([1.0, 0.0, 0.0]), Some(0.4), Some(6.0), None, &meta("")).unwrap_err();
|
||||
let err = set_style(&mut doc, 0, k, StyleChange::new(Some([1.0, 0.0, 0.0]), Some(0.4), Some(6.0), None), &meta("")).unwrap_err();
|
||||
assert!(matches!(&err, AnnotError::Undrawable(m) if m.contains("can't redraw") && m.contains("\"欢\" (U+6B22)")), "{err:?}");
|
||||
assert_eq!(list(&doc, 0)[k], before, "a refused restyle keeps the colour, opacity, width and appearance");
|
||||
let err = set_rect(&mut doc, 0, k, [40.0, 40.0, 180.0, 90.0], &meta("")).unwrap_err();
|
||||
@@ -1476,7 +1535,7 @@ fn a_comment_listed_many_times_is_drawn_once_for_display() {
|
||||
fn text_box_font_size_changes_the_da_and_grows_the_box() {
|
||||
let mut doc = fixture();
|
||||
let t = add_annotation(&mut doc, &new(0, Shape::TextBox { rect: [100.0, 680.0, 220.0, 692.0], font_size: 12.0 }), &meta("t")).unwrap();
|
||||
set_style(&mut doc, 0, t, Some([1.0, 0.0, 0.0]), None, None, None, &meta("")).unwrap();
|
||||
set_style(&mut doc, 0, t, StyleChange::new(Some([1.0, 0.0, 0.0]), None, None, None), &meta("")).unwrap();
|
||||
set_contents(&mut doc, 0, t, "one two three four five six seven eight nine ten eleven twelve", &meta("")).unwrap();
|
||||
let height = |doc: &Document| {
|
||||
let rect: Vec<f64> = list(doc, 0)[t].get(b"Rect").unwrap().as_array().unwrap().iter().map(|x| x.as_f64().unwrap()).collect();
|
||||
@@ -1522,7 +1581,7 @@ fn text_boxes_and_callouts_can_change_fill_and_border() {
|
||||
let index = add_annotation(&mut doc, &new(0, shape), &meta("test")).unwrap();
|
||||
assert!(props(&doc, 0, index).unwrap().fillable);
|
||||
set_fill(&mut doc, 0, index, Some([1.0, 1.0, 1.0]), &meta("test")).unwrap();
|
||||
set_style(&mut doc, 0, index, None, None, Some(3.0), None, &meta("test")).unwrap();
|
||||
set_style(&mut doc, 0, index, StyleChange::new(None, None, Some(3.0), None), &meta("test")).unwrap();
|
||||
let saved = reopen(&doc);
|
||||
let properties = props(&saved, 0, index).unwrap();
|
||||
assert_eq!(properties.fill, Some([1.0; 3]));
|
||||
@@ -1791,7 +1850,7 @@ fn a_star_note_keeps_its_star_when_recoloured() {
|
||||
b"<< /Type /Annot /Subtype /Text /Rect [100 100 120 120] /Name /Star /C [1 0.82 0] /F 4 >>",
|
||||
]);
|
||||
assert_eq!(props(&doc, 0, 0).and_then(|p| p.icon), Some(NoteIcon::Star));
|
||||
set_style(&mut doc, 0, 0, Some([0.0, 0.0, 1.0]), None, None, None, &meta("")).unwrap();
|
||||
set_style(&mut doc, 0, 0, StyleChange::new(Some([0.0, 0.0, 1.0]), None, None, None), &meta("")).unwrap();
|
||||
let doc = reopen(&doc);
|
||||
let d = &list(&doc, 0)[0];
|
||||
assert_eq!(d.name(b"Name"), Some(&b"Star"[..]));
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use super::create::normalize;
|
||||
use super::*;
|
||||
use super::{ObjRef, appearance};
|
||||
|
||||
pub type Rgb = [f64; 3];
|
||||
|
||||
@@ -563,6 +563,33 @@ pub struct Style {
|
||||
pub fill: Option<Rgb>,
|
||||
}
|
||||
|
||||
/// The style properties changed by one annotation edit. `None` leaves a property unchanged.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct StyleChange {
|
||||
pub color: Option<Rgb>,
|
||||
pub opacity: Option<f64>,
|
||||
pub width: Option<f64>,
|
||||
pub endings: Option<Vec<LineEnding>>,
|
||||
}
|
||||
|
||||
impl StyleChange {
|
||||
pub fn new(color: Option<Rgb>, opacity: Option<f64>, width: Option<f64>, endings: Option<Vec<LineEnding>>) -> Self {
|
||||
Self { color, opacity, width, endings }
|
||||
}
|
||||
}
|
||||
|
||||
/// Inputs for replacing selected text with a grouped strikeout and caret annotation.
|
||||
pub struct TextReplacement<'a> {
|
||||
pub page: usize,
|
||||
pub quads: &'a [[f64; 8]],
|
||||
pub replacement: &'a str,
|
||||
pub author: &'a str,
|
||||
pub strike: &'a Style,
|
||||
pub caret: &'a Style,
|
||||
pub strike_meta: &'a Meta,
|
||||
pub caret_meta: &'a Meta,
|
||||
}
|
||||
|
||||
impl Default for Style {
|
||||
fn default() -> Self {
|
||||
Self { color: [1.0, 0.82, 0.0], opacity: 1.0, width: 1.0, fill: None }
|
||||
|
||||
@@ -181,6 +181,12 @@ working document unchanged.
|
||||
`content_list` or `object_list`. It removes only that item in a read-only preview and is
|
||||
mutually exclusive with `hide_text_block`.
|
||||
|
||||
When the renderer reports a warning for the page, `page_render` and `render_preview` return a
|
||||
JSON part after the PNG, `{ "page": 1, "warnings": [...] }`, with the sentences
|
||||
`pdfcraft-cli render` prints: "content past the page's safety budget was skipped" and "a colour
|
||||
that could not be computed was painted in a fallback colour". A page without warnings returns
|
||||
the PNG alone.
|
||||
|
||||
|
||||
## Existing text and document fonts
|
||||
|
||||
@@ -214,6 +220,18 @@ unapplied with a warning.
|
||||
folders. The CLI also exposes it as `pdfcraft-cli batch`. See the
|
||||
[batch guide](../../docs/cli-batch.md) for examples, output protection, errors and limits.
|
||||
|
||||
## Editing button export values
|
||||
|
||||
Use `form_set_props` with `field`, `export_value` and optional `widget`
|
||||
(1-based, default 1) to change a checkbox or radio button export value.
|
||||
`form_fields` returns `export_values` in widget order. The selected/default
|
||||
appearance states are preserved; the operation is undoable and survives saving.
|
||||
Widgets sharing an appearance state keep one export value. Bulk edits are not
|
||||
supported for this widget-specific property. Empty values, `Off`, conflicting
|
||||
choices and values over 4096 UTF-8 bytes return an error.
|
||||
|
||||
Example: `form_set_props doc=1 field=agree export_value=Accepted widget=1`.
|
||||
|
||||
## Viewer navigation history
|
||||
|
||||
A running PdfCraft instance launched with `--control FILE` exposes its per-tab history through
|
||||
@@ -229,3 +247,10 @@ behavior. Back/Forward
|
||||
returns to page tops, does not restore zoom, does not switch documents, and is not saved across
|
||||
restarts. Standalone engine/MCP sessions have no viewport, so they do not have a separate
|
||||
navigation-history tool; use the opt-in UI control channel to navigate the displayed document.
|
||||
|
||||
## Fill & Sign text appearance
|
||||
|
||||
`fill_sign_add` accepts `font_size` (4–300 pt, default 10) and `color`
|
||||
(`#RRGGBB`, default black) for `text` and `date`. The colour is saved in the
|
||||
FreeText appearance and survives reopening. Other mark/signature types reject
|
||||
`color`; their appearance controls are separate.
|
||||
@@ -1,11 +1,11 @@
|
||||
use super::*;
|
||||
use super::{Args, Automation, Result, ToolError, Value, child, failed, json, unused, write_atomic};
|
||||
|
||||
impl Automation {
|
||||
pub(crate) fn doc_export_office(&self, a: &Args) -> Result<Value> {
|
||||
let path = self.resolve(a.str("path")?, true)?;
|
||||
let ext = path.extension().map(|e| e.to_string_lossy().into_owned()).unwrap_or_default();
|
||||
let format = pdfcraft_engine::compare::OfficeFormat::from_extension(&ext)
|
||||
.ok_or_else(|| ToolError::InvalidArgs(format!("unsupported extension {ext:?} (docx, pptx, html or rtf)")))?;
|
||||
.ok_or_else(|| ToolError::InvalidArgs(format!("unsupported extension {ext:?} (docx, pptx, html, rtf or md)")))?;
|
||||
let export = self.doc_to_copy(a)?.export_office_checked(format);
|
||||
write_atomic(&path, &export.bytes)?;
|
||||
// Text left out to keep a hostile page bounded is said, not silent (#3120).
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use super::*;
|
||||
use super::{Args, Automation, Result, ToolError, Value, failed, json, write_atomic};
|
||||
|
||||
/// A script's request to the viewer as the JSON that running a script reports; a side panel
|
||||
/// goes by its fixed id.
|
||||
@@ -17,14 +17,21 @@ fn request_json(r: &pdfcraft_engine::js::Request) -> Value {
|
||||
}
|
||||
}
|
||||
|
||||
/// A message a script showed, as `js_run` reports it: its text, title (null when it gave none),
|
||||
/// icon and buttons.
|
||||
fn alert_json(m: &pdfcraft_engine::js::Message) -> Value {
|
||||
json!({ "message": m.text, "title": m.title, "icon": m.icon.name(), "buttons": m.buttons.name() })
|
||||
}
|
||||
|
||||
impl Automation {
|
||||
/// `js_run`: run `script` in the document, or as button `field`'s script, and report its
|
||||
/// messages, console lines, requests, error, the failing document scripts' errors and result.
|
||||
pub(crate) fn js_run(&mut self, a: &Args) -> Result<Value> {
|
||||
let id = self.doc(a)?.id;
|
||||
let o = self.session.run_javascript(id, a.str("script")?, a.opt_str("field")?).map_err(failed)?;
|
||||
let reqs: Vec<Value> = o.requests.iter().map(request_json).collect();
|
||||
Ok(
|
||||
json!({ "alerts": o.alerts, "console": o.console, "requests": reqs, "error": o.error, "document_errors": o.doc_errors, "result": o.result }),
|
||||
)
|
||||
let alerts: Vec<Value> = o.alerts.iter().map(alert_json).collect();
|
||||
Ok(json!({ "alerts": alerts, "console": o.console, "requests": reqs, "error": o.error, "document_errors": o.doc_errors, "result": o.result }))
|
||||
}
|
||||
|
||||
pub(crate) fn js_document_scripts(&self, a: &Args) -> Result<Value> {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use super::*;
|
||||
use super::{Args, Automation, Result, ToolError, Value, child, failed, json, write_atomic};
|
||||
|
||||
impl Automation {
|
||||
/// Recognition settings from the arguments: `dpi` (clamped to 72–600), `language` (refused
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use super::error::{Result, ToolError, failed};
|
||||
use super::json::{Args, one_based, summary};
|
||||
use super::paths::{child, read_input, read_input_bytes, unused, write_atomic};
|
||||
use super::*;
|
||||
use super::{Arc, Automation, CombineSource, Edit, Path, PathBuf, Value, json};
|
||||
|
||||
impl Automation {
|
||||
pub(crate) fn doc_create(&mut self, a: &Args) -> Result<Value> {
|
||||
|
||||
@@ -17,6 +17,7 @@ const MAX_INPUT: u64 = 512 * 1024 * 1024;
|
||||
struct Recipe<'a> {
|
||||
steps: Vec<&'a str>,
|
||||
images: optimize::ImageSettings,
|
||||
mono: optimize::MonoSettings,
|
||||
ocr: ocr::OcrSettings,
|
||||
}
|
||||
|
||||
@@ -38,12 +39,17 @@ impl<'a> Recipe<'a> {
|
||||
}
|
||||
}
|
||||
let mut images = optimize::ImageSettings::REDUCE;
|
||||
let mut mono = optimize::MonoSettings::REDUCE;
|
||||
if let Some(ppi) = args.opt_num("ppi")? {
|
||||
if !(9.0..=1600.0).contains(&ppi) {
|
||||
return Err(Args::wrong("ppi", "9 to 1600"));
|
||||
}
|
||||
images.target_ppi = ppi;
|
||||
images.above_ppi = ppi * 1.5;
|
||||
// Black-and-white images keep Reduce File Size's higher resolution, at which text
|
||||
// stays legible, and are never taken below a higher `ppi` asked for.
|
||||
mono.target_ppi = mono.target_ppi.max(ppi);
|
||||
mono.above_ppi = mono.target_ppi * 1.5;
|
||||
}
|
||||
if let Some(q) = args.opt_int("quality")? {
|
||||
if !(1..=100).contains(&q) {
|
||||
@@ -54,7 +60,7 @@ impl<'a> Recipe<'a> {
|
||||
if args.opt_num("dpi")?.is_some_and(|dpi| !(72.0..=600.0).contains(&dpi)) {
|
||||
return Err(Args::wrong("dpi", "72 to 600"));
|
||||
}
|
||||
Ok(Self { steps, images, ocr: auto.ocr_settings(args)? })
|
||||
Ok(Self { steps, images, mono, ocr: auto.ocr_settings(args)? })
|
||||
}
|
||||
|
||||
fn accepts(&self, path: &Path) -> bool {
|
||||
@@ -88,7 +94,7 @@ impl<'a> Recipe<'a> {
|
||||
}
|
||||
"optimize" => {
|
||||
let id = session.open(name, None, bytes.clone(), None).map_err(failed)?;
|
||||
let settings = optimize::Settings { color: self.images, gray: self.images, ..Default::default() };
|
||||
let settings = optimize::Settings { color: self.images, gray: self.images, mono: self.mono, ..Default::default() };
|
||||
let (candidate, _) = session.optimized_bytes(id, &settings, &[])?;
|
||||
session.close(id);
|
||||
if candidate.len() < bytes.len() {
|
||||
|
||||
@@ -502,6 +502,10 @@ impl Automation {
|
||||
if sensitivity.is_some() && !scan {
|
||||
return Err(ToolError::InvalidArgs("sensitivity is only for scan: true".into()));
|
||||
}
|
||||
let requested_color = a.color("color")?;
|
||||
if requested_color.is_some() && !matches!(kind, "text" | "date") {
|
||||
return Err(ToolError::InvalidArgs("color is only for type text or date".into()));
|
||||
}
|
||||
let requested_size = a.opt_num("font_size")?;
|
||||
if requested_size.is_some() && !matches!(kind, "text" | "date") {
|
||||
return Err(ToolError::InvalidArgs("font_size is only for type text or date".into()));
|
||||
@@ -579,7 +583,10 @@ impl Automation {
|
||||
(Shape::Mark { rect: mark.rect_at(at, i64::from(info.rotation)), mark }, String::new())
|
||||
}
|
||||
};
|
||||
let style = Style::default_for(&shape);
|
||||
let mut style = Style::default_for(&shape);
|
||||
if let Some(color) = requested_color {
|
||||
style.color = color;
|
||||
}
|
||||
self.apply(a, Edit::AddAnnotation(NewAnnotation { page, shape, style, contents, author }))
|
||||
}
|
||||
|
||||
|
||||
@@ -53,13 +53,13 @@ fn style(a: &Args, t: &mut AddedText) -> Result<()> {
|
||||
t.color = parse_color(c)?;
|
||||
}
|
||||
if let Some(al) = a.opt_str("align")? {
|
||||
t.align = match al {
|
||||
"left" => TextAlign::Left,
|
||||
"center" | "centre" => TextAlign::Center,
|
||||
"right" => TextAlign::Right,
|
||||
"justify" => TextAlign::Justify,
|
||||
other => return Err(bad(format!("unknown align {other:?}"))),
|
||||
};
|
||||
t.align = parse_align(al)?;
|
||||
// The whole box: no paragraph keeps an alignment of its own unless `aligns` gives it one.
|
||||
t.aligns.clear();
|
||||
}
|
||||
if let Some(aligns) = opt_aligns(a)? {
|
||||
let count = pdfcraft_engine::paragraph_align::count(&t.text);
|
||||
t.aligns = pdfcraft_engine::paragraph_align::tidy(aligns.into_iter().take(count).collect(), t.align);
|
||||
}
|
||||
if let Some(c) = a.opt_num("char_spacing")? {
|
||||
if !(-ADDED_CHAR_SPACING_LIMIT..=ADDED_CHAR_SPACING_LIMIT).contains(&c) {
|
||||
@@ -70,6 +70,37 @@ fn style(a: &Args, t: &mut AddedText) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn parse_align(al: &str) -> Result<TextAlign> {
|
||||
Ok(match al {
|
||||
"left" => TextAlign::Left,
|
||||
"center" | "centre" => TextAlign::Center,
|
||||
"right" => TextAlign::Right,
|
||||
"justify" => TextAlign::Justify,
|
||||
other => return Err(bad(format!("unknown align {other:?}"))),
|
||||
})
|
||||
}
|
||||
|
||||
/// Most entries `aligns` takes: one per paragraph, and no text has this many.
|
||||
const MAX_ALIGNS: usize = 4096;
|
||||
|
||||
/// `aligns`: each paragraph's (line's) own alignment, or null where it follows `align`.
|
||||
pub(crate) fn opt_aligns(a: &Args) -> Result<Option<Vec<Option<TextAlign>>>> {
|
||||
let Some(v) = a.get("aligns") else { return Ok(None) };
|
||||
let items = v.as_array().ok_or_else(|| bad("aligns must be an array of left, center, right, justify or null"))?;
|
||||
if items.len() > MAX_ALIGNS {
|
||||
return Err(bad(format!("aligns takes at most {MAX_ALIGNS} entries")));
|
||||
}
|
||||
items
|
||||
.iter()
|
||||
.map(|v| match v {
|
||||
Value::Null => Ok(None),
|
||||
Value::String(s) => parse_align(s).map(Some),
|
||||
_ => Err(bad("each entry of aligns is left, center, right, justify or null")),
|
||||
})
|
||||
.collect::<Result<Vec<_>>>()
|
||||
.map(Some)
|
||||
}
|
||||
|
||||
impl Automation {
|
||||
pub(crate) fn content_list(&self, a: &Args) -> Result<Value> {
|
||||
let doc = self.doc(a)?;
|
||||
@@ -160,6 +191,8 @@ impl Automation {
|
||||
match &mut content {
|
||||
AddedContent::Text(t) => {
|
||||
if let Some(s) = a.opt_str("text")? {
|
||||
// Each paragraph keeps its own alignment through the retyping.
|
||||
t.aligns = pdfcraft_engine::paragraph_align::remap(&t.text, s, &t.aligns);
|
||||
t.text = s.to_string();
|
||||
}
|
||||
style(a, t)?;
|
||||
@@ -171,8 +204,8 @@ impl Automation {
|
||||
if a.get("text").is_some() {
|
||||
return Err(bad("images have no text"));
|
||||
}
|
||||
if ["font", "size", "bold", "italic", "color", "align", "char_spacing"].iter().any(|k| a.get(k).is_some()) {
|
||||
return Err(bad("font, size, bold, italic, color, align and char_spacing apply to text"));
|
||||
if ["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 let Some(deg) = a.opt_int("rotate")? {
|
||||
if deg.rem_euclid(90) != 0 {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//! Shared command/inspection/preview entry points, using the existing confined tool path.
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::{Args, Automation, Content, Result, ToolError, encode_png, failed, info, tools};
|
||||
use crate::{Args, Automation, Content, Result, ToolError, failed, info, rendered_content, tools};
|
||||
use pdfcraft_engine::commands;
|
||||
use pdfcraft_render::{RenderRequest, RequestKind};
|
||||
|
||||
@@ -108,7 +108,8 @@ impl Automation {
|
||||
Ok(json!({"documents":self.session.docs().iter().map(info).collect::<Vec<_>>()}))
|
||||
}
|
||||
|
||||
pub(crate) fn render_preview(&mut self, args: &Args) -> Result<Content> {
|
||||
/// A bounded PNG of the page, with its render warnings after it as `page_render` gives them.
|
||||
pub(crate) fn render_preview(&mut self, args: &Args) -> Result<Vec<Content>> {
|
||||
let id = if args.opt_int("doc")?.is_some() {
|
||||
self.doc(args)?.id
|
||||
} else {
|
||||
@@ -134,7 +135,6 @@ impl Automation {
|
||||
if let Some(error) = out.error {
|
||||
return Err(failed(error));
|
||||
}
|
||||
let data = encode_png(out.width, out.height, &out.rgba)?;
|
||||
Ok(Content::Png { data, width: out.width, height: out.height })
|
||||
rendered_content(&out, page)
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
use super::error::{Result, ToolError, failed};
|
||||
use super::json::{Args, document_attachment_keys, info, one_based, parse_style_ranges, security, summary};
|
||||
use super::json::{Args, document_attachment_keys, info, one_based, parse_style_ranges, security, summary, text_style_levels};
|
||||
use super::paths::{read_input, write_atomic};
|
||||
use super::*;
|
||||
use super::{Arc, Automation, Edit, Value, block_overlapping, comments, content, json, tools};
|
||||
|
||||
/// One piece of a tool's result.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
@@ -38,7 +38,7 @@ impl Automation {
|
||||
let edit = Edit::SetInfo { key: a.str("key")?.into(), value: a.str("value")?.into() };
|
||||
self.apply(&a, edit)?
|
||||
}
|
||||
"page_render" => return self.page_render(&a).map(|c| vec![c]),
|
||||
"page_render" => return self.page_render(&a),
|
||||
"comment_image_preview" => return self.comment_image_preview(&a),
|
||||
"text_extract" => self.text_extract(&a)?,
|
||||
"text_word_count" => self.text_word_count(&a)?,
|
||||
@@ -142,7 +142,7 @@ impl Automation {
|
||||
"command_run" => return self.command_run(&a),
|
||||
"command_batch" => self.command_batch(&a)?,
|
||||
"doc_inspect" => self.doc_inspect(&a)?,
|
||||
"render_preview" => return self.render_preview(&a).map(|c| vec![c]),
|
||||
"render_preview" => return self.render_preview(&a),
|
||||
"page_number" => {
|
||||
use pdfcraft_organize::LabelStyle as L;
|
||||
let n = self.doc(&a)?.info.pages.len();
|
||||
@@ -234,6 +234,34 @@ impl Automation {
|
||||
out["next"] = listing["next"].clone();
|
||||
out
|
||||
}
|
||||
"text_styles" => {
|
||||
// The samples are the document's text, as text_lines is.
|
||||
let doc = self.doc_to_copy(&a)?;
|
||||
let styles: Vec<Value> = doc
|
||||
.text_styles()
|
||||
.into_iter()
|
||||
.map(|u| {
|
||||
json!({
|
||||
"font": u.style.font,
|
||||
"size": u.style.size,
|
||||
"bold": u.style.bold,
|
||||
"italic": u.style.italic,
|
||||
"lines": u.lines,
|
||||
"pages": u.pages,
|
||||
"sample": u.sample,
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
json!({ "styles": styles })
|
||||
}
|
||||
"bookmark_from_text_styles" => {
|
||||
let levels = text_style_levels(&a)?;
|
||||
let mut out = self.apply(&a, Edit::BookmarksFromTextStyles { levels })?;
|
||||
let listing = self.bookmark_listing(&a)?;
|
||||
out["bookmarks"] = listing["bookmarks"].clone();
|
||||
out["next"] = listing["next"].clone();
|
||||
out
|
||||
}
|
||||
"doc_protect" => self.doc_protect(&a)?,
|
||||
"page_replace" => {
|
||||
let pages = self.pages(&a, "pages")?;
|
||||
@@ -510,7 +538,15 @@ impl Automation {
|
||||
};
|
||||
let index = self.paragraph_index(id, page, k, &blocks)?;
|
||||
let block = blocks.get(index).cloned().ok_or_else(|| ToolError::InvalidArgs(format!("paragraph {k} is out of range")))?;
|
||||
let text = a.opt_str("text")?.map(str::to_owned).unwrap_or(block.text);
|
||||
let width = a.opt_num("width")?;
|
||||
// Explicit row alignments keep the editor's row boundaries; a width-only
|
||||
// reflow rejoins soft wraps while retaining typed newlines and spaces.
|
||||
let text = match a.opt_str("text")? {
|
||||
Some(text) => text.to_owned(),
|
||||
None if a.get("aligns").is_some() => block.editor_text,
|
||||
None if width.is_some() => block.reflow_text.clone(),
|
||||
None => block.text,
|
||||
};
|
||||
let mut style = pdfcraft_engine::BlockStyle {
|
||||
ranges: parse_style_ranges(a.get("ranges"))?,
|
||||
resource: a.opt_str("font_resource")?.map(str::to_owned),
|
||||
@@ -520,7 +556,7 @@ impl Automation {
|
||||
line_spacing: a.opt_num("line_spacing")?,
|
||||
char_spacing: a.opt_num("char_spacing")?,
|
||||
scale: a.opt_num("scale")?,
|
||||
width: a.opt_num("width")?,
|
||||
width,
|
||||
..Default::default()
|
||||
};
|
||||
let (dx, dy) = (a.opt_num("dx")?, a.opt_num("dy")?);
|
||||
@@ -540,13 +576,10 @@ impl Automation {
|
||||
style.color = Some(comments::parse_color(c)?);
|
||||
}
|
||||
if let Some(al) = a.opt_str("align")? {
|
||||
style.align = Some(match al {
|
||||
"left" => pdfcraft_engine::TextAlign::Left,
|
||||
"center" => pdfcraft_engine::TextAlign::Center,
|
||||
"right" => pdfcraft_engine::TextAlign::Right,
|
||||
"justify" => pdfcraft_engine::TextAlign::Justify,
|
||||
other => return Err(ToolError::InvalidArgs(format!("unknown align {other:?}"))),
|
||||
});
|
||||
style.align = Some(content::parse_align(al)?);
|
||||
}
|
||||
if let Some(aligns) = content::opt_aligns(&a)? {
|
||||
style.aligns = aligns;
|
||||
}
|
||||
// Where the paragraph is drawn after the edit: moved by dx, dy (up is +dy).
|
||||
let [dx, dy] = style.offset.unwrap_or([0.0, 0.0]);
|
||||
@@ -608,6 +641,7 @@ impl Automation {
|
||||
}
|
||||
"doc_export_images" | "doc_export_text" | "doc_export_all_images" => self.export(name, &a)?,
|
||||
"doc_header_footer" | "doc_watermark" | "doc_background" | "doc_remove_marks" => self.marks(name, &a)?,
|
||||
"doc_backdrops" => self.backdrops(&a)?,
|
||||
"doc_unprotect" => {
|
||||
let mut out = self.apply(&a, Edit::RemoveProtection)?;
|
||||
out["security"] = security(self.doc(&a)?);
|
||||
@@ -742,7 +776,7 @@ impl Automation {
|
||||
let ids: Vec<Value> = pdfcraft_engine::sign::keychain::identities(None)
|
||||
.map_err(failed)?
|
||||
.iter()
|
||||
.map(|id| json!({ "id": pdfcraft_engine::sign::keychain::reference(&id.certificate), "certificate": signing::cert_json(&id.certificate) }))
|
||||
.map(|id| json!({ "id": pdfcraft_engine::sign::keychain::reference(&id.certificate), "certificate": super::signing::cert_json(&id.certificate) }))
|
||||
.collect();
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
let ids: Vec<Value> = Vec::new();
|
||||
@@ -755,7 +789,7 @@ impl Automation {
|
||||
let ids = listing
|
||||
.ids
|
||||
.iter()
|
||||
.map(|id| json!({ "id": pdfcraft_engine::sign::windows::reference(&id.certificate), "certificate": signing::cert_json(&id.certificate) }))
|
||||
.map(|id| json!({ "id": pdfcraft_engine::sign::windows::reference(&id.certificate), "certificate": super::signing::cert_json(&id.certificate) }))
|
||||
.collect();
|
||||
let unusable = listing
|
||||
.unusable
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use super::error::{Result, ToolError, failed};
|
||||
use super::json::{Args, nest_rows, security, summary};
|
||||
use super::paths::{child, read_input, write_atomic};
|
||||
use super::*;
|
||||
use super::{Arc, Automation, BlockKey, DocId, Document, Edit, Path, PathBuf, TextBlock, Value, comments, file_access, json};
|
||||
|
||||
/// 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;
|
||||
@@ -279,7 +279,8 @@ impl Automation {
|
||||
}
|
||||
|
||||
pub(crate) fn doc_optimize(&mut self, a: &Args) -> Result<Value> {
|
||||
use pdfcraft_engine::optimize::{Compatibility, Compression, ImageSettings, Preset};
|
||||
use pdfcraft_engine::optimize::{Compatibility, Compression, ImageSettings, MonoCompression, Preset};
|
||||
const MONO_KEYS: [&str; 4] = ["downsample", "ppi", "above_ppi", "compression"];
|
||||
let id = self.doc(a)?.id;
|
||||
let before = self.doc(a)?.bytes.len();
|
||||
let path = self.resolve(a.str("path")?, true)?;
|
||||
@@ -317,6 +318,38 @@ impl Automation {
|
||||
};
|
||||
settings.color = images("color", settings.color)?;
|
||||
settings.gray = images("gray", settings.gray)?;
|
||||
if let Some(mono) = a.get("mono") {
|
||||
let unknown = |c: &Value| ToolError::InvalidArgs(format!("unknown mono compression {c} (ccitt_g4, jbig2, retain)"));
|
||||
let mono = mono.as_object().ok_or_else(|| {
|
||||
ToolError::InvalidArgs("mono must be an object: { downsample, ppi, above_ppi, compression: ccitt_g4|jbig2|retain }".into())
|
||||
})?;
|
||||
// A misspelled key would otherwise leave the preset's setting in place unnoticed.
|
||||
if let Some(key) = mono.keys().find(|k| !MONO_KEYS.contains(&k.as_str())) {
|
||||
return Err(ToolError::InvalidArgs(format!("unknown mono key {key:?} ({})", MONO_KEYS.join(", "))));
|
||||
}
|
||||
let m = &mut settings.mono;
|
||||
if let Some(d) = mono.get("downsample") {
|
||||
m.downsample = d.as_bool().ok_or_else(|| ToolError::InvalidArgs(format!("mono downsample must be true or false, not {d}")))?;
|
||||
}
|
||||
for (key, ppi) in [("ppi", &mut m.target_ppi), ("above_ppi", &mut m.above_ppi)] {
|
||||
if let Some(p) = mono.get(key) {
|
||||
*ppi = p
|
||||
.as_f64()
|
||||
.filter(|p| p.is_finite())
|
||||
.ok_or_else(|| ToolError::InvalidArgs(format!("mono {key} must be a number, not {p}")))?
|
||||
.clamp(9.0, 2400.0);
|
||||
}
|
||||
}
|
||||
m.above_ppi = m.above_ppi.max(m.target_ppi);
|
||||
if let Some(c) = mono.get("compression") {
|
||||
m.compression = match c.as_str() {
|
||||
Some("ccitt_g4" | "ccitt" | "g4") => MonoCompression::CcittG4,
|
||||
Some("jbig2") => MonoCompression::Jbig2,
|
||||
Some("retain") => MonoCompression::Retain,
|
||||
_ => return Err(unknown(c)),
|
||||
};
|
||||
}
|
||||
}
|
||||
for (key, flag) in [
|
||||
("merge_fragments", &mut settings.merge_fragments),
|
||||
("discard_thumbnails", &mut settings.discard_thumbnails),
|
||||
@@ -356,7 +389,9 @@ impl Automation {
|
||||
let pw = self.doc(a).ok().and_then(|d| d.password.as_deref());
|
||||
let doc = pdfcraft_cos::Document::open_with_password(bytes.clone(), pw).ok()?;
|
||||
let root = doc.root()?;
|
||||
doc.get(root).as_dict()?.name(b"Version").and_then(valid_version).map(str::to_owned)
|
||||
// Through a reference too, as the optimizer reads it.
|
||||
let version = doc.get(root).as_dict()?.get(b"Version")?.clone();
|
||||
doc.resolve(&version).as_name().and_then(valid_version).map(str::to_owned)
|
||||
})
|
||||
.flatten();
|
||||
let header_version = bytes.strip_prefix(b"%PDF-").and_then(|b| b.get(..3)).and_then(valid_version);
|
||||
@@ -416,6 +451,28 @@ impl Automation {
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Pages whose own backdrop hides a background (see `pdfcraft_edit::backdrop`).
|
||||
pub(crate) fn backdrops(&mut self, a: &Args) -> Result<Value> {
|
||||
let n = self.doc(a)?.info.pages.len();
|
||||
let pages = match a.opt_ints("pages")? {
|
||||
Some(_) => self.pages(a, "pages")?,
|
||||
None => (0..n).collect(),
|
||||
};
|
||||
let doc = self.doc(a)?;
|
||||
let found: Vec<Value> = pages
|
||||
.iter()
|
||||
.zip(doc.page_backdrops(&pages))
|
||||
.filter_map(|(p, found)| {
|
||||
let kind = match found? {
|
||||
pdfcraft_engine::Backdrop::Fill => "fill",
|
||||
pdfcraft_engine::Backdrop::Image => "image",
|
||||
};
|
||||
Some(json!({ "page": p + 1, "backdrop": kind }))
|
||||
})
|
||||
.collect();
|
||||
Ok(json!({ "pages": found }))
|
||||
}
|
||||
|
||||
pub(crate) fn marks(&mut self, tool: &str, a: &Args) -> Result<Value> {
|
||||
use pdfcraft_engine::{Background, HeaderFooter, MarkKind, Watermark};
|
||||
let n = self.doc(a)?.info.pages.len();
|
||||
@@ -483,6 +540,7 @@ impl Automation {
|
||||
color: color("color", [1.0; 3])?,
|
||||
opacity: a.opt_num("opacity")?.unwrap_or(1.0),
|
||||
scale: a.opt_num("scale")?.unwrap_or(1.0).clamp(0.01, 1.0),
|
||||
replace_backdrop: a.opt_bool("replace_backdrop")?.unwrap_or(true),
|
||||
..Background::default()
|
||||
},
|
||||
replace,
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//! Form tools: list fields, fill them (several at once, one undo step), clear the form, and
|
||||
//! prepare a form (add fields one at a time or as a table, change and delete them).
|
||||
|
||||
use pdfcraft_engine::form_scripts::{CalcOp, Calculate, Format, Validate};
|
||||
use pdfcraft_engine::form_scripts::{CalcOp, Calculate, Format, NOTATION_NOT_STORABLE, Validate, notation_storable};
|
||||
use pdfcraft_engine::{CalculationIssue, Edit, FieldProps, FieldValue, FormField, FormFieldKind, NewField, field_flags};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
@@ -94,13 +94,20 @@ fn look_arg(v: &Value) -> Result<pdfcraft_engine::FieldLookPatch> {
|
||||
})
|
||||
}
|
||||
|
||||
/// `{"min": 0, "max": 100}` or `"none"`.
|
||||
/// `{"min": 0, "max": 100}` or `"none"`. A null bound is no bound, as `form_fields` shows it.
|
||||
fn validate_arg(v: &Value) -> Result<Validate> {
|
||||
if v.as_str() == Some("none") {
|
||||
return Ok(Validate::None);
|
||||
}
|
||||
let o = v.as_object().ok_or_else(|| bad("validate must be {\"min\": …, \"max\": …} or \"none\""))?;
|
||||
let (min, max) = (o.get("min").and_then(Value::as_f64), o.get("max").and_then(Value::as_f64));
|
||||
if let Some(k) = o.keys().find(|k| !matches!(k.as_str(), "min" | "max")) {
|
||||
return Err(bad(format!("unknown key {k:?} in validate (min, max)")));
|
||||
}
|
||||
let bound = |k: &str| match o.get(k) {
|
||||
None | Some(Value::Null) => Ok(None),
|
||||
Some(x) => x.as_f64().map(Some).ok_or_else(|| bad(format!("validate {k} must be a number"))),
|
||||
};
|
||||
let (min, max) = (bound("min")?, bound("max")?);
|
||||
if min.is_none() && max.is_none() {
|
||||
return Err(bad("validate needs min, max or both"));
|
||||
}
|
||||
@@ -113,25 +120,67 @@ fn calculate_arg(v: &Value) -> Result<Calculate> {
|
||||
return Ok(Calculate::None);
|
||||
}
|
||||
let o = v.as_object().ok_or_else(|| bad("calculate must be {\"op\": …, \"fields\": […]}, {\"notation\": …} or \"none\""))?;
|
||||
if let Some(n) = o.get("notation").and_then(Value::as_str) {
|
||||
// Before anything else is read, so a script given beside a notation isn't dropped unnoticed.
|
||||
if o.contains_key("script") {
|
||||
return Err(bad("a custom calculate script is set with form_set_script (event: calculate)"));
|
||||
}
|
||||
if let Some(k) = o.keys().find(|k| !matches!(k.as_str(), "op" | "fields" | "notation")) {
|
||||
return Err(bad(format!("unknown key {k:?} in calculate (op and fields, or notation)")));
|
||||
}
|
||||
// A null is no value, as for the tool's own arguments.
|
||||
let get = |k: &str| o.get(k).filter(|v| !v.is_null());
|
||||
if let Some(n) = get("notation") {
|
||||
if get("op").is_some() || get("fields").is_some() {
|
||||
return Err(bad("calculate takes a notation, or op and fields, not both"));
|
||||
}
|
||||
let n = n.as_str().ok_or_else(|| bad("notation must be a string such as \"Price * Qty\""))?;
|
||||
// Refused rather than stored as a different formula.
|
||||
if !notation_storable(n) {
|
||||
return Err(bad(NOTATION_NOT_STORABLE));
|
||||
}
|
||||
return Ok(Calculate::Notation(n.to_string()));
|
||||
}
|
||||
let op = match o.get("op").and_then(Value::as_str).unwrap_or("") {
|
||||
"sum" => CalcOp::Sum,
|
||||
"product" => CalcOp::Product,
|
||||
"average" => CalcOp::Average,
|
||||
"min" | "minimum" => CalcOp::Minimum,
|
||||
"max" | "maximum" => CalcOp::Maximum,
|
||||
x => return Err(bad(format!("unknown op {x:?} (sum, product, average, min, max)"))),
|
||||
let op = get("op").ok_or_else(|| bad("calculate needs op and fields, or a notation"))?;
|
||||
let op = match op.as_str().ok_or_else(|| bad("op must be one of sum, product, average, min, max"))? {
|
||||
"minimum" => CalcOp::Minimum,
|
||||
"maximum" => CalcOp::Maximum,
|
||||
x => {
|
||||
CalcOp::ALL.into_iter().find(|&op| op_name(op) == x).ok_or_else(|| bad(format!("unknown op {x:?} (sum, product, average, min, max)")))?
|
||||
}
|
||||
};
|
||||
let fields: Vec<String> =
|
||||
o.get("fields").and_then(Value::as_array).map(|a| a.iter().filter_map(|x| x.as_str().map(str::to_owned)).collect()).unwrap_or_default();
|
||||
let fields = get("fields").and_then(Value::as_array).ok_or_else(|| bad("calculate fields must be a list of field names"))?;
|
||||
let fields: Vec<String> = fields
|
||||
.iter()
|
||||
.map(|x| x.as_str().map(str::to_owned).ok_or_else(|| bad("calculate fields must be field names (strings)")))
|
||||
.collect::<Result<_>>()?;
|
||||
if fields.is_empty() {
|
||||
return Err(bad("calculate needs fields"));
|
||||
}
|
||||
Ok(Calculate::Simple { op, fields })
|
||||
}
|
||||
|
||||
/// An operation's name in `calculate`, as `form_set_props` takes it and the listings show it.
|
||||
fn op_name(op: CalcOp) -> &'static str {
|
||||
match op {
|
||||
CalcOp::Sum => "sum",
|
||||
CalcOp::Product => "product",
|
||||
CalcOp::Average => "average",
|
||||
CalcOp::Minimum => "min",
|
||||
CalcOp::Maximum => "max",
|
||||
}
|
||||
}
|
||||
|
||||
/// A field's calculation as `form_fields` and `form_calculation_order` show it, in
|
||||
/// `form_set_props`'s shape, or `{"script": …}` for a custom Calculate script; `None` without one.
|
||||
fn calculate_json(f: &FormField) -> Option<Value> {
|
||||
match (&f.actions.calculate, &f.actions.scripts.calculate) {
|
||||
(Calculate::Simple { op, fields }, _) => Some(json!({ "op": op_name(*op), "fields": fields })),
|
||||
(Calculate::Notation(n), _) => Some(json!({ "notation": n })),
|
||||
(Calculate::None, Some(js)) => Some(json!({ "script": js })),
|
||||
(Calculate::None, None) => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn format_json(f: &Format) -> Value {
|
||||
match f {
|
||||
Format::None => Value::Null,
|
||||
@@ -220,18 +269,15 @@ impl Automation {
|
||||
if let Validate::Range { min, max } = &f.actions.validate {
|
||||
o.insert("validate".into(), json!({ "min": min, "max": max }));
|
||||
}
|
||||
match &f.actions.calculate {
|
||||
Calculate::Simple { op, fields } => {
|
||||
o.insert("calculate".into(), json!({ "op": op.code().to_lowercase(), "fields": fields }));
|
||||
}
|
||||
Calculate::Notation(n) => {
|
||||
o.insert("calculate".into(), json!({ "notation": n }));
|
||||
}
|
||||
Calculate::None => {}
|
||||
if let Some(c) = calculate_json(f) {
|
||||
o.insert("calculate".into(), c);
|
||||
}
|
||||
if !f.actions.unsupported.is_empty() {
|
||||
o.insert("unsupported_scripts".into(), json!(f.actions.unsupported));
|
||||
}
|
||||
if matches!(f.kind, FormFieldKind::CheckBox | FormFieldKind::Radio) {
|
||||
o.insert("export_values".into(), json!((0..f.widgets.len()).map(|i| f.export_of(i)).collect::<Vec<_>>()));
|
||||
}
|
||||
match f.kind {
|
||||
FormFieldKind::PushButton => {
|
||||
o.insert("caption".into(), json!(w.and_then(|w| w.caption.as_deref()).unwrap_or_default()));
|
||||
@@ -418,8 +464,8 @@ impl Automation {
|
||||
}
|
||||
|
||||
pub(crate) fn form_set_props(&mut self, a: &Args) -> Result<Value> {
|
||||
if a.get("widget").is_some() && a.get("caption").is_none() {
|
||||
return Err(bad("widget requires caption"));
|
||||
if a.get("widget").is_some() && a.get("caption").is_none() && a.get("export_value").is_none() {
|
||||
return Err(bad("widget requires caption or export_value"));
|
||||
}
|
||||
let single = a.opt_str("field")?;
|
||||
let bulk = a.get("fields").is_some();
|
||||
@@ -438,7 +484,7 @@ impl Automation {
|
||||
return Err(bad(format!("field {name:?} is listed more than once")));
|
||||
}
|
||||
}
|
||||
for key in ["name", "rect", "rotation", "caption", "widget"] {
|
||||
for key in ["name", "rect", "rotation", "caption", "export_value", "widget"] {
|
||||
if a.get(key).is_some() {
|
||||
return Err(bad(format!("{key} applies to one field; use field instead of fields")));
|
||||
}
|
||||
@@ -502,6 +548,15 @@ impl Automation {
|
||||
};
|
||||
Ok(FieldProps {
|
||||
rect,
|
||||
export_value: a
|
||||
.opt_str("export_value")?
|
||||
.map(|value| -> Result<_> {
|
||||
let index = a.opt_int("widget")?.unwrap_or(1);
|
||||
let index =
|
||||
usize::try_from(index).ok().and_then(|n| n.checked_sub(1)).ok_or_else(|| bad("widget must be a positive 1-based index"))?;
|
||||
Ok((index, value.to_owned()))
|
||||
})
|
||||
.transpose()?,
|
||||
name: a.opt_str("name")?.map(str::to_owned),
|
||||
tooltip: a.opt_str("tooltip")?.map(str::to_owned),
|
||||
caption: a
|
||||
@@ -600,17 +655,23 @@ impl Automation {
|
||||
};
|
||||
let mut out = self.apply(a, Edit::MoveInTabOrder { name: field.to_owned(), earlier })?;
|
||||
out["tab_order"] = self.tab_sequence(a)?;
|
||||
out["page_tabs"] = self.page_tabs(a)?;
|
||||
return Ok(out);
|
||||
}
|
||||
let order = match a.str("order")? {
|
||||
"row" | "rows" => pdfcraft_engine::TabOrder::Row,
|
||||
"column" | "columns" => pdfcraft_engine::TabOrder::Column,
|
||||
"structure" => pdfcraft_engine::TabOrder::Structure,
|
||||
"annotations" | "unspecified" => pdfcraft_engine::TabOrder::Annotations,
|
||||
o => return Err(bad(format!("unknown order {o:?} (row, column, structure, annotations)"))),
|
||||
let order = match a.opt_str("order")? {
|
||||
None => None,
|
||||
Some("row" | "rows") => Some(pdfcraft_engine::TabOrder::Row),
|
||||
Some("column" | "columns") => Some(pdfcraft_engine::TabOrder::Column),
|
||||
Some("structure") => Some(pdfcraft_engine::TabOrder::Structure),
|
||||
Some("annotations" | "unspecified") => Some(pdfcraft_engine::TabOrder::Annotations),
|
||||
Some(o) => return Err(bad(format!("unknown order {o:?} (row, column, structure, annotations)"))),
|
||||
};
|
||||
let mut out = match order {
|
||||
Some(order) => self.apply(a, Edit::SetTabOrder { pages, order })?,
|
||||
None => json!({}),
|
||||
};
|
||||
let mut out = self.apply(a, Edit::SetTabOrder { pages, order })?;
|
||||
out["tab_order"] = self.tab_sequence(a)?;
|
||||
out["page_tabs"] = self.page_tabs(a)?;
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
@@ -647,15 +708,28 @@ impl Automation {
|
||||
};
|
||||
let order = self.doc(a)?.calculation_order();
|
||||
let issue = |i: &CalculationIssue| match i {
|
||||
CalculationIssue::MissingField { field } => json!({ "issue": "missing_field", "field": field }),
|
||||
CalculationIssue::RunsTooEarly { field } => json!({ "issue": "runs_too_early", "field": field }),
|
||||
CalculationIssue::Cycle { fields } => json!({ "issue": "cycle", "fields": fields }),
|
||||
CalculationIssue::NotInOrder => json!({ "issue": "not_in_order" }),
|
||||
CalculationIssue::BuiltNames => json!({ "issue": "built_names" }),
|
||||
};
|
||||
// By field object, not name: two calculated fields can share a name in a malformed form.
|
||||
let doc = self.doc(a)?;
|
||||
let by_obj: std::collections::HashMap<_, &FormField> = doc.form.iter().map(|f| (f.obj, f)).collect();
|
||||
out["calculation_order"] = json!(order.fields.iter().map(|f| f.name.as_str()).collect::<Vec<_>>());
|
||||
out["fields"] = order
|
||||
.fields
|
||||
.iter()
|
||||
.map(|f| json!({ "name": f.name, "reads": f.reads, "listed": f.listed, "issues": f.issues.iter().map(issue).collect::<Vec<_>>() }))
|
||||
.map(|f| {
|
||||
json!({
|
||||
"name": f.name,
|
||||
"formula": by_obj.get(&f.obj).and_then(|x| calculate_json(x)),
|
||||
"reads": f.reads,
|
||||
"listed": f.listed,
|
||||
"issues": f.issues.iter().map(issue).collect::<Vec<_>>(),
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
out["extra"] = json!(order.extra);
|
||||
out["fixable"] = json!(order.fixable());
|
||||
@@ -671,12 +745,35 @@ impl Automation {
|
||||
Ok(json!(seq.iter().map(|x| x.1).collect::<Vec<_>>()))
|
||||
}
|
||||
|
||||
/// Each page's tab order (Page properties ▸ Tab order), in page order.
|
||||
fn page_tabs(&self, a: &Args) -> Result<Value> {
|
||||
let names: Vec<&str> = self
|
||||
.doc(a)?
|
||||
.tab_orders()
|
||||
.into_iter()
|
||||
.map(|o| match o {
|
||||
pdfcraft_engine::TabOrder::Row => "row",
|
||||
pdfcraft_engine::TabOrder::Column => "column",
|
||||
pdfcraft_engine::TabOrder::Structure => "structure",
|
||||
pdfcraft_engine::TabOrder::Annotations => "annotations",
|
||||
})
|
||||
.collect();
|
||||
Ok(json!(names))
|
||||
}
|
||||
|
||||
pub(crate) fn form_delete_field(&mut self, a: &Args) -> Result<Value> {
|
||||
let name = a.str("field")?.to_owned();
|
||||
if !self.doc(a)?.form.iter().any(|f| f.name == name) {
|
||||
return Err(failed(format!("there is no field named {name:?} (see form_fields)")));
|
||||
}
|
||||
self.apply(a, Edit::DeleteField { name })
|
||||
let Some(widget) = a.opt_int("widget")? else { return self.apply(a, Edit::DeleteField { name }) };
|
||||
let count = self.doc(a)?.form.iter().find(|f| f.name == name).map_or(0, |f| f.widgets.len());
|
||||
let widget = usize::try_from(widget)
|
||||
.ok()
|
||||
.and_then(|w| w.checked_sub(1))
|
||||
.filter(|w| *w < count)
|
||||
.ok_or_else(|| bad(format!("widget must be 1 to {count}: {name} has {count} widgets")))?;
|
||||
self.apply(a, Edit::DeleteWidget { name, widget })
|
||||
}
|
||||
|
||||
pub(crate) fn doc_export_data(&mut self, a: &Args) -> Result<Value> {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use super::error::{Result, ToolError};
|
||||
use super::*;
|
||||
use super::{Document, Value, comments, json};
|
||||
|
||||
/// How far from the page's corner a bookmark's position may be given, in points (a PDF page is at
|
||||
/// most 14 400 across).
|
||||
@@ -7,6 +7,36 @@ const MAX_BOOKMARK_POSITION: f64 = 1_000_000.0;
|
||||
|
||||
// ---- JSON helpers ----------------------------------------------------------------------------
|
||||
|
||||
/// The most bookmark levels `bookmark_from_text_styles` takes.
|
||||
const MAX_STYLE_LEVELS: usize = 9;
|
||||
|
||||
/// bookmark_from_text_styles' `levels`: one style per bookmark level, the first level 1, each
|
||||
/// `{ font, size, bold, italic }` as text_styles lists them.
|
||||
pub(crate) fn text_style_levels(a: &Args) -> Result<Vec<pdfcraft_engine::text_style_bookmarks::TextStyle>> {
|
||||
let levels =
|
||||
a.get("levels").and_then(Value::as_array).ok_or_else(|| ToolError::InvalidArgs("levels must list a style for each bookmark level".into()))?;
|
||||
if levels.is_empty() || levels.len() > MAX_STYLE_LEVELS {
|
||||
return Err(ToolError::InvalidArgs(format!("levels must list 1 to {MAX_STYLE_LEVELS} styles")));
|
||||
}
|
||||
levels
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, v)| {
|
||||
let bad = |what: &str| ToolError::InvalidArgs(format!("levels[{i}]: {what}"));
|
||||
let font =
|
||||
v.get("font").and_then(Value::as_str).filter(|f| !f.is_empty()).ok_or_else(|| bad("font must be a font name from text_styles"))?;
|
||||
let size =
|
||||
v.get("size").and_then(Value::as_f64).filter(|s| s.is_finite() && *s > 0.0).ok_or_else(|| bad("size must be a positive number"))?;
|
||||
let flag = |key: &str| match v.get(key) {
|
||||
None | Some(Value::Null) => Ok(false),
|
||||
Some(Value::Bool(b)) => Ok(*b),
|
||||
Some(_) => Err(bad(&format!("{key} must be true or false"))),
|
||||
};
|
||||
Ok(pdfcraft_engine::text_style_bookmarks::TextStyle { font: font.to_string(), size, bold: flag("bold")?, italic: flag("italic")? })
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub(crate) fn parse_style_ranges(value: Option<&Value>) -> Result<Vec<pdfcraft_engine::RangeStyle>> {
|
||||
let Some(value) = value else { return Ok(Vec::new()) };
|
||||
let values = value.as_array().filter(|v| v.len() <= 1024).ok_or_else(|| Args::wrong("ranges", "an array of at most 1024 style objects"))?;
|
||||
|
||||
@@ -62,7 +62,7 @@ use error::{Result, failed};
|
||||
pub(crate) use json::destination;
|
||||
pub use json::view_rect;
|
||||
use json::{Args, info, summary};
|
||||
use pages::{DEFAULT_DPI, MAX_DPI, encode_png};
|
||||
use pages::{DEFAULT_DPI, MAX_DPI, encode_png, rendered_content};
|
||||
#[cfg(test)]
|
||||
use pages::{FIND_FIRST_BATCH, FIND_MAX_WARNING_BYTES, FIND_MAX_WARNINGS, extract_parallel};
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use super::dispatch::Content;
|
||||
use super::error::{Result, ToolError, failed};
|
||||
use super::json::{Args, one_based};
|
||||
use super::*;
|
||||
use super::{Arc, Automation, DocId, HashMap, PageRenderer, PageText, RenderConfig, RenderRequest, RequestKind, Value, commands, json, tools};
|
||||
|
||||
/// Default and maximum resolution for `page_render`.
|
||||
pub(crate) const DEFAULT_DPI: f64 = 96.0;
|
||||
@@ -65,7 +65,9 @@ impl Automation {
|
||||
Ok(&mut entry.1)
|
||||
}
|
||||
|
||||
pub(crate) fn page_render(&mut self, a: &Args) -> Result<Content> {
|
||||
/// The page as a PNG, followed by a JSON part listing the render warnings when there are any,
|
||||
/// so a caller can tell that the picture is incomplete, as `pdfcraft-cli render` does (#4340).
|
||||
pub(crate) fn page_render(&mut self, a: &Args) -> Result<Vec<Content>> {
|
||||
let id = self.doc(a)?.id;
|
||||
let page = self.page(a)?;
|
||||
let dpi = a.opt_num("dpi")?.unwrap_or(DEFAULT_DPI);
|
||||
@@ -98,8 +100,7 @@ impl Automation {
|
||||
if let Some(e) = out.error {
|
||||
return Err(failed(format!("page {} could not be rendered: {e}", page + 1)));
|
||||
}
|
||||
let data = encode_png(out.width, out.height, &out.rgba)?;
|
||||
Ok(Content::Png { data, width: out.width, height: out.height })
|
||||
rendered_content(&out, page)
|
||||
}
|
||||
|
||||
/// A page as RGBA pixels, without encoding a PNG. `page` is 1-based and `scale` is pixels
|
||||
@@ -324,6 +325,29 @@ pub(crate) fn encode_png(width: u32, height: u32, premultiplied: &[u8]) -> Resul
|
||||
pdfcraft_engine::export::encode_png(width, height, premultiplied).map_err(failed)
|
||||
}
|
||||
|
||||
/// The output of a page-rendering tool: the PNG of the 0-based `page`, followed by a JSON part
|
||||
/// listing its render warnings when there are any. Without warnings it is the PNG alone, as it
|
||||
/// always was.
|
||||
pub(crate) fn rendered_content(out: &pdfcraft_render::RenderedPage, page: usize) -> Result<Vec<Content>> {
|
||||
let data = encode_png(out.width, out.height, &out.rgba)?;
|
||||
let mut content = vec![Content::Png { data, width: out.width, height: out.height }];
|
||||
if !out.warnings.is_empty() {
|
||||
// Sentences, like the other tools' `warnings`, so command_run can add its own to the list.
|
||||
let warnings: Vec<&str> = out.warnings.iter().map(|&w| render_warning_text(w)).collect();
|
||||
content.push(Content::Json(json!({ "page": page.saturating_add(1), "warnings": warnings })));
|
||||
}
|
||||
Ok(content)
|
||||
}
|
||||
|
||||
/// What a render warning means, in the words `pdfcraft-cli render` prints for it.
|
||||
fn render_warning_text(warning: pdfcraft_render::RenderWarning) -> &'static str {
|
||||
use pdfcraft_render::RenderWarning;
|
||||
match warning {
|
||||
RenderWarning::ContentTruncated => "content past the page's safety budget was skipped",
|
||||
RenderWarning::ColourFallback => "a colour that could not be computed was painted in a fallback colour",
|
||||
}
|
||||
}
|
||||
|
||||
/// Extract the text of `pages` (0-based) with one renderer per worker thread.
|
||||
pub(crate) fn extract_parallel(bytes: &Arc<Vec<u8>>, password: Option<Arc<str>>, pages: &[usize]) -> PageTexts {
|
||||
let extract = |r: &mut PageRenderer, p: usize| {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use super::error::{Result, failed};
|
||||
use super::*;
|
||||
use super::{Automation, Path, PathBuf, StagingName, file_access, foreign_share, staging_suffixes};
|
||||
|
||||
impl Automation {
|
||||
// ---- paths -------------------------------------------------------------------------------
|
||||
|
||||
@@ -121,7 +121,7 @@ pub fn tools() -> Vec<ToolDef> {
|
||||
let save_out = json!({ "type": "string", "description": "File to write. Omit to open the result as a new unsaved document instead." });
|
||||
let open = json!({ "type": "boolean", "description": "Also open the result as a new document (default: only when out is omitted)." });
|
||||
vec![
|
||||
t("doc_batch", "Process files and folders", "Run convert, ocr and/or optimize over files and folders, one file at a time. recursive defaults to false. Preserve paths relative to each selected folder inside out_dir; duplicate inputs run once. Skip unsupported files, links and the output subtree. Existing outputs receive numbered names and are never replaced. Continue after per-file errors unless stop_on_error is true. Return completed/failed/skipped counts and per-file results. Discovery is bounded to 10000 entries and 64 folder levels. Convert must be first; each step can appear once. OCR uses installed models. Optimize uses Reduce File Size settings, optionally overriding target ppi (threshold 1.5 times ppi) and JPEG quality; a larger candidate keeps the original bytes. Sources and open documents are unchanged.")
|
||||
t("doc_batch", "Process files and folders", "Run convert, ocr and/or optimize over files and folders, one file at a time. recursive defaults to false. Preserve paths relative to each selected folder inside out_dir; duplicate inputs run once. Skip unsupported files, links and the output subtree. Existing outputs receive numbered names and are never replaced. Continue after per-file errors unless stop_on_error is true. Return completed/failed/skipped counts and per-file results. Discovery is bounded to 10000 entries and 64 folder levels. Convert must be first; each step can appear once. OCR uses installed models. Optimize uses Reduce File Size settings, optionally overriding target ppi (threshold 1.5 times ppi; black-and-white images go to the larger of ppi and 300) and JPEG quality; a larger candidate keeps the original bytes. Sources and open documents are unchanged.")
|
||||
.with(schema(json!({
|
||||
"paths": {"type":"array","items":{"type":"string"},"minItems":1,"maxItems":1000},
|
||||
"out_dir": {"type":"string"},
|
||||
@@ -167,7 +167,7 @@ pub fn tools() -> Vec<ToolDef> {
|
||||
)),
|
||||
t("doc_set_info", "Set document metadata", "Set a document information entry such as Title, Author, Subject or Keywords, or a custom property under any other name (no spaces, delimiters, / or #; at most 127 bytes; doc_info lists them under custom); an empty value removes it. When the file has XMP metadata, the matching XMP property (dc:title, dc:creator, dc:description, pdf:Keywords, xmp:CreatorTool, pdf:Producer) is changed too, so viewers that read XMP first show the new value. Undoable.")
|
||||
.with(schema(json!({ "doc": doc(), "key": { "type": "string" }, "value": { "type": "string" } }), &["doc", "key", "value"])),
|
||||
t("page_render", "Render a page", "Render one page to a PNG image (default 96 dpi, at most 600).")
|
||||
t("page_render", "Render a page", "Render one page to a PNG image (default 96 dpi, at most 600). When the picture is incomplete or approximate (content cut at the page's safety budget, a colour painted in a fallback colour), a JSON part follows the image: { page, warnings: [sentence, ...] }.")
|
||||
.ro()
|
||||
.with(schema(json!({ "doc": doc(), "page": { "type": "integer", "minimum": 1 }, "dpi": { "type": "number", "minimum": 1, "maximum": 600 },
|
||||
"hide_text_block": { "type": "integer", "minimum": 1, "description": "Render an inline editor background without this paragraph (number from text_paragraphs, resolved as text_edit does: refused once an edit merged that paragraph into a neighbour). Does not modify the document." },
|
||||
@@ -347,6 +347,39 @@ pub fn tools() -> Vec<ToolDef> {
|
||||
"Make bookmarks from the document's tagged headings (H, H1-H6), nested by level under a new first bookmark titled \"Untitled\". Fails if the document has no tagged headings. Returns the first page of the bookmark tree (see bookmark_list). Undoable.",
|
||||
)
|
||||
.with(schema(json!({ "doc": doc() }), &["doc"])),
|
||||
t(
|
||||
"text_styles",
|
||||
"List text styles",
|
||||
"The styles the document's text is set in, the largest first: font (without its subset tag), the size it is shown at in points, bold, italic, how many lines and pages use it, and the first line in it as a sample. For choosing the styles bookmark_from_text_styles makes bookmarks from (headings are usually the larger, rarer styles). Reads the first 5000 pages.",
|
||||
)
|
||||
.ro()
|
||||
.with(schema(json!({ "doc": doc() }), &["doc"])),
|
||||
t(
|
||||
"bookmark_from_text_styles",
|
||||
"New bookmarks from text styles",
|
||||
"Make bookmarks from the lines set in chosen text styles, for documents whose headings are not tagged: levels lists one style per bookmark level ({font, size, bold, italic} as text_styles gives them; sizes within a quarter point match), the first level 1, the next nested under the bookmark before it, and so on. A heading set on several lines is one bookmark, and each goes to the top of its heading. They go under a new first bookmark titled \"Untitled\". Fails if no text is set in the styles. Returns the first page of the bookmark tree (see bookmark_list). Undoable.",
|
||||
)
|
||||
.with(schema(
|
||||
json!({
|
||||
"doc": doc(),
|
||||
"levels": {
|
||||
"type": "array",
|
||||
"minItems": 1,
|
||||
"maxItems": 9,
|
||||
"items": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"font": { "type": "string", "minLength": 1 },
|
||||
"size": { "type": "number", "exclusiveMinimum": 0 },
|
||||
"bold": { "type": "boolean" },
|
||||
"italic": { "type": "boolean" }
|
||||
},
|
||||
"required": ["font", "size"]
|
||||
}
|
||||
}
|
||||
}),
|
||||
&["doc", "levels"],
|
||||
)),
|
||||
t("page_number", "Number pages", "Label a range of pages (e.g. i, ii, iii for front matter, or A-1, A-2 for an appendix). Later pages keep their labels. Undoable.").with(schema(
|
||||
json!({
|
||||
"doc": doc(),
|
||||
@@ -358,7 +391,7 @@ pub fn tools() -> Vec<ToolDef> {
|
||||
}),
|
||||
&["doc", "from", "to"],
|
||||
)),
|
||||
t("form_fields", "List form fields", "Every interactive form field: name, type (text, checkbox, radio, combo, list, button, signature), value, options, page, rect (top-left-origin points) and rotation (0, 90, 180 or 270 degrees counterclockwise), read-only and required flags. Push buttons include caption (first widget's normal label) and captions [{widget, caption}] for all widgets (1-based).")
|
||||
t("form_fields", "List form fields", "Every interactive form field: name, type (text, checkbox, radio, combo, list, button, signature), value, options, page, rect (top-left-origin points) and rotation (0, 90, 180 or 270 degrees counterclockwise), read-only and required flags. A calculated field includes calculate: {op, fields} or {notation} as form_set_props takes them, or {script} for a custom Calculate script (set with form_set_script). Push buttons include caption (first widget's normal label) and captions [{widget, caption}] for all widgets (1-based).")
|
||||
.ro()
|
||||
.with(schema(json!({ "doc": doc() }), &["doc"])),
|
||||
t(
|
||||
@@ -442,8 +475,9 @@ pub fn tools() -> Vec<ToolDef> {
|
||||
"fields": { "type": "array", "items": { "type": "string" }, "minItems": 1, "maxItems": 1000, "uniqueItems": true, "description": "Apply the same changes to these fields in one atomic edit. Use either field or fields." },
|
||||
"name": { "type": "string" },
|
||||
"tooltip": { "type": "string" },
|
||||
"export_value": { "type": "string", "description": "Checkbox/radio export value; preserves appearance states and selection. Requires a single field." },
|
||||
"caption": { "type": "string", "description": "Normal push-button label; an empty string clears it. Requires a single field." },
|
||||
"widget": { "type": "integer", "minimum": 1, "description": "Widget whose caption changes (1-based, default 1). Requires caption. See form_fields.captions." },
|
||||
"widget": { "type": "integer", "minimum": 1, "description": "Widget whose caption or export value changes (1-based, default 1). Requires caption or export_value. See form_fields.captions and export_values." },
|
||||
"read_only": { "type": "boolean" },
|
||||
"required": { "type": "boolean" },
|
||||
"multiline": { "type": "boolean" },
|
||||
@@ -459,17 +493,17 @@ pub fn tools() -> Vec<ToolDef> {
|
||||
"rotation": { "type": "integer", "enum": [0, 90, 180, 270], "description": "Widget rotation in degrees, counterclockwise. Changing between horizontal and vertical swaps the rectangle around its center." },
|
||||
"appearance": { "type": "object", "description": "Appearance tab: border, fill, text_color (#RRGGBB, a name or \"none\"), width (0–12 points; 1 thin, 2 medium, 3 thick), style (solid, dashed, beveled, inset, underline), font (helvetica, times, courier)." },
|
||||
"format": { "description": "Format tab: {\"type\": \"number\", \"decimals\": 2, \"currency\": \"$\", \"separator\": 0-4, \"negative\": 0-3}, {\"type\": \"percent\"}, {\"type\": \"date\"|\"time\", \"pattern\": \"mm/dd/yyyy\"}, {\"type\": \"zip\"|\"zip4\"|\"phone\"|\"ssn\"}, {\"type\": \"mask\", \"mask\": \"AA-9999\"}, or \"none\"." },
|
||||
"validate": { "description": "Validate tab: {\"min\": 0, \"max\": 100} (either may be left out) or \"none\"." },
|
||||
"validate": { "description": "Validate tab: {\"min\": 0, \"max\": 100} (either may be left out, or null) or \"none\"." },
|
||||
"calculate": { "description": "Calculate tab: {\"op\": \"sum\"|\"product\"|\"average\"|\"min\"|\"max\", \"fields\": [\"a\", \"b\"]}, {\"notation\": \"Price * Qty\"} (simplified field notation), or \"none\"." },
|
||||
}),
|
||||
&["doc"],
|
||||
)),
|
||||
t("form_tab_order", "Set the tab order", "Set the tab order of pages (default all): row (top to bottom, left to right), column, structure, or annotations (unspecified). Or order tabs manually: `field` with `move` earlier|later moves that field one place on its page. Returns the resulting order of fields. Undoable.")
|
||||
t("form_tab_order", "Set the tab order", "Set the tab order of pages (default all): row (top to bottom, left to right; right to left in a document bound on the right), column, structure, or annotations (unspecified). Or order tabs manually: `field` with `move` earlier|later moves that field one place on its page. Without `order` or `field` it only reads. Returns the resulting order of fields (`tab_order`) and each page's tab order (`page_tabs`, as Page properties ▸ Tab Order shows it). Undoable.")
|
||||
.with(schema(
|
||||
json!({ "doc": doc(), "order": { "type": "string", "enum": ["row", "column", "structure", "annotations"] }, "pages": pages("to set (default: all)"), "field": { "type": "string" }, "move": { "type": "string", "enum": ["earlier", "later"] } }),
|
||||
&["doc"],
|
||||
)),
|
||||
t("form_calculation_order", "Read or set the calculation order", "The calculated fields in the order they calculate (Acrobat: Set Field Calculation Order), each with the fields its formula reads (`reads`; a script's names built at run time aren't known) and its `issues`: runs_too_early (it reads `field`, which calculates after it, so it shows a stale value), cycle (it reads `fields`, which read it back: no order fixes that, a formula has to change) and not_in_order (the PDF's order leaves it out, so other viewers may not calculate it). `extra` lists entries of the PDF's order that calculate nothing. Without a change it only reads. Changes, one at a time: `order` (these fields first, in this order, then the other calculated fields in their order), `field` with `move` earlier|later (one place), or `fix` true (only what must move moves, so every field calculates after the fields it reads, and the extra entries go). A change recalculates the form. Undoable.")
|
||||
t("form_calculation_order", "Read or set the calculation order", "The calculated fields in the order they calculate (Acrobat: Set Field Calculation Order), each with its `formula` (as form_fields shows calculate), the fields it reads (`reads`; a script's names built at run time aren't known) and its `issues`: missing_field (it reads `field`, which the form doesn't have, so it gets no value there), runs_too_early (it reads `field`, which calculates after it, so it shows a stale value), cycle (it reads `fields`, which read it back: no order fixes that, a formula has to change) and not_in_order (the PDF's order leaves it out, so other viewers may not calculate it) and built_names (its script also reads fields by names it builds at run time, which aren't checked). `extra` lists entries of the PDF's order that calculate nothing. Without a change it only reads. Changes, one at a time: `order` (these fields first, in this order, then the other calculated fields in their order), `field` with `move` earlier|later (one place), or `fix` true (only what must move moves, so every field calculates after the fields it reads, and the extra entries go). A change recalculates the form. Undoable.")
|
||||
.cmd("form.calculation_order")
|
||||
.with(schema(
|
||||
json!({ "doc": doc(), "order": { "type": "array", "items": { "type": "string" } }, "field": { "type": "string" }, "move": { "type": "string", "enum": ["earlier", "later"] }, "fix": { "type": "boolean" } }),
|
||||
@@ -478,11 +512,11 @@ pub fn tools() -> Vec<ToolDef> {
|
||||
t("doc_export_data", "Export comments or form data", "Write comments and/or form data to path; the extension picks the format: .xfdf or .fdf (comments and/or fields), .xml, .csv or .txt (form data). For an XFA form, .xml is its data alone (rooted at the form's root data node, as Acrobat exports it) and .xdp an XML Data Package holding the whole datasets. what: all (default), comments, fields.")
|
||||
.destructive()
|
||||
.with(schema(json!({ "doc": doc(), "path": { "type": "string" }, "what": { "type": "string", "enum": ["all", "comments", "fields"] } }), &["doc", "path"])),
|
||||
t("doc_import_data", "Import comments or form data", "Import comments and/or field values from an XFDF, FDF, XML, CSV or tab-delimited text file (detected from its content). Comments with the same name are replaced; values go through the form's formats and validation. For an XFA form, an XDP, datasets or data XML file replaces the form's data: a laid-out form is laid out again from it (rows included) and its calculations run. Undoable.")
|
||||
t("doc_import_data", "Import comments or form data", "Import comments and/or field values from an XFDF, FDF, XML, CSV or tab-delimited text file (detected from its content), or the comments of another PDF, each onto the page with the same number (comments on pages past this document's last page are left out). Comments with the same name are replaced; values go through the form's formats and validation. For an XFA form, an XDP, datasets or data XML file replaces the form's data: a laid-out form is laid out again from it (rows included) and its calculations run. Undoable.")
|
||||
.with(schema(json!({ "doc": doc(), "path": { "type": "string" } }), &["doc", "path"])),
|
||||
t("form_delete_field", "Delete a field", "Delete a form field and all its widgets. Undoable.")
|
||||
t("form_delete_field", "Delete a field", "Delete a form field and all its widgets, or with widget only that one: one radio button of a group (widget n is the nth of the radio group's options in form_fields), or one copy of a duplicated field. A field's last widget takes the field with it. Undoable.")
|
||||
.destructive()
|
||||
.with(schema(json!({ "doc": doc(), "field": { "type": "string" } }), &["doc", "field"])),
|
||||
.with(schema(json!({ "doc": doc(), "field": { "type": "string" }, "widget": { "type": "integer", "minimum": 1, "description": "Delete only this widget (1-based)." } }), &["doc", "field"])),
|
||||
t(
|
||||
"redact_mark",
|
||||
"Mark for redaction",
|
||||
@@ -603,6 +637,7 @@ pub fn tools() -> Vec<ToolDef> {
|
||||
"font": { "type": "string", "enum": ["helvetica", "times", "courier"] }, "size": { "type": "number", "minimum": 1, "maximum": 500 },
|
||||
"bold": { "type": "boolean" }, "italic": { "type": "boolean" }, "color": { "type": "string" },
|
||||
"align": { "type": "string", "enum": ["left", "center", "right", "justify"] },
|
||||
"aligns": { "type": "array", "maxItems": 4096, "items": { "enum": ["left", "center", "right", "justify", null] }, "description": "Each paragraph's (line's) own alignment, by index; null follows align." },
|
||||
"char_spacing": { "type": "number", "minimum": -500, "maximum": 500, "description": "Points after each character." },
|
||||
}),
|
||||
&["doc", "page", "text"],
|
||||
@@ -625,6 +660,7 @@ pub fn tools() -> Vec<ToolDef> {
|
||||
"font": { "type": "string", "enum": ["helvetica", "times", "courier"] }, "size": { "type": "number", "minimum": 1, "maximum": 500 },
|
||||
"bold": { "type": "boolean" }, "italic": { "type": "boolean" }, "color": { "type": "string" },
|
||||
"align": { "type": "string", "enum": ["left", "center", "right", "justify"] },
|
||||
"aligns": { "type": "array", "maxItems": 4096, "items": { "enum": ["left", "center", "right", "justify", null] }, "description": "Each paragraph's (line's) own alignment, by index; null follows align." },
|
||||
"char_spacing": { "type": "number", "minimum": -500, "maximum": 500, "description": "Points after each character." },
|
||||
"rotate": { "type": "integer" }, "flip_h": { "type": "boolean" }, "flip_v": { "type": "boolean" },
|
||||
"crop": { "type": "array", "items": { "type": "number", "minimum": 0, "maximum": 0.95 }, "minItems": 4, "maxItems": 4, "description": "Fractions trimmed: left, bottom, right, top. Left and right together, and bottom and top together, trim at most 0.95." },
|
||||
@@ -886,7 +922,7 @@ pub fn tools() -> Vec<ToolDef> {
|
||||
)),
|
||||
t("comment_image_preview", "Preview image signature layers", "Return a PNG of the page without the selected image signature/initials (layer=background, default), or its embedded image with alpha (layer=image). Includes the displayed rectangle, document rotation, image_rotation (how far clockwise the image is shown turned) and annotation opacity. Cache these layers for live placement/resizing; commit once with comment_edit. Does not change the document or undo history.")
|
||||
.ro().with(schema(comment_ref(json!({ "layer": { "type": "string", "enum": ["background", "image"], "default": "background" }, "dpi": { "type": "number", "minimum": 1, "maximum": 600, "default": 96 } })), &["doc"])),
|
||||
t("comment_delete", "Delete a comment", "Delete a comment with its pop-up and replies. Undoable.").destructive().with(schema(comment_ref(json!({})), &["doc"])),
|
||||
t("comment_delete", "Delete a comment", "Delete a comment with its pop-up and replies, or one reply (its id, or page and index, from comment_list) with its pop-up and the replies to it; the comment and its other replies stay. Undoable.").destructive().with(schema(comment_ref(json!({})), &["doc"])),
|
||||
t(
|
||||
"doc_protect",
|
||||
"Protect with passwords",
|
||||
@@ -996,12 +1032,16 @@ pub fn tools() -> Vec<ToolDef> {
|
||||
}),
|
||||
&["doc"],
|
||||
)),
|
||||
t("doc_background", "Add background", "Fill page backgrounds with a colour, or a picture from `file` (an image, or page `file_page` of a PDF) fitted at `scale` (default 1), behind the content. Undoable.")
|
||||
t("doc_background", "Add background", "Fill page backgrounds with a colour, or a picture from `file` (an image, or page `file_page` of a PDF) fitted at `scale` (default 1), behind the content. A page that paints its own opaque white backdrop would hide it, so that backdrop is replaced unless replace_backdrop is false (removing the background turns it back on where that is still safe, and doc_remove_marks warns about the pages where it isn't); a scanned page's picture still hides it (doc_backdrops lists both). Undoable.")
|
||||
.cmd("edit.background")
|
||||
.with(schema(
|
||||
json!({ "doc": doc(), "pages": pages("to fill (default: all)"), "color": { "type": "string" }, "file": { "type": "string" }, "file_page": { "type": "integer", "minimum": 1 }, "scale": { "type": "number", "exclusiveMinimum": 0, "maximum": 1 }, "opacity": { "type": "number", "minimum": 0, "maximum": 1 }, "replace": { "type": "boolean" } }),
|
||||
json!({ "doc": doc(), "pages": pages("to fill (default: all)"), "color": { "type": "string" }, "file": { "type": "string" }, "file_page": { "type": "integer", "minimum": 1 }, "scale": { "type": "number", "exclusiveMinimum": 0, "maximum": 1 }, "opacity": { "type": "number", "minimum": 0, "maximum": 1 }, "replace": { "type": "boolean" }, "replace_backdrop": { "type": "boolean", "description": "Replace a white backdrop the page paints itself, which would hide the background. Default true." } }),
|
||||
&["doc"],
|
||||
)),
|
||||
t("doc_backdrops", "List page backdrops", "Pages that paint their own backdrop, which hides a background added behind the content: `fill` (an opaque white fill doc_background can replace) or `image` (a page-sized picture, e.g. a scan, that still hides it). Pages are 1-based; pages without one are left out.")
|
||||
.ro()
|
||||
.cmd("edit.background")
|
||||
.with(schema(json!({ "doc": doc(), "pages": pages("to check (default: all)") }), &["doc"])),
|
||||
t("doc_remove_marks", "Remove header & footer, watermark or background", "Remove every header and footer, watermark or background PdfCraft (or a compatible tool) added. Undoable.")
|
||||
.destructive()
|
||||
.with(schema(json!({ "doc": doc(), "kind": { "type": "string", "enum": ["header_footer", "watermark", "background"] } }), &["doc", "kind"])),
|
||||
@@ -1135,7 +1175,7 @@ pub fn tools() -> Vec<ToolDef> {
|
||||
t("form_merge_data", "Merge data files into spreadsheet", "Collect the field values of form data files (FDF, XFDF) or filled-in PDF forms into one CSV file at path: a column per field name, a row per file. Returns the row and column counts.")
|
||||
.cmd("form.merge_data")
|
||||
.with(schema(json!({ "paths": { "type": "array", "items": { "type": "string" }, "minItems": 1 }, "path": { "type": "string" } }), &["paths", "path"])),
|
||||
t("js_run", "Run JavaScript", "Run Acrobat JavaScript in the document, as the JavaScript console does (or as push button `field`'s Mouse Up script when field is given; on a laid-out XFA form, `field` runs that button's XFA click script instead, JavaScript or FormCalc, which can add and remove rows and show or hide subforms). The form object model is available: this/getField, event, app, util, console, display, color, and the document-level scripts (except the PDF container scripts when XFA layout is active; they remain available through js_document_scripts). Field changes and resetForm are applied as one undoable step; returns the script's alerts, console output, requests (print, page, url, submit), error, and the errors of document-level scripts that failed (the rest still ran).")
|
||||
t("js_run", "Run JavaScript", "Run Acrobat JavaScript in the document, as the JavaScript console does (or as push button `field`'s Mouse Up script when field is given; on a laid-out XFA form, `field` runs that button's XFA click script instead, JavaScript or FormCalc, which can add and remove rows and show or hide subforms). The form object model is available: this/getField, event, app, util, console, display, color, and the document-level scripts (except the PDF container scripts when XFA layout is active; they remain available through js_document_scripts). Field changes and resetForm are applied as one undoable step; returns the script's alerts (each with its message, title, icon and buttons, in order; every question is still answered OK), console output, requests (print, page, url, submit), error, and the errors of document-level scripts that failed (the rest still ran).")
|
||||
.cmd("tools.js_console")
|
||||
.with(schema(
|
||||
json!({ "doc": doc(), "script": { "type": "string" }, "field": { "type": "string", "description": "Run as this button's Mouse Up event." } }),
|
||||
@@ -1154,7 +1194,7 @@ pub fn tools() -> Vec<ToolDef> {
|
||||
json!({ "doc": doc(), "field": { "type": "string" }, "event": { "type": "string", "enum": ["keystroke", "format", "validate", "calculate", "mouse_up"] }, "script": { "type": "string" } }),
|
||||
&["doc", "field", "event"],
|
||||
)),
|
||||
t("doc_export_office", "Export to Word, PowerPoint, HTML or RTF", "Export a PDF ▸ Word (.docx), PowerPoint (.pptx, one slide per page), HTML (.html, one file with images inline) or RTF (.rtf), chosen by path's extension: text, headings, bold and italic. Word uses borderless inferred tables and positioned editable shapes on pages with artwork, rotated or large text; each source page retains its size. Font matching and vector graphics remain limited. Export reads forms 50 deep and up to 50 000 a page, counting forms the page draws itself. Pages that go past either limit are listed in truncated_pages, with a warning; the text and images of the forms left out are missing.")
|
||||
t("doc_export_office", "Export to Word, PowerPoint, HTML, RTF or Markdown", "Export a PDF ▸ Word (.docx), PowerPoint (.pptx, one slide per page), HTML (.html, one file with images inline), RTF (.rtf) or Markdown (.md or .markdown: pipe tables, images left out), chosen by path's extension: text, headings, bold and italic. Word uses borderless inferred tables and positioned editable shapes on pages with artwork, rotated or large text; each source page retains its size. Font matching and vector graphics remain limited. Export reads forms 50 deep and up to 50 000 a page, counting forms the page draws itself. Pages that go past either limit are listed in truncated_pages, with a warning; the text and images of the forms left out are missing.")
|
||||
.cmd("export.docx")
|
||||
.with(schema(json!({ "doc": doc(), "path": { "type": "string" } }), &["doc", "path"])),
|
||||
t("pdfa_verify", "Verify PDF/A", "Standards ▸ Verify PDF/A compliance: the PDF/A-2b or 3b rules the document breaks (ISO 19005 clause, message, page, whether Save as PDF/A can fix it), plus what it declares.")
|
||||
@@ -1241,7 +1281,7 @@ pub fn tools() -> Vec<ToolDef> {
|
||||
.ro()
|
||||
.cmd("ocr.recognize")
|
||||
.with(schema(json!({}), &[])),
|
||||
t("doc_export_all_images", "Export all images", "Write the images that pages use into a folder (`<name>_Page_<n>_Image_<k>.jpg|png`, n zero-padded to the page count's digits), each once: JPEG images unchanged, others as PNG with their soft mask as alpha. min_size skips images with fewer pixels on their shorter side. Images that can't be decoded yet (JPEG 2000, JBIG2, CCITT, separations) are listed under skipped. Includes unsaved edits.")
|
||||
t("doc_export_all_images", "Export all images", "Write the images that pages use into a folder (`<name>_Page_<n>_Image_<k>.jpg|png`, n zero-padded to the page count's digits), each once: JPEG images unchanged, others as PNG with their soft mask as alpha. min_size skips images with fewer pixels on their shorter side. Images that can't be decoded yet (JPEG 2000, JBIG2 inside other filters, separations) are listed under skipped. Includes unsaved edits.")
|
||||
.cmd("export.all_images")
|
||||
.with(schema(
|
||||
json!({
|
||||
@@ -1258,7 +1298,7 @@ pub fn tools() -> Vec<ToolDef> {
|
||||
t(
|
||||
"fill_sign_add",
|
||||
"Fill & Sign: type text or place a mark",
|
||||
"Fill in a form that has no fields, as Acrobat's Fill & Sign does: type text (`text`, default 10 pt; `font_size` 4–300 pt), place a check, cross, dot or line, today's date (in Preferences ▸ Date format, see fill_sign_date_format, or `format`; `font_size` also applies), or a signature or initials (either `text` drawn in a script font, or `path` to a local PNG/JPEG image up to 4 MiB and 32 megapixels, scaled down to 4 megapixels, preserving transparency; with `scan: true`, `path` is instead a photo of a signature on paper, within the same limits: the signature is found, and the paper, shadows and table around it are removed, with `sensitivity` 0–100, default 50, picking up fainter ink when higher). `at` [x, y] is in points from the top-left of the page: text's top-left, mark's centre, signature's left edge centred vertically. Image signatures fit within 150 pt wide and 32 pt tall (24 pt for initials). Creates movable, undoable annotations. Typed text the standard fonts can't draw is saved and drawn as `?` (`warnings` in the result says so); a typed signature neither the script font nor its fallback can draw is refused (pass `path` instead).",
|
||||
"Fill in a form that has no fields, as Acrobat's Fill & Sign does: type text (`text`, default 10 pt; `font_size` 4–300 pt; optional `color` as #RRGGBB for text/date, default black), place a check, cross, dot or line, today's date (in Preferences ▸ Date format, see fill_sign_date_format, or `format`; `font_size` also applies), or a signature or initials (either `text` drawn in a script font, or `path` to a local PNG/JPEG image up to 4 MiB and 32 megapixels, scaled down to 4 megapixels, preserving transparency; with `scan: true`, `path` is instead a photo of a signature on paper, within the same limits: the signature is found, and the paper, shadows and table around it are removed, with `sensitivity` 0–100, default 50, picking up fainter ink when higher). `at` [x, y] is in points from the top-left of the page: text's top-left, mark's centre, signature's left edge centred vertically. Image signatures fit within 150 pt wide and 32 pt tall (24 pt for initials). Creates movable, undoable annotations. Typed text the standard fonts can't draw is saved and drawn as `?` (`warnings` in the result says so); a typed signature neither the script font nor its fallback can draw is refused (pass `path` instead).",
|
||||
)
|
||||
.cmd("sign.fill.text")
|
||||
.with(schema(
|
||||
@@ -1269,6 +1309,7 @@ pub fn tools() -> Vec<ToolDef> {
|
||||
"at": point(),
|
||||
"text": { "type": "string", "minLength": 1 },
|
||||
"font_size": { "type": "number", "minimum": 4, "maximum": 300, "description": "For type text or date (default 10 pt)." },
|
||||
"color": color(),
|
||||
"path": { "type": "string", "description": "PNG or JPEG for signature/initials; pass either path or text." },
|
||||
"scan": { "type": "boolean", "description": "With path: scan a photo of a signature on paper (default false)." },
|
||||
"sensitivity": { "type": "integer", "minimum": 0, "maximum": 100, "description": "With scan: how faint ink may be, 0–100 (default 50)." },
|
||||
@@ -1299,7 +1340,7 @@ pub fn tools() -> Vec<ToolDef> {
|
||||
}),
|
||||
&["from"],
|
||||
)),
|
||||
t("doc_reduce", "Reduce file size", "Write a smaller copy of the document to `path` with Acrobat's Reduce File Size choices: images above 225 ppi downsampled to 150 ppi and JPEG-compressed (medium quality), thumbnails dropped, identical fonts and images merged, unused objects dropped, compressed object streams. If the copy wouldn't be smaller, nothing is written and `written` is false. The open document is unchanged.")
|
||||
t("doc_reduce", "Reduce file size", "Write a smaller copy of the document to `path` with Acrobat's Reduce File Size choices: colour and grey images above 225 ppi downsampled to 150 ppi and JPEG-compressed (medium quality), black-and-white images averaged down to 300 ppi above 450 ppi and each stored as CCITT Group 4 (or 1-bit Flate, once resampled or packed from more bits) whenever that is smaller, thumbnails dropped, identical fonts and images merged, unused objects dropped, compressed object streams. If the copy wouldn't be smaller, nothing is written and `written` is false. The open document is unchanged.")
|
||||
.cmd("optimize.reduce")
|
||||
.with(schema(json!({ "doc": doc(), "path": { "type": "string" } }), &["doc", "path"])),
|
||||
t("doc_initial_view", "Initial view", "Read or change how the document opens (Document Properties ▸ Initial View) and its reading options: navigation (page, bookmarks, pages, attachments, layers), layout (default, single, continuous, two_up, two_up_continuous, two_up_cover, two_up_continuous_cover), magnification (default, actual, fit_page, fit_width, fit_height, fit_visible, or a percentage), page, window options (fit_window, center_window, full_screen, display_title), interface options (hide_menubar, hide_toolbar, hide_window_ui), language and binding (left, right). Only the given ones change; returns the result. Undoable.").with(schema(
|
||||
@@ -1387,6 +1428,7 @@ pub fn tools() -> Vec<ToolDef> {
|
||||
"size": { "type": "number", "exclusiveMinimum": 0 },
|
||||
"color": { "type": "string", "description": "#rrggbb" },
|
||||
"align": { "type": "string", "enum": ["left", "center", "right", "justify"] },
|
||||
"aligns": { "type": "array", "maxItems": 4096, "items": { "enum": ["left", "center", "right", "justify", null] }, "description": "Each paragraph's (line's) own alignment, by index; null follows align." },
|
||||
"underline": { "type": "boolean" },
|
||||
"line_spacing": { "type": "number", "description": "Multiple of the font size (1.2 is ordinary)." },
|
||||
"dx": { "type": "number", "description": "Paragraph only: move right by this many points (negative: left)." },
|
||||
@@ -1400,7 +1442,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). 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, Group 3 fax images, black-and-white RGB and indexed images using only palette entries 0 and 1 among them, counted in images_recompressed; retain resamples only, a CCITT image staying CCITT and any other becoming Flate). Images are measured where pages draw them and replaced only when smaller. discard_*: thumbnails (default true), alternate_images (true), tags, print_settings; flate_unencoded (true); object_streams (default true; always off for 1.4); lzw_to_flate (true) decodes LZW streams and stores them with Flate instead, leaving any it cannot decode unchanged (lzw_streams counts the streams converted); remove_invalid_links and remove_unreferenced_dests (true); images and forms the pages list but never draw are always dropped (unused_xobjects). discard: Remove Hidden Information categories (metadata, attachments, comments, form-fields, hidden-text, hidden-layers, bookmarks, links-actions-scripts, private-data). Signed documents are refused. The open document is unchanged.")
|
||||
.cmd("optimize.advanced")
|
||||
.with(schema(
|
||||
json!({
|
||||
@@ -1411,6 +1453,7 @@ pub fn tools() -> Vec<ToolDef> {
|
||||
"merge_fragments": { "type": "boolean" },
|
||||
"color": { "type": "object" },
|
||||
"gray": { "type": "object" },
|
||||
"mono": { "type": "object" },
|
||||
"discard_thumbnails": { "type": "boolean" },
|
||||
"discard_alternate_images": { "type": "boolean" },
|
||||
"discard_tags": { "type": "boolean" },
|
||||
@@ -1445,7 +1488,7 @@ pub fn tools() -> Vec<ToolDef> {
|
||||
.destructive().with(schema(json!({"steps":{"type":"array","items":schema(json!({"id":{"type":"string"},"params":{"type":"object"}}), &["id"])},"stop_on_error":{"type":"boolean"}}), &["steps"])),
|
||||
t("doc_inspect", "Inspect open documents", "With doc, return doc_info; otherwise return information for every open document (empty documents array when none are open).")
|
||||
.ro().with(schema(json!({"doc":doc()}), &[])),
|
||||
t("render_preview", "Render a preview", "Render a PNG bounded by max_side (default 1024), without changing or saving the document. Page defaults to 1; doc may be omitted when exactly one document is open.")
|
||||
t("render_preview", "Render a preview", "Render a PNG bounded by max_side (default 1024), without changing or saving the document. Page defaults to 1; doc may be omitted when exactly one document is open. Render warnings follow the image as page_render gives them.")
|
||||
.ro().with(schema(json!({"doc":doc(),"page":{"type":"integer","minimum":1},"max_side":{"type":"integer","minimum":1,"maximum":4096}}), &[])),
|
||||
]
|
||||
}
|
||||
|
||||
@@ -0,0 +1,269 @@
|
||||
//! Add Background on pages that paint their own backdrop, end to end through the tools: what
|
||||
//! `page_render` draws, `doc_backdrops`, save and reopen, and Remove putting the page back.
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
use pdfcraft_automation::{Automation, Content};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
/// Two 200 × 100 pt pages saying "Hi": page 1 on a white fill of its own (as browsers write),
|
||||
/// page 2 on bare paper; a third page is a "scan" (a page-sized grey picture).
|
||||
fn fixture() -> Vec<u8> {
|
||||
let text = "0 g BT /F1 24 Tf 20 40 Td (Hi) Tj ET";
|
||||
let contents = [format!("q 1 1 1 rg 0 0 200 100 re f Q {text}"), text.to_string(), format!("q 200 0 0 100 0 0 cm /Im0 Do Q {text}")];
|
||||
let mut objs: Vec<String> = vec![
|
||||
"<< /Type /Catalog /Pages 2 0 R >>".into(),
|
||||
"<< /Type /Pages /Kids [4 0 R 6 0 R 8 0 R] /Count 3 /MediaBox [0 0 200 100] >>".into(),
|
||||
"<< /Type /XObject /Subtype /Image /Width 1 /Height 1 /ColorSpace /DeviceGray /BitsPerComponent 8 /Length 1 >>\nstream\n\u{80}\nendstream"
|
||||
.into(),
|
||||
];
|
||||
for (i, c) in contents.iter().enumerate() {
|
||||
objs.push(format!(
|
||||
"<< /Type /Page /Parent 2 0 R /Contents {} 0 R /Resources << /Font << /F1 << /Type /Font /Subtype /Type1 /BaseFont /Helvetica >> >> /XObject << /Im0 3 0 R >> >> >>",
|
||||
5 + 2 * i
|
||||
));
|
||||
objs.push(format!("<< /Length {} >>\nstream\n{c}\nendstream", c.len()));
|
||||
}
|
||||
let mut out = b"%PDF-1.7\n".to_vec();
|
||||
let mut offs = Vec::new();
|
||||
for (i, o) in objs.iter().enumerate() {
|
||||
offs.push(out.len());
|
||||
out.extend_from_slice(format!("{} 0 obj\n{o}\nendobj\n", i + 1).as_bytes());
|
||||
}
|
||||
let x = 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{x}\n%%EOF\n", objs.len() + 1).as_bytes());
|
||||
out
|
||||
}
|
||||
|
||||
fn workdir() -> PathBuf {
|
||||
named_workdir("main")
|
||||
}
|
||||
|
||||
/// A folder of its own per test: the tests of this binary run at the same time.
|
||||
fn named_workdir(name: &str) -> PathBuf {
|
||||
let dir = std::env::temp_dir().join(format!("pdfcraft-automation-backdrop-{}-{name}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
std::fs::write(dir.join("a.pdf"), fixture()).unwrap();
|
||||
dir
|
||||
}
|
||||
|
||||
fn ok(a: &mut Automation, tool: &str, args: Value) -> Value {
|
||||
match a.call(tool, &args) {
|
||||
Ok(mut c) => match c.remove(0) {
|
||||
Content::Json(v) => v,
|
||||
other => panic!("{tool}: expected JSON, got {other:?}"),
|
||||
},
|
||||
Err(e) => panic!("{tool} {args}: {e}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// The RGB of a blank spot (top-right corner area) of a page rendered at 72 dpi.
|
||||
fn blank_spot(a: &mut Automation, doc: u64, page: u64) -> [u8; 3] {
|
||||
let rendered = a.call("page_render", &json!({ "doc": doc, "page": page, "dpi": 72 })).unwrap();
|
||||
let Content::Png { data, width, .. } = &rendered[0] else { panic!("expected a PNG") };
|
||||
let mut reader = png::Decoder::new(std::io::Cursor::new(data)).read_info().unwrap();
|
||||
let mut pixels = vec![0; reader.output_buffer_size().unwrap()];
|
||||
let info = reader.next_frame(&mut pixels).unwrap();
|
||||
let channels = info.color_type.samples();
|
||||
let at = (10 * *width as usize + 180) * channels;
|
||||
[pixels[at], pixels[at + 1], pixels[at + 2]]
|
||||
}
|
||||
|
||||
const RED: [u8; 3] = [255, 0, 0];
|
||||
const WHITE: [u8; 3] = [255, 255, 255];
|
||||
|
||||
#[test]
|
||||
fn a_background_shows_on_a_page_that_paints_its_own_white_backdrop() {
|
||||
let dir = workdir();
|
||||
let mut a = Automation::new().with_root(&dir).unwrap();
|
||||
let doc = ok(&mut a, "doc_open", json!({ "path": "a.pdf" }))["doc"].as_u64().unwrap();
|
||||
assert_eq!(
|
||||
ok(&mut a, "doc_backdrops", json!({ "doc": doc }))["pages"],
|
||||
json!([{ "page": 1, "backdrop": "fill" }, { "page": 3, "backdrop": "image" }])
|
||||
);
|
||||
|
||||
// Not replacing: the page's own white hides the background, as it always did.
|
||||
ok(&mut a, "doc_background", json!({ "doc": doc, "color": "#FF0000", "replace_backdrop": false }));
|
||||
assert_eq!(blank_spot(&mut a, doc, 1), WHITE);
|
||||
assert_eq!(blank_spot(&mut a, doc, 2), RED);
|
||||
ok(&mut a, "edit_undo", json!({ "doc": doc }));
|
||||
|
||||
// The default replaces it: red on both pages; the scan still hides it.
|
||||
ok(&mut a, "doc_background", json!({ "doc": doc, "color": "#FF0000" }));
|
||||
assert_eq!(blank_spot(&mut a, doc, 1), RED);
|
||||
assert_eq!(blank_spot(&mut a, doc, 2), RED);
|
||||
assert_ne!(blank_spot(&mut a, doc, 3), RED);
|
||||
assert_eq!(ok(&mut a, "doc_backdrops", json!({ "doc": doc }))["pages"], json!([{ "page": 3, "backdrop": "image" }]));
|
||||
|
||||
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();
|
||||
assert_eq!(blank_spot(&mut a, saved, 1), RED, "after save and reopen");
|
||||
ok(&mut a, "doc_remove_marks", json!({ "doc": saved, "kind": "background" }));
|
||||
assert_eq!(blank_spot(&mut a, saved, 1), WHITE);
|
||||
assert_eq!(
|
||||
ok(&mut a, "doc_backdrops", json!({ "doc": saved, "pages": [1] }))["pages"],
|
||||
json!([{ "page": 1, "backdrop": "fill" }]),
|
||||
"the backdrop is back"
|
||||
);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// One 200 × 100 pt page on a white fill of its own: a line to redact, invisible (`3 Tr`) text
|
||||
/// that Remove Hidden Information removes, and a line that stays (`0 Tr` again: the render mode
|
||||
/// outlives `ET`). With `tag`, the content is a
|
||||
/// backdrop copy carrying that tag, under a background.
|
||||
fn secret_pdf(tag: Option<&str>) -> Vec<u8> {
|
||||
let fill = if tag.is_some() { "n" } else { "f" };
|
||||
let content = format!(
|
||||
"1 1 1 rg 0 0 200 100 re {fill} 0 g BT /F1 12 Tf 10 70 Td (SECRET-LINE) Tj ET BT 3 Tr /F1 12 Tf 10 45 Td (HIDDEN-LINE) Tj ET BT 0 Tr /F1 12 Tf 10 20 Td (KEEP) Tj ET"
|
||||
);
|
||||
let bg = "q 1 0 0 rg 0 0 200 100 re f Q";
|
||||
let (contents, extra) = match tag {
|
||||
Some(t) => (
|
||||
"[5 0 R 6 0 R]",
|
||||
vec![
|
||||
format!("<< /PCMark /Background /Length {} >>\nstream\n{bg}\nendstream", bg.len()),
|
||||
format!("<< /PCBackdrop {t} /Length {} >>\nstream\n{content}\nendstream", content.len()),
|
||||
],
|
||||
),
|
||||
None => ("[5 0 R]", vec![format!("<< /Length {} >>\nstream\n{content}\nendstream", content.len())]),
|
||||
};
|
||||
let mut objs: Vec<String> = vec![
|
||||
"<< /Type /Catalog /Pages 2 0 R >>".into(),
|
||||
"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 200 100] >>".into(),
|
||||
format!("<< /Type /Page /Parent 2 0 R /Contents {contents} /Resources << /Font << /F1 4 0 R >> >> >>"),
|
||||
"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>".into(),
|
||||
];
|
||||
objs.extend(extra);
|
||||
let mut out = b"%PDF-1.7\n".to_vec();
|
||||
let mut offs = Vec::new();
|
||||
for (i, o) in objs.iter().enumerate() {
|
||||
offs.push(out.len());
|
||||
out.extend_from_slice(format!("{} 0 obj\n{o}\nendobj\n", i + 1).as_bytes());
|
||||
}
|
||||
let x = 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{x}\n%%EOF\n", objs.len() + 1).as_bytes());
|
||||
out
|
||||
}
|
||||
|
||||
/// Every stream of a saved file, decoded, joined: what anyone reading the file can recover.
|
||||
fn every_stream(path: &std::path::Path) -> String {
|
||||
let doc = pdfcraft_cos::Document::open(std::sync::Arc::new(std::fs::read(path).unwrap())).unwrap();
|
||||
doc.scan_objects()
|
||||
.filter_map(|(_, o)| match &*o {
|
||||
pdfcraft_cos::Object::Stream(s) => Some(String::from_utf8_lossy(&s.decoded().unwrap_or_default()).into_owned()),
|
||||
_ => None,
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n")
|
||||
}
|
||||
|
||||
/// Text a redaction or Remove Hidden Information took off a page whose backdrop a background
|
||||
/// replaced is gone from the saved file. The backdrop copy's tag used to keep a reference to the
|
||||
/// page's original content stream, and with it the removed text. Removing the background
|
||||
/// afterwards still turns the page's white fill back on.
|
||||
#[test]
|
||||
fn removed_text_leaves_the_file_when_a_background_replaced_the_pages_backdrop() {
|
||||
for (remove, gone) in [
|
||||
(vec![("redact_mark", json!({ "find": "SECRET-LINE" })), ("redact_apply", json!({}))], "SECRET-LINE"),
|
||||
(vec![("doc_remove_hidden", json!({ "categories": ["hidden-text"] }))], "HIDDEN-LINE"),
|
||||
] {
|
||||
let dir = named_workdir(gone);
|
||||
std::fs::write(dir.join("s.pdf"), secret_pdf(None)).unwrap();
|
||||
let mut a = Automation::new().with_root(&dir).unwrap();
|
||||
let doc = ok(&mut a, "doc_open", json!({ "path": "s.pdf" }))["doc"].as_u64().unwrap();
|
||||
ok(&mut a, "doc_background", json!({ "doc": doc, "color": "#FF0000" }));
|
||||
for (tool, args) in &remove {
|
||||
let mut args = args.clone();
|
||||
args["doc"] = json!(doc);
|
||||
ok(&mut a, tool, args);
|
||||
}
|
||||
ok(&mut a, "doc_save", json!({ "doc": doc, "path": "out.pdf", "full": true }));
|
||||
let file = every_stream(&dir.join("out.pdf"));
|
||||
assert!(file.contains("(KEEP)"), "{gone}: the page's other text is still there: {file}");
|
||||
assert!(!file.contains(gone), "{gone} is still in the file: {file}");
|
||||
|
||||
let saved = ok(&mut a, "doc_open", json!({ "path": "out.pdf" }))["doc"].as_u64().unwrap();
|
||||
let removed = ok(&mut a, "doc_remove_marks", json!({ "doc": saved, "kind": "background" }));
|
||||
assert!(removed.get("warnings").is_none(), "{gone}: {removed}");
|
||||
assert_eq!(
|
||||
ok(&mut a, "doc_backdrops", json!({ "doc": saved }))["pages"],
|
||||
json!([{ "page": 1, "backdrop": "fill" }]),
|
||||
"{gone}: the fill is back"
|
||||
);
|
||||
assert_eq!(blank_spot(&mut a, saved, 1), WHITE);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
}
|
||||
|
||||
/// When the backdrop can't be turned back on safely, Remove background says which pages keep it
|
||||
/// off.
|
||||
#[test]
|
||||
fn remove_background_warns_about_pages_whose_own_backdrop_stays_off() {
|
||||
let dir = named_workdir("left-off");
|
||||
// A tag whose hash doesn't match the bytes before the fill: they changed since.
|
||||
let tag = format!("<< /Index 2 /Op (f) /Before <{}> >>", "00".repeat(32));
|
||||
std::fs::write(dir.join("t.pdf"), secret_pdf(Some(&tag))).unwrap();
|
||||
let mut a = Automation::new().with_root(&dir).unwrap();
|
||||
let doc = ok(&mut a, "doc_open", json!({ "path": "t.pdf" }))["doc"].as_u64().unwrap();
|
||||
let removed = ok(&mut a, "doc_remove_marks", json!({ "doc": doc, "kind": "background" }));
|
||||
let warnings = removed["warnings"].as_array().unwrap_or_else(|| panic!("{removed}"));
|
||||
assert_eq!(warnings.len(), 1, "{removed}");
|
||||
assert!(warnings[0].as_str().unwrap().starts_with("page 1 changed after the background was added"), "{removed}");
|
||||
assert_eq!(ok(&mut a, "doc_backdrops", json!({ "doc": doc }))["pages"], json!([]), "the fill stays off");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// Two 200 × 100 pt pages whose full-page `1 g` fill is not a plain white backdrop (#2815
|
||||
/// review): page 1 paints it half transparent, through a `gs` that sets `ca` and a later one
|
||||
/// that only sets the line width; page 2 sends it through a transfer function that maps 1 to 0.
|
||||
fn graphics_state_pdf() -> Vec<u8> {
|
||||
let invert = "<< /FunctionType 2 /Domain [0 1] /C0 [1] /C1 [0] /N 1 >>";
|
||||
let resources = format!("<< /ExtGState << /Transparent << /ca 0.5 >> /LineOnly << /LW 2 >> /Invert << /TR {invert} >> >> >>");
|
||||
let contents = ["/Transparent gs /LineOnly gs 1 g 0 0 200 100 re f", "/Invert gs 1 g 0 0 200 100 re f"];
|
||||
let mut objs: Vec<String> =
|
||||
vec!["<< /Type /Catalog /Pages 2 0 R >>".into(), "<< /Type /Pages /Kids [3 0 R 5 0 R] /Count 2 /MediaBox [0 0 200 100] >>".into()];
|
||||
for (i, c) in contents.iter().enumerate() {
|
||||
objs.push(format!("<< /Type /Page /Parent 2 0 R /Contents {} 0 R /Resources {resources} >>", 4 + 2 * i));
|
||||
objs.push(format!("<< /Length {} >>\nstream\n{c}\nendstream", c.len()));
|
||||
}
|
||||
let mut out = b"%PDF-1.7\n".to_vec();
|
||||
let mut offs = Vec::new();
|
||||
for (i, o) in objs.iter().enumerate() {
|
||||
offs.push(out.len());
|
||||
out.extend_from_slice(format!("{} 0 obj\n{o}\nendobj\n", i + 1).as_bytes());
|
||||
}
|
||||
let x = 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{x}\n%%EOF\n", objs.len() + 1).as_bytes());
|
||||
out
|
||||
}
|
||||
|
||||
/// #2815 review: a translucent fill (its `ca` left in force by a later `gs`) and a fill through
|
||||
/// a transfer function are not backdrops, so a red background goes under them and the
|
||||
/// translucent white still lightens it.
|
||||
#[test]
|
||||
fn fills_the_graphics_state_changes_are_not_replaced() {
|
||||
let dir = named_workdir("graphics-state");
|
||||
std::fs::write(dir.join("gs.pdf"), graphics_state_pdf()).unwrap();
|
||||
let mut a = Automation::new().with_root(&dir).unwrap();
|
||||
let doc = ok(&mut a, "doc_open", json!({ "path": "gs.pdf" }))["doc"].as_u64().unwrap();
|
||||
assert_eq!(ok(&mut a, "doc_backdrops", json!({ "doc": doc }))["pages"], json!([]), "neither fill is a backdrop");
|
||||
ok(&mut a, "doc_background", json!({ "doc": doc, "color": "#FF0000" }));
|
||||
let [r, g, b] = blank_spot(&mut a, doc, 1);
|
||||
assert_eq!(r, 255, "{:?}", [r, g, b]);
|
||||
assert!((100..=160).contains(&g) && (100..=160).contains(&b), "half-transparent white over red, not red: {:?}", [r, g, b]);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
@@ -151,3 +151,26 @@ fn bulk_options_apply_per_field_and_refuse_an_invalid_comb_atomically() {
|
||||
assert_eq!(bytes(&a, id), before);
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn button_export_edit_is_one_undo_step_and_survives_save() {
|
||||
let (mut a, id, dir) = setup("button-export");
|
||||
tool(&mut a, "form_add_field", json!({"doc": id, "page": 1, "type": "checkbox", "name": "agree", "rect": [20, 20, 40, 40]}));
|
||||
tool(&mut a, "form_fill", json!({"doc": id, "values": {"agree": true}}));
|
||||
let before = bytes(&a, id);
|
||||
call(&mut a, json!({"doc": id, "field": "agree", "export_value": "Accepted", "widget": 1}));
|
||||
let f = tool(&mut a, "form_fields", json!({"doc": id}));
|
||||
let check = f["fields"].as_array().unwrap().iter().find(|f| f["name"] == "agree").unwrap();
|
||||
assert_eq!(check["export_values"], json!(["Accepted"]));
|
||||
assert_eq!(check["value"], true);
|
||||
tool(&mut a, "edit_undo", json!({"doc": id}));
|
||||
assert_eq!(bytes(&a, id), before);
|
||||
tool(&mut a, "edit_redo", json!({"doc": id}));
|
||||
tool(&mut a, "doc_save", json!({"doc": id, "path": "saved.pdf"}));
|
||||
let reopened = tool(&mut a, "doc_open", json!({"path": "saved.pdf"}))["doc"].as_u64().unwrap();
|
||||
let f = tool(&mut a, "form_fields", json!({"doc": reopened}));
|
||||
let check = f["fields"].as_array().unwrap().iter().find(|f| f["name"] == "agree").unwrap();
|
||||
assert_eq!(check["export_values"], json!(["Accepted"]));
|
||||
assert_eq!(check["value"], true);
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
@@ -3,8 +3,12 @@
|
||||
mod attachment_key;
|
||||
mod automation;
|
||||
mod automation_roots;
|
||||
mod backdrop;
|
||||
mod batch;
|
||||
mod button_caption;
|
||||
mod form_bulk;
|
||||
mod hostile_args;
|
||||
mod optimize_content_boundaries;
|
||||
mod redact_after_stray_q_form;
|
||||
mod redact_text_after_q;
|
||||
mod render_warnings;
|
||||
@@ -0,0 +1,67 @@
|
||||
//! Search-and-redact of page text drawn after a form XObject with more `Q` than `q`. Find's boxes
|
||||
//! come from the renderer's text and redaction measures the content itself, so the two must agree
|
||||
//! that the form's stray `Q`s do not undo the page's `cm` (vendored hayro-interpret patch 68).
|
||||
|
||||
use pdfcraft_automation::{Automation, Content};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
const CONTENT: &str = "q 1 0 0 1 20 -100 cm BT /F1 12 Tf 72 700 Td (AAAA) Tj ET /X Do \
|
||||
BT /F1 12 Tf 72 680 Td (SECRET) Tj ET Q";
|
||||
const FORM: &str = "BT /F1 12 Tf 200 0 Td ET Q Q Q";
|
||||
|
||||
fn pdf() -> Vec<u8> {
|
||||
let objects = [
|
||||
"<< /Type /Catalog /Pages 2 0 R >>".to_owned(),
|
||||
"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_owned(),
|
||||
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents 4 0 R /Resources << /Font << \
|
||||
/F1 << /Type /Font /Subtype /Type1 /BaseFont /Helvetica >> >> /XObject << /X 5 0 R >> >> >>"
|
||||
.to_owned(),
|
||||
format!("<< /Length {} >>\nstream\n{CONTENT}\nendstream", CONTENT.len()),
|
||||
format!("<< /Type /XObject /Subtype /Form /BBox [0 0 612 792] /Length {} >>\nstream\n{FORM}\nendstream", FORM.len()),
|
||||
];
|
||||
let mut out = b"%PDF-1.7\n".to_vec();
|
||||
let mut offsets = Vec::new();
|
||||
for (i, object) in objects.iter().enumerate() {
|
||||
offsets.push(out.len());
|
||||
out.extend_from_slice(format!("{} 0 obj\n{object}\nendobj\n", i + 1).as_bytes());
|
||||
}
|
||||
let xref = out.len();
|
||||
out.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objects.len() + 1).as_bytes());
|
||||
for offset in offsets {
|
||||
out.extend_from_slice(format!("{offset:010} 00000 n \n").as_bytes());
|
||||
}
|
||||
out.extend_from_slice(format!("trailer << /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objects.len() + 1).as_bytes());
|
||||
out
|
||||
}
|
||||
|
||||
fn ok(a: &mut Automation, tool: &str, args: Value) -> Value {
|
||||
match a.call(tool, &args) {
|
||||
Ok(mut c) => match c.remove(0) {
|
||||
Content::Json(v) => v,
|
||||
other => panic!("{tool}: expected JSON, got {other:?}"),
|
||||
},
|
||||
Err(e) => panic!("{tool} {args}: {e}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn text(a: &mut Automation, doc: &Value) -> String {
|
||||
ok(a, "text_extract", json!({ "doc": doc }))["pages"][0]["text"].as_str().unwrap_or_default().to_owned()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn find_and_redact_removes_text_drawn_after_a_form_with_stray_q() {
|
||||
let dir = std::env::temp_dir().join(format!("pdfcraft-redact-stray-q-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
std::fs::write(dir.join("in.pdf"), pdf()).unwrap();
|
||||
let mut a = Automation::new().with_root(&dir).unwrap();
|
||||
let doc = ok(&mut a, "doc_open", json!({ "path": "in.pdf" }))["doc"].clone();
|
||||
assert_eq!(ok(&mut a, "redact_mark", json!({ "doc": doc, "find": "SECRET" }))["marked"], 1);
|
||||
ok(&mut a, "redact_apply", json!({ "doc": doc }));
|
||||
ok(&mut a, "doc_save", json!({ "doc": doc, "path": "out.pdf", "full": true }));
|
||||
let saved = ok(&mut a, "doc_open", json!({ "path": "out.pdf" }))["doc"].clone();
|
||||
let after = text(&mut a, &saved);
|
||||
assert!(!after.contains("SECRET"), "{after:?}");
|
||||
assert!(after.contains("AAAA"), "the text before the mark stays: {after:?}");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
//! Search-and-redact of text that follows a `q`/`Q` inside a text object. `Q` restores the text
|
||||
//! matrices there (ISO 32000-2 §9.4.1 as corrected by the PDF Association's errata, issue 368), so
|
||||
//! "SECRET" is drawn from the pen position before `q`, over the "B". Find's boxes come from the
|
||||
//! renderer's text, which places it there; redaction measures the content itself, and while it
|
||||
//! carried the pen across `Q` the two disagreed and `redact_apply` refused to change anything.
|
||||
use pdfcraft_automation::{Automation, Content};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
/// The content, the text that stays after SECRET is redacted, and the text that goes with it.
|
||||
const CASES: [(&str, &str, &str); 3] = [
|
||||
// A larger font inside `q`/`Q`: the font and the pen are both restored, so SECRET lies over
|
||||
// the B and the B goes with it.
|
||||
("BT /F1 12 Tf 72 700 Td (AAAA) Tj q /F2 24 Tf (B) Tj Q (SECRET) Tj ET", "AAAA", "B"),
|
||||
// A move inside `q`/`Q` is undone.
|
||||
("BT /F1 12 Tf 72 700 Td (AA) Tj q 100 0 Td Q (SECRET) Tj ET", "AA", "SECRET"),
|
||||
// The text line matrix is restored too: `T*` starts the next line from the line before `q`.
|
||||
("BT /F1 12 Tf 14 TL 72 700 Td (AA) Tj q 100 0 Td Q T* (SECRET) Tj ET", "AA", "SECRET"),
|
||||
];
|
||||
|
||||
fn pdf(content: &str) -> Vec<u8> {
|
||||
let objects = [
|
||||
"<< /Type /Catalog /Pages 2 0 R >>".to_owned(),
|
||||
"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_owned(),
|
||||
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents 4 0 R /Resources << /Font << \
|
||||
/F1 << /Type /Font /Subtype /Type1 /BaseFont /Helvetica >> \
|
||||
/F2 << /Type /Font /Subtype /Type1 /BaseFont /Courier >> >> >> >>"
|
||||
.to_owned(),
|
||||
format!("<< /Length {} >>\nstream\n{content}\nendstream", content.len()),
|
||||
];
|
||||
let mut out = b"%PDF-2.0\n".to_vec();
|
||||
let mut offsets = Vec::new();
|
||||
for (i, object) in objects.iter().enumerate() {
|
||||
offsets.push(out.len());
|
||||
out.extend_from_slice(format!("{} 0 obj\n{object}\nendobj\n", i + 1).as_bytes());
|
||||
}
|
||||
let xref = out.len();
|
||||
out.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objects.len() + 1).as_bytes());
|
||||
for offset in offsets {
|
||||
out.extend_from_slice(format!("{offset:010} 00000 n \n").as_bytes());
|
||||
}
|
||||
out.extend_from_slice(format!("trailer << /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objects.len() + 1).as_bytes());
|
||||
out
|
||||
}
|
||||
|
||||
fn ok(a: &mut Automation, tool: &str, args: Value) -> Value {
|
||||
match a.call(tool, &args) {
|
||||
Ok(mut c) => match c.remove(0) {
|
||||
Content::Json(v) => v,
|
||||
other => panic!("{tool}: expected JSON, got {other:?}"),
|
||||
},
|
||||
Err(e) => panic!("{tool} {args}: {e}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn text(a: &mut Automation, doc: &Value) -> String {
|
||||
ok(a, "text_extract", json!({ "doc": doc }))["pages"][0]["text"].as_str().unwrap_or_default().to_owned()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn find_and_redact_removes_text_after_a_q_q_inside_its_text_object() {
|
||||
for (case, (content, kept, gone)) in CASES.iter().enumerate() {
|
||||
let dir = std::env::temp_dir().join(format!("pdfcraft-redact-after-q-{}-{case}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
std::fs::write(dir.join("in.pdf"), pdf(content)).unwrap();
|
||||
let mut a = Automation::new().with_root(&dir).unwrap();
|
||||
let doc = ok(&mut a, "doc_open", json!({ "path": "in.pdf" }))["doc"].clone();
|
||||
assert_eq!(ok(&mut a, "redact_mark", json!({ "doc": doc, "find": "SECRET" }))["marked"], 1, "{content}");
|
||||
ok(&mut a, "redact_apply", json!({ "doc": doc }));
|
||||
ok(&mut a, "doc_save", json!({ "doc": doc, "path": "out.pdf", "full": true }));
|
||||
let saved = ok(&mut a, "doc_open", json!({ "path": "out.pdf" }))["doc"].clone();
|
||||
let after = text(&mut a, &saved);
|
||||
assert!(!after.contains("SECRET") && !after.contains(gone), "{content}: {after:?}");
|
||||
assert!(after.contains(kept), "{content}: the text before the mark stays: {after:?}");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
//! `page_render` reports the renderer's warnings next to the PNG, so a headless caller can tell
|
||||
//! that a picture is incomplete or approximate, as `pdfcraft-cli render` can (#4340).
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
use pdfcraft_automation::{Automation, Content};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
/// The warning a colour that falls back gives, worded as `pdfcraft-cli render` prints it.
|
||||
const FALLBACK: &str = "a colour that could not be computed was painted in a fallback colour";
|
||||
|
||||
/// A one-page 200 × 200 pt PDF that draws `content`, with the colour space `CS1` defined as
|
||||
/// `[/DeviceN [/Spot1 /Spot2] /DeviceRGB 5 0 R]` and object 5 a calculator function `program`.
|
||||
fn devicen_pdf(content: &str, program: &str) -> Vec<u8> {
|
||||
format!(
|
||||
"%PDF-1.7\n1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj\n\
|
||||
2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj\n\
|
||||
3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Resources << /ColorSpace << /CS1 [/DeviceN [/Spot1 /Spot2] /DeviceRGB 5 0 R] >> >> /Contents 4 0 R >> endobj\n\
|
||||
4 0 obj << /Length {} >> stream\n{content}\nendstream endobj\n\
|
||||
5 0 obj << /FunctionType 4 /Domain [0 1 0 1] /Range [0 1 0 1 0 1] /Length {} >> stream\n{program}\nendstream endobj\n\
|
||||
trailer << /Root 1 0 R >>\n%%EOF",
|
||||
content.len(),
|
||||
program.len()
|
||||
)
|
||||
.into_bytes()
|
||||
}
|
||||
|
||||
/// A page whose colour falls back: the tint transform pops more than it is given, so it can't be
|
||||
/// evaluated (the renderer's own test of the warning uses the same function).
|
||||
fn fallback_pdf() -> Vec<u8> {
|
||||
devicen_pdf("/CS1 cs 0.5 0.5 scn 0 0 100 100 re f", "{ pop pop pop }")
|
||||
}
|
||||
|
||||
/// The same page with a tint transform that works: nothing to warn about.
|
||||
fn clean_pdf() -> Vec<u8> {
|
||||
devicen_pdf("/CS1 cs 0.5 0.5 scn 0 0 100 100 re f", "{ pop pop 0 0 0 }")
|
||||
}
|
||||
|
||||
/// A fresh folder holding `fallback.pdf` and `clean.pdf`, and an automation rooted there.
|
||||
fn setup(test: &str) -> (PathBuf, Automation) {
|
||||
let dir = std::env::temp_dir().join(format!("pdfcraft-render-warnings-{test}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
std::fs::write(dir.join("fallback.pdf"), fallback_pdf()).unwrap();
|
||||
std::fs::write(dir.join("clean.pdf"), clean_pdf()).unwrap();
|
||||
let a = Automation::new().with_root(&dir).unwrap();
|
||||
(dir, a)
|
||||
}
|
||||
|
||||
fn open(a: &mut Automation, path: &str) -> u64 {
|
||||
match a.call("doc_open", &json!({ "path": path })).unwrap().remove(0) {
|
||||
Content::Json(v) => v["doc"].as_u64().unwrap(),
|
||||
other => panic!("expected JSON: {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn page_render_lists_the_warnings_after_the_png() {
|
||||
let (dir, mut a) = setup("fallback");
|
||||
let doc = open(&mut a, "fallback.pdf");
|
||||
let out = a.call("page_render", &json!({ "doc": doc, "page": 1, "dpi": 72 })).unwrap();
|
||||
assert_eq!(out.len(), 2, "the PNG and the warnings: {out:?}");
|
||||
assert!(matches!(out[0], Content::Png { width: 200, height: 200, .. }), "the image comes first, as before");
|
||||
let Content::Json(report) = &out[1] else { panic!("expected the warnings as JSON: {:?}", out[1]) };
|
||||
assert_eq!(report["page"], 1, "the page is 1-based, like the argument");
|
||||
assert_eq!(report["warnings"], json!([FALLBACK]));
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn render_preview_lists_the_warnings_after_the_png_too() {
|
||||
let (dir, mut a) = setup("preview");
|
||||
let doc = open(&mut a, "fallback.pdf");
|
||||
let out = a.call("render_preview", &json!({ "doc": doc, "max_side": 64 })).unwrap();
|
||||
assert!(matches!(out.first(), Some(Content::Png { width: 64, height: 64, .. })), "{out:?}");
|
||||
let Some(Content::Json(report)) = out.get(1) else { panic!("expected the warnings as JSON: {out:?}") };
|
||||
assert_eq!(report["page"], 1, "the page defaults to the first");
|
||||
assert_eq!(report["warnings"], json!([FALLBACK]));
|
||||
let clean = open(&mut a, "clean.pdf");
|
||||
assert_eq!(a.call("render_preview", &json!({ "doc": clean })).unwrap().len(), 1, "a clean page gives the PNG alone");
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_clean_page_renders_to_the_png_alone() {
|
||||
let (dir, mut a) = setup("clean");
|
||||
let fallback = open(&mut a, "fallback.pdf");
|
||||
let clean = open(&mut a, "clean.pdf");
|
||||
// The warning of one render doesn't carry over to the next, nor to another document.
|
||||
a.call("page_render", &json!({ "doc": fallback, "page": 1, "dpi": 72 })).unwrap();
|
||||
let out = a.call("page_render", &json!({ "doc": clean, "page": 1, "dpi": 72 })).unwrap();
|
||||
assert_eq!(out.len(), 1, "no warnings, no extra part: {out:?}");
|
||||
assert!(matches!(out[0], Content::Png { .. }));
|
||||
let again = a.call("page_render", &json!({ "doc": fallback, "page": 1, "dpi": 72 })).unwrap();
|
||||
assert_eq!(again.len(), 2, "a cached renderer still reports the page's warning: {again:?}");
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
/// Over MCP the warnings are a text block after the image and the call's `structuredContent`.
|
||||
#[cfg(feature = "mcp")]
|
||||
#[test]
|
||||
fn mcp_page_render_carries_the_warnings_as_structured_content() {
|
||||
use pdfcraft_automation::mcp::McpServer;
|
||||
let (dir, a) = setup("mcp");
|
||||
let mut s = McpServer::new(a);
|
||||
let mut rpc = |id: u64, method: &str, params: Value| -> Value {
|
||||
let line = json!({ "jsonrpc": "2.0", "id": id, "method": method, "params": params }).to_string();
|
||||
serde_json::from_str(&s.handle_line(&line).expect("a reply")).unwrap()
|
||||
};
|
||||
rpc(1, "initialize", json!({}));
|
||||
rpc(2, "tools/call", json!({ "name": "doc_open", "arguments": { "path": "fallback.pdf" } }));
|
||||
let reply = rpc(3, "tools/call", json!({ "name": "page_render", "arguments": { "doc": 1, "page": 1 } }));
|
||||
let result = &reply["result"];
|
||||
assert_eq!(result["isError"], false, "{reply}");
|
||||
assert_eq!(result["content"][0]["type"], "image");
|
||||
assert_eq!(result["content"][1]["type"], "text");
|
||||
assert_eq!(result["structuredContent"]["warnings"], json!([FALLBACK]));
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
@@ -24,6 +24,9 @@ let obj = doc.get(ObjRef { num: 12, gen: 0 }); // load (and cache): Arc<Ob
|
||||
let real = doc.resolve(&obj); // follow one indirect reference
|
||||
let d = doc.dict(&obj); // Option<Dict>, resolving first
|
||||
let data = stream.decoded()?; // filters applied on demand
|
||||
let data = doc.with_direct_parms(&stream).decoded()?; // /DecodeParms given by reference too
|
||||
let px = doc.decoded_image(&stream)?; // an image's samples, a CCITT fax image's too
|
||||
let fax = doc.fax_params(&stream); // a CCITT fax image's /DecodeParms, Table 11 defaults
|
||||
|
||||
doc.set(r, Object::Dict(d)); // edit: lands in the overlay
|
||||
let r = doc.add(obj); // append a new object
|
||||
@@ -87,5 +90,6 @@ recognisable in a diff and byte-stable when re-serialized.
|
||||
- Linearized output, Fast Web View (`core.linearization`, M11).
|
||||
- Structural validation against the Arlington model (`core.arlington-validation`), which will live
|
||||
in the reserved `arlington` crate.
|
||||
- Image codecs. `pdfcraft-filters` carries the non-image filters; DCT, JPX, JBIG2 and CCITT are
|
||||
still decoded through the bootstrap renderer (`core.image-filters`, M2.6).
|
||||
- Image codecs. `pdfcraft-filters` carries the non-image filters and CCITT fax decoding
|
||||
(`Document::decoded_image`); DCT, JPX and JBIG2 are still decoded through the bootstrap renderer
|
||||
(`core.image-filters`, M2.6).
|
||||
@@ -5,11 +5,12 @@
|
||||
//! Edits never touch the original bytes; the writer appends them (incremental save) or rewrites
|
||||
//! the file (full save).
|
||||
|
||||
use std::borrow::Cow;
|
||||
use std::collections::{BTreeMap, HashMap, HashSet};
|
||||
use std::sync::{Arc, Mutex, Weak};
|
||||
|
||||
use crate::CosError;
|
||||
use crate::object::{Dict, ObjRef, Object};
|
||||
use crate::object::{Dict, MAX_DECODED, ObjRef, Object, Stream};
|
||||
use crate::parser::{EndstreamIndex, Lexer, is_whitespace, parse_indirect, parse_indirect_shared};
|
||||
|
||||
mod objects;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use super::reader::find;
|
||||
use super::state::{LENGTHS, LoadGuard, ObjStm, ObjectReader, ReadState, Slot, SourceIdentity, objstm_member, owned_bytes};
|
||||
use super::xref::{Revision, XrefEntry};
|
||||
use super::*;
|
||||
use super::{Arc, CosError, Cow, Dict, Document, Lexer, MAX_DECODED, ObjRef, Object, Stream, is_whitespace, parse_indirect_shared};
|
||||
|
||||
impl Document {
|
||||
pub fn bytes(&self) -> &Arc<Vec<u8>> {
|
||||
@@ -158,11 +158,148 @@ impl Document {
|
||||
}
|
||||
}
|
||||
|
||||
/// `s` with the `/DecodeParms` its filters use made direct, so [`Stream::decoded`] reads them:
|
||||
/// an indirect dictionary resolved, and of an array (itself perhaps indirect), the entries at
|
||||
/// the filters' places (`/Crypt` counts, ISO 32000-2 §7.4.1) resolved, the rest dropped. Of
|
||||
/// each dictionary only the entries the decoders read are kept, numbers and flags given by
|
||||
/// reference (`/Predictor 7 0 R`) resolved; `/JBIG2Globals` stays a reference. A `/Crypt`
|
||||
/// entry, which no decoder reads ([`Stream::filters`] leaves it out), is null. `s` itself
|
||||
/// when none of those is indirect, or when the other filters are more than any decoder takes
|
||||
/// ([`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 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(),
|
||||
Some(f) => vec![crypt(f)],
|
||||
None => Vec::new(),
|
||||
};
|
||||
if filters.iter().filter(|c| !**c).count() > pdfcraft_filters::MAX_CHAIN {
|
||||
return Cow::Borrowed(s);
|
||||
}
|
||||
let mut changed = matches!(p, Object::Ref(_));
|
||||
// Its numbers and flags kept, resolved; anything else is no filter's parameters (null).
|
||||
let one = |e: &Object, changed: &mut bool| -> Object {
|
||||
*changed |= matches!(e, Object::Ref(_));
|
||||
let Object::Dict(d) = &*self.held(e) else { return Object::Null };
|
||||
let mut made = Dict::new();
|
||||
for key in DECODE_PARMS_KEYS {
|
||||
let Some(v) = d.get(key) else { continue };
|
||||
*changed |= matches!(v, Object::Ref(_));
|
||||
let v = self.held(v);
|
||||
if matches!(*v, Object::Int(_) | Object::Real(_) | Object::Bool(_)) {
|
||||
made.set(key.to_vec(), (*v).clone());
|
||||
}
|
||||
}
|
||||
if let Some(g @ Object::Ref(_)) = d.get(b"JBIG2Globals") {
|
||||
made.set(b"JBIG2Globals".to_vec(), g.clone());
|
||||
}
|
||||
Object::Dict(made)
|
||||
};
|
||||
let made = match &*self.held(p) {
|
||||
Object::Array(a) => {
|
||||
Object::Array(a.iter().zip(&filters).map(|(e, crypt)| if *crypt { Object::Null } else { one(e, &mut changed) }).collect())
|
||||
}
|
||||
_ => 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)
|
||||
}
|
||||
|
||||
/// `o`, or the object it refers to, without copying either.
|
||||
fn held<'o>(&self, o: &'o Object) -> Held<'o> {
|
||||
match o {
|
||||
Object::Ref(_) => Held::Resolved(self.resolve(o)),
|
||||
o => Held::Direct(o),
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolve and return a dictionary (a stream's dictionary counts).
|
||||
pub fn dict(&self, o: &Object) -> Option<Dict> {
|
||||
self.resolve(o).as_dict().cloned()
|
||||
}
|
||||
|
||||
/// The CCITT parameters of image `s` when its last filter is `CCITTFaxDecode`: its
|
||||
/// `/DecodeParms` (resolved; the dictionary of a lone filter, or its entry in an array), with the
|
||||
/// defaults of ISO 32000-2 Table 11 for what that leaves out. `None` for another image, and for
|
||||
/// one whose `/Filter` isn't a name or an array of names.
|
||||
pub fn fax_params(&self, s: &Stream) -> Option<pdfcraft_filters::CcittParams> {
|
||||
let chain = s.readable_filters().ok()?;
|
||||
if !matches!(chain.last(), Some((pdfcraft_filters::Filter::CcittFax, _))) {
|
||||
return None;
|
||||
}
|
||||
// Its place in /Filter, /Crypt included, pairs it with its /DecodeParms entry (§7.4.1): the
|
||||
// last filter but a /Crypt, which `filters` leaves out wherever it stands.
|
||||
let index = match s.dict.get(b"Filter") {
|
||||
Some(Object::Array(a)) => a.iter().rposition(|f| f.as_name() != Some(b"Crypt".as_slice())).unwrap_or(0),
|
||||
_ => 0,
|
||||
};
|
||||
let parms = match s.dict.get(b"DecodeParms").map(|p| self.resolve(p)).as_deref() {
|
||||
Some(Object::Array(a)) => a.get(index).and_then(|p| self.dict(p)),
|
||||
Some(p) if index == 0 => p.as_dict().cloned(),
|
||||
_ => None,
|
||||
}
|
||||
.unwrap_or_default();
|
||||
let int = |key: &[u8], default: i64| parms.get(key).and_then(|v| self.resolve(v).as_int()).unwrap_or(default);
|
||||
let flag = |key: &[u8], default: bool| match parms.get(key).map(|v| self.resolve(v)).as_deref() {
|
||||
Some(Object::Bool(b)) => *b,
|
||||
_ => default,
|
||||
};
|
||||
let d = pdfcraft_filters::CcittParams::default();
|
||||
Some(pdfcraft_filters::CcittParams {
|
||||
k: int(b"K", d.k),
|
||||
columns: int(b"Columns", d.columns),
|
||||
rows: int(b"Rows", d.rows),
|
||||
end_of_line: flag(b"EndOfLine", d.end_of_line),
|
||||
encoded_byte_align: flag(b"EncodedByteAlign", d.encoded_byte_align),
|
||||
end_of_block: flag(b"EndOfBlock", d.end_of_block),
|
||||
black_is_1: flag(b"BlackIs1", d.black_is_1),
|
||||
})
|
||||
}
|
||||
|
||||
/// The samples of image `s`, decoded: through its filters ([`Stream::decoded`]), or, for a
|
||||
/// CCITT fax image (its last filter), through the filters before it and then
|
||||
/// [`pdfcraft_filters::decode_ccitt`] with its [`Document::fax_params`], as `CCITTFaxDecode`
|
||||
/// gives them (ISO 32000-2 §7.4.6). Parameters given by reference count, for every filter
|
||||
/// ([`Document::with_direct_parms`]). A fax image's `/Columns` has to be its `/Width`. Up to
|
||||
/// its `/Height` rows are decoded, whatever `/Rows` says, within [`MAX_DECODED`] bytes; damaged
|
||||
/// data gives fewer, so a caller checks it has the rows it needs.
|
||||
pub fn decoded_image(&self, s: &Stream) -> Result<Vec<u8>, CosError> {
|
||||
self.decoded_image_within(s, MAX_DECODED)
|
||||
}
|
||||
|
||||
/// [`Document::decoded_image`] for an image whose decoding has a tighter bound than
|
||||
/// [`MAX_DECODED`]: no stage, the filters before a fax decoder included, may produce more than
|
||||
/// `max` bytes.
|
||||
pub fn decoded_image_within(&self, s: &Stream, max: usize) -> Result<Vec<u8>, CosError> {
|
||||
let max = max.min(MAX_DECODED);
|
||||
let s = &*self.with_direct_parms(s);
|
||||
let Some(p) = self.fax_params(s) else { return s.decoded_within(max) };
|
||||
// As many rows as the image has: a /Rows below /Height would cut the picture short, and
|
||||
// rows past /Height aren't drawn.
|
||||
let p = pdfcraft_filters::CcittParams { rows: 0, ..p };
|
||||
if s.dict.int(b"Width") != Some(p.columns) {
|
||||
return Err(CosError::Filter("a fax image's /Columns aren't its /Width".into()));
|
||||
}
|
||||
let height = s.dict.int(b"Height").and_then(|h| u32::try_from(h).ok()).unwrap_or(0);
|
||||
let stride = usize::try_from(p.columns).unwrap_or(usize::MAX).div_ceil(8).max(1);
|
||||
let rows = u32::try_from(max / stride).unwrap_or(u32::MAX).min(height);
|
||||
// The filters before it, such as ASCII85Decode, are undone first.
|
||||
let chain = s.readable_filters().map_err(|e| CosError::Filter(e.to_string()))?;
|
||||
let data = match chain.split_last() {
|
||||
Some((_, before)) if !before.is_empty() => {
|
||||
Cow::Owned(pdfcraft_filters::decode_tolerant(before, &s.raw, max).map_err(|e| CosError::Filter(e.to_string()))?.0)
|
||||
}
|
||||
_ => Cow::Borrowed(&s.raw[..]),
|
||||
};
|
||||
pdfcraft_filters::decode_ccitt(&data, &p, rows).map_err(|e| CosError::Filter(e.to_string()))
|
||||
}
|
||||
|
||||
pub fn try_get(&self, num: u32) -> Result<Arc<Object>, CosError> {
|
||||
match self.overlay.get(&num) {
|
||||
Some(Slot::Set(_, o)) => return Ok(o.clone()),
|
||||
@@ -570,3 +707,40 @@ impl Document {
|
||||
matches!(self.try_get(r.num).as_deref(), Ok(Object::Dict(d)) if d.name(b"Type") == Some(b"Catalog") || d.contains(b"Pages"))
|
||||
}
|
||||
}
|
||||
|
||||
/// The `/DecodeParms` entries the decoders read (ISO 32000-2 Tables 8, 11 and 13: the Flate and
|
||||
/// LZW predictors, CCITT, DCT's colour transform): numbers and flags a file may give by
|
||||
/// reference, which [`Dict::int`] doesn't follow.
|
||||
const DECODE_PARMS_KEYS: [&[u8]; 13] = [
|
||||
b"Predictor",
|
||||
b"Colors",
|
||||
b"BitsPerComponent",
|
||||
b"Columns",
|
||||
b"EarlyChange",
|
||||
b"K",
|
||||
b"Rows",
|
||||
b"EndOfLine",
|
||||
b"EncodedByteAlign",
|
||||
b"EndOfBlock",
|
||||
b"BlackIs1",
|
||||
b"DamagedRowsBeforeError",
|
||||
b"ColorTransform",
|
||||
];
|
||||
|
||||
/// An object read in place, or the object a reference names as the document holds it: either way
|
||||
/// nothing is copied ([`Document::held`]).
|
||||
enum Held<'o> {
|
||||
Direct(&'o Object),
|
||||
Resolved(Arc<Object>),
|
||||
}
|
||||
|
||||
impl std::ops::Deref for Held<'_> {
|
||||
type Target = Object;
|
||||
|
||||
fn deref(&self) -> &Object {
|
||||
match self {
|
||||
Held::Direct(o) => o,
|
||||
Held::Resolved(o) => o,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
use super::reader::{find, generated_id};
|
||||
use super::reader::find;
|
||||
use super::state::Credentials;
|
||||
use super::xref::XrefIndex;
|
||||
use super::*;
|
||||
use super::{Arc, BTreeMap, CosError, Dict, Document, ObjRef, Object};
|
||||
|
||||
impl Document {
|
||||
/// A new document with an empty page tree (for split / extract / combine). It has no
|
||||
@@ -271,8 +271,7 @@ impl Document {
|
||||
let id0 = match self.trailer.get(b"ID") {
|
||||
Some(Object::Array(a)) if a.len() == 2 => a[0].as_string().map(|s| s.bytes.clone()).unwrap_or_default(),
|
||||
_ => {
|
||||
let mut id = generated_id(¶ms.seed);
|
||||
id.truncate(16);
|
||||
let id = pdfcraft_crypt::file_id(¶ms.seed);
|
||||
let s = Object::String(crate::PdfString { bytes: id.clone(), hex: true });
|
||||
self.trailer.set(b"ID".to_vec(), Object::Array(vec![s.clone(), s]));
|
||||
id
|
||||
|
||||
@@ -3,7 +3,7 @@ use super::state::SECTION_READS;
|
||||
use super::xref::{
|
||||
MAX_COMPACT_XREF_BYTES, MAX_COMPACT_XREF_ROWS, Revision, XrefEntry, XrefIndex, XrefRange, XrefRevisionSection, XrefSection, XrefSectionData,
|
||||
};
|
||||
use super::*;
|
||||
use super::{Arc, BTreeMap, CosError, Dict, Document, HashMap, HashSet, Lexer, ObjRef, Object, is_whitespace, parse_indirect, parse_indirect_shared};
|
||||
|
||||
impl Document {
|
||||
#[allow(clippy::type_complexity)]
|
||||
@@ -818,18 +818,6 @@ pub(super) fn rfind(hay: &[u8], needle: &[u8], from: usize) -> Option<usize> {
|
||||
(from..=hay.len() - needle.len()).rev().find(|&i| &hay[i..i + needle.len()] == needle)
|
||||
}
|
||||
|
||||
/// A file identifier derived from entropy supplied by the caller.
|
||||
pub(super) fn generated_id(seed: &[u8; 32]) -> Vec<u8> {
|
||||
use std::hash::{Hash, Hasher};
|
||||
let mut out = Vec::new();
|
||||
for i in 0..2u8 {
|
||||
let mut h = std::collections::hash_map::DefaultHasher::new();
|
||||
(seed, i, b"pdfcraft id").hash(&mut h);
|
||||
out.extend_from_slice(&h.finish().to_be_bytes());
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The object number a classic xref subsection really starts at. A common producer bug heads the
|
||||
/// table `1 n` and then writes object 0's free entry (`0000000000 65535 f`) as its first row, so
|
||||
/// every row would be read one number too high and object 1 as free. Such a subsection is read
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use super::xref::XrefEntry;
|
||||
use super::*;
|
||||
use super::{Arc, BTreeMap, CosError, Dict, Document, HashMap, ObjRef, Object, Weak};
|
||||
|
||||
thread_local! {
|
||||
/// The objects being loaded on this thread, innermost last (see `Document::try_get`).
|
||||
|
||||
@@ -1,5 +1,210 @@
|
||||
use super::*;
|
||||
|
||||
/// /DecodeParms given by reference, whole, as array entries or as the numbers inside, are read
|
||||
/// once made direct: here a Flate predictor, which the stream alone doesn't see. Only the entries the filters use are
|
||||
/// resolved, and nothing is for a chain longer than a decoder takes.
|
||||
#[test]
|
||||
fn decode_parms_given_by_reference_are_read_once_direct() {
|
||||
let rows = [1u8, 2, 3, 4, 5, 6, 7, 8];
|
||||
let params = pdfcraft_filters::Params { predictor: 12, colors: 1, bits_per_component: 8, columns: 4, early_change: 1 };
|
||||
let coded = pdfcraft_filters::encode(&pdfcraft_filters::Filter::Flate, ¶ms, &rows).unwrap();
|
||||
let mut parms = Dict::new();
|
||||
parms.set(b"Predictor".to_vec(), Object::Int(12));
|
||||
parms.set(b"Columns".to_vec(), Object::Int(4));
|
||||
let mut doc = Document::new_empty();
|
||||
let r = doc.add(Object::Dict(parms.clone()));
|
||||
let array = doc.add(Object::Array(vec![Object::Ref(r)]));
|
||||
let stream = |filters: usize, p: Object| {
|
||||
let mut d = Dict::new();
|
||||
d.set(b"Filter".to_vec(), Object::Array(vec![Object::name("FlateDecode"); filters]));
|
||||
d.set(b"DecodeParms".to_vec(), p);
|
||||
Stream::from_raw(d, coded.clone())
|
||||
};
|
||||
for p in [Object::Ref(r), Object::Array(vec![Object::Ref(r)]), Object::Ref(array)] {
|
||||
let s = stream(1, p.clone());
|
||||
assert_ne!(s.decoded().unwrap(), rows, "{p:?} read as it is");
|
||||
assert_eq!(doc.with_direct_parms(&s).decoded().unwrap(), rows, "{p:?}");
|
||||
}
|
||||
// A number inside given by reference, which `Dict::int` doesn't follow: in the dictionary
|
||||
// itself, and in an array's entry.
|
||||
let twelve = doc.add(Object::Int(12));
|
||||
let mut inner = parms.clone();
|
||||
inner.set(b"Predictor".to_vec(), Object::Ref(twelve));
|
||||
for p in [Object::Dict(inner.clone()), Object::Array(vec![Object::Dict(inner)])] {
|
||||
let s = stream(1, p.clone());
|
||||
assert_ne!(s.decoded().unwrap(), rows, "{p:?} read as it is");
|
||||
assert_eq!(doc.with_direct_parms(&s).decoded().unwrap(), rows, "{p:?}");
|
||||
}
|
||||
// Only numbers and flags are copied: a key naming a big array, or an entry that is no
|
||||
// dictionary, is left out (a file could name one big object from every key and filter).
|
||||
let big = doc.add(Object::Array(vec![Object::Int(1); 100_000]));
|
||||
let mut hostile = Dict::new();
|
||||
hostile.set(b"Predictor".to_vec(), Object::Ref(big));
|
||||
hostile.set(b"Columns".to_vec(), Object::Ref(big));
|
||||
hostile.set(b"Colors".to_vec(), Object::Ref(twelve));
|
||||
let entry = doc.add(Object::Dict(hostile));
|
||||
let two = stream(2, Object::Array(vec![Object::Ref(entry), Object::Ref(big)]));
|
||||
let made = doc.with_direct_parms(&two);
|
||||
let made = made.dict.get(b"DecodeParms").and_then(Object::as_array).unwrap();
|
||||
let first = made[0].as_dict().unwrap();
|
||||
assert_eq!((first.contains(b"Predictor"), first.contains(b"Columns"), first.int(b"Colors")), (false, false, Some(12)));
|
||||
assert!(matches!(made[1], Object::Null), "{:?}", made[1]);
|
||||
let direct = stream(1, Object::Dict(parms));
|
||||
assert!(matches!(doc.with_direct_parms(&direct), Cow::Borrowed(_)), "nothing to resolve");
|
||||
assert_eq!(direct.decoded().unwrap(), rows);
|
||||
// Entries past the filters' are left out, unresolved; so is everything past the chain limit.
|
||||
let many = stream(1, Object::Array(vec![Object::Ref(r); 1000]));
|
||||
let made = doc.with_direct_parms(&many);
|
||||
assert_eq!(made.dict.get(b"DecodeParms").and_then(Object::as_array).map(Vec::len), Some(1));
|
||||
let long = stream(pdfcraft_filters::MAX_CHAIN + 1, Object::Array(vec![Object::Ref(r); 9]));
|
||||
assert!(matches!(doc.with_direct_parms(&long), Cow::Borrowed(_)));
|
||||
// A chain as long as a decoder takes is resolved, and a `/Crypt` in it doesn't count, as
|
||||
// the decoders leave it out: ASCIIHex as often as the limit allows, then the predictor's
|
||||
// Flate, its parameters by reference.
|
||||
let hex = |b: &[u8]| b.iter().flat_map(|x| format!("{x:02X}").into_bytes()).chain(*b">").collect::<Vec<u8>>();
|
||||
let wrapped = (1..pdfcraft_filters::MAX_CHAIN).fold(coded.clone(), |data, _| hex(&data));
|
||||
for crypt in [false, true] {
|
||||
let mut names = vec![Object::name("ASCIIHexDecode"); pdfcraft_filters::MAX_CHAIN - 1];
|
||||
names.push(Object::name("FlateDecode"));
|
||||
if crypt {
|
||||
names.insert(0, Object::name("Crypt"));
|
||||
}
|
||||
let mut entries = vec![Object::Null; names.len() - 1];
|
||||
entries.push(Object::Ref(r));
|
||||
let mut d = Dict::new();
|
||||
d.set(b"Filter".to_vec(), Object::Array(names));
|
||||
d.set(b"DecodeParms".to_vec(), Object::Array(entries));
|
||||
let s = Stream::from_raw(d, wrapped.clone());
|
||||
assert_eq!(doc.with_direct_parms(&s).decoded().unwrap(), rows, "with /Crypt: {crypt}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A CCITT fax image reads through its /DecodeParms, given directly, in an array or by
|
||||
/// reference (its numbers too), with /BlackIs1, and behind other filters; one whose /Columns
|
||||
/// aren't its /Width is refused, /Height rows are decoded whatever /Rows says, and other images
|
||||
/// decode through their filters.
|
||||
#[test]
|
||||
fn fax_images_decode_with_their_parameters() {
|
||||
// 10 × 3: the first five samples of each row white, the rest black.
|
||||
let bits = [0b1111_1000, 0, 0b1111_1000, 0, 0b1111_1000, 0];
|
||||
let coded = pdfcraft_filters::encode_g4(&bits, 10, 3).unwrap();
|
||||
let mut doc = Document::new_empty();
|
||||
let mut parms = Dict::new();
|
||||
parms.set(b"K".to_vec(), Object::Int(-1));
|
||||
parms.set(b"Columns".to_vec(), Object::Int(10));
|
||||
let indirect = doc.add(Object::Dict(parms.clone()));
|
||||
let image = |doc: &Document, parms: Option<Object>, width: i64, height: i64| {
|
||||
let mut d = Dict::new();
|
||||
d.set(b"Width".to_vec(), Object::Int(width));
|
||||
d.set(b"Height".to_vec(), Object::Int(height));
|
||||
d.set(b"Filter".to_vec(), Object::name("CCITTFaxDecode"));
|
||||
if let Some(p) = parms {
|
||||
d.set(b"DecodeParms".to_vec(), p);
|
||||
}
|
||||
doc.decoded_image(&Stream::from_raw(d, coded.clone()))
|
||||
};
|
||||
for p in [
|
||||
Object::Dict(parms.clone()),
|
||||
Object::Array(vec![Object::Dict(parms.clone())]),
|
||||
Object::Ref(indirect),
|
||||
Object::Array(vec![Object::Ref(indirect)]),
|
||||
] {
|
||||
assert_eq!(image(&doc, Some(p.clone()), 10, 3).unwrap(), bits, "{p:?}");
|
||||
}
|
||||
let mut inverted = parms.clone();
|
||||
inverted.set(b"BlackIs1".to_vec(), Object::Bool(true));
|
||||
assert_eq!(
|
||||
image(&doc, Some(Object::Dict(inverted)), 10, 3).unwrap(),
|
||||
[0b0000_0111, 0b1100_0000, 0b0000_0111, 0b1100_0000, 0b0000_0111, 0b1100_0000]
|
||||
);
|
||||
assert_eq!(image(&doc, Some(Object::Dict(parms.clone())), 10, 2).unwrap(), bits[..4], "at most /Height rows");
|
||||
// Within a bound: no more rows than it holds.
|
||||
let mut bounded = Dict::new();
|
||||
bounded.set(b"Width".to_vec(), Object::Int(10));
|
||||
bounded.set(b"Height".to_vec(), Object::Int(3));
|
||||
bounded.set(b"Filter".to_vec(), Object::name("CCITTFaxDecode"));
|
||||
bounded.set(b"DecodeParms".to_vec(), Object::Dict(parms.clone()));
|
||||
assert_eq!(doc.decoded_image_within(&Stream::from_raw(bounded, coded.clone()), 5).unwrap(), bits[..4], "two rows of two bytes in five");
|
||||
let mut by_reference = Dict::new();
|
||||
by_reference.set(b"K".to_vec(), Object::Ref(doc.add(Object::Int(-1))));
|
||||
by_reference.set(b"Columns".to_vec(), Object::Ref(doc.add(Object::Int(10))));
|
||||
assert_eq!(image(&doc, Some(Object::Dict(by_reference)), 10, 3).unwrap(), bits, "/K and /Columns by reference");
|
||||
let mut understated = parms.clone();
|
||||
understated.set(b"Rows".to_vec(), Object::Int(1));
|
||||
assert_eq!(image(&doc, Some(Object::Dict(understated.clone())), 10, 3).unwrap(), bits, "/Height rows, whatever /Rows says");
|
||||
// The parameters as the file gives them, /Rows included, and Table 11's defaults.
|
||||
let mut d = Dict::new();
|
||||
d.set(b"Filter".to_vec(), Object::name("CCITTFaxDecode"));
|
||||
d.set(b"DecodeParms".to_vec(), Object::Dict(understated));
|
||||
let p = doc.fax_params(&Stream::from_raw(d.clone(), Vec::new())).unwrap();
|
||||
assert_eq!((p.k, p.columns, p.rows, p.end_of_block, p.black_is_1), (-1, 10, 1, true, false));
|
||||
d.set(b"Filter".to_vec(), Object::name("FlateDecode"));
|
||||
assert!(doc.fax_params(&Stream::from_raw(d, Vec::new())).is_none(), "not a fax image");
|
||||
assert!(matches!(image(&doc, Some(Object::Dict(parms.clone())), 12, 3), Err(CosError::Filter(_))), "/Columns other than /Width");
|
||||
assert!(matches!(image(&doc, None, 10, 3), Err(CosError::Filter(_))), "the default 1728 /Columns");
|
||||
let mut plain = Dict::new();
|
||||
plain.set(b"Filter".to_vec(), Object::name("FlateDecode"));
|
||||
assert_eq!(doc.decoded_image(&Stream::from_raw(plain, pdfcraft_filters::encode_flate(&bits))).unwrap(), bits);
|
||||
|
||||
// Behind other filters, its parameters at its own place in the array (/Crypt counts).
|
||||
let behind = |filters: &[Object], parms: &[Object], data: Vec<u8>| {
|
||||
let mut d = Dict::new();
|
||||
d.set(b"Width".to_vec(), Object::Int(10));
|
||||
d.set(b"Height".to_vec(), Object::Int(3));
|
||||
d.set(b"Filter".to_vec(), Object::Array(filters.to_vec()));
|
||||
d.set(b"DecodeParms".to_vec(), Object::Array(parms.to_vec()));
|
||||
doc.decoded_image(&Stream::from_raw(d, data))
|
||||
};
|
||||
let (fax, null, own) = (Object::name("CCITTFaxDecode"), Object::Null, Object::Dict(parms.clone()));
|
||||
let hex = coded.iter().map(|b| format!("{b:02x}")).chain([">".to_string()]).collect::<String>().into_bytes();
|
||||
let flated = pdfcraft_filters::encode_flate(&coded);
|
||||
let ahx = [Object::name("AHx"), fax.clone()];
|
||||
assert_eq!(behind(&ahx, &[null.clone(), Object::Ref(indirect)], hex.clone()).unwrap(), bits, "behind ASCIIHexDecode");
|
||||
assert_eq!(
|
||||
behind(&[Object::name("FlateDecode"), Object::name("CCF")], &[null.clone(), own.clone()], flated.clone()).unwrap(),
|
||||
bits,
|
||||
"behind Flate"
|
||||
);
|
||||
assert_eq!(behind(&[Object::name("Crypt"), fax.clone()], &[null.clone(), own.clone()], coded.clone()).unwrap(), bits, "after /Crypt");
|
||||
// A /Crypt belongs first (§7.4.10); one after the fax filter leaves it its own entry.
|
||||
assert_eq!(behind(&[fax.clone(), Object::name("Crypt")], &[own.clone(), null.clone()], coded.clone()).unwrap(), bits, "before /Crypt");
|
||||
assert!(behind(&ahx, &[own.clone(), null.clone()], hex).is_err(), "the first entry is the other filter's");
|
||||
assert!(behind(&[fax.clone(), Object::name("FlateDecode")], &[own.clone(), null.clone()], flated).is_err(), "CCITT, then Flate");
|
||||
assert!(behind(&[Object::Int(5), fax], &[null, own], coded.clone()).is_err(), "a /Filter entry that isn't a name");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_missing_file_id_is_derived_from_the_encryption_seed() {
|
||||
let mut doc = Document::new_empty();
|
||||
let seed = [9u8; 32];
|
||||
doc.set_encryption(&pdfcraft_crypt::NewEncryption {
|
||||
algorithm: pdfcraft_crypt::Algorithm::Aes256,
|
||||
user_password: "user",
|
||||
owner_password: "owner",
|
||||
permissions: -4,
|
||||
encrypt_metadata: true,
|
||||
seed,
|
||||
})
|
||||
.unwrap();
|
||||
let id = doc.trailer().get(b"ID").and_then(|o| o.as_array()).and_then(|a| a.first()).and_then(|o| o.as_string()).map(|s| s.bytes.clone());
|
||||
assert_eq!(id.as_deref(), Some(pdfcraft_crypt::file_id(&seed).as_slice()));
|
||||
|
||||
let mut kept = Document::new_empty();
|
||||
let fixed = Object::String(crate::PdfString { bytes: b"0123456789abcdef".to_vec(), hex: true });
|
||||
kept.trailer_mut().set(b"ID".to_vec(), Object::Array(vec![fixed.clone(), fixed]));
|
||||
kept.set_encryption(&pdfcraft_crypt::NewEncryption {
|
||||
algorithm: pdfcraft_crypt::Algorithm::Aes256,
|
||||
user_password: "user",
|
||||
owner_password: "owner",
|
||||
permissions: -4,
|
||||
encrypt_metadata: true,
|
||||
seed,
|
||||
})
|
||||
.unwrap();
|
||||
let still = kept.trailer().get(b"ID").and_then(|o| o.as_array()).and_then(|a| a.first()).and_then(|o| o.as_string()).map(|s| s.bytes.clone());
|
||||
assert_eq!(still.as_deref(), Some(b"0123456789abcdef".as_slice()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_read_state_matches_a_clone_and_no_changed_document() {
|
||||
let mut doc = Document::new_empty();
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use super::*;
|
||||
use super::{Arc, BTreeMap, Lexer};
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum XrefEntry {
|
||||
|
||||
@@ -261,7 +261,7 @@ impl Stream {
|
||||
/// [`Stream::filters`], or an error when `/Filter` is present but is not a name or an
|
||||
/// array of names (an indirect reference, say): the data is not unfiltered, so it must not
|
||||
/// read as decoded.
|
||||
fn readable_filters(&self) -> Result<Vec<(Filter, Params)>, pdfcraft_filters::FilterError> {
|
||||
pub(crate) fn readable_filters(&self) -> Result<Vec<(Filter, Params)>, pdfcraft_filters::FilterError> {
|
||||
let readable = match self.dict.get(b"Filter") {
|
||||
None | Some(Object::Null | Object::Name(_)) => true,
|
||||
Some(Object::Array(a)) => a.iter().all(|f| f.as_name().is_some()),
|
||||
|
||||
@@ -10,8 +10,13 @@ workspace = true
|
||||
|
||||
[dependencies]
|
||||
pdfcraft-cos = { workspace = true }
|
||||
pdfcraft-filters = { workspace = true }
|
||||
pdfcraft-model = { workspace = true }
|
||||
pdfcraft-fonts = { workspace = true }
|
||||
# For `image::bmp_with_pixel_offset`, shared with XFA pictures.
|
||||
pdfcraft-xfa = { workspace = true }
|
||||
# Already in the graph through hayro: decodes JBIG2 images for Export ▸ Images.
|
||||
hayro-jbig2.workspace = true
|
||||
png = "0.18"
|
||||
tiff = "0.11"
|
||||
image = { version = "0.25", default-features = false, features = ["bmp", "gif", "jpeg"] }
|
||||
@@ -22,5 +27,8 @@ thiserror = { workspace = true }
|
||||
encoding_rs = "0.8"
|
||||
|
||||
[dev-dependencies]
|
||||
# An independent CCITT decoder, to check Create PDF's Group 4 images.
|
||||
hayro-ccitt.workspace = true
|
||||
image = { version = "0.25", default-features = false, features = ["bmp", "gif", "jpeg"] }
|
||||
hayro-syntax = { workspace = true }
|
||||
pdfcraft-filters = { workspace = true }
|
||||
@@ -6,7 +6,9 @@ Layer L4. Create a PDF (Acrobat's Create a PDF tool), execution plan M10.2:
|
||||
- `from_images(&[(name, bytes)])`: one page per image, sized from the image's resolution
|
||||
(PNG `pHYs`, JPEG JFIF density; 72 dpi when absent). JPEG data is embedded as is
|
||||
(`/DCTDecode`, grey, RGB or Adobe-inverted CMYK); PNG is decoded and stored with Flate,
|
||||
with transparency as a soft mask. An ICC profile in the file (JPEG `APP2 ICC_PROFILE`, PNG
|
||||
with transparency as a soft mask. A picture of only pure black and white (a 1-bit PNG or TIFF,
|
||||
eight-bit grey, a two-colour palette, RGB without a profile) is stored at one bit per pixel, as
|
||||
CCITT Group 4 or Flate, whichever is smaller as stored (`pdfcraft_filters::encode_g4`). An ICC profile in the file (JPEG `APP2 ICC_PROFILE`, PNG
|
||||
`iCCP`) that matches the image's colour space is kept as an `/ICCBased` colour space with
|
||||
the device space as `/Alternate`; images with the same profile share one profile object.
|
||||
JPEG metadata scanning skips marker fill bytes and reads application segments after the
|
||||
@@ -25,9 +27,20 @@ Layer L4. Create a PDF (Acrobat's Create a PDF tool), execution plan M10.2:
|
||||
Every function returns a `pdfcraft_cos::Document`; the caller writes it.
|
||||
|
||||
Image export and Save Image As apply each lossless image's Decode pair before converting its color components.
|
||||
JBIG2 images and masks (JBIG2 as their only filter) are decoded with `hayro-jbig2`, their `/JBIG2Globals` included,
|
||||
as `JBIG2Decode` gives them: black as 0. An image whose JBIG2 page has another width than the image, or more
|
||||
pixels than an exported image may have, or whose globals decode to more than 32 MiB (they are decoded before the
|
||||
page's size is known, so they have a limit of their own), is skipped; such a mask is left out and the image
|
||||
exported opaque, as JPX and CCITT masks are.
|
||||
Indexed Decode values select palette entries after rounding and clipping. Color-key masks compare the original samples.
|
||||
Missing, null or malformed Decode arrays keep the default mapping.
|
||||
Soft-mask Decode intervals map samples to opacity before the mask is resized, including reversed ranges and indirect entries.
|
||||
The existing 16-bit path still uses each sample's high byte.
|
||||
JPEG image Decode handling remains limited.
|
||||
ICC transforms and calibrated color conversion remain outside this export path.
|
||||
CCITT fax images (Group 3 and 4) are decoded for export through `pdfcraft_cos::Document::decoded_image` with their
|
||||
`/DecodeParms` (`/Columns` has to be the image's width; up to `/Height` rows, whatever `/Rows` says), behind other filters such as
|
||||
`ASCII85Decode` too. Byte-aligned Group 3 rows are read by their end-of-line codes, whether the fill starts each code on a byte or
|
||||
ends it on one, when the data starts with one (T.4 sends one before the first row), and on bytes otherwise, whatever `/EndOfLine`
|
||||
says; data that comes up short is reported. Data with codes but none before the first row is read on bytes, and is reported or,
|
||||
at `/K 0`, may come out wrong. JPEG 2000 and JBIG2 images are still reported, not exported.
|
||||
@@ -1,7 +1,7 @@
|
||||
//! Export a PDF ▸ Image ▸ Export all images, and Edit ▸ Save image as: the images that pages
|
||||
//! use, as files. JPEG images are written unchanged; other images, and JPEG images with
|
||||
//! transparency or with CMYK samples a viewer would read inverted, are decoded and written as PNG with their soft mask, stencil mask or colour
|
||||
//! key as alpha. Images PdfCraft can't decode yet (JPEG 2000, JBIG2, CCITT, separations) are
|
||||
//! key as alpha. Images PdfCraft can't decode yet (JPEG 2000, separations) are
|
||||
//! reported, never silently left out.
|
||||
|
||||
use std::collections::HashSet;
|
||||
@@ -100,6 +100,116 @@ fn filters(s: &Stream) -> Vec<Vec<u8>> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The samples of image `s`, decoded: through its filters, with a `/DecodeParms` dictionary given
|
||||
/// by reference, or as an array's entry, or with numbers inside by reference, read too (a predictor
|
||||
/// given so would otherwise be lost), or, for a JBIG2 image
|
||||
/// (its only filter), through a JBIG2 decoder with its `/JBIG2Globals`, as rows of one-bit samples
|
||||
/// each starting on a byte, with black as 0, as `JBIG2Decode` gives them (ISO 32000-2 §7.4.7).
|
||||
fn decoded(doc: &Document, s: &Stream) -> Result<Vec<u8>, String> {
|
||||
match filters(s).as_slice() {
|
||||
[f] if f == b"JBIG2Decode" => jbig2(doc, s),
|
||||
_ => doc.decoded_image(s).map_err(|e| e.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The `/DecodeParms` of a stream with one filter: a dictionary, or the one in an array (7.4.2).
|
||||
fn decode_parms(doc: &Document, s: &Stream) -> Dict {
|
||||
let Some(p) = s.dict.get(b"DecodeParms").map(|p| doc.resolve(p)) else { return Dict::default() };
|
||||
let p = match &*p {
|
||||
Object::Array(a) => match a.first() {
|
||||
Some(first) => doc.resolve(first),
|
||||
None => return Dict::default(),
|
||||
},
|
||||
_ => p,
|
||||
};
|
||||
p.as_dict().cloned().unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The most an image's `/JBIG2Globals` decode to: the symbol and pattern dictionaries an encoder
|
||||
/// shares between pages, themselves coded, so far less than any stream may decode to
|
||||
/// ([`pdfcraft_cos::MAX_DECODED`], 1 GiB). Globals past it refuse the image.
|
||||
const MAX_GLOBALS: usize = 32 << 20;
|
||||
|
||||
/// [`decoded`] for a JBIG2 image. Its JBIG2 page has to be the image's width, which the caller
|
||||
/// checked against the export's size limit, and within that limit itself: the decoder decodes the
|
||||
/// whole page, rows past the image's height too, so a small `/Height` over a far taller page
|
||||
/// would cost more than the limit allows. Rows past the image's height are dropped, and too few
|
||||
/// rows are refused by the caller. Globals that can't be read refuse the image, rather than
|
||||
/// decoding it without them. They are decoded before the page's size is known, so the page's
|
||||
/// limit can't bound them; they have [`MAX_GLOBALS`] of their own.
|
||||
fn jbig2(doc: &Document, s: &Stream) -> Result<Vec<u8>, String> {
|
||||
let globals = match decode_parms(doc, s).get(b"JBIG2Globals").map(|g| doc.resolve(g)).as_deref() {
|
||||
Some(Object::Stream(g)) => {
|
||||
Some(doc.with_direct_parms(g).decoded_within(MAX_GLOBALS).map_err(|e| format!("the JBIG2 globals can't be read: {e}"))?)
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
let image = hayro_jbig2::Image::new_embedded(&s.raw, globals.as_deref()).map_err(|e| format!("the JBIG2 image can't be read: {e}"))?;
|
||||
if s.dict.int(b"Width") != Some(i64::from(image.width())) {
|
||||
return Err("the JBIG2 image's width isn't the image's width".into());
|
||||
}
|
||||
if u64::from(image.width()).saturating_mul(u64::from(image.height())) > MAX_PIXELS {
|
||||
return Err(format!("the JBIG2 page, {} × {}, is too large to export", image.width(), image.height()));
|
||||
}
|
||||
let height = s.dict.int(b"Height").and_then(|h| usize::try_from(h).ok()).unwrap_or(0);
|
||||
let mut rows = Rows::new(image.width() as usize, height);
|
||||
image.decode(&mut rows).map_err(|e| format!("the JBIG2 image can't be decoded: {e}"))?;
|
||||
Ok(rows.out)
|
||||
}
|
||||
|
||||
/// Rows of one-bit samples, each starting on a byte, filled from a decoder's pixels: `columns`
|
||||
/// a row and at most `rows` rows. Pixels past a row's end and rows past the last are dropped, so
|
||||
/// the output is bounded by the size the caller gave.
|
||||
struct Rows {
|
||||
out: Vec<u8>,
|
||||
row: Vec<u8>,
|
||||
x: usize,
|
||||
columns: usize,
|
||||
rows: usize,
|
||||
done: usize,
|
||||
}
|
||||
|
||||
impl Rows {
|
||||
fn new(columns: usize, rows: usize) -> Self {
|
||||
Rows { out: Vec::new(), row: vec![0; columns.div_ceil(8)], x: 0, columns, rows, done: 0 }
|
||||
}
|
||||
|
||||
/// `count` pixels, as 1 samples when `one`.
|
||||
fn push(&mut self, one: bool, count: usize) {
|
||||
let end = self.x.saturating_add(count);
|
||||
if one {
|
||||
for x in self.x..end.min(self.columns) {
|
||||
if let Some(b) = self.row.get_mut(x / 8) {
|
||||
*b |= 0x80 >> (x % 8);
|
||||
}
|
||||
}
|
||||
}
|
||||
self.x = end;
|
||||
}
|
||||
|
||||
fn end_row(&mut self) {
|
||||
if self.done < self.rows {
|
||||
self.out.extend_from_slice(&self.row);
|
||||
self.done += 1;
|
||||
}
|
||||
self.row.fill(0);
|
||||
self.x = 0;
|
||||
}
|
||||
}
|
||||
|
||||
/// JBIG2 codes black as 1, which `JBIG2Decode` gives as 0.
|
||||
impl hayro_jbig2::Decoder for Rows {
|
||||
fn push_pixel(&mut self, black: bool) {
|
||||
self.push(!black, 1);
|
||||
}
|
||||
fn push_pixel_chunk(&mut self, black: bool, chunks: u32) {
|
||||
self.push(!black, (chunks as usize).saturating_mul(8));
|
||||
}
|
||||
fn next_line(&mut self) {
|
||||
self.end_row();
|
||||
}
|
||||
}
|
||||
|
||||
/// The file for one image: its JPEG data as is, or a PNG. An image with transparency (a soft
|
||||
/// mask, a stencil `/Mask` or a colour-key `/Mask`) is always a PNG with that transparency as
|
||||
/// alpha, JPEG images included, so cut-out images keep their transparent background.
|
||||
@@ -108,8 +218,7 @@ fn image(doc: &Document, s: &Stream) -> Result<(&'static str, Vec<u8>), String>
|
||||
let jpeg = matches!(f.last().map(Vec::as_slice), Some(b"DCTDecode" | b"DCT")) && f.len() == 1;
|
||||
match f.last().map(Vec::as_slice) {
|
||||
Some(b"JPXDecode") => return Err("JPEG 2000 images can't be exported yet".into()),
|
||||
Some(b"JBIG2Decode") => return Err("JBIG2 images can't be exported yet".into()),
|
||||
Some(b"CCITTFaxDecode" | b"CCF") => return Err("CCITT fax images can't be exported yet".into()),
|
||||
Some(b"JBIG2Decode") if f.len() > 1 => return Err("JBIG2 images inside other filters can't be exported yet".into()),
|
||||
Some(b"DCTDecode" | b"DCT") if !jpeg => return Err("JPEG images inside other filters can't be exported yet".into()),
|
||||
_ => {}
|
||||
}
|
||||
@@ -148,7 +257,7 @@ fn image(doc: &Document, s: &Stream) -> Result<(&'static str, Vec<u8>), String>
|
||||
space = decoded;
|
||||
(samples, 8)
|
||||
} else {
|
||||
let data = s.decoded().map_err(|e| e.to_string())?;
|
||||
let data = decoded(doc, s)?;
|
||||
let bpc = if mask { 1 } else { s.dict.int(b"BitsPerComponent").unwrap_or(8) };
|
||||
let bpc = match bpc {
|
||||
1 => 1,
|
||||
@@ -403,9 +512,11 @@ 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(),
|
||||
Some(Object::Stream(t)) => {
|
||||
t.decoded_within(MAX_LOOKUP).map_err(|_| "an indexed colour space with an oversized or damaged lookup table".to_string())?
|
||||
}
|
||||
// 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())?,
|
||||
_ => return Err("an indexed colour space without a lookup table".into()),
|
||||
};
|
||||
Ok(Space::Indexed(Box::new(base), hival, table))
|
||||
@@ -466,7 +577,7 @@ fn stencil_mask(doc: &Document, s: &Stream, w: usize, h: usize) -> Option<Vec<u8
|
||||
}
|
||||
|
||||
/// A one-component mask image as 8-bit values (its `/Decode` interval applied), scaled to
|
||||
/// `w` × `h`. `None` when it can't be decoded (JPEG 2000, JBIG2 and CCITT masks).
|
||||
/// `w` × `h`. `None` when it can't be decoded (JPEG 2000 masks).
|
||||
fn gray_plane(doc: &Document, m: &Stream, w: usize, h: usize) -> Option<Vec<u8>> {
|
||||
let (mw, mh) = size(m.dict.int(b"Width")?, m.dict.int(b"Height")?)?;
|
||||
let stencil = m.dict.get(b"ImageMask").is_some_and(|v| matches!(&*doc.resolve(v), Object::Bool(true)));
|
||||
@@ -476,7 +587,7 @@ fn gray_plane(doc: &Document, m: &Stream, w: usize, h: usize) -> Option<Vec<u8>>
|
||||
let img = image::load_from_memory_with_format(&m.raw, image::ImageFormat::Jpeg).ok()?.into_luma8();
|
||||
(img.width() as usize == mw && img.height() as usize == mh).then(|| img.into_raw())?
|
||||
}
|
||||
Some(b"DCTDecode" | b"DCT" | b"JPXDecode" | b"JBIG2Decode" | b"CCITTFaxDecode" | b"CCF") => return None,
|
||||
Some(b"DCTDecode" | b"DCT" | b"JPXDecode") => return None,
|
||||
_ => {
|
||||
let bpc = if stencil { 1 } else { m.dict.int(b"BitsPerComponent").unwrap_or(8) };
|
||||
let bpc = match bpc {
|
||||
@@ -488,7 +599,7 @@ fn gray_plane(doc: &Document, m: &Stream, w: usize, h: usize) -> Option<Vec<u8>>
|
||||
_ => return None,
|
||||
};
|
||||
let max = (1u32 << bpc.min(8)) - 1;
|
||||
unpack(&m.decoded().ok()?, mw, mh, 1, bpc)?.into_iter().map(|v| (v as u32 * 255 / max) as u8).collect()
|
||||
unpack(&decoded(doc, m).ok()?, mw, mh, 1, bpc)?.into_iter().map(|v| (v as u32 * 255 / max) as u8).collect()
|
||||
}
|
||||
};
|
||||
if let Some([lo, hi]) = decode(doc, m, 1).and_then(|pairs| pairs.first().copied()) {
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
|
||||
use pdfcraft_cos::{Dict, Document, ObjRef, Object, PdfString, Stream};
|
||||
use pdfcraft_cos::{Dict, Document, ObjRef, Object, PdfString, Stream, serialize};
|
||||
|
||||
mod extract;
|
||||
mod upright_image;
|
||||
@@ -108,9 +108,42 @@ fn jpeg_icc(mut chunks: Vec<(u8, u8, &[u8])>) -> Option<Vec<u8>> {
|
||||
complete.then(|| chunks.iter().flat_map(|c| c.2.iter().copied()).collect())
|
||||
}
|
||||
|
||||
/// The samples of a black-and-white image packed one bit per pixel (1 for white, each row
|
||||
/// starting on a byte): eight-bit grey (`n` 1) or RGB (`n` 3) whose every pixel is pure black or
|
||||
/// pure white, or one-bit grey, already packed (a bilevel TIFF). `None` for anything else, found
|
||||
/// at its first other pixel.
|
||||
fn bilevel(data: &[u8], (w, h): (u32, u32), n: usize, bits: Option<i64>) -> Option<Vec<u8>> {
|
||||
let (w, h) = (usize::try_from(w).ok()?, usize::try_from(h).ok()?);
|
||||
let stride = w.div_ceil(8);
|
||||
let size = stride.checked_mul(h)?;
|
||||
match (bits, n) {
|
||||
(Some(1), 1) => data.get(..size).map(<[u8]>::to_vec),
|
||||
(Some(8), 1 | 3) if w > 0 => {
|
||||
let samples = data.get(..w.checked_mul(h)?.checked_mul(n)?)?;
|
||||
let mut packed = vec![0u8; size];
|
||||
for (i, px) in samples.chunks_exact(n).enumerate() {
|
||||
let white = match px {
|
||||
[0] | [0, 0, 0] => false,
|
||||
[255] | [255, 255, 255] => true,
|
||||
_ => return None,
|
||||
};
|
||||
if white && let Some(b) = packed.get_mut((i / w) * stride + (i % w) / 8) {
|
||||
*b |= 0x80 >> (i % w % 8);
|
||||
}
|
||||
}
|
||||
Some(packed)
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Add `img` to `doc` as an image XObject. An ICC profile becomes an `/ICCBased` colour space
|
||||
/// (with the device space as `/Alternate`); `profiles` shares one object between images that
|
||||
/// carry the same profile.
|
||||
///
|
||||
/// A black-and-white image is stored at one bit per pixel, as CCITT Group 4 when that is smaller
|
||||
/// than Flate: losslessly, and several times smaller than the eight bits a scan saved as a 1-bit
|
||||
/// PNG decodes to. RGB keeps its colour space when it has a colour profile.
|
||||
fn add_image(doc: &mut Document, img: Embedded, profiles: &mut Vec<(Vec<u8>, ObjRef)>) -> ObjRef {
|
||||
let mut d = img.dict;
|
||||
d.set(b"Type".to_vec(), Object::name("XObject"));
|
||||
@@ -118,12 +151,48 @@ fn add_image(doc: &mut Document, img: Embedded, profiles: &mut Vec<(Vec<u8>, Obj
|
||||
d.set(b"Width".to_vec(), Object::Int(img.px.0 as i64));
|
||||
d.set(b"Height".to_vec(), Object::Int(img.px.1 as i64));
|
||||
let device = d.name(b"ColorSpace").map(<[u8]>::to_vec);
|
||||
let n = match device.as_deref() {
|
||||
let mut n = match device.as_deref() {
|
||||
Some(b"DeviceGray") => 1,
|
||||
Some(b"DeviceRGB") => 3,
|
||||
Some(b"DeviceCMYK") => 4,
|
||||
_ => 0,
|
||||
};
|
||||
let (mut data, mut filtered) = (img.data, img.filtered);
|
||||
let profiled_rgb = n == 3 && img.icc.is_some();
|
||||
if !filtered
|
||||
&& !profiled_rgb
|
||||
&& let Some(packed) = bilevel(&data, img.px, n, d.int(b"BitsPerComponent"))
|
||||
{
|
||||
if n == 3 {
|
||||
d.set(b"ColorSpace".to_vec(), Object::name("DeviceGray"));
|
||||
n = 1;
|
||||
}
|
||||
d.set(b"BitsPerComponent".to_vec(), Object::Int(1));
|
||||
// The smaller as stored, dictionary included: Group 4's parameters outweigh its saving on
|
||||
// a tiny image.
|
||||
let stored = |d: &Dict, data: &[u8]| {
|
||||
let mut out = Vec::new();
|
||||
serialize(&Object::Dict(d.clone()), &mut out);
|
||||
out.len().saturating_add(data.len())
|
||||
};
|
||||
let mut flate_dict = d.clone();
|
||||
flate_dict.set(b"Filter".to_vec(), Object::name("FlateDecode"));
|
||||
let flate = pdfcraft_filters::encode_flate(&packed);
|
||||
(d, data) = match pdfcraft_filters::encode_g4(&packed, img.px.0, img.px.1) {
|
||||
Ok(g4) => {
|
||||
let mut parms = Dict::new();
|
||||
parms.set(b"K".to_vec(), Object::Int(-1));
|
||||
parms.set(b"Columns".to_vec(), Object::Int(i64::from(img.px.0)));
|
||||
parms.set(b"Rows".to_vec(), Object::Int(i64::from(img.px.1)));
|
||||
let mut g4_dict = d.clone();
|
||||
g4_dict.set(b"Filter".to_vec(), Object::name("CCITTFaxDecode"));
|
||||
g4_dict.set(b"DecodeParms".to_vec(), Object::Dict(parms));
|
||||
if stored(&g4_dict, &g4) < stored(&flate_dict, &flate) { (g4_dict, g4) } else { (flate_dict, flate) }
|
||||
}
|
||||
Err(_) => (flate_dict, flate),
|
||||
};
|
||||
filtered = true;
|
||||
}
|
||||
if let (Some(icc), Some(device)) = (img.icc.and_then(|p| icc_for(p, n)), device) {
|
||||
let r = match profiles.iter().find(|(p, _)| *p == icc) {
|
||||
Some((_, r)) => *r,
|
||||
@@ -142,7 +211,7 @@ fn add_image(doc: &mut Document, img: Embedded, profiles: &mut Vec<(Vec<u8>, Obj
|
||||
let mr = doc.add(Object::Stream(Stream::flate(m, &alpha)));
|
||||
d.set(b"SMask".to_vec(), Object::Ref(mr));
|
||||
}
|
||||
let stream = if img.filtered { Stream::from_raw(d, img.data) } else { Stream::flate(d, &img.data) };
|
||||
let stream = if filtered { Stream::from_raw(d, data) } else { Stream::flate(d, &data) };
|
||||
doc.add(Object::Stream(stream))
|
||||
}
|
||||
|
||||
@@ -562,7 +631,7 @@ fn embed(name: &str, bytes: &[u8], wanted: usize) -> Result<Vec<Embedded>, Creat
|
||||
} else if is_tiff(bytes) {
|
||||
tiff_pages(name, bytes, wanted)
|
||||
} else if bytes.starts_with(b"BM") {
|
||||
Ok(vec![decoded(name, bytes, image::ImageFormat::Bmp)?])
|
||||
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 bytes.starts_with(JP2_SIGNATURE) || bytes.starts_with(&[0xFF, 0x4F, 0xFF, 0x51]) {
|
||||
|
||||
@@ -186,7 +186,7 @@ fn bmp_gif_and_multi_page_tiff_images() {
|
||||
let mut enc = image::codecs::gif::GifEncoder::new(&mut gif);
|
||||
enc.encode(img.as_raw(), 2, 2, image::ExtendedColorType::Rgba8).unwrap();
|
||||
}
|
||||
// TIFF: two pages, an 8-bit gray one at 144 dpi and a 1-bit one.
|
||||
// TIFF: two 8-bit gray pages, one at 144 dpi and one of only black and white.
|
||||
let mut tif = std::io::Cursor::new(Vec::new());
|
||||
{
|
||||
let mut enc = tiff::encoder::TiffEncoder::new(&mut tif).unwrap();
|
||||
@@ -206,6 +206,26 @@ fn bmp_gif_and_multi_page_tiff_images() {
|
||||
assert!(matches!(from_images(&[("x.webp".into(), b"RIFF0000WEBP".to_vec())]), Err(CreateError::Image(..))));
|
||||
}
|
||||
|
||||
/// #4937: a BMP whose header gives the pixel data's offset as 0 is placed as the same image as
|
||||
/// the intact file, not shifted by the header bytes.
|
||||
#[test]
|
||||
fn a_bmp_with_a_zero_pixel_offset_is_placed_like_the_intact_file() {
|
||||
use image::ImageEncoder;
|
||||
let mut bmp = Vec::new();
|
||||
let pixels: Vec<u8> = (0..18).map(|i| i * 13).collect();
|
||||
image::codecs::bmp::BmpEncoder::new(&mut bmp).write_image(&pixels, 3, 2, image::ExtendedColorType::Rgb8).unwrap();
|
||||
let mut zero = bmp.clone();
|
||||
zero[10..14].copy_from_slice(&0u32.to_le_bytes());
|
||||
let samples = |data: Vec<u8>| {
|
||||
let doc = reopen(&from_images(&[("a.bmp".into(), data)]).unwrap());
|
||||
let res = doc.resolve(pages(&doc)[0].get(b"Resources").unwrap()).as_dict().cloned().unwrap();
|
||||
let xo = doc.resolve(res.get(b"XObject").unwrap()).as_dict().cloned().unwrap();
|
||||
let Object::Stream(s) = &*doc.resolve(xo.get(b"Im0").unwrap()) else { panic!("not an image") };
|
||||
s.decoded().unwrap()
|
||||
};
|
||||
assert_eq!(samples(zero), samples(bmp));
|
||||
}
|
||||
|
||||
/// #665 lifted the tiff crate's 256 MiB decode limit; a few bytes claiming a 60000x60000 page
|
||||
/// (3.6 GB of gray pixels) must still be refused, not allocated.
|
||||
#[test]
|
||||
@@ -1275,6 +1295,48 @@ fn a_cyclic_indexed_colour_space_is_refused() {
|
||||
assert_eq!(out.skipped.len(), 1, "{:?}", out.skipped);
|
||||
}
|
||||
|
||||
/// A baseline TIFF of one uncompressed strip of 1-bit samples, `packed` rows each starting on a
|
||||
/// byte, 0 for black (BlackIsZero; TIFF 6.0, section 3): the `tiff` crate writes no 1-bit images.
|
||||
fn one_bit_tiff(w: u32, h: u32, packed: &[u8]) -> Vec<u8> {
|
||||
// Tag, type (3 SHORT, 4 LONG), value; the strip follows the IFD.
|
||||
let entries: [(u16, u16, u32); 8] =
|
||||
[(256, 4, w), (257, 4, h), (258, 3, 1), (259, 3, 1), (262, 3, 1), (273, 4, 0), (278, 4, h), (279, 4, packed.len() as u32)];
|
||||
let strip = 8 + 2 + entries.len() as u32 * 12 + 4;
|
||||
let mut out = b"II*\0".to_vec();
|
||||
out.extend(8u32.to_le_bytes());
|
||||
out.extend((entries.len() as u16).to_le_bytes());
|
||||
for (tag, kind, value) in entries {
|
||||
let value = if tag == 273 { strip } else { value };
|
||||
out.extend(tag.to_le_bytes());
|
||||
out.extend(kind.to_le_bytes());
|
||||
out.extend(1u32.to_le_bytes());
|
||||
match kind {
|
||||
3 => out.extend((value as u16).to_le_bytes().into_iter().chain([0, 0])),
|
||||
_ => out.extend(value.to_le_bytes()),
|
||||
}
|
||||
}
|
||||
out.extend(0u32.to_le_bytes());
|
||||
out.extend_from_slice(packed);
|
||||
out
|
||||
}
|
||||
|
||||
/// A bilevel TIFF (one bit a sample) stays one bit, stored as Group 4 when that is smaller, and
|
||||
/// exports as its picture.
|
||||
#[test]
|
||||
fn a_one_bit_tiff_is_stored_as_group_4() {
|
||||
let (w, h) = (1200u32, 240u32);
|
||||
let bits = strokes(w, h);
|
||||
let stride = (w as usize).div_ceil(8);
|
||||
let picture: Vec<bool> =
|
||||
(0..(w * h) as usize).map(|i| bits[i / w as usize * stride + i % w as usize / 8] & (0x80 >> (i % w as usize % 8)) != 0).collect();
|
||||
let doc = from_images(&[("scan.tif".into(), one_bit_tiff(w, h, &bits))]).unwrap();
|
||||
let im = image_of(&doc, 0);
|
||||
assert_eq!((im.int(b"BitsPerComponent"), im.name(b"Filter")), (Some(1), Some(&b"CCITTFaxDecode"[..])));
|
||||
let out = extract_images(&doc, &[0], 0);
|
||||
assert!(out.skipped.is_empty(), "{:?}", out.skipped);
|
||||
assert_eq!(exported_white(&out.images[0].data), picture);
|
||||
}
|
||||
|
||||
/// A TIFF of `pages` 64×64 gray pages, then (with `unreadable`) one whose samples Create can't read.
|
||||
fn gray_tiff(pages: usize, unreadable: bool) -> Vec<u8> {
|
||||
let mut tif = std::io::Cursor::new(Vec::new());
|
||||
@@ -1318,3 +1380,832 @@ fn a_tiny_gif_on_a_huge_screen_is_refused() {
|
||||
let doc = reopen(&from_images(&[("small.gif".into(), gif_on_screen(40, 30))]).unwrap());
|
||||
assert_eq!(media(&pages(&doc)[0]), [0.0, 0.0, 40.0, 30.0]);
|
||||
}
|
||||
|
||||
/// A PNG of `w` × `h` samples `data` in `color` at `depth`, with a palette or an ICC profile.
|
||||
fn png_of(w: u32, h: u32, color: png::ColorType, depth: png::BitDepth, data: &[u8], palette: Option<Vec<u8>>, icc: Option<Vec<u8>>) -> Vec<u8> {
|
||||
let mut out = Vec::new();
|
||||
{
|
||||
let mut info = png::Info::with_size(w, h);
|
||||
info.color_type = color;
|
||||
info.bit_depth = depth;
|
||||
info.palette = palette.map(Into::into);
|
||||
info.icc_profile = icc.map(Into::into);
|
||||
let mut writer = png::Encoder::with_info(&mut out, info).unwrap().write_header().unwrap();
|
||||
writer.write_image_data(data).unwrap();
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Rows of `w` one-bit samples (1 white), each on a new byte: lines of glyphs drawn from a few
|
||||
/// shapes at uneven spacing, whose edges move a pixel now and then, as a scan of text has them.
|
||||
/// (Clean, evenly spaced strokes favour Flate over Group 4.)
|
||||
fn strokes(w: u32, h: u32) -> Vec<u8> {
|
||||
let stride = (w as usize).div_ceil(8);
|
||||
let mut data = vec![0xFF; stride * h as usize];
|
||||
let mut seed = 0x9E37_79B9_7F4A_7C15u64;
|
||||
let mut next = move || {
|
||||
seed ^= seed << 13;
|
||||
seed ^= seed >> 7;
|
||||
seed ^= seed << 17;
|
||||
seed
|
||||
};
|
||||
let (w, h) = (w as usize, h as usize);
|
||||
for line in (4..h.saturating_sub(18)).step_by(24) {
|
||||
let mut x = 8;
|
||||
while x + 16 < w {
|
||||
let wide = 5 + (next() % 4) as usize;
|
||||
let shape = next() % 4;
|
||||
let mut fill = |x0: usize, x1: usize, y0: usize, y1: usize| {
|
||||
for y in line + y0..line + y1 {
|
||||
let ragged = |r: u64| match r % 8 {
|
||||
0 => 0,
|
||||
1 => 2,
|
||||
_ => 1,
|
||||
};
|
||||
let (left, right) = ((x + x0 + 1).saturating_sub(ragged(next())), x + x1 + ragged(next()));
|
||||
for xx in left..right.saturating_sub(1).min(w) {
|
||||
data[y * stride + xx / 8] &= !(0x80 >> (xx % 8));
|
||||
}
|
||||
}
|
||||
};
|
||||
match shape {
|
||||
0 => fill(0, 2, 0, 14),
|
||||
1 => {
|
||||
fill(0, wide, 4, 6);
|
||||
fill(0, wide, 12, 14);
|
||||
fill(0, 2, 4, 14);
|
||||
fill(wide - 2, wide, 4, 14);
|
||||
}
|
||||
2 => {
|
||||
fill(0, 2, 4, 14);
|
||||
fill(wide - 2, wide, 6, 14);
|
||||
fill(0, wide - 1, 4, 6);
|
||||
}
|
||||
_ => {
|
||||
fill(0, 2, 7, 14);
|
||||
fill(0, 2, 2, 4);
|
||||
}
|
||||
}
|
||||
x += wide + 2 + (next() % 2) as usize + if next() % 6 == 0 { 7 } else { 0 };
|
||||
}
|
||||
}
|
||||
data
|
||||
}
|
||||
|
||||
/// The one-bit samples (true for white) a Group 4 image stream decodes to, through an
|
||||
/// independent decoder.
|
||||
fn g4_rows(s: &Stream) -> Vec<Vec<bool>> {
|
||||
struct Rows(Vec<Vec<bool>>, Vec<bool>, usize);
|
||||
impl hayro_ccitt::Decoder for Rows {
|
||||
fn push_pixel(&mut self, white: bool) {
|
||||
self.1.push(white);
|
||||
}
|
||||
fn push_pixel_chunk(&mut self, white: bool, chunks: u32) {
|
||||
self.1.extend(std::iter::repeat_n(white, chunks as usize * 8));
|
||||
}
|
||||
fn next_line(&mut self) {
|
||||
let mut row = std::mem::take(&mut self.1);
|
||||
row.truncate(self.2);
|
||||
self.0.push(row);
|
||||
}
|
||||
}
|
||||
let (w, h) = (s.dict.int(b"Width").unwrap() as u32, s.dict.int(b"Height").unwrap() as u32);
|
||||
let settings = hayro_ccitt::DecodeSettings {
|
||||
columns: w,
|
||||
rows: h,
|
||||
end_of_block: true,
|
||||
end_of_line: false,
|
||||
rows_are_byte_aligned: false,
|
||||
encoding: hayro_ccitt::EncodingMode::Group4,
|
||||
invert_black: false,
|
||||
};
|
||||
let mut out = Rows(Vec::new(), Vec::new(), w as usize);
|
||||
hayro_ccitt::decode(&s.raw, &mut out, &mut hayro_ccitt::DecoderContext::new(settings)).unwrap();
|
||||
out.0
|
||||
}
|
||||
|
||||
fn image_stream(doc: &Document, page: usize) -> Stream {
|
||||
let p = &pages(doc)[page];
|
||||
let res = doc.resolve(p.get(b"Resources").unwrap()).as_dict().cloned().unwrap();
|
||||
let xo = doc.resolve(res.get(b"XObject").unwrap()).as_dict().cloned().unwrap();
|
||||
match &*doc.resolve(xo.get(b"Im0").unwrap()) {
|
||||
Object::Stream(s) => s.clone(),
|
||||
_ => panic!("not an image"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Black-and-white pictures are stored at one bit per pixel, as CCITT Group 4 when that is
|
||||
/// smaller, whichever way the file holds them: a 1-bit PNG (which decodes to eight bits), eight-bit
|
||||
/// grey of only black and white, a two-colour palette, black-and-white RGB. The bits are the
|
||||
/// picture's. A grey profile stays; a picture with any other shade, colour, or an RGB profile is
|
||||
/// stored as before.
|
||||
#[test]
|
||||
fn black_and_white_images_are_stored_at_one_bit() {
|
||||
use png::{BitDepth, ColorType};
|
||||
let (w, h) = (1200u32, 240u32);
|
||||
let bits = strokes(w, h);
|
||||
let stride = (w as usize).div_ceil(8);
|
||||
let white = |x: usize, y: usize| bits[y * stride + x / 8] & (0x80 >> (x % 8)) != 0;
|
||||
let expected: Vec<Vec<bool>> = (0..h as usize).map(|y| (0..w as usize).map(|x| white(x, y)).collect()).collect();
|
||||
let grey: Vec<u8> = expected.iter().flatten().map(|&wh| if wh { 255 } else { 0 }).collect();
|
||||
let rgb: Vec<u8> = grey.iter().flat_map(|&v| [v, v, v]).collect();
|
||||
let pictures = [
|
||||
png_of(w, h, ColorType::Grayscale, BitDepth::One, &bits, None, None),
|
||||
png_of(w, h, ColorType::Grayscale, BitDepth::Eight, &grey, None, None),
|
||||
png_of(w, h, ColorType::Indexed, BitDepth::One, &bits.iter().map(|b| !b).collect::<Vec<_>>(), Some(vec![255, 255, 255, 0, 0, 0]), None),
|
||||
png_of(w, h, ColorType::Rgb, BitDepth::Eight, &rgb, None, None),
|
||||
png_of(w, h, ColorType::Grayscale, BitDepth::One, &bits, None, Some(icc_profile(b"GRAY"))),
|
||||
];
|
||||
let files: Vec<(String, Vec<u8>)> = pictures.into_iter().enumerate().map(|(i, p)| (format!("{i}.png"), p)).collect();
|
||||
let doc = reopen(&from_images(&files).unwrap());
|
||||
for page in 0..5 {
|
||||
let s = image_stream(&doc, page);
|
||||
assert_eq!((s.dict.int(b"BitsPerComponent"), s.dict.name(b"Filter")), (Some(1), Some(&b"CCITTFaxDecode"[..])), "page {page}");
|
||||
assert_eq!(g4_rows(&s), expected, "page {page}");
|
||||
assert!(s.raw.len() < bits.len(), "page {page}: {} bytes, smaller than its one-bit samples", s.raw.len());
|
||||
}
|
||||
assert_eq!(image_of(&doc, 3).name(b"ColorSpace"), Some(&b"DeviceGray"[..]), "black-and-white RGB becomes grey");
|
||||
assert_eq!(icc_of(&doc, &image_of(&doc, 4)).map(|(n, ..)| n), Some(1), "the grey profile stays");
|
||||
|
||||
// Another shade, colour, an RGB profile: as before. A tiny picture: one bit, but Flate.
|
||||
let mut shaded = grey.clone();
|
||||
shaded[5] = 128;
|
||||
let mut coloured = rgb.clone();
|
||||
coloured[0] = 200;
|
||||
let others = [
|
||||
png_of(w, h, ColorType::Grayscale, BitDepth::Eight, &shaded, None, None),
|
||||
png_of(w, h, ColorType::Rgb, BitDepth::Eight, &coloured, None, None),
|
||||
png_of(w, h, ColorType::Rgb, BitDepth::Eight, &rgb, None, Some(icc_profile(b"RGB "))),
|
||||
png_of(2, 2, ColorType::Grayscale, BitDepth::Eight, &[0, 255, 255, 0], None, None),
|
||||
];
|
||||
let files: Vec<(String, Vec<u8>)> = others.into_iter().enumerate().map(|(i, p)| (format!("o{i}.png"), p)).collect();
|
||||
let doc = reopen(&from_images(&files).unwrap());
|
||||
let kept: Vec<(Option<i64>, Option<Vec<u8>>)> =
|
||||
(0..4).map(|p| (image_of(&doc, p).int(b"BitsPerComponent"), image_of(&doc, p).name(b"Filter").map(<[u8]>::to_vec))).collect();
|
||||
assert_eq!(
|
||||
kept[..3],
|
||||
[(Some(8), Some(b"FlateDecode".to_vec())), (Some(8), Some(b"FlateDecode".to_vec())), (Some(8), Some(b"FlateDecode".to_vec()))]
|
||||
);
|
||||
assert_eq!(kept[3], (Some(1), Some(b"FlateDecode".to_vec())), "Group 4 isn't smaller for 2 × 2");
|
||||
}
|
||||
|
||||
/// The pixels of an exported PNG (RGB), as true for white.
|
||||
fn exported_white(png_data: &[u8]) -> Vec<bool> {
|
||||
let mut reader = png::Decoder::new(std::io::Cursor::new(png_data.to_vec())).read_info().unwrap();
|
||||
let mut buf = vec![0; reader.output_buffer_size().unwrap()];
|
||||
let frame = reader.next_frame(&mut buf).unwrap();
|
||||
assert_eq!(frame.color_type, png::ColorType::Rgb);
|
||||
buf[..frame.buffer_size()].as_chunks::<3>().0.iter().map(|p| *p == [255, 255, 255]).collect()
|
||||
}
|
||||
|
||||
/// Export ▸ Images reads CCITT fax images: a page created from a 1-bit PNG (Group 4 now) exports as
|
||||
/// the picture, as does the picture coded the other way round with /BlackIs1, the picture with its
|
||||
/// filter and parameters in arrays, with /K and /Columns given by reference, with a /Rows below its
|
||||
/// height, and behind another filter (its parameters by reference too). One whose /Columns aren't
|
||||
/// its width is skipped, not misread.
|
||||
#[test]
|
||||
fn ccitt_fax_images_export_as_their_picture() {
|
||||
use png::{BitDepth, ColorType};
|
||||
let (w, h) = (1200u32, 240u32);
|
||||
let bits = strokes(w, h);
|
||||
let stride = (w as usize).div_ceil(8);
|
||||
let picture: Vec<bool> =
|
||||
(0..h as usize).flat_map(|y| (0..w as usize).map(move |x| (y, x))).map(|(y, x)| bits[y * stride + x / 8] & (0x80 >> (x % 8)) != 0).collect();
|
||||
let mut doc = from_images(&[("scan.png".into(), png_of(w, h, ColorType::Grayscale, BitDepth::One, &bits, None, None))]).unwrap();
|
||||
assert_eq!(image_of(&doc, 0).name(b"Filter"), Some(&b"CCITTFaxDecode"[..]));
|
||||
let out = extract_images(&doc, &[0], 0);
|
||||
assert!(out.skipped.is_empty(), "{:?}", out.skipped);
|
||||
assert_eq!(exported_white(&out.images[0].data), picture);
|
||||
|
||||
// The same picture coded with 1 for black, which /BlackIs1 says.
|
||||
let r = {
|
||||
let page = pdfcraft_model::pages(&doc)[0].clone();
|
||||
let res = doc.resolve(page.dict.get(b"Resources").unwrap()).as_dict().cloned().unwrap();
|
||||
let xo = doc.resolve(res.get(b"XObject").unwrap()).as_dict().cloned().unwrap();
|
||||
xo.get(b"Im0").and_then(Object::as_ref).unwrap()
|
||||
};
|
||||
let base = image_of(&doc, 0);
|
||||
let with = |black_is_1: bool, columns: i64, data: Vec<u8>| {
|
||||
let mut d = base.clone();
|
||||
let mut parms = Dict::new();
|
||||
parms.set(b"K".to_vec(), Object::Int(-1));
|
||||
parms.set(b"Columns".to_vec(), Object::Int(columns));
|
||||
parms.set(b"Rows".to_vec(), Object::Int(i64::from(h)));
|
||||
parms.set(b"BlackIs1".to_vec(), Object::Bool(black_is_1));
|
||||
d.set(b"DecodeParms".to_vec(), Object::Dict(parms));
|
||||
d.remove(b"Length");
|
||||
Stream::from_raw(d, data)
|
||||
};
|
||||
let inverted: Vec<u8> = bits.iter().map(|b| !b).collect();
|
||||
let stream = with(true, i64::from(w), pdfcraft_filters::encode_g4(&inverted, w, h).unwrap());
|
||||
doc.set(r, Object::Stream(stream));
|
||||
let out = extract_images(&doc, &[0], 0);
|
||||
assert_eq!(exported_white(&out.images[0].data), picture, "BlackIs1");
|
||||
|
||||
let mut stream = with(false, i64::from(w), pdfcraft_filters::encode_g4(&bits, w, h).unwrap());
|
||||
let parms = stream.dict.get(b"DecodeParms").cloned().unwrap();
|
||||
stream.dict.set(b"DecodeParms".to_vec(), Object::Array(vec![parms]));
|
||||
stream.dict.set(b"Filter".to_vec(), Object::Array(vec![Object::name("CCITTFaxDecode")]));
|
||||
doc.set(r, Object::Stream(stream));
|
||||
let out = extract_images(&doc, &[0], 0);
|
||||
assert!(out.skipped.is_empty(), "{:?}", out.skipped);
|
||||
assert_eq!(exported_white(&out.images[0].data), picture, "in arrays");
|
||||
|
||||
let mut stream = with(false, i64::from(w), pdfcraft_filters::encode_g4(&bits, w, h).unwrap());
|
||||
let mut parms = stream.dict.get(b"DecodeParms").and_then(Object::as_dict).cloned().unwrap();
|
||||
parms.set(b"K".to_vec(), Object::Ref(doc.add(Object::Int(-1))));
|
||||
parms.set(b"Columns".to_vec(), Object::Ref(doc.add(Object::Int(i64::from(w)))));
|
||||
parms.set(b"Rows".to_vec(), Object::Int(1));
|
||||
stream.dict.set(b"DecodeParms".to_vec(), Object::Dict(parms));
|
||||
doc.set(r, Object::Stream(stream));
|
||||
let out = extract_images(&doc, &[0], 0);
|
||||
assert!(out.skipped.is_empty(), "{:?}", out.skipped);
|
||||
assert_eq!(exported_white(&out.images[0].data), picture, "/K and /Columns by reference, /Rows 1");
|
||||
|
||||
// Behind another filter, with its parameters second in the array, as 7.4.1 pairs them.
|
||||
let g4 = pdfcraft_filters::encode_g4(&bits, w, h).unwrap();
|
||||
let hex = g4.iter().map(|b| format!("{b:02x}")).chain([">".to_string()]).collect::<String>().into_bytes();
|
||||
for (outer, data) in [("ASCIIHexDecode", hex), ("FlateDecode", pdfcraft_filters::encode_flate(&g4))] {
|
||||
let mut stream = with(false, i64::from(w), data);
|
||||
let parms = stream.dict.get(b"DecodeParms").cloned().unwrap();
|
||||
stream.dict.set(b"DecodeParms".to_vec(), Object::Array(vec![Object::Null, parms]));
|
||||
stream.dict.set(b"Filter".to_vec(), Object::Array(vec![Object::name(outer), Object::name("CCITTFaxDecode")]));
|
||||
doc.set(r, Object::Stream(stream));
|
||||
let out = extract_images(&doc, &[0], 0);
|
||||
assert!(out.skipped.is_empty(), "{outer}: {:?}", out.skipped);
|
||||
assert_eq!(exported_white(&out.images[0].data), picture, "behind {outer}");
|
||||
}
|
||||
// Behind Flate with a PNG predictor, whose parameters are given by reference.
|
||||
let padded: Vec<u8> = g4.iter().copied().chain(std::iter::repeat_n(0, 16 - g4.len() % 16)).collect();
|
||||
let params = pdfcraft_filters::Params { predictor: 12, colors: 1, bits_per_component: 8, columns: 16, early_change: 1 };
|
||||
let predicted = pdfcraft_filters::encode(&pdfcraft_filters::Filter::Flate, ¶ms, &padded).unwrap();
|
||||
let mut flate_parms = Dict::new();
|
||||
flate_parms.set(b"Predictor".to_vec(), Object::Int(12));
|
||||
flate_parms.set(b"Columns".to_vec(), Object::Int(16));
|
||||
let flate_parms = doc.add(Object::Dict(flate_parms));
|
||||
let mut stream = with(false, i64::from(w), predicted);
|
||||
let parms = stream.dict.get(b"DecodeParms").cloned().unwrap();
|
||||
stream.dict.set(b"DecodeParms".to_vec(), Object::Array(vec![Object::Ref(flate_parms), parms]));
|
||||
stream.dict.set(b"Filter".to_vec(), Object::Array(vec![Object::name("FlateDecode"), Object::name("CCITTFaxDecode")]));
|
||||
doc.set(r, Object::Stream(stream));
|
||||
let out = extract_images(&doc, &[0], 0);
|
||||
assert!(out.skipped.is_empty(), "{:?}", out.skipped);
|
||||
assert_eq!(exported_white(&out.images[0].data), picture, "behind Flate with a predictor given by reference");
|
||||
// CCITT before another filter isn't a picture yet.
|
||||
let mut stream = with(false, i64::from(w), pdfcraft_filters::encode_flate(&g4));
|
||||
stream.dict.set(b"Filter".to_vec(), Object::Array(vec![Object::name("CCITTFaxDecode"), Object::name("FlateDecode")]));
|
||||
doc.set(r, Object::Stream(stream));
|
||||
let out = extract_images(&doc, &[0], 0);
|
||||
assert!(out.images.is_empty() && out.skipped.len() == 1, "CCITT, then Flate: skipped");
|
||||
|
||||
let stream = with(false, i64::from(w) + 8, pdfcraft_filters::encode_g4(&bits, w, h).unwrap());
|
||||
doc.set(r, Object::Stream(stream));
|
||||
let out = extract_images(&doc, &[0], 0);
|
||||
assert!(out.images.is_empty() && out.skipped.len() == 1, "columns other than the width: skipped");
|
||||
}
|
||||
|
||||
/// Group 3 data: rows of run lengths below 64, white first, coded one-dimensionally with T.4's
|
||||
/// terminating codes (ITU-T T.4 Tables 2 and 3). Each row starts with an end-of-line code with
|
||||
/// `eol`, then with `tag` a 1 bit (the next row one-dimensional, as `/K` above 0 has it). Fill bits
|
||||
/// (0s) go where `fill` says.
|
||||
fn group_3(rows: &[impl AsRef<[u32]>], eol: bool, tag: bool, fill: Fill) -> Vec<u8> {
|
||||
// The codes for runs 0 to 63, in order.
|
||||
const WHITE: &str = concat!(
|
||||
"00110101 000111 0111 1000 1011 1100 1110 1111 10011 10100 00111 01000 001000 000011 110100 110101 101010 101011 ",
|
||||
"0100111 0001100 0001000 0010111 0000011 0000100 0101000 0101011 0010011 0100100 0011000 00000010 00000011 00011010 ",
|
||||
"00011011 00010010 00010011 00010100 00010101 00010110 00010111 00101000 00101001 00101010 00101011 00101100 00101101 ",
|
||||
"00000100 00000101 00001010 00001011 01010010 01010011 01010100 01010101 00100100 00100101 01011000 01011001 01011010 ",
|
||||
"01011011 01001010 01001011 00110010 00110011 00110100",
|
||||
);
|
||||
const BLACK: &str = concat!(
|
||||
"0000110111 010 11 10 011 0011 0010 00011 000101 000100 0000100 0000101 0000111 00000100 00000111 000011000 0000010111 ",
|
||||
"0000011000 0000001000 00001100111 00001101000 00001101100 00000110111 00000101000 00000010111 00000011000 ",
|
||||
"000011001010 000011001011 000011001100 000011001101 000001101000 000001101001 000001101010 000001101011 000011010010 ",
|
||||
"000011010011 000011010100 000011010101 000011010110 000011010111 000001101100 000001101101 000011011010 000011011011 ",
|
||||
"000001010100 000001010101 000001010110 000001010111 000001100100 000001100101 000001010010 000001010011 000000100100 ",
|
||||
"000000110111 000000111000 000000100111 000000101000 000001011000 000001011001 000000101011 000000101100 000001011010 ",
|
||||
"000001100110 000001100111",
|
||||
);
|
||||
let code = |white: bool, run: u32| (if white { WHITE } else { BLACK }).split(' ').nth(run as usize).expect("a run below 64");
|
||||
let mut bits = String::new();
|
||||
for row in rows {
|
||||
// The end-of-line code is 12 bits.
|
||||
let ends_code = if fill == Fill::CodeEnd && eol { 12 } else { 0 };
|
||||
while fill != Fill::None && !(bits.len() + ends_code).is_multiple_of(8) {
|
||||
bits.push('0');
|
||||
}
|
||||
if eol {
|
||||
bits.push_str("000000000001");
|
||||
}
|
||||
if tag {
|
||||
bits.push('1');
|
||||
}
|
||||
row.as_ref().iter().enumerate().for_each(|(i, run)| bits.push_str(code(i % 2 == 0, *run)));
|
||||
}
|
||||
bits.as_bytes().chunks(8).map(|c| c.iter().enumerate().fold(0u8, |b, (i, d)| b | (u8::from(*d == b'1') << (7 - i)))).collect()
|
||||
}
|
||||
|
||||
/// `count` text-like pictures `w` by `h` for [`group_3`], from a fixed seed: rows of random runs,
|
||||
/// long white ones and short black ones, and a row may start black.
|
||||
fn random_pictures(w: u32, h: u32, count: usize) -> Vec<Vec<Vec<u32>>> {
|
||||
let mut seed = 0x9E37_79B9_7F4A_7C15u64;
|
||||
let mut random = |n: u64| {
|
||||
seed ^= seed << 13;
|
||||
seed ^= seed >> 7;
|
||||
seed ^= seed << 17;
|
||||
(seed % n) as u32
|
||||
};
|
||||
let mut row = || {
|
||||
let (mut runs, mut left) = (Vec::new(), w);
|
||||
while left > 0 {
|
||||
let run = match runs.len() % 2 {
|
||||
0 if runs.is_empty() => random(31),
|
||||
0 => 1 + random(30),
|
||||
_ => 1 + random(5),
|
||||
};
|
||||
runs.push(run.min(left));
|
||||
left -= run.min(left);
|
||||
}
|
||||
runs
|
||||
};
|
||||
(0..count).map(|_| (0..h).map(|_| row()).collect()).collect()
|
||||
}
|
||||
|
||||
/// The picture `rows` of runs (white first) make, `w` by `h`, true where white.
|
||||
fn white_of(rows: &[Vec<u32>], w: u32, h: u32) -> Vec<bool> {
|
||||
let mut white = vec![false; (w * h) as usize];
|
||||
for (y, row) in rows.iter().enumerate() {
|
||||
let mut x = y * w as usize;
|
||||
for (i, run) in row.iter().enumerate() {
|
||||
white[x..x + *run as usize].fill(i % 2 == 0);
|
||||
x += *run as usize;
|
||||
}
|
||||
}
|
||||
white
|
||||
}
|
||||
|
||||
/// Where [`group_3`] puts fill bits: none; so each row, its end-of-line code first, starts on a
|
||||
/// byte; or so each end-of-line code ends on one (T.4's fill, as TIFF writes it).
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
enum Fill {
|
||||
None,
|
||||
RowStart,
|
||||
CodeEnd,
|
||||
}
|
||||
|
||||
/// What Export ▸ Images claims for CCITT and for parameters given by reference, each checked
|
||||
/// against the same picture stored another way: Group 3 one-dimensional data (`/K 0`) exports as
|
||||
/// its picture; a CCITT soft mask and a CCITT stencil `/Mask` export as the same masks in Flate;
|
||||
/// and a Flate image's PNG predictor, and an indexed image's lookup table stream with one, read
|
||||
/// the same with their `/DecodeParms` given by reference as direct.
|
||||
#[test]
|
||||
fn group_3_ccitt_masks_and_parameters_by_reference_export_as_their_picture() {
|
||||
use png::{BitDepth, ColorType};
|
||||
let (w, h) = (64u32, 16u32);
|
||||
let rows: Vec<&[u32]> = (0..h).map(|y| if y % 2 == 0 { &[32u32, 32][..] } else { &[16, 16, 32][..] }).collect();
|
||||
let mut bits = vec![0u8; 8 * h as usize];
|
||||
for (y, runs) in rows.iter().enumerate() {
|
||||
let mut x = 0;
|
||||
for (i, run) in runs.iter().enumerate() {
|
||||
if i % 2 == 0 {
|
||||
(x..x + *run as usize).for_each(|xx| bits[y * 8 + xx / 8] |= 0x80 >> (xx % 8));
|
||||
}
|
||||
x += *run as usize;
|
||||
}
|
||||
}
|
||||
let picture: Vec<bool> = (0..(w * h) as usize).map(|i| bits[i / 8] & (0x80 >> (i % 8)) != 0).collect();
|
||||
let mut doc = from_images(&[("scan.png".into(), png_of(w, h, ColorType::Grayscale, BitDepth::One, &bits, None, None))]).unwrap();
|
||||
let r = {
|
||||
let page = pdfcraft_model::pages(&doc)[0].clone();
|
||||
let res = doc.resolve(page.dict.get(b"Resources").unwrap()).as_dict().cloned().unwrap();
|
||||
let xo = doc.resolve(res.get(b"XObject").unwrap()).as_dict().cloned().unwrap();
|
||||
xo.get(b"Im0").and_then(Object::as_ref).unwrap()
|
||||
};
|
||||
let image = |entries: &[(&str, Object)]| {
|
||||
let mut d = Dict::new();
|
||||
d.set(b"Type".to_vec(), Object::name("XObject"));
|
||||
d.set(b"Subtype".to_vec(), Object::name("Image"));
|
||||
d.set(b"Width".to_vec(), Object::Int(w.into()));
|
||||
d.set(b"Height".to_vec(), Object::Int(h.into()));
|
||||
for (k, v) in entries {
|
||||
d.set(k.as_bytes().to_vec(), v.clone());
|
||||
}
|
||||
d
|
||||
};
|
||||
let fax = |k: i64| {
|
||||
let mut parms = Dict::new();
|
||||
parms.set(b"K".to_vec(), Object::Int(k));
|
||||
parms.set(b"Columns".to_vec(), Object::Int(w.into()));
|
||||
parms.set(b"Rows".to_vec(), Object::Int(h.into()));
|
||||
[("Filter", Object::name("CCITTFaxDecode")), ("DecodeParms", Object::Dict(parms))]
|
||||
};
|
||||
let grey = |bits: i64| [("BitsPerComponent", Object::Int(bits)), ("ColorSpace", Object::name("DeviceGray"))];
|
||||
|
||||
// One-dimensional (/K 0) plain, with end-of-line codes, with each row on a byte, and with
|
||||
// both; mixed (/K 1, each row tagged one-dimensional) with end-of-line codes and without.
|
||||
// Byte-aligned with end-of-line codes either way: each code starting on a byte, or ending on
|
||||
// one (T.4's fill, as TIFF writes it). /EncodedByteAlign is given by reference once, and so is
|
||||
// a /BlackIs1 that inverts the picture.
|
||||
let inverted: Vec<bool> = picture.iter().map(|white| !white).collect();
|
||||
for (k, eol, fill, align_by_reference, black_is_1) in [
|
||||
(0, false, Fill::None, false, false),
|
||||
(0, true, Fill::None, false, false),
|
||||
(0, false, Fill::RowStart, true, false),
|
||||
(0, true, Fill::RowStart, false, false),
|
||||
(0, true, Fill::CodeEnd, false, false),
|
||||
(1, true, Fill::None, false, false),
|
||||
(1, false, Fill::None, false, false),
|
||||
(1, true, Fill::CodeEnd, false, false),
|
||||
(0, false, Fill::None, false, true),
|
||||
] {
|
||||
let mut d = image(&[&grey(1)[..], &fax(k)].concat());
|
||||
let align = Object::Bool(fill != Fill::None);
|
||||
let align = if align_by_reference { Object::Ref(doc.add(align)) } else { align };
|
||||
let inverts = Object::Ref(doc.add(Object::Bool(black_is_1)));
|
||||
if let Some(Object::Dict(parms)) = d.get_mut(b"DecodeParms") {
|
||||
parms.set(b"EndOfLine".to_vec(), Object::Bool(eol));
|
||||
parms.set(b"EncodedByteAlign".to_vec(), align);
|
||||
parms.set(b"BlackIs1".to_vec(), inverts);
|
||||
}
|
||||
doc.set(r, Object::Stream(Stream::from_raw(d, group_3(&rows, eol, k > 0, fill))));
|
||||
let case = format!("/K {k}, EndOfLine {eol}, fill {fill:?}, BlackIs1 {black_is_1}");
|
||||
let out = extract_images(&doc, &[0], 0);
|
||||
assert!(out.skipped.is_empty(), "{case}: {:?}", out.skipped);
|
||||
assert_eq!(exported_white(&out.images[0].data), if black_is_1 { inverted.clone() } else { picture.clone() }, "{case}");
|
||||
}
|
||||
// Byte-aligned rows against /EndOfLine, over several pictures, as how a misreading comes out
|
||||
// depends on the picture: no codes (as TIFF's Modified Huffman has it), and /EndOfLine without
|
||||
// them; codes, each starting on a byte or ending on one, /EndOfLine or not. Each exports as its
|
||||
// picture, and a byte short is reported. The first picture is stripes, every row 32 white then
|
||||
// 32 black; the others are text-like rows of random runs.
|
||||
let image_with = |doc: &mut Document, k: i64, eol: bool, data: Vec<u8>| {
|
||||
let mut d = image(&[&grey(1)[..], &fax(k)].concat());
|
||||
if let Some(Object::Dict(parms)) = d.get_mut(b"DecodeParms") {
|
||||
parms.set(b"EndOfLine".to_vec(), Object::Bool(eol));
|
||||
parms.set(b"EncodedByteAlign".to_vec(), Object::Bool(true));
|
||||
}
|
||||
doc.set(r, Object::Stream(Stream::from_raw(d, data)));
|
||||
extract_images(doc, &[0], 0)
|
||||
};
|
||||
let mut pictures = vec![vec![vec![32u32, 32]; h as usize]];
|
||||
pictures.extend(random_pictures(w, h, 8));
|
||||
for (n, runs) in pictures.iter().enumerate() {
|
||||
let white = white_of(runs, w, h);
|
||||
for k in [0, 1] {
|
||||
for (codes, fill, eol) in [
|
||||
(false, Fill::RowStart, false),
|
||||
(false, Fill::RowStart, true),
|
||||
(true, Fill::RowStart, false),
|
||||
(true, Fill::RowStart, true),
|
||||
(true, Fill::CodeEnd, false),
|
||||
(true, Fill::CodeEnd, true),
|
||||
] {
|
||||
let out = image_with(&mut doc, k, eol, group_3(runs, codes, k > 0, fill));
|
||||
let case = format!("picture {n}, /K {k}, codes {codes}, fill {fill:?}, /EndOfLine {eol}");
|
||||
assert!(out.skipped.is_empty(), "{case}: {:?}", out.skipped);
|
||||
assert_eq!(exported_white(&out.images[0].data), white, "{case}");
|
||||
// A byte short, it is reported, not read the other way into other rows.
|
||||
let mut short = group_3(runs, codes, k > 0, fill);
|
||||
short.pop();
|
||||
let out = image_with(&mut doc, k, eol, short);
|
||||
assert!(out.images.is_empty() && out.skipped.len() == 1, "{case}, a byte short: {:?}", out.skipped);
|
||||
// At /K 1, codes with none before the first row (the first code and its fill are 2
|
||||
// bytes here) are read on bytes: the picture or reported, never another picture.
|
||||
if k == 1 && fill == Fill::CodeEnd {
|
||||
let out = image_with(&mut doc, k, eol, group_3(runs, codes, true, fill).split_off(2));
|
||||
assert!(out.images.iter().all(|i| exported_white(&i.data) == white), "{case}, no code first");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Group 4 rows on bytes keep their aligned read, /EndOfLine or not: here white rows, each the
|
||||
// one code 1 (vertical, no change) and its fill.
|
||||
for eol in [false, true] {
|
||||
let out = image_with(&mut doc, -1, eol, vec![0x80; h as usize]);
|
||||
assert!(out.skipped.is_empty(), "byte-aligned Group 4, /EndOfLine {eol}: {:?}", out.skipped);
|
||||
assert!(exported_white(&out.images[0].data).iter().all(|white| *white), "byte-aligned Group 4, /EndOfLine {eol}");
|
||||
}
|
||||
|
||||
// A grey picture under the same bits as a soft mask, then as a stencil mask: CCITT against Flate.
|
||||
let g4 = pdfcraft_filters::encode_g4(&bits, w, h).unwrap();
|
||||
for (key, mask) in [("SMask", grey(1).to_vec()), ("Mask", vec![("ImageMask", Object::Bool(true))])] {
|
||||
let mut exported = Vec::new();
|
||||
for coded in [true, false] {
|
||||
let m = if coded { Stream::from_raw(image(&[&mask[..], &fax(-1)].concat()), g4.clone()) } else { Stream::flate(image(&mask), &bits) };
|
||||
let m = doc.add(Object::Stream(m));
|
||||
let d = image(&[&grey(8)[..], &[(key, Object::Ref(m))]].concat());
|
||||
doc.set(r, Object::Stream(Stream::flate(d, &vec![100u8; (w * h) as usize])));
|
||||
exported.push(exported_rgba(&doc));
|
||||
}
|
||||
assert!(exported[0].1.chunks(4).any(|p| p[3] == 0), "{key}: masked somewhere");
|
||||
assert_eq!(exported[0], exported[1], "{key}: CCITT as Flate");
|
||||
}
|
||||
|
||||
// A PNG predictor given by reference, for the samples and for a lookup table.
|
||||
let predicted = |rows: &[u8], columns: i64| {
|
||||
let params = pdfcraft_filters::Params { predictor: 12, colors: 1, bits_per_component: 8, columns, early_change: 1 };
|
||||
let mut parms = Dict::new();
|
||||
parms.set(b"Predictor".to_vec(), Object::Int(12));
|
||||
parms.set(b"Columns".to_vec(), Object::Int(columns));
|
||||
(pdfcraft_filters::encode(&pdfcraft_filters::Filter::Flate, ¶ms, rows).unwrap(), parms)
|
||||
};
|
||||
let shades: Vec<u8> = (0..w * h).map(|i| (i * 7 % 256) as u8).collect();
|
||||
let (table, table_parms) = predicted(&[255, 0, 0, 0, 0, 255], 3);
|
||||
let indices: Vec<u8> = (0..w * h).map(|i| (i % 3 % 2) as u8).collect();
|
||||
let mut exported = Vec::new();
|
||||
for by_reference in [false, true] {
|
||||
let parms = |doc: &mut Document, p: &Dict| if by_reference { Object::Ref(doc.add(Object::Dict(p.clone()))) } else { Object::Dict(p.clone()) };
|
||||
let (samples, sample_parms) = predicted(&shades, w.into());
|
||||
let sample_parms = parms(&mut doc, &sample_parms);
|
||||
let d = image(&[&grey(8)[..], &[("Filter", Object::name("FlateDecode")), ("DecodeParms", sample_parms)]].concat());
|
||||
doc.set(r, Object::Stream(Stream::from_raw(d, samples)));
|
||||
let plain = exported_rgba(&doc);
|
||||
|
||||
let mut lookup = Dict::new();
|
||||
lookup.set(b"Filter".to_vec(), Object::name("FlateDecode"));
|
||||
lookup.set(b"DecodeParms".to_vec(), parms(&mut doc, &table_parms));
|
||||
let lookup = doc.add(Object::Stream(Stream::from_raw(lookup, table.clone())));
|
||||
let cs = Object::Array(vec![Object::name("Indexed"), Object::name("DeviceRGB"), 1.into(), Object::Ref(lookup)]);
|
||||
let d = image(&[("BitsPerComponent", Object::Int(8)), ("ColorSpace", cs)]);
|
||||
doc.set(r, Object::Stream(Stream::flate(d, &indices)));
|
||||
exported.push((plain, exported_rgba(&doc)));
|
||||
}
|
||||
assert_eq!(exported[0].0.1.chunks(4).map(|p| p[0]).collect::<Vec<_>>(), shades, "the samples, direct");
|
||||
assert_eq!(exported[0].1.1.get(..8), Some(&[255, 0, 0, 255, 0, 0, 255, 255][..]), "red, then blue");
|
||||
assert_eq!(exported[1], exported[0], "by reference as direct");
|
||||
}
|
||||
|
||||
/// An image whose PNG predictor is given by reference exports as its picture: its `/DecodeParms`
|
||||
/// dictionary given by reference, as an array's entry, or direct with its numbers by reference. So
|
||||
/// do an indexed image whose lookup table is a stream with its `/DecodeParms` given by reference,
|
||||
/// and a JBIG2 image whose `/JBIG2Globals` stream has them so. `Stream::decoded` reads only a
|
||||
/// direct `/DecodeParms` with direct numbers: the row tags stayed in the samples, and the picture
|
||||
/// came out shifted.
|
||||
#[test]
|
||||
fn images_whose_predictor_is_given_by_reference_export_as_their_picture() {
|
||||
// PNG predictor parameters for `columns` one-byte samples a row.
|
||||
let parms = |columns: i64| {
|
||||
let mut p = Dict::new();
|
||||
p.set(b"Predictor".to_vec(), Object::Int(15));
|
||||
p.set(b"Colors".to_vec(), Object::Int(1));
|
||||
p.set(b"BitsPerComponent".to_vec(), Object::Int(8));
|
||||
p.set(b"Columns".to_vec(), Object::Int(columns));
|
||||
p
|
||||
};
|
||||
// Two rows of four grey samples, each behind a PNG "None" row tag.
|
||||
let predicted = pdfcraft_filters::encode_flate(&[0, 10, 20, 30, 40, 0, 50, 60, 70, 80]);
|
||||
let grey: Vec<u8> = [10u8, 20, 30, 40, 50, 60, 70, 80].iter().flat_map(|v| [*v, *v, *v, 255]).collect();
|
||||
for form in ["a reference", "an array of a reference", "numbers by reference"] {
|
||||
let mut doc = from_images(&[("flat.png".into(), png_bytes(false))]).unwrap();
|
||||
with_image(&mut doc, |doc| {
|
||||
let mut d = image_dict(4, 2, "DeviceGray", 8);
|
||||
d.set(b"Filter".to_vec(), Object::name("FlateDecode"));
|
||||
let decode_parms = match form {
|
||||
"numbers by reference" => {
|
||||
let mut p = parms(4);
|
||||
for key in [&b"Predictor"[..], b"Columns"] {
|
||||
let v = p.get(key).cloned().unwrap();
|
||||
p.set(key.to_vec(), Object::Ref(doc.add(v)));
|
||||
}
|
||||
Object::Dict(p)
|
||||
}
|
||||
"a reference" => Object::Ref(doc.add(Object::Dict(parms(4)))),
|
||||
_ => Object::Array(vec![Object::Ref(doc.add(Object::Dict(parms(4))))]),
|
||||
};
|
||||
d.set(b"DecodeParms".to_vec(), decode_parms);
|
||||
Stream::from_raw(d, predicted.clone())
|
||||
});
|
||||
assert_eq!(exported_rgba(&doc), ("png", grey.clone()), "/DecodeParms as {form}");
|
||||
}
|
||||
// An indexed image's lookup table, red then blue, as a stream behind a "None" row tag.
|
||||
let mut doc = from_images(&[("flat.png".into(), png_bytes(false))]).unwrap();
|
||||
with_image(&mut doc, |doc| {
|
||||
let mut t = Dict::new();
|
||||
t.set(b"Filter".to_vec(), Object::name("FlateDecode"));
|
||||
t.set(b"DecodeParms".to_vec(), Object::Ref(doc.add(Object::Dict(parms(6)))));
|
||||
let table = doc.add(Object::Stream(Stream::from_raw(t, pdfcraft_filters::encode_flate(&[0, 255, 0, 0, 0, 0, 255]))));
|
||||
let mut d = image_dict(4, 1, "DeviceGray", 8);
|
||||
d.set(b"ColorSpace".to_vec(), Object::Array(vec![Object::name("Indexed"), Object::name("DeviceRGB"), Object::Int(1), Object::Ref(table)]));
|
||||
Stream::from_raw(d, vec![0, 1, 0, 1])
|
||||
});
|
||||
let (red, blue) = ([255, 0, 0, 255], [0, 0, 255, 255]);
|
||||
assert_eq!(exported_rgba(&doc), ("png", [red, blue, red, blue].concat()), "the lookup table's /DecodeParms by reference");
|
||||
// A JBIG2 image whose globals hold one extension segment (ISO/IEC 14492 7.4.14) a decoder
|
||||
// ignores, behind a "None" row tag. With the tag left in, the globals can't be read and the
|
||||
// image is skipped.
|
||||
let segment = [0, 0, 0, 0, 0x3E, 0, 0, 0, 0, 0, 4, 0, 0, 0, 1];
|
||||
let bits = [0xF0u8, 0x0F, 0xAA, 0x55];
|
||||
let mut doc = from_images(&[("flat.png".into(), png_bytes(false))]).unwrap();
|
||||
with_image(&mut doc, |doc| {
|
||||
let mut g = Dict::new();
|
||||
g.set(b"Filter".to_vec(), Object::name("FlateDecode"));
|
||||
g.set(b"DecodeParms".to_vec(), Object::Ref(doc.add(Object::Dict(parms(segment.len() as i64)))));
|
||||
let tagged: Vec<u8> = [0].iter().chain(&segment).copied().collect();
|
||||
let globals = doc.add(Object::Stream(Stream::from_raw(g, pdfcraft_filters::encode_flate(&tagged))));
|
||||
let mut decode_parms = Dict::new();
|
||||
decode_parms.set(b"JBIG2Globals".to_vec(), Object::Ref(globals));
|
||||
let mut d = image_dict(16, 2, "DeviceGray", 1);
|
||||
d.set(b"Filter".to_vec(), Object::name("JBIG2Decode"));
|
||||
d.set(b"DecodeParms".to_vec(), Object::Dict(decode_parms));
|
||||
Stream::from_raw(d, pdfcraft_filters::encode_jbig2_generic(&bits, 16, 2).unwrap())
|
||||
});
|
||||
let picture: Vec<u8> = (0..32).flat_map(|i| if bits[i / 8] & (0x80 >> (i % 8)) != 0 { [255, 255, 255, 255] } else { [0, 0, 0, 255] }).collect();
|
||||
assert_eq!(exported_rgba(&doc), ("png", picture), "the JBIG2 globals' /DecodeParms by reference");
|
||||
}
|
||||
|
||||
/// An image the optimizer stored as JBIG2 symbols (a symbol dictionary and text regions, rather
|
||||
/// than one generic region) exports as its picture.
|
||||
#[test]
|
||||
fn symbol_coded_jbig2_images_export_as_their_picture() {
|
||||
const LETTERS: [[&str; 7]; 3] = [
|
||||
["#####", "#....", "####.", "#....", "#....", "#....", "#####"],
|
||||
[".###.", "#...#", "#....", "#....", "#....", "#...#", ".###."],
|
||||
["#...#", "#...#", "#####", "#...#", "#...#", "#...#", "#...#"],
|
||||
];
|
||||
let (w, h) = (400usize, 40usize);
|
||||
let stride = w.div_ceil(8);
|
||||
// 1 samples white, as a grey image's are; the letters' pixels 0.
|
||||
let mut bits = vec![0xFFu8; stride * h];
|
||||
for (line, top) in [2usize, 12, 22, 32].into_iter().enumerate() {
|
||||
for (k, x) in (3..w - 6).step_by(7).enumerate() {
|
||||
for (dy, row) in LETTERS[(k + line) % 3].iter().enumerate() {
|
||||
for (dx, c) in row.bytes().enumerate() {
|
||||
if c == b'#' {
|
||||
bits[(top + dy) * stride + (x + dx) / 8] &= !(0x80 >> ((x + dx) % 8));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let jbig2 = pdfcraft_filters::encode_jbig2(&bits, w as u32, h as u32).unwrap();
|
||||
let generic = pdfcraft_filters::encode_jbig2_generic(&bits, w as u32, h as u32).unwrap();
|
||||
assert!(jbig2.len() < generic.len(), "symbol coded: {} bytes, generic {}", jbig2.len(), generic.len());
|
||||
let mut doc = from_images(&[("flat.png".into(), png_bytes(false))]).unwrap();
|
||||
with_image(&mut doc, |_| {
|
||||
let mut d = image_dict(w as i64, h as i64, "DeviceGray", 1);
|
||||
d.set(b"Filter".to_vec(), Object::name("JBIG2Decode"));
|
||||
Stream::from_raw(d, jbig2)
|
||||
});
|
||||
let picture: Vec<u8> = (0..w * h)
|
||||
.flat_map(|i| if bits[i / w * stride + i % w / 8] & (0x80 >> (i % w % 8)) != 0 { [255, 255, 255, 255] } else { [0, 0, 0, 255] })
|
||||
.collect();
|
||||
assert_eq!(exported_rgba(&doc), ("png", picture));
|
||||
}
|
||||
|
||||
/// Export ▸ Images reads JBIG2 images (ISO 32000-2 §7.4.7), JBIG2 black as 0: as the image, and as
|
||||
/// a stencil `/Mask` of another. Their `/JBIG2Globals` are read, from a dictionary or the one in
|
||||
/// an array, so globals that can't be read skip the image rather than being ignored. Rows past the
|
||||
/// image's height are left out; a JBIG2 page of another width, or with fewer rows than the image,
|
||||
/// or larger than an exported image may be (however small the image's `/Height`), or data that
|
||||
/// isn't JBIG2, skips the image.
|
||||
#[test]
|
||||
fn jbig2_images_export_as_their_picture() {
|
||||
let (w, h) = (203i64, 41i64);
|
||||
let stride = 26;
|
||||
let mut seed = 0x2545_F491_4F6C_DD1Du64;
|
||||
let bits: Vec<u8> = (0..stride * h as usize)
|
||||
.map(|_| {
|
||||
seed ^= seed << 13;
|
||||
seed ^= seed >> 7;
|
||||
seed ^= seed << 17;
|
||||
seed as u8
|
||||
})
|
||||
.collect();
|
||||
// The first `rows` rows as RGBA: a 1 sample white, a 0 black.
|
||||
let picture = |rows: i64| -> Vec<u8> {
|
||||
(0..rows as usize)
|
||||
.flat_map(|y| (0..w as usize).map(move |x| (x, y)))
|
||||
.flat_map(|(x, y)| {
|
||||
let v = if bits[y * stride + x / 8] & (0x80 >> (x % 8)) != 0 { 255 } else { 0 };
|
||||
[v, v, v, 255]
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
let jbig2 = pdfcraft_filters::encode_jbig2_generic(&bits, w as u32, h as u32).unwrap();
|
||||
// A page whose image is `data` as JBIG2, `width` × `height`. With `globals`, its /DecodeParms
|
||||
// (an array when `.1`) name a globals stream; with `mask`, it is the stencil /Mask of a grey
|
||||
// image.
|
||||
let page = |width: i64, height: i64, data: &[u8], globals: Option<(&[u8], bool)>, mask: bool| {
|
||||
let mut doc = from_images(&[("flat.png".into(), png_bytes(false))]).unwrap();
|
||||
with_image(&mut doc, |doc| {
|
||||
let mut d = image_dict(width, height, "DeviceGray", 1);
|
||||
d.set(b"Filter".to_vec(), Object::name("JBIG2Decode"));
|
||||
if let Some((g, in_array)) = globals {
|
||||
let g = doc.add(Object::Stream(Stream::from_raw(Dict::new(), g.to_vec())));
|
||||
let mut parms = Dict::new();
|
||||
parms.set(b"JBIG2Globals".to_vec(), Object::Ref(g));
|
||||
d.set(b"DecodeParms".to_vec(), if in_array { Object::Array(vec![Object::Dict(parms)]) } else { Object::Dict(parms) });
|
||||
}
|
||||
if !mask {
|
||||
return Stream::from_raw(d, data.to_vec());
|
||||
}
|
||||
d.remove(b"ColorSpace");
|
||||
d.set(b"ImageMask".to_vec(), Object::Bool(true));
|
||||
let m = doc.add(Object::Stream(Stream::from_raw(d, data.to_vec())));
|
||||
let mut image = image_dict(width, height, "DeviceGray", 8);
|
||||
image.set(b"Mask".to_vec(), Object::Ref(m));
|
||||
Stream::from_raw(image, vec![128; (width * height) as usize])
|
||||
});
|
||||
doc
|
||||
};
|
||||
let skipped = |doc: &Document| {
|
||||
let out = extract_images(doc, &[0], 0);
|
||||
out.images.is_empty() && out.skipped.len() == 1
|
||||
};
|
||||
|
||||
assert_eq!(exported_rgba(&page(w, h, &jbig2, None, false)), ("png", picture(h)));
|
||||
assert_eq!(exported_rgba(&page(w, h, &jbig2, Some((&[][..], false)), false)).1, picture(h), "empty globals");
|
||||
for in_array in [false, true] {
|
||||
assert!(skipped(&page(w, h, &jbig2, Some((&b"not JBIG2"[..], in_array)), false)), "unreadable globals, in an array: {in_array}");
|
||||
}
|
||||
assert_eq!(exported_rgba(&page(w, h - 5, &jbig2, None, false)).1, picture(h - 5), "rows past the height");
|
||||
for (width, height, data) in [(w + 8, h, &jbig2[..]), (w - 1, h, &jbig2[..]), (w, h + 1, &jbig2[..]), (w, h, &b"not JBIG2"[..])] {
|
||||
assert!(skipped(&page(width, height, data, None, false)), "{width} × {height}, {} bytes", data.len());
|
||||
}
|
||||
// The same stream with its page information (the first segment's data, after its 11-byte
|
||||
// header: width, then height) claiming a 20,000 × 10,000 page: 200 million pixels, over the
|
||||
// export's 100 million, behind an image of 20,000 × 4. The decoder would decode the whole page
|
||||
// (it takes pages of up to about 2^28 pixels), so it is refused first.
|
||||
let mut large = jbig2.clone();
|
||||
large[11..15].copy_from_slice(&20_000u32.to_be_bytes());
|
||||
large[15..19].copy_from_slice(&10_000u32.to_be_bytes());
|
||||
assert!(skipped(&page(20_000, 4, &large, None, false)), "a page over the export's size");
|
||||
// Refused the same ways as a stencil /Mask, it is left out: the image exports opaque.
|
||||
for (width, height, mask) in [(w + 8, h, &jbig2), (20_000, 4, &large)] {
|
||||
let rgba = exported_rgba(&page(width, height, mask, None, true)).1;
|
||||
assert_eq!(rgba.len() as i64, width * height * 4, "a {width}-wide mask");
|
||||
assert!(alphas(&rgba).iter().all(|a| *a == 255), "a refused {width}-wide mask is left out");
|
||||
}
|
||||
// A page of exactly the budget, 20,000 × 5,000, is decoded; one row more is refused.
|
||||
for (rows, refused) in [(5_000u32, false), (5_001, true)] {
|
||||
large[15..19].copy_from_slice(&rows.to_be_bytes());
|
||||
let doc = page(20_000, 4, &large, None, false);
|
||||
assert_eq!(skipped(&doc), refused, "a page of 20,000 × {rows}");
|
||||
if !refused {
|
||||
assert_eq!(exported_rgba(&doc).1.len(), 20_000 * 4 * 4);
|
||||
}
|
||||
}
|
||||
// Damaged data never panics.
|
||||
for end in [0, 1, 10, 20, 30, jbig2.len() / 2] {
|
||||
let _ = extract_images(&page(w, h, &jbig2[..end], None, false), &[0], 0);
|
||||
}
|
||||
|
||||
// As a stencil /Mask, its 1 samples (JBIG2 white) hide the image.
|
||||
let alpha: Vec<u8> = picture(h).as_chunks::<4>().0.iter().map(|p| 255 - p[0]).collect();
|
||||
assert_eq!(alphas(&exported_rgba(&page(w, h, &jbig2, None, true)).1), alpha);
|
||||
}
|
||||
|
||||
/// A JBIG2 image's `/JBIG2Globals` are decoded before its JBIG2 page's size is known, so they have
|
||||
/// a limit of their own, 32 MiB, far below the 1 GiB of any stream: globals that Flate-decode to
|
||||
/// one byte more skip the image, with the limit in the reason, though they take a few kilobytes
|
||||
/// in the file. Globals of exactly the limit are read, and the limit is the same through an
|
||||
/// indirect `/DecodeParms`, in an array or not.
|
||||
#[test]
|
||||
fn jbig2_globals_are_decoded_within_a_limit_of_their_own() {
|
||||
const LIMIT: usize = 32 << 20;
|
||||
let bits = [0xF0u8, 0x0F, 0xAA, 0x55];
|
||||
let jbig2 = pdfcraft_filters::encode_jbig2_generic(&bits, 16, 2).unwrap();
|
||||
let picture: Vec<u8> = (0..32).flat_map(|i| if bits[i / 8] & (0x80 >> (i % 8)) != 0 { [255; 4] } else { [0, 0, 0, 255] }).collect();
|
||||
// Globals of `len` bytes, Flate-encoded: one extension segment (ISO/IEC 14492 7.4.14), which a
|
||||
// decoder skips; its 11-byte header gives the length of the data after it.
|
||||
let globals = |len: usize| {
|
||||
let mut g = vec![0, 0, 0, 0, 0x3E, 0, 0];
|
||||
g.extend_from_slice(&u32::try_from(len - 11).unwrap().to_be_bytes());
|
||||
g.extend_from_slice(&[0, 0, 0, 1]);
|
||||
g.resize(len, 0);
|
||||
pdfcraft_filters::encode_flate(&g)
|
||||
};
|
||||
// The image, its /DecodeParms naming `flated` as its globals: direct (0), by reference (1), or
|
||||
// by reference in an array (2).
|
||||
let page = |flated: &[u8], form: usize| {
|
||||
let mut doc = from_images(&[("flat.png".into(), png_bytes(false))]).unwrap();
|
||||
with_image(&mut doc, |doc| {
|
||||
let mut g = Dict::new();
|
||||
g.set(b"Filter".to_vec(), Object::name("FlateDecode"));
|
||||
let g = doc.add(Object::Stream(Stream::from_raw(g, flated.to_vec())));
|
||||
let mut parms = Dict::new();
|
||||
parms.set(b"JBIG2Globals".to_vec(), Object::Ref(g));
|
||||
let parms = match form {
|
||||
0 => Object::Dict(parms),
|
||||
1 => Object::Ref(doc.add(Object::Dict(parms))),
|
||||
_ => Object::Array(vec![Object::Ref(doc.add(Object::Dict(parms)))]),
|
||||
};
|
||||
let mut d = image_dict(16, 2, "DeviceGray", 1);
|
||||
d.set(b"Filter".to_vec(), Object::name("JBIG2Decode"));
|
||||
d.set(b"DecodeParms".to_vec(), parms);
|
||||
Stream::from_raw(d, jbig2.clone())
|
||||
});
|
||||
doc
|
||||
};
|
||||
|
||||
let (small, full, over) = (globals(15), globals(LIMIT), globals(LIMIT + 1));
|
||||
assert!(over.len() < 64 << 10, "the oversized globals take {} bytes in the file", over.len());
|
||||
assert_eq!(exported_rgba(&page(&full, 0)).1, picture, "globals of exactly the limit");
|
||||
for form in 0..3 {
|
||||
assert_eq!(exported_rgba(&page(&small, form)).1, picture, "small globals, form {form}");
|
||||
let out = extract_images(&page(&over, form), &[0], 0);
|
||||
assert!(out.images.is_empty(), "globals over the limit, form {form}");
|
||||
let why = &out.skipped.first().expect("the image is skipped").2;
|
||||
assert!(why.starts_with("the JBIG2 globals can't be read") && why.contains(&format!("limit of {LIMIT} bytes")), "{why}");
|
||||
}
|
||||
}
|
||||
@@ -634,12 +634,20 @@ fn expand(seed: &[u8; 32], label: &[u8], n: usize) -> Vec<u8> {
|
||||
h.update(label);
|
||||
h.update(counter.to_le_bytes());
|
||||
out.extend_from_slice(&h.finalize());
|
||||
counter += 1;
|
||||
counter = counter.saturating_add(1);
|
||||
}
|
||||
out.truncate(n);
|
||||
out
|
||||
}
|
||||
|
||||
/// Sixteen bytes of file identifier from `seed` (SHA-256 in counter mode, label `id`).
|
||||
///
|
||||
/// `/ID` is written in the clear. Deriving it the same way as the file key keeps that public
|
||||
/// value from being an unkeyed hash of the seed.
|
||||
pub fn file_id(seed: &[u8; 32]) -> Vec<u8> {
|
||||
expand(seed, b"id", 16)
|
||||
}
|
||||
|
||||
/// Build the `/Encrypt` values and an authenticated (owner) handler for a new encryption.
|
||||
pub fn create(params: &NewEncryption, id0: &[u8]) -> Result<SecurityHandler, CryptError> {
|
||||
// Bits 7–8 and 13–32 must be 1; bits 1–2 must be 0 (§7.6.4.2).
|
||||
|
||||
@@ -4,6 +4,16 @@ fn hex(s: &str) -> Vec<u8> {
|
||||
(0..s.len()).step_by(2).map(|i| u8::from_str_radix(&s[i..i + 2], 16).unwrap()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn file_id_is_a_one_way_16_byte_identifier() {
|
||||
let seed = [7u8; 32];
|
||||
let id = file_id(&seed);
|
||||
assert_eq!(id.len(), 16);
|
||||
assert_eq!(id, file_id(&seed));
|
||||
assert_ne!(id, seed[..16]);
|
||||
assert_ne!(id, file_id(&[8u8; 32]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rc4_reference_vectors() {
|
||||
assert_eq!(rc4(b"Key", b"Plaintext"), hex("bbf316e8d940af0ad3"));
|
||||
|
||||
@@ -15,6 +15,8 @@ pdfcraft-content = { workspace = true }
|
||||
pdfcraft-fonts = { workspace = true }
|
||||
pdfcraft-model = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
# A backdrop copy's tag records a hash of the operators before the fill it turned off (backdrop.rs).
|
||||
sha2 = "0.11"
|
||||
kurbo = { workspace = true }
|
||||
# Display order of right-to-left lines in added text, and reading and writing order in Edit text;
|
||||
# already in the tree via the interface.
|
||||
|
||||
@@ -67,5 +67,23 @@ impl Content {
|
||||
}
|
||||
}
|
||||
|
||||
fn align_code(a: Align) -> i64 {
|
||||
match a {
|
||||
Align::Left => 0,
|
||||
Align::Center => 1,
|
||||
Align::Right => 2,
|
||||
Align::Justify => 3,
|
||||
}
|
||||
}
|
||||
|
||||
fn align_from(code: Option<i64>) -> Align {
|
||||
match code {
|
||||
Some(1) => Align::Center,
|
||||
Some(2) => Align::Right,
|
||||
Some(3) => Align::Justify,
|
||||
_ => Align::Left,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod arabic_tests;
|
||||
@@ -24,7 +24,7 @@ fn cluster(id: u32, advance: f64) -> ShapedCluster {
|
||||
fn line(clusters: Vec<ShapedCluster>, rtl: bool) -> LaidLine {
|
||||
let text = clusters.iter().map(|c| c.text.as_str()).collect();
|
||||
let width = clusters.iter().map(|c| c.advance).sum::<f64>() * item().size;
|
||||
(text, rtl, vec![Piece::Shaped(clusters)], width)
|
||||
(text, rtl, 0, vec![Piece::Shaped(clusters)], width)
|
||||
}
|
||||
|
||||
/// A glyph outline: a box on the baseline, `advance` em wide.
|
||||
@@ -147,7 +147,7 @@ fn an_item_below_the_old_limit_is_drawn_exactly_as_before() {
|
||||
let space = ShapedCluster { script: ShapedScript::Arabic, glyphs: vec![(6, [0.0, 0.0])], advance: 0.25, text: " ".into() };
|
||||
let ligature = ShapedCluster { script: ShapedScript::Arabic, glyphs: vec![(4, [0.0, 0.0]), (5, [-0.1, 0.2])], advance: 0.6, text: "لا".into() };
|
||||
let mixed: LaidLine =
|
||||
("Hi ب".into(), false, vec![Piece::Latin("Hi ".into()), Piece::Shaped(vec![cluster(1, 0.5), cluster(2, 0.5), space, ligature])], 4.0);
|
||||
("Hi ب".into(), false, 0, vec![Piece::Latin("Hi ".into()), Piece::Shaped(vec![cluster(1, 0.5), cluster(2, 0.5), space, ligature])], 4.0);
|
||||
let rtl = line(vec![cluster(2, 0.5), cluster(9, 0.75)], true);
|
||||
let laid = vec![mixed, rtl];
|
||||
let mut doc = Document::new_empty();
|
||||
|
||||
@@ -1,8 +1,11 @@
|
||||
use super::layout::{
|
||||
Piece, arabic_error, hebrew_error, is_arabic, is_hebrew, is_thai, latin_width, lines, norm, shaped_layout, text_rect, thai_error, wrapped,
|
||||
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::*;
|
||||
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,
|
||||
};
|
||||
|
||||
fn font_name(base: &str) -> String {
|
||||
format!("PCF{}", base.replace('-', ""))
|
||||
@@ -13,8 +16,26 @@ fn font_name(base: &str) -> String {
|
||||
pub(super) const GLYPHS_PER_FONT: usize = 240;
|
||||
|
||||
/// A line of a shaped-text item after layout: its text, whether its paragraph runs right to left,
|
||||
/// its pieces in drawing order and its width at the item's size.
|
||||
pub(super) type LaidLine = (String, bool, Vec<Piece>, f64);
|
||||
/// its paragraph, its pieces in drawing order and its width at the item's size.
|
||||
pub(super) type LaidLine = (String, bool, usize, Vec<Piece>, f64);
|
||||
|
||||
/// Where line `i` (`w` wide unstretched, with `spaces` spaces) starts in the box `r`, and its word
|
||||
/// spacing. `paragraphs` holds each line's paragraph: a line takes its paragraph's alignment, and
|
||||
/// every line of a justified paragraph but its last is stretched to the box's width.
|
||||
fn placed(t: &AddedText, r: [f64; 4], paragraphs: &[usize], i: usize, w: f64, spaces: usize, rtl: bool) -> (f64, f64) {
|
||||
let paragraph = paragraphs.get(i).copied().unwrap_or(0);
|
||||
let align = t.paragraph_align(paragraph);
|
||||
let ends_paragraph = paragraphs.get(i + 1) != Some(¶graph);
|
||||
let tw = if align == Align::Justify && !ends_paragraph && spaces > 0 { ((r[2] - r[0]) - w).max(0.0) / spaces as f64 } else { 0.0 };
|
||||
let x = match align {
|
||||
// A right-to-left paragraph's unstretched last line ends at the right edge.
|
||||
Align::Justify if rtl => r[2] - w - tw * spaces as f64,
|
||||
Align::Left | Align::Justify => r[0],
|
||||
Align::Center => r[0] + ((r[2] - r[0]) - w) / 2.0,
|
||||
Align::Right => r[2] - w,
|
||||
};
|
||||
(x, tw)
|
||||
}
|
||||
|
||||
/// Draw a text item that has Arabic, Hebrew or Thai in it. Each line is laid out in display order; their glyphs
|
||||
/// come from Type 3 fonts drawn from the craft-fonts face's outlines (no font file is embedded),
|
||||
@@ -22,7 +43,7 @@ pub(super) type LaidLine = (String, bool, Vec<Piece>, f64);
|
||||
fn draw_shaped(doc: &mut Document, t: &AddedText, taken: &Dict, fonts: &mut Dict, out: &mut Vec<u8>) -> Result<(), EditError> {
|
||||
let laid = wrapped(t)
|
||||
.into_iter()
|
||||
.map(|(line, rtl)| shaped_layout(t, &line, rtl).map(|(pieces, w)| (line, rtl, pieces, w)))
|
||||
.map(|(line, rtl, paragraph)| shaped_layout(t, &line, rtl).map(|(pieces, w)| (line, rtl, paragraph, pieces, w)))
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
draw_laid_shaped(doc, t, &laid, taken, fonts, out, shaped_glyph)
|
||||
}
|
||||
@@ -44,7 +65,7 @@ pub(super) fn draw_laid_shaped(
|
||||
// one of the fonts, so copy and search get each character exactly once.
|
||||
let mut keys: Vec<&ShapedCluster> = Vec::new();
|
||||
let mut index: HashMap<ClusterKey, usize> = HashMap::new();
|
||||
for c in laid.iter().flat_map(|(_, _, pieces, _)| pieces).flat_map(|p| match p {
|
||||
for c in laid.iter().flat_map(|(_, _, _, pieces, _)| pieces).flat_map(|p| match p {
|
||||
Piece::Shaped(clusters) => clusters.as_slice(),
|
||||
Piece::Latin(_) => &[],
|
||||
}) {
|
||||
@@ -89,21 +110,14 @@ pub(super) fn draw_laid_shaped(
|
||||
if t.char_spacing != 0.0 {
|
||||
out.extend(format!("{} Tc\n", n(t.char_spacing)).bytes());
|
||||
}
|
||||
for (i, (line, rtl, pieces, w)) in laid.iter().enumerate() {
|
||||
let paragraphs: Vec<usize> = laid.iter().map(|(_, _, p, ..)| *p).collect();
|
||||
for (i, (line, rtl, _, pieces, w)) in laid.iter().enumerate() {
|
||||
// Shaped glyphs are painted in visual order. Keep the original line's typing order
|
||||
// explicitly, including marks, ligatures, digits and mixed-script punctuation.
|
||||
let logical: String = line.encode_utf16().map(|u| format!("{u:04X}")).collect();
|
||||
out.extend(format!("/Span <</ActualText <FEFF{logical}>>> BDC\n").bytes());
|
||||
let spaces = line.matches(' ').count();
|
||||
// Justified: the spaces of every line but the last stretch to fill the box.
|
||||
let tw = if t.align == Align::Justify && i + 1 < laid.len() && spaces > 0 { ((r[2] - r[0]) - w).max(0.0) / spaces as f64 } else { 0.0 };
|
||||
let x = match t.align {
|
||||
// A right-to-left paragraph's unstretched last line ends at the right edge.
|
||||
Align::Justify if *rtl => r[2] - w - tw * spaces as f64,
|
||||
Align::Left | Align::Justify => r[0],
|
||||
Align::Center => r[0] + ((r[2] - r[0]) - w) / 2.0,
|
||||
Align::Right => r[2] - w,
|
||||
};
|
||||
let (x, tw) = placed(t, r, ¶graphs, i, *w, spaces, *rtl);
|
||||
let y = r[3] - (i as f64 * 1.2 + 0.95) * t.size;
|
||||
let mut pen = x;
|
||||
let mut current: Option<&str> = None;
|
||||
@@ -284,20 +298,14 @@ pub(super) fn draw(doc: &mut Document, c: &Content, view: [f64; 6], taken: &Dict
|
||||
if t.char_spacing != 0.0 {
|
||||
out.extend(format!("{} Tc\n", n(t.char_spacing)).bytes());
|
||||
}
|
||||
let all = lines(t);
|
||||
for (i, line) in all.iter().enumerate() {
|
||||
let all = wrapped(t);
|
||||
let paragraphs: Vec<usize> = all.iter().map(|(_, _, p)| *p).collect();
|
||||
for (i, (line, ..)) in all.iter().enumerate() {
|
||||
let w = latin_width(t, line);
|
||||
let x = match t.align {
|
||||
Align::Left | Align::Justify => r[0],
|
||||
Align::Center => r[0] + ((r[2] - r[0]) - w) / 2.0,
|
||||
Align::Right => r[2] - w,
|
||||
};
|
||||
// Baseline: 0.8 em below the line top.
|
||||
let y = r[3] - (i as f64 * 1.2 + 0.95) * t.size;
|
||||
// Justified: word spacing makes every line but the last fill the box.
|
||||
let spaces = line.matches(' ').count();
|
||||
let tw =
|
||||
if t.align == Align::Justify && i + 1 < all.len() && spaces > 0 { ((r[2] - r[0]) - w).max(0.0) / spaces as f64 } else { 0.0 };
|
||||
// Justified: word spacing makes every line of a paragraph but its last fill the box.
|
||||
let (x, tw) = placed(t, r, ¶graphs, i, w, line.matches(' ').count(), false);
|
||||
out.extend(format!("1 0 0 1 {} {} Tm {} Tw ", n(x), n(y), n(tw)).bytes());
|
||||
out.extend(literal(&win_ansi(line)));
|
||||
out.extend_from_slice(b" Tj\n");
|
||||
@@ -347,15 +355,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));
|
||||
d.set(
|
||||
b"Align".to_vec(),
|
||||
Object::Int(match t.align {
|
||||
Align::Left => 0,
|
||||
Align::Center => 1,
|
||||
Align::Right => 2,
|
||||
Align::Justify => 3,
|
||||
}),
|
||||
);
|
||||
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);
|
||||
if !aligns.is_empty() {
|
||||
d.set(b"Aligns".to_vec(), Object::Array(aligns.iter().map(|a| a.map_or(Object::Null, |a| Object::Int(align_code(a)))).collect()));
|
||||
}
|
||||
d.set(b"Rect".to_vec(), arr(&text_rect(t)));
|
||||
if t.char_spacing != 0.0 {
|
||||
d.set(b"CharSpacing".to_vec(), Object::Real(t.char_spacing));
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
use super::types::{AddedImage, AddedText};
|
||||
use super::*;
|
||||
use super::{
|
||||
Content, Document, EditError, GlyphError, Level, ObjRef, Object, ParagraphBidiInfo, ShapedCluster, ShapedScript, shape_arabic, shape_hebrew,
|
||||
shape_thai,
|
||||
};
|
||||
|
||||
pub(super) fn nums(doc: &Document, o: Option<&Object>) -> Vec<f64> {
|
||||
o.map(|o| doc.resolve(o)).and_then(|a| a.as_array().map(|a| a.iter().filter_map(Object::as_f64).collect())).unwrap_or_default()
|
||||
@@ -17,7 +20,7 @@ pub(super) fn latin_width(t: &AddedText, s: &str) -> f64 {
|
||||
|
||||
/// The lines of a text item after wrapping to its box width.
|
||||
pub fn lines(t: &AddedText) -> Vec<String> {
|
||||
wrapped(t).into_iter().map(|(line, _)| line).collect()
|
||||
wrapped(t).into_iter().map(|(line, ..)| line).collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -27,13 +30,13 @@ thread_local! {
|
||||
}
|
||||
|
||||
/// [`lines`], each with whether its paragraph runs right to left (its first strong character
|
||||
/// does).
|
||||
pub(super) fn wrapped(t: &AddedText) -> Vec<(String, bool)> {
|
||||
/// does) and which paragraph it is in.
|
||||
pub(super) fn wrapped(t: &AddedText) -> Vec<(String, bool, usize)> {
|
||||
#[cfg(test)]
|
||||
WRAP_CALLS.with(|c| c.set(c.get().saturating_add(1)));
|
||||
let width = (t.rect[2] - t.rect[0]).max(t.size);
|
||||
let mut out = Vec::new();
|
||||
for para in t.text.split('\n') {
|
||||
for (index, para) in t.text.split('\n').enumerate() {
|
||||
// Arabic or Hebrew: laid out with the bidirectional algorithm and shaped.
|
||||
let rtl_script = para.chars().any(|c| is_arabic(c) || is_hebrew(c));
|
||||
let thai = para.chars().any(is_thai);
|
||||
@@ -41,7 +44,7 @@ pub(super) fn wrapped(t: &AddedText) -> Vec<(String, bool)> {
|
||||
&& !rtl_script
|
||||
&& let Ok(lines) = thai_lines(t, para, width)
|
||||
{
|
||||
out.extend(lines.into_iter().map(|line| (line, false)));
|
||||
out.extend(lines.into_iter().map(|line| (line, false, index)));
|
||||
continue;
|
||||
}
|
||||
let rtl = rtl_script && unicode_bidi::get_base_direction(para) == unicode_bidi::Direction::Rtl;
|
||||
@@ -57,7 +60,7 @@ pub(super) fn wrapped(t: &AddedText) -> Vec<(String, bool)> {
|
||||
let candidate_w =
|
||||
if rtl_script || thai { if line.is_empty() { measure(word) } else { line_w + space + measure(word) } } else { measure(&candidate) };
|
||||
if !line.is_empty() && candidate_w > width {
|
||||
out.push((std::mem::take(&mut line), rtl));
|
||||
out.push((std::mem::take(&mut line), rtl, index));
|
||||
line = word.to_string();
|
||||
line_w = measure(word);
|
||||
} else {
|
||||
@@ -65,7 +68,7 @@ pub(super) fn wrapped(t: &AddedText) -> Vec<(String, bool)> {
|
||||
line_w = candidate_w;
|
||||
}
|
||||
}
|
||||
out.push((line, rtl));
|
||||
out.push((line, rtl, index));
|
||||
}
|
||||
out
|
||||
}
|
||||
@@ -139,7 +142,7 @@ pub fn first_undrawable(t: &AddedText) -> Option<char> {
|
||||
return t.text.split('\n').find_map(pdfcraft_fonts::first_non_win_ansi);
|
||||
}
|
||||
// What `shaped_layout` leaves to the standard font, exactly as `draw_shaped` splits it.
|
||||
wrapped(t).into_iter().find_map(|(line, rtl)| {
|
||||
wrapped(t).into_iter().find_map(|(line, rtl, _)| {
|
||||
let (pieces, _) = shaped_layout(t, &line, rtl).ok()?;
|
||||
pieces.iter().find_map(|p| match p {
|
||||
Piece::Latin(s) => pdfcraft_fonts::first_non_win_ansi(s),
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use super::draw::{draw, params};
|
||||
use super::layout::{first_undrawable, is_thai, nums, shaped_arabic, thai_error};
|
||||
use super::types::{Added, AddedImage, AddedText, Align, CHAR_SPACING_LIMIT, Family, MarkerScan, TAG};
|
||||
use super::*;
|
||||
use super::types::{Added, AddedImage, AddedText, CHAR_SPACING_LIMIT, Family, MarkerScan, TAG};
|
||||
use super::{Content, Dict, Document, EditError, GlyphError, MarkKind, ObjRef, Object, Stream, align_from, check, contents, page_list, place_tagged};
|
||||
|
||||
fn parse(doc: &Document, d: &Dict) -> Option<Content> {
|
||||
let r = nums(doc, d.get(b"Rect"));
|
||||
@@ -10,20 +10,27 @@ fn parse(doc: &Document, d: &Dict) -> Option<Content> {
|
||||
b"Text" => {
|
||||
let (family, bold, italic) = Family::from_base(d.name(b"Font").unwrap_or(b"Helvetica"));
|
||||
let c = nums(doc, d.get(b"Color"));
|
||||
let text = d.get(b"Text").and_then(|t| doc.resolve(t).as_string().map(|s| s.to_text())).unwrap_or_default();
|
||||
let align = align_from(d.int(b"Align"));
|
||||
// At most one entry per paragraph, whatever the file says.
|
||||
let aligns = d
|
||||
.get(b"Aligns")
|
||||
.and_then(|a| {
|
||||
doc.resolve(a)
|
||||
.as_array()
|
||||
.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 {
|
||||
rect,
|
||||
text: d.get(b"Text").and_then(|t| doc.resolve(t).as_string().map(|s| s.to_text())).unwrap_or_default(),
|
||||
text,
|
||||
family,
|
||||
bold,
|
||||
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] },
|
||||
align: match d.int(b"Align") {
|
||||
Some(1) => Align::Center,
|
||||
Some(2) => Align::Right,
|
||||
Some(3) => Align::Justify,
|
||||
_ => Align::Left,
|
||||
},
|
||||
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),
|
||||
}))
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use super::layout::norm;
|
||||
use super::*;
|
||||
use super::{Content, MarkKind, ObjRef, Std14};
|
||||
|
||||
pub(super) const TAG: &str = "Added";
|
||||
|
||||
@@ -104,6 +104,16 @@ pub struct AddedText {
|
||||
pub align: Align,
|
||||
/// Extra space after every character, in points: the PDF's character spacing (`Tc`).
|
||||
pub char_spacing: f64,
|
||||
/// Paragraphs (lines typed with Enter) aligned other than [`AddedText::align`], by index;
|
||||
/// `None` and paragraphs past the end follow `align` ([`crate::paragraph_align`]).
|
||||
pub aligns: Vec<Option<Align>>,
|
||||
}
|
||||
|
||||
impl AddedText {
|
||||
/// Paragraph `i`'s alignment.
|
||||
pub fn paragraph_align(&self, i: usize) -> Align {
|
||||
crate::paragraph_align::align_of(&self.aligns, i, self.align)
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for AddedText {
|
||||
@@ -117,6 +127,7 @@ impl Default for AddedText {
|
||||
size: 12.0,
|
||||
color: [0.0; 3],
|
||||
align: Align::Left,
|
||||
aligns: Vec::new(),
|
||||
char_spacing: 0.0,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,7 +5,7 @@ use super::place::{
|
||||
END, Isolation, add_page_resources, add_resources, begin, check, check_on_top, contents, free_font_name, isolation, page_fonts, page_list, place,
|
||||
place_inside_wrapper, stream_tag, text_op, undrawable, wrapper_role,
|
||||
};
|
||||
use super::*;
|
||||
use super::{Document, EditError, Object, added, backdrop, helvetica_width};
|
||||
|
||||
/// Add a header and footer to `pages` (0-based). With `replace`, existing headers and footers on
|
||||
/// those pages are removed first (Acrobat's Replace Existing).
|
||||
@@ -199,7 +199,9 @@ pub fn add_watermark(doc: &mut Document, pages: &[usize], wm: &Watermark, replac
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Add a solid-colour background behind the content of `pages`.
|
||||
/// Add a solid-colour background behind the content of `pages`. With `bg.replace_backdrop`, a
|
||||
/// white backdrop a page paints itself is replaced first, so the background shows (see
|
||||
/// [`backdrop`]); a picture backdrop (a scan) still hides it.
|
||||
pub fn add_background(doc: &mut Document, pages: &[usize], bg: &Background, replace: bool) -> Result<(), EditError> {
|
||||
let all = page_list(doc);
|
||||
check(pages, all.len())?;
|
||||
@@ -208,7 +210,10 @@ pub fn add_background(doc: &mut Document, pages: &[usize], bg: &Background, repl
|
||||
}
|
||||
let opacity = if bg.opacity.is_finite() { bg.opacity.clamp(0.0, 1.0) } else { 1.0 };
|
||||
for &i in pages {
|
||||
let page = page_list(doc)[i].clone();
|
||||
let mut page = page_list(doc)[i].clone();
|
||||
if bg.replace_backdrop && backdrop::replace(doc, &page)? {
|
||||
page = page_list(doc)[i].clone();
|
||||
}
|
||||
let (w, h) = page.display_size(doc);
|
||||
let mut content = begin(MarkKind::Background, "Background", page.view_matrix(doc));
|
||||
match &bg.source {
|
||||
@@ -231,13 +236,18 @@ pub fn add_background(doc: &mut Document, pages: &[usize], bg: &Background, repl
|
||||
|
||||
/// Remove marks of `kind` from `pages`; returns how many were removed. Wrappers left with
|
||||
/// nothing after them go too, restoring the original content list; a wrapper that content
|
||||
/// after it still relies on (another tool's appended stream) stays.
|
||||
/// after it still relies on (another tool's appended stream) stays. Removing backgrounds also
|
||||
/// turns a backdrop [`add_background`] replaced back on where that is still safe; the pages where
|
||||
/// it isn't are [`backdrops_left_off`].
|
||||
pub fn remove_marks(doc: &mut Document, pages: &[usize], kind: MarkKind) -> Result<usize, EditError> {
|
||||
let all = page_list(doc);
|
||||
check(pages, all.len())?;
|
||||
let mut removed = 0;
|
||||
for &i in pages {
|
||||
let page = &all[i];
|
||||
if kind == MarkKind::Background {
|
||||
backdrop::restore(doc, page)?;
|
||||
}
|
||||
let list = contents(doc, page)?;
|
||||
let before = list.len();
|
||||
let mut kept: Vec<Object> = list.into_iter().filter(|o| stream_tag(doc, o).as_deref() != Some(kind.tag())).collect();
|
||||
|
||||
@@ -0,0 +1,584 @@
|
||||
//! A page's own backdrop: an opaque white fill (or a picture) covering the whole visible page
|
||||
//! before anything else is drawn. Many writers paint one (browsers' Save as PDF, print drivers;
|
||||
//! scans are a page-sized picture), and it hides anything placed behind the content, so a
|
||||
//! background added behind such a page never shows.
|
||||
//!
|
||||
//! A white fill can be replaced: the one fill operator becomes `n` (end the path without
|
||||
//! painting), which looks the same on white paper. The page then gets a copy of the content
|
||||
//! stream that held it, tagged `/PCBackdrop << /Index n /Op (f) /Before <SHA-256> /Was [num gen] >>`:
|
||||
//! how many of the copy's operators come before the `n`, the operator it stands in for, a hash of
|
||||
//! those operators (their values, not their spacing: redaction writes a stream out again with
|
||||
//! other whitespace), and the number of the stream it was copied from. The stream itself is left
|
||||
//! alone (other pages may share it). [`restore`] turns the fill back on when the background is
|
||||
//! removed, even after the page was edited or redacted, as long as the operators before the fill
|
||||
//! are unchanged and the fill would again be the first thing painted, covering the page.
|
||||
//! Otherwise the fill stays off, and [`backdrops_left_off`] names those pages. A picture can't be
|
||||
//! replaced without losing it, so it is only reported.
|
||||
//!
|
||||
//! The tag holds no page content and no reference that keeps another object alive (`/Was` is two
|
||||
//! numbers, not a reference): a reference to the original stream would keep text in the file
|
||||
//! that a redaction, Remove Hidden Information or Edit Text removed from the copy.
|
||||
//!
|
||||
//! Detection is deliberately strict: only one rectangle (`re`), in DeviceGray, DeviceRGB or
|
||||
//! DeviceCMYK, opaque, unmasked, normally blended and with the identity transfer function as the
|
||||
//! graphics state stands after every `gs` so far (each sets only its own keys), with an
|
||||
//! axis-aligned transform, filled before any other painting, and covering the crop box.
|
||||
//! Anything else is real content and stays.
|
||||
|
||||
use pdfcraft_content::{Matrix, Op, Pieces};
|
||||
use pdfcraft_cos::{DecodeBudget, Dict, Document, ObjRef, Object, PdfString, Stream};
|
||||
use sha2::{Digest, Sha256};
|
||||
|
||||
use crate::{EditError, MarkKind};
|
||||
|
||||
/// The dictionary key of a backdrop copy's tag.
|
||||
const TAG: &[u8] = b"PCBackdrop";
|
||||
/// The fill operators a backdrop can be painted with, and so the only ones a tag may restore.
|
||||
const FILLS: [&[u8]; 3] = [b"f", b"F", b"f*"];
|
||||
|
||||
/// How much of a page's content is read looking for a backdrop: it has to come first.
|
||||
const SCAN_BYTES: usize = 64 * 1024;
|
||||
/// How many operators are walked before giving up.
|
||||
const SCAN_OPS: usize = 4096;
|
||||
/// How far (in points) a backdrop may fall short of the crop box and still count as covering it.
|
||||
const COVER_EPS: f64 = 1.0;
|
||||
/// Components at least this close to white (per channel) count as white: a near-white fill
|
||||
/// (`0.99 g`) is a backdrop too, and replacing it changes the page by at most 2%.
|
||||
const WHITE: f64 = 0.98;
|
||||
|
||||
/// What paints a page's backdrop.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Backdrop {
|
||||
/// An opaque white fill: replaceable.
|
||||
Fill,
|
||||
/// A picture covering the page (a scan): a background behind it stays hidden.
|
||||
Image,
|
||||
}
|
||||
|
||||
/// Where a replaceable fill is: the content streams (references in `/Contents` order, untagged
|
||||
/// ones only), their joined bytes, where each starts in them, and the fill operator's joined
|
||||
/// byte range.
|
||||
struct Found {
|
||||
refs: Vec<(usize, ObjRef)>,
|
||||
pieces: Pieces,
|
||||
starts: Vec<usize>,
|
||||
op: std::ops::Range<usize>,
|
||||
}
|
||||
|
||||
impl Found {
|
||||
/// The piece holding the fill operator, and the operator's offset in it.
|
||||
fn place(&self) -> Option<(usize, usize)> {
|
||||
let piece = self.pieces.piece_of(self.op.start);
|
||||
Some((piece, self.op.start.checked_sub(*self.starts.get(piece)?)?))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct State {
|
||||
ctm: Matrix,
|
||||
/// Clip in default user space, when it is a known rectangle; `None` = unknown shape.
|
||||
clip: Option<[f64; 4]>,
|
||||
/// The fill colour is white.
|
||||
white: bool,
|
||||
/// Non-stroking colour space components (1, 3, 4), or 0 for a space we don't read.
|
||||
space: usize,
|
||||
paint: Paint,
|
||||
}
|
||||
|
||||
/// The graphics-state parameters (ExtGState, ISO 32000-2 §8.4.5) that decide whether a fill
|
||||
/// paints its colour as given. A `gs` sets only the keys its dictionary has, so each is kept on
|
||||
/// its own: a later dictionary that leaves one out keeps the earlier value.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
struct Paint {
|
||||
/// Non-stroking alpha (`ca`) is 1.
|
||||
full_alpha: bool,
|
||||
/// No soft mask (`SMask` is `/None`).
|
||||
no_soft_mask: bool,
|
||||
/// The blend mode (`BM`) is Normal or Compatible.
|
||||
normal_blend: bool,
|
||||
/// The transfer function (`TR`, or `TR2`, which takes precedence) is the identity: a
|
||||
/// function could turn white into any colour.
|
||||
identity_transfer: bool,
|
||||
}
|
||||
|
||||
impl Paint {
|
||||
const INITIAL: Paint = Paint { full_alpha: true, no_soft_mask: true, normal_blend: true, identity_transfer: true };
|
||||
|
||||
/// A fill paints its colour exactly, opaque.
|
||||
fn plain(self) -> bool {
|
||||
self.full_alpha && self.no_soft_mask && self.normal_blend && self.identity_transfer
|
||||
}
|
||||
}
|
||||
|
||||
/// The backdrop `page` (0-based) paints, if any. Finding the page walks the page tree, so to
|
||||
/// check many pages use [`page_backdrops`], which walks it once.
|
||||
pub fn page_backdrop(doc: &Document, page: usize) -> Result<Option<Backdrop>, EditError> {
|
||||
let all = pdfcraft_model::pages(doc);
|
||||
let p = all.get(page).ok_or(EditError::NoSuchPage(page))?;
|
||||
Ok(scan(doc, p, None).map(|(b, _)| b))
|
||||
}
|
||||
|
||||
/// The backdrop each of `pages` (0-based) paints, in the same order, walking the page tree once.
|
||||
/// A page past the end has none, and doesn't hide what the others paint: a page count taken
|
||||
/// elsewhere (the viewer's) can disagree with the page tree's on a malformed document.
|
||||
pub fn page_backdrops(doc: &Document, pages: &[usize]) -> Vec<Option<Backdrop>> {
|
||||
let all = pdfcraft_model::pages(doc);
|
||||
pages.iter().map(|&p| all.get(p).and_then(|page| scan(doc, page, None)).map(|(b, _)| b)).collect()
|
||||
}
|
||||
|
||||
/// Pages (0-based, ascending) whose own white backdrop [`replace`] turned off and [`restore`]
|
||||
/// couldn't turn back on: a tagged copy is still in their content, with no background over it.
|
||||
/// They look the same on white paper.
|
||||
pub fn backdrops_left_off(doc: &Document) -> Vec<usize> {
|
||||
let tag_of = |o: &Object| crate::place::stream_tag(doc, o);
|
||||
let copy = |o: &Object| doc.resolve(o).as_dict().is_some_and(|d| d.get(TAG).is_some());
|
||||
pdfcraft_model::pages(doc)
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, p)| {
|
||||
let list: Vec<Object> = match p.dict.get(b"Contents").map(|c| doc.resolve(c)).as_deref() {
|
||||
Some(Object::Array(a)) => a.clone(),
|
||||
Some(_) => p.dict.get(b"Contents").cloned().into_iter().collect(),
|
||||
None => Vec::new(),
|
||||
};
|
||||
list.iter().any(copy) && !list.iter().any(|o| tag_of(o).as_deref() == Some(MarkKind::Background.tag()))
|
||||
})
|
||||
.map(|(i, _)| i)
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Replace `page`'s white backdrop fill, if it has one (see the module doc). Returns whether it
|
||||
/// did; when it did, `page` no longer matches the document. A picture backdrop is left alone.
|
||||
pub(crate) fn replace(doc: &mut Document, page: &pdfcraft_model::Page) -> Result<bool, EditError> {
|
||||
let Some((Backdrop::Fill, Some(found))) = scan(doc, page, None) else { return Ok(false) };
|
||||
let Some((piece, at)) = found.place() else { return Ok(false) };
|
||||
let op = found.pieces.data().get(found.op.clone()).unwrap_or_default().to_vec();
|
||||
let edited = found.pieces.splice([(found.op.clone(), b"n".to_vec())]);
|
||||
let (Some(&(_, original)), Some(bytes)) = (found.refs.get(piece), edited.get(piece)) else { return Ok(false) };
|
||||
// The `n` among the copy's own operators. A copy whose fill can't be found that way again is
|
||||
// not made: there would be no safe way back.
|
||||
let parsed = pdfcraft_content::parse(head(bytes));
|
||||
let Some(index) = parsed.ops.iter().position(|o| o.span.start == at && o.op == b"n") else { return Ok(false) };
|
||||
let Some(before) = parsed.ops.get(..index) else { return Ok(false) };
|
||||
let mut note = Dict::new();
|
||||
note.set(b"Index".to_vec(), Object::Int(i64::try_from(index).unwrap_or(i64::MAX)));
|
||||
note.set(b"Op".to_vec(), Object::String(PdfString::literal(op)));
|
||||
note.set(b"Before".to_vec(), Object::String(PdfString { bytes: ops_hash(before), hex: true }));
|
||||
note.set(b"Was".to_vec(), Object::Array(vec![Object::Int(original.num.into()), Object::Int(original.generation.into())]));
|
||||
// The copy keeps the original's dictionary (unknown entries included) less what describes
|
||||
// the old encoding; `scan` refused streams whose bytes live in an external file (`/F`).
|
||||
let Object::Stream(source) = &*doc.get(original) else { return Ok(false) };
|
||||
let mut dict = source.dict.clone();
|
||||
for key in [&b"Length"[..], b"DL", TAG] {
|
||||
dict.remove(key);
|
||||
}
|
||||
dict.set(TAG.to_vec(), Object::Dict(note));
|
||||
let copy = doc.add(Object::Stream(Stream::flate(dict, bytes)));
|
||||
// scan accepts only one execution of this stream on the page. Other pages keep the
|
||||
// original stream; ambiguous repeated executions are never rewritten.
|
||||
let mut list = crate::place::contents(doc, page)?;
|
||||
let mut replaced = false;
|
||||
for entry in list.iter_mut().filter(|o| matches!(o, Object::Ref(r) if *r == original)) {
|
||||
*entry = Object::Ref(copy);
|
||||
replaced = true;
|
||||
}
|
||||
if replaced {
|
||||
doc.update_dict(page.obj, |d| d.set(b"Contents".to_vec(), Object::Array(list)))?;
|
||||
}
|
||||
Ok(replaced)
|
||||
}
|
||||
|
||||
/// Turn the fills [`replace`] turned off on `page` back on, where [`restored_copy`] finds that
|
||||
/// safe; a copy listed in several slots is restored in each. Returns how many slots it restored.
|
||||
/// A copy it can't restore stays as it is, tag and all, so [`backdrops_left_off`] names its page.
|
||||
pub(crate) fn restore(doc: &mut Document, page: &pdfcraft_model::Page) -> Result<usize, EditError> {
|
||||
let mut list = crate::place::contents(doc, page)?;
|
||||
// Per copy: the stream that takes its place, or `None` when it stays.
|
||||
let mut done: Vec<(ObjRef, Option<ObjRef>)> = Vec::new();
|
||||
let mut restored = 0;
|
||||
for entry in list.iter_mut() {
|
||||
let Object::Ref(copy) = *entry else { continue };
|
||||
let with = match done.iter().find(|(c, _)| *c == copy) {
|
||||
Some(&(_, with)) => with,
|
||||
None => {
|
||||
let with = restored_copy(doc, page, copy).map(|(bytes, dict, was)| {
|
||||
// The stream it was copied from, while that is still here with these bytes
|
||||
// (other pages may share it): the page is then exactly as it was. `/Was` is
|
||||
// only a number, and a full save renumbers objects, so the bytes decide.
|
||||
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())
|
||||
}
|
||||
_ => false,
|
||||
};
|
||||
match was.filter(same) {
|
||||
Some(w) => w,
|
||||
None => doc.add(Object::Stream(Stream::flate(dict, &bytes))),
|
||||
}
|
||||
});
|
||||
done.push((copy, with));
|
||||
with
|
||||
}
|
||||
};
|
||||
if let Some(with) = with {
|
||||
*entry = Object::Ref(with);
|
||||
restored += 1;
|
||||
}
|
||||
}
|
||||
if restored > 0 {
|
||||
doc.update_dict(page.obj, |d| d.set(b"Contents".to_vec(), Object::Array(list)))?;
|
||||
}
|
||||
Ok(restored)
|
||||
}
|
||||
|
||||
/// `copy` (a stream [`replace`] wrote for `page`) with its fill turned back on: the bytes, its
|
||||
/// dictionary without the tag, and the stream it was copied from. `None` when it isn't such a
|
||||
/// copy, or when turning the fill on could paint over something: the operators before the fill
|
||||
/// changed since (their hash no longer matches), or the page would no longer paint the fill
|
||||
/// first, covering it. What comes after the fill (an edit, a redaction) is kept as it is.
|
||||
fn restored_copy(doc: &Document, page: &pdfcraft_model::Page, copy: ObjRef) -> Option<(Vec<u8>, Dict, Option<ObjRef>)> {
|
||||
let obj = doc.get(copy);
|
||||
let Object::Stream(s) = &*obj else { return None };
|
||||
let note = s.dict.get(TAG).map(|n| doc.resolve(n))?;
|
||||
let note = note.as_dict()?;
|
||||
let index = usize::try_from(note.get(b"Index")?.as_int()?).ok()?;
|
||||
let op = note.get(b"Op")?.as_string()?.bytes.as_slice();
|
||||
if !FILLS.contains(&op) {
|
||||
return None;
|
||||
}
|
||||
let hash = note.get(b"Before")?.as_string()?;
|
||||
let bytes = DecodeBudget::new(SCAN_BYTES, 0).decode_strict(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)?;
|
||||
if fill.op != b"n" || !fill.operands.is_empty() || ops_hash(parsed.ops.get(..index)?) != hash.bytes {
|
||||
return None;
|
||||
}
|
||||
let mut out = Vec::with_capacity(bytes.len().saturating_add(op.len()));
|
||||
out.extend_from_slice(bytes.get(..fill.span.start)?);
|
||||
out.extend_from_slice(op);
|
||||
out.extend_from_slice(bytes.get(fill.span.end..)?);
|
||||
let (Backdrop::Fill, Some(found)) = scan(doc, page, Some((copy, &out)))? else { return None };
|
||||
let (piece, offset) = found.place()?;
|
||||
if found.refs.get(piece).map(|&(_, r)| r) != Some(copy) || offset != fill.span.start || found.op.len() != op.len() {
|
||||
return None;
|
||||
}
|
||||
let mut dict = s.dict.clone();
|
||||
for key in [&b"Length"[..], b"DL", TAG] {
|
||||
dict.remove(key);
|
||||
}
|
||||
let was = match note.get(b"Was").and_then(Object::as_array).map(Vec::as_slice) {
|
||||
Some([num, generation]) => Some(ObjRef { num: u32::try_from(num.as_int()?).ok()?, generation: u16::try_from(generation.as_int()?).ok()? }),
|
||||
_ => None,
|
||||
};
|
||||
Some((out, dict, was))
|
||||
}
|
||||
|
||||
/// As much of a content stream as a backdrop could be in: it has to come first.
|
||||
fn head(bytes: &[u8]) -> &[u8] {
|
||||
bytes.get(..bytes.len().min(SCAN_BYTES)).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// A SHA-256 of what `ops` are, not how they are written: keywords and operand values, with
|
||||
/// numbers in one form (`1`, `1.0` and `1.00000` are the same), so a stream written out again
|
||||
/// with other spacing or number formatting still matches.
|
||||
fn ops_hash(ops: &[Op]) -> Vec<u8> {
|
||||
let mut h = Sha256::new();
|
||||
for op in ops {
|
||||
for o in &op.operands {
|
||||
canonical(o, &mut h, 0);
|
||||
}
|
||||
if let Some((dict, data)) = &op.inline {
|
||||
canonical_dict(dict, &mut h, 0);
|
||||
bytes(b'i', data, &mut h);
|
||||
}
|
||||
bytes(b'k', &op.op, &mut h);
|
||||
}
|
||||
h.finalize().to_vec()
|
||||
}
|
||||
|
||||
/// How deep [`canonical`] follows nested arrays and dictionaries; deeper ones count as equal.
|
||||
const CANONICAL_DEPTH: usize = 32;
|
||||
|
||||
fn canonical(o: &Object, h: &mut Sha256, depth: usize) {
|
||||
if depth > CANONICAL_DEPTH {
|
||||
h.update(b"~");
|
||||
return;
|
||||
}
|
||||
match o {
|
||||
Object::Null => h.update(b"z"),
|
||||
Object::Bool(b) => h.update(if *b { b"T" } else { b"F" }),
|
||||
Object::Int(i) => number(&i.to_string(), h),
|
||||
Object::Real(r) if *r == 0.0 => number("0", h),
|
||||
Object::Real(r) => number(&format!("{r:.5}"), h),
|
||||
Object::String(s) => bytes(b's', &s.bytes, h),
|
||||
Object::Name(n) => bytes(b'/', n, h),
|
||||
Object::Array(a) => {
|
||||
h.update(b"[");
|
||||
for x in a {
|
||||
canonical(x, h, depth.saturating_add(1));
|
||||
}
|
||||
h.update(b"]");
|
||||
}
|
||||
Object::Dict(d) => canonical_dict(d, h, depth),
|
||||
Object::Stream(_) | Object::Ref(_) => h.update(b"?"),
|
||||
}
|
||||
}
|
||||
|
||||
fn canonical_dict(d: &Dict, h: &mut Sha256, depth: usize) {
|
||||
h.update(b"<");
|
||||
for (k, v) in d.iter() {
|
||||
bytes(b'/', k, h);
|
||||
canonical(v, h, depth.saturating_add(1));
|
||||
}
|
||||
h.update(b">");
|
||||
}
|
||||
|
||||
/// A number written with up to five decimals, without trailing zeros.
|
||||
fn number(text: &str, h: &mut Sha256) {
|
||||
let t = if text.contains('.') { text.trim_end_matches('0').trim_end_matches('.') } else { text };
|
||||
bytes(b'#', t.as_bytes(), h);
|
||||
}
|
||||
|
||||
/// A typed, length-prefixed value, so no two different sequences hash the same way.
|
||||
fn bytes(kind: u8, b: &[u8], h: &mut Sha256) {
|
||||
h.update([kind]);
|
||||
h.update(u64::try_from(b.len()).unwrap_or(u64::MAX).to_le_bytes());
|
||||
h.update(b);
|
||||
}
|
||||
|
||||
/// Find the backdrop, and for a fill, where it is. With `swap`, that stream reads as those bytes
|
||||
/// instead of its own (to check a change before making it).
|
||||
fn scan(doc: &Document, p: &pdfcraft_model::Page, swap: Option<(ObjRef, &[u8])>) -> Option<(Backdrop, Option<Found>)> {
|
||||
let crop = p.crop(doc);
|
||||
let c = p.dict.get(b"Contents")?;
|
||||
let list: Vec<Object> = match &*doc.resolve(c) {
|
||||
Object::Array(a) if a.len() <= SCAN_OPS => a.clone(),
|
||||
Object::Array(_) => return None,
|
||||
_ => vec![c.clone()],
|
||||
};
|
||||
// The page's own content: untagged streams (marks and the q/Q wrapper carry /PCMark). Read
|
||||
// only as far as a backdrop could be.
|
||||
let mut refs = Vec::new();
|
||||
let mut data = Vec::new();
|
||||
let mut starts = Vec::new();
|
||||
let mut total = 0usize;
|
||||
let mut budget = DecodeBudget::new(SCAN_BYTES, 0);
|
||||
for (slot, o) in list.iter().enumerate() {
|
||||
if total >= SCAN_BYTES {
|
||||
break;
|
||||
}
|
||||
let Object::Ref(r) = o else { return None };
|
||||
let obj = doc.get(*r);
|
||||
let Object::Stream(s) = &*obj else { continue };
|
||||
if s.dict.get(b"PCMark").is_some() {
|
||||
continue;
|
||||
}
|
||||
// Bytes in an external file (`/F`) replace the stream's own: what it draws is unknown here.
|
||||
if s.dict.get(b"F").is_some() {
|
||||
return None;
|
||||
}
|
||||
let bytes = match swap {
|
||||
Some((with, b)) if with == *r => {
|
||||
if b.len() > SCAN_BYTES.saturating_sub(total) {
|
||||
return None;
|
||||
}
|
||||
budget.decode_strict(&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()?,
|
||||
};
|
||||
if bytes.len() > SCAN_BYTES.saturating_sub(total).saturating_sub(1) {
|
||||
return None;
|
||||
}
|
||||
starts.push(total);
|
||||
total += bytes.len() + 1;
|
||||
refs.push((slot, *r));
|
||||
data.push(bytes);
|
||||
}
|
||||
let pieces = Pieces::join(&data);
|
||||
let parsed = pdfcraft_content::parse(head(pieces.data()));
|
||||
let res = resources(doc, &p.dict);
|
||||
let found = walk(doc, &res, crop, &parsed.ops);
|
||||
// A match proves the graphics state for one execution only. Repeated references may
|
||||
// paint real artwork under a different color or transform: leave them untouched.
|
||||
if let Some((Backdrop::Fill, Some(op))) = &found {
|
||||
let piece = pieces.piece_of(op.start);
|
||||
let (_, reference) = refs.get(piece)?;
|
||||
if list.iter().filter(|o| matches!(o, Object::Ref(r) if r == reference)).count() != 1 {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
found.map(|(b, op)| match (b, op) {
|
||||
(Backdrop::Fill, Some(op)) => (b, Some(Found { refs, pieces, starts, op })),
|
||||
_ => (b, None),
|
||||
})
|
||||
}
|
||||
|
||||
fn resources(doc: &Document, page: &Dict) -> Dict {
|
||||
page.get(b"Resources").map(|r| doc.resolve(r)).and_then(|r| r.as_dict().cloned()).unwrap_or_default()
|
||||
}
|
||||
|
||||
fn sub(doc: &Document, res: &Dict, kind: &[u8], name: &[u8]) -> Option<std::sync::Arc<Object>> {
|
||||
let d = res.get(kind).map(|d| doc.resolve(d))?;
|
||||
let o = d.as_dict()?.get(name)?.clone();
|
||||
Some(doc.resolve(&o))
|
||||
}
|
||||
|
||||
/// Walk the operators until the first one that paints; a backdrop is that one, or nothing.
|
||||
fn walk(doc: &Document, res: &Dict, crop: [f64; 4], ops: &[Op]) -> Option<(Backdrop, Option<std::ops::Range<usize>>)> {
|
||||
let mut st = State { ctm: Matrix::IDENTITY, clip: Some([f64::MIN, f64::MIN, f64::MAX, f64::MAX]), white: false, space: 1, paint: Paint::INITIAL };
|
||||
let mut saved: Vec<State> = Vec::new();
|
||||
// Current path: its rectangles in user space, or `None` once it is anything else.
|
||||
let mut path: Option<Vec<[f64; 4]>> = Some(Vec::new());
|
||||
let mut clip_next = false;
|
||||
for op in ops.iter().take(SCAN_OPS) {
|
||||
match op.op.as_slice() {
|
||||
b"q" => {
|
||||
if saved.len() >= 64 {
|
||||
return None;
|
||||
}
|
||||
saved.push(st.clone());
|
||||
}
|
||||
b"Q" => st = saved.pop()?,
|
||||
b"cm" => {
|
||||
let m = Matrix::from_operands(op.operands.get(op.operands.len().checked_sub(6)?..)?)?;
|
||||
if !m.0.iter().all(|v| v.is_finite()) {
|
||||
return None;
|
||||
}
|
||||
st.ctm = m.then(&st.ctm);
|
||||
}
|
||||
b"gs" => apply_state(doc, res, op.name(0)?, &mut st.paint)?,
|
||||
b"g" => set_colour(&mut st, 1, op),
|
||||
b"rg" => set_colour(&mut st, 3, op),
|
||||
b"k" => set_colour(&mut st, 4, op),
|
||||
b"cs" => {
|
||||
st.space = match op.name(0)? {
|
||||
b"DeviceGray" => 1,
|
||||
b"DeviceRGB" => 3,
|
||||
b"DeviceCMYK" => 4,
|
||||
_ => 0,
|
||||
};
|
||||
// The initial colour of these spaces is black.
|
||||
st.white = false;
|
||||
}
|
||||
b"sc" | b"scn" => {
|
||||
let n = st.space;
|
||||
set_colour(&mut st, n, op)
|
||||
}
|
||||
b"re" => {
|
||||
let [x, y, w, h] = op.nums::<4>()?;
|
||||
let finite = [x, y, w, h].iter().all(|v| v.is_finite());
|
||||
match (&mut path, finite && axis_aligned(&st.ctm)) {
|
||||
(Some(rects), true) => rects.push(st.ctm.bbox([x.min(x + w), y.min(y + h), x.max(x + w), y.max(y + h)])),
|
||||
_ => path = None,
|
||||
}
|
||||
}
|
||||
b"m" | b"l" | b"c" | b"v" | b"y" | b"h" => path = None,
|
||||
b"W" | b"W*" => clip_next = true,
|
||||
b"n" => {
|
||||
if clip_next {
|
||||
st.clip = clipped(st.clip, path.as_deref());
|
||||
}
|
||||
path = Some(Vec::new());
|
||||
clip_next = false;
|
||||
}
|
||||
b"f" | b"F" | b"f*" => {
|
||||
// One rectangle: with two, a fill rule can cut a hole where content shows.
|
||||
let covers = match path.as_deref() {
|
||||
Some([r]) => st.clip.and_then(|c| intersect(*r, c)).is_some_and(|r| pdfcraft_content::contains(r, crop, COVER_EPS)),
|
||||
_ => false,
|
||||
};
|
||||
return (covers && st.white && st.paint.plain() && !clip_next).then(|| (Backdrop::Fill, Some(op.span.clone())));
|
||||
}
|
||||
b"Do" => {
|
||||
let xo = sub(doc, res, b"XObject", op.name(0)?)?;
|
||||
let Object::Stream(s) = &*xo else { return None };
|
||||
// A stencil or masked picture lets what is behind it show.
|
||||
let masked = [&b"SMask"[..], b"Mask"].iter().any(|k| s.dict.get(k).is_some())
|
||||
|| s.dict.get(b"ImageMask").is_some_and(|m| matches!(*doc.resolve(m), Object::Bool(true)));
|
||||
let image = s.dict.name(b"Subtype") == Some(b"Image") && !masked;
|
||||
return covers_unit_square(&st, crop, image).then_some((Backdrop::Image, None));
|
||||
}
|
||||
b"BI" => {
|
||||
let masked = op
|
||||
.inline
|
||||
.as_ref()
|
||||
.is_some_and(|(d, _)| [&b"IM"[..], b"ImageMask"].iter().any(|k| d.get(k).is_some_and(|m| matches!(m, Object::Bool(true)))));
|
||||
return covers_unit_square(&st, crop, !masked).then_some((Backdrop::Image, None));
|
||||
}
|
||||
// Anything else that paints comes first: no backdrop.
|
||||
b"S" | b"s" | b"B" | b"B*" | b"b" | b"b*" | b"sh" | b"Tj" | b"TJ" | b"'" | b"\"" | b"EI" | b"d0" | b"d1" => return None,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// A picture placed by the CTM (onto the unit square) covering the crop box, opaque, unclipped.
|
||||
fn covers_unit_square(st: &State, crop: [f64; 4], image: bool) -> bool {
|
||||
image
|
||||
&& st.paint.plain()
|
||||
&& axis_aligned(&st.ctm)
|
||||
&& st.clip.and_then(|c| intersect(st.ctm.bbox([0.0, 0.0, 1.0, 1.0]), c)).is_some_and(|r| pdfcraft_content::contains(r, crop, COVER_EPS))
|
||||
}
|
||||
|
||||
fn set_colour(st: &mut State, components: usize, op: &Op) {
|
||||
st.space = components;
|
||||
let vals: Vec<f64> = op.operands.iter().filter_map(Object::as_f64).collect();
|
||||
st.white = vals.len() == components
|
||||
&& match components {
|
||||
1 | 3 => vals.iter().all(|v| *v >= WHITE),
|
||||
4 => vals.iter().all(|v| *v <= 1.0 - WHITE),
|
||||
_ => false,
|
||||
};
|
||||
}
|
||||
|
||||
/// Apply the named ExtGState's keys that [`Paint`] tracks; the keys it doesn't have leave
|
||||
/// `paint` as it was. `None` when the dictionary or one of those values can't be read.
|
||||
fn apply_state(doc: &Document, res: &Dict, name: &[u8], paint: &mut Paint) -> Option<()> {
|
||||
let gs = sub(doc, res, b"ExtGState", name)?;
|
||||
let gs = gs.as_dict()?;
|
||||
if let Some(alpha) = gs.get(b"ca") {
|
||||
paint.full_alpha = doc.resolve(alpha).as_f64()? >= 0.999;
|
||||
}
|
||||
if let Some(mask) = gs.get(b"SMask") {
|
||||
paint.no_soft_mask = doc.resolve(mask).as_name() == Some(b"None");
|
||||
}
|
||||
if let Some(blend) = gs.get(b"BM") {
|
||||
paint.normal_blend = matches!(doc.resolve(blend).as_name(), Some(b"Normal" | b"Compatible"));
|
||||
}
|
||||
// TR2 takes precedence over TR in the same dictionary (§8.4.5, Table 57). Only the names
|
||||
// are read: a function (or one per colourant) is taken to change white.
|
||||
if let Some(transfer) = gs.get(b"TR2") {
|
||||
paint.identity_transfer = matches!(doc.resolve(transfer).as_name(), Some(b"Identity" | b"Default"));
|
||||
} else if let Some(transfer) = gs.get(b"TR") {
|
||||
paint.identity_transfer = doc.resolve(transfer).as_name() == Some(b"Identity");
|
||||
}
|
||||
Some(())
|
||||
}
|
||||
|
||||
/// Rotations by multiples of 90° and scales only: rectangles stay rectangles.
|
||||
fn axis_aligned(m: &Matrix) -> bool {
|
||||
let [a, b, c, d, ..] = m.0;
|
||||
(b.abs() < 1e-9 && c.abs() < 1e-9) || (a.abs() < 1e-9 && d.abs() < 1e-9)
|
||||
}
|
||||
|
||||
fn intersect(a: [f64; 4], b: [f64; 4]) -> Option<[f64; 4]> {
|
||||
let r = [a[0].max(b[0]), a[1].max(b[1]), a[2].min(b[2]), a[3].min(b[3])];
|
||||
(r.iter().all(|v| v.is_finite()) && r[2] > r[0] && r[3] > r[1]).then_some(r)
|
||||
}
|
||||
|
||||
/// The clip after intersecting with a path: known only when the path is one rectangle.
|
||||
fn clipped(clip: Option<[f64; 4]>, path: Option<&[[f64; 4]]>) -> Option<[f64; 4]> {
|
||||
match path {
|
||||
Some([r]) => intersect(clip?, *r).or(Some([0.0, 0.0, 0.0, 0.0])),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "backdrop_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,607 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use pdfcraft_cos::{Dict, Document, ObjRef, Object, SaveOptions, Stream, write_full, write_incremental};
|
||||
|
||||
use super::*;
|
||||
use crate::{Background, MarkKind, add_background, remove_marks};
|
||||
|
||||
const TEXT: &str = "BT /F1 24 Tf 40 90 Td (Hello) Tj ET";
|
||||
|
||||
/// A document from its objects (object 1 is the catalog, 2 the page tree).
|
||||
fn build(objs: &[String]) -> Document {
|
||||
let mut out = b"%PDF-1.7\n".to_vec();
|
||||
let mut offs = Vec::new();
|
||||
for (i, o) in objs.iter().enumerate() {
|
||||
offs.push(out.len());
|
||||
out.extend_from_slice(format!("{} 0 obj\n{o}\nendobj\n", i + 1).as_bytes());
|
||||
}
|
||||
let x = 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{x}\n%%EOF\n", objs.len() + 1).as_bytes());
|
||||
Document::open(Arc::new(out)).unwrap()
|
||||
}
|
||||
|
||||
fn stream(dict: &str, data: &str) -> String {
|
||||
format!("<< {dict} /Length {} >>\nstream\n{data}\nendstream", data.len())
|
||||
}
|
||||
|
||||
/// One 300 × 200 page drawing `pieces` (objects 5…), with a font, a page-sized image `/Im0`
|
||||
/// (object 4) and two graphics states, `/Half` (ca 0.5) and `/Full` (ca 1).
|
||||
/// The graphics states [`page`] offers. `INVERT` is a transfer function that maps 1 to 0, so
|
||||
/// `1 g` through it paints black (#2815 review).
|
||||
const GRAPHICS_STATES: &str = concat!(
|
||||
"/Half << /ca 0.5 >> /Full << /ca 1 /CA 1 >> /LineOnly << /LW 2 >> ",
|
||||
"/Masked << /SMask << /S /Luminosity /G 4 0 R >> >> /Unmasked << /SMask /None >> ",
|
||||
"/Multiply << /BM /Multiply >> /NormalBlend << /BM /Normal >> ",
|
||||
"/Invert << /TR << /FunctionType 2 /Domain [0 1] /C0 [1] /C1 [0] /N 1 >> >> ",
|
||||
"/Invert2 << /TR2 << /FunctionType 2 /Domain [0 1] /C0 [1] /C1 [0] /N 1 >> >> ",
|
||||
"/IdentityTR << /TR /Identity >> /DefaultTR2 << /TR2 /Default >> ",
|
||||
"/InvertButTR2Default << /TR << /FunctionType 2 /Domain [0 1] /C0 [1] /C1 [0] /N 1 >> /TR2 /Default >> ",
|
||||
"/IdentityButTR2Invert << /TR /Identity /TR2 << /FunctionType 2 /Domain [0 1] /C0 [1] /C1 [0] /N 1 >> >>",
|
||||
);
|
||||
|
||||
fn page(pieces: &[&str]) -> Document {
|
||||
let refs: Vec<String> = (0..pieces.len()).map(|i| format!("{} 0 R", i + 5)).collect();
|
||||
let mut objs = vec![
|
||||
"<< /Type /Catalog /Pages 2 0 R >>".to_string(),
|
||||
"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".into(),
|
||||
format!(
|
||||
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 200] /Contents [{}] /Resources << /Font << /F1 << /Type /Font /Subtype /Type1 /BaseFont /Helvetica >> >> /XObject << /Im0 4 0 R >> /ExtGState << {GS} >> >> >>",
|
||||
refs.join(" "),
|
||||
GS = GRAPHICS_STATES
|
||||
),
|
||||
stream("/Type /XObject /Subtype /Image /Width 1 /Height 1 /ColorSpace /DeviceGray /BitsPerComponent 8", "\u{80}"),
|
||||
];
|
||||
objs.extend(pieces.iter().map(|p| stream("", p)));
|
||||
build(&objs)
|
||||
}
|
||||
|
||||
/// The decoded content of a page, stream by stream.
|
||||
fn streams(doc: &Document) -> Vec<String> {
|
||||
let p = &pdfcraft_model::pages(doc)[0];
|
||||
let list = match p.dict.get(b"Contents").map(|c| doc.resolve(c)).as_deref() {
|
||||
Some(Object::Array(a)) => a.clone(),
|
||||
_ => vec![],
|
||||
};
|
||||
list.iter()
|
||||
.map(|o| match &*doc.resolve(o) {
|
||||
Object::Stream(s) => String::from_utf8_lossy(&s.decoded().unwrap()).into_owned(),
|
||||
_ => String::new(),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn reopen(doc: &Document) -> Document {
|
||||
let bytes = write_incremental(doc, &SaveOptions::default()).unwrap();
|
||||
Document::open(Arc::new(bytes)).unwrap()
|
||||
}
|
||||
|
||||
fn red() -> Background {
|
||||
Background { color: [1.0, 0.0, 0.0], ..Background::default() }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_white_fill_backdrop_is_replaced_and_put_back_when_the_background_goes() {
|
||||
let content = format!("q 1 1 1 rg 0 0 300 200 re f Q {TEXT}");
|
||||
let mut doc = page(&[&content]);
|
||||
assert_eq!(page_backdrop(&doc, 0).unwrap(), Some(Backdrop::Fill));
|
||||
let original = streams(&doc);
|
||||
add_background(&mut doc, &[0], &red(), false).unwrap();
|
||||
let s = streams(&reopen(&doc));
|
||||
assert_eq!(s.len(), 2, "{s:?}");
|
||||
assert!(s[0].contains("/PCMark /Background"));
|
||||
assert_eq!(s[1], format!("q 1 1 1 rg 0 0 300 200 re n Q {TEXT}"), "only the fill operator changed");
|
||||
assert_eq!(page_backdrop(&doc, 0).unwrap(), None, "nothing hides the background now");
|
||||
// The original stream object is untouched; the page points at a copy.
|
||||
let Object::Stream(orig) = &*doc.get(ObjRef { num: 5, generation: 0 }) else { panic!("object 5 is the content") };
|
||||
assert_eq!(String::from_utf8_lossy(&orig.decoded().unwrap()), content);
|
||||
assert_eq!(remove_marks(&mut doc, &[0], MarkKind::Background).unwrap(), 1);
|
||||
assert_eq!(streams(&reopen(&doc)), original, "exactly the original content");
|
||||
assert_eq!(page_backdrop(&doc, 0).unwrap(), Some(Backdrop::Fill));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn updating_the_background_replaces_the_backdrop_once_and_removing_still_restores() {
|
||||
let mut doc = page(&[&format!("1 1 1 rg 0 0 300 200 re f 0 g {TEXT}")]);
|
||||
let original = streams(&doc);
|
||||
add_background(&mut doc, &[0], &red(), false).unwrap();
|
||||
add_background(&mut doc, &[0], &Background { color: [0.0, 0.0, 1.0], ..Background::default() }, true).unwrap();
|
||||
let s = streams(&doc);
|
||||
assert_eq!(s.len(), 2, "one background, one copy: {s:?}");
|
||||
assert!(s[1].contains("re n"));
|
||||
remove_marks(&mut doc, &[0], MarkKind::Background).unwrap();
|
||||
assert_eq!(streams(&doc), original);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_backdrop_split_across_content_streams_is_replaced_in_the_piece_holding_the_operator() {
|
||||
let mut doc = page(&["1 1 1 rg 0 0 300 200 re", &format!("f* {TEXT}")]);
|
||||
let original = streams(&doc);
|
||||
assert_eq!(page_backdrop(&doc, 0).unwrap(), Some(Backdrop::Fill));
|
||||
add_background(&mut doc, &[0], &red(), false).unwrap();
|
||||
let s = streams(&doc);
|
||||
assert_eq!(s[1..], ["1 1 1 rg 0 0 300 200 re".to_string(), format!("n {TEXT}")], "{s:?}");
|
||||
remove_marks(&mut doc, &[0], MarkKind::Background).unwrap();
|
||||
assert_eq!(streams(&doc), original);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn backdrops_writers_paint_are_recognised() {
|
||||
for content in [
|
||||
// Browsers: a flipped, scaled coordinate system and a page clip first.
|
||||
"q 0.5 0 0 -0.5 0 200 cm 0 0 600 400 re W n 1 1 1 rg 0 0 600 400 re f Q",
|
||||
// Larger than the page, in CMYK, through an opaque graphics state.
|
||||
"/Full gs 0 0 0 0 k -10 -10 320 220 re f",
|
||||
"/DeviceRGB cs 1 1 1 sc 0 0 300 200 re F",
|
||||
"0.99 g 0 0 300 200 re f",
|
||||
// Turned a quarter: still a rectangle.
|
||||
"0 1 -1 0 300 0 cm 1 g 0 0 200 300 re f",
|
||||
] {
|
||||
let doc = page(&[&format!("{content} 0 g {TEXT}")]);
|
||||
assert_eq!(page_backdrop(&doc, 0).unwrap(), Some(Backdrop::Fill), "{content}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn content_that_is_not_a_page_backdrop_is_left_alone() {
|
||||
for content in [
|
||||
// Not the whole page.
|
||||
"1 g 0 0 300 150 re f",
|
||||
"q 0 0 100 100 re W n 1 g 0 0 300 200 re f Q",
|
||||
// Not white, or not opaque.
|
||||
"0.5 g 0 0 300 200 re f",
|
||||
"1 0 0 rg 0 0 300 200 re f",
|
||||
"0 0 0 0.5 k 0 0 300 200 re f",
|
||||
"/Half gs 1 g 0 0 300 200 re f",
|
||||
"/Missing gs 1 g 0 0 300 200 re f",
|
||||
"/Pattern cs /P0 scn 0 0 300 200 re f",
|
||||
// The initial colour is black.
|
||||
"0 0 300 200 re f",
|
||||
// Something else is painted first.
|
||||
"BT /F1 9 Tf (x) Tj ET 1 g 0 0 300 200 re f",
|
||||
"0 g 0 0 1 1 re f 1 g 0 0 300 200 re f",
|
||||
"1 g 0 0 300 200 re S 1 g 0 0 300 200 re f",
|
||||
// Not a single rectangle: a hole, a turned square, a fill-and-stroke.
|
||||
"1 g 0 0 300 200 re 50 50 10 10 re f*",
|
||||
"1 g 0 0 m 300 0 l 300 200 l 0 200 l h f",
|
||||
"0.7 0.7 -0.7 0.7 150 -100 cm 1 g 0 0 400 400 re f",
|
||||
"1 g 0 0 300 200 re B",
|
||||
// Malformed.
|
||||
"Q 1 g 0 0 300 200 re f",
|
||||
"1 g 0 0 300 re f",
|
||||
"1 g 0 0 1e400 200 re f",
|
||||
] {
|
||||
let mut doc = page(&[&format!("{content} {TEXT}")]);
|
||||
assert_eq!(page_backdrop(&doc, 0).unwrap(), None, "{content}");
|
||||
let before = streams(&doc);
|
||||
add_background(&mut doc, &[0], &red(), false).unwrap();
|
||||
assert_eq!(streams(&doc)[1..], before[..], "{content}: the page's content is unchanged");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_scanned_page_is_reported_and_its_picture_kept() {
|
||||
let mut doc = page(&[&format!("q 300 0 0 200 0 0 cm /Im0 Do Q {TEXT}")]);
|
||||
assert_eq!(page_backdrop(&doc, 0).unwrap(), Some(Backdrop::Image));
|
||||
let before = streams(&doc);
|
||||
add_background(&mut doc, &[0], &red(), false).unwrap();
|
||||
assert_eq!(streams(&doc)[1..], before[..]);
|
||||
// A small picture is content, not a backdrop.
|
||||
let doc = page(&["q 30 0 0 20 0 0 cm /Im0 Do Q"]);
|
||||
assert_eq!(page_backdrop(&doc, 0).unwrap(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn replacing_can_be_turned_off() {
|
||||
let mut doc = page(&[&format!("1 g 0 0 300 200 re f {TEXT}")]);
|
||||
let before = streams(&doc);
|
||||
add_background(&mut doc, &[0], &Background { replace_backdrop: false, ..red() }, false).unwrap();
|
||||
assert_eq!(streams(&doc)[1..], before[..]);
|
||||
}
|
||||
|
||||
/// Rewrite the page's backdrop copy (the stream after the background) as another tool would:
|
||||
/// Edit text and redaction keep its dictionary and change its bytes.
|
||||
fn rewrite_copy(doc: &mut Document, bytes: &str) -> ObjRef {
|
||||
let p = &pdfcraft_model::pages(doc)[0];
|
||||
let Some(Object::Array(list)) = p.dict.get(b"Contents").cloned() else { panic!("contents") };
|
||||
let Object::Ref(copy) = list[1] else { panic!("a reference") };
|
||||
let Object::Stream(s) = (*doc.get(copy)).clone() else { panic!("a stream") };
|
||||
assert!(s.dict.get(b"PCBackdrop").is_some(), "the copy");
|
||||
doc.set(copy, Object::Stream(Stream::flate(s.dict.clone(), bytes.as_bytes())));
|
||||
copy
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_edit_after_the_fill_is_kept_and_the_backdrop_still_comes_back() {
|
||||
let mut doc = page(&[&format!("1 g 0 0 300 200 re f {TEXT}")]);
|
||||
add_background(&mut doc, &[0], &red(), false).unwrap();
|
||||
rewrite_copy(&mut doc, "1 g 0 0 300 200 re n BT /F1 24 Tf 40 90 Td (Edited) Tj ET");
|
||||
remove_marks(&mut doc, &[0], MarkKind::Background).unwrap();
|
||||
assert_eq!(streams(&doc), ["1 g 0 0 300 200 re f BT /F1 24 Tf 40 90 Td (Edited) Tj ET"], "the edit survives, under the fill");
|
||||
assert_eq!(page_backdrop(&doc, 0).unwrap(), Some(Backdrop::Fill));
|
||||
assert_eq!(backdrops_left_off(&doc), Vec::<usize>::new());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_change_before_the_fill_leaves_it_off_and_names_the_page() {
|
||||
for edited in [
|
||||
// A different colour before the fill: the hash of what comes before it no longer matches.
|
||||
"0.99 g 0 0 300 200 re n BT /F1 24 Tf 40 90 Td (Edited) Tj ET",
|
||||
// Something painted before it.
|
||||
"BT /F1 9 Tf (x) Tj ET 1 g 0 0 300 200 re n",
|
||||
// The fill is gone.
|
||||
"BT /F1 24 Tf 40 90 Td (Edited) Tj ET",
|
||||
] {
|
||||
let mut doc = page(&[&format!("1 g 0 0 300 200 re f {TEXT}")]);
|
||||
add_background(&mut doc, &[0], &red(), false).unwrap();
|
||||
assert_eq!(backdrops_left_off(&doc), Vec::<usize>::new(), "a background is over it");
|
||||
rewrite_copy(&mut doc, edited);
|
||||
remove_marks(&mut doc, &[0], MarkKind::Background).unwrap();
|
||||
assert_eq!(streams(&doc), [edited.to_string()], "{edited}: the copy stays as it is");
|
||||
assert_eq!(backdrops_left_off(&doc), [0], "{edited}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_fill_that_would_cover_content_painted_before_it_stays_off() {
|
||||
let mut doc = page(&[&format!("1 g 0 0 300 200 re f {TEXT}")]);
|
||||
add_background(&mut doc, &[0], &red(), false).unwrap();
|
||||
// A tool puts a stream of its own before the copy, untagged: turning the fill back on would
|
||||
// now paint white over that text.
|
||||
let over = doc.add(Object::Stream(Stream::flate(pdfcraft_cos::Dict::new(), b"BT /F1 9 Tf 10 10 Td (Over) Tj ET")));
|
||||
let p = pdfcraft_model::pages(&doc)[0].clone();
|
||||
let Some(Object::Array(mut list)) = p.dict.get(b"Contents").cloned() else { panic!("contents") };
|
||||
list.insert(1, Object::Ref(over));
|
||||
doc.update_dict(p.obj, |d| d.set(b"Contents".to_vec(), Object::Array(list))).unwrap();
|
||||
remove_marks(&mut doc, &[0], MarkKind::Background).unwrap();
|
||||
let s = streams(&doc);
|
||||
assert_eq!(s.len(), 2, "{s:?}");
|
||||
assert!(s[1].contains("re n") && !s[1].contains("re f"), "nothing white goes over the text: {s:?}");
|
||||
assert_eq!(backdrops_left_off(&doc), [0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_tag_holds_no_reference_and_a_full_save_keeps_no_second_copy_of_the_page() {
|
||||
let mut doc = page(&[&format!("1 g 0 0 300 200 re f {TEXT}")]);
|
||||
add_background(&mut doc, &[0], &red(), false).unwrap();
|
||||
let saved = Document::open(Arc::new(write_full(&doc, &SaveOptions::default()).unwrap())).unwrap();
|
||||
// Every stream in the file that holds the page's text: only the copy the page draws. A
|
||||
// reference from the tag to the original stream kept a second, which a redaction or Remove
|
||||
// Hidden Information on the copy left in the file.
|
||||
let holding: Vec<(ObjRef, Dict)> = saved
|
||||
.scan_objects()
|
||||
.filter_map(|(r, o)| match &*o {
|
||||
Object::Stream(s) if String::from_utf8_lossy(&s.decoded().unwrap_or_default()).contains("(Hello)") => Some((r, s.dict.clone())),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(holding.len(), 1, "{holding:?}");
|
||||
let Some(Object::Dict(note)) = holding[0].1.get(b"PCBackdrop").map(|n| (*saved.resolve(n)).clone()) else { panic!("the tag") };
|
||||
fn refs(o: &Object) -> bool {
|
||||
match o {
|
||||
Object::Ref(_) => true,
|
||||
Object::Array(a) => a.iter().any(refs),
|
||||
Object::Dict(d) => d.iter().any(|(_, v)| refs(v)),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
assert!(!note.iter().any(|(_, v)| refs(v)), "{note:?}");
|
||||
assert_eq!(note.get(b"Op").and_then(Object::as_string).map(|s| s.bytes.clone()), Some(b"f".to_vec()));
|
||||
assert_eq!(note.get(b"Before").and_then(Object::as_string).map(|s| s.bytes.len()), Some(32), "a SHA-256");
|
||||
// The original is gone, so Remove writes the fill back into a stream of its own.
|
||||
let mut saved = saved;
|
||||
remove_marks(&mut saved, &[0], MarkKind::Background).unwrap();
|
||||
assert_eq!(streams(&saved), [format!("1 g 0 0 300 200 re f {TEXT}")]);
|
||||
assert_eq!(page_backdrop(&saved, 0).unwrap(), Some(Backdrop::Fill));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_copy_written_out_again_with_other_spacing_still_comes_back() {
|
||||
// Redaction writes the whole stream out again: one operator a line, numbers its own way.
|
||||
let mut doc = page(&[&format!("1 g 0 0 300 200 re f {TEXT}")]);
|
||||
add_background(&mut doc, &[0], &red(), false).unwrap();
|
||||
rewrite_copy(&mut doc, "1.0 g\n0 0 300.000 200 re\nn\nBT\n/F1 24 Tf\n40 90 Td\n[-6505] TJ\nET");
|
||||
remove_marks(&mut doc, &[0], MarkKind::Background).unwrap();
|
||||
assert_eq!(streams(&doc), ["1.0 g\n0 0 300.000 200 re\nf\nBT\n/F1 24 Tf\n40 90 Td\n[-6505] TJ\nET"], "the fill is back, the rest as written");
|
||||
assert_eq!(backdrops_left_off(&doc), Vec::<usize>::new());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_tag_that_does_not_add_up_is_left_alone() {
|
||||
let content = format!("1 g 0 0 300 200 re f {TEXT}");
|
||||
let copied = format!("1 g 0 0 300 200 re n {TEXT}");
|
||||
let good = ops_hash(&pdfcraft_content::parse(b"1 g 0 0 300 200 re").ops);
|
||||
let hex = |b: &[u8]| b.iter().map(|x| format!("{x:02x}")).collect::<String>();
|
||||
for tag in [
|
||||
// Not a fill operator, a wrong hash, an index that isn't the `n` or runs past the end.
|
||||
format!("<< /Index 2 /Op (B) /Before <{}> >>", hex(&good)),
|
||||
format!("<< /Index 2 /Op (f) /Before <{}> >>", hex(&[0; 32])),
|
||||
format!("<< /Index 1 /Op (f) /Before <{}> >>", hex(&good)),
|
||||
format!("<< /Index 99999 /Op (f) /Before <{}> >>", hex(&good)),
|
||||
format!("<< /Index -1 /Op (f) /Before <{}> >>", hex(&good)),
|
||||
// Missing entries, wrong types, and the reference earlier test builds wrote.
|
||||
"<< /Index 2 /Op (f) >>".to_string(),
|
||||
"<< /Index (2) /Op /f /Before 3 >>".to_string(),
|
||||
"<< /Original 5 0 R /At 19 /Len 1 >>".to_string(),
|
||||
"(not a dictionary)".to_string(),
|
||||
] {
|
||||
let mut doc = build(&[
|
||||
"<< /Type /Catalog /Pages 2 0 R >>".to_string(),
|
||||
"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 300 200] >>".into(),
|
||||
"<< /Type /Page /Parent 2 0 R /Contents [4 0 R] >>".into(),
|
||||
stream(&format!("/PCBackdrop {tag}"), &copied),
|
||||
stream("", &content),
|
||||
]);
|
||||
remove_marks(&mut doc, &[0], MarkKind::Background).unwrap();
|
||||
assert_eq!(streams(&doc), std::slice::from_ref(&copied), "{tag}");
|
||||
assert_eq!(backdrops_left_off(&doc), [0], "{tag}");
|
||||
}
|
||||
// The same page with an honest tag comes back.
|
||||
let mut doc = build(&[
|
||||
"<< /Type /Catalog /Pages 2 0 R >>".to_string(),
|
||||
"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 300 200] >>".into(),
|
||||
"<< /Type /Page /Parent 2 0 R /Contents [4 0 R] >>".into(),
|
||||
stream(&format!("/PCBackdrop << /Index 2 /Op (f) /Before <{}> >>", hex(&good)), &copied),
|
||||
]);
|
||||
remove_marks(&mut doc, &[0], MarkKind::Background).unwrap();
|
||||
assert_eq!(streams(&doc), [content]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn operators_hash_by_value_not_by_spelling() {
|
||||
let h = |s: &[u8]| ops_hash(&pdfcraft_content::parse(s).ops);
|
||||
assert_eq!(h(b"1 g 0 0 300 200 re"), h(b"1.0 g\n0 0 300.00000 200 re"));
|
||||
assert_eq!(h(b"0 g"), h(b"-0.0 g"));
|
||||
assert_ne!(h(b"1 g 0 0 300 200 re"), h(b"0.99 g 0 0 300 200 re"));
|
||||
assert_ne!(h(b"(ab) Tj"), h(b"(a) (b) Tj"), "operand boundaries count");
|
||||
assert_ne!(h(b"/a /b BDC"), h(b"/ab BDC"));
|
||||
assert_ne!(h(b""), h(b"q"));
|
||||
// Nesting is bounded: deep arrays hash without running out of stack.
|
||||
let deep = format!("{}{} Tj", "[".repeat(1000), "]".repeat(1000));
|
||||
let _ = h(deep.as_bytes());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_content_stream_shared_by_two_pages_is_copied_for_the_one_page() {
|
||||
let content = format!("1 g 0 0 300 200 re f {TEXT}");
|
||||
let mut doc = build(&[
|
||||
"<< /Type /Catalog /Pages 2 0 R >>".to_string(),
|
||||
"<< /Type /Pages /Kids [3 0 R 4 0 R] /Count 2 /MediaBox [0 0 300 200] >>".into(),
|
||||
"<< /Type /Page /Parent 2 0 R /Contents 5 0 R >>".into(),
|
||||
"<< /Type /Page /Parent 2 0 R /Contents 5 0 R >>".into(),
|
||||
stream("", &content),
|
||||
]);
|
||||
add_background(&mut doc, &[0], &red(), false).unwrap();
|
||||
assert_eq!(page_backdrop(&doc, 0).unwrap(), None);
|
||||
assert_eq!(page_backdrop(&doc, 1).unwrap(), Some(Backdrop::Fill), "the other page keeps its backdrop");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pages_without_content_or_with_odd_contents_have_no_backdrop() {
|
||||
let doc = build(&[
|
||||
"<< /Type /Catalog /Pages 2 0 R >>".to_string(),
|
||||
"<< /Type /Pages /Kids [3 0 R 4 0 R] /Count 2 /MediaBox [0 0 300 200] >>".into(),
|
||||
"<< /Type /Page /Parent 2 0 R >>".into(),
|
||||
"<< /Type /Page /Parent 2 0 R /Contents [5 0 R 99 0 R] >>".into(),
|
||||
"<< /Not /AStream >>".into(),
|
||||
]);
|
||||
assert_eq!(page_backdrop(&doc, 0).unwrap(), None);
|
||||
assert_eq!(page_backdrop(&doc, 1).unwrap(), None);
|
||||
assert!(matches!(page_backdrop(&doc, 7), Err(EditError::NoSuchPage(7))));
|
||||
}
|
||||
|
||||
/// `pages` 300 × 200 pages in a flat tree; even pages paint a white backdrop, odd ones don't.
|
||||
fn many_pages(pages: usize) -> Document {
|
||||
let kids: Vec<String> = (0..pages).map(|i| format!("{} 0 R", i + 5)).collect();
|
||||
let mut objs = vec![
|
||||
"<< /Type /Catalog /Pages 2 0 R >>".to_string(),
|
||||
format!("<< /Type /Pages /Kids [{}] /Count {pages} /MediaBox [0 0 300 200] >>", kids.join(" ")),
|
||||
stream("", &format!("1 g 0 0 300 200 re f 0 g {TEXT}")),
|
||||
stream("", TEXT),
|
||||
];
|
||||
objs.extend((0..pages).map(|i| format!("<< /Type /Page /Parent 2 0 R /Contents {} 0 R >>", 3 + i % 2)));
|
||||
build(&objs)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn checking_many_pages_walks_the_page_tree_once() {
|
||||
// The Add Background dialog checks every page of a long document. Looking each page up on
|
||||
// its own walked the whole tree per page, so checking them all grew with the square of the
|
||||
// page count (minutes at 20,000 pages); one walk keeps it in proportion.
|
||||
const PAGES: usize = 4000;
|
||||
let doc = many_pages(PAGES);
|
||||
let all: Vec<usize> = (0..PAGES).collect();
|
||||
let start = std::time::Instant::now();
|
||||
let found = page_backdrops(&doc, &all);
|
||||
let took = start.elapsed();
|
||||
assert_eq!(found.len(), PAGES);
|
||||
for (i, f) in found.iter().enumerate() {
|
||||
assert_eq!(*f, (i % 2 == 0).then_some(Backdrop::Fill), "page {i}");
|
||||
}
|
||||
assert!(took < std::time::Duration::from_secs(5), "checking {PAGES} pages took {took:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_batch_answers_in_the_order_asked_and_a_missing_page_hides_nothing() {
|
||||
let doc = many_pages(5);
|
||||
assert_eq!(page_backdrops(&doc, &[3, 0, 0]), [None, Some(Backdrop::Fill), Some(Backdrop::Fill)]);
|
||||
assert_eq!(page_backdrops(&doc, &[]), []);
|
||||
// The viewer can count more pages than the page tree holds: the others still answer.
|
||||
assert_eq!(page_backdrops(&doc, &[2, 5, usize::MAX]), [Some(Backdrop::Fill), None, None]);
|
||||
assert_eq!(page_backdrop(&doc, 4).unwrap(), Some(Backdrop::Fill));
|
||||
assert!(matches!(page_backdrop(&doc, 5), Err(EditError::NoSuchPage(5))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_background_over_many_pages_replaces_each_backdrop_and_removing_restores_them() {
|
||||
// Pages share their content streams, so each replaced page gets its own copy and the rest
|
||||
// are checked against the document as it is after the earlier ones.
|
||||
let mut doc = many_pages(4);
|
||||
let all = [0, 1, 2, 3];
|
||||
let before: Vec<Object> = pdfcraft_model::pages(&doc).iter().filter_map(|p| p.dict.get(b"Contents").cloned()).collect();
|
||||
add_background(&mut doc, &all, &red(), true).unwrap();
|
||||
assert_eq!(page_backdrops(&doc, &all), [None; 4]);
|
||||
// Update: the backdrops are gone already, so nothing is copied again.
|
||||
add_background(&mut doc, &all, &red(), true).unwrap();
|
||||
assert_eq!(page_backdrops(&doc, &all), [None; 4]);
|
||||
remove_marks(&mut doc, &all, MarkKind::Background).unwrap();
|
||||
let after: Vec<Object> = pdfcraft_model::pages(&doc).iter().filter_map(|p| p.dict.get(b"Contents").cloned()).collect();
|
||||
let refs = |list: &[Object]| -> Vec<Vec<Object>> {
|
||||
list.iter()
|
||||
.map(|c| match &*doc.resolve(c) {
|
||||
Object::Array(a) => a.clone(),
|
||||
_ => vec![c.clone()],
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
assert_eq!(refs(&after), refs(&before), "every page points at its original stream again");
|
||||
assert_eq!(page_backdrops(&doc, &all), [Some(Backdrop::Fill), None, Some(Backdrop::Fill), None]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_content_stream_whose_bytes_live_in_an_external_file_is_left_alone() {
|
||||
let objs = vec![
|
||||
"<< /Type /Catalog /Pages 2 0 R >>".to_string(),
|
||||
"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 300 200] >>".into(),
|
||||
"<< /Type /Page /Parent 2 0 R /Contents [4 0 R] >>".into(),
|
||||
stream("/F (content.bin)", &format!("1 g 0 0 300 200 re f {TEXT}")),
|
||||
];
|
||||
let mut doc = build(&objs);
|
||||
assert_eq!(page_backdrop(&doc, 0).unwrap(), None, "the inline bytes are not what the page draws");
|
||||
let before = streams(&doc);
|
||||
add_background(&mut doc, &[0], &red(), false).unwrap();
|
||||
assert_eq!(streams(&doc)[1..], before[..]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_backdrop_copy_keeps_the_original_dictionary_less_its_old_encoding() {
|
||||
let objs = vec![
|
||||
"<< /Type /Catalog /Pages 2 0 R >>".to_string(),
|
||||
"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 300 200] >>".into(),
|
||||
"<< /Type /Page /Parent 2 0 R /Contents [4 0 R] >>".into(),
|
||||
stream("/Vendor (keep me) /DL 9999", &format!("1 g 0 0 300 200 re f {TEXT}")),
|
||||
];
|
||||
let mut doc = build(&objs);
|
||||
add_background(&mut doc, &[0], &red(), false).unwrap();
|
||||
let doc = reopen(&doc);
|
||||
let p = &pdfcraft_model::pages(&doc)[0];
|
||||
let Some(Object::Array(list)) = p.dict.get(b"Contents").map(|c| (*doc.resolve(c)).clone()) else { panic!("contents") };
|
||||
let Object::Stream(copy) = &*doc.resolve(&list[1]) else { panic!("a stream") };
|
||||
assert!(copy.dict.get(b"Vendor").is_some(), "unknown entries survive");
|
||||
assert!(copy.dict.get(b"DL").is_none(), "the old decoded length no longer holds");
|
||||
assert!(copy.dict.get(b"PCBackdrop").is_some());
|
||||
assert_eq!(String::from_utf8_lossy(©.decoded().unwrap()), format!("1 g 0 0 300 200 re n {TEXT}"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stream_listed_twice_is_left_untouched_as_ambiguous() {
|
||||
let mut doc = build(&[
|
||||
"<< /Type /Catalog /Pages 2 0 R >>".to_string(),
|
||||
"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 300 200] >>".into(),
|
||||
"<< /Type /Page /Parent 2 0 R /Contents [4 0 R 4 0 R] >>".into(),
|
||||
stream("", &format!("q 1 g 0 0 300 200 re f Q {TEXT}")),
|
||||
]);
|
||||
let original = streams(&doc);
|
||||
add_background(&mut doc, &[0], &red(), false).unwrap();
|
||||
let s = streams(&doc);
|
||||
assert_eq!(s.len(), 3, "{s:?}");
|
||||
assert_eq!(s[1..], original[..], "repeated executions are not qualified independently");
|
||||
remove_marks(&mut doc, &[0], MarkKind::Background).unwrap();
|
||||
assert_eq!(streams(&doc), original);
|
||||
}
|
||||
|
||||
/// #2815 review: a `gs` sets only the keys its dictionary has, so a translucent, masked,
|
||||
/// blended or transferred fill stays that way through a later `gs` that leaves the key out,
|
||||
/// and a transfer function that isn't the identity can turn `1 g` into any colour.
|
||||
#[test]
|
||||
fn graphics_state_a_later_gs_leaves_out_still_keeps_the_fill() {
|
||||
for state in [
|
||||
"/Half gs /LineOnly gs",
|
||||
"/Masked gs /LineOnly gs",
|
||||
"/Multiply gs /LineOnly gs",
|
||||
"/Invert gs /LineOnly gs",
|
||||
"/Invert2 gs /LineOnly gs",
|
||||
"/Invert gs",
|
||||
"/Invert2 gs",
|
||||
"/IdentityButTR2Invert gs",
|
||||
"/Invert gs q /LineOnly gs Q",
|
||||
] {
|
||||
let mut doc = page(&[&format!("{state} 1 g 0 0 300 200 re f {TEXT}")]);
|
||||
assert_eq!(page_backdrop(&doc, 0).unwrap(), None, "{state}");
|
||||
let before = streams(&doc);
|
||||
add_background(&mut doc, &[0], &red(), false).unwrap();
|
||||
assert_eq!(streams(&doc)[1..], before[..], "{state}: the page's content is unchanged");
|
||||
}
|
||||
}
|
||||
|
||||
/// The other side of the same rule: a later `gs` that does set the key back, `TR2` naming the
|
||||
/// default over a `TR` function, and `Q` restoring what `q` saved still leave a plain white fill.
|
||||
#[test]
|
||||
fn graphics_state_set_back_before_the_fill_still_finds_the_backdrop() {
|
||||
for state in [
|
||||
"/Half gs /Full gs",
|
||||
"/Masked gs /Unmasked gs",
|
||||
"/Multiply gs /NormalBlend gs",
|
||||
"/Invert gs /IdentityTR gs",
|
||||
"/Invert2 gs /DefaultTR2 gs",
|
||||
"/InvertButTR2Default gs",
|
||||
"/LineOnly gs",
|
||||
"q /Half gs Q",
|
||||
"q /Invert gs Q",
|
||||
] {
|
||||
let doc = page(&[&format!("{state} 1 g 0 0 300 200 re f {TEXT}")]);
|
||||
assert_eq!(page_backdrop(&doc, 0).unwrap(), Some(Backdrop::Fill), "{state}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_undecodable_stream_before_a_white_fill_keeps_the_backdrop_unknown() {
|
||||
let objs = vec![
|
||||
"<< /Type /Catalog /Pages 2 0 R >>".to_string(),
|
||||
"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 300 200] >>".into(),
|
||||
"<< /Type /Page /Parent 2 0 R /Contents [4 0 R 5 0 R] >>".into(),
|
||||
stream("/Filter /FlateDecode", "not a deflate stream"),
|
||||
stream("", &format!("1 g 0 0 300 200 re f {TEXT}")),
|
||||
];
|
||||
let doc = build(&objs);
|
||||
assert_eq!(page_backdrop(&doc, 0).unwrap(), None, "unknown earlier paint must not be treated as an empty stream");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shared_fill_used_as_later_artwork_is_not_rewritten() {
|
||||
let mut doc = build(&[
|
||||
"<< /Type /Catalog /Pages 2 0 R >>".to_string(),
|
||||
"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 300 200] >>".into(),
|
||||
"<< /Type /Page /Parent 2 0 R /Contents [4 0 R 5 0 R 6 0 R 5 0 R 7 0 R] >>".into(),
|
||||
stream("", "1 g"),
|
||||
stream("", "0 0 300 200 re f"),
|
||||
stream("", "q 0 g 0.25 0 0 0.25 20 20 cm"),
|
||||
stream("", "Q"),
|
||||
]);
|
||||
assert_eq!(page_backdrop(&doc, 0).unwrap(), None);
|
||||
let original = streams(&doc);
|
||||
add_background(&mut doc, &[0], &red(), false).unwrap();
|
||||
assert_eq!(streams(&doc)[1..], original[..], "the later black artwork keeps its fill");
|
||||
let mut saved = reopen(&doc);
|
||||
assert_eq!(streams(&saved)[1..], original[..]);
|
||||
remove_marks(&mut saved, &[0], MarkKind::Background).unwrap();
|
||||
assert_eq!(streams(&saved), original);
|
||||
assert_eq!(streams(&reopen(&saved)), original);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compressed_backdrop_content_is_refused_before_expanding_past_the_scan_budget() {
|
||||
let mut doc = page(&["1 g 0 0 300 200 re f"]);
|
||||
let mut bytes = b"1 g 0 0 300 200 re f\n".to_vec();
|
||||
bytes.resize(2 * 1024 * 1024, b' ');
|
||||
let source = doc.add(Object::Stream(Stream::flate(Dict::new(), &bytes)));
|
||||
let page = pdfcraft_model::pages(&doc)[0].obj;
|
||||
doc.update_dict(page, |d| d.set(b"Contents".to_vec(), Object::Ref(source))).unwrap();
|
||||
assert_eq!(page_backdrop(&doc, 0).unwrap(), None);
|
||||
add_background(&mut doc, &[0], &red(), false).unwrap();
|
||||
let Object::Stream(unchanged) = &*doc.get(source) else { panic!("stream") };
|
||||
assert_eq!(unchanged.decoded_strict().unwrap(), bytes, "refusal preserves the source");
|
||||
}
|
||||
@@ -16,6 +16,7 @@ use pdfcraft_cos::{Dict, Document, ObjRef, Object};
|
||||
use crate::{EditError, check, n, page_list, place_tagged};
|
||||
|
||||
const HIDDEN: i64 = 2;
|
||||
const NO_ROTATE: i64 = 16;
|
||||
const NO_VIEW: i64 = 32;
|
||||
|
||||
fn nums(doc: &Document, o: Option<&Object>) -> Option<Vec<f64>> {
|
||||
@@ -74,6 +75,28 @@ fn placement(doc: &Document, form: &Dict, rect: [f64; 4]) -> Option<[f64; 6]> {
|
||||
Some([sx, 0.0, 0.0, sy, rect[0] - x0 * sx, rect[1] - y0 * sy])
|
||||
}
|
||||
|
||||
/// `m` followed by a turn of `degrees` (the page's /Rotate) about the upper-left corner of
|
||||
/// `rect`: a NoRotate annotation stays upright on a rotated page (ISO 32000-2 §12.5.3), its
|
||||
/// upper-left corner where it was, which is how MuPDF and Poppler draw it.
|
||||
fn upright(m: [f64; 6], degrees: i64, rect: [f64; 4]) -> [f64; 6] {
|
||||
let (sin, cos) = match degrees.rem_euclid(360) {
|
||||
90 => (1.0, 0.0),
|
||||
180 => (0.0, -1.0),
|
||||
270 => (-1.0, 0.0),
|
||||
_ => return m,
|
||||
};
|
||||
let (px, py) = (rect[0], rect[3]);
|
||||
let t = [cos, sin, -sin, cos, px - px * cos + py * sin, py - px * sin - py * cos];
|
||||
[
|
||||
m[0] * t[0] + m[1] * t[2],
|
||||
m[0] * t[1] + m[1] * t[3],
|
||||
m[2] * t[0] + m[3] * t[2],
|
||||
m[2] * t[1] + m[3] * t[3],
|
||||
m[4] * t[0] + m[5] * t[2] + t[4],
|
||||
m[4] * t[1] + m[5] * t[3] + t[5],
|
||||
]
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum Which {
|
||||
/// Every comment and/or every form field.
|
||||
@@ -194,6 +217,7 @@ fn flatten_in(doc: &mut Document, pages: &[usize], which: Which) -> Result<usize
|
||||
let mut gone_inline: HashSet<usize> = HashSet::new();
|
||||
// Selected, but nothing was drawn for it: it stays, pop-up and reply handling included.
|
||||
let mut undrawn: HashSet<ObjRef> = HashSet::new();
|
||||
let rotation = page.dict.get(b"Rotate").map(|r| doc.resolve(r)).and_then(|r| r.as_int()).unwrap_or(0);
|
||||
// A viewer draws many comments from their dictionary even when the file stores no
|
||||
// appearance (notes, FreeText, ink, stamps…). Build the appearance it would show, so
|
||||
// flattening keeps a comment that still has ink on screen instead of deleting it.
|
||||
@@ -230,6 +254,7 @@ fn flatten_in(doc: &mut Document, pages: &[usize], which: Which) -> Result<usize
|
||||
if let (Some(ap), Some(rect)) = (appearance(doc, d), rect) {
|
||||
let form = doc.get(ap).as_dict().cloned().unwrap_or_default();
|
||||
if let Some(m) = placement(doc, &form, rect) {
|
||||
let m = if flags & NO_ROTATE != 0 { upright(m, rotation, rect) } else { m };
|
||||
let name = xobject_name(&existing_xo, &xobjects, &mut name_n);
|
||||
content.push_str(&format!("q {} {} {} {} {} {} cm /{name} Do Q\n", n(m[0]), n(m[1]), n(m[2]), n(m[3]), n(m[4]), n(m[5])));
|
||||
xobjects.set(name.into_bytes(), Object::Ref(ap));
|
||||
|
||||
@@ -186,11 +186,9 @@ impl ImageState {
|
||||
self.path.curve_to(self.point(x1, y1), end, end);
|
||||
}
|
||||
}
|
||||
b"h" => {
|
||||
// ClosePath with no subpath panics by the same contract (#3581).
|
||||
if self.path.elements().last().is_some() {
|
||||
self.path.close_path();
|
||||
}
|
||||
// ClosePath with no subpath panics by the same contract (#3581).
|
||||
b"h" if self.path.elements().last().is_some() => {
|
||||
self.path.close_path();
|
||||
}
|
||||
b"re" => {
|
||||
if let Some([x, y, w, h]) = op.nums::<4>() {
|
||||
|
||||